Unpacking Software Livestream

Join our monthly Unpacking Software livestream to hear about the latest news, chat and opinion on packaging, software deployment and lifecycle management!

Learn More

Chocolatey Product Spotlight

Join the Chocolatey Team on our regular monthly stream where we put a spotlight on the most recent Chocolatey product releases. You'll have a chance to have your questions answered in a live Ask Me Anything format.

Learn More

Chocolatey Coding Livestream

Join us for the Chocolatey Coding Livestream, where members of our team dive into the heart of open source development by coding live on various Chocolatey projects. Tune in to witness real-time coding, ask questions, and gain insights into the world of package management. Don't miss this opportunity to engage with our team and contribute to the future of Chocolatey!

Learn More

Calling All Chocolatiers! Whipping Up Windows Automation with Chocolatey Central Management

Webinar from
Wednesday, 17 January 2024

We are delighted to announce the release of Chocolatey Central Management v0.12.0, featuring seamless Deployment Plan creation, time-saving duplications, insightful Group Details, an upgraded Dashboard, bug fixes, user interface polishing, and refined documentation. As an added bonus we'll have members of our Solutions Engineering team on-hand to dive into some interesting ways you can leverage the new features available!

Watch On-Demand
Chocolatey Community Coffee Break

Join the Chocolatey Team as we discuss all things Community, what we do, how you can get involved and answer your Chocolatey questions.

Watch The Replays
Chocolatey and Intune Overview

Webinar Replay from
Wednesday, 30 March 2022

At Chocolatey Software we strive for simple, and teaching others. Let us teach you just how simple it could be to keep your 3rd party applications updated across your devices, all with Intune!

Watch On-Demand
Chocolatey For Business. In Azure. In One Click.

Livestream from
Thursday, 9 June 2022

Join James and Josh to show you how you can get the Chocolatey For Business recommended infrastructure and workflow, created, in Azure, in around 20 minutes.

Watch On-Demand
The Future of Chocolatey CLI

Livestream from
Thursday, 04 August 2022

Join Paul and Gary to hear more about the plans for the Chocolatey CLI in the not so distant future. We'll talk about some cool new features, long term asks from Customers and Community and how you can get involved!

Watch On-Demand
Hacktoberfest Tuesdays 2022

Livestreams from
October 2022

For Hacktoberfest, Chocolatey ran a livestream every Tuesday! Re-watch Cory, James, Gary, and Rain as they share knowledge on how to contribute to open-source projects such as Chocolatey CLI.

Watch On-Demand

Downloads:

169,759

Downloads of v 0.9.737:

190

Last Update:

09 Jan 2019

Package Maintainer(s):

Software Author(s):

  • Chrissy LeMaire

Tags:

admin powershell module template dba sqlserver sql tools database

dbatools (PowerShell Module)

This is not the latest version of dbatools (PowerShell Module) available.

  • 1
  • 2
  • 3

0.9.737 | Updated: 09 Jan 2019

Downloads:

169,759

Downloads of v 0.9.737:

190

Maintainer(s):

Software Author(s):

  • Chrissy LeMaire

dbatools (PowerShell Module) 0.9.737

This is not the latest version of dbatools (PowerShell Module) available.

  • 1
  • 2
  • 3

All Checks are Passing

3 Passing Tests


Validation Testing Passed


Verification Testing Passed

Details

Scan Testing Successful:

No detections found in any package files

Details
Learn More

Deployment Method: Individual Install, Upgrade, & Uninstall

To install dbatools (PowerShell Module), run the following command from the command line or from PowerShell:

>

To upgrade dbatools (PowerShell Module), run the following command from the command line or from PowerShell:

>

To uninstall dbatools (PowerShell Module), run the following command from the command line or from PowerShell:

>

Deployment Method:

NOTE

This applies to both open source and commercial editions of Chocolatey.

1. Enter Your Internal Repository Url

(this should look similar to https://community.chocolatey.org/api/v2/)


2. Setup Your Environment

1. Ensure you are set for organizational deployment

Please see the organizational deployment guide

2. Get the package into your environment

  • Open Source or Commercial:
    • Proxy Repository - Create a proxy nuget repository on Nexus, Artifactory Pro, or a proxy Chocolatey repository on ProGet. Point your upstream to https://community.chocolatey.org/api/v2/. Packages cache on first access automatically. Make sure your choco clients are using your proxy repository as a source and NOT the default community repository. See source command for more information.
    • You can also just download the package and push it to a repository Download

3. Copy Your Script

choco upgrade dbatools -y --source="'INTERNAL REPO URL'" --version="'0.9.737'" [other options]

See options you can pass to upgrade.

See best practices for scripting.

Add this to a PowerShell script or use a Batch script with tools and in places where you are calling directly to Chocolatey. If you are integrating, keep in mind enhanced exit codes.

If you do use a PowerShell script, use the following to ensure bad exit codes are shown as failures:


choco upgrade dbatools -y --source="'INTERNAL REPO URL'" --version="'0.9.737'" 
$exitCode = $LASTEXITCODE

Write-Verbose "Exit code was $exitCode"
$validExitCodes = @(0, 1605, 1614, 1641, 3010)
if ($validExitCodes -contains $exitCode) {
  Exit 0
}

Exit $exitCode

- name: Install dbatools
  win_chocolatey:
    name: dbatools
    version: '0.9.737'
    source: INTERNAL REPO URL
    state: present

See docs at https://docs.ansible.com/ansible/latest/modules/win_chocolatey_module.html.


chocolatey_package 'dbatools' do
  action    :install
  source   'INTERNAL REPO URL'
  version  '0.9.737'
end

See docs at https://docs.chef.io/resource_chocolatey_package.html.


cChocoPackageInstaller dbatools
{
    Name     = "dbatools"
    Version  = "0.9.737"
    Source   = "INTERNAL REPO URL"
}

Requires cChoco DSC Resource. See docs at https://github.com/chocolatey/cChoco.


package { 'dbatools':
  ensure   => '0.9.737',
  provider => 'chocolatey',
  source   => 'INTERNAL REPO URL',
}

Requires Puppet Chocolatey Provider module. See docs at https://forge.puppet.com/puppetlabs/chocolatey.


4. If applicable - Chocolatey configuration/installation

See infrastructure management matrix for Chocolatey configuration elements and examples.

WARNING

There are versions of this package awaiting moderation . See the Version History section below.

Package Approved

This package was approved as a trusted package on 09 Jan 2019.

Description

dbatools logo dbatools is sort of like a command-line SQL Server Management Studio. The project initially started out as Start-SqlMigration.ps1, but has now grown into a collection of over 300 commands that help automate SQL Server tasks and encourage best practices.

NOTE: This module requires a minimum of PowerShell v3.

NOTE: This is an automatically updated package. If you find it is out of date by more than a week, please contact the maintainer(s) and let them know the package is no longer updating correctly.


tools\.skipAutoUninstaller
 
tools\chocolateyBeforeModify.ps1
$ErrorActionPreference = 'Stop'

$moduleName = 'dbatools'      # this could be different from package name

$module = Get-Module -Name $moduleName
if ($module) {
    Write-Verbose "Module '$moduleName' is imported into the session. Removing it."
    Remove-Module -Name $moduleName -Force -ErrorAction SilentlyContinue

    if ($lib = [appdomain]::CurrentDomain.GetAssemblies() | Where-Object FullName -like "dbatools, *") {
        Write-Verbose "Found locked DLL files for module '$moduleName'."
        $moduleDir = Split-Path $module.Path -Parent
        if ($lib.Location -like "$moduleDir\*") {
            Write-Warning @"
We have detected dbatools to be already imported from '$moduleDir' and the dll files have been locked and cannot be updated.
Please close all consoles that have dbatools imported (Remove-Module dbatools is NOT enough).
"@
            throw 
        }
    }
}
tools\chocolateyInstall.ps1
$ErrorActionPreference = 'Stop'

$toolsDir   = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
$moduleName = 'dbatools'  # this may be different from the package name and different case

if ($PSVersionTable.PSVersion.Major -lt 3) {
    throw "$moduleName) module requires a minimum of PowerShell v3."
}

# module may already be installed outside of Chocolatey
Remove-Module -Name $moduleName -Force -ErrorAction SilentlyContinue

$sourcePath = Join-Path -Path $toolsDir -ChildPath "$modulename\*"
$destPath   = Join-Path -Path $env:ProgramFiles -ChildPath "WindowsPowerShell\Modules\$moduleName"

if ($PSVersionTable.PSVersion.Major -ge 5)
{
    $manifestFile = Join-Path -Path $toolsDir -ChildPath "$moduleName\$moduleName.psd1"
    $manifest     = Test-ModuleManifest -Path $manifestFile -WarningAction Ignore -ErrorAction Stop
    $destPath     = Join-Path -Path $destPath -ChildPath $manifest.Version.ToString()
}

Write-Verbose "Creating destination directory '$destPath' for module."
New-Item -Path $destPath -ItemType Directory -Force -ErrorAction SilentlyContinue | Out-Null

Write-Verbose "Moving '$moduleName' files from '$sourcePath' to '$destPath'."
Move-Item -Path $sourcePath -Destination $destPath -Force

if ($PSVersionTable.PSVersion.Major -lt 4)
{
    $modulePaths = [Environment]::GetEnvironmentVariable('PSModulePath', 'Machine') -split ';'
    if ($modulePaths -notcontains $destPath)
    {
        Write-Verbose "Adding '$destPath' to PSModulePath."
        $newModulePath = @($destPath, $modulePaths) -join ';'

        [Environment]::SetEnvironmentVariable('PSModulePath', $newModulePath, 'Machine')
        $env:PSModulePath = $newModulePath
    }
}
tools\chocolateyUninstall.ps1
$ErrorActionPreference = 'Stop'

$moduleName = 'dbatools'
$sourcePath = Join-Path -Path $env:ProgramFiles -ChildPath "WindowsPowerShell\Modules\$moduleName"

Write-Verbose "Removing all version of '$moduleName' from '$sourcePath'."
Remove-Item -Path $sourcePath -Recurse -Force -ErrorAction SilentlyContinue

if ($PSVersionTable.PSVersion.Major -lt 4) {
    $modulePaths = [Environment]::GetEnvironmentVariable('PSModulePath', 'Machine') -split ';'

    Write-Verbose "Removing '$sourcePath' from PSModulePath."
    $newModulePath = $modulePaths | Where-Object { $_ -ne $sourcePath }

    [Environment]::SetEnvironmentVariable('PSModulePath', $newModulePath, 'Machine')
    $env:PSModulePath = $newModulePath
}
tools\dbatools\allcommands.zip
md5: 7E28A9F7385C7C5BAC5FB420B998230A | sha1: B26876262EE60284BE5280DD7B8DB2424748FED9 | sha256: CF19B3702405D995E35B505718DF5EC385D36B0A982138E052D196BDF0479FA6 | sha512: C6366D5F7830D6B00F5D580D87A3A91FF24ACDB71C2C713B132959F330FCB49FB6745AB2CD79A3B2F109322130EACE17FD6D54E9D4EE740D5143BEDE53738A59
tools\dbatools\bin\bcp\bcp.exe
md5: 0056F153E8574FD9C429946E4983E962 | sha1: 41E89575060091A52A52EAA1656B93D7DF67EA01 | sha256: D59D296E846CBD83F5E55CB5852CC2AAA9E1DECC8E0A324B7D0964C4CDF7B425 | sha512: 61F6608BA778FB3B5D1FC02F3F8EB2A006E5378ED629A70F095A62F116A4E4FA0C34B3033D618BF371E7EAB0EAC9FAD27E2AD586C7EF527BAAF72558F12BCD43
tools\dbatools\bin\bcp\Resources\1033\bcp.rll
 
tools\dbatools\bin\build-project.ps1
[CmdletBinding()]
param (
    [string]$ProjectPath = (Resolve-Path -Path (Join-Path -Path $PSModuleRoot -ChildPath 'bin\projects\dbatools\dbatools.sln')),
    [ValidateSet('ps3', 'ps4', 'Release', 'Debug')]
    [string]$MsbuildConfiguration = "Release",
    [string]$MsbuildOptions = "",
    [Parameter(HelpMessage = 'Target to run instead of build')]
    [string]$MsbuildTarget = 'Build'
)

if (-not $PSBoundParameters.ContainsKey('MsbuildConfiguration')) {
    $_MsbuildConfiguration = switch ($PSVersionTable.PSVersion.Major) {
        3 {
            "ps3"
        }
        4 {
            "ps4"
        }
        default {
            "Release"
        }
    }
} else {
    $_MsbuildConfiguration = $MsbuildConfiguration
}

function Get-MsBuildPath {
    [CmdletBinding()]
    [OutputType([string])]
    param ()
    process {
        $rawPath = "$(Split-Path ([string].Assembly.Location))\msbuild.exe"
        (Resolve-Path $rawPath).Path
    }
}

$start = Get-Date
$msbuild = Get-MsBuildPath

if (-not (Test-Path $msbuild)) {
    throw "msbuild not found, cannot compile library! Check your .NET installation health, then try again. Path checked: $msbuild"
}

if ($env:APPVEYOR -eq 'True') {
    $MsbuildOptions = $MsbuildOptions + '/logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" '
    $_MsbuildConfiguration = 'Debug'
    
    if (-not (Test-Path "C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll")) {
        throw "msbuild logger not found, cannot compile library! Check your .NET installation health, then try again. Path checked: $msbuild"
    }
}

#$MsbuildOptions = $MsbuildOptions + '/logger:BinaryLogger,"{0}";"{1}" ' -f (Join-Path $PSScriptRoot 'StructuredLogger.dll'), (Resolve-Path '..\msbuild.bin.log').Path

if (-not (Test-Path $ProjectPath)) {
    throw new-object 'System.IO.FileNotFoundException' 'Could not file project or solution', $ProjectPath
}

Write-Verbose -Message "Building the library with command $msbuild $ProjectPath /p:Configuration=$_MsbuildConfiguration $MsbuildOptions /t:$MsBuildTarget"
& $msbuild $ProjectPath "/p:Configuration=$_MsbuildConfiguration" $MsbuildOptions "/t:$MsBuildTarget"

if ($MsbuildTarget -eq 'Build') {
    try {
        Write-Verbose -Message "Found library, trying to copy & import"
        if ($script:alwaysBuildLibrary) {
            Move-Item -Path (Resolve-Path -Path "$PSModuleRoot\bin\dbatools.dll") -Destination $script:DllRoot -Force -ErrorAction Stop
        } else {
            Copy-Item -Path (Resolve-Path -Path "$PSModuleRoot\bin\dbatools.dll") -Destination $script:DllRoot -Force -ErrorAction Stop
        }
        Add-Type -Path (Resolve-Path -Path "$PSModuleRoot\dbatools.dll") -ErrorAction Stop
    } catch {
        Write-Verbose -Message "Failed to copy & import, attempting to import straight from the module directory"
        Add-Type -Path (Resolve-Path -Path "$PSModuleRoot\bin\dbatools.dll") -ErrorAction Stop
    }
    Write-Verbose -Message "Total duration: $((Get-Date) - $start)"
}
tools\dbatools\bin\csv\LumenWorks.Framework.IO.dll
md5: C76D91D1714B0A395844F80FCC28514E | sha1: 7E6241585218C1578FBCD31233B57B55DEF3877A | sha256: 8B86914D50465C35119F85AAAF9364316E9F98B2C2BE80CA2CA6E4D862E68782 | sha512: C7C77C66CF09EDF58D13952F007599E3F73DD3B223340427277FDDE8277EA088F449A31B18DD2A2B4239E87A99277EEC2ADC2E7794BA4236AD127CA346FE9C2B
tools\dbatools\bin\datamasking\Bogus.dll
md5: 20F763BE815B160592018EA082632C6C | sha1: A8213E021FA517E4360CAC1E038BCD6C6001F4CC | sha256: EA6693548EB2A0A2B8248C424FCEEECEE9F4F811F2702DF4F2E64E5E82FCBDAB | sha512: 19E0776A83A735EBC09F65F873028D38B96ED562059961291B51CC6E1BA9EDFD028A9D36F01E0B4D545C109226EABF889C5B97F2DE965D5382D66B5AA1B8AAA9
tools\dbatools\bin\datamasking\columntypes.json
[
    {
        "TypeName": "Firstname",
        "Synonym": [
            "Firstname",
            "Forename"
        ]
    },
    {
        "TypeName": "Lastname",
        "Synonym": [
            "Lastname",
            "Surname"
        ]
    },
    {
        "TypeName": "Fullname",
        "Synonym": [
            "Fullname",
            "TypeName"
        ]
    },
    {
        "TypeName": "Phone",
        "Synonym": [
            "Phonenumber",
            "Phone",
            "Telephone",
            "TelephoneNumber"
        ]
    },
    {
        "TypeName": "Address",
        "Synonym": [
            "Address",
            "Location",
            "Headquarters",
            "Street"
        ]
    },
    {
        "TypeName": "Zipcode",
        "Synonym": [
            "Zipcode",
            "Zip",
            "Postalcode"
        ]
    },
    {
        "TypeName": "City",
        "Synonym": [
            "City"
        ]
    },
    {
        "TypeName": "State",
        "Synonym": [
            "State"
        ]
    },
    {
        "TypeName": "Country",
        "Synonym": [
            "Country"
        ]
    },
    {
        "TypeName": "CountryCode",
        "Synonym": [
            "CountryCode"
        ]
    },
    {
        "TypeName": "Latitude",
        "Synonym": [
            "Latitude",
            "Lat"
        ]
    },
    {
        "TypeName": "Longitude",
        "Synonym": [
            "Longitude",
            "Lon"
        ]
    },
    {
        "TypeName": "Creditcard",
        "Synonym": [
            "Creditcard",
            "CreditcardNumber"
        ]
    },
    {
        "TypeName": "Username",
        "Synonym": [
            "Login",
			"LoginId",
            "User",
            "UserId"
        ]
    }
]
tools\dbatools\bin\datamasking\example.tables.json
[
    {
        "Name": "Credicards",
        "Columns": {
            "Name": "CredicardNumber",
            "MaskingType": "CreditCard",
            "SubType": "MasterCard"
        }
    },
    {
        "Name": "Customer",
        "Columns": [
            {
                "Name": "Firstname",
                "MaskingType": "FirstName"
            },
            {
                "Name": "Lastname",
                "MaskingType": "Lastname"
            },
            {
                "Name": "Address",
                "MaskingType": "Address"
            },
            {
                "Name": "Zipcode",
                "MaskingType": "Zipcode"
            },
            {
                "Name": "City",
                "MaskingType": "City"
            }
        ]
    },
    {
        "Name": "ContactInformation",
        "Columns": [
            {
                "Name": "EmailAddress",
                "MaskingType": "Email"
            },
            {
                "Name": "HomePhone",
                "MaskingType": "Phone"
            }
        ]
    }
]
tools\dbatools\bin\datamasking\firstnames_all.txt
Aaron
Abbey
Abbie
Abby
Abdul
Abe
Abel
Abigail
Abraham
Abram
Ada
Adah
Adalberto
Adaline
Adam
Adan
Addie
Adela
Adelaida
Adelaide
Adele
Adelia
Adelina
Adeline
Adell
Adella
Adelle
Adena
Adina
Adolfo
Adolph
Adria
Adrian
Adriana
Adriane
Adrianna
Adrianne
Adrien
Adriene
Adrienne
Afton
Agatha
Agnes
Agnus
Agripina
Agueda
Agustin
Agustina
Ahmad
Ahmed
Ai
Aida
Aide
Aiko
Aileen
Ailene
Aimee
Aisha
Aja
Akiko
Akilah
Al
Alaina
Alaine
Alan
Alana
Alane
Alanna
Alayna
Alba
Albert
Alberta
Albertha
Albertina
Albertine
Alberto
Albina
Alda
Alden
Aldo
Alease
Alec
Alecia
Aleen
Aleida
Aleisha
Alejandra
Alejandrina
Alejandro
Alena
Alene
Alesha
Aleshia
Alesia
Alessandra
Aleta
Aletha
Alethea
Alethia
Alex
Alexa
Alexander
Alexandra
Alexandria
Alexia
Alexis
Alfonso
Alfonzo
Alfred
Alfreda
Alfredia
Alfredo
Ali
Alia
Alica
Alice
Alicia
Alida
Alina
Aline
Alisa
Alise
Alisha
Alishia
Alisia
Alison
Alissa
Alita
Alix
Aliza
Alla
Allan
Alleen
Allegra
Allen
Allena
Allene
Allie
Alline
Allison
Allyn
Allyson
Alma
Almeda
Almeta
Alona
Alonso
Alonzo
Alpha
Alphonse
Alphonso
Alta
Altagracia
Altha
Althea
Alton
Alva
Alvaro
Alvera
Alverta
Alvin
Alvina
Alyce
Alycia
Alysa
Alyse
Alysha
Alysia
Alyson
Alyssa
Amada
Amado
Amal
Amalia
Amanda
Amber
Amberly
Ambrose
Amee
Amelia
America
Ami
Amie
Amiee
Amina
Amira
Ammie
Amos
Amparo
Amy
An
Ana
Anabel
Analisa
Anamaria
Anastacia
Anastasia
Andera
Anderson
Andra
Andre
Andrea
Andreas
Andree
Andres
Andrew
Andria
Andy
Anette
Angel
Angela
Angele
Angelena
Angeles
Angelia
Angelic
Angelica
Angelika
Angelina
Angeline
Angelique
Angelita
Angella
Angelo
Angelyn
Angie
Angila
Angla
Angle
Anglea
Anh
Anibal
Anika
Anisa
Anisha
Anissa
Anita
Anitra
Anja
Anjanette
Anjelica
Ann
Anna
Annabel
Annabell
Annabelle
Annalee
Annalisa
Annamae
Annamaria
Annamarie
Anne
Anneliese
Annelle
Annemarie
Annett
Annetta
Annette
Annice
Annie
Annika
Annis
Annita
Annmarie
Anthony
Antione
Antionette
Antoine
Antoinette
Anton
Antone
Antonetta
Antonette
Antonia
Antonietta
Antonina
Antonio
Antony
Antwan
Anya
Apolonia
April
Apryl
Ara
Araceli
Aracelis
Aracely
Arcelia
Archie
Ardath
Ardelia
Ardell
Ardella
Ardelle
Arden
Ardis
Ardith
Aretha
Argelia
Argentina
Ariana
Ariane
Arianna
Arianne
Arica
Arie
Ariel
Arielle
Arla
Arlean
Arleen
Arlen
Arlena
Arlene
Arletha
Arletta
Arlette
Arlie
Arlinda
Arline
Arlyne
Armand
Armanda
Armandina
Armando
Armida
Arminda
Arnetta
Arnette
Arnita
Arnold
Arnoldo
Arnulfo
Aron
Arron
Art
Arthur
Artie
Arturo
Arvilla
Asa
Asha
Ashanti
Ashely
Ashlea
Ashlee
Ashleigh
Ashley
Ashli
Ashlie
Ashly
Ashlyn
Ashton
Asia
Asley
Assunta
Astrid
Asuncion
Athena
Aubrey
Audie
Audra
Audrea
Audrey
Audria
Audrie
Audry
August
Augusta
Augustina
Augustine
Augustus
Aundrea
Aura
Aurea
Aurelia
Aurelio
Aurora
Aurore
Austin
Autumn
Ava
Avelina
Avery
Avis
Avril
Awilda
Ayako
Ayana
Ayanna
Ayesha
Azalee
Azucena
Azzie
Babara
Babette
Bailey
Bambi
Bao
Barabara
Barb
Barbar
Barbara
Barbera
Barbie
Barbra
Bari
Barney
Barrett
Barrie
Barry
Bart
Barton
Basil
Basilia
Bea
Beata
Beatrice
Beatris
Beatriz
Beau
Beaulah
Bebe
Becki
Beckie
Becky
Bee
Belen
Belia
Belinda
Belkis
Bell
Bella
Belle
Belva
Ben
Benedict
Benita
Benito
Benjamin
Bennett
Bennie
Benny
Benton
Berenice
Berna
Bernadette
Bernadine
Bernard
Bernarda
Bernardina
Bernardine
Bernardo
Berneice
Bernetta
Bernice
Bernie
Berniece
Bernita
Berry
Bert
Berta
Bertha
Bertie
Bertram
Beryl
Bess
Bessie
Beth
Bethanie
Bethann
Bethany
Bethel
Betsey
Betsy
Bette
Bettie
Bettina
Betty
Bettyann
Bettye
Beula
Beulah
Bev
Beverlee
Beverley
Beverly
Bianca
Bibi
Bill
Billi
Billie
Billy
Billye
Birdie
Birgit
Blaine
Blair
Blake
Blanca
Blanch
Blanche
Blondell
Blossom
Blythe
Bo
Bob
Bobbi
Bobbie
Bobby
Bobbye
Bobette
Bok
Bong
Bonita
Bonnie
Bonny
Booker
Boris
Boyce
Boyd
Brad
Bradford
Bradley
Bradly
Brady
Brain
Branda
Brande
Brandee
Branden
Brandi
Brandie
Brandon
Brandy
Brant
Breana
Breann
Breanna
Breanne
Bree
Brenda
Brendan
Brendon
Brenna
Brent
Brenton
Bret
Brett
Brian
Briana
Brianna
Brianne
Brice
Bridget
Bridgett
Bridgette
Brigette
Brigid
Brigida
Brigitte
Brinda
Britany
Britney
Britni
Britt
Britta
Brittaney
Brittani
Brittanie
Brittany
Britteny
Brittney
Brittni
Brittny
Brock
Broderick
Bronwyn
Brook
Brooke
Brooks
Bruce
Bruna
Brunilda
Bruno
Bryan
Bryanna
Bryant
Bryce
Brynn
Bryon
Buck
Bud
Buddy
Buena
Buffy
Buford
Bula
Bulah
Bunny
Burl
Burma
Burt
Burton
Buster
Byron
Caitlin
Caitlyn
Calandra
Caleb
Calista
Callie
Calvin
Camelia
Camellia
Cameron
Cami
Camie
Camila
Camilla
Camille
Cammie
Cammy
Candace
Candance
Candelaria
Candi
Candice
Candida
Candie
Candis
Candra
Candy
Candyce
Caprice
Cara
Caren
Carey
Cari
Caridad
Carie
Carin
Carina
Carisa
Carissa
Carita
Carl
Carla
Carlee
Carleen
Carlena
Carlene
Carletta
Carley
Carli
Carlie
Carline
Carlita
Carlo
Carlos
Carlota
Carlotta
Carlton
Carly
Carlyn
Carma
Carman
Carmel
Carmela
Carmelia
Carmelina
Carmelita
Carmella
Carmelo
Carmen
Carmina
Carmine
Carmon
Carol
Carola
Carolann
Carole
Carolee
Carolin
Carolina
Caroline
Caroll
Carolyn
Carolyne
Carolynn
Caron
Caroyln
Carri
Carrie
Carrol
Carroll
Carry
Carson
Carter
Cary
Caryl
Carylon
Caryn
Casandra
Casey
Casie
Casimira
Cassandra
Cassaundra
Cassey
Cassi
Cassidy
Cassie
Cassondra
Cassy
Catalina
Catarina
Caterina
Catharine
Catherin
Catherina
Catherine
Cathern
Catheryn
Cathey
Cathi
Cathie
Cathleen
Cathrine
Cathryn
Cathy
Catina
Catrice
Catrina
Cayla
Cecelia
Cecil
Cecila
Cecile
Cecilia
Cecille
Cecily
Cedric
Cedrick
Celena
Celesta
Celeste
Celestina
Celestine
Celia
Celina
Celinda
Celine
Celsa
Ceola
Cesar
Chad
Chadwick
Chae
Chan
Chana
Chance
Chanda
Chandra
Chanel
Chanell
Chanelle
Chang
Chantal
Chantay
Chante
Chantel
Chantell
Chantelle
Chara
Charis
Charise
Charissa
Charisse
Charita
Charity
Charla
Charleen
Charlena
Charlene
Charles
Charlesetta
Charlette
Charley
Charlie
Charline
Charlott
Charlotte
Charlsie
Charlyn
Charmain
Charmaine
Charolette
Chas
Chase
Chasidy
Chasity
Chassidy
Chastity
Chau
Chauncey
Chaya
Chelsea
Chelsey
Chelsie
Cher
Chere
Cheree
Cherelle
Cheri
Cherie
Cherilyn
Cherise
Cherish
Cherly
Cherlyn
Cherri
Cherrie
Cherry
Cherryl
Chery
Cheryl
Cheryle
Cheryll
Chester
Chet
Cheyenne
Chi
Chia
Chieko
Chin
China
Ching
Chiquita
Chloe
Chong
Chris
Chrissy
Christa
Christal
Christeen
Christel
Christen
Christena
Christene
Christi
Christia
Christian
Christiana
Christiane
Christie
Christin
Christina
Christine
Christinia
Christoper
Christopher
Christy
Chrystal
Chu
Chuck
Chun
Chung
Ciara
Cicely
Ciera
Cierra
Cinda
Cinderella
Cindi
Cindie
Cindy
Cinthia
Cira
Clair
Claire
Clara
Clare
Clarence
Claretha
Claretta
Claribel
Clarice
Clarinda
Clarine
Claris
Clarisa
Clarissa
Clarita
Clark
Classie
Claud
Claude
Claudette
Claudia
Claudie
Claudine
Claudio
Clay
Clayton
Clelia
Clemencia
Clement
Clemente
Clementina
Clementine
Clemmie
Cleo
Cleopatra
Cleora
Cleotilde
Cleta
Cletus
Cleveland
Cliff
Clifford
Clifton
Clint
Clinton
Clora
Clorinda
Clotilde
Clyde
Codi
Cody
Colby
Cole
Coleen
Coleman
Colene
Coletta
Colette
Colin
Colleen
Collen
Collene
Collette
Collin
Colton
Columbus
Concepcion
Conception
Concetta
Concha
Conchita
Connie
Conrad
Constance
Consuela
Consuelo
Contessa
Cora
Coral
Coralee
Coralie
Corazon
Cordelia
Cordell
Cordia
Cordie
Coreen
Corene
Coretta
Corey
Cori
Corie
Corina
Corine
Corinna
Corinne
Corliss
Cornelia
Cornelius
Cornell
Corrie
Corrin
Corrina
Corrine
Corrinne
Cortez
Cortney
Cory
Courtney
Coy
Craig
Creola
Cris
Criselda
Crissy
Crista
Cristal
Cristen
Cristi
Cristie
Cristin
Cristina
Cristine
Cristobal
Cristopher
Cristy
Cruz
Crysta
Crystal
Crystle
Cuc
Curt
Curtis
Cyndi
Cyndy
Cynthia
Cyril
Cyrstal
Cyrus
Cythia
Dacia
Dagmar
Dagny
Dahlia
Daina
Daine
Daisey
Daisy
Dakota
Dale
Dalene
Dalia
Dalila
Dallas
Dalton
Damaris
Damian
Damien
Damion
Damon
Dan
Dana
Danae
Dane
Danelle
Danette
Dani
Dania
Danial
Danica
Daniel
Daniela
Daniele
Daniell
Daniella
Danielle
Danika
Danille
Danilo
Danita
Dann
Danna
Dannette
Dannie
Dannielle
Danny
Dante
Danuta
Danyel
Danyell
Danyelle
Daphine
Daphne
Dara
Darby
Darcel
Darcey
Darci
Darcie
Darcy
Darell
Daren
Daria
Darin
Dario
Darius
Darla
Darleen
Darlena
Darlene
Darline
Darnell
Daron
Darrel
Darrell
Darren
Darrick
Darrin
Darron
Darryl
Darwin
Daryl
Dave
David
Davida
Davina
Davis
Dawn
Dawna
Dawne
Dayle
Dayna
Daysi
Deadra
Dean
Deana
Deandra
Deandre
Deandrea
Deane
Deangelo
Deann
Deanna
Deanne
Deb
Debbi
Debbie
Debbra
Debby
Debera
Debi
Debora
Deborah
Debra
Debrah
Debroah
Dede
Dedra
Dee
Deeann
Deeanna
Deedee
Deedra
Deena
Deetta
Deidra
Deidre
Deirdre
Deja
Del
Delaine
Delana
Delbert
Delcie
Delena
Delfina
Delia
Delicia
Delila
Delilah
Delinda
Delisa
Dell
Della
Delma
Delmar
Delmer
Delmy
Delois
Deloise
Delora
Deloras
Delores
Deloris
Delorse
Delpha
Delphia
Delphine
Delsie
Delta
Demarcus
Demetra
Demetria
Demetrice
Demetrius
Dena
Denae
Deneen
Denese
Denice
Denis
Denise
Denisha
Denisse
Denita
Denna
Dennis
Dennise
Denny
Denver
Denyse
Deon
Deonna
Derek
Derick
Derrick
Deshawn
Desirae
Desire
Desiree
Desmond
Despina
Dessie
Destiny
Detra
Devin
Devon
Devona
Devora
Devorah
Dewayne
Dewey
Dewitt
Dexter
Dia
Diamond
Dian
Diana
Diane
Diann
Dianna
Dianne
Dick
Diedra
Diedre
Diego
Dierdre
Digna
Dillon
Dimple
Dina
Dinah
Dino
Dinorah
Dion
Dione
Dionna
Dionne
Dirk
Divina
Dixie
Dodie
Dollie
Dolly
Dolores
Doloris
Domenic
Domenica
Dominga
Domingo
Dominic
Dominica
Dominick
Dominique
Dominque
Domitila
Domonique
Don
Dona
Donald
Donella
Donetta
Donette
Dong
Donita
Donn
Donna
Donnell
Donnetta
Donnette
Donnie
Donny
Donovan
Donte
Donya
Dora
Dorathy
Dorcas
Doreatha
Doreen
Dorene
Doretha
Dorethea
Doretta
Dori
Doria
Dorian
Dorie
Dorinda
Dorine
Doris
Dorla
Dorotha
Dorothea
Dorothy
Dorris
Dorsey
Dortha
Dorthea
Dorthey
Dorthy
Dot
Dottie
Dotty
Doug
Douglas
Douglass
Dovie
Doyle
Dreama
Drema
Drew
Drucilla
Drusilla
Duane
Dudley
Dulce
Dulcie
Duncan
Dung
Dusti
Dustin
Dusty
Dwain
Dwana
Dwayne
Dwight
Dyan
Dylan
Earl
Earle
Earlean
Earleen
Earlene
Earlie
Earline
Earnest
Earnestine
Eartha
Easter
Eboni
Ebonie
Ebony
Echo
Ed
Eda
Edda
Eddie
Eddy
Edelmira
Eden
Edgar
Edgardo
Edie
Edison
Edith
Edmond
Edmund
Edmundo
Edna
Edra
Edris
Eduardo
Edward
Edwardo
Edwin
Edwina
Edyth
Edythe
Effie
Efrain
Efren
Ehtel
Eileen
Eilene
Ela
Eladia
Elaina
Elaine
Elana
Elane
Elanor
Elayne
Elba
Elbert
Elda
Elden
Eldon
Eldora
Eldridge
Eleanor
Eleanora
Eleanore
Elease
Elena
Elene
Eleni
Elenor
Elenora
Elenore
Eleonor
Eleonora
Eleonore
Elfreda
Elfrieda
Elfriede
Eli
Elia
Eliana
Elias
Elicia
Elida
Elidia
Elijah
Elin
Elina
Elinor
Elinore
Elisa
Elisabeth
Elise
Eliseo
Elisha
Elissa
Eliz
Eliza
Elizabet
Elizabeth
Elizbeth
Elizebeth
Elke
Ella
Ellamae
Ellan
Ellen
Ellena
Elli
Ellie
Elliot
Elliott
Ellis
Ellsworth
Elly
Ellyn
Elma
Elmer
Elmira
Elmo
Elna
Elnora
Elodia
Elois
Eloisa
Eloise
Elouise
Eloy
Elroy
Elsa
Else
Elsie
Elsy
Elton
Elva
Elvera
Elvia
Elvie
Elvin
Elvina
Elvira
Elvis
Elwanda
Elwood
Elyse
Elza
Ema
Emanuel
Emelda
Emelia
Emelina
Emeline
Emely
Emerald
Emerita
Emerson
Emery
Emiko
Emil
Emile
Emilee
Emilia
Emilie
Emilio
Emily
Emma
Emmaline
Emmanuel
Emmett
Emmie
Emmitt
Emmy
Emogene
Emory
Ena
Enda
Enedina
Eneida
Enid
Enoch
Enola
Enrique
Enriqueta
Epifania
Era
Erasmo
Eric
Erica
Erich
Erick
Ericka
Erik
Erika
Erin
Erinn
Erlene
Erlinda
Erline
Erma
Ermelinda
Erminia
Erna
Ernest
Ernestina
Ernestine
Ernesto
Ernie
Errol
Ervin
Erwin
Eryn
Esmeralda
Esperanza
Essie
Esta
Esteban
Estefana
Estela
Estell
Estella
Estelle
Ester
Esther
Estrella
Etha
Ethan
Ethel
Ethelene
Ethelyn
Ethyl
Etsuko
Etta
Ettie
Eufemia
Eugena
Eugene
Eugenia
Eugenie
Eugenio
Eula
Eulah
Eulalia
Eun
Euna
Eunice
Eura
Eusebia
Eusebio
Eustolia
Eva
Evalyn
Evan
Evangelina
Evangeline
Eve
Evelia
Evelin
Evelina
Eveline
Evelyn
Evelyne
Evelynn
Everett
Everette
Evette
Evia
Evie
Evita
Evon
Evonne
Ewa
Exie
Ezekiel
Ezequiel
Ezra
Fabian
Fabiola
Fae
Fairy
Faith
Fallon
Fannie
Fanny
Farah
Farrah
Fatima
Fatimah
Faustina
Faustino
Fausto
Faviola
Fawn
Fay
Faye
Fe
Federico
Felecia
Felica
Felice
Felicia
Felicidad
Felicita
Felicitas
Felipa
Felipe
Felisa
Felisha
Felix
Felton
Ferdinand
Fermin
Fermina
Fern
Fernanda
Fernande
Fernando
Ferne
Fidel
Fidela
Fidelia
Filiberto
Filomena
Fiona
Flavia
Fleta
Fletcher
Flo
Flor
Flora
Florance
Florence
Florencia
Florencio
Florene
Florentina
Florentino
Floretta
Floria
Florida
Florinda
Florine
Florrie
Flossie
Floy
Floyd
Fonda
Forest
Forrest
Foster
Fran
France
Francene
Frances
Francesca
Francesco
Franchesca
Francie
Francina
Francine
Francis
Francisca
Francisco
Francoise
Frank
Frankie
Franklin
Franklyn
Fransisca
Fred
Freda
Fredda
Freddie
Freddy
Frederic
Frederica
Frederick
Fredericka
Fredia
Fredric
Fredrick
Fredricka
Freeda
Freeman
Freida
Frida
Frieda
Fritz
Fumiko
Gabriel
Gabriela
Gabriele
Gabriella
Gabrielle
Gail
Gala
Gale
Galen
Galina
Garfield
Garland
Garnet
Garnett
Garret
Garrett
Garry
Garth
Gary
Gaston
Gavin
Gay
Gaye
Gayla
Gayle
Gaylene
Gaylord
Gaynell
Gaynelle
Gearldine
Gema
Gemma
Gena
Genaro
Gene
Genesis
Geneva
Genevie
Genevieve
Genevive
Genia
Genie
Genna
Gennie
Genny
Genoveva
Geoffrey
Georgann
George
Georgeann
Georgeanna
Georgene
Georgetta
Georgette
Georgia
Georgiana
Georgiann
Georgianna
Georgianne
Georgie
Georgina
Georgine
Gerald
Geraldine
Geraldo
Geralyn
Gerard
Gerardo
Gerda
Geri
Germaine
German
Gerri
Gerry
Gertha
Gertie
Gertrud
Gertrude
Gertrudis
Gertude
Ghislaine
Gia
Gianna
Gidget
Gigi
Gil
Gilbert
Gilberte
Gilberto
Gilda
Gillian
Gilma
Gina
Ginette
Ginger
Ginny
Gino
Giovanna
Giovanni
Gisela
Gisele
Giselle
Gita
Giuseppe
Giuseppina
Gladis
Glady
Gladys
Glayds
Glen
Glenda
Glendora
Glenn
Glenna
Glennie
Glennis
Glinda
Gloria
Glory
Glynda
Glynis
Golda
Golden
Goldie
Gonzalo
Gordon
Grace
Gracia
Gracie
Graciela
Grady
Graham
Graig
Grant
Granville
Grayce
Grazyna
Greg
Gregg
Gregoria
Gregorio
Gregory
Greta
Gretchen
Gretta
Gricelda
Grisel
Griselda
Grover
Guadalupe
Gudrun
Guillermina
Guillermo
Gus
Gussie
Gustavo
Guy
Gwen
Gwenda
Gwendolyn
Gwenn
Gwyn
Gwyneth
Ha
Hae
Hai
Hailey
Hal
Haley
Halina
Halley
Hallie
Han
Hana
Hang
Hanh
Hank
Hanna
Hannah
Hannelore
Hans
Harlan
Harland
Harley
Harmony
Harold
Harriet
Harriett
Harriette
Harris
Harrison
Harry
Harvey
Hassan
Hassie
Hattie
Haydee
Hayden
Hayley
Haywood
Hazel
Heath
Heather
Hector
Hedwig
Hedy
Hee
Heide
Heidi
Heidy
Heike
Helaine
Helen
Helena
Helene
Helga
Hellen
Henrietta
Henriette
Henry
Herb
Herbert
Heriberto
Herlinda
Herma
Herman
Hermelinda
Hermila
Hermina
Hermine
Herminia
Herschel
Hershel
Herta
Hertha
Hester
Hettie
Hiedi
Hien
Hilaria
Hilario
Hilary
Hilda
Hilde
Hildegard
Hildegarde
Hildred
Hillary
Hilma
Hilton
Hipolito
Hiram
Hiroko
Hisako
Hoa
Hobert
Holley
Holli
Hollie
Hollis
Holly
Homer
Honey
Hong
Hope
Horace
Horacio
Hortencia
Hortense
Hortensia
Hosea
Houston
Howard
Hoyt
Hsiu
Hubert
Hue
Huey
Hugh
Hugo
Hui
Hulda
Humberto
Hung
Hunter
Huong
Hwa
Hyacinth
Hye
Hyman
Hyo
Hyon
Hyun
Ian
Ida
Idalia
Idell
Idella
Iesha
Ignacia
Ignacio
Ike
Ila
Ilana
Ilda
Ileana
Ileen
Ilene
Iliana
Illa
Ilona
Ilse
Iluminada
Ima
Imelda
Imogene
In
Ina
India
Indira
Inell
Ines
Inez
Inga
Inge
Ingeborg
Inger
Ingrid
Inocencia
Iola
Iona
Ione
Ira
Iraida
Irena
Irene
Irina
Iris
Irish
Irma
Irmgard
Irvin
Irving
Irwin
Isa
Isaac
Isabel
Isabell
Isabella
Isabelle
Isadora
Isaiah
Isaias
Isaura
Isela
Isiah
Isidra
Isidro
Isis
Ismael
Isobel
Israel
Isreal
Issac
Iva
Ivan
Ivana
Ivelisse
Ivette
Ivey
Ivonne
Ivory
Ivy
Izetta
Izola
Ja
Jacalyn
Jacelyn
Jacinda
Jacinta
Jacinto
Jack
Jackeline
Jackelyn
Jacki
Jackie
Jacklyn
Jackqueline
Jackson
Jaclyn
Jacob
Jacqualine
Jacque
Jacquelin
Jacqueline
Jacquelyn
Jacquelyne
Jacquelynn
Jacques
Jacquetta
Jacqui
Jacquie
Jacquiline
Jacquline
Jacqulyn
Jada
Jade
Jadwiga
Jae
Jaime
Jaimee
Jaimie
Jake
Jaleesa
Jalisa
Jama
Jamaal
Jamal
Jamar
Jame
Jamee
Jamel
James
Jamey
Jami
Jamie
Jamika
Jamila
Jamison
Jammie
Jan
Jana
Janae
Janay
Jane
Janean
Janee
Janeen
Janel
Janell
Janella
Janelle
Janene
Janessa
Janet
Janeth
Janett
Janetta
Janette
Janey
Jani
Janice
Janie
Janiece
Janina
Janine
Janis
Janise
Janita
Jann
Janna
Jannet
Jannette
Jannie
January
Janyce
Jaqueline
Jaquelyn
Jared
Jarod
Jarred
Jarrett
Jarrod
Jarvis
Jasmin
Jasmine
Jason
Jasper
Jaunita
Javier
Jay
Jaye
Jayme
Jaymie
Jayna
Jayne
Jayson
Jazmin
Jazmine
Jc
Jean
Jeana
Jeane
Jeanelle
Jeanene
Jeanett
Jeanetta
Jeanette
Jeanice
Jeanie
Jeanine
Jeanmarie
Jeanna
Jeanne
Jeannetta
Jeannette
Jeannie
Jeannine
Jed
Jeff
Jefferey
Jefferson
Jeffery
Jeffie
Jeffrey
Jeffry
Jen
Jena
Jenae
Jene
Jenee
Jenell
Jenelle
Jenette
Jeneva
Jeni
Jenice
Jenifer
Jeniffer
Jenine
Jenise
Jenna
Jennefer
Jennell
Jennette
Jenni
Jennie
Jennifer
Jenniffer
Jennine
Jenny
Jerald
Jeraldine
Jeramy
Jere
Jeremiah
Jeremy
Jeri
Jerica
Jerilyn
Jerlene
Jermaine
Jerold
Jerome
Jeromy
Jerrell
Jerri
Jerrica
Jerrie
Jerrod
Jerrold
Jerry
Jesenia
Jesica
Jess
Jesse
Jessenia
Jessi
Jessia
Jessica
Jessie
Jessika
Jestine
Jesus
Jesusa
Jesusita
Jetta
Jettie
Jewel
Jewell
Ji
Jill
Jillian
Jim
Jimmie
Jimmy
Jin
Jina
Jinny
Jo
Joan
Joana
Joane
Joanie
Joann
Joanna
Joanne
Joannie
Joaquin
Joaquina
Jocelyn
Jodee
Jodi
Jodie
Jody
Joe
Joeann
Joel
Joella
Joelle
Joellen
Joesph
Joetta
Joette
Joey
Johana
Johanna
Johanne
John
Johna
Johnathan
Johnathon
Johnetta
Johnette
Johnie
Johnna
Johnnie
Johnny
Johnsie
Johnson
Joi
Joie
Jolanda
Joleen
Jolene
Jolie
Joline
Jolyn
Jolynn
Jon
Jona
Jonah
Jonas
Jonathan
Jonathon
Jone
Jonell
Jonelle
Jong
Joni
Jonie
Jonna
Jonnie
Jordan
Jordon
Jorge
Jose
Josef
Josefa
Josefina
Josefine
Joselyn
Joseph
Josephina
Josephine
Josette
Josh
Joshua
Josiah
Josie
Joslyn
Jospeh
Josphine
Josue
Jovan
Jovita
Joy
Joya
Joyce
Joycelyn
Joye
Juan
Juana
Juanita
Jude
Judi
Judie
Judith
Judson
Judy
Jule
Julee
Julene
Jules
Juli
Julia
Julian
Juliana
Juliane
Juliann
Julianna
Julianne
Julie
Julieann
Julienne
Juliet
Julieta
Julietta
Juliette
Julio
Julissa
Julius
June
Jung
Junie
Junior
Junita
Junko
Justa
Justin
Justina
Justine
Jutta
Ka
Kacey
Kaci
Kacie
Kacy
Kai
Kaila
Kaitlin
Kaitlyn
Kala
Kaleigh
Kaley
Kali
Kallie
Kalyn
Kam
Kamala
Kami
Kamilah
Kandace
Kandi
Kandice
Kandis
Kandra
Kandy
Kanesha
Kanisha
Kara
Karan
Kareem
Kareen
Karen
Karena
Karey
Kari
Karie
Karima
Karin
Karina
Karine
Karisa
Karissa
Karl
Karla
Karleen
Karlene
Karly
Karlyn
Karma
Karmen
Karol
Karole
Karoline
Karolyn
Karon
Karren
Karri
Karrie
Karry
Kary
Karyl
Karyn
Kasandra
Kasey
Kasha
Kasi
Kasie
Kassandra
Kassie
Kate
Katelin
Katelyn
Katelynn
Katerine
Kathaleen
Katharina
Katharine
Katharyn
Kathe
Katheleen
Katherin
Katherina
Katherine
Kathern
Katheryn
Kathey
Kathi
Kathie
Kathleen
Kathlene
Kathline
Kathlyn
Kathrin
Kathrine
Kathryn
Kathryne
Kathy
Kathyrn
Kati
Katia
Katie
Katina
Katlyn
Katrice
Katrina
Kattie
Katy
Kay
Kayce
Kaycee
Kaye
Kayla
Kaylee
Kayleen
Kayleigh
Kaylene
Kazuko
Kecia
Keeley
Keely
Keena
Keenan
Keesha
Keiko
Keila
Keira
Keisha
Keith
Keitha
Keli
Kelle
Kellee
Kelley
Kelli
Kellie
Kelly
Kellye
Kelsey
Kelsi
Kelsie
Kelvin
Kemberly
Ken
Kena
Kenda
Kendal
Kendall
Kendra
Kendrick
Keneth
Kenia
Kenisha
Kenna
Kenneth
Kennith
Kenny
Kent
Kenton
Kenya
Kenyatta
Kenyetta
Kera
Keren
Keri
Kermit
Kerri
Kerrie
Kerry
Kerstin
Kesha
Keshia
Keturah
Keva
Keven
Kevin
Khadijah
Khalilah
Kia
Kiana
Kiara
Kiera
Kiersten
Kiesha
Kieth
Kiley
Kim
Kimber
Kimberely
Kimberlee
Kimberley
Kimberli
Kimberlie
Kimberly
Kimbery
Kimbra
Kimi
Kimiko
Kina
Kindra
King
Kip
Kira
Kirby
Kirk
Kirsten
Kirstie
Kirstin
Kisha
Kit
Kittie
Kitty
Kiyoko
Kizzie
Kizzy
Klara
Korey
Kori
Kortney
Kory
Kourtney
Kraig
Kris
Krishna
Krissy
Krista
Kristal
Kristan
Kristeen
Kristel
Kristen
Kristi
Kristian
Kristie
Kristin
Kristina
Kristine
Kristle
Kristofer
Kristopher
Kristy
Kristyn
Krysta
Krystal
Krysten
Krystin
Krystina
Krystle
Krystyna
Kum
Kurt
Kurtis
Kyla
Kyle
Kylee
Kylie
Kym
Kymberly
Kyoko
Kyong
Kyra
Kyung
Lacey
Lachelle
Laci
Lacie
Lacresha
Lacy
Ladawn
Ladonna
Lady
Lael
Lahoma
Lai
Laila
Laine
Lajuana
Lakeesha
Lakeisha
Lakendra
Lakenya
Lakesha
Lakeshia
Lakia
Lakiesha
Lakisha
Lakita
Lala
Lamar
Lamonica
Lamont
Lan
Lana
Lance
Landon
Lane
Lanell
Lanelle
Lanette
Lang
Lani
Lanie
Lanita
Lannie
Lanny
Lanora
Laquanda
Laquita
Lara
Larae
Laraine
Laree
Larhonda
Larisa
Larissa
Larita
Laronda
Larraine
Larry
Larue
Lasandra
Lashanda
Lashandra
Lashaun
Lashaunda
Lashawn
Lashawna
Lashawnda
Lashay
Lashell
Lashon
Lashonda
Lashunda
Lasonya
Latanya
Latarsha
Latasha
Latashia
Latesha
Latia
Laticia
Latina
Latisha
Latonia
Latonya
Latoria
Latosha
Latoya
Latoyia
Latrice
Latricia
Latrina
Latrisha
Launa
Laura
Lauralee
Lauran
Laure
Laureen
Laurel
Lauren
Laurena
Laurence
Laurene
Lauretta
Laurette
Lauri
Laurice
Laurie
Laurinda
Laurine
Lauryn
Lavada
Lavelle
Lavenia
Lavera
Lavern
Laverna
Laverne
Laveta
Lavette
Lavina
Lavinia
Lavon
Lavona
Lavonda
Lavone
Lavonia
Lavonna
Lavonne
Lawana
Lawanda
Lawanna
Lawerence
Lawrence
Layla
Layne
Lazaro
Le
Lea
Leah
Lean
Leana
Leandra
Leandro
Leann
Leanna
Leanne
Leanora
Leatha
Leatrice
Lecia
Leda
Lee
Leeann
Leeanna
Leeanne
Leena
Leesa
Leia
Leida
Leif
Leigh
Leigha
Leighann
Leila
Leilani
Leisa
Leisha
Lekisha
Lela
Lelah
Leland
Lelia
Lemuel
Len
Lena
Lenard
Lenita
Lenna
Lennie
Lenny
Lenora
Lenore
Leo
Leola
Leoma
Leon
Leona
Leonard
Leonarda
Leonardo
Leone
Leonel
Leonia
Leonida
Leonie
Leonila
Leonor
Leonora
Leonore
Leontine
Leopoldo
Leora
Leota
Lera
Leroy
Les
Lesa
Lesha
Lesia
Leslee
Lesley
Lesli
Leslie
Lessie
Lester
Leta
Letha
Leticia
Letisha
Letitia
Lettie
Letty
Levi
Lewis
Lexie
Lezlie
Li
Lia
Liana
Liane
Lianne
Libbie
Libby
Liberty
Librada
Lida
Lidia
Lien
Lieselotte
Ligia
Lila
Lili
Lilia
Lilian
Liliana
Lilla
Lilli
Lillia
Lilliam
Lillian
Lilliana
Lillie
Lilly
Lily
Lin
Lina
Lincoln
Linda
Lindsay
Lindsey
Lindsy
Lindy
Linette
Ling
Linh
Linn
Linnea
Linnie
Lino
Linsey
Linwood
Lionel
Lisa
Lisabeth
Lisandra
Lisbeth
Lise
Lisette
Lisha
Lissa
Lissette
Lita
Livia
Liz
Liza
Lizabeth
Lizbeth
Lizeth
Lizette
Lizzette
Lizzie
Lloyd
Loan
Logan
Loida
Lois
Loise
Lola
Lolita
Loma
Lon
Lona
Londa
Long
Loni
Lonna
Lonnie
Lonny
Lora
Loraine
Loralee
Lore
Lorean
Loree
Loreen
Lorelei
Loren
Lorena
Lorene
Lorenza
Lorenzo
Loreta
Loretta
Lorette
Lori
Loria
Loriann
Lorie
Lorilee
Lorina
Lorinda
Lorine
Loris
Lorita
Lorna
Lorraine
Lorretta
Lorri
Lorriane
Lorrie
Lorrine
Lory
Lottie
Lou
Louann
Louanne
Louella
Louetta
Louie
Louis
Louisa
Louise
Loura
Lourdes
Lourie
Louvenia
Love
Lovella
Lovetta
Lovie
Lowell
Loyce
Loyd
Lu
Luana
Luann
Luanna
Luanne
Luba
Lucas
Luci
Lucia
Luciana
Luciano
Lucie
Lucien
Lucienne
Lucila
Lucile
Lucilla
Lucille
Lucina
Lucinda
Lucio
Lucius
Lucrecia
Lucretia
Lucy
Ludie
Ludivina
Lue
Luella
Luetta
Luigi
Luis
Luisa
Luise
Luke
Lula
Lulu
Luna
Lupe
Lupita
Lura
Lurlene
Lurline
Luther
Luvenia
Luz
Lyda
Lydia
Lyla
Lyle
Lyman
Lyn
Lynda
Lyndia
Lyndon
Lyndsay
Lyndsey
Lynell
Lynelle
Lynetta
Lynette
Lynn
Lynna
Lynne
Lynnette
Lynsey
Lynwood
Ma
Mabel
Mabelle
Mable
Mac
Machelle
Macie
Mack
Mackenzie
Macy
Madalene
Madaline
Madalyn
Maddie
Madelaine
Madeleine
Madelene
Madeline
Madelyn
Madge
Madie
Madison
Madlyn
Madonna
Mae
Maegan
Mafalda
Magali
Magaly
Magan
Magaret
Magda
Magdalen
Magdalena
Magdalene
Magen
Maggie
Magnolia
Mahalia
Mai
Maia
Maida
Maile
Maira
Maire
Maisha
Maisie
Major
Majorie
Makeda
Malcolm
Malcom
Malena
Malia
Malik
Malika
Malinda
Malisa
Malissa
Malka
Mallie
Mallory
Malorie
Malvina
Mamie
Mammie
Man
Mana
Manda
Mandi
Mandie
Mandy
Manie
Manual
Manuel
Manuela
Many
Mao
Maple
Mara
Maragaret
Maragret
Maranda
Marc
Marcel
Marcela
Marcelene
Marcelina
Marceline
Marcelino
Marcell
Marcella
Marcelle
Marcellus
Marcelo
Marcene
Marchelle
Marci
Marcia
Marcie
Marco
Marcos
Marcus
Marcy
Mardell
Maren
Marg
Margaret
Margareta
Margarete
Margarett
Margaretta
Margarette
Margarita
Margarite
Margarito
Margart
Marge
Margene
Margeret
Margert
Margery
Marget
Margherita
Margie
Margit
Margo
Margorie
Margot
Margret
Margrett
Marguerita
Marguerite
Margurite
Margy
Marhta
Mari
Maria
Mariah
Mariam
Marian
Mariana
Marianela
Mariann
Marianna
Marianne
Mariano
Maribel
Maribeth
Marica
Maricela
Maricruz
Marie
Mariel
Mariela
Mariella
Marielle
Marietta
Mariette
Mariko
Marilee
Marilou
Marilu
Marilyn
Marilynn
Marin
Marina
Marinda
Marine
Mario
Marion
Maris
Marisa
Marisela
Marisha
Marisol
Marissa
Marita
Maritza
Marivel
Marjorie
Marjory
Mark
Marketta
Markita
Markus
Marla
Marlana
Marleen
Marlen
Marlena
Marlene
Marlin
Marline
Marlo
Marlon
Marlyn
Marlys
Marna
Marni
Marnie
Marquerite
Marquetta
Marquis
Marquita
Marquitta
Marry
Marsha
Marshall
Marta
Marth
Martha
Marti
Martin
Martina
Martine
Marty
Marva
Marvel
Marvella
Marvin
Marvis
Marx
Mary
Marya
Maryalice
Maryam
Maryann
Maryanna
Maryanne
Marybelle
Marybeth
Maryellen
Maryetta
Maryjane
Maryjo
Maryland
Marylee
Marylin
Maryln
Marylou
Marylouise
Marylyn
Marylynn
Maryrose
Masako
Mason
Matha
Mathew
Mathilda
Mathilde
Matilda
Matilde
Matt
Matthew
Mattie
Maud
Maude
Maudie
Maura
Maureen
Maurice
Mauricio
Maurine
Maurita
Mauro
Mavis
Max
Maxie
Maxima
Maximina
Maximo
Maxine
Maxwell
May
Maya
Maybell
Maybelle
Maye
Mayme
Maynard
Mayola
Mayra
Mazie
Mckenzie
Mckinley
Meagan
Meaghan
Mechelle
Meda
Mee
Meg
Megan
Meggan
Meghan
Meghann
Mei
Mel
Melaine
Melani
Melania
Melanie
Melany
Melba
Melda
Melia
Melida
Melina
Melinda
Melisa
Melissa
Melissia
Melita
Mellie
Mellisa
Mellissa
Melodee
Melodi
Melodie
Melody
Melonie
Melony
Melva
Melvin
Melvina
Melynda
Mendy
Mercedes
Mercedez
Mercy
Meredith
Meri
Merideth
Meridith
Merilyn
Merissa
Merle
Merlene
Merlin
Merlyn
Merna
Merri
Merrie
Merrilee
Merrill
Merry
Mertie
Mervin
Meryl
Meta
Mi
Mia
Mica
Micaela
Micah
Micha
Michael
Michaela
Michaele
Michal
Michale
Micheal
Michel
Michele
Michelina
Micheline
Michell
Michelle
Michiko
Mickey
Micki
Mickie
Miesha
Migdalia
Mignon
Miguel
Miguelina
Mika
Mikaela
Mike
Mikel
Miki
Mikki
Mila
Milagro
Milagros
Milan
Milda
Mildred
Miles
Milford
Milissa
Millard
Millicent
Millie
Milly
Milo
Milton
Mimi
Min
Mina
Minda
Mindi
Mindy
Minerva
Ming
Minh
Minna
Minnie
Minta
Miquel
Mira
Miranda
Mireille
Mirella
Mireya
Miriam
Mirian
Mirna
Mirta
Mirtha
Misha
Miss
Missy
Misti
Mistie
Misty
Mitch
Mitchel
Mitchell
Mitsue
Mitsuko
Mittie
Mitzi
Mitzie
Miyoko
Modesta
Modesto
Mohamed
Mohammad
Mohammed
Moira
Moises
Mollie
Molly
Mona
Monet
Monica
Monika
Monique
Monnie
Monroe
Monserrate
Monte
Monty
Moon
Mora
Morgan
Moriah
Morris
Morton
Mose
Moses
Moshe
Mozell
Mozella
Mozelle
Mui
Muoi
Muriel
Murray
My
Myesha
Myles
Myong
Myra
Myriam
Myrl
Myrle
Myrna
Myron
Myrta
Myrtice
Myrtie
Myrtis
Myrtle
Myung
Na
Nada
Nadene
Nadia
Nadine
Naida
Nakesha
Nakia
Nakisha
Nakita
Nam
Nan
Nana
Nancee
Nancey
Nanci
Nancie
Nancy
Nanette
Nannette
Nannie
Naoma
Naomi
Napoleon
Narcisa
Natacha
Natalia
Natalie
Natalya
Natasha
Natashia
Nathalie
Nathan
Nathanael
Nathanial
Nathaniel
Natisha
Natividad
Natosha
Neal
Necole
Ned
Neda
Nedra
Neely
Neida
Neil
Nelda
Nelia
Nelida
Nell
Nella
Nelle
Nellie
Nelly
Nelson
Nena
Nenita
Neoma
Neomi
Nereida
Nerissa
Nery
Nestor
Neta
Nettie
Neva
Nevada
Neville
Newton
Nga
Ngan
Ngoc
Nguyet
Nia
Nichelle
Nichol
Nicholas
Nichole
Nicholle
Nick
Nicki
Nickie
Nickolas
Nickole
Nicky
Nicol
Nicola
Nicolas
Nicolasa
Nicole
Nicolette
Nicolle
Nida
Nidia
Niesha
Nieves
Nigel
Niki
Nikia
Nikita
Nikki
Nikole
Nila
Nilda
Nilsa
Nina
Ninfa
Nisha
Nita
Noah
Noble
Nobuko
Noe
Noel
Noelia
Noella
Noelle
Noemi
Nohemi
Nola
Nolan
Noma
Nona
Nora
Norah
Norbert
Norberto
Noreen
Norene
Noriko
Norine
Norma
Norman
Normand
Norris
Nova
Novella
Nu
Nubia
Numbers
Nydia
Nyla
Obdulia
Ocie
Octavia
Octavio
Oda
Odelia
Odell
Odessa
Odette
Odilia
Odis
Ofelia
Ok
Ola
Olen
Olene
Oleta
Olevia
Olga
Olimpia
Olin
Olinda
Oliva
Olive
Oliver
Olivia
Ollie
Olympia
Oma
Omar
Omega
Omer
Ona
Oneida
Onie
Onita
Opal
Ophelia
Ora
Oralee
Oralia
Oren
Oretha
Orlando
Orpha
Orval
Orville
Oscar
Ossie
Osvaldo
Oswaldo
Otelia
Otha
Otilia
Otis
Otto
Ouida
Owen
Ozell
Ozella
Ozie
Pa
Pablo
Page
Paige
Palma
Palmer
Palmira
Pam
Pamala
Pamela
Pamelia
Pamella
Pamila
Pamula
Pandora
Pansy
Paola
Paris
Parker
Parthenia
Particia
Pasquale
Pasty
Pat
Patience
Patria
Patrica
Patrice
Patricia
Patrick
Patrina
Patsy
Patti
Pattie
Patty
Paul
Paula
Paulene
Pauletta
Paulette
Paulina
Pauline
Paulita
Paz
Pearl
Pearle
Pearlene
Pearlie
Pearline
Pearly
Pedro
Peg
Peggie
Peggy
Pei
Penelope
Penney
Penni
Pennie
Penny
Percy
Perla
Perry
Pete
Peter
Petra
Petrina
Petronila
Phebe
Phil
Philip
Phillip
Phillis
Philomena
Phoebe
Phung
Phuong
Phylicia
Phylis
Phyliss
Phyllis
Pia
Piedad
Pierre
Pilar
Ping
Pinkie
Piper
Pok
Polly
Porfirio
Porsche
Porsha
Porter
Portia
Precious
Preston
Pricilla
Prince
Princess
Priscila
Priscilla
Providencia
Prudence
Pura
Qiana
Queen
Queenie
Quentin
Quiana
Quincy
Quinn
Quintin
Quinton
Quyen
Rachael
Rachal
Racheal
Rachel
Rachele
Rachell
Rachelle
Racquel
Rae
Raeann
Raelene
Rafael
Rafaela
Raguel
Raina
Raisa
Raleigh
Ralph
Ramiro
Ramon
Ramona
Ramonita
Rana
Ranae
Randa
Randal
Randall
Randee
Randell
Randi
Randolph
Randy
Ranee
Raphael
Raquel
Rashad
Rasheeda
Rashida
Raul
Raven
Ray
Raye
Rayford
Raylene
Raymon
Raymond
Raymonde
Raymundo
Rayna
Rea
Reagan
Reanna
Reatha
Reba
Rebbeca
Rebbecca
Rebeca
Rebecca
Rebecka
Rebekah
Reda
Reed
Reena
Refugia
Refugio
Regan
Regena
Regenia
Reggie
Regina
Reginald
Regine
Reginia
Reid
Reiko
Reina
Reinaldo
Reita
Rema
Remedios
Remona
Rena
Renae
Renaldo
Renata
Renate
Renato
Renay
Renda
Rene
Renea
Renee
Renetta
Renita
Renna
Ressie
Reta
Retha
Retta
Reuben
Reva
Rex
Rey
Reyes
Reyna
Reynalda
Reynaldo
Rhea
Rheba
Rhett
Rhiannon
Rhoda
Rhona
Rhonda
Ria
Ricarda
Ricardo
Rich
Richard
Richelle
Richie
Rick
Rickey
Ricki
Rickie
Ricky
Rico
Rigoberto
Rikki
Riley
Rima
Rina
Risa
Rita
Riva
Rivka
Rob
Robbi
Robbie
Robbin
Robby
Robbyn
Robena
Robert
Roberta
Roberto
Robin
Robt
Robyn
Rocco
Rochel
Rochell
Rochelle
Rocio
Rocky
Rod
Roderick
Rodger
Rodney
Rodolfo
Rodrick
Rodrigo
Rogelio
Roger
Roland
Rolanda
Rolande
Rolando
Rolf
Rolland
Roma
Romaine
Roman
Romana
Romelia
Romeo
Romona
Ron
Rona
Ronald
Ronda
Roni
Ronna
Ronni
Ronnie
Ronny
Roosevelt
Rory
Rosa
Rosalba
Rosalee
Rosalia
Rosalie
Rosalina
Rosalind
Rosalinda
Rosaline
Rosalva
Rosalyn
Rosamaria
Rosamond
Rosana
Rosann
Rosanna
Rosanne
Rosaria
Rosario
Rosaura
Roscoe
Rose
Roseann
Roseanna
Roseanne
Roselee
Roselia
Roseline
Rosella
Roselle
Roselyn
Rosemarie
Rosemary
Rosena
Rosenda
Rosendo
Rosetta
Rosette
Rosia
Rosie
Rosina
Rosio
Rosita
Roslyn
Ross
Rossana
Rossie
Rosy
Rowena
Roxana
Roxane
Roxann
Roxanna
Roxanne
Roxie
Roxy
Roy
Royal
Royce
Rozanne
Rozella
Ruben
Rubi
Rubie
Rubin
Ruby
Rubye
Rudolf
Rudolph
Rudy
Rueben
Rufina
Rufus
Rupert
Russ
Russel
Russell
Rusty
Ruth
Rutha
Ruthann
Ruthanne
Ruthe
Ruthie
Ryan
Ryann
Sabina
Sabine
Sabra
Sabrina
Sacha
Sachiko
Sade
Sadie
Sadye
Sage
Sal
Salena
Salina
Salley
Sallie
Sally
Salome
Salvador
Salvatore
Sam
Samantha
Samara
Samatha
Samella
Samira
Sammie
Sammy
Samual
Samuel
Sana
Sanda
Sandee
Sandi
Sandie
Sandra
Sandy
Sanford
Sang
Sanjuana
Sanjuanita
Sanora
Santa
Santana
Santiago
Santina
Santo
Santos
Sara
Sarah
Sarai
Saran
Sari
Sarina
Sarita
Sasha
Saturnina
Sau
Saul
Saundra
Savanna
Savannah
Scarlet
Scarlett
Scot
Scott
Scottie
Scotty
Sean
Season
Sebastian
Sebrina
See
Seema
Selena
Selene
Selina
Selma
Sena
Senaida
September
Serafina
Serena
Sergio
Serina
Serita
Seth
Setsuko
Seymour
Sha
Shad
Shae
Shaina
Shakia
Shakira
Shakita
Shala
Shalanda
Shalon
Shalonda
Shameka
Shamika
Shan
Shana
Shanae
Shanda
Shandi
Shandra
Shane
Shaneka
Shanel
Shanell
Shanelle
Shani
Shanice
Shanika
Shaniqua
Shanita
Shanna
Shannan
Shannon
Shanon
Shanta
Shantae
Shantay
Shante
Shantel
Shantell
Shantelle
Shanti
Shaquana
Shaquita
Shara
Sharan
Sharda
Sharee
Sharell
Sharen
Shari
Sharice
Sharie
Sharika
Sharilyn
Sharita
Sharla
Sharleen
Sharlene
Sharmaine
Sharolyn
Sharon
Sharonda
Sharri
Sharron
Sharyl
Sharyn
Shasta
Shaun
Shauna
Shaunda
Shaunna
Shaunta
Shaunte
Shavon
Shavonda
Shavonne
Shawana
Shawanda
Shawanna
Shawn
Shawna
Shawnda
Shawnee
Shawnna
Shawnta
Shay
Shayla
Shayna
Shayne
Shea
Sheba
Sheena
Sheila
Sheilah
Shela
Shelba
Shelby
Sheldon
Shelia
Shella
Shelley
Shelli
Shellie
Shelly
Shelton
Shemeka
Shemika
Shena
Shenika
Shenita
Shenna
Shera
Sheree
Sherell
Sheri
Sherice
Sheridan
Sherie
Sherika
Sherill
Sherilyn
Sherise
Sherita
Sherlene
Sherley
Sherly
Sherlyn
Sherman
Sheron
Sherrell
Sherri
Sherrie
Sherril
Sherrill
Sherron
Sherry
Sherryl
Sherwood
Shery
Sheryl
Sheryll
Shiela
Shila
Shiloh
Shin
Shira
Shirely
Shirl
Shirlee
Shirleen
Shirlene
Shirley
Shirly
Shizue
Shizuko
Shon
Shona
Shonda
Shondra
Shonna
Shonta
Shoshana
Shu
Shyla
Sibyl
Sid
Sidney
Sierra
Signe
Sigrid
Silas
Silva
Silvana
Silvia
Sima
Simon
Simona
Simone
Simonne
Sina
Sindy
Siobhan
Sirena
Siu
Sixta
Skye
Slyvia
So
Socorro
Sofia
Soila
Sol
Solange
Soledad
Solomon
Somer
Sommer
Son
Sona
Sondra
Song
Sonia
Sonja
Sonny
Sonya
Soo
Sook
Soon
Sophia
Sophie
Soraya
Sparkle
Spencer
Spring
Stacee
Stacey
Staci
Stacia
Stacie
Stacy
Stan
Stanford
Stanley
Stanton
Star
Starla
Starr
Stasia
Stefan
Stefani
Stefania
Stefanie
Stefany
Steffanie
Stella
Stepanie
Stephaine
Stephan
Stephane
Stephani
Stephania
Stephanie
Stephany
Stephen
Stephenie
Stephine
Stephnie
Sterling
Steve
Steven
Stevie
Stewart
Stormy
Stuart
Su
Suanne
Sudie
Sue
Sueann
Suellen
Suk
Sulema
Sumiko
Summer
Sun
Sunday
Sung
Sunni
Sunny
Sunshine
Susan
Susana
Susann
Susanna
Susannah
Susanne
Susie
Susy
Suzan
Suzann
Suzanna
Suzanne
Suzette
Suzi
Suzie
Suzy
Svetlana
Sybil
Syble
Sydney
Sylvester
Sylvia
Sylvie
Synthia
Syreeta
Ta
Tabatha
Tabetha
Tabitha
Tad
Tai
Taina
Taisha
Tajuana
Takako
Takisha
Talia
Talisha
Talitha
Tam
Tama
Tamala
Tamar
Tamara
Tamatha
Tambra
Tameika
Tameka
Tamekia
Tamela
Tamera
Tamesha
Tami
Tamica
Tamie
Tamika
Tamiko
Tamisha
Tammara
Tammera
Tammi
Tammie
Tammy
Tamra
Tana
Tandra
Tandy
Taneka
Tanesha
Tangela
Tania
Tanika
Tanisha
Tanja
Tanna
Tanner
Tanya
Tara
Tarah
Taren
Tari
Tarra
Tarsha
Taryn
Tasha
Tashia
Tashina
Tasia
Tatiana
Tatum
Tatyana
Taunya
Tawana
Tawanda
Tawanna
Tawna
Tawny
Tawnya
Taylor
Tayna
Ted
Teddy
Teena
Tegan
Teisha
Telma
Temeka
Temika
Tempie
Temple
Tena
Tenesha
Tenisha
Tennie
Tennille
Teodora
Teodoro
Teofila
Tequila
Tera
Tereasa
Terence
Teresa
Terese
Teresia
Teresita
Teressa
Teri
Terica
Terina
Terisa
Terra
Terrance
Terrell
Terrence
Terresa
Terri
Terrie
Terrilyn
Terry
Tesha
Tess
Tessa
Tessie
Thad
Thaddeus
Thalia
Thanh
Thao
Thea
Theda
Thelma
Theo
Theodora
Theodore
Theola
Theresa
Therese
Theresia
Theressa
Theron
Thersa
Thi
Thomas
Thomasena
Thomasina
Thomasine
Thora
Thresa
Thu
Thurman
Thuy
Tia
Tiana
Tianna
Tiara
Tien
Tiera
Tierra
Tiesha
Tifany
Tiffaney
Tiffani
Tiffanie
Tiffany
Tiffiny
Tijuana
Tilda
Tillie
Tim
Timika
Timmy
Timothy
Tina
Tinisha
Tiny
Tisa
Tish
Tisha
Titus
Tobi
Tobias
Tobie
Toby
Toccara
Tod
Todd
Toi
Tom
Tomas
Tomasa
Tomeka
Tomi
Tomika
Tomiko
Tommie
Tommy
Tommye
Tomoko
Tona
Tonda
Tonette
Toney
Toni
Tonia
Tonie
Tonisha
Tonita
Tonja
Tony
Tonya
Tora
Tori
Torie
Torri
Torrie
Tory
Tosha
Toshia
Toshiko
Tova
Towanda
Toya
Tracee
Tracey
Traci
Tracie
Tracy
Tran
Trang
Travis
Treasa
Treena
Trena
Trent
Trenton
Tresa
Tressa
Tressie
Treva
Trevor
Trey
Tricia
Trina
Trinh
Trinidad
Trinity
Trish
Trisha
Trista
Tristan
Troy
Trudi
Trudie
Trudy
Trula
Truman
Tu
Tuan
Tula
Tuyet
Twana
Twanda
Twanna
Twila
Twyla
Ty
Tyesha
Tyisha
Tyler
Tynisha
Tyra
Tyree
Tyrell
Tyron
Tyrone
Tyson
Ula
Ulrike
Ulysses
Un
Una
Ursula
Usha
Ute
Vada
Val
Valarie
Valda
Valencia
Valene
Valentin
Valentina
Valentine
Valeri
Valeria
Valerie
Valery
Vallie
Valorie
Valrie
Van
Vance
Vanda
Vanesa
Vanessa
Vanetta
Vania
Vanita
Vanna
Vannesa
Vannessa
Vashti
Vasiliki
Vaughn
Veda
Velda
Velia
Vella
Velma
Velva
Velvet
Vena
Venessa
Venetta
Venice
Venita
Vennie
Venus
Veola
Vera
Verda
Verdell
Verdie
Verena
Vergie
Verla
Verlene
Verlie
Verline
Vern
Verna
Vernell
Vernetta
Vernia
Vernice
Vernie
Vernita
Vernon
Verona
Veronica
Veronika
Veronique
Versie
Vertie
Vesta
Veta
Vi
Vicenta
Vicente
Vickey
Vicki
Vickie
Vicky
Victor
Victoria
Victorina
Vida
Viki
Vikki
Vilma
Vina
Vince
Vincent
Vincenza
Vincenzo
Vinita
Vinnie
Viola
Violet
Violeta
Violette
Virgen
Virgie
Virgil
Virgilio
Virgina
Virginia
Vita
Vito
Viva
Vivan
Vivian
Viviana
Vivien
Vivienne
Von
Voncile
Vonda
Vonnie
Wade
Wai
Waldo
Walker
Wallace
Wally
Walter
Walton
Waltraud
Wan
Wanda
Waneta
Wanetta
Wanita
Ward
Warner
Warren
Wava
Waylon
Wayne
Wei
Weldon
Wen
Wendell
Wendi
Wendie
Wendolyn
Wendy
Wenona
Werner
Wes
Wesley
Weston
Whitley
Whitney
Wilber
Wilbert
Wilbur
Wilburn
Wilda
Wiley
Wilford
Wilfred
Wilfredo
Wilhelmina
Wilhemina
Will
Willa
Willard
Willena
Willene
Willetta
Willette
Willia
William
Williams
Willian
Willie
Williemae
Willis
Willodean
Willow
Willy
Wilma
Wilmer
Wilson
Wilton
Windy
Winford
Winfred
Winifred
Winnie
Winnifred
Winona
Winston
Winter
Wm
Wonda
Woodrow
Wyatt
Wynell
Wynona
Xavier
Xenia
Xiao
Xiomara
Xochitl
Xuan
Yadira
Yaeko
Yael
Yahaira
Yajaira
Yan
Yang
Yanira
Yasmin
Yasmine
Yasuko
Yee
Yelena
Yen
Yer
Yesenia
Yessenia
Yetta
Yevette
Yi
Ying
Yoko
Yolanda
Yolande
Yolando
Yolonda
Yon
Yong
Yoshie
Yoshiko
Youlanda
Young
Yu
Yuette
Yuk
Yuki
Yukiko
Yuko
Yulanda
Yun
Yung
Yuonne
Yuri
Yuriko
Yvette
Yvone
Yvonne
Zachariah
Zachary
Zachery
Zack
Zackary
Zada
Zaida
Zana
Zandra
Zane
Zelda
Zella
Zelma
Zena
Zenaida
Zenia
Zenobia
Zetta
Zina
Zita
Zoe
Zofia
Zoila
Zola
Zona
Zonia
Zora
Zoraida
Zula
Zulema
Zulma
tools\dbatools\bin\datamasking\firstnames_female.txt
Abbey
Abbie
Abby
Abigail
Ada
Adah
Adaline
Adam
Addie
Adela
Adelaida
Adelaide
Adele
Adelia
Adelina
Adeline
Adell
Adella
Adelle
Adena
Adina
Adria
Adrian
Adriana
Adriane
Adrianna
Adrianne
Adrien
Adriene
Adrienne
Afton
Agatha
Agnes
Agnus
Agripina
Agueda
Agustina
Ai
Aida
Aide
Aiko
Aileen
Ailene
Aimee
Aisha
Aja
Akiko
Akilah
Alaina
Alaine
Alana
Alane
Alanna
Alayna
Alba
Albert
Alberta
Albertha
Albertina
Albertine
Albina
Alda
Alease
Alecia
Aleen
Aleida
Aleisha
Alejandra
Alejandrina
Alena
Alene
Alesha
Aleshia
Alesia
Alessandra
Aleta
Aletha
Alethea
Alethia
Alex
Alexa
Alexander
Alexandra
Alexandria
Alexia
Alexis
Alfreda
Alfredia
Ali
Alia
Alica
Alice
Alicia
Alida
Alina
Aline
Alisa
Alise
Alisha
Alishia
Alisia
Alison
Alissa
Alita
Alix
Aliza
Alla
Alleen
Allegra
Allen
Allena
Allene
Allie
Alline
Allison
Allyn
Allyson
Alma
Almeda
Almeta
Alona
Alpha
Alta
Altagracia
Altha
Althea
Alva
Alvera
Alverta
Alvina
Alyce
Alycia
Alysa
Alyse
Alysha
Alysia
Alyson
Alyssa
Amada
Amal
Amalia
Amanda
Amber
Amberly
Amee
Amelia
America
Ami
Amie
Amiee
Amina
Amira
Ammie
Amparo
Amy
An
Ana
Anabel
Analisa
Anamaria
Anastacia
Anastasia
Andera
Andra
Andre
Andrea
Andree
Andrew
Andria
Anette
Angel
Angela
Angele
Angelena
Angeles
Angelia
Angelic
Angelica
Angelika
Angelina
Angeline
Angelique
Angelita
Angella
Angelo
Angelyn
Angie
Angila
Angla
Angle
Anglea
Anh
Anika
Anisa
Anisha
Anissa
Anita
Anitra
Anja
Anjanette
Anjelica
Ann
Anna
Annabel
Annabell
Annabelle
Annalee
Annalisa
Annamae
Annamaria
Annamarie
Anne
Anneliese
Annelle
Annemarie
Annett
Annetta
Annette
Annice
Annie
Annika
Annis
Annita
Annmarie
Anthony
Antionette
Antoinette
Antonetta
Antonette
Antonia
Antonietta
Antonina
Antonio
Anya
Apolonia
April
Apryl
Ara
Araceli
Aracelis
Aracely
Arcelia
Ardath
Ardelia
Ardell
Ardella
Ardelle
Ardis
Ardith
Aretha
Argelia
Argentina
Ariana
Ariane
Arianna
Arianne
Arica
Arie
Ariel
Arielle
Arla
Arlean
Arleen
Arlena
Arlene
Arletha
Arletta
Arlette
Arlinda
Arline
Arlyne
Armanda
Armandina
Armida
Arminda
Arnetta
Arnette
Arnita
Arthur
Artie
Arvilla
Asha
Ashanti
Ashely
Ashlea
Ashlee
Ashleigh
Ashley
Ashli
Ashlie
Ashly
Ashlyn
Ashton
Asia
Asley
Assunta
Astrid
Asuncion
Athena
Aubrey
Audie
Audra
Audrea
Audrey
Audria
Audrie
Audry
Augusta
Augustina
Augustine
Aundrea
Aura
Aurea
Aurelia
Aurora
Aurore
Austin
Autumn
Ava
Avelina
Avery
Avis
Avril
Awilda
Ayako
Ayana
Ayanna
Ayesha
Azalee
Azucena
Azzie
Babara
Babette
Bailey
Bambi
Bao
Barabara
Barb
Barbar
Barbara
Barbera
Barbie
Barbra
Bari
Barrie
Basilia
Bea
Beata
Beatrice
Beatris
Beatriz
Beaulah
Bebe
Becki
Beckie
Becky
Bee
Belen
Belia
Belinda
Belkis
Bell
Bella
Belle
Belva
Benita
Bennie
Berenice
Berna
Bernadette
Bernadine
Bernarda
Bernardina
Bernardine
Berneice
Bernetta
Bernice
Bernie
Berniece
Bernita
Berry
Berta
Bertha
Bertie
Beryl
Bess
Bessie
Beth
Bethanie
Bethann
Bethany
Bethel
Betsey
Betsy
Bette
Bettie
Bettina
Betty
Bettyann
Bettye
Beula
Beulah
Bev
Beverlee
Beverley
Beverly
Bianca
Bibi
Billi
Billie
Billy
Billye
Birdie
Birgit
Blair
Blake
Blanca
Blanch
Blanche
Blondell
Blossom
Blythe
Bobbi
Bobbie
Bobby
Bobbye
Bobette
Bok
Bong
Bonita
Bonnie
Bonny
Branda
Brande
Brandee
Brandi
Brandie
Brandon
Brandy
Breana
Breann
Breanna
Breanne
Bree
Brenda
Brenna
Brett
Brian
Briana
Brianna
Brianne
Bridget
Bridgett
Bridgette
Brigette
Brigid
Brigida
Brigitte
Brinda
Britany
Britney
Britni
Britt
Britta
Brittaney
Brittani
Brittanie
Brittany
Britteny
Brittney
Brittni
Brittny
Bronwyn
Brook
Brooke
Bruna
Brunilda
Bryanna
Brynn
Buena
Buffy
Bula
Bulah
Bunny
Burma
Caitlin
Caitlyn
Calandra
Calista
Callie
Camelia
Camellia
Cameron
Cami
Camie
Camila
Camilla
Camille
Cammie
Cammy
Candace
Candance
Candelaria
Candi
Candice
Candida
Candie
Candis
Candra
Candy
Candyce
Caprice
Cara
Caren
Carey
Cari
Caridad
Carie
Carin
Carina
Carisa
Carissa
Carita
Carl
Carla
Carlee
Carleen
Carlena
Carlene
Carletta
Carley
Carli
Carlie
Carline
Carlita
Carlos
Carlota
Carlotta
Carly
Carlyn
Carma
Carman
Carmel
Carmela
Carmelia
Carmelina
Carmelita
Carmella
Carmen
Carmina
Carmon
Carol
Carola
Carolann
Carole
Carolee
Carolin
Carolina
Caroline
Caroll
Carolyn
Carolyne
Carolynn
Caron
Caroyln
Carri
Carrie
Carrol
Carroll
Carry
Cary
Caryl
Carylon
Caryn
Casandra
Casey
Casie
Casimira
Cassandra
Cassaundra
Cassey
Cassi
Cassidy
Cassie
Cassondra
Cassy
Catalina
Catarina
Caterina
Catharine
Catherin
Catherina
Catherine
Cathern
Catheryn
Cathey
Cathi
Cathie
Cathleen
Cathrine
Cathryn
Cathy
Catina
Catrice
Catrina
Cayla
Cecelia
Cecil
Cecila
Cecile
Cecilia
Cecille
Cecily
Celena
Celesta
Celeste
Celestina
Celestine
Celia
Celina
Celinda
Celine
Celsa
Ceola
Chae
Chan
Chana
Chanda
Chandra
Chanel
Chanell
Chanelle
Chang
Chantal
Chantay
Chante
Chantel
Chantell
Chantelle
Chara
Charis
Charise
Charissa
Charisse
Charita
Charity
Charla
Charleen
Charlena
Charlene
Charles
Charlesetta
Charlette
Charlie
Charline
Charlott
Charlotte
Charlsie
Charlyn
Charmain
Charmaine
Charolette
Chasidy
Chasity
Chassidy
Chastity
Chau
Chaya
Chelsea
Chelsey
Chelsie
Cher
Chere
Cheree
Cherelle
Cheri
Cherie
Cherilyn
Cherise
Cherish
Cherly
Cherlyn
Cherri
Cherrie
Cherry
Cherryl
Chery
Cheryl
Cheryle
Cheryll
Cheyenne
Chi
Chia
Chieko
Chin
China
Ching
Chiquita
Chloe
Chong
Chris
Chrissy
Christa
Christal
Christeen
Christel
Christen
Christena
Christene
Christi
Christia
Christian
Christiana
Christiane
Christie
Christin
Christina
Christine
Christinia
Christopher
Christy
Chrystal
Chu
Chun
Chung
Ciara
Cicely
Ciera
Cierra
Cinda
Cinderella
Cindi
Cindie
Cindy
Cinthia
Cira
Clair
Claire
Clara
Clare
Clarence
Claretha
Claretta
Claribel
Clarice
Clarinda
Clarine
Claris
Clarisa
Clarissa
Clarita
Classie
Claude
Claudette
Claudia
Claudie
Claudine
Clelia
Clemencia
Clementina
Clementine
Clemmie
Cleo
Cleopatra
Cleora
Cleotilde
Cleta
Clora
Clorinda
Clotilde
Clyde
Codi
Cody
Colby
Coleen
Colene
Coletta
Colette
Colleen
Collen
Collene
Collette
Concepcion
Conception
Concetta
Concha
Conchita
Connie
Constance
Consuela
Consuelo
Contessa
Cora
Coral
Coralee
Coralie
Corazon
Cordelia
Cordia
Cordie
Coreen
Corene
Coretta
Corey
Cori
Corie
Corina
Corine
Corinna
Corinne
Corliss
Cornelia
Corrie
Corrin
Corrina
Corrine
Corrinne
Cortney
Cory
Courtney
Creola
Cris
Criselda
Crissy
Crista
Cristal
Cristen
Cristi
Cristie
Cristin
Cristina
Cristine
Cristy
Cruz
Crysta
Crystal
Crystle
Cuc
Curtis
Cyndi
Cyndy
Cynthia
Cyrstal
Cythia
Dacia
Dagmar
Dagny
Dahlia
Daina
Daine
Daisey
Daisy
Dakota
Dale
Dalene
Dalia
Dalila
Dallas
Damaris
Dan
Dana
Danae
Danelle
Danette
Dani
Dania
Danica
Daniel
Daniela
Daniele
Daniell
Daniella
Danielle
Danika
Danille
Danita
Dann
Danna
Dannette
Dannie
Dannielle
Danuta
Danyel
Danyell
Danyelle
Daphine
Daphne
Dara
Darby
Darcel
Darcey
Darci
Darcie
Darcy
Daria
Darla
Darleen
Darlena
Darlene
Darline
Darnell
Daryl
David
Davida
Davina
Dawn
Dawna
Dawne
Dayle
Dayna
Daysi
Deadra
Dean
Deana
Deandra
Deandrea
Deane
Deann
Deanna
Deanne
Deb
Debbi
Debbie
Debbra
Debby
Debera
Debi
Debora
Deborah
Debra
Debrah
Debroah
Dede
Dedra
Dee
Deeann
Deeanna
Deedee
Deedra
Deena
Deetta
Deidra
Deidre
Deirdre
Deja
Delaine
Delana
Delcie
Delena
Delfina
Delia
Delicia
Delila
Delilah
Delinda
Delisa
Dell
Della
Delma
Delmy
Delois
Deloise
Delora
Deloras
Delores
Deloris
Delorse
Delpha
Delphia
Delphine
Delsie
Delta
Demetra
Demetria
Demetrice
Demetrius
Dena
Denae
Deneen
Denese
Denice
Denise
Denisha
Denisse
Denita
Denna
Dennis
Dennise
Denny
Denyse
Deon
Deonna
Desirae
Desire
Desiree
Despina
Dessie
Destiny
Detra
Devin
Devon
Devona
Devora
Devorah
Dia
Diamond
Dian
Diana
Diane
Diann
Dianna
Dianne
Diedra
Diedre
Dierdre
Digna
Dimple
Dina
Dinah
Dinorah
Dion
Dione
Dionna
Dionne
Divina
Dixie
Dodie
Dollie
Dolly
Dolores
Doloris
Domenica
Dominga
Dominica
Dominique
Dominque
Domitila
Domonique
Dona
Donald
Donella
Donetta
Donette
Dong
Donita
Donna
Donnetta
Donnette
Donnie
Donya
Dora
Dorathy
Dorcas
Doreatha
Doreen
Dorene
Doretha
Dorethea
Doretta
Dori
Doria
Dorian
Dorie
Dorinda
Dorine
Doris
Dorla
Dorotha
Dorothea
Dorothy
Dorris
Dortha
Dorthea
Dorthey
Dorthy
Dot
Dottie
Dotty
Dovie
Dreama
Drema
Drew
Drucilla
Drusilla
Dulce
Dulcie
Dung
Dusti
Dusty
Dwana
Dyan
Earlean
Earleen
Earlene
Earlie
Earline
Earnestine
Eartha
Easter
Eboni
Ebonie
Ebony
Echo
Eda
Edda
Eddie
Edelmira
Eden
Edie
Edith
Edna
Edra
Edris
Edward
Edwina
Edyth
Edythe
Effie
Ehtel
Eileen
Eilene
Ela
Eladia
Elaina
Elaine
Elana
Elane
Elanor
Elayne
Elba
Elda
Eldora
Eleanor
Eleanora
Eleanore
Elease
Elena
Elene
Eleni
Elenor
Elenora
Elenore
Eleonor
Eleonora
Eleonore
Elfreda
Elfrieda
Elfriede
Elia
Eliana
Elicia
Elida
Elidia
Elin
Elina
Elinor
Elinore
Elisa
Elisabeth
Elise
Elisha
Elissa
Eliz
Eliza
Elizabet
Elizabeth
Elizbeth
Elizebeth
Elke
Ella
Ellamae
Ellan
Ellen
Ellena
Elli
Ellie
Ellis
Elly
Ellyn
Elma
Elmer
Elmira
Elna
Elnora
Elodia
Elois
Eloisa
Eloise
Elouise
Elsa
Else
Elsie
Elsy
Elva
Elvera
Elvia
Elvie
Elvina
Elvira
Elwanda
Elyse
Elza
Ema
Emelda
Emelia
Emelina
Emeline
Emely
Emerald
Emerita
Emiko
Emilee
Emilia
Emilie
Emily
Emma
Emmaline
Emmie
Emmy
Emogene
Ena
Enda
Enedina
Eneida
Enid
Enola
Enriqueta
Epifania
Era
Eric
Erica
Ericka
Erika
Erin
Erinn
Erlene
Erlinda
Erline
Erma
Ermelinda
Erminia
Erna
Ernestina
Ernestine
Eryn
Esmeralda
Esperanza
Essie
Esta
Estefana
Estela
Estell
Estella
Estelle
Ester
Esther
Estrella
Etha
Ethel
Ethelene
Ethelyn
Ethyl
Etsuko
Etta
Ettie
Eufemia
Eugena
Eugene
Eugenia
Eugenie
Eula
Eulah
Eulalia
Eun
Euna
Eunice
Eura
Eusebia
Eustolia
Eva
Evalyn
Evan
Evangelina
Evangeline
Eve
Evelia
Evelin
Evelina
Eveline
Evelyn
Evelyne
Evelynn
Evette
Evia
Evie
Evita
Evon
Evonne
Ewa
Exie
Fabiola
Fae
Fairy
Faith
Fallon
Fannie
Fanny
Farah
Farrah
Fatima
Fatimah
Faustina
Faviola
Fawn
Fay
Faye
Fe
Felecia
Felica
Felice
Felicia
Felicidad
Felicita
Felicitas
Felipa
Felisa
Felisha
Fermina
Fern
Fernanda
Fernande
Ferne
Fidela
Fidelia
Filomena
Fiona
Flavia
Fleta
Flo
Flor
Flora
Florance
Florence
Florencia
Florene
Florentina
Floretta
Floria
Florida
Florinda
Florine
Florrie
Flossie
Floy
Fonda
Fran
France
Francene
Frances
Francesca
Franchesca
Francie
Francina
Francine
Francis
Francisca
Francisco
Francoise
Frank
Frankie
Fransisca
Fred
Freda
Fredda
Freddie
Frederica
Fredericka
Fredia
Fredricka
Freeda
Freida
Frida
Frieda
Fumiko
Gabriel
Gabriela
Gabriele
Gabriella
Gabrielle
Gail
Gala
Gale
Galina
Garnet
Garnett
Gary
Gay
Gaye
Gayla
Gayle
Gaylene
Gaynell
Gaynelle
Gearldine
Gema
Gemma
Gena
Gene
Genesis
Geneva
Genevie
Genevieve
Genevive
Genia
Genie
Genna
Gennie
Genny
Genoveva
Georgann
George
Georgeann
Georgeanna
Georgene
Georgetta
Georgette
Georgia
Georgiana
Georgiann
Georgianna
Georgianne
Georgie
Georgina
Georgine
Gerald
Geraldine
Geralyn
Gerda
Geri
Germaine
Gerri
Gerry
Gertha
Gertie
Gertrud
Gertrude
Gertrudis
Gertude
Ghislaine
Gia
Gianna
Gidget
Gigi
Gilberte
Gilda
Gillian
Gilma
Gina
Ginette
Ginger
Ginny
Giovanna
Gisela
Gisele
Giselle
Gita
Giuseppina
Gladis
Glady
Gladys
Glayds
Glenda
Glendora
Glenn
Glenna
Glennie
Glennis
Glinda
Gloria
Glory
Glynda
Glynis
Golda
Golden
Goldie
Grace
Gracia
Gracie
Graciela
Grayce
Grazyna
Gregoria
Gregory
Greta
Gretchen
Gretta
Gricelda
Grisel
Griselda
Guadalupe
Gudrun
Guillermina
Gussie
Gwen
Gwenda
Gwendolyn
Gwenn
Gwyn
Gwyneth
Ha
Hae
Hailey
Haley
Halina
Halley
Hallie
Han
Hana
Hang
Hanh
Hanna
Hannah
Hannelore
Harmony
Harold
Harriet
Harriett
Harriette
Hassie
Hattie
Haydee
Hayley
Hazel
Heather
Hedwig
Hedy
Hee
Heide
Heidi
Heidy
Heike
Helaine
Helen
Helena
Helene
Helga
Hellen
Henrietta
Henriette
Henry
Herlinda
Herma
Hermelinda
Hermila
Hermina
Hermine
Herminia
Herta
Hertha
Hester
Hettie
Hiedi
Hien
Hilaria
Hilary
Hilda
Hilde
Hildegard
Hildegarde
Hildred
Hillary
Hilma
Hiroko
Hisako
Hoa
Holley
Holli
Hollie
Hollis
Holly
Honey
Hong
Hope
Hortencia
Hortense
Hortensia
Hsiu
Hue
Hui
Hulda
Huong
Hwa
Hyacinth
Hye
Hyo
Hyon
Hyun
Ida
Idalia
Idell
Idella
Iesha
Ignacia
Ila
Ilana
Ilda
Ileana
Ileen
Ilene
Iliana
Illa
Ilona
Ilse
Iluminada
Ima
Imelda
Imogene
In
Ina
India
Indira
Inell
Ines
Inez
Inga
Inge
Ingeborg
Inger
Ingrid
Inocencia
Iola
Iona
Ione
Ira
Iraida
Irena
Irene
Irina
Iris
Irish
Irma
Irmgard
Isa
Isabel
Isabell
Isabella
Isabelle
Isadora
Isaura
Isela
Isidra
Isis
Isobel
Iva
Ivana
Ivelisse
Ivette
Ivey
Ivonne
Ivory
Ivy
Izetta
Izola
Ja
Jacalyn
Jacelyn
Jacinda
Jacinta
Jack
Jackeline
Jackelyn
Jacki
Jackie
Jacklyn
Jackqueline
Jaclyn
Jacqualine
Jacque
Jacquelin
Jacqueline
Jacquelyn
Jacquelyne
Jacquelynn
Jacquetta
Jacqui
Jacquie
Jacquiline
Jacquline
Jacqulyn
Jada
Jade
Jadwiga
Jae
Jaime
Jaimee
Jaimie
Jaleesa
Jalisa
Jama
Jame
Jamee
James
Jamey
Jami
Jamie
Jamika
Jamila
Jammie
Jan
Jana
Janae
Janay
Jane
Janean
Janee
Janeen
Janel
Janell
Janella
Janelle
Janene
Janessa
Janet
Janeth
Janett
Janetta
Janette
Janey
Jani
Janice
Janie
Janiece
Janina
Janine
Janis
Janise
Janita
Jann
Janna
Jannet
Jannette
Jannie
January
Janyce
Jaqueline
Jaquelyn
Jasmin
Jasmine
Jason
Jaunita
Jay
Jaye
Jayme
Jaymie
Jayna
Jayne
Jazmin
Jazmine
Jean
Jeana
Jeane
Jeanelle
Jeanene
Jeanett
Jeanetta
Jeanette
Jeanice
Jeanie
Jeanine
Jeanmarie
Jeanna
Jeanne
Jeannetta
Jeannette
Jeannie
Jeannine
Jeffie
Jeffrey
Jen
Jena
Jenae
Jene
Jenee
Jenell
Jenelle
Jenette
Jeneva
Jeni
Jenice
Jenifer
Jeniffer
Jenine
Jenise
Jenna
Jennefer
Jennell
Jennette
Jenni
Jennie
Jennifer
Jenniffer
Jennine
Jenny
Jeraldine
Jeremy
Jeri
Jerica
Jerilyn
Jerlene
Jerri
Jerrica
Jerrie
Jerry
Jesenia
Jesica
Jesse
Jessenia
Jessi
Jessia
Jessica
Jessie
Jessika
Jestine
Jesus
Jesusa
Jesusita
Jetta
Jettie
Jewel
Jewell
Ji
Jill
Jillian
Jimmie
Jimmy
Jin
Jina
Jinny
Jo
Joan
Joana
Joane
Joanie
Joann
Joanna
Joanne
Joannie
Joaquina
Jocelyn
Jodee
Jodi
Jodie
Jody
Joe
Joeann
Joel
Joella
Joelle
Joellen
Joetta
Joette
Joey
Johana
Johanna
Johanne
John
Johna
Johnetta
Johnette
Johnie
Johnna
Johnnie
Johnny
Johnsie
Joi
Joie
Jolanda
Joleen
Jolene
Jolie
Joline
Jolyn
Jolynn
Jon
Jona
Jone
Jonell
Jonelle
Jong
Joni
Jonie
Jonna
Jonnie
Jordan
Jose
Josefa
Josefina
Josefine
Joselyn
Joseph
Josephina
Josephine
Josette
Joshua
Josie
Joslyn
Josphine
Jovan
Jovita
Joy
Joya
Joyce
Joycelyn
Joye
Juan
Juana
Juanita
Jude
Judi
Judie
Judith
Judy
Jule
Julee
Julene
Juli
Julia
Julian
Juliana
Juliane
Juliann
Julianna
Julianne
Julie
Julieann
Julienne
Juliet
Julieta
Julietta
Juliette
Julio
Julissa
June
Jung
Junie
Junita
Junko
Justa
Justin
Justina
Justine
Jutta
Ka
Kacey
Kaci
Kacie
Kacy
Kai
Kaila
Kaitlin
Kaitlyn
Kala
Kaleigh
Kaley
Kali
Kallie
Kalyn
Kam
Kamala
Kami
Kamilah
Kandace
Kandi
Kandice
Kandis
Kandra
Kandy
Kanesha
Kanisha
Kara
Karan
Kareen
Karen
Karena
Karey
Kari
Karie
Karima
Karin
Karina
Karine
Karisa
Karissa
Karl
Karla
Karleen
Karlene
Karly
Karlyn
Karma
Karmen
Karol
Karole
Karoline
Karolyn
Karon
Karren
Karri
Karrie
Karry
Kary
Karyl
Karyn
Kasandra
Kasey
Kasha
Kasi
Kasie
Kassandra
Kassie
Kate
Katelin
Katelyn
Katelynn
Katerine
Kathaleen
Katharina
Katharine
Katharyn
Kathe
Katheleen
Katherin
Katherina
Katherine
Kathern
Katheryn
Kathey
Kathi
Kathie
Kathleen
Kathlene
Kathline
Kathlyn
Kathrin
Kathrine
Kathryn
Kathryne
Kathy
Kathyrn
Kati
Katia
Katie
Katina
Katlyn
Katrice
Katrina
Kattie
Katy
Kay
Kayce
Kaycee
Kaye
Kayla
Kaylee
Kayleen
Kayleigh
Kaylene
Kazuko
Kecia
Keeley
Keely
Keena
Keesha
Keiko
Keila
Keira
Keisha
Keith
Keitha
Keli
Kelle
Kellee
Kelley
Kelli
Kellie
Kelly
Kellye
Kelsey
Kelsi
Kelsie
Kemberly
Kena
Kenda
Kendal
Kendall
Kendra
Kenia
Kenisha
Kenna
Kenneth
Kenya
Kenyatta
Kenyetta
Kera
Keren
Keri
Kerri
Kerrie
Kerry
Kerstin
Kesha
Keshia
Keturah
Keva
Kevin
Khadijah
Khalilah
Kia
Kiana
Kiara
Kiera
Kiersten
Kiesha
Kiley
Kim
Kimber
Kimberely
Kimberlee
Kimberley
Kimberli
Kimberlie
Kimberly
Kimbery
Kimbra
Kimi
Kimiko
Kina
Kindra
Kira
Kirby
Kirsten
Kirstie
Kirstin
Kisha
Kit
Kittie
Kitty
Kiyoko
Kizzie
Kizzy
Klara
Kori
Kortney
Kourtney
Kris
Krishna
Krissy
Krista
Kristal
Kristan
Kristeen
Kristel
Kristen
Kristi
Kristian
Kristie
Kristin
Kristina
Kristine
Kristle
Kristy
Kristyn
Krysta
Krystal
Krysten
Krystin
Krystina
Krystle
Krystyna
Kum
Kyla
Kyle
Kylee
Kylie
Kym
Kymberly
Kyoko
Kyong
Kyra
Kyung
Lacey
Lachelle
Laci
Lacie
Lacresha
Lacy
Ladawn
Ladonna
Lady
Lael
Lahoma
Lai
Laila
Laine
Lajuana
Lakeesha
Lakeisha
Lakendra
Lakenya
Lakesha
Lakeshia
Lakia
Lakiesha
Lakisha
Lakita
Lala
Lamonica
Lan
Lana
Lane
Lanell
Lanelle
Lanette
Lang
Lani
Lanie
Lanita
Lannie
Lanora
Laquanda
Laquita
Lara
Larae
Laraine
Laree
Larhonda
Larisa
Larissa
Larita
Laronda
Larraine
Larry
Larue
Lasandra
Lashanda
Lashandra
Lashaun
Lashaunda
Lashawn
Lashawna
Lashawnda
Lashay
Lashell
Lashon
Lashonda
Lashunda
Lasonya
Latanya
Latarsha
Latasha
Latashia
Latesha
Latia
Laticia
Latina
Latisha
Latonia
Latonya
Latoria
Latosha
Latoya
Latoyia
Latrice
Latricia
Latrina
Latrisha
Launa
Laura
Lauralee
Lauran
Laure
Laureen
Laurel
Lauren
Laurena
Laurence
Laurene
Lauretta
Laurette
Lauri
Laurice
Laurie
Laurinda
Laurine
Lauryn
Lavada
Lavelle
Lavenia
Lavera
Lavern
Laverna
Laverne
Laveta
Lavette
Lavina
Lavinia
Lavon
Lavona
Lavonda
Lavone
Lavonia
Lavonna
Lavonne
Lawana
Lawanda
Lawanna
Lawrence
Layla
Layne
Le
Lea
Leah
Lean
Leana
Leandra
Leann
Leanna
Leanne
Leanora
Leatha
Leatrice
Lecia
Leda
Lee
Leeann
Leeanna
Leeanne
Leena
Leesa
Leia
Leida
Leigh
Leigha
Leighann
Leila
Leilani
Leisa
Leisha
Lekisha
Lela
Lelah
Lelia
Lena
Lenita
Lenna
Lennie
Lenora
Lenore
Leo
Leola
Leoma
Leon
Leona
Leonarda
Leone
Leonia
Leonida
Leonie
Leonila
Leonor
Leonora
Leonore
Leontine
Leora
Leota
Lera
Lesa
Lesha
Lesia
Leslee
Lesley
Lesli
Leslie
Lessie
Lester
Leta
Letha
Leticia
Letisha
Letitia
Lettie
Letty
Lewis
Lexie
Lezlie
Li
Lia
Liana
Liane
Lianne
Libbie
Libby
Liberty
Librada
Lida
Lidia
Lien
Lieselotte
Ligia
Lila
Lili
Lilia
Lilian
Liliana
Lilla
Lilli
Lillia
Lilliam
Lillian
Lilliana
Lillie
Lilly
Lily
Lin
Lina
Linda
Lindsay
Lindsey
Lindsy
Lindy
Linette
Ling
Linh
Linn
Linnea
Linnie
Linsey
Lisa
Lisabeth
Lisandra
Lisbeth
Lise
Lisette
Lisha
Lissa
Lissette
Lita
Livia
Liz
Liza
Lizabeth
Lizbeth
Lizeth
Lizette
Lizzette
Lizzie
Loan
Logan
Loida
Lois
Loise
Lola
Lolita
Loma
Lona
Londa
Loni
Lonna
Lonnie
Lora
Loraine
Loralee
Lore
Lorean
Loree
Loreen
Lorelei
Loren
Lorena
Lorene
Lorenza
Loreta
Loretta
Lorette
Lori
Loria
Loriann
Lorie
Lorilee
Lorina
Lorinda
Lorine
Loris
Lorita
Lorna
Lorraine
Lorretta
Lorri
Lorriane
Lorrie
Lorrine
Lory
Lottie
Lou
Louann
Louanne
Louella
Louetta
Louie
Louis
Louisa
Louise
Loura
Lourdes
Lourie
Louvenia
Love
Lovella
Lovetta
Lovie
Loyce
Lu
Luana
Luann
Luanna
Luanne
Luba
Luci
Lucia
Luciana
Lucie
Lucienne
Lucila
Lucile
Lucilla
Lucille
Lucina
Lucinda
Lucrecia
Lucretia
Lucy
Ludie
Ludivina
Lue
Luella
Luetta
Luis
Luisa
Luise
Lula
Lulu
Luna
Lupe
Lupita
Lura
Lurlene
Lurline
Luvenia
Luz
Lyda
Lydia
Lyla
Lyn
Lynda
Lyndia
Lyndsay
Lyndsey
Lynell
Lynelle
Lynetta
Lynette
Lynn
Lynna
Lynne
Lynnette
Lynsey
Ma
Mabel
Mabelle
Mable
Machelle
Macie
Mackenzie
Macy
Madalene
Madaline
Madalyn
Maddie
Madelaine
Madeleine
Madelene
Madeline
Madelyn
Madge
Madie
Madison
Madlyn
Madonna
Mae
Maegan
Mafalda
Magali
Magaly
Magan
Magaret
Magda
Magdalen
Magdalena
Magdalene
Magen
Maggie
Magnolia
Mahalia
Mai
Maia
Maida
Maile
Maira
Maire
Maisha
Maisie
Majorie
Makeda
Malena
Malia
Malika
Malinda
Malisa
Malissa
Malka
Mallie
Mallory
Malorie
Malvina
Mamie
Mammie
Man
Mana
Manda
Mandi
Mandie
Mandy
Manie
Manuela
Many
Mao
Maple
Mara
Maragaret
Maragret
Maranda
Marcela
Marcelene
Marcelina
Marceline
Marcell
Marcella
Marcelle
Marcene
Marchelle
Marci
Marcia
Marcie
Marcy
Mardell
Maren
Marg
Margaret
Margareta
Margarete
Margarett
Margaretta
Margarette
Margarita
Margarite
Margart
Marge
Margene
Margeret
Margert
Margery
Marget
Margherita
Margie
Margit
Margo
Margorie
Margot
Margret
Margrett
Marguerita
Marguerite
Margurite
Margy
Marhta
Mari
Maria
Mariah
Mariam
Marian
Mariana
Marianela
Mariann
Marianna
Marianne
Maribel
Maribeth
Marica
Maricela
Maricruz
Marie
Mariel
Mariela
Mariella
Marielle
Marietta
Mariette
Mariko
Marilee
Marilou
Marilu
Marilyn
Marilynn
Marin
Marina
Marinda
Marine
Mario
Marion
Maris
Marisa
Marisela
Marisha
Marisol
Marissa
Marita
Maritza
Marivel
Marjorie
Marjory
Mark
Marketta
Markita
Marla
Marlana
Marleen
Marlen
Marlena
Marlene
Marlin
Marline
Marlo
Marlyn
Marlys
Marna
Marni
Marnie
Marquerite
Marquetta
Marquita
Marquitta
Marry
Marsha
Marshall
Marta
Marth
Martha
Marti
Martin
Martina
Martine
Marty
Marva
Marvel
Marvella
Marvis
Marx
Mary
Marya
Maryalice
Maryam
Maryann
Maryanna
Maryanne
Marybelle
Marybeth
Maryellen
Maryetta
Maryjane
Maryjo
Maryland
Marylee
Marylin
Maryln
Marylou
Marylouise
Marylyn
Marylynn
Maryrose
Masako
Matha
Mathilda
Mathilde
Matilda
Matilde
Matthew
Mattie
Maud
Maude
Maudie
Maura
Maureen
Maurice
Maurine
Maurita
Mavis
Maxie
Maxima
Maximina
Maxine
May
Maya
Maybell
Maybelle
Maye
Mayme
Mayola
Mayra
Mazie
Mckenzie
Meagan
Meaghan
Mechelle
Meda
Mee
Meg
Megan
Meggan
Meghan
Meghann
Mei
Melaine
Melani
Melania
Melanie
Melany
Melba
Melda
Melia
Melida
Melina
Melinda
Melisa
Melissa
Melissia
Melita
Mellie
Mellisa
Mellissa
Melodee
Melodi
Melodie
Melody
Melonie
Melony
Melva
Melvin
Melvina
Melynda
Mendy
Mercedes
Mercedez
Mercy
Meredith
Meri
Merideth
Meridith
Merilyn
Merissa
Merle
Merlene
Merlyn
Merna
Merri
Merrie
Merrilee
Merrill
Merry
Mertie
Meryl
Meta
Mi
Mia
Mica
Micaela
Micah
Micha
Michael
Michaela
Michaele
Michal
Micheal
Michel
Michele
Michelina
Micheline
Michell
Michelle
Michiko
Mickey
Micki
Mickie
Miesha
Migdalia
Mignon
Miguelina
Mika
Mikaela
Mike
Miki
Mikki
Mila
Milagro
Milagros
Milda
Mildred
Milissa
Millicent
Millie
Milly
Mimi
Min
Mina
Minda
Mindi
Mindy
Minerva
Ming
Minh
Minna
Minnie
Minta
Mira
Miranda
Mireille
Mirella
Mireya
Miriam
Mirian
Mirna
Mirta
Mirtha
Misha
Miss
Missy
Misti
Mistie
Misty
Mitchell
Mitsue
Mitsuko
Mittie
Mitzi
Mitzie
Miyoko
Modesta
Moira
Mollie
Molly
Mona
Monet
Monica
Monika
Monique
Monnie
Monserrate
Moon
Mora
Morgan
Moriah
Mozell
Mozella
Mozelle
Mui
Muoi
Muriel
My
Myesha
Myong
Myra
Myriam
Myrl
Myrle
Myrna
Myrta
Myrtice
Myrtie
Myrtis
Myrtle
Myung
Na
Nada
Nadene
Nadia
Nadine
Naida
Nakesha
Nakia
Nakisha
Nakita
Nam
Nan
Nana
Nancee
Nancey
Nanci
Nancie
Nancy
Nanette
Nannette
Nannie
Naoma
Naomi
Narcisa
Natacha
Natalia
Natalie
Natalya
Natasha
Natashia
Nathalie
Natisha
Natividad
Natosha
Necole
Neda
Nedra
Neely
Neida
Nelda
Nelia
Nelida
Nell
Nella
Nelle
Nellie
Nelly
Nena
Nenita
Neoma
Neomi
Nereida
Nerissa
Nery
Neta
Nettie
Neva
Nevada
Nga
Ngan
Ngoc
Nguyet
Nia
Nichelle
Nichol
Nichole
Nicholle
Nicki
Nickie
Nickole
Nicky
Nicol
Nicola
Nicolasa
Nicole
Nicolette
Nicolle
Nida
Nidia
Niesha
Nieves
Niki
Nikia
Nikita
Nikki
Nikole
Nila
Nilda
Nilsa
Nina
Ninfa
Nisha
Nita
Nobuko
Noel
Noelia
Noella
Noelle
Noemi
Nohemi
Nola
Noma
Nona
Nora
Norah
Noreen
Norene
Noriko
Norine
Norma
Norman
Nova
Novella
Nu
Nubia
Numbers
Nydia
Nyla
Obdulia
Ocie
Octavia
Oda
Odelia
Odell
Odessa
Odette
Odilia
Ofelia
Ok
Ola
Olene
Oleta
Olevia
Olga
Olimpia
Olinda
Oliva
Olive
Olivia
Ollie
Olympia
Oma
Omega
Ona
Oneida
Onie
Onita
Opal
Ophelia
Ora
Oralee
Oralia
Oretha
Orpha
Oscar
Ossie
Otelia
Otha
Otilia
Ouida
Ozell
Ozella
Ozie
Pa
Page
Paige
Palma
Palmira
Pam
Pamala
Pamela
Pamelia
Pamella
Pamila
Pamula
Pandora
Pansy
Paola
Paris
Parthenia
Particia
Pasty
Pat
Patience
Patria
Patrica
Patrice
Patricia
Patrick
Patrina
Patsy
Patti
Pattie
Patty
Paul
Paula
Paulene
Pauletta
Paulette
Paulina
Pauline
Paulita
Paz
Pearl
Pearle
Pearlene
Pearlie
Pearline
Pearly
Peg
Peggie
Peggy
Pei
Penelope
Penney
Penni
Pennie
Penny
Perla
Perry
Peter
Petra
Petrina
Petronila
Phebe
Phillis
Philomena
Phoebe
Phung
Phuong
Phylicia
Phylis
Phyliss
Phyllis
Pia
Piedad
Pilar
Ping
Pinkie
Piper
Pok
Polly
Porsche
Porsha
Portia
Precious
Pricilla
Princess
Priscila
Priscilla
Providencia
Prudence
Pura
Qiana
Queen
Queenie
Quiana
Quinn
Quyen
Rachael
Rachal
Racheal
Rachel
Rachele
Rachell
Rachelle
Racquel
Rae
Raeann
Raelene
Rafaela
Raguel
Raina
Raisa
Ramona
Ramonita
Rana
Ranae
Randa
Randee
Randi
Randy
Ranee
Raquel
Rasheeda
Rashida
Raven
Ray
Raye
Raylene
Raymond
Raymonde
Rayna
Rea
Reagan
Reanna
Reatha
Reba
Rebbeca
Rebbecca
Rebeca
Rebecca
Rebecka
Rebekah
Reda
Reena
Refugia
Refugio
Regan
Regena
Regenia
Regina
Regine
Reginia
Reiko
Reina
Reita
Rema
Remedios
Remona
Rena
Renae
Renata
Renate
Renay
Renda
Rene
Renea
Renee
Renetta
Renita
Renna
Ressie
Reta
Retha
Retta
Reva
Reyna
Reynalda
Rhea
Rheba
Rhiannon
Rhoda
Rhona
Rhonda
Ria
Ricarda
Richard
Richelle
Ricki
Rickie
Rikki
Rima
Rina
Risa
Rita
Riva
Rivka
Robbi
Robbie
Robbin
Robbyn
Robena
Robert
Roberta
Roberto
Robin
Robyn
Rochel
Rochell
Rochelle
Rocio
Rolanda
Rolande
Roma
Romaine
Romana
Romelia
Romona
Rona
Ronald
Ronda
Roni
Ronna
Ronni
Ronnie
Rory
Rosa
Rosalba
Rosalee
Rosalia
Rosalie
Rosalina
Rosalind
Rosalinda
Rosaline
Rosalva
Rosalyn
Rosamaria
Rosamond
Rosana
Rosann
Rosanna
Rosanne
Rosaria
Rosario
Rosaura
Rose
Roseann
Roseanna
Roseanne
Roselee
Roselia
Roseline
Rosella
Roselle
Roselyn
Rosemarie
Rosemary
Rosena
Rosenda
Rosetta
Rosette
Rosia
Rosie
Rosina
Rosio
Rosita
Roslyn
Rossana
Rossie
Rosy
Rowena
Roxana
Roxane
Roxann
Roxanna
Roxanne
Roxie
Roxy
Roy
Royce
Rozanne
Rozella
Rubi
Rubie
Ruby
Rubye
Rudy
Rufina
Russell
Ruth
Rutha
Ruthann
Ruthanne
Ruthe
Ruthie
Ryan
Ryann
Sabina
Sabine
Sabra
Sabrina
Sacha
Sachiko
Sade
Sadie
Sadye
Sage
Salena
Salina
Salley
Sallie
Sally
Salome
Sam
Samantha
Samara
Samatha
Samella
Samira
Sammie
Sammy
Samuel
Sana
Sanda
Sandee
Sandi
Sandie
Sandra
Sandy
Sang
Sanjuana
Sanjuanita
Sanora
Santa
Santana
Santina
Santos
Sara
Sarah
Sarai
Saran
Sari
Sarina
Sarita
Sasha
Saturnina
Sau
Saundra
Savanna
Savannah
Scarlet
Scarlett
Scott
Scottie
Sean
Season
Sebrina
See
Seema
Selena
Selene
Selina
Selma
Sena
Senaida
September
Serafina
Serena
Serina
Serita
Setsuko
Sha
Shae
Shaina
Shakia
Shakira
Shakita
Shala
Shalanda
Shalon
Shalonda
Shameka
Shamika
Shan
Shana
Shanae
Shanda
Shandi
Shandra
Shane
Shaneka
Shanel
Shanell
Shanelle
Shani
Shanice
Shanika
Shaniqua
Shanita
Shanna
Shannan
Shannon
Shanon
Shanta
Shantae
Shantay
Shante
Shantel
Shantell
Shantelle
Shanti
Shaquana
Shaquita
Shara
Sharan
Sharda
Sharee
Sharell
Sharen
Shari
Sharice
Sharie
Sharika
Sharilyn
Sharita
Sharla
Sharleen
Sharlene
Sharmaine
Sharolyn
Sharon
Sharonda
Sharri
Sharron
Sharyl
Sharyn
Shasta
Shaun
Shauna
Shaunda
Shaunna
Shaunta
Shaunte
Shavon
Shavonda
Shavonne
Shawana
Shawanda
Shawanna
Shawn
Shawna
Shawnda
Shawnee
Shawnna
Shawnta
Shay
Shayla
Shayna
Shayne
Shea
Sheba
Sheena
Sheila
Sheilah
Shela
Shelba
Shelby
Shelia
Shella
Shelley
Shelli
Shellie
Shelly
Shemeka
Shemika
Shena
Shenika
Shenita
Shenna
Shera
Sheree
Sherell
Sheri
Sherice
Sheridan
Sherie
Sherika
Sherill
Sherilyn
Sherise
Sherita
Sherlene
Sherley
Sherly
Sherlyn
Sheron
Sherrell
Sherri
Sherrie
Sherril
Sherrill
Sherron
Sherry
Sherryl
Shery
Sheryl
Sheryll
Shiela
Shila
Shiloh
Shin
Shira
Shirely
Shirl
Shirlee
Shirleen
Shirlene
Shirley
Shirly
Shizue
Shizuko
Shona
Shonda
Shondra
Shonna
Shonta
Shoshana
Shu
Shyla
Sibyl
Sidney
Sierra
Signe
Sigrid
Silva
Silvana
Silvia
Sima
Simona
Simone
Simonne
Sina
Sindy
Siobhan
Sirena
Siu
Sixta
Skye
Slyvia
So
Socorro
Sofia
Soila
Sol
Solange
Soledad
Somer
Sommer
Son
Sona
Sondra
Song
Sonia
Sonja
Sonya
Soo
Sook
Soon
Sophia
Sophie
Soraya
Sparkle
Spring
Stacee
Stacey
Staci
Stacia
Stacie
Stacy
Star
Starla
Starr
Stasia
Stefani
Stefania
Stefanie
Stefany
Steffanie
Stella
Stepanie
Stephaine
Stephane
Stephani
Stephania
Stephanie
Stephany
Stephen
Stephenie
Stephine
Stephnie
Steven
Stevie
Stormy
Su
Suanne
Sudie
Sue
Sueann
Suellen
Suk
Sulema
Sumiko
Summer
Sun
Sunday
Sung
Sunni
Sunny
Sunshine
Susan
Susana
Susann
Susanna
Susannah
Susanne
Susie
Susy
Suzan
Suzann
Suzanna
Suzanne
Suzette
Suzi
Suzie
Suzy
Svetlana
Sybil
Syble
Sydney
Sylvia
Sylvie
Synthia
Syreeta
Ta
Tabatha
Tabetha
Tabitha
Tai
Taina
Taisha
Tajuana
Takako
Takisha
Talia
Talisha
Talitha
Tam
Tama
Tamala
Tamar
Tamara
Tamatha
Tambra
Tameika
Tameka
Tamekia
Tamela
Tamera
Tamesha
Tami
Tamica
Tamie
Tamika
Tamiko
Tamisha
Tammara
Tammera
Tammi
Tammie
Tammy
Tamra
Tana
Tandra
Tandy
Taneka
Tanesha
Tangela
Tania
Tanika
Tanisha
Tanja
Tanna
Tanya
Tara
Tarah
Taren
Tari
Tarra
Tarsha
Taryn
Tasha
Tashia
Tashina
Tasia
Tatiana
Tatum
Tatyana
Taunya
Tawana
Tawanda
Tawanna
Tawna
Tawny
Tawnya
Taylor
Tayna
Teena
Tegan
Teisha
Telma
Temeka
Temika
Tempie
Temple
Tena
Tenesha
Tenisha
Tennie
Tennille
Teodora
Teofila
Tequila
Tera
Tereasa
Teresa
Terese
Teresia
Teresita
Teressa
Teri
Terica
Terina
Terisa
Terra
Terrell
Terresa
Terri
Terrie
Terrilyn
Terry
Tesha
Tess
Tessa
Tessie
Thalia
Thanh
Thao
Thea
Theda
Thelma
Theo
Theodora
Theola
Theresa
Therese
Theresia
Theressa
Thersa
Thi
Thomas
Thomasena
Thomasina
Thomasine
Thora
Thresa
Thu
Thuy
Tia
Tiana
Tianna
Tiara
Tien
Tiera
Tierra
Tiesha
Tifany
Tiffaney
Tiffani
Tiffanie
Tiffany
Tiffiny
Tijuana
Tilda
Tillie
Timika
Timothy
Tina
Tinisha
Tiny
Tisa
Tish
Tisha
Tobi
Tobie
Toby
Toccara
Toi
Tomasa
Tomeka
Tomi
Tomika
Tomiko
Tommie
Tommy
Tommye
Tomoko
Tona
Tonda
Tonette
Toni
Tonia
Tonie
Tonisha
Tonita
Tonja
Tony
Tonya
Tora
Tori
Torie
Torri
Torrie
Tory
Tosha
Toshia
Toshiko
Tova
Towanda
Toya
Tracee
Tracey
Traci
Tracie
Tracy
Tran
Trang
Travis
Treasa
Treena
Trena
Tresa
Tressa
Tressie
Treva
Tricia
Trina
Trinh
Trinidad
Trinity
Trish
Trisha
Trista
Tristan
Troy
Trudi
Trudie
Trudy
Trula
Tu
Tula
Tuyet
Twana
Twanda
Twanna
Twila
Twyla
Tyesha
Tyisha
Tyler
Tynisha
Tyra
Ula
Ulrike
Un
Una
Ursula
Usha
Ute
Vada
Val
Valarie
Valda
Valencia
Valene
Valentina
Valentine
Valeri
Valeria
Valerie
Valery
Vallie
Valorie
Valrie
Van
Vanda
Vanesa
Vanessa
Vanetta
Vania
Vanita
Vanna
Vannesa
Vannessa
Vashti
Vasiliki
Veda
Velda
Velia
Vella
Velma
Velva
Velvet
Vena
Venessa
Venetta
Venice
Venita
Vennie
Venus
Veola
Vera
Verda
Verdell
Verdie
Verena
Vergie
Verla
Verlene
Verlie
Verline
Verna
Vernell
Vernetta
Vernia
Vernice
Vernie
Vernita
Vernon
Verona
Veronica
Veronika
Veronique
Versie
Vertie
Vesta
Veta
Vi
Vicenta
Vickey
Vicki
Vickie
Vicky
Victor
Victoria
Victorina
Vida
Viki
Vikki
Vilma
Vina
Vincenza
Vinita
Vinnie
Viola
Violet
Violeta
Violette
Virgen
Virgie
Virgil
Virgina
Virginia
Vita
Viva
Vivan
Vivian
Viviana
Vivien
Vivienne
Voncile
Vonda
Vonnie
Wai
Walter
Waltraud
Wan
Wanda
Waneta
Wanetta
Wanita
Wava
Wei
Wen
Wendi
Wendie
Wendolyn
Wendy
Wenona
Wesley
Whitley
Whitney
Wilda
Wilhelmina
Wilhemina
Willa
Willena
Willene
Willetta
Willette
Willia
William
Willie
Williemae
Willodean
Willow
Wilma
Windy
Winifred
Winnie
Winnifred
Winona
Winter
Wonda
Wynell
Wynona
Xenia
Xiao
Xiomara
Xochitl
Xuan
Yadira
Yaeko
Yael
Yahaira
Yajaira
Yan
Yang
Yanira
Yasmin
Yasmine
Yasuko
Yee
Yelena
Yen
Yer
Yesenia
Yessenia
Yetta
Yevette
Yi
Ying
Yoko
Yolanda
Yolande
Yolando
Yolonda
Yon
Yong
Yoshie
Yoshiko
Youlanda
Young
Yu
Yuette
Yuk
Yuki
Yukiko
Yuko
Yulanda
Yun
Yung
Yuonne
Yuri
Yuriko
Yvette
Yvone
Yvonne
Zada
Zaida
Zana
Zandra
Zelda
Zella
Zelma
Zena
Zenaida
Zenia
Zenobia
Zetta
Zina
Zita
Zoe
Zofia
Zoila
Zola
Zona
Zonia
Zora
Zoraida
Zula
Zulema
Zulma
tools\dbatools\bin\datamasking\firstnames_male.txt
Aaron
Abdul
Abe
Abel
Abraham
Abram
Adalberto
Adam
Adan
Adolfo
Adolph
Adrian
Agustin
Ahmad
Ahmed
Al
Alan
Albert
Alberto
Alden
Aldo
Alec
Alejandro
Alex
Alexander
Alexis
Alfonso
Alfonzo
Alfred
Alfredo
Ali
Allan
Allen
Alonso
Alonzo
Alphonse
Alphonso
Alton
Alva
Alvaro
Alvin
Amado
Ambrose
Amos
Anderson
Andre
Andrea
Andreas
Andres
Andrew
Andy
Angel
Angelo
Anibal
Anthony
Antione
Antoine
Anton
Antone
Antonia
Antonio
Antony
Antwan
Archie
Arden
Ariel
Arlen
Arlie
Armand
Armando
Arnold
Arnoldo
Arnulfo
Aron
Arron
Art
Arthur
Arturo
Asa
Ashley
Aubrey
August
Augustine
Augustus
Aurelio
Austin
Avery
Barney
Barrett
Barry
Bart
Barton
Basil
Beau
Ben
Benedict
Benito
Benjamin
Bennett
Bennie
Benny
Benton
Bernard
Bernardo
Bernie
Berry
Bert
Bertram
Bill
Billie
Billy
Blaine
Blair
Blake
Bo
Bob
Bobbie
Bobby
Booker
Boris
Boyce
Boyd
Brad
Bradford
Bradley
Bradly
Brady
Brain
Branden
Brandon
Brant
Brendan
Brendon
Brent
Brenton
Bret
Brett
Brian
Brice
Britt
Brock
Broderick
Brooks
Bruce
Bruno
Bryan
Bryant
Bryce
Bryon
Buck
Bud
Buddy
Buford
Burl
Burt
Burton
Buster
Byron
Caleb
Calvin
Cameron
Carey
Carl
Carlo
Carlos
Carlton
Carmelo
Carmen
Carmine
Carol
Carrol
Carroll
Carson
Carter
Cary
Casey
Cecil
Cedric
Cedrick
Cesar
Chad
Chadwick
Chance
Chang
Charles
Charley
Charlie
Chas
Chase
Chauncey
Chester
Chet
Chi
Chong
Chris
Christian
Christoper
Christopher
Chuck
Chung
Clair
Clarence
Clark
Claud
Claude
Claudio
Clay
Clayton
Clement
Clemente
Cleo
Cletus
Cleveland
Cliff
Clifford
Clifton
Clint
Clinton
Clyde
Cody
Colby
Cole
Coleman
Colin
Collin
Colton
Columbus
Connie
Conrad
Cordell
Corey
Cornelius
Cornell
Cortez
Cory
Courtney
Coy
Craig
Cristobal
Cristopher
Cruz
Curt
Curtis
Cyril
Cyrus
Dale
Dallas
Dalton
Damian
Damien
Damion
Damon
Dan
Dana
Dane
Danial
Daniel
Danilo
Dannie
Danny
Dante
Darell
Daren
Darin
Dario
Darius
Darnell
Daron
Darrel
Darrell
Darren
Darrick
Darrin
Darron
Darryl
Darwin
Daryl
Dave
David
Davis
Dean
Deandre
Deangelo
Dee
Del
Delbert
Delmar
Delmer
Demarcus
Demetrius
Denis
Dennis
Denny
Denver
Deon
Derek
Derick
Derrick
Deshawn
Desmond
Devin
Devon
Dewayne
Dewey
Dewitt
Dexter
Dick
Diego
Dillon
Dino
Dion
Dirk
Domenic
Domingo
Dominic
Dominick
Dominique
Don
Donald
Dong
Donn
Donnell
Donnie
Donny
Donovan
Donte
Dorian
Dorsey
Doug
Douglas
Douglass
Doyle
Drew
Duane
Dudley
Duncan
Dustin
Dusty
Dwain
Dwayne
Dwight
Dylan
Earl
Earle
Earnest
Ed
Eddie
Eddy
Edgar
Edgardo
Edison
Edmond
Edmund
Edmundo
Eduardo
Edward
Edwardo
Edwin
Efrain
Efren
Elbert
Elden
Eldon
Eldridge
Eli
Elias
Elijah
Eliseo
Elisha
Elliot
Elliott
Ellis
Ellsworth
Elmer
Elmo
Eloy
Elroy
Elton
Elvin
Elvis
Elwood
Emanuel
Emerson
Emery
Emil
Emile
Emilio
Emmanuel
Emmett
Emmitt
Emory
Enoch
Enrique
Erasmo
Eric
Erich
Erick
Erik
Erin
Ernest
Ernesto
Ernie
Errol
Ervin
Erwin
Esteban
Ethan
Eugene
Eugenio
Eusebio
Evan
Everett
Everette
Ezekiel
Ezequiel
Ezra
Fabian
Faustino
Fausto
Federico
Felipe
Felix
Felton
Ferdinand
Fermin
Fernando
Fidel
Filiberto
Fletcher
Florencio
Florentino
Floyd
Forest
Forrest
Foster
Frances
Francesco
Francis
Francisco
Frank
Frankie
Franklin
Franklyn
Fred
Freddie
Freddy
Frederic
Frederick
Fredric
Fredrick
Freeman
Fritz
Gabriel
Gail
Gale
Galen
Garfield
Garland
Garret
Garrett
Garry
Garth
Gary
Gaston
Gavin
Gayle
Gaylord
Genaro
Gene
Geoffrey
George
Gerald
Geraldo
Gerard
Gerardo
German
Gerry
Gil
Gilbert
Gilberto
Gino
Giovanni
Giuseppe
Glen
Glenn
Gonzalo
Gordon
Grady
Graham
Graig
Grant
Granville
Greg
Gregg
Gregorio
Gregory
Grover
Guadalupe
Guillermo
Gus
Gustavo
Guy
Hai
Hal
Hank
Hans
Harlan
Harland
Harley
Harold
Harris
Harrison
Harry
Harvey
Hassan
Hayden
Haywood
Heath
Hector
Henry
Herb
Herbert
Heriberto
Herman
Herschel
Hershel
Hilario
Hilton
Hipolito
Hiram
Hobert
Hollis
Homer
Hong
Horace
Horacio
Hosea
Houston
Howard
Hoyt
Hubert
Huey
Hugh
Hugo
Humberto
Hung
Hunter
Hyman
Ian
Ignacio
Ike
Ira
Irvin
Irving
Irwin
Isaac
Isaiah
Isaias
Isiah
Isidro
Ismael
Israel
Isreal
Issac
Ivan
Ivory
Jacinto
Jack
Jackie
Jackson
Jacob
Jacques
Jae
Jaime
Jake
Jamaal
Jamal
Jamar
Jame
Jamel
James
Jamey
Jamie
Jamison
Jan
Jared
Jarod
Jarred
Jarrett
Jarrod
Jarvis
Jason
Jasper
Javier
Jay
Jayson
Jc
Jean
Jed
Jeff
Jefferey
Jefferson
Jeffery
Jeffrey
Jeffry
Jerald
Jeramy
Jere
Jeremiah
Jeremy
Jermaine
Jerold
Jerome
Jeromy
Jerrell
Jerrod
Jerrold
Jerry
Jess
Jesse
Jessie
Jesus
Jewel
Jewell
Jim
Jimmie
Jimmy
Joan
Joaquin
Jody
Joe
Joel
Joesph
Joey
John
Johnathan
Johnathon
Johnie
Johnnie
Johnny
Johnson
Jon
Jonah
Jonas
Jonathan
Jonathon
Jordan
Jordon
Jorge
Jose
Josef
Joseph
Josh
Joshua
Josiah
Jospeh
Josue
Juan
Jude
Judson
Jules
Julian
Julio
Julius
Junior
Justin
Kareem
Karl
Kasey
Keenan
Keith
Kelley
Kelly
Kelvin
Ken
Kendall
Kendrick
Keneth
Kenneth
Kennith
Kenny
Kent
Kenton
Kermit
Kerry
Keven
Kevin
Kieth
Kim
King
Kip
Kirby
Kirk
Korey
Kory
Kraig
Kris
Kristofer
Kristopher
Kurt
Kurtis
Kyle
Lacy
Lamar
Lamont
Lance
Landon
Lane
Lanny
Larry
Lauren
Laurence
Lavern
Laverne
Lawerence
Lawrence
Lazaro
Leandro
Lee
Leif
Leigh
Leland
Lemuel
Len
Lenard
Lenny
Leo
Leon
Leonard
Leonardo
Leonel
Leopoldo
Leroy
Les
Lesley
Leslie
Lester
Levi
Lewis
Lincoln
Lindsay
Lindsey
Lino
Linwood
Lionel
Lloyd
Logan
Lon
Long
Lonnie
Lonny
Loren
Lorenzo
Lou
Louie
Louis
Lowell
Loyd
Lucas
Luciano
Lucien
Lucio
Lucius
Luigi
Luis
Luke
Lupe
Luther
Lyle
Lyman
Lyndon
Lynn
Lynwood
Mac
Mack
Major
Malcolm
Malcom
Malik
Man
Manual
Manuel
Marc
Marcel
Marcelino
Marcellus
Marcelo
Marco
Marcos
Marcus
Margarito
Maria
Mariano
Mario
Marion
Mark
Markus
Marlin
Marlon
Marquis
Marshall
Martin
Marty
Marvin
Mary
Mason
Mathew
Matt
Matthew
Maurice
Mauricio
Mauro
Max
Maximo
Maxwell
Maynard
Mckinley
Mel
Melvin
Merle
Merlin
Merrill
Mervin
Micah
Michael
Michal
Michale
Micheal
Michel
Mickey
Miguel
Mike
Mikel
Milan
Miles
Milford
Millard
Milo
Milton
Minh
Miquel
Mitch
Mitchel
Mitchell
Modesto
Mohamed
Mohammad
Mohammed
Moises
Monroe
Monte
Monty
Morgan
Morris
Morton
Mose
Moses
Moshe
Murray
Myles
Myron
Napoleon
Nathan
Nathanael
Nathanial
Nathaniel
Neal
Ned
Neil
Nelson
Nestor
Neville
Newton
Nicholas
Nick
Nickolas
Nicky
Nicolas
Nigel
Noah
Noble
Noe
Noel
Nolan
Norbert
Norberto
Norman
Normand
Norris
Numbers
Octavio
Odell
Odis
Olen
Olin
Oliver
Ollie
Omar
Omer
Oren
Orlando
Orval
Orville
Oscar
Osvaldo
Oswaldo
Otha
Otis
Otto
Owen
Pablo
Palmer
Paris
Parker
Pasquale
Pat
Patricia
Patrick
Paul
Pedro
Percy
Perry
Pete
Peter
Phil
Philip
Phillip
Pierre
Porfirio
Porter
Preston
Prince
Quentin
Quincy
Quinn
Quintin
Quinton
Rafael
Raleigh
Ralph
Ramiro
Ramon
Randal
Randall
Randell
Randolph
Randy
Raphael
Rashad
Raul
Ray
Rayford
Raymon
Raymond
Raymundo
Reed
Refugio
Reggie
Reginald
Reid
Reinaldo
Renaldo
Renato
Rene
Reuben
Rex
Rey
Reyes
Reynaldo
Rhett
Ricardo
Rich
Richard
Richie
Rick
Rickey
Rickie
Ricky
Rico
Rigoberto
Riley
Rob
Robbie
Robby
Robert
Roberto
Robin
Robt
Rocco
Rocky
Rod
Roderick
Rodger
Rodney
Rodolfo
Rodrick
Rodrigo
Rogelio
Roger
Roland
Rolando
Rolf
Rolland
Roman
Romeo
Ron
Ronald
Ronnie
Ronny
Roosevelt
Rory
Rosario
Roscoe
Rosendo
Ross
Roy
Royal
Royce
Ruben
Rubin
Rudolf
Rudolph
Rudy
Rueben
Rufus
Rupert
Russ
Russel
Russell
Rusty
Ryan
Sal
Salvador
Salvatore
Sam
Sammie
Sammy
Samual
Samuel
Sandy
Sanford
Sang
Santiago
Santo
Santos
Saul
Scot
Scott
Scottie
Scotty
Sean
Sebastian
Sergio
Seth
Seymour
Shad
Shane
Shannon
Shaun
Shawn
Shayne
Shelby
Sheldon
Shelton
Sherman
Sherwood
Shirley
Shon
Sid
Sidney
Silas
Simon
Sol
Solomon
Son
Sonny
Spencer
Stacey
Stacy
Stan
Stanford
Stanley
Stanton
Stefan
Stephan
Stephen
Sterling
Steve
Steven
Stevie
Stewart
Stuart
Sung
Sydney
Sylvester
Tad
Tanner
Taylor
Ted
Teddy
Teodoro
Terence
Terrance
Terrell
Terrence
Terry
Thad
Thaddeus
Thanh
Theo
Theodore
Theron
Thomas
Thurman
Tim
Timmy
Timothy
Titus
Tobias
Toby
Tod
Todd
Tom
Tomas
Tommie
Tommy
Toney
Tony
Tory
Tracey
Tracy
Travis
Trent
Trenton
Trevor
Trey
Trinidad
Tristan
Troy
Truman
Tuan
Ty
Tyler
Tyree
Tyrell
Tyron
Tyrone
Tyson
Ulysses
Val
Valentin
Valentine
Van
Vance
Vaughn
Vern
Vernon
Vicente
Victor
Vince
Vincent
Vincenzo
Virgil
Virgilio
Vito
Von
Wade
Waldo
Walker
Wallace
Wally
Walter
Walton
Ward
Warner
Warren
Waylon
Wayne
Weldon
Wendell
Werner
Wes
Wesley
Weston
Whitney
Wilber
Wilbert
Wilbur
Wilburn
Wiley
Wilford
Wilfred
Wilfredo
Will
Willard
William
Williams
Willian
Willie
Willis
Willy
Wilmer
Wilson
Wilton
Winford
Winfred
Winston
Wm
Woodrow
Wyatt
Xavier
Yong
Young
Zachariah
Zachary
Zachery
Zack
Zackary
Zane
tools\dbatools\bin\datamasking\lastnames_all.txt
Aaberg
Aaby
Aadland
Aagaard
Aakre
Aaland
Aalbers
Aalderink
Aalund
Aamodt
Aamot
Aanderud
Aanenson
Aanerud
Aarant
Aardema
Aarestad
Aarhus
Aaron
Aarons
Aaronson
Aarsvold
Aas
Aasby
Aase
Aasen
Aavang
Abad
Abadi
Abadie
Abair
Abaja
Abajian
Abalos
Abaloz
Abar
Abarca
Abare
Abascal
Abasta
Abate
Abati
Abatiell
Abato
Abatti
Abaunza
Abaya
Abbadessa
Abbamonte
Abbas
Abbasi
Abbassi
Abbate
Abbatiello
Abbay
Abbe
Abbed
Abbenante
Abbey
Abbinanti
Abbington
Abbitt
Abbot
Abbott
Abboud
Abbruzzese
Abbs
Abby
Abdalla
Abdallah
Abdel
Abdelal
Abdelaziz
Abdeldayen
Abdelhamid
Abdella
Abdelmuti
Abdelrahman
Abdelwahed
Abdi
Abdin
Abdo
Abdon
Abdool
Abdou
Abdul
Abdula
Abdulaziz
Abdulkarim
Abdulla
Abdullah
Abdullai
Abdulmateen
Abdulmuniem
Abdur
Abe
Abeb
Abed
Abedelah
Abedi
Abee
Abegg
Abeita
Abel
Abela
Abelar
Abelardo
Abele
Abeles
Abell
Abella
Abellera
Abelman
Abeln
Abels
Abelson
Aben
Abend
Abendroth
Aber
Abercombie
Abercrombie
Aberle
Abernatha
Abernathy
Abernethy
Aberson
Abes
Abeta
Abete
Abetrani
Abeyta
Abide
Abigantus
Abila
Abilay
Abild
Abilez
Abina
Abington
Abitong
Abke
Abkemeier
Ablang
Ablao
Able
Ableman
Abler
Ables
Ablin
Abling
Abner
Abnet
Abney
Abo
Abolafia
Abolt
Abood
Aboshihata
Aboud
Aboudi
Aboulahoud
Aboulissan
Abousaleh
Aboytes
Abplanalp
Abrachinsky
Abraham
Abrahamian
Abrahams
Abrahamsen
Abrahamson
Abram
Abramek
Abramian
Abramoff
Abramov
Abramovich
Abramovitz
Abramowitz
Abramowski
Abrams
Abramson
Abrantes
Abreau
Abrecht
Abrego
Abrell
Abreo
Abreu
Abrev
Abrew
Abrey
Abrial
Abril
Abriola
Abrom
Abron
Abruzzese
Abruzzino
Abruzzo
Absalon
Abshear
Absher
Abshier
Abshire
Abson
Abston
Abt
Abts
Abu
Abuaita
Abubakr
Abud
Abuel
Abugn
Abuhl
Abundis
Abundiz
Aburto
Abusufait
Acal
Acampora
Accala
Accardi
Accardo
Accetta
Accetturo
Accola
Accomando
Accornero
Accosta
Accurso
Ace
Acebedo
Acebo
Acedo
Acee
Aceituno
Acencio
Aceret
Acerno
Acero
Acerra
Aceto
Aceuedo
Acevado
Aceveda
Acevedo
Aceves
Acey
Acfalle
Achane
Ache
Acheampong
Achee
Achekian
Achenbach
Acheson
Achille
Achilles
Achin
Achor
Achord
Achorn
Achter
Achterhof
Achzet
Achziger
Acierno
Acimovic
Ack
Ackah
Acken
Acker
Ackerley
Ackerly
Ackerman
Ackermann
Ackers
Ackerson
Ackert
Ackies
Ackins
Ackison
Ackiss
Ackland
Acklen
Ackles
Ackley
Acklin
Ackman
Ackmann
Ackroyd
Acly
Acoba
Acocella
Acock
Acoff
Acor
Acord
Acorda
Acors
Acosta
Acosto
Acothley
Acquaviva
Acquilla
Acre
Acree
Acres
Acrey
Acri
Acron
Actis
Acton
Acuff
Acuna
Acy
Ada
Adachi
Adair
Adalja
Adam
Adamaitis
Adamcik
Adamczak
Adamczyk
Adame
Adamec
Adamek
Adames
Adami
Adamiak
Adamik
Adamis
Adamitis
Adamo
Adamos
Adamowski
Adams
Adamsen
Adamski
Adamsky
Adamson
Adamsonis
Adamyan
Adan
Adank
Adas
Adauto
Adaway
Aday
Adcock
Adcox
Addair
Addams
Addario
Addeo
Adderley
Adderly
Addesso
Addicks
Addie
Addiego
Addington
Addis
Addison
Addleman
Addo
Adduci
Addy
Ade
Adebisi
Adee
Adel
Adelblue
Adelgren
Adelizzi
Adell
Adelman
Adelmann
Adelmund
Adels
Adelsberg
Adelson
Adelsperger
Adelstein
Adema
Aden
Adens
Ader
Aderhold
Aderholdt
Aderholt
Aderman
Aderson
Ades
Adessa
Adesso
Adey
Adeyemo
Adger
Adham
Adhami
Adi
Adib
Adickes
Adie
Adil
Adinolfi
Adjei
Adjutant
Adkerson
Adkin
Adkins
Adkinson
Adkison
Adkisson
Adlam
Adle
Adleman
Adler
Adley
Adling
Adloff
Admas
Admire
Adner
Adney
Adolf
Adolfo
Adolfson
Adolph
Adolphe
Adolphsen
Adolphson
Adolphus
Adomaitis
Adon
Adonis
Adorno
Adragna
Adrian
Adriance
Adriano
Adrid
Adrien
Adrion
Adrovel
Adside
Adsit
Adu
Aduddell
Adule
Adwell
Ady
Adzhabakyan
Aegerter
Aeillo
Aeling
Aemmer
Aerni
Aerts
Aery
Aeschbacher
Aeschliman
Aeschlimann
Afable
Afalava
Afan
Afanador
Affagato
Affeld
Affelt
Affeltranger
Affleck
Afflick
Affolter
Affronti
Aflalo
Afoa
Afonso
Africa
Afshar
Afshari
Afton
Afurong
Afzal
Agamao
Agan
Agans
Agar
Agard
Agarwal
Agbayani
Agbisit
Agcaoili
Age
Ageboi
Agee
Agel
Agemy
Agena
Agent
Ager
Agers
Agerter
Agerton
Aggarwal
Aggas
Aggers
Agib
Agilar
Agin
Agins
Agle
Agler
Agliam
Agne
Agnelli
Agnello
Agner
Agnes
Agnew
Agney
Agni
Agnor
Agoff
Agonoy
Agor
Agoras
Agoro
Agosta
Agosti
Agostinelli
Agostini
Agostino
Agosto
Agpaoa
Agramonte
Agrawal
Agre
Agreda
Agredano
Agrela
Agresta
Agreste
Agresti
Agresto
Agricola
Agriesti
Agrios
Agro
Agron
Agtarap
Aguada
Aguado
Aguallo
Aguas
Aguayo
Agudelo
Agudo
Agueda
Aguele
Aguero
Aguiar
Aguila
Aguilar
Aguiler
Aguilera
Aguillar
Aguillard
Aguillera
Aguillon
Aguinaga
Aguinaldo
Aguiniga
Aguino
Aguire
Aguirre
Agular
Aguliar
Agumga
Agundez
Agunos
Aguon
Agurs
Agustin
Agustine
Agustino
Agyeman
Ahal
Ahalt
Aharon
Aharoni
Aharonof
Ahart
Ahaus
Ahearn
Ahern
Aherns
Ahhee
Ahia
Ahimud
Ahl
Ahlberg
Ahlborn
Ahlbrecht
Ahle
Ahlemeyer
Ahler
Ahlers
Ahles
Ahlf
Ahlfield
Ahlgren
Ahlheim
Ahlin
Ahlm
Ahlman
Ahlo
Ahlquist
Ahlstedt
Ahlstrom
Ahluwalia
Ahmad
Ahmadi
Ahmann
Ahmau
Ahmed
Ahn
Ahne
Ahnell
Ahner
Aho
Aholt
Ahonen
Ahr
Ahrendes
Ahrends
Ahrendt
Ahrenholtz
Ahrenholz
Ahrens
Ahrenstorff
Ahrent
Ahrns
Ahsan
Ahsing
Ahuja
Ahumada
Ahuna
Ahyet
Ahyou
Aiava
Aichele
Aicklen
Aid
Aidt
Aiello
Aievoli
Aigner
Aihara
Aiken
Aikens
Aikey
Aikin
Aikins
Aikman
Ailes
Ailey
Ailiff
Aills
Ailor
Ailshire
Ailstock
Ailsworth
Ailts
Aimbez
Aimone
Aina
Aines
Ainge
Aini
Ainley
Ainscough
Ainsley
Ainslie
Ainsworth
Aiola
Aiona
Aipopo
Aiporlani
Aipperspach
Aird
Airhart
Airington
Airola
Airth
Aispuro
Aita
Aitcheson
Aitchison
Aites
Aitken
Aitkin
Aitkins
Aiton
Aiu
Aiudi
Aiuto
Aivao
Aiyer
Aja
Ajani
Ajasin
Ajayi
Ajello
Ajoku
Ajose
Akahi
Akal
Akamine
Akamiro
Akana
Akande
Akapo
Akard
Akau
Akawanzie
Akbar
Akbari
Ake
Akel
Akemon
Aken
Aker
Akerley
Akerman
Akers
Akerson
Akery
Akes
Akey
Akhand
Akhavan
Akhtar
Aki
Akiereisen
Akim
Akima
Akimseu
Akin
Akinrefon
Akins
Akinyooye
Akiona
Akiyama
Akkerman
Akles
Akley
Akmal
Ako
Akoni
Akpan
Akram
Akre
Akridge
Akright
Aksamit
Aksoy
Akuchie
Akuna
Akwei
Ala
Alacano
Alagna
Alai
Alaibilla
Alaimo
Alalem
Alam
Alambar
Alameda
Alameida
Alamia
Alamilla
Alamillo
Alamin
Alamo
Alamos
Alampi
Alan
Aland
Alanis
Alaniz
Alanko
Alano
Alapai
Alar
Alarcon
Alarcone
Alarid
Alarie
Alario
Alas
Alatorre
Alatosse
Alattar
Alavi
Alawdi
Alaya
Alba
Albach
Albair
Albaladejo
Alban
Albanese
Albanez
Albang
Albani
Albano
Albany
Albarado
Albarazi
Albares
Albarez
Albarracin
Albarran
Albaugh
Albe
Albea
Albee
Albelo
Alben
Alber
Alberda
Alberding
Alberg
Albergotti
Alberico
Albero
Alberro
Alberry
Albers
Alberson
Albert
Alberta
Alberthal
Alberti
Albertine
Albertini
Alberto
Alberts
Albertsen
Albertson
Alberty
Albery
Albin
Albini
Albino
Albiston
Albor
Alborn
Albornoz
Albracht
Albrashi
Albrecht
Albrekht
Albright
Albriton
Albrittain
Albritton
Albro
Albrough
Albu
Albury
Albus
Alby
Alcaide
Alcala
Alcalde
Alcantar
Alcantara
Alcantas
Alcaoa
Alcaraz
Alcazar
Alce
Alcide
Alcina
Alcine
Alcini
Alcivar
Alcocer
Alcock
Alcombright
Alcon
Alconcel
Alcorn
Alcorta
Alcoser
Alcosiba
Alcott
Aldaba
Aldaco
Aldama
Aldana
Aldapa
Aldape
Aldarondo
Aldas
Aldava
Alday
Aldaz
Aldecoa
Alden
Alder
Alderete
Alderfer
Alderink
Alderman
Alderson
Alderton
Aldi
Aldinger
Aldo
Aldonza
Aldous
Aldred
Aldredge
Aldrege
Aldrete
Aldrich
Aldridge
Aldrige
Aldrow
Aldworth
Alea
Alecca
Aleem
Aleff
Alegar
Alegi
Alegre
Alegria
Aleizar
Alejandre
Alejandrez
Alejandro
Alejo
Alejos
Alekna
Aleksey
Aleman
Alemany
Alen
Aleo
Alepin
Alequin
Aler
Alers
Alert
Alerte
Ales
Alesci
Alescio
Aleshire
Alesi
Alesna
Alessandrini
Alessandro
Alessandroni
Alesse
Alessi
Alessio
Alevedo
Alevras
Alewine
Alex
Alexader
Alexaki
Alexakis
Alexander
Alexanders
Alexandra
Alexandre
Alexandria
Alexandropoul
Alexanian
Alexender
Alexidor
Alexion
Alexiou
Alexis
Alexnder
Alexopoulos
Alexy
Alexzander
Aley
Aleyandrez
Alf
Alfandre
Alfano
Alfaro
Alfera
Alferez
Alfero
Alff
Alfieri
Alfiero
Alfisi
Alfonsi
Alfonso
Alfonzo
Alford
Alfred
Alfredo
Alfreds
Alfrey
Alfson
Algarin
Alge
Algee
Algeo
Alger
Alghamdi
Algien
Algier
Algire
Algood
Alguire
Alhaddad
Alhambra
Alhameed
Alhusseini
Ali
Aliaga
Aliano
Alias
Aliberti
Alibozek
Alicandro
Alice
Alicea
Alicer
Alicia
Alicuben
Alie
Alier
Aliff
Alig
Alim
Aliment
Alimento
Alimo
Aline
Alioto
Aliotta
Alipio
Alire
Alires
Alirez
Alisauskas
Alison
Alix
Alizadeh
Aljemal
Alkana
Alkbsh
Alkema
Alken
Alkins
Alkire
All
Allaband
Allabaugh
Allah
Allain
Allaire
Allam
Allaman
Allamon
Allamong
Allan
Allanson
Allara
Allard
Allateef
Allaway
Allbee
Allbert
Allbones
Allbright
Allbritten
Allbritton
Allcock
Allcorn
Allday
Allder
Alldredge
Allebach
Allee
Allegood
Allegra
Allegre
Allegretta
Allegretti
Allegrini
Allegrucci
Alleman
Allemand
Allemond
Allen
Allenbach
Allenbaugh
Allenbrand
Allende
Allender
Allendorf
Allenson
Allensworth
Aller
Allerman
Allers
Allerton
Alleruzzo
Allery
Alles
Alleshouse
Allessi
Allessio
Alleva
Allevato
Allex
Alley
Alleyne
Allford
Allgaeuer
Allgaier
Allgeier
Allgeyer
Allgier
Allgire
Allgood
Allhands
Alli
Alliance
Allie
Alligood
Alliman
Allin
Allinder
Alling
Allinger
Allington
Allio
Allis
Allison
Alliston
Allman
Allmand
Allmon
Allmond
Allnutt
Allocca
Allocco
Allon
Allor
Alloway
Allphin
Allred
Allridge
Alls
Allsbrook
Allsbrooks
Allscheid
Allshouse
Allsop
Allston
Allstott
Allsup
Allton
Alltop
Allum
Allums
Allvin
Allwardt
Allwood
Ally
Allyn
Allyne
Alm
Alma
Almada
Almaguer
Almajhoub
Alman
Almand
Almanza
Almanzar
Almaras
Almaraz
Almarez
Almario
Almarza
Almas
Almasi
Almazan
Alme
Almeda
Almeida
Almen
Almenar
Almendarez
Almengor
Almerico
Almestica
Almeter
Almeyda
Almgren
Almiron
Almodova
Almodovar
Almon
Almond
Almonte
Almos
Almquist
Almstead
Almsteadt
Almy
Alnas
Alnoor
Alnutt
Alo
Aloan
Aloe
Aloi
Aloia
Aloisi
Alonge
Alongi
Alonso
Alonza
Alonzo
Alosa
Alosta
Alouf
Aloy
Alpaugh
Alper
Alperin
Alpern
Alpers
Alpert
Alpha
Alpheaus
Alphin
Alphonse
Alphonso
Alpis
Alpizar
Alquesta
Alquicira
Alquijay
Alquisira
Alrais
Alred
Alrich
Alrod
Alsandor
Alsaqri
Alsberry
Alsbrook
Alsbrooks
Alsbury
Alsdon
Alsheimer
Alshouse
Alsina
Alsing
Alsip
Alsman
Alsobrook
Alsobrooks
Alson
Alsop
Alspach
Alspaugh
Alstad
Alston
Alstott
Alstrom
Alsup
Alt
Altadonna
Altamirano
Altamiruno
Altaras
Altavilla
Altemus
Altenbach
Altenburg
Altenhofen
Alter
Alteri
Alterio
Alterman
Altermatt
Altes
Altew
Althaus
Althauser
Altheimer
Althiser
Althoff
Althouse
Altic
Altice
Altidor
Altier
Altieri
Altiery
Altig
Altimus
Altizer
Altken
Altman
Altmann
Altmark
Altmiller
Altmire
Alto
Altobell
Altobelli
Altobello
Altom
Altomare
Altomari
Altomonte
Alton
Altonen
Altop
Altreche
Altringer
Altro
Altrogge
Altschuler
Altshuler
Altsisi
Altstatt
Altum
Altvater
Altwies
Alty
Alu
Aluarado
Aluarez
Aluise
Alukonis
Alumbaugh
Alummoottil
Aluqdah
Alva
Alvacado
Alvalle
Alvanas
Alvanez
Alvara
Alvarado
Alvardo
Alvarenga
Alvarengo
Alvares
Alvarez
Alvaro
Alvarracin
Alvarran
Alvear
Alvelo
Alven
Alverado
Alveraz
Alverest
Alverez
Alverio
Alvernaz
Alvero
Alverson
Alves
Alvey
Alvez
Alvia
Alviar
Alvidrez
Alvin
Alvine
Alvino
Alvira
Alvirez
Alvis
Alviso
Alvizo
Alvord
Alvorez
Alwan
Alwang
Alward
Alwardt
Alway
Alwazan
Alwin
Alwine
Aly
Alyea
Alzaga
Alzate
Alzugaray
Amabile
Amacher
Amack
Amacker
Amadeo
Amadi
Amadio
Amado
Amadon
Amador
Amailla
Amaker
Amalfitano
Amalong
Aman
Amancio
Amann
Amano
Amante
Amanza
Amar
Amara
Amaral
Amarante
Amargo
Amari
Amarian
Amarillas
Amaro
Amas
Amason
Amass
Amat
Amati
Amato
Amauty
Amavisca
Amaya
Amazan
Ambagis
Ambeau
Amber
Amberg
Ambers
Amberson
Ambert
Amble
Ambler
Amboise
Amboree
Amborn
Ambres
Ambrister
Ambriz
Ambrogi
Ambrose
Ambrosia
Ambrosini
Ambrosino
Ambrosio
Ambrosius
Ambrosone
Ambroz
Ambroziak
Ambuehl
Amburgey
Amburgy
Amburn
Amdahl
Amderson
Amedee
Amedeo
Amedro
Ameduri
Ameen
Ameigh
Amejorado
Amel
Amela
Amelang
Ameling
Amelio
Amell
Amelung
Amemiya
Amen
Amend
Amendola
Ament
Amenta
Amentler
Amento
Amer
America
American
Amerine
Amerio
Amerman
Amero
Amerson
Amert
Ames
Amesbury
Amescua
Amesquieto
Amesquita
Amey
Amezaga
Amezcua
Amezquita
Amici
Amick
Amico
Amicone
Amidei
Amidi
Amidon
Amie
Amigo
Amigon
Amill
Amin
Amini
Aminov
Amiot
Amir
Amirault
Amiri
Amirian
Amis
Amisano
Amison
Amistadi
Amistoso
Amith
Amlin
Ammann
Ammar
Ammer
Ammerman
Ammirata
Ammirati
Ammirato
Ammon
Ammonds
Ammons
Amo
Amoa
Amoah
Amoako
Amodei
Amodeo
Amodio
Amodt
Amoe
Amolsch
Amon
Amonette
Amons
Amor
Amore
Amorello
Amores
Amoriello
Amorim
Amorin
Amormino
Amoros
Amorose
Amorosi
Amoroso
Amoruso
Amory
Amos
Amoss
Amott
Amour
Amous
Amparan
Amparo
Amphy
Ampy
Amr
Amrein
Amrhein
Amrich
Amrine
Amsbaugh
Amsberry
Amsdell
Amsden
Amsili
Amsinger
Amsler
Amsley
Amspaugh
Amspoker
Amstein
Amster
Amsterdam
Amstrong
Amstutz
Amtower
Amundsen
Amundson
Amunrud
Amuso
Amweg
Amy
Amyot
Amyotte
Amys
Amyx
An
Ana
Anable
Anacker
Anadio
Anagnos
Anagnost
Anagnostou
Anakalea
Analla
Anand
Anania
Ananias
Anasagasti
Anast
Anastacio
Anastas
Anastasi
Anastasia
Anastasiades
Anastasio
Anastos
Anauo
Anawalt
Anawaty
Anaya
Ancalade
Ancar
Ancel
Ancelet
Ancell
Ancheta
Anchondo
Anchors
Ancic
Ancira
Anciso
Ancona
Ancrum
Anctil
Ancy
Anda
Andalora
Andary
Andaverde
Andaya
Andebe
Andel
Andelman
Ander
Andera
Anderberg
Andere
Anderegg
Anderholm
Anderl
Anderlik
Anderman
Anderon
Anders
Andersen
Anderson
Andersson
Anderst
Andert
Anderton
Andes
Andeson
Andina
Anding
Andino
Andis
Ando
Andoh
Andon
Andonian
Andra
Andrachak
Andracki
Andrada
Andrade
Andrades
Andradez
Andrado
Andrae
Andrango
Andras
Andre
Andrea
Andreadis
Andreas
Andreasen
Andreason
Andreassen
Andreassi
Andreatta
Andree
Andreen
Andreessen
Andregg
Andren
Andreola
Andreoli
Andreoni
Andreotti
Andreozzi
Andrepont
Andres
Andresen
Andress
Andreu
Andreula
Andrew
Andrews
Andrian
Andrich
Andrick
Andries
Andringa
Andrino
Andrion
Andriopulos
Andris
Andrle
Androde
Androes
Androlewicz
Andronis
Andros
Androsky
Andrson
Andrulis
Andrus
Andruss
Andruszkiewic
Andruzzi
Andry
Andrzejczak
Andrzejczyk
Andrzejewski
Andueza
Andujar
Andujo
Andy
Andzulis
Anecelle
Anelli
Anello
Anene
Anerton
Anes
Aneshansley
Anesi
Anestos
Anetsberger
Anewalt
Aney
Anez
Anfinson
Ang
Angalich
Angarola
Ange
Angel
Angela
Angelbeck
Angeles
Angeletti
Angeli
Angelica
Angelico
Angelilli
Angelillo
Angeline
Angelini
Angelino
Angell
Angelle
Angello
Angellotti
Angelo
Angelocci
Angeloff
Angelone
Angeloni
Angeloro
Angelos
Angelotti
Angelou
Angelovich
Angelozzi
Angelson
Angelucci
Anger
Angerer
Angerman
Angermeier
Angeron
Angers
Angert
Angevine
Angiano
Angier
Angilello
Angileri
Angilletta
Angiolelli
Angiolillo
Angione
Angis
Anglada
Anglade
Angland
Angle
Anglea
Angleberger
Anglebrandt
Anglemyer
Anglen
Angles
Angleton
Angley
Anglin
Anglum
Angocicco
Angold
Angolo
Angon
Angotti
Angove
Angrisano
Angry
Angst
Angstadt
Angton
Anguiano
Angulo
Angus
Angustia
Angviano
Angwin
Anhalt
Anhorn
Anibal
Anichini
Anick
Anidi
Aniello
Animashaun
Aningalan
Aninion
Aniol
Anis
Anitok
Ankenman
Ankeny
Anker
Ankersen
Anklam
Ankney
Ankrapp
Ankrom
Ankrum
Anliker
Ann
Anna
Annabel
Annable
Annal
Annala
Annan
Annand
Annarino
Annarummo
Annarumo
Annas
Anne
Anneler
Annen
Annese
Anness
Annett
Annette
Annibale
Annicchiarico
Annichiarico
Anning
Annino
Annis
Anno
Annon
Annonio
Annunziata
Annuzzi
Ano
Anoe
Anolick
Anon
Anos
Anreozzi
Ansara
Ansari
Ansbacher
Ansbro
Anschutz
Ansel
Ansell
Anselm
Anselmi
Anselmo
Anshutz
Ansley
Anslinger
Ansloan
Anslow
Ansoategui
Anson
Anspach
Anspaugh
Anstead
Anstett
Anstey
Anstine
Antal
Antao
Antaya
Antczak
Anteby
Antee
Antell
Antenor
Antenucci
Anter
Antes
Anthes
Anthis
Anthon
Anthony
Antich
Antignani
Antigua
Antila
Antill
Antilla
Antillon
Antinarelli
Antinore
Antinoro
Antione
Antis
Antista
Antkowiak
Antle
Antley
Antman
Antoine
Antolak
Antolik
Antolin
Antolini
Antolos
Anton
Antona
Antonacci
Antonaccio
Antonakos
Antone
Antonelli
Antonellis
Antonello
Antonetti
Antonetty
Antonia
Antoniak
Antonich
Antoniewicz
Antonini
Antonio
Antoniotti
Antoniou
Antonis
Antoniuk
Antonopoulos
Antonovich
Antonsen
Antonson
Antonucci
Antony
Antos
Antosh
Antrican
Antrikin
Antrim
Antrobus
Antronica
Anttila
Antu
Antuna
Antunes
Antunez
Antwi
Antwine
Anwar
Anway
Anyan
Anzai
Anzaldo
Anzaldua
Anzalone
Anzideo
Anzora
Anzualda
Anzures
Ao
Aoay
Aoki
Aono
Apa
Apadaca
Apadoca
Apaez
Apalategui
Apana
Aparicio
Aparo
Ape
Apel
Apela
Apelian
Aper
Aperges
Apfel
Apgar
Apicella
Apilado
Apker
Apkin
Apking
Apland
Apley
Aplin
Apling
Aplington
Apo
Apodaca
Apodace
Apodoca
Apolinar
Apolito
Apollo
Apolo
Aponta
Aponte
Apostal
Apostol
App
Appana
Appel
Appelbaum
Appelgate
Appelgren
Appeling
Appell
Appello
Appelman
Appelt
Appenzeller
Apperson
Appert
Appia
Appiah
Appl
Apple
Applebaum
Applebee
Appleberry
Applebury
Appleby
Applegarth
Applegate
Appleman
Applen
Appleton
Applewhaite
Applewhite
Appleyard
Applin
Appling
Applonie
Appolonia
Aprea
Apresa
Aprigliano
April
Aprill
Apruzzese
Apsey
Apshire
Apt
Apthorpe
Apuzzi
Apuzzo
Apyuan
Aquas
Aquero
Aquil
Aquilar
Aquilera
Aquilina
Aquilino
Aquino
Aquirre
Ar
Arab
Arabajian
Arabia
Arabian
Arabie
Aracena
Aradanas
Aragaki
Aragan
Aragao
Aragon
Aragones
Aragoni
Aragundi
Aragus
Arai
Araiza
Arakaki
Arakawa
Araki
Araldi
Aramboles
Arambuia
Arambula
Arambulo
Aramini
Aran
Arana
Aranas
Arancibia
Arand
Aranda
Araneo
Arango
Aranjo
Arano
Arant
Araque
Arashiro
Arata
Arato
Arau
Araujo
Arauz
Arave
Aravjo
Araya
Arb
Arballo
Arbaugh
Arbeiter
Arbertha
Arbetman
Arbizo
Arbo
Arbogast
Arbogust
Arboleda
Arbolida
Arbon
Arbour
Arbry
Arbucci
Arbuckle
Arbuthnot
Arca
Arcadipane
Arcand
Arcangel
Arcano
Arcaro
Arcaute
Arce
Arcea
Arcega
Arcement
Arceneaux
Arceo
Arch
Archacki
Archambault
Archambeau
Archambeault
Archangel
Archbell
Archbold
Archdale
Archer
Archey
Archibald
Archibeque
Archibold
Archie
Archila
Archilla
Archiopoli
Archuleta
Archuletta
Archut
Arcia
Arciba
Arcieri
Arciga
Arcila
Arcilla
Arciniega
Arcino
Arciola
Arcizo
Arcoraci
Arcos
Arcudi
Arcuo
Arcuri
Ard
Ardaly
Ardan
Ardd
Ardelean
Arden
Ardeneaux
Ardery
Ardinger
Ardion
Ardis
Ardito
Ardizone
Ardizzone
Ardman
Ardner
Ardoin
Ardolino
Ardon
Ardrey
Ardry
Ards
Arduini
Area
Areas
Arebalo
Arebela
Arechiga
Aredondo
Arehano
Arehart
Areias
Areizaga
Arel
Arellanes
Arellano
Arelleano
Arena
Arenales
Arenas
Arenburg
Arend
Arendale
Arendall
Arendash
Arender
Arends
Arendsee
Arendt
Arendz
Arenivar
Arenivas
Arenos
Arens
Arenson
Arenstam
Arent
Arentz
Arenz
Areola
Ares
Aresco
Arevalo
Arevalos
Arey
Arflack
Arfman
Argabright
Argall
Arganbright
Argandona
Argenal
Argenbright
Argenti
Argentieri
Argento
Argenziano
Argetsinger
Argie
Argiro
Argo
Argote
Argrave
Argro
Argrow
Argubright
Argudin
Argudo
Argue
Arguelles
Arguellez
Arguello
Argueta
Arguijo
Arguilez
Arguillo
Arguin
Argulewicz
Argumedo
Argust
Argyle
Arhart
Arhelger
Ariail
Ariano
Arias
Ariaza
Aricas
Arichabala
Arico
Aridas
Arie
Ariel
Aries
Arietta
Arif
Arigo
Arildsen
Arimas
Arimoto
Aring
Arington
Ariola
Aris
Arisa
Arismendez
Arispe
Arista
Aristide
Aristizabal
Arisumi
Arita
Ariyoshi
Ariza
Arizaga
Arizmendi
Arizola
Arizzi
Arjes
Arjona
Arjune
Arkadie
Arkell
Arkema
Arkenberg
Arkin
Arking
Arkins
Arko
Arkontaky
Arlan
Arledge
Arlen
Arleth
Arlia
Arline
Arlinghaus
Arlington
Arlotta
Arlt
Arm
Armacost
Armada
Armagost
Arman
Armand
Armando
Armant
Armantrout
Armas
Armato
Armbrester
Armbrister
Armbrust
Armbruster
Armel
Armeli
Armelin
Armen
Armendarez
Armendariz
Armengol
Arment
Armenta
Armenteros
Armento
Armentor
Armentrout
Armer
Armes
Armesto
Armfield
Armiger
Armijo
Armijos
Armillei
Armintrout
Armiso
Armistead
Armitage
Armlin
Armocida
Armold
Armon
Armond
Armor
Armour
Armout
Arms
Armson
Armstead
Armster
Armstong
Armstrong
Armwood
Army
Arn
Arnaldo
Arnall
Arnao
Arnau
Arnaud
Arnaudet
Arndell
Arndorfer
Arndt
Arne
Arneberg
Arneecher
Arnell
Arner
Arnerich
Arnesen
Arneson
Arnet
Arnett
Arnette
Arney
Arnhart
Arnhold
Arnholt
Arnholtz
Arning
Arnio
Arniotes
Arnitz
Arnn
Arno
Arnold
Arnoldi
Arnoldy
Arnone
Arnot
Arnott
Arnoux
Arnow
Arns
Arnsberger
Arnspiger
Arnst
Arnstein
Arnsworth
Arnt
Arntson
Arntt
Arntz
Arntzen
Arnwine
Arnzen
Aro
Aroca
Arocha
Aroche
Arocho
Arollo
Aromin
Aron
Arone
Aronhalt
Aronica
Aronoff
Aronov
Aronow
Aronowitz
Arons
Aronson
Aronstein
Arora
Arosemena
Arostegui
Arouri
Aroyo
Arp
Arpin
Arpino
Arps
Arquelles
Arquero
Arqueta
Arquette
Arquitt
Arra
Arraiol
Arrambide
Arrance
Arrand
Arrant
Arrants
Arras
Arrasmith
Arre
Arreaga
Arredla
Arredondo
Arreguin
Arrellano
Arrellin
Arrendell
Arrendondo
Arreola
Arrequin
Arrey
Arrez
Arrezola
Arriaga
Arriano
Arriaza
Arriazola
Arribas
Arrick
Arrieta
Arrigo
Arrigone
Arrindel
Arrington
Arriola
Arris
Arrisola
Arrison
Arritola
Arrizaga
Arrizola
Arrocha
Arrocho
Arrojo
Arroliga
Arrollo
Arron
Arrospide
Arrott
Arrow
Arrowood
Arrowsmith
Arroyano
Arroyd
Arroyo
Arroyos
Arruda
Arsenault
Arseneau
Arseneault
Arsham
Arslan
Arslanian
Art
Artale
Artalejo
Arteaga
Artega
Arter
Arterberry
Arterburn
Arterbury
Arters
Artez
Arthun
Arthur
Arthurs
Artiaga
Artibee
Artice
Arties
Artiga
Artiles
Artinger
Artinian
Artis
Artison
Artist
Artley
Artman
Artmann
Artola
Arton
Artrip
Artry
Arts
Arturo
Artus
Artuso
Artz
Artzer
Aruiso
Aruizu
Arujo
Arunachalam
Arundel
Arva
Arvan
Arvanitis
Arvay
Arvayo
Arvelo
Arvesen
Arvez
Arvidson
Arvie
Arview
Arvin
Arviso
Arvizo
Arvizu
Arwood
Ary
Arya
Arzabala
Arzaga
Arzate
Arzilli
Arzo
Arzola
Arzt
Arzu
Asa
Asad
Asaeli
Asai
Asakura
Asal
Asam
Asamoah
Asano
Asante
Asar
Asaro
Asato
Asay
Asbell
Asberry
Asbill
Asbridge
Asbury
Asby
Ascencio
Ascensio
Ascenzo
Asch
Aschan
Aschbacher
Ascheman
Aschenbach
Aschenbrener
Aschenbrenner
Ascher
Aschim
Aschmann
Aschoff
Ascol
Ascolese
Asebedo
Asel
Aselage
Aseltine
Asen
Asencio
Aseng
Asenjo
Asevedo
Asfour
Ash
Ashaf
Ashalintubbi
Ashauer
Ashbach
Ashbacher
Ashbaugh
Ashbourne
Ashbrook
Ashburn
Ashby
Ashcraft
Ashcroft
Ashdown
Ashe
Ashely
Ashenfelter
Asher
Ashfield
Ashford
Ashing
Ashkettle
Ashland
Ashley
Ashlin
Ashline
Ashlock
Ashly
Ashman
Ashmead
Ashmen
Ashmore
Ashner
Ashpole
Ashraf
Ashton
Ashurst
Ashwell
Ashwood
Ashworth
Asiedu
Asiello
Asif
Ask
Askam
Askari
Aske
Askegren
Asken
Askew
Askey
Askia
Askiew
Askin
Askins
Askland
Askren
Askvig
Askwith
Aslam
Aslanian
Asleson
Aslett
Asley
Aslin
Aslinger
Asma
Asman
Asmar
Asmus
Asmussen
Asner
Asnicar
Asp
Aspacio
Aspden
Aspegren
Aspell
Aspen
Asper
Asperheim
Aspinall
Aspinwall
Aspley
Asplin
Asplund
Aspri
Asquith
Asrari
Assad
Assael
Assaf
Assalone
Assante
Asselin
Asselmeier
Asselta
Assenmacher
Assing
Assis
Assum
Ast
Asta
Astacio
Astafan
Astarita
Aste
Asters
Astillero
Astin
Astle
Astley
Astol
Astolfi
Aston
Astor
Astorga
Astorino
Astrella
Astrologo
Astrup
Astry
Astudillo
Asturias
Astwood
Asuncion
Aswegan
Atala
Atallah
Atamanczyk
Atamian
Atanacio
Atay
Atcher
Atcheson
Atchinson
Atchison
Atchity
Atchley
Atcitty
Aten
Atencio
Atengco
Ater
Ates
Atha
Athalone
Athan
Athanasiou
Athans
Athas
Athay
Athayde
Athearn
Athens
Atherholt
Atherley
Atherton
Athey
Athmann
Athy
Atienza
Atilano
Atiles
Atiyeh
Atkerson
Atkeson
Atkin
Atkins
Atkinson
Atkison
Atkisson
Atlas
Atleh
Atma
Atmore
Atnip
Atoe
Aton
Ator
Atta
Attal
Attanasio
Attard
Attaway
Atteberry
Attebery
Atteburg
Atterberry
Atterbury
Atterson
Atthowe
Attia
Attianese
Attig
Attilio
Attinger
Attkisson
Attles
Attleson
Attridge
Attwell
Attwood
Atwater
Atwell
Atwill
Atwood
Atzhorn
Atzinger
Au
Auala
Aube
Aubel
Auber
Auberry
Aubert
Aubertine
Aubin
Auble
Aubrecht
Aubrey
Aubry
Aubuchon
Aubut
Auces
Auch
Auchmoody
Auck
Auckerman
Auckley
Auclair
Aucoin
Aucter
Aud
Audain
Audas
Audelhuk
Audet
Audette
Audi
Audia
Audibert
Audie
Audirsch
Audrey
Auduong
Aue
Auel
Auer
Auerbach
Auerswald
Aufderheide
Auffrey
Aufiero
Auge
Augello
Augenstein
Auger
Augeri
Aughe
Aughenbaugh
Aughtman
Aughtry
Augle
Augliano
Augsburger
Augspurger
August
Augusta
Augustave
Auguste
Augustin
Augustine
Augusto
Augustson
Augustus
Augustyn
Augustyniak
Auila
Auiles
Aujla
Aukamp
Auker
Aukerman
Aukes
Aul
Aulabaugh
Aulbach
Auld
Aulder
Auldridge
Aulds
Auler
Auletta
Aull
Auls
Ault
Aultman
Aultz
Auman
Aumann
Aumavae
Aumen
Aumend
Aument
Aumich
Aumick
Aumiller
Aun
Auna
Aune
Aungst
Aunkst
Aupperle
Auprey
Aurand
Aurelia
Aurelio
Aures
Aurges
Auricchio
Aurich
Auringer
Aurora
Aurrichio
Aus
Ausbrooks
Ausburn
Ausby
Ausdemore
Ausherman
Ausiello
Auslam
Ausland
Auslander
Ausley
Ausman
Ausmus
Aust
Austad
Austell
Austen
Auster
Austerberry
Austgen
Austill
Austin
Austine
Austino
Auston
Austria
Autaubo
Auten
Auter
Auteri
Autery
Authement
Auther
Authur
Autin
Autio
Autman
Autobee
Auton
Autovino
Autrano
Autrey
Autry
Autullo
Auvil
Auwaerter
Auwarter
Auxier
Auxilien
Auyer
Auyeung
Auyon
Auyong
Auzat
Auzenne
Auzston
Avala
Avallone
Avalos
Avance
Avancena
Avans
Avansino
Avant
Avants
Avanzato
Avarbuch
Avary
Ave
Aveado
Avelar
Aveles
Aveline
Avelino
Avella
Avellaneda
Avellano
Avellar
Avellino
Avello
Avena
Avendano
Aveni
Avenia
Avenoso
Avent
Aver
Avera
Averbach
Averbeck
Averett
Averette
Averhart
Averill
Averitt
Averitte
Avers
Aversa
Aversano
Avery
Averyt
Avetisyan
Avey
Avie
Avila
Avilar
Aviles
Avilez
Avilla
Avina
Avinger
Avino
Avirett
Avis
Avison
Avita
Avitabile
Avitia
Avner
Avola
Avolio
Avon
Avona
Avrett
Avril
Aw
Awad
Awada
Awai
Awalt
Awbrey
Awe
Awender
Awkard
Awkward
Awong
Awtrey
Awtry
Awyie
Ax
Axe
Axel
Axelrad
Axelrod
Axelsen
Axelson
Axford
Axley
Axline
Axman
Axon
Axsom
Axson
Axt
Axtell
Axthelm
Axtman
Axton
Ayaia
Ayala
Ayalla
Ayars
Ayarza
Aybar
Aycock
Aycox
Aydelott
Aydin
Aydlett
Aydt
Aye
Ayele
Ayer
Ayers
Ayersman
Ayhens
Aykroid
Ayles
Aylesworth
Ayling
Aylock
Aylor
Aylsworth
Aylward
Aymar
Aymond
Aynes
Ayo
Ayola
Ayon
Ayoob
Ayotte
Ayoub
Ayre
Ayres
Ayscue
Aysien
Aytes
Ayudan
Ayuso
Ayyad
Azad
Azahar
Azapinto
Azar
Azatyan
Azbell
Azbill
Azcona
Azebedo
Azeem
Azen
Azer
Azevedo
Azhocar
Azim
Azimi
Aziz
Azor
Azore
Azotea
Azoulay
Azua
Azulay
Azuma
Azure
Azzano
Azzara
Azzarella
Azzarito
Azzaro
Azznara
Azzopardi
Ba
Baab
Baack
Baade
Baadsgaard
Baar
Baars
Baarts
Baas
Baatz
Bab
Baba
Babat
Babauta
Babb
Babbel
Babbin
Babbish
Babbit
Babbitt
Babbs
Babcock
Babe
Babecki
Babel
Babena
Baber
Babers
Babeu
Babey
Babiarz
Babic
Babich
Babick
Babicke
Babicz
Babikian
Babilon
Babilonia
Babin
Babine
Babineau
Babineaux
Babington
Babino
Babinski
Babione
Babiracki
Babish
Babitsch
Babjeck
Bablak
Bable
Babonis
Babrow
Babson
Babst
Babu
Babula
Babyak
Baca
Bacak
Bacarella
Bacayo
Bacca
Baccam
Baccari
Bacchi
Bacchus
Bacco
Baccouche
Baccus
Bacerra
Bach
Bacha
Bachan
Bachand
Bachar
Bachas
Bache
Bachelder
Bachelor
Bacher
Bachert
Bachhuber
Bachicha
Bachinski
Bachleda
Bachler
Bachman
Bachmann
Bachmeier
Bachmeyer
Bachner
Bacho
Bachor
Bachorski
Bachrach
Bachrodt
Bachta
Bachtel
Bachtell
Bachtold
Bachus
Bacich
Bacigalupi
Bacigalupo
Bacik
Bacino
Bacio
Back
Backbone
Backe
Backen
Backenstose
Backer
Backers
Backes
Backey
Backfisch
Backhaus
Backhuus
Backlund
Backman
Backmon
Backous
Backstrom
Backues
Backus
Bacman
Bacolor
Bacon
Bacone
Bacorn
Bacot
Bacote
Baculpo
Bacurin
Bacus
Bacy
Baczewski
Bad
Badagliacca
Badal
Badalamenti
Badame
Badami
Badamo
Badanguio
Badasci
Baddeley
Badder
Badders
Baddley
Baddour
Bade
Badeau
Badeaux
Baden
Badena
Badenoch
Bader
Badertscher
Badey
Badger
Badgero
Badget
Badgett
Badgley
Badia
Badie
Badilla
Badillo
Badini
Badlam
Badley
Badman
Bado
Badolato
Badon
Badoni
Badour
Badruddin
Badua
Badura
Bady
Badzinski
Bae
Baehr
Baek
Baell
Baena
Baenziger
Baer
Baerg
Baerga
Baeringer
Baerlocher
Baerman
Baese
Baeskens
Baessler
Baetz
Baez
Baeza
Baff
Baffa
Bafford
Baffuto
Bafia
Bagan
Bagaoisan
Bagby
Bagdasarian
Bagdon
Bagdonas
Bageant
Bagen
Bagent
Bagg
Bagge
Baggenstoss
Bagger
Baggerly
Baggesen
Baggett
Baggette
Baggio
Baggott
Baggs
Baghdasarian
Bagheri
Bagi
Baginski
Bagley
Baglione
Bagnall
Bagnaschi
Bagnato
Bagne
Bagnell
Bagner
Bagni
Bagnoli
Bagoyo
Bagozzi
Bagron
Bagsby
Bagshaw
Bagu
Bagwell
Bagwill
Bah
Bahadue
Baham
Bahamonde
Bahar
Bahde
Bahe
Bahena
Baher
Bahl
Bahler
Bahlmann
Bahls
Bahm
Bahn
Bahner
Bahnsen
Bahoora
Bahr
Bahri
Bahrke
Bahrmasel
Bahrs
Bahun
Bai
Baibak
Baich
Baichan
Baier
Baiera
Baierl
Baig
Baik
Bail
Bailado
Bailard
Baile
Bailer
Bailes
Bailey
Bailie
Bailiff
Bailin
Baillargeon
Baille
Baillet
Bailleu
Baillie
Baillio
Bailly
Bailon
Bailony
Bailor
Baily
Baim
Baima
Bain
Bainard
Bainbridge
Baine
Bainer
Baines
Bainey
Bains
Bainter
Bainum
Baio
Baiotto
Bair
Bairam
Baird
Baires
Bairo
Bairos
Baisch
Baisden
Baise
Baisey
Baish
Baisley
Baison
Baisten
Baites
Baitg
Baitner
Baity
Baiz
Baiza
Baize
Baizer
Baj
Bajaj
Bajdas
Bajek
Bajko
Bajorek
Bajwa
Bak
Baka
Bakalar
Bakalars
Bakaler
Bakanauskas
Bake
Bakeley
Bakemeier
Baken
Baker
Bakerville
Bakes
Bakewell
Bakey
Bakhshian
Bakios
Bakkala
Bakke
Bakken
Bakker
Bakko
Bakkum
Bakley
Baklund
Bakos
Bakowski
Bakr
Baksh
Bakshi
Baksi
Bakst
Bakula
Bal
Bala
Balaam
Balaban
Baladejo
Balado
Balafoutas
Balagtas
Balak
Balancia
Balandran
Balangatan
Balanoff
Balas
Balasa
Balasco
Balash
Balaski
Balasko
Balassi
Balasubramani
Balay
Balaz
Balazs
Balbas
Balbi
Balbin
Balboa
Balboni
Balbontin
Balbuena
Balcazar
Balceiro
Balcer
Balcerzak
Balch
Balchunas
Balcitis
Balck
Balckburn
Balckwell
Balcom
Balcomb
Balcorta
Balcos
Bald
Balda
Baldacchino
Baldacci
Baldasaro
Baldassano
Baldassara
Baldassare
Baldassarre
Baldauf
Balde
Baldearena
Baldelli
Balden
Baldenegro
Balder
Balderama
Balderas
Balderrama
Balderree
Balderson
Balderston
Baldi
Balding
Baldinger
Baldini
Baldino
Baldivia
Baldiviez
Baldo
Baldock
Baldomero
Baldon
Baldonado
Baldor
Baldos
Baldree
Baldrey
Baldridge
Baldrige
Balducci
Balduf
Baldus
Balduzzi
Baldwin
Baldwyn
Baldy
Baldyga
Bale
Balensiefen
Balent
Balentine
Balerio
Bales
Balestra
Balestrieri
Balette
Baley
Balezentis
Balfany
Balfe
Balford
Balfour
Balhorn
Bali
Balian
Balich
Balick
Balicki
Baliga
Baligod
Balin
Balint
Balis
Balish
Balistreri
Balistrieri
Balitas
Balius
Balk
Balkcom
Balke
Balkey
Balkin
Balko
Balkus
Ball
Balla
Balladares
Ballagas
Ballagh
Ballam
Ballan
Ballance
Ballantine
Ballantyne
Ballar
Ballard
Ballas
Ballato
Balle
Ballejos
Ballek
Ballen
Ballena
Ballengee
Ballenger
Ballensky
Ballentine
Baller
Ballerini
Balles
Ballestas
Ballester
Ballestero
Ballesteros
Ballesterous
Balletta
Balletto
Ballew
Balley
Ballez
Balleza
Balli
Balliet
Balliett
Balliew
Ballif
Ballin
Ballina
Balling
Ballinger
Ballintyn
Ballman
Ballmann
Ballmer
Ballog
Ballon
Balloon
Ballou
Ballow
Ballowe
Ballreich
Balls
Balluch
Ballweg
Bally
Balm
Balmaceda
Balmer
Balmes
Balmir
Balmores
Balmos
Balnis
Balo
Balock
Balog
Balogh
Balogun
Balok
Balon
Balonek
Balow
Balowski
Baloy
Balque
Balsam
Balsamo
Balsano
Balser
Balsiger
Balsis
Balsley
Balson
Balster
Baltazar
Baltazor
Balter
Baltes
Balthazar
Balthazor
Balthrop
Baltierra
Baltimore
Baltodano
Balton
Baltrip
Baltruweit
Baltz
Baltzell
Baltzer
Baltzley
Balvanz
Balwin
Balwinski
Balyeat
Balza
Balzano
Balzarine
Balzarini
Balzer
Balzotti
Bamba
Bambace
Bambach
Bambaci
Bambacigno
Bambas
Bambeck
Bambenek
Bamber
Bamberg
Bamberger
Bambhrolia
Bambino
Bambrick
Bamburg
Bame
Bamfield
Bamford
Bamforth
Bammon
Ban
Banaag
Banach
Banahan
Banales
Banana
Banas
Banasiak
Banaszak
Banaszek
Banbury
Bance
Banchero
Bancks
Banco
Bancourt
Bancroft
Band
Banda
Bandanza
Bandarra
Bandasak
Bandel
Bandemer
Banderas
Bandin
Bandle
Bandley
Bandt
Banducci
Bandulin
Bandura
Bandy
Bandyk
Bane
Banecker
Banegas
Banek
Banerjee
Banerji
Banes
Banet
Baney
Banez
Banfield
Banfill
Bang
Bangert
Banghart
Bangle
Bangs
Bangura
Banh
Bania
Baniaga
Banick
Banik
Banis
Banister
Bank
Bankard
Banke
Bankemper
Banker
Bankert
Bankes
Bankey
Bankhead
Banko
Bankos
Bankowski
Banks
Bankson
Bankston
Bann
Bannan
Banner
Bannerman
Bannett
Banning
Bannister
Bannon
Bannowsky
Banome
Banos
Banowetz
Banowski
Bansal
Bansbach
Banse
Bansmer
Banta
Bantay
Banter
Banther
Bantillan
Bantin
Banton
Bantug
Bantz
Banuelos
Banvelos
Banville
Banwarth
Banwell
Banyas
Banzhaf
Baoloy
Bapties
Baptise
Baptist
Baptista
Baptiste
Baque
Baquero
Baquet
Baquiran
Bar
Bara
Baraban
Barabas
Barabin
Baraby
Baracani
Barach
Barad
Baradi
Baragan
Baragar
Barager
Baragona
Barahana
Barahona
Barajas
Barajos
Barak
Barakat
Baral
Baran
Baranga
Baranick
Baranoski
Baranovic
Baranow
Baranowski
Baranski
Baransky
Baras
Barasch
Barash
Baratta
Baratto
Baraw
Baray
Barayuga
Barb
Barba
Barbadillo
Barbagallo
Barbagelata
Barbaglia
Barbalich
Barban
Barbano
Barbar
Barbara
Barbare
Barbaria
Barbarin
Barbarino
Barbarito
Barbaro
Barbati
Barbato
Barbaza
Barbe
Barbeau
Barbee
Barbella
Barben
Barber
Barbera
Barberi
Barberian
Barberio
Barberis
Barbero
Barberr
Barbetta
Barbian
Barbie
Barbier
Barbiere
Barbieri
Barbin
Barbini
Barbish
Barbo
Barbone
Barbor
Barbosa
Barbot
Barbour
Barboza
Barbre
Barbrick
Barbu
Barbur
Barbuto
Barby
Barca
Barcello
Barcellos
Barcelo
Barcelona
Barcena
Barcenas
Barch
Barchacky
Barchick
Barchus
Barcia
Barcik
Barck
Barclay
Barcley
Barcliff
Barclift
Barco
Barcomb
Barcroft
Barcus
Barczak
Bard
Barda
Bardach
Bardales
Barde
Bardeen
Bardell
Barden
Bardes
Bardill
Bardin
Bardis
Bardney
Bardo
Bardon
Bardoner
Bardos
Bardsley
Bardwell
Bare
Barefield
Barefoot
Bareford
Bareilles
Bareis
Barela
Barella
Baremore
Barends
Barentine
Barer
Barera
Bares
Baresi
Barett
Barette
Barff
Barfield
Barfknecht
Barfoot
Barfuss
Barg
Barga
Barganier
Bargar
Bargas
Barge
Bargen
Barger
Bargeron
Bargerstock
Barges
Barginear
Bargmann
Bargo
Bargstadt
Barham
Barhorst
Barhydt
Bari
Baria
Barias
Baribeau
Barich
Barick
Barickman
Baridon
Barie
Barientos
Baril
Barile
Barill
Barillari
Barillaro
Barillas
Barillo
Barimah
Baringer
Barino
Bario
Barios
Baris
Barish
Barjas
Barjenbruch
Bark
Barkalow
Barkan
Barkdoll
Barkdull
Barke
Barkema
Barken
Barkenhagen
Barker
Barkes
Barket
Barkett
Barkhimer
Barkhurst
Barkie
Barkins
Barkle
Barkley
Barklow
Barkman
Barko
Barks
Barksdale
Barkus
Barlage
Barlak
Barlau
Barlett
Barletta
Barlette
Barley
Barlip
Barlock
Barlow
Barlowe
Barlup
Barman
Barmer
Barmes
Barmettler
Barmore
Barn
Barna
Barnaba
Barnaby
Barnacle
Barnak
Barnar
Barnard
Barnas
Barnathan
Barncastle
Barndt
Barne
Barnebey
Barnell
Barner
Barners
Barnes
Barness
Barnet
Barnett
Barnette
Barney
Barnfield
Barnhardt
Barnhart
Barnhill
Barnhouse
Barnhurst
Barnick
Barnicle
Barninger
Barno
Barnoski
Barns
Barnscater
Barnt
Barnthouse
Barnum
Barnwell
Baro
Barocio
Baroldy
Baron
Barona
Barone
Baroni
Baronne
Baroody
Baros
Barquera
Barr
Barra
Barrack
Barraclough
Barraco
Barragan
Barrale
Barran
Barranca
Barranco
Barranger
Barras
Barrasa
Barratt
Barraz
Barraza
Barre
Barreca
Barreda
Barredo
Barree
Barreira
Barreiro
Barrell
Barren
Barrena
Barreneche
Barrentine
Barrer
Barrera
Barreras
Barrero
Barresi
Barret
Barrete
Barreto
Barrett
Barretta
Barrette
Barretto
Barria
Barriault
Barribeau
Barricelli
Barrick
Barrickman
Barrie
Barrieau
Barrientes
Barrientez
Barrientos
Barrier
Barriere
Barries
Barriga
Barrigan
Barriger
Barrile
Barrilleaux
Barrineau
Barriner
Barringer
Barrington
Barrio
Barrios
Barris
Barrish
Barritt
Barro
Barrocas
Barrois
Barrom
Barron
Barros
Barroso
Barrott
Barrow
Barrowman
Barrows
Barrs
Barrus
Barry
Barryman
Bars
Barsalou
Barsamian
Barsanti
Barscewski
Barsch
Barschdoor
Barsegyan
Barsh
Barshaw
Barski
Barsky
Barsness
Barson
Barsotti
Barsoum
Barstad
Barstow
Barsuhn
Barswell
Bart
Barta
Bartamian
Bartash
Bartberger
Bartch
Bartczak
Barte
Bartee
Bartek
Bartel
Bartell
Bartels
Bartelson
Bartelt
Bartenfield
Barter
Barters
Bartgis
Barth
Bartha
Barthe
Barthel
Barthelemy
Barthell
Barthelman
Barthelmes
Barthen
Barthlow
Barthol
Barthold
Bartholemew
Bartholf
Bartholic
Bartholomay
Bartholomeu
Bartholomew
Bartholow
Bartimus
Bartin
Bartkiewicz
Bartko
Bartkowiak
Bartkowski
Bartkus
Bartl
Bartle
Bartlebaugh
Bartles
Bartleson
Bartlet
Bartlett
Bartlette
Bartley
Bartling
Bartlome
Bartlone
Bartlow
Bartman
Bartmes
Bartmess
Bartnett
Bartnick
Bartnik
Barto
Bartol
Bartoldus
Bartolet
Bartoletti
Bartoli
Bartolini
Bartolo
Bartolome
Bartolomei
Bartolomeo
Bartolomucci
Bartolone
Bartolotta
Bartolotto
Barton
Bartone
Bartos
Bartosch
Bartosh
Bartosiak
Bartosiewicz
Bartosik
Bartosz
Bartoszek
Bartow
Bartram
Bartron
Bartrop
Bartrum
Barts
Bartsch
Bartucca
Bartucci
Bartula
Bartunek
Bartus
Bartush
Bartuska
Bartylla
Bartz
Baruch
Barufaldi
Baruffa
Baruffi
Barus
Barut
Baruth
Barvick
Barvosa
Barwell
Barwick
Bary
Barz
Barze
Barzey
Basa
Basaldua
Basanta
Basara
Basbas
Bascas
Bascetta
Basch
Bascle
Basco
Bascom
Bascomb
Bascombe
Basden
Base
Basehore
Basel
Baseler
Baseley
Baselice
Baseman
Basemore
Basey
Basford
Basgall
Bash
Basha
Basham
Bashara
Bashaw
Basher
Bashford
Bashi
Bashinelli
Bashir
Bashline
Bashor
Bashore
Basich
Basil
Basila
Basile
Basiliere
Basilio
Basilone
Basinger
Basini
Basinski
Basista
Baskas
Baskerville
Basket
Baskett
Baskette
Baskin
Baskind
Baskins
Baskow
Basler
Basley
Basner
Basnett
Basnight
Basom
Bason
Basone
Basora
Basore
Basque
Basques
Basquez
Bass
Bassage
Bassali
Bassani
Bassano
Basse
Bassel
Basset
Bassett
Bassette
Bassetti
Bassford
Bassham
Bassi
Bassil
Bassin
Bassiti
Bassler
Basso
Bassolino
Bassuk
Bast
Basta
Bastain
Bastarache
Bastardi
Bastedo
Basten
Baster
Bastian
Bastianelli
Bastic
Bastick
Bastida
Bastidas
Bastidos
Bastien
Bastilla
Bastille
Bastin
Bastine
Baston
Bastone
Bastos
Bastow
Bastress
Bastura
Basu
Basua
Basulto
Basurto
Baswell
Basye
Batala
Batalla
Batalona
Batara
Batarse
Batas
Batch
Batchelder
Batcheller
Batchellor
Batchelor
Batcher
Batdorf
Bate
Batel
Bateman
Bater
Baters
Bates
Batesole
Bateson
Batey
Bath
Bathe
Bathke
Bathrick
Bathurst
Batie
Batimon
Batis
Batista
Batiste
Batistich
Batiz
Batkin
Batko
Batley
Batliner
Batlis
Batlle
Batman
Baton
Bator
Batra
Batres
Batrez
Batrich
Batrum
Batson
Batt
Batta
Battaglia
Battaglini
Battaglino
Battani
Batte
Battee
Batteen
Batteiger
Batten
Battenfield
Battenhouse
Batter
Batterman
Batters
Battersby
Battershell
Batterson
Batterton
Battey
Battiata
Battiato
Battie
Battiest
Battig
Battin
Battino
Battis
Battista
Battiste
Battisti
Battistini
Battisto
Battistone
Battistoni
Battko
Battle
Battles
Batto
Batton
Batts
Battson
Battuello
Batty
Batun
Baty
Batz
Batzer
Batzli
Batzri
Bau
Baublitz
Bauce
Bauch
Baucher
Bauchspies
Baucom
Baucum
Bauder
Baudino
Baudler
Baudoin
Baudry
Bauer
Bauerkemper
Bauerle
Bauerlein
Bauermeister
Bauernfeind
Bauers
Baugatz
Baugess
Baugh
Baugham
Baughan
Baugher
Baughey
Baughman
Baughn
Bauguess
Baugus
Bauknecht
Bauknight
Baul
Baulch
Bault
Baum
Bauman
Baumann
Baumbach
Baumberger
Baumbusch
Baumeister
Baumer
Baumert
Baumfalk
Baumgard
Baumgardner
Baumgardt
Baumgarn
Baumgarner
Baumgart
Baumgartel
Baumgarten
Baumgarter
Baumgartner
Baumhoer
Baumiester
Baumkirchner
Baumler
Baumli
Baumohl
Baun
Baune
Baunleuang
Baur
Baurer
Baures
Baus
Bausch
Bauserman
Bauske
Bausley
Bausman
Bauswell
Bautch
Baute
Bautista
Bautiste
Bautz
Bauza
Bava
Bavard
Bavaro
Bavelas
Baver
Baves
Bavier
Bavzee
Bawa
Bawany
Bawcombe
Bawcum
Bawden
Bawek
Bawer
Bawks
Bawner
Bax
Baxa
Baxendale
Baxi
Baxley
Baxter
Baxtor
Bay
Bayala
Bayani
Bayard
Bayardo
Bayas
Baydal
Bayer
Bayerl
Bayers
Bayes
Bayete
Baygents
Bayhonan
Bayird
Bayle
Bayles
Bayless
Bayley
Bayliff
Baylis
Bayliss
Baylock
Baylon
Baylor
Bayly
Bayman
Baymon
Bayn
Baynard
Bayne
Baynes
Baynham
Bayon
Bayona
Bayot
Bayouth
Bays
Baysden
Baysinger
Baysmore
Bayt
Bayton
Baytos
Bayuk
Bayus
Baza
Bazaldua
Bazan
Bazar
Bazarte
Bazata
Baze
Bazel
Bazelais
Bazemore
Bazer
Bazil
Bazile
Bazin
Bazinet
Bazner
Bazydlo
Bazylewicz
Bazzanella
Bazzano
Bazzel
Bazzell
Bazzi
Bazzle
Be
Bea
Beaber
Beabout
Beach
Beacham
Beachamp
Beachel
Beachell
Beachem
Beacher
Beachler
Beachman
Beachum
Beachy
Beacom
Beadell
Beadle
Beadles
Beadling
Beadnell
Beady
Beagan
Beagle
Beagley
Beahan
Beahm
Beahn
Beaird
Beakley
Beal
Beale
Bealer
Beales
Beall
Bealle
Bealmear
Beals
Beam
Beaman
Beamer
Beames
Beamesderfer
Beamish
Beamon
Beams
Bean
Beanblossom
Beandoin
Beane
Beaner
Beans
Bear
Bearce
Beard
Beardall
Bearded
Bearden
Beardmore
Beardon
Beards
Beardslee
Beardsley
Beare
Bearfield
Bearman
Bears
Bearse
Bearup
Beary
Beas
Beasley
Beasly
Beasmore
Beason
Beaston
Beat
Beath
Beathe
Beatie
Beatley
Beato
Beaton
Beatrice
Beatson
Beattie
Beattle
Beatty
Beaty
Beau
Beaubien
Beaubrun
Beaucage
Beauchaine
Beauchamp
Beauchemin
Beauchesne
Beaudet
Beaudette
Beaudin
Beaudine
Beaudion
Beaudoin
Beaudreau
Beaudreault
Beaudrie
Beaudry
Beaufait
Beauford
Beaufort
Beaugard
Beauharnois
Beaulac
Beaule
Beaulieu
Beauliev
Beauman
Beaumier
Beaumont
Beaumonte
Beauparlant
Beaupre
Beauprez
Beauregard
Beaureguard
Beaushaw
Beausoleil
Beauvais
Beaven
Beaver
Beavers
Beavin
Beavis
Beaz
Beazer
Beazley
Bebber
Bebeau
Bebee
Beberwyk
Bebo
Bebout
Beccaria
Beccue
Becena
Becenti
Becera
Becerra
Becerril
Bech
Bechard
Bechel
Becher
Becherer
Bechler
Bechman
Becht
Bechtel
Bechthold
Bechtol
Bechtold
Beck
Becka
Becke
Beckel
Beckelheimer
Beckelhimer
Beckem
Beckenbach
Beckendorf
Becker
Beckerdite
Beckerle
Beckerman
Beckers
Beckert
Beckes
Becket
Beckett
Beckey
Beckfield
Beckford
Beckham
Beckim
Beckius
Beckler
Beckles
Beckley
Becklin
Becklund
Beckman
Beckmann
Beckmeyer
Becknell
Beckner
Beckom
Beckor
Becks
Beckstead
Beckstrand
Beckstrom
Beckton
Beckum
Beckwith
Beckworth
Becky
Becnel
Becraft
Becton
Becvar
Becwar
Becze
Bedar
Bedard
Bedatsky
Bedaw
Beddard
Beddia
Beddingfield
Beddo
Beddoe
Beddome
Beddow
Beddows
Bede
Bedeau
Bedee
Bedeker
Bedell
Bedenbaugh
Bedenfield
Beder
Bedford
Bedgood
Bedient
Bedillion
Bedingfield
Bedker
Bedlion
Bednar
Bednarczyk
Bednarek
Bednarik
Bednarowicz
Bednarski
Bednarz
Bedner
Bedney
Bednorz
Bedocs
Bedoka
Bedolla
Bedonie
Bedor
Bedore
Bedoya
Bedre
Bedrosian
Bedsaul
Bedsole
Bedson
Bedward
Bedwell
Bee
Beebe
Beebee
Beebout
Beech
Beecham
Beecher
Beeching
Beechler
Beechner
Beechum
Beeck
Beecken
Beeckman
Beecroft
Beed
Beede
Beedham
Beedle
Beedles
Beedoo
Beedy
Beeghly
Beegle
Beehler
Beek
Beeker
Beekman
Beeks
Beel
Beelar
Beelby
Beeler
Beem
Beeman
Beemer
Beemon
Been
Beene
Beenel
Beer
Beerbohm
Beere
Beerer
Beerle
Beerling
Beerly
Beerman
Beermann
Beermudez
Beers
Beery
Bees
Beese
Beesley
Beesmer
Beeson
Beetley
Beets
Beetz
Beevers
Beezley
Befort
Befus
Bega
Began
Begay
Begaye
Begeal
Begeman
Begen
Beger
Begg
Beggs
Beghtol
Begin
Begley
Begnaud
Begnoche
Begolli
Begonia
Begor
Beguelin
Beguhl
Begum
Begun
Behal
Behan
Behanan
Behanna
Behar
Behel
Behen
Beherns
Behimer
Behizadeh
Behl
Behlen
Behler
Behling
Behlke
Behlmer
Behm
Behme
Behmer
Behn
Behne
Behner
Behney
Behning
Behnke
Behnken
Behr
Behran
Behrend
Behrends
Behrendt
Behrens
Behrenwald
Behring
Behringer
Behrle
Behrman
Behrmann
Behrns
Behun
Behunin
Behymer
Beichner
Beidleman
Beidler
Beien
Beier
Beierle
Beierschmitt
Beigert
Beighley
Beightol
Beik
Beil
Beile
Beiler
Beiley
Beilfuss
Beilinson
Beilke
Beilman
Beilstein
Bein
Beine
Beinlich
Beiriger
Beirise
Beirne
Beisch
Beisel
Beiser
Beish
Beisner
Beissel
Beisser
Beiswanger
Beiswenger
Beitel
Beiter
Beith
Beitler
Beitz
Beitzel
Beja
Bejar
Bejaran
Bejarano
Bejcek
Bejerano
Bejger
Bejil
Bejjani
Bek
Bekele
Beker
Bekerman
Bekhit
Bekins
Bekis
Bekius
Bekker
Bel
Bela
Belair
Belak
Belancer
Beland
Belanger
Belangia
Belanich
Belarde
Belardo
Belarmino
Belasco
Belay
Belback
Belcastro
Belch
Belcher
Belchior
Belcourt
Belden
Beldin
Belding
Beldon
Belen
Belew
Beley
Belezos
Belfanti
Belfast
Belfi
Belfield
Belfiglio
Belfiore
Belflower
Belford
Belfort
Belfy
Belgard
Belgarde
Belgrade
Belgrave
Belhumeur
Beliard
Belich
Belidor
Belieu
Belile
Beliles
Belin
Belina
Belinski
Belinsky
Belisle
Belitz
Beliveau
Beliz
Belizaire
Beljan
Belk
Belka
Belke
Belken
Belkin
Belknap
Belko
Belkowski
Bell
Bella
Bellace
Bellafiore
Bellah
Bellair
Bellaire
Bellamy
Bellanca
Belland
Bellanger
Bellantone
Bellantoni
Bellantuono
Bellany
Bellar
Bellard
Bellas
Bellavance
Bellavia
Bellazer
Belle
Belleau
Bellefeuille
Bellefleur
Bellefontaine
Bellehumeur
Bellemare
Bellemy
Bellen
Bellendir
Beller
Bellerdine
Bellerose
Belles
Bellessa
Bellettiere
Belletto
Belleville
Bellew
Bellfleur
Bellflower
Bellflowers
Bellhouse
Belli
Belliard
Bellido
Bellin
Bellina
Bellinder
Belling
Bellinger
Bellingham
Bellinghausen
Bellingtier
Bellini
Bellino
Bellion
Bellipanni
Bellis
Bellisario
Bellish
Bellisle
Belliston
Bellitti
Belliveau
Bellizzi
Bellman
Bellmay
Bellmore
Bello
Bellocchio
Belloma
Bellomo
Bellomy
Bellon
Bellone
Belloso
Bellott
Bellotti
Bellow
Bellows
Bellrichard
Bells
Bellucci
Bellue
Belluomini
Bellus
Bellusci
Belluz
Bellville
Belman
Belmarez
Belmont
Belmonte
Belmore
Belnap
Belnas
Beloate
Beloff
Belon
Belone
Belonger
Belongia
Belongie
Belony
Belote
Belotti
Belous
Belousson
Belovs
Below
Belrose
Belscher
Belschner
Belser
Belsey
Belshaw
Belsheim
Belsito
Belski
Belsky
Belson
Belstad
Belt
Belter
Belton
Beltrain
Beltram
Beltrame
Beltrami
Beltramo
Beltran
Beltre
Beltron
Belts
Beltz
Belue
Belveal
Belvees
Belville
Belvin
Belvins
Belwood
Belyea
Belyoussian
Belz
Belzer
Belzung
Beman
Bemben
Bemberry
Bembi
Bemboom
Bembry
Bembury
Bement
Bemer
Bemiller
Bemis
Bemiss
Bemo
Bemrich
Bemrose
Ben
Bena
Benabides
Benac
Benach
Benack
Benadom
Benafield
Benage
Benak
Benallie
Benally
Benamati
Benanti
Benard
Benari
Benasher
Benassi
Benauides
Benavente
Benavides
Benavidez
Benbenek
Benberry
Benbow
Benbrook
Bence
Bench
Benchoff
Bencivenga
Benck
Benckendorf
Bencomo
Bencosme
Bend
Benda
Bendall
Bendana
Bendas
Bendavid
Bendel
Bendele
Bendell
Bender
Benderman
Benders
Bendetti
Bendick
Bendickson
Bendig
Bending
Bendis
Bendit
Bendix
Bendixen
Bendlage
Bendle
Bendler
Bendolph
Bendorf
Bendt
Bendtsen
Bendu
Bendure
Bendy
Bendzans
Bendzus
Bene
Benear
Benecke
Benedek
Benedetti
Benedetto
Benedick
Benedict
Benedicto
Benedith
Benedix
Beneduce
Benedum
Benefiel
Benefield
Benejan
Benek
Beneke
Beneker
Benell
Benenati
Benes
Benesch
Benesh
Benestad
Benet
Benett
Beneuento
Benevento
Benevides
Beneze
Benezra
Benfer
Benfield
Benford
Benge
Bengel
Bengelsdorf
Bengochia
Bengston
Bengtson
Benhaim
Benham
Benigni
Benigno
Benik
Benike
Benimadho
Beninati
Beninato
Benincasa
Benincase
Bening
Benintendi
Benion
Beniquez
Benischek
Benisek
Benish
Benites
Benitez
Benito
Benitone
Benitz
Benjamen
Benjamin
Benjamine
Benje
Benke
Benken
Benker
Benkert
Benko
Benkosky
Benn
Bennafield
Bennage
Bennard
Benne
Bennefield
Benner
Bennerman
Bennerson
Bennes
Bennet
Benneth
Bennett
Bennette
Bennetts
Benney
Bennice
Bennick
Bennie
Bennight
Bennin
Benning
Benninger
Benningfield
Bennings
Bennington
Bennink
Bennion
Bennis
Bennison
Benno
Benns
Benny
Beno
Benoff
Benoist
Benoit
Benoy
Bens
Bensberg
Bensch
Benscoter
Bense
Bensen
Benser
Benshoof
Bensing
Bensinger
Benskin
Bensley
Bensman
Benson
Benston
Bent
Bentancourt
Bente
Bentele
Benthall
Bentham
Benthin
Benthusen
Bentivegna
Bentle
Bentler
Bentley
Bently
Bento
Benton
Bentrem
Bentrup
Bentsen
Bentson
Benty
Bentz
Bentzen
Bentzinger
Benulis
Benusa
Benvenuti
Benvenuto
Benwarc
Benward
Benware
Benway
Benwell
Benya
Benyamin
Benyard
Benyo
Benz
Benzango
Benzee
Benzel
Benzer
Benzi
Benzie
Benziger
Benzing
Benzinger
Benzschawel
Beougher
Beppu
Bequette
Bequillard
Bera
Beran
Beranek
Berard
Berardi
Berardinelli
Berardino
Berardo
Beras
Beraun
Berber
Berbereia
Berberian
Berberich
Berbes
Berbig
Bercegeay
Berceir
Berch
Bercher
Berchielli
Bercier
Berczel
Berczy
Berdahl
Berdan
Berdar
Berdecia
Berdes
Berdin
Berdine
Berdugo
Berdux
Berdy
Bereda
Beren
Berenbaum
Berends
Berendt
Berendzen
Berenger
Berenguer
Berens
Berenschot
Berenson
Berent
Berentson
Berentz
Beres
Beresford
Beresik
Beresky
Beresnyak
Berey
Berez
Bereznak
Berezny
Berfield
Berg
Berga
Bergami
Bergamine
Bergamini
Bergamo
Bergan
Bergant
Bergantzel
Berganza
Bergara
Bergdoll
Bergdorf
Berge
Bergeaux
Bergem
Bergeman
Bergemann
Bergen
Bergene
Bergener
Bergenstock
Bergenty
Berger
Bergeron
Bergerson
Bergert
Berges
Bergesen
Bergeson
Berget
Bergevin
Bergey
Bergfalk
Bergfeld
Bergfield
Berggren
Bergh
Bergholm
Bergholz
Bergin
Bergland
Berglund
Bergman
Bergmann
Bergmark
Bergmeier
Bergmeyer
Bergner
Bergo
Bergold
Bergouignan
Bergquist
Bergreen
Bergren
Bergseng
Bergsjo
Bergsma
Bergsman
Bergstedt
Bergsten
Bergstresser
Bergstrom
Bergum
Berhalter
Berhe
Berhow
Bering
Beringer
Berisford
Berish
Berisha
Berishaj
Berk
Berka
Berkbigler
Berke
Berkebile
Berkeley
Berken
Berkenbile
Berkery
Berkey
Berkhalter
Berkheimer
Berkhimer
Berkich
Berkley
Berkman
Berkoff
Berkovich
Berkovitch
Berkovitz
Berkowitz
Berks
Berkshire
Berkson
Berkstresser
Berky
Berl
Berlacher
Berland
Berlandy
Berlanga
Berley
Berliew
Berlin
Berliner
Berling
Berlinger
Berlingeri
Berlinghof
Berlingo
Berlinski
Berlo
Berlove
Berman
Bermea
Bermejo
Bermel
Bermeo
Bermers
Bermingham
Bermudes
Bermudez
Bern
Berna
Bernabe
Bernabei
Bernabo
Bernacchi
Bernacki
Bernadette
Bernal
Bernand
Bernard
Bernardez
Bernardi
Bernardin
Bernardini
Bernardino
Bernardo
Bernardon
Bernardoni
Bernarducci
Bernardy
Bernas
Bernasconi
Bernat
Bernatchez
Bernath
Bernatowicz
Bernau
Bernaudo
Bernbeck
Bernd
Berndsen
Berndt
Berne
Bernecker
Bernell
Berner
Berneri
Bernes
Bernet
Bernett
Berney
Bernhagen
Bernhard
Bernhardt
Bernhart
Bernheim
Berni
Berniard
Bernice
Bernick
Bernier
Bernieri
Berning
Berninger
Bernitsky
Bernmen
Berno
Bernon
Bernos
Bernoski
Bernosky
Bernot
Bernotas
Berns
Bernsen
Bernskoetter
Bernson
Bernstein
Bernstock
Bernstrom
Bernt
Berntsen
Berntson
Bernucho
Bero
Berquist
Berra
Berray
Berrell
Berret
Berreth
Berrett
Berretta
Berretti
Berrey
Berri
Berrian
Berridge
Berrie
Berrien
Berrier
Berrigan
Berringer
Berrio
Berrios
Berroa
Berrocal
Berrones
Berrong
Berrospe
Berry
Berryhill
Berryman
Bers
Bersamin
Bersaw
Bersch
Berschauer
Bershadsky
Berson
Berstein
Berstler
Bert
Berta
Bertagna
Bertagnoli
Bertagnolli
Bertaina
Bertalan
Bertao
Bertch
Berte
Berteau
Bertel
Bertella
Bertelle
Bertels
Bertelsen
Bertelson
Berteotti
Berth
Bertha
Berthelette
Berthelot
Berthelsen
Berther
Berthiaume
Berthold
Bertholf
Berti
Bertie
Bertin
Bertinetti
Bertini
Bertino
Bertke
Bertley
Bertling
Bertman
Berto
Bertog
Bertolami
Bertolasio
Bertoldo
Bertoli
Bertolini
Bertolino
Berton
Bertoncini
Bertone
Bertoni
Bertorelli
Bertot
Bertotti
Bertovich
Bertozzi
Bertram
Bertran
Bertrand
Bertrano
Bertrum
Bertsch
Bertsche
Bertschy
Bertucci
Bertus
Bertuzzi
Berube
Berulie
Berum
Berumen
Berver
Bervig
Berwald
Berwick
Bery
Berzas
Berzins
Berzunza
Besa
Besancon
Besanson
Besant
Besares
Besarra
Besaw
Besch
Beschorner
Besco
Beseau
Besecker
Beseke
Besemer
Besen
Besendorfer
Beser
Beserra
Beshara
Beshaw
Beshear
Beshears
Beshero
Besherse
Beshore
Besio
Beska
Beske
Beskom
Besler
Besley
Besner
Besong
Bess
Bessard
Besse
Bessel
Bessellieu
Bessemer
Bessent
Besser
Bessette
Bessey
Bessick
Bessinger
Bessire
Bessix
Bessler
Bessmer
Besso
Besson
Bessone
Best
Beste
Bester
Bestine
Beston
Bestwick
Beswick
Betacourt
Betak
Betance
Betances
Betancourt
Betancourth
Betancur
Betcher
Betenbaugh
Betenson
Betesh
Beteta
Beth
Betha
Bethany
Bethard
Bethay
Bethea
Bethel
Bethell
Bethers
Bethey
Bethke
Bethley
Bethoney
Bethune
Bethurem
Bethurum
Betit
Betita
Betker
Beto
Betran
Betry
Betsch
Betschart
Betschman
Betsill
Betsinger
Betson
Bettcher
Bettencourt
Bettendorf
Bettenhausen
Better
Betteridge
Betterley
Betterman
Betters
Betterton
Bettes
Betthauser
Betti
Betties
Bettin
Bettinger
Bettini
Bettino
Bettinson
Bettis
Bettle
Bettley
Bettman
Bettner
Betton
Bettridge
Betts
Betty
Betz
Betzel
Betzen
Betzer
Betzig
Betzler
Betzner
Betzold
Beu
Beuchat
Beuchler
Beucke
Beucler
Beuerle
Beukelman
Beukema
Beul
Beulah
Beumer
Beurskens
Beus
Beuse
Beute
Beutel
Beuter
Beuth
Beuther
Beuthin
Beutler
Beutnagel
Beuttel
Bevacqua
Bevan
Bevans
Bevard
Bevel
Bevelacqua
Bevell
Bevelle
Bevels
Bevens
Bever
Beverage
Beveridge
Beverley
Beverlin
Beverly
Bevers
Bevevino
Bevier
Bevil
Bevilacqua
Bevilaqua
Bevill
Beville
Bevington
Bevins
Bevis
Bevly
Bew
Bewick
Bewig
Bewley
Bex
Bey
Beyah
Beyal
Beyale
Beyda
Beydler
Beydoun
Beyea
Beyene
Beyer
Beyerl
Beyerlein
Beyers
Beyersdorf
Beyett
Beyke
Beyl
Beylotte
Beynon
Beyrer
Beyser
Beyt
Bez
Beza
Bezak
Bezanson
Bezdicek
Bezenek
Bezio
Bezner
Bezzo
Bhagat
Bhairo
Bhakta
Bhalla
Bhamaraniyama
Bhan
Bhandari
Bhardwaj
Bhaskar
Bhat
Bhatia
Bhatnagar
Bhatt
Bhattacharya
Bhatti
Bhayani
Bhola
Bhullar
Bi
Bia
Biafore
Biagas
Biagi
Biagini
Biagioni
Bialas
Bialaszewski
Bialczyk
Bialecki
Bialek
Bialik
Bialke
Bialy
Biamonte
Bianca
Biancaniello
Biancardi
Bianchi
Bianchin
Bianchini
Bianco
Biancuzzo
Biangone
Biard
Bias
Biase
Biasi
Biasotti
Biastock
Biava
Bibb
Bibber
Bibbins
Bibbs
Bibby
Bibeau
Bibee
Bibel
Biber
Bibian
Bibiano
Bibiloni
Bible
Bibler
Bibles
Bibo
Biby
Bica
Biccum
Bice
Bicek
Bichel
Bichler
Bichoff
Bichoupan
Bichrest
Bichsel
Bick
Bickart
Bickel
Bickelhaupt
Bickell
Bicker
Bickers
Bickerstaff
Bickerton
Bickes
Bicket
Bickett
Bickford
Bickham
Bicking
Bickle
Bicklein
Bickleman
Bickler
Bickley
Bickman
Bickmore
Bicknase
Bicknell
Bicknese
Bicksler
Biddick
Biddie
Bidding
Biddinger
Biddiscombe
Biddix
Biddle
Biddlecome
Biddleman
Biddulph
Biddy
Bideaux
Bidell
Biderman
Bidez
Bidgood
Bidlack
Bidle
Bidner
Bidon
Bidrowski
Bidstrup
Bidwell
Biebel
Bieber
Bieberle
Biedekapp
Biedenbender
Biederman
Biedermann
Biederwolf
Biedrzycki
Biegel
Biegler
Biehl
Biehle
Biehn
Bieker
Biel
Bielak
Bielat
Bielawski
Bielby
Biele
Bielec
Bielecki
Bielefeld
Bielefeldt
Bielefield
Bieler
Bielicki
Bielik
Bielinski
Bielke
Biello
Bielser
Bielski
Biemer
Bien
Bienek
Bienenstock
Biener
Bienfang
Bieniek
Bienkowski
Bienvenu
Bienvenue
Bier
Bierbaum
Bierbower
Bierbrauer
Bierce
Bierer
Bieri
Bierkortte
Bierl
Bierle
Bierlein
Bierley
Bierly
Bierman
Biermann
Biernacki
Biernat
Bierner
Bierod
Biersack
Bierschbach
Biersner
Bierstedt
Bierut
Bierwagen
Bierwirth
Biery
Bies
Bieschke
Biesecker
Biesenthal
Biesheuvel
Biesinger
Bietsch
Bievenue
Biever
Biewald
Biez
Biffar
Biffer
Biffle
Big
Bigalk
Bigas
Bigaud
Bigbee
Bigby
Bigda
Bigelow
Bigford
Bigg
Biggar
Biggard
Biggart
Bigger
Biggers
Biggerstaff
Biggins
Biggio
Biggs
Bigham
Bighorse
Bigio
Bigler
Bigley
Biglin
Biglow
Bignall
Bignell
Bigness
Bigney
Bigony
Bigos
Bigsby
Bigus
Bigusiak
Bigwood
Bihari
Bihl
Bihler
Bihm
Bijan
Bijou
Bila
Bilagody
Bilal
Bilansky
Bilazzo
Bilbao
Bilberry
Bilbo
Bilbrew
Bilbrey
Bilbro
Bilby
Bilchak
Bilcik
Bild
Bilden
Bilder
Bilderback
Bile
Bilecki
Bilek
Bilello
Biler
Biles
Biley
Bilger
Bilich
Bilinski
Bilis
Bilka
Bilkiss
Bill
Billa
Billafuerte
Billard
Bille
Billeaudeau
Billeck
Billegas
Billen
Biller
Billerbeck
Billesbach
Billet
Billeter
Billett
Billey
Billheimer
Billiar
Billick
Billie
Billiel
Billiet
Billig
Billigmeier
Billing
Billinger
Billingham
Billinghurst
Billings
Billingsby
Billingslea
Billingsley
Billingsly
Billington
Billinsley
Billiot
Billiott
Billips
Billiter
Billman
Billo
Billock
Billon
Billops
Billot
Billotte
Billotti
Billow
Bills
Billue
Billups
Billus
Billy
Bilodeau
Bilotta
Bilotti
Bilotto
Bilous
Bilsborough
Bilski
Bilson
Bilton
Biltz
Bilyeu
Bimler
Bina
Binam
Bindas
Bindel
Binder
Binderup
Bindrup
Bineau
Binegar
Bines
Binet
Binette
Binetti
Binford
Bing
Bingaman
Bingamon
Binger
Bingert
Binggeli
Bingham
Bingle
Bingler
Bingley
Bingman
Binienda
Bininger
Binion
Bink
Binker
Binkerd
Binkiewicz
Binkley
Binkowski
Binks
Binn
Binner
Binney
Binnicker
Binnie
Binning
Binns
Binsfeld
Binstock
Bintliff
Bintner
Bintz
Binz
Bio
Bionda
Biondi
Biondo
Biondolillo
Biorkman
Bippus
Bir
Birak
Birch
Birchall
Birchard
Bircher
Birchett
Birchfield
Birchler
Birchwood
Birckbichler
Birckett
Birckhead
Bird
Birden
Birdette
Birdin
Birdine
Birdinground
Birdo
Birdon
Birdow
Birdsall
Birdsell
Birdsey
Birdsong
Birdtail
Birdwell
Birely
Biren
Birenbaum
Bires
Birge
Biringer
Birk
Birkeland
Birkenhagen
Birkenhead
Birkenholz
Birkenmeier
Birkes
Birkett
Birkey
Birkhead
Birkhimer
Birkholz
Birkland
Birklid
Birkline
Birkmaier
Birkner
Birks
Birky
Birley
Birman
Birmingham
Birnbaum
Birnberg
Birnell
Birner
Birney
Birnie
Biro
Biron
Bironas
Biros
Birr
Birrell
Birrittella
Birrueta
Birsner
Birt
Birtcher
Birthwright
Birton
Birts
Birtwell
Bis
Bisaccia
Bisagna
Bisaillon
Bisanz
Bisard
Bisarra
Bisbee
Bisby
Biscahall
Biscardi
Biscari
Biscaro
Bisceglia
Bisch
Bischel
Bischke
Bischof
Bischoff
Biscocho
Biscoe
Bisconer
Bise
Bisel
Biser
Bisesi
Bisges
Bish
Bishard
Bishel
Bisher
Bishoff
Bishop
Bishopp
Bisi
Bisignano
Bisikirski
Bisio
Biskach
Bisker
Bisking
Biskup
Bisogno
Bisom
Bison
Bisonette
Bisono
Bispham
Bisping
Biss
Bissada
Bissegger
Bissel
Bissell
Bissen
Bisset
Bissett
Bissette
Bisso
Bissol
Bisson
Bissonette
Bissonnette
Bister
Bistline
Bistodeau
Bitah
Bitar
Bitetto
Bitler
Bitner
Bitonti
Bitsko
Bitsui
Bitsuie
Bittel
Bittenbender
Bitter
Bitterman
Bitters
Bittick
Bitting
Bittinger
Bittle
Bittman
Bittner
Bitto
Bitton
Bitz
Bitzel
Bitzenhofer
Bitzer
Bivans
Biven
Bivens
Biviano
Bivin
Bivings
Bivins
Bivona
Bixby
Bixel
Bixler
Bizarro
Bizcassa
Bizier
Bizub
Bizzard
Bizzaro
Bizzell
Bizzle
Bjella
Bjelland
Bjerk
Bjerke
Bjerken
Bjerknes
Bjorgen
Bjork
Bjorklund
Bjorkman
Bjorkquist
Bjorlin
Bjorn
Bjornberg
Bjornson
Bjornstad
Bjornstrom
Bjorseth
Blach
Blache
Blacher
Blachly
Blachowski
Blacio
Black
Blackaby
Blackard
Blackbird
Blackbum
Blackburn
Blacker
Blackerby
Blacketer
Blackett
Blackford
Blackgoat
Blackham
Blackhurst
Blackie
Blackington
Blackledge
Blackler
Blackley
Blacklock
Blackman
Blackmar
Blackmer
Blackmon
Blackmond
Blackmoore
Blackmore
Blacknall
Blackner
Blackshear
Blacksher
Blackshire
Blacksmith
Blackson
Blackstad
Blackstar
Blackstock
Blackston
Blackstone
Blackwall
Blackwater
Blackwelder
Blackwell
Blackwood
Blacock
Blad
Blada
Blade
Bladen
Blades
Bladt
Blady
Blaese
Blaeser
Blafield
Blagg
Blagman
Blaha
Blahnik
Blaho
Blaich
Blaida
Blailock
Blain
Blaine
Blair
Blaire
Blais
Blaisdell
Blaise
Blaize
Blake
Blakeborough
Blakeley
Blakelock
Blakely
Blakeman
Blakemore
Blakeney
Blakenship
Blaker
Blakes
Blakeslee
Blakesley
Blakeway
Blakey
Blakley
Blakney
Blakstad
Blalack
Blalock
Blamer
Blan
Blanc
Blanca
Blancarte
Blancas
Blancato
Blancett
Blanch
Blanchard
Blanche
Blanchet
Blanchett
Blanchette
Blanchfield
Blanck
Blanco
Bland
Blanda
Blander
Blandford
Blandin
Blanding
Blandino
Blando
Blandon
Blandy
Blane
Blaney
Blanford
Blanga
Blank
Blanke
Blanken
Blankenbaker
Blankenbeckle
Blankenbecler
Blankenberg
Blankenburg
Blankenship
Blankinship
Blankley
Blanko
Blanks
Blankschan
Blankship
Blankumsee
Blann
Blannon
Blanquart
Blanquet
Blanscet
Blansett
Blanton
Blanzy
Blare
Blas
Blaschke
Blasco
Blase
Blasen
Blasengame
Blasenhauer
Blaser
Blasetti
Blash
Blashak
Blasi
Blasing
Blasingame
Blasingim
Blasini
Blasius
Blaske
Blaski
Blasko
Blaskovich
Blasl
Blass
Blassingame
Blasz
Blaszak
Blaszczyk
Blatchford
Blatchley
Blatherwick
Blatnick
Blatnik
Blatt
Blatteau
Blattel
Blatter
Blatti
Blattler
Blattner
Blatz
Blau
Blauch
Blaum
Blauman
Blauser
Blausey
Blaustein
Blauvelt
Blauw
Blaxland
Blay
Blaydes
Blaydon
Blaylock
Blayney
Blaze
Blazejewski
Blazek
Blazer
Blazich
Blazier
Blazina
Blazing
Blazon
Blazosky
Blea
Bleacher
Bleak
Bleakley
Bleakney
Bleasdale
Bleattler
Bleau
Bleazard
Blecha
Blechinger
Blechman
Bleck
Blecker
Bledsaw
Bledsoe
Blee
Bleeck
Bleecker
Bleeker
Blegen
Bleggi
Blehm
Bleich
Bleicher
Bleichner
Bleier
Bleifus
Bleile
Bleiler
Bleimehl
Bleininger
Bleiweiss
Blem
Blemel
Blend
Blenden
Blender
Blenker
Blenman
Blenner
Bleser
Blesh
Blesofsky
Bless
Blessett
Blessing
Blessinger
Blessman
Blethen
Blette
Blevans
Blevens
Blevins
Blew
Blewett
Blewitt
Blews
Bley
Bleyer
Bleyl
Bleything
Blice
Blick
Blickem
Blickenstaff
Blicker
Blide
Bliek
Blier
Bliese
Bligen
Blight
Blihovde
Bliler
Blimka
Blincoe
Blind
Blindt
Bline
Blinebry
Blinka
Blinks
Blinn
Blinston
Blint
Blish
Bliske
Bliss
Blisset
Blissett
Blitch
Blitz
Bliven
Blixt
Blizard
Blizzard
Bloch
Blochberger
Blocher
Block
Blocker
Blockett
Blocklinger
Blockmon
Bloczynski
Blodgett
Bloebaum
Bloedel
Bloem
Bloemer
Bloemker
Bloes
Bloeser
Blogg
Blohm
Blois
Bloise
Blok
Blom
Blomberg
Blomdahl
Blome
Blomgren
Blomker
Blomme
Blommel
Blommer
Blomquist
Blomstrand
Blomstrom
Blondeau
Blondell
Blonder
Blondin
Blong
Blonigan
Blonsky
Blood
Bloodgood
Bloodough
Bloodsaw
Bloodsworth
Bloodworth
Bloom
Bloomberg
Bloome
Bloomer
Bloomfield
Bloomgren
Bloomingdale
Bloomquist
Bloomsburg
Bloomstrand
Bloomstrom
Bloor
Blore
Bloschichak
Blose
Blosfield
Bloss
Blosser
Blossom
Blossomgame
Blotsky
Blott
Blotter
Blough
Blouin
Blouir
Blount
Blovin
Blow
Blowe
Blower
Blowers
Bloxham
Bloxom
Bloxsom
Bloyd
Bloye
Bloyer
Blubaugh
Bludworth
Blue
Bluel
Bluemel
Bluestein
Bluett
Bluford
Bluhm
Bluitt
Blum
Bluma
Blumberg
Blume
Blumenberg
Blumenfeld
Blumenkrantz
Blumenkranz
Blumenschein
Blumenstein
Blumenstock
Blumenthal
Blumer
Blumhardt
Bluming
Blumkin
Blumstein
Blundell
Blunden
Blundo
Blunk
Blunkall
Blunt
Blurton
Blush
Blust
Blute
Bluth
Bluto
Bly
Blyden
Blye
Blyler
Blystone
Blyth
Blythe
Blyther
Blyze
Blyzes
Bo
Boadway
Boady
Boahn
Boak
Boakye
Boal
Boaldin
Boals
Boamah
Boan
Boane
Board
Boardley
Boardman
Boards
Boardway
Boardwine
Boarman
Boarts
Boas
Boast
Boateng
Boatfield
Boatman
Boatner
Boatright
Boatwright
Boaz
Bob
Boback
Bobadilla
Bobak
Bobb
Bobbett
Bobbit
Bobbitt
Bobbs
Bobby
Bobe
Bobeck
Bobek
Boben
Bober
Boberg
Bobet
Bobian
Bobic
Bobier
Bobino
Bobko
Boblak
Boblett
Boblitt
Bobo
Bobola
Bobowiec
Bobrosky
Bobrow
Bobrowski
Bobseine
Bobsin
Bobson
Bobst
Bobzien
Bocage
Bocanegra
Boccanfuso
Boccard
Boccella
Bocchi
Bocchicchio
Bocchieri
Bocchini
Bocchino
Bocci
Boccia
Boccio
Bocek
Boch
Bochat
Boche
Bochek
Bochenek
Bochenski
Boches
Bochicchio
Bochner
Bock
Bockelman
Bockelmann
Bockemehl
Bockenkamp
Bockenstedt
Bocker
Bockhorn
Bockhorst
Bocklage
Bocklund
Bockman
Bockoven
Bockover
Bockrath
Bockskopf
Boclair
Bocock
Bocook
Bocskor
Boczar
Boda
Bodah
Bodak
Bodamer
Bodary
Boday
Bodda
Boddeker
Bodden
Boddie
Boddorf
Boddy
Bode
Bodell
Bodelson
Bodemann
Boden
Bodenhagen
Bodenhamer
Bodenheimer
Bodenschatz
Bodenstein
Bodensteiner
Boderick
Bodey
Bodfish
Bodford
Bodi
Bodie
Bodiford
Bodily
Bodin
Bodine
Bodiroga
Bodison
Bodkin
Bodkins
Bodle
Bodley
Bodman
Bodnar
Bodner
Bodo
Bodon
Bodor
Bodovsky
Bodreau
Bodrey
Bodrick
Bodway
Bodwell
Bodwin
Body
Bodyfelt
Bodziony
Boe
Boebinger
Boeck
Boecker
Boeckmann
Boeckx
Boedecker
Boedeker
Boeding
Boege
Boegel
Boeger
Boeh
Boehl
Boehlar
Boehle
Boehler
Boehlke
Boehm
Boehman
Boehme
Boehmer
Boehmke
Boehne
Boehner
Boehning
Boehnke
Boehnlein
Boehringer
Boeke
Boekelman
Boeken
Boekhout
Boele
Boelk
Boelke
Boelsche
Boelter
Boemer
Boemig
Boen
Boender
Boeneke
Boenig
Boening
Boenisch
Boensch
Boepple
Boer
Boera
Boerboom
Boerger
Boeri
Boerm
Boerma
Boerner
Boero
Boers
Boersma
Boerst
Boerstler
Boes
Boesch
Boese
Boesel
Boesen
Boesenberg
Boesenhofer
Boeser
Boeshore
Boesiger
Boeson
Boespflug
Boetcher
Boettcher
Boettger
Boettner
Boeve
Boever
Boevers
Boeving
Boey
Boffa
Bofinger
Boga
Bogacki
Bogacz
Bogaert
Bogan
Bogany
Bogar
Bogard
Bogardus
Bogart
Bogatay
Bogatitus
Bogda
Bogdan
Bogdanovich
Bogdanski
Bogden
Bogdon
Boge
Bogel
Bogema
Bogen
Bogenschneide
Bogenschutz
Boger
Bogert
Bogg
Boggan
Boggess
Boggi
Boggiano
Boggio
Boggioni
Boggs
Bogguess
Boggus
Bogh
Boghosian
Boghossian
Bogie
Bogin
Bogle
Boglioli
Bognar
Bogner
Bognuda
Bogosh
Bogren
Bogucki
Bogue
Bogumil
Bogus
Bogust
Bogut
Bohac
Bohall
Boham
Bohan
Bohanan
Bohannan
Bohannon
Bohanon
Bohart
Bohaty
Bohinc
Bohl
Bohland
Bohlander
Bohlen
Bohler
Bohley
Bohlig
Bohling
Bohlinger
Bohlke
Bohlken
Bohlman
Bohlmann
Bohlsen
Bohm
Bohman
Bohmann
Bohmer
Bohmker
Bohn
Bohne
Bohnen
Bohnenblust
Bohnenkamp
Bohner
Bohnert
Bohnet
Bohney
Bohnker
Bohnsack
Boho
Bohol
Bohon
Bohonik
Bohorquez
Bohr
Bohren
Bohrer
Bohringer
Bohrman
Bohrn
Bohs
Boiani
Boice
Boid
Boie
Boies
Boike
Boilard
Boileau
Boiles
Boillot
Boin
Bois
Boisclair
Boise
Boisen
Boiser
Boisjolie
Boislard
Boisse
Boisseau
Boisselle
Boissoneault
Boissonnault
Boissonneault
Boissy
Boisuert
Boisvert
Boitel
Boitnott
Boivin
Bojanowski
Boje
Bojko
Bojorquez
Bok
Bokal
Bokanovich
Boken
Boker
Boklund
Bokman
Bokor
Bolado
Bolan
Boland
Bolander
Bolanos
Bolante
Bolar
Bolay
Bolch
Bold
Bolda
Bolde
Bolden
Boldenow
Bolder
Boldery
Boldin
Bolding
Boldizsar
Boldman
Boldon
Boldosser
Boldrin
Bolds
Boldt
Bolduan
Bolduc
Boldue
Boldul
Boldwyn
Bole
Bolebruch
Bolejack
Bolek
Bolen
Bolenbaugh
Bolender
Boler
Bolerjack
Boles
Bolevice
Boleware
Boley
Boleyn
Bolf
Bolfa
Bolger
Bolian
Bolich
Bolick
Boliek
Bolieu
Bolig
Bolin
Bolinder
Boline
Boling
Bolinger
Bolins
Bolinsky
Bolio
Bolitho
Bolivar
Boliver
Bolk
Bolka
Boll
Bolla
Bollacker
Bollaert
Bolland
Bollard
Bollbach
Bollen
Bollens
Boller
Bolles
Bollettino
Bollich
Bollie
Bollier
Bollig
Bolliger
Bollin
Bolling
Bollinger
Bollis
Bollman
Bollom
Bollozos
Bolls
Bolman
Bolner
Bolnick
Bologna
Bolognese
Bolognia
Bolon
Bolorin
Bolser
Bolstad
Bolster
Bolt
Bolte
Bolten
Bolter
Boltinghouse
Bolton
Boltz
Boluda
Bolus
Bolvin
Bolyard
Bolz
Boman
Bomar
Bomaster
Bomba
Bombaci
Bombard
Bombardier
Bomberger
Bombich
Bombino
Bomer
Bomgardner
Bomia
Bomilla
Bomkamp
Bommarito
Bommer
Bompane
Bompiani
Bomstad
Bomzer
Bon
Bona
Bonacci
Bonaccorsi
Bonaccorso
Bonadio
Bonadona
Bonadonna
Bonadurer
Bonaguidi
Bonagurio
Bonalumi
Bonam
Bonamico
Bonamo
Bonanni
Bonanno
Bonano
Bonapart
Bonaparte
Bonar
Bonardi
Bonas
Bonasera
Bonato
Bonatti
Bonaventura
Bonaventure
Bonavia
Bonavita
Bonawitz
Boncella
Bond
Bonda
Bondanza
Bonde
Bonder
Bondi
Bondoc
Bondre
Bondroff
Bonds
Bondura
Bondurant
Bondy
Bone
Bonebrake
Bonebright
Bonefield
Bonefont
Bonelli
Bonello
Bonenberger
Bonenfant
Bonepart
Boner
Bones
Boness
Bonesteel
Bonet
Boneta
Bonett
Bonetti
Bonetto
Boney
Bonfield
Bonfiglio
Bong
Bonga
Bongard
Bongartz
Bonge
Bongers
Bongiardina
Bongio
Bongiorno
Bongiovanni
Bongivengo
Bongle
Bongo
Bonham
Bonhomme
Boni
Boniello
Bonier
Boniface
Bonifacio
Bonifant
Bonifay
Bonifer
Bonifield
Bonilla
Bonillas
Bonillo
Bonin
Bonina
Bonine
Boning
Bonini
Bonino
Boniol
Bonita
Bonito
Bonjorno
Bonjour
Bonk
Bonker
Bonkowski
Bonn
Bonne
Bonneau
Bonnel
Bonnell
Bonnema
Bonnenfant
Bonner
Bonnes
Bonnet
Bonnett
Bonnette
Bonneville
Bonney
Bonnick
Bonnie
Bonnifield
Bonnin
Bonning
Bonniwell
Bonnlander
Bonno
Bonnoitt
Bonnot
Bonny
Bono
Bonomi
Bonomini
Bonomo
Bonow
Bonsal
Bonsall
Bonsee
Bonsell
Bonser
Bonsey
Bonsignore
Bonson
Bonsu
Bonte
Bontempo
Bontemps
Bonton
Bontrager
Bonucchi
Bonugli
Bonura
Bonus
Bonuz
Bonventre
Bonvillain
Bonwell
Bonyai
Bonzo
Boock
Boocks
Boocock
Boody
Booe
Booher
Book
Bookamer
Bookard
Bookbinder
Booker
Bookhardt
Bookhart
Bookman
Bookmiller
Bookout
Books
Bookter
Bookwalter
Boole
Boom
Boomer
Boomershine
Boomhower
Boon
Boone
Boonstra
Boop
Boor
Booras
Boord
Boore
Boorman
Boorom
Boos
Boosalis
Boose
Booser
Boot
Boote
Booten
Booth
Boothby
Boothe
Boothman
Boothroyd
Booton
Boots
Booty
Booze
Boozer
Bopp
Boppre
Boque
Boquet
Bora
Borah
Boran
Boratko
Borba
Borbon
Borbridge
Borchard
Borchardt
Borchelt
Borcher
Borcherding
Borchers
Borchert
Borcuk
Bord
Borda
Bordas
Borde
Bordeau
Bordeaux
Bordeleau
Bordelon
Borden
Bordenet
Bordenkircher
Border
Borders
Bordes
Bordges
Bordi
Bordin
Bordinger
Bordley
Bordner
Bordon
Bordonaro
Bordoy
Bordwell
Bordwine
Boreen
Borek
Borel
Boreland
Borell
Borella
Borelli
Borello
Boreman
Boren
Borenstein
Borer
Bores
Borey
Borg
Borgatti
Borge
Borgella
Borgelt
Borgen
Borger
Borgerding
Borgers
Borgert
Borges
Borgese
Borgeson
Borghese
Borghi
Borghoff
Borgia
Borglum
Borgman
Borgmann
Borgmeyer
Borgos
Borgstede
Borgstrom
Borguez
Boria
Borich
Boring
Borio
Boris
Borja
Borjas
Borjon
Bork
Borke
Borkenhagen
Borkholder
Borkin
Borkoski
Borkowski
Borla
Borlace
Borland
Borlin
Borling
Borman
Bormann
Bormes
Bormet
Bormuth
Born
Borne
Borneman
Bornemann
Borner
Bornhorst
Bornman
Bornmann
Borns
Bornstein
Borodec
Boroff
Borok
Borom
Boron
Boronat
Boros
Boroski
Boroughs
Borovec
Borovetz
Borowiak
Borowicz
Borowiec
Borowik
Borowski
Borozny
Borquez
Borr
Borra
Borras
Borrayo
Borre
Borreggine
Borrego
Borrell
Borrelli
Borrello
Borremans
Borrero
Borreta
Borriello
Borries
Borrigo
Borris
Borroel
Borrolli
Borromeo
Borror
Borroto
Borrow
Borruso
Bors
Borsa
Borsari
Borsellino
Borseth
Borsh
Borski
Borson
Borsos
Borst
Borstad
Borth
Borthwick
Bortignon
Bortle
Bortner
Borton
Bortz
Borucki
Boruff
Borum
Borunda
Borup
Boruvka
Borwig
Bory
Borycz
Borys
Borysewicz
Boryszewski
Borza
Borzea
Borzillo
Bos
Bosa
Bosack
Bosak
Bosarge
Boscarello
Boscarino
Bosch
Bosche
Boschee
Boschert
Boschult
Boscia
Boscio
Bosco
Bose
Bosefski
Bosell
Boseman
Bosen
Boser
Bosh
Boshard
Boshart
Boshears
Bosheers
Boshell
Boshers
Boshes
Boshnack
Bosio
Bosket
Bosko
Bosler
Boslet
Bosley
Bosma
Bosman
Boso
Bosold
Bosowski
Bosque
Bosques
Bosquet
Bosquez
Boss
Bossard
Bossardet
Bossart
Bosse
Bossen
Bossenbroek
Bosserman
Bossert
Bossey
Bosshardt
Bosshart
Bossi
Bossick
Bossie
Bossier
Bossler
Bossley
Bosson
Bost
Bostain
Bostel
Bostelman
Bostelmann
Bosten
Boster
Bostian
Bostic
Bostick
Bostock
Boston
Bostow
Bostrom
Bostwick
Boswell
Boswink
Bosworth
Botcher
Botdorf
Boteilho
Boteler
Botelho
Botellio
Botello
Botero
Both
Botha
Bothe
Bothman
Bothner
Bothof
Bothwell
Botkin
Botkins
Botner
Botos
Botras
Botros
Botsford
Bott
Botta
Bottalico
Bottari
Bottaro
Bottcher
Bottella
Bottemiller
Botten
Bottenfield
Botterbusch
Bottex
Bottgenbach
Botti
Botticello
Bottiggi
Bottiglieri
Bottin
Botting
Bottini
Bottino
Botto
Bottolene
Bottolfson
Bottom
Bottomley
Bottomly
Bottoms
Botton
Bottone
Bottoni
Bottorf
Bottorff
Bottrell
Botts
Bottum
Botwin
Botwinick
Botz
Bou
Boucaud
Bouch
Bouchaert
Bouchard
Bouche
Boucher
Bouchey
Bouchie
Bouchillon
Bouck
Boucouvalas
Boudewyns
Boudin
Boudinot
Boudjouk
Boudle
Boudoin
Boudreau
Boudreaux
Boudrie
Boudrieau
Bouer
Bouffard
Boufford
Bouges
Bough
Boughamer
Boughan
Boughman
Boughn
Boughner
Boughter
Boughton
Bougie
Bouie
Bouillion
Bouillon
Bouknight
Boulais
Boulanger
Boulay
Boulch
Boulden
Bouldin
Boulding
Boulds
Boule
Bouler
Boulerice
Bouleris
Boulet
Boulette
Bouley
Boulger
Boulier
Bouliouris
Boullion
Boulos
Boulter
Boultinghouse
Boulton
Boulware
Bouma
Bouman
Boumthavee
Bound
Bounds
Boundy
Bounleut
Bounthapanya
Bouquet
Bouquin
Bour
Bouras
Bourassa
Bourbeau
Bourbois
Bourbon
Bourbonnais
Bourdage
Bourdages
Bourdeau
Bourdeaux
Bourdier
Bourdon
Bourek
Bouret
Bourff
Bourg
Bourgault
Bourgeault
Bourgeois
Bourget
Bourgoin
Bourgoine
Bourgois
Bourgon
Bourgoyne
Bourgue
Bourjolly
Bourke
Bourland
Bourlier
Bourn
Bournazian
Bourne
Bournes
Bourns
Bourque
Bourquin
Bourraine
Bourret
Boursaw
Boursiquot
Bouse
Boushie
Bouska
Bousley
Bousman
Bousquet
Bousqute
Bousson
Boustead
Bousum
Boutchyard
Boutelle
Bouten
Boutet
Bouthillette
Bouthot
Boutiette
Boutilier
Boutin
Bouton
Boutot
Boutros
Boutte
Boutwell
Bouvia
Bouvier
Bouwens
Bouwkamp
Bouwman
Bouy
Bouyea
Bouyer
Bouza
Bova
Bovain
Bovard
Bove
Bovee
Boveja
Bovell
Boven
Bovey
Bovia
Bovian
Bovie
Bovio
Bow
Bowan
Bowar
Boward
Bowcock
Bowcutt
Bowden
Bowdich
Bowdish
Bowditch
Bowdle
Bowdler
Bowdoin
Bowdon
Bowdre
Bowdry
Bowe
Bowell
Bowels
Bowen
Bowens
Bower
Bowering
Bowerize
Bowerman
Bowers
Bowersmith
Bowersock
Bowersox
Bowery
Bowes
Bowey
Bowgren
Bowhall
Bowie
Bowin
Bowker
Bowl
Bowlan
Bowland
Bowlby
Bowlds
Bowle
Bowlen
Bowler
Bowles
Bowlet
Bowley
Bowlick
Bowlin
Bowline
Bowling
Bowlus
Bowman
Bowmer
Bown
Bownds
Bowne
Bowren
Bowring
Bowron
Bowser
Bowsher
Bowthorpe
Bowyer
Box
Boxell
Boxer
Boxley
Boxton
Boxwell
Boxx
Boyack
Boyan
Boyance
Boyanton
Boyar
Boyarski
Boyarsky
Boyas
Boyce
Boyd
Boyda
Boyde
Boyden
Boydston
Boydstun
Boye
Boyea
Boyenga
Boyens
Boyer
Boyers
Boyes
Boyett
Boyette
Boyington
Boyken
Boykin
Boykins
Boyko
Boyl
Boylan
Boyland
Boyle
Boylen
Boyles
Boylston
Boyn
Boyne
Boynes
Boynton
Boys
Boysel
Boysen
Boyson
Boyster
Boyt
Boyte
Boyter
Boyton
Boyum
Boza
Bozak
Bozard
Bozarth
Boze
Bozek
Bozell
Bozelle
Bozeman
Bozenski
Bozic
Bozich
Bozinovich
Bozman
Bozovich
Bozwell
Bozych
Bozzell
Bozzi
Bozzo
Bozzone
Braam
Braasch
Braaten
Braatz
Braband
Brabant
Brabazon
Brabble
Brabec
Brabham
Braboy
Brabson
Brabston
Bracaloni
Bracamonte
Bracamontes
Braccia
Bracco
Brace
Bracero
Bracetty
Bracewell
Bracey
Brach
Bracher
Brachle
Brachman
Bracht
Brack
Brackbill
Brackeen
Brackelsberg
Brackemyre
Bracken
Brackenbury
Brackenridge
Brackens
Bracker
Bracket
Brackett
Brackey
Brackin
Brackins
Brackley
Bracklin
Brackman
Brackney
Bracks
Bracy
Brad
Bradac
Bradberry
Bradburn
Bradbury
Bradby
Bradd
Braddock
Braddy
Brade
Bradeen
Braden
Brader
Bradey
Bradfield
Bradford
Bradfute
Bradham
Bradica
Bradicich
Bradick
Bradigan
Brading
Bradish
Bradley
Bradly
Bradmon
Bradner
Bradney
Bradon
Bradrick
Bradshaw
Bradsher
Bradstreet
Bradt
Bradtke
Bradway
Bradwell
Brady
Braegelmann
Braff
Brafford
Brafman
Braga
Bragado
Bragan
Bragas
Bragdon
Brage
Brager
Braget
Bragg
Braggs
Brague
Brah
Braham
Brahler
Brahm
Brahney
Braig
Brailey
Brailford
Brailsford
Braim
Brain
Brainard
Brainerd
Brais
Braisted
Braithwaite
Braitman
Brak
Brake
Brakebill
Brakefield
Brakeman
Braker
Brakhage
Brakke
Brakstad
Braley
Bralley
Brallier
Braly
Bram
Bramall
Braman
Bramante
Bramasco
Brambila
Bramble
Bramblett
Brame
Bramel
Bramer
Bramhall
Bramham
Bramlet
Bramlett
Bramlette
Bramley
Bramlitt
Brammell
Brammer
Bramon
Bramsen
Bramson
Bramucci
Bramuchi
Bramwell
Bran
Brana
Branagan
Branam
Branaman
Branan
Branaugh
Branca
Brancaccio
Brancanto
Brancati
Brancato
Brancazio
Branch
Branchaud
Branche
Brancheau
Branciforte
Branck
Branco
Brand
Brandal
Brandau
Brandauer
Brande
Brandeis
Brandel
Brandeland
Branden
Brandenberg
Brandenberger
Brandenburg
Brandenburger
Brander
Brandes
Brandewie
Brandi
Brandis
Brandl
Brandle
Brandler
Brandley
Brandly
Brandman
Brandner
Brando
Brandolini
Brandolino
Brandom
Brandon
Brandorff
Brandow
Brands
Brandsrud
Brandstetter
Brandstrom
Brandt
Brandwein
Brandy
Branecki
Branen
Braner
Branes
Branford
Brang
Brangan
Brangers
Branham
Branhan
Braniff
Branigan
Branin
Branine
Brank
Branker
Brankovich
Brann
Brannam
Brannan
Brannen
Branner
Brannick
Brannigan
Brannin
Branning
Brannock
Brannon
Brannum
Brano
Branon
Branot
Branscom
Branscomb
Branscombe
Branscome
Branscum
Branseum
Bransfield
Bransford
Branske
Branski
Bransom
Branson
Branstad
Branstetter
Branstrom
Branstutter
Brant
Branter
Branting
Brantingham
Brantley
Brantly
Brantner
Branton
Brantz
Branum
Branyan
Branyon
Branz
Brar
Bras
Brasby
Brasch
Brase
Brasel
Braseth
Brasfield
Brash
Brashaw
Brashear
Brashears
Brasher
Brashers
Brashier
Brasier
Brasil
Brasington
Brasket
Braskett
Braskey
Brass
Brassard
Brasseaux
Brassell
Brasser
Brasseur
Brasseux
Brassfield
Brassil
Brasswell
Brasuell
Brasure
Braswell
Bratcher
Bratchett
Bratek
Brath
Brathwaite
Bratsch
Bratt
Brattain
Bratten
Brattin
Bratton
Bratu
Bratz
Brau
Brauch
Braucher
Brauchla
Braucht
Braucks
Braud
Braue
Brauer
Braught
Braughton
Braukus
Braulio
Brault
Braum
Brauman
Braun
Braunbeck
Braunberger
Braund
Braune
Brauner
Brauning
Braunschweige
Braunsdorf
Braunstein
Braunwarth
Brause
Brautigam
Bravard
Bravata
Brave
Bravender
Braver
Braverman
Bravo
Brawdy
Brawer
Brawley
Brawn
Brawner
Braxton
Bray
Brayboy
Braye
Brayer
Brayley
Braylock
Brayman
Braymer
Braymiller
Brayton
Braz
Brazan
Brazeal
Brazeau
Brazee
Brazel
Brazell
Brazelton
Brazen
Brazie
Braziel
Brazier
Brazil
Brazile
Brazill
Brazille
Brazington
Brazinski
Brazle
Brazler
Brazzel
Brazzell
Brazzi
Brazzle
Brdar
Brea
Breach
Bread
Bready
Breakell
Breaker
Breakey
Breakfield
Bream
Brean
Breard
Brearley
Breashears
Breath
Breau
Breaud
Breault
Breaux
Breaz
Breazeal
Breazeale
Brebes
Breceda
Brech
Brechbiel
Brechbill
Brecheen
Brecheisen
Brechner
Brecht
Brechtel
Breck
Breckel
Breckenridge
Breckenstein
Breckinridge
Breckley
Breda
Bredahl
Brede
Bredehoft
Bredemeier
Breden
Bredernitz
Bredesen
Bredeson
Bredeweg
Bredice
Bredin
Bredlow
Bredow
Bredy
Bree
Breece
Breech
Breed
Breedan
Breeden
Breeding
Breedlove
Breedon
Breehl
Breeland
Breeman
Breen
Breer
Brees
Breese
Breeze
Brefka
Bregantini
Brege
Bregel
Breger
Bregman
Bregon
Brehant
Brehaut
Breheny
Brehm
Brehmer
Brehon
Brehony
Brei
Breidel
Breidenbach
Breidenbaugh
Breidenstein
Breidenthal
Breidigan
Breier
Breighner
Breihan
Breiland
Breiling
Breiner
Breines
Breining
Breisch
Breister
Breit
Breitbach
Breitbart
Breitbarth
Breiten
Breitenbach
Breitenberg
Breitenbucher
Breitenfeldt
Breitenstein
Breiter
Breithaupt
Breitkreutz
Breitling
Breitmeyer
Breitung
Breitweiser
Brekke
Breland
Brelje
Brelsford
Brem
Breman
Bremer
Bremme
Bremmer
Bremner
Brems
Bremseth
Bren
Brenagh
Brenaman
Brence
Brenchley
Brend
Brenda
Brendal
Brendel
Brendeland
Brenden
Brender
Brendle
Brendlinger
Brendon
Brenek
Breneman
Brener
Brenes
Brengettey
Brengle
Brenhaug
Brening
Breniser
Brenna
Brennaman
Brennan
Brennecke
Brenneis
Brenneman
Brennen
Brennenstuhl
Brenner
Brennick
Brenning
Brennon
Brenowitz
Brensel
Brensinger
Brensnan
Brent
Brentano
Brentari
Brentley
Brentlinger
Brentnall
Brenton
Brents
Brentson
Brentz
Breon
Brereton
Brescia
Bresciani
Bresee
Bresemann
Bresett
Bresette
Breshears
Breske
Bresko
Breslauer
Breslawski
Bresler
Breslin
Breslow
Bresnahan
Bresnan
Bresolin
Bresse
Bresser
Bressette
Bressi
Bressler
Bressman
Brest
Brester
Bretado
Bretana
Breth
Brethour
Bretl
Breton
Bretos
Brett
Bretthauer
Brettmann
Bretto
Brettschneide
Bretz
Breu
Breuer
Breunig
Breuning
Breuninger
Breutzman
Breutzmann
Brevard
Brevell
Brevig
Brevik
Brevil
Brevitz
Brevo
Brew
Brewbaker
Brewen
Brewer
Brewington
Brewster
Brewton
Brey
Breyer
Breyers
Breyfogle
Brez
Brezeale
Brezee
Brezenski
Brezina
Brezinka
Brezinski
Breznak
Breznay
Bria
Briagas
Brian
Briand
Briano
Brians
Briant
Briante
Briar
Briare
Bribiesca
Brice
Briceno
Brichetto
Brick
Brickel
Brickell
Bricker
Brickett
Brickey
Brickhouse
Brickle
Brickles
Brickley
Brickman
Bricknell
Brickner
Brickson
Briddell
Briddick
Bride
Brideau
Bridegroom
Briden
Bridenbaker
Bridenbaugh
Bridenbecker
Bridendolph
Bridenstine
Bridge
Bridgeford
Bridgeforth
Bridgeman
Bridgens
Bridger
Bridgers
Bridges
Bridget
Bridgett
Bridgette
Bridgewater
Bridgford
Bridgforth
Bridgham
Bridgman
Bridgmon
Bridjmohan
Bridson
Bridwell
Bried
Briede
Brieger
Briehl
Briel
Brien
Brienen
Brieno
Brient
Brienza
Brier
Briere
Brierley
Brierly
Brierre
Brierton
Bries
Briese
Brigance
Brigante
Briganti
Brigantino
Brigg
Briggeman
Briggerman
Brigges
Briggman
Briggs
Brigham
Brighenti
Brighi
Bright
Brightbill
Brighter
Brightful
Brightharp
Brightly
Brightman
Brighton
Brightwell
Briglia
Brigman
Brigmond
Brignac
Brigner
Brignolo
Brignoni
Briguglio
Brihm
Brihon
Briles
Briley
Brilhante
Brill
Brilla
Brillant
Brillhart
Brilliant
Brillon
Brilowski
Brim
Brimage
Brimer
Brimeyer
Brimfield
Brimhall
Brimley
Brimm
Brimmage
Brimmer
Brin
Brinar
Brincat
Brincefield
Brinck
Brinckerhoff
Brincks
Brinda
Brindamour
Brindel
Brindger
Brindisi
Brindle
Brindley
Brindza
Brine
Brinegar
Briner
Brines
Briney
Bring
Bringantino
Bringard
Bringas
Bringer
Bringham
Bringhurst
Bringle
Bringman
Brinich
Brining
Brininger
Brinius
Brink
Brinker
Brinkerhoff
Brinkhaus
Brinkley
Brinkly
Brinkman
Brinkmann
Brinkmeier
Brinkmeyer
Brinks
Brinlee
Brinley
Brinn
Brinsfield
Brinson
Brint
Brintnall
Brinton
Briola
Brion
Briones
Brisban
Brisbane
Brisbin
Brisbois
Brisbon
Brisbone
Brisby
Brisco
Briscoe
Brisendine
Briseno
Brisentine
Brisk
Brisker
Briskey
Briski
Brisky
Brislan
Brisley
Brislin
Brison
Brissett
Brissette
Brissey
Brisson
Brister
Bristle
Bristo
Bristol
Briston
Bristow
Britain
Britcher
Brite
Britnell
Brito
Brits
Britsch
Britschgi
Britson
Britt
Brittain
Brittan
Britten
Brittenham
Brittian
Brittin
Brittingham
Brittle
Brittman
Britto
Britton
Britts
Brittsan
Britz
Brix
Brixey
Brixius
Brixner
Briz
Brizendine
Brizeno
Brizuela
Brletich
Bro
Broach
Broad
Broadaway
Broadbent
Broaddus
Broaden
Broadfoot
Broadhead
Broadhurst
Broadie
Broadnax
Broadnay
Broadrick
Broadstone
Broadstreet
Broadus
Broadwater
Broadway
Broadwell
Broady
Broas
Brobeck
Broberg
Brobst
Brocato
Broccoli
Broccolo
Broce
Broch
Brochard
Brochet
Brochhausen
Brochu
Brochure
Brociner
Brocious
Brock
Brockberg
Brockel
Brockell
Brockelmeyer
Brockenberry
Brocker
Brockert
Brockett
Brockhaus
Brockhouse
Brockie
Brockington
Brocklebank
Brocklehurst
Brocklesby
Brockman
Brockmann
Brockmeier
Brockmeyer
Brockney
Brocks
Brockus
Brockway
Brockwell
Brod
Broda
Brodbeck
Broddy
Brode
Brodell
Broden
Broder
Broderick
Brodersen
Broderson
Brodes
Brodess
Brodeur
Brodey
Brodfuehrer
Brodhag
Brodhead
Brodhurst
Brodi
Brodie
Brodigan
Brodin
Brodine
Brodis
Brodish
Brodka
Brodmerkel
Brodnax
Brodnex
Brodnicki
Brodowski
Brodrick
Brodsho
Brodsky
Brodt
Brodtmann
Brody
Brodzik
Broe
Broeckel
Broege
Broekemeier
Broeker
Broenneke
Broering
Broerman
Broermann
Broers
Broersma
Brofft
Brofman
Brog
Brogan
Brogden
Brogdon
Brogglin
Brogley
Broglie
Broglio
Brogna
Brogren
Brohawn
Brohl
Brohn
Broich
Broida
Broitzman
Brojakowski
Brokaw
Broker
Broking
Brokins
Brokke
Broks
Brola
Broll
Brom
Bromagen
Broman
Brombach
Bromberek
Bromberg
Brome
Bromfield
Bromley
Brommer
Bromwell
Bron
Bronaugh
Broncheau
Bronchetti
Bronder
Brondyke
Broner
Brong
Bronikowski
Bronk
Bronn
Bronner
Bronsky
Bronson
Bronstad
Bronstein
Bronston
Bronw
Bronzo
Brood
Broody
Brook
Brooke
Brookens
Brooker
Brookes
Brookfield
Brookhart
Brookhouse
Brookie
Brooking
Brookings
Brookins
Brooklyn
Brookman
Brookover
Brooks
Brookshaw
Brookshear
Brooksher
Brookshier
Brookshire
Brookskennedy
Broom
Broome
Broomell
Broomes
Broomfield
Broomhall
Broomhead
Brooms
Brophy
Brosch
Broschinsky
Broscious
Brosco
Brose
Brosey
Brosh
Brosi
Brosig
Brosious
Brosius
Broski
Brosky
Brosman
Brosnahan
Brosnan
Bross
Brossard
Brossart
Brosseau
Brossett
Brossman
Brossmann
Brossoit
Brost
Brostoff
Brostrom
Brotemarkle
Broten
Brothen
Brothern
Brothers
Brotherson
Brotherton
Brotman
Brott
Brotzman
Broudy
Brough
Brougham
Brougher
Brought
Broughton
Brouhard
Brouillard
Brouillet
Brouillette
Brouk
Broumley
Broun
Brounson
Brous
Brousard
Brouse
Broussard
Brousseau
Brouwer
Brouwers
Brow
Broward
Browder
Browe
Browen
Brower
Browers
Browing
Browley
Browm
Browman
Brown
Brownd
Browne
Brownell
Browner
Brownfield
Brownie
Browning
Brownle
Brownlee
Brownley
Brownlie
Brownlow
Brownrigg
Browns
Brownsberger
Brownson
Brownstein
Brownsword
Brownsworth
Brownwood
Browy
Brox
Broxson
Broxterman
Broxton
Broy
Broyhill
Broyle
Broyles
Broz
Brozek
Brozell
Brozena
Brozeski
Brozie
Brozina
Brozovich
Brozowski
Brozyna
Brroks
Brubach
Brubaker
Brubeck
Brucato
Bruccoleri
Brucculeri
Bruce
Bruch
Bruchey
Bruchman
Brucie
Bruck
Brucken
Brucker
Brucki
Bruckman
Bruckmeier
Bruckner
Brucks
Brucz
Bruder
Bruderer
Brudner
Brudnicki
Brue
Bruechert
Brueck
Brueckman
Brueckner
Brueggeman
Brueggemann
Bruegger
Bruegman
Bruemmer
Bruen
Bruender
Bruenderman
Bruening
Bruer
Brueske
Bruess
Bruestle
Bruff
Bruffee
Brug
Brugal
Bruggeman
Brugger
Bruggman
Brugh
Brugler
Brugliera
Brugman
Brugnoli
Bruh
Bruhn
Bruin
Bruington
Bruins
Bruk
Bruker
Brule
Bruley
Brull
Brulotte
Brum
Brumaghim
Brumbach
Brumback
Brumbalow
Brumbaugh
Brumbelow
Brumble
Brumbley
Brumby
Brumer
Brumet
Brumett
Brumfield
Brumit
Brumitt
Brumleve
Brumley
Brumlow
Brumm
Brummel
Brummell
Brummer
Brummet
Brummett
Brummitt
Brummond
Brumsey
Brumwell
Brun
Bruna
Brunback
Brunckhorst
Brund
Brundage
Brunderman
Brundidge
Brundige
Brundin
Brundrett
Brune
Bruneau
Brunecz
Brunell
Brunelle
Brunelli
Bruner
Brunet
Brunett
Brunetta
Brunette
Brunetti
Brunetto
Bruney
Brunfield
Brungard
Brungardt
Bruni
Brunick
Bruning
Brunjes
Brunk
Brunke
Brunken
Brunker
Brunkhardt
Brunkhorst
Brunkow
Brunmeier
Brunn
Brunnemer
Brunner
Brunnett
Bruno
Brunot
Brunow
Bruns
Brunscheen
Brunskill
Brunson
Brunsting
Brunston
Brunsvold
Brunswick
Brunt
Brunton
Bruntz
Brunz
Brunzel
Brus
Bruscato
Bruschi
Bruschke
Bruscino
Brusco
Bruse
Brush
Brushwood
Bruski
Bruso
Bruson
Bruss
Brusseau
Brussel
Brussell
Brusser
Brust
Bruster
Brustkern
Brustmann
Brusuelas
Brutger
Brutlag
Bruton
Brutsch
Brutus
Bruun
Bruyere
Bruyn
Bruzas
Bruzek
Bruzewicz
Bruzewski
Brwon
Bryan
Bryand
Bryans
Bryant
Bryar
Bryars
Bryce
Bryd
Bryden
Brydges
Brydon
Brye
Bryer
Bryington
Bryk
Bryla
Brymer
Bryne
Bryner
Brynestad
Brynga
Bryngelson
Brynteson
Bryon
Brys
Bryson
Bryton
Bryum
Brzenk
Brzezicki
Brzezinski
Brzezowski
Brzoska
Brzostek
Brzostowski
Brzozowski
Brzuchalski
Brzycki
Bua
Bual
Buanno
Bub
Buba
Bubak
Buban
Bubar
Bubash
Bubb
Bubbico
Buben
Bubert
Bubier
Bubis
Bublitz
Buboltz
Bubolz
Bubrig
Bucanan
Bucaram
Bucaro
Buccellato
Buccheri
Bucchin
Bucci
Bucciarelli
Buccieri
Bucciero
Buccino
Bucco
Bucek
Bucey
Buch
Buchal
Buchalter
Buchaman
Buchan
Buchana
Buchanan
Buchann
Buchannan
Buchannon
Buchanon
Buchar
Buchauer
Buchberger
Buchbinder
Bucheli
Buchenau
Bucher
Buchert
Buchetto
Buchheim
Buchheit
Buchholtz
Buchholz
Buchinski
Buchinsky
Buchite
Buchko
Buchler
Buchli
Buchman
Buchmann
Buchmeier
Buchmiller
Buchna
Buchner
Bucholtz
Bucholz
Buchs
Buchsbaum
Buchser
Buchta
Buchtel
Buchwald
Buchwalter
Bucio
Buck
Buckalew
Buckaloo
Buckbee
Bucke
Buckel
Buckelew
Buckendorf
Bucker
Buckett
Buckey
Buckhalter
Buckham
Buckhanan
Buckhannon
Buckhanon
Buckholtz
Buckholz
Buckingham
Buckland
Buckle
Buckler
Buckles
Buckless
Bucklew
Buckley
Bucklin
Buckman
Buckmaster
Buckmeon
Buckmiller
Bucknam
Bucknell
Buckner
Bucknor
Bucko
Buckovitch
Buckreis
Buckridge
Bucks
Buckson
Buckwald
Buckwalter
Buco
Bucolo
Bucy
Buczak
Buczek
Buczko
Buczkowski
Buczynski
Bud
Buda
Budak
Buday
Budd
Budde
Buddemeyer
Budden
Buddenhagen
Buddie
Buddington
Buddle
Budds
Buddy
Buden
Buder
Budesa
Budge
Budhram
Budhu
Budiao
Budin
Budine
Budinich
Budish
Budke
Budlong
Budney
Budnick
Budniewski
Budnik
Budreau
Budrovich
Budrow
Budworth
Budy
Budz
Budzik
Budzinski
Budziszewski
Budzyna
Budzynski
Bue
Bueche
Buechel
Buechele
Buecher
Buechler
Buechner
Bueckers
Buege
Bueggens
Buegler
Buehl
Buehler
Buehlman
Buehner
Buehring
Buehrle
Buel
Bueler
Buell
Buelna
Buelow
Buemi
Buen
Buena
Buenaventura
Buendia
Buenger
Buening
Bueno
Buenrostro
Buentello
Buenviaje
Buer
Buerge
Buergel
Buerger
Buerk
Buerkle
Buerstatte
Bueschel
Buescher
Buesgens
Buesing
Buess
Bueter
Bueti
Buetow
Buetti
Buettner
Buff
Buffa
Buffalo
Buffaloe
Buffett
Buffey
Buffin
Buffington
Buffkin
Buffo
Buffone
Bufford
Buffum
Buffy
Bufkin
Buford
Bufton
Buganski
Bugarewicz
Bugarin
Bugay
Bugayong
Bugbee
Bugenhagen
Bugett
Bugg
Bugge
Buggie
Buggs
Buggy
Bugh
Bugler
Buglione
Buglisi
Bugna
Bugni
Bugos
Bugtong
Buhite
Buhl
Buhler
Buhlig
Buhman
Buhmann
Buhoveckey
Buhr
Buhrke
Buhrman
Bui
Buice
Buie
Buike
Buikema
Builes
Buis
Buissereth
Buisson
Buist
Buitrago
Buitron
Buja
Bujak
Bujarski
Bujnowski
Bujol
Buker
Bukhari
Bukovac
Bukovsky
Bukowiecki
Bukowinski
Bukowski
Bukrim
Bula
Bulacan
Bulan
Buland
Bularz
Bulat
Bulcao
Buley
Bulfer
Bulgarella
Bulger
Bulgin
Bulgrin
Bulick
Bulik
Bulin
Bulinski
Bulisco
Bulkeley
Bulkin
Bulkley
Bull
Bulla
Bulland
Bullara
Bullard
Bullaro
Bulle
Bullen
Buller
Bulleri
Bullers
Bullert
Bullerwell
Bullett
Bullie
Bullin
Bulliner
Bullinger
Bullington
Bullins
Bullion
Bullis
Bullivant
Bullman
Bullmore
Bullo
Bulloch
Bullock
Bullocks
Bulls
Bulluck
Bulman
Bulmer
Bulnes
Bulock
Bulosan
Bulow
Bulson
Bult
Bultema
Bulter
Bultman
Bultron
Bulwinkle
Buman
Bumatay
Bumba
Bumbaca
Bumbalo
Bumbalough
Bumbray
Bumbrey
Bumby
Bumford
Bumgardner
Bumgarner
Bumm
Bump
Bumpas
Bumpass
Bumpaus
Bumpers
Bumps
Bumpus
Bumstead
Bun
Bunal
Bunce
Bunch
Bunche
Bunck
Bunda
Bundage
Bunde
Bundette
Bundi
Bundick
Bundley
Bundren
Bundrick
Bundschuh
Bundy
Bunes
Bunetta
Bungard
Bungart
Bungay
Bunge
Bunger
Bungert
Bungo
Bungy
Bunk
Bunke
Bunker
Bunkers
Bunkley
Bunn
Bunnell
Bunner
Bunning
Bunselmeyer
Bunson
Bunt
Buntain
Bunte
Bunten
Buntenbach
Buntin
Bunting
Buntjer
Bunton
Buntrock
Bunts
Buntyn
Buntz
Bunyan
Bunyard
Bunyea
Bunzey
Buol
Buonadonna
Buonaiuto
Buonamici
Buonanno
Buonassisi
Buono
Buonocore
Buonomo
Buontempo
Buote
Buoy
Bupp
Buquet
Buquo
Bur
Burak
Burakowski
Buran
Burandt
Buras
Buratti
Burau
Burba
Burbach
Burback
Burbage
Burbank
Burbano
Burbidge
Burbine
Burbridge
Burby
Burce
Burch
Burcham
Burchard
Burchell
Burchess
Burchett
Burchette
Burchfiel
Burchfield
Burchill
Burchinal
Burciaga
Burcin
Burck
Burckhard
Burczyk
Burd
Burda
Burde
Burdell
Burden
Burdeshaw
Burdess
Burdett
Burdette
Burdex
Burdg
Burdge
Burdi
Burdick
Burdier
Burdin
Burdine
Burdis
Burditt
Burdman
Burdo
Burdock
Burdon
Burdsall
Burdzel
Bure
Bureau
Burel
Burell
Buren
Bures
Buresh
Buress
Buretta
Burfeind
Burfield
Burford
Burg
Burga
Burgamy
Burgan
Burgard
Burgardt
Burgas
Burgbacher
Burgdorf
Burgdorfer
Burge
Burgees
Burgen
Burgener
Burger
Burgert
Burges
Burgeson
Burgess
Burget
Burgett
Burgette
Burgey
Burggraf
Burgh
Burghard
Burghardt
Burghart
Burgher
Burgie
Burgin
Burgio
Burglin
Burgman
Burgner
Burgo
Burgoa
Burgoon
Burgos
Burgoyne
Burgraff
Burgs
Burgueno
Burgun
Burgy
Burham
Burhans
Burhanuddin
Buri
Burian
Burich
Burick
Burigsay
Burin
Burington
Buris
Burk
Burka
Burkard
Burkart
Burkdoll
Burke
Burkeen
Burkel
Burker
Burkert
Burkes
Burket
Burkett
Burkette
Burkey
Burkhalter
Burkham
Burkhammer
Burkhard
Burkhardt
Burkhart
Burkhead
Burkholder
Burki
Burkin
Burkins
Burkitt
Burkland
Burkle
Burkleo
Burkley
Burklow
Burkly
Burkman
Burkowski
Burks
Burkstrand
Burl
Burlage
Burland
Burlando
Burlaza
Burle
Burleigh
Burleson
Burlett
Burlette
Burlew
Burley
Burlile
Burlin
Burling
Burlingame
Burlingham
Burlington
Burlison
Burlock
Burlson
Burly
Burm
Burman
Burmaster
Burmeister
Burmester
Burmside
Burn
Burnam
Burnaman
Burnap
Burnard
Burnash
Burnaugh
Burneisen
Burnell
Burner
Burnes
Burness
Burnet
Burnett
Burnette
Burney
Burnham
Burnias
Burnie
Burningham
Burnison
Burnley
Burno
Burns
Burnsed
Burnside
Burnstein
Burnsworth
Burnum
Burnworth
Buro
Buroker
Buron
Burow
Burows
Burpee
Burpo
Burr
Burrage
Burrall
Burras
Burrel
Burrell
Burrelli
Burrer
Burres
Burreson
Burress
Burri
Burrichter
Burridge
Burrier
Burries
Burriesci
Burright
Burrill
Burrington
Burris
Burriss
Burritt
Burrola
Burross
Burrough
Burroughs
Burrous
Burrow
Burrowes
Burrows
Burrs
Burruel
Burrup
Burrus
Burruss
Burry
Bursch
Burse
Bursell
Bursey
Bursi
Bursik
Bursley
Burson
Burstein
Burston
Burt
Burtch
Burtchell
Burtell
Burtenshaw
Burth
Burtin
Burtis
Burtle
Burtless
Burtman
Burtner
Burton
Burts
Burtschi
Burtt
Burttram
Burtts
Burum
Burvine
Burwell
Burwick
Burwinkel
Burwood
Bury
Burzlaff
Burzynski
Busa
Busacca
Busack
Busacker
Busalacchi
Busard
Busbee
Busbey
Busbin
Busboom
Busby
Buscaglia
Buscarino
Buscemi
Busch
Busche
Buscher
Buschman
Buschmann
Buschner
Buschur
Buse
Buseck
Buseman
Busenbark
Busenius
Buser
Busey
Bush
Bushard
Bushart
Bushaw
Bushby
Bushee
Bushell
Busher
Bushey
Bushfield
Bushie
Bushlen
Bushmaker
Bushman
Bushnell
Bushner
Bushong
Bushorn
Bushovisky
Bushrod
Bushway
Bushweller
Bushy
Busi
Busic
Busick
Busico
Busie
Busing
Busitzky
Busk
Buske
Busker
Buskey
Buskirk
Buskohl
Busl
Busler
Busman
Busque
Buss
Bussa
Bussani
Bussard
Busscher
Busse
Busselberg
Bussell
Bussen
Busser
Bussert
Bussey
Bussie
Bussiere
Bussing
Bussinger
Bussink
Busskohl
Bussler
Bussman
Bussmann
Bussom
Busson
Bussone
Bussy
Busta
Bustad
Bustamante
Bustamente
Bustard
Buster
Bustillo
Bustillos
Bustin
Bustinza
Bustios
Bustle
Busto
Bustos
Busuttil
Buswell
Buszak
But
Butac
Butala
Butanda
Butaud
Butay
Butch
Butchee
Butcher
Butchko
Bute
Buteau
Buteaux
Butel
Butenhoff
Butera
Buterbaugh
Buteux
Buth
Buther
Butkiewicz
Butkovich
Butkowski
Butkus
Butland
Butler
Butman
Butner
Butor
Butorac
Butremovic
Butrick
Butron
Butsch
Butscher
Butt
Butta
Buttaccio
Buttari
Buttaro
Buttars
Butte
Buttel
Butter
Butterbaugh
Butterfield
Butteris
Buttermore
Butters
Butterworth
Buttery
Buttimer
Buttino
Buttitta
Buttke
Buttler
Buttner
Buttolph
Button
Buttram
Buttray
Buttrey
Buttrick
Buttross
Buttrum
Buttry
Butts
Buttz
Butz
Butzen
Butzer
Butzke
Butzlaff
Buvens
Buvinghausen
Bux
Buxbaum
Buxton
Buyak
Buyck
Buyes
Buys
Buysse
Buza
Buzard
Buzbee
Buzby
Buzek
Buzhardt
Buziak
Buzick
Buzis
Buzo
Buzza
Buzzanca
Buzzard
Buzzell
Buzzelle
Buzzelli
Buzzeo
Buzzi
Buzzo
Bverger
Byal
Byam
Byan
Byant
Byard
Byars
Byas
Byassee
Bybee
Bybel
Byczek
Bye
Byer
Byerley
Byerly
Byers
Byes
Byfield
Byford
Byham
Byington
Byker
Bykowski
Byland
Byler
Byles
Bylsma
Bylund
Byman
Bynam
Bynd
Byndon
Byner
Bynes
Bynoe
Bynon
Bynum
Bynun
Byod
Byon
Byone
Byous
Byra
Byram
Byran
Byrant
Byrd
Byrdsong
Byrer
Byrge
Byrley
Byrn
Byrne
Byrnes
Byrns
Byrnside
Byro
Byrom
Byron
Byrum
Byse
Bystrom
Bystron
Byther
Bytheway
Byun
Byus
Bywater
Bywaters
Bzhyan
Caal
Caamano
Caba
Cabada
Cabading
Cabag
Cabal
Caballero
Caballes
Cabam
Caban
Cabana
Cabanas
Cabanela
Cabanes
Cabanilla
Cabanillas
Cabaniss
Cabarcas
Cabasso
Cabatu
Cabbagestalk
Cabbell
Cabble
Cabe
Cabebe
Cabeceira
Cabell
Cabellero
Cabello
Cabellon
Cabera
Caberto
Cabeza
Cabezas
Cabibbo
Cabido
Cabiles
Cabiltes
Cabiness
Cabiya
Cabla
Cable
Cabler
Cables
Cabon
Caborn
Cabos
Cabot
Cabotage
Cabotaje
Cabral
Cabrales
Cabrar
Cabrara
Cabreja
Cabrena
Cabrera
Cabrero
Cabreros
Cabriales
Cabugos
Cacace
Cacal
Cacatian
Caccamise
Caccamo
Caccavale
Caccia
Cacciatore
Cacciatori
Cacciola
Cacciotti
Caceres
Cachero
Cacho
Cachola
Cachu
Caci
Cacibauda
Cacioppo
Cackett
Cackowski
Cacy
Cada
Cadarette
Cadavid
Cadavieco
Caddel
Caddell
Cadden
Caddick
Caddigan
Caddle
Caddy
Cade
Cadelina
Cademartori
Caden
Cadena
Cadenas
Cadenhead
Cader
Cadet
Cadice
Cadieux
Cadigan
Cadiz
Cadle
Cadlett
Cadman
Cadmen
Cadmus
Cadoff
Cadogan
Cadorette
Cadotte
Cadoy
Cadrette
Cadriel
Cadwallader
Cadwell
Cady
Caesar
Caetano
Caez
Cafagno
Cafarella
Cafarelli
Cafaro
Cafasso
Caffarel
Caffarelli
Caffee
Caffentzis
Cafferky
Cafferty
Caffery
Caffey
Caffie
Caffrey
Caflisch
Cafourek
Cagan
Cage
Cager
Cagey
Caggiano
Cagle
Cagley
Cagliostro
Cagney
Cagno
Cagnon
Caguimbal
Cahal
Cahalan
Cahalane
Cahall
Cahan
Cahee
Cahela
Cahill
Cahillane
Cahn
Caho
Cahoon
Cahue
Cai
Caiafa
Caiazzo
Caicedo
Cail
Cailler
Caillier
Caillouet
Caimi
Cain
Caine
Caines
Cainglit
Cainion
Cainne
Cains
Caiozzo
Caira
Caire
Caires
Cairns
Cairo
Cairone
Caison
Caisse
Caissie
Caito
Caivano
Cajas
Cajero
Cajigas
Cajka
Cajucom
Cajulus
Cajune
Cakanic
Cake
Cakmak
Cal
Calabrese
Calabretta
Calabria
Calabro
Calaf
Calahan
Calais
Calamare
Calamari
Calamarino
Calame
Calamia
Calamity
Calandra
Calarco
Calaway
Calaycay
Calbert
Calcagino
Calcagni
Calcagno
Calcano
Calcao
Calcara
Calcaterra
Calchera
Calciano
Calco
Calcote
Calcutt
Caldarella
Caldarera
Caldarone
Caldas
Caldeira
Calder
Caldera
Calderara
Calderaro
Calderin
Caldero
Calderon
Calderone
Calderson
Calderwood
Caldon
Caldoron
Caldron
Caldwell
Cale
Caleb
Calegari
Calemine
Calender
Calendine
Caler
Calero
Cales
Caley
Calfee
Calger
Calhaun
Calhoon
Calhoun
Cali
Calibuso
Calica
Calico
Calicott
Calicut
Calicutt
Caliendo
Califano
Califf
Caligari
Caligiuri
Caliguire
Calija
Caliman
Calin
Calip
Calise
Calisto
Calix
Calixte
Calixto
Calixtro
Caliz
Calizo
Calk
Calkin
Calkins
Call
Callabrass
Callado
Callaghan
Callagher
Callagy
Callaham
Callahan
Callais
Callam
Callan
Callanan
Callander
Callar
Callari
Callarman
Callaro
Callas
Callaway
Calle
Callegari
Calleja
Callejas
Callejo
Callen
Callendar
Callender
Callens
Calleo
Caller
Calleros
Callery
Calles
Calley
Callez
Callicoat
Callicott
Callicutt
Callier
Callies
Calligan
Calligaro
Calligy
Calliham
Callihan
Callin
Callinan
Callington
Callins
Callis
Callison
Calliste
Callister
Callnan
Callo
Callon
Callow
Calloway
Callsen
Callum
Calmes
Calmese
Calnan
Calnen
Calnick
Calnimptewa
Calo
Caloca
Calogero
Calonne
Calonsag
Calowell
Calpin
Calrk
Calta
Caltabiano
Caltagirone
Calton
Calumag
Caluya
Calvan
Calvani
Calvano
Calvaresi
Calvaruso
Calvary
Calvello
Calvelo
Calvent
Calver
Calverley
Calvert
Calvery
Calvetti
Calvey
Calvi
Calvillo
Calvin
Calvino
Calvo
Calway
Calwell
Calzada
Calzadilla
Calzado
Calzone
Cam
Camacho
Camack
Camaeho
Camaj
Camak
Camancho
Camano
Camara
Camarata
Camarda
Camarena
Camareno
Camarero
Camargo
Camarillo
Camaron
Camastro
Camba
Cambareri
Cambel
Cambell
Cambero
Camberos
Cambi
Cambia
Camble
Cambra
Cambre
Cambria
Cambric
Cambridge
Cambron
Cambronne
Camburn
Camcam
Camden
Camejo
Camel
Cameli
Camelin
Camell
Camelo
Camenisch
Camera
Camerano
Camerena
Camerino
Camero
Cameron
Camey
Camferdam
Camfield
Camic
Camidge
Camille
Camilleri
Camilli
Camillo
Camilo
Caminero
Caminita
Caminiti
Camino
Caminos
Camire
Camisa
Camlin
Camm
Cammack
Cammarano
Cammarata
Cammarn
Cammarota
Cammon
Camon
Camors
Camp
Campa
Campagna
Campagne
Campagnini
Campagnone
Campain
Campainha
Campana
Campanaro
Campanella
Campanelli
Campanile
Campany
Campas
Campau
Campbel
Campbell
Campble
Campean
Campeau
Campell
Campellone
Campen
Camper
Campese
Campfield
Campi
Campillo
Campion
Campione
Campise
Campisi
Campman
Campo
Campobasso
Campoli
Campolo
Campolongo
Campora
Campos
Camposano
Campoverde
Campoy
Camps
Campton
Campus
Campusano
Campuzano
Camren
Camus
Camuso
Can
Cana
Canaan
Canada
Canaday
Canady
Canak
Canal
Canale
Canales
Canalez
Canan
Canant
Canard
Canario
Canarte
Canary
Canas
Canatella
Canavan
Canaway
Canby
Cance
Cancel
Cancelliere
Cancer
Canchola
Cancilla
Cancino
Cancio
Canclini
Cancro
Candanoza
Candee
Candela
Candelaria
Candelario
Candell
Candella
Canders
Candia
Candido
Candill
Candland
Candle
Candler
Candlish
Candon
Candozo
Candy
Cane
Canedo
Canedy
Caneer
Canel
Canela
Caneles
Canella
Canellas
Canelo
Canepa
Canerday
Canes
Canestraro
Canestrini
Canestro
Canete
Canetta
Caneva
Canevari
Canevazzi
Caney
Canez
Caneza
Canfield
Cangas
Cange
Cangelosi
Cangemi
Cangey
Cangialosi
Cangiano
Canham
Canida
Canino
Canion
Canipe
Canizales
Canizares
Canlas
Cann
Cannada
Cannaday
Cannady
Cannan
Cannard
Cannata
Cannatella
Cannavo
Cannedy
Cannell
Cannella
Cannellos
Canner
Canney
Canniff
Canning
Cannington
Cannistraro
Cannizzaro
Cannizzo
Cannon
Cannone
Cannonier
Cannuli
Canny
Cano
Canon
Canonica
Canonico
Canori
Canova
Canoy
Canpos
Canseco
Cansibog
Cansino
Cansler
Canslor
Canson
Canta
Cantabrana
Cantadore
Cantakis
Cantara
Cantarano
Cantarella
Cantatore
Cantave
Cante
Cantell
Cantella
Canter
Canterberry
Canterbury
Cantero
Cantey
Cantfield
Cantillo
Cantin
Cantine
Cantley
Cantlow
Canto
Canton
Cantone
Cantoni
Cantor
Cantoral
Cantoran
Cantore
Cantos
Cantrall
Cantre
Cantrel
Cantrell
Cantrelle
Cantres
Cantu
Cantua
Cantv
Cantwell
Canty
Canu
Canul
Canup
Canupp
Canute
Canwell
Canzio
Canzoneri
Cao
Caoagdan
Caoile
Caoili
Caouette
Cap
Capaccino
Capalbo
Capaldi
Capaldo
Capalongan
Capan
Capanna
Capano
Caparelli
Caparoula
Caparros
Capas
Capasso
Capata
Capati
Capdeville
Cape
Capece
Capehart
Capek
Capel
Capell
Capella
Capellan
Capellas
Capelli
Capello
Capelo
Capels
Capen
Capener
Caper
Caperon
Capers
Caperton
Capes
Capestany
Capestro
Capetillo
Capetl
Capezzuto
Capicotto
Capiga
Capilla
Capinpin
Capistran
Capitani
Capitano
Capito
Capizzi
Caplan
Caple
Caplener
Caples
Caplette
Capley
Caplin
Caplinger
Capo
Capobianco
Capoccia
Capone
Caponera
Caponi
Caponigro
Caporale
Caporali
Caporiccio
Caposole
Capossela
Capote
Capouch
Capozzi
Capozzoli
Capp
Cappa
Cappaert
Capparelli
Cappas
Cappel
Cappellano
Cappelletti
Cappelli
Cappellini
Cappello
Cappelluti
Capper
Cappetta
Cappiello
Cappleman
Cappo
Cappola
Capponi
Capps
Cappucci
Capra
Capracotta
Caprario
Capraro
Capri
Capria
Capriccioso
Caprice
Caprio
Capriola
Capriotti
Capristo
Capron
Capshaw
Capshaws
Captain
Capua
Capuano
Capuchin
Capulong
Capurro
Caputi
Caputo
Capuzzi
Capwell
Caquias
Car
Cara
Carabajal
Caraballo
Carabello
Carabez
Carabine
Caracci
Caracciola
Caracciolo
Caracso
Caradine
Caradonna
Caraher
Caraig
Caraker
Caram
Caramanica
Caramella
Caramelo
Carandang
Carangelo
Carano
Caranza
Caras
Carasco
Carasquillo
Carathers
Carattini
Caravalho
Caravantes
Caravati
Caravella
Caravello
Caraveo
Caravetta
Caraway
Carback
Carbajal
Carbal
Carballo
Carbary
Carbaugh
Carbee
Carberry
Carbery
Carbin
Carbine
Carbo
Carbon
Carbonara
Carbonaro
Carbone
Carboneau
Carbonell
Carbonella
Carboni
Carbonneau
Carby
Carcamo
Carcana
Carcano
Carchi
Carchidi
Carcia
Carcieri
Carco
Card
Carda
Cardamone
Cardani
Cardarelli
Cardazone
Cardeiro
Cardejon
Cardell
Cardella
Cardelli
Cardello
Carden
Cardena
Cardenal
Cardenas
Cardenos
Carder
Cardera
Cardero
Cardi
Cardiel
Cardiff
Cardillo
Cardimino
Cardin
Cardinal
Cardinale
Cardinali
Cardinalli
Cardinas
Cardine
Cardino
Cardish
Cardle
Cardno
Cardo
Cardon
Cardona
Cardone
Cardoni
Cardonia
Cardono
Cardosa
Cardosi
Cardoso
Cardova
Cardoza
Cardozo
Carducci
Cardwell
Cardy
Care
Careaga
Carel
Carela
Carella
Carello
Caren
Carethers
Caretto
Carew
Carey
Carfagno
Carfora
Carfrey
Cargile
Cargill
Cargle
Cargo
Carhart
Cariaga
Carias
Cariaso
Carico
Caricofe
Cariddi
Caride
Carideo
Caridine
Carie
Cariello
Carignan
Cariker
Carilli
Carillion
Carillo
Carin
Carina
Carine
Caringi
Carini
Carinio
Carino
Carioscia
Caris
Caristo
Carithers
Cariveau
Carkhuff
Carknard
Carl
Carlacci
Carlan
Carland
Carlberg
Carle
Carlee
Carlen
Carleo
Carles
Carleton
Carlew
Carley
Carli
Carlile
Carlill
Carlin
Carline
Carlington
Carlini
Carlino
Carlis
Carlise
Carlisle
Carll
Carlo
Carlock
Carlon
Carlone
Carloni
Carlos
Carlough
Carlow
Carlozzi
Carls
Carlsen
Carlsley
Carlson
Carlsson
Carlsten
Carlston
Carlstrom
Carlton
Carlucci
Carlye
Carlyle
Carlyon
Carmack
Carmain
Carman
Carmant
Carmany
Carmean
Carmel
Carmell
Carmella
Carmello
Carmen
Carmena
Carmer
Carmichael
Carmicheal
Carmichel
Carmickel
Carmickle
Carmicle
Carmin
Carmine
Carmley
Carmody
Carmolli
Carmon
Carmona
Carmony
Carmouche
Carn
Carnagey
Carnahan
Carnahiba
Carnall
Carnalla
Carnathan
Carne
Carneal
Carnegia
Carnegie
Carnell
Carner
Carnero
Carnes
Carnett
Carnevale
Carney
Carnicelli
Carnie
Carnighan
Carnillo
Carnine
Carnley
Carnohan
Carnoske
Carnovale
Carnrike
Carns
Caro
Carodine
Carol
Carolan
Carolfi
Caroli
Carolin
Carolina
Caroline
Caroll
Carolla
Carollo
Carolus
Caron
Carone
Caronna
Carosella
Caroselli
Carosiello
Carota
Carotenuto
Carothers
Carouthers
Carovski
Carow
Caroway
Carozza
Carp
Carpanini
Carpen
Carpenito
Carpente
Carpenter
Carpentier
Carpentieri
Carper
Carpinelli
Carpinello
Carpino
Carpinteyro
Carpio
Carr
Carra
Carrabine
Carradine
Carragher
Carrahan
Carraher
Carrales
Carran
Carranco
Carrano
Carransa
Carranza
Carranzo
Carrao
Carrara
Carras
Carrasco
Carrasquillo
Carratala
Carratura
Carraturo
Carrauza
Carraway
Carrazco
Carre
Carrea
Carrecter
Carreira
Carreiro
Carrejo
Carreker
Carrel
Carrell
Carrelli
Carreno
Carreon
Carrera
Carreras
Carrere
Carrero
Carretero
Carrethers
Carretino
Carretta
Carriaga
Carrick
Carrico
Carridine
Carrie
Carriedo
Carrier
Carriere
Carrig
Carrigan
Carriger
Carrigg
Carriker
Carril
Carrillo
Carrilo
Carrin
Carrington
Carrino
Carrio
Carrion
Carris
Carrisalez
Carrison
Carrithers
Carriveau
Carrizal
Carrizales
Carrizo
Carro
Carroca
Carrol
Carroll
Carron
Carros
Carrothers
Carrousal
Carrow
Carroway
Carrozza
Carruba
Carrubba
Carrus
Carruth
Carruthers
Carry
Carscallen
Carse
Carsen
Carsey
Carskadon
Carsno
Carson
Carstarphen
Carsten
Carstens
Carstensen
Carston
Carswell
Cart
Carta
Cartagena
Cartan
Cartaya
Carte
Cartee
Cartegena
Cartelli
Carten
Carter
Cartez
Carthen
Carthens
Carther
Carthew
Carthon
Cartier
Cartin
Cartland
Cartledge
Cartlidge
Cartmell
Cartmill
Cartner
Carton
Cartrette
Cartright
Cartwright
Carty
Carualho
Caruana
Carucci
Carullo
Caruso
Caruth
Caruthers
Carvajal
Carvalho
Carvallo
Carvalno
Carvana
Carvel
Carvell
Carver
Carvett
Carvey
Carvill
Carville
Carvin
Carwell
Carwile
Carwin
Cary
Caryk
Caryl
Carza
Casa
Casabona
Casacchia
Casaceli
Casad
Casada
Casadei
Casado
Casados
Casady
Casagranda
Casagrande
Casal
Casale
Casalenda
Casales
Casali
Casaliggi
Casalman
Casamayor
Casamento
Casana
Casanas
Casano
Casanova
Casar
Casarella
Casareno
Casares
Casarez
Casario
Casarrubias
Casarz
Casas
Casasola
Casassa
Casaus
Casavant
Casavez
Casazza
Casbarro
Casbeer
Casburn
Cascia
Casciano
Casciato
Cascio
Cascioli
Casco
Cascone
Casdorph
Case
Casebeer
Casebier
Casebolt
Caselden
Casella
Caselli
Casello
Caselton
Caseman
Casement
Caseres
Caserta
Casewell
Casey
Casgrove
Cash
Cashatt
Cashaw
Cashdollar
Cashen
Casher
Cashett
Cashin
Cashing
Cashio
Cashion
Cashman
Cashmer
Cashmore
Cashon
Cashour
Cashwell
Casiano
Casias
Casida
Casile
Casilla
Casillas
Casilles
Casillo
Casimir
Casimiro
Casini
Casino
Casio
Casis
Casivant
Caska
Caskey
Casler
Casley
Caslin
Casmore
Casner
Caso
Casola
Casolary
Cason
Casoria
Caspar
Caspari
Casparian
Casparis
Caspary
Casper
Caspers
Caspersen
Casperson
Caspi
Cass
Cassa
Cassada
Cassaday
Cassady
Cassagne
Cassandra
Cassani
Cassano
Cassanova
Cassar
Cassara
Cassard
Cassarino
Cassaro
Cassarubias
Cassase
Cassata
Cassatt
Cassavaugh
Casseday
Cassel
Casselberry
Cassell
Cassella
Cassello
Cassells
Casselman
Cassels
Cassem
Cassens
Casserly
Cassese
Cassetta
Cassette
Cassetty
Casseus
Cassey
Cassi
Cassiano
Cassiday
Cassidy
Cassilano
Cassin
Cassinelli
Cassino
Cassio
Cassion
Cassis
Cassisse
Cassity
Cassius
Cassler
Cassman
Cassmeyer
Casso
Casson
Cassone
Casstevens
Cast
Castagna
Castagnier
Castagnola
Castaldi
Castaldo
Castanada
Castanado
Castaneda
Castanedo
Castaner
Castanio
Castano
Castanon
Casteel
Castejon
Castel
Castelan
Castelhano
Castell
Castellan
Castellana
Castellaneta
Castellani
Castellano
Castellanos
Castellanoz
Castellari
Castellaw
Castelli
Castellion
Castello
Castellon
Castellonese
Castellow
Castells
Castellucci
Castelluccio
Castelo
Castelum
Casten
Castenada
Castenanos
Casteneda
Caster
Castera
Casterline
Castiglia
Castiglione
Castile
Castilla
Castillanos
Castille
Castilleja
Castillejo
Castillero
Castillio
Castillion
Castillo
Castillon
Castilo
Castin
Castine
Castiola
Castle
Castleberry
Castleman
Castlen
Castles
Castleton
Castner
Casto
Castoe
Caston
Castonguay
Castongvay
Castor
Castoral
Castorena
Castoreno
Castrataro
Castrejon
Castrellon
Castrey
Castricone
Castrillo
Castro
Castrogiovann
Castronova
Castronovo
Castros
Castrovinci
Castruita
Casuat
Casumpang
Casuscelli
Casuse
Caswell
Cata
Catacun
Catacutan
Catala
Catalan
Catalanatto
Catalani
Catalano
Catalanotto
Cataldi
Cataldo
Catalfamo
Catalina
Cataline
Catalino
Catalli
Catan
Catanach
Catanese
Catani
Catania
Catano
Catanzano
Catanzarite
Catanzaro
Catapano
Cataquet
Catching
Catchings
Catchpole
Cate
Catella
Catello
Catena
Catenaccio
Cater
Caterina
Caterino
Cates
Cathcart
Cathell
Cather
Catherine
Catherman
Cathers
Catherson
Catherwood
Cathey
Cathie
Catholic
Cathy
Catignani
Catillo
Catinella
Catino
Catledge
Catlett
Catlin
Catlow
Catmull
Cato
Catoe
Catoggio
Catoire
Caton
Catone
Catozzi
Catrambone
Catrett
Catrini
Catron
Catrone
Catt
Cattabriga
Cattanach
Cattaneo
Cattano
Cattell
Catterson
Catterton
Cattladge
Catto
Catton
Cattrell
Catts
Catucci
Catus
Cauazos
Cauble
Cauchon
Caudel
Caudell
Caudill
Caudillo
Caudle
Caudy
Cauffman
Caufield
Caughell
Caughey
Caughlin
Caughman
Caughorn
Caughran
Caughron
Caul
Caulder
Cauley
Caulfield
Caulk
Caulkins
Caulley
Causby
Causey
Causley
Cauterucci
Cauthen
Cauthon
Cauthorne
Cauthron
Cautillo
Cava
Cavaco
Cavagna
Cavagnaro
Cavaiani
Cavalaris
Cavalcante
Cavaleri
Cavalero
Cavalier
Cavaliere
Cavalieri
Cavaliero
Cavallario
Cavallaro
Cavallero
Cavalli
Cavallo
Cavaluzzi
Cavan
Cavanagh
Cavanah
Cavanaugh
Cavaness
Cavaretta
Cavasos
Cavazos
Cave
Cavel
Cavender
Cavendish
Cavener
Caveness
Caveney
Caver
Caverly
Cavers
Caves
Cavett
Cavey
Cavez
Cavezon
Cavicchi
Cavicchia
Caviggia
Cavill
Cavin
Caviness
Cavins
Cavitt
Cavness
Cavrak
Cawein
Cawley
Cawon
Cawood
Cawthon
Cawthorn
Cawthorne
Cawthron
Cay
Caya
Cayabyab
Cayanan
Cayce
Cayea
Cayer
Cayetano
Caylor
Cayne
Cayo
Cayouette
Cayson
Cayton
Caywood
Caza
Cazaree
Cazares
Cazarez
Cazeau
Cazeault
Cazel
Cazenave
Cazier
Cazorla
Cazzell
Cdebaca
Cea
Cearley
Cearlock
Cearns
Ceasar
Cease
Ceaser
Ceasor
Ceballos
Cebula
Cecala
Ceccarelli
Cecchetti
Cecchi
Cecchinato
Cecchini
Cecena
Cecere
Cech
Cechini
Cecil
Cecilia
Cecilio
Ceconi
Cecot
Cedano
Cedar
Cedars
Cedeno
Ceder
Cederberg
Cederstrom
Cedillo
Cedillos
Cedotal
Cedrone
Cefalo
Cefalu
Cefaratti
Cegielski
Cegla
Ceglinski
Ceja
Cejka
Celadon
Celani
Celano
Celaya
Celedon
Celentano
Celenza
Celeste
Celestin
Celestine
Celestino
Celeya
Celi
Celia
Celis
Celius
Cella
Cellar
Celli
Cellini
Cellio
Cellucci
Cellupica
Celmer
Celso
Celuch
Cely
Ceman
Cembura
Cena
Cenat
Cenci
Cendan
Cendana
Cendejas
Ceniceros
Censky
Centanni
Centano
Centeno
Center
Centers
Centi
Centini
Centner
Centola
Centore
Centorino
Centrella
Centrich
Centrone
Ceo
Ceovantes
Ceparano
Cepas
Cepeda
Cepero
Cephas
Cephus
Cepin
Ceppetelli
Cera
Cerami
Ceranski
Cerao
Ceraos
Cerar
Cerasi
Ceraso
Cerasoli
Cerasuolo
Ceravolo
Cerbantes
Cerbone
Cerce
Cerceo
Cerchia
Cercone
Cercy
Cerda
Cerdan
Cerecedes
Cerecer
Cereceres
Cereghino
Cerenzia
Cereo
Ceretti
Cerezo
Cerf
Cerino
Cerio
Cerise
Cermak
Cermeno
Cerminaro
Cerna
Cernansky
Cerney
Cerni
Cerniglia
Cernoch
Cernohous
Cernota
Cernuto
Cerny
Ceron
Cerone
Ceroni
Ceronsky
Cerqueira
Cerra
Cerrano
Cerrato
Cerrello
Cerreta
Cerri
Cerrillo
Cerritelli
Cerrito
Cerritos
Cerrone
Cerroni
Cerros
Cerruti
Cerruto
Cersey
Certain
Certalich
Certosimo
Ceruantes
Cerulli
Cerullo
Cerutti
Cerva
Cervantes
Cervantez
Cervantsz
Cervenak
Cervenka
Cerventez
Cerveny
Cervera
Cerverizzo
Cervetti
Cervin
Cervone
Cervoni
Cerza
Cesa
Cesar
Cesare
Cesari
Cesario
Cesena
Cespedes
Cessna
Cessor
Cestari
Cestero
Cestia
Cestone
Cetta
Cevallos
Cevera
Cezar
Cezil
Cha
Chaban
Chabaud
Chabbez
Chaberek
Chabez
Chabolla
Chabot
Chabotte
Chaboya
Chace
Chachere
Chacko
Chaco
Chacon
Chaconas
Chad
Chadbourn
Chadbourne
Chadburn
Chadd
Chadderton
Chaddick
Chaddlesone
Chaddock
Chadek
Chaderton
Chadez
Chadick
Chadsey
Chadwell
Chadwick
Chae
Chafe
Chafetz
Chaffee
Chaffer
Chaffey
Chaffin
Chaffins
Chafin
Chafins
Chagnon
Chagolla
Chagollan
Chagoya
Chahal
Chai
Chaidez
Chaidy
Chaiken
Chaille
Chaim
Chain
Chainey
Chaires
Chairez
Chais
Chaisson
Chaisty
Chait
Chaix
Chajon
Chakkalakal
Chaknis
Chalaban
Chalcraft
Chalender
Chalepah
Chalet
Chaleun
Chalfant
Chalfin
Chalifour
Chalifoux
Chaligoj
Chalita
Chalk
Chalker
Chalkley
Chall
Challa
Challacombe
Challberg
Challen
Challender
Challenger
Challinor
Challis
Chalmers
Chaloner
Chaloux
Chalow
Chalupa
Chalupsky
Cham
Chamber
Chamberlain
Chamberland
Chamberlian
Chamberlin
Chambers
Chamble
Chamblee
Chambless
Chambley
Chamblin
Chambliss
Chamers
Chamlee
Chamley
Chamnanphony
Chamness
Chamorro
Champ
Champa
Champaco
Champagne
Champany
Champeau
Champey
Champine
Champion
Champlain
Champlin
Champman
Champney
Champoux
Champy
Chamul
Chan
Chanady
Chananie
Chance
Chancellor
Chancer
Chancey
Chanchuan
Chanco
Chancy
Chand
Chander
Chandier
Chandler
Chandley
Chandra
Chandrasekara
Chandrasekhar
Chandronnait
Chandsawangbh
Chanel
Chaney
Chanez
Chang
Chango
Chanin
Chanler
Chanley
Channel
Channell
Channer
Channey
Channing
Chanofsky
Chanoine
Chant
Chantha
Chanthasene
Chanthaumlsa
Chantler
Chantos
Chantry
Chao
Chaobal
Chapa
Chaparro
Chapdelaine
Chapek
Chapel
Chapell
Chapelle
Chapen
Chapin
Chapko
Chaple
Chaplean
Chaplen
Chaples
Chaplik
Chaplin
Chapman
Chapmon
Chapmond
Chapnick
Chapoton
Chapp
Chappa
Chappan
Chapparo
Chappel
Chappelear
Chappell
Chappelle
Chappie
Chapple
Chappo
Chappuis
Chaput
Char
Charan
Charania
Chararria
Charboneau
Charbonneau
Charbonneaux
Charbonnel
Charbonnet
Chard
Charest
Charette
Chareunrath
Chareunsri
Charfauros
Chargois
Chargualaf
Chari
Charif
Charisse
Charity
Charland
Charle
Charlebois
Charles
Charleston
Charlesworth
Charleton
Charlette
Charley
Charlie
Charlot
Charlson
Charlton
Charm
Charney
Charnley
Charnoski
Charo
Charon
Charpentier
Charpia
Charping
Charrier
Charriez
Charron
Charry
Chars
Charsky
Charter
Charters
Chartier
Chartrand
Chartraw
Charvat
Charves
Charvet
Chary
Chase
Chasen
Chasey
Chasin
Chaskey
Chasnoff
Chason
Chass
Chassaniol
Chasse
Chasser
Chasson
Chastain
Chastang
Chastant
Chasteen
Chasten
Chastin
Chastine
Chatagnier
Chatampaya
Chatcho
Chatelain
Chatfield
Chatham
Chatley
Chatlos
Chatman
Chatmon
Chaton
Chatriand
Chatt
Chatten
Chatterjee
Chatters
Chatterson
Chatterton
Chattin
Chau
Chauarria
Chauca
Chaudet
Chaudhry
Chaudhuri
Chaudoin
Chauez
Chauffe
Chauhan
Chauhdrey
Chaulk
Chaulklin
Chaumont
Chauncey
Chausse
Chautin
Chauvaux
Chauvette
Chauvin
Chavana
Chavaria
Chavarin
Chavarria
Chavayda
Chaven
Chavera
Chavers
Chaves
Chavez
Chaviano
Chavies
Chavira
Chavis
Chavous
Chavoustie
Chawla
Chay
Chayka
Che
Chea
Cheadle
Cheairs
Cheak
Cheam
Chean
Cheaney
Chears
Cheas
Cheatam
Cheatem
Cheater
Cheatham
Cheathan
Cheatom
Cheatum
Cheatwood
Chebahtah
Chebret
Checa
Checca
Chech
Check
Checkett
Checketts
Checo
Cheda
Chee
Cheek
Cheeks
Cheely
Cheeney
Cheers
Cheese
Cheeseboro
Cheesebrough
Cheeseman
Cheesman
Cheetham
Cheever
Cheevers
Cheeves
Chefalo
Cheffer
Chegwidden
Chehab
Chehebar
Cheirs
Chelette
Chelf
Cheli
Chell
Chellis
Chelton
Chemell
Chemin
Chen
Chenail
Chenaille
Chenard
Chenauls
Chenault
Chene
Chenet
Chenette
Chenevert
Chenevey
Cheney
Cheng
Chenier
Chennault
Chenot
Chenoweth
Cheon
Cheong
Chepiga
Cheramie
Cheranichit
Cherchio
Cherebin
Cherenfant
Cherep
Cherepy
Cherian
Cherico
Chermak
Chern
Chernak
Chernay
Cherne
Chernesky
Cherney
Chernich
Chernick
Chernoff
Chernosky
Chernow
Cherny
Cheroki
Cherpak
Cherrette
Cherrez
Cherrie
Cherrier
Cherrin
Cherrington
Cherry
Cherubin
Cherubini
Cherubino
Cherven
Chervin
Cherwinski
Chery
Chesanek
Chesbro
Chesbrough
Chesebro
Cheser
Chesher
Cheshier
Cheshire
Chesick
Chesla
Cheslak
Chesler
Chesley
Cheslock
Chesmore
Chesner
Chesney
Chesnut
Chesnutt
Chess
Chesser
Chessher
Chessman
Chesson
Chessor
Chestand
Chestang
Chesteen
Chester
Chesterfield
Chesterman
Chestnut
Chestnutt
Chet
Chetelat
Chetram
Cheu
Cheung
Cheuvront
Chevalier
Chevarie
Chevas
Chevere
Cheverez
Cheverton
Cheves
Chevez
Chevis
Chevres
Chevrette
Chevrier
Chew
Chewning
Chey
Cheyne
Cheyney
Chez
Chhabra
Chham
Chhan
Chheang
Chheng
Chhim
Chhom
Chhon
Chhor
Chhoun
Chhour
Chhum
Chhun
Chhuon
Chi
Chia
Chiado
Chiaminto
Chianese
Chiang
Chiapetti
Chiapetto
Chiappari
Chiappetta
Chiappinelli
Chiappone
Chiara
Chiaramonte
Chiaravalle
Chiarella
Chiarelli
Chiarello
Chiarenza
Chiariello
Chiarini
Chiarito
Chiarmonte
Chiaro
Chiasson
Chiavaroli
Chica
Chicalace
Chicas
Chicca
Chicharello
Chichester
Chick
Chickering
Chicles
Chico
Chicoine
Chicon
Chidester
Chieffo
Chiem
Chien
Chieng
Chier
Chiera
Chiesa
Chieves
Chiffriller
Chihak
Chihuahua
Chikko
Chila
Chilcoat
Chilcote
Chilcott
Chilcutt
Child
Childers
Childes
Childree
Childres
Childress
Childrey
Childs
Chilek
Chilen
Chiles
Chilinskas
Chill
Chillemi
Chillis
Chillo
Chilo
Chilsom
Chilson
Chilton
Chilvers
Chim
Chima
Chimal
Chime
Chimeno
Chimenti
Chimento
Chimera
Chimes
Chimilio
Chin
China
Chinault
Chinchilla
Chindlund
Chinen
Chinetti
Ching
Chinick
Chinn
Chinnery
Chinni
Chinnici
Chinnis
Chino
Chinskey
Chinweze
Chinzi
Chio
Chiodi
Chiodini
Chiodo
Chiola
Chioma
Chionchio
Chiong
Chiotti
Chiou
Chiphe
Chipley
Chipman
Chipp
Chipps
Chiprean
Chiquito
Chirafisi
Chiras
Chirasello
Chirco
Chirdon
Chirico
Chirino
Chirinos
Chisam
Chisari
Chischilly
Chisem
Chisholm
Chisler
Chisley
Chislom
Chism
Chisman
Chisnall
Chisolm
Chisom
Chisum
Chiszar
Chitrik
Chittam
Chittenden
Chittester
Chittick
Chittom
Chittum
Chitty
Chitwood
Chiu
Chiulli
Chiumento
Chiv
Chivalette
Chivers
Chiverton
Chiz
Chizek
Chizmar
Chkouri
Chladek
Chlebek
Chlebus
Chludzinski
Chmela
Chmelicek
Chmelik
Chmiel
Chmielewski
Chmielowiec
Chmura
Cho
Choat
Choate
Choates
Chobot
Chochrek
Chock
Chockley
Chocron
Chodorov
Choe
Choen
Choi
Choice
Choiniere
Choinski
Chojnacki
Chojnowski
Chokshi
Chol
Cholakyan
Cholewa
Cholewinski
Cholico
Chollett
Cholula
Choma
Chomali
Chomicki
Chomka
Chon
Chong
Choo
Chopelas
Chopp
Chopra
Chopton
Choquette
Chor
Chorley
Chorlton
Chorney
Chott
Chou
Choudhary
Choudhury
Chough
Chouinard
Choules
Choulnard
Choun
Choung
Chounlapane
Choute
Chouteau
Chovanec
Chow
Chowanec
Chowansky
Chowdhury
Chowen
Chowenhill
Chowhan
Chown
Chowning
Choy
Chrabasz
Chrabaszcz
Chreene
Chrest
Chrestman
Chretien
Chris
Chrisco
Chriscoe
Chrisjohn
Chrisler
Chrisley
Chrislip
Chrisman
Chrismer
Chrismon
Chrisp
Chrispen
Chrispin
Chriss
Christ
Christain
Christal
Christaldi
Christan
Christe
Christel
Christello
Christen
Christenberry
Christenbury
Christensen
Christenson
Christerson
Christescu
Christesen
Christeson
Christi
Christian
Christiana
Christiani
Christiano
Christians
Christiansen
Christianson
Christie
Christin
Christina
Christinat
Christine
Christinsen
Christion
Christison
Christle
Christler
Christley
Christlieb
Christman
Christmann
Christmas
Christmau
Christner
Christo
Christodoulou
Christoff
Christoffer
Christofferse
Christofferso
Christoforou
Christon
Christoph
Christophe
Christophel
Christopher
Christopherse
Christopherso
Christopoulos
Christou
Christy
Chriswell
Chritton
Chroman
Chrones
Chronis
Chronister
Chrosniak
Chrostowski
Chruch
Chrusciel
Chrysler
Chryst
Chrystal
Chrzan
Chrzanowski
Chu
Chua
Chuang
Chuba
Chubb
Chubbs
Chubbuck
Chubicks
Chuc
Chuck
Chudej
Chudy
Chudzik
Chudzinski
Chueng
Chugg
Chuh
Chui
Chukes
Chukri
Chulla
Chum
Chuma
Chumbler
Chumbley
Chumley
Chun
Chung
Chunn
Chuong
Chupik
Chupka
Chupp
Chuppa
Chura
Churan
Churape
Church
Churches
Churchfield
Churchill
Churchman
Churchville
Churchwell
Churley
Churn
Churner
Chustz
Chuta
Chute
Chuyangher
Chvilicek
Chwalek
Chwieroth
Chy
Chyle
Chynoweth
Ciaburri
Ciaccia
Ciaccio
Ciafardoni
Ciaffone
Ciak
Cialella
Ciallella
Ciampa
Ciampanella
Ciampi
Cianchetti
Cianci
Ciancio
Cianciola
Cianciolo
Cianciotta
Cianciulli
Cianflone
Cianfrani
Cianfrini
Ciani
Ciano
Ciaramitaro
Ciardullo
Ciarlante
Ciarletta
Ciarlo
Ciarrocchi
Ciaschi
Ciavardini
Cibik
Ciborowski
Cibrian
Cibula
Cibulskas
Cicala
Cicale
Cicalese
Cicali
Cicarella
Cicatello
Ciccarelli
Ciccarello
Ciccarone
Cicchetti
Cicciarelli
Cicco
Ciccolini
Ciccone
Cicconi
Cicen
Cicerchia
Cicerelli
Cicero
Cichocki
Cichon
Cichonski
Cichosz
Cichowski
Cichy
Cicio
Cicione
Ciciora
Cicora
Cicoria
Cid
Cidre
Ciejka
Cieloha
Cieloszyk
Cienega
Cienfuegos
Cieri
Cierley
Cierpke
Ciers
Ciersezwski
Ciervo
Ciesco
Ciesielski
Ciesiolka
Ciesla
Cieslak
Cieslik
Cieslinski
Ciesluk
Cieszynski
Cifaldi
Cifelli
Cifuentes
Ciganek
Cihak
Cihon
Cilano
Cilek
Cilenti
Cilento
Cilfone
Ciliberto
Cilibrasi
Ciliento
Cilley
Cillis
Cillo
Cills
Cilva
Cima
Cimaglia
Cimeno
Cimiano
Ciminera
Cimini
Cimino
Cimko
Cimmino
Cimmiyotti
Cimo
Cimorelli
Cina
Cinadr
Cinalli
Cinar
Cinco
Cincotta
Cindrich
Cinelli
Cini
Cink
Cinkan
Cinkosky
Cinnamon
Cinnamond
Cinotti
Cinotto
Cinquanti
Cinque
Cintora
Cintra
Cintron
Ciocca
Cioffi
Ciolek
Ciolli
Cione
Cioni
Cioppa
Ciotta
Ciotti
Cipcic
Cipkowski
Cipolla
Cipollone
Cipolloni
Cipolone
Cippina
Cipponeri
Ciprian
Cipriani
Cipriano
Cipro
Cipullo
Cira
Ciraco
Ciraolo
Ciraulo
Circelli
Circle
Cirella
Cirelli
Ciresi
Ciriaco
Ciriello
Cirigliano
Cirilli
Cirillo
Cirilo
Cirino
Cirioni
Cirocco
Cirone
Cirri
Cirrincione
Cirullo
Cisar
Cisco
Cisewski
Ciskowski
Cislo
Cisnero
Cisneros
Cisneroz
Cisney
Cisowski
Cissel
Cissell
Cistrunk
Citarella
Citino
Citizen
Cito
Citrano
Citrin
Citrino
Citro
Citron
Citrone
Citroni
Cittadini
Cittadino
City
Ciubal
Ciucci
Ciuffreda
Ciufo
Ciulla
Ciullo
Cius
Civale
Civatte
Civcci
Civiello
Civil
Civils
Civitello
Cizek
Claar
Claassen
Clabaugh
Clabo
Claborn
Clabough
Claburn
Clacher
Clack
Claes
Claessens
Claeys
Claffey
Claflin
Clagett
Clagg
Claggett
Claghorn
Clagon
Clague
Claiborne
Clain
Clair
Clairday
Claire
Clairmont
Clakley
Clam
Claman
Clammer
Clamp
Clampett
Clampitt
Clan
Clance
Clancey
Clancy
Clanin
Clankscales
Clanton
Clantz
Clap
Clapham
Clapp
Clapper
Clapsaddle
Clar
Clara
Clarbour
Clardy
Clare
Clarenbach
Clarence
Clarendon
Clarey
Clarida
Claridge
Clarity
Clark
Clarke
Clarkin
Clarks
Clarkson
Clarkston
Clarno
Claro
Claros
Clarson
Clary
Clas
Clasby
Clase
Clasen
Clason
Class
Classen
Classon
Clater
Claton
Clattenburg
Clatterbuck
Claucherty
Claud
Claude
Claudio
Claughton
Claunch
Claus
Clause
Clausel
Clausell
Clausen
Clausi
Clausing
Clauson
Clauss
Claussen
Clavelle
Claverie
Clavette
Clavey
Clavijo
Clavin
Claw
Clawges
Clawson
Claxton
Clay
Claybaugh
Claybon
Clayborn
Clayborne
Claybourn
Claybourne
Claybron
Claybrook
Claybrooks
Clayburg
Clayburn
Claycamp
Claycomb
Clayman
Claypole
Claypool
Claypoole
Clayson
Clayter
Clayton
Claytor
Claywell
Cleal
Cleamons
Clear
Cleare
Cleark
Clearman
Clearo
Clearwater
Cleary
Cleasby
Cleath
Cleaveland
Cleavenger
Cleaver
Cleaves
Cleckler
Cleckley
Cleckner
Cleek
Cleere
Clegg
Cleghorn
Cleland
Clelland
Clem
Clemans
Clemen
Clemence
Clemens
Clemenson
Clement
Clemente
Clementi
Clements
Clemenza
Clemmens
Clemments
Clemmer
Clemmey
Clemmo
Clemmon
Clemmons
Clemo
Clemon
Clemons
Clemson
Clendaniel
Clendenen
Clendenin
Clendening
Clendennen
Clendenon
Clenney
Clennon
Clepper
Cler
Clerc
Clerf
Clerico
Clerk
Clerkley
Clermont
Clery
Clesca
Clesen
Clester
Cleve
Cleveland
Cleven
Clevenger
Clever
Cleverley
Cleverly
Clevette
Clevinger
Clevland
Clewell
Clewes
Clewis
Cliatt
Clibon
Cliburn
Cliche
Click
Clickner
Client
Cliett
Cliff
Cliffe
Clifford
Cliffton
Clift
Clifton
Climer
Climes
Clinard
Clinch
Cline
Clinebell
Clineman
Clines
Clingan
Clingenpeel
Clinger
Clingerman
Clingingsmith
Clingman
Clink
Clinkenbeard
Clinker
Clinkinbeard
Clinkingbeard
Clinkscale
Clinkscales
Clint
Clinton
Clipp
Clippard
Clipper
Clippinger
Clise
Clish
Clisham
Clites
Clive
Clizbe
Clock
Clodfelter
Cloe
Cloepfil
Cloer
Cloffi
Clogston
Cloke
Clokey
Clolinger
Cloman
Clonch
Cloney
Cloninger
Clonts
Clontz
Cloonan
Cloos
Clopp
Clopper
Clopton
Clore
Clos
Close
Closey
Closovschi
Closs
Closser
Clossin
Closson
Closter
Clothey
Clothier
Clouatre
Cloud
Clouden
Clough
Clougher
Clougherty
Cloughly
Clouse
Clouser
Clouston
Clouthier
Cloutier
Cloutman
Clover
Clovis
Clow
Cloward
Clowdus
Clower
Clowerd
Clowers
Clowes
Clowney
Clowser
Cloyd
Clozza
Clubb
Clubbs
Clubs
Clucas
Cluck
Cluckey
Cluesman
Cluff
Clugston
Clukey
Clukies
Clum
Clumpner
Clune
Clunes
Clunie
Clure
Clusky
Cluster
Clute
Clutter
Clutts
Cluver
Cluxton
Cly
Clyatt
Clyburn
Clyde
Clyman
Clymer
Clymore
Clyne
Clynes
Cmiel
Co
Coach
Coache
Coachman
Coachys
Coad
Coady
Coak
Coaker
Coakley
Coale
Coalson
Coalter
Coan
Coant
Coar
Coard
Coarsey
Coast
Coaster
Coate
Coates
Coatie
Coatley
Coatney
Coats
Coatsworth
Coaxum
Cobane
Cobar
Cobarrubias
Cobb
Cobbett
Cobbin
Cobbins
Cobble
Cobbley
Cobbs
Cobden
Cobell
Coberley
Coberly
Cobern
Cobert
Cobetto
Cobey
Cobham
Cobia
Cobian
Cobine
Cobio
Coble
Coblentz
Cobler
Cobo
Cobos
Cobourn
Cobrin
Coburn
Coby
Coca
Cocanougher
Cocca
Coccia
Cocco
Coccoli
Coch
Cochell
Cochenour
Cocherell
Cochis
Cochran
Cochrane
Cochren
Cochron
Cochrum
Cockayne
Cockburn
Cocke
Cocker
Cockerell
Cockerham
Cockerhan
Cockerill
Cockett
Cockey
Cockfield
Cocking
Cockley
Cocklin
Cockman
Cockram
Cockran
Cockreham
Cockrel
Cockrell
Cockriel
Cockrill
Cockrin
Cockroft
Cockrum
Cocks
Coco
Cocola
Cocomazzi
Cocopoti
Cocoran
Cocoros
Cocozza
Cocran
Cocroft
Cocuzza
Cocuzzo
Coda
Coday
Codd
Codde
Codding
Coddington
Code
Codell
Codeluppi
Coder
Codere
Coderre
Codey
Codilla
Codispot
Codispoti
Codling
Codner
Cody
Coe
Coelho
Coello
Coen
Coenen
Coerver
Cofer
Coffee
Coffel
Coffell
Coffelt
Coffen
Coffer
Coffey
Coffie
Coffield
Coffill
Coffin
Coffinberger
Coffland
Coffman
Cofield
Cofone
Cofran
Cofrancesco
Cofresi
Cogan
Cogar
Cogbill
Cogburn
Cogdell
Cogdill
Cogen
Coger
Coggan
Coggeshall
Coggin
Coggins
Coggsdale
Coghill
Coghlan
Cogill
Cogley
Cogliano
Cogswell
Cohagan
Cohan
Cohea
Cohee
Cohen
Cohenour
Cohens
Cohick
Cohill
Cohlmia
Cohn
Coho
Cohoe
Cohoon
Cohran
Cohron
Cohrs
Coia
Coil
Coile
Coin
Coiner
Coins
Coiro
Coit
Coke
Cokel
Cokeley
Cokely
Coker
Cokins
Cokley
Coklow
Cola
Colabella
Colabrese
Colace
Colacone
Coladonato
Colafrancesco
Colagiovanni
Colaiacovo
Colaianni
Colaizzi
Colaizzo
Colaluca
Colamarino
Colan
Colander
Colanero
Colangelo
Colantonio
Colantro
Colantuono
Colao
Colapietro
Colapinto
Colar
Colarossi
Colarusso
Colas
Colasacco
Colasamte
Colasante
Colasanti
Colasuonno
Colasurdo
Colato
Colatruglio
Colavito
Colaw
Colbath
Colbaugh
Colbeck
Colbenson
Colberg
Colbert
Colbeth
Colborn
Colburn
Colby
Colchado
Colcher
Colclasure
Colclough
Colcord
Colden
Colder
Colding
Coldiron
Coldivar
Coldren
Coldsmith
Coldwell
Cole
Colebank
Colebrook
Colecchi
Colee
Colegrove
Colehour
Colella
Colello
Coleman
Colemen
Colemon
Colen
Coler
Coles
Colesar
Coleson
Colestock
Coletta
Coletti
Coley
Colfer
Colflesh
Colford
Colgan
Colgate
Colgin
Colglazier
Colgrove
Colian
Colicchio
Colier
Colin
Colina
Colindres
Colinger
Colins
Colker
Coll
Colla
Collaco
Collado
Collaer
Collamore
Collar
Collard
Collari
Collazo
Colle
Collea
Colledge
Colleen
College
Collella
Collelo
Collen
Coller
Colleran
Collet
Collett
Colletta
Collette
Colletti
Colley
Colli
Collica
Collick
Collicott
Collie
Collier
Colligan
Collin
Colling
Collings
Collingsworth
Collington
Collingwood
Collini
Collins
Collinson
Collinsworth
Collis
Collison
Collister
Colliver
Collman
Collmeyer
Collom
Collon
Collons
Collopy
Collora
Collova
Collozo
Collum
Collums
Collura
Colly
Collyer
Collymore
Colman
Colmenares
Colmenero
Colmer
Coln
Colo
Cologie
Colom
Coloma
Colomb
Colomba
Colombe
Colombini
Colombo
Colomy
Colon
Colona
Colondres
Colone
Colonel
Colonna
Colonnese
Colony
Colop
Colopy
Colorado
Colorina
Colosi
Colosimo
Colp
Colpa
Colpack
Colpaert
Colpetzer
Colpi
Colpitts
Colquitt
Colsch
Colschen
Colson
Colston
Colt
Colten
Colter
Coltey
Coltharp
Coltman
Colton
Coltrain
Coltrane
Coltrin
Colucci
Coluccio
Columbia
Columbo
Columbres
Columbus
Colunga
Colvard
Colver
Colvert
Colville
Colvin
Colwell
Colyar
Colyer
Colyott
Coma
Comacho
Coman
Comans
Comar
Comas
Combass
Combe
Combee
Comber
Combes
Combest
Comboy
Combs
Comden
Come
Comeau
Comeaux
Comeauy
Comee
Comegys
Comella
Comer
Comerford
Comes
Comfort
Comings
Cominotti
Comins
Cominski
Cominsky
Comish
Comiskey
Comisky
Comiso
Comissiong
Comito
Comley
Comly
Commander
Commendatore
Comment
Commer
Commerford
Commes
Commings
Commins
Commiskey
Commodore
Common
Commons
Comnick
Como
Comoletti
Comp
Compagna
Compagno
Companie
Companion
Comparoni
Compau
Compean
Compeau
Compere
Compher
Compiseno
Compo
Compono
Compos
Compres
Compston
Compton
Comrey
Comrie
Comstock
Comtois
Comunale
Conable
Conaghan
Conales
Conant
Conard
Conary
Conatser
Conaty
Conaughty
Conaway
Conboy
Conca
Concannon
Concatelli
Conceicao
Concepcion
Concepion
Conception
Conces
Conch
Concha
Conchado
Conchas
Concho
Concienne
Concilio
Concini
Conda
Conde
Condelario
Condell
Condello
Conder
Condi
Condict
Condie
Condiff
Condina
Condino
Condit
Conditt
Condo
Condon
Condra
Condray
Condreay
Condren
Condrey
Condron
Condroski
Condry
Conduff
Cone
Conedy
Conejo
Conell
Conelli
Conelly
Conely
Coner
Conerly
Conery
Cones
Coneway
Coney
Coneys
Confair
Confalone
Confer
Conforme
Conforti
Conforto
Confrey
Cong
Congdon
Conger
Congleton
Congo
Congress
Congrove
Conigliaro
Coniglio
Conine
Conkel
Conkey
Conkin
Conkle
Conklin
Conkling
Conkright
Conkrite
Conkwright
Conlan
Conlans
Conlee
Conley
Conliffe
Conlin
Conlisk
Conlogue
Conlon
Conly
Conmy
Conn
Connally
Connard
Connarton
Connaughton
Connealy
Conneely
Connel
Connell
Connelley
Connelly
Connely
Conner
Connerat
Connerley
Connerly
Conners
Connerton
Connerty
Connery
Conness
Connet
Connett
Connette
Conney
Connick
Connie
Conniff
Connin
Conninghan
Connington
Connley
Connole
Connolly
Connoly
Connon
Connor
Connors
Connyer
Conole
Conoley
Conolly
Conoly
Conorich
Conour
Conover
Conquest
Conrad
Conradi
Conradt
Conrady
Conran
Conrath
Conrod
Conrow
Conroy
Conry
Cons
Consalvo
Consentino
Conser
Considine
Consigli
Consiglio
Consla
Consolazio
Console
Consoli
Consolini
Consolo
Consolver
Consorti
Constable
Constance
Constancio
Constant
Constante
Constantin
Constantine
Constantineau
Constantini
Constantino
Constanza
Constanzo
Constine
Consuegra
Consuelo
Conte
Contee
Conteh
Contento
Conteras
Conterras
Contes
Conti
Continenza
Contini
Contino
Contofalsky
Contois
Contopoulos
Contorno
Contos
Contraras
Contras
Contratto
Contreas
Contrell
Contrenas
Contrera
Contreras
Contreraz
Contreres
Contreros
Contrerras
Contrino
Conveniencia
Conver
Converse
Convery
Conville
Conway
Conwell
Conwill
Conwright
Conyer
Conyers
Conzales
Conzalez
Conze
Conzemius
Cooch
Coodey
Coody
Cooey
Coogan
Coogen
Cook
Cooke
Cookerly
Cookey
Cookingham
Cookis
Cookman
Cooks
Cooksey
Cooksley
Cookson
Cookus
Cool
Coolahan
Coolbaugh
Coolbeth
Coolbrith
Cooler
Cooley
Coolidge
Coolman
Cools
Coombe
Coomber
Coombes
Coombs
Coomer
Coomes
Coomey
Coon
Coonan
Coonce
Coone
Cooner
Coones
Cooney
Coonfare
Coonfield
Coonley
Coonrad
Coonradt
Coonrod
Coons
Coonse
Coontz
Coop
Coopage
Cooper
Cooperider
Cooperman
Cooperrider
Coopersmith
Cooperstein
Cooperwood
Coopey
Coopper
Coopwood
Coor
Coore
Coote
Cooter
Coots
Coover
Coovert
Copa
Copas
Copass
Cope
Copelan
Copeland
Copelin
Copeman
Copen
Copenhaver
Copening
Copes
Copher
Copier
Coplan
Copland
Coplen
Coples
Copley
Coplin
Coplon
Copney
Coponen
Copp
Coppa
Coppage
Coppedge
Coppenger
Coppens
Copper
Coppernoll
Coppersmith
Coppes
Coppess
Coppin
Copping
Coppinger
Copple
Coppler
Coppock
Coppola
Coppolino
Copps
Copsey
Copstead
Copus
Cora
Coradi
Corado
Coraham
Corak
Coral
Corallo
Coram
Coran
Corathers
Coray
Corazza
Corban
Corbeil
Corbell
Corbelli
Corbet
Corbett
Corbi
Corbin
Corbisiero
Corbit
Corbitt
Corbley
Corbo
Corbridge
Corburn
Corby
Corchado
Corchero
Corcino
Corcoran
Corcuera
Cord
Corda
Cordano
Cordaro
Cordas
Cordasco
Corde
Cordeiro
Cordel
Cordell
Cordenas
Corder
Corderman
Cordero
Cordes
Cordew
Cordia
Cordial
Cordier
Cordiero
Cordill
Cordle
Cordner
Cordoba
Cordon
Cordona
Cordone
Cordonnier
Cordoua
Cordova
Cordovano
Cordovi
Cordoza
Cordray
Cordrey
Cords
Cordts
Cordwell
Cordy
Core
Corea
Coreas
Coreen
Coreil
Corell
Corella
Corelli
Coren
Coressel
Corey
Corf
Corfman
Corgan
Corgiat
Coria
Coriano
Coriaty
Coric
Corid
Coriell
Corigliano
Corin
Corington
Corino
Corio
Corippo
Corish
Coriz
Cork
Corke
Corker
Corkern
Corkery
Corkill
Corkins
Corkran
Corkron
Corkum
Corl
Corle
Corlee
Corless
Corlett
Corlew
Corley
Corliss
Cormack
Corman
Cormany
Cormia
Cormican
Cormier
Corn
Corna
Cornacchio
Corne
Cornea
Corneau
Corneil
Corneille
Cornejo
Cornelia
Cornelio
Cornelious
Cornelison
Cornelius
Cornell
Cornella
Cornelson
Corneluis
Cornely
Corner
Corners
Cornes
Cornet
Cornett
Cornetta
Cornette
Corney
Cornfield
Cornford
Cornforth
Cornick
Corniel
Corning
Cornish
Cornman
Cornmesser
Cornn
Cornog
Corns
Cornutt
Cornwall
Cornwell
Coro
Corolis
Corolla
Coron
Corona
Coronado
Coronel
Coroniti
Corp
Corpe
Corpening
Corpeno
Corping
Corporal
Corporan
Corporon
Corprew
Corpus
Corpuz
Corr
Corra
Corradini
Corradino
Corrado
Corral
Corrales
Corrao
Corraro
Corre
Correa
Correale
Correau
Corredor
Correia
Correira
Correiro
Correl
Correla
Correll
Corren
Corrente
Correo
Correra
Correro
Corrett
Correy
Corrga
Corria
Corrice
Corrick
Corridan
Corridoni
Corrie
Corriere
Corrieri
Corrigan
Corrigeux
Corriher
Corrington
Corrio
Corrion
Corriveau
Corron
Corrow
Corry
Corsa
Corsaro
Corsaut
Corscadden
Corse
Corsello
Corseri
Corsetti
Corsey
Corsi
Corsilles
Corsini
Corsino
Corso
Corson
Corsoro
Cort
Corte
Corter
Cortes
Cortese
Cortesi
Cortez
Corti
Cortijo
Cortina
Cortinas
Cortinez
Cortis
Cortner
Corton
Cortopassi
Cortright
Cortwright
Corujo
Corum
Corvan
Corvelli
Corvera
Corvi
Corvin
Corvino
Corvo
Corwell
Corwin
Cory
Coryea
Coryell
Corza
Corzine
Corzo
Cos
Cosano
Cosby
Cosca
Coscia
Cosden
Cose
Cosen
Cosentino
Cosenza
Cosey
Cosgrave
Cosgray
Cosgriff
Cosgrove
Coshow
Cosico
Cosier
Cosimini
Cosio
Coskey
Coskrey
Coslan
Coslett
Cosley
Coslow
Cosma
Cosman
Cosme
Cosmo
Cosner
Cosper
Coss
Cossa
Cossaboom
Cossaboon
Cossairt
Cossano
Cossel
Cossell
Cosselman
Cossett
Cossette
Cossey
Cossin
Cossio
Cost
Costa
Costabile
Costagliola
Costain
Costales
Costaneda
Costantini
Costantino
Costanza
Costanzi
Costanzo
Costas
Coste
Costeira
Costell
Costella
Costello
Costellowo
Costen
Costenive
Coster
Costigan
Costilla
Costillo
Costilow
Costin
Costine
Costley
Costlow
Costner
Coston
Coswell
Cota
Cotant
Cote
Coteat
Cotelesse
Cotey
Cotham
Cother
Cotheran
Cotherman
Cothern
Cothran
Cothren
Cothron
Cotilla
Cotillo
Cotler
Cotman
Cotner
Cotney
Cotnoir
Coto
Coton
Cotreau
Cotrell
Cotrone
Cotroneo
Cotsis
Cott
Cotta
Cottam
Cotten
Cottengim
Cotter
Cotterell
Cotterman
Cottew
Cotti
Cottier
Cottillion
Cottingham
Cottle
Cottman
Cotto
Cottom
Cotton
Cottone
Cottongim
Cottrell
Cottrill
Cotty
Cotugno
Coty
Couch
Couchenour
Couchman
Couden
Coudriet
Couey
Coufal
Cough
Coughenour
Coughlan
Coughlin
Coughran
Couillard
Coulas
Coulbourne
Couley
Coulibaly
Coull
Coullard
Coulombe
Coulon
Coulson
Coulston
Coult
Coultas
Coulter
Coulthard
Coultrap
Counce
Counceller
Council
Councill
Councilman
Counihan
Counselman
Countee
Counter
Counterman
Countess
Countis
Countryman
Counts
Coup
Coupe
Couper
Coupland
Courcelle
Courchene
Courchesne
Courchine
Courcy
Couret
Courey
Courie
Courier
Courington
Courneya
Cournoyer
Couron
Courrege
Course
Courseault
Courser
Coursey
Courson
Court
Courtad
Courteau
Courtemanche
Courtenay
Courter
Courtnage
Courtney
Courtois
Courton
Courtoy
Courtright
Courts
Courtway
Courtwright
Courville
Coury
Cousain
Cousar
Couse
Cousens
Couser
Cousey
Cousin
Cousineau
Cousino
Cousins
Coutant
Coutch
Coutcher
Coutee
Coutermarsh
Coutinho
Coutino
Couto
Coutre
Couts
Coutts
Coutu
Couture
Couturier
Couty
Couvertier
Couvillier
Couvillion
Couzens
Cova
Coval
Covalt
Covar
Covarrubia
Covarrubias
Covarrubio
Covarruvia
Cove
Covel
Covell
Covelli
Covello
Coven
Coveney
Coventon
Coventry
Cover
Coverdale
Coverdell
Coverstone
Covert
Coverton
Covey
Coviello
Covil
Covill
Coville
Covin
Covington
Covino
Covitt
Covitz
Covone
Covotta
Cowan
Cowans
Coward
Cowart
Cowboy
Cowden
Cowder
Cowdery
Cowdin
Cowdrey
Cowee
Cowell
Cowels
Cowen
Cowens
Cower
Cowett
Cowger
Cowgill
Cowher
Cowherd
Cowick
Cowie
Cowin
Cowing
Cowles
Cowley
Cowlin
Cowling
Cowman
Cowns
Cowper
Cowser
Cowsert
Cox
Coxe
Coxen
Coxey
Coxon
Coxum
Coxwell
Coy
Coyan
Coyazo
Coyco
Coye
Coyer
Coyier
Coykendall
Coyle
Coyne
Coyner
Coyt
Cozad
Cozadd
Cozart
Cozby
Cozier
Cozine
Cozort
Cozza
Cozzens
Cozzi
Cozzolino
Cozzone
Cozzy
Craan
Craawford
Crabb
Crabbe
Crabbs
Crabill
Crable
Crabtree
Cracas
Cracchiolo
Crace
Cracknell
Cracolici
Cracraft
Craddieth
Craddock
Cradduck
Crader
Cradic
Cradle
Cradler
Crady
Craffey
Crafford
Craft
Crafter
Crafton
Crafts
Cragan
Cragar
Crager
Cragg
Craghead
Cragin
Cragle
Crago
Cragun
Craib
Craig
Craige
Craigen
Craiger
Craighead
Craigmiles
Craigmyle
Craigo
Craigue
Craigwell
Crail
Crain
Craine
Craker
Crall
Cram
Cramblet
Cramblit
Cramer
Cramm
Cramp
Crampton
Cran
Crance
Crandal
Crandall
Crandell
Crandle
Crane
Craner
Craney
Cranfield
Cranfill
Cranford
Crank
Cranker
Crankshaw
Cranmer
Cranmore
Crannell
Cranney
Cranor
Crans
Cranshaw
Cranson
Cranston
Crantz
Crapanzano
Crape
Crapo
Crapp
Crapps
Crapse
Crapser
Crary
Crasco
Crase
Crask
Crass
Cratch
Crate
Crater
Crathers
Cratic
Cratin
Cration
Craton
Cratty
Craun
Crauswell
Cravalho
Cravatta
Craveiro
Craven
Cravenho
Cravens
Craver
Cravey
Cravy
Craw
Crawford
Crawhorn
Crawley
Crawmer
Crawn
Crawshaw
Cray
Craycraft
Crayford
Crayne
Crays
Crayton
Craze
Crazier
Crea
Creach
Creacy
Creager
Creagh
Creamer
Crean
Crear
Creary
Crease
Creaser
Creasey
Creasman
Creason
Creasy
Creath
Crebs
Crecco
Crecelius
Credell
Credeur
Credi
Credille
Credit
Credle
Credo
Cree
Creech
Creecy
Creed
Creeden
Creedon
Creegan
Creehan
Creek
Creekbaum
Creekmore
Creekmur
Creeks
Creel
Creeley
Creenan
Creer
Creese
Cregan
Cregar
Cregeen
Creger
Cregger
Creggett
Cregin
Creglow
Crego
Crehan
Creighton
Creitz
Crelia
Crellin
Cremar
Cremeans
Cremeens
Cremer
Cremers
Cremin
Cremins
Cremona
Cremonese
Crenshaw
Crenwelge
Crepeau
Crepps
Creps
Creque
Crescenti
Crescenzo
Cresci
Creselious
Cresencio
Creson
Crespi
Crespin
Crespino
Crespo
Cress
Cressell
Cressey
Cressman
Cresswell
Cressy
Crest
Cresta
Cresto
Creswell
Crete
Cretella
Creten
Cretsinger
Creveling
Crevier
Creviston
Crew
Crewe
Crews
Criado
Cribari
Cribb
Cribbin
Cribbs
Criblez
Crichlow
Crichton
Crick
Crickard
Crickenberger
Crickmore
Criddle
Crider
Cridge
Cridland
Crieghton
Crier
Criger
Crigger
Crighton
Crigler
Criley
Crill
Crilly
Crim
Crimes
Crimi
Crimin
Crimmins
Crincoli
Criner
Cring
Cringle
Crinklaw
Cripe
Crippen
Crippin
Cripps
Criqui
Crisafi
Crisafulli
Crisalli
Crisan
Crisanti
Crisci
Criscillis
Criscione
Crisco
Criscuolo
Crise
Crisler
Crislip
Crisman
Crismon
Crismond
Crisostomo
Crisp
Crispell
Crispen
Crispin
Crispino
Crispo
Criss
Crissey
Crissinger
Crissler
Crissman
Crisson
Crist
Cristal
Cristaldi
Cristales
Criste
Cristelli
Cristello
Cristiano
Cristina
Cristino
Cristo
Cristobal
Cristofaro
Cristofori
Cristy
Criswell
Critchelow
Critcher
Critchfield
Critchley
Critchlow
Critelli
Crites
Criton
Crittenden
Crittendon
Crittle
Critton
Critz
Critzer
Critzman
Crivaro
Crivelli
Crivello
Crnich
Crnkovich
Croak
Croan
Croasmun
Crocco
Croce
Crocetti
Crochet
Crocitto
Crock
Crockarell
Crocker
Crocket
Crockett
Crockette
Crockwell
Croes
Croff
Croffie
Crofford
Crofoot
Croft
Crofton
Crofts
Crofutt
Crogan
Croghan
Crogier
Crognale
Croissant
Croke
Croker
Croley
Croll
Crolley
Crom
Cromack
Croman
Cromartie
Crombie
Crome
Cromeans
Cromedy
Cromeens
Cromer
Cromey
Cromie
Cromley
Crompton
Cromuel
Cromwell
Cron
Cronan
Cronauer
Cronce
Crone
Cronenberg
Croner
Croney
Cronholm
Cronic
Cronin
Cronk
Cronkhite
Cronkite
Cronoble
Cronon
Cronquist
Cronshaw
Cronwell
Crook
Crooke
Crooked
Crooker
Crookes
Crooks
Crookshank
Crookshanks
Crookston
Croom
Crooms
Croon
Cropley
Cropp
Cropper
Cropsey
Crosbie
Crosby
Crosdale
Crose
Croshaw
Crosiar
Crosier
Croskey
Crosland
Croslen
Crosley
Croslin
Crosman
Crosno
Croson
Cross
Crossan
Crossen
Crosser
Crossett
Crossfield
Crossgrove
Crossin
Crossland
Crossley
Crosslin
Crossman
Crossmon
Crossno
Crosson
Crosswell
Crosswhite
Crosten
Crosthwaite
Croston
Croswell
Croteau
Crother
Crothers
Crotteau
Crotts
Crotty
Crotwell
Crotzer
Crouch
Croucher
Crouchet
Crough
Crounse
Crouse
Crouser
Croushorn
Crousore
Crout
Croutch
Crouter
Crouthamel
Crover
Crovo
Crow
Crowden
Crowder
Crowdis
Crowe
Crowell
Crowers
Crowford
Crowin
Crowl
Crowley
Crown
Crowner
Crownover
Crowson
Crowston
Crowther
Crowthers
Croxen
Croxford
Croxton
Croy
Croyle
Crozat
Crozier
Cruce
Cruden
Crudo
Crudup
Cruea
Cruel
Cruell
Cruey
Cruff
Cruice
Cruickshank
Cruikshank
Cruise
Cruiz
Crull
Crum
Crumb
Crumble
Crumbley
Crumbliss
Crumbly
Crumby
Crume
Crumedy
Crumley
Crumlish
Crumly
Crumm
Crummedyo
Crummell
Crummett
Crummey
Crummie
Crummitt
Crump
Crumpacker
Crumpler
Crumpton
Crumrine
Crumwell
Crunk
Crunkilton
Crunkleton
Crupe
Crupi
Crupper
Crusan
Cruse
Cruser
Crusinberry
Crusoe
Cruson
Crutch
Crutcher
Crutchev
Crutchfield
Crutchley
Crute
Cruther
Cruthers
Cruthird
Cruthirds
Crutison
Crutsinger
Cruz
Cruzado
Cruzan
Cruze
Cruzen
Cryan
Cryar
Cryder
Cryderman
Crye
Cryer
Crysler
Crystal
Crytser
Crytzer
Csaszar
Csensich
Cser
Csizmadia
Csubak
Csuhta
Cua
Cuadra
Cuadrado
Cuadras
Cuadro
Cuadros
Cuaresma
Cuartas
Cuascut
Cuba
Cubano
Cubas
Cubbage
Cubbison
Cubero
Cubeta
Cubias
Cubie
Cubillo
Cubine
Cubit
Cubito
Cubr
Cuccaro
Cucchiara
Cucchiaro
Cuccia
Cuccinello
Cucco
Cuch
Cuchares
Cuchiara
Cucinella
Cucino
Cucinotta
Cuckler
Cucufate
Cuculich
Cucuta
Cucuzza
Cucvas
Cuda
Cudan
Cudd
Cuddeback
Cuddihee
Cuddington
Cuddy
Cude
Cudjoe
Cudmore
Cudney
Cudworth
Cue
Cuebas
Cuellar
Cuello
Cuen
Cuenca
Cuervo
Cuesta
Cuestas
Cueto
Cueva
Cuevas
Cuez
Cuff
Cuffari
Cuffe
Cuffee
Cuffia
Cuffie
Cuffman
Cuffy
Cugini
Cuhel
Cui
Cuizon
Cujas
Cukaj
Culajay
Culberson
Culbert
Culberth
Culbertson
Culbreath
Culbreth
Culcasi
Culhane
Culkin
Cull
Cullar
Cullars
Cullen
Cullens
Culler
Cullers
Culleton
Culley
Cullifer
Culligan
Cullin
Cullinan
Cullinane
Cullins
Cullip
Cullison
Culliton
Cullity
Cullivan
Culliver
Cullom
Cullop
Culloton
Cullum
Cully
Culmer
Culnane
Culotta
Culotti
Culp
Culpepper
Culpit
Cultice
Culton
Culver
Culverhouse
Culverson
Culwell
Cumba
Cumbaa
Cumbass
Cumbee
Cumber
Cumberbatch
Cumberland
Cumberlander
Cumberledge
Cumbie
Cumblidge
Cumbo
Cumby
Cumens
Cumings
Cumins
Cumiskey
Cumley
Cummer
Cumming
Cummingham
Cummings
Cummins
Cummiskey
Cummisky
Cumoletti
Cumpston
Cumpton
Cun
Cuna
Cunanan
Cunard
Cunas
Cundick
Cundiff
Cundy
Cuneio
Cuneo
Cung
Cunha
Cunico
Cuningham
Cunio
Cunis
Cunliffe
Cunnane
Cunneen
Cunnick
Cunniff
Cunniffe
Cunnigham
Cunning
Cunningan
Cunningham
Cunninghan
Cunnington
Cuny
Cuoco
Cuomo
Cuozzo
Cupe
Cupelli
Cuperus
Cupit
Cupp
Cuppernell
Cuppett
Cupples
Cupps
Cupstid
Cura
Curameng
Curatolo
Curb
Curbeam
Curbelo
Curbo
Curbow
Curboy
Curby
Curci
Curcio
Curcuru
Curd
Curdy
Cure
Cureau
Curella
Curenton
Curet
Cureton
Curey
Curfman
Curi
Curia
Curie
Curiel
Curimao
Curington
Curio
Curit
Curl
Curle
Curlee
Curles
Curless
Curley
Curleyhair
Curlin
Curling
Curlis
Curll
Curls
Curly
Curney
Curnow
Curnutt
Curnutte
Curo
Curpupoz
Curra
Curran
Currans
Currell
Curren
Currence
Currens
Current
Curreri
Currey
Currie
Currier
Curriere
Currin
Currington
Curro
Curry
Curson
Curt
Curtice
Curtin
Curtis
Curtiss
Curtner
Curto
Curts
Curtsinger
Curvey
Curvin
Curylo
Curz
Curzi
Cusack
Cusanelli
Cusano
Cusatis
Cusenza
Cush
Cushard
Cushen
Cushenberry
Cusher
Cushinberry
Cushing
Cushingberry
Cushman
Cushner
Cushwa
Cushway
Cusic
Cusick
Cusimano
Cusmano
Cussen
Cussins
Cusson
Custa
Custance
Custard
Custeau
Custer
Custis
Custodio
Cusumano
Cusworth
Cutaia
Cutbirth
Cutburth
Cutchall
Cutchember
Cutcher
Cutchin
Cutchins
Cutforth
Cuthbert
Cuthbertson
Cuther
Cuthill
Cuthrell
Cuti
Cutia
Cutillo
Cutler
Cutliff
Cutlip
Cutno
Cutone
Cutrell
Cutrer
Cutrera
Cutri
Cutright
Cutrona
Cutrone
Cutsforth
Cutshall
Cutshaw
Cutsinger
Cutt
Cutten
Cutter
Cutting
Cuttino
Cuttitta
Cuttler
Cutts
Cutty
Cutwright
Cuva
Cuyler
Cuzco
Cuzick
Cuzman
Cuzzi
Cuzzo
Cuzzort
Cvetkovic
Cwalinski
Cwiakala
Cwiek
Cwik
Cwikla
Cwiklinski
Cybart
Cybulski
Cychosz
Cyfers
Cygan
Cyganiewicz
Cygrymus
Cyler
Cylkowski
Cynova
Cynthia
Cypert
Cypher
Cyphers
Cyphert
Cypress
Cypret
Cyprian
Cyr
Cyran
Cyree
Cyrnek
Cyrulik
Cyrus
Cywinski
Czach
Czachor
Czachorowski
Czaja
Czajka
Czajkowski
Czap
Czapiewski
Czapla
Czaplewski
Czaplicki
Czaplinski
Czapor
Czapski
Czar
Czarkowski
Czarnecki
Czarniecki
Czarnik
Czarnota
Czarny
Czartoryski
Czech
Czechowski
Czekaj
Czekanski
Czelusniak
Czepiel
Czerkies
Czerniak
Czernik
Czerno
Czernovski
Czerwinski
Czlapinski
Czolba
Czosek
Czuba
Czubakowski
Czubia
Czupryna
Czwakiel
Czyrnik
Czysz
Czyz
Czyzewski
Dabadie
Dabato
Dabbraccio
Dabbs
Dabdoub
Dabe
Daber
Dabney
Dabrowski
Dacamara
Dacanay
Dace
Dacey
Dach
Dachelet
Dachs
Dack
Dacosta
Dacpano
Dacquel
Dacres
Dacruz
Dacunha
Dacunto
Dacus
Dacy
Daczewitz
Dad
Dada
Dadamo
Dadd
Daddabbo
Daddario
Daddea
Daddio
Daddona
Dadds
Dade
Dadey
Dadisman
Dadlani
Dado
Dadson
Dady
Dae
Daehler
Daehn
Daer
Daffern
Daffin
Daffron
Dafoe
Dafonseca
Dafonte
Daft
Dagan
Dagata
Dagdag
Dage
Dagel
Dagen
Dagenais
Dagenhart
Dager
Dagesse
Dagg
Daggett
Daggs
Daggy
Daghita
Dagis
Dagle
Dagley
Dagnan
Dagner
Dagnese
Dagnon
Dagnone
Dago
Dagon
Dagostino
Dagraca
Dagrella
Dagres
Dague
Daguerre
Daguio
Dahan
Daher
Dahill
Dahl
Dahlberg
Dahle
Dahlem
Dahlen
Dahler
Dahley
Dahlgren
Dahlhauser
Dahlheimer
Dahlin
Dahline
Dahling
Dahlka
Dahlke
Dahlman
Dahlquist
Dahlstedt
Dahlstrom
Dahm
Dahman
Dahme
Dahmen
Dahmer
Dahms
Dahn
Dahnke
Dahood
Dai
Daichendt
Daidone
Daigh
Daigle
Daignault
Daigneault
Daigre
Dail
Dailey
Dailing
Daill
Daily
Daimaru
Dain
Dainack
Daine
Dainels
Daines
Dains
Dair
Daire
Dais
Daise
Daisey
Daisley
Daisy
Daiton
Daivs
Daiz
Dajani
Dajer
Dakan
Dake
Daken
Dakes
Dakin
Daking
Dakins
Daku
Dalal
Dalaq
Dalba
Dalbec
Dalbeck
Dalbey
Dalby
Dalcour
Dale
Dalecki
Dalee
Dalegowski
Dalen
Dalenberg
Dalene
Daleo
Dalere
Dales
Dalesandro
Daleske
Dalessandro
Dalessio
Daleus
Daley
Dalfonso
Dalgleish
Dalhart
Dalhover
Dalin
Dalio
Dalitz
Daliva
Dalka
Dalke
Dall
Dalla
Dallago
Dallaire
Dallam
Dallas
Dallavalle
Dallen
Daller
Dallesandro
Dalleva
Dalley
Dallis
Dallison
Dallman
Dallmann
Dallmeyer
Dallmier
Dalluge
Dally
Dalman
Dalmata
Dalmau
Dalmida
Dalmoro
Dalo
Daloia
Daloisio
Dalomba
Dalonzo
Dalpe
Dalphonse
Dalpiaz
Dalponte
Dalporto
Dalrymple
Dalsanto
Dalton
Daltorio
Daluz
Daly
Dalzell
Dalzen
Dalziel
Dam
Dama
Daman
Damann
Damario
Damas
Damasco
Damato
Dambach
Dambakly
Damberger
Damboise
Dambra
Dambrose
Dambrosi
Dambrosia
Dambrosio
Dambrozio
Dame
Damelio
Damerell
Dameron
Dames
Damewood
Dami
Damian
Damiani
Damiano
Damico
Damien
Damis
Damm
Dammad
Dammann
Damme
Dammen
Dammeyer
Dammrich
Damms
Damon
Damone
Damore
Damoro
Damoth
Damour
Damours
Dampeer
Dampf
Damphousse
Dampier
Damrell
Damron
Damrow
Dan
Dana
Danaher
Danahy
Danas
Danby
Danca
Dancause
Dance
Dancel
Dancer
Dancey
Danchetz
Danco
Dancoes
Dancy
Danczak
Dando
Dandoy
Dandrade
Dandrea
Dandridge
Dandrow
Dandurand
Dandy
Dane
Danehy
Danek
Danekas
Daneker
Danella
Daner
Danes
Danese
Danesh
Danesi
Danfield
Danford
Danforth
Dang
Dangel
Dangelis
Dangelo
Danger
Dangerfield
Dangler
Danh
Dani
Danial
Danials
Daniel
Daniele
Danielian
Daniell
Danielle
Daniello
Danielovich
Daniels
Danielsen
Danielski
Danielson
Daniely
Danis
Danish
Danison
Danker
Dankert
Dankmeyer
Danko
Danks
Danley
Dann
Danna
Dannard
Dannatt
Dannecker
Dannelley
Dannelly
Dannels
Danneman
Dannenberg
Dannenfelser
Danner
Dannhaus
Danni
Danniels
Dannis
Danns
Dannunzio
Danny
Dano
Danoff
Danos
Danoski
Danowski
Dansbury
Dansby
Danser
Dansereau
Dansie
Danson
Dant
Dante
Dantes
Dantin
Danton
Dantoni
Dantonio
Dantos
Dantuono
Dantzler
Danuser
Danyow
Danz
Danza
Danzer
Danziger
Danzy
Dao
Daoud
Daoust
Dapas
Dapice
Dapinto
Dapolito
Daponte
Dapoz
Dapper
Daprile
Dapvaala
Daquila
Daquilante
Daquino
Daquip
Dar
Darakjian
Darakjy
Daramola
Daras
Darbeau
Darbonne
Darbouze
Darbro
Darby
Darbyshire
Darcangelo
Darcey
Darco
Darcus
Darcy
Dardagnac
Dardar
Dardashti
Darden
Dardenne
Dardis
Dardon
Dardy
Dare
Darensbourg
Darey
Darga
Dargan
Dargatz
Dargenio
Dargie
Dargin
Dargis
Dari
Daria
Dariano
Daricek
Darienzo
Daring
Darington
Dario
Daris
Darity
Darius
Darjean
Dark
Darke
Darkis
Darks
Darland
Darley
Darlin
Darling
Darlington
Darm
Darmiento
Darmody
Darnall
Darnel
Darnell
Darner
Darnick
Darnley
Darnold
Darnstaedt
Daro
Darocha
Daron
Daros
Darosa
Darou
Darr
Darracott
Darragh
Darrah
Darras
Darrell
Darrigo
Darrin
Darring
Darrington
Darrisaw
Darroch
Darron
Darrough
Darrow
Darrup
Darsch
Darsey
Darsi
Darsow
Darst
Dart
Darter
Dartez
Darthard
Darting
Dartt
Darty
Darugar
Daruszka
Darveau
Darvile
Darville
Darvin
Darvish
Darwich
Darwin
Darwish
Dary
Daryanl
Das
Dasalia
Dasch
Daschofsky
Dase
Dasen
Dasgupta
Dash
Dashem
Dasher
Dashiell
Dashnaw
Dashne
Dashner
Dashno
Dasilua
Dasilva
Dasinger
Daskal
Daskam
Dasmann
Daso
Dasouza
Dasovich
Dass
Dasso
Dassow
Daste
Dastoli
Dastrup
Datamphay
Datcher
Dates
Dathe
Datil
Datko
Dato
Datri
Datson
Datt
Datta
Datte
Dattilio
Dattilo
Datu
Datwyler
Daty
Datz
Dau
Daub
Daubendiek
Daubenmire
Daubenspeck
Dauber
Dauberman
Daubert
Daubney
Daubs
Daudelin
Daudier
Daudt
Dauenhauer
Dauer
Daufeldt
Daugaard
Dauge
Daugereau
Daughdrill
Daughenbaugh
Daugherty
Daughetee
Daughety
Daughrity
Daughters
Daughterty
Daughtery
Daughton
Daughtrey
Daughtridge
Daughtry
Dauila
Daul
Daulerio
Daulton
Daum
Daunt
Dauphin
Dauphinais
Dauria
Daurizio
Daus
Dausch
Dause
Dauster
Dauterive
Dauterman
Dauteuil
Dautremont
Dautrich
Dauzart
Dauzat
Davalos
Davance
Davanzo
Davari
Davault
Davaz
Davda
Dave
Davel
Daven
Davenport
Davensizer
Davern
Davers
Daversa
Daves
Davey
Davi
Davia
Daviau
Davich
Davick
David
Davide
Davidek
Davidian
Davidoff
Davidowicz
Davids
Davidsen
Davidsmeyer
Davidson
Davie
Davies
Davignon
Davila
Davilla
Davin
Davine
Davino
Davion
Davirro
Davis
Davise
Davison
Davisson
Davito
Davitt
Davney
Davolt
Davoren
Davos
Davtyan
Davy
Davydov
Daw
Dawahoya
Dawber
Dawdy
Dawe
Dawes
Dawkin
Dawkins
Dawley
Dawn
Dawood
Dawoud
Daws
Dawsey
Dawson
Dax
Day
Daya
Dayal
Dayan
Dayao
Daye
Dayem
Dayer
Dayhoff
Dayhuff
Daykin
Dayley
Daylong
Daymude
Dayne
Dayrit
Days
Dayton
Daywalt
Daza
Dazey
Dazi
Dazzi
Dea
Deacetis
Deacon
Deacy
Deaderick
Deadmond
Deadwyler
Deady
Deaguero
Deaguiar
Deahl
Deak
Deakin
Deakins
Deakyne
Deal
Dealba
Deale
Dealmeida
Dealy
Deamer
Dean
Deanda
Deandrade
Deane
Deaner
Deanes
Deang
Deangeles
Deangelis
Deangelo
Deangelus
Deanhardt
Deanne
Deans
Deaquino
Dear
Dearborn
Dearco
Dearcos
Dearden
Deardon
Deardorff
Deardurff
Deare
Dearin
Dearing
Dearinger
Dearman
Dearmas
Dearment
Dearmitt
Dearmon
Dearmond
Dearmore
Dearo
Dearring
Dearruda
Dears
Dearson
Dearstyne
Dearth
Deary
Deas
Dease
Deases
Deasis
Deason
Deasy
Deatherage
Deatley
Deaton
Deats
Deaver
Deavers
Deavila
Deaville
Debaca
Deback
Debacker
Debaecke
Debaets
Debar
Debarba
Debardelaben
Debarge
Debari
Debarr
Debarros
Debartolo
Debbins
Debeaumont
Debeer
Debelak
Debell
Debella
Debellis
Debello
Debem
Debenedetti
Debenedetto
Debenedictis
Debenedittis
Debenham
Deberg
Debernardi
Deberry
Debes
Debettignies
Debey
Debiase
Debiasi
Debiasio
Debien
Debiew
Deblanc
Deblase
Deblasi
Deblasio
Deblauw
Deblieck
Deblois
Debnam
Debnar
Debo
Deboard
Deboe
Deboef
Deboer
Debois
Debold
Debolt
Debona
Debonis
Debord
Deborde
Debore
Debose
Debouse
Debow
Debrae
Debraga
Debray
Debrecht
Debreto
Debrie
Debrita
Debrito
Debro
Debrock
Debrosse
Debrot
Debroux
Debruce
Debruhl
Debruin
Debruler
Debruyn
Debry
Debski
Debuhr
Debus
Debuse
Debusk
Debutiaco
Debutts
Dec
Decaen
Decaire
Decambra
Decamp
Decandia
Decaneo
Decann
Decant
Decapite
Decaprio
Decapua
Decardenas
Decardo
Decarlo
Decarmine
Decaro
Decarolis
Decarr
Decarvalho
Decasanova
Decasas
Decastro
Decato
Decatur
Dececco
Decelle
Decelles
December
Decena
Decent
Decenzo
Decesare
Dech
Dechaine
Dechambeau
Dechamplain
Dechant
Dechart
Dechavez
Dechellis
Dechert
Dechick
Dechico
Decicco
Decillis
Decinti
Decio
Decius
Deck
Deckard
Deckelbaum
Deckelman
Decker
Deckers
Deckert
Deckman
Declark
Declercq
Declerk
Declet
Declouette
Declue
Decock
Decola
Decomo
Deconti
Decook
Decorte
Decos
Decost
Decosta
Decoste
Decoster
Decoteau
Decou
Decoud
Decourcey
Decourley
Decoursey
Decourt
Decoux
Decraene
Decree
Decristofaro
Decristoforo
Decroo
Decrosta
Decuir
Deculus
Decurtis
Dedaj
Dede
Dedeaux
Dedecker
Dedek
Dedeke
Dederich
Dederick
Dedic
Dedicke
Dedier
Dedinas
Dedios
Dedman
Dedmon
Dednam
Dedo
Dedominicis
Dedon
Dedrick
Dedrickson
Dee
Deeb
Deed
Deedrick
Deeds
Deeg
Deegan
Deeken
Deeks
Deel
Deeley
Deely
Deem
Deemer
Deems
Deen
Deener
Deep
Deer
Deerdoff
Deere
Deering
Deerman
Dees
Deese
Deeter
Deeters
Deets
Deetz
Deever
Defaber
Defabio
Defalco
Defaria
Defayette
Defazio
Defee
Defelice
Defenbaugh
Defenderfer
Defeo
Deffenbaugh
Deffibaugh
Defibaugh
Defide
Defiglio
Defiguero
Defilippi
Defilippis
Defilippo
Defina
Defino
Defiore
Defir
Deflorio
Defoe
Defonce
Defont
Defoor
Defoore
Deford
Defore
Deforest
Deforge
Deforrest
Defosse
Defosses
Defosset
Defouw
Defrain
Defrance
Defranceschi
Defrancesco
Defrancis
Defrancisco
Defranco
Defrang
Defrank
Defrates
Defreece
Defreese
Defreitas
Defries
Defusco
Degado
Degaetano
Degagne
Degan
Degarmo
Degasparre
Degasperis
Degaust
Degear
Degeare
Degeest
Degelbeck
Degele
Degen
Degenaro
Degener
Degenfelder
Degenhardt
Degenhart
Degennaro
Degeorge
Degeston
Degeyter
Degiacomo
Degidio
Degiorgio
Degirolamo
Degiulio
Deglandon
Deglanville
Degler
Deglopper
Deglow
Degman
Degnan
Degner
Degnim
Degolier
Degollado
Degolyer
Degon
Degonia
Degooyer
Degori
Degraaf
Degrace
Degracia
Degraff
Degraffenreid
Degraffenried
Degrand
Degrande
Degrandpre
Degrange
Degrass
Degrasse
Degrate
Degrave
Degravelle
Degraw
Degrazia
Degrazio
Degre
Degree
Degreenia
Degregorio
Degrella
Degrenier
Degro
Degroat
Degroff
Degrood
Degroot
Degroote
Degross
Degruy
Deguire
Deguise
Degunya
Deguzman
Dehaan
Dehaas
Dehaemers
Dehan
Dehaney
Deharo
Dehart
Dehass
Dehaven
Dehay
Deherrera
Dehetre
Dehghani
Dehl
Dehler
Dehlinger
Dehm
Dehmer
Dehn
Dehne
Dehner
Dehnert
Dehoff
Dehombre
Dehoyos
Dehrer
Deibel
Deibert
Deible
Deibler
Deichman
Deichmann
Deida
Deidrick
Deierlein
Deigado
Deighan
Deighton
Deignan
Deihl
Deike
Deily
Deimund
Deinert
Deines
Deinhardt
Deininger
Deir
Deis
Deisch
Deischer
Deisher
Deiss
Deist
Deister
Deitch
Deiter
Deiters
Deitrich
Deitrick
Deitsch
Deitz
Deja
Dejackome
Dejaeger
Dejager
Dejarden
Dejardin
Dejarme
Dejarnett
Dejarnette
Dejean
Dejes
Dejesus
Dejohn
Dejoie
Dejong
Dejonge
Dejongh
Dejoode
Dejoseph
Dejulio
Dekalb
Dekany
Dekay
Dekenipp
Dekeyser
Dekeyzer
Dekine
Dekker
Dekle
Deklerk
Dekok
Dekoning
Dekorne
Dekort
Dekorte
Dekrey
Dekruif
Dekuyper
Del
Dela
Delabarre
Delacerda
Delacruz
Delacuesta
Delacueva
Delacy
Delaet
Delafontaine
Delafuente
Delagado
Delagarza
Delage
Delaglio
Delagol
Delagrange
Delaguardia
Delaguila
Delahanty
Delahay
Delahoussaye
Delahoya
Delahoz
Delahunt
Delaine
Delair
Delalla
Delallo
Delaluz
Delamar
Delamare
Delamarter
Delamater
Delamora
Delana
Delancey
Delancy
Deland
Delaney
Delang
Delange
Delangel
Delano
Delanoche
Delanoy
Delanuez
Delany
Delao
Delap
Delapaz
Delapena
Delapenha
Delaplane
Delaporte
Delaportilla
Delapp
Delapuente
Delara
Delaremore
Delarge
Delargy
Delariva
Delarme
Delaroca
Delarosa
Delasancha
Delasbour
Delash
Delashaw
Delashmit
Delashmutt
Delasko
Delatorre
Delatrinidad
Delatte
Delauder
Delaughter
Delaune
Delaura
Delaurentis
Delaurie
Delauter
Delavega
Delavergne
Delavina
Delaware
Delawder
Delawyer
Delay
Delbalso
Delbene
Delbert
Delbo
Delbosque
Delbridge
Delbrocco
Delbrune
Delbusto
Delcambre
Delcamp
Delcampo
Delcarlo
Delcarmen
Delcastillo
Delce
Delcid
Delcine
Delco
Delcolle
Delcour
Delcourt
Delcueto
Deldeo
Deldonno
Delduca
Delea
Delee
Deleeuw
Delegado
Delegeane
Delehanty
Delehoy
Delekta
Delellis
Delemos
Delena
Delenick
Deleo
Deleon
Deleonardis
Deleonardo
Deleone
Deleppo
Delerme
Delessio
Deleston
Delettre
Delevik
Deley
Delfavero
Delfelder
Delfi
Delfierro
Delfin
Delfino
Delfs
Delfuente
Delgadillo
Delgadilo
Delgado
Delgardo
Delgato
Delgatto
Delgenio
Delger
Delgiudice
Delgoda
Delgrande
Delgreco
Delgrosso
Delguercio
Delguidice
Delhierro
Delhomme
Delhoyo
Delia
Deliberato
Delibertis
Deliberto
Delilla
Delille
Delilli
Delillo
Delima
Deline
Delinois
Delio
Delira
Delisa
Delisi
Delisio
Delisle
Deliso
Delisser
Deliz
Delk
Delker
Dell
Della
Dellaca
Dellacioppa
Dellagatta
Dellajacono
Dellamonica
Dellamora
Dellamore
Dellano
Dellapaolera
Dellapenna
Dellapenta
Dellapina
Dellaporta
Dellaratta
Dellaripa
Dellarocco
Dellarose
Dellasanta
Dellasciucca
Dellavalle
Dellbringge
Delle
Dellefave
Dellen
Dellenbaugh
Deller
Delles
Delley
Delli
Dellibovi
Delligatti
Delling
Dellinger
Dellis
Delliveneri
Dellon
Dellos
Dellosso
Dellow
Dellum
Dellwo
Delmage
Delman
Delmar
Delmas
Delmastro
Delmedico
Delmendo
Delmolino
Delmonaco
Delmonico
Delmont
Delmonte
Delmoral
Delmore
Delmoro
Delmundo
Delmuro
Delnegro
Delnero
Delnoce
Delo
Deloach
Deloatch
Deloe
Deloera
Deloff
Deloge
Delois
Delon
Delonais
Delone
Deloney
Delong
Delonge
Delongis
Delorbe
Delore
Delorenzo
Delorey
Delorge
Deloria
Delorme
Delos
Delosa
Delosangeles
Delosanglel
Delosantos
Delosh
Delosier
Delosreyes
Delosrios
Delossanto
Delossantos
Delouise
Deloy
Deloye
Delozier
Delp
Delpaggio
Delpapa
Delperdang
Delph
Delphia
Delpiano
Delpino
Delpit
Delpozo
Delprete
Delprincipe
Delpriore
Delre
Delreal
Delrie
Delrio
Delrosario
Delross
Delrossi
Delrosso
Delsavio
Delsignore
Delsoin
Delsol
Delson
Delsordo
Delton
Deltora
Deltoro
Deltufo
Deluca
Delucas
Delucca
Delucchi
Deluccia
Delucia
Delucian
Deluco
Delude
Deluise
Delullo
Deluna
Deluney
Delung
Delusia
Deluz
Deluzio
Delva
Delval
Delvalle
Delvecchio
Delveechio
Delvillar
Delvin
Delwiche
Delzell
Delzer
Demaggio
Demagistris
Demaine
Demaio
Demaire
Demaline
Demallie
Deman
Demange
Demar
Demara
Demarais
Demaranville
Demaray
Demarc
Demarce
Demarco
Demarcus
Demaree
Demarest
Demaria
Demarini
Demarinis
Demarino
Demario
Demaris
Demark
Demarrais
Demars
Demarse
Demarsico
Demart
Demartini
Demartino
Demary
Demarzio
Demas
Demase
Demasi
Demasters
Demastus
Demateo
Dematos
Dematteis
Dematteo
Demattia
Demattos
Demauri
Demauro
Demay
Demayo
Dembek
Dember
Dembinski
Dembitzer
Dembo
Dembosky
Dembowski
Dembroski
Demby
Demchak
Demchok
Demedeiros
Demeester
Demeglio
Demel
Demelis
Demello
Demelo
Demendonca
Dement
Demeo
Demer
Demerchant
Demere
Demeris
Demeritt
Demeritte
Demers
Demerson
Demery
Demesa
Demeter
Demetrakos
Demetree
Demetriou
Demetris
Demetro
Demeyer
Demeza
Demian
Demianczyk
Demicco
Demich
Demichele
Demichelis
Demichiel
Demick
Demiel
Demien
Demik
Demille
Demilt
Deming
Demint
Demirchyan
Demirjian
Demiter
Demko
Demler
Demling
Demma
Demman
Demme
Demmel
Demmer
Demmert
Demming
Demmon
Demmons
Demmy
Demny
Demo
Demonbreun
Demond
Demonett
Demoney
Demont
Demonte
Demontigny
Demopoulos
Demora
Demoranville
Demore
Demorest
Demorizi
Demorrett
Demory
Demos
Demoss
Demosthenes
Demott
Demotta
Demoura
Demoya
Dempewolf
Demps
Dempsey
Dempster
Dempsy
Demro
Demry
Demsey
Demshar
Demske
Demski
Demsky
Demuizon
Demulling
Demuro
Demus
Demuth
Demuzio
Demyan
Demyers
Dena
Denafo
Denapoli
Denard
Denardi
Denardis
Denardo
Denaro
Denault
Denbo
Denboer
Denbow
Denburger
Denby
Dence
Dench
Dencklau
Dender
Dendy
Dene
Deneal
Deneen
Denegre
Deneke
Denenberg
Denery
Denes
Denet
Denetclaw
Deneui
Denfip
Deng
Dengel
Denger
Dengler
Denham
Denhartog
Denherder
Denholm
Deni
Denice
Denick
Denicola
Denier
Denike
Deniken
Denina
Deninno
Denio
Deniro
Denis
Denisco
Denise
Denison
Deniston
Deniz
Denjen
Denk
Denker
Denkins
Denley
Denlinger
Denman
Denmark
Denmon
Denn
Denna
Dennard
Denne
Dennehy
Dennen
Denner
Dennert
Dennett
Denney
Denni
Dennie
Dennies
Dennig
Dennin
Denning
Dennington
Dennis
Dennison
Denniston
Denno
Denny
Deno
Denoble
Denofrio
Denogean
Denoia
Denomme
Denoncourt
Denoon
Denooyer
Denos
Denoyelles
Denoyer
Dense
Densford
Densieski
Denski
Densley
Denslow
Densmore
Denson
Dent
Dente
Dentel
Denten
Dentino
Dentler
Denton
Dentremont
Denty
Denunzio
Denver
Denwood
Denyer
Denyes
Denzel
Denzer
Denzin
Denzine
Denzler
Deocampo
Deodato
Deojay
Deoliveira
Deon
Deonarian
Deonarine
Deorio
Depa
Depace
Depadua
Depalma
Depalo
Depaola
Depaoli
Depaolo
Depasquale
Depass
Depasse
Depaul
Depaula
Depaulis
Depauw
Depaz
Depedro
Depena
Deperro
Deperte
Depetris
Depetro
Depew
Depeyster
Dephillips
Depierre
Depierro
Depietro
Depina
Depinho
Depinto
Depippo
Depiro
Depner
Depolis
Depolito
Depolo
Depont
Deponte
Deporter
Depottey
Depoyster
Depp
Deppe
Deppen
Depperschmidt
Deppert
Depping
Deppner
Deprato
Depratt
Depree
Deprey
Deprez
Depriest
Deprince
Deprizio
Deprofio
Deprospero
Depsky
Deptula
Depue
Depugh
Depung
Deputy
Depuy
Depuydt
Dequattro
Dequinzio
Der
Deralph
Deramo
Deramus
Deraney
Deranick
Deraps
Deras
Derasmo
Derastel
Deraveniere
Derbacher
Derbes
Derby
Derbyshire
Derck
Dercole
Derden
Derderian
Derego
Deremer
Deremiah
Deren
Derenberger
Derendal
Derensis
Derenthal
Derentis
Derenzi
Derenzis
Derenzo
Derer
Dereu
Dereus
Derezinski
Derfler
Derflinger
Derfus
Derga
Dergance
Dergurahian
Derham
Derhammer
Derian
Derick
Derickson
Derico
Deridder
Derider
Derienzo
Deriggi
Dering
Deringer
Derington
Derion
Derise
Derita
Deritis
Derito
Derivan
Derizzio
Derk
Derkach
Derkas
Derks
Derksen
Dermady
Derman
Dermer
Dermo
Dermody
Dermott
Dern
Dernier
Derobertis
Deroberts
Derobles
Derocco
Deroche
Derocher
Deroeck
Deroest
Derogatis
Deroin
Deroko
Deromer
Deroos
Derosa
Derosby
Derose
Derosia
Derosie
Derosier
Deross
Derosset
Derossett
Derosso
Derouchie
Derouen
Derouin
Derousse
Derousselle
Deroven
Deroy
Derr
Derrah
Derrer
Derrick
Derrickson
Derrico
Derricott
Derrig
Derrigo
Derring
Derringer
Derrington
Derriso
Derrow
Derry
Derryberry
Dersch
Dershem
Derting
Dertinger
Derubeis
Deruiter
Derusha
Deruso
Deruyter
Derwin
Derwitsch
Derx
Dery
Desadier
Desai
Desak
Desalle
Desalvatore
Desalvo
Desamito
Desamparo
Desan
Desanctis
Desando
Desano
Desanti
Desantiago
Desantigo
Desantis
Desanto
Desantos
Desanty
Desatnik
Desaulniers
Desautel
Desautelle
Desautels
Desbiens
Descamps
Desch
Deschaine
Deschambault
Deschambeault
Deschamp
Deschamps
Deschene
Deschenes
Deschepper
Deschino
Deschner
Deschomp
Descombes
Descoteau
Descoteaux
Desena
Deserio
Deserres
Desforges
Desfosses
Desgroseillie
Desha
Deshaies
Desharnais
Deshaw
Deshay
Deshayes
Deshazer
Deshazior
Deshazo
Desher
Deshields
Deshler
Deshner
Deshon
Deshong
Deshotel
Deshotels
Deshpande
Desiato
Desiderio
Desiga
Desilets
Desilva
Desilvio
Desilvo
Desimas
Desimone
Desimoni
Desir
Desisles
Desisto
Desiyatnikov
Desjardin
Desjardins
Desjardiws
Desjarlais
Deskin
Deskins
Desko
Deslandes
Deslatte
Deslaurier
Deslauriers
Desler
Desloge
Desmarais
Desmarias
Desmaris
Desmet
Desmeules
Desmith
Desmond
Desmore
Desnoyers
Deso
Desola
Desolier
Desomma
Desonia
Desorbo
Desorcy
Desormeau
Desormeaux
Desormo
Desort
Desotel
Desoto
Desousa
Desouza
Despain
Despard
Desparrois
Desper
Despino
Desporte
Desposito
Despres
Desquare
Desrevisseau
Desroberts
Desrocher
Desrochers
Desroches
Desrosier
Desrosiers
Desruisseaux
Dess
Dessecker
Desselle
Dessert
Desso
Dest
Destasio
Destefani
Destefanis
Destefano
Destephano
Destephen
Destiche
Destime
Destina
Destine
Destree
Destro
Desue
Desutter
Desvergnes
Detaeye
Detamble
Detamore
Detar
Detchon
Detemple
Deter
Deterding
Detering
Deterline
Determan
Determann
Deters
Deteso
Detherage
Dethlefs
Dethlefsen
Dethomas
Dethomasis
Detienne
Detillier
Detillion
Detjen
Detlefs
Detlefsen
Detmer
Detoma
Detommaso
Detone
Detore
Detorres
Detraglia
Detrich
Detrick
Detro
Detrolio
Detten
Detter
Detterich
Dettinger
Dettling
Dettloff
Dettman
Dettmann
Dettmer
Dettmering
Dettor
Dettore
Dettori
Dettorre
Dettra
Detty
Detullio
Deturenne
Detweiler
Detwiler
Detz
Detzel
Detzler
Deubler
Deubner
Deuel
Deuell
Deuermeyer
Deuink
Deuman
Deupree
Deur
Deus
Deuschel
Deuschle
Deuser
Deutsch
Deutschendorf
Deutscher
Deutschman
Devai
Deval
Devalcourt
Devalk
Devall
Devalle
Devan
Devane
Devaney
Devanski
Devany
Devara
Devargas
Devarona
Devary
Devasier
Devaughan
Devaughn
Devaul
Devault
Devaux
Devazier
Deveau
Deveaux
Deveja
Devel
Develbiss
Develice
Devendorf
Devenecia
Deveney
Devenney
Devenny
Devenport
Devens
Devenuto
Deveny
Dever
Devera
Devere
Devereaux
Devereux
Devericks
Devers
Devery
Devey
Deveyra
Devich
Devick
Devier
Devilbiss
Devilla
Deville
Devillez
Devillier
Devilliers
Devin
Devincent
Devincentis
Devincenzi
Devincenzo
Devine
Deviney
Devinney
Devino
Devins
Devis
Devit
Devita
Devitis
Devito
Devitt
Devitto
Deviva
Devivo
Devlin
Devoe
Devoid
Devol
Devoll
Devon
Devone
Devonish
Devonshire
Devoogd
Devor
Devora
Devore
Devos
Devoss
Devost
Devot
Devoti
Devotie
Devoto
Devoy
Devreese
Devries
Dew
Dewaard
Dewaele
Dewald
Dewall
Dewalt
Dewan
Dewar
Dewaratanawan
Dewater
Dewaters
Dewberry
Dewees
Deweese
Dewer
Dewese
Dewey
Dewhirst
Dewhurst
Dewick
Dewiel
Dewilde
Dewindt
Dewing
Dewinne
Dewinter
Dewire
Dewispelaere
Dewit
Dewitt
Dewitte
Dewitz
Dewolf
Dewolfe
Dewolff
Dewoody
Dews
Dewulf
Dewyer
Dewyse
Dexheimer
Dexter
Dey
Deya
Deyak
Deyarmin
Deyarmond
Deyette
Deyo
Deyoe
Deyon
Deyoung
Dez
Dezalia
Dezan
Dezarn
Dezayas
Dezeeuw
Dezell
Dezenzo
Dezern
Dezzutti
Dhaliwal
Dhamer
Dhar
Dharas
Dheel
Dhein
Dhillon
Dhondt
Dhosane
Dhruva
Diab
Diachenko
Diaco
Diak
Dial
Diallo
Dials
Diamant
Diamante
Diamantopoulo
Diamico
Diamond
Diana
Diangelis
Diangelo
Diani
Diano
Dias
Diaz
Diazdeleon
Dibacco
Dibari
Dibartolo
Dibartolomeo
Dibattista
Dibben
Dibbern
Dibble
Dibblee
Dibbles
Dibella
Dibello
Dibenedetti
Dibenedetto
Dibenedict
Diberardino
Dibernardo
Dibert
Dibiase
Dibiasi
Diblase
Diblasi
Diblasio
Dible
Dibley
Dibona
Dibonaventura
Dibrell
Dibrino
Dibrito
Dicamillo
Dicampli
Dicaprio
Dicapua
Dicara
Dicarlo
Dicaro
Dicastro
Dice
Dicecco
Dicello
Dicerbo
Dicesare
Dicey
Dicharry
Dichiara
Dichiaro
Dichristopher
Diciano
Dicicco
Dicioccio
Dick
Dickason
Dicke
Dickel
Dicken
Dickens
Dickensheets
Dickenson
Dicker
Dickerman
Dickerson
Dickert
Dickes
Dickeson
Dickey
Dickhaus
Dickhaut
Dickhoff
Dickie
Dickins
Dickinson
Dickirson
Dickison
Dickman
Dickmann
Dickow
Dicks
Dickson
Dickstein
Dickun
Dickus
Diclaudio
Dicocco
Dicola
Dicorcia
Dicorpo
Dicosmo
Dicostanzo
Dicus
Didamo
Didato
Diddle
Didier
Didio
Didion
Didlake
Didomenico
Didomizio
Didonatis
Didonato
Didonna
Didriksen
Didway
Didyk
Dieball
Diebol
Diebold
Diec
Dieckman
Dieckmann
Diede
Diederich
Diederichs
Diedrich
Diedrick
Diedricks
Diefenbach
Diefenderfer
Diefendorf
Dieffenbach
Dieffenbacher
Diegel
Diegidio
Diego
Dieguez
Diehl
Diehm
Diekema
Dieken
Diekman
Diekmann
Diekrager
Diel
Dielman
Diem
Diemer
Diemert
Diemoz
Dien
Diener
Dienes
Dieng
Dienhart
Dienst
Diep
Diepenbrock
Dieppa
Dier
Diercks
Dieringer
Dierker
Dierkes
Dierking
Dierks
Dierolf
Diers
Diersen
Dies
Diesel
Diesen
Diesi
Diestel
Diestler
Dietel
Dieteman
Dieter
Dieterich
Dieterle
Dietert
Dietl
Dietlin
Dietrich
Dietrick
Dietsch
Dietsche
Dietterick
Dietz
Dietze
Dietzel
Dietzen
Dietzler
Dietzman
Dieudonne
Diewold
Diez
Difabio
Difalco
Difebbo
Difede
Difelice
Difeo
Diffee
Diffendal
Diffenderfer
Diffey
Diffley
Difilippo
Difillippo
Difiora
Difiore
Diflorio
Difonzo
Difrancesco
Difrancisco
Difranco
Difronzo
Difusco
Diga
Digaetano
Digangi
Digby
Digennaro
Digeorgio
Digerolamo
Digesare
Digges
Diggins
Diggs
Dighton
Digiacinto
Digiacomo
Digiambattist
Digian
Digilio
Digioia
Digiorgi
Digiorgio
Digiouanni
Digiovanni
Digirolamo
Digirolomo
Digiulio
Digiuseppe
Digman
Digmann
Dignan
Digness
Digrande
Digrazia
Digregorio
Digsby
Dihel
Diiorio
Diiulio
Dijulio
Dike
Dikeman
Dikens
Diker
Dikes
Diket
Dikkers
Dilalla
Dilallo
Dilan
Dilaura
Dilauro
Dilbeck
Dilbert
Dilchand
Dilcher
Dilda
Dilday
Dildine
Dildy
Dile
Dilella
Dilello
Dilena
Dileo
Dileonardo
Diles
Diley
Dilg
Dilgard
Dilger
Dilibero
Diliberti
Diliberto
Dilick
Dilillo
Dilisio
Dilks
Dill
Dillabough
Dillahunt
Dillahunty
Dillaman
Dillard
Dillashaw
Dillavou
Dille
Dillehay
Dillen
Dillenbeck
Dillenburg
Diller
Dilleshaw
Dilley
Dilliard
Dillie
Dilligard
Dillin
Dilliner
Dilling
Dillinger
Dillingham
Dillion
Dillis
Dillman
Dillmore
Dillon
Dillow
Dills
Dillworth
Dilly
Dilmore
Dilorenzo
Diloreto
Dilox
Dils
Dilsaver
Dilthey
Dilts
Diltz
Diluca
Dilucca
Dilullo
Diluzio
Dilworth
Dimaggio
Dimaio
Dimalanta
Dimanche
Dimarco
Dimare
Dimaria
Dimariano
Dimarino
Dimario
Dimartino
Dimarzio
Dimarzo
Dimas
Dimascio
Dimassimo
Dimatteo
Dimattia
Dimauro
Dimeglio
Dimeo
Dimery
Dimes
Dimezza
Dimicco
Dimiceli
Dimick
Diminich
Diminno
Dimino
Dimitri
Dimitriadis
Dimitriou
Dimitroff
Dimitrov
Dimitry
Dimitt
Dimler
Dimling
Dimmack
Dimmer
Dimmick
Dimmitt
Dimock
Dimodica
Dimon
Dimond
Dimopoulos
Dimoulakis
Dimperio
Dimpfl
Dimpson
Dimsdale
Dimucci
Dimuccio
Dimuzio
Din
Dina
Dinan
Dinapoli
Dinardi
Dinardo
Dinatale
Dincher
Dinco
Dine
Dineen
Dinehart
Dines
Ding
Dingee
Dingel
Dingeldein
Dingell
Dinger
Dinges
Dingess
Dingfelder
Dingie
Dingillo
Dingivan
Dinglasan
Dingle
Dingler
Dingman
Dingmann
Dings
Dingson
Dingus
Dingwall
Dinh
Dinham
Dinho
Dini
Dinicola
Dininger
Dininno
Dinis
Dinitto
Dinius
Diniz
Dinizio
Dinkel
Dinkens
Dinkin
Dinkins
Dinkle
Dinn
Dinneen
Dinnen
Dinnendahl
Dinning
Dinnocenzo
Dino
Dinola
Dinora
Dinos
Dinovi
Dinovo
Dinsdale
Dinsmoor
Dinsmore
Dintino
Dinucci
Dinunzio
Dinuzzo
Dinwiddie
Dinwoodie
Diodonet
Diogo
Diomede
Dion
Dioneff
Diones
Dionisio
Dionisopoulos
Dionne
Diop
Diorio
Diosdado
Diotte
Dipalma
Dipanfilo
Dipaola
Dipaolo
Dipasquale
Diperna
Dipiano
Dipiazza
Dipiero
Dipierro
Dipietrantoni
Dipietro
Dipilato
Dipinto
Dipippo
Dipirro
Dipolito
Diponio
Dippel
Dippery
Dippolito
Diprima
Dirado
Dirago
Dircks
Dirden
Dire
Direnzo
Dirickson
Dirico
Dirienzo
Dirk
Dirker
Dirks
Dirkse
Dirksen
Dirkson
Dirlam
Dirocco
Dirollo
Dirosa
Dirose
Dirr
Dirth
Dirusso
Diruzzo
Disabato
Disalvatore
Disalvi
Disalvo
Disandro
Disano
Disanti
Disanto
Disarufino
Disbro
Disbrow
Discala
Discenza
Disch
Discher
Dischinger
Dischner
Discipio
Discon
Diserens
Diseth
Disharoon
Dishaw
Disher
Dishian
Dishinger
Dishman
Dishmon
Dishner
Dishon
Dishong
Disilvestro
Disimone
Diskin
Diskind
Disla
Dismang
Dismore
Dismuke
Dismukes
Disney
Dison
Disorbo
Disorda
Disotell
Disparte
Dispenza
Dispirito
Disponette
Disque
Diss
Dissinger
Disspain
Distad
Distaffen
Distance
Distasio
Distefano
Distel
Distilo
Distin
Distler
Ditch
Ditchfield
Ditman
Ditmars
Ditmore
Dito
Ditolla
Ditomasso
Ditommaso
Ditore
Ditsch
Ditta
Dittberner
Dittbrenner
Dittemore
Ditter
Ditti
Dittman
Dittmann
Dittmar
Dittmer
Ditto
Ditton
Dittrich
Dittrick
Dittus
Ditty
Ditucci
Ditullio
Dituri
Ditzel
Ditzler
Diulio
Divalerio
Divan
Divel
Divelbiss
Diveley
Dively
Diven
Divenere
Divens
Divento
Diventura
Diver
Divers
Divin
Divincenzo
Divine
Diviney
Divirgilio
Divis
Divita
Divito
Divlio
Divoll
Diwan
Dix
Dixey
Dixie
Dixion
Dixon
Dixons
Dixson
Diza
Dizadare
Dizer
Dizon
Djuric
Dk
Dlabaj
Dlobik
Dlouhy
Dlugos
Dluhy
Dmitriev
Do
Doak
Doakes
Doan
Doane
Dobb
Dobbe
Dobberfuhl
Dobberstein
Dobbin
Dobbins
Dobbratz
Dobbs
Dobbyn
Dobek
Doberstein
Dobert
Dobes
Dobesh
Dobey
Dobias
Dobie
Dobies
Dobiesz
Dobin
Dobine
Dobis
Dobison
Dobkin
Dobkins
Dobkowski
Doble
Dobler
Dobles
Dobmeier
Dobos
Dobosh
Dobosz
Dobransky
Dobrasz
Dobratz
Dobre
Dobrich
Dobrin
Dobrinin
Dobrinski
Dobrosky
Dobrowolski
Dobrowski
Dobrunz
Dobrushin
Dobry
Dobrynski
Dobrzykowski
Dobson
Doby
Dobyns
Doceti
Docherty
Dochterman
Docimo
Dock
Dockal
Docken
Dockendorf
Docker
Dockerty
Dockery
Dockett
Dockham
Dockins
Dockray
Dockstader
Dockter
Dockum
Dockus
Dockwiller
Doctor
Dodd
Dodds
Doderer
Dodge
Dodgen
Dodgion
Dodgson
Dodich
Dodier
Dodimead
Dodoo
Dodridge
Dodrill
Dodson
Dodsworth
Dodwell
Dody
Doe
Doeberling
Doebler
Doede
Doeden
Doege
Doegg
Doehring
Doelger
Doell
Doelling
Doemelt
Doepke
Doepner
Doerfler
Doerflinger
Doerhoff
Doering
Doerksen
Doerle
Doerner
Doerr
Doerrer
Doersam
Doescher
Doetsch
Doffing
Dogan
Doggett
Doggette
Dohan
Doheny
Doherty
Dohm
Dohman
Dohn
Dohnal
Dohogne
Dohring
Dohrman
Dohrmann
Dohrn
Dohse
Doi
Doidge
Doiel
Doig
Doil
Doiley
Doing
Doino
Doire
Doiron
Dok
Doke
Doker
Dokes
Dokka
Dokken
Dokovic
Dokuchitz
Dolak
Dolan
Doland
Dolbeare
Dolbee
Dolberry
Dolbin
Dolbow
Dolby
Dolce
Dolcetto
Dolch
Dold
Dolder
Doldo
Dole
Doleac
Dolecek
Dolecki
Dolejsi
Doleman
Dolen
Dolence
Doler
Doles
Dolese
Dolezal
Dolfay
Dolfi
Dolgas
Dolhon
Dolhun
Dolin
Dolinar
Dolinger
Dolinski
Dolinsky
Dolio
Doliveira
Doljac
Doll
Dollahite
Dollak
Dollar
Dollard
Dollarhide
Dolle
Dollen
Doller
Dolley
Dollinger
Dollings
Dollins
Dollison
Dolliver
Dolloff
Dolly
Dollyhigh
Dolmajian
Dolman
Dolney
Dolores
Dolph
Dolphin
Dols
Dolsen
Dolson
Dolton
Dolven
Dom
Domagala
Domagall
Domagalski
Doman
Domangue
Domann
Domanski
Domas
Dombeck
Dombek
Dombkowski
Dombroski
Dombrosky
Dombrowski
Dome
Domebo
Domeier
Domek
Domenech
Domenget
Domenice
Domenick
Domenico
Domer
Domhoff
Domiano
Domianus
Domin
Domina
Domine
Dominey
Dominga
Dominges
Domingez
Domingo
Domingos
Domingue
Domingues
Dominguez
Domingus
Dominiak
Dominic
Dominici
Dominick
Dominico
Dominicus
Dominiguez
Dominik
Dominion
Dominique
Dominiquez
Dominis
Domino
Dominowski
Dominque
Dominquez
Dominski
Dominy
Domio
Domitrovich
Domke
Domkowski
Dommel
Dommer
Domnick
Domowicz
Dompe
Don
Dona
Donaby
Donachie
Donadio
Donado
Donaghe
Donaghey
Donaghue
Donaghy
Donah
Donaher
Donahey
Donaho
Donahoe
Donahoo
Donahue
Donald
Donalds
Donaldson
Donalson
Donar
Donart
Donat
Donate
Donatelli
Donatello
Donath
Donathan
Donati
Donatich
Donatien
Donato
Donavan
Donawa
Donaway
Donayre
Doncaster
Donchatz
Donchez
Dondero
Dondlinger
Done
Donegan
Donehoo
Donel
Donelan
Donelly
Donelon
Donelson
Doner
Donerson
Dones
Doney
Donez
Dong
Donges
Dongo
Donham
Donhoe
Donica
Doniel
Donigan
Doniger
Donilon
Donis
Donivan
Donkervoet
Donkin
Donkle
Donkor
Donlan
Donley
Donlin
Donlon
Donlyuk
Donmore
Donmoyer
Donn
Donna
Donnalley
Donnally
Donnan
Donndelinger
Donne
Donnel
Donnell
Donnellan
Donnelley
Donnellon
Donnelly
Donnelson
Donnely
Donner
Donnerberg
Donnick
Donnie
Donning
Dono
Donofrio
Donoghue
Donoho
Donohoe
Donohoo
Donohue
Donohve
Donoso
Donota
Donovan
Donson
Dontas
Donten
Donton
Donze
Doody
Doogan
Dool
Doolan
Doolen
Dooley
Doolin
Dooling
Doolittle
Doom
Dooms
Doonan
Dooner
Dooney
Doop
Door
Doore
Doorley
Doorn
Doornbos
Doose
Dootson
Dopazo
Dopf
Dopico
Dopita
Dople
Dopler
Doporto
Dopp
Dopson
Dora
Dorado
Dorais
Dorame
Doran
Dorantes
Dorat
Dorazio
Dorcas
Dorce
Dorcelus
Dorcent
Dorch
Dorchy
Dorcy
Dore
Doremus
Doren
Dorenfeld
Dorer
Dorey
Dorf
Dorff
Dorfman
Dorgan
Dorge
Doria
Dorian
Dorich
Dorie
Doriean
Dorin
Doring
Dorinirl
Dorio
Dorion
Doris
Dority
Dorka
Dorkin
Dorko
Dorl
Dorland
Dorlando
Dormaier
Dorman
Dormane
Dormanen
Dormer
Dorminey
Dorminy
Dorn
Dornak
Dornan
Dornbos
Dornbrook
Dornbusch
Dorne
Dornellas
Dorner
Dorney
Dornfeld
Dornhelm
Dornier
Dorning
Dornon
Dornseif
Doro
Doroff
Doronio
Dorosan
Dorosh
Doroski
Dorosky
Dorothy
Dorough
Dorow
Dorph
Dorpinghaus
Dorr
Dorrance
Dorrell
Dorrian
Dorries
Dorrill
Dorrington
Dorris
Dorrough
Dorsaint
Dorsainvil
Dorsay
Dorsch
Dorschner
Dorset
Dorsett
Dorsette
Dorsey
Dorshimer
Dorshorst
Dorsinville
Dorso
Dorson
Dorst
Dort
Dorta
Dortch
Dortilla
Dorton
Dorval
Dorvee
Dorvil
Dorvillier
Dorward
Dorweiler
Dory
Dosal
Dosch
Doscher
Dose
Doseck
Doser
Dosh
Dosher
Doshi
Doshier
Dosier
Doskocil
Dosreis
Doss
Dossantos
Dossett
Dossey
Dossie
Dossman
Dossous
Dost
Dostal
Doster
Dostie
Doswell
Doten
Dothard
Dotie
Doto
Dotolo
Dotson
Dotstry
Dottavio
Dotter
Dotterer
Dotterweich
Dottery
Dottin
Dottle
Dotto
Dotts
Doty
Dotzler
Dou
Doub
Doubek
Doubet
Double
Doubleday
Doubrava
Douce
Doucet
Doucett
Doucette
Doud
Doudna
Douds
Douet
Douga
Dougal
Dougall
Dougan
Doughan
Dougharity
Dougharty
Dougher
Dougherty
Doughman
Doughtery
Doughtie
Doughton
Doughtry
Doughty
Douglas
Douglass
Douillet
Douin
Doukas
Doulani
Douma
Doung
Dourado
Dousay
Douse
Doussan
Douthart
Douthett
Douthit
Douthitt
Doutt
Douty
Douvia
Douvier
Douville
Douyette
Douyon
Dovalina
Dove
Dovel
Dovenbarger
Dovenmuehler
Dover
Doverspike
Dovey
Dow
Doward
Dowd
Dowda
Dowdall
Dowdell
Dowden
Dowding
Dowdle
Dowds
Dowdy
Dowe
Dowell
Dowen
Dower
Dowers
Dowery
Dowey
Dowgiallo
Dowhower
Dowis
Dowker
Dowland
Dowlen
Dowler
Dowless
Dowlin
Dowling
Down
Downard
Downen
Downer
Downes
Downey
Downham
Downhour
Downie
Downin
Downing
Downs
Downton
Downum
Downy
Dowse
Dowsett
Dowson
Dowst
Dowtin
Dowty
Doxbeck
Doxey
Doxie
Doxon
Doxtater
Doxtator
Doyal
Doyan
Doyel
Doyen
Doyer
Doyle
Doyne
Doyon
Doyscher
Dozal
Dozar
Dozer
Dozier
Dozois
Draa
Drabant
Drabek
Drabicki
Drach
Drader
Draeger
Drafall
Draffen
Draffin
Draft
Drafton
Drafts
Dragaj
Dragan
Drage
Drager
Dragg
Draggett
Draggoo
Draghi
Dragich
Dragna
Drago
Dragon
Dragone
Dragoo
Dragos
Dragotta
Dragovich
Dragt
Dragula
Dragun
Draheim
Drahos
Drahota
Draime
Drain
Draine
Drainer
Drainville
Drake
Drakeford
Drakes
Drakos
Drakulic
Draleau
Dralle
Dramis
Drane
Draney
Drape
Drapeau
Drapeaux
Draper
Drapkin
Drappo
Dratch
Drath
Draudt
Draughn
Draughon
Draves
Dravland
Drawbaugh
Drawdy
Drawe
Drawec
Drawhorn
Drawy
Draxler
Dray
Drayer
Drayton
Drda
Dreben
Drebes
Drechsler
Dreckman
Dredge
Drees
Dreese
Dreesman
Dreessen
Dreger
Dreggs
Dregrich
Dreher
Drehmer
Drehobl
Drehs
Dreibelbis
Dreier
Dreiling
Dreisbach
Dreiss
Dreith
Dreitzler
Drejka
Dreka
Drelick
Drennan
Drennen
Drenner
Drenning
Drennon
Drenon
Drenth
Drentlaw
Dreps
Dresbach
Dresch
Drescher
Dresel
Dresher
Dresner
Dress
Dressel
Dressen
Dresser
Dressler
Dressman
Dretzka
Dreuitt
Drevs
Drew
Drewel
Drewer
Drewery
Drewes
Drewett
Drewing
Drewniak
Drewry
Drews
Drewski
Drexel
Drexler
Drey
Dreyer
Dreyfus
Dreyfuss
Driedric
Drier
Driere
Dries
Driesbach
Driesel
Driesenga
Driessen
Driever
Driggars
Driggers
Driggins
Driggs
Drilling
Drillock
Drimmer
Drinen
Drinkall
Drinkard
Drinkley
Drinkwater
Drinkwine
Drinnen
Drinnon
Drinski
Dripps
Driscol
Driscoll
Drisdelle
Drish
Driskell
Driskill
Drisko
Drissel
Drivas
Driver
Drivers
Drizin
Drobny
Drobot
Drock
Droege
Droegmiller
Droesch
Droessler
Droggitis
Drohan
Droke
Drolet
Drollinger
Dromgoole
Drone
Droneburg
Dronen
Drones
Dronet
Droney
Drong
Dronick
Dronko
Drook
Drop
Dropinski
Drorbaugh
Drosick
Droski
Dross
Drossman
Drossos
Drost
Droste
Drott
Droubay
Drought
Drouillard
Drouin
Drouse
Drovin
Drow
Drown
Drowne
Droy
Droz
Drozd
Drozda
Drozdenko
Drozdowicz
Drozdowski
Droze
Dru
Drube
Druck
Drucker
Druckhammer
Druckman
Drude
Drue
Druetta
Drugan
Drullard
Drum
Drumbore
Drumgo
Drumgole
Drumgoole
Drumheiser
Drumheller
Drumm
Drummer
Drummey
Drummond
Drummonds
Drumwright
Drungo
Drury
Druschel
Drust
Drutman
Druvenga
Dry
Drybread
Dryden
Drye
Dryer
Drylie
Dryman
Drymon
Drysdale
Drzazgowski
Drzewicki
Drzewiecki
Dsaachs
Dsouza
Dspain
Du
Dua
Duane
Duarte
Duartes
Dub
Duba
Dubach
Dubaldi
Duball
Duban
Dubard
Dubas
Dubay
Dubberly
Dubbert
Dubbin
Dubbs
Dube
Dubeau
Dubeck
Dubej
Dubel
Duber
Duberry
Duberstein
Dubey
Dubiansky
Dubicki
Dubie
Dubiel
Dubill
Dubin
Dubinsky
Dubis
Dubitsky
Duble
Dubler
Dublin
Dubois
Duboise
Dubon
Dubonnet
Dubord
Dubose
Dubourg
Dubovsky
Dubow
Dubray
Dubre
Dubree
Dubreuil
Dubrey
Dubrock
Dubrow
Dubs
Dubson
Dubuc
Dubuisson
Dubuque
Duby
Dubyk
Duca
Ducan
Ducas
Ducasse
Ducat
Ducatelli
Ducay
Ducayne
Ducceschi
Ducci
Duce
Duceman
Ducey
Duch
Duchaine
Duchane
Ducharme
Duchatellier
Duchemin
Duchene
Duchesne
Duchesneau
Duchesney
Duchnowski
Duchon
Duchow
Duchscherer
Duck
Ducker
Duckett
Duckey
Duckhorn
Ducking
Ducklow
Ducksworth
Duckwall
Duckworth
Duclo
Duclos
Ducos
Ducote
Ducotey
Ducrepin
Duda
Dudack
Dudak
Dudas
Dudash
Dudasik
Dudden
Dudding
Duddy
Dudeck
Dudek
Duden
Dudenbostel
Dudenhoeffer
Duderstadt
Dudgeon
Dudik
Dudleson
Dudley
Dudman
Dudney
Dudycha
Dudziak
Dudzic
Dudzik
Dudzinski
Due
Dueber
Dueck
Dueitt
Duel
Duell
Duellman
Duelm
Duemmel
Duenas
Duenes
Duenez
Duenke
Dueno
Duenow
Duensing
Duenwald
Duer
Duerkop
Duerksen
Duerkson
Duerr
Duerson
Duerst
Dues
Duesenberg
Duesing
Duesterback
Duesterhaus
Duet
Duett
Duewall
Duey
Dufauchard
Dufault
Dufek
Dufer
Duff
Duffany
Duffee
Duffek
Duffel
Duffer
Duffett
Duffey
Dufficy
Duffie
Duffield
Duffin
Duffney
Dufford
Duffus
Duffy
Dufilho
Dufner
Duford
Dufort
Dufour
Dufrain
Dufrane
Dufrene
Dufresne
Duft
Dugal
Dugan
Dugar
Dugas
Dugat
Dugay
Dugdale
Duggan
Duggar
Dugger
Duggin
Duggins
Dughi
Dugi
Dugmore
Dugo
Dugre
Duguay
Dugue
Duguette
Duh
Duhaime
Duhamel
Duhan
Duhart
Duhe
Duhl
Duhn
Duhon
Duignan
Duin
Duis
Duitch
Duitscher
Duk
Duka
Dukart
Dukas
Duke
Dukelow
Dukeman
Duker
Dukes
Dukeshier
Dukeshire
Dukett
Dukette
Dukhovny
Dukich
Dul
Dula
Dulac
Dulak
Dulan
Dulaney
Dulany
Dular
Dulatre
Dulay
Dulberg
Duldulao
Dulek
Dulemba
Duley
Duliba
Dulin
Duling
Dulkis
Dull
Dulle
Dullea
Dullen
Dullum
Dulmage
Dulong
Dulude
Duma
Dumag
Dumaine
Dumais
Duman
Dumar
Dumars
Dumas
Dumay
Dumbar
Dumbleton
Dumdei
Dume
Dumeny
Dumes
Dumesnil
Dumez
Dumire
Dumke
Dumlao
Dumler
Dumm
Dummer
Dummermuth
Dummett
Dummitt
Dumond
Dumont
Dumouchel
Dumoulin
Dumpe
Dumpert
Dumphy
Dumpson
Dun
Dunagan
Dunagin
Dunahoe
Dunahoo
Dunakin
Dunavant
Dunaway
Dunay
Dunbar
Duncan
Duncans
Duncanson
Duncil
Dunckel
Duncker
Duncklee
Duncomb
Duncombe
Dundas
Dundee
Dunderman
Dundlow
Dundon
Dunegan
Dunemann
Dunemn
Dunfee
Dunford
Dung
Dungan
Dungee
Dungey
Dungy
Dunham
Dunigan
Dunivan
Dunk
Dunkan
Dunkel
Dunkelberger
Dunken
Dunkentell
Dunker
Dunkerley
Dunkerson
Dunkin
Dunkinson
Dunkle
Dunkleberger
Dunklee
Dunkley
Dunklin
Dunks
Dunlap
Dunlavy
Dunleavy
Dunlevy
Dunlop
Dunlow
Dunman
Dunmead
Dunmire
Dunmore
Dunn
Dunnagan
Dunnahoo
Dunnam
Dunnavant
Dunnaville
Dunnaway
Dunne
Dunneback
Dunnegan
Dunnell
Dunnigan
Dunning
Dunnings
Dunnington
Dunnivan
Dunnum
Dunny
Dunomes
Dunovant
Dunphe
Dunphy
Dunscomb
Dunseith
Dunsford
Dunshee
Dunshie
Dunsing
Dunsmoor
Dunsmore
Dunson
Dunstan
Dunster
Dunston
Dunsworth
Dunt
Dunten
Duntley
Dunton
Duntz
Dunwiddie
Dunwoody
Dunworth
Dunzelman
Duong
Duonola
Duos
Dupar
Dupas
Dupaski
Dupass
Dupaty
Dupay
Dupee
Duperclay
Duperre
Duperry
Dupes
Duplaga
Duplanti
Duplantis
Duplechain
Duplechin
Dupler
Duplesis
Duplessis
Duplessy
Duplin
Dupont
Duponte
Dupoux
Dupouy
Duppstadt
Dupras
Duprat
Dupray
Dupre
Dupree
Duprey
Dupriest
Dupuis
Dupuy
Duquaine
Duque
Duquette
Dura
Duracher
Duraku
Dural
Durall
Duran
Duranceau
Durand
Durando
Durant
Durante
Durate
Durazo
Durbin
Durboraw
Durch
Durda
Durdan
Durden
Durdy
Dure
Duree
Durell
Durelli
Duren
Durepo
Duresky
Durett
Durette
Durfee
Durfey
Durgan
Durgin
Durham
Durhan
Durian
Durick
Durie
Durig
Duriga
During
Durio
Duris
Durisseau
Durk
Durke
Durkee
Durkes
Durkin
Durkins
Durland
Durley
Durling
Durman
Durnan
Durnell
Durney
Durnford
Durnil
Durnin
Durning
Durniok
Durocher
Durol
Duron
Duropan
Duroseau
Duross
Durough
Durousseau
Durpee
Durphey
Durr
Durrah
Durrance
Durrani
Durrant
Durre
Durrell
Durrenberger
Durrett
Durrette
Durrwachter
Dursch
Durso
Durst
Dursteler
Durtsche
Durtschi
Durun
Durupan
Durward
Duryea
Duryee
Dus
Dusablon
Dusak
Dusatko
Dusch
Dusek
Dusel
Dusen
Dusenberry
Dusenbery
Dusenbury
Dusett
Dush
Dushaj
Dushane
Dushkin
Dusi
Dusik
Dusing
Duskey
Duskin
Dusky
Duso
Dussault
Dusseault
Dust
Duster
Dustin
Dustman
Duston
Dusza
Duszynski
Dutch
Dutcher
Dutchess
Dutchover
Dute
Duteau
Dutel
Duthie
Dutil
Dutile
Dutka
Dutkiewicz
Dutko
Dutra
Dutremble
Dutro
Dutrow
Dutschmann
Dutson
Dutt
Dutta
Dutter
Duttinger
Dutton
Duttry
Duttweiler
Duty
Duva
Duval
Duvall
Duve
Duvel
Duverne
Duverney
Duvernois
Duwe
Duwhite
Dux
Duxbury
Duy
Duyer
Duzan
Dvorak
Dvorsky
Dwaileebe
Dwan
Dwane
Dweck
Dwelle
Dwelley
Dwellingham
Dwiggins
Dwight
Dwinell
Dwire
Dworaczyk
Dworak
Dworkin
Dwornik
Dwyar
Dwyer
Dy
Dyal
Dyals
Dyar
Dyas
Dyba
Dybala
Dyce
Dyche
Dyches
Dyck
Dyckman
Dycus
Dyda
Dydell
Dydo
Dye
Dyen
Dyer
Dyers
Dyess
Dyett
Dygert
Dykas
Dyke
Dykema
Dykeman
Dykes
Dykhoff
Dykhouse
Dykhuizen
Dykstra
Dyl
Dyle
Dyll
Dylla
Dymek
Dyment
Dymke
Dymond
Dyner
Dynes
Dyreson
Dyron
Dyrstad
Dys
Dysart
Dyser
Dysinger
Dyson
Dzama
Dziadek
Dziak
Dziduch
Dziedzic
Dziegielewski
Dziekan
Dzierzanowski
Dziewanowski
Dzinski
Dziuba
Dziuban
Dziuk
Dziurawiec
Dzledzic
Dzubak
Dzurilla
Dzurnak
Dzuro
Dzwonkowski
Eaby
Eacho
Eachus
Eacret
Eaddy
Eade
Eadens
Eader
Eades
Eadie
Eads
Eady
Eafford
Eagan
Eagar
Eagen
Eager
Eagin
Eagle
Eagleman
Eaglen
Eagles
Eagleson
Eagleston
Eagleton
Eaglin
Eagon
Eagy
Eaker
Eakes
Eakin
Eakins
Eakle
Eakles
Eaks
Ealand
Ealey
Ealick
Ealley
Ealy
Eames
Eanes
Eanni
Eans
Eapen
Ear
Eardley
Earehart
Earenfight
Eargle
Earhart
Earheart
Earing
Earl
Earle
Earles
Earley
Earleywine
Earlgy
Earll
Earls
Early
Earlywine
Earman
Earnest
Earney
Earnhardt
Earnhart
Earnheart
Earnshaw
Earp
Earps
Earthly
Earthman
Earvin
Earwood
Eary
Easdon
Easey
Eash
Easker
Easler
Easley
Easlick
Easly
Easom
Eason
East
Eastburn
Eastep
Easter
Easterbrook
Easterbrooks
Easterday
Easterlin
Easterling
Easterly
Eastern
Easterwood
Eastes
Eastham
Eastin
Eastland
Eastlick
Eastling
Eastlund
Eastman
Eastmond
Easton
Eastridge
Eastwood
Eatherly
Eatman
Eatmon
Eaton
Eatough
Eavenson
Eaves
Eavey
Eayrs
Ebach
Ebadi
Ebanks
Ebarb
Ebaugh
Ebbers
Ebbert
Ebberts
Ebbesen
Ebbett
Ebbighausen
Ebbing
Ebbs
Ebe
Ebeid
Ebel
Ebeling
Eben
Ebener
Ebenstein
Eber
Eberenz
Eberhard
Eberhardt
Eberhart
Eberheart
Eberl
Eberle
Eberlein
Eberley
Eberlin
Eberline
Eberling
Eberly
Ebershoff
Ebersol
Ebersold
Ebersole
Eberspacher
Eberst
Ebert
Eberth
Eberting
Eberts
Eberwein
Ebesu
Ebesugawa
Ebey
Ebia
Ebilane
Ebinger
Eble
Eblen
Eblin
Ebling
Ebner
Ebo
Ebrahim
Ebrahimi
Ebrani
Ebright
Ebron
Ebsen
Eby
Eccles
Eccleston
Echard
Echaure
Echavarria
Echave
Echavez
Echegoyen
Echelberger
Echemendia
Echenique
Echevaria
Echevarria
Echeverri
Echeverria
Echeverry
Echoles
Echols
Echter
Echternach
Eck
Eckard
Eckardt
Eckart
Eckberg
Eckblad
Eckel
Eckelman
Eckels
Eckenrode
Ecker
Eckerle
Eckerman
Eckersley
Eckerson
Eckert
Eckes
Eckford
Eckhard
Eckhardt
Eckhart
Eckhoff
Eckis
Eckl
Eckland
Ecklar
Eckle
Eckler
Eckles
Eckley
Eckloff
Ecklund
Eckman
Eckmann
Eckmeyer
Eckols
Eckrich
Eckroad
Eckrote
Eckstein
Eckstrom
Eclarinal
Ecoffey
Economides
Economos
Economou
Economus
Economy
Ecord
Ecton
Ector
Edberg
Edd
Edde
Eddens
Eddie
Eddinger
Eddings
Eddington
Eddins
Eddleman
Eddlemon
Edds
Eddy
Ede
Edeker
Edel
Edelblute
Edelbrock
Edelen
Edeline
Edell
Edelman
Edelmann
Edelson
Edelstein
Edem
Edemann
Eden
Edenfield
Edenholm
Edens
Eder
Edes
Edey
Edgar
Edgcomb
Edge
Edgecomb
Edgehill
Edgell
Edgeman
Edgemon
Edgerly
Edgerson
Edgerton
Edgeston
Edgett
Edgeworth
Edghill
Edgin
Edgington
Edgley
Edgman
Edgmon
Edholm
Edick
Edie
Ediger
Edin
Edinger
Edington
Edis
Edison
Edith
Edland
Edlao
Edler
Edleston
Edley
Edlin
Edling
Edlow
Edlund
Edman
Edmeier
Edmerson
Edminster
Edmison
Edmisten
Edmister
Edmiston
Edmond
Edmonds
Edmondson
Edmons
Edmonson
Edmonston
Edmund
Edmunds
Edmundson
Edmunson
Edner
Edney
Ednie
Ednilao
Edouard
Edralin
Edridge
Edrington
Edris
Edsall
Edson
Edster
Edstrom
Edu
Eduardo
Edvalson
Edwads
Edward
Edwards
Edwardson
Edwin
Ee
Eeds
Eekhoff
Eelkema
Eells
Eerkes
Efaw
Effinger
Effland
Effler
Effner
Efford
Effron
Efird
Eflin
Efrati
Efron
Eftekhari
Efthimiou
Efurd
Egan
Egans
Egar
Egbe
Egbert
Ege
Egel
Egeland
Egelhoff
Egelston
Eger
Egerer
Egersdorf
Egert
Egerton
Egertson
Eget
Eggart
Egge
Eggebrecht
Eggeman
Eggen
Eggenberg
Eggenberger
Egger
Eggers
Eggert
Eggett
Eggimann
Eggington
Eggink
Eggins
Eggler
Eggleston
Eggleton
Egidio
Egitto
Egizi
Egland
Egle
Egler
Egleston
Egleton
Egley
Egli
Eglin
Eglinton
Egloff
Egner
Egnew
Egnor
Ego
Egolf
Eguchi
Eguia
Eguizabal
Egure
Egvirre
Egwuohua
Eheler
Ehigiator
Ehiginator
Ehinger
Ehl
Ehle
Ehleiter
Ehlen
Ehler
Ehlers
Ehlert
Ehli
Ehlke
Ehlman
Ehly
Ehman
Ehmann
Ehmen
Ehmer
Ehmke
Ehn
Ehnis
Ehorn
Ehr
Ehrenberg
Ehrenfeld
Ehrenzeller
Ehresman
Ehret
Ehrgott
Ehrhard
Ehrhardt
Ehrhart
Ehrich
Ehrisman
Ehrismann
Ehrke
Ehrle
Ehrler
Ehrlich
Ehrman
Ehrmann
Ehsan
Eibel
Eibell
Eiben
Eich
Eichberg
Eichberger
Eiche
Eichel
Eichelberger
Eichele
Eichelmann
Eichenauer
Eichenberg
Eichenberger
Eichenlaub
Eichenmiller
Eicher
Eichert
Eichholz
Eichhorn
Eichhorst
Eichinger
Eichler
Eichman
Eichmann
Eichner
Eichorn
Eichorst
Eichstadt
Eichstedt
Eick
Eicke
Eickhoff
Eickhorst
Eickman
Eickmeyer
Eid
Eide
Eidem
Eidemiller
Eiden
Eidinger
Eidschun
Eidson
Eidt
Eiesland
Eifert
Eifler
Eighmey
Eighmy
Eigner
Eigo
Eike
Eiken
Eikenberry
Eikleberry
Eikmeier
Eikner
Eiland
Eilbeck
Eilbert
Eilders
Eilderts
Eiler
Eilerman
Eilers
Eilert
Eilertson
Eilts
Eimer
Eimers
Einck
Einfeldt
Einhorn
Einspahr
Einstein
Einwalter
Eirich
Eirls
Eis
Eisaman
Eisbach
Eischeid
Eischen
Eischens
Eisel
Eisele
Eiselein
Eiselman
Eiseman
Eisen
Eisenbarth
Eisenbeis
Eisenbeisz
Eisenberg
Eisenberger
Eisenbrandt
Eisenhardt
Eisenhart
Eisenhauer
Eisenhaver
Eisenhower
Eisenman
Eisenmann
Eisenmenger
Eisensmith
Eisenstadt
Eisenstein
Eisentrout
Eisenzimmer
Eiser
Eisermann
Eisert
Eisiminger
Eisinger
Eisler
Eisley
Eisman
Eismann
Eismont
Eisnaugle
Eisner
Eison
Eissinger
Eitel
Eitniear
Eitnier
Eitzen
Ejide
Ek
Ekas
Ekberg
Ekdahl
Eke
Eken
Ekhoff
Ekholm
Ekin
Ekins
Ekis
Ekker
Eklov
Eklund
Ekman
Ekmark
Ekstein
Ekstrand
Ekstrom
Ekstrum
Ekwall
El
Elahi
Elam
Elamin
Eland
Elawar
Elazegui
Elbahtity
Elbaum
Elbaz
Elbe
Elbers
Elberson
Elbert
Elbertson
Elbie
Elbogen
Elchert
Elcock
Eld
Elden
Elder
Elderidge
Elderkin
Elders
Eldert
Eldib
Eldred
Eldredge
Eldreth
Eldridge
Eldrige
Eldringhoff
Eleam
Eleazer
Eleby
Eledge
Elefritz
Elek
Elem
Elena
Elenbaas
Elerick
Elerson
Elery
Eleveld
Elewa
Eley
Elfenbein
Elfering
Elfers
Elfert
Elford
Elfrink
Elfstrom
Elftman
Elg
Elgar
Elgart
Elgas
Elgen
Elger
Elgert
Elgin
Elguezabal
Elhaddad
Elhadi
Elhaj
Elhard
Elhassan
Elhosni
Eli
Elia
Eliades
Elian
Elias
Eliasen
Eliason
Eliassen
Elick
Elicker
Elie
Elieff
Eliezrie
Elifritz
Eligio
Elijah
Elio
Elion
Eliopoulos
Eliot
Eliott
Elis
Eliseo
Elison
Elisondo
Eliszewski
Elizabeth
Elizalde
Elizando
Elizarraras
Elizondo
Elk
Elkan
Elkayam
Elke
Elkin
Elkind
Elkington
Elkins
Elko
Elks
Ell
Ellamar
Elland
Ellanson
Ellard
Ellars
Ellcessor
Elldrege
Ellebracht
Ellebrecht
Elleby
Elledge
Ellefson
Ellegood
Elleman
Ellen
Ellena
Ellenbecker
Ellenbee
Ellenberg
Ellenberger
Ellenbogen
Ellenburg
Ellender
Ellens
Ellenwood
Eller
Ellerbe
Ellerbeck
Ellerbee
Ellerbrock
Ellerbusch
Ellerby
Ellerd
Ellerkamp
Ellerman
Ellermann
Ellers
Ellerson
Ellert
Ellery
Elles
Ellestad
Elletson
Ellett
Elliam
Ellias
Ellicott
Ellie
Elliem
Ellies
Elliff
Ellifritt
Ellifritz
Elling
Ellingboe
Ellingburg
Ellinger
Ellingham
Ellinghuysen
Ellingsen
Ellingson
Ellingsworth
Ellington
Ellingwood
Ellinwood
Elliot
Elliott
Ellis
Ellison
Ellisor
Elliston
Ellithorpe
Ellman
Ellner
Ello
Ellout
Ellrod
Ells
Ellsbury
Ellsmore
Ellson
Ellstrom
Ellsworth
Ellwanger
Ellwein
Ellwood
Ellworths
Ellyson
Ellzey
Elm
Elmaghrabi
Elman
Elmblad
Elmendorf
Elmer
Elmes
Elmo
Elmore
Elmquist
Elms
Elnicki
Elofson
Eloy
Elpert
Elquist
Elreda
Elrick
Elridge
Elrod
Elroy
Elsa
Elsaesser
Elsass
Elsasser
Elsayed
Elsberry
Elsbree
Elsbury
Else
Elsea
Elsen
Elsensohn
Elser
Elsey
Elshair
Elshant
Elsheimer
Elshere
Elsinger
Elskamp
Elsken
Elsmore
Elsner
Elson
Elstad
Elstner
Elston
Elswick
Elsworth
Elter
Elting
Elton
Eltringham
Eltzroth
Elumbaugh
Elvers
Elvert
Elvey
Elvin
Elvington
Elvira
Elvis
Elvsaas
Elward
Elway
Elwell
Elwer
Elwick
Elwonger
Elwood
Elworthy
Ely
Elza
Elzey
Elzie
Elzinga
Elzy
Em
Emal
Emami
Emano
Emanuel
Emanuele
Emanuelson
Emanus
Emard
Emayo
Embelton
Emberger
Emberley
Emberlin
Emberling
Emberson
Emberton
Embertson
Embery
Embler
Embleton
Embly
Embree
Embrey
Embry
Embs
Embt
Embury
Emch
Emde
Emdee
Emeche
Emel
Emenaha
Emerald
Emerich
Emerick
Emerling
Emerson
Emert
Emerton
Emeru
Emery
Emfield
Emfinger
Emge
Emhoff
Emick
Emig
Emigh
Emigholz
Emile
Emiliano
Emilio
Emily
Emison
Emke
Emlay
Emler
Emley
Emlin
Emling
Emma
Emmanuel
Emme
Emmel
Emmer
Emmerich
Emmerling
Emmerson
Emmert
Emmett
Emmette
Emmi
Emmick
Emmitt
Emmond
Emmons
Emmrich
Emms
Emo
Emond
Emons
Emore
Emory
Emoto
Empasis
Emperor
Empey
Empfield
Empie
Empleo
Empson
Emrich
Emrick
Emry
Emshoff
Emshwiller
Emslander
Emslie
Emswiler
Emuka
Emziah
Enama
Enamorado
Enbody
Encalade
Encallado
Encarnacion
Ence
Encinas
Encinias
Encino
Enciso
Enck
End
Ende
Endecott
Ender
Enderby
Enderle
Enderlin
Enders
Endersbe
Enderson
Endicott
Endito
Endler
Endlich
Endo
Endorf
Endow
Endres
Endresen
Endreson
Endries
Endris
Ends
Endsley
Enerson
Enfield
Enfinger
Enfort
Eng
Engard
Engberg
Engberson
Engblom
Engbretson
Engdahl
Enge
Engebretsen
Engebretson
Engel
Engelbach
Engelberg
Engelbert
Engelbrecht
Engelhard
Engelhardt
Engelhart
Engelhaupt
Engelke
Engelkemier
Engelken
Engelkes
Engelking
Engellant
Engelman
Engelmann
Engelmeyer
Engels
Engelsman
Engelson
Engelstad
Engeman
Engemann
Engen
Enger
Engerman
Engert
Engesser
Engessor
Enget
Engfer
Engh
Engholm
Engl
Englade
England
Englander
Englar
Engle
Engleberg
Englebert
Englebrecht
Engleby
Englehardt
Englehart
Engleking
Engleman
Englemann
Engler
Englert
Englerth
Engles
Engleson
Englett
Engley
Englin
English
Englund
Engman
Engnath
Engquist
Engram
Engroff
Engstrom
Engwall
Engwer
Enick
Enis
Enix
Enke
Enkerud
Enloe
Enlow
Enman
Enmon
Ennaco
Ennals
Ennels
Ennen
Ennenga
Ennes
Ennett
Ennis
Ennist
Enno
Enns
Enny
Eno
Enocencio
Enoch
Enochs
Enock
Enockson
Enomoto
Enos
Enote
Enrico
Enright
Enriguez
Enrique
Enriques
Enriquez
Enrriquez
Ensel
Ensell
Ensey
Ensign
Ensing
Enslen
Ensley
Enslinger
Enslow
Ensminger
Ensor
Enstad
Enstrom
Ensworth
Ensz
Entel
Enter
Enterline
Entin
Entinger
Entler
Entrekin
Entress
Entriken
Entrikin
Entrup
Entsminger
Entwisle
Entwistle
Entz
Entzi
Enwall
Enwright
Enyart
Enyeart
Enz
Enzenauer
Enzor
Eoff
Eon
Eovaldi
Epel
Eperson
Ephraim
Ephriam
Epifano
Epler
Epley
Eplin
Epling
Epolito
Epp
Eppard
Eppenger
Epperheimer
Epperley
Epperly
Epperson
Eppert
Eppes
Eppich
Eppihimer
Eppinette
Epping
Eppinger
Epple
Eppler
Eppley
Eppolito
Epps
Epson
Epstein
Epting
Equia
Equihua
Equils
Equiluz
Eracleo
Erard
Eraso
Erath
Erazmus
Erazo
Erb
Erbach
Erbe
Erben
Erbentraut
Erber
Erbes
Erbst
Erbstein
Erby
Ercanbrack
Erceg
Ercek
Erchul
Erck
Ercolani
Ercolano
Ercole
Erdahl
Erdelt
Erding
Erdley
Erdman
Erdmann
Erdmun
Erdner
Erdos
Ereaux
Erebia
Eredia
Erekson
Erenrich
Ereth
Erfert
Erger
Erhard
Erhardt
Erhart
Erholm
Eric
Erice
Erich
Erichsen
Erichson
Erick
Ericks
Ericksen
Erickson
Ericson
Ericsson
Erie
Eriks
Eriksen
Erikson
Eriksson
Erin
Erion
Eriquez
Erisman
Erixon
Erke
Erkela
Erker
Erkkila
Erlandson
Erlanger
Erlanson
Erle
Erlebach
Erlenbusch
Erler
Erlewine
Erlich
Erling
Erlwein
Erm
Ermatinger
Ermert
Ermita
Ermitanio
Ermitano
Ermogemous
Ernandez
Erne
Erner
Ernest
Ernesto
Erno
Ernsberger
Ernspiker
Ernst
Ernster
Ernstes
Ernstrom
Ernzen
Ero
Eroh
Eroman
Eron
Eros
Erp
Erpelding
Erpenbach
Erps
Errera
Errett
Errico
Errington
Erschen
Ersery
Erskin
Erskine
Erspamer
Erstad
Ertel
Ertelt
Ertl
Ertle
Ertley
Ertman
Ertz
Ertzbischoff
Ervay
Erven
Ervin
Ervine
Erving
Erway
Erwin
Erxleben
Erz
Esannason
Esary
Esau
Esaw
Esbensen
Esbenshade
Esbrandt
Escajeda
Escalante
Escalera
Escalero
Escalet
Escalon
Escalona
Escamilla
Escandon
Escanlar
Escarcega
Escareno
Escarrega
Escarsega
Escatel
Esch
Eschbaugh
Eschberger
Eschborn
Esche
Eschen
Eschenbach
Eschenbacher
Eschenbrenner
Eschenburg
Escher
Eschete
Eschette
Eschief
Eschmann
Eschrich
Esco
Escobar
Escobedo
Escobeo
Escober
Escobio
Escoe
Escorcia
Escort
Escorza
Escoto
Escott
Escovar
Escovedo
Escribano
Escudero
Escue
Escuriex
Escutia
Esenwein
Esera
Esfahani
Esguerra
Esh
Eshbaugh
Eshelman
Eshenbrenner
Eshleman
Eshlerman
Eshmon
Eshom
Eska
Eskaf
Eskaran
Eske
Eskeets
Eskelsen
Eskelson
Eskenazi
Esker
Eskew
Eskin
Eskind
Eskins
Eskola
Eskra
Eskridge
Eskuchen
Eslava
Esler
Eslick
Eslinger
Esmaili
Esmay
Esmiol
Esmon
Esmond
Esmont
Esnard
Esoimeme
Espada
Espadas
Espaillat
Espalin
Espana
Espanol
Esparaza
Esparsen
Esparza
Espe
Espejel
Espejo
Espeland
Espelien
Espenlaub
Espenoza
Espenscheid
Espenschied
Espenshade
Esper
Esperanza
Espericueta
Esperon
Espert
Espey
Espina
Espinal
Espindola
Espinel
Espino
Espinol
Espinola
Espinosa
Espinoza
Espiridion
Espiritu
Espitia
Esplain
Esplin
Esponda
Esposita
Esposito
Esposto
Espree
Espy
Esque
Esquea
Esqueda
Esquer
Esquerra
Esquerre
Esquibel
Esquilin
Esquinaldo
Esquirel
Esquiuel
Esquivel
Esquivez
Esquivias
Essa
Essaff
Essaid
Essary
Esselink
Esselman
Essen
Essency
Essepian
Esser
Essery
Esses
Essex
Esshaki
Essick
Essig
Essinger
Essix
Esskew
Essler
Esslinger
Essman
Essner
Esson
Estaban
Estabillo
Estabrook
Estabrooks
Estacion
Estain
Estala
Estanislau
Esteb
Esteban
Esteen
Estel
Estela
Estell
Estella
Estelle
Esten
Estep
Estepp
Ester
Esterbrook
Estergard
Esterline
Esterling
Esterly
Esters
Esterson
Estes
Estess
Estevane
Esteve
Esteves
Estevez
Estey
Esteybar
Esther
Estill
Estimable
Estis
Estle
Estler
Estock
Estok
Estorga
Estrada
Estrade
Estrado
Estrela
Estrella
Estrello
Estrem
Estremera
Estridge
Estrin
Estronza
Estus
Estwick
Esty
Esworthy
Etchells
Etchinson
Etchison
Etcitty
Eth
Ethel
Ethen
Etheredge
Etheridge
Etherington
Etherton
Ethier
Ethington
Ethridge
Etienne
Etier
Etkin
Etling
Etoll
Etringer
Etsitty
Ettel
Etter
Etters
Ettienne
Ettinger
Ettison
Ettl
Ettman
Etulain
Etzel
Etzkorn
Etzler
Eubank
Eubanks
Euber
Eudy
Euell
Euertz
Eugene
Eugenio
Eugley
Euler
Eull
Eun
Eunice
Eurbin
Eure
Euresti
Eurich
Europe
Eurton
Eury
Eusebio
Euser
Eustace
Eustache
Eustice
Eustis
Euton
Eutsey
Eutsler
Euvrard
Eva
Evan
Evanchalk
Evancho
Evanchyk
Evangelist
Evangelista
Evangelo
Evanich
Evanko
Evanoff
Evanoski
Evanosky
Evans
Evanski
Evansky
Evanson
Evaristo
Evarts
Evartt
Evasco
Evatt
Eve
Eveland
Eveleigh
Eveler
Eveleth
Eveline
Evelo
Evelyn
Even
Evener
Evens
Evensen
Evenson
Evenstad
Everage
Everding
Everest
Everet
Everett
Everette
Everetts
Everhardt
Everhart
Everheart
Everidge
Evering
Everitt
Everleth
Everley
Everline
Everly
Everman
Everroad
Evers
Eversley
Eversman
Eversmann
Eversmeyer
Eversole
Eversoll
Everson
Evert
Everton
Everts
Evertsen
Evertt
Evertz
Every
Eves
Evett
Evetts
Evey
Evick
Evilsizer
Evilsizor
Evinger
Evins
Eviston
Evitt
Evitts
Evjen
Evola
Evon
Evora
Evoy
Ewald
Ewalt
Ewan
Ewards
Ewart
Ewbank
Ewelike
Ewell
Ewen
Ewens
Ewer
Ewers
Ewert
Ewig
Ewin
Ewing
Ewings
Ewoldt
Ewton
Ewy
Exantus
Excell
Exe
Exel
Exford
Exilus
Exler
Exley
Exline
Exner
Exon
Expose
Extine
Exton
Exum
Eychaner
Eye
Eyer
Eyerman
Eyermann
Eyestone
Eyler
Eyles
Eylicio
Eyman
Eynon
Eyre
Eyrich
Eyster
Eytcheson
Eytchison
Eyton
Eyubeh
Ezagui
Ezdebski
Ezechu
Ezekiel
Ezell
Ezelle
Ezer
Ezernack
Ezparza
Ezpeleta
Ezzell
Ezzelle
Ezzo
Faaita
Faas
Fabacher
Fabbozzi
Fabbri
Fabeck
Fabel
Fabela
Fabello
Faber
Fabert
Fabian
Fabiani
Fabiano
Fabin
Fabio
Fabionar
Fabiszewski
Fabozzi
Fabre
Fabrizi
Fabrizio
Fabrizius
Fabro
Fabroquez
Fabros
Fabry
Fabula
Fabus
Faby
Facchine
Face
Facello
Facemire
Facenda
Facer
Facey
Facio
Fack
Fackler
Fackrell
Facteau
Factor
Facundo
Fadale
Fadden
Faddis
Fadei
Fadel
Fadeley
Fadely
Faden
Fader
Fadley
Fadness
Fadri
Faehnle
Faerber
Faes
Faessler
Faeth
Fafard
Fafinski
Fagala
Fagan
Fagen
Fager
Fageraes
Fagerlund
Fagerquist
Fagerstrom
Fagg
Faggard
Faggett
Faggins
Faggs
Fagin
Fagle
Fagley
Faglie
Fagnan
Fagnani
Fagnant
Fagnoni
Fago
Fague
Fagundes
Fagundo
Faherty
Fahey
Fahie
Fahl
Fahlsing
Fahlstedt
Fahner
Fahnestock
Fahning
Fahrenbruck
Fahrendorff
Fahrenkrug
Fahrenthold
Fahrenwald
Fahringer
Fahrlander
Fahrner
Fahrney
Fahrni
Fahs
Fahy
Faichtinger
Faidley
Faiella
Faigin
Faigle
Faigley
Fail
Failde
Failey
Failing
Failla
Faille
Failor
Fails
Fain
Faine
Faines
Faiola
Fair
Fairall
Fairbairn
Fairbank
Fairbanks
Fairbrother
Fairburn
Fairchild
Faircloth
Fairclough
Faire
Faires
Fairey
Fairfax
Fairfield
Fairhurst
Fairleigh
Fairless
Fairley
Fairly
Fairman
Fairrow
Fairweather
Fairy
Faisca
Faison
Faist
Fait
Faith
Faivre
Faix
Fajardo
Fajen
Fake
Fakhouri
Fakhoury
Fala
Falacco
Falack
Falah
Falanga
Falardeau
Falasco
Falb
Falbo
Falce
Falchi
Falci
Falcione
Falcioni
Falck
Falco
Falcon
Falcone
Falconer
Falconeri
Falconi
Falconio
Faldyn
Falencki
Faler
Falero
Fales
Faletti
Faley
Falge
Falgoust
Falgout
Falha
Falick
Falin
Falis
Falk
Falke
Falkenberg
Falkenhagen
Falkenstein
Falkenthal
Falker
Falkiewicz
Falkner
Falknor
Falkowski
Falks
Fall
Falla
Fallago
Fallaw
Falldorf
Fallen
Fallenstein
Faller
Fallert
Falley
Fallick
Fallie
Fallin
Falling
Fallis
Fallo
Fallon
Fallone
Fallow
Fallows
Falls
Falor
Falsetta
Falsetti
Falso
Falson
Falt
Falter
Falterman
Faltin
Falto
Faltus
Faltz
Falu
Falvey
Falvo
Falwell
Falzarano
Falzon
Falzone
Fam
Fama
Famageltto
Fambro
Fambrough
Famiano
Famiglietti
Familia
Famulare
Famy
Fan
Fanara
Fanatia
Fancher
Fandel
Fandino
Fandrich
Fane
Fanelle
Fanelli
Fang
Fangman
Fangmann
Fanguy
Faniel
Fanion
Fanizza
Fanizzi
Fanjoy
Fankhauser
Fann
Fannell
Fanner
Fanney
Fannin
Fanning
Fannings
Fanno
Fannon
Fanny
Fanoele
Fansher
Fansler
Fant
Fantasia
Fantauzzi
Fantauzzo
Fantazia
Fanter
Fanti
Fantin
Fantini
Fanton
Fantozzi
Fantroy
Fantz
Fanucchi
Fanzo
Fara
Farabaugh
Farabee
Farace
Faraci
Faraco
Farag
Faragher
Farago
Faragoza
Farah
Farahkhan
Faraimo
Faraj
Faraldo
Faraone
Farb
Farber
Farbman
Fardo
Fare
Farell
Farella
Faren
Farenbaugh
Farer
Farese
Faretra
Farfaglia
Farfalla
Farfan
Fargnoli
Fargo
Farguharson
Farha
Farhart
Farhat
Faria
Farias
Farid
Fariello
Faries
Farin
Farina
Farinacci
Farinas
Farinella
Farinha
Farino
Faris
Farish
Fariss
Farkas
Farkus
Farland
Farlee
Farler
Farless
Farley
Farlin
Farlow
Farm
Farman
Farmar
Farmer
Farmsworth
Farmwald
Farnam
Farnan
Farnell
Farner
Farnes
Farnese
Farness
Farney
Farnham
Farnsworth
Farnum
Farnworth
Faro
Faron
Farone
Farquer
Farquhar
Farquharson
Farr
Farra
Farrah
Farraj
Farrall
Farran
Farrand
Farrant
Farrar
Farrare
Farrauto
Farrel
Farrell
Farrelly
Farren
Farrens
Farrer
Farrey
Farria
Farrier
Farrill
Farrin
Farrington
Farrior
Farris
Farrish
Farro
Farron
Farrow
Farruggio
Farrugia
Farry
Fars
Farson
Farstvedt
Farthing
Farug
Faruolo
Farve
Farver
Farwell
Farwick
Farzan
Fasano
Fasbender
Fasching
Fasci
Fasciano
Fasel
Fasenmyer
Fash
Fashaw
Fasheh
Fasick
Faske
Faso
Fason
Fasone
Fass
Fassett
Fassinger
Fassino
Fassio
Fassler
Fassnacht
Fast
Faster
Fastic
Fastlaben
Fasula
Fasulo
Fasy
Fat
Fata
Fatchett
Fate
Fath
Fatheree
Fathree
Fathy
Fatica
Fatigate
Fatone
Fatora
Fattig
Fattore
Fatula
Fatzinger
Faubel
Fauber
Faubert
Faubion
Fauble
Faubus
Faucett
Faucette
Faucher
Fauci
Faudree
Fauerbach
Faughn
Faughnan
Faught
Faul
Faulcon
Faulconer
Faulds
Faulhaber
Faulisi
Faulk
Faulkenberry
Faulkenburg
Faulkenbury
Faulker
Faulkes
Faulkingham
Faulknen
Faulkner
Faulks
Faull
Fauls
Faulstich
Faulstick
Faunce
Fauntleroy
Faupel
Faur
Faure
Faurot
Faurote
Faurrieta
Faus
Fauscett
Fausel
Fauset
Fausett
Fausey
Fauske
Fausnaugh
Fausnaught
Fausset
Faust
Faustini
Faustino
Faustman
Fausto
Fauteux
Fauth
Fauver
Faux
Fava
Favalora
Favaloro
Favaro
Favaron
Favazza
Favela
Faver
Favero
Favia
Favian
Favieri
Favila
Favilla
Faville
Favolise
Favor
Favorite
Favorito
Favors
Favre
Favreau
Favro
Favuzza
Favuzzi
Faw
Fawbush
Fawcett
Fawell
Fawler
Fawley
Fawson
Fawver
Faxon
Fay
Fayad
Fayard
Faycurry
Faye
Fayer
Faykosh
Faylor
Fayne
Fayson
Faz
Fazekas
Fazenbaker
Fazio
Fazzari
Fazzi
Fazzina
Fazzinga
Fazzino
Fazzio
Fazzone
Feagan
Feaganes
Feagans
Feagen
Feagin
Feagins
Feagler
Feagley
Fealy
Feamster
Fear
Fearen
Fearheller
Fearing
Fearn
Fearnow
Fearon
Fears
Feary
Feasel
Feast
Feaster
Feather
Featheringham
Featheroff
Feathers
Featherston
Featherstone
Feauto
Feavel
Feazel
Feazell
Feazelle
Febbo
Febbraio
Febles
Febo
Febre
Febres
Febus
Fecat
Fecher
Fechner
Fechtel
Fechter
Fechtig
Fechtner
Feck
Fecko
Fecteau
Fecto
Fedak
Fedalen
Fedd
Fedde
Fedder
Fedderly
Feddersen
Feddes
Fede
Fedel
Fedele
Feder
Federer
Federgreen
Federici
Federick
Federico
Federkeil
Federle
Federowicz
Fedewa
Fedezko
Fedie
Fedigan
Fedler
Fedor
Fedora
Fedorchak
Fedorczyk
Fedorek
Fedoriw
Fedorka
Fedorko
Fedrick
Feduccia
Feduniewicz
Fee
Feeback
Feehan
Feehery
Feehly
Feekes
Feela
Feeler
Feeley
Feeling
Feely
Feemster
Feenan
Feener
Feeney
Feenstra
Feeny
Feerick
Feerst
Feery
Fees
Feeser
Feezell
Feezor
Fefer
Fegan
Fegaro
Feger
Fegett
Fegette
Feggins
Fegles
Fegley
Fego
Fegueroa
Fegurgur
Feher
Fehl
Fehling
Fehlinger
Fehlman
Fehn
Fehnel
Fehr
Fehrenbach
Fehribach
Fehringer
Fehrle
Fehrman
Fehrs
Feibusch
Feichter
Feichtner
Feick
Feickert
Feierman
Feiertag
Feig
Feigel
Feigenbaum
Feigh
Feighan
Feighner
Feight
Feijoo
Feikles
Feil
Feilbach
Feild
Feilds
Feiler
Feimster
Fein
Feinberg
Feinblatt
Feindt
Feinen
Feiner
Feingold
Feinman
Feinstein
Feintuch
Feirer
Feist
Feister
Feisthamel
Feistner
Feit
Feiteira
Feith
Fejes
Fekete
Fekety
Felan
Felarca
Felber
Felberbaum
Felch
Felcher
Felciano
Feld
Felde
Felder
Felderman
Feldhake
Feldhaus
Feldkamp
Feldker
Feldman
Feldmann
Feldmeier
Feldner
Feldpausch
Feldstein
Feldt
Feldtman
Feleppa
Felgenhauer
Felger
Feliberty
Felicano
Felice
Felicetti
Felicia
Feliciano
Felicien
Felicione
Felico
Felila
Felio
Felipa
Felipe
Feliu
Felix
Feliz
Felizardo
Felkel
Felker
Felkins
Felkner
Felks
Fell
Fellars
Felleman
Fellenbaum
Fellenz
Feller
Fellers
Fellezs
Fellhauer
Felli
Fellin
Felling
Fellinger
Fellman
Fellner
Fellon
Fellows
Fells
Felman
Felmet
Felmlee
Felonia
Felps
Fels
Felsenthal
Felsher
Felske
Felson
Felsted
Felt
Felten
Feltenberger
Felter
Feltes
Feltham
Feltman
Feltmann
Feltner
Felton
Felts
Feltus
Felty
Feltz
Felux
Felver
Felzien
Femat
Femi
Femia
Femmer
Femrite
Fenbert
Fenceroy
Fenchel
Fencil
Fencl
Fend
Fender
Fenderson
Fendlason
Fendler
Fendley
Fendrick
Fendt
Fenech
Feneis
Fenelon
Fenelus
Feng
Fenger
Fengler
Fenimore
Fenison
Fenix
Fenk
Fenley
Fenlon
Fenn
Fennel
Fennell
Fennelly
Fennema
Fenner
Fennern
Fennessey
Fennessy
Fennewald
Fenney
Fennig
Fenniman
Fennimore
Fenninger
Fenniwald
Fenny
Feno
Fenoff
Fenoglio
Fenrich
Fensel
Fenske
Fenster
Fenstermacher
Fenstermaker
Fent
Fenti
Fenton
Fentress
Fenty
Fenwick
Feola
Feoli
Fequiere
Fera
Feraco
Feramisco
Ferandez
Ferard
Ferber
Ferbrache
Ferch
Ferderer
Ferdico
Ferdig
Ferdin
Ferdinand
Ferdinandsen
Ferdolage
Ferdon
Ferebee
Fereday
Fereira
Ferell
Ferenc
Ference
Ferencz
Ferentz
Ferenz
Ferer
Feret
Ferg
Fergason
Ferge
Fergen
Fergerson
Fergerstrom
Fergeson
Fergoson
Fergurson
Fergus
Fergusen
Ferguson
Fergusson
Feria
Ferioli
Feris
Ferjerang
Ferkel
Ferko
Ferkovich
Ferland
Ferlenda
Ferlic
Ferm
Ferman
Fermin
Fermo
Fern
Fernades
Fernadez
Fernald
Fernanders
Fernandes
Fernandez
Fernando
Fernandz
Fernatt
Fernberg
Ferndez
Fernelius
Fernendez
Ferner
Fernet
Fernette
Fernholz
Ferniza
Fernow
Ferns
Fernsler
Fernstaedt
Fernstrom
Fero
Feron
Ferone
Ferouz
Feroz
Ferr
Ferra
Ferracioli
Ferraiolo
Ferraiz
Ferrales
Ferrall
Ferran
Ferrand
Ferrandino
Ferrando
Ferrante
Ferranti
Ferranto
Ferrao
Ferrar
Ferrara
Ferraraccio
Ferrari
Ferrarini
Ferrario
Ferraris
Ferraro
Ferrarotti
Ferratella
Ferrato
Ferratt
Ferre
Ferrebee
Ferree
Ferreira
Ferrel
Ferrell
Ferren
Ferrence
Ferrer
Ferrera
Ferreri
Ferrero
Ferrett
Ferretti
Ferreyra
Ferri
Ferrick
Ferrie
Ferrier
Ferriera
Ferries
Ferrigno
Ferrill
Ferriman
Ferrin
Ferringer
Ferringo
Ferrington
Ferrini
Ferrio
Ferriola
Ferriolo
Ferris
Ferrise
Ferriss
Ferriter
Ferro
Ferron
Ferrone
Ferroni
Ferrucci
Ferrufino
Ferrusi
Ferruso
Ferry
Ferryman
Fersner
Ferster
Fertal
Fertig
Fertik
Fertitta
Ferugson
Ferullo
Fesenbek
Fesenmyer
Feser
Fesh
Fesko
Fesler
Fesmire
Fesperman
Fess
Fessel
Fessenden
Fessler
Fest
Festa
Fester
Festerman
Festini
Fesus
Fetch
Fetchko
Feth
Fetherolf
Fetherston
Fetner
Fetrow
Fetsko
Fett
Fette
Fetter
Fetterhoff
Fetterly
Fetterman
Fetterolf
Fetters
Fettes
Fettig
Fetty
Fetui
Fetz
Fetzer
Feucht
Feuer
Feuerberg
Feuerborn
Feuerstein
Feulner
Feurtado
Feusier
Feuss
Feutz
Fevig
Fevold
Few
Fewell
Fewless
Fey
Feyen
Feyereisen
Feyh
Feyler
Fiacco
Fial
Fiala
Fialho
Fialkowski
Fiallo
Fiallos
Fiaschetti
Fiato
Ficarra
Ficchi
Ficek
Ficenec
Ficher
Fichera
Ficht
Fichter
Fichtner
Fick
Fickas
Fickbohm
Ficke
Fickel
Ficken
Ficker
Fickert
Fickes
Fickett
Fickle
Ficklen
Ficklin
Fickling
Ficks
Fico
Ficorilli
Fida
Fiddelke
Fiddler
Fidel
Fidell
Fidler
Fido
Fidsky
Fiducia
Fie
Fiebelkorn
Fiebich
Fiebig
Fiechter
Fieck
Fiecke
Fiedler
Fiedor
Fiedorowicz
Fiedtkou
Fiegel
Field
Fielden
Fielder
Fieldhouse
Fielding
Fieldman
Fields
Fieldson
Fieldstadt
Fiely
Fiene
Fiereck
Fierge
Fierman
Fiermonte
Fiero
Fierra
Fierro
Fierros
Fiers
Fierst
Fies
Fiesel
Fieselman
Fieser
Fiest
Fietek
Fietsam
Fife
Fifer
Fifield
Figaro
Figarsky
Figart
Figary
Figeroa
Figert
Figg
Figge
Figgeurs
Figgins
Figgs
Figiel
Figlar
Figler
Figley
Figliola
Figlioli
Figone
Figueira
Figueiras
Figueiredo
Figuera
Figueras
Figuerda
Figueredo
Figueroa
Figueron
Figura
Figurelli
Figures
Figuroa
Figurski
Fijal
Fijalkowski
Fike
Fikes
Fil
Fila
Filak
Filan
Filarecki
Filary
Filas
Filbert
Filbey
Filbrardt
Filburn
Filby
File
Fileds
Filer
Files
Filgo
Filhiol
Fili
Filiault
Filice
Filicetti
Filimaua
Filion
Filip
Filipek
Filipelli
Filipi
Filipiak
Filipovic
Filipovich
Filippelli
Filippello
Filippi
Filippides
Filippini
Filippo
Filippone
Filipponi
Filipski
Filkey
Filkins
Fill
Filla
Fillare
Filler
Fillers
Fillerup
Filley
Fillhart
Fillinger
Fillingham
Fillingim
Fillion
Fillip
Fillman
Fillmore
Fillo
Fillpot
Fillyaw
Filmer
Filmore
Filo
Filonuk
Filosa
Filoteo
Filpo
Filpus
Fils
Filsaime
Filsinger
Filson
Filteau
Filter
Filthaut
Filyan
Filyaw
Filzen
Fimbres
Fimbrez
Fina
Finamore
Finan
Finau
Finazzo
Fincel
Finch
Fincham
Fincher
Finchman
Finchum
Finck
Finco
Finder
Finders
Findlay
Findlen
Findley
Findling
Fine
Fineberg
Finefrock
Finegan
Finell
Finello
Finely
Fineman
Fineout
Finer
Fineran
Finerty
Fines
Finey
Finfrock
Fingado
Fingal
Fingar
Finger
Fingerhut
Fingerman
Fingerson
Fingleton
Fini
Finical
Finigan
Finister
Finizio
Fink
Finkbeiner
Finke
Finkel
Finkelman
Finkelson
Finkelstein
Finken
Finkenbinder
Finkenbiner
Finkle
Finklea
Finkler
Finklestein
Finkley
Finks
Finland
Finlay
Finlayson
Finley
Finn
Finne
Finnefrock
Finnegan
Finnel
Finnell
Finnemore
Finnen
Finner
Finneran
Finnerty
Finney
Finni
Finnicum
Finnie
Finnigan
Finnila
Finnin
Finnley
Fino
Finocan
Finocchiaro
Finona
Finseth
Finstad
Finster
Finto
Finton
Finucan
Finucane
Finwall
Finzel
Fiora
Fioranelli
Fioravanti
Fiore
Fiorella
Fiorelli
Fiorello
Fiorentini
Fiorentino
Fiorenza
Fiorenzi
Fioretti
Fiori
Fiorica
Fiorilli
Fiorillo
Fiorini
Fiorino
Fiorita
Fiorito
Fioritto
Fioto
Fiotodimitrak
Fipps
Fiqueroa
Fire
Firebaugh
Fireman
Firenze
Firestein
Firestine
Firestone
Firkey
Firkins
Firlik
Firlit
Firman
Firmin
Firoozbakht
Firpi
Firpo
Firsching
First
Firth
Fisanick
Fiscal
Fiscalini
Fiscel
Fiscella
Fisch
Fischang
Fischbach
Fischbein
Fischel
Fischels
Fischer
Fischetti
Fischhaber
Fischl
Fischler
Fischman
Fiscus
Fiser
Fisette
Fisger
Fish
Fishback
Fishbaugh
Fishbeck
Fishbein
Fishburn
Fishburne
Fishel
Fishell
Fisher
Fisherman
Fishman
Fisichella
Fisk
Fiske
Fisler
Fissel
Fissell
Fisser
Fissori
Fister
Fistler
Fitanides
Fitch
Fitcheard
Fitchett
Fitchette
Fitchpatrick
Fite
Fitgerald
Fithen
Fithian
Fitser
Fitsgerald
Fitten
Fitterer
Fitting
Fittje
Fitton
Fitts
Fitz
Fitzen
Fitzer
Fitzerald
Fitzgerald
Fitzgerlad
Fitzgerrel
Fitzgibbon
Fitzgibbons
Fitzhenry
Fitzherbert
Fitzhugh
Fitzke
Fitzloff
Fitzmaurice
Fitzmier
Fitzmorris
Fitzner
Fitzpatrick
Fitzrandolph
Fitzsimmons
Fitzsimons
Fitzwater
Fiumara
Fiume
Fiumefreddo
Fiveash
Fivecoat
Fiwck
Fix
Fixari
Fixico
Fizer
Fjeld
Fjeseth
Fjetland
Flaa
Flach
Flachs
Flack
Flad
Fladger
Fladung
Flagel
Flager
Flagg
Flagge
Flaggs
Flagiello
Flagler
Flagstad
Flaharty
Flahaven
Flaherty
Flahive
Flaig
Flaim
Flair
Flake
Flaker
Flakes
Flakne
Flaks
Flam
Flamand
Flamenco
Flament
Flamer
Flaming
Flaminio
Flamino
Flamio
Flamm
Flammang
Flanagan
Flanagin
Flanary
Fland
Flander
Flanders
Flanegan
Flanery
Flanigan
Flank
Flannagan
Flanner
Flannery
Flannigan
Flansburg
Flash
Flasher
Flatau
Flaten
Flater
Flath
Flathers
Flatley
Flatness
Flato
Flatt
Flatten
Flatter
Flattery
Flauding
Flaugher
Flaum
Flautt
Flavell
Flavin
Flavors
Flax
Flaxman
Fleagle
Fleak
Flebbe
Flecha
Flechas
Flecher
Flechsig
Fleck
Fleckenstein
Fleckles
Flecther
Fleeger
Fleegle
Fleek
Fleeks
Fleeman
Fleener
Fleenor
Fleer
Fleet
Fleeting
Fleetwood
Flegal
Flegel
Flegle
Flegler
Fleharty
Fleig
Fleischacker
Fleischer
Fleischhacker
Fleischman
Fleischmann
Fleischner
Fleisher
Fleishman
Fleisner
Fleitas
Fleites
Fleitman
Flem
Fleming
Flemings
Flemister
Flemm
Flemming
Flemmings
Flemmon
Flemmons
Flemons
Flenard
Flenaugh
Flener
Fleniken
Flenner
Flenniken
Flennoy
Flenord
Flenory
Flens
Flentge
Flentroy
Flesch
Fleschner
Flesher
Fleshman
Fleshner
Flesner
Flessner
Fletchen
Fletcher
Fletes
Flether
Flett
Fleurant
Fleurantin
Fleurent
Fleurilus
Fleurissaint
Fleury
Flever
Flewellen
Flewelling
Flexer
Flicek
Flick
Flicker
Flickinger
Flickner
Flieller
Flierl
Flies
Fliger
Flight
Flin
Flinchbaugh
Flinchum
Flinck
Flinders
Fling
Flink
Flinn
Flinner
Flinspach
Flint
Flinton
Flintroy
Flipp
Flippen
Flippin
Flippo
Flirt
Flis
Fliss
Flister
Flitcroft
Flitsch
Flitt
Flitter
Flitton
Flo
Floan
Flocco
Floch
Flock
Flocke
Flockerzi
Flockhart
Flodin
Flodman
Floe
Floer
Floerchinger
Floerke
Flohr
Flom
Flood
Flook
Floor
Floore
Flor
Flora
Floran
Florance
Floras
Florczak
Flore
Florea
Florek
Floren
Florence
Florencio
Florendo
Florens
Florentine
Florentino
Florenz
Flores
Floresca
Florestal
Florey
Florez
Flori
Floria
Florian
Floriano
Florida
Florido
Florin
Florine
Florio
Floris
Florkowski
Floro
Floros
Flory
Flosi
Floss
Flot
Flota
Floth
Floto
Flotow
Flott
Flournay
Flourney
Flournoy
Flow
Flowe
Flower
Flowers
Floyd
Fluaitt
Flucas
Fluck
Flud
Fludd
Flueck
Fluegel
Fluegge
Fluellen
Fluet
Fluetsch
Fluette
Flug
Flugence
Flugum
Fluharty
Fluhman
Fluitt
Fluke
Fluker
Flum
Flumerfelt
Flummer
Flurry
Flury
Flusche
Fluty
Fly
Flye
Flygare
Flynn
Flynt
Flythe
Flyzik
Foard
Foat
Fobbs
Fobes
Focht
Focke
Fockler
Focks
Foddrell
Foddrill
Fode
Foder
Fodera
Foderaro
Fodge
Fodness
Fodor
Foecke
Foecking
Foell
Foeller
Foerschler
Foerster
Foersterling
Foertsch
Foesch
Fogal
Fogarty
Fogel
Fogelman
Fogelquist
Fogelson
Fogerson
Fogerty
Fogg
Foggie
Foggs
Fogle
Fogleman
Fogler
Foglesong
Foglia
Foglio
Fogo
Fogt
Fogus
Fohl
Fohn
Foil
Foiles
Foister
Foisy
Fok
Foks
Folan
Foland
Folden
Folds
Foley
Folgar
Folger
Folino
Folio
Folk
Folken
Folkens
Folker
Folkers
Folkerts
Folkes
Folkins
Folkman
Folkner
Folks
Folland
Follansbee
Foller
Follett
Follette
Folley
Folliard
Follick
Follie
Follin
Follis
Follman
Follmer
Followell
Folmar
Folmer
Folse
Folsom
Folson
Folta
Folts
Foltz
Folwell
Folz
Fomby
Fon
Fonceca
Fonck
Fonda
Fondaw
Fondell
Fonder
Fondow
Fondren
Fondriest
Fondy
Fones
Fonesca
Foney
Fong
Fongeallaz
Fonger
Fongvongsa
Fonner
Fonnesbeck
Fonohema
Fons
Fonseca
Fonsecn
Font
Fontaine
Fontan
Fontana
Fontane
Fontanella
Fontanetta
Fontanez
Fontanilla
Fontanini
Fonte
Fonteboa
Fontecchio
Fontelroy
Fonteneau
Fontenelle
Fontenette
Fonteno
Fontenot
Fontes
Fontillas
Fontneau
Fontus
Fonua
Fonville
Foo
Foody
Fooks
Foor
Foore
Foos
Foose
Foot
Foote
Footer
Footman
Foots
Foppe
Foppiano
Foradori
Foraker
Foran
Forand
Forbach
Forber
Forberg
Forbes
Forbess
Forbis
Forbish
Forbs
Forbus
Forbush
Forcade
Force
Forcell
Forcello
Forch
Forchione
Forcht
Forcier
Forcino
Forck
Forcum
Ford
Forde
Forden
Fordham
Fordon
Fordyce
Fore
Foreback
Foree
Forehand
Forejt
Foreman
Forero
Foresman
Forest
Foresta
Forester
Foret
Forgach
Forge
Forget
Forgette
Forgey
Forgie
Forgione
Forgrave
Forgue
Forguson
Forgy
Foriest
Forinash
Foringer
Forister
Forkan
Forkell
Forker
Forkey
Forkin
Forkner
Forkosh
Forkum
Forlani
Forline
Forlivio
Form
Formaggioni
Forman
Formanek
Formato
Formby
Formella
Formento
Formey
Formhals
Formica
Formichelli
Formisano
Formosa
Fornaro
Fornataro
Fornea
Fornell
Forner
Fornerod
Fornes
Forness
Forney
Forni
Fornicola
Fornier
Fornili
Fornkohl
Forno
Foronda
Forpahl
Forquer
Forren
Forrer
Forres
Forrest
Forrester
Forrister
Forro
Forry
Fors
Forsberg
Forsch
Forschner
Forsee
Forsell
Forseth
Forsey
Forsgren
Forsha
Forshaw
Forshay
Forshee
Forshey
Forslin
Forslund
Forsman
Forsmann
Forsmark
Forson
Forss
Forst
Forstedt
Forster
Forsthoffer
Forsting
Forstner
Forston
Forsyth
Forsythe
Fort
Fortado
Forte
Fortenberry
Fortes
Fortgang
Forth
Forthman
Forti
Fortier
Fortin
Fortini
Fortino
Fortis
Fortman
Fortmann
Fortna
Fortner
Fortney
Forts
Fortson
Fortun
Fortuna
Fortunato
Fortune
Forward
Forwood
Forys
Fosberg
Fosbrook
Fosburg
Fosburgh
Foscue
Fosdick
Foshay
Foshee
Fosher
Foshie
Foskett
Foskey
Fosler
Foslien
Fosmire
Fosnaugh
Fosnough
Foss
Fossa
Fossati
Fosse
Fosselman
Fossen
Fosser
Fossett
Fossey
Fosso
Fosson
Fossum
Foste
Foster
Fostervold
Foston
Fote
Foth
Fothergill
Fotheringham
Foti
Fotopoulos
Foucault
Fouch
Foucha
Fouche
Foucher
Fougere
Fought
Fougner
Fouhy
Foulcard
Foulds
Foules
Foulger
Foulk
Foulke
Foulkes
Foulks
Found
Founds
Fountain
Fountaine
Fouquet
Fouquette
Fouracre
Fouraker
Fournet
Fournier
Fourre
Fouse
Fousek
Foushee
Foussell
Foust
Fout
Foutain
Foutch
Foute
Fouts
Fouty
Foutz
Foux
Fouyer
Fowble
Fower
Fowkes
Fowlar
Fowle
Fowler
Fowles
Fowley
Fowlie
Fowlkes
Fowlston
Fox
Foxe
Foxhoven
Foxman
Foxwell
Foxworth
Foxworthy
Foxx
Foy
Foye
Foyer
Frabizio
Frabizzio
Frabott
Frabotta
Fracassa
Fracasso
Fracchia
Fraccola
Fracier
Frack
Fraction
Fradette
Fradkin
Frady
Fraga
Fragale
Fragassi
Fragman
Fragmin
Fragnoli
Frago
Fragosa
Fragoso
Fragozo
Fraher
Frahm
Fraile
Frailey
Frain
Fraine
Fraint
Fraioli
Frair
Fraire
Fraise
Fraiser
Fraize
Fraizer
Fraker
Frakes
Fraklin
Fraleigh
Fraley
Fralic
Fralick
Fralin
Fralix
Fram
Frame
Framer
Frames
Frampton
Franc
Franca
France
Frances
Franceschi
Franceschina
Franceschini
Francesco
Francescon
Francescone
Francesconi
Francese
Franceski
Francey
Franch
Francher
Franchette
Franchi
Franchini
Francia
Francies
Francillon
Francione
Francios
Franciosa
Francis
Francisco
Franciscus
Francisque
Franck
Francke
Franckowiak
Franco
Francoeur
Francois
Francoise
Francolino
Francom
Francour
Franculli
Francy
Frandeen
Frandsen
Franeo
Franey
Frangione
Franich
Frank
Frankart
Franke
Frankel
Franken
Frankenberg
Frankenberry
Frankenfeld
Frankenfield
Frankenreiter
Frankenstein
Frankford
Frankforter
Frankhouser
Frankie
Frankiewicz
Frankin
Frankina
Frankl
Frankland
Franklin
Franklyn
Franko
Frankovich
Frankowski
Franks
Frankson
Frankum
Franpton
Franqui
Frans
Fransen
Fransisco
Franson
Franssen
Franta
Frantum
Franty
Frantz
Frantzich
Franz
Franza
Franze
Franzel
Franzen
Franzeo
Franzese
Franzetti
Franzi
Franzini
Franzman
Franzmann
Franzone
Franzoni
Frappier
Frary
Frasca
Frascella
Frasch
Fraschilla
Frasco
Frascone
Frase
Fraser
Frasher
Frashure
Frasier
Frasso
Frasure
Frater
Fratercangelo
Frates
Frati
Fratrick
Fratta
Frattali
Frattini
Fratto
Fratus
Fratzke
Frauenfelder
Frauenkron
Fraughton
Fraunfelter
Frausto
Frautschi
Fravel
Frawkin
Frawley
Fray
Frayer
Frayne
Frayre
Frayser
Fraze
Frazee
Frazell
Frazer
Frazey
Frazier
Frazzano
Frear
Freas
Frease
Freber
Freberg
Frech
Frechette
Frecker
Freckleton
Fred
Freda
Freddrick
Frede
Fredeen
Fredell
Fredenberg
Fredenburg
Frederic
Frederick
Fredericks
Fredericksen
Frederickson
Frederico
Frederiksen
Frederique
Fredette
Frediani
Fredicks
Fredieu
Fredin
Fredley
Fredline
Fredlund
Fredo
Fredregill
Fredric
Fredrick
Fredricks
Fredricksen
Fredrickson
Fredrikson
Free
Freeberg
Freeborn
Freeburg
Freeburger
Freeburn
Freeby
Freed
Freeders
Freedland
Freedlander
Freedle
Freedman
Freeh
Freehan
Freehling
Freehoffer
Freel
Freeland
Freeley
Freelon
Freelove
Freels
Freeman
Freemantle
Freemon
Freemyer
Freeney
Freer
Freerksen
Frees
Freese
Freestone
Freet
Freetage
Freeze
Fregeau
Freggiaro
Fregia
Fregoe
Fregoso
Fregozo
Freguson
Frehse
Frei
Freiberg
Freiberger
Freibert
Freid
Freidel
Freidet
Freidhof
Freidin
Freidkin
Freidman
Freie
Freier
Freiermuth
Freifeld
Freiheit
Freije
Freil
Freiler
Freilich
Freiling
Freilino
Freiman
Freimark
Freimuth
Frein
Freire
Freise
Freiseis
Freiser
Freisner
Freistuhler
Freitag
Freitas
Freker
Freligh
Frelow
Freman
Freme
Fremin
Fremming
Fremon
Fremont
French
Frend
Frenette
Frenger
Freniere
Frenkel
Frenner
Freno
Frens
Frentzel
Frenz
Frenzel
Frere
Frerich
Frerichs
Frericks
Frerking
Frescas
Fresch
Frese
Fresh
Freshley
Freshour
Freshwater
Fresquez
Fresta
Fret
Frett
Fretwell
Fretz
Freud
Freuden
Freudenberg
Freudenberger
Freudenburg
Freudenstein
Freudenthal
Freudiger
Freund
Freundlich
Frever
Frevert
Frew
Frewing
Frey
Freydel
Freyer
Freyermuth
Freyman
Freymuth
Freyre
Freytag
Freytas
Frezza
Frezzo
Friar
Frias
Friberg
Fribley
Fricano
Frichette
Frick
Fricke
Frickel
Fricker
Fricks
Frickson
Frid
Fridal
Friday
Friddell
Friddle
Fridell
Fridge
Fridley
Fridlington
Fridman
Frie
Friebel
Fried
Friedberg
Friede
Friedeck
Friedel
Frieden
Friedenberg
Friedenthal
Friederich
Friedhaber
Friedl
Friedland
Friedlander
Friedle
Friedler
Friedli
Friedline
Friedly
Friedman
Friedmann
Friedrich
Friedrichs
Friedrichsen
Friedrick
Friedstrom
Friedt
Friehauf
Friehe
Friel
Frieler
Frieling
Friels
Frieman
Friemering
Friend
Friendly
Friends
Frier
Frierdich
Frierson
Fries
Friese
Friesen
Friesenhahn
Friesner
Frieson
Friess
Friest
Friesz
Frietas
Frietsch
Frieze
Frigge
Frigo
Frigon
Frihart
Friis
Frija
Frikken
Friley
Friling
Frilling
Frilot
Fringer
Frings
Fringuello
Frink
Frint
Friot
Friou
Fripp
Frisbee
Frisbey
Frisbie
Frisby
Frisch
Frische
Frischkorn
Frischman
Friscia
Frisco
Frisell
Frisella
Frishkorn
Frishman
Frisina
Frisinger
Frisino
Frisk
Friske
Friskney
Frison
Frist
Fristoe
Fritch
Fritcher
Fritchey
Fritchley
Fritchman
Frith
Fritsch
Fritsche
Fritter
Fritts
Frittz
Fritz
Fritze
Fritzgerald
Fritzinger
Fritzler
Fritzman
Fritzpatrick
Frix
Frizell
Frizzell
Frizzle
Froats
Froberg
Frobish
Frock
Frodge
Frodsham
Froebe
Froedge
Froehle
Froehlich
Froehner
Froelich
Froeliger
Froemming
Froeschle
Froese
Frogge
Frohberg
Frohlich
Frohling
Frohman
Frohock
Frohwein
Froid
Froiland
Froio
Frolich
From
Froman
Fromberg
Fromdahl
Frometa
Fromm
Fromme
Frommer
Fromong
Fron
Fronce
Froncek
Froncillo
Fronczak
Frondorf
Fronduti
Froneberger
Fronek
Fronick
Froning
Fronk
Frontera
Frontiero
Frontis
Frontz
Froozy
Frosch
Froschheiser
Fross
Frossard
Frost
Frosto
Frothingham
Froyd
Fruchey
Fruchter
Frueh
Fruehauf
Fruehling
Fruge
Frugoli
Fruhling
Fruin
Fruit
Fruits
Frullate
Frum
Fruman
Frumkin
Frump
Frusci
Frusciante
Frush
Frushour
Frutchey
Fruth
Frutiger
Frutos
Frutoz
Fruusto
Fry
Fryar
Fryberger
Fryday
Frydman
Frye
Fryer
Fryling
Fryman
Frymark
Frymier
Frymire
Frymoyer
Frymyer
Fryou
Fryrear
Fryson
Fu
Fuapau
Fucci
Fuchs
Fuchser
Fucile
Fucillo
Fuda
Fudacz
Fudala
Fude
Fudge
Fuehrer
Fuel
Fuell
Fuelling
Fuemmeler
Fuentas
Fuente
Fuentes
Fuentez
Fuents
Fuerbringer
Fuerman
Fuerst
Fuerstenau
Fuerstenberg
Fuerstenberge
Fuerte
Fuertes
Fuery
Fuess
Fuest
Fuesting
Fugah
Fugate
Fugatt
Fuger
Fugere
Fugett
Fugh
Fugit
Fugitt
Fugle
Fugler
Fuglsang
Fugo
Fugua
Fugueroa
Fuhr
Fuhrer
Fuhri
Fuhriman
Fuhrman
Fuhrmann
Fuhrmeister
Fuhs
Fujihara
Fujii
Fujikake
Fujikawa
Fujimoto
Fujimura
Fujino
Fujioka
Fujisawa
Fujita
Fujiwara
Fukada
Fukano
Fukuda
Fukui
Fukumoto
Fukunaga
Fukuroku
Fukushima
Fulbright
Fulcher
Fulco
Fulda
Fuleki
Fulena
Fulenwider
Fulfer
Fulford
Fulgham
Fulghum
Fulginiti
Fulham
Fulk
Fulker
Fulkerson
Fulks
Fullagar
Fullam
Fullard
Fullbright
Fullem
Fullen
Fullenkamp
Fullenwider
Fuller
Fullerton
Fullford
Fullilove
Fulling
Fullington
Fulliton
Fullman
Fullmer
Fullmore
Fullwiler
Fullwood
Fulmer
Fulmore
Fulop
Fulp
Fuls
Fulsom
Fulson
Fulton
Fults
Fultz
Fulvio
Fulwider
Fulwiler
Fulwood
Fumagalli
Fumero
Funai
Funari
Funaro
Funches
Funchess
Funck
Fundenberger
Funderberg
Funderbunk
Funderburg
Funderburk
Funderburke
Fundis
Fundora
Fune
Funes
Funez
Fung
Funicello
Funk
Funke
Funkhouser
Funn
Funnell
Funnye
Funston
Funt
Fuoco
Fupocyupanqui
Fuqua
Fuquay
Furay
Furbeck
Furbee
Furber
Furbish
Furblur
Furbush
Furby
Furch
Furches
Furci
Furcron
Fure
Furer
Furey
Furfaro
Furfey
Furgason
Furgerson
Furgeson
Furgison
Furguson
Furia
Furino
Furkin
Furl
Furlan
Furler
Furlone
Furlong
Furlotte
Furlough
Furlow
Furman
Furmanik
Furna
Furnace
Furnari
Furnas
Furne
Furner
Furness
Furney
Furnia
Furnish
Furniss
Furno
Furr
Furrer
Furrh
Furrow
Furry
Furse
Furst
Furstenberg
Furtado
Furtak
Furtaw
Furth
Furtick
Furton
Furubotten
Furukawa
Furuta
Furutani
Furuya
Furuyama
Fury
Fus
Fusaro
Fusca
Fuscaldo
Fusch
Fuschetto
Fusco
Fuse
Fuselier
Fusha
Fushimi
Fusi
Fusik
Fusilier
Fusillo
Fusner
Fuson
Fuss
Fussell
Fusselman
Fussner
Fust
Fuster
Fuston
Futch
Futral
Futrell
Futrelle
Futter
Futterman
Fventes
Fyall
Fydenkevez
Fye
Fyfe
Fyffe
Fyke
Fykes
Fyksen
Fyler
Fyles
Fylnn
Fyock
Gaal
Gaar
Gaarder
Gaarsland
Gab
Gaba
Gabak
Gabaldon
Gabard
Gabardi
Gabaree
Gabay
Gabbamonte
Gabbard
Gabbay
Gabbert
Gabbett
Gabbin
Gabby
Gabe
Gabehart
Gabel
Gabeline
Gaber
Gabert
Gabhart
Gabino
Gabisi
Gabl
Gable
Gabler
Gables
Gabor
Gaboriault
Gabossi
Gabouer
Gabourel
Gaboury
Gabrel
Gabrelcik
Gabrenas
Gabri
Gabrial
Gabriel
Gabriele
Gabrielli
Gabrielsen
Gabrielson
Gabrysch
Gaby
Gacad
Gaccione
Gacek
Gach
Gachupin
Gacia
Gack
Gacke
Gackle
Gacusan
Gadapee
Gadbaw
Gadberry
Gadbois
Gadbury
Gadd
Gaddie
Gaddis
Gaddy
Gade
Gaden
Gades
Gadewoltz
Gadison
Gadley
Gadlin
Gadomski
Gadoury
Gadsby
Gadsden
Gadsen
Gadson
Gadue
Gadwah
Gadway
Gady
Gadzinski
Gaebler
Gaeddert
Gaede
Gaekle
Gaer
Gaerlan
Gaertner
Gaestel
Gaeta
Gaetani
Gaetano
Gaete
Gaeth
Gaetke
Gaetz
Gafanha
Gaff
Gaffer
Gaffey
Gaffigan
Gaffke
Gaffney
Gafford
Gagan
Gagarin
Gage
Gagel
Gagen
Gager
Gagg
Gaglia
Gagliano
Gagliardi
Gagliardo
Gagliardotto
Gaglio
Gaglione
Gagne
Gagner
Gagney
Gagnier
Gagnon
Gago
Gagon
Gahagan
Gahan
Gahl
Gahlman
Gahm
Gahn
Gahr
Gahring
Gaibler
Gaier
Gaietto
Gaige
Gail
Gailes
Gailey
Gailis
Gaillard
Gailliard
Gails
Gailun
Gain
Gainer
Gaines
Gainey
Gainforth
Gainor
Gainous
Gains
Gair
Gaiser
Gaisford
Gaitan
Gaiter
Gaiters
Gaither
Gaito
Gaitor
Gajardo
Gajate
Gajda
Gajeski
Gajewski
Gajica
Gal
Gala
Galabeas
Galacio
Galagher
Galam
Galamay
Galan
Galang
Galanga
Galanis
Galano
Galante
Galanti
Galapon
Galardi
Galardo
Galarita
Galarneau
Galarza
Galas
Galashaw
Galaska
Galassi
Galassini
Galasso
Galathe
Galati
Galauiz
Galavis
Galaviz
Galayda
Galaz
Galban
Galbavy
Galbiso
Galbo
Galbraith
Galbreath
Galbreth
Galdames
Galdamez
Galdi
Galdo
Galdon
Gale
Galea
Galeana
Galeano
Galeas
Galeazzi
Galecki
Galella
Galen
Galentine
Galeoto
Galeotti
Galer
Gales
Galetta
Galetti
Galey
Galfayan
Galford
Galgano
Galhardo
Gali
Galiano
Galic
Galicia
Galicinao
Galietti
Galik
Galimba
Galimberti
Galimi
Galimore
Galin
Galindez
Galindo
Galinis
Galinol
Galinoo
Galinski
Galioto
Galipeau
Galipo
Galizia
Galjour
Galka
Galkin
Gall
Galla
Gallacher
Gallaga
Gallager
Gallagher
Gallagos
Gallahan
Gallaher
Gallamore
Galland
Gallander
Gallant
Gallante
Gallardo
Gallarello
Gallargo
Gallaspy
Gallati
Gallatin
Gallaty
Gallaugher
Gallaway
Galle
Gallegas
Gallegher
Gallegly
Gallego
Gallegos
Gallegoz
Galleher
Gallemore
Gallen
Galleno
Gallenstein
Gallentine
Galler
Gallerani
Gallero
Gallery
Galles
Gallese
Gallet
Galleta
Galletta
Galletti
Galley
Galli
Gallian
Gallicchio
Gallichio
Gallien
Gallier
Galligan
Galligher
Galliher
Gallihugh
Gallik
Gallimore
Gallina
Gallinari
Gallinaro
Gallinger
Gallington
Gallion
Gallipeau
Gallipo
Gallishaw
Gallivan
Gallman
Gallmon
Gallo
Gallob
Gallodoro
Gallogly
Gallon
Gallop
Gallosa
Gallow
Galloway
Gallucci
Galluccio
Gallup
Gallups
Gallus
Gallusser
Galluzzi
Galluzzo
Gallwas
Gally
Galm
Galmore
Galo
Galofaro
Galon
Galow
Galper
Galpin
Gals
Galson
Galstad
Galster
Galstian
Galston
Galt
Galuppo
Galusha
Galuska
Galuski
Galustian
Galuszka
Galva
Galvan
Galvani
Galvano
Galven
Galves
Galvez
Galvin
Galvis
Galway
Galyan
Galyean
Galyen
Galyon
Gama
Gamache
Gamage
Gamarra
Gamba
Gambaiani
Gambale
Gambardella
Gambee
Gambel
Gambell
Gamber
Gamberg
Gamberini
Gambill
Gambino
Gamble
Gambler
Gambles
Gamblin
Gamboa
Gambold
Gambone
Gambrel
Gambrell
Gambrill
Gamby
Gamel
Gamela
Gamelin
Gamello
Gamer
Gamero
Gameros
Games
Gamet
Gamewell
Gamez
Gamino
Gamlin
Gamm
Gamma
Gammage
Gammel
Gammell
Gammill
Gammon
Gammond
Gammons
Gamon
Gamons
Gamotan
Gampong
Gampp
Gamrath
Gan
Gana
Ganas
Ganaway
Gancio
Gandara
Gandarilla
Gandarillia
Gandee
Gander
Gandert
Gandeza
Gandhi
Gandhy
Gandia
Gandolfi
Gandolfo
Gandrud
Gandy
Gane
Ganem
Ganer
Ganes
Ganesh
Ganey
Ganfield
Gang
Ganga
Gangadyal
Gange
Gangel
Gangelhoff
Gangell
Gangemi
Ganger
Gangestad
Gangi
Gangl
Gangler
Gangloff
Gangluff
Ganguli
Gangwer
Gangwish
Gani
Ganiban
Ganibe
Ganie
Ganigan
Ganim
Ganin
Ganino
Ganiron
Ganis
Ganison
Ganja
Ganji
Ganley
Gann
Gannaway
Ganner
Gannett
Gannetti
Gannoe
Gannon
Ganns
Gano
Ganoe
Ganong
Ganotisi
Ganoung
Gans
Gansburg
Gansen
Ganser
Gansert
Ganska
Ganske
Gant
Ganter
Gantert
Gantewood
Ganther
Gantner
Gantnier
Gantt
Gantvoort
Gantz
Gantzler
Ganus
Ganz
Ganze
Ganzer
Gao
Gaona
Gapen
Gapinski
Gapp
Gappa
Gara
Garabedian
Garacci
Garacia
Garafalo
Garafano
Garafola
Garahan
Garala
Garan
Garand
Garant
Garasha
Garate
Garavaglia
Garavelli
Garaventa
Garay
Garb
Garbacz
Garbarini
Garbarino
Garbe
Garber
Garbett
Garbin
Garbo
Garbutt
Garcea
Garceau
Garced
Garcelon
Garces
Garcia
Garcias
Garcilazo
Garcon
Garcy
Garczynski
Gard
Garde
Gardea
Gardecki
Gardella
Gardemal
Garden
Gardenas
Gardener
Gardenhire
Garder
Gardin
Gardiner
Garding
Gardinier
Gardino
Gardley
Gardner
Gardocki
Gardon
Gardunio
Garduno
Gardy
Gareau
Garelick
Garelik
Garen
Gares
Garetson
Garett
Garey
Garf
Garff
Garfias
Garfield
Garfinkel
Garfinkle
Garfunkel
Garg
Gargan
Gargani
Gargano
Gargis
Gargiulo
Garguilo
Gargus
Garhart
Gari
Garia
Garib
Garibai
Garibaldi
Garibaldo
Garibay
Garica
Garich
Garick
Gariepy
Gariety
Garigen
Garigliano
Garin
Garing
Garinger
Garis
Gariti
Garito
Garitty
Garity
Garivay
Garkow
Garland
Garlett
Garley
Garlick
Garling
Garlinger
Garlington
Garlits
Garlitz
Garlock
Garlovsky
Garlow
Garman
Garmany
Garmen
Garmire
Garmoe
Garmon
Garms
Garn
Garnache
Garnand
Garnder
Garneau
Garner
Garnes
Garness
Garnet
Garnett
Garnette
Garney
Garnham
Garnica
Garnick
Garnier
Garno
Garnow
Garns
Garnsey
Garnto
Garo
Garofalo
Garofano
Garofolo
Garon
Garone
Garoner
Garoutte
Garr
Garra
Garrabrant
Garraghty
Garrahan
Garramone
Garrand
Garrard
Garratt
Garraway
Garre
Garrean
Garreh
Garrell
Garrels
Garren
Garret
Garretson
Garrett
Garrette
Garrettson
Garrick
Garrido
Garriepy
Garriga
Garrigan
Garrigus
Garringer
Garrington
Garriott
Garris
Garrish
Garrison
Garriss
Garritson
Garrity
Garro
Garrod
Garron
Garrott
Garroutte
Garrow
Garry
Garsee
Garsia
Garside
Garsjo
Garske
Garski
Garson
Garst
Garstka
Garten
Gartenhaus
Gartenmayer
Garter
Garth
Garthee
Garthwaite
Gartin
Gartland
Gartley
Gartman
Gartner
Garton
Gartrell
Gartz
Garufi
Garuti
Garve
Garver
Garverick
Garvey
Garvie
Garvin
Garvis
Garwin
Garwood
Gary
Garza
Garzia
Garzon
Garzone
Gasaway
Gasbarro
Gasca
Gasch
Gaschke
Gascho
Gasco
Gascoigne
Gascon
Gascot
Gase
Gaseoma
Gaser
Gash
Gasienica
Gasiewski
Gasior
Gasiorowski
Gaska
Gaskamp
Gaskell
Gaskey
Gaskill
Gaskin
Gaskins
Gaslin
Gasman
Gasmen
Gasner
Gaspar
Gaspard
Gaspari
Gasparino
Gasper
Gasperi
Gasperini
Gasque
Gasquet
Gass
Gassaway
Gasse
Gassel
Gassen
Gasser
Gassert
Gassett
Gassler
Gassman
Gassner
Gasson
Gassoway
Gast
Gastel
Gastello
Gastellum
Gastelo
Gastelum
Gastelun
Gaster
Gastineau
Gastley
Gaston
Gastonguay
Gata
Gatch
Gatchalian
Gatchel
Gatchell
Gate
Gateley
Gately
Gaters
Gates
Gatesman
Gatesy
Gatewood
Gath
Gather
Gatheright
Gathers
Gathing
Gathings
Gathje
Gathman
Gathright
Gatica
Gatley
Gatliff
Gatlin
Gatling
Gato
Gaton
Gatrell
Gatski
Gatson
Gatta
Gattas
Gatten
Gatti
Gattie
Gattis
Gattison
Gatto
Gatton
Gatts
Gattshall
Gattuso
Gatwood
Gatz
Gatza
Gatzke
Gatzow
Gau
Gauani
Gaub
Gaubert
Gauch
Gaucher
Gauci
Gaucin
Gaud
Gaudenzi
Gaudet
Gaudett
Gaudette
Gaudier
Gaudin
Gaudino
Gaudio
Gaudioso
Gaudreau
Gaudy
Gauer
Gaufin
Gaufusi
Gauger
Gaughan
Gaughran
Gaugler
Gaukel
Gaukroger
Gaul
Gauld
Gaulden
Gauldin
Gaulding
Gaulin
Gaulke
Gault
Gaultney
Gaulzetti
Gaumer
Gaumond
Gaumont
Gauna
Gaunce
Gaunt
Gauntlett
Gauntner
Gauntt
Gauron
Gaus
Gause
Gausman
Gauss
Gaustad
Gaut
Gautam
Gauthier
Gauthreaux
Gautier
Gautney
Gautreau
Gautreaux
Gautsch
Gauvin
Gauwain
Gauze
Gavagan
Gavaldon
Gavalis
Gavan
Gave
Gavel
Gavell
Gavenda
Gaver
Gaves
Gavett
Gavette
Gavia
Gavidia
Gavigan
Gaviglia
Gavilanes
Gavin
Gavina
Gavinski
Gaviria
Gavit
Gavitt
Gavles
Gavula
Gaw
Gawel
Gawith
Gawlak
Gawlas
Gawlik
Gawron
Gawronski
Gawrych
Gawrys
Gawthorp
Gaxiola
Gay
Gayanilo
Gayden
Gaydos
Gaydosh
Gaye
Gayer
Gayfield
Gayhart
Gayheart
Gayle
Gayler
Gayles
Gaylor
Gaylord
Gayman
Gaymes
Gaymon
Gayne
Gayner
Gaynor
Gayo
Gayoso
Gaytan
Gayton
Gazaille
Gazaway
Gazda
Gazdecki
Gazdik
Gazella
Gazitano
Gaznes
Gazo
Gazza
Gazzara
Gazzillo
Gazzo
Gazzola
Gbur
Gdovin
Gdula
Geach
Geagan
Gealy
Gean
Geanopulos
Geans
Geant
Gear
Gearan
Gearhart
Gearheart
Gearin
Gearing
Gearlds
Gearn
Gearon
Gearwar
Geary
Geasley
Geater
Geathers
Gebauer
Gebbia
Gebbie
Gebel
Gebers
Gebert
Geberth
Gebhard
Gebhardt
Gebhart
Gebo
Gebrayel
Gecan
Gechas
Geck
Geckles
Geddes
Geddie
Geddings
Geddis
Gede
Gedeon
Gederman
Gedman
Gedney
Gedo
Gedris
Gedye
Gee
Geeding
Geel
Geelan
Geen
Geer
Geerdes
Geerken
Geers
Geery
Geesaman
Geesey
Geeslin
Geeter
Geeting
Geffers
Geffert
Geffken
Geffrard
Geffre
Gefroh
Gegenheimer
Gehl
Gehlbach
Gehle
Gehler
Gehlert
Gehlhausen
Gehling
Gehm
Gehman
Geho
Gehr
Gehred
Gehrer
Gehret
Gehrett
Gehri
Gehrig
Gehring
Gehringer
Gehris
Gehrke
Gehrki
Gehrking
Gehrlein
Gehrmann
Gehron
Geib
Geibel
Geibig
Geidl
Geidner
Geier
Geigel
Geiger
Geigle
Geiken
Geil
Geils
Geiman
Geimer
Geis
Geise
Geisel
Geiselman
Geisen
Geiser
Geisinger
Geisinsky
Geisler
Geiss
Geissel
Geissler
Geist
Geister
Geiszler
Geitgey
Geitner
Geitz
Gekas
Gelabert
Gelb
Gelbach
Gelbart
Gelber
Gelbowitz
Gelder
Geldmacher
Geldrich
Gelen
Gelerter
Gelfand
Gelfo
Gelfond
Gelger
Gelhar
Gelinas
Gelineau
Gelino
Gell
Gellatly
Gelle
Geller
Gellert
Gelles
Gellespie
Gellinger
Gellings
Gellis
Gellman
Gelman
Gelner
Gelo
Gelormino
Gelrud
Gelsinger
Gelston
Geltz
Gelvin
Gelzer
Gelzinis
Gemaehlich
Gembarowski
Gembe
Gemberling
Gembler
Gemes
Geml
Gemma
Gemme
Gemmel
Gemmell
Gemmen
Gemmer
Gemmill
Gemmiti
Gena
Genao
Genas
Genberg
Gencarelli
Genco
Gendel
Gendernalik
Gendler
Gendreau
Gendron
Gendusa
Gene
Gener
Genera
General
Generalao
Genereux
Generoso
Generous
Geneseo
Genest
Genet
Genett
Genetti
Geney
Geng
Genga
Genge
Gengler
Genia
Genich
Genier
Geniesse
Genin
Genis
Genito
Genna
Gennarelli
Gennaria
Gennaro
Gennett
Gennette
Gennings
Gennock
Gennusa
Geno
Genous
Genova
Genovese
Genovesi
Genre
Genrich
Gens
Gensel
Gensler
Genson
Gent
Genta
Gentelia
Genter
Gentery
Gentes
Gentges
Genther
Genthner
Gentilcore
Gentile
Gentili
Gentille
Gentis
Gentle
Gentleman
Gentles
Gentner
Gentry
Gentsy
Gentz
Gentzler
Genualdi
Genualdo
Genuario
Genung
Genz
Genzel
Genzone
Geoffrey
Geoffrion
Geoffroy
Geoghan
Geoghegan
Geohagan
Geoly
Georgalas
Georgales
George
Georgelis
Georges
Georgeson
Georgevic
Georghiou
Georgi
Georgia
Georgiades
Georgiadis
Georgiana
Georgiou
Georgis
Georgl
Georgopoulos
Gephardt
Gephart
Gepner
Geppert
Gerace
Gerache
Geraci
Geraghty
Gerald
Geraldes
Geraldo
Geralds
Gerard
Gerardi
Gerardo
Gerardot
Gerathy
Gerba
Gerbatz
Gerber
Gerberich
Gerbi
Gerbig
Gerbino
Gerbitz
Gerbs
Gercak
Gerchak
Gerckens
Gerczak
Gerdel
Gerdeman
Gerdes
Gerdiman
Gerding
Gerdis
Gerdsen
Gerdts
Gere
Gerecke
Geremia
Geren
Gerena
Geres
Gerety
Gerfin
Gergel
Gergely
Gergen
Gerguson
Gerhard
Gerhardt
Gerhart
Gerhauser
Gerhold
Gerich
Gerig
Gering
Geringer
Geris
Gerke
Gerken
Gerkin
Gerking
Gerl
Gerla
Gerlach
Gerland
Gerleman
Gerlich
Gerling
Gerlock
Gerloff
Gerlt
Germain
Germaine
German
Germana
Germani
Germann
Germano
Germany
Germer
Germershausen
Germinaro
Germon
Germond
Germundson
Germy
Gernatt
Gerner
Gernert
Gerney
Gero
Gerock
Geroge
Gerold
Gerondale
Geronime
Geronimo
Gerosa
Gerould
Gerow
Gerpheide
Gerrald
Gerrard
Gerraro
Gerrero
Gerringer
Gerrior
Gerrish
Gerrits
Gerritsen
Gerrity
Gerry
Gers
Gersbach
Gersch
Gershen
Gershenson
Gershey
Gershkovich
Gershman
Gershon
Gerson
Gerst
Gerstein
Gersten
Gerstenberger
Gerstenkorn
Gerster
Gerstle
Gerstner
Gerteisen
Gertel
Gertelman
Gerten
Gerth
Gerthung
Gertken
Gertner
Gerton
Gertsch
Gertsema
Gertsen
Gerty
Gertz
Gerula
Gerundo
Gervais
Gervase
Gervasi
Gervasio
Gerveler
Gervin
Gerwe
Gerweck
Gerwig
Gerwin
Gerwitz
Gerych
Geryol
Gerz
Gesamondo
Geschke
Gesell
Gesick
Gesing
Gesinski
Geske
Gesmondi
Gesner
Gess
Gessel
Gesselli
Gessert
Gessford
Gessner
Gest
Gestes
Gestether
Gesualdi
Gesualdo
Getachew
Getchell
Getchius
Getchman
Geter
Gethers
Getler
Getman
Getschman
Getsinger
Getson
Gett
Gettel
Gettelman
Gettenberg
Gettens
Getter
Gettig
Getting
Gettinger
Gettings
Gettis
Gettle
Gettman
Getto
Getts
Getty
Gettys
Getz
Getzlaff
Getzschman
Geuder
Geurin
Geurts
Gevara
Gevedon
Geving
Gevorkian
Gevorkyan
Gewant
Gewinner
Gey
Geyer
Geyette
Geyman
Gezalyan
Gfeller
Gfroerer
Ghaemmaghami
Ghamdi
Ghan
Ghanayem
Ghane
Ghant
Ghantt
Ghaor
Gharing
Ghazal
Ghazi
Ghaziani
Ghazvini
Ghea
Ghebremicael
Ghee
Gheen
Gheewala
Ghekiere
Ghelfi
Ghent
Ghera
Gherardi
Gherardini
Ghere
Gherman
Gheza
Ghia
Ghianni
Ghibaudy
Ghil
Ghiloni
Ghio
Ghiorso
Ghiringhelli
Gholar
Gholson
Gholston
Ghormley
Ghosh
Ghosn
Ghosten
Ghoston
Ghramm
Ghrist
Giacalone
Giacchi
Giacchino
Giaccio
Giaccone
Giachelli
Giacherio
Giachino
Giacobbe
Giacoletti
Giacolone
Giacomazzi
Giacomelli
Giacomini
Giacomo
Giacone
Giacopelli
Giagni
Giaimo
Giallorenzo
Giambalvo
Giambanco
Giambattista
Giambra
Giambrone
Giambruno
Giamichael
Giammarino
Giammona
Giampaolo
Giampapa
Giampietro
Gian
Gianandrea
Giancarlo
Giancaspro
Giancola
Giandelone
Giandomenico
Gianelli
Giang
Giangregorio
Giangrosso
Gianikas
Gianino
Giannakopoulo
Giannattasio
Giannavola
Giannecchini
Giannell
Giannelli
Giannetti
Giannetto
Gianni
Giannini
Giannitti
Giannone
Giannotti
Gianola
Gianopoulos
Gianopulos
Gianotti
Giantonio
Gianunzio
Giaquinta
Giaquinto
Giard
Giardina
Giardini
Giardino
Giarrano
Giarraputo
Giarratano
Giarrusso
Giarusso
Giasson
Gibala
Gibas
Gibb
Gibbard
Gibbens
Gibbings
Gibbins
Gibble
Gibbon
Gibboney
Gibbons
Gibbs
Gibbson
Gibby
Gibeau
Gibeault
Gibeaut
Giberson
Gibert
Gibes
Gibler
Giblin
Gibney
Giboney
Gibson
Gica
Gick
Gicker
Giczewski
Gidaro
Gidcumb
Gidden
Giddens
Giddings
Giddins
Gideon
Gidley
Gidney
Gidwani
Giebel
Gieber
Giebler
Giebner
Gieck
Giedlin
Giefer
Gieger
Giegerich
Giehl
Giel
Gielow
Gielstra
Gienger
Gier
Giera
Giere
Gierhart
Gieringer
Gierisch
Gierke
Gierlach
Gierling
Gierman
Giernoth
Gierut
Gies
Giesbrecht
Giese
Gieseke
Gieseking
Giesel
Gieselman
Gieseman
Giesen
Gieser
Giesing
Giesler
Giessinger
Giessler
Giesy
Gietz
Gietzen
Giff
Giffee
Giffen
Giffin
Giffith
Gifford
Gift
Gigante
Gigantino
Giger
Gigger
Giggey
Giggie
Gigler
Giglio
Gigliotti
Gignac
Gigstad
Giguere
Gihring
Gil
Gilani
Gilarski
Gilb
Gilbar
Gilbeau
Gilberg
Gilbert
Gilberti
Gilbertson
Gilbo
Gilboy
Gilbreath
Gilbreth
Gilbride
Gilcher
Gilchrest
Gilchrist
Gilcoine
Gilcrease
Gilcreast
Gilcrest
Gilcris
Gilday
Gildea
Gildemeister
Gilden
Gilder
Gilderman
Gildersleeve
Gilding
Gildner
Gildon
Gildore
Gildow
Gildroy
Gile
Giles
Gilespie
Gilfillan
Gilford
Gilfoy
Gilgan
Gilger
Gilgore
Gilgour
Gilham
Gilhooley
Gilhooly
Gilhousen
Gilhuly
Giliberto
Gilio
Gilkerson
Gilkes
Gilkey
Gilkison
Gill
Gillam
Gillan
Gilland
Gillard
Gillaspie
Gillcrest
Gille
Gillece
Gilleland
Gillem
Gillen
Gillentine
Gillenwater
Gillenwaters
Giller
Gillerist
Gillert
Gilles
Gillespi
Gillespie
Gillet
Gillett
Gillette
Gilley
Gillham
Gilliam
Gillian
Gilliand
Gillians
Gilliard
Gillice
Gillich
Gillick
Gillie
Gillies
Gillig
Gilligan
Gillihan
Gillikin
Gillilan
Gilliland
Gillim
Gillin
Gilling
Gillingham
Gillings
Gillins
Gilliom
Gillion
Gillis
Gillison
Gillispie
Gilliss
Gillitzer
Gillman
Gillmer
Gillming
Gillmor
Gillmore
Gillock
Gillogly
Gillom
Gillon
Gillooly
Gillotti
Gills
Gillson
Gillstrap
Gillum
Gillund
Gilly
Gillyard
Gilman
Gilmartin
Gilmer
Gilmore
Gilmour
Gilner
Gilomen
Gilpatric
Gilpatrick
Gilpin
Gilreath
Gilroy
Gilruth
Gilsdorf
Gilson
Gilstad
Gilster
Gilstrap
Giltner
Gilton
Gilvin
Gilyard
Gilzow
Gimar
Gimbel
Gimble
Gimenez
Gimlin
Gimm
Gimpel
Gimse
Gin
Ginanni
Ginard
Ginder
Gindhart
Gindi
Gindlesperger
Giner
Gines
Ging
Gingell
Ginger
Gingerich
Gingery
Gingg
Gingles
Gingras
Gingrich
Gingues
Ginkel
Ginn
Ginnery
Ginnetti
Ginnings
Ginnis
Ginns
Ginocchio
Ginolfi
Ginoza
Gins
Ginsberg
Ginsburg
Ginsel
Ginsky
Ginter
Ginther
Ginty
Ginyard
Ginzel
Gioacchini
Gioe
Gioffre
Gioia
Giombetti
Gionest
Gionet
Gionfriddo
Gionson
Gionta
Giordano
Giorgi
Giorgianni
Giorgini
Giorgio
Gioriano
Giorno
Giottonini
Giovanelli
Giovanetti
Giovanini
Giovanni
Giovannini
Giove
Giovinco
Giovino
Gip
Gipe
Gipp
Gipple
Gipson
Gira
Girad
Giraldo
Girand
Girard
Girardeau
Girardi
Girardin
Girardot
Girauard
Giraud
Girbach
Girdler
Girdley
Girdner
Gire
Girellini
Girgenti
Girgis
Girillo
Girling
Girman
Girmazion
Girod
Giroir
Girolami
Girolamo
Giron
Girona
Gironda
Girone
Girote
Girouard
Giroux
Girres
Girsch
Girsh
Girst
Girt
Girten
Girton
Girty
Girvan
Girven
Girvin
Gischer
Giscombe
Gish
Gishal
Gisi
Gisin
Gislason
Gisler
Gismondi
Gisondi
Gisriel
Gissel
Gissler
Gist
Gitchell
Gitelman
Githens
Gitlewski
Gitlin
Gitt
Gittelman
Gittens
Gitter
Gittere
Gitthens
Gitting
Gittinger
Gittings
Gittins
Gittleman
Gittler
Gitto
Gitzen
Gitzlaff
Giudice
Giuffre
Giuffrida
Giulian
Giuliani
Giuliano
Giulioli
Giumarro
Giunta
Gius
Giusti
Giusto
Givan
Givant
Given
Givens
Givhan
Gividen
Givliani
Giza
Gizinski
Gizzi
Gizzo
Gjelaj
Gjeltema
Gjelten
Gjerde
Gjertsen
Gjesdal
Gjokaj
Gjorven
Glaab
Glab
Glacken
Glackin
Glad
Gladden
Gladding
Glade
Gladen
Glader
Gladfelter
Gladhart
Gladhill
Gladin
Gladish
Gladle
Gladney
Gladson
Gladstein
Gladstone
Gladu
Gladue
Gladwell
Gladwin
Glady
Gladys
Gladysiewski
Gladysz
Glaeser
Glahn
Glance
Glancy
Glanden
Glander
Glandon
Glanton
Glantz
Glanville
Glanz
Glanzer
Glanzman
Glapion
Glarson
Glas
Glasbrenner
Glasby
Glasco
Glascock
Glascoe
Glascott
Glaser
Glasford
Glasglow
Glasgow
Glashen
Glasier
Glasner
Glasow
Glasper
Glaspie
Glaspy
Glass
Glassburn
Glassco
Glasscock
Glassel
Glasser
Glassett
Glassey
Glassford
Glassing
Glassman
Glassner
Glasson
Glathar
Glatt
Glatter
Glatz
Glatzel
Glau
Glauberman
Glaubke
Glaude
Glaue
Glauner
Glaus
Glauser
Glausier
Glavan
Glave
Glaves
Glaviano
Glavin
Glawe
Glawson
Glay
Glaza
Glaze
Glazebrook
Glazener
Glazer
Glazewski
Glazier
Glazner
Gleason
Gleaton
Gleave
Gleaves
Gleber
Glebocki
Gleckler
Gledhill
Glee
Gleen
Gleeson
Gleghorn
Gleich
Gleicher
Gleichman
Gleichweit
Gleim
Gleisner
Gleiss
Gleitz
Glembocki
Glen
Glende
Glendening
Glendenning
Glenister
Glenn
Glenna
Glennon
Glenny
Glesener
Glessing
Glessner
Glew
Glicher
Glick
Glicken
Glickman
Glickson
Glidden
Glidewell
Glidwell
Gliem
Glime
Glimp
Glimpse
Glines
Glinka
Glinkerman
Glinski
Glisan
Glise
Glish
Glisson
Glista
Gliues
Gliwski
Glock
Glockner
Glod
Gloden
Glodich
Glodo
Glodowski
Gloe
Gloeckler
Gloeckner
Gloff
Glogowski
Glomb
Glomski
Gloodt
Gloor
Glor
Glordano
Glore
Gloria
Glorioso
Glorius
Glory
Glos
Gloshen
Gloss
Glosser
Glossner
Glosson
Gloster
Gloston
Glotfelty
Glotzbach
Glotzbecker
Glover
Glovier
Glovinsky
Glow
Glowacki
Glowacky
Glowinski
Glowka
Glowski
Gloyd
Gluc
Gluck
Gluckman
Glucksman
Glud
Glueck
Glueckert
Glugla
Glumac
Glunt
Glunz
Gluszek
Gluth
Glymph
Glyn
Glynn
Gmernicki
Gnabah
Gnagey
Gnas
Gnatek
Gnau
Gnegy
Gneiser
Gnerre
Gniewek
Gnoza
Go
Goad
Goade
Goan
Goans
Goar
Goard
Goates
Goatley
Gobbi
Gobble
Gobbo
Gobea
Gobeil
Gobeille
Gobel
Gobeli
Goben
Gober
Gobern
Gobert
Gobeyn
Gobin
Goble
Gobler
Goblirsch
Gobrecht
Gocek
Gocha
Gochal
Gochanour
Gochenour
Gochett
Gochie
Gochnauer
Gochnour
Gocke
Gockel
Gockerell
Gockley
Goda
Godar
Godard
Godbe
Godbee
Godbey
Godbold
Godboldt
Godbolt
Godbout
Godby
Goddard
Godde
Godden
Gode
Godeaux
Godek
Godel
Goderich
Godert
Godette
Godfray
Godfrey
Godin
Godina
Godine
Godines
Godinez
Goding
Godinho
Godino
Godkin
Godleski
Godlewski
Godley
Godlove
Godnick
Godown
Godoy
Godsey
Godshall
Godsman
Godson
Godwin
Godwyn
Godyn
Godzik
Goe
Goebel
Goecke
Goeckel
Goedde
Goede
Goedecke
Goeden
Goedicke
Goedken
Goehl
Goehner
Goehring
Goehringer
Goeing
Goeke
Goeken
Goel
Goeldner
Goeller
Goeltz
Goelz
Goeman
Goen
Goens
Goepel
Goepfarth
Goepfert
Goeppinger
Goeppner
Goerdel
Goerdt
Goergen
Goerges
Goering
Goerke
Goerlich
Goerlitz
Goerner
Goers
Goertz
Goertzen
Goes
Goeser
Goessl
Goethals
Goethe
Goetjen
Goetsch
Goettel
Goetter
Goettig
Goetting
Goettl
Goettle
Goettman
Goettsch
Goettsche
Goetz
Goetze
Goetzinger
Goetzke
Goewey
Goff
Goffe
Goffer
Goffigan
Goffinet
Goffman
Goffney
Goffredo
Gofman
Goforth
Gofton
Goga
Gogan
Gogel
Goger
Gogerty
Goggans
Goggin
Goggins
Gogins
Goglia
Gogocha
Goguen
Goh
Goheen
Gohlke
Gohn
Gohr
Gohring
Goich
Goick
Goicoechea
Goike
Goin
Goines
Going
Goings
Goins
Goist
Gojcaj
Gojmerac
Gokey
Gola
Golab
Golabek
Golackson
Golan
Golanski
Golar
Golas
Golaszewski
Golay
Golba
Golberg
Golbin
Gold
Golda
Goldade
Goldak
Goldammer
Goldbach
Goldbaum
Goldbeck
Goldberg
Goldberger
Goldblatt
Golde
Goldeman
Golden
Goldenberg
Goldenman
Goldenstein
Golder
Golderer
Goldermann
Goldey
Goldfarb
Goldfeder
Goldfeld
Goldfield
Goldfine
Goldfischer
Goldfuss
Goldhaber
Goldhahn
Goldhammer
Goldhirsh
Goldhorn
Goldie
Goldin
Golding
Goldinger
Goldizen
Goldkamp
Goldklang
Goldman
Goldmann
Goldner
Goldrich
Goldrick
Goldrup
Golds
Goldsberry
Goldsboro
Goldsborough
Goldsby
Goldschmidt
Goldsmith
Goldson
Goldstein
Goldstock
Goldston
Goldstone
Goldsworthy
Goldthorpe
Goldthwait
Goldthwaite
Goldtooth
Goldtrap
Goldware
Goldwater
Goldwire
Goldwyn
Goldy
Goldyn
Golebiewski
Golebiowski
Golec
Goleman
Golemba
Golembeski
Golembiewski
Golen
Goletz
Goley
Golia
Golian
Golias
Golick
Golida
Goliday
Golie
Golightley
Golightly
Goligoski
Golik
Golinski
Golish
Golk
Golka
Golkin
Goll
Golla
Golladay
Gollehon
Goller
Gollhofer
Golliday
Gollier
Gollihar
Gollihue
Gollin
Gollman
Gollnick
Gollob
Gollogly
Gollop
Gollwitzer
Golly
Golob
Golojuch
Golom
Golomb
Golombecki
Golombek
Golonka
Golpe
Golphin
Golson
Golston
Golt
Goltra
Goltry
Goltz
Golub
Goluba
Golumski
Golz
Gomaz
Gomberg
Gombert
Gombos
Gome
Gomer
Gomes
Gomey
Gomez
Gomillion
Gomm
Gommer
Gomoll
Gomora
Gomoran
Gompert
Gompf
Gomzales
Gomzalez
Gonales
Gonalez
Gonazlez
Goncalves
Gonce
Gonchoff
Gonda
Gondek
Gonder
Gondola
Gondran
Gone
Gones
Goney
Gonez
Gong
Gongalez
Gongalves
Gongora
Gonnella
Gonnerman
Gonneville
Gonsales
Gonsalez
Gonsalues
Gonsalves
Gonsar
Gonser
Gonseth
Gonsiewski
Gonsior
Gonska
Gonsoulin
Gonterman
Gonthier
Gonya
Gonyea
Gonyer
Gonyo
Gonyou
Gonzaga
Gonzalas
Gonzalaz
Gonzale
Gonzalea
Gonzales
Gonzalez
Gonzalis
Gonzaliz
Gonzalos
Gonzelas
Gonzeles
Gonzelez
Gonzolas
Gonzoles
Gonzolez
Goo
Gooch
Good
Goodacre
Goodaker
Goodale
Goodall
Goodard
Goodchild
Goode
Goodell
Goodemote
Gooden
Goodenberger
Goodenough
Goodenow
Gooder
Goodermote
Goodfellow
Goodfield
Goodfriend
Goodger
Goodgine
Goodgion
Goodhart
Goodheart
Goodhile
Goodhue
Goodie
Goodiel
Goodier
Goodin
Goodine
Gooding
Goodkin
Goodknight
Goodland
Goodlet
Goodlett
Goodley
Goodlin
Goodling
Goodloe
Goodlow
Goodly
Goodman
Goodmanson
Goodmon
Goodner
Goodness
Goodnight
Goodnoe
Goodnough
Goodnow
Goodpaster
Goodpastor
Goodpasture
Goodreau
Goodrich
Goodrick
Goodridge
Goodroe
Goodrow
Goodrum
Goods
Goodsell
Goodsite
Goodson
Goodspeed
Goodstein
Goodvin
Goodwater
Goodwill
Goodwin
Goodwine
Goodwyn
Goody
Goodyear
Googe
Gookin
Goold
Goolden
Goolesby
Gooley
Goolia
Goolman
Goolsbee
Goolsby
Goombi
Goon
Goonan
Goonen
Goonez
Goos
Goosby
Goosen
Goosey
Gooslin
Goossen
Goossens
Gootee
Gootz
Gopen
Gopie
Gopin
Gora
Goracke
Goral
Goralski
Gorans
Goranson
Gorbea
Gorbet
Gorby
Gorczyca
Gorczynski
Gord
Gordan
Gorden
Gorder
Gordey
Gordillo
Gordils
Gordin
Gordineer
Gordinier
Gordis
Gordley
Gordner
Gordo
Gordon
Gordy
Gore
Gorecki
Goreczny
Goree
Gorelick
Gorelik
Gorell
Gorelli
Goren
Gorena
Gorenberg
Gorence
Gorenflo
Gores
Goretti
Gorey
Gorglione
Gorgo
Gorgone
Gorham
Gori
Gorin
Goring
Goris
Gorius
Gorka
Gorley
Gorlich
Gormally
Gorman
Gormanous
Gormley
Gormly
Gormont
Gorn
Gorneault
Gorney
Gornick
Gornie
Gornikiewicz
Gornto
Gorny
Gorovitz
Gorr
Gorrell
Gorri
Gorrill
Gorrindo
Gorringe
Gorski
Gorsky
Gorsline
Gorsuch
Gort
Gorter
Gortman
Gorton
Gorum
Gory
Gorychka
Gorz
Gorzynski
Gosa
Gosch
Gosche
Gosda
Gosden
Gosdin
Gose
Gosewisch
Gosey
Gosha
Goshay
Goshen
Goshi
Goshorn
Goshow
Gosier
Goslee
Goslin
Gosline
Gosling
Gosman
Gosnell
Gosney
Goss
Gossack
Gossage
Gossard
Gosse
Gosselin
Gossen
Gosser
Gosserand
Gosset
Gossett
Gossi
Gossin
Gossling
Gossman
Gosso
Gossom
Gosson
Gossow
Gostlin
Gostomski
Goston
Gostowski
Gosvener
Goswami
Goswick
Gosz
Gotay
Gotch
Gotcher
Gotchy
Goth
Gotham
Gothard
Gothe
Gothier
Gothro
Gotimer
Gotlib
Goto
Gotowka
Gotschall
Gotsche
Gotshall
Gott
Gotta
Gottardo
Gottdenger
Gottemoeller
Gotter
Gottesman
Gottfried
Gotthard
Gotthardt
Gotthelf
Gottke
Gottleber
Gottlieb
Gottlob
Gotto
Gottron
Gotts
Gottsch
Gottschalk
Gottschall
Gottshall
Gottula
Gottwald
Gotwalt
Gou
Goubeaux
Goucher
Gouchie
Goud
Goude
Goudeau
Goudelock
Goudge
Goudie
Goudreau
Goudy
Gouge
Gougeon
Gouger
Gough
Goughnour
Gougis
Gouin
Gouker
Goulart
Goularte
Goulas
Goulbourne
Gould
Goulden
Gouldie
Goulding
Gouldman
Gouldsberry
Goulet
Goulette
Gounder
Goupil
Gour
Gouras
Gourd
Gourdin
Gourdine
Gourlay
Gourley
Gouse
Gouthier
Goutremout
Gouty
Gouveia
Gouzalez
Gouzy
Govan
Gove
Govea
Gover
Govern
Governale
Govero
Govert
Govia
Govin
Govindeisami
Govoni
Govostes
Gow
Gowan
Gowans
Gowda
Gowdy
Gowell
Gowen
Gowens
Gower
Gowers
Gowey
Gowin
Gowing
Gowins
Gowler
Goy
Goya
Goyal
Goyco
Goyda
Goyen
Goyer
Goyette
Goyne
Goynes
Goza
Gozalez
Gozman
Graaf
Graap
Graban
Grabarczyk
Grabau
Grabauskas
Grabe
Grabel
Graben
Grabenstein
Graber
Grabert
Grabhorn
Grabill
Grabinger
Grabinski
Grable
Grabler
Grabner
Grabo
Grabonski
Graboski
Grabow
Grabowiecki
Grabowski
Grabowsky
Grabski
Grace
Graceffo
Gracely
Graces
Gracey
Graci
Gracia
Graciana
Graciani
Graciano
Gracie
Gracy
Graczyk
Grad
Graddy
Grade
Gradel
Graden
Gradert
Gradford
Gradias
Gradilla
Gradillas
Gradle
Gradley
Gradney
Grado
Gradowski
Gradwell
Gradwohl
Grady
Grae
Graeber
Graef
Graefe
Graeff
Graen
Graeser
Graeter
Graetz
Graf
Grafals
Grafe
Grafenstein
Graff
Graffagnino
Graffam
Graffeo
Graffney
Graft
Grafton
Gragas
Grage
Grageda
Gragert
Gragg
Grago
Gragson
Graham
Grahams
Grahan
Grahe
Grahl
Grahm
Grahn
Grahovac
Graichen
Graig
Grain
Grainey
Grainger
Graise
Grajales
Grajeda
Grajek
Grala
Gralak
Graleski
Grall
Gram
Gramacy
Gramajo
Gramberg
Gramble
Grambling
Grambo
Gramby
Gramc
Gramer
Grames
Gramham
Graminski
Gramley
Gramlich
Gramling
Gramm
Grammatica
Grammer
Grammes
Grammont
Gramolini
Grams
Gramza
Gran
Grana
Granada
Granade
Granado
Granados
Granahan
Granai
Granat
Granata
Granath
Granato
Granberg
Granberry
Granbois
Granby
Grand
Granda
Grandberry
Grandbois
Grandchild
Grande
Grandel
Granderson
Grandfield
Grandi
Grandin
Grandinetti
Grandison
Grandjean
Grandmaison
Grandmont
Grandner
Grando
Grandolfo
Grandon
Grandos
Grandstaff
Grandt
Grandusky
Grandy
Granelli
Graner
Granes
Graney
Granfield
Grange
Granger
Granholm
Graniela
Granier
Granieri
Graniero
Granillo
Granizo
Granlund
Grannan
Grannell
Granneman
Grannis
Grannum
Grano
Granquist
Granroth
Gransberry
Gransky
Granstaff
Granstrom
Grant
Grantham
Granthan
Grantier
Grantland
Granto
Grantz
Granucci
Granvil
Granville
Granvold
Granzella
Granzin
Granzow
Grap
Graper
Grapes
Grapp
Grappe
Grappo
Gras
Graser
Grasha
Grashot
Grasman
Grasmick
Grasmuck
Grass
Grassano
Grasse
Grasser
Grassham
Grassi
Grassia
Grassie
Grassl
Grassle
Grassman
Grassmyer
Grasso
Grastorf
Grasty
Grat
Grate
Grater
Grates
Grattan
Grattelo
Gratton
Gratz
Grau
Graubard
Grauberger
Graue
Grauel
Grauer
Graughard
Graul
Grauman
Graus
Grav
Grava
Gravat
Gravatt
Grave
Gravel
Gravelin
Graveline
Gravell
Gravelle
Gravely
Graven
Gravenstein
Graver
Gravert
Graves
Gravett
Gravette
Gravina
Gravino
Gravis
Gravit
Gravito
Gravitt
Gravitz
Gravley
Gravlin
Gravois
Graw
Grawburg
Grawe
Gray
Graybeal
Graybill
Graydon
Grayer
Grayes
Grays
Grayson
Graza
Graziani
Graziano
Grazier
Grazioplene
Graziosi
Grboyan
Grdina
Grealish
Gream
Greaney
Greany
Grear
Greaser
Greason
Greathouse
Greaux
Greaver
Greaves
Greb
Grebe
Grebel
Greber
Grebin
Grebner
Grebs
Grecco
Grech
Greco
Greczkowski
Greder
Greear
Greeb
Greek
Greeley
Greely
Greem
Green
Greenan
Greenawalt
Greenaway
Greenbacker
Greenbaum
Greenberg
Greenberger
Greenblatt
Greenburg
Greenbush
Greene
Greenen
Greener
Greenfeld
Greenfelder
Greenfield
Greengo
Greenhalge
Greenhalgh
Greenham
Greenhaw
Greenhill
Greenhouse
Greenhoward
Greenidge
Greenier
Greening
Greenland
Greenlaw
Greenleaf
Greenlee
Greenlees
Greenler
Greenley
Greenlief
Greenlow
Greenlun
Greenly
Greenman
Greenmyer
Greeno
Greenough
Greenrose
Greensfelder
Greenspan
Greenstein
Greenstreet
Greenup
Greenwade
Greenwald
Greenwaldt
Greenwall
Greenwalt
Greenway
Greenweig
Greenwell
Greenwood
Greep
Greer
Greeson
Greet
Greever
Greeves
Grefe
Greff
Grefrath
Greg
Grega
Gregan
Gregas
Greger
Gregersen
Gregerson
Gregg
Greggory
Greggs
Grego
Gregoire
Gregor
Gregoreski
Gregori
Gregoria
Gregorich
Gregorio
Gregoroff
Gregorski
Gregory
Gregson
Gregston
Gregus
Gregware
Greiber
Greider
Greif
Greife
Greig
Greigo
Greil
Grein
Greiner
Greinke
Greis
Greiser
Greisiger
Greising
Greisser
Greist
Greiwe
Grell
Grella
Gremel
Gremer
Gremillion
Greminger
Gremler
Gremmels
Gremminger
Gremo
Gren
Grenda
Grenet
Grenfell
Grengs
Grenier
Greninger
Grenke
Grenko
Grennan
Grennay
Grennon
Grenon
Grensky
Grenway
Grenz
Gresco
Gresh
Gresham
Gresko
Gresl
Gress
Gressett
Gressler
Gressley
Gressman
Gressmire
Greth
Grether
Greto
Gretsch
Grett
Gretter
Gretz
Gretzinger
Gretzner
Greubel
Greuel
Greulich
Grev
Greve
Grever
Greviston
Grew
Grewal
Grewe
Grewell
Grey
Greydanus
Greynolds
Greyovich
Greytak
Grgurevic
Grham
Gribben
Gribbin
Gribbins
Gribble
Griblin
Grice
Grich
Grider
Gridley
Grieb
Griebel
Griebling
Grieco
Grief
Grieff
Grieger
Griego
Griem
Grieme
Griep
Griepentrog
Grier
Grierson
Gries
Griesbach
Griesbaum
Griese
Grieser
Grieshaber
Grieshop
Griesi
Griesinger
Griesmeyer
Griess
Griest
Grieve
Grieves
Grife
Griffan
Griffard
Griffee
Griffel
Griffen
Griffes
Griffeth
Griffey
Griffie
Griffies
Griffieth
Griffin
Griffing
Griffins
Griffis
Griffith
Griffiths
Griffitt
Griffitts
Griffo
Griffon
Griffth
Griffy
Grifin
Grigaliunas
Grigalonis
Grigas
Grigg
Griggers
Griggs
Griglen
Grignon
Grigoreas
Grigorov
Grigsby
Grijalva
Grill
Grillette
Grilley
Grilli
Grillo
Grillot
Grills
Grim
Grima
Grimaldi
Grimaldo
Grimard
Grimaud
Grime
Grimes
Grimley
Grimlie
Grimm
Grimme
Grimmer
Grimmett
Grimmius
Grims
Grimshaw
Grimsley
Grimstead
Grimwood
Grinage
Grinberg
Grinde
Grindel
Grindeland
Grindell
Grinder
Grindle
Grindstaff
Grine
Griner
Grines
Grinie
Grinkley
Grinman
Grinnan
Grinnell
Grinner
Grinstead
Grinter
Grinvalsky
Grip
Gripp
Grippe
Grippen
Gripper
Grippi
Grippo
Grisanti
Grisby
Grise
Griseta
Grishaber
Grisham
Grishan
Grismer
Grismore
Grisom
Grisostomo
Grissam
Grisset
Grissett
Grissinger
Grisso
Grissom
Grisson
Grist
Gristede
Griswald
Griswell
Griswold
Griswould
Grit
Gritman
Gritsch
Gritten
Gritton
Gritz
Grivas
Grivetti
Grivna
Grivno
Grix
Grizzaffi
Grizzard
Grizzel
Grizzell
Grizzle
Groat
Grob
Grobe
Grober
Groberg
Grobes
Grobmyer
Grobstein
Groby
Groce
Groceman
Groch
Grochmal
Grochow
Grochowski
Grocott
Grode
Grodecki
Groden
Groder
Grodi
Grodin
Grodski
Groeber
Groebner
Groehler
Groen
Groene
Groenendyk
Groeneveld
Groeneweg
Groening
Groenke
Groepper
Groesbeck
Groeschel
Groesser
Groetken
Groetsch
Grof
Groff
Groft
Grogan
Grogg
Groh
Grohman
Grohmann
Groholski
Grohoske
Grohowski
Grohs
Groleau
Groll
Grollimund
Grollman
Grom
Groman
Gromer
Gromley
Gromoll
Gron
Grona
Gronberg
Grondahl
Grondin
Groner
Gronert
Gronewald
Gronitz
Gronlund
Gronosky
Gronowski
Gronquist
Gronstal
Gronvall
Groody
Groom
Groombridge
Groome
Groomes
Grooms
Groos
Groot
Groote
Groover
Gropp
Gropper
Gros
Grosbier
Grosby
Grosch
Grosclaude
Groscost
Grose
Groseclose
Grosenick
Grosh
Groshans
Groshek
Groshong
Grosjean
Groskreutz
Grosky
Grosland
Grosman
Gross
Grossack
Grossberg
Grosse
Grossen
Grossenbacher
Grosser
Grossetete
Grossett
Grosshans
Grossi
Grossklaus
Grosskopf
Grosskreutz
Grossley
Grossman
Grossmann
Grossmeyer
Grossnickle
Grosso
Grosswiler
Grosvenor
Grosz
Groszkiewicz
Grotberg
Grote
Grotelueschen
Groth
Grothaus
Grothe
Grotheer
Grothen
Grothoff
Groton
Grotts
Grotz
Grotzinger
Grotzke
Groulx
Ground
Grounds
Groupe
Grout
Grove
Grover
Groves
Grovier
Grow
Growcock
Growden
Growell
Growney
Groys
Grriffin
Gruba
Grubaugh
Grubb
Grubba
Grubbs
Grube
Grubel
Gruben
Gruber
Grubman
Gruby
Gruca
Gruda
Grudem
Grudt
Grudzien
Grudzinski
Grueber
Gruell
Gruen
Gruenberg
Gruenes
Gruenewald
Gruenhagen
Gruening
Grueninger
Gruenwald
Gruesbeck
Grueser
Gruett
Gruger
Gruhlke
Gruhn
Gruiger
Gruis
Grulke
Grulkey
Grullon
Grum
Gruman
Grumbach
Grumbine
Grumbles
Grumbling
Grumer
Grumet
Grumney
Grun
Grunau
Grunberg
Grund
Grunden
Grunder
Grundhoefer
Grundman
Grundmann
Grundmeier
Grundon
Grundy
Grune
Gruner
Grunert
Grunewald
Grunin
Gruninger
Grunlien
Grunow
Grunst
Gruntz
Grunwald
Grupa
Grupe
Grupp
Gruse
Grusenmeyer
Grush
Gruska
Grussendorf
Grussing
Grustas
Gruters
Gruver
Gruwell
Gruz
Gruzinsky
Grybel
Gryder
Grygiel
Grymes
Gryniuk
Gryszowka
Grzebien
Grzegorek
Grzelak
Grzesiak
Grzesik
Grzyb
Grzybowski
Grzywacz
Grzywinski
Gschwend
Gschwind
Gsell
Gstohl
Gu
Guadagno
Guadagnolo
Guadalajara
Guadalupe
Guadarrama
Guadeloupe
Guadian
Guadiana
Guagenti
Guagliano
Guagliardo
Guajardo
Gualdoni
Gualtieri
Guaman
Guan
Guanche
Guandique
Guanio
Guard
Guardado
Guardarrama
Guardia
Guardian
Guardino
Guardiola
Guardipee
Guareno
Guariglia
Guariglio
Guarin
Guarini
Guarino
Guarisco
Guarnera
Guarneri
Guarnieri
Guarno
Guarracino
Guarriello
Guasp
Guastella
Guay
Guba
Gubala
Gubbins
Guberman
Gubernath
Gubin
Gubitosi
Gubler
Gubser
Gucciardi
Gucciardo
Guccione
Gucker
Guckes
Guckin
Gucman
Gucwa
Gudaitis
Gudat
Gude
Gudenkauf
Guderian
Guderjahn
Gudgel
Gudgell
Gudger
Gudiel
Gudinas
Gudino
Gudis
Gudmundson
Gudmundsson
Gudroe
Gue
Guebara
Guebert
Guecho
Guedea
Guedes
Guedesse
Guedjian
Guedry
Gueits
Guel
Guelespe
Guelff
Guell
Guella
Guelpa
Guemmer
Guempel
Guenette
Guenin
Gueningsman
Guenison
Guenther
Guenthner
Guenthur
Guerard
Guercio
Guereca
Guerena
Guerera
Guerero
Guererro
Gueretta
Guerette
Guerin
Guerini
Guerino
Guerinot
Guernsey
Guerra
Guerrant
Guerrazzi
Guerreiro
Guerrera
Guerrero
Guerrette
Guerrido
Guerrier
Guerrieri
Guerriero
Guerrini
Guerro
Guerrouxo
Guerry
Guers
Guertin
Guesman
Guess
Guest
Guetersloh
Gueth
Guethle
Guetierrez
Guevana
Guevara
Guevarra
Guevera
Guevin
Guffanti
Guffey
Guffin
Guffy
Gugel
Guger
Gugerty
Guggemos
Guggenheim
Gugino
Gugler
Guglielmi
Guglielmina
Guglielmo
Gugliotta
Gugliotti
Gugliuzza
Guhl
Guiab
Guialdo
Guiao
Guiberteau
Guice
Guichard
Guida
Guidaboni
Guiden
Guider
Guidera
Guidetti
Guidi
Guidice
Guido
Guidos
Guidotti
Guidrey
Guidroz
Guidry
Guieb
Guiel
Guier
Guiffre
Guiga
Guiggey
Guignard
Guiher
Guijarro
Guilbault
Guilbe
Guilbeau
Guilbeault
Guilbeaux
Guilbert
Guilboard
Guild
Guildford
Guile
Guiles
Guilfoil
Guilfoos
Guilford
Guilfoyle
Guilianelli
Guiliani
Guiliano
Guill
Guillama
Guillan
Guillary
Guillaume
Guillebeau
Guillemette
Guillen
Guillerault
Guillereault
Guillermo
Guillet
Guillette
Guilliam
Guilliams
Guillory
Guillot
Guillote
Guillotte
Guilmain
Guilmette
Guilstorf
Guiltner
Guimaraes
Guimares
Guimond
Guin
Guinan
Guinane
Guinasso
Guiney
Guinle
Guinn
Guinnip
Guinta
Guintanilla
Guinther
Guinto
Guinyard
Guion
Guirand
Guire
Guirgis
Guisbert
Guise
Guisinger
Guiski
Guisti
Guitano
Guitar
Guitard
Guiterez
Guiterrez
Guith
Guitian
Guitierez
Guitierrez
Guitreau
Guittar
Guittennez
Guitterez
Guity
Guizar
Gula
Gulan
Gularte
Gulati
Gulbraa
Gulbrandsen
Gulbrandson
Gulbransen
Gulbranson
Gulde
Guldemond
Gulden
Guldin
Guler
Guley
Gulick
Gulikers
Gulini
Gulino
Gulinson
Gulisano
Gulizio
Gulke
Gull
Gulla
Gullace
Gullage
Gullatt
Gullatte
Gulledge
Gullett
Gullette
Gulley
Gullick
Gullickson
Gulliksen
Gulling
Gullion
Gulliver
Gullixson
Gullo
Gullotta
Gullung
Gully
Gulnac
Gulnick
Gulotta
Gulston
Gulsvig
Gulyas
Gum
Gumaer
Gumb
Gumbel
Gumbert
Gumbs
Gumina
Gumm
Gummer
Gummersall
Gummersheimer
Gummo
Gump
Gumpert
Gumphrey
Gumprecht
Gums
Gumz
Gun
Gunagan
Gunawan
Gunby
Gundelach
Gunder
Gunderman
Gundersen
Gunderson
Gundert
Gundlach
Gundrum
Gundry
Gundy
Gungor
Gunia
Gunkel
Gunkelman
Gunlock
Gunn
Gunnarson
Gunnell
Gunnells
Gunnels
Gunner
Gunnerson
Gunnett
Gunning
Gunnoe
Gunselman
Gunsolley
Gunsolus
Gunst
Gunstream
Gunter
Gunterman
Guntert
Guntharp
Gunther
Gunthrop
Gunto
Guntrum
Gunyan
Gunyon
Gunzalez
Gunzelman
Gunzenhauser
Guo
Guoan
Guppy
Gupta
Guptill
Gupton
Gura
Gural
Guralnick
Gurecki
Gureczny
Gurevich
Gurganious
Gurganus
Guridi
Gurin
Guritz
Gurka
Gurke
Gurkin
Gurley
Gurne
Gurnee
Gurner
Gurnett
Gurney
Gurnsey
Gurr
Gurrad
Gurrero
Gurrieri
Gurrola
Gurry
Gurske
Gurski
Gursky
Gurtin
Gurtner
Gurule
Gurvine
Gurwell
Gurwitz
Gusa
Gusciora
Guse
Gusewelle
Gushard
Gushee
Gushi
Gushiken
Gushue
Gushwa
Guske
Gusky
Gusler
Gusman
Gusmar
Guss
Gussin
Gussler
Gussman
Gussow
Gust
Gustafson
Gustason
Gustave
Gustaveson
Gustavson
Guster
Gustin
Gustine
Gustis
Gustison
Gustitus
Gustovich
Gustus
Guszak
Gut
Gutches
Gutekunst
Gutenberg
Gutenberger
Gutenson
Guterman
Gutermuth
Guterrez
Guterriez
Gutgesell
Guth
Guthary
Gutherie
Guthmiller
Guthorn
Guthridge
Guthrie
Gutiennez
Gutieres
Gutierez
Gutierre
Gutierres
Gutierrex
Gutierrez
Gutirrez
Gutjahr
Gutkin
Gutknecht
Gutkowski
Gutman
Gutmann
Gutoski
Gutowski
Gutrerrez
Gutreuter
Gutsche
Gutschow
Gutshall
Gutt
Gutta
Guttenberg
Gutter
Gutteridge
Gutterman
Gutterrez
Guttery
Guttierez
Guttierrez
Gutting
Guttirez
Guttman
Guttmann
Guttormson
Gutzler
Gutzman
Gutzmann
Gutzmer
Gutzwiller
Guy
Guye
Guyer
Guyet
Guyett
Guyette
Guyll
Guymon
Guynes
Guynn
Guynup
Guyon
Guyot
Guyott
Guys
Guyton
Guz
Guzalak
Guzek
Guzewicz
Guzi
Guziak
Guziczek
Guziec
Guzik
Guzma
Guzman
Guzmdn
Guzon
Guzowski
Guzy
Guzzardo
Guzzetta
Guzzi
Guzzio
Guzzo
Gverrero
Gwalthney
Gwaltney
Gwartney
Gwathney
Gwenn
Gwillim
Gwilt
Gwin
Gwinn
Gwinner
Gwirtz
Gwozdz
Gwyn
Gwynes
Gwynn
Gyaki
Gyatso
Gyger
Gyles
Gyllenband
Gyllensten
Gysin
Gyurko
Gzym
Ha
Haab
Haaby
Haack
Haacke
Haaf
Haag
Haaga
Haage
Haagensen
Haak
Haake
Haakenson
Haakenstad
Haaker
Haakinson
Haaland
Haan
Haapala
Haar
Haare
Haarstad
Haas
Haasch
Haase
Haass
Haataja
Haaz
Habash
Habben
Habbs
Habbyshaw
Habeck
Habeeb
Habegger
Habel
Habenicht
Haber
Haberer
Haberern
Haberkamp
Haberkorn
Haberle
Haberman
Habermann
Habermehl
Habersham
Haberstroh
Habib
Habibi
Habicht
Habif
Habig
Habina
Habisch
Hable
Haboush
Habowski
Habrock
Haby
Hach
Hacher
Hachette
Hachey
Hachez
Hachigian
Hachting
Hack
Hackathorn
Hackbart
Hackbarth
Hackborn
Hacke
Hackel
Hacken
Hackenberg
Hackenbery
Hackenmiller
Hacker
Hackerd
Hackerott
Hackethal
Hackett
Hackey
Hackford
Hacking
Hackl
Hackle
Hackleman
Hackler
Hackley
Hackman
Hackmann
Hackmeyer
Hackner
Hackney
Hackshaw
Hackwell
Hackworth
Hacopian
Haczynski
Hada
Hadad
Hadaller
Hadaway
Hadcock
Haddad
Haddan
Haddaway
Hadden
Haddenham
Hadder
Haddick
Haddix
Haddock
Haddon
Haddow
Haddox
Hade
Hadef
Hadel
Haden
Hader
Hadesty
Hadfield
Hadges
Hadian
Hadiaris
Hadland
Hadler
Hadley
Hadlock
Hadnot
Hadnott
Hadsall
Hadsell
Hadson
Hadvab
Hadwin
Hady
Haeber
Haeck
Haeckel
Haecker
Haeder
Haefele
Haefner
Haegele
Haeger
Haehn
Haen
Haener
Haer
Haering
Haerr
Haertel
Haerter
Haese
Haessig
Haessler
Haessly
Haeuser
Haeussler
Hafele
Hafeman
Hafemeister
Hafen
Hafenbrack
Hafenstein
Hafer
Haferkamp
Haff
Hafferkamp
Haffey
Haffling
Haffner
Hafford
Haflett
Hafley
Hafner
Haft
Hafter
Haga
Hagadone
Hagadorn
Hagaman
Hagan
Hagans
Hagar
Hagarty
Hagberg
Hage
Hagebusch
Hagedorn
Hagee
Hagel
Hagele
Hagelgans
Hageman
Hagemann
Hagemeier
Hagemeyer
Hagen
Hagenbaugh
Hagenbrok
Hagenbuch
Hagene
Hagenhoff
Hagens
Hagenson
Hageny
Hager
Hagerman
Hagert
Hagerty
Hages
Hagey
Hagg
Haggan
Haggans
Haggar
Haggard
Haggart
Haggarty
Haggberg
Hagge
Haggen
Hagger
Haggermaker
Haggerton
Haggerty
Haggett
Haggin
Haggins
Haggis
Hagglund
Haggstrom
Haghighi
Hagie
Hagin
Hagins
Hagist
Hagle
Hagler
Hagley
Haglund
Hagmaier
Hagman
Hagmann
Hagner
Hagon
Hagood
Hagopian
Hagos
Hagstrom
Hague
Hagwell
Hagwood
Hagy
Hahl
Hahm
Hahn
Hahne
Hahner
Hahnert
Hahs
Hai
Haid
Haider
Haifa
Haifley
Haig
Haigh
Haight
Haigler
Haigwood
Haik
Hail
Haile
Hailes
Hailey
Hails
Hailstock
Hailstone
Haimes
Haims
Hain
Hainds
Haine
Hainer
Haines
Hainesworth
Hainey
Hainley
Hainline
Hains
Hainsey
Hainsworth
Hair
Haire
Hairell
Hairfield
Hairgrove
Hairr
Hairster
Hairston
Haislett
Haisley
Haislip
Haist
Haisten
Hait
Haith
Haithcock
Haitz
Hajdas
Hajduk
Hajdukiewicz
Hajek
Hakala
Hakanson
Hake
Hakeem
Hakel
Haken
Haker
Hakes
Hakey
Hakim
Hakimi
Hakimian
Hakkila
Hal
Halaas
Halaby
Halajian
Halaliky
Halama
Halas
Halasz
Halat
Halbach
Halberg
Halbershtam
Halberstam
Halbert
Halbritter
Halbrook
Halbrooks
Halbur
Halburnt
Halcom
Halcomb
Halcon
Halcott
Hald
Haldane
Haldeman
Halder
Halderman
Haldi
Haldiman
Hale
Haleamau
Halechko
Halek
Halen
Hales
Haley
Half
Halfacre
Halferty
Halfhill
Halfmann
Halford
Halgas
Halgren
Halgrimson
Haliburton
Halick
Halifax
Halik
Halim
Halima
Halk
Halko
Hall
Halla
Hallack
Hallada
Halladay
Hallahan
Hallam
Hallan
Hallas
Hallauer
Hallaway
Hallback
Hallberg
Hallczuk
Halle
Halleck
Hallee
Halleen
Hallemeyer
Hallenbeck
Haller
Hallerman
Hallet
Hallett
Halley
Hallford
Hallgren
Halliburton
Hallick
Halliday
Hallie
Halligan
Hallihan
Halliman
Hallin
Hallinan
Halling
Hallinger
Hallio
Hallisey
Halliwell
Hallman
Hallmark
Hallmon
Hallo
Hallock
Halloran
Halloway
Hallowell
Hallowich
Hallquist
Halls
Hallstead
Hallstrom
Hallum
Hallums
Hally
Halm
Halma
Halman
Halmes
Halmick
Halmstead
Halnon
Halo
Halon
Halonen
Halpain
Halpainy
Halper
Halperin
Halpern
Halpert
Halphen
Halpin
Halprin
Hals
Halsall
Halse
Halsell
Halsema
Halseth
Halsey
Halstead
Halsted
Halston
Halstrom
Halt
Halter
Halterman
Haltiwanger
Haltom
Halton
Haluska
Halverson
Halvorsen
Halvorson
Halward
Halwick
Halwood
Halyk
Ham
Hamacher
Hamad
Hamada
Hamai
Hamaker
Hamalainen
Hamalak
Hamamoto
Haman
Hamann
Hamano
Hamar
Hamara
Hamasaki
Hamb
Hambelton
Hamberg
Hamberger
Hamberlin
Hamberry
Hamblen
Hamblet
Hambleton
Hambley
Hamblin
Hambly
Hamborsky
Hambrecht
Hambric
Hambrick
Hambright
Hamburg
Hamburger
Hamby
Hamdan
Hamden
Hamdn
Hamed
Hameen
Hameister
Hamel
Hamelin
Hamelinck
Hamelton
Hamer
Hamernik
Hamers
Hamersly
Hames
Hamett
Hamff
Hamic
Hamid
Hamidi
Hamiel
Hamil
Hamill
Hamiltan
Hamilton
Hamiss
Hamiter
Hamiton
Hamler
Hamlet
Hamlett
Hamlette
Hamley
Hamlin
Hamling
Hamm
Hammacher
Hammack
Hammaker
Hamman
Hammang
Hammann
Hammans
Hammar
Hammargren
Hammarlund
Hammatt
Hamme
Hammed
Hammel
Hammell
Hammen
Hammer
Hammeren
Hammerle
Hammerlund
Hammerly
Hammerman
Hammers
Hammerschmidt
Hammersley
Hammersmith
Hammerstad
Hammerstein
Hammerstone
Hammerstrom
Hammes
Hammet
Hammett
Hammette
Hammill
Hamming
Hammitt
Hammock
Hammon
Hammond
Hammonds
Hammons
Hammontree
Hammrich
Hamn
Hamner
Hamnon
Hamolik
Hamon
Hamonds
Hamons
Hamontree
Hamor
Hamp
Hamparian
Hampe
Hampel
Hamper
Hample
Hampon
Hampshire
Hampson
Hampton
Hamra
Hamre
Hamric
Hamrick
Hams
Hamsher
Hamsik
Hamson
Hamstra
Hamway
Hamza
Hamzik
Han
Hanacek
Hanafan
Hanafin
Hanagami
Hanagan
Hanahan
Hanan
Hanauer
Hanavan
Hanawalt
Hanaway
Hanback
Hanberg
Hanberry
Hanbury
Hanby
Hance
Hancey
Hancher
Hanchett
Hancin
Hancock
Hancox
Hand
Handal
Handcock
Handel
Handeland
Handelman
Handelsman
Handerson
Handford
Handin
Handing
Handke
Handkins
Handler
Handley
Handlin
Handly
Handon
Handren
Handrick
Hands
Handsaker
Handschumaker
Handshaw
Handshoe
Handsom
Handsome
Handt
Handville
Handwerk
Handwerker
Handy
Handzel
Handzlik
Hane
Hanebutt
Hanegan
Hanek
Hanekamp
Haneke
Hanel
Haneline
Hanemann
Hanenberger
Hanenkrat
Haner
Hanes
Haney
Hanf
Hanford
Hanft
Hang
Hangartner
Hanger
Hanhan
Hanhardt
Hanible
Hanifan
Hanify
Hanigan
Haning
Hanington
Hanis
Hanisch
Hanisco
Hanisko
Hank
Hanke
Hankel
Hanken
Hankerson
Hankey
Hankin
Hankins
Hankinson
Hankison
Hankla
Hanko
Hanks
Hanle
Hanley
Hanlin
Hanline
Hanlon
Hanly
Hanmer
Hanmore
Hann
Hanna
Hannafin
Hannaford
Hannagan
Hannah
Hannahs
Hannam
Hannaman
Hannan
Hannasch
Hannawalt
Hannaway
Hannay
Hannegan
Hanneken
Hannem
Hanneman
Hannemann
Hannen
Hanner
Hanners
Hannes
Hanney
Hanni
Hannibal
Hannifan
Hannig
Hannigan
Hanninen
Hanning
Hanno
Hannold
Hannon
Hanns
Hannula
Hannum
Hano
Hanoa
Hanock
Hanohano
Hanoharo
Hanold
Hanover
Hanrahan
Hanrath
Hanry
Hans
Hansard
Hansberger
Hansberry
Hansbrough
Hansbury
Hansch
Hansche
Hanscom
Hansel
Hansell
Hanselman
Hansen
Hanser
Hanserd
Hanses
Hansford
Hanshaw
Hanshew
Hansil
Hansing
Hansis
Hansley
Hansman
Hansmann
Hansome
Hanson
Hansrote
Hansson
Hansteen
Hanstein
Hanstine
Hant
Hanten
Hanthorn
Hantman
Hanton
Hantula
Hantz
Hantzarides
Hanus
Hanusey
Hanvey
Hanville
Hanway
Hanz
Hanzel
Hanzely
Hanzl
Hanzlik
Hao
Hape
Hapeman
Haper
Hapgood
Hapke
Happ
Happe
Happel
Happenny
Happer
Happney
Haptonstall
Haq
Haque
Har
Hara
Harabedian
Harada
Harader
Haraguchi
Harajli
Harajly
Haraldson
Haralson
Haramoto
Haran
Harang
Harapat
Harari
Harary
Haraway
Harb
Harbach
Harbater
Harbaugh
Harbeck
Harben
Harber
Harbert
Harbeson
Harbick
Harbin
Harbinson
Harbison
Harbold
Harbolt
Harbor
Harborth
Harbottle
Harbough
Harbour
Harbuck
Harbus
Harby
Harcar
Harcey
Harcharik
Harclerode
Harcourt
Harcrow
Harcum
Harcus
Hard
Hardacre
Hardage
Hardaker
Hardaman
Hardan
Hardaway
Hardcastle
Harde
Hardebeck
Hardee
Hardegree
Hardel
Hardell
Hardeman
Hardemon
Harden
Hardenbrook
Hardenburg
Harder
Harderman
Harders
Hardester
Hardesty
Hardey
Hardge
Hardges
Hardgrave
Hardgrove
Hardi
Hardie
Hardigan
Hardigree
Hardiman
Hardimon
Hardin
Hardina
Hardine
Harding
Hardinger
Hardinson
Hardison
Hardister
Hardisty
Hardman
Hardmon
Hardnett
Hardnette
Hardney
Hardon
Hardrick
Hardrict
Hardridge
Hards
Hardsock
Hardt
Hardter
Hardung
Hardway
Hardwick
Hardy
Hardyman
Hare
Harell
Harelson
Haren
Harens
Harer
Harewood
Harfert
Harford
Hargenrader
Hargens
Harger
Hargers
Harges
Hargest
Hargett
Hargis
Hargitt
Hargrave
Hargraves
Hargreaves
Hargroder
Hargrove
Hargrow
Hargus
Harian
Harig
Haring
Harington
Hariri
Haris
Harison
Hariston
Harjo
Harjochee
Harju
Hark
Harkavy
Harkcom
Harke
Harkema
Harken
Harkenreader
Harker
Harkey
Harkin
Harkins
Harkleroad
Harklerode
Harkless
Harkley
Harkness
Harkrader
Harkrider
Harl
Harlan
Harland
Harle
Harlee
Harlem
Harleman
Harles
Harless
Harleston
Harley
Harlin
Harling
Harloff
Harlor
Harlow
Harlowe
Harlston
Harm
Harman
Harmann
Harmen
Harmening
Harmer
Harmeson
Harmeyer
Harmison
Harmon
Harmond
Harms
Harmsen
Harn
Harnack
Harnage
Harnan
Harnar
Harnden
Harne
Harned
Harner
Harnes
Harness
Harnett
Harney
Harnisch
Harnish
Harnist
Harnly
Harnois
Harnos
Harns
Haro
Harold
Haroldsen
Haroldson
Harootunian
Haros
Harouff
Haroun
Haroutunian
Harp
Harpe
Harpel
Harper
Harpham
Harpin
Harpine
Harpold
Harpole
Harpool
Harps
Harpst
Harpster
Harr
Harraden
Harradine
Harradon
Harrah
Harral
Harrald
Harralson
Harre
Harrel
Harrell
Harrellson
Harrelson
Harren
Harrer
Harres
Harrett
Harrey
Harriage
Harrier
Harries
Harriet
Harriett
Harrigan
Harriger
Harrigill
Harrigton
Harrill
Harriman
Harring
Harrington
Harriott
Harris
Harrison
Harrisow
Harriss
Harrist
Harriston
Harritt
Harrod
Harrold
Harrop
Harroun
Harrow
Harrower
Harry
Harryman
Harsch
Harsey
Harsh
Harsha
Harshaw
Harshbarger
Harshberger
Harshfield
Harshman
Harsin
Harstad
Harston
Harsy
Hart
Hartage
Harte
Harteau
Hartel
Harten
Hartenstein
Harter
Hartert
Hartery
Hartfiel
Hartfield
Hartford
Hartgerink
Hartgrave
Hartgraves
Hartgrove
Harth
Harthcock
Harthorne
Harthun
Hartig
Hartigan
Hartill
Hartin
Harting
Hartinger
Hartis
Hartje
Hartjen
Hartke
Hartkopf
Hartl
Hartlage
Hartle
Hartleben
Hartlein
Hartlen
Hartlep
Hartless
Hartley
Hartline
Hartling
Hartly
Hartman
Hartmann
Hartnell
Hartness
Hartnett
Hartney
Hartog
Harton
Hartong
Hartory
Hartpence
Hartquist
Hartranft
Hartrick
Hartrum
Hartry
Harts
Hartsch
Hartse
Hartsell
Hartsfield
Hartshorn
Hartshorne
Hartsock
Hartsoe
Hartson
Hartsook
Hartsough
Hartstein
Hartt
Hartung
Hartup
Hartvigsen
Hartwell
Hartwick
Hartwig
Hartwigsen
Harty
Hartz
Hartzell
Hartzer
Hartzfeld
Hartzheim
Hartzler
Hartzo
Hartzog
Haruta
Harutunian
Harvard
Harvat
Harvath
Harvel
Harvell
Harver
Harvest
Harvey
Harvick
Harvie
Harvilchuck
Harvilicz
Harvill
Harvilla
Harville
Harvin
Harvison
Harviston
Harvley
Harward
Harwell
Harwick
Harwin
Harwood
Has
Hasak
Hasan
Hasas
Hasbell
Hasberry
Hasbni
Hasbrouck
Hascall
Hasch
Haschke
Hascup
Hase
Hasegawa
Hasek
Haselden
Haselhorst
Haselhuhn
Haseloff
Haseltine
Haselton
Haseman
Hasen
Hasenauer
Hasenbeck
Hasenberg
Hasencamp
Hasenfratz
Hasenfuss
Haser
Hasfjord
Hasgill
Hash
Hasha
Hashaway
Hashbarger
Hashem
Hashim
Hashimoto
Hashmi
Haskamp
Haske
Haskel
Haskell
Hasker
Haskett
Haskew
Haskin
Haskins
Hasko
Haskovec
Haslam
Haslem
Hasler
Haslett
Hasley
Haslinger
Haslip
Haspel
Hasper
Hass
Hassan
Hassanein
Hassard
Hasse
Hassel
Hasselbarth
Hasselkus
Hassell
Hasselman
Hasselvander
Hassen
Hassenfritz
Hassenger
Hassenplug
Hassett
Hassey
Hassian
Hassick
Hassig
Hassin
Hassing
Hassinger
Hassler
Hasson
Hasstedt
Haste
Hastedt
Hasten
Hastert
Hastie
Hastin
Hasting
Hastings
Haston
Hasty
Haswell
Hasychak
Hatada
Hatake
Hatala
Hataway
Hatch
Hatchcock
Hatchel
Hatchell
Hatcher
Hatcherson
Hatchet
Hatchett
Hatchette
Hatchitt
Hatfield
Hathaway
Hathcoat
Hathcock
Hathcox
Hatherly
Hatheway
Hathorn
Hathorne
Hathway
Hatke
Hatlee
Hatler
Hatley
Hatmaker
Hatman
Hatori
Hatridge
Hatstat
Hatt
Hatta
Hattabaugh
Hattan
Hattaway
Hatten
Hattenbach
Hatter
Hatteyer
Hattier
Hattley
Hattman
Hatto
Hatton
Hattori
Hattub
Hatzell
Hatzenbihler
Hatzenbuehler
Hatzenbuhler
Hau
Hauan
Haub
Hauben
Hauber
Haubert
Haubner
Haubold
Haubrich
Haubrick
Hauch
Hauck
Hauenstein
Hauer
Hauersperger
Hauf
Hauff
Hauffe
Haufler
Haug
Haugaard
Haugabrook
Hauge
Haugen
Hauger
Haugh
Haughey
Haughn
Haughney
Haught
Haughton
Haugland
Haugrud
Hauk
Haukaas
Hauke
Haulbrook
Hauley
Haulk
Haulter
Hauman
Haumesser
Haun
Haupert
Haupt
Hauptly
Hauptman
Hauptmann
Haurin
Haury
Haus
Hausam
Hausauer
Hauschild
Hauschildt
Hause
Hausen
Hauser
Haushalter
Hausher
Hauskins
Hausladen
Hauslein
Hausler
Hausman
Hausmann
Hausner
Hausrath
Hauss
Hausteen
Haustein
Hauswald
Haut
Hautala
Hautamaki
Hautan
Hauth
Hauxwell
Hauze
Havard
Havas
Havatone
Havekost
Havel
Havelka
Havely
Haveman
Haven
Havener
Havenhill
Havens
Haver
Havercroft
Haverfield
Haverkamp
Haverland
Haverly
Havermale
Havermann
Havers
Haverstick
Haverstock
Haverty
Havey
Havice
Havier
Haviland
Havir
Havis
Havlicek
Havlick
Havlik
Havlin
Havnen
Havner
Haw
Haward
Hawbaker
Hawe
Hawelu
Hawes
Hawf
Hawk
Hawke
Hawken
Hawker
Hawkes
Hawkey
Hawkin
Hawkinberry
Hawking
Hawkings
Hawkins
Hawkinson
Hawks
Hawksley
Hawley
Hawman
Hawn
Haworth
Hawrylak
Haws
Hawse
Hawthorn
Hawthorne
Hawthrone
Hawver
Haxby
Haxton
Hay
Haya
Hayakawa
Hayase
Hayashi
Hayashida
Hayball
Haybarger
Hayburn
Haycock
Haycook
Haycraft
Haydal
Haydel
Hayden
Haydock
Haydon
Haydt
Haydu
Hayduk
Haye
Hayek
Hayenga
Hayer
Hayertz
Hayes
Hayford
Haygood
Hayhoe
Hayhurst
Hayles
Haylett
Haylock
Haymaker
Hayman
Haymans
Haymer
Haymes
Haymon
Haymond
Haymore
Hayn
Haynam
Hayne
Hayner
Haynes
Haynesworth
Haynie
Haynsworth
Hayoz
Hayre
Hays
Haysbert
Hayse
Hayslett
Hayslip
Hayter
Hayth
Hayton
Hayward
Haywood
Hayword
Hayworth
Hayzlett
Haza
Hazan
Hazard
Hazarika
Hazekamp
Hazel
Hazelbaker
Hazelbush
Hazelett
Hazelgrove
Hazelhurst
Hazelip
Hazell
Hazelrig
Hazelrigg
Hazeltine
Hazelton
Hazelwood
Hazen
Hazer
Hazim
Hazinski
Hazle
Hazlegrove
Hazleton
Hazlett
Hazlewood
Hazley
Hazlip
Hazlitt
Hazouri
Hazy
Hazzard
He
Heaberlin
Heacock
Heacox
Head
Headd
Heade
Headen
Heading
Headings
Headington
Headlam
Headland
Headlee
Headley
Headlon
Headly
Headman
Headrick
Heads
Heady
Heafey
Heafner
Heagany
Heagle
Heagney
Heagy
Heaivilin
Heal
Healan
Heald
Healey
Heally
Healy
Heam
Hean
Heaney
Heang
Heany
Heap
Heape
Heaphy
Heaps
Heard
Heare
Hearin
Hearing
Hearl
Hearn
Hearne
Hearnen
Hearns
Hearnsberger
Hearon
Hearron
Hearson
Hearst
Hearston
Heart
Heartley
Heartsill
Heartz
Heaslet
Heasley
Heaslip
Heaston
Heater
Heath
Heathcock
Heathcote
Heather
Heatherington
Heatherly
Heathershaw
Heatherton
Heathman
Heatley
Heatly
Heaton
Heatwole
Heavener
Heaviland
Heavilin
Heavin
Heavner
Heavrin
Hebard
Hebb
Hebblethwaite
Hebda
Hebden
Hebdon
Hebeisen
Hebel
Hebenstreit
Heber
Heberer
Heberle
Heberlein
Heberling
Heberly
Hebert
Hebets
Hebig
Hebner
Hebrank
Hebrard
Hebron
Hebsch
Hechinger
Hechmer
Hecht
Heck
Heckaman
Heckard
Heckart
Heckathorn
Heckathorne
Heckbert
Hecke
Heckel
Heckenberg
Heckendorf
Hecker
Heckerman
Heckers
Heckert
Heckford
Heckle
Heckler
Heckman
Heckmann
Heckstall
Hecox
Hect
Hector
Hedberg
Hedden
Hedding
Heddins
Heddleson
Heddlesten
Hedeen
Hedegaard
Hedegore
Hedeiros
Hedemann
Hedge
Hedgebeth
Hedgecock
Hedgepath
Hedgepeth
Hedger
Hedges
Hedgespeth
Hedglin
Hedgpeth
Hediger
Hedin
Hedinger
Hedler
Hedley
Hedlund
Hedman
Hedon
Hedquist
Hedrich
Hedrick
Hedrington
Hedrix
Hedspeth
Hedstrom
Hedtke
Hee
Heebner
Heebsh
Heefner
Heeg
Heelan
Heemstra
Heenan
Heeney
Heep
Heer
Heeralall
Heerdt
Heeren
Heerkes
Heern
Heers
Heersink
Heery
Heesch
Heese
Heeter
Heeth
Hefel
Heffelbower
Heffelfinger
Hefferan
Hefferman
Heffern
Heffernan
Heffernen
Hefferon
Heffington
Heffler
Heffley
Hefflinger
Heffner
Heffren
Heffron
Hefler
Hefley
Heflin
Hefner
Heft
Hefter
Hefti
Hefty
Hegan
Hegarty
Hegdahl
Hege
Hegedus
Hegel
Hegeman
Hegener
Heger
Hegg
Heggan
Hegge
Heggen
Heggestad
Heggie
Heggins
Heggood
Heggs
Hegland
Heglar
Hegler
Heglin
Heglund
Hegmann
Hegna
Hegner
Hegre
Hegstad
Hegwer
Hegwood
Hegyi
Hehir
Hehl
Hehn
Heholt
Hehr
Heibel
Heiberg
Heiberger
Heibult
Heichel
Heick
Heid
Heidbreder
Heide
Heidebrecht
Heidebrink
Heidecker
Heidel
Heidelberg
Heidelberger
Heidelburg
Heidema
Heideman
Heidemann
Heiden
Heidenescher
Heidenreich
Heider
Heiderman
Heidgerken
Heidi
Heidinger
Heidkamp
Heidler
Heidmann
Heidorn
Heidrich
Heidrick
Heidt
Heidtbrink
Heidtke
Heidtman
Heier
Heiermann
Heifner
Heigh
Height
Heigl
Heiken
Heikes
Heikkila
Heikkinen
Heil
Heilbron
Heilbrun
Heileman
Heiler
Heilig
Heiliger
Heilman
Heilmann
Heim
Heiman
Heimann
Heimark
Heimbach
Heimbaugh
Heimbigner
Heimbuch
Heimburger
Heimer
Heimerdinger
Heimerl
Heimlich
Heimlicher
Heimrich
Heims
Heimsness
Heimsoth
Hein
Heinandez
Heinbach
Heinbaugh
Heindel
Heindl
Heine
Heineck
Heinecke
Heineken
Heineman
Heinemann
Heinemeyer
Heinen
Heiner
Heines
Heiney
Heingartner
Heinicke
Heinig
Heiniger
Heininger
Heinis
Heinitz
Heinke
Heinl
Heinle
Heinlein
Heinlen
Heinly
Heino
Heinold
Heinonen
Heinrich
Heinricher
Heinrichs
Heinritz
Heins
Heinsohn
Heintz
Heintzelman
Heintzman
Heiny
Heinz
Heinze
Heinzelman
Heinzen
Heinzerling
Heinzig
Heinzle
Heinzman
Heinzmann
Heiple
Heir
Heird
Heirendt
Heiro
Heisdorffer
Heise
Heisel
Heiser
Heiserman
Heisey
Heishman
Heising
Heisinger
Heiskell
Heisler
Heisner
Heiss
Heisse
Heisser
Heisserer
Heist
Heistand
Heister
Heit
Heitbrink
Heitger
Heither
Heiting
Heitkamp
Heitland
Heitman
Heitmann
Heitmeyer
Heitmuller
Heitner
Heitschmidt
Heitz
Heitzman
Heitzmann
Heizer
Heizman
Hejl
Hejny
Hekman
Hektner
Helaire
Helander
Helberg
Helbert
Helbig
Helbing
Helble
Helbling
Held
Helde
Heldenbrand
Helder
Helderman
Heldman
Heldreth
Heldt
Hele
Helem
Helems
Helen
Helena
Helf
Helfen
Helfenbein
Helfenstein
Helfer
Helfert
Helferty
Helfgott
Helfin
Helfinstine
Helfrey
Helfrich
Helfrick
Helfritz
Helgaas
Helgager
Helgason
Helger
Helgerman
Helgerson
Helgert
Helgesen
Helgeson
Helget
Helgren
Helie
Helin
Heline
Heling
Helke
Helker
Hellams
Helland
Hellar
Hellard
Hellberg
Helle
Hellen
Hellenbrand
Heller
Hellerman
Helley
Hellgren
Hellickson
Helling
Hellinger
Hellings
Helliwell
Hellman
Hellmann
Hellmich
Hellmuth
Hellner
Hellriegel
Hellstrom
Hellums
Hellweg
Hellwig
Hellyer
Helm
Helman
Helmbrecht
Helmbright
Helmcamp
Helmen
Helmer
Helmers
Helmert
Helmes
Helmich
Helmick
Helmig
Helminiak
Helmink
Helmkamp
Helmke
Helmle
Helmlinger
Helmly
Helms
Helmsing
Helmstetler
Helmstetter
Helmus
Helmuth
Helmy
Helo
Helom
Helowicz
Helper
Helphenstine
Helphinstine
Helquist
Helscher
Helsel
Helser
Helseth
Helsey
Helsing
Helsley
Helson
Helstad
Helstrom
Helt
Helton
Heltsley
Heltzel
Helverson
Helveston
Helvey
Helvie
Helvik
Helvy
Helweg
Helwick
Helwig
Helzer
Hem
Hema
Heman
Hemanes
Hemani
Hemann
Hemans
Hemauer
Hemberger
Hembre
Hembree
Hembrey
Hembrough
Hembry
Hemby
Hemenway
Hemeon
Hemerly
Hemesath
Hemeyer
Heming
Heminger
Hemingway
Heminover
Hemish
Hemken
Hemker
Hemlepp
Hemler
Hemley
Hemm
Hemmann
Hemme
Hemmeke
Hemmelgarn
Hemmen
Hemmer
Hemmerling
Hemmert
Hemmes
Hemmeter
Hemmie
Hemmig
Hemming
Hemminger
Hemmings
Hemmingsen
Hemmingway
Hemon
Hemond
Hemp
Hempe
Hempel
Hemperley
Hempfling
Hemphill
Hemple
Hempstead
Hempton
Hemric
Hemrich
Hemrick
Hemry
Hemsath
Hemsley
Hemstreet
Hemsworth
Henagan
Henaire
Henandez
Henao
Henard
Henault
Henby
Hence
Hench
Hencheck
Henchel
Hencken
Hendee
Hendel
Hender
Hendericks
Henderickson
Henderlight
Henderlite
Henderosn
Hendershot
Hendershott
Henderso
Henderson
Hendeson
Hendler
Hendley
Hendon
Hendren
Hendrick
Hendricks
Hendricksen
Hendrickson
Hendrickx
Hendrics
Hendrie
Hendrik
Hendriks
Hendrikson
Hendrix
Hendrixson
Hendron
Hendry
Hendryx
Hendsbee
Hendson
Hendy
Henebry
Henedia
Henegan
Henegar
Henehan
Henein
Heneisen
Henerson
Henery
Henesey
Heney
Henfling
Heng
Hengel
Hengen
Henges
Henggeler
Hengl
Hengst
Henifin
Henig
Henigan
Heningburg
Heninger
Henington
Henion
Henjes
Henk
Henke
Henkel
Henken
Henkensiefken
Henkes
Henkey
Henkhaus
Henkin
Henkle
Henle
Henley
Henline
Henly
Henman
Henn
Hennagin
Hennagir
Hennard
Henne
Henneberg
Henneberger
Henneberry
Hennecke
Hennegan
Henneke
Henneman
Hennemann
Hennen
Hennes
Henness
Hennessee
Hennessey
Hennessy
Hennesy
Henney
Hennick
Hennies
Hennig
Hennigan
Henniger
Hennigh
Hennighausen
Henning
Henninger
Hennings
Henningsen
Henningson
Hennington
Hennis
Hennon
Henretta
Henrey
Henri
Henrich
Henrichs
Henrichsen
Henrick
Henricks
Henricksen
Henrickson
Henrie
Henriguez
Henriksen
Henrikson
Henriques
Henriquez
Henrity
Henry
Henscheid
Henschel
Henschen
Henschke
Hensdill
Hense
Hensel
Henseler
Hensen
Henshall
Henshaw
Hensle
Henslee
Hensler
Hensley
Henslin
Henson
Henstrom
Henter
Hentges
Henthorn
Henthorne
Henton
Hentrich
Hentschel
Hentz
Hentze
Henwood
Henze
Henzel
Henzler
Heon
Hepa
Hepburn
Hepfer
Hepker
Hepler
Hepner
Hepp
Heppding
Heppe
Heppeard
Heppel
Heppell
Hepper
Hepperly
Heppert
Heppler
Heppner
Heptinstall
Hepworth
Hequembourg
Her
Hera
Heral
Herald
Herandez
Herard
Heras
Heraty
Herauf
Herb
Herbein
Herbel
Herber
Herbers
Herbert
Herbick
Herbig
Herbin
Herbison
Herbold
Herbolsheimer
Herbst
Herbster
Herby
Herceg
Hercher
Hercman
Hercules
Herd
Herda
Herder
Herdes
Herdman
Herdon
Herdt
Hereda
Heredia
Hereford
Herek
Herem
Herena
Herendeen
Herera
Hererra
Hereth
Herford
Herforth
Hergenrader
Hergenreter
Hergenroeder
Hergert
Herget
Heriford
Herimann
Hering
Herington
Heritage
Herke
Herkel
Herkenratt
Herkert
Herklotz
Herkstroeter
Herl
Herley
Herlihy
Herline
Herling
Herlocker
Herlong
Herman
Hermance
Hermandez
Hermann
Hermanns
Hermanowicz
Hermans
Hermansen
Hermanson
Hermanstorfer
Hermenau
Hermenegildo
Hermens
Hermes
Hermez
Hermida
Hermie
Hermon
Hermosilla
Hermosillo
Hermosura
Herms
Hermsen
Hermus
Hern
Hernadez
Hernan
Hernanadez
Hernandaz
Hernande
Hernander
Hernanders
Hernandes
Hernandez
Hernando
Hernandz
Hernanez
Herndon
Herne
Herner
Hernon
Hernton
Herny
Hero
Herod
Herold
Heroman
Heron
Heronemus
Heroth
Herout
Heroux
Herpich
Herpolsheimer
Herr
Herra
Herrada
Herran
Herrand
Herrandez
Herrara
Herrarte
Herrboldt
Herre
Herrea
Herrel
Herrell
Herren
Herrera
Herreras
Herrero
Herres
Herriage
Herrick
Herridge
Herrig
Herriges
Herriman
Herrin
Herring
Herrington
Herrion
Herriot
Herriott
Herritt
Herrlich
Herrling
Herrman
Herrmann
Herrnandez
Herrod
Herrold
Herron
Herrud
Herry
Hersberger
Hersch
Herschaft
Herschel
Herschell
Herschelman
Herscher
Hersey
Hersh
Hersha
Hershaw
Hershberg
Hershberger
Hershelman
Hershenson
Hershey
Hershfield
Hershkop
Hershkowitz
Hershman
Hershnowitz
Herskovic
Herskovits
Hersman
Hersom
Herson
Herstad
Herston
Hert
Herta
Hertel
Hertenstein
Herter
Herth
Herting
Hertle
Hertlein
Hertler
Hertweck
Hertz
Hertzberg
Hertzel
Hertzler
Hertzog
Hervert
Hervey
Hervig
Hervol
Herwehe
Herwig
Herwood
Heryford
Herz
Herzberg
Herzberger
Herzbrun
Herzer
Herzfeld
Herzig
Herzing
Herzog
Hesby
Hesch
Heschke
Hescock
Hesford
Hesketh
Heskett
Heslep
Hesler
Hesley
Heslin
Heslop
Hespe
Hespen
Hess
Hesse
Hessee
Hessel
Hesselbach
Hesselbein
Hesselink
Hessell
Hesselman
Hesselrode
Hesselschward
Hesseltine
Hessenthaler
Hesser
Hessey
Hessian
Hessing
Hession
Hessler
Hessling
Hessman
Hesson
Hessong
Hestand
Hester
Hesterly
Hesterman
Hesters
Heston
Hetcher
Hetchman
Heter
Heth
Hethcote
Hethcox
Hetherington
Hetherman
Hetjonk
Hetland
Hetling
Hetrick
Hetsler
Hett
Hettenhausen
Hettes
Hettich
Hettinga
Hettinger
Hettler
Hettrick
Hettwer
Hetu
Hetz
Hetzel
Hetzer
Hetzler
Heu
Heuangvilay
Heuberger
Heubusch
Heuck
Heuer
Heuett
Heugel
Heuman
Heumann
Heung
Heupel
Heuring
Heuschkel
Heusel
Heuser
Heusinkveld
Heusley
Heusner
Heutmaker
Heuvelmann
Heuwinkel
Heverin
Heverley
Heverly
Hevessy
Hevesy
Hevey
Hevia
Hevner
Hevrin
Hevron
Hew
Heward
Hewatt
Hewell
Hewes
Hewett
Hewey
Hewgley
Hewins
Hewitt
Hewko
Hewlett
Hewlin
Hews
Hewson
Heximer
Hey
Heybrock
Heyd
Heyde
Heydel
Heyden
Heydenreich
Heydt
Heyduck
Heye
Heyen
Heyer
Heyes
Heying
Heykoop
Heyl
Heyliger
Heyman
Heymann
Heyn
Heyne
Heynen
Heys
Heyser
Heyveld
Heyward
Heywood
Heziak
Hiatt
Hibbard
Hibben
Hibberd
Hibbert
Hibbets
Hibbetts
Hibbits
Hibbitt
Hibbitts
Hibble
Hibbler
Hibbs
Hibdon
Hibert
Hibl
Hibler
Hibley
Hibma
Hibner
Hibshman
Hice
Hichens
Hiciano
Hick
Hickam
Hickel
Hicken
Hickenbottom
Hickernell
Hickerson
Hickert
Hickethier
Hickey
Hickie
Hickinbotham
Hickingbotham
Hickingbottom
Hickle
Hickley
Hicklin
Hickling
Hickman
Hickmon
Hickock
Hickok
Hickonbottom
Hickory
Hickox
Hicks
Hickson
Hickton
Hidaka
Hidalgo
Hiday
Hidde
Hidden
Hides
Hidinger
Hidrogo
Hidvegi
Hidy
Hieatt
Hieb
Hieber
Hiebert
Hiedeman
Hiefnar
Hielscher
Hiemer
Hiemstra
Hiens
Hier
Hierholcer
Hierholzer
Hieronymus
Hierro
Hiers
Hiersche
Hieserich
Hiestand
Hiester
Hietala
Hiett
Higa
Higaneda
Higashi
Higashida
Higbee
Higbie
Higby
Higdon
Higgason
Higgenbotham
Higgenbottom
Higgens
Higgin
Higginbotham
Higginbothan
Higginbottom
Higgins
Higginson
Higgons
Higgs
High
Higham
Highbaugh
Highberger
Highers
Highfield
Highfill
Highland
Highley
Highman
Highnote
Highshaw
Highsmith
Hight
Hightower
Hightree
Hightshoe
Higinbotham
Higle
Higley
Higman
Higney
Hignight
Hignite
Higson
Higuchi
Higuera
Higueros
Higy
Hija
Hikel
Hikes
Hila
Hilado
Hilaire
Hiland
Hilario
Hilb
Hilbert
Hilbig
Hilbner
Hilborn
Hilbrand
Hilbun
Hilburn
Hilby
Hilcher
Hilchey
Hild
Hilda
Hildago
Hildahl
Hilde
Hildebrand
Hildebrandt
Hildebrant
Hilden
Hildenbrand
Hilderbrand
Hilderbrandt
Hilderman
Hildesheim
Hilding
Hildinger
Hildman
Hildner
Hildred
Hildreth
Hildring
Hile
Hileman
Hiler
Hiles
Hiley
Hilferty
Hilfiger
Hilfiker
Hilgefort
Hilgeman
Hilgendorf
Hilger
Hilgers
Hilgert
Hilk
Hilke
Hilker
Hilkert
Hill
Hilla
Hillabush
Hillaire
Hillan
Hillanbrand
Hilland
Hillard
Hillary
Hillberry
Hillbrant
Hillburg
Hille
Hilleary
Hillebrand
Hillebrandt
Hillebrano
Hillegas
Hillegass
Hilleman
Hillen
Hillenbrand
Hiller
Hillered
Hillerman
Hillers
Hillerud
Hillery
Hilles
Hillesheim
Hillesland
Hillestad
Hilley
Hillhouse
Hillian
Hilliard
Hillie
Hillier
Hilliker
Hillin
Hilling
Hillis
Hillman
Hillmer
Hillock
Hills
Hillseth
Hillsgrove
Hillsman
Hillstrom
Hillwig
Hillyard
Hillyer
Hilman
Hilmer
Hilmes
Hilo
Hilovsky
Hilpert
Hilsabeck
Hilscher
Hilse
Hilsenbeck
Hilsendager
Hilser
Hilsgen
Hilsinger
Hilson
Hilst
Hilstad
Hilston
Hilt
Hiltbrand
Hiltebeitel
Hiltner
Hilton
Hilts
Hiltunen
Hilty
Hiltz
Hilu
Hilvers
Hilyar
Hilyard
Hilyer
Hilz
Hilzer
Him
Himanga
Himber
Hime
Himebaugh
Himel
Himelfarb
Himelstein
Himenez
Himes
Himmel
Himmelmann
Himmelright
Himmelsbach
Himmelspach
Himmelwright
Himmons
Hin
Hinahon
Hinajosa
Hinaman
Hince
Hinch
Hinchcliff
Hinchcliffe
Hinchee
Hinchey
Hinchliff
Hinchliffe
Hinchman
Hinck
Hinckle
Hinckley
Hincks
Hinckson
Hind
Hindall
Hindbaugh
Hinde
Hinderaker
Hinderberger
Hinderer
Hinderliter
Hinderman
Hinders
Hindes
Hindin
Hindle
Hindley
Hindman
Hindmarsh
Hinds
Hindsman
Hindson
Hine
Hinebaugh
Hinegardner
Hineline
Hinely
Hineman
Hiner
Hinerman
Hines
Hinesley
Hiney
Hing
Hinger
Hingle
Hingst
Hingston
Hinh
Hinish
Hink
Hinke
Hinkel
Hinken
Hinkes
Hinkey
Hinkle
Hinkley
Hinks
Hinkson
Hinkston
Hinley
Hinman
Hinnant
Hinnen
Hinnenkamp
Hinners
Hinojos
Hinojosa
Hinokawa
Hinostroza
Hinote
Hinrichs
Hinrichsen
Hinsch
Hinsey
Hinshaw
Hinsley
Hinson
Hint
Hintergardt
Hintermeister
Hinton
Hintson
Hintz
Hintze
Hintzen
Hinz
Hinze
Hinzman
Hinzmann
Hiott
Hipkins
Hipol
Hipolito
Hipp
Hippe
Hippen
Hippensteel
Hippenstiel
Hippert
Hipple
Hippler
Hippley
Hippo
Hipps
Hipsher
Hipsley
Hipwell
Hirai
Hiraki
Hiraldo
Hirano
Hirao
Hiraoka
Hirata
Hirayama
Hird
Hire
Hires
Hirezi
Hirkaler
Hirko
Hirleman
Hirliman
Hirn
Hirneise
Hironaka
Hirons
Hirose
Hirota
Hirpara
Hirsbrunner
Hirsch
Hirschberg
Hirsche
Hirschfeld
Hirschfield
Hirschhorn
Hirschi
Hirschman
Hirschmann
Hirschy
Hirsh
Hirshberg
Hirst
Hirstein
Hirt
Hirte
Hirth
Hirtz
Hirz
Hisaw
Hiscock
Hiscox
Hise
Hisel
Hiser
Hisey
Hiske
Hiskey
Hisle
Hislip
Hislop
Hislope
Hisman
Hismith
Hisrich
Hiss
Hissam
Hissem
Hisserich
Hissom
Hissong
Histand
Hitch
Hitchcock
Hitchen
Hitchens
Hitchingham
Hitchings
Hitchko
Hitchman
Hite
Hiteman
Hiter
Hites
Hitsman
Hitson
Hitt
Hittle
Hittman
Hittner
Hittson
Hitz
Hitzel
Hitzeman
Hitzfelder
Hitzler
Hively
Hives
Hix
Hixenbaugh
Hixon
Hixson
Hizer
Hizkiya
Hjalmarson
Hjelle
Hjelm
Hjermstad
Hjort
Hlad
Hladek
Hladik
Hlastala
Hlavac
Hlavacek
Hlavaty
Hlavka
Hledik
Hluska
Hlywa
Hnat
Hnatow
Hnot
Hnyda
Ho
Hoa
Hoadley
Hoag
Hoagberg
Hoage
Hoagland
Hoaglin
Hoaglund
Hoague
Hoak
Hoang
Hoar
Hoard
Hoare
Hoback
Hoban
Hobart
Hobaugh
Hobb
Hobbie
Hobbins
Hobbs
Hobby
Hobday
Hobden
Hobdy
Hobel
Hobell
Hoben
Hober
Hoberek
Hoberg
Hobert
Hobgood
Hobin
Hobkirk
Hobler
Hoblit
Hobock
Hobson
Hobstetter
Hocate
Hoch
Hochadel
Hochard
Hochberg
Hochfelder
Hochhalter
Hochhauser
Hochman
Hochmuth
Hochnadel
Hochschild
Hochstatter
Hochstedler
Hochstein
Hochstetler
Hochstetter
Hochstine
Hock
Hockaday
Hocke
Hockema
Hockenberry
Hockenbrock
Hockenbury
Hockensmith
Hocker
Hockersmith
Hockett
Hockey
Hocking
Hockins
Hockley
Hockman
Hocutt
Hoda
Hodak
Hodan
Hodapp
Hodd
Hodde
Hodder
Hodek
Hodel
Hodell
Hoder
Hodermarsky
Hodes
Hodgdon
Hodge
Hodgeman
Hodgen
Hodgens
Hodges
Hodgin
Hodgins
Hodgkin
Hodgkins
Hodgkinson
Hodgkiss
Hodgman
Hodgson
Hodkinson
Hodnefield
Hodnett
Hodnicki
Hodo
Hodor
Hodos
Hodosy
Hodrick
Hodsdon
Hodson
Hodum
Hoe
Hoeck
Hoecker
Hoefel
Hoefer
Hoefert
Hoeffer
Hoeffliger
Hoefflin
Hoeffner
Hoefle
Hoefler
Hoeflich
Hoefling
Hoeft
Hoeg
Hoeger
Hoegerl
Hoegh
Hoehl
Hoehn
Hoehne
Hoek
Hoeke
Hoekman
Hoekstra
Hoel
Hoell
Hoeller
Hoellwarth
Hoelscher
Hoelter
Hoelzel
Hoemann
Hoen
Hoene
Hoener
Hoenig
Hoenstine
Hoeper
Hoepfner
Hoeppner
Hoerauf
Hoerger
Hoerig
Hoerl
Hoernemann
Hoerner
Hoerr
Hoerter
Hoes
Hoeschen
Hoese
Hoeser
Hoesing
Hoesly
Hoetger
Hoevel
Hoey
Hof
Hofacker
Hofbauer
Hofe
Hofer
Hoff
Hoffa
Hoffart
Hoffarth
Hoffeditz
Hoffee
Hoffelmeyer
Hoffelt
Hoffer
Hofferber
Hoffert
Hoffhines
Hoffine
Hoffis
Hoffler
Hoffman
Hoffmann
Hoffmaster
Hoffmeister
Hoffmeyer
Hoffnagle
Hoffner
Hofford
Hoffpauir
Hoffpavir
Hoffschneider
Hoffses
Hoffstatter
Hoffstetter
Hoffstot
Hofheimer
Hofhine
Hofius
Hofland
Hofler
Hofman
Hofmann
Hofmans
Hofmeister
Hofstad
Hofstadter
Hofstetter
Hofstra
Hoftiezer
Hoga
Hogains
Hogan
Hogancamp
Hogans
Hoganson
Hogarth
Hogarty
Hogatt
Hogberg
Hoge
Hogeland
Hogelin
Hogen
Hogenmiller
Hogenson
Hoger
Hogg
Hoggan
Hoggard
Hoggatt
Hogge
Hoggins
Hoggle
Hoglan
Hogland
Hogle
Hoglen
Hoglund
Hogon
Hogrefe
Hogsed
Hogsett
Hogsette
Hogsten
Hogston
Hogstrum
Hogue
Hoguet
Hogy
Hoh
Hohaia
Hoheisel
Hohenberger
Hohenbrink
Hohensee
Hohenstein
Hohiudden
Hohl
Hohler
Hohlfeld
Hohlstein
Hohlt
Hohm
Hohman
Hohmann
Hohmeier
Hohn
Hohner
Hohney
Hohnson
Hohnstein
Hohowski
Hohstadt
Hoilman
Hoinacki
Hoines
Hoiness
Hoiseth
Hoisington
Hoisl
Hoist
Hoistion
Hoit
Hoitt
Hoium
Hoivik
Hojczyk
Hojeij
Hojnacki
Hok
Hokama
Hokanson
Hoke
Hokenson
Hokes
Hokett
Hokkanen
Hokula
Hokutan
Holabaugh
Holaday
Holahan
Holak
Holan
Holaway
Holbach
Holbein
Holben
Holberg
Holbert
Holberton
Holbrook
Holbrooks
Holcey
Holch
Holck
Holcomb
Holcombe
Holcroft
Holda
Holdaway
Holdbrook
Holdcraft
Holdeman
Holden
Holder
Holderbaum
Holderby
Holderfield
Holderman
Holderness
Holdgrafer
Holdiness
Holding
Holdman
Holdness
Holdorf
Holdren
Holdridge
Holdsworth
Holdt
Holdvogt
Holdy
Hole
Holec
Holecek
Holecz
Holeman
Holen
Holes
Holesovsky
Holets
Holey
Holford
Holgate
Holgersen
Holgerson
Holguin
Holian
Holibaugh
Holiday
Holien
Holifeild
Holifield
Holihan
Holiman
Holizna
Holje
Holk
Holka
Holl
Holla
Hollabaugh
Hollack
Holladay
Hollamon
Hollan
Holland
Hollander
Hollands
Hollandsworth
Hollar
Hollard
Hollarn
Hollars
Hollaway
Hollberg
Holle
Holleman
Hollembaek
Hollemon
Hollen
Hollenbach
Hollenback
Hollenbaugh
Hollenbeck
Hollenberg
Hollender
Hollendonner
Hollenshead
Holler
Holleran
Hollering
Hollerman
Hollerud
Hollett
Holley
Holleyman
Hollibaugh
Holliday
Hollidge
Hollie
Hollier
Hollifield
Holliman
Hollimon
Hollin
Holling
Hollinger
Hollinghead
Hollinghurst
Hollings
Hollingshead
Hollingshed
Hollingsworth
Hollington
Hollingworth
Hollinrake
Hollins
Hollinshead
Hollinshed
Hollinsworth
Hollis
Hollister
Holliway
Hollman
Hollmann
Hollner
Hollo
Hollobaugh
Holloman
Hollomon
Hollon
Hollopeter
Holloran
Hollow
Holloway
Hollowell
Hollway
Holly
Hollyday
Hollyfield
Hollywood
Holm
Holman
Holmberg
Holme
Holmen
Holmer
Holmers
Holmes
Holmgren
Holmlund
Holmon
Holmquest
Holmquist
Holms
Holmstead
Holmstrom
Holness
Holohan
Holom
Holoman
Holoway
Holowell
Holpp
Holquin
Holquist
Holroyd
Holsapple
Holscher
Holsclaw
Holsey
Holshouser
Holshovser
Holshue
Holsing
Holsinger
Holsman
Holsomback
Holsonback
Holsopple
Holst
Holstad
Holste
Holstege
Holstein
Holsten
Holster
Holstine
Holston
Holstrom
Holsworth
Holt
Holtan
Holtberg
Holte
Holten
Holter
Holterman
Holtgrefe
Holtgrewe
Holtham
Holthaus
Holthoff
Holthouse
Holthus
Holtkamp
Holtman
Holtmann
Holtmeier
Holton
Holtorf
Holtrop
Holtry
Holts
Holtsclaw
Holtsoi
Holtz
Holtzberg
Holtzclaw
Holtzen
Holtzer
Holtzlander
Holtzman
Holub
Holubar
Holverson
Holvey
Holway
Holweger
Holy
Holycross
Holyfield
Holyoak
Holyoke
Holz
Holzboog
Holze
Holzem
Holzer
Holzerland
Holzhauer
Holzheimer
Holzhueter
Holzinger
Holzman
Holzmeister
Holzmiller
Holznecht
Holzner
Holzwart
Holzwarth
Holzworth
Hom
Homa
Homan
Homann
Homans
Homburg
Homby
Homchick
Home
Homen
Homer
Homerding
Homes
Homesley
Homestead
Homewood
Homeyer
Homiak
Homles
Homma
Homme
Hommel
Hommell
Hommer
Hommerding
Homola
Homrich
Homrighaus
Homs
Homsey
Homsher
Homyak
Homza
Hon
Honahni
Honahnie
Honaker
Honan
Honanie
Honas
Honberger
Honch
Honchell
Honchul
Honda
Hondel
Hondorp
Hondros
Hone
Honea
Honeck
Honegger
Honer
Honerkamp
Hones
Honey
Honeycott
Honeycut
Honeycutt
Honeyestewa
Honeyman
Honeysucker
Honeywell
Hong
Honga
Hongach
Hongerholt
Hongeva
Hongisto
Hongo
Honhart
Honie
Honig
Honigsberg
Honkanen
Honma
Honn
Honnen
Honnerlaw
Honnette
Honnold
Honohan
Honokaupu
Honold
Honor
Honore
Honour
Hons
Honsberger
Honse
Honsinger
Honts
Hontz
Honus
Honyumptewa
Honza
Honzel
Honzell
Hoo
Hoobler
Hoock
Hood
Hooe
Hooey
Hoof
Hoofard
Hoogendoorn
Hoogheem
Hooghkirk
Hoogland
Hook
Hookano
Hooke
Hooker
Hookfin
Hooks
Hool
Hooley
Hoolihan
Hoomana
Hoon
Hoop
Hoopengardner
Hooper
Hoopes
Hoopii
Hoopingarner
Hoople
Hoops
Hoos
Hoose
Hooser
Hoosier
Hoosock
Hoot
Hooten
Hootman
Hooton
Hoots
Hootsell
Hoover
Hoovler
Hope
Hopes
Hopewell
Hopf
Hopfauf
Hopfensperger
Hopfer
Hopgood
Hopke
Hopkin
Hopkins
Hopkinson
Hopko
Hopman
Hopp
Hoppa
Hoppe
Hoppel
Hoppenrath
Hoppenstedt
Hopper
Hopperstad
Hoppes
Hoppesch
Hoppin
Hopping
Hoppins
Hopple
Hoppman
Hopps
Hopskins
Hopson
Hopton
Hopwood
Hoque
Hor
Hora
Horabik
Horace
Horack
Horak
Horal
Horan
Horaney
Horbert
Horchler
Hord
Horde
Hordge
Hordyk
Hore
Horelick
Horen
Horenstein
Hores
Horesco
Horeth
Horey
Horgan
Horgen
Horger
Hori
Horigan
Horii
Horikoshi
Horimoto
Horine
Horio
Horita
Horiuchi
Horka
Horkey
Horkley
Horky
Horman
Hormander
Hormann
Hormell
Hormuth
Horn
Hornack
Hornaday
Hornak
Hornandez
Hornbacher
Hornback
Hornbaker
Hornbarger
Hornbeak
Hornbeck
Hornberg
Hornberger
Hornbrook
Hornbuckle
Hornby
Horne
Horneff
Horner
Hornes
Horney
Horniak
Hornick
Hornig
Hornik
Horning
Hornish
Hornlein
Hornoff
Hornor
Horns
Hornsby
Hornshaw
Hornstein
Hornstrom
Hornung
Hornyak
Horodyski
Horoschak
Horovitz
Horowitz
Horr
Horras
Horrell
Horridge
Horrigan
Horris
Horrocks
Horry
Horsburgh
Horsch
Horse
Horseford
Horsely
Horseman
Horsey
Horsfall
Horsfield
Horsford
Horsley
Horsman
Horst
Horstead
Horstman
Horstmann
Hort
Horta
Hortein
Horten
Horth
Hortillosa
Hortin
Hortman
Horton
Horuath
Horvat
Horvath
Horvers
Horvitz
Horwath
Horwich
Horwitz
Horwood
Hosack
Hosaka
Hosang
Hosch
Hoschander
Hoscheid
Hoscheit
Hoschek
Hoschouer
Hose
Hosea
Hoseck
Hosein
Hosek
Hoseman
Hosendove
Hosey
Hosfeld
Hosfield
Hosford
Hoshall
Hoshaw
Hoshino
Hosick
Hosie
Hosier
Hoskey
Hoskie
Hoskin
Hosking
Hoskins
Hoskinson
Hoskyns
Hosle
Hosler
Hosley
Hosman
Hosmer
Hosner
Hosoi
Hospelhorn
Hospkins
Hoss
Hossack
Hossain
Hosse
Hosseini
Hossfeld
Hossler
Host
Hoste
Hosteller
Hosten
Hoster
Hosterman
Hostert
Hostetler
Hostetter
Hostettler
Hostin
Hostler
Hostoffer
Hoston
Hotaki
Hotalen
Hotaling
Hotard
Hotchkin
Hotchkiss
Hotek
Hotelling
Hoth
Hothan
Hotovec
Hotrum
Hott
Hottel
Hottell
Hotten
Hotter
Hottes
Hottinger
Hottle
Hottman
Hotton
Hotz
Hotze
Hou
Houben
Houch
Houchard
Houchen
Houchens
Houchin
Houchins
Houck
Houde
Houdek
Houey
Houf
Houff
Hougas
Houge
Hougen
Hough
Hougham
Houghland
Houghtaling
Houghtelling
Houghtling
Houghton
Hougland
Houglum
Houis
Houk
Houlahan
Houlberg
Houle
Houlihan
Houltberg
Houlton
Houman
Hounchell
Hounshell
Houp
Houpe
Houpt
Hourani
Hourigan
Hourihan
Housand
Housden
House
Houseal
Householder
Housekeeper
Houseknecht
Housel
Houseman
Housemate
Housen
Houser
Houseworth
Housewright
Housey
Housh
Housholder
Houska
Houskeeper
Housler
Housley
Housman
Housner
Housten
Houston
Hout
Houtchens
Houten
Houtkooper
Houtman
Houts
Houtz
Houy
Houzah
Houze
Hovanec
Hovanes
Hovanesian
Hovantzi
Hovard
Hovarter
Hovatter
Hovda
Hovde
Hovden
Hove
Hovell
Hovelson
Hoven
Hovenga
Hover
Hovermale
Hoverson
Hoversten
Hovey
Hovi
Hovick
Hoving
Hovis
Hovland
Hovnanian
Hovorka
Hovsepian
How
Howard
Howarter
Howarth
Howat
Howatt
Howden
Howdeshell
Howdyshell
Howe
Howell
Howells
Howen
Howenstine
Hower
Howerter
Howerton
Howery
Howes
Howeth
Howett
Howey
Howick
Howie
Howieson
Howington
Howison
Howitt
Howk
Howkins
Howland
Howle
Howles
Howlett
Howley
Howlin
Howlingwolf
Howman
Howorth
Howry
Howryla
Howsare
Howse
Howser
Howson
Howton
Howze
Howzell
Hoxie
Hoxit
Hoxsie
Hoxworth
Hoy
Hoyal
Hoye
Hoyer
Hoying
Hoyland
Hoyle
Hoyles
Hoylton
Hoyman
Hoyne
Hoyos
Hoysock
Hoysradt
Hoyt
Hoyte
Hozempa
Hoznour
Hrabal
Hrabovsky
Hradecky
Hranchak
Hrapski
Hrbacek
Hrbek
Hrcka
Hrdlicka
Hreha
Hren
Hribal
Hribar
Hric
Hricko
Hritz
Hrivnak
Hrna
Hrobsky
Hromek
Hronek
Hronick
Hrovat
Hruby
Hruska
Hrycenko
Hrycko
Hryniewich
Hsi
Hsia
Hsiang
Hsiao
Hsieh
Hsing
Hsu
Hsueh
Hsun
Hsy
Htwe
Hu
Hua
Huaman
Huang
Huante
Huard
Huba
Hubach
Huban
Hubbard
Hubbartt
Hubbel
Hubbell
Hubbert
Hubble
Hubbs
Hubby
Hubel
Hubenthal
Huber
Huberman
Hubert
Hubertus
Huberty
Hubertz
Hubiak
Hubin
Hubka
Hubl
Hubler
Hubley
Hubner
Hubric
Hubright
Hubsch
Hubschmitt
Huch
Huck
Huckabaa
Huckabay
Huckabee
Huckabey
Huckabone
Huckaby
Huckeba
Huckeby
Huckfeldt
Huckins
Huckle
Huckleberry
Hucks
Huckstadt
Huckstep
Hudach
Hudack
Hudak
Hudalla
Hudas
Huddelston
Huddle
Huddleson
Huddleston
Huddy
Hudec
Hudecek
Hudek
Hudelson
Hudes
Hudgens
Hudgeons
Hudgins
Hudkins
Hudler
Hudley
Hudlin
Hudlow
Hudman
Hudmon
Hudnall
Hudnell
Hudnut
Hudock
Hudok
Hudon
Hudrick
Hudson
Hudspeth
Hudy
Hue
Huebert
Huebner
Huebsch
Huebschman
Hueckman
Hueftle
Huegel
Huehn
Huell
Huelle
Huels
Huelse
Huelskamp
Huelsman
Huemmer
Huenergardt
Huenink
Huereca
Huerta
Huertas
Huertes
Huerto
Hueser
Huesing
Huesman
Hueso
Huesso
Huestis
Hueston
Huether
Huett
Huettman
Huewe
Huey
Huezo
Huf
Hufana
Huff
Huffaker
Huffer
Huffine
Huffines
Huffman
Huffmaster
Huffner
Hufford
Huffstetler
Huffstickler
Huffstutler
Huffstutter
Hufft
Hufnagel
Hufstedler
Hufstetler
Huft
Hufton
Hufty
Hug
Hugar
Huge
Hugee
Hugel
Huger
Huges
Hugg
Huggard
Hugger
Huggett
Hugghins
Hugghis
Huggins
Huggler
Hugh
Hughart
Hughe
Hughen
Hughes
Hughett
Hughey
Hughlett
Hughley
Hughs
Hughson
Hughston
Hugi
Hugill
Hugle
Hugley
Hugo
Hugron
Hugueley
Huguenin
Huguet
Huguley
Hugus
Huh
Huhammad
Huhman
Huhn
Huhta
Huhtala
Huhtasaari
Hui
Huie
Huirgs
Huisenga
Huish
Huisinga
Huisman
Huit
Huiting
Huitink
Huitron
Huitt
Huitzacua
Huizar
Huizenga
Huizinga
Hujer
Hukill
Hukle
Hulan
Huland
Hulbert
Hulburt
Hulcy
Hulen
Hules
Hulet
Hulett
Hulette
Hulick
Hulin
Huling
Hulings
Hulitt
Hull
Hullender
Hullett
Hullihen
Hullinger
Hullings
Hullum
Hulm
Hulme
Hulmes
Hulon
Huls
Hulse
Hulsey
Hulshoff
Hulsizer
Hulslander
Hulsman
Hulst
Hulstine
Hulstrand
Hult
Hultberg
Hultgren
Hultman
Hulton
Hultquist
Hults
Hultz
Hulvey
Hulzing
Hum
Human
Humann
Humason
Humbard
Humbarger
Humbel
Humber
Humberson
Humbert
Humbertson
Humbird
Humble
Humbles
Humburg
Hume
Humenik
Humeniuk
Humerick
Humerickhouse
Humes
Humetewa
Humfeld
Huminski
Humiston
Humm
Hummel
Hummell
Hummer
Hummert
Hummingbird
Hummons
Humpal
Humpert
Humphers
Humphery
Humpherys
Humphrey
Humphreys
Humphries
Humphry
Humphrys
Humprey
Humpries
Humston
Hun
Hunckler
Hund
Hundemer
Hunderlach
Hundertmark
Hundley
Hundt
Huneke
Huner
Huneycutt
Hung
Hungate
Hunger
Hungerford
Hunke
Hunkele
Hunker
Hunkin
Hunking
Hunkins
Hunley
Hunn
Hunnell
Hunnewell
Hunneyman
Hunnicut
Hunnicutt
Hunnings
Hunsaker
Hunsberger
Hunsicker
Hunsinger
Hunsley
Hunson
Hunsperger
Hunstad
Hunstiger
Hunsucker
Hunt
Hunte
Hunten
Hunter
Hunting
Huntington
Huntley
Hunton
Huntoon
Huntress
Huntsberger
Huntsberry
Huntsinger
Huntsman
Huntzinger
Hunyadi
Hunze
Hunzeker
Hunzelman
Hunziker
Huor
Huot
Huotari
Hupe
Hupf
Hupka
Hupman
Hupp
Huppe
Huppenbauer
Hupper
Huppert
Huprich
Hupy
Hur
Hurban
Hurd
Hurde
Hurdle
Huret
Hurford
Hurl
Hurla
Hurlbert
Hurlburt
Hurlbut
Hurlbutt
Hurlebaus
Hurles
Hurless
Hurley
Hurlock
Hurlston
Hurm
Hurme
Hurn
Hurndon
Hurne
Hurney
Hurni
Hurns
Huro
Huron
Hurrell
Hurren
Hurrigan
Hurrington
Hurrle
Hurry
Hurse
Hursey
Hursh
Hurst
Hurston
Hurt
Hurta
Hurtado
Hurter
Hurtgen
Hurtig
Hurtis
Hurtt
Hurtubise
Hurtz
Hurwitz
Husain
Husaini
Husak
Husanini
Husar
Husayko
Husband
Husbands
Husby
Husch
Huscher
Huschle
Huse
Huseby
Husein
Huseman
Husenaj
Huser
Huseth
Husfelt
Hush
Hushon
Husk
Huska
Huskey
Huski
Huskin
Huskins
Huskinson
Husky
Huslander
Husman
Husmann
Husni
Huso
Huson
Huss
Hussain
Hussaini
Hussar
Hussein
Husseini
Husselbee
Husser
Hussey
Hussian
Hussien
Hussman
Husson
Hussong
Hussy
Hust
Hustace
Hustead
Husted
Hustedt
Huston
Hustus
Husul
Huszar
Hutch
Hutchcraft
Hutchcroft
Hutchen
Hutchens
Hutchenson
Hutcherson
Hutcheson
Hutchin
Hutching
Hutchings
Hutchingson
Hutchins
Hutchinson
Hutchison
Hutchkiss
Huter
Huth
Hutley
Hutmacher
Hutnak
Hutsell
Hutsler
Hutson
Hutt
Huttar
Hutten
Hutter
Hutti
Huttle
Huttman
Hutto
Hutton
Hutts
Hutyra
Hutzel
Hutzler
Huus
Huval
Huver
Huwe
Hux
Huxford
Huxhold
Huxley
Huxman
Huxtable
Huy
Huyard
Huyck
Huyett
Huyghe
Huyler
Huyna
Huynh
Huyser
Huysman
Huzzard
Hvizdos
Hwang
Hwee
Hy
Hyacinthe
Hyams
Hyatt
Hyatte
Hybarger
Hyberger
Hych
Hyche
Hyde
Hyden
Hyder
Hydrick
Hydzik
Hyer
Hyers
Hyett
Hykes
Hylan
Hyland
Hylands
Hyldahl
Hyle
Hyler
Hyles
Hylinski
Hylle
Hylton
Hyman
Hymas
Hymel
Hymen
Hymer
Hymes
Hymon
Hymowitz
Hynd
Hyndman
Hynds
Hynek
Hyneman
Hynes
Hynson
Hynum
Hyon
Hypes
Hypolite
Hyppolite
Hyre
Hyrkas
Hysell
Hyser
Hysinger
Hyske
Hyslop
Hysmith
Hysom
Hyson
Hysong
Hysquierdo
Hyten
Hyter
Hytros
Hyun
Hyzer
Iachetta
Iacobelli
Iacobellis
Iacobucci
Iacono
Iacopino
Iacovelli
Iacovetto
Iacovino
Iacovissi
Iacovone
Iacuzio
Iadarola
Iafrate
Ialongo
Iamiceli
Iams
Ianacone
Iannaccone
Iannacone
Iannalo
Iannelli
Ianni
Ianniello
Iannone
Iannotti
Iannucci
Iannuzzi
Ianuzzi
Iara
Iarocci
Iarossi
Iarussi
Iatarola
Iavarone
Iba
Ibach
Ibale
Ibanez
Ibara
Ibarra
Ibasitas
Ibbetson
Ibbotson
Ibdah
Iberg
Iberra
Ibey
Ible
Iborra
Ibraham
Ibrahim
Ibric
Ibsen
Iburg
Icard
Icardo
Ice
Icenhour
Icenogle
Ichikawa
Ichinose
Ichinotsubo
Ickert
Ickes
Ida
Iddings
Ide
Idell
Idema
Idemoto
Iden
Ideue
Idiart
Idleburg
Idler
Idol
Idris
Idriss
Idrovo
Ienco
Ieng
Iennaco
Iese
Iezzi
Ifantides
Ifeanyi
Iffert
Iffland
Ifft
Ifie
Ifill
Ifversen
Igartua
Igbal
Igbinosun
Igel
Iglehart
Igler
Igles
Iglesia
Iglesias
Ignacio
Ignasiak
Igneri
Ignoria
Ignowski
Igo
Igoe
Igou
Igtanloc
Iguina
Igus
Igwe
Iha
Ihde
Iheme
Ihenyen
Ihle
Ihlenfeld
Ihm
Ihnat
Ihnen
Ihrig
Ihrke
Iiams
Iida
Iino
Ijames
Ijams
Ikard
Ike
Ikeard
Ikeda
Ikehara
Ikemire
Ikemoto
Ikenberry
Iker
Ikerd
Ikkela
Ikner
Ikuta
Ikzda
Ilacqua
Ilagan
Ilalio
Ilardi
Ilaria
Ilarraza
Ilasin
Ildefonso
Iler
Iles
Ilg
Ilic
Iliff
Iliffe
Ill
Illa
Illar
Illas
Ille
Iller
Illes
Illescas
Illian
Illiano
Illich
Illies
Illig
Illingworth
Illovsky
Illsley
Illuzzi
Ilse
Iltzsch
Im
Imada
Imai
Imaino
Imaizumi
Imam
Imamura
Iman
Imbach
Imber
Imberg
Imbert
Imbesi
Imbier
Imbimbo
Imboden
Imbrenda
Imbriale
Imbrock
Imbrogno
Imbruglia
Imburgia
Imdieke
Imel
Imes
Imeson
Imfeld
Imgrund
Imhof
Imhoff
Imholte
Imig
Imlay
Imler
Imm
Imme
Immediato
Immel
Immen
Immerman
Imming
Immordino
Imondi
Imoto
Imparato
Imperato
Imperatore
Imperial
Impson
Imrie
Imus
In
Ina
Inaba
Inabinet
Inabinett
Inabnit
Inacio
Inafuku
Inagaki
Inbody
Incarnato
Ince
Incera
Inch
Inches
Inciong
Inclan
Incle
Incomstanti
Incorvaia
Inda
Indal
Indeck
Indelicato
Indermuehle
Indest
Indovina
Induddi
Iner
Ines
Ineson
Inestroza
Infante
Infantino
Infantolino
Inferrera
Infield
Infinger
Ing
Inga
Ingala
Ingalls
Ingalsbe
Ingargiola
Ingargiolo
Ingber
Inge
Ingebretsen
Ingegneri
Ingels
Ingemi
Ingenito
Ingersol
Ingersoll
Ingerson
Ingham
Inghem
Inghram
Ingle
Ingles
Inglese
Ingleton
Inglin
Inglis
Inglish
Ingmire
Ingold
Ingole
Ingraffea
Ingraham
Ingrahm
Ingram
Ingran
Ingrassia
Ingrim
Ingrum
Inguardsen
Ingvolostad
Ingwell
Ingwersen
Ingwerson
Inhulsen
Iniestra
Iniguez
Iniquez
Ink
Inkavesvanitc
Inklebarger
Inks
Inloes
Inlow
Inman
Inmon
Innamorato
Innarelli
Innella
Innerst
Innes
Innis
Inniss
Innocent
Innocenti
Inoa
Inocencio
Inocente
Inostraza
Inoue
Inouye
Insalaco
Insana
Inscho
Insco
Inscoe
Inscore
Inserra
Inskeep
Insko
Insley
Insogna
Insognia
Instasi
Interdonato
Interiano
Intermill
Interrante
Intihar
Intrabartolo
Intriago
Intrieri
Introini
Intveld
Inverso
Inyart
Inzana
Inzano
Inzer
Inzerillo
Inzunza
Ioannidis
Iodice
Ioele
Ioli
Ion
Ionescu
Iopa
Iorio
Iossa
Iott
Iovino
Iozzi
Iozzo
Ip
Ipock
Ippolito
Ipsen
Ipson
Iqbal
Iracheta
Iraheta
Irani
Irby
Iredale
Irelan
Ireland
Irene
Ireson
Irestone
Ireton
Irey
Iriarte
Irias
Iribarren
Irick
Irie
Irigoyen
Irimata
Irineo
Irion
Irish
Irizarri
Irizarry
Irizary
Irizzary
Irland
Irle
Irmeger
Iron
Ironhorse
Irons
Irr
Irsik
Iruegas
Irvan
Irvin
Irvine
Irving
Irwin
Irzyk
Isa
Isaac
Isaack
Isaacks
Isaacs
Isaacsen
Isaacson
Isaak
Isabel
Isabell
Isabella
Isabelle
Isachsen
Isackson
Isacs
Isacson
Isadore
Isagawa
Isagba
Isaiah
Isais
Isaksen
Isakson
Isales
Isam
Isaman
Isassi
Isaza
Isbell
Isbill
Isbister
Isbrecht
Isby
Isch
Isebrand
Iseley
Iseli
Iseman
Isenbarger
Isenberg
Isenberger
Isenhart
Isenhour
Isenhower
Iser
Iseri
Iserman
Isett
Isgrigg
Isgro
Isgur
Ishak
Isham
Ishee
Isherwood
Ishibashi
Ishida
Ishihara
Ishii
Ishikawa
Ishizu
Ishmael
Ishman
Ishmon
Isidore
Isidoro
Isidro
Isiminger
Ising
Isiordia
Isip
Isita
Iskra
Isla
Islam
Island
Islar
Islas
Isle
Isleib
Isler
Isles
Isley
Ismael
Ismail
Ismay
Isner
Isola
Isom
Isome
Ison
Israel
Israels
Israelsen
Israelson
Isreal
Issa
Issac
Issacs
Issler
Istorico
Istre
Italia
Italiano
Itani
Ith
Itkin
Itnyre
Ito
Itri
Itson
Ittner
Iturbe
Iturbide
Iturralde
Itzkowitz
Iuchs
Iulianetti
Iuliano
Iuliucci
Iulo
Iurato
Ivan
Ivancevic
Ivancic
Ivancich
Ivanoff
Ivanov
Ivans
Ivaska
Iveans
Ivel
Ivener
Ivens
Ivers
Iversen
Iverslie
Iverson
Ivery
Ives
Iveson
Ivester
Ivey
Ivie
Ivins
Ivon
Ivory
Ivrin
Ivy
Iwami
Iwamoto
Iwanejko
Iwanicki
Iwanowski
Iwanski
Iwanyszyn
Iwaoka
Iwasa
Iwasaki
Iwashita
Iwasko
Iwata
Iyengar
Iyer
Iyo
Izaguine
Izaguirre
Izak
Izaquirre
Izard
Izarraras
Izatt
Izquierdo
Izsak
Izumi
Izzard
Izzi
Izzo
Jaap
Jaarda
Jabaay
Jabali
Jabaut
Jabbie
Jabbour
Jaber
Jabiro
Jablon
Jablonowski
Jablonski
Jablonsky
Jabour
Jabs
Jacaruso
Jacckson
Jacek
Jach
Jacinthe
Jacinto
Jack
Jacka
Jackel
Jackels
Jackett
Jackiewicz
Jackley
Jacklin
Jackman
Jacko
Jackola
Jackon
Jackosn
Jackovitz
Jackowiak
Jackowski
Jacks
Jacksits
Jackso
Jackson
Jackstadt
Jaco
Jacob
Jacobellis
Jacobi
Jacobitz
Jacobo
Jacobos
Jacobovits
Jacobowitz
Jacobs
Jacobsen
Jacobsma
Jacobsohn
Jacobson
Jacobus
Jacoby
Jacocks
Jacome
Jaconski
Jacot
Jacoway
Jacox
Jacquay
Jacque
Jacquelin
Jacquem
Jacquemin
Jacques
Jacquet
Jacquez
Jacquier
Jacquin
Jacquot
Jaculina
Jadin
Jadlowiec
Jadoo
Jae
Jaecks
Jaeger
Jaegers
Jaekel
Jaenicke
Jaenke
Jaeschke
Jafari
Jafek
Jaffe
Jaffee
Jaffray
Jaffy
Jageman
Jager
Jagers
Jagger
Jaggers
Jaggie
Jagher
Jagiello
Jagielski
Jagla
Jagneaux
Jago
Jagoda
Jagodzinski
Jagoe
Jagow
Jahaly
Jahde
Jahn
Jahncke
Jahnel
Jahnke
Jahns
Jahnsen
Jahoda
Jahosky
Jahr
Jaillet
Jaime
Jaimes
Jain
Jainlett
Jaiyesimi
Jaji
Jakab
Jakeman
Jakes
Jakiela
Jakob
Jakobsen
Jakobson
Jakovac
Jakowich
Jaksch
Jaksic
Jakubczak
Jakubek
Jakubiak
Jakubik
Jakuboski
Jakubov
Jakubowski
Jakupcak
Jalbert
Jalkut
Jalomo
Jalonen
Jalovel
Jamaica
Jamal
Jamar
Jamason
Jame
Jameel
Jamel
Jamer
Jamerson
James
Jameson
Jamesson
Jamgochian
Jami
Jamie
Jamieson
Jamili
Jamin
Jaminet
Jamir
Jamison
Jammer
Jamon
Jamwant
Jan
Jana
Janacek
Janack
Janak
Janas
Jancik
Janco
Janczak
Janczewski
Janczunski
Janda
Jandl
Jandreau
Jandres
Jandrey
Jandrin
Jandris
Jandron
Jane
Janecek
Janecka
Janeczek
Janeczko
Janeiro
Janek
Janelle
Janes
Janeway
Janey
Jang
Jangula
Janhunen
Janiak
Janice
Janick
Janicke
Janicki
Janik
Janikowski
Janis
Janisch
Janise
Janish
Janiszewski
Janitz
Jank
Janka
Jankauskas
Janke
Jankins
Jankoff
Jankoski
Jankowiak
Jankowski
Jann
Jannell
Janner
Jannett
Jannetti
Janney
Janning
Jannise
Jannsen
Jannusch
Janocha
Janoff
Janofsky
Janos
Janosek
Janosik
Janoski
Janosko
Janousek
Janovich
Janovsek
Janow
Janower
Janowiak
Janowicz
Janowiec
Janowski
Janrhett
Jans
Jansen
Jansing
Janski
Jansky
Jansma
Janson
Jansons
Janssen
Jansson
Janszen
Jantz
Jantzen
January
Janulewicz
Janus
Janusz
Januszewski
Janvier
Janway
Janysek
Janz
Janzen
Japak
Japp
Jappa
Jaqua
Jaquay
Jaques
Jaquess
Jaquet
Jaquez
Jaquins
Jaquish
Jaquith
Jara
Jarad
Jaradat
Jaramillo
Jarboe
Jarchow
Jardel
Jardell
Jardin
Jardine
Jarding
Jardon
Jardot
Jarecke
Jarecki
Jared
Jarell
Jarels
Jarema
Jaremka
Jarencio
Jares
Jaret
Jarett
Jargas
Jarman
Jarmin
Jarmon
Jarnagin
Jarnesky
Jarnigan
Jarnutowski
Jarocki
Jaros
Jaroscak
Jarosh
Jaroski
Jaross
Jarosz
Jarquin
Jarrar
Jarrard
Jarratt
Jarreau
Jarred
Jarrel
Jarrell
Jarrells
Jarret
Jarrett
Jarrette
Jarriett
Jarry
Jaruis
Jarva
Jarver
Jarvi
Jarvie
Jarvinen
Jarvis
Jarzembowski
Jarzombek
Jarzynka
Jasch
Jasica
Jasik
Jasin
Jasinski
Jasionowski
Jaskiewicz
Jasko
Jaskolka
Jaskolski
Jaskot
Jasmann
Jasmer
Jasmin
Jasmine
Jaso
Jason
Jasper
Jaspers
Jasperse
Jass
Jasso
Jaster
Jastrebski
Jastremski
Jastrzebski
Jatho
Jaubert
Jauch
Jaudon
Jauhar
Jaure
Jauregui
Jaureguy
Jaurequi
Jaurez
Jaurigue
Jaurigui
Jauron
Jaus
Jauss
Jaussen
Jaussi
Javarone
Javaux
Jave
Javed
Javellana
Javens
Javers
Javery
Javier
Javis
Javor
Jawad
Jaworowicz
Jaworowski
Jaworski
Jaworsky
Jax
Jay
Jaycox
Jaye
Jayes
Jayme
Jayne
Jaynes
Jayo
Jayroe
Jayson
Jaysura
Jazwa
Jean
Jeanbaptise
Jeanbaptiste
Jeanbart
Jeancharles
Jeanclaude
Jeancy
Jeane
Jeanes
Jeanette
Jeanfrancois
Jeangilles
Jeanjacques
Jeanlouis
Jeanmard
Jeanneret
Jeannette
Jeannoel
Jeannotte
Jeanpaul
Jeanphilippe
Jeanpierre
Jeanquart
Jeans
Jeansonne
Jeantet
Jeanty
Jeavons
Jebb
Jebbett
Jech
Jeck
Jecklin
Jecmenek
Jedan
Jedele
Jedik
Jedlicka
Jedrey
Jedziniak
Jee
Jefcoat
Jeff
Jeffcoat
Jefferds
Jefferies
Jefferis
Jeffers
Jefferson
Jeffery
Jefferys
Jeffirs
Jefford
Jeffords
Jeffress
Jeffrey
Jeffreys
Jeffrie
Jeffries
Jeffris
Jeffry
Jeffryes
Jeffs
Jeffus
Jegede
Jehl
Jehle
Jehlicka
Jekel
Jekot
Jelarde
Jelden
Jelen
Jeleniewski
Jelinek
Jelinski
Jelks
Jelle
Jellerson
Jelley
Jellinek
Jellings
Jellis
Jellison
Jelome
Jelovich
Jelsma
Jeltema
Jemenez
Jemerson
Jeminez
Jemison
Jemmett
Jemmings
Jemmott
Jempty
Jen
Jenab
Jenaye
Jenck
Jencks
Jenderer
Jendras
Jendrick
Jendro
Jeng
Jenifer
Jenious
Jenison
Jenista
Jenkens
Jenkerson
Jenkin
Jenkins
Jenkinson
Jenks
Jenne
Jennelle
Jenner
Jenness
Jennett
Jennette
Jenney
Jennie
Jennifer
Jenniges
Jenning
Jennings
Jennins
Jennison
Jennkie
Jennrich
Jenny
Jenovese
Jenquin
Jenrette
Jens
Jenschke
Jensen
Jenson
Jensrud
Jensvold
Jent
Jentry
Jentsch
Jentzen
Jentzsch
Jeoffroy
Jeon
Jeong
Jephson
Jepko
Jepperson
Jeppesen
Jeppsen
Jeppson
Jepsen
Jepson
Jerabek
Jerald
Jerauld
Jerde
Jerdee
Jerden
Jerding
Jerdon
Jereb
Jeremiah
Jerez
Jergen
Jergens
Jergenson
Jerger
Jerich
Jericho
Jerido
Jerkin
Jerkins
Jerko
Jerman
Jermeland
Jernberg
Jernejcic
Jernigan
Jernstad
Jernstrom
Jerome
Jerone
Jeronimo
Jerowski
Jerrel
Jerrell
Jerrett
Jerry
Jersey
Jervey
Jervis
Jes
Jeschke
Jeschon
Jesenovec
Jesiolowski
Jeska
Jeske
Jeskie
Jesko
Jesmer
Jespersen
Jesperson
Jess
Jessamy
Jesse
Jessee
Jessel
Jesseman
Jessen
Jessica
Jessick
Jessie
Jessop
Jessup
Jest
Jester
Jestes
Jestis
Jesus
Jeswald
Jeter
Jethro
Jethva
Jett
Jette
Jetter
Jetton
Jetty
Jeudy
Jeune
Jevnikar
Jevtic
Jew
Jewel
Jewell
Jewels
Jewett
Jewkes
Jews
Jex
Jez
Jezek
Jezewski
Jezierski
Jeziorski
Jhanson
Jhingree
Jhonson
Jhonston
Ji
Jiang
Jiau
Jiggetts
Jilek
Jiles
Jilk
Jill
Jillson
Jim
Jimbo
Jimenes
Jimenez
Jimeno
Jimenz
Jimerez
Jimerson
Jimeson
Jiminez
Jiminian
Jimison
Jimmerson
Jimmison
Jin
Jindra
Jinenez
Jines
Jing
Jingst
Jinkens
Jinkerson
Jinkins
Jinks
Jinright
Jinwright
Jipson
Jira
Jirak
Jiran
Jirasek
Jirik
Jirjis
Jiron
Jirsa
Jitchaku
Jividen
Jn
Jo
Joa
Joachim
Joachin
Joanette
Joanis
Joans
Joaquin
Joas
Job
Jobe
Jobes
Jobin
Jobs
Jobson
Jobst
Jochems
Jochim
Jochum
Jochumsen
Jock
Jockers
Jocoy
Jodha
Jodoin
Jodon
Jodway
Jody
Joe
Joeckel
Joecks
Joehnck
Joel
Joelson
Joens
Joerg
Joerger
Joerling
Joern
Joesph
Joffe
Joffrion
Joganic
Joh
Johal
Johanek
Johann
Johannes
Johannesen
Johannessen
Johanning
Johanningmeie
Johanns
Johannsen
Johansen
Johansing
Johanson
Johansson
Johar
Johe
Johengen
Johll
John
Johndrow
Johngrass
Johnico
Johnigan
Johniken
Johnikins
Johnke
Johnny
Johnosn
Johns
Johnsen
Johnsey
Johnshoy
Johnso
Johnson
Johnsrud
Johnstad
Johnston
Johnstonbaugh
Johnstone
Johnting
Johson
Joice
Joiner
Joines
Jointer
Jojola
Jokela
Joki
Jokinen
Joler
Joles
Jolicoeur
Jolie
Joliet
Jolin
Jolina
Joline
Jolissaint
Jolivette
Jolla
Jolley
Jollie
Jolliff
Jolliffe
Jollimore
Jolls
Jolly
Joly
Joma
Jome
Jomes
Jonah
Jonak
Jonas
Jonason
Jonassen
Jonathan
Joncas
Jondahl
Jondle
Jondrow
Jone
Jones
Joneson
Jong
Jongebloed
Jongeling
Jongsma
Jonhson
Jonke
Jonker
Jonnson
Jons
Jonson
Jonsson
Jonte
Joo
Joor
Joos
Joosten
Joplin
Jopling
Jorda
Jordahl
Jordan
Jorde
Jorden
Jording
Jordison
Jordon
Jordt
Jore
Jorge
Jorgensen
Jorgenson
Jorinscay
Joris
Jorn
Jorres
Jorrisch
Jorski
Jorstad
Jory
Jose
Josef
Josefy
Joseph
Josephpauline
Josephs
Josephsen
Josephson
Josey
Joshi
Joshlin
Joshua
Josiah
Josias
Josic
Josich
Josilowsky
Joslin
Joslyn
Joss
Josselyn
Jossund
Jost
Josten
Jostes
Josue
Joswick
Jotblad
Joto
Jou
Joubert
Joulwan
Joun
Joung
Jourdain
Jourdan
Journeay
Journell
Journey
Journot
Jovanovic
Jovanovich
Jove
Jovel
Jover
Jovich
Jowell
Jowers
Jowett
Joy
Joya
Joyal
Joyce
Joye
Joyne
Joyner
Joynes
Joynson
Joynt
Jozsa
Jozwiak
Jozwick
Ju
Juaire
Juan
Juanico
Juarbe
Juares
Juarez
Juariqui
Juart
Juba
Juback
Jubb
Jubeh
Jubert
Jubic
Jubie
Jubilee
Jubinville
Jubran
Jubyna
Jucean
Juckett
Juda
Judah
Judd
Jude
Judge
Judice
Judie
Judkins
Judon
Judson
Judy
Jue
Juedes
Juel
Juelfs
Juelich
Juell
Juen
Juenemann
Juenger
Juengling
Juergens
Juett
Jufer
Jugan
Jugo
Juhas
Juhasz
Juhl
Juhnke
Jui
Juilfs
Jukes
Jukich
Julander
Julca
Julen
Jules
Julia
Julian
Juliana
Juliano
Juliar
Julias
Julien
Juliet
Julio
Julitz
Julius
Juliusson
Julock
Julson
Julsrud
Juluke
July
Julye
Jumalon
Jumbo
Jumonville
Jump
Jumper
Jun
Juncaj
Juncker
Jund
Jundt
June
Juneau
Juneja
Junes
Jung
Jungbluth
Jungck
Junge
Jungels
Jungen
Jungers
Junghans
Jungling
Jungman
Jungquist
Jungwirth
Junick
Juniel
Junior
Junious
Juniper
Junius
Junk
Junke
Junker
Junkersfeld
Junkin
Junkins
Junod
Junor
Juntunen
Jupin
Jupiter
Jura
Jurado
Juran
Juras
Jurasek
Jurasin
Juray
Jurcik
Jurczak
Jurczyk
Jurden
Jure
Jurek
Jurewicz
Jurez
Jurgen
Jurgens
Jurgensen
Jurgensmeier
Jurgensmeyer
Jurgenson
Jurica
Jurich
Juriga
Jurik
Jurin
Jurina
Juris
Jurisch
Jurist
Jurkiewicz
Jurkovich
Jurkowski
Jurney
Jurries
Jurs
Jury
Jusino
Jusko
Just
Justak
Justason
Juste
Justen
Justesen
Justian
Justice
Justin
Justine
Justinger
Justiniano
Justino
Justis
Justiss
Justman
Justo
Justus
Jutras
Jutte
Juul
Juve
Juvenal
Juvera
Juza
Ka
Kaai
Kaaihue
Kaak
Kaan
Kaanana
Kaarlela
Kaas
Kaase
Kaatz
Kaaua
Kaauamo
Kaawa
Kaaz
Kaba
Kababik
Kabacinski
Kabala
Kabanuck
Kabat
Kabba
Kabel
Kaber
Kabigting
Kabina
Kabir
Kabler
Kaboos
Kabrick
Kabus
Kabzinski
Kacerski
Kach
Kachel
Kachelmeyer
Kacher
Kachermeyer
Kachikian
Kachiroubas
Kachmar
Kachmarsky
Kacic
Kacik
Kackley
Kacprowski
Kacvinsky
Kacynski
Kaczka
Kaczmarczyk
Kaczmarek
Kaczmarski
Kaczor
Kaczorowski
Kaczynski
Kadakia
Kadar
Kade
Kadel
Kadelak
Kader
Kaderlik
Kadi
Kading
Kadis
Kadish
Kadle
Kadlec
Kadlubowski
Kadner
Kadow
Kadri
Kaduk
Kady
Kaea
Kaeding
Kaehler
Kaelin
Kaelker
Kaemingk
Kaemmerer
Kaemmerling
Kaempfer
Kaeo
Kaer
Kaercher
Kaesemeyer
Kaeser
Kaestner
Kaetzel
Kaewprasert
Kafel
Kafer
Kaffka
Kafka
Kafton
Kagan
Kagarise
Kagawa
Kagay
Kagel
Kager
Kagey
Kagimoto
Kagle
Kagy
Kah
Kahae
Kahahane
Kahal
Kahalehoe
Kahaleua
Kahan
Kahana
Kahanaoi
Kahanek
Kahao
Kahawai
Kahele
Kahen
Kahill
Kahl
Kahle
Kahler
Kahley
Kahn
Kahola
Kahoohalphala
Kahookele
Kahoun
Kahre
Kahrer
Kahrs
Kahuhu
Kai
Kaiama
Kaib
Kaid
Kaighn
Kaigle
Kaigler
Kaiktsian
Kail
Kailey
Kaili
Kailiponi
Kain
Kaina
Kaines
Kaing
Kainoa
Kainz
Kais
Kaiser
Kaiserman
Kaitz
Kaiwi
Kaizer
Kaja
Kajder
Kakacek
Kakani
Kakar
Kakaviatos
Kakeh
Kakimoto
Kakos
Kakowski
Kaku
Kakudji
Kala
Kalaf
Kalafarski
Kalafatis
Kalafut
Kalahiki
Kalal
Kalama
Kalamaras
Kalan
Kalandek
Kalani
Kalar
Kalas
Kalata
Kalathas
Kalauli
Kalawe
Kalb
Kalbach
Kalbaugh
Kalberer
Kalberg
Kalbfleisch
Kalchik
Kalchthaler
Kaldahl
Kaldas
Kale
Kaleel
Kalehuawehe
Kaleiwahea
Kalen
Kalenak
Kalenkoski
Kaleohano
Kaler
Kalert
Kales
Kaleta
Kaley
Kalfa
Kalfas
Kalfayan
Kalfus
Kalgren
Kalhorn
Kali
Kalich
Kalichman
Kaliher
Kalil
Kalima
Kalin
Kalina
Kalinger
Kalinoski
Kalinowski
Kalinski
Kalis
Kalisch
Kalisek
Kalish
Kalista
Kaliszewski
Kaliszuk
Kalk
Kalka
Kalkbrenner
Kalkman
Kalkwarf
Kall
Kalla
Kallaher
Kallal
Kallam
Kalland
Kallas
Kallberg
Kallbrier
Kallen
Kallenbach
Kallenberg
Kallenberger
Kaller
Kallestad
Kallevig
Kalley
Kallfelz
Kallhoff
Kallin
Kallio
Kallman
Kallmeyer
Kalloch
Kallstrom
Kallus
Kalman
Kalmar
Kalmbach
Kalmen
Kalmer
Kalmus
Kaloi
Kaloudis
Kaloustian
Kalp
Kalpakoff
Kalscheuer
Kalsow
Kalt
Kaltefleiter
Kaltenbach
Kaltenhauser
Kalter
Kalthoff
Kaltved
Kaltz
Kalua
Kaluna
Kalupa
Kaluzny
Kalvaitis
Kalvig
Kam
Kama
Kamada
Kamai
Kamaka
Kamakea
Kamal
Kamalii
Kaman
Kamansky
Kamara
Kamat
Kamaunu
Kamb
Kamber
Kame
Kamealoha
Kamel
Kamelamela
Kamemoto
Kamen
Kamens
Kamensky
Kamer
Kamerad
Kamerer
Kamerling
Kamienski
Kamimura
Kamin
Kaminaka
Kaminer
Kaminetzky
Kaminska
Kaminski
Kaminsky
Kamirez
Kamiya
Kamke
Kamler
Kamm
Kamman
Kammann
Kammel
Kammer
Kammerdiener
Kammerer
Kammerzell
Kammes
Kammler
Kamna
Kamnik
Kamp
Kampa
Kampe
Kampen
Kamper
Kampf
Kampfer
Kamph
Kamphoefner
Kampman
Kampmann
Kampner
Kamps
Kamradt
Kamrath
Kamrowski
Kamstra
Kamuda
Kan
Kana
Kanaan
Kanable
Kanady
Kanae
Kanagy
Kanahele
Kanai
Kanakares
Kanan
Kanarek
Kanaris
Kanas
Kanatzar
Kand
Kanda
Kandarian
Kandel
Kander
Kandoll
Kandra
Kandt
Kanduth
Kane
Kaneakua
Kanealii
Kaneholani
Kaneko
Kanekuni
Kanelos
Kanemoto
Kaner
Kaneshiro
Kaneta
Kanevsky
Kang
Kangas
Kangleon
Kania
Kaniecki
Kaniewski
Kanipe
Kanis
Kanish
Kanjirathinga
Kann
Kannady
Kannan
Kannard
Kannas
Kanne
Kannel
Kannenberg
Kanner
Kanney
Kanniard
Kanno
Kano
Kanoa
Kanode
Kanoff
Kanoon
Kanosh
Kanoy
Kanoza
Kansas
Kansky
Kant
Kanta
Kantah
Kantarian
Kanter
Kanthak
Kantis
Kantner
Kantola
Kantor
Kantrowitz
Kantz
Kanwar
Kanz
Kanzenbach
Kanzler
Kao
Kaopua
Kap
Kapa
Kapadia
Kapahu
Kapanke
Kapaun
Kapelke
Kaper
Kaperonis
Kapetanos
Kapfer
Kapichok
Kapiloff
Kapinos
Kapitula
Kapke
Kaplan
Kapler
Kaplin
Kaplowitz
Kaplun
Kapnick
Kapoi
Kapoor
Kapp
Kappa
Kappe
Kappel
Kappeler
Kappelmann
Kappen
Kapper
Kapperman
Kappes
Kapphahn
Kappler
Kapps
Kapral
Kapraun
Kaps
Kapsalis
Kapsner
Kapsos
Kapur
Kapuscinski
Kapusniak
Kar
Kara
Karabin
Karadimas
Karaffa
Karageorge
Karagiannes
Karagiannis
Karakas
Karalis
Karam
Karamchandani
Karangelen
Karapetian
Karapetyan
Karas
Karasek
Karasti
Karathanasis
Karatz
Karau
Karayan
Karban
Karbowski
Karch
Karcher
Karcich
Karcz
Karczewski
Kardas
Kardashian
Kardell
Kardos
Kardux
Kareem
Karel
Karell
Karella
Karels
Karen
Karg
Karge
Karger
Karhoff
Kari
Kariger
Karim
Karimi
Karin
Karins
Karjala
Karkut
Karl
Karle
Karlen
Karley
Karlgaard
Karlin
Karlinsky
Karlovich
Karls
Karlsen
Karlson
Karlsson
Karlstad
Karma
Karman
Karmann
Karmazyn
Karmel
Karmely
Karmo
Karn
Karnas
Karnath
Karner
Karnes
Karney
Karnish
Karnofski
Karnopp
Karns
Karo
Karol
Karoly
Karow
Karp
Karpe
Karpel
Karpen
Karper
Karpf
Karpiak
Karpin
Karpinen
Karpinski
Karpinsky
Karpowich
Karpowicz
Karpstein
Karr
Karraker
Karras
Karratti
Karrels
Karren
Karrenberg
Karro
Karroach
Karry
Karsh
Karshner
Karsnak
Karst
Karsten
Karstens
Karstensen
Karstetter
Kartchner
Karter
Kartes
Karth
Kartman
Karty
Kartye
Karvis
Karvonen
Karwoski
Karwowski
Kary
Karz
Kasa
Kasack
Kasahara
Kasal
Kascak
Kasch
Kaschak
Kaschel
Kaschmitter
Kasdon
Kase
Kasee
Kasel
Kasemeier
Kasen
Kaser
Kasey
Kash
Kashan
Kashani
Kashner
Kashuba
Kasica
Kasik
Kasimis
Kasinger
Kaska
Kaskey
Kasky
Kasmarek
Kasmir
Kasowski
Kaspar
Kasparek
Kaspari
Kasparian
Kasper
Kasperek
Kasperski
Kasprak
Kasprowicz
Kasprzak
Kasprzyk
Kass
Kassa
Kassab
Kassabaum
Kassabian
Kassam
Kassay
Kassebaum
Kassel
Kassell
Kassem
Kasserman
Kassim
Kassin
Kassing
Kassis
Kassler
Kassman
Kassner
Kasson
Kassouf
Kassulke
Kast
Kastanes
Kastein
Kastel
Kasten
Kastendieck
Kastens
Kaster
Kasting
Kastl
Kastler
Kastman
Kastner
Kastning
Kastor
Kasuba
Kasuboski
Kasula
Kasun
Kaszinski
Kaszton
Kaszuba
Kaszynski
Kata
Katan
Kataoka
Katayama
Katcher
Katcsmorak
Kate
Katechis
Kately
Katen
Kater
Kates
Kath
Kathan
Katheder
Kathel
Kathleen
Kathman
Katie
Katin
Katis
Katke
Katnik
Kato
Katoa
Katoh
Katon
Katona
Katos
Katowicz
Katra
Kats
Katsaounis
Katsbulas
Katsch
Katsuda
Katt
Kattan
Kattaura
Katten
Katterjohn
Kattner
Katula
Katynski
Katz
Katzaman
Katzberg
Katzen
Katzenbach
Katzenberg
Katzenberger
Katzer
Katzman
Katzmann
Katzmark
Katzner
Kaua
Kauahi
Kaub
Kauble
Kaucher
Kauder
Kauer
Kauffeld
Kauffman
Kauffmann
Kaufhold
Kaufman
Kaufmann
Kaufusi
Kaui
Kauk
Kaukola
Kaul
Kaull
Kaumans
Kaumo
Kaune
Kaunisto
Kauo
Kaup
Kauphusman
Kaupp
Kauppi
Kaupu
Kaur
Kaus
Kausch
Kaushal
Kaushiva
Kaut
Kautz
Kautzer
Kautzman
Kauzlarich
Kava
Kavadias
Kavanagh
Kavanah
Kavanaugh
Kavaney
Kave
Kaveney
Kaveny
Kavin
Kawa
Kawaa
Kawachi
Kawaguchi
Kawahara
Kawai
Kawaiaea
Kawakami
Kawamoto
Kawamura
Kawano
Kawasaki
Kawashima
Kawata
Kawczynski
Kawell
Kawelo
Kawski
Kawulok
Kay
Kaya
Kayastha
Kayat
Kaye
Kayes
Kayler
Kaylo
Kaylor
Kayrouz
Kays
Kayser
Kaywood
Kaz
Kaza
Kazabi
Kazakos
Kazan
Kazanjian
Kazanowski
Kazar
Kazarian
Kazda
Kazeck
Kazee
Kazemi
Kazi
Kazimi
Kazin
Kazmer
Kazmi
Kazmierczak
Kazmierski
Kazmorck
Kazunas
Ke
Kea
Keach
Keadle
Keady
Keaffaber
Keagle
Keagy
Keahey
Keal
Keala
Kealey
Kealoha
Kealohanui
Kealy
Keamo
Keams
Kean
Keane
Keaney
Keanu
Keanum
Keany
Kear
Kearbey
Kearby
Kearin
Kearl
Kearley
Kearn
Kearney
Kearns
Kearny
Kears
Kearse
Kearsey
Kearsley
Keas
Keaser
Keasey
Keasler
Keasley
Keast
Keat
Keate
Keaten
Keath
Keathley
Keating
Keatley
Keaton
Keator
Keats
Keatts
Keaty
Keaveney
Keaveny
Keavney
Keawe
Keay
Keba
Kebalka
Kebe
Kebede
Kebert
Keblish
Kebort
Keck
Kecker
Keckler
Kecskes
Keddy
Kedia
Keding
Kedley
Kedra
Kedzierski
Kee
Keeble
Keebler
Keech
Keedah
Keedy
Keef
Keefauver
Keefe
Keefer
Keefner
Keegan
Keehan
Keehn
Keehne
Keehner
Keel
Keelan
Keele
Keeler
Keeley
Keelin
Keeling
Keels
Keely
Keeman
Keemer
Keen
Keena
Keenan
Keene
Keener
Keeneth
Keeney
Keenom
Keens
Keenum
Keeny
Keep
Keepers
Keer
Keeran
Keery
Kees
Keese
Keesecker
Keesee
Keeser
Keesey
Keesler
Keesling
Keet
Keetan
Keetch
Keeter
Keeth
Keeton
Keets
Keever
Keezer
Kefauver
Keffer
Kegel
Kegerries
Kegg
Kegler
Kegley
Keglovic
Keh
Kehew
Kehl
Kehler
Kehm
Kehn
Kehoe
Kehr
Kehrer
Kehres
Kehs
Keib
Keicher
Keidong
Keifer
Keiffer
Keiger
Keigley
Keihl
Keil
Keilen
Keilholtz
Keilholz
Keilty
Keim
Keimig
Keinonen
Keipe
Keiper
Keir
Keirn
Keirnan
Keirns
Keirstead
Keis
Keisacker
Keisel
Keiser
Keisker
Keisler
Keisling
Keiss
Keister
Keiswetter
Keitel
Keiter
Keith
Keithan
Keithley
Keithly
Keitsock
Keitt
Keitzer
Keizer
Kekahuna
Kekiwi
Keks
Kekua
Kela
Kelash
Kelau
Kelch
Kelchner
Kelcourse
Kelder
Kelderman
Keledjian
Keleher
Keleman
Kelemen
Kelii
Keliiholokai
Keliihoomalu
Keliikoa
Keliipaakaua
Keliipio
Kelk
Kelker
Kell
Kellam
Kellams
Kellan
Kellar
Kellaway
Kellebrew
Kelleher
Kellem
Kellems
Kellen
Kellenberger
Keller
Kellerhouse
Kellerman
Kellermann
Kellett
Kelley
Kellie
Kelliher
Kellin
Kelling
Kellis
Kellish
Kellison
Kellman
Kelln
Kellner
Kello
Kellog
Kellogg
Kellom
Kellon
Kellough
Kellow
Kells
Kellstrom
Kellum
Kelly
Kellywood
Kelm
Kelman
Kelnhofer
Kelp
Kelsay
Kelsch
Kelsey
Kelsheimer
Kelso
Kelsoe
Kelson
Kelstrom
Kelter
Keltner
Kelton
Keltt
Kelty
Keltz
Kelzer
Kem
Kemble
Kemerer
Kemerling
Kemerly
Kemery
Kemfort
Kemick
Kemler
Kemme
Kemmer
Kemmerer
Kemmeries
Kemmerlin
Kemmerling
Kemmis
Kemmler
Kemna
Kemner
Kemnitz
Kemp
Kempa
Kempe
Kempel
Kempen
Kemper
Kempf
Kempfer
Kemph
Kempinski
Kempisty
Kempkens
Kempker
Kemple
Kempler
Kemplin
Kempner
Kempon
Kemppainen
Kemps
Kempson
Kempster
Kempt
Kempter
Kempton
Ken
Kenaan
Kenady
Kenaga
Kenagy
Kenan
Kendal
Kendall
Kendell
Kenderdine
Kendi
Kendig
Kendle
Kendra
Kendrew
Kendrick
Kendricks
Kendrix
Kendzierski
Kendzior
Kendziora
Keneally
Kenealy
Kenebrew
Kenefick
Keneipp
Kenekham
Kenely
Keney
Kenfield
Kenik
Kenimer
Keniry
Kenison
Keniston
Kenkel
Kenley
Kenmore
Kenna
Kennady
Kennamer
Kennamore
Kennan
Kennard
Kennaugh
Kenndey
Kenndy
Kenne
Kenneally
Kennealy
Kennebeck
Kennebrew
Kennedy
Kennel
Kennell
Kennelley
Kennelly
Kennelty
Kennemer
Kennemore
Kennemur
Kennemuth
Kenner
Kennerly
Kennerson
Kennet
Kenneth
Kennett
Kenney
Kenngott
Kennie
Kennin
Kenning
Kennington
Kennis
Kennison
Kenniston
Kennon
Kenny
Keno
Kenon
Kenouo
Kenoyer
Kenrick
Kensey
Kensinger
Kenson
Kent
Kenter
Kentner
Kenton
Kenwood
Kenworthy
Kenyon
Kenzie
Keo
Keobaunleuang
Keodalah
Keogan
Keogh
Keoghan
Keohane
Keomanivong
Keomany
Keomuangtai
Keough
Keovongxay
Keown
Kepani
Kephart
Kepke
Kepler
Kepley
Keplin
Keplinger
Kepner
Kepp
Keppel
Keppers
Kepple
Keppler
Keppner
Ker
Keranen
Kerans
Kerbel
Kerber
Kerbo
Kerbow
Kerbs
Kerby
Kercado
Kerce
Kerchal
Kercheff
Kercher
Kercheval
Kerchner
Kercy
Kerechanko
Kerekes
Kereluk
Kerens
Kerestes
Kerfien
Kerfoot
Kerger
Keri
Kerin
Kerins
Kerk
Kerkel
Kerker
Kerkhoff
Kerkman
Kerksiek
Kerkvliet
Kerl
Kerley
Kerlin
Kerman
Kermes
Kern
Kernagis
Kernan
Kerne
Kernell
Kernen
Kerner
Kernes
Kerney
Kernighan
Kernodle
Kerns
Kerntke
Kero
Keros
Kerper
Kerr
Kerrick
Kerrigan
Kerry
Kersch
Kerscher
Kerschner
Kersey
Kersh
Kershaw
Kershbaumer
Kershner
Kerska
Kerslake
Kerson
Kerss
Kerst
Kerstein
Kersten
Kerstetter
Kersting
Kertels
Kertesz
Kerth
Kertis
Kertz
Kertzman
Kervin
Kerwin
Kerwood
Kerzer
Kerzman
Kesby
Kesek
Keser
Kesey
Keshishian
Keshishyan
Kesich
Kesinger
Keske
Keslar
Kesler
Kesley
Kesling
Kesner
Kess
Kessans
Kessel
Kessell
Kesselman
Kesselring
Kessenich
Kessinger
Kessler
Kessner
Kesson
Kesten
Kester
Kesterson
Kestle
Kestler
Kestner
Keszler
Ket
Ketay
Ketch
Ketcham
Ketchem
Ketchen
Ketcher
Ketchersid
Ketcherside
Ketcheside
Ketchie
Ketchum
Ketelaar
Ketelhut
Ketelsen
Kethcart
Ketler
Ketner
Keto
Ketola
Ketring
Ketron
Kett
Kettel
Kettell
Kettelle
Kettenring
Ketter
Ketterer
Kettering
Ketteringham
Ketterl
Ketterling
Ketterman
Kettinger
Kettl
Kettle
Kettler
Kettlewell
Kettman
Kettmann
Kettner
Ketzler
Keuler
Keup
Keuper
Kevan
Kevelin
Kever
Kevern
Keveth
Keville
Kevin
Kevorkian
Kevwitch
Kew
Kewal
Kewanwytewa
Kewish
Kexel
Key
Keye
Keyes
Keyl
Keylon
Keylor
Keyna
Keyon
Keys
Keyser
Keyt
Keyton
Keywan
Keyworth
Kezar
Kezele
Keziah
Kha
Khachatoorian
Khairallah
Khalaf
Khaleck
Khaleel
Khalid
Khalifah
Khalife
Khalil
Khalili
Khalsa
Kham
Khammixay
Khamo
Khamsyuorauon
Khamvongsa
Khan
Khang
Khanna
Khano
Khanponaphan
Khansari
Khare
Khat
Khatak
Khatcherian
Khatib
Khatri
Khauv
Khay
Khazaleh
Khazdozian
Khela
Khemmanivong
Khensamphanh
Khensovan
Kher
Khiev
Khilling
Khim
Khlok
Khn
Kho
Khokher
Kholodivker
Khong
Khoo
Khora
Khosravi
Khou
Khoun
Khounborine
Khounthavong
Khouri
Khoury
Khov
Khu
Khubba
Khum
Khuu
Kiah
Kiang
Kiani
Kibbe
Kibbee
Kibbey
Kibble
Kibbler
Kibby
Kibe
Kibel
Kibler
Kibodeaux
Kichline
Kick
Kickel
Kicker
Kicklighter
Kicks
Kid
Kida
Kidane
Kidd
Kidder
Kiddle
Kiddy
Kidner
Kidney
Kidwell
Kie
Kiebala
Kiebler
Kieck
Kiecker
Kiedrowski
Kief
Kiefel
Kiefer
Kiefert
Kieff
Kieffer
Kieft
Kieger
Kiehl
Kiehm
Kiehn
Kiehne
Kiekbusch
Kieke
Kiel
Kielar
Kielbasa
Kieler
Kielich
Kielman
Kielty
Kiely
Kienast
Kienbaum
Kiener
Kiening
Kienitz
Kienle
Kienow
Kientz
Kientzy
Kienzle
Kiepert
Kier
Kierce
Kiernan
Kierstead
Kierzewski
Kies
Kiesel
Kieser
Kiesewetter
Kiesling
Kiesow
Kiesser
Kiessling
Kiest
Kiester
Kiesz
Kietzer
Kietzman
Kiever
Kievit
Kiewiet
Kifer
Kiffe
Kiffer
Kiflezghie
Kiger
Kiggins
Kight
Kightlinger
Kihlstrom
Kihn
Kiili
Kijak
Kijek
Kijowski
Kiker
Kikkert
Kiko
Kikuchi
Kil
Kilarjian
Kilb
Kilbane
Kilberg
Kilbert
Kilborn
Kilborne
Kilbourn
Kilbourne
Kilbride
Kilburn
Kilbury
Kilby
Kilcher
Kilcoyne
Kilcrease
Kilcrest
Kilcullen
Kildare
Kilday
Kildoo
Kildow
Kilduff
Kile
Kiles
Kiley
Kilfoyle
Kilgallon
Kilger
Kilgo
Kilgor
Kilgore
Kilgour
Kilian
Kilichowski
Kilimnik
Kilkenny
Kilker
Kilkus
Kill
Killam
Killary
Killay
Kille
Killeagle
Killean
Killebrew
Killeen
Killelea
Killen
Killer
Killette
Killgore
Killian
Killiany
Killibrew
Killick
Killilea
Killin
Killingbeck
Killinger
Killings
Killingsworth
Killingworth
Killins
Killion
Killius
Killman
Killmer
Killmeyer
Killmon
Killoran
Killoren
Killough
Killoy
Killpack
Kilman
Kilmartin
Kilmer
Kilmister
Kilmon
Kilner
Kilness
Kilogan
Kilpatrick
Kilroy
Kilson
Kilstofte
Kiltie
Kilton
Kilts
Kilty
Kiltz
Kilver
Kilzer
Kim
Kimak
Kimbal
Kimball
Kimbel
Kimbell
Kimber
Kimberl
Kimberley
Kimberlin
Kimberling
Kimberly
Kimble
Kimbler
Kimbley
Kimbral
Kimbrel
Kimbrell
Kimbriel
Kimbril
Kimbro
Kimbrough
Kimbrow
Kime
Kimel
Kimery
Kimes
Kimler
Kimm
Kimme
Kimmel
Kimmell
Kimmer
Kimmerle
Kimmes
Kimmet
Kimmey
Kimminau
Kimmins
Kimmons
Kimoto
Kimpel
Kimple
Kimpton
Kimrey
Kimsey
Kimura
Kimzey
Kin
Kina
Kinabrew
Kinahan
Kinaj
Kinan
Kinard
Kinart
Kinas
Kinatyan
Kincade
Kincaid
Kincaide
Kincannon
Kincer
Kincey
Kinch
Kincheloe
Kinchen
Kincy
Kind
Kindall
Kindberg
Kinde
Kindel
Kindell
Kinder
Kinderknecht
Kinderman
Kindermann
Kindig
Kindl
Kindla
Kindle
Kindler
Kindley
Kindlimann
Kindred
Kindregan
Kindrick
Kinds
Kindschuh
Kindt
Kine
Kiner
Kinerson
Kines
King
Kingcade
Kingdom
Kingdon
Kingen
Kingery
Kingfisher
Kingham
Kinghorn
Kingma
Kingman
Kingore
Kingrey
Kingry
Kings
Kingsberry
Kingsbury
Kingsford
Kingshott
Kingsland
Kingsley
Kingsolver
Kingson
Kingston
Kington
Kingwood
Kini
Kinikini
Kinion
Kiniry
Kinkade
Kinkaid
Kinkead
Kinkel
Kinkelaar
Kinkella
Kinker
Kinkin
Kinkle
Kinlaw
Kinlecheeny
Kinley
Kinlin
Kinloch
Kinlock
Kinman
Kinn
Kinna
Kinnaird
Kinnaman
Kinnamon
Kinnan
Kinnard
Kinnare
Kinne
Kinnear
Kinnebrew
Kinneman
Kinner
Kinnett
Kinney
Kinniburgh
Kinnick
Kinnie
Kinnier
Kinning
Kinningham
Kinnion
Kinnison
Kinnon
Kinnunen
Kinoshita
Kinroth
Kins
Kinsel
Kinsella
Kinser
Kinseth
Kinsey
Kinsinger
Kinsky
Kinsland
Kinsler
Kinsley
Kinslow
Kinsman
Kinsolving
Kinson
Kinstle
Kinstler
Kint
Kinter
Kintigh
Kintner
Kinton
Kintop
Kintopp
Kintsel
Kintz
Kintzel
Kintzer
Kinville
Kinyon
Kinzel
Kinzer
Kinzie
Kinzig
Kinzinger
Kinzle
Kio
Kious
Kip
Kiper
Kipfer
Kiphart
Kipka
Kipling
Kipp
Kippel
Kipper
Kippes
Kipping
Kipple
Kippley
Kipps
Kiracofe
Kirakosyan
Kiral
Kiraly
Kirberger
Kirbie
Kirbo
Kirby
Kirch
Kirchausen
Kirchbaum
Kirchberg
Kirchen
Kircher
Kirchgesler
Kirchgessner
Kirchherr
Kirchhofer
Kirchhoff
Kirchman
Kirchmann
Kirchmeier
Kirchner
Kirchoff
Kirckof
Kirgan
Kiritsy
Kirk
Kirkbride
Kirkby
Kirkconnell
Kirkeby
Kirkegaard
Kirkendall
Kirkendoll
Kirker
Kirkey
Kirkham
Kirkhart
Kirkland
Kirklen
Kirkley
Kirklin
Kirkling
Kirkman
Kirkner
Kirkness
Kirkpatric
Kirkpatrick
Kirks
Kirksey
Kirkwood
Kirley
Kirlin
Kirmer
Kirn
Kirner
Kirnon
Kirouac
Kirovac
Kirsch
Kirschbaum
Kirschenbaum
Kirschenman
Kirschenmann
Kirschke
Kirschman
Kirschner
Kirscht
Kirsh
Kirshman
Kirshner
Kirson
Kirsopp
Kirst
Kirstein
Kirsten
Kirt
Kirtdoll
Kirtland
Kirtley
Kirtner
Kirton
Kirts
Kirven
Kirvin
Kirwan
Kirwin
Kiryakoza
Kirylo
Kisak
Kisamore
Kisch
Kise
Kiser
Kish
Kishaba
Kishbaugh
Kishel
Kishi
Kishimoto
Kisicki
Kisiel
Kisielewski
Kisinger
Kisker
Kisler
Kisling
Kisner
Kisor
Kisro
Kiss
Kissack
Kissam
Kissane
Kissee
Kissel
Kisselburg
Kissell
Kisser
Kissi
Kissick
Kissik
Kissinger
Kissler
Kissling
Kissner
Kist
Kistenmacher
Kister
Kistle
Kistler
Kistner
Kisto
Kiszka
Kita
Kitagawa
Kitamura
Kitanik
Kitch
Kitchel
Kitchell
Kitchen
Kitchenman
Kitchens
Kitcher
Kitchin
Kitching
Kite
Kitelinger
Kithcart
Kitka
Kitner
Kitsmiller
Kitson
Kitt
Kittel
Kittelberger
Kittell
Kittelman
Kittelson
Kitten
Kitterman
Kitthikoune
Kittinger
Kittle
Kittler
Kittles
Kittleson
Kittner
Kitto
Kittredge
Kittrell
Kitts
Kitty
Kitz
Kitzerow
Kitzman
Kitzmiller
Kitzrow
Kivel
Kivela
Kivett
Kivi
Kivioja
Kivisto
Kiyabu
Kiyuna
Kizer
Kizewski
Kizior
Kizzee
Kizzia
Kizziar
Kizzie
Kjar
Kjeldgaard
Kjelland
Kjellberg
Kjellman
Kjellsen
Kjergaard
Kjetland
Kjolseth
Kjos
Klaameyer
Klaas
Klaass
Klaassen
Klabunde
Klacic
Klaers
Klafehn
Klaft
Klages
Klahn
Klahr
Klaiber
Klaich
Klaja
Klakowicz
Klaman
Klamert
Klamet
Klamm
Klammer
Klamn
Klan
Klancnik
Klande
Klang
Klann
Klapec
Klaphake
Klapp
Klapper
Klapperich
Klappholz
Klar
Klarberg
Klare
Klaren
Klarich
Klarin
Klarman
Klarr
Klas
Klase
Klasen
Klasing
Klasinski
Klass
Klassen
Klatt
Klatte
Klauer
Klaus
Klauser
Klausner
Klave
Klaver
Klavetter
Klavon
Klavuhn
Klawinski
Klawiter
Klawitter
Klawuhn
Klay
Klayman
Klear
Kleban
Klebanoff
Klebanow
Klebe
Kleber
Klebes
Klecha
Kleck
Klecker
Kleckley
Kleckner
Klee
Kleeb
Kleefisch
Kleekamp
Kleeman
Kleen
Klees
Kleese
Kleespies
Kleffman
Kleffner
Kleftogiannis
Klegin
Klehn
Klei
Kleiber
Kleiboeker
Kleid
Kleidon
Kleier
Kleifgen
Kleiman
Kleimola
Klein
Kleinberg
Kleinberger
Kleindienst
Kleine
Kleiner
Kleinert
Kleinfeld
Kleinfelder
Kleinhans
Kleinhenz
Kleinke
Kleinknecht
Kleinkopf
Kleinman
Kleinmann
Kleinpeter
Kleinsasser
Kleinschmidt
Kleinsmith
Kleinsorge
Kleintop
Kleinwolterin
Kleis
Kleist
Klem
Kleman
Klemanski
Klemash
Klemen
Klemenc
Klemencic
Klemens
Klement
Klemetson
Klemisch
Klemish
Klemke
Klemm
Klemme
Klemp
Klempa
Klena
Klenk
Klenke
Klenovich
Klepac
Klepacki
Klepacz
Kleparek
Klepchick
Klepfer
Kleppe
Kleppen
Klepper
Kleppinger
Kless
Kletschka
Klett
Klette
Kleve
Kleven
Klevene
Klever
Klevjer
Kley
Kleyman
Kleypas
Klez
Klice
Klich
Klick
Klicka
Klicker
Klickman
Kliebert
Kliem
Klien
Klier
Kliethermes
Kliever
Kliewer
Kliger
Klima
Klimas
Klimaszewski
Klimavicius
Klimczyk
Klimek
Kliment
Klimes
Klimesh
Klimko
Klimkowicz
Klimo
Klinck
Klindt
Kline
Klinedinst
Klinefelter
Klinekole
Klines
Klinetob
Kling
Klingaman
Klingbeil
Klingberg
Klinge
Klingel
Klingelhoefer
Klingelhoets
Klingen
Klingenberg
Klingenberger
Klingensmith
Klinger
Klingerman
Klingler
Klinglesmith
Klingman
Klingner
Klingshirn
Klinich
Klink
Klinkenberg
Klinker
Klinkhammer
Klinko
Klinner
Klinnert
Klinski
Klint
Klintworth
Klipfel
Klipp
Klippel
Klis
Klish
Kliskey
Klitsch
Klitz
Klitzing
Klitzner
Kljucaric
Kloberdanz
Klobucar
Kloc
Klocek
Klock
Klockars
Klocke
Kloeck
Kloefkorn
Kloeker
Kloeppel
Kloepper
Kloer
Klohe
Klohr
Klohs
Kloiber
Kloke
Klomp
Klonoski
Klonowski
Kloock
Kloos
Klopf
Klopfenstein
Klopfer
Klopp
Kloppenburg
Klos
Klose
Klosinski
Kloska
Klosky
Klosner
Klosowski
Kloss
Klossner
Kloster
Klosterman
Klostermann
Kloth
Klotz
Klotzbach
Klouda
Kluber
Kluck
Kludt
Kluemper
Kluender
Kluesner
Kluever
Klug
Kluge
Klugh
Klugman
Kluka
Klukan
Klukas
Klukken
Klump
Klumph
Klumpp
Klun
Klund
Klunder
Klunk
Klus
Kluse
Klusman
Klusmeyer
Kluss
Klussmann
Klute
Kluth
Klutts
Kluttz
Klutz
Kluver
Kluz
Klyce
Klym
Klyn
Kman
Kmatz
Kment
Kmet
Kmetz
Kmiec
Kmiecik
Kmiotek
Knaack
Knaak
Knab
Knabb
Knabe
Knabjian
Knable
Knack
Knackstedt
Knaebel
Knaff
Knaggs
Knake
Knall
Knap
Knapchuck
Knape
Knaphus
Knapick
Knapik
Knapke
Knapko
Knapp
Knappe
Knappenberger
Knapper
Knappert
Knarr
Knatt
Knaub
Knauer
Knauf
Knauff
Knaus
Knauss
Knaust
Knavel
Knazs
Knebel
Knecht
Knedler
Knee
Kneedler
Kneefe
Kneeland
Kneeskern
Knehans
Kneifel
Kneifl
Kneip
Kneisel
Kneisler
Kneisley
Knell
Kneller
Knellinger
Knepel
Knepp
Knepper
Knepshield
Knerien
Knerr
Knesek
Knesel
Kneser
Knestrick
Knetsch
Kneuper
Knewtson
Knezevic
Knezevich
Knezovich
Kniceley
Knicely
Knick
Knickelbein
Knickerbocker
Knickman
Knickrehm
Knie
Kniefel
Knieper
Knier
Knieriem
Knierim
Knies
Kniesel
Kniess
Knife
Kniffen
Kniffin
Knigge
Knight
Knighten
Knighter
Knightly
Knighton
Knights
Knightstep
Knilands
Knill
Kniola
Knipe
Knipfel
Kniphfer
Knipp
Knippel
Knippenberg
Knipper
Knippers
Knipping
Knipple
Knisely
Knisley
Knispel
Kniss
Knittel
Knittle
Knizley
Knknown
Knobbe
Knobel
Knoblauch
Knoble
Knobler
Knobloch
Knoblock
Knoch
Knoche
Knochel
Knock
Knockaert
Knocke
Knodel
Knoebel
Knoechel
Knoedler
Knoell
Knoepfler
Knoepke
Knoeppel
Knoerzer
Knoff
Knoflicek
Knoke
Knole
Knoles
Knoll
Knollenberg
Knollman
Knolton
Knoop
Knop
Knopf
Knopinski
Knopp
Knore
Knori
Knorp
Knorr
Knost
Knotek
Knoten
Knoth
Knotowicz
Knott
Knotts
Knouff
Knous
Knouse
Knowell
Knower
Knowiton
Knowles
Knowling
Knowlton
Knows
Knox
Knoy
Knuckles
Knudsen
Knudson
Knudsuig
Knudsvig
Knudtson
Knueppel
Knupke
Knupp
Knust
Knuteson
Knuth
Knutsen
Knutson
Knutt
Knutzen
Knyzewski
Ko
Koba
Koback
Kobak
Kobara
Kobashigawa
Kobayashi
Kobbe
Kobel
Kober
Koberg
Kobernick
Kobialka
Kobie
Kobis
Koble
Kobler
Koblick
Kobold
Kobrin
Kobryn
Kobs
Kobus
Kobylarczyk
Kobylarz
Kobylinski
Kobylski
Kobza
Koc
Kocab
Kocaj
Koch
Kochan
Kochanek
Kochanski
Kochel
Kochen
Kocher
Kochert
Kochevar
Kochheiser
Kochis
Kochkodin
Kochler
Kochmanski
Koci
Kocian
Kocieda
Kocik
Kociolek
Kock
Kocka
Kockler
Kocon
Kocourek
Kocsis
Kocur
Kocurek
Koczela
Koczera
Koczur
Koczwara
Koda
Kodadek
Kodama
Kodani
Kodera
Kodish
Kody
Koe
Koebel
Koebley
Koeck
Koegel
Koegler
Koehl
Koehler
Koehly
Koehn
Koehne
Koehnen
Koehring
Koeing
Koelbel
Koelewyn
Koelle
Koeller
Koelling
Koellmann
Koellner
Koelsch
Koelzer
Koen
Koenecke
Koeneman
Koenemund
Koenen
Koener
Koenig
Koenigs
Koenigsberg
Koenigsfeld
Koenigsman
Koenigstein
Koening
Koeninger
Koenitzer
Koenning
Koep
Koepf
Koepke
Koepnick
Koepp
Koeppe
Koeppel
Koeppen
Koepper
Koeppl
Koepsel
Koepsell
Koerber
Koerner
Koerper
Koers
Koerwitz
Koes
Koester
Koestler
Koestner
Koetje
Koets
Koetter
Koetting
Koetz
Koewler
Kofa
Kofahl
Koff
Koffler
Koffman
Kofford
Kofler
Kofman
Kofoed
Kofoid
Kofoot
Kofron
Kofutua
Koga
Kogan
Kogel
Kogen
Koger
Kogler
Koguchi
Kogut
Koh
Kohan
Kohara
Kohatsu
Kohel
Kohen
Kohl
Kohler
Kohles
Kohlhepp
Kohlhoff
Kohli
Kohlman
Kohlmeier
Kohlmeyer
Kohlmyer
Kohls
Kohm
Kohn
Kohnen
Kohner
Kohnert
Kohnke
Kohnz
Kohout
Kohr
Kohrman
Kohrs
Kohrt
Kohs
Kohus
Kohut
Koiner
Koinzan
Koistinen
Koitzsch
Koizumi
Kojima
Kok
Kokaly
Kokenge
Kokesh
Kokko
Koko
Kokocinski
Kokoska
Kokoszka
Kokubun
Kol
Kolacki
Kolaga
Kolakowski
Kolander
Kolar
Kolarik
Kolasa
Kolash
Kolasinski
Kolassa
Kolat
Kolata
Kolb
Kolbe
Kolbeck
Kolber
Kolberg
Kolbo
Kolbusz
Kolby
Kolda
Kolden
Kolding
Kole
Kolehmainen
Kolek
Kolen
Kolenda
Koles
Kolesar
Kolesnik
Kolias
Kolic
Kolich
Kolikas
Kolin
Kolinski
Kolinsky
Kolis
Kolk
Kolkemeyer
Kolker
Kolkhorst
Kolkman
Kolkmann
Kolkowski
Koll
Kollar
Kollasch
Kolle
Kollen
Koller
Kolling
Kollman
Kollmeyer
Kollmorgen
Kollos
Kollross
Kolm
Kolman
Kolmer
Kolmetz
Kolnik
Kolo
Koloc
Kolodziej
Kolodzieski
Kolodzik
Kology
Kolopajlo
Koloski
Kolosky
Kolp
Kolppa
Kolsrud
Kolstad
Kolter
Kolthoff
Kolts
Koltz
Kolupke
Kolwyck
Koma
Komada
Koman
Komar
Komara
Komarek
Komatsu
Komatz
Kombe
Komer
Kominek
Kominski
Komis
Komlos
Komm
Kommer
Komo
Komorowski
Komosinski
Komp
Komsthoeft
Komula
Kon
Konakowitz
Konarik
Konarski
Konat
Koncan
Konczak
Konczewski
Kondel
Konderla
Kondo
Kondos
Kondracki
Kondratowicz
Kone
Konecni
Konecny
Konefal
Konek
Konen
Konetchy
Koneval
Kong
Konger
Konicek
Konick
Konicki
Konieczka
Konieczko
Konieczny
Konig
Konigsberg
Konik
Koning
Konishi
Konkel
Konkle
Konkol
Konma
Konn
Konno
Kono
Konon
Konopacki
Konopacky
Konopka
Konopnicki
Konopski
Konow
Konowal
Konrad
Konruff
Konstantinidi
Kontogianis
Kontogiannis
Kontos
Konty
Konwinski
Konye
Konyn
Konz
Konzal
Konzen
Koo
Koob
Kooch
Koogle
Koogler
Kooistra
Kook
Kooken
Kooker
Kool
Koolman
Koon
Koonce
Koone
Koong
Koons
Koontz
Koonz
Koop
Koopman
Koopmann
Koopmans
Koor
Koors
Koos
Kooser
Koosman
Kooy
Kooyman
Kopacz
Kopald
Kopan
Kopas
Kopatz
Kopay
Kopchick
Kopczyk
Kopczynski
Kopec
Kopecky
Kopel
Kopelman
Koper
Kopera
Koperski
Kopet
Kopf
Kopfer
Kopiak
Kopiasz
Kopicko
Kopin
Kopinski
Kopis
Kopischke
Kopka
Kopke
Kopko
Koplin
Kopp
Koppa
Koppang
Koppel
Koppelman
Koppelmann
Koppen
Koppenhaver
Kopper
Kopperman
Kopperud
Koppes
Koppinger
Kopple
Kopplin
Kopps
Koppy
Kopriva
Koprowski
Kops
Kopsho
Kor
Korab
Koral
Koralewski
Koran
Korando
Korb
Korba
Korbal
Korbar
Korbel
Korber
Korbin
Korby
Korchnak
Korczynski
Kordas
Kordiak
Kordish
Kordowski
Kordsmeier
Kordus
Kordys
Koren
Korenek
Korenic
Kores
Koretsky
Korewdit
Korey
Korf
Korff
Korfhage
Korgie
Korhonen
Koria
Korineck
Korinek
Korinta
Koritko
Korkmas
Korman
Kormann
Kormos
Korn
Kornbau
Kornblatt
Kornblum
Kornbluth
Kornegay
Korner
Kornfeld
Kornfield
Kornhauser
Kornman
Kornn
Kornprobst
Kornreich
Kornrumpf
Korns
Koroch
Korol
Koroma
Korona
Korpal
Korpela
Korpi
Korsak
Korsen
Korshak
Korslund
Korsmeyer
Korst
Kort
Korte
Kortemeier
Kortge
Korth
Korthauer
Kortkamp
Kortright
Kortum
Kortz
Korus
Korvin
Korwatch
Korwin
Kory
Korynta
Korzenski
Korzep
Korzybski
Korzyniowski
Kos
Kosa
Kosack
Kosak
Kosakowski
Kosanke
Kosanovic
Kosar
Kosareff
Kosbab
Kosch
Koschnitzki
Koscho
Koscielak
Koscielniak
Koscinski
Kosco
Kosek
Kosel
Kosen
Koser
Kosh
Koshar
Koshi
Koshiol
Koshy
Kosiba
Kosicki
Kosier
Kosik
Kosin
Kosinar
Kosinski
Kosiorek
Kosir
Kositzke
Koska
Koskela
Koski
Koskie
Koskinen
Kosky
Koslan
Kosloski
Koslosky
Koslow
Koslowski
Kosmala
Kosman
Kosmatka
Kosmicki
Kosmowski
Koso
Kosoff
Kosofsky
Kosorog
Kososky
Kosowski
Koss
Kossack
Kossak
Kossakowski
Kosse
Kossen
Kossey
Kossin
Kossman
Kossmann
Kossow
Kost
Kostal
Kostecki
Kostek
Kostel
Kostelecky
Kostelnick
Kostelnik
Kosten
Kostenko
Koster
Kosters
Kostic
Kostich
Kostick
Kostis
Kostiuk
Kostiv
Kostka
Kostohryz
Kostrzewa
Kostura
Kosty
Kostyk
Kostyla
Kosuta
Koszyk
Kot
Kotaki
Kotara
Kotarski
Kotas
Kotch
Kotcher
Kotecki
Kotek
Koteles
Kotera
Koteras
Koterba
Kotey
Koth
Kothakota
Kothari
Kothe
Kotheimer
Kothenbeutel
Kotlar
Kotler
Kotlowski
Kotnik
Kotonski
Kotow
Kotowski
Kotrba
Kotrys
Kotschevar
Kotson
Kott
Kotte
Kottenstette
Kotter
Kotterna
Kottke
Kottler
Kottlowski
Kottman
Kottraba
Kottre
Kotts
Kottsick
Kottwitz
Kotula
Kotur
Kotyk
Kotz
Kotzen
Kotzur
Kou
Koualeski
Kouba
Koudelka
Kough
Koulabout
Koulalis
Koulavongsa
Kounce
Kounick
Kounkel
Kounlavong
Kounovsky
Kouns
Kounter
Kounthapanya
Kounthong
Kountz
Kouri
Kourkoumellis
Kourt
Koury
Kousonsavath
Koussa
Koutras
Koutz
Kouyate
Kovac
Kovacevic
Kovach
Kovacic
Kovacich
Kovacik
Kovack
Kovacs
Koval
Kovalaske
Kovalcheck
Kovalchik
Kovalcik
Kovalcin
Kovaleski
Kovalik
Kovalovsky
Kovalsky
Kovar
Kovarik
Kovarovic
Kovatch
Kovats
Kover
Koverman
Koves
Kovich
Kowal
Kowalchick
Kowalchuk
Kowalcyk
Kowalczyk
Kowald
Kowalec
Kowaleski
Kowalewski
Kowalik
Kowalke
Kowalkowski
Kowall
Kowallis
Kowalowski
Kowalske
Kowalski
Kowalsky
Kowing
Kowis
Kowitz
Kown
Kownacki
Koy
Koyama
Koyanagi
Koza
Kozak
Kozakiewicz
Kozan
Kozar
Kozatek
Kozee
Kozel
Kozeliski
Kozera
Kozeyah
Koziak
Kozicki
Koziel
Kozielski
Kozik
Kozikowski
Kozinski
Koziol
Kozisek
Kozlak
Kozlik
Kozloff
Kozloski
Kozlovsky
Kozlow
Kozlowski
Kozma
Kozola
Kozub
Kozubal
Kozuch
Kozusko
Kozyra
Kraack
Kraasch
Kraatz
Krabbe
Krabbenhoft
Krabel
Krabill
Krach
Kracht
Krack
Kracke
Kracker
Kradel
Kraebel
Kraeger
Kraemer
Kraetsch
Krafft
Kraft
Krag
Krage
Krager
Kragh
Kragt
Krah
Kraham
Krahe
Krahenbuhl
Krahn
Krahulec
Kraichely
Kraig
Krail
Krain
Krainbucher
Krajcer
Krajcik
Krajewski
Krajnik
Krajnovich
Krakauer
Krake
Kraker
Krakowiak
Krakowski
Krakowsky
Kral
Kralicek
Kralik
Kraling
Krall
Krallis
Krallman
Kram
Kramarczyk
Kramb
Kramer
Kramm
Krammer
Krammes
Kramp
Krampe
Kramper
Krampitz
Kranawetter
Krance
Krane
Kranendonk
Kraner
Kranich
Kranock
Krans
Krantz
Kranwinkle
Kranz
Kranze
Kranzler
Krapf
Krapfl
Krapp
Kras
Krase
Krasinski
Kraska
Kraskouskas
Krasley
Krasnansky
Krasnecky
Krasner
Krasnici
Krasnow
Krason
Krasovec
Krass
Krassow
Kraszewski
Kratchman
Kratky
Kratochvil
Kratochwil
Kratofil
Kratowicz
Kratt
Kratz
Kratzer
Kratzke
Krauel
Kraus
Krause
Krauser
Kraushaar
Krauskopf
Krausmann
Krauss
Krausse
Krausz
Kraut
Krauth
Kravec
Kravets
Kravetsky
Kravetz
Kravitz
Kravs
Krawchuk
Krawczyk
Krawetz
Krawiec
Krawiecz
Krawitz
Kray
Kraynak
Kreager
Kreamalmeyer
Kreamer
Kreatsoulas
Kreb
Krebbs
Krebel
Krebs
Krebsbach
Krech
Kreck
Kreeger
Kreese
Krefft
Kreft
Kreger
Kregger
Kreh
Krehbiel
Krehel
Kreidel
Kreider
Kreidler
Kreig
Kreiger
Kreighbaum
Kreiman
Kreimer
Krein
Kreinbring
Kreiner
Kreines
Kreinhagen
Kreis
Kreisberg
Kreischer
Kreisel
Kreiser
Kreisher
Kreisler
Kreisman
Kreiss
Kreissler
Kreiter
Kreitler
Kreitlow
Kreitner
Kreitz
Kreitzbender
Kreitzer
Krejci
Krejcik
Krejsa
Kreke
Krell
Kremen
Kremer
Kremers
Kremmel
Kremple
Krenek
Krenik
Krenke
Krenn
Krenning
Krentz
Krenz
Krenzer
Krenzke
Krepp
Krepps
Kreps
Kresal
Kresge
Kresha
Kresky
Kress
Kresse
Kressierer
Kressin
Kressler
Kretchmar
Kretlow
Kretschman
Kretschmann
Kretschmer
Kretsinger
Kretz
Kretzer
Kretzinger
Kretzschmar
Kreul
Kreusch
Kreuter
Kreutzbender
Kreutzer
Kreuzer
Kreuziger
Krewer
Krewson
Krey
Kribbs
Kribs
Krichbaum
Krick
Kridel
Krider
Kridler
Kriebel
Krieg
Kriege
Kriegel
Krieger
Kriegh
Kriegshauser
Kriek
Kriener
Krienke
Krier
Kriese
Kriesel
Krieser
Kriete
Krigbaum
Kriger
Krigger
Krikorian
Krill
Krimple
Kriner
Kring
Kringas
Kringel
Krings
Krinke
Krinov
Krinsky
Krips
Krise
Kriser
Krisher
Krishman
Krishna
Krishnamurthy
Krishnan
Krishun
Kriske
Kriskovich
Krisman
Kriss
Krissie
Krist
Kristan
Kristek
Kristen
Kristensen
Kristiansen
Kristianson
Kristin
Kristof
Kristoff
Kristofferson
Kriston
Kristy
Krites
Kriticos
Kritikos
Kritter
Kritz
Kritzer
Krivak
Krivanec
Krivanek
Kriz
Krizan
Krizek
Krnach
Krob
Krobath
Kroc
Krochmal
Krock
Kroeger
Kroeker
Kroell
Kroells
Kroemer
Kroencke
Kroener
Kroening
Kroenke
Kroes
Kroese
Kroesing
Kroetch
Kroetz
Kroeze
Krofft
Kroft
Krofta
Krog
Kroger
Krogh
Krogman
Krogmann
Krogstad
Kroh
Krohn
Krois
Krok
Krokos
Krokus
Krol
Krolak
Krolczyk
Krolick
Krolikowski
Kroll
Krom
Krome
Kromer
Kromka
Kromm
Krommes
Krompel
Kromrey
Kron
Kronau
Kronberg
Kronberger
Krone
Kronemeyer
Kronenberg
Kroner
Kroninger
Kronk
Kronstedt
Kroon
Kropf
Kropfelder
Kropff
Kropidlowski
Kropp
Kroschel
Kross
Krossen
Krostag
Krotine
Krotz
Krotzer
Krough
Kroupa
Krous
Krouse
Krout
Krovious
Krows
Krstic
Kruchten
Krucke
Kruckeberg
Kruckenberg
Krucker
Kruczek
Krudop
Kruebbe
Kruegel
Krueger
Kruel
Kruer
Krueth
Krug
Kruger
Krugh
Krugman
Kruiboesch
Kruis
Kruizenga
Kruk
Krukiel
Krukowski
Krul
Krulicki
Krulik
Krulish
Krull
Krum
Krumbach
Krumbein
Krumbholz
Krumenauer
Krumholz
Krumins
Kruml
Krumm
Krumme
Krummel
Krumrine
Krumroy
Krumsiek
Krumvieda
Krumwiede
Krupa
Krupansky
Krupiak
Krupicka
Krupinski
Krupinsky
Krupka
Krupke
Krupp
Kruppa
Kruppenbacher
Krupski
Krus
Kruschke
Kruse
Krusemark
Krusen
Krush
Krushansky
Kruskie
Krusor
Kruss
Kruszewski
Krutsch
Krutz
Kruyt
Kruzan
Kruzel
Kruzewski
Kry
Kryder
Krygier
Krylo
Krynicki
Krys
Krysh
Krysiak
Krysinski
Krysl
Kryst
Krystal
Krystek
Krystofiak
Kryston
Kryzak
Krzak
Krzal
Krzan
Krzeczkowski
Krzemien
Krzeminski
Krzesinski
Krzewinski
Krzykowski
Krzyminski
Krzynowek
Krzyston
Krzywicki
Krzyzanowski
Kshywonis
Ksiazek
Kszaszcz
Ku
Kua
Kuakini
Kualii
Kuamoo
Kuan
Kuang
Kuanoni
Kuarez
Kub
Kuba
Kubacki
Kubal
Kubala
Kuban
Kubas
Kubasch
Kubasik
Kubaska
Kubat
Kube
Kubeck
Kubecka
Kubeika
Kubera
Kuberski
Kubert
Kubes
Kubesh
Kubiak
Kubic
Kubica
Kubicek
Kubick
Kubicki
Kubicz
Kubie
Kubik
Kubilus
Kubin
Kubinski
Kubis
Kubish
Kubishta
Kubisiak
Kubiszewski
Kubitz
Kubler
Kubley
Kubly
Kubo
Kubota
Kuboushek
Kubsch
Kubu
Kuc
Kuca
Kucan
Kucek
Kucel
Kucera
Kuch
Kucha
Kuchan
Kuchar
Kucharik
Kucharski
Kuchel
Kuchem
Kuchenbecker
Kuchenmeister
Kuchera
Kuchinski
Kuchle
Kuchler
Kuchta
Kuchto
Kuciemba
Kucinskas
Kucinski
Kuck
Kuckens
Kuczenski
Kuczkowski
Kuczma
Kuczynski
Kudasik
Kudej
Kudelka
Kuder
Kudla
Kudlacik
Kudley
Kudo
Kudrick
Kudrle
Kudrna
Kudro
Kudron
Kudzma
Kue
Kuebler
Kuechle
Kuechler
Kuehl
Kuehler
Kuehn
Kuehne
Kuehnel
Kuehneman
Kuehner
Kuehnert
Kuehnhold
Kuehnle
Kueker
Kuemmerle
Kuen
Kuennen
Kuenstler
Kueny
Kuenzi
Kuepfer
Kuerbitz
Kues
Kuester
Kueter
Kuether
Kufalk
Kufel
Kufeldt
Kuffa
Kuffel
Kufner
Kugel
Kugler
Kuh
Kuhar
Kuharik
Kuhens
Kuhl
Kuhle
Kuhlenschmidt
Kuhlman
Kuhlmann
Kuhlmey
Kuhlo
Kuhls
Kuhn
Kuhne
Kuhnel
Kuhnemund
Kuhnen
Kuhner
Kuhnert
Kuhnke
Kuhnle
Kuhns
Kuhr
Kuhre
Kuhry
Kuhs
Kuhse
Kuhta
Kuhtz
Kuick
Kuilan
Kuiper
Kuipers
Kuitu
Kuiz
Kuizinas
Kuja
Kujak
Kujala
Kujat
Kujath
Kujawa
Kujawski
Kuk
Kuka
Kukahiko
Kukauskas
Kukene
Kuker
Kukielka
Kukla
Kuklenski
Kukler
Kuklinski
Kuklis
Kukowski
Kuks
Kukucka
Kukura
Kula
Kulacz
Kulaga
Kulak
Kulakowski
Kulas
Kulback
Kulbacki
Kulbeth
Kulbida
Kulcona
Kules
Kulesa
Kulesza
Kulhanek
Kulick
Kulig
Kuliga
Kuligowski
Kulik
Kulikowski
Kulinski
Kulis
Kulish
Kulju
Kulka
Kulkarni
Kull
Kulla
Kullas
Kulling
Kullman
Kullmann
Kully
Kulon
Kulow
Kulp
Kulpa
Kulseth
Kulwicki
Kulzer
Kum
Kumalaa
Kuman
Kumar
Kumfer
Kumlander
Kumm
Kummer
Kummerow
Kump
Kumpf
Kumro
Kun
Kuna
Kunau
Kunc
Kunda
Kundanani
Kunde
Kundert
Kundinger
Kundla
Kundrick
Kundtz
Kunert
Kunesh
Kuney
Kung
Kuni
Kunich
Kunicki
Kunimitsu
Kunin
Kuning
Kunis
Kunishige
Kuniyoshi
Kunka
Kunkel
Kunkle
Kunkleman
Kunkler
Kuns
Kunsch
Kunselman
Kunshier
Kunsman
Kunst
Kunstlinger
Kunter
Kuntz
Kuntzman
Kunz
Kunze
Kunzel
Kunzelman
Kunzie
Kunzler
Kunzman
Kuo
Kuokkanen
Kupchinsky
Kupcho
Kupec
Kuper
Kuperman
Kupersmith
Kupetz
Kupfer
Kupferberg
Kupferer
Kupiec
Kupihea
Kupka
Kupper
Kupres
Kuprewicz
Kupstas
Kur
Kura
Kuralt
Kuramoto
Kurant
Kuras
Kurasz
Kurban
Kurcaba
Kurdyla
Kurdziel
Kurek
Kurelko
Kuretich
Kurgan
Kurian
Kuriger
Kurihara
Kurisu
Kuritz
Kurk
Kurka
Kurkeyerian
Kurkjian
Kurkowski
Kurland
Kurnik
Kurns
Kuroda
Kurohara
Kurokawa
Kurowski
Kurpiel
Kurpinski
Kurr
Kurrie
Kurschner
Kurshuk
Kurt
Kurtenbach
Kurter
Kurth
Kurtich
Kurtin
Kurtis
Kurtti
Kurtulus
Kurtyka
Kurtz
Kurtzeborn
Kurtzer
Kurtzman
Kurutz
Kuruvilla
Kury
Kurylo
Kurz
Kurzinski
Kurzyniec
Kus
Kusak
Kusch
Kuschel
Kuse
Kusek
Kusel
Kuser
Kush
Kushaney
Kushi
Kushin
Kushiner
Kushlan
Kushner
Kushnir
Kusiak
Kusick
Kusinski
Kuske
Kusko
Kusky
Kusner
Kusnic
Kuss
Kussel
Kussman
Kussmaul
Kuster
Kusterer
Kustes
Kustra
Kusuma
Kusumoto
Kuszlyk
Kuszynski
Kut
Kuta
Kutch
Kutchar
Kutcher
Kutchera
Kutchie
Kutchin
Kutella
Kuter
Kuthe
Kuti
Kutil
Kutlu
Kutner
Kutsch
Kutscher
Kutt
Kuttler
Kuttner
Kuty
Kutz
Kutzer
Kutzner
Kuwada
Kuwahara
Kuwana
Kuy
Kuykendall
Kuykendoll
Kuyper
Kuypers
Kuza
Kuzara
Kuzel
Kuzemchak
Kuzia
Kuziel
Kuzio
Kuzma
Kuzmanic
Kuzmin
Kuzminski
Kuzmish
Kuzniar
Kuznicki
Kuzyk
Kvam
Kvamme
Kvaternik
Kveen
Kvek
Kveton
Kvilhaug
Kvoeschen
Kvzian
Kwack
Kwak
Kwan
Kwang
Kwapniewski
Kwasnicki
Kwasniewski
Kwasnik
Kwasny
Kwaterski
Kwek
Kwiat
Kwiatkowski
Kwiecien
Kwiecinski
Kwilosz
Kwit
Kwok
Kwon
Kwong
Ky
Kye
Kyer
Kyger
Kyhn
Kyker
Kyle
Kyler
Kyles
Kylish
Kyllonen
Kym
Kynard
Kynaston
Kyner
Kyper
Kypuros
Kysar
Kyser
Kyseth
Kyte
Kytle
Kyung
Kyzar
Kyzer
La
Laa
Laabs
Laack
Laake
Laaker
Laakso
Laasaga
Laatsch
Lab
Laba
Lababit
Labadie
Labady
Laban
Labar
Labarba
Labarbara
Labarbera
Labarge
Labaro
Labarr
Labarre
Labarriere
Labat
Labate
Labatt
Labauve
Labay
Labbadia
Labbe
Labbee
Labbie
Labean
Labeau
Labella
Labelle
Labeots
Laber
Laberge
Laberpool
Labianca
Labier
Labine
Labita
Labitan
Labkovsky
Lablanc
Lablue
Labo
Laboe
Labog
Laboissonnier
Labombar
Labombard
Labonne
Labonte
Labonville
Labor
Laborde
Labore
Laborin
Laborn
Labossiere
Labounta
Labounty
Labove
Labovitch
Laboy
Labrada
Labrador
Labrake
Labranche
Labre
Labrec
Labreche
Labreck
Labrecque
Labree
Labreque
Labrie
Labriola
Labrode
Labrum
Labrune
Labruyere
Labruzzo
Labs
Labuda
Labuff
Lacaille
Lacasa
Lacassagne
Lacasse
Lacatena
Lacau
Lacava
Lacayo
Lacaze
Lace
Lacefield
Lacek
Lacer
Lacerda
Lacerenza
Lacerte
Lacewell
Lacey
Lach
Lachance
Lachapelle
Lachappelle
Lacharite
Lachat
Lachenauer
Lacher
Lachermeier
Lachiatto
Lachino
Lachley
Lachner
Lachney
Lachowicz
Lachowski
Lachowsky
Lachut
Lacina
Lacinski
Lacio
Lack
Lackage
Lackett
Lackey
Lacki
Lackie
Lackland
Lackman
Lackner
Lacko
Lacks
Laclair
Laclaire
Lacock
Lacognata
Lacomb
Lacombe
Laconte
Lacorte
Lacoss
Lacosse
Lacosta
Lacoste
Lacouette
Lacount
Lacour
Lacourse
Lacovara
Lacoy
Lacroix
Lacrone
Lacross
Lacrosse
Lacrue
Lacsamana
Lacson
Lacuesta
Lacusky
Lacy
Lacz
Lada
Ladabouche
Ladage
Ladakakos
Ladas
Laday
Ladd
Ladden
Lade
Ladeau
Ladebauche
Ladell
Lader
Laderer
Laderman
Ladesma
Ladewig
Ladick
Ladieu
Ladika
Laditka
Ladner
Ladnier
Lado
Ladonne
Ladouce
Ladouceur
Ladson
Ladt
Ladtkow
Laduc
Laducer
Ladue
Laduke
Ladwig
Lady
Ladyman
Laeger
Laehn
Laesser
Laessig
Laface
Lafantano
Lafarga
Lafarge
Lafaso
Lafata
Lafauci
Lafave
Lafaver
Lafavor
Lafay
Lafayette
Lafemina
Lafera
Laferney
Laferriere
Laferte
Laferty
Lafever
Lafevers
Lafevre
Laffer
Lafferty
Laffey
Laffin
Laffitte
Laffoon
Laffredo
Lafield
Lafkas
Laflam
Laflame
Laflamme
Lafleche
Laflen
Lafler
Lafleur
Laflin
Laflore
Lafluer
Lafoe
Lafollette
Lafon
Lafond
Lafone
Lafont
Lafontain
Lafontaine
Lafontant
Lafoon
Laforce
Laford
Laforest
Laforey
Laforge
Laforrest
Laforte
Lafortune
Lafosse
Lafountain
Lafountaine
Lafoy
Laframboise
Lafranca
Lafrance
Lafrancois
Lafrate
Lafratta
Lafrazia
Lafreniere
Lafromboise
Lafuente
Lafuze
Lagace
Lagadinos
Lagamba
Lagan
Lagana
Laganga
Lagant
Lagard
Lagarde
Lagares
Lagasca
Lagasse
Lagassie
Lagatella
Lagatta
Lagazo
Lage
Lageman
Lager
Lagerberg
Lagergren
Lagerman
Lagerquist
Lagerstedt
Lagerstrom
Lagesse
Laggan
Lagge
Laginess
Lagle
Laglie
Lagman
Lagnese
Lago
Lagoa
Lagomarsino
Lagoni
Lagonia
Lagoo
Lagore
Lagorio
Lagory
Lagos
Lagraize
Lagrand
Lagrange
Lagrant
Lagrasse
Lagrave
Lagreca
Lagrenade
Lagrimas
Lagrone
Lagroon
Lagrotta
Lagrow
Laguardia
Lague
Laguer
Laguerre
Lagueux
Laguire
Laguna
Lagunas
Lah
Lahaie
Laham
Lahar
Lahay
Lahaye
Laher
Lahey
Lahip
Lahm
Lahman
Lahmann
Lahmers
Lahn
Lahne
Lahr
Lahren
Lahrman
Lahti
Lahtinen
Lahue
Lai
Laib
Laiben
Laible
Laich
Laiche
Laidlaw
Laidler
Laigle
Laigo
Lail
Lain
Laine
Lainez
Laing
Lainhart
Laino
Lainson
Laios
Laipple
Lair
Laird
Lairmore
Lairsey
Lairson
Lairy
Lais
Laisure
Laite
Laitila
Laitinen
Laity
Laizure
Lajara
Lajaunie
Lajeunesse
Lajoie
Lajoy
Lajoye
Lajza
Lakatos
Lake
Lakeman
Laker
Lakes
Lakey
Lakhan
Lakhani
Lakin
Lakins
Lakner
Lakowski
Laky
Lal
Lala
Laland
Lalande
Lalanne
Lalata
Lale
Laliberte
Laliberty
Lalich
Lalim
Lalin
Lalinde
Laliotis
Lalk
Lalka
Lall
Lalla
Lallave
Lallemand
Lalley
Lalli
Lallier
Lallo
Lally
Lalonde
Lalone
Lalor
Lalumiere
Lam
Lama
Lamaack
Lamacchia
Lamadrid
Lamagna
Lamaitre
Laman
Lamana
Lamance
Lamango
Lamanna
Lamantagne
Lamantia
Lamar
Lamarca
Lamarch
Lamarche
Lamark
Lamarque
Lamarr
Lamarra
Lamarre
Lamarsh
Lamarta
Lamartina
Lamas
Lamascolo
Lamaster
Lamastus
Lamattina
Lamax
Lamay
Lamb
Lambdin
Lambe
Lambeck
Lamber
Lambermont
Lamberson
Lambert
Lamberth
Lamberti
Lamberto
Lamberton
Lambertson
Lambertus
Lamberty
Lambes
Lambeth
Lambey
Lambiase
Lambie
Lambing
Lambino
Lambka
Lamblin
Lamborn
Lamborne
Lambourne
Lamboy
Lambrakis
Lambrecht
Lambright
Lambros
Lambrukos
Lambson
Lambuth
Lame
Lameda
Lamela
Lamendola
Lamens
Lamer
Lamere
Lamers
Lamery
Lamey
Lamfers
Lamia
Lamica
Lamie
Lamielle
Laminack
Laming
Lamirand
Lamirande
Lamison
Lamke
Lamkin
Lamkins
Lamm
Lamme
Lammel
Lammers
Lammert
Lammey
Lammi
Lammie
Lammon
Lammy
Lamoine
Lamon
Lamond
Lamonda
Lamonica
Lamons
Lamont
Lamontagna
Lamontagne
Lamonte
Lamoore
Lamora
Lamore
Lamoreau
Lamoreaux
Lamoree
Lamorella
Lamoreux
Lamorgese
Lamorte
Lamos
Lamothe
Lamott
Lamotte
Lamountain
Lamour
Lamoureaux
Lamoureux
Lamp
Lamparski
Lampe
Lampel
Lamper
Lampert
Lampey
Lamphear
Lamphere
Lamphiear
Lamphier
Lampi
Lampiasi
Lampinen
Lamping
Lampitt
Lampke
Lampkin
Lampkins
Lampl
Lampley
Lampman
Lampo
Lamport
Lampp
Lamprecht
Lamprey
Lampron
Lampros
Lampsas
Lampshire
Lampson
Lampton
Lamson
Lamudio
Lamunyon
Lamus
Lamy
Lan
Lana
Lanagan
Lanahan
Lanasa
Lancaster
Lance
Lancey
Lancia
Lanciotti
Lanclos
Lancon
Lancour
Lanctot
Lancz
Land
Landa
Landacre
Landaker
Landan
Landau
Landauer
Landavazo
Landaverde
Landazuri
Landberg
Landborg
Lande
Landefeld
Landen
Landenberger
Lander
Landerman
Landero
Landeros
Landers
Landes
Landesberg
Landess
Landevos
Landey
Landfair
Landford
Landfried
Landgraf
Landgrebe
Landgren
Landham
Landherr
Landi
Landin
Landing
Landingham
Landini
Landis
Landkamer
Landman
Landmann
Landmark
Landmesser
Lando
Landolf
Landolfi
Landolfo
Landolt
Landon
Landoni
Landor
Landowski
Landquist
Landram
Landreneau
Landres
Landress
Landreth
Landreville
Landrey
Landrian
Landrie
Landrigan
Landrith
Landro
Landron
Landrum
Landrus
Landruth
Landry
Lands
Landsaw
Landsberg
Landsberry
Landsman
Landstrom
Landt
Landu
Landucci
Landvatter
Landwehr
Landy
Lane
Laneaux
Lanehart
Lanen
Lanes
Lanese
Laneve
Laney
Lanfair
Lanfear
Lanfor
Lanford
Lanfranco
Lang
Langager
Langan
Langanke
Langarica
Langbehn
Langbein
Langdale
Langdon
Lange
Langefels
Langehennig
Langel
Langeland
Langelier
Langella
Langen
Langenbach
Langendorf
Langeness
Langenfeld
Langenheim
Langer
Langerman
Langeveld
Langevin
Langfeldt
Langfield
Langfitt
Langford
Langgood
Langham
Langhans
Langhart
Langholdt
Langholz
Langhorn
Langhorne
Langhorst
Langhout
Langi
Langill
Langille
Langin
Langkabel
Langlais
Langland
Langlands
Langley
Langlinais
Langlitz
Langlo
Langlois
Langloss
Langmaid
Langman
Langmo
Langmyer
Langner
Langness
Lango
Langolf
Langon
Langone
Langoni
Langowski
Langreck
Langridge
Langrum
Langsam
Langsdale
Langseth
Langshaw
Langstaff
Langston
Langstraat
Langton
Langtry
Languell
Languirand
Langwell
Langwith
Langworthy
Lanham
Lani
Laniado
Lanie
Lanier
Lanigan
Laning
Laninga
Laningham
Lanini
Lanius
Lank
Lanka
Lankard
Lankford
Lankster
Lanman
Lann
Lanna
Lannan
Lannen
Lanners
Lanni
Lannier
Lannigan
Lanning
Lanno
Lannom
Lannon
Lano
Lanoie
Lanois
Lanosa
Lanosga
Lanoue
Lanouette
Lanphear
Lanpher
Lanphere
Lanphier
Lanquist
Lansang
Lansberg
Lansberry
Lansdale
Lansdell
Lansden
Lansdowne
Lanser
Lansey
Lansford
Lansing
Lanski
Lanson
Lant
Lantaff
Lantagne
Lanteigne
Lantelme
Lanter
Lanterman
Lantey
Lantgen
Lanthier
Lantier
Lantieri
Lantigua
Lanting
Lantis
Lanton
Lantrip
Lantry
Lantto
Lantz
Lantzy
Lanum
Lanuza
Lanz
Lanza
Lanzafame
Lanzalotti
Lanzarin
Lanzarotta
Lanze
Lanzer
Lanzetta
Lanzi
Lanzillo
Lanzillotti
Lanzilotta
Lanzo
Lanzoni
Lao
Laorange
Laos
Lapa
Lapadula
Lapage
Lapaglia
Lapalme
Lapan
Lapar
Lapari
Lapatra
Lape
Lapek
Lapenta
Laper
Lapere
Laperle
Laperouse
Laperriere
Laperuta
Lapete
Lapeyrolerie
Lapeyrouse
Lapham
Lapiana
Lapid
Lapidus
Lapier
Lapierre
Lapila
Lapilio
Lapin
Lapine
Lapinski
Lapinsky
Lapinta
Lapitan
Laplaca
Laplace
Laplant
Laplante
Laplaunt
Laplume
Lapoint
Lapointe
Lapolla
Lapora
Lapore
Laport
Laporta
Laporte
Lapp
Lappa
Lappas
Lappe
Lappi
Lappin
Lapping
Lappinga
Lapradd
Laprade
Laprairie
Laprarie
Lapre
Laprete
Laprise
Lapsley
Lapuerta
Lapusnak
Lapuz
Laquay
Laquerre
Lara
Larabee
Larabel
Larabell
Laraby
Laracuente
Laragy
Laraia
Laramee
Laramie
Laramore
Larance
Laranjo
Larason
Larate
Laravie
Laraway
Larbi
Larbie
Larcade
Larch
Larche
Larcher
Larcom
Lard
Larde
Lardieri
Lardin
Lardizabal
Lardner
Lardone
Lardydell
Lare
Lareau
Laredo
Laregina
Laremont
Larence
Lares
Larew
Larey
Larez
Largay
Large
Largen
Largena
Largent
Larger
Largin
Largo
Lariccia
Larick
Larimer
Larimore
Larin
Larios
Lariosa
Laris
Larish
Larison
Larita
Larive
Lariviere
Larizza
Lark
Larkan
Larke
Larkey
Larkin
Larkins
Larko
Larman
Larmer
Larmett
Larmon
Larmore
Larner
Larney
Laro
Larocca
Larocco
Laroche
Larochelle
Larock
Larocque
Laroe
Laroia
Laronda
Laroque
Larosa
Larose
Larotta
Larouche
Larousse
Laroux
Larowe
Larr
Larrabee
Larralde
Larranaga
Larrea
Larreta
Larribeau
Larrick
Larrier
Larrieu
Larrimore
Larrison
Larriuz
Larriva
Larrivee
Larriviere
Larroque
Larrosa
Larrow
Larry
Lars
Larsen
Larsh
Larson
Larsson
Lartey
Lartigue
Larubbio
Larue
Laruffa
Larusch
Larusso
Larve
Lary
Larzazs
Larzelere
Lasage
Lasagna
Lasaint
Lasala
Lasalle
Lasane
Lasanta
Lasasso
Lasater
Lascala
Lascano
Lascaro
Lasch
Laschinger
Lascody
Lascola
Lascurain
Lasecki
Lasell
Laselle
Lasenby
Laser
Laserna
Laseter
Lash
Lashbaugh
Lashbrook
Lasher
Lashier
Lashlee
Lashley
Lashmet
Lashomb
Lashua
Lashure
Lashute
Lashutva
Lashway
Lasik
Lasin
Lasiter
Lask
Laska
Laske
Lasker
Laskey
Laski
Laskin
Lasko
Laskoski
Laskoskie
Laskosky
Laskowitz
Laskowski
Lasky
Lasley
Laslie
Laslo
Laso
Lason
Lasorsa
Lasota
Laspina
Lass
Lassa
Lassalle
Lassan
Lasseigne
Lasselle
Lassen
Lasser
Lassere
Lasserre
Lasseson
Lasseter
Lassetter
Lassiter
Lassley
Lasso
Lassonde
Lasswell
Last
Lastella
Laster
Lastinger
Lastiri
Lastovica
Lastra
Lastrape
Lastrapes
Lastufka
Lasure
Laswell
Lasyone
Laszlo
Lat
Lataille
Latam
Lataquin
Latassa
Latch
Latchaw
Late
Latella
Latendresse
Later
Laterza
Latessa
Latham
Lathan
Lathe
Lathem
Lathen
Lather
Lathern
Lathim
Lathon
Lathrop
Lathrum
Latif
Latigo
Latiker
Latimer
Latimore
Latin
Latina
Latini
Latino
Latiolais
Latko
Latner
Latney
Lato
Laton
Latona
Latorre
Latortue
Latos
Latouche
Latouf
Latour
Latourette
Latourrette
Latronica
Latsha
Latshaw
Latsko
Latson
Latta
Lattanzi
Lattanzio
Lattari
Lattea
Latten
Latterell
Lattig
Lattimer
Lattimore
Lattin
Latting
Lattner
Lattrell
Lattus
Latty
Latu
Latulas
Latulipe
Latulippe
Latunski
Latus
Latz
Latzig
Latzka
Latzke
Lau
Laub
Laubach
Laubacher
Laube
Lauber
Laubersheimer
Laubhan
Laubscher
Lauby
Lauchaire
Lauck
Lauckner
Laud
Laudadio
Laudat
Laudato
Laude
Laudeman
Lauden
Laudenslager
Lauder
Lauderback
Lauderbaugh
Lauderdale
Lauderman
Laudermilk
Laue
Lauenroth
Lauer
Lauerman
Laufenberg
Laufer
Lauffer
Laugen
Laughary
Laughbaum
Laughead
Laughery
Laughinghouse
Laughlin
Laughman
Laughner
Laughon
Laughridge
Laughter
Laughton
Lauigne
Lauinger
Laukitis
Laulu
Laumann
Laumbach
Laumea
Laumeyer
Laun
Launderville
Laundree
Laundry
Launelez
Launer
Launey
Launiere
Launius
Launt
Laur
Laura
Laurance
Laurange
Laureano
Laurel
Laureles
Laurelli
Lauren
Laurence
Laurenceau
Laurendeau
Laurenitis
Laureno
Laurens
Laurent
Laurente
Laurenti
Laurenza
Laurenzano
Lauretta
Laurey
Lauri
Lauria
Lauriano
Lauricella
Laurich
Lauridsen
Laurie
Laurila
Laurimore
Laurin
Laurino
Laurion
Laurita
Laurito
Lauritsen
Lauritzen
Lauro
Laurole
Laursen
Laury
Lauschus
Lausell
Lausen
Lauseng
Lauser
Lausier
Lauster
Laut
Lautaret
Lautenbach
Lautenschlage
Lauter
Lauterbach
Lauterborn
Lauters
Lauth
Lauthern
Lautieri
Lautman
Lautner
Lautt
Lauture
Lautz
Lautzenheiser
Lauver
Lauw
Lauwers
Laux
Lauze
Lauzier
Lauzon
Lav
Lava
Lavadera
Lavadie
Lavagnino
Lavala
Lavalais
Lavalette
Lavalla
Lavalle
Lavallee
Lavalley
Lavallie
Lavan
Lavancha
Lavanchy
Lavander
Lavani
Lavant
Lavanway
Lavatch
Lave
Lavear
Lavecchia
Lavee
Lavelett
Lavell
Lavelle
Lavelli
Laven
Lavender
Lavene
Laventure
Laver
Laverde
Laverdiere
Laverdure
Lavere
Laverette
Lavergne
Lavern
Laverne
Laverriere
Lavertu
Lavertue
Laverty
Lavery
Lavesque
Lavette
Lavey
Lavezzo
Lavgle
Lavi
Laviero
Lavigna
Lavigne
Lavin
Lavina
Lavinder
Lavine
Laviola
Laviolette
Lavis
Lavista
Lavoie
Lavole
Lavon
Lavongsar
Lavorini
Lavoy
Lavy
Lavzon
Law
Lawal
Lawalin
Lawall
Laware
Lawary
Lawbaugh
Lawcewicz
Lawe
Lawer
Lawerance
Lawerence
Lawernce
Lawery
Lawes
Lawford
Lawhead
Lawhon
Lawhorn
Lawhorne
Lawin
Lawing
Lawis
Lawler
Lawless
Lawley
Lawlis
Lawlor
Lawman
Lawn
Lawnicki
Lawrance
Lawrence
Lawrentz
Lawrenz
Lawrey
Lawrie
Lawry
Laws
Lawshe
Lawsky
Lawson
Lawter
Lawther
Lawton
Lawver
Lawwill
Lawyer
Lax
Laxen
Laxson
Laxton
Lay
Laychock
Laycock
Laycox
Layden
Laye
Layel
Layell
Layer
Layfield
Layher
Layhew
Layland
Layman
Laymon
Layne
Layng
Layo
Layous
Layson
Layssard
Layton
Layva
Laza
Lazaga
Lazalde
Lazano
Lazar
Lazarczyk
Lazard
Lazare
Lazares
Lazarine
Lazarini
Lazaro
Lazaroff
Lazarski
Lazarte
Lazarus
Lazarz
Lazcano
Lazenberry
Lazenby
Lazenson
Lazer
Lazewski
Lazich
Lazier
Lazio
Lazo
Lazor
Lazos
Lazott
Lazurek
Lazusky
Lazzar
Lazzara
Lazzari
Lazzaro
Lazzell
Lazzeri
Le
Lea
Leab
Leabow
Leach
Leachman
Leacock
Leadbeater
Leadbetter
Leader
Leadford
Leadingham
Leadley
Leadman
Leady
Leaf
Leafe
Leagjeld
League
Leah
Leahey
Leahman
Leahy
Leaird
Leak
Leake
Leakes
Leaks
Leal
Leaman
Leamer
Leaming
Leamon
Leamy
Lean
Leanard
Leander
Leandro
Leandry
Leanen
Leanos
Leanza
Leap
Leaper
Leaphart
Leapheart
Lear
Leard
Leardi
Learman
Learn
Learned
Leary
Leas
Lease
Leaser
Leash
Leasher
Leask
Leason
Leasor
Leasure
Leasy
Leath
Leatham
Leather
Leatherberry
Leatherman
Leathers
Leatherwood
Leaton
Leavell
Leavelle
Leaven
Leavengood
Leavens
Leavenworth
Leaver
Leaverton
Leavigne
Leavins
Leavitt
Leavy
Leazer
Lebahn
Leban
Lebarge
Lebario
Lebaron
Lebarron
Lebaugh
Lebby
Lebeau
Lebeaux
Lebeck
Lebeda
Lebedeff
Lebel
Leben
Lebeouf
Leber
Leberman
Lebert
Leberte
Lebish
Lebitski
Leblanc
Leblane
Lebleu
Leblond
Lebo
Leboeuf
Lebold
Lebon
Lebouef
Lebouf
Lebourgeois
Lebovic
Lebow
Lebowitz
Lebrane
Lebrecht
Lebrecque
Lebroke
Lebron
Lebrun
Lebsack
Lebsock
Lecain
Lecaros
Lecates
Lecato
Lecea
Lech
Lechel
Lechelt
Lecher
Lechlak
Lechleidner
Lechler
Lechliter
Lechman
Lechner
Lechuga
Leck
Leckband
Leckbee
Leckie
Leckington
Leckman
Lecky
Leclair
Leclaire
Leclare
Leclear
Lecleir
Leclerc
Leclere
Lecocq
Lecompte
Lecomte
Leconey
Leconte
Lecorchick
Lecoultre
Lecount
Lecourt
Lecrone
Lecroy
Lecuyer
Lecy
Lecznar
Led
Ledain
Leday
Ledbetter
Ledden
Leddon
Leddy
Ledebuhr
Ledec
Ledee
Ledenbach
Leder
Lederer
Lederhos
Lederman
Ledermann
Ledesma
Ledet
Ledezma
Ledford
Ledger
Ledgerwood
Ledin
Ledingham
Ledl
Ledley
Ledlie
Ledlow
Ledo
Ledon
Ledonne
Ledoux
Ledsinger
Ledsome
Leduc
Ledue
Leduke
Ledwell
Ledwig
Ledwith
Ledy
Ledyard
Lee
Leeber
Leebrick
Leech
Leed
Leeder
Leedom
Leeds
Leedy
Leef
Leehan
Leehy
Leek
Leeker
Leeks
Leeman
Leemans
Leemaster
Leeming
Leemow
Leen
Leep
Leeper
Leer
Leerar
Lees
Leese
Leesman
Leesmann
Leeson
Leet
Leetch
Leete
Leeth
Leetham
Leever
Leewright
Leezer
Lefave
Lefaver
Lefchik
Lefeber
Lefebre
Lefebure
Lefebvre
Lefeld
Lefever
Lefevers
Lefevre
Lefew
Leff
Leffel
Leffelman
Leffers
Leffert
Leffew
Leffingwell
Leffler
Lefkowitz
Leflar
Lefler
Lefleur
Leflore
Leflores
Lefore
Leforge
Lefort
Lefrancois
Left
Lefthand
Lefton
Leftridge
Leftwich
Lefurgy
Legaard
Legace
Legacy
Legall
Legalley
Legallo
Legan
Legard
Legare
Legarreta
Legaspi
Legassie
Legat
Legate
Legath
Legato
Legault
Lege
Legel
Legendre
Leger
Legere
Legerski
Legette
Legeyt
Legg
Leggans
Leggat
Legge
Legget
Leggett
Leggette
Leggins
Leggio
Leggitt
Leggs
Leghorn
Legier
Legions
Legleiter
Legler
Legleu
Legner
Legnon
Lego
Legoff
Legore
Legorreta
Legoullon
Legra
Legrand
Legrande
Legrant
Legree
Legro
Legrone
Legros
Legrotte
Legrow
Legum
Leh
Lehan
Lehane
Lehar
Lehberger
Lehenbauer
Leheny
Lehew
Lehigh
Lehman
Lehmann
Lehmberg
Lehmer
Lehmkuhl
Lehn
Lehne
Lehneis
Lehnen
Lehner
Lehnert
Lehnertz
Lehnherr
Lehnhoff
Lehning
Lehnortt
Leho
Lehoullier
Lehoux
Lehr
Lehrer
Lehrfeld
Lehrian
Lehrke
Lehrman
Lehtinen
Lehto
Lehtomaki
Lehtonen
Lei
Leialoha
Leib
Leiba
Leibe
Leibee
Leibel
Leibenstein
Leiber
Leibert
Leiberton
Leibfried
Leibman
Leibold
Leibowitz
Leiby
Leich
Leicher
Leichner
Leicht
Leichtenberge
Leichtman
Leichty
Leick
Leid
Leidall
Leidecker
Leidel
Leider
Leidholt
Leidich
Leidig
Leiding
Leidy
Leiendecker
Leier
Leif
Leifer
Leiferman
Leigers
Leigh
Leight
Leighton
Leighty
Leigland
Leija
Leikam
Leiker
Leilich
Leimbach
Leimberger
Leimer
Leimkuehler
Leimkuhler
Lein
Leinbach
Leinberger
Leinen
Leinenbach
Leiner
Leingang
Leinhart
Leininger
Leino
Leinonen
Leins
Leinwand
Leinweber
Leiper
Leipert
Leipheimer
Leipold
Leis
Leisch
Leischner
Leise
Leisenring
Leiser
Leisey
Leisher
Leishman
Leising
Leisinger
Leisner
Leiss
Leist
Leisten
Leister
Leistiko
Leistner
Leisure
Leisy
Leitao
Leitch
Leite
Leitem
Leiter
Leith
Leithauser
Leitheiser
Leithiser
Leithoff
Leitman
Leitner
Leitten
Leitz
Leitze
Leitzel
Leitzinger
Leitzke
Leiva
Leja
Lejenne
Lejeune
Lejman
Lejune
Lek
Lekan
Lekas
Lekberg
Lekey
Leko
Lekwa
Lelacheur
Lelah
Leland
Lele
Leleux
Lelis
Lella
Lelle
Lelli
Lellig
Lelonek
Lem
Lema
Lemaire
Lemaitre
Leman
Lemans
Lemanski
Lemansky
Lemar
Lemarie
Lemarr
Lemaster
Lemasters
Lemay
Lembcke
Lembke
Lembo
Lembrick
Lemcke
Lemear
Lemelin
Lemelle
Lemen
Lemere
Lemert
Lemery
Lemich
Lemick
Lemieux
Lemin
Leming
Lemings
Lemire
Lemish
Lemkau
Lemke
Lemle
Lemler
Lemley
Lemm
Lemma
Lemme
Lemmen
Lemmer
Lemmert
Lemming
Lemmings
Lemmo
Lemmon
Lemmond
Lemmonds
Lemmons
Lemoine
Lemon
Lemond
Lemonds
Lemone
Lemonier
Lemons
Lemont
Lemos
Lemoyne
Lemp
Lempe
Lempicki
Lempka
Lempke
Lemucchi
Lemus
Len
Lena
Lenahan
Lenard
Lenart
Lenarz
Lenberg
Lench
Lenci
Lencioni
Lenczyk
Lenderman
Lendo
Lendon
Lendor
Lendrum
Lendt
Lene
Leneau
Leneave
Lenehan
Lener
Leners
Lenertz
Lenfest
Leng
Lengacher
Lengel
Lenger
Lengerich
Lengle
Lengyel
Lenhard
Lenhardt
Lenharr
Lenhart
Lenherr
Lenhoff
Lenig
Lenigan
Lenihan
Lening
Lenior
Lenis
Lenius
Lenix
Lenk
Lenke
Lenker
Lenkiewicz
Lenling
Lenn
Lennan
Lennard
Lennart
Lennert
Lennertz
Lennihan
Lenning
Lennington
Lennis
Lennon
Lennox
Lenny
Leno
Lenoch
Lenoci
Lenoir
Lenon
Lenord
Lenort
Lenorud
Lenoue
Lenox
Lenser
Lensing
Lenske
Lenski
Lent
Lente
Lenters
Lentine
Lentini
Lento
Lenton
Lents
Lentsch
Lentz
Leny
Lenyard
Lenz
Lenza
Lenze
Lenzen
Lenzi
Lenzini
Lenzo
Leo
Leofsky
Leomiti
Leon
Leona
Leonaggeo
Leonard
Leonardi
Leonardis
Leonardo
Leonberger
Leone
Leonelli
Leonello
Leones
Leonesio
Leonette
Leonetti
Leong
Leonhard
Leonhardt
Leonhart
Leoni
Leonick
Leonides
Leonor
Leonpacher
Leonti
Leopard
Leopardi
Leopold
Leopoldo
Leos
Leota
Lepage
Lepak
Lepard
Lepe
Lepera
Lepere
Lepetich
Lepez
Lepine
Lepinski
Lepisto
Lepke
Lepkowski
Lepley
Lepo
Lepore
Lepp
Leppanen
Lepper
Leppert
Lepping
Leppink
Leppke
Leppla
Lepre
Lepretre
Lepri
Leps
Lequire
Leray
Lerch
Lerer
Lerew
Leri
Leriche
Lerma
Lerman
Lermon
Lermond
Lerner
Lerno
Lero
Leroux
Lerow
Leroy
Lerper
Lerra
Lertora
Lerud
Lerwick
Lerwill
Lesa
Lesage
Lesane
Lescano
Lescarbeau
Lescavage
Lesch
Lesches
Lesco
Lese
Leser
Lesesne
Lesh
Leshem
Lesher
Leshinsky
Leshko
Leshure
Lesiak
Lesieur
Lesinski
Leske
Leski
Lesko
Leskovac
Leskovar
Leskovec
Lesky
Lesley
Leslie
Lesly
Lesmeister
Lesmerises
Lesneski
Lesney
Lesniak
Lesnick
Lesniewski
Leso
Lespedes
Lesperance
Lespier
Less
Lessa
Lessard
Lessen
Lessenberry
Lesser
Lessey
Lessig
Lessin
Lessley
Lesslie
Lessly
Lessman
Lessmann
Lessner
Lesso
Lessor
Lestage
Lestelle
Lester
Leston
Lestor
Lestourgeon
Lestrange
Lestronge
Lesuer
Lesueur
Lesure
Leszczynski
Leta
Letalien
Letang
Letarte
Letbetter
Letchaw
Letcher
Letchworth
Letellier
Letender
Letendre
Letersky
Leth
Lethco
Letizia
Letko
Letlow
Letman
Leto
Letofsky
Letourneau
Letourneaux
Letran
Letrent
Letsche
Letscher
Letsinger
Letson
Lett
Letteer
Letteney
Letterlough
Letterman
Letters
Lettiere
Lettieri
Lettinga
Lettman
Lettre
Letts
Lettsome
Letze
Leu
Leuasseur
Leubner
Leuchs
Leuck
Leuckel
Leuenberger
Leuenthal
Leuga
Leuhring
Leukhardt
Leukuma
Leung
Leupold
Leusink
Leuters
Leuthauser
Leuthe
Leuthold
Leutwiler
Leuty
Leuy
Leuze
Lev
Leva
Leval
Levalley
Levan
Levander
Levandofsky
Levandoski
Levandowski
Levanger
Levangie
Levans
Levar
Levario
Levasseur
Levatino
Levay
Leve
Levecke
Levee
Leveille
Leveillee
Level
Levell
Levels
Leven
Levendoski
Levendosky
Levene
Levengood
Levenhagen
Levens
Levenson
Levenstein
Leventer
Leventhal
Leveque
Lever
Leverance
Levere
Leverentz
Leverenz
Leverett
Leverette
Leverich
Levering
Leverone
Levers
Leversee
Leverson
Levert
Leverton
Levesgue
Levesque
Leveston
Leveto
Levett
Levey
Levi
Levian
Levick
Levie
Levielle
Levien
Levier
Levin
Levine
Leviner
Levings
Levingston
Levins
Levinsky
Levinson
Levinthal
Levis
Levison
Levister
Leviston
Levitan
Levitas
Levitch
Levites
Levitin
Leviton
Levitre
Levitsky
Levitt
Levitz
Levo
Levoci
Levoy
Levra
Levreau
Levreault
Levron
Levy
Lew
Lewallen
Lewan
Lewand
Lewandoski
Lewandowski
Lewandowsky
Lewark
Lewars
Lewczyk
Lewellen
Lewelling
Lewellyn
Lewerke
Lewey
Lewi
Lewicki
Lewin
Lewinski
Lewis
Lewison
Lewitt
Lewman
Lewry
Lewter
Lewton
Lewy
Lex
Lexer
Ley
Leya
Leyba
Leyda
Leydecker
Leyden
Leyendecker
Leyh
Leyland
Leymeister
Leynes
Leyra
Leyrer
Leys
Leysath
Leyson
Leyton
Leyua
Leyva
Leyvas
Leza
Lezak
Lezama
Lezcano
Lezer
Lezo
Lezon
Lheureux
Lhommedieu
Lhuillier
Li
Lia
Liakos
Lian
Lianes
Liang
Liano
Liao
Liapis
Lias
Liaw
Libbee
Libberton
Libbey
Libby
Libel
Libengood
Libera
Liberati
Liberato
Liberatore
Liberman
Libert
Liberti
Libertini
Liberto
Liberty
Libke
Libman
Liborio
Libra
Librandi
Libre
Librizzi
Liburd
Libutti
Licalzi
Licano
Licari
Licata
Licause
Licausi
Licavoli
Licciardi
Liccione
Liccketto
Licea
Liceaga
Licerio
Lich
Lichak
Lichenstein
Lichliter
Lichlyter
Lichorat
Lichota
Lichstein
Licht
Lichte
Lichtenberg
Lichtenberger
Lichtenfeld
Lichtenstein
Lichtenwalner
Lichtenwalter
Lichter
Lichtig
Lichtman
Lichty
Lick
Lickert
Lickey
Lickfelt
Lickiss
Lickley
Licklider
Lickliter
Lickness
Lickteig
Lico
Licon
Licor
Licudine
Licursi
Lidbom
Liddell
Lidder
Liddiard
Liddick
Liddicoat
Liddie
Liddle
Liddy
Lide
Lidey
Lidge
Lidie
Lidke
Lidster
Lidstone
Lidstrom
Lidtke
Lie
Lieb
Liebau
Liebe
Liebeck
Liebel
Liebelt
Liebenow
Liebenthal
Lieber
Lieberg
Lieberman
Liebermann
Liebert
Liebhardt
Liebherr
Liebig
Liebl
Liebler
Lieblong
Liebman
Liebold
Liebowitz
Liebrecht
Liebross
Liebsch
Liebskind
Liechti
Liechty
Lied
Liedberg
Lieder
Liederbach
Liedke
Liedtke
Liedy
Liefer
Liegler
Liehr
Liekhus
Liem
Lien
Liendo
Lienemann
Lieng
Lienhard
Lienke
Liepins
Lierle
Lierman
Lierz
Lies
Liesch
Lieser
Lieske
Liesman
Liesmann
Liess
Liest
Liestman
Liesveld
Lieto
Lietz
Lietzke
Lietzow
Lieu
Lieuallen
Lieurance
Lievano
Lievens
Lievsay
Liew
Liewald
Life
Lifer
Liff
Liffick
Lifford
Lifland
Liford
Lifschitz
Lifsey
Lifshitz
Liftin
Lifton
Ligas
Lige
Liggans
Ligget
Liggett
Liggin
Liggins
Liggons
Light
Lightbody
Lightbourne
Lightcap
Lighter
Lightfoot
Lightford
Lighthall
Lighthart
Lighthill
Lightle
Lightner
Lightning
Lights
Lightsey
Lighty
Ligler
Ligman
Ligon
Ligonis
Ligons
Liguori
Liiv
Lijewski
Likar
Like
Likens
Likes
Likins
Likio
Likos
Lilburn
Lile
Liles
Liley
Lilien
Lilienthal
Lilja
Liljeberg
Liljedahl
Liljenquist
Lill
Lilla
Lillard
Lilleberg
Lillehaug
Liller
Lilley
Lillian
Lillibridge
Lillich
Lillick
Lillie
Lillig
Lillis
Lillo
Lillpop
Lilly
Lillywhite
Liloia
Lily
Lilyblade
Lilyquist
Lim
Lima
Limage
Limardi
Limardo
Limas
Limauro
Limb
Limbach
Limbaugh
Limber
Limberg
Limbert
Limbo
Limbrick
Limburg
Lime
Limehouse
Limerick
Limes
Limesand
Liming
Limke
Limle
Limmel
Limmer
Limoges
Limoli
Limon
Limones
Limthong
Lin
Lina
Linahan
Linak
Linamen
Linan
Linander
Linard
Linardi
Linares
Linarez
Linberg
Linburg
Linch
Lincicome
Lincicum
Linck
Lincks
Lincoln
Lincourt
Lind
Linda
Lindabury
Lindahl
Lindall
Lindaman
Lindamood
Lindau
Lindauer
Lindbeck
Lindberg
Lindblad
Lindblom
Lindbloom
Lindbo
Lindboe
Lindburg
Linde
Lindeen
Lindel
Lindeland
Lindell
Lindelof
Lindeman
Lindemann
Lindemuth
Linden
Lindenbaum
Lindenberg
Lindenberger
Lindenfelser
Lindenmuth
Lindenpitz
Linder
Linderholm
Linderleaf
Linderman
Linders
Lindersmith
Lindert
Lindesmith
Lindfors
Lindgren
Lindholm
Lindhorst
Lindie
Lindig
Lindinha
Lindler
Lindley
Lindline
Lindloff
Lindman
Lindmeyer
Lindner
Lindo
Lindon
Lindorf
Lindow
Lindquist
Lindroth
Lindsay
Lindsey
Lindskog
Lindsley
Lindstedt
Lindstrom
Lindwall
Lindy
Lindzy
Line
Linea
Linear
Lineback
Linebarger
Linebaugh
Lineberger
Lineberry
Linebrink
Linegar
Linehan
Lineman
Linen
Linenberger
Liner
Linero
Lines
Linet
Lineweaver
Linford
Ling
Lingad
Lingafelt
Lingafelter
Lingao
Lingard
Lingardo
Lingbeck
Lingbeek
Lingberg
Lingefelt
Lingel
Lingelbach
Lingenfelter
Linger
Lingerfelt
Lingerfelter
Lingg
Linginfelter
Lingle
Lingley
Lingner
Lingo
Lingren
Linhardt
Linhares
Linhart
Lininger
Linington
Link
Linke
Linker
Linkert
Linkhart
Linkkila
Linklater
Linko
Linkon
Linkous
Linkovich
Linkowski
Links
Linley
Linman
Linn
Linnan
Linnane
Linne
Linnear
Linnecke
Linnell
Linneman
Linnemann
Linnen
Linnert
Linnertz
Linney
Lino
Linquist
Lins
Linsay
Linscomb
Linscott
Linsdau
Linsday
Linsenmayer
Linsey
Linsin
Linsky
Linsley
Linsner
Linson
Linssen
Linstrom
Lint
Linthicum
Lintner
Linton
Lints
Lintz
Linville
Linwood
Linz
Linza
Linzan
Linzey
Linzie
Linzy
Lio
Lion
Lionberger
Lionello
Lionetti
Lions
Liontos
Liotta
Liou
Lipa
Lipan
Lipani
Lipari
Lipe
Lipford
Lipham
Lipinski
Lipinsky
Lipira
Lipitz
Lipka
Lipke
Lipkin
Lipkind
Lipkovitch
Lipman
Lipner
Lipoma
Lipovsky
Lipp
Lippa
Lippard
Lippe
Lippeatt
Lipper
Lippert
Lipphardt
Lippi
Lippincott
Lippitt
Lippman
Lippold
Lippoldt
Lipps
Lippy
Lips
Lipschutz
Lipscomb
Lipscombe
Lipsett
Lipsey
Lipsie
Lipsitz
Lipskar
Lipski
Lipsky
Lipson
Lipstone
Lipszyc
Liptak
Liptok
Lipton
Liptow
Liptrap
Liptrot
Liquet
Liquori
Lira
Lirag
Liranzo
Lirette
Liriano
Lis
Lisa
Lisanti
Lisbey
Lisboa
Lisby
Liscano
Lischak
Liscio
Liscomb
Lisee
Lisena
Lisenbee
Lisenby
Lish
Lisherness
Lishman
Lisi
Lisiecki
Lisitano
Lisius
Lisk
Liska
Liskai
Liske
Lisker
Liskey
Liskiewicz
Lisko
Liskovec
Lisle
Lisman
Lisonbee
Lisowe
Lisowski
Liss
Lissard
Lisser
Lissy
List
Lista
Listen
Lister
Listi
Liston
Lisy
Liszewski
Litaker
Litalien
Litano
Litchard
Litchfield
Litchford
Litchmore
Litecky
Litehiser
Liter
Lites
Litherland
Litka
Litke
Litle
Litman
Litmanowicz
Litner
Litrenta
Litscher
Litsey
Litster
Litt
Littau
Litteer
Littell
Litten
Litter
Litteral
Litterer
Littfin
Littich
Little
Littledave
Littlefield
Littlehale
Littlejohn
Littlepage
Littler
Littles
Littleton
Littlewood
Littman
Littmann
Litton
Littrel
Littrell
Litts
Litty
Litvak
Litvin
Litwiler
Litwin
Litz
Litza
Litzau
Litzenberg
Litzenberger
Litzinger
Litzsinger
Liu
Liukko
Liukkonen
Liuzza
Liuzzi
Liv
Livas
Livasy
Livecchi
Lively
Livengood
Liveoak
Liverance
Liverani
Liverman
Livermon
Livermore
Livernash
Livernoche
Livernois
Liverpool
Livers
Liversedge
Livesay
Livesey
Livezey
Livi
Livigni
Living
Livingood
Livings
Livingston
Livingstone
Livington
Livinton
Livley
Livoti
Livsey
Livshits
Liwanag
Liz
Lizak
Lizama
Lizana
Lizaola
Lizarda
Lizardi
Lizardo
Lizarraga
Lizarrago
Lizer
Lizotte
Ljungquist
Llamas
Llams
Llanas
Llanes
Llanet
Llanez
Llaneza
Llano
Llanos
Llarena
Llarenas
Llera
Lleras
Llerena
Llewellyn
Llewlyn
Lloid
Llopis
Llorca
Llorens
Lloyd
Llyod
Lo
Loa
Loach
Loader
Loadholt
Loaiza
Loan
Loar
Loarca
Loatman
Loats
Lob
Lobach
Lobalbo
Loban
Lobasso
Lobato
Lobaton
Lobaugh
Lobb
Lobban
Lobbins
Lobdell
Lobe
Lobel
Lobell
Lobello
Lobendahn
Lober
Loberg
Lobianco
Lobingier
Lobley
Lobner
Lobo
Lobos
Lobosco
Lobregat
Lobstein
Lobue
Lobur
Locante
Locantore
Locascio
Locastro
Locatelli
Locey
Loch
Lochan
Loche
Lochen
Locher
Lochner
Lochotzki
Lochrico
Lochridge
Lochte
Locicero
Lock
Lockaby
Lockamy
Lockard
Lockart
Lockbaum
Locke
Lockemer
Locken
Locker
Lockerby
Lockerman
Lockery
Locket
Lockett
Lockette
Lockey
Lockhart
Lockheart
Lockie
Lockington
Locklar
Locklear
Lockley
Locklier
Locklin
Lockman
Lockmiller
Locknane
Lockner
Lockrem
Lockridge
Locks
Lockshaw
Lockwood
Lockyer
Lococo
Loconte
Locorriere
Locsin
Locus
Locust
Locy
Lodato
Lodeiro
Loden
Lodense
Loder
Lodge
Lodholz
Lodi
Lodrigue
Loduca
Lodwick
Loe
Loeb
Loeber
Loeblein
Loebs
Loecken
Loeckle
Loeffel
Loeffelholz
Loeffler
Loegering
Loehlein
Loehner
Loehr
Loehrer
Loehrs
Loendorf
Loeper
Loepp
Loeppke
Loeppky
Loera
Loertscher
Loerwald
Loerzel
Loesch
Loesche
Loescher
Loeschner
Loeser
Loessberg
Loethen
Loetz
Loeurm
Loeven
Loew
Loewe
Loewen
Loewenstein
Loewenthal
Loewer
Loeza
Lofaro
Lofaso
Loffelbein
Loffier
Loffler
Loffredo
Lofft
Lofgreen
Lofgren
Lofguist
Lofing
Lofink
Lofland
Loflen
Loflin
Lofman
Loforte
Lofquist
Lofredo
Lofstead
Lofstrom
Loft
Lofte
Loften
Lofthouse
Lofthus
Lofties
Loftin
Loftis
Loftman
Lofton
Lofts
Loftus
Lofty
Lofwall
Logalbo
Logan
Logarbo
Loge
Logel
Logemann
Logero
Loges
Loggains
Loggens
Logghe
Loggin
Loggins
Loghry
Logie
Logins
Logiudice
Logoleo
Logosso
Lograsso
Logrono
Logsdon
Logston
Logue
Loguidice
Logwood
Loh
Lohan
Lohden
Lohman
Lohmann
Lohmeier
Lohmeyer
Lohmiller
Lohn
Lohnes
Lohoff
Lohr
Lohre
Lohrenz
Lohrey
Lohrke
Lohrman
Lohrmann
Lohry
Lohse
Loht
Lohwasser
Loi
Loia
Loiacona
Loiacono
Loiko
Loil
Lois
Loiseau
Loisel
Loiselle
Lojek
Lok
Lokan
Lokaphone
Loken
Loker
Lokey
Lokhmator
Lokhmatov
Lokietek
Lokke
Lokken
Lokker
Lokuta
Lola
Lolagne
Lolar
Loli
Loll
Lollar
Lolley
Lolli
Lollie
Lolling
Lollis
Loma
Lomack
Lomago
Loman
Lomanto
Lomartire
Lomas
Lomascolo
Lomasney
Lomax
Lomay
Lomba
Lombard
Lombardi
Lombardino
Lombardo
Lombel
Lombera
Lomboy
Lombrana
Lomedico
Lomeli
Lomen
Lomg
Lominack
Lomino
Lominy
Lommel
Lomonaco
Lomonte
Lompa
Lomu
Lomuscio
Lona
Lonabaugh
Lonas
Loncar
Loncaric
Londagin
Londner
Londo
London
Londono
Londre
Lone
Loner
Lonergan
Lonero
Lones
Loney
Long
Longabaugh
Longacre
Longaker
Longan
Longanecker
Longbine
Longbotham
Longbottom
Longbrake
Longchamps
Longcor
Longden
Longe
Longenberger
Longendyke
Longenecker
Longerbeam
Longest
Longfellow
Longfield
Longford
Longhenry
Longhi
Longhini
Longhofer
Longhurst
Longie
Longin
Longino
Longinotti
Longiotti
Longknife
Longley
Longman
Longmire
Longmore
Longnecker
Longo
Longobardi
Longoria
Longpre
Longs
Longsdorf
Longshore
Longstaff
Longstreet
Longstreth
Longsworth
Longtin
Longton
Longueville
Longway
Longwell
Longwith
Longworth
Lonie
Lonn
Lonneman
Lonon
Lons
Lonsdale
Lonsinger
Lonsway
Lontz
Lonzo
Loo
Looby
Loock
Loofbourrow
Looft
Looi
Look
Lookabaugh
Lookadoo
Looker
Looman
Loomer
Loomis
Looney
Loop
Looper
Loos
Loose
Loosen
Loosey
Loosier
Loosle
Loosli
Lootens
Loots
Loparco
Lopardo
Loparo
Lopas
Lopata
Lopau
Lopaz
Lope
Lopeman
Loper
Lopera
Loperena
Loperfido
Lopes
Lopey
Lopez
Lopiccalo
Lopiccolo
Lopilato
Lopinto
Lopp
Lopresti
Lopresto
Lopriore
Lopus
Lopuzzo
Lopze
Loque
Lor
Lora
Lorah
Loraine
Loran
Lorance
Lorandeau
Lorange
Loranger
Loras
Lorber
Lorch
Lord
Lorden
Lordi
Lords
Lore
Loreaux
Loredo
Loree
Loreg
Lorelli
Lorello
Loreman
Loren
Lorenc
Lorence
Lorens
Lorensen
Lorenson
Lorent
Lorente
Lorentine
Lorentz
Lorentzen
Lorenz
Lorenzana
Lorenzano
Lorenzen
Lorenzetti
Lorenzi
Lorenzini
Lorenzo
Loreto
Lorett
Lorette
Loretto
Loretz
Lorey
Lorge
Lori
Loria
Lorick
Lorimer
Lorimor
Lorin
Lorincz
Loring
Lorino
Lorio
Lorion
Lorkowski
Lorman
Lormand
Lorna
Loron
Lorona
Lorquet
Lorr
Lorraine
Lorson
Lorsung
Lortie
Lorton
Lorts
Lortz
Lorusso
Lory
Lorz
Los
Losa
Losacco
Losada
Losado
Losano
Losardo
Losavio
Loscalzo
Losch
Loschiavo
Losco
Lose
Losecco
Losee
Loseke
Loser
Loseth
Losey
Losh
Loshbaugh
Loshe
Loshek
Losier
Losiewski
Losinger
Losinski
Losito
Loske
Loskill
Loskot
Losneck
Loso
Losolla
Loson
Losoya
Loss
Lossa
Losser
Lossett
Lossing
Lossius
Lossman
Lostetter
Loston
Lostracco
Lostroh
Loszynski
Lot
Lota
Lotan
Lotempio
Loter
Loterbauer
Loth
Lothamer
Lother
Lothian
Lothridge
Lothringer
Lothrop
Lothspeich
Lotridge
Lotshaw
Lotson
Lotspeich
Lott
Lotta
Lotter
Lotthammer
Lotti
Lottie
Lotto
Lotton
Lotts
Lotz
Lotze
Lotzer
Lou
Louato
Loubier
Louch
Louchen
Louck
Loucks
Loud
Louden
Loudenslager
Louder
Louderback
Loudermelt
Loudermilk
Loudermill
Loudin
Loudon
Loudy
Louer
Louge
Lougee
Lough
Loughary
Loughborough
Lougheed
Loughery
Loughlin
Loughman
Loughmiller
Loughnan
Loughnane
Loughner
Loughney
Loughran
Loughrey
Loughridge
Loughry
Louie
Louil
Louis
Louise
Louissaint
Louissant
Louk
Louka
Loukanis
Loukas
Loukidis
Loukota
Louks
Lounder
Lounds
Loung
Lounsberry
Lounsbery
Lounsbury
Loup
Loupe
Louque
Loura
Louras
Lourdes
Loureiro
Lourence
Lourenco
Lourens
Lourentzos
Louria
Louris
Lournes
Louro
Loury
Louser
Lousteau
Lout
Louth
Louthan
Louthen
Louvier
Louviere
Louwagie
Loux
Lovaas
Lovaglio
Lovallo
Lovan
Lovas
Lovasz
Lovato
Love
Loveall
Loveberry
Lovec
Lovecchio
Loveday
Loveh
Lovejoy
Lovelace
Lovelady
Loveland
Loveless
Lovell
Lovellette
Lovelock
Lovely
Loveman
Loven
Lovenbury
Lovenduski
Lovensheimer
Lover
Lovera
Loverde
Loverdi
Loverich
Loveridge
Lovering
Loverink
Lovern
Lovero
Lovet
Lovetinsky
Lovett
Lovette
Lovfald
Lovgren
Lovich
Lovick
Lovie
Lovier
Lovig
Lovin
Loving
Lovinggood
Lovingood
Lovings
Lovins
Loviska
Lovisone
Lovitt
Lovitz
Lovorn
Lovstad
Lovvorn
Low
Lowa
Lowber
Lowcks
Lowd
Lowden
Lowder
Lowdermilk
Lowe
Lowek
Lowell
Lowen
Lowenstein
Lowenthal
Lower
Lowers
Lowery
Lowes
Lowhorn
Lowin
Lowing
Lowis
Lowitz
Lowler
Lowman
Lown
Lowndes
Lowney
Lownsbery
Lowrance
Lowrey
Lowrie
Lowrimore
Lowry
Lowther
Lowthert
Lowthorp
Lowy
Loxley
Loxtercamp
Loxton
Loy
Loya
Loyack
Loyal
Loyborg
Loyd
Loyed
Loyer
Loynd
Loynes
Loyola
Loyst
Loza
Lozada
Lozado
Lozano
Lozaro
Lozaya
Loze
Lozeau
Lozey
Lozier
Lozinski
Lozito
Lozo
Lozon
Lozowski
Lozoya
Lozzi
Lu
Lua
Luaces
Luague
Luallen
Luangamath
Luangrath
Luangsingotha
Luangxay
Luarca
Lubahn
Lubawy
Lubben
Lubbers
Lubbert
Lubbock
Lubbs
Lube
Lubeck
Lubell
Lubelski
Luben
Luber
Luberger
Lubic
Lubin
Lubinski
Lubinsky
Lubke
Lubman
Lubow
Lubrano
Luby
Luc
Luca
Lucarell
Lucarelli
Lucario
Lucas
Lucash
Lucatero
Lucca
Lucchese
Lucchesi
Lucchetti
Lucchini
Lucci
Luccous
Luce
Lucear
Lucek
Lucena
Lucente
Lucero
Lucey
Luchenbill
Lucherini
Luchesi
Luchessa
Luchetti
Luchini
Luchsinger
Lucht
Luchterhand
Luci
Lucia
Lucian
Luciani
Luciano
Lucic
Lucich
Lucidi
Lucido
Lucie
Lucien
Lucier
Lucik
Lucio
Lucion
Lucious
Lucis
Lucius
Luck
Luckado
Luckadoo
Lucke
Lucken
Luckenbach
Luckenbaugh
Luckenbill
Lucker
Luckett
Luckey
Luckhardt
Luckie
Luckinbill
Luckman
Luckner
Luckow
Luckritz
Lucks
Lucksinger
Lucksom
Lucky
Luco
Lucore
Lucus
Lucy
Luczak
Luczki
Luczkowiak
Luczynski
Ludd
Ludden
Luddy
Ludecke
Ludeke
Ludeker
Ludeman
Ludemann
Ludera
Luderman
Ludewig
Ludgate
Ludgood
Ludington
Ludke
Ludkowski
Ludlam
Ludlow
Ludlum
Ludolph
Ludovici
Ludovico
Ludtke
Ludvigsen
Ludvigson
Ludvik
Ludwick
Ludwig
Ludy
Lue
Luebano
Luebbe
Luebbering
Luebbers
Luebbert
Luebke
Luecht
Luechtefeld
Lueck
Luecke
Lueckenbach
Lueckenhoff
Lueckenotte
Luecking
Luedecke
Luedeman
Lueder
Lueders
Luedi
Luedke
Luedtke
Luehring
Luehrs
Lueker
Lueking
Luelf
Luellen
Luening
Luensmann
Luepke
Luer
Luera
Lueras
Luers
Luersen
Lueschen
Luescher
Lueth
Luetkemeyer
Luetmer
Luette
Luevand
Luevano
Luevanos
Lufborough
Luff
Luffman
Luffy
Lufkin
Lufsey
Luft
Luga
Lugabihl
Lugar
Lugardo
Luger
Lugg
Luginbill
Lugo
Lugones
Luhman
Luhmann
Luhn
Luhnow
Luhr
Luhring
Luhrs
Lui
Luick
Luikart
Luing
Luinstra
Luis
Luisi
Luiso
Luitjens
Luiz
Lujan
Lujano
Luk
Luka
Lukach
Lukacs
Lukan
Lukander
Lukas
Lukasiewicz
Lukasik
Lukaskiewicz
Lukaszewicz
Lukaszewski
Lukavsky
Luke
Lukehart
Luken
Lukens
Luker
Lukes
Lukesh
Lukianov
Lukin
Lukins
Lukman
Lukow
Lukowski
Luksa
Lulas
Lule
Lulewicz
Lulic
Lull
Luloff
Lulow
Lum
Luma
Lumadue
Luman
Lumantas
Lumas
Lumb
Lumba
Lumbard
Lumbert
Lumbley
Lumbra
Lumbreras
Luminati
Lumley
Lumm
Lummis
Lummus
Lumpkin
Lumpkins
Lumpp
Lumsden
Lumukanda
Luna
Lunan
Lunceford
Lunch
Luncsford
Lund
Lundahl
Lunday
Lundberg
Lundblad
Lundborg
Lundburg
Lundby
Lunde
Lundeby
Lundeen
Lundell
Lundemo
Lunden
Lunderman
Lunderville
Lundgreen
Lundgren
Lundholm
Lundi
Lundie
Lundin
Lundman
Lundmark
Lundquist
Lundrigan
Lundsford
Lundsten
Lundstrom
Lundvall
Lundy
Luneau
Lunemann
Lunetta
Lunford
Lung
Lunger
Lunghofer
Lungren
Lungsford
Lungstrom
Lungwitz
Lunn
Lunney
Lunning
Lunnon
Lunsford
Lunstrum
Lunt
Lunter
Lunz
Luo
Luoma
Luong
Luongo
Luoto
Lupacchino
Lupardus
Luper
Lupercio
Lupez
Lupfer
Lupi
Lupiani
Lupien
Lupinacci
Lupino
Lupkes
Lupkin
Lupo
Lupoe
Lupold
Luppino
Luptak
Lupton
Lupu
Lupul
Luque
Luquette
Luquin
Lura
Lurey
Luria
Lurie
Lurry
Lurtz
Lurvey
Lury
Lurye
Lurz
Lusane
Lusardi
Lusby
Luscavage
Lusco
Luscombe
Luse
Lush
Lushbaugh
Lusher
Lusignan
Lusk
Luskey
Luskin
Luss
Lussier
Lust
Lustberg
Luster
Lustig
Lusty
Lutao
Lutchman
Lute
Luten
Luter
Lutes
Lutfy
Lutgen
Luth
Luthe
Luther
Luthi
Luthy
Lutjen
Lutke
Lutkins
Lutkus
Lutman
Luton
Lutrell
Lutrick
Lutsky
Luttenegger
Lutter
Lutterman
Luttman
Luttmer
Lutton
Luttrell
Luttrull
Lutts
Lutwin
Lutz
Lutze
Lutzi
Luu
Luvene
Luvera
Luvert
Luvian
Luvianos
Lux
Luxenberg
Luxmore
Luxon
Luxton
Luy
Luyando
Luz
Luzader
Luzania
Luzar
Luzell
Luzi
Luzier
Luzinski
Luzuriaga
Luzzi
Lweis
Ly
Lyall
Lyalls
Lyas
Lyau
Lybarger
Lybbert
Lybecker
Lyberger
Lybert
Lybrand
Lycan
Lychwala
Lyda
Lyday
Lyde
Lydecker
Lyden
Lydia
Lydic
Lydick
Lydon
Lye
Lyell
Lyerla
Lyerly
Lyew
Lyford
Lykam
Lyke
Lyken
Lykens
Lykes
Lykins
Lykke
Lykken
Lyle
Lyles
Lym
Lyman
Lymaster
Lyme
Lymon
Lyn
Lynady
Lynah
Lynam
Lynaugh
Lynch
Lynchard
Lynchj
Lynd
Lyndaker
Lynde
Lyndon
Lynds
Lyne
Lynema
Lynes
Lyness
Lyng
Lynge
Lyngholm
Lynk
Lynn
Lynne
Lynott
Lynskey
Lynum
Lyon
Lyons
Lysaght
Lysak
Lysen
Lyseski
Lysher
Lysiak
Lysne
Lyson
Lyssy
Lyster
Lytal
Lytch
Lytell
Lyter
Lytle
Lyttle
Lytton
Lyvers
Ma
Maack
Maag
Maahs
Maalouf
Maarx
Maas
Maasch
Maasen
Maaske
Maass
Maassen
Maatta
Mabane
Mabary
Mabb
Mabbott
Mabe
Mabee
Mabel
Maben
Maberry
Mabery
Mabey
Mabie
Mabin
Mabins
Mable
Mabon
Mabone
Mabra
Mabray
Mabrey
Mabry
Mabus
Mac
Macabeo
Macadam
Macadamia
Macadangdang
Macafee
Macahilas
Macall
Macallister
Macalma
Macaluso
Macanas
Macandog
Macapagal
Macaraeg
Macaraig
Macareno
Macari
Macarthur
Macartney
Macaskill
Macaulay
Macauley
Macayan
Macbean
Macbeth
Macbride
Maccabe
Maccallum
Maccarini
Maccarino
Maccarone
Maccarter
Maccarthy
Maccartney
Maccauley
Maccheyne
Macchi
Macchia
Macchiarella
Macchiaroli
Macchio
Macchione
Maccini
Macclairty
Macclellan
Maccoll
Macconaghy
Macconnell
Maccord
Maccormack
Macculloch
Maccutcheon
Macdaniel
Macdermott
Macdiarmid
Macdonald
Macdonell
Macdonnell
Macdougal
Macdougald
Macdougall
Macdowell
Macduff
Macduffee
Mace
Maceachern
Maceda
Macedo
Macedonio
Macek
Macentee
Macer
Macera
Macewen
Macey
Maceyak
Macfarland
Macfarlane
Macgillivray
Macgowan
Macgregor
Macguire
Mach
Macha
Machacek
Machado
Machain
Machak
Machala
Machalek
Machamer
Machan
Machel
Machen
Machenry
Machens
Machesky
Machey
Machi
Machia
Machida
Machin
Machinsky
Machkovich
Machle
Machlin
Machnik
Macho
Machol
Machold
Machon
Machover
Machowski
Macht
Machtley
Machuca
Machuga
Macia
Maciag
Maciak
Maciarello
Macias
Maciasz
Macie
Maciej
Maciejczyk
Maciejewski
Maciejko
Maciel
Macina
Macinnes
Macinnis
Macintosh
Macintyre
Macioce
Maciolek
Macione
Macisaac
Maciver
Macivor
Mack
Mackall
Mackaman
Mackay
Macke
Mackechnie
Mackedanz
Mackeen
Mackel
Mackell
Mackellar
Macken
Mackenthun
Mackenzie
Macker
Mackerl
Mackert
Mackessy
Mackesy
Mackey
Macki
Mackie
Mackiewicz
Mackillop
Mackimmie
Mackin
Mackinaw
Mackinder
Mackinlay
Mackinnon
Mackins
Mackintosh
Mackle
Macklem
Mackler
Mackley
Macklin
Macknair
Mackney
Macknight
Macko
Mackowiak
Mackowski
Macks
Macksey
Mackson
Macksoud
Mackstutis
Macky
Mackynen
Maclachlan
Maclain
Maclaren
Maclauchlan
Maclaughlin
Maclaurin
Maclay
Maclead
Maclean
Maclellan
Maclennan
Macleod
Maclin
Macmahon
Macmanus
Macmaster
Macmillan
Macmillen
Macmullan
Macmullen
Macmurray
Macnab
Macnair
Macnamara
Macnamee
Macnaught
Macnaughton
Macneal
Macneil
Macneill
Macnevin
Macnutt
Maco
Macola
Macomb
Macomber
Macon
Macoreno
Macpartland
Macphail
Macphee
Macpherson
Macquarrie
Macqueen
Macrae
Macreno
Macri
Macrina
Macrostie
Macrowski
Macrum
Macugay
Macumber
Macura
Macurdy
Macvane
Macvean
Macvicar
Macwilliams
Macy
Maczko
Mad
Mada
Madaffari
Madagan
Madalinski
Madamba
Madan
Madara
Madarang
Madaras
Madariaga
Madaris
Maday
Madayag
Maddalena
Maddaleno
Maddaloni
Madden
Maddern
Maddin
Madding
Maddison
Maddix
Maddock
Maddocks
Maddox
Maddoy
Maddrey
Maddron
Maddry
Maddux
Maddy
Madeau
Madeira
Madeiros
Madeja
Maden
Madena
Madenford
Mader
Madera
Maderas
Madere
Maderios
Madero
Mades
Madewell
Madge
Madhavan
Madho
Madi
Madia
Madigan
Madill
Madin
Madina
Madine
Madinger
Madise
Madison
Maditz
Madkin
Madkins
Madlem
Madler
Madlock
Madlung
Madnick
Madock
Madole
Madon
Madonia
Madonna
Mador
Madore
Madrano
Madras
Madray
Madrazo
Madre
Madren
Madrid
Madrigal
Madril
Madriz
Madron
Madrueno
Madruga
Madry
Madsen
Madson
Madu
Maduena
Madueno
Madura
Maduro
Mady
Madyun
Madziar
Mae
Maeda
Maedche
Maeder
Maedke
Maenaga
Maendel
Maenhout
Maenius
Maenner
Maeno
Maenpaa
Maertens
Maertz
Maerz
Maes
Maese
Maestas
Maestos
Maestre
Maestri
Maeweather
Maez
Maffei
Maffeo
Maffett
Maffey
Maffia
Maffit
Maffitt
Maffucci
Mafnas
Mafua
Maga
Magadan
Magaddino
Magaha
Magaldi
Magallan
Magallanes
Magallanez
Magallon
Magalong
Magalski
Magan
Magana
Magano
Magar
Magarelli
Magario
Magat
Magathan
Magaw
Magaziner
Magbitang
Magby
Magda
Magdalena
Magdaleno
Magdefrau
Mage
Maged
Magedanz
Magee
Magel
Magelssen
Mager
Magera
Magers
Mages
Magett
Magette
Magg
Maggard
Maggart
Maggert
Maggi
Maggie
Maggini
Magginson
Maggio
Maggiore
Maggit
Maggs
Magic
Magid
Magierski
Magil
Magill
Magin
Maginn
Maginnis
Magistrale
Magitt
Maglaras
Maglaughlin
Maglaya
Magleby
Magley
Magliacane
Magliano
Maglio
Magliocca
Magliocco
Maglioli
Magliolo
Maglione
Magliulo
Maglori
Maglott
Magnall
Magnan
Magnani
Magnano
Magnant
Magnanti
Magner
Magness
Magnett
Magnetti
Magni
Magnia
Magnie
Magnifico
Magnini
Magno
Magnone
Magnotta
Magnotti
Magnus
Magnuson
Magnusson
Mago
Magobet
Magone
Magoon
Magorina
Magos
Magouirk
Magouliotis
Magoun
Magouyrk
Magowan
Magpali
Magpuri
Magpusao
Magrann
Magrath
Magraw
Magri
Magro
Magrone
Magruder
Magsamen
Magsayo
Magsby
Maguet
Maguire
Magwire
Magwood
Magyar
Mah
Maha
Mahabir
Mahaffey
Mahaffy
Mahajan
Mahal
Mahala
Mahaley
Mahalko
Mahall
Maham
Mahan
Mahana
Mahaney
Mahanna
Mahany
Mahapatra
Mahar
Maharaj
Maharg
Maharrey
Mahaxay
Mahdi
Mahe
Maheia
Maher
Maheras
Maheu
Maheux
Mahfouz
Mahi
Mahin
Mahl
Mahle
Mahler
Mahley
Mahli
Mahlke
Mahlman
Mahlum
Mahmood
Mahmoud
Mahmud
Mahn
Mahnke
Mahnken
Mahoe
Maholmes
Mahomes
Mahomly
Mahon
Mahone
Mahoney
Mahony
Mahood
Mahowald
Mahr
Mahran
Mahraun
Mahrenholz
Mahrer
Mahula
Mahuna
Mahung
Mahunik
Mahurin
Mahusay
Mai
Maia
Maiava
Maicus
Maid
Maida
Maiden
Maidens
Maidonado
Maiello
Maier
Maiers
Maietta
Maifeld
Maignan
Maigret
Maikoksoong
Mail
Mailander
Maile
Mailes
Mailey
Mailhiot
Mailhot
Maillard
Maille
Maillet
Mailliard
Mailloux
Mailman
Mailo
Maimone
Main
Mainard
Maine
Mainella
Mainello
Mainer
Mainero
Maines
Mainetti
Mainey
Mainguy
Mainiero
Mainland
Maino
Mainolfi
Mainor
Mainord
Mains
Mainville
Mainwaring
Mainz
Maio
Maiocco
Maiolo
Maione
Maiorano
Mair
Maire
Mairot
Mairs
Mais
Maisano
Maisch
Maise
Maisel
Maisenbacher
Maisey
Maish
Maison
Maisonave
Maisonet
Maisto
Maita
Maiten
Maitland
Maixner
Maize
Maizes
Maj
Majamay
Majano
Majcher
Majchrzak
Majeau
Majeed
Majer
Majera
Majercik
Majercin
Majerowski
Majersky
Majerus
Majeske
Majeski
Majestic
Majette
Majewski
Majic
Majica
Majid
Majied
Majka
Majkowski
Majkut
Majmundar
Majocka
Major
Majorga
Majors
Majure
Majuste
Mak
Maka
Makanani
Makar
Makara
Makarem
Makarewicz
Makekau
Makel
Makela
Makepeace
Maker
Makey
Makhija
Maki
Makin
Makinen
Makino
Makins
Makinson
Makinster
Makler
Makley
Mako
Makofsky
Makos
Makovec
Makowski
Makowsky
Makris
Maks
Makua
Makuch
Malabanan
Malabe
Malabey
Malacara
Malach
Malachi
Malachowski
Malady
Malafronte
Malagarie
Malagisi
Malagon
Malahan
Malak
Malakai
Malakan
Malakowsky
Malama
Malamud
Malan
Malanado
Malanaphy
Maland
Malander
Malandra
Malandrino
Malandruccolo
Malaney
Malanga
Malango
Malara
Malarkey
Malas
Malasky
Malaspina
Malaterre
Malatesta
Malave
Malaver
Malavet
Malawy
Malay
Malbaurn
Malboeuf
Malbon
Malbrough
Malchow
Malcik
Malcolm
Malcom
Malcomb
Malcome
Malcomson
Maldanado
Malden
Maldenado
Maldomado
Maldonado
Maldonaldo
Malec
Malech
Malecha
Maleck
Malecki
Maleh
Malehorn
Malek
Malekan
Malekzadeh
Malen
Malena
Malenfant
Malenke
Malensek
Maleonado
Maler
Males
Maleski
Malesky
Maleszka
Malet
Malett
Maletta
Malette
Maletz
Malewski
Maley
Malfatti
Malgieri
Malhi
Malhotra
Malia
Malicdem
Malich
Malichi
Malick
Malicoat
Malicote
Malik
Malikowski
Malin
Malina
Malinak
Malinchalk
Malinconico
Maline
Malinky
Malinoski
Malinovsky
Malinowski
Malinski
Malinsky
Malis
Maliska
Maliszewski
Malit
Malito
Malizia
Malkani
Malkasian
Malkiewicz
Malkin
Malkoski
Malkowski
Mall
Malla
Mallacara
Mallach
Mallahan
Mallak
Mallalieu
Mallar
Mallard
Mallari
Mallary
Mallas
Mallat
Malle
Malleck
Mallegni
Mallek
Mallen
Maller
Mallernee
Mallery
Mallet
Mallett
Mallette
Malley
Mallia
Mallick
Mallicoat
Mallie
Mallin
Mallinak
Malling
Mallinger
Mallinson
Mallis
Mallo
Malloch
Mallon
Mallone
Mallonee
Mallory
Mallow
Malloy
Mallozzi
Mally
Malm
Malmanger
Malmberg
Malmgren
Malmin
Malmquist
Malnar
Malo
Maloch
Malocha
Maloff
Malone
Maloney
Maloof
Malool
Maloon
Malory
Malott
Malotte
Malouf
Malouff
Malovich
Maloy
Malpass
Malphurs
Malpica
Malsam
Malsch
Malsom
Malson
Malstrom
Malta
Maltais
Maltas
Maltba
Maltbia
Maltbie
Maltby
Malter
Maltese
Maltez
Maltie
Malton
Maltos
Maltsberger
Maltz
Malueg
Malusky
Malvaez
Malveaux
Malvern
Malvin
Maly
Malys
Malzahn
Malzhan
Mam
Mamaclay
Mamaril
Mamer
Mammano
Mammen
Mammenga
Mammo
Mammoccio
Mammucari
Mamo
Mamon
Mamone
Mamoran
Mamros
Mamudoski
Mamula
Man
Mana
Manago
Manahan
Manaker
Manalang
Manalili
Manalo
Manansala
Manaois
Manard
Manary
Manas
Manasares
Manasco
Manassa
Manasse
Manatt
Manaugh
Manbeck
Manby
Manca
Mance
Mancell
Mancera
Mancha
Manche
Manchel
Mancher
Mancherian
Manchester
Manchini
Mancia
Mancias
Manciel
Mancil
Mancill
Mancilla
Mancillas
Mancina
Mancine
Mancinelli
Mancini
Mancino
Manco
Mancos
Mancusi
Mancuso
Mand
Manda
Mandahl
Mandala
Mandaloniz
Mandap
Mandarino
Mandato
Mandel
Mandelbaum
Mandelberg
Mandelik
Mandell
Mandella
Mander
Manders
Manderscheid
Manderson
Mandes
Mandeville
Mandez
Mandi
Mandia
Mandich
Mandigo
Mandino
Mandiola
Mandler
Mandley
Mandolfo
Mandolini
Mandonado
Mandoza
Mandrell
Mandril
Mandry
Mandt
Mandujano
Mandy
Mane
Maneafaiga
Manecke
Manely
Manemann
Maner
Manera
Manero
Manery
Manes
Maness
Manetta
Maney
Manford
Manfra
Manfre
Manfred
Manfredi
Manfredini
Manfredonia
Mang
Mangan
Manganaro
Manganelli
Manganello
Manganiello
Mangano
Mangaoang
Mangas
Mangat
Mangel
Mangels
Mangen
Manger
Manges
Mangham
Manghane
Mangiafico
Mangiamele
Mangiapane
Mangiaracina
Mangicavallo
Mangieri
Mangina
Mangine
Manginelli
Mangini
Mangino
Mangione
Mangis
Mangle
Manglona
Mango
Mangold
Mangon
Mangone
Mangram
Mangrich
Mangrum
Mangual
Mangubat
Mangum
Mangus
Manha
Manhardt
Manhart
Manheim
Mani
Mania
Maniace
Maniaci
Maniar
Maniatis
Manicchio
Maniccia
Manier
Manieri
Manifold
Manigault
Manigo
Manigold
Manikas
Manikowski
Manila
Manin
Manino
Manion
Manire
Manis
Maniscalco
Manista
Manivong
Manjarres
Manjarrez
Mank
Manka
Manke
Mankel
Manker
Mankey
Mankiewicz
Mankin
Mankins
Manko
Mankoski
Mankowski
Mankus
Manlangit
Manley
Manliguis
Manlito
Manlove
Manly
Mann
Manna
Mannan
Mannarino
Mannchen
Manne
Mannebach
Mannella
Mannello
Manner
Manners
Mannes
Manney
Mannheim
Mannheimer
Manni
Mannick
Mannie
Mannina
Mannine
Manning
Mannings
Mannino
Mannion
Mannis
Mannix
Manno
Mannon
Manns
Mannschreck
Manny
Mano
Manocchia
Manocchio
Manoi
Manokey
Manolakis
Manolis
Manon
Manoni
Manoogian
Manor
Manora
Manos
Manoso
Manous
Manozca
Manquero
Manring
Manrique
Manriquez
Manross
Manrriquez
Manry
Mans
Mansanares
Mansbach
Mansbridge
Manseau
Mansel
Mansell
Manser
Mansfield
Manship
Mansi
Mansir
Manske
Mansker
Mansmann
Mansmith
Manso
Manson
Mansour
Mansouri
Manspeaker
Mansukhani
Mansur
Mantano
Mantanona
Mante
Manteca
Mantegna
Mantel
Mantele
Mantell
Mantella
Mantelli
Manter
Manternach
Manteuffel
Mantey
Manthe
Manthei
Manthey
Mantia
Mantifel
Mantik
Mantilia
Mantilla
Mantini
Mantione
Mantis
Mantle
Manto
Manton
Mantooth
Mantsch
Mantuano
Mantyla
Mantz
Manual
Manuel
Manuele
Manuelito
Manuell
Manues
Manuia
Manus
Manusyants
Manvel
Manvelito
Manvelyan
Manville
Manwaring
Manwarren
Manweiler
Manwill
Many
Manygoats
Manylath
Manz
Manza
Manzanares
Manzanarez
Manzanero
Manzanilla
Manzano
Manzay
Manzella
Manzer
Manzi
Manzie
Manzione
Manzo
Manzone
Manzueta
Manzur
Mao
Maobi
Maohu
Maontesano
Mapa
Mapalo
Mapel
Mapes
Maphis
Maple
Maples
Mapp
Mapps
Mapston
Mapstone
Mapua
Maquis
Mar
Mara
Marabella
Marable
Maracle
Marade
Maradiaga
Marafioti
Maragh
Maragni
Maragno
Maraia
Marak
Maraldo
Marales
Marallo
Maran
Marana
Maranan
Maranda
Marander
Marandi
Marando
Marandola
Marangoni
Marani
Marano
Marante
Maranto
Marantz
Maranville
Maras
Marascalco
Marasciulo
Marasco
Marash
Marashi
Marashio
Marasigan
Maratos
Maratre
Maravilla
Marazas
Marazzi
Marbach
Marban
Marberry
Marble
Marbley
Marbray
Marbry
Marburger
Marbury
Marbus
Marbut
Marc
Marca
Marcaida
Marcano
Marcantel
Marcantonio
Marceau
Marceaux
Marcel
Marcelin
Marcelino
Marcell
Marcella
Marcelle
Marcelli
Marcellino
Marcello
Marcellus
Marcelynas
Marcet
Marcey
March
Marchak
Marchal
Marchaland
Marchall
Marchan
Marchand
Marchant
Marchbanks
Marchel
Marchell
Marchello
Marchena
Marchesano
Marchese
Marchesi
Marcheski
Marchessault
Marchesseault
Marchetta
Marchetti
Marchi
Marchiano
Marchio
Marchione
Marchionese
Marchionni
Marchiony
Marchiori
Marchitto
Marchizano
Marchman
Marchuk
Marci
Marcia
Marcial
Marciano
Marciante
Marciel
Marcil
Marcille
Marcin
Marcinek
Marciniak
Marcinka
Marcinkiewicz
Marcinko
Marcinkowski
Marcisak
Marcks
Marco
Marcoguisepp
Marcolina
Marcoline
Marcom
Marcon
Marcone
Marconi
Marconis
Marcos
Marcotrigiano
Marcott
Marcotte
Marcou
Marcoux
Marcrum
Marcucci
Marcum
Marcus
Marcusen
Marcussen
Marcy
Marczak
Marden
Marder
Mardesich
Mardini
Mardirosian
Mardirossian
Mardis
Mare
Maready
Marean
Marecki
Maree
Marek
Marello
Maren
Marenco
Marengo
Mareno
Marentes
Marentez
Marentis
Marer
Marero
Mares
Maresca
Maresco
Maresh
Maret
Marett
Maretti
Marevka
Marez
Marfil
Marflak
Margaitis
Margan
Margaret
Margaris
Margarita
Margaryan
Margason
Margel
Margerum
Margeson
Margheim
Margiotta
Margis
Margison
Margo
Margolies
Margolin
Margolis
Margosian
Margot
Margotta
Margraf
Margreiter
Marguardt
Marguez
Margulies
Margulis
Marhefka
Marhoefer
Mari
Maria
Mariacher
Marian
Mariani
Mariano
Marich
Marichalar
Maricich
Maricle
Marie
Mariello
Marien
Marier
Marietta
Maril
Marin
Marina
Marinacci
Marinaccio
Marinaro
Marinas
Marine
Marineau
Marinella
Marinelli
Marinello
Mariner
Marinero
Marines
Marinese
Marinez
Maring
Marini
Marinko
Marinkovic
Marino
Marinoni
Marinos
Marinucci
Mario
Marion
Marioni
Marionneaux
Mariotti
Maris
Mariscal
Mariska
Maritato
Maritn
Maritnez
Maritt
Marius
Marjan
Marjenhoff
Mark
Markakis
Markarian
Marke
Markee
Markegard
Markel
Markell
Marken
Marker
Markert
Markes
Market
Markette
Markevich
Markewich
Markey
Markgraf
Markham
Marki
Markie
Markiewicz
Markin
Marking
Markins
Markis
Markland
Markle
Markley
Marklund
Markman
Marko
Markoff
Markos
Markou
Markovich
Markovitz
Markow
Markowitz
Markowski
Markrof
Marks
Marksberry
Marksbury
Markson
Markstrom
Markt
Markum
Markunas
Markus
Markuson
Markve
Markwardt
Markway
Markwell
Markwood
Markworth
Marland
Marlar
Marlatt
Marlborough
Marlene
Marler
Marlett
Marlette
Marley
Marlin
Marling
Marlo
Marlor
Marlow
Marlowe
Marmas
Marmerchant
Marmie
Marmion
Marmo
Marmol
Marmolejo
Marmolejos
Marmon
Marn
Marnell
Marner
Marnett
Marney
Maro
Marocco
Marohl
Marohnic
Marois
Marola
Marold
Marolda
Marolf
Marolt
Maron
Marona
Marone
Maroney
Maronge
Maroni
Maroon
Marose
Marotta
Marotte
Marotti
Marotto
Marotz
Maroudas
Maroun
Marousek
Marovic
Marovich
Marozzi
Marple
Marples
Marquard
Marquardt
Marquart
Marque
Marquena
Marques
Marquess
Marquette
Marquez
Marquina
Marquis
Marquitz
Marr
Marra
Marrable
Marrano
Marrapese
Marrapodi
Marrara
Marrazzo
Marreel
Marrello
Marren
Marreo
Marrero
Marrett
Marrier
Marrietta
Marrin
Marrinan
Marriner
Marrington
Marrion
Marriot
Marriott
Marris
Marrison
Marro
Marroguin
Marron
Marrone
Marroquin
Marrotte
Marrow
Marrs
Marruffo
Marrufo
Marrujo
Marry
Mars
Marsac
Marsack
Marsala
Marsalis
Marsaw
Marsch
Marschall
Marschel
Marschke
Marsden
Marse
Marsee
Marseglia
Marseille
Marseilles
Marsek
Marsell
Marsella
Marsette
Marsh
Marsha
Marshak
Marshal
Marshalek
Marshall
Marshalsea
Marshbanks
Marshburn
Marshell
Marshman
Marsicek
Marsico
Marsiglia
Marsili
Marsingill
Marske
Marsland
Marso
Marsolais
Marsolek
Marson
Marstaller
Marsteller
Marsters
Marston
Marszalek
Mart
Marta
Martabano
Martain
Marte
Martel
Martell
Martella
Martellaro
Martelle
Martelles
Martelli
Martello
Marten
Marteney
Martenez
Martens
Martensen
Martenson
Marter
Martes
Martey
Marth
Martha
Marthaler
Marthe
Marti
Martian
Martiarena
Martich
Martie
Martiez
Martig
Martignago
Martillo
Martin
Martina
Martinas
Martinat
Martincic
Martindale
Martindelcamp
Martine
Martinea
Martineau
Martinek
Martinel
Martinell
Martinelli
Martines
Martinet
Martinetti
Martinetto
Martinex
Martinez
Martineze
Martini
Martinie
Martinis
Martiniz
Martinkus
Martino
Martinolli
Martinon
Martinov
Martins
Martinsen
Martinson
Martinsons
Martiny
Martinz
Martir
Martirano
Martire
Martis
Martischnig
Martling
Martnez
Marton
Martone
Martorana
Martorano
Martorell
Martorella
Martorelli
Martorello
Martos
Martowski
Marts
Martsolf
Martt
Martucci
Marturano
Marty
Martyn
Martyr
Martz
Maruca
Marucci
Maruco
Maruffo
Marugg
Marullo
Marum
Marumoto
Marungo
Marus
Marusak
Marusarz
Maruscak
Maruschak
Marushia
Marusiak
Maruska
Maruyama
Marvel
Marvier
Marville
Marvin
Marvray
Marwick
Marx
Marxen
Marxsen
Mary
Marye
Maryland
Maryott
Marz
Marzan
Marzano
Marze
Marzec
Marzella
Marzett
Marzette
Marzigliano
Marzili
Marzinske
Marzocchi
Marzolf
Marzullo
Mas
Masaitis
Masak
Masaki
Masar
Masaracchia
Masaya
Mascagni
Mascall
Mascarena
Mascarenas
Mascari
Mascaro
Mascetti
Masch
Maschak
Mascheck
Maschino
Maschio
Maschke
Maschmeyer
Masci
Mascia
Masciantonio
Mascio
Mascioli
Mascola
Mascolo
Mascorro
Mascot
Mascroft
Masden
Mase
Masek
Masell
Masella
Maselli
Masello
Masenten
Maser
Masero
Masey
Masgalas
Mash
Mashack
Mashak
Mashall
Mashaw
Mashburn
Mashek
Masher
Mashiah
Mashni
Mashore
Masi
Masias
Masiclat
Masiejczyk
Masiello
Masilko
Masin
Masincup
Masingale
Masini
Masino
Mask
Maskaly
Maske
Maskell
Masker
Maski
Maslak
Maslakowski
Maslanka
Maslen
Masley
Maslin
Maslonka
Masloski
Maslow
Maslowski
Maslowsky
Maslyn
Maso
Masom
Mason
Masone
Masoner
Masood
Masotti
Masoud
Masri
Mass
Massa
Massaglia
Massanelli
Massanet
Massaquoi
Massar
Massard
Massare
Massarelli
Massari
Massaro
Massart
Massay
Masse
Massed
Massee
Massei
Massella
Massena
Massenberg
Massenburg
Massengale
Massengill
Masser
Masseria
Massett
Massetti
Massey
Massi
Massiah
Massicotte
Massie
Massimino
Massimo
Massing
Massingale
Massingill
Massini
Massman
Massmann
Masso
Masson
Massoni
Massoud
Massucci
Massy
Mast
Mastalski
Mastel
Mastella
Masteller
Masten
Mastenbrook
Master
Mastera
Masterman
Masters
Masterson
Masterton
Mastin
Mastine
Maston
Mastoris
Mastrangelo
Mastrelli
Mastrianna
Mastrianni
Mastriano
Mastro
Mastrobuono
Mastrocola
Mastrocovi
Mastrogiovann
Mastroianni
Mastrolia
Mastromarino
Mastronardi
Mastropaolo
Mastropietro
Masturzo
Masucci
Masuda
Masudi
Masullo
Masunaga
Masupha
Masur
Masure
Masuyama
Masztal
Mata
Mataalii
Matacale
Mataka
Matakonis
Matalavage
Matalka
Matamoros
Matanane
Matar
Matarazzo
Matarese
Matarrita
Matas
Matava
Matayoshi
Matchen
Matchett
Matchette
Matczak
Mate
Mateen
Mateer
Mateiro
Mateja
Matejek
Matejka
Matelic
Matelich
Matelski
Maten
Mateo
Mateos
Mater
Matera
Matern
Materna
Matero
Mates
Matesic
Mateus
Matey
Math
Mathai
Mathal
Mathe
Matheis
Mathelier
Mathen
Mathena
Matheney
Mathenia
Matheny
Mather
Matherly
Mathern
Matherne
Mathers
Matherson
Mathery
Mathes
Matheson
Matheu
Matheus
Mathew
Mathewes
Mathews
Mathewson
Mathey
Mathia
Mathias
Mathiasen
Mathiason
Mathie
Mathies
Mathiesen
Mathieson
Mathieu
Mathiew
Mathis
Mathisen
Mathison
Mathony
Mathre
Mathson
Mathur
Mathurin
Mathus
Mathwich
Mathys
Matias
Matice
Matier
Matin
Matinez
Matis
Matise
Matison
Matkin
Matkins
Matko
Matkovic
Matkowski
Matkowsky
Matlack
Matley
Matlick
Matlin
Matlock
Matlow
Matney
Mato
Matonak
Matone
Matos
Matot
Matott
Matousek
Matranga
Matras
Matrejek
Matrey
Matrisciano
Matro
Matrone
Matros
Matsen
Matskin
Matsko
Matson
Matsoukas
Matsu
Matsubara
Matsuda
Matsuhara
Matsui
Matsuki
Matsumoto
Matsumura
Matsunaga
Matsuno
Matsuo
Matsuoka
Matsushima
Matsushita
Matsuura
Matsuzaki
Matt
Matta
Mattan
Mattas
Matte
Mattei
Matteis
Matten
Matteo
Matter
Mattera
Mattern
Matters
Matterson
Mattes
Matteson
Matteucci
Mattews
Mattey
Matthai
Matthees
Mattheis
Matthes
Matthew
Matthews
Matthewson
Matthey
Matthias
Matthies
Matthiesen
Matthis
Matthys
Mattia
Mattiace
Mattias
Mattice
Mattick
Mattie
Mattiello
Mattier
Mattila
Mattimoe
Mattina
Mattingley
Mattingly
Mattinson
Mattioli
Mattione
Mattis
Mattison
Mattix
Mattke
Mattler
Mattlin
Matto
Mattock
Mattocks
Matton
Mattoon
Mattos
Mattox
Matts
Mattsen
Mattsey
Mattson
Mattsson
Mattu
Matturro
Matty
Mattys
Matuck
Matuke
Matula
Matulewicz
Maturi
Matus
Matusek
Matuseski
Matushevsky
Matusiak
Matusiewicz
Matusik
Matuska
Matusz
Matuszak
Matuszek
Matuszeski
Matuszewski
Matute
Matya
Matyas
Matye
Matyi
Matysiak
Matz
Matza
Matzek
Matzen
Matzinger
Matzke
Mau
Mauceli
Mauceri
Mauch
Mauck
Maud
Maudlin
Mauer
Mauffray
Mauger
Maugeri
Maughan
Maughn
Mauk
Maul
Maulden
Mauldin
Maulding
Maule
Mauleon
Maulin
Maull
Mauller
Maulsby
Maultasch
Maultsby
Maun
Maune
Mauney
Maung
Maupin
Maupins
Maupredi
Maura
Mauracher
Maurais
Mauras
Maurer
Maurey
Maurice
Mauricio
Mauriello
Maurin
Mauritz
Maurizio
Mauro
Maurus
Maury
Maus
Mausbach
Mauser
Mauseth
Mausey
Maushardt
Mauson
Mauss
Mausser
Maust
Maute
Mauter
Mautino
Mautner
Mautone
Mautte
Mautz
Mauzey
Mauzy
Mavai
Maver
Maves
Mavins
Mavis
Mavity
Mavle
Mavraganis
Mavris
Mavro
Mavromatis
Mavropoulos
Maw
Mawhinney
Mawhorter
Mawk
Mawson
Mawyer
Max
Maxam
Maxberry
Maxcy
Maxedon
Maxell
Maxey
Maxfield
Maxham
Maxi
Maxie
Maxim
Maximo
Maxin
Maxon
Maxson
Maxton
Maxwell
May
Maya
Mayala
Mayall
Mayans
Mayard
Maybee
Mayben
Mayberry
Maybin
Maybrier
Maybury
Maycock
Maycumber
Mayden
Maydew
Maye
Mayeaux
Mayeda
Mayen
Mayenschein
Mayer
Mayerle
Mayers
Mayes
Mayeshiba
Mayeski
Mayette
Mayeux
Mayfield
Mayhall
Mayhan
Mayher
Mayhew
Mayhood
Mayhorn
Mayhue
Mayhugh
Mayland
Mayle
Maylone
Maymi
Maymon
Maynard
Mayne
Mayner
Maynerich
Maynes
Maynez
Maynor
Mayo
Mayoka
Mayol
Mayon
Mayone
Mayor
Mayoral
Mayoras
Mayorca
Mayorga
Mayotte
Mayou
Mayr
Mayrant
Mayrose
Mays
Mayse
Mayshack
Mayson
Maysonet
Mayton
Maytorena
Maytubby
Mayville
Maywalt
Mayweather
Maywood
Mayze
Mayzes
Maza
Mazanec
Mazar
Mazariego
Mazariegos
Maze
Mazell
Mazella
Mazer
Mazey
Maziarz
Mazierski
Mazikowski
Mazin
Mazingo
Mazion
Mazique
Mazo
Mazon
Mazor
Mazowieski
Mazuc
Mazuera
Mazuo
Mazur
Mazurek
Mazurk
Mazurkiewicz
Mazurowski
Mazy
Mazyck
Mazza
Mazzacano
Mazzaferro
Mazzanti
Mazzara
Mazzarella
Mazzariello
Mazzarino
Mazzawi
Mazze
Mazzei
Mazzella
Mazzeo
Mazzera
Mazzetti
Mazzie
Mazzillo
Mazzini
Mazzo
Mazzocco
Mazzola
Mazzone
Mazzoni
Mazzotta
Mazzuca
Mazzucco
Mazzurco
Mbamalu
Mbonu
Mc
Mcabee
Mcabier
Mcaboy
Mcadam
Mcadams
Mcadoo
Mcadory
Mcafee
Mcaferty
Mcaffee
Mcalarney
Mcalary
Mcaleer
Mcaleese
Mcalevy
Mcalexander
Mcalhaney
Mcalister
Mcall
Mcallen
Mcallister
Mcalmond
Mcaloon
Mcalphin
Mcalpin
Mcalpine
Mcalvain
Mcamis
Mcanallen
Mcanally
Mcanany
Mcanaw
Mcandrew
Mcandrews
Mcanelly
Mcaneny
Mcaninch
Mcannally
Mcanulty
Mcardell
Mcardle
Mcaree
Mcarthun
Mcarthur
Mcarthy
Mcartor
Mcaskill
Mcatee
Mcateer
Mcaulay
Mcauley
Mcauliffe
Mcauly
Mcausland
Mcaveney
Mcavoy
Mcbain
Mcbane
Mcbath
Mcbay
Mcbean
Mcbeath
Mcbee
Mcbeth
Mcbrady
Mcbratney
Mcbrayer
Mcbrearty
Mcbreen
Mcbride
Mcbrien
Mcbroom
Mcbroome
Mcbrown
Mcbryar
Mcbryde
Mcburnett
Mcburney
Mcburnie
Mcburrough
Mcburrows
Mccaa
Mccabe
Mccadams
Mccadden
Mccaddon
Mccade
Mccafferty
Mccaffery
Mccaffity
Mccaffree
Mccaffrey
Mccage
Mccaghren
Mccague
Mccahan
Mccahill
Mccaie
Mccaig
Mccain
Mccaine
Mccalanahan
Mccaleb
Mccalebb
Mccalister
Mccall
Mccalla
Mccallen
Mccalley
Mccallie
Mccallion
Mccallister
Mccallon
Mccallough
Mccallum
Mccallun
Mccally
Mccalman
Mccalment
Mccalmont
Mccalop
Mccalpane
Mccalpin
Mccalvin
Mccaman
Mccamant
Mccambridge
Mccament
Mccamey
Mccamish
Mccammack
Mccammon
Mccampbell
Mccamy
Mccan
Mccance
Mccandles
Mccandless
Mccandlish
Mccandliss
Mccandrew
Mccane
Mccanless
Mccann
Mccanna
Mccannon
Mccanse
Mccant
Mccants
Mccard
Mccardell
Mccardle
Mccarey
Mccargar
Mccargo
Mccarl
Mccarley
Mccarn
Mccarney
Mccarns
Mccarr
Mccarraher
Mccarrel
Mccarrell
Mccarren
Mccarrick
Mccarrol
Mccarroll
Mccarron
Mccarry
Mccarson
Mccart
Mccartan
Mccarte
Mccarter
Mccartha
Mccarther
Mccarthey
Mccarthy
Mccartin
Mccartney
Mccartt
Mccarty
Mccarver
Mccarvill
Mccarville
Mccarvy
Mccary
Mccash
Mccaskell
Mccaskey
Mccaskill
Mccaskin
Mccasland
Mccaslin
Mccaster
Mccastle
Mccathern
Mccathran
Mccatty
Mccaughan
Mccaughey
Mccaul
Mccauley
Mccaulley
Mccausland
Mccaw
Mccawley
Mccay
Mccelland
Mcchain
Mcchesney
Mcchristian
Mcchristion
Mcchriston
Mccier
Mcclafferty
Mcclaflin
Mcclaim
Mcclain
Mcclaine
Mcclair
Mcclallen
Mcclam
Mcclamma
Mcclammy
Mcclamroch
Mcclamy
Mcclanahan
Mcclanan
Mcclane
Mcclaney
Mcclaran
Mcclard
Mcclaren
Mcclarin
Mcclarnon
Mcclarty
Mcclary
Mcclaskey
Mcclatcher
Mcclatchey
Mcclaugherty
Mcclaughry
Mcclave
Mcclay
Mccleaf
Mcclean
Mcclearen
Mccleary
Mccleave
Mcclee
Mccleer
Mccleery
Mcclees
Mccleese
Mcclellan
Mcclelland
Mcclellon
Mcclement
Mcclenaghan
Mcclenahan
Mcclendon
Mcclenic
Mcclennan
Mcclenningham
Mcclennon
Mcclenny
Mcclenon
Mcclenton
Mcclenty
Mccleod
Mcclerkin
Mccleskey
Mcclester
Mccleve
Mccleveland
Mcclimans
Mcclimens
Mcclimon
Mccline
Mcclinsey
Mcclintic
Mcclintick
Mcclintock
Mcclinton
Mcclish
Mcclod
Mcclodden
Mccloe
Mcclory
Mccloskey
Mcclosky
Mccloud
Mccloude
Mccloudy
Mccloughan
Mcclour
Mccloy
Mcclucas
Mccluer
Mcclune
Mccluney
Mcclung
Mcclure
Mcclurg
Mcclurkan
Mcclurken
Mcclurkin
Mccluskey
Mcclusky
Mcclymonds
Mccoach
Mccoard
Mccoggle
Mccoid
Mccoil
Mccoin
Mccole
Mccolgan
Mccoll
Mccollam
Mccollester
Mccolley
Mccollin
Mccollins
Mccollister
Mccolloch
Mccollom
Mccollough
Mccollum
Mccolm
Mccolpin
Mccomack
Mccomas
Mccomb
Mccomber
Mccombie
Mccombs
Mccomis
Mccomish
Mccommon
Mccommons
Mccomsey
Mcconaghy
Mcconahay
Mcconahy
Mcconathy
Mcconaughy
Mcconchie
Mcconico
Mcconkey
Mcconn
Mcconnal
Mcconnaughey
Mcconnaughhay
Mcconnaughy
Mcconnel
Mcconnell
Mcconney
Mcconnico
Mcconomy
Mcconville
Mccoo
Mccooey
Mccook
Mccool
Mccoon
Mccoppin
Mccord
Mccorey
Mccorison
Mccorkell
Mccorkindale
Mccorkle
Mccormack
Mccormic
Mccormick
Mccormik
Mccornack
Mccorrison
Mccorry
Mccort
Mccorvey
Mccory
Mccosh
Mccosker
Mccoskey
Mccotter
Mccoubrey
Mccoulskey
Mccoun
Mccourt
Mccourtney
Mccovery
Mccowan
Mccowen
Mccowin
Mccown
Mccoy
Mccoyle
Mccra
Mccrabb
Mccracken
Mccracker
Mccrackin
Mccrady
Mccrae
Mccraig
Mccraight
Mccrain
Mccraken
Mccrane
Mccraney
Mccranie
Mccrary
Mccrate
Mccraven
Mccravy
Mccraw
Mccray
Mccrea
Mccreadie
Mccready
Mccreary
Mccredie
Mccree
Mccreedy
Mccreery
Mccreight
Mccreless
Mccright
Mccrimmon
Mccrimon
Mccrobie
Mccrohan
Mccrone
Mccrorey
Mccrory
Mccroskey
Mccrosky
Mccrossen
Mccrossin
Mccroy
Mccrudden
Mccrum
Mccrumb
Mccrystal
Mccuaig
Mccuan
Mccubbin
Mccubbins
Mccubrey
Mccue
Mccuen
Mccuien
Mccuin
Mccuistion
Mccuiston
Mcculla
Mccullagh
Mccullah
Mccullan
Mccullar
Mccullars
Mccullen
Mcculler
Mccullers
Mcculley
Mccullick
Mccullin
Mcculloch
Mccullock
Mccullogh
Mcculloh
Mccullom
Mccullon
Mccullors
Mccullough
Mccullum
Mccully
Mcculough
Mccumbee
Mccumber
Mccumbers
Mccumiskey
Mccune
Mccunn
Mccurdy
Mccure
Mccurine
Mccurley
Mccurren
Mccurry
Mccurtain
Mccurtis
Mccurty
Mccusker
Mccutchan
Mccutchen
Mccutcheon
Mcdade
Mcdaid
Mcdale
Mcdanel
Mcdaneld
Mcdanial
Mcdaniel
Mcdaniels
Mcdannald
Mcdannell
Mcdannold
Mcdargh
Mcdaries
Mcdaris
Mcdavid
Mcdavis
Mcdavitt
Mcday
Mcdearman
Mcdearmon
Mcdearmont
Mcdeavitt
Mcdermett
Mcdermid
Mcdermitt
Mcdermond
Mcdermott
Mcdevitt
Mcdewitt
Mcdiarmid
Mcdilda
Mcdill
Mcdivitt
Mcdoe
Mcdole
Mcdonagh
Mcdonal
Mcdonald
Mcdonalds
Mcdonel
Mcdonell
Mcdoniel
Mcdonnall
Mcdonnel
Mcdonnell
Mcdonough
Mcdorman
Mcdougal
Mcdougald
Mcdougall
Mcdougle
Mcdoulett
Mcdow
Mcdowall
Mcdowell
Mcduff
Mcduffee
Mcduffey
Mcduffie
Mcduffy
Mcdugle
Mcdunn
Mceachern
Mceachin
Mceachran
Mceachron
Mceaddy
Mceady
Mceathron
Mceirath
Mcelderry
Mceldowney
Mcelduff
Mcelfresh
Mcelhaney
Mcelhannon
Mcelhany
Mcelhattan
Mcelhenney
Mcelheny
Mcelhiney
Mcelhinney
Mcelhinny
Mcelhone
Mcelligott
Mcelmarry
Mcelmeel
Mcelmurry
Mcelmury
Mcelpraug
Mcelrath
Mcelravy
Mcelreath
Mcelreavy
Mcelroy
Mcelvain
Mcelvaine
Mcelvany
Mcelveen
Mcelvy
Mcelwain
Mcelwaine
Mcelwee
Mcelwine
Mcelyea
Mcenaney
Mcenany
Mcendarfer
Mceneny
Mcenery
Mceniry
Mcennis
Mcenroe
Mcentee
Mcentegart
Mcentire
Mcentyre
Mcerlean
Mceuen
Mcever
Mcevers
Mcevoy
Mcewan
Mcewen
Mcewin
Mcfadden
Mcfaddin
Mcfadin
Mcfadyen
Mcfall
Mcfalls
Mcfan
Mcfann
Mcfarlain
Mcfarlan
Mcfarland
Mcfarlane
Mcfarlen
Mcfarlin
Mcfarling
Mcfarren
Mcfate
Mcfatridge
Mcfatten
Mcfatter
Mcfaul
Mcfee
Mcfeeley
Mcfeely
Mcfeeters
Mcferran
Mcferren
Mcferrin
Mcferron
Mcfetridge
Mcfield
Mcfolley
Mcgaffee
Mcgafferty
Mcgaffey
Mcgaha
Mcgahan
Mcgahee
Mcgahen
Mcgahey
Mcgalliard
Mcgann
Mcgannon
Mcgarey
Mcgarity
Mcgarr
Mcgarrah
Mcgarraugh
Mcgarrell
Mcgarrigle
Mcgarrity
Mcgarry
Mcgartland
Mcgarvey
Mcgarvie
Mcgary
Mcgath
Mcgathy
Mcgaugh
Mcgaughan
Mcgaughey
Mcgaughy
Mcgauley
Mcgavin
Mcgavisk
Mcgavock
Mcgaw
Mcgeachy
Mcgeady
Mcgeary
Mcgee
Mcgeehan
Mcgeeney
Mcgeever
Mcgehee
Mcgeorge
Mcgeough
Mcgettigan
Mcghan
Mcghaney
Mcghay
Mcghee
Mcghehey
Mcghie
Mcghin
Mcghinnis
Mcgibbon
Mcgibboney
Mcgibney
Mcgiboney
Mcgilberry
Mcgill
Mcgillen
Mcgillicuddy
Mcgillis
Mcgillivray
Mcgilton
Mcgilvery
Mcgilvray
Mcginister
Mcginity
Mcginley
Mcginn
Mcginnes
Mcginness
Mcginnis
Mcginnity
Mcginty
Mcgirr
Mcgirt
Mcgivern
Mcgiveron
Mcgivney
Mcglade
Mcglamery
Mcglasson
Mcglathery
Mcglauflin
Mcglaughlin
Mcglaun
Mcglawn
Mcglew
Mcglinchey
Mcglinn
Mcglocklin
Mcglockton
Mcglohon
Mcgloin
Mcglon
Mcglone
Mcglory
Mcgloster
Mcglothen
Mcglothern
Mcglothian
Mcglothin
Mcglothlen
Mcglothlin
Mcglown
Mcglumphy
Mcglynn
Mcgoey
Mcgoff
Mcgohan
Mcgoldrick
Mcgonagle
Mcgonigal
Mcgonigle
Mcgonnell
Mcgoogan
Mcgoon
Mcgorry
Mcgory
Mcgougan
Mcgough
Mcgovern
Mcgowan
Mcgowen
Mcgowin
Mcgown
Mcgrade
Mcgrady
Mcgraff
Mcgrail
Mcgrain
Mcgranahan
Mcgrane
Mcgrann
Mcgranor
Mcgrant
Mcgraph
Mcgrapth
Mcgrath
Mcgraw
Mcgray
Mcgready
Mcgreal
Mcgreen
Mcgreevy
Mcgregor
Mcgregory
Mcgrevey
Mcgrew
Mcgriff
Mcgroarty
Mcgrogan
Mcgrone
Mcgrory
Mcgrotha
Mcgrotty
Mcgruder
Mcgrue
Mcguckin
Mcgue
Mcguff
Mcguffee
Mcguffey
Mcguffie
Mcguffin
Mcgugin
Mcguigan
Mcguin
Mcguiness
Mcguinn
Mcguinnes
Mcguinness
Mcguire
Mcguirk
Mcguirl
Mcguirt
Mcgunagle
Mcgunnigle
Mcgunnis
Mcgurie
Mcgurk
Mcgurl
Mcgurn
Mcgurr
Mcgurren
Mcguyer
Mcgwier
Mcgwin
Mchaffie
Mchale
Mchalffey
Mchan
Mchaney
Mchardy
Mchargue
Mchattie
Mchendry
Mchenry
Mchone
Mchorse
Mchugh
Mchughes
Mcie
Mciff
Mcilhinney
Mcillwain
Mcilrath
Mcilroy
Mciltrot
Mcilvain
Mcilvaine
Mcilvenny
Mcilwain
Mcilwaine
Mcilwraith
Mcinally
Mcindoe
Mcinerney
Mcinerny
Mcinnes
Mcinnis
Mcinnish
Mcinroy
Mcintee
Mcintire
Mcintosh
Mcintrye
Mcinture
Mcinturf
Mcinturff
Mcintyde
Mcintyre
Mcinvale
Mcirvin
Mcisaac
Mciver
Mcivor
Mciwraith
Mcjunkin
Mcjunkins
Mckague
Mckahan
Mckaig
Mckain
Mckale
Mckamey
Mckamie
Mckane
Mckanic
Mckaskle
Mckasson
Mckaughan
Mckay
Mckeag
Mckeague
Mckean
Mckeand
Mckeane
Mckearin
Mckearney
Mckechnie
Mckee
Mckeegan
Mckeehan
Mckeel
Mckeeman
Mckeen
Mckeever
Mckeighan
Mckeirnan
Mckeithan
Mckeithen
Mckell
Mckellan
Mckellar
Mckeller
Mckellip
Mckellips
Mckellop
Mckelphin
Mckelvey
Mckelvie
Mckelvin
Mckelvy
Mckemie
Mcken
Mckendall
Mckendree
Mckendrick
Mckendry
Mckenize
Mckenley
Mckenna
Mckennan
Mckenney
Mckennie
Mckennon
Mckenny
Mckennzie
Mckenrick
Mckensie
Mckentie
Mckenty
Mckenzie
Mckenzy
Mckeon
Mckeone
Mckeown
Mckercher
Mckerchie
Mckerley
Mckerlie
Mckern
Mckernan
Mckernin
Mckerrow
Mckesson
Mckethan
Mckever
Mckevitt
Mckew
Mckewen
Mckey
Mckibben
Mckibbens
Mckibbin
Mckibbon
Mckiddy
Mckie
Mckiernan
Mckillip
Mckillips
Mckillop
Mckim
Mckimley
Mckimmy
Mckin
Mckindra
Mckines
Mckiney
Mckinlay
Mckinley
Mckinna
Mckinnell
Mckinney
Mckinnie
Mckinnies
Mckinnis
Mckinnon
Mckinny
Mckinsey
Mckinstry
Mckinzey
Mckinzie
Mckinzy
Mckirgan
Mckirryher
Mckissack
Mckissic
Mckissick
Mckisson
Mckitrick
Mckittrick
Mckiver
Mcklveen
Mckneely
Mcknight
Mckoan
Mckone
Mckoon
Mckosky
Mckouen
Mckowen
Mckown
Mckoy
Mckray
Mckune
Mckusick
Mckusker
Mclachlan
Mclaen
Mclafferty
Mclagan
Mclain
Mclaine
Mclaird
Mclamb
Mclamore
Mclanahan
Mclane
Mclaney
Mclaren
Mclarney
Mclarty
Mclatchy
Mclauchlen
Mclauchlin
Mclaughin
Mclaughlan
Mclaughlin
Mclauglin
Mclauren
Mclaurin
Mclaurine
Mclavrin
Mclawhorn
Mclaws
Mclay
Mclead
Mclean
Mclear
Mclearan
Mcleary
Mclee
Mclees
Mcleese
Mcleish
Mcleland
Mclellan
Mclelland
Mclemore
Mclendon
Mclennan
Mclennon
Mcleod
Mcleon
Mcleoud
Mclernon
Mcleroy
Mclerran
Mcleskey
Mclester
Mclilly
Mclin
Mcloone
Mcloud
Mcloughlin
Mclouth
Mcloy
Mclucas
Mcluckie
Mcluen
Mclure
Mclyman
Mcmackin
Mcmahan
Mcmahen
Mcmahill
Mcmahon
Mcmain
Mcmains
Mcmaken
Mcmakin
Mcmanamon
Mcmanamy
Mcmanaway
Mcmanemy
Mcmanigal
Mcmanis
Mcmann
Mcmannus
Mcmanuis
Mcmanus
Mcmarlin
Mcmartin
Mcmaster
Mcmasters
Mcmath
Mcmeans
Mcmeekin
Mcmeel
Mcmeen
Mcmellen
Mcmenamin
Mcmenamy
Mcmenimen
Mcmenomy
Mcmichael
Mcmicheal
Mcmickell
Mcmickle
Mcmikle
Mcmillan
Mcmillen
Mcmilleon
Mcmiller
Mcmilliam
Mcmillian
Mcmillin
Mcmillion
Mcmillon
Mcmina
Mcmindes
Mcminn
Mcmonagle
Mcmonigle
Mcmorran
Mcmorries
Mcmorris
Mcmorrow
Mcmulen
Mcmullan
Mcmullen
Mcmullin
Mcmullins
Mcmunn
Mcmurdie
Mcmurdo
Mcmurphy
Mcmurray
Mcmurrey
Mcmurrin
Mcmurry
Mcmurtrey
Mcmurtrie
Mcmurtry
Mcmutry
Mcnab
Mcnabb
Mcnail
Mcnair
Mcnairy
Mcnally
Mcnamar
Mcnamara
Mcnamee
Mcnamer
Mcnaney
Mcnany
Mcnary
Mcnatt
Mcnaught
Mcnaughton
Mcnay
Mcnayr
Mcneal
Mcnealey
Mcnealy
Mcnear
Mcneary
Mcnease
Mcnee
Mcneece
Mcneel
Mcneeley
Mcneely
Mcneer
Mcnees
Mcneese
Mcneff
Mcneil
Mcneill
Mcneilly
Mcneish
Mcnelis
Mcnell
Mcnelley
Mcnellie
Mcnellis
Mcnelly
Mcnemar
Mcneme
Mcnerney
Mcnertney
Mcnespey
Mcnett
Mcnevin
Mcnew
Mcnichol
Mcnicholas
Mcnichols
Mcnickle
Mcnicol
Mcnicoll
Mcniel
Mcniell
Mcniff
Mcnight
Mcninch
Mcnish
Mcnitt
Mcnolty
Mcnorton
Mcnuh
Mcnulty
Mcnurlen
Mcnutt
Mcnutty
Mcomber
Mconnell
Mcowen
Mcoy
Mcpadden
Mcparland
Mcpartland
Mcpartlin
Mcpeak
Mcpeake
Mcpeck
Mcpeek
Mcpeters
Mcphail
Mcphan
Mcpharlane
Mcphatter
Mcphaul
Mcphearson
Mcphee
Mcpheeters
Mcpheron
Mcpherren
Mcpherson
Mcphetridge
Mcphie
Mcphillips
Mcpike
Mcquade
Mcquage
Mcquaid
Mcquaide
Mcquaig
Mcquain
Mcquarrie
Mcquary
Mcquay
Mcqueary
Mcqueen
Mcqueeney
Mcqueeny
Mcquerry
Mcquesten
Mcquiddy
Mcquigg
Mcquiggan
Mcquilkin
Mcquillan
Mcquillen
Mcquiller
Mcquilliams
Mcquinn
Mcquire
Mcquirk
Mcquirter
Mcquistion
Mcquiston
Mcquitty
Mcquown
Mcrae
Mcraney
Mcrary
Mcratt
Mcraven
Mcravin
Mcray
Mcrea
Mcreath
Mcredmond
Mcree
Mcrenolds
Mcreynolds
Mcright
Mcrill
Mcritchie
Mcrobbie
Mcroberts
Mcrorie
Mcroy
Mcroyal
Mcshan
Mcshane
Mcsharry
Mcshaw
Mcshea
Mcsherry
Mcsorley
Mcspadden
Mcsparin
Mcsparren
Mcspedon
Mcspirit
Mcstay
Mcswain
Mcsween
Mcsweeney
Mcsweeny
Mcswiggan
Mctaggart
Mctague
Mctarnaghan
Mctee
Mcteer
Mcthay
Mcthige
Mcthune
Mctier
Mctiernan
Mctighe
Mctigue
Mctush
Mcumber
Mcvaigh
Mcvay
Mcvea
Mcvean
Mcveigh
Mcvenes
Mcvey
Mcvicar
Mcvicker
Mcvinney
Mcvoy
Mcwade
Mcwain
Mcwalters
Mcward
Mcwaters
Mcwatters
Mcwayne
Mcweeney
Mcwells
Mcwethy
Mcwherter
Mcwhinney
Mcwhinnie
Mcwhirt
Mcwhirter
Mcwhite
Mcwhorter
Mcwilliam
Mcwilliams
Mcwilson
Mcwright
Mczeal
Me
Meabon
Meach
Meacham
Meachem
Meachen
Meachum
Mead
Meade
Meaden
Meader
Meaders
Meador
Meadors
Meadow
Meadowcroft
Meadows
Meads
Meadville
Meager
Meagher
Meahl
Meaker
Meakin
Mealer
Mealey
Mealing
Mealor
Meals
Mealy
Mean
Meaney
Meanor
Means
Meany
Meara
Meardon
Meares
Mearing
Mearns
Mears
Mearse
Meas
Mease
Measeck
Measheaw
Measom
Meason
Meath
Meaux
Meazell
Mebane
Mebus
Mecannic
Mecardo
Mecca
Meccia
Mech
Mecham
Mechanic
Meche
Mechem
Mechler
Mechling
Mecias
Meck
Meckel
Meckes
Meckler
Meckley
Meconi
Mecum
Meczywor
Medak
Medal
Medalion
Medanich
Medaries
Medas
Medawar
Medbery
Medcalf
Meddaugh
Medders
Meddock
Mede
Medearis
Medeiras
Medeiros
Medel
Medell
Medellin
Medema
Meder
Mederios
Medero
Mederos
Medez
Medford
Medhus
Medi
Media
Median
Mediano
Mediate
Medich
Medici
Medicine
Medick
Medico
Medicus
Medieros
Medill
Medin
Medina
Medine
Medinger
Medino
Medious
Meditz
Medland
Medlar
Medlen
Medler
Medley
Medlin
Medling
Medlock
Mednick
Mednis
Medoff
Medora
Medosch
Medovich
Medows
Medoza
Medrano
Medsker
Meduna
Medure
Medus
Medvec
Medved
Mee
Meece
Meech
Meecham
Meeder
Meeds
Meegan
Meehan
Meehl
Meehleder
Meek
Meeker
Meekins
Meeks
Meeler
Meemken
Meenach
Meenan
Meer
Meerdink
Meeroff
Meers
Mees
Meese
Meeske
Meester
Meeter
Meetze
Meeuwsen
Mefferd
Meffert
Mefford
Mega
Megahan
Megan
Megeath
Megee
Meger
Meggers
Meggerson
Meggett
Megginson
Meggison
Meggitt
Meggs
Megia
Megill
Meginnes
Meginnis
Megivern
Meglio
Megna
Mego
Megown
Megrabyan
Megraw
Mehaffey
Mehaffy
Mehalic
Mehalko
Mehall
Mehan
Meharg
Meharry
Mehdi
Mehdizadeh
Mehelich
Mehis
Mehl
Mehle
Mehler
Mehlhaff
Mehlig
Mehling
Mehlman
Mehner
Mehok
Meholick
Mehr
Mehrens
Mehrer
Mehrhoff
Mehring
Mehringer
Mehrotra
Mehrtens
Mehserle
Mehta
Mehtala
Mehtani
Mei
Meidinger
Meidl
Meidlinger
Meier
Meierhofer
Meierotto
Meiers
Meigel
Meiggs
Meighan
Meighen
Meigs
Meihofer
Meikle
Meil
Meile
Meiler
Meilleur
Mein
Meinberg
Meinders
Meinecke
Meineke
Meinel
Meinen
Meinerding
Meiners
Meinershagen
Meinert
Meinhard
Meinhardt
Meinhart
Meininger
Meinke
Meinsen
Meints
Meinzer
Meir
Meireles
Meirick
Meis
Meisch
Meise
Meisel
Meisels
Meisenburg
Meisenheimer
Meiser
Meisinger
Meisler
Meisner
Meiss
Meissner
Meiste
Meister
Meitner
Meitz
Meitzler
Meixelberger
Meixner
Meja
Mejia
Mejias
Mejorado
Mekee
Mekeel
Mekonis
Mekus
Melady
Melahn
Melamed
Melancon
Meland
Melander
Melandez
Melanson
Melara
Melaro
Melaun
Melber
Melberg
Melbert
Melbourne
Melby
Melbye
Melcer
Melcher
Melchert
Melchin
Melching
Melchior
Melchiori
Melchiorre
Melchor
Meldahl
Melder
Meldrum
Mele
Melear
Melecio
Meleen
Melen
Melena
Melencamp
Melendes
Melendez
Melendres
Melendrez
Melendy
Meleo
Meler
Melero
Meleski
Meley
Melfi
Melford
Melgaard
Melgar
Melgarejo
Melgoza
Melhorn
Meli
Melia
Melian
Melich
Melichar
Melick
Melikian
Melikyan
Melillo
Melin
Meline
Meling
Melino
Melis
Melish
Melito
Melius
Melkonian
Mell
Mella
Mellado
Mellady
Mellage
Melland
Mellard
Mellas
Mellberg
Melle
Mellecker
Mellekas
Mellema
Mellen
Mellencamp
Mellendorf
Mellenthin
Meller
Mellerson
Mellett
Melley
Mellgren
Mellick
Mellie
Melliere
Mellin
Melling
Mellinger
Mellis
Mellish
Mellison
Mello
Mellom
Mellon
Mellor
Mellors
Mellos
Mellott
Mellow
Melloy
Mells
Melman
Melnick
Melnik
Melnyk
Melo
Meloan
Meloche
Melochick
Melodia
Melody
Melone
Melonson
Melot
Melott
Meloy
Melquist
Melrose
Melroy
Melser
Melsheimer
Melso
Melson
Melstrom
Melter
Melton
Meltz
Meltzer
Meltzner
Melugin
Melusky
Meluso
Melve
Melville
Melvin
Melzer
Members
Membreno
Memmer
Memmo
Memmott
Memo
Memolo
Memory
Memos
Mems
Men
Mena
Menaker
Menapace
Menard
Menas
Menasco
Mencer
Mench
Menchaca
Menchavez
Menchen
Menches
Menchu
Mencia
Menck
Mencke
Mencl
Mency
Mend
Mende
Mendel
Mendell
Mendelowitz
Mendelsohn
Mendelson
Menden
Mendenhall
Mender
Mendes
Mendesa
Mendez
Mendia
Mendias
Mendiaz
Mendibles
Mendicino
Mendieta
Mendillo
Mendiola
Mendivel
Mendivil
Mendizabal
Mendler
Mendoca
Mendola
Mendolia
Mendonca
Mendonsa
Mendosa
Mendoza
Mendrala
Mendrin
Mends
Mendyk
Meneal
Menear
Menedez
Meneely
Menees
Menefee
Menefield
Meneley
Menendez
Menes
Meneses
Menesez
Menette
Meneus
Menez
Menezes
Meng
Mengarelli
Menge
Mengel
Menger
Menges
Menghini
Mengle
Mengsteab
Mengwasser
Menhennett
Menier
Menietto
Menifee
Menino
Menist
Menitz
Menjares
Menjes
Menjiva
Menjivar
Menk
Menke
Menken
Menkin
Menlove
Menn
Menna
Menne
Mennecke
Mennella
Mennen
Mennenga
Menner
Mennie
Mennig
Menning
Menninger
Meno
Menon
Menoni
Menor
Menotti
Menousek
Mensah
Mensalvas
Mensch
Mense
Mensen
Menser
Mensi
Mensick
Mensik
Mensing
Mensinger
Menso
Menson
Mente
Mentel
Menter
Mentgen
Mention
Mentis
Mentkowski
Mentnech
Mento
Menton
Mentz
Mentzel
Mentzer
Menucci
Menuey
Menz
Menze
Menzel
Menzella
Menzer
Menzie
Menzies
Meo
Meola
Mera
Merales
Merana
Merancio
Meranda
Merando
Merante
Meranto
Meras
Merati
Meray
Meraz
Merbaum
Mercadante
Mercado
Mercando
Mercante
Mercardo
Merced
Mercedes
Merceir
Mercer
Merchant
Merchen
Mercier
Mercik
Merck
Merckling
Mercure
Mercuri
Mercurio
Mercury
Mercy
Merdian
Meredith
Merel
Merenda
Merendino
Mereno
Meres
Merette
Merfeld
Merganthaler
Mergel
Mergen
Mergenthaler
Mergist
Merhar
Merica
Merical
Merickel
Mericle
Merida
Merideth
Meridieth
Meridith
Merila
Merilos
Merine
Mering
Meringolo
Merino
Merisier
Merithew
Meritt
Meriweather
Meriwether
Merk
Merkel
Merker
Merkerson
Merkey
Merkl
Merkle
Merklein
Merkley
Merklin
Merkling
Merkowitz
Merksamer
Merkt
Merkwan
Merl
Merlain
Merlan
Merle
Merles
Merlette
Merli
Merlin
Merling
Merlini
Merlino
Merlo
Merlos
Mermelstein
Mermis
Merna
Merner
Mernin
Mero
Merola
Merone
Meroney
Merow
Merrbach
Merrell
Merren
Merrett
Merriam
Merrick
Merrifield
Merrigan
Merrih
Merrihew
Merril
Merrill
Merrills
Merriman
Merring
Merrion
Merriott
Merrit
Merrithew
Merritt
Merritts
Merriweather
Merriwether
Merrow
Merry
Merryman
Merryweather
Mersch
Merschman
Merseal
Mersereau
Mershon
Mersinger
Mersman
Merson
Merta
Mertel
Merten
Mertens
Mertes
Merthie
Mertine
Mertins
Merton
Mertz
Mervin
Mervine
Mervis
Mervyn
Merwin
Mery
Meryman
Merz
Merzig
Merzlak
Mesa
Mesaros
Mesch
Mescher
Meschino
Meschke
Mesdaq
Mesecar
Mesecher
Mesenbring
Mesenbrink
Meserole
Meserve
Meservey
Meservy
Meshanko
Meshell
Meshew
Meshyock
Mesi
Mesia
Mesias
Mesich
Mesick
Mesidor
Mesina
Mesiona
Mesiti
Meske
Mesker
Meskill
Mesko
Mesler
Mesmer
Mesoloras
Mespelt
Mesplay
Mesquita
Mesrobian
Mess
Messa
Messamore
Messan
Messana
Messano
Messel
Messenger
Messer
Messerli
Messerly
Messerschmidt
Messersmith
Messervy
Messey
Messick
Messier
Messina
Messineo
Messing
Messinger
Messler
Messman
Messmer
Messmore
Messner
Messore
Mesta
Mestad
Mestanza
Mestas
Mestayer
Mestemacher
Mester
Mesteth
Mestler
Mestre
Mestrovich
Meszaros
Metallo
Metaxas
Metayer
Metcalf
Metcalfe
Metchikoff
Meteer
Metelko
Metellus
Metelus
Metenosky
Meter
Metevelis
Metevia
Metevier
Metge
Meth
Methe
Metheney
Metheny
Metherell
Methot
Methven
Methvin
Metia
Metier
Metil
Metivier
Metler
Metos
Metott
Metoxen
Metoyer
Metrick
Metro
Metroka
Metropoulos
Metsker
Metta
Mette
Mettee
Mettenburg
Metter
Metters
Mettert
Mettig
Mettille
Metting
Mettle
Mettlen
Mettler
Mettling
Metts
Metty
Metz
Metzel
Metzer
Metzga
Metzgar
Metzger
Metzinger
Metzker
Metzler
Metzner
Meua
Meucci
Meulemans
Meuler
Meuller
Meullion
Meunier
Meurer
Meurin
Meury
Meusa
Meuse
Meusel
Meuser
Mevers
Mevis
Mew
Mewborn
Mewbourn
Mewes
Mews
Mexicano
Mey
Meydid
Meyer
Meyerhoefer
Meyerhofer
Meyerhoff
Meyerhoffer
Meyering
Meyerman
Meyerott
Meyerowitz
Meyers
Meyerson
Meyette
Meylor
Meyn
Meynard
Meysembourg
Meza
Mezera
Mezey
Mezick
Mezo
Mezquita
Mezydlo
Mezza
Mezzanotte
Mezzatesta
Mezzenga
Mezzina
Mezzinni
Mguyen
Mhoon
Miah
Miano
Miao
Mias
Miazga
Micale
Micali
Micalizzi
Micallef
Micari
Micciche
Miccio
Micco
Micek
Miceli
Micha
Michael
Michaeli
Michaelis
Michaels
Michaelsen
Michaelson
Michal
Michalak
Michalczik
Michalec
Michalek
Michalenko
Michales
Michalicek
Michalik
Michalke
Michalowski
Michals
Michalski
Michand
Michard
Michaud
Michaux
Michavd
Micheal
Micheals
Michealson
Micheau
Michel
Michela
Michele
Michelena
Michelet
Micheletti
Michelfelder
Micheli
Michelin
Michelini
Michell
Michelle
Michelli
Michello
Michelman
Michelotti
Michels
Michelsen
Michelson
Michelstein
Michener
Michetti
Michie
Michieli
Michienzi
Michioka
Michitsch
Michl
Michlich
Michlin
Michna
Michniak
Michno
Michocki
Michon
Michonski
Mick
Mickel
Mickelberry
Mickell
Mickels
Mickelsen
Mickelson
Mickenheim
Mickens
Mickey
Mickiewicz
Mickle
Mickleberry
Mickler
Mickles
Mickley
Micklos
Mickolick
Mickonis
Micks
Mickulskis
Mickus
Miclette
Microni
Micthell
Micucci
Midcap
Middaugh
Midden
Middendorf
Middents
Middlebrook
Middlebrooks
Middlekauff
Middlemiss
Middlesworth
Middleton
Middough
Midget
Midgett
Midgette
Midgley
Midkiff
Midthun
Midura
Midy
Midyett
Miears
Mieczkowski
Miecznikowski
Miedema
Miehe
Mielcarek
Mielcarz
Mielczarek
Miele
Mieles
Mielke
Mielkie
Mielnicki
Mieloszyk
Mielsch
Miene
Mientka
Mier
Miera
Mieras
Mierau
Mierez
Miernicki
Miernik
Mierow
Miers
Mierzejewski
Mierzwa
Mierzwiak
Mierzwinski
Miesch
Miesen
Miesner
Miesse
Miessler
Miessner
Mieszala
Mieth
Mietus
Mifflin
Mifsud
Miga
Migdal
Miggins
Miggo
Mighty
Migl
Migliaccio
Migliore
Migliori
Migliorisi
Miglorie
Mignano
Migneault
Mignogna
Mignone
Mignot
Miguel
Migues
Miguez
Mihaila
Mihal
Mihalak
Mihalchik
Mihalco
Mihalek
Mihaliak
Mihalick
Mihalik
Mihalios
Mihalko
Mihalkovic
Mihaly
Mihara
Mihatsch
Mihelcic
Mihelic
Mihelich
Mihlfeld
Mihm
Mihok
Mihor
Mihovk
Mijangos
Mijares
Mika
Mikami
Mikasa
Mike
Mikel
Mikell
Mikels
Mikelsen
Mikelson
Miker
Mikes
Mikesell
Mikeska
Mikez
Mikhaiel
Mikhail
Mikita
Mikkelsen
Mikkelson
Mikko
Mikkola
Miklas
Mikler
Mikles
Miklitz
Miklos
Miko
Mikola
Mikolajczak
Mikolajczyk
Mikolon
Mikos
Mikota
Mikovec
Mikowski
Mikrot
Mikrut
Mikula
Mikulak
Mikulec
Mikulecky
Mikulich
Mikulski
Mikus
Mikuszewski
Mila
Milak
Milam
Milan
Miland
Milanes
Milanese
Milanesi
Milani
Milano
Milanowski
Milar
Milardo
Milare
Milas
Milazzo
Milbauer
Milberger
Milbert
Milbourn
Milbourne
Milbradt
Milbrandt
Milbrath
Milbrett
Milbrodt
Milburn
Milbury
Milby
Milch
Milcher
Mildenberger
Mildenhall
Mildenstein
Milder
Milderberger
Mildon
Mildred
Mildren
Mildrum
Mile
Mileham
Milek
Milelr
Miler
Milera
Miles
Mileski
Mileti
Milette
Milewski
Miley
Milfeld
Milford
Milfort
Milham
Milhoan
Milholland
Milhorn
Milhous
Milhouse
Milian
Milich
Milici
Milillo
Milin
Milinazzo
Milionis
Militano
Militante
Milite
Militello
Milito
Milius
Milke
Milkent
Milkey
Milkovich
Milkowski
Milks
Mill
Milla
Millage
Millam
Millan
Milland
Millar
Millard
Millare
Millay
Millberg
Millbern
Millbrand
Mille
Millea
Milledge
Millen
Millender
Millener
Miller
Millerbernd
Millerd
Millerr
Millers
Milles
Milleson
Millet
Millett
Millette
Milley
Millhiser
Millholland
Millhouse
Millian
Milliard
Millican
Millich
Millick
Millie
Millien
Millier
Milligan
Millikan
Milliken
Millikin
Millimaki
Milliman
Millin
Milliner
Milling
Millings
Millington
Millinor
Million
Milliren
Milliron
Millis
Millison
Millisor
Millman
Millner
Millon
Millonzi
Millora
Millot
Millott
Milloway
Milloy
Millraney
Mills
Millsap
Millsaps
Millson
Millspaugh
Millstead
Millstein
Millward
Millwee
Millwood
Milly
Milman
Milne
Milner
Milnes
Milnik
Milnor
Milo
Milon
Milonas
Milone
Milord
Milos
Milosch
Milosevic
Milosevich
Milot
Milota
Milovich
Milroy
Milsap
Milsaps
Milson
Milstead
Milstein
Milster
Milteer
Miltenberger
Miltner
Milton
Miltz
Milum
Milush
Milward
Milwee
Milz
Mimaki
Mimbs
Mimes
Mimis
Mimms
Mimnaugh
Mimozo
Mims
Min
Mina
Minaai
Minacci
Minahan
Minalga
Minar
Minarcik
Minarcin
Minard
Minardi
Minardo
Minari
Minarik
Minas
Minasian
Minassian
Minato
Minatra
Minaya
Mince
Mincer
Mincey
Minch
Minchella
Mincher
Minchew
Minchey
Minchow
Minckler
Mincks
Mincy
Mindell
Minden
Minder
Minderman
Mindingall
Mineah
Minear
Mineau
Minecci
Mineconzo
Minehan
Minehart
Minella
Minelli
Mineo
Miner
Minerd
Minerich
Minero
Miners
Minert
Minerva
Minervini
Minery
Mines
Minette
Minford
Ming
Minge
Mingee
Minger
Minges
Mingione
Mingioni
Mingle
Mingledorff
Mingo
Mingrone
Mings
Mingus
Minhas
Mini
Miniard
Minic
Minich
Minichiello
Minick
Minicozzi
Minicucci
Minier
Minifield
Minihan
Minihane
Mininger
Minion
Minish
Minissale
Minister
Miniuk
Minium
Minix
Minjares
Minjarez
Mink
Minkel
Minkin
Minkins
Minkler
Minkoff
Minkowitz
Minks
Minn
Minnaert
Minnatee
Minnehan
Minnema
Minner
Minnerly
Minneweather
Minney
Minnich
Minnick
Minnie
Minniear
Minniefield
Minnier
Minnifield
Minning
Minnis
Minniti
Minnix
Minns
Mino
Minock
Minogue
Minon
Minor
Minors
Minot
Minott
Minotti
Minozzi
Minrod
Mins
Minshall
Minshew
Minskey
Minson
Minster
Minteer
Minten
Minter
Mintey
Mintken
Minto
Minton
Mintor
Mintos
Mintreas
Minturn
Minty
Mintz
Mintzer
Minucci
Minugh
Minus
Minutillo
Minvielle
Minyard
Minzel
Minzenberger
Minzenmayer
Minzy
Mio
Mioduszewski
Miolen
Mione
Miosek
Miosky
Miotke
Miquel
Miquelon
Mir
Mira
Mirabal
Mirabella
Mirabelli
Mirabile
Mirabito
Miracle
Miraflores
Mirafuentes
Miraglia
Miralles
Miramon
Miramontes
Miramontez
Miran
Miranda
Mirando
Mirante
Mirao
Mirarchi
Miras
Miravalle
Mirbaha
Mirchandani
Mire
Mireles
Mirelez
Mires
Mirich
Mirick
Miricle
Miriello
Mirisola
Mirjah
Mirkovich
Mirles
Mirman
Mirmow
Miro
Miron
Mirr
Mirra
Mirsch
Mirsky
Mirto
Mirza
Mirzadeh
Mis
Misasi
Miscavage
Misch
Mischel
Mischke
Mischler
Mischnick
Mischo
Miscione
Miscoe
Miscovich
Misek
Misemer
Misener
Misenheimer
Misenhimer
Misenti
Miser
Misercola
Miserendino
Misfeldt
Mish
Mishar
Mishaw
Mishkin
Mishler
Mishoe
Mishou
Mishra
Mishulouin
Mishulovin
Misiak
Misiaszek
Misiewicz
Misik
Miska
Miske
Miskell
Miskelly
Miskiewicz
Miskin
Miskinis
Misko
Miskovich
Misluk
Mismit
Misner
Misnick
Misove
Misra
Misrahi
Miss
Missel
Missey
Missildine
Missler
Mister
Mistler
Mistretta
Mistrot
Mistry
Misty
Misumi
Misura
Misuraca
Mita
Mital
Mitani
Mitch
Mitcham
Mitchan
Mitchel
Mitchell
Mitchelle
Mitcheltree
Mitchem
Mitchen
Mitchener
Mitchiner
Mitchler
Mitchum
Mitchusson
Mith
Mithani
Mithcell
Mithell
Mitkowski
Mitman
Mitnick
Mitra
Mitrani
Mitri
Mitro
Mitsakos
Mitsch
Mitschelen
Mitschke
Mitsdarffer
Mitsuda
Mittag
Mittan
Mittchell
Mittelman
Mittelstadt
Mittelstaedt
Mittelsteadt
Mittelstedt
Mitten
Mittendorf
Mitter
Mittiga
Mittleman
Mittler
Mittlestadt
Mittman
Mitton
Mitts
Mitzel
Mitzner
Miu
Miura
Miville
Mivshek
Mix
Mixdorf
Mixer
Mixon
Mixson
Miya
Miyagawa
Miyagi
Miyagishima
Miyahara
Miyahira
Miyake
Miyamoto
Miyamura
Miyanaga
Miyao
Miyares
Miyasaka
Miyasaki
Miyasato
Miyashiro
Miyashita
Miyata
Miyataki
Miyazaki
Miyose
Miyoshi
Mize
Mizee
Mizell
Mizelle
Mizenko
Mizer
Mizia
Mizner
Mizrahi
Mizukami
Mizuno
Mizutani
Mizwicki
Mizzell
Mizzelle
Mizzi
Mleczko
Mleczynski
Mlenar
Mlinar
Mlodzianowski
Mlynek
Mo
Moad
Moag
Moak
Moake
Moala
Moallankamp
Moan
Moat
Moates
Moats
Moatz
Moayyad
Mobbs
Moberg
Moberley
Moberly
Mobilia
Mobilio
Mobley
Mobus
Moc
Mocarski
Moccasin
Moccia
Moccio
Mocco
Moceri
Moch
Mocha
Mochel
Mocher
Mochizuki
Mock
Mockbee
Mockler
Mockus
Moctezuma
Moczo
Moczulski
Moczygemba
Modafferi
Moddejonge
Mode
Model
Modena
Moder
Modero
Moderski
Modert
Modesitt
Modest
Modeste
Modesto
Modglin
Modgling
Modha
Modi
Modic
Modica
Modin
Modine
Modique
Modisett
Modisette
Modlin
Modrak
Modugno
Mody
Modzeleski
Modzelewski
Moe
Moeck
Moeckel
Moede
Moeder
Moehle
Moehlman
Moehn
Moehr
Moehring
Moehrle
Moel
Moeller
Moellers
Moellman
Moelter
Moen
Moench
Moening
Moenius
Moerbe
Moerke
Moerman
Moers
Moes
Moesch
Moeser
Moessner
Moeuy
Moevao
Moffa
Moffat
Moffatt
Moffet
Moffett
Moffit
Moffitt
Mofford
Mofield
Mofle
Moga
Mogan
Mogannam
Mogavero
Mogel
Mogensen
Moger
Mogg
Moghadam
Mogle
Moglia
Mogollon
Mogren
Mogro
Mogus
Mogush
Moh
Mohabeer
Mohabir
Mohair
Mohamad
Mohamed
Mohammad
Mohammed
Mohan
Mohar
Mohaupt
Mohd
Mohead
Moher
Mohinani
Mohl
Mohler
Mohlke
Mohmand
Mohmed
Mohn
Mohney
Mohomed
Mohorovich
Mohr
Mohrbacher
Mohre
Mohring
Mohrlock
Mohrman
Mohrmann
Mohs
Mohseni
Mohsin
Moilanen
Moilien
Moine
Moir
Moisa
Moisan
Moisant
Moise
Moises
Moisey
Moistner
Moitoso
Moitoza
Mojardin
Mojarro
Mojica
Mojzisik
Mok
Mokbel
Mokiao
Mokler
Mokriski
Mokry
Mola
Molacek
Molaison
Moland
Molander
Molands
Molano
Molash
Molavi
Molchan
Moldan
Molden
Moldenhauer
Molder
Moldonado
Moldovan
Moldrem
Mole
Molek
Molen
Molenda
Moler
Moles
Moleski
Molesworth
Molett
Molette
Molfetta
Molgard
Molima
Molin
Molina
Molinar
Molinari
Molinaro
Molinary
Molinas
Moline
Molineaux
Molinelli
Molinere
Moling
Molinini
Molino
Molinski
Moliterno
Molitor
Molitoris
Moll
Molla
Mollberg
Molle
Molleda
Molleker
Mollema
Mollenhauer
Mollenkopf
Moller
Mollere
Molles
Mollet
Mollett
Mollette
Molleur
Mollica
Mollicone
Molliere
Mollins
Mollison
Mollo
Mollohan
Molloy
Mollura
Molly
Molnar
Molnau
Molner
Molock
Molon
Molone
Moloney
Molony
Molpus
Molsan
Molski
Molstad
Molt
Molter
Molton
Moltrie
Moltz
Molyneaux
Molyneux
Molz
Molzahn
Mom
Moma
Moman
Momaya
Momeni
Moment
Momin
Mominee
Momon
Momper
Momphard
Momplaisir
Mompoint
Momsen
Mon
Mona
Monachino
Monaco
Monagan
Monagas
Monaghan
Monagle
Monaham
Monahan
Monaldi
Monarca
Monarch
Monard
Monares
Monarez
Monarque
Monarrez
Monas
Monasterio
Monat
Monath
Moncada
Moncayo
Monce
Monceaux
Moncher
Moncier
Moncion
Moncivais
Monckton
Monclova
Moncrief
Moncrieff
Moncrieffe
Moncur
Moncure
Moncus
Monda
Mondaine
Mondale
Monday
Mondejar
Mondell
Mondella
Mondelli
Mondello
Monden
Mondesir
Mondier
Mondino
Mondloch
Mondo
Mondok
Mondone
Mondor
Mondoux
Mondoza
Mondragon
Mondry
Monds
Mondt
Mondy
Mone
Moneaux
Monegro
Monell
Mones
Monestime
Monestine
Monet
Monette
Monetti
Money
Moneyhun
Moneymaker
Moneypenny
Monfils
Monford
Monfore
Monfort
Monforte
Mong
Mongan
Mongar
Monge
Mongeau
Mongelli
Mongeon
Monger
Monges
Mongiello
Mongillo
Mongiovi
Mongold
Mongolo
Mongomery
Mongon
Mongrain
Mongue
Monholland
Monhollen
Moniak
Monica
Monico
Monie
Monier
Monigold
Monington
Monios
Moniot
Moniz
Monjaras
Monje
Monjure
Monk
Monka
Monkhouse
Monkowski
Monks
Monn
Monnerjahn
Monnet
Monnett
Monnier
Monnin
Monninger
Monnot
Monohan
Monopoli
Monot
Monoz
Monreal
Monro
Monroe
Monroig
Monrow
Monroy
Monrreal
Monrroy
Mons
Monsalve
Monsanto
Monsay
Monsees
Monsegur
Monsen
Monserrat
Monserrate
Monsivais
Monske
Monsky
Monsma
Monson
Monsour
Monsrud
Mont
Montag
Montagna
Montagne
Montague
Montaivo
Montalban
Montalbano
Montalbo
Montalgo
Montalto
Montaluo
Montalvan
Montalvo
Montan
Montana
Montanari
Montanaro
Montandon
Montane
Montanez
Montano
Montante
Montanye
Montaque
Montas
Montavon
Montaya
Montayes
Montazami
Montbriand
Montcalm
Monte
Monteagudo
Montealegre
Montecalvo
Montecillo
Montee
Monteforte
Montefusco
Montegut
Monteiro
Monteith
Montejano
Montejo
Monteleone
Montell
Montella
Montellano
Montelle
Montello
Montelongo
Montemarano
Montemayor
Montembeau
Montemurro
Montenegro
Monter
Montera
Monterio
Montero
Monteros
Monterrano
Monterrosa
Monterroso
Monterroza
Monterrubio
Montes
Montesa
Montesano
Montesdeoca
Montesi
Montesino
Montesinos
Monteverde
Montey
Montez
Montezuma
Montford
Montfort
Montgomery
Montgonery
Monti
Monticello
Montie
Montiel
Montier
Montiero
Montierth
Montieth
Montijano
Montijo
Montilla
Montis
Montjoy
Montminy
Montney
Montogomery
Monton
Montondo
Montone
Montoney
Montonez
Montono
Montooth
Montore
Montori
Montoro
Montoto
Montour
Montoure
Montoya
Montpas
Montpetit
Montrella
Montreuil
Montrose
Montross
Montroy
Monts
Montufar
Montuori
Montuoro
Montville
Monty
Montz
Monville
Monz
Monzingo
Monzo
Monzon
Mooberry
Moochler
Moock
Mood
Moodie
Moodispaugh
Moody
Mooe
Mooers
Moog
Mook
Moomaw
Moomey
Moon
Moone
Moonen
Mooney
Mooneyham
Mooneyhan
Moons
Moonshower
Moonsommy
Moor
Mooradian
Moorcroft
Moore
Moorefield
Moorehead
Moorehouse
Mooreland
Moorer
Moores
Moorhead
Moorhouse
Mooring
Moorman
Moors
Moos
Moosa
Moosbrugger
Moose
Mooser
Moosman
Moote
Moothart
Mootispaw
Mootry
Moots
Mooty
Mootz
Moppin
Moquin
Mor
Mora
Morabito
Morace
Morad
Morada
Moradel
Moradian
Morado
Moraga
Morago
Morain
Morais
Moraites
Moraitis
Morak
Moralas
Morale
Morales
Moralez
Moralis
Moran
Morand
Moranda
Morandi
Morando
Morang
Morano
Morant
Morante
Moranville
Morar
Morario
Morarity
Moras
Morasca
Morasch
Morasco
Morataya
Morath
Moratto
Moravec
Moravek
Moravick
Morawa
Morawski
Morber
Morch
Morck
Morcos
Morda
Mordan
Mordarski
Mordaunt
Mordecai
Mordeci
Mordehay
Morden
Mordhorst
Mordini
Mordino
Mordue
More
Morea
Moreau
Moreb
Moreci
Moredock
Moree
Morefield
Morehead
Morehouse
Moreida
Morein
Moreira
Morejon
Morel
Moreland
Morelen
Moreles
Morell
Morella
Morelle
Morelli
Morello
Morelock
Morelos
Morely
Moreman
Moren
Morena
Morence
Morenco
Morency
Moreno
Morentin
Morenz
Morera
Moreschi
Moresco
Moreshead
Moresi
Moret
Moreta
Moreton
Moretta
Moretti
Moretto
Moretz
Morey
Morfee
Morfin
Morford
Morga
Morgado
Morgan
Morgana
Morgandi
Morganfield
Morgano
Morgans
Morganson
Morgante
Morganti
Morgas
Morge
Morgen
Morgenroth
Morgensen
Morgenstein
Morgenstern
Morgenthaler
Morger
Morgia
Morgner
Morgon
Morgret
Morguson
Mori
Moriarity
Moriarty
Moribayed
Moricca
Morice
Morici
Moricle
Morie
Moriera
Morikawa
Morillo
Morimoto
Morin
Morine
Moring
Morini
Morino
Morinville
Morioka
Moris
Morise
Morisey
Morishita
Morishito
Morisky
Morison
Morisseau
Morissette
Morita
Moritz
Moriwaki
Mork
Morken
Morkert
Morkve
Morla
Morlan
Morland
Morlas
Morledge
Morles
Morley
Morlino
Morlock
Morman
Mormann
Mormile
Mormino
Mormon
Morn
Morna
Morneau
Morneault
Morning
Morningstar
Moro
Morocco
Morock
Moroles
Moron
Morones
Moroney
Moroni
Morono
Moronta
Moros
Morosco
Morosow
Morowski
Moroz
Morphew
Morphis
Morphy
Morquecho
Morr
Morra
Morral
Morrales
Morrall
Morre
Morreale
Morreau
Morrell
Morren
Morrero
Morrey
Morrical
Morrill
Morrin
Morring
Morris
Morrisette
Morrisey
Morrish
Morrison
Morrisroe
Morriss
Morrisseau
Morrissette
Morrissey
Morro
Morron
Morrone
Morrow
Morsbach
Morsberger
Morse
Morsell
Morsey
Morson
Morss
Mort
Morta
Mortel
Mortell
Mortellaro
Morten
Mortensen
Mortenson
Morter
Morthland
Mortier
Mortimer
Mortimore
Mortin
Mortinez
Mortis
Mortland
Morton
Morua
Morva
Morvant
Morvay
Morvillo
Morway
Mory
Moryl
Mosakowski
Mosbarger
Mosbey
Mosbrucker
Mosburg
Mosby
Mosca
Moscardelli
Moscariello
Moscaritolo
Moscato
Moschella
Moschetti
Moschetto
Moscicki
Mosco
Moscoffian
Moscone
Mosconi
Moscoso
Moscovic
Moscowitz
Moscrip
Mose
Mosebach
Moseby
Moseley
Moselle
Mosely
Moseman
Mosen
Mosena
Moser
Moses
Mosey
Mosgrove
Mosha
Mosher
Moshier
Mosho
Mosholder
Moshos
Mosier
Mosiman
Mosimann
Mosinski
Moskal
Moskau
Mosko
Moskop
Moskos
Moskovitz
Moskowitz
Moskwa
Mosler
Mosley
Mosman
Mosmeyer
Mosqueda
Mosquera
Moss
Mossa
Mossbarger
Mossberg
Mossel
Mosser
Mosseri
Mosses
Mossey
Mossien
Mossing
Mossman
Mosson
Mossor
Most
Mostad
Mostafavi
Mostella
Mosteller
Moster
Mostero
Mostert
Mostiller
Mostoller
Mostowy
Mostrom
Mosty
Mostyn
Mosure
Mosz
Mota
Motamed
Motamedi
Motayen
Motayne
Mote
Moten
Motes
Mothershead
Mothershed
Motil
Motl
Motley
Motola
Moton
Motonaga
Motsinger
Mott
Motta
Mottai
Motte
Motten
Motter
Mottern
Mottershead
Motteshard
Mottet
Mottillo
Mottinger
Mottley
Motto
Mottola
Motton
Mottram
Motts
Motyka
Motz
Motzer
Mou
Moua
Moudry
Moudy
Moul
Mould
Moulden
Moulder
Mouldin
Moulding
Moulds
Moulhem
Moulin
Moulinos
Moulthrop
Moulton
Moultrie
Moultry
Moun
Mounce
Mound
Mounger
Mounkes
Mounsey
Mount
Mountain
Mountcastle
Mountford
Mountjoy
Mounts
Moura
Mourad
Moure
Mourer
Mouret
Mourino
Mouritsen
Mourning
Moury
Mousa
Mouse
Mousel
Mouser
Mousley
Moussa
Mousseau
Mousser
Moussette
Moustafa
Mouton
Moutoux
Moutray
Mouw
Mouzas
Mouzon
Mova
Movius
Movlin
Mow
Mowan
Mowat
Mowatt
Mowbray
Mowder
Mowdy
Mowell
Mowen
Mower
Mowers
Mowery
Mowles
Mowrer
Mowrey
Mowris
Mowry
Moxey
Moxham
Moxley
Moxness
Moy
Moya
Moyd
Moye
Moyer
Moyerman
Moyers
Moyes
Moyet
Moylan
Moyle
Moyler
Moynahan
Moynihan
Moyse
Mozak
Mozdzierz
Mozee
Mozelak
Mozell
Mozena
Mozer
Mozga
Mozgala
Mozick
Mozie
Mozier
Mozingo
Mozley
Moznett
Mozo
Mozzone
Mracek
Mraw
Mraz
Mrazek
Mrazik
Mrkvicka
Mrnak
Mrochek
Mroczkowski
Mrotek
Mrotz
Mrowka
Mroz
Mrozek
Mrozinski
Mrozoski
Mruczek
Mruk
Mrvan
Mt
Mthimunye
Mu
Mucci
Muccia
Muccigrosso
Muccio
Mucciolo
Mucerino
Much
Mucha
Mucher
Muchler
Muchmore
Muchortow
Muchow
Muck
Muckel
Muckelroy
Muckelvaney
Muckenfuss
Muckenthaler
Muckerman
Muckey
Muckle
Muckleroy
Muckley
Mucklow
Muczynski
Mudd
Muddaththir
Muddiman
Mudge
Mudger
Mudget
Mudgett
Mudie
Mudra
Mudrick
Muecke
Muegge
Muehl
Muehlbach
Muehlberger
Muehleisen
Muehlman
Muell
Mueller
Muellerleile
Muellner
Muench
Muenchow
Muenkel
Muenzenberger
Mueske
Muessig
Muether
Muetzel
Muff
Muffett
Muffley
Muffoletto
Mugford
Mugg
Mugge
Muggeo
Muggley
Mugica
Mugleston
Mugnolo
Mugrage
Muha
Muhammad
Muhammed
Muhl
Muhlbach
Muhlbauer
Muhlenkamp
Muhlestein
Muhlhauser
Muhlstein
Muhn
Muhr
Muhs
Muhtaseb
Mui
Muilenburg
Muina
Muinos
Muir
Muirhead
Muise
Mujalli
Mujica
Mukai
Mukherjee
Mukhtar
Mula
Mulac
Mulanax
Mulaney
Mulato
Mulberry
Mulcahey
Mulcahy
Mulch
Mulchrone
Mulder
Mulderig
Mulders
Muldoon
Muldowney
Muldrew
Muldrow
Mule
Mulero
Mulford
Mulgrew
Mulhall
Mulhearn
Mulherin
Mulhern
Mulholland
Mulhollen
Mulich
Mulik
Mulinix
Mulkerin
Mulkern
Mulkey
Mulkhey
Mulkin
Mulkins
Mull
Mullahey
Mullahy
Mullally
Mullaly
Mullan
Mullane
Mullaney
Mullany
Mullarkey
Mullee
Mullen
Mullenaux
Mullenax
Mullenbach
Mullendore
Mullenix
Mullennex
Mullennix
Mullens
Muller
Mullet
Mullett
Mullican
Mullice
Mullick
Mulligan
Mullikin
Mullin
Mullinax
Mullineaux
Mulliner
Mullinex
Mulling
Mullings
Mulliniks
Mullinix
Mullins
Mullis
Mullison
Mullner
Mullowney
Mulloy
Mulneix
Mulnix
Mulqueen
Mulrain
Mulready
Mulrenin
Mulroney
Mulrooney
Mulroy
Mulry
Mulryan
Mulvahill
Mulvaney
Mulvehill
Mulverhill
Mulvey
Mulvihill
Mulville
Mulzer
Muma
Mumaugh
Mumaw
Mumbower
Mumby
Mumford
Mumm
Mumma
Mumme
Mummert
Mummey
Mumper
Mumpower
Mun
Muna
Munafo
Munar
Munari
Munaz
Munce
Muncey
Munch
Muncher
Munchmeyer
Muncie
Muncil
Muncrief
Muncy
Mund
Munda
Mundahl
Munday
Mundel
Mundell
Munden
Munder
Munderville
Mundhenk
Mundie
Mundine
Munding
Mundinger
Mundo
Mundorf
Mundschau
Mundschenk
Mundt
Mundwiller
Mundy
Mundz
Mundziak
Munerlyn
Munet
Muney
Munez
Munford
Munger
Mungia
Mungin
Mungle
Mungo
Munguia
Munhall
Muni
Munier
Muninger
Munion
Munir
Munis
Munise
Munivez
Muniz
Munk
Munkberg
Munks
Munl
Munley
Munlin
Munn
Munnell
Munnelly
Munnerlyn
Munning
Munnis
Munno
Munns
Muno
Munos
Munoz
Munro
Munroe
Muns
Munsch
Munsell
Munselle
Munsen
Munsey
Munshi
Munshower
Munsinger
Munson
Munster
Munsterman
Munstermann
Munt
Muntean
Munteanu
Munter
Muntz
Munuz
Munyer
Munyon
Munz
Munzell
Munzer
Muoio
Muphy
Mura
Murach
Muraco
Murad
Murai
Murak
Murakami
Murakawa
Muralles
Murallies
Muramoto
Muran
Muranaka
Murano
Murany
Muraoka
Muraro
Muraski
Murasso
Murat
Murata
Muratalla
Muratore
Murawski
Muray
Murayama
Murch
Murchie
Murchinson
Murchison
Murcia
Murcko
Murdaugh
Murden
Murders
Murdick
Murdoch
Murdock
Murdough
Murdy
Mure
Murel
Murelli
Murello
Muresan
Murff
Murfin
Murga
Murgia
Murguia
Muri
Murie
Muriel
Murilla
Murillo
Murin
Murley
Murnan
Murnane
Murnock
Muro
Muros
Murph
Murphey
Murphree
Murphrey
Murphy
Murr
Murra
Murrah
Murrain
Murray
Murrell
Murrey
Murri
Murrie
Murriel
Murrieta
Murrietta
Murril
Murrill
Murrillo
Murrin
Murrish
Murrock
Murrow
Murrufo
Murry
Mursch
Mursko
Murtagh
Murtaugh
Murtha
Murthy
Murton
Murty
Murwin
Murzycki
Murzyn
Murzynski
Musa
Musacchia
Musacchio
Musante
Musca
Muscara
Muscarella
Muscarello
Muscaro
Muscat
Muscatello
Muscato
Muscente
Musch
Muschamp
Muschaweck
Muschett
Muschick
Muschik
Musco
Muscolino
Muscott
Muse
Musel
Musemeche
Musetti
Musgrave
Musgraves
Musgrove
Musguire
Mushero
Mushett
Mushrush
Mushtaq
Musi
Musial
Music
Musich
Musick
Musielak
Musigdilok
Musil
Musilli
Musinski
Musitano
Muska
Muske
Muskelly
Muskett
Muskopf
Muskrat
Muskthel
Muskus
Muslim
Musni
Musolf
Musolino
Musquiz
Muss
Mussa
Musse
Mussel
Mussell
Musselman
Musselwhite
Mussen
Mussenden
Musser
Musshorn
Musslewhite
Mussman
Mussmann
Musso
Musson
Must
Mustache
Mustafa
Mustafaa
Mustain
Mustard
Mustaro
Muster
Mustian
Mustin
Musto
Mustoe
Muston
Musty
Musulin
Musumeci
Muszar
Muszynski
Muta
Mutana
Mutart
Mutch
Mutchler
Muterspaw
Muth
Muthana
Muthart
Muther
Mutherspaw
Muthig
Muthler
Mutner
Muto
Mutolo
Mutone
Mutschelknaus
Mutschler
Mutter
Mutters
Mutton
Mutty
Mutz
Muwwakkil
Muyres
Muysenberg
Muyskens
Muzacz
Muzii
Muzio
Muzquiz
Muzyka
Muzzarelli
Muzzey
Muzzillo
Muzzy
Mwakitwile
Mway
Myall
Myart
Myatt
Mycroft
Myer
Myers
Myerscough
Myerson
Myes
Myhand
Myhr
Myhre
Myint
Myking
Mykins
Myklebust
Mylar
Myler
Myles
Mylott
Mynatt
Mynear
Mynhier
Mynnerlyn
Myntti
Myott
Myra
Myracle
Myrck
Myre
Myree
Myren
Myres
Myrick
Myricks
Myrie
Myrlie
Myrman
Myron
Myrtle
Myrum
Mysak
Mysinger
Myslim
Myslin
Myslinski
Mysliwiec
Mytych
Myung
Na
Naab
Naas
Naasz
Nab
Nabarowsky
Nabarrete
Nabarro
Nabavian
Nabb
Naber
Nabers
Nabhan
Nabity
Nabor
Naborg
Nabors
Nabours
Nabozny
Nabritt
Nabzdyk
Nacar
Naccarato
Naccari
Nacci
Nace
Nachazel
Nachbar
Nachman
Nachmias
Nachor
Nachtrieb
Nacion
Nacisse
Nack
Nacke
Naclerio
Nacol
Nacy
Nadal
Naddeo
Nadeau
Nadel
Nadelbach
Nadell
Nadelson
Nader
Naderi
Naderman
Nadile
Nadine
Nading
Nadler
Nadoff
Nadolny
Nadolski
Naecker
Naef
Naegele
Naegeli
Naegle
Naeher
Naes
Naeve
Naff
Naffziger
Naftali
Naftel
Naftzger
Naftzinger
Nafziger
Nagai
Nagamine
Nagano
Nagao
Nagarajan
Nagasawa
Nagase
Nagata
Nagel
Nagele
Nagelhout
Nagelkirk
Nagelschmidt
Nagengast
Nageotte
Nager
Nagg
Nagindas
Nagle
Nagler
Nagode
Nagorski
Nagtalon
Naguin
Nagura
Nagy
Nahari
Nahas
Nahass
Nahhas
Nahl
Nahm
Nahmias
Nahrstedt
Nahrwold
Naidoo
Naidu
Naifeh
Naik
Nail
Nailer
Naill
Naillon
Nailor
Nails
Naiman
Naimoli
Nair
Nairn
Naish
Naito
Najar
Najarian
Najarro
Najera
Naji
Najjar
Nakaahiki
Nakada
Nakagawa
Nakahara
Nakai
Nakajima
Nakama
Nakamatsu
Nakamori
Nakamoto
Nakamura
Nakanishi
Nakano
Nakao
Nakaoka
Nakashima
Nakasone
Nakata
Nakatsu
Nakayama
Nakhle
Naki
Nakken
Nakonechny
Nalbach
Nalbandian
Nalbone
Nalder
Nale
Nalepa
Nalepka
Nalevanko
Nall
Nalley
Nallie
Nalls
Nally
Nalty
Nam
Namaka
Naman
Namanny
Namanworth
Namauu
Namdar
Namer
Namey
Namihira
Namisnak
Namm
Nampel
Namsaly
Namur
Nan
Nanas
Nanasy
Nance
Nancy
Nanda
Nanes
Nanez
Nanfito
Nang
Nangle
Nani
Nania
Nanik
Nanka
Nanke
Nanna
Nannen
Nanney
Nanni
Nannie
Nannini
Nanny
Nansteel
Nantanapibul
Nanthanong
Nanton
Nantwi
Nantz
Nanz
Nao
Naomi
Naone
Nap
Napenas
Napier
Napierala
Napieralski
Napihaa
Naples
Napoleon
Napoles
Napoletano
Napoli
Napolitano
Napp
Napper
Nappi
Nappier
Nappo
Napps
Napue
Naputi
Naquin
Naqvi
Naragon
Narain
Naraine
Naramore
Naranjo
Narasimhan
Narayan
Narayanan
Narciso
Narcisse
Nard
Nardecchia
Nardella
Nardelli
Nardi
Nardini
Nardino
Nardo
Nardone
Nardozzi
Narducci
Nardy
Nares
Naret
Narez
Nargi
Narimatsu
Narine
Narkevicius
Narkier
Narlock
Naro
Naron
Narr
Narramore
Narro
Narron
Narrow
Naruaez
Narum
Narvaez
Narvaiz
Nary
Nasaire
Nasalroad
Nasby
Nasca
Naschke
Nascimento
Nase
Naselli
Naser
Nasers
Nases
Nash
Nashe
Nasif
Nasir
Naslund
Naso
Nason
Nasr
Nass
Nassar
Nassef
Nasser
Nasseri
Nassie
Nassif
Nassimi
Nasso
Nasson
Nassr
Nast
Nasta
Nastase
Nastasi
Nastasia
Nasti
Nastri
Nasuti
Nasworthy
Natal
Natale
Natalello
Natali
Natalia
Natalie
Natalizio
Natani
Natcher
Nate
Nater
Natera
Natewa
Nath
Nathan
Nathaniel
Nathans
Nathanson
Nathe
Natho
Nathoo
Nati
Natiello
Nation
Nations
Natividad
Natoli
Natonabah
Natsis
Natt
Natter
Nattiah
Nattress
Natvig
Natwick
Nau
Nauarro
Naud
Nauer
Naufzinger
Naugher
Naughton
Naugle
Naugler
Nault
Nauman
Naumann
Naumes
Naumoff
Nauss
Nauyen
Nava
Naval
Navalta
Navan
Navanjo
Navappo
Navar
Navarete
Navaretta
Navarette
Navarez
Navaro
Navarra
Navarrate
Navarre
Navarrete
Navarrette
Navarro
Navas
Nave
Navedo
Naveed
Naveja
Navejar
Navejas
Naves
Navia
Navin
Navo
Navone
Navor
Navorro
Navratil
Navy
Nawda
Nawfel
Nawn
Nawrocki
Nawwar
Nay
Nayar
Nayee
Nayes
Naylor
Nayman
Naysmith
Naz
Nazaire
Nazar
Nazareno
Nazari
Nazarian
Nazario
Nazaroff
Naze
Nazelrod
Nazir
Nazzal
Nazzaro
Nazzise
Ncneal
Neace
Nead
Neagle
Neahr
Neal
Neale
Nealeigh
Nealen
Nealer
Nealey
Nealious
Nealis
Neall
Nealley
Neally
Nealon
Nealy
Neang
Near
Nearing
Neary
Neas
Nease
Neason
Neat
Neathery
Neault
Neave
Neaves
Nebarez
Nebeker
Nebel
Nebergall
Nebesnik
Nebesny
Nebgen
Neblett
Neblock
Neborak
Nebred
Necaise
Necessary
Nech
Necochea
Ned
Nedbalek
Nedd
Neddenriep
Neddo
Nedeau
Nedelman
Nederostek
Nedina
Nedley
Nedman
Nedrow
Nedry
Nedved
Nee
Neeb
Neece
Needam
Needels
Needham
Needle
Needleman
Needler
Needles
Needs
Needy
Neef
Neehouse
Neel
Neeld
Neeley
Neelly
Neelon
Neely
Neemann
Neenan
Neeper
Neer
Neering
Nees
Neese
Neeser
Neesmith
Neeson
Neff
Nefzger
Negbenebor
Negley
Neglia
Neglio
Negrana
Negreta
Negrete
Negrette
Negri
Negrin
Negrisor
Negro
Negron
Negroni
Negus
Neher
Nehls
Nehlsen
Nehme
Nehmer
Nehring
Nehrt
Neibert
Neice
Neid
Neidecker
Neidenbach
Neider
Neiderhiser
Neidert
Neidhardt
Neidich
Neidig
Neidiger
Neidlinger
Neifer
Neifert
Neiffer
Neiford
Neigenfind
Neiger
Neigh
Neighbor
Neighbors
Neighbours
Neihart
Neihoff
Neikirk
Neil
Neilan
Neild
Neiling
Neill
Neilly
Neils
Neilsen
Neilson
Neiman
Neimeyer
Nein
Neiner
Neiper
Neira
Neis
Neisen
Neish
Neisius
Neisler
Neiss
Neiswander
Neiswender
Neiswoger
Neiswonger
Neita
Neither
Neithercutt
Neitz
Neitzel
Neitzke
Neives
Neizer
Neja
Nejaime
Nejman
Nekola
Nelder
Neldon
Nelisse
Nelke
Nell
Nellem
Nellenback
Neller
Nelles
Nelli
Nelligan
Nellis
Nellon
Nellum
Nellums
Nelmark
Nelmes
Nelms
Neloms
Nelon
Nelsen
Nelson
Nelton
Neman
Nemani
Nemard
Nembhard
Nemec
Nemecek
Nemer
Nemerofsky
Nemes
Nemet
Nemeth
Nemets
Nemetz
Nemith
Nemitz
Nemoede
Nemunaitis
Nemzek
Nemzin
Nenez
Nenni
Nenninger
Nenno
Neonakis
Nepa
Nephew
Nepomuceno
Neptune
Nerad
Nerbonne
Nerby
Neren
Nerenberg
Neri
Neria
Nerio
Neris
Nerlich
Nern
Nerney
Nero
Nerpio
Nerren
Nersesian
Nervis
Nery
Nesbeth
Nesbit
Nesbitt
Nesby
Nesheim
Neshem
Nesin
Neske
Nesland
Nesler
Nesline
Neslusan
Nesmith
Ness
Nessel
Nesselrodt
Nessen
Nesser
Nesset
Nesseth
Nesslein
Nessler
Nessmith
Nessner
Nesspor
Nest
Nestel
Nester
Nesti
Nestico
Nestingen
Nestle
Nestler
Nestor
Nesvig
Net
Neth
Nethercutt
Netherland
Netherton
Nethery
Nethken
Nethkin
Netkowicz
Netland
Netley
Neto
Netolicky
Netrosio
Nett
Nette
Netter
Netters
Netterville
Netti
Nettik
Nettle
Nettleingham
Nettles
Nettleton
Netto
Netz
Netzel
Netzer
Netzley
Neu
Neubacher
Neubauer
Neubaum
Neubecker
Neuberger
Neubert
Neubig
Neuburger
Neuby
Neudeck
Neuendorf
Neuenfeldt
Neuenschwande
Neuenswander
Neufeld
Neufer
Neufville
Neugebauer
Neugent
Neugin
Neuhart
Neuhaus
Neuhauser
Neuhoff
Neujahr
Neumaier
Neuman
Neumann
Neumayer
Neumeier
Neumeister
Neumeyer
Neumiller
Neun
Neundorfer
Neuner
Neurohr
Neusch
Neuschwander
Neuse
Neuser
Neuweg
Neuwirth
Neuzil
Nev
Nevala
Nevares
Nevarez
Nevarrez
Neve
Nevel
Nevels
Nevens
Never
Neverman
Nevers
Neverson
Neves
Neveu
Neveux
Nevil
Nevill
Neville
Nevilles
Nevills
Nevils
Nevin
Nevinger
Nevins
Nevis
Nevison
Nevitt
Nevius
Nevland
Nevue
Nevwirth
New
Newall
Newand
Newark
Newball
Newbauer
Newbell
Newberg
Newberger
Newbern
Newberry
Newbert
Newbery
Newbill
Newbold
Newborn
Newbound
Newbraugh
Newbrough
Newburg
Newburn
Newbury
Newby
Newcom
Newcomb
Newcombe
Newcome
Newcomer
Newell
Newenle
Newens
Newer
Newes
Newey
Newfield
Newgard
Newgent
Newhall
Newham
Newhard
Newhart
Newhook
Newhouse
Newill
Newingham
Newitt
Newkirk
Newlan
Newland
Newlin
Newlon
Newman
Newmann
Newmark
Newmeyer
Newmon
Newmyer
Newnam
Newness
Newnham
Newnum
Newport
Newquist
Newsam
Newsham
Newsom
Newsome
Newson
Newstead
Newsted
Newstrom
Newsum
Newton
Newtown
Newville
Newyear
Ney
Neyaci
Neyer
Neyhart
Neyland
Neylon
Neyman
Neymeyer
Neyra
Nez
Nezat
Nezich
Ng
Nghe
Nghiem
Ngin
Ngo
Ngoun
Ngov
Nguen
Ngueyn
Nguy
Nguyan
Nguyen
Nguyn
Ngvyen
Ngyun
Nham
Nhatsavang
Nhek
Nhep
Ni
Nian
Niang
Niau
Nibbe
Nibbs
Nibert
Niblack
Nibler
Niblett
Niblock
Nicar
Nicarry
Nicastro
Niccoli
Niccum
Nice
Nicely
Niceswander
Nicewander
Nicewarner
Nicewonger
Nichalson
Nichell
Nichelson
Nichlos
Nichois
Nichol
Nicholas
Nicholason
Nichole
Nicholes
Nicholl
Nicholls
Nichols
Nicholsen
Nicholson
Nichter
Nici
Nick
Nicka
Nickas
Nickel
Nickell
Nickels
Nickelson
Nickelston
Nickenberry
Nickens
Nickerson
Nickeson
Nickey
Nickisch
Nickl
Nicklas
Nicklaus
Nicklaw
Nickle
Nickleberry
Nickles
Nickleson
Nickless
Nicklien
Nicklin
Nicklos
Nicklous
Nicklow
Nickodem
Nickol
Nickolas
Nickoley
Nickolich
Nickolls
Nickols
Nickolson
Nicks
Nickson
Nicley
Nico
Nicodemus
Nicol
Nicola
Nicolai
Nicolaides
Nicolais
Nicolaisen
Nicolas
Nicolau
Nicolaus
Nicolay
Nicolaysen
Nicole
Nicolella
Nicoles
Nicolet
Nicoletta
Nicolette
Nicoletti
Nicoli
Nicolia
Nicolini
Nicoll
Nicolls
Nicolo
Nicolosi
Nicolozakes
Nicols
Nicolson
Nicome
Nicometo
Nicosia
Nicoson
Nicotera
Nicoulin
Nida
Niday
Nidiffer
Nido
Nie
Niebaum
Niebel
Niebergall
Niebla
Niebuhr
Niebyl
Niece
Nied
Niedbala
Niedbalec
Niedbalski
Niedecken
Niedens
Nieder
Niederberger
Niederer
Niederhaus
Niederhauser
Niederkorn
Niedermaier
Niedermayer
Niedermeier
Niedermeyer
Niedringhaus
Niedzielski
Niedzwiecki
Niedzwiedz
Niedzwiedzki
Niehaus
Niehoff
Niehus
Niel
Nieland
Nield
Nielsen
Nielson
Nieman
Niemann
Niemants
Niemczyk
Niemeier
Niemela
Niemeyer
Niemi
Niemie
Niemiec
Niemiel
Niemietz
Nieminen
Niemitzio
Nienaber
Nieng
Nienhaus
Nienhuis
Nienow
Nier
Nieratko
Nierenberg
Nierer
Nierman
Niermann
Nies
Niesborella
Niese
Niesen
Niesent
Niesman
Niesporek
Niess
Nietfeldt
Niethamer
Nieto
Nietupski
Nietzer
Nieva
Nievas
Nieves
Niewiadomski
Niewieroski
Niez
Niezgoda
Niffenegger
Nifong
Niforos
Nigg
Niggemann
Nigh
Nighbert
Nighbor
Nighman
Nighswander
Night
Nightengale
Nightingale
Nightlinger
Nightwine
Nigl
Niglio
Nigon
Nigro
Nihart
Nihei
Niheu
Nii
Niimi
Nik
Nikach
Nikaido
Nikas
Nikirk
Nikkel
Nikocevic
Nikodem
Nikolai
Nikolas
Nikolic
Niksich
Nikula
Nila
Nilan
Niland
Niles
Nilges
Nill
Nilles
Nilmeier
Nilsby
Nilsen
Nilson
Nilsson
Nim
Nimick
Nimmer
Nimmo
Nimmons
Nimocks
Nimon
Nimox
Nimrod
Nims
Nimtz
Nimura
Nimz
Nin
Nina
Nincehelsor
Nindorf
Nine
Niner
Ninh
Nini
Ninke
Ninneman
Ninnemann
Ninness
Nino
Ninos
Nip
Nipp
Nippe
Nipper
Nippert
Nipple
Nipps
Niquette
Nirenberg
Nirmaier
Niro
Nirschl
Nisbet
Nisbett
Nisbit
Nish
Nishi
Nishida
Nishiguchi
Nishihara
Nishikawa
Nishimori
Nishimoto
Nishimura
Nishina
Nishio
Nishioka
Nishitani
Nishiyama
Niskala
Niskanen
Nisley
Nisly
Nisonger
Niss
Nissalke
Nissan
Nissen
Nissila
Nissley
Nist
Nistendirk
Nistler
Niswander
Niswender
Niswonger
Nita
Nitchals
Nitcher
Nitchman
Niten
Nitka
Nitkowski
Nitsche
Nitschke
Nitta
Nitterhouse
Nitti
Nittinger
Nittler
Nitz
Nitzel
Nitzkowski
Nitzsche
Nitzschke
Niu
Nivala
Nivar
Niven
Nivens
Niver
Niverson
Nives
Nivison
Niwa
Nix
Nixa
Nixion
Nixon
Nixson
Niziol
Niziolek
Niznik
Nizo
Njango
Njie
Njoku
Nkomo
Nkuku
No
Noa
Noack
Noah
Noakes
Noaks
Nobbe
Nobel
Nobile
Nobis
Noble
Nobles
Noblet
Noblett
Noblin
Noblitt
Noboa
Nobrega
Nobregas
Nobriga
Nocar
Nocek
Nocella
Nocera
Nocito
Nock
Nockai
Nockels
Nocket
Nocks
Nocon
Nocum
Noda
Nodal
Nodarse
Nodd
Nodine
Nodland
Nodurft
Noe
Noecker
Noegel
Noel
Noeldner
Noell
Noens
Noerenberg
Noerr
Noethiger
Noey
Noffsinger
Nofsinger
Noftsger
Noftsier
Nofziger
Noga
Nogales
Noggle
Noggler
Noggles
Nogle
Nogoda
Nogosek
Nogowski
Noguchi
Nogueda
Nogueira
Noguera
Nogueras
Noh
Nohe
Nohel
Noia
Noice
Noiseux
Nojiri
Noke
Nokes
Nokken
Nokleby
Nol
Nola
Nolan
Noland
Nolasco
Nolau
Nolazco
Nold
Nolda
Nolde
Nolden
Nolder
Nole
Nolen
Noles
Nolet
Nolette
Nolf
Nolfe
Noli
Nolie
Nolin
Noll
Nolle
Noller
Nollet
Nollette
Nolley
Nollman
Nollora
Nolt
Nolte
Noltensmeier
Nolting
Nolton
Noman
Nommay
Nomura
Nonaka
Nonamaker
Nondorf
Nonemaker
Noneman
Nones
Nonnemacher
Nono
Nonroe
Nonu
Nooe
Nooman
Noon
Noonan
Noone
Nooner
Nooney
Noonkester
Noonon
Noor
Noorani
Noorda
Noordam
Noori
Noorigian
Nop
Nopachai
Nopper
Nora
Norales
Norals
Norat
Norbeck
Norberg
Norbo
Norbury
Norby
Norcia
Norcott
Norcross
Nord
Nordahl
Nordan
Nordberg
Nordby
Nordeen
Nordell
Norden
Nordenson
Nordenstrom
Norder
Nordes
Nordgren
Nordhoff
Nordick
Nordin
Nordine
Nordlie
Nordling
Nordlinger
Nordlund
Nordman
Nordmann
Nordmark
Nordmeyer
Nordon
Nordquist
Nordsiek
Nordstrand
Nordstrom
Nordwall
Nordyke
Nore
Nored
Noreen
Noreiga
Norem
Noren
Norena
Norenberg
Norfleet
Norfolk
Norg
Norgaard
Norgard
Nori
Noriega
Noriego
Noris
Norise
Nork
Norkaitis
Norkin
Norko
Norkus
Norland
Norlander
Norley
Norlien
Norlin
Norling
Norlund
Norma
Norman
Normand
Normandeau
Normandin
Normann
Norment
Normington
Normoyle
Norn
Norquest
Norquist
Norr
Norred
Norrell
Norrick
Norrid
Norrie
Norrington
Norris
Norrix
Norrod
Norsaganay
Norse
Norsen
Norseth
Norseworthy
Norsingle
Norskog
Norstrand
Norstrom
Norstrud
Norsworthy
Nortesano
North
Northam
Northan
Northcote
Northcott
Northcraft
Northcross
Northcut
Northcutt
Northern
Northey
Northington
Northouse
Northover
Northrop
Northrup
Northum
Northup
Northway
Northwood
Norton
Nortz
Norum
Norvell
Norviel
Norville
Norway
Norwell
Norwood
Norzagaray
Nosacka
Nosal
Nosbisch
Nose
Noseff
Nosek
Nosel
Noser
Nosis
Noss
Nossett
Nost
Nostrand
Nostro
Nosworthy
Notah
Notari
Notarnicola
Notaro
Notch
Noteboom
Notestine
Noth
Nothacker
Nothem
Nothnagel
Nothstein
Nothstine
Nothum
Notice
Notik
Notis
Notley
Noto
Notoma
Notowich
Notowitz
Nott
Nottage
Notte
Notter
Notti
Nottingham
Notto
Notwick
Noud
Noujaim
Noullet
Noun
Nouri
Nourse
Noury
Nouth
Nova
Novacek
Novack
Novad
Novak
Novakovich
Novara
Novas
Novel
Novell
Novelli
Novellino
Novello
Novelly
November
Novembre
Novencido
Novetsky
Novi
Novick
Novicki
Novickis
Novida
Novielli
Noviello
Novik
Novikoff
Novinger
Novitske
Novitski
Novitsky
Novo
Novoa
Novosel
Novotny
Novy
Nowack
Nowacki
Nowaczyk
Nowak
Nowakowski
Nowden
Nowell
Nowick
Nowicki
Nowinski
Nowitzke
Nowlan
Nowland
Nowlen
Nowley
Nowlin
Nowling
Nowosadko
Nowosielski
Nowzari
Noxon
Noy
Noya
Noyd
Noye
Noyer
Noyes
Noyola
Nozick
Nozicka
Nozum
Nquyen
Nuanes
Nuara
Nuber
Nucci
Nuccio
Nuccitelli
Nuce
Nuchols
Nuckels
Nuckles
Nucklos
Nuckoles
Nuckolls
Nuckols
Nudelman
Nuding
Nuesca
Nuessen
Nuessle
Nuetzman
Nuffer
Nugal
Nugen
Nugent
Nuhfer
Nuhn
Nulisch
Null
Nulle
Nulph
Nulty
Numan
Number
Numbers
Numkena
Nunamaker
Nuncio
Nunemaker
Nuner
Nunery
Nunes
Nunev
Nunez
Nungesser
Nuniz
Nunlee
Nunley
Nunmaker
Nunn
Nunnally
Nunnelee
Nunnelley
Nunnenkamp
Nunnery
Nunno
Nuno
Nunoz
Nuntaray
Nunz
Nunziata
Nunziato
Nuon
Nuque
Nuriddin
Nurmi
Nurnberger
Nurre
Nurse
Nurthen
Nusbaum
Nuse
Nush
Nusom
Nuss
Nussbaum
Nussbaumer
Nusser
Nussey
Nusz
Nutall
Nute
Nuth
Nutile
Nutley
Nutt
Nuttall
Nutter
Nutting
Nutzmann
Nuuanu
Nuvallie
Nuxoll
Nuzback
Nuzenski
Nuzum
Nuzzi
Nuzzo
Nwabeke
Nwachukwu
Nwadiora
Nwagbara
Nwakanma
Nwankwo
Ny
Nyahay
Nyberg
Nybo
Nyce
Nycum
Nydam
Nydegger
Nydick
Nye
Nyenhuis
Nygaard
Nygard
Nygaro
Nygren
Nyhan
Nyholm
Nyhus
Nykiel
Nyland
Nylander
Nylen
Nylin
Nylund
Nyman
Nypaver
Nyquist
Nyreen
Nyseth
Nysether
Nystrom
Nyswonger
Nyulassy
Oachs
Oajaca
Oak
Oakden
Oakes
Oakeson
Oakey
Oakland
Oakleaf
Oakley
Oakman
Oaks
Oar
Oard
Oare
Oas
Oates
Oatfield
Oathout
Oatis
Oatley
Oatman
Oatney
Oatridge
Oats
Oaxaca
Oba
Obaker
Oballe
Obando
Obanion
Obanner
Obannion
Obannon
Obar
Obarr
Obas
Obbink
Obeid
Obeirne
Obenauer
Obenchain
Obeng
Obenshain
Ober
Oberbeck
Oberdick
Oberdier
Oberdorf
Oberer
Oberfell
Oberg
Obergfell
Oberhaus
Oberhausen
Oberhelman
Oberholtzer
Oberholzer
Oberlander
Oberle
Oberley
Oberlies
Oberlin
Oberloh
Oberly
Oberman
Obermann
Obermeier
Obermeyer
Obermier
Obermiller
Obermoeller
Obermuller
Oberpriller
Oberry
Oberski
Oberson
Oberst
Obert
Obery
Obeso
Obey
Obhof
Obholz
Obi
Obiano
Obie
Obierne
Obiesie
Obin
Oblak
Oblander
Obleness
Obleton
Oblinger
Oblinski
Oblow
Obnegon
Oborne
Oborny
Oboyle
Obradovich
Obray
Obrecht
Obregon
Obrein
Obremski
Obrian
Obriant
Obrien
Obringer
Obrion
Obrist
Obryan
Obryant
Obryon
Obrzut
Obst
Obstfeld
Oby
Obyrne
Ocacio
Ocain
Ocallaghan
Ocallahan
Ocamb
Ocampo
Ocana
Ocanas
Ocanaz
Ocano
Ocarroll
Ocasio
Occhino
Occhiogrosso
Occhipinti
Occhuizzo
Ocean
Ocegueda
Oceguera
Ocejo
Ocenasek
Och
Ocha
Ochakovsky
Ochal
Ochalek
Ocheltree
Ochiai
Ochiltree
Ochinang
Ochoa
Ochocki
Ochotorena
Ochs
Ochsenbein
Ochsner
Ochwat
Ocken
Ockenfels
Ocker
Ockerman
Ockey
Ockimey
Ockleberry
Ockman
Ockmond
Oclair
Ocon
Oconnel
Oconnell
Oconner
Oconnor
Oconor
Ocran
Octave
Ocus
Oczon
Oda
Odair
Odam
Odaniel
Oday
Odden
Oddi
Oddo
Ode
Odea
Odear
Odebralski
Odegaard
Odegard
Odeh
Odekirk
Odell
Odem
Odems
Oden
Odenheimer
Odens
Odenwald
Oder
Oderkirk
Odermott
Odess
Odette
Odgen
Odgers
Odham
Odhner
Odiase
Odien
Odil
Odin
Odiorne
Odle
Odmark
Odneal
Odo
Odoherty
Odom
Odome
Odomes
Odoms
Odon
Odonahue
Odonal
Odonald
Odonell
Odonnel
Odonnell
Odonoghue
Odonovan
Odor
Odore
Odorizzi
Odougherty
Odowd
Odriscoll
Odum
Odums
Odwyer
Oechsle
Oedekerk
Oeder
Oeftger
Oehl
Oehlenschlage
Oehler
Oehlert
Oehlschlager
Oehm
Oehmig
Oehmke
Oehrle
Oehrlein
Oeler
Oelke
Oelschlaeger
Oelschlager
Oeltjen
Oelze
Oen
Oertel
Oerther
Oertle
Oesch
Oest
Oesterle
Oesterling
Oesterreich
Oestmann
Oestreich
Oestreicher
Oetken
Oetting
Oetzel
Ofallon
Ofarrell
Ofer
Off
Offen
Offenbacker
Offenberger
Offer
Offerdahl
Offerman
Offermann
Officer
Offield
Offill
Offley
Offner
Offord
Offret
Offutt
Oflaherty
Oflahrity
Oflynn
Ofsak
Oftedahl
Ogaldez
Ogami
Ogan
Ogando
Oganesian
Ogans
Oganyan
Ogara
Ogarro
Ogas
Ogasawara
Ogata
Ogawa
Ogaz
Ogbonnaya
Ogborn
Ogburn
Ogden
Oge
Ogeen
Ogen
Oger
Ogg
Ogiamien
Ogiba
Ogier
Ogilive
Ogilvie
Oginski
Ogle
Ogles
Oglesbee
Oglesby
Ogletree
Ogley
Ogorman
Ogrady
Ogram
Ogren
Ogrodowicz
Ogston
Oguendo
Oguin
Oguinn
Ogunyemi
Ogutu
Ogwin
Ogwynn
Ogzewalla
Oh
Ohagan
Ohair
Ohaire
Ohalloran
Ohan
Ohanesian
Ohanian
Ohanley
Ohanlon
Ohara
Ohare
Oharra
Oharroll
Ohashi
Ohaver
Ohayon
Ohearn
Ohern
Oheron
Oherron
Ohl
Ohland
Ohle
Ohlemacher
Ohlen
Ohlenbusch
Ohlendorf
Ohlensehlen
Ohler
Ohlhauser
Ohlinger
Ohlmacher
Ohlmann
Ohlrich
Ohlsen
Ohlson
Ohlsson
Ohlund
Ohm
Ohman
Ohmann
Ohme
Ohmen
Ohmer
Ohmie
Ohmit
Ohms
Ohno
Ohnstad
Ohora
Ohotnicky
Ohotto
Ohr
Ohren
Ohrenich
Ohrnstein
Ohrt
Ohs
Ohta
Ohyama
Oieda
Oien
Oiler
Oilvares
Oines
Oinonen
Oishi
Oja
Ojala
Ojanen
Ojano
Ojard
Ojeda
Ojima
Ojito
Ok
Oka
Okada
Okafor
Okajima
Okamoto
Okamura
Okane
Okano
Okazaki
Okeefe
Okeeffe
Okeke
Okel
Okelberry
Okelley
Okelly
Oken
Okerblom
Okerlund
Okerson
Okeson
Okey
Oki
Okie
Okihara
Okimoto
Okin
Okinaka
Okino
Okins
Okitsu
Okken
Okojie
Okoli
Okolo
Okon
Okonek
Okoniewski
Okonski
Okoren
Okoro
Okoronkwo
Okorududu
Okoye
Okray
Okrent
Oksen
Oktavec
Okubo
Okuda
Okuhara
Okula
Okuley
Okumoto
Okumura
Okun
Okuna
Okuniewski
Okuno
Okura
Okutsu
Okwuona
Olaes
Olafson
Olague
Olah
Olalde
Olan
Oland
Olander
Olano
Olarte
Olaughlin
Olausen
Olavarria
Olay
Olaya
Olazabal
Olberding
Olbrish
Olckhart
Olcott
Olcus
Old
Oldaker
Oldakowski
Oldani
Olde
Olden
Oldenburg
Oldenburger
Oldenkamp
Older
Oldershaw
Oldfather
Oldfield
Oldham
Olding
Oldow
Oldridge
Oldroyd
Olds
Olea
Oleary
Olecki
Olejarski
Olejarz
Olejniczak
Oleksa
Oleksiak
Oleksy
Olen
Olenick
Olenius
Olenski
Oler
Olerud
Oles
Olesen
Oleskiewicz
Olesky
Olesnevich
Oleson
Oleveda
Olevera
Olewine
Olewinski
Olexa
Olexy
Oley
Olfers
Olgin
Olguin
Olgvin
Olheiser
Olide
Olien
Oliff
Oligee
Oliger
Oligschlaeger
Olin
Oline
Olinger
Olinghouse
Olinick
Olinsky
Oliphant
Olis
Oliva
Olivar
Olivares
Olivarez
Olivarra
Olivarres
Olivarri
Olivarria
Olivas
Olive
Oliveira
Oliven
Olivencia
Oliver
Olivera
Oliveras
Oliveres
Oliveri
Oliveria
Oliverio
Olivero
Oliveros
Olivers
Oliverson
Olives
Olivia
Olivid
Olivier
Oliviera
Olivieri
Olivio
Olivo
Olivos
Olk
Olkowski
Ollar
Ollech
Ollendick
Oller
Ollhoff
Olli
Ollie
Olliff
Ollig
Ollila
Ollis
Ollison
Olliver
Ollivier
Ollivierre
Ollmann
Ollom
Olloqui
Olm
Olma
Olmeda
Olmedo
Olmo
Olmos
Olmscheid
Olmstead
Olmsted
Olnes
Olney
Olnick
Olofson
Olona
Olores
Oloughlin
Olowe
Olp
Olpin
Olquin
Olrich
Olsby
Olsen
Olshan
Olshefski
Olsin
Olson
Olsson
Olstad
Olsten
Olszewski
Olszowka
Olten
Olthoff
Oltman
Oltmanns
Olton
Oltremari
Oltrogge
Oltz
Olubunmi
Olufson
Olup
Olveda
Olvedo
Olveira
Olvera
Olverson
Olvey
Olwin
Olynger
Omahony
Omalley
Oman
Omar
Omara
Omarah
Omary
Omdahl
Omeara
Omelia
Omer
Omernik
Omersa
Ominelli
Omland
Omli
Omlin
Ommen
Omo
Omohundro
Omoto
Omoyosi
Oms
Omtiveros
Omullan
Omundson
Omura
On
Ona
Onaga
Onan
Oncale
Ondeck
Ondersma
Ondic
Ondik
Ondo
Ondrey
Ondrick
Ondrusek
Oneal
Oneale
Oneel
Oneil
Oneill
Onell
Oney
Onezne
Ong
Oniel
Oniell
Onifade
Onishea
Onishi
Onisick
Onitsuka
Onken
Onks
Onkst
Onley
Onnen
Ono
Onofre
Onofrio
Onorata
Onorati
Onorato
Onsgard
Onstad
Onstead
Onstott
Onsurez
Ontiveros
Ontiveroz
Ontko
Onukogu
Onusko
Onwunli
Onyeagu
Onyeanus
Ooley
Oommen
Oosterhof
Ooten
Ooton
Opaka
Opal
Opalicki
Opalka
Opara
Opatrny
Opatz
Opdahl
Opdyke
Opeka
Opel
Opela
Opell
Openshaw
Opet
Opfer
Opheim
Opher
Ophus
Opichka
Opie
Opiela
Opielski
Opiola
Opitz
Opland
Oplinger
Opoien
Opoka
Opp
Oppegard
Oppel
Oppelt
Oppenheim
Oppenheimer
Oppenlander
Opper
Opperman
Oppliger
Oppy
Opray
Opsahl
Opstein
Opteyndt
Opula
Opunui
Opyd
Oquenda
Oquendo
Oquin
Oquinn
Or
Ora
Orabone
Orabuena
Orahood
Oram
Orama
Oran
Orandello
Orange
Oransky
Orantes
Oras
Oravec
Oravetz
Orazine
Orbaker
Orban
Orbeck
Orbin
Orbison
Orce
Orchard
Orcholski
Orcutt
Ord
Ordahl
Ordal
Ordas
Ordaz
Ordazzo
Ordeneaux
Ording
Ordiway
Ordman
Ordner
Ordon
Ordona
Ordones
Ordonez
Ordorica
Ordoyne
Orduna
Orduno
Ordway
Ore
Orea
Orear
Oreb
Orebaugh
Oree
Orefice
Oregan
Oregel
Oregon
Orehek
Oreilly
Oreily
Orejel
Orejuela
Orellama
Orellana
Orellano
Orem
Oren
Orendain
Orender
Orendorff
Orengo
Orenstein
Ores
Oreskovich
Orewiler
Orey
Orf
Orff
Orford
Orgain
Organ
Organek
Organista
Orgeron
Orgill
Orgovan
Orhenkowski
Ori
Orick
Orie
Orielley
Orielly
Origer
Orihuela
Oriley
Orillion
Orines
Orio
Oriol
Orion
Oriordan
Oris
Orison
Oriti
Oritz
Orizabal
Orizetti
Orji
Ork
Orkin
Orkwis
Orland
Orlander
Orlandi
Orlando
Orleans
Orlich
Orlikowski
Orlin
Orlinski
Orlinsky
Orlof
Orloff
Orloski
Orlosky
Orlove
Orlow
Orlowski
Orlowsky
Orm
Orman
Ormand
Orme
Ormerod
Ormes
Ormiston
Ormond
Ormonde
Orms
Ormsbee
Ormsby
Orn
Orndoff
Orndorf
Orndorff
Orne
Ornedo
Ornelas
Ornelaz
Ornellas
Ornelos
Orner
Ornstein
Oroak
Oroark
Orobona
Orochena
Orofino
Orona
Orone
Oropesa
Oropeza
Ororke
Oros
Orosco
Orosz
Orouke
Orourke
Oroz
Orozco
Orozeo
Orpen
Orphey
Orpin
Orr
Orrala
Orrantia
Orrego
Orrell
Orren
Orrick
Orrico
Orrill
Orris
Orrison
Orrock
Orsak
Orsborn
Orsburn
Orscheln
Orser
Orsi
Orsini
Orsino
Orso
Orson
Orsten
Orszulak
Ort
Orta
Ortaga
Orte
Ortea
Ortega
Ortego
Ortegon
Ortell
Ortelli
Ortelt
Ortenzio
Ortez
Ortga
Orth
Ortic
Ortis
Ortiz
Ortlieb
Ortman
Ortmann
Ortmeier
Ortmeyer
Ortner
Orto
Ortolano
Ortolf
Orton
Orts
Orttenburger
Ortuno
Ortwein
Ortwine
Ortz
Orum
Orvin
Orvis
Orwick
Orwig
Orwin
Ory
Orzalli
Orzech
Orzechowski
Orzel
Orzell
Osaile
Osaki
Osako
Osario
Osawa
Osayande
Osazuwa
Osbeck
Osberg
Osbey
Osbment
Osbon
Osborn
Osborne
Osbourn
Osbourne
Osburn
Osburne
Osby
Oscar
Oscarson
Osche
Oschmann
Osden
Osdoba
Osegueda
Oseguera
Osei
Osen
Osendorf
Osenkowski
Osentowski
Osequera
Oser
Osgood
Oshaughnessy
Oshea
Oshell
Osher
Oshey
Oshields
Oshima
Oshinsky
Oshiro
Oshita
Oshman
Osias
Osick
Osiecki
Osier
Osika
Osinski
Osisek
Oskins
Oslan
Osland
Osle
Osler
Osley
Oslin
Oslund
Osman
Osmanski
Osment
Osmer
Osmera
Osmers
Osmon
Osmond
Osmun
Osmundson
Osmus
Osnoe
Osofsky
Osol
Osollo
Osoria
Osorio
Osornio
Osorno
Ososki
Ososkie
Osowicz
Osowski
Ospina
Ospital
Ossenfort
Ossman
Osso
Ossola
Ossowski
Osswald
Ost
Ostaba
Ostasiewicz
Ostberg
Ostby
Osteen
Osten
Ostenberg
Ostendorf
Ostendorff
Ostenson
Oster
Osterberg
Osterberger
Osterdyk
Osterfeld
Ostergard
Ostergren
Osterhaut
Osterholt
Osterhoudt
Osterhouse
Osterhout
Osterland
Osterloh
Osterlund
Osterman
Ostermann
Ostermeyer
Ostermiller
Osterstuck
Ostertag
Ostheimer
Osthoff
Ostiguy
Osting
Ostler
Ostlie
Ostling
Ostlund
Ostolaza
Ostorga
Ostrander
Ostrem
Ostroff
Ostrom
Ostroot
Ostroski
Ostrosky
Ostrov
Ostrow
Ostrowski
Ostrum
Ostrye
Ostrzyeki
Ostwald
Ostwinkle
Osuch
Osucha
Osullivan
Osumi
Osuna
Osvaldo
Oswald
Oswalt
Oszust
Ota
Otake
Otani
Otanicar
Otano
Otar
Otega
Otero
Otex
Otey
Other
Othman
Othon
Othoudt
Otinger
Otis
Otiz
Otley
Oto
Otomo
Otool
Otoole
Otremba
Otsman
Otsu
Otsuka
Ott
Otta
Ottalagano
Ottaway
Otte
Ottem
Otteman
Otten
Ottenwess
Otter
Otterbein
Otterbine
Otterholt
Otterson
Ottesen
Otteson
Ottey
Ottilige
Otting
Ottinger
Ottino
Ottis
Ottley
Ottman
Otto
Ottogary
Ottomaniello
Ottosen
Ottoson
Ottrix
Otts
Ottum
Otuafi
Otukolo
Otutaha
Otwell
Ou
Oubre
Ouch
Ouchi
Oudekerk
Ouderkirk
Oudker
Ouelette
Ouellet
Ouellete
Ouellette
Ouillette
Ouimet
Ouimette
Ouinones
Ouk
Oulette
Oullette
Oum
Oun
Ounsy
Ourada
Ouren
Ours
Oursler
Ourso
Ourth
Oury
Ousdahl
Ousley
Outcalt
Outen
Outhier
Outhouse
Outland
Outlaw
Outler
Outley
Outman
Outram
Outten
Outwater
Outzen
Ouye
Ouzts
Ovadilla
Ovall
Ovalle
Ovalles
Ovando
Ovard
Ovdenk
Ovellette
Oven
Ovens
Over
Overall
Overbaugh
Overbay
Overbeck
Overbee
Overbeek
Overbey
Overbo
Overbough
Overby
Overcash
Overcast
Overdick
Overdorf
Overfelt
Overfield
Overgaard
Overholser
Overholt
Overholtzer
Overhulser
Overkamp
Overland
Overlee
Overley
Overlie
Overlock
Overly
Overman
Overmann
Overmeyer
Overmire
Overmyer
Overocker
Overpeck
Overshiner
Overshown
Overson
Overstreet
Overstrom
Overton
Overturf
Overweg
Overy
Ovesen
Oveson
Oviatt
Oviedo
Ovington
Ovit
Ovitt
Ovitz
Ovsanik
Ow
Owca
Owczarzak
Owen
Owenby
Owens
Owensby
Owers
Owings
Ownbey
Ownby
Ownes
Owney
Owoc
Owolabi
Owsley
Owston
Owusu
Oxborough
Oxborrow
Oxendine
Oxenrider
Oxford
Oxley
Oxman
Oxnam
Oxner
Oxton
Oya
Oyabu
Oyama
Oyellette
Oyen
Oyer
Oyervides
Oyler
Oyola
Oyster
Oyston
Oyuela
Oz
Oza
Ozaeta
Ozaine
Ozaki
Ozane
Ozawa
Ozbun
Ozburn
Ozenne
Ozer
Ozga
Ozier
Ozimek
Ozley
Ozment
Ozminkowski
Ozog
Ozolins
Ozols
Ozuna
Ozzella
Pa
Paa
Paalan
Paap
Paar
Paarmann
Paasch
Paaske
Paavola
Pabelick
Paben
Pabey
Pabich
Pablo
Pabon
Pabst
Pac
Pacana
Pacapac
Pacas
Pacchiana
Paccione
Pace
Pacek
Pacella
Pacelli
Pacenta
Pacer
Pacetti
Pacewicz
Pacey
Pach
Pachar
Pacheco
Pachelo
Pacheo
Pachero
Pachew
Pachla
Pachlin
Pacho
Pacholec
Pacholski
Pachter
Pachucki
Paci
Pacific
Pacifico
Pacilio
Pacini
Paciolla
Pacior
Paciorek
Pacitti
Pacitto
Pacius
Pack
Packard
Packebush
Packen
Packer
Packett
Packham
Packineau
Packingham
Packwood
Pacleb
Paco
Pacol
Pacquette
Pacquin
Pacubas
Paczkowski
Padalecki
Padamadan
Padarebones
Padavano
Padavich
Padberg
Paddack
Padden
Paddick
Paddilla
Paddio
Paddison
Paddock
Paddy
Padeken
Padel
Paden
Padfield
Padget
Padgett
Padgette
Padilla
Padillia
Padillo
Padin
Padinha
Padiong
Padley
Padlo
Padmanabhan
Padmore
Padol
Padon
Padovani
Padovano
Padro
Padron
Padua
Paduano
Padula
Pae
Paek
Paet
Paeth
Paetz
Paetzold
Paez
Pafel
Paff
Pafford
Paffrath
Pafundi
Paga
Pagaduan
Pagan
Paganelli
Pagani
Paganico
Paganini
Pagano
Pagdanganan
Page
Pageau
Pagel
Pagels
Pagenkopf
Pages
Paget
Pagett
Pagley
Paglia
Paglialunga
Pagliari
Pagliarini
Pagliaro
Paglinawan
Paglio
Paglione
Pagliuca
Pagnello
Pagni
Pagnozzi
Pago
Pagoda
Pagon
Pagonis
Paguin
Paguirigan
Pahk
Pahl
Pahler
Pahls
Pahmeier
Pahnke
Pahulu
Pai
Paider
Paige
Paik
Pailet
Paillant
Paille
Paillet
Pailthorpe
Pain
Paine
Paino
Painter
Painton
Pair
Paire
Pais
Paisley
Pait
Paith
Paiva
Paiz
Pajak
Pajerski
Pajtas
Pak
Pake
Pakele
Paker
Pakonen
Pal
Pala
Palacio
Palacios
Palacious
Palacois
Paladin
Paladini
Paladino
Palafox
Palagi
Palaia
Palakiko
Palamara
Palamino
Palange
Palanza
Palardy
Palas
Palasik
Palaspas
Palau
Palay
Palazola
Palazzi
Palazzo
Palazzola
Palazzolo
Palchetti
Palczewski
Palczynski
Pale
Paleaae
Palecek
Palek
Palen
Palencia
Palenik
Palenzuela
Paleo
Palermo
Palesano
Palese
Paletta
Palevic
Paley
Palfreyman
Palhegyi
Pali
Palifka
Palilla
Palin
Paling
Palinkas
Palino
Palinski
Paliotta
Palis
Palisano
Palisbo
Palischak
Palisi
Palitti
Palk
Palka
Palko
Pall
Palla
Palladino
Pallafor
Pallan
Pallanes
Pallansch
Pallant
Pallante
Pallares
Pallas
Pallazzo
Pallerino
Palleschi
Pallesen
Pallet
Pallett
Palley
Pallino
Pallone
Pallotta
Pallotto
Palm
Palma
Palmateer
Palmatier
Palmberg
Palme
Palmer
Palmeri
Palmerin
Palmerino
Palmero
Palmerton
Palmertree
Palmese
Palmeter
Palmieri
Palmiero
Palmino
Palmios
Palmiotto
Palmisano
Palmisciano
Palmiter
Palmitessa
Palmo
Palmore
Palmour
Palmquist
Palmrose
Palms
Palmucci
Palo
Paloma
Palomaki
Palomar
Palomares
Palomarez
Palomba
Palombit
Palombo
Palomin
Palomino
Palomo
Palone
Palos
Paloukos
Palovick
Palowoda
Pals
Palsgrove
Palso
Paltanavage
Palu
Palubiak
Paluch
Paluck
Paluk
Palumbo
Paluso
Paluszynski
Paluzzi
Palys
Pam
Pama
Pamer
Pamintuan
Pamperin
Pamphile
Pamplin
Pampusch
Pan
Pana
Panagakos
Panagiotopoul
Panagis
Panagos
Panagoulias
Panah
Panahon
Panak
Panakos
Panameno
Panarella
Panarello
Panaro
Panas
Panasci
Pancake
Panchak
Panchal
Panchana
Pancheri
Panchik
Pancho
Pancholi
Panciera
Pancoast
Panda
Pander
Pandey
Pandiani
Pandit
Pando
Pandola
Pandolfi
Pandolfo
Panduro
Pandy
Pandya
Pane
Panebianco
Paneczko
Panek
Panela
Panell
Panella
Panelli
Panepinto
Paneque
Panessa
Paneto
Panetta
Panfil
Panfilov
Pang
Pangallo
Pangan
Panganiban
Pangborn
Pangburn
Pangelina
Pangelinan
Pangilinan
Pangle
Pangrazio
Paniagua
Panias
Paniccia
Panich
Panico
Panik
Panila
Panis
Panitz
Pankake
Pankau
Panke
Pankey
Pankhurst
Pankiewicz
Pankiw
Panko
Pankow
Pankowski
Pankratz
Pannebaker
Pannell
Pannenbacker
Pannhoff
Panning
Pannone
Pannunzio
Panny
Pano
Panone
Panora
Panos
Panowicz
Panozzo
Panrell
Pansini
Pansullo
Pantaleo
Pantaleon
Pantalone
Pantano
Pante
Pantelakis
Panter
Pantera
Panther
Pantle
Panto
Pantoja
Pantojz
Pantoliano
Panton
Pantone
Pantoni
Pantosa
Pantuso
Panuccio
Panyik
Panyko
Panza
Panzarella
Panzarino
Panzella
Panzer
Panzica
Pao
Paola
Paolello
Paoletta
Paoletti
Paoletto
Paoli
Paolicelli
Paolini
Paolino
Paolucci
Paone
Paonessa
Paongo
Pap
Papa
Papadakis
Papadopoulos
Papageorge
Papagni
Papai
Papaioannou
Papakostas
Papale
Papaleo
Papalia
Papallo
Papan
Papandrea
Papania
Papanikolas
Papantonio
Paparella
Paparelli
Paparello
Paparo
Papas
Papasergi
Papay
Papazian
Papciak
Pape
Papelian
Papen
Papenfuss
Papetti
Papi
Papich
Papiernik
Papik
Papike
Papillion
Papin
Papineau
Papitto
Papka
Papke
Paplow
Paponetti
Papp
Pappa
Pappajohn
Pappalardo
Pappan
Pappas
Pappenheim
Papps
Pappy
Papranec
Paprocki
Papson
Papstein
Paquet
Paquette
Paquin
Para
Parada
Paradee
Paradis
Paradise
Paradiso
Parado
Paradowski
Parady
Paragas
Parah
Parajon
Paramo
Paramore
Paranada
Parara
Paras
Parat
Paratore
Paravano
Paravati
Paray
Parayno
Parayuelos
Paraz
Parbo
Parbol
Parbs
Parcel
Parcell
Parcells
Parchman
Parchment
Parco
Parda
Pardall
Parde
Pardee
Parden
Pardew
Pardey
Pardi
Pardieck
Pardini
Pardo
Pardoe
Pardon
Pardue
Parduhn
Pardun
Pardy
Pare
Paredes
Paredez
Paree
Pareja
Parekh
Parent
Parente
Parenteau
Parenti
Parents
Pares
Paretti
Parez
Parfait
Parfitt
Parga
Pargman
Pargo
Parham
Parhan
Parido
Pariente
Parihar
Parikh
Parilla
Parillo
Parinas
Paripovich
Paris
Parise
Pariseau
Pariser
Parish
Parisi
Parisian
Parisien
Parisio
Parizek
Parizo
Park
Parke
Parker
Parkers
Parkerson
Parkes
Parkey
Parkhill
Parkhouse
Parkhurst
Parkin
Parkins
Parkinson
Parkison
Parkman
Parkos
Parks
Parlato
Parlavecchio
Parle
Parlee
Parler
Parlet
Parlett
Parlier
Parliman
Parlin
Parlor
Parlow
Parm
Parma
Parmalee
Parman
Parmann
Parmantier
Parmar
Parmele
Parmelee
Parmely
Parmenter
Parmentier
Parmer
Parmeter
Parmley
Parms
Parnell
Parnes
Parness
Parnin
Paro
Parobek
Paroda
Parodi
Parody
Parolari
Parolini
Parone
Paronto
Parpan
Parquette
Parr
Parra
Parrack
Parraga
Parral
Parrales
Parramore
Parran
Parras
Parraz
Parreira
Parrella
Parreno
Parrent
Parrett
Parriera
Parrigan
Parrill
Parrilla
Parrillo
Parrin
Parrinello
Parrington
Parrino
Parriott
Parris
Parrish
Parron
Parrot
Parrott
Parrotta
Parrotte
Parrow
Parry
Parsa
Parsell
Parsells
Parsens
Parsh
Parshall
Parshotam
Parsi
Parsley
Parslow
Parson
Parsons
Parsygnat
Part
Partain
Partch
Partee
Partelow
Parten
Partenope
Parter
Parthemer
Parthemore
Partible
Partida
Partido
Partin
Partington
Partipilo
Partis
Partlow
Partman
Partmann
Parton
Partridge
Party
Partyka
Paruta
Parviainen
Parvin
Parvis
Parziale
Parzych
Pasana
Pasanen
Pasaya
Pasaye
Pascal
Pascale
Pascall
Pascanik
Pascarella
Pascarelli
Pascascio
Pasceri
Pasch
Paschal
Paschall
Pasche
Paschel
Pascher
Paschke
Pasco
Pascoal
Pascocello
Pascoe
Pascorell
Pascua
Pascual
Pascucci
Pasculli
Pascuzzi
Pase
Pasek
Paseur
Pasey
Pash
Pasha
Pashal
Pashea
Pashel
Pashia
Pashley
Pasho
Pasierb
Pasillas
Pasinski
Pasion
Paske
Paskel
Paskell
Paskert
Pasket
Paskett
Paskey
Paskiewicz
Paskin
Pasko
Paskoff
Paskow
Pasley
Pason
Pasqua
Pasqual
Pasquale
Pasqualetti
Pasqualino
Pasquarella
Pasquarelli
Pasquarello
Pasquariello
Pasquel
Pasquin
Pasquini
Pasquino
Pass
Passalacqua
Passantino
Passarella
Passarelli
Passaretti
Passaro
Passe
Passer
Passeri
Passerino
Passero
Passey
Passi
Passineau
Passini
Passino
Passley
Passman
Passmore
Passon
Passow
Passwater
Passy
Pastano
Pastel
Paster
Pasternack
Pasternak
Pastian
Pastick
Pastiva
Pasto
Pastor
Pastora
Pastore
Pastorin
Pastorino
Pastorius
Pastrana
Pastrano
Pastuch
Pastula
Pastures
Pasvizaca
Paswaters
Paszek
Paszkiewicz
Pat
Pata
Patadia
Patague
Patajo
Patak
Pataki
Patalano
Patane
Patanella
Patao
Patch
Patchell
Patchen
Patcher
Patches
Patchett
Patchin
Pate
Patee
Patek
Patel
Patella
Patellis
Paten
Patenaude
Pater
Patera
Paterniti
Paterno
Paterson
Pates
Patete
Pathak
Patience
Patient
Patierno
Patik
Patil
Patillo
Patin
Patino
Patka
Patlan
Patman
Patmon
Patmore
Patnaude
Patneaude
Patnode
Patock
Patocka
Patoine
Patolot
Paton
Patout
Patras
Patraw
Patria
Patriarco
Patrias
Patrice
Patrich
Patricia
Patricio
Patrick
Patridge
Patrie
Patrin
Patriquin
Patriss
Patron
Patrone
Patronella
Patrum
Patruno
Patry
Patrylak
Patsy
Patt
Pattee
Patten
Pattengale
Patter
Patterson
Patteson
Patti
Pattie
Pattillo
Pattinson
Pattison
Patton
Patts
Pattum
Patty
Pattyre
Patuel
Patuto
Patwell
Patz
Patzer
Patzke
Patzner
Pauda
Paugh
Paugsch
Pauk
Pauker
Paukert
Paukstis
Paul
Paula
Paulas
Paulauskas
Paulauskis
Paulding
Pauldo
Paule
Paules
Paulette
Pauley
Paulhus
Pauli
Paulic
Paulick
Paulik
Paulin
Paulina
Pauline
Pauling
Paulino
Paulis
Paulk
Paull
Paullin
Paullus
Paulman
Paulmino
Paulo
Paulos
Pauls
Paulsell
Paulsen
Paulseth
Paulshock
Paulson
Paulus
Pauly
Paup
Pausch
Paustian
Pautler
Pautz
Pauza
Pav
Pavan
Pavao
Paveglio
Pavek
Pavel
Pavelec
Pavelich
Pavelka
Pavelko
Pavella
Pavelski
Pavese
Pavey
Pavia
Pavich
Pavick
Paviol
Paviolitis
Pavis
Pavish
Pavlak
Pavlas
Pavlat
Pavletic
Pavlica
Pavlicek
Pavlich
Pavlick
Pavlides
Pavlik
Pavlikowski
Pavliska
Pavlo
Pavlock
Pavloski
Pavlosky
Pavlov
Pavlovic
Pavlovich
Pavolini
Pavon
Pavone
Pavoni
Pavy
Pawelczyk
Pawelek
Pawelk
Pawell
Pawlak
Pawley
Pawlicki
Pawlik
Pawlikowski
Pawlitschek
Pawloski
Pawlosky
Pawlowicz
Pawlowski
Pawluch
Pawluk
Pawlusiak
Pax
Paxman
Paxson
Paxton
Pay
Paya
Payamps
Payan
Payano
Payant
Payden
Paye
Payen
Payenda
Payer
Payes
Payette
Payeur
Paylor
Payment
Payn
Payna
Payne
Paynes
Payno
Paynter
Payor
Paysen
Payseur
Paysinger
Payson
Paysour
Paytes
Payton
Paywa
Paz
Pazan
Pazderski
Pazik
Pazmino
Pazo
Pazos
Pea
Peabody
Peace
Peacemaker
Peach
Peachay
Peacher
Peaches
Peachey
Peacock
Peacy
Pead
Peaden
Peagler
Peairs
Peak
Peake
Peaker
Peakes
Peaks
Peal
Peale
Pealer
Peals
Pean
Pear
Pearce
Pearcey
Pearcy
Peard
Peare
Pearl
Pearle
Pearlman
Pearlstein
Pearman
Pears
Pearsall
Pearse
Pearson
Peart
Peary
Pearyer
Peasant
Pease
Peasel
Peaslee
Peasley
Peasnall
Peat
Peatman
Peatross
Peatry
Peavey
Peavler
Peavy
Peay
Pebbles
Pebley
Pebsworth
Pebworth
Peca
Pecanty
Pecararo
Pecarina
Pecatoste
Pecci
Peccia
Pech
Pecha
Pechacek
Pechaira
Pechal
Pechar
Pechart
Peche
Pecher
Pechin
Pechon
Pecht
Pecina
Pecinousky
Pecinovsky
Peck
Pecka
Peckenpaugh
Peckens
Peckham
Peckinpaugh
Peckler
Peckman
Peco
Pecor
Pecora
Pecoraino
Pecoraro
Pecore
Pecorelli
Pecos
Pecot
Pectol
Pecue
Pecukonis
Ped
Pedaci
Pedde
Pedder
Peddicord
Peddie
Peddy
Pede
Pedeare
Pedelty
Peden
Pedersen
Pederson
Pederzani
Pedez
Pedigo
Pedlar
Pedley
Pedlow
Pedone
Pedraja
Pedralba
Pedraza
Pedregon
Pedretti
Pedri
Pedrick
Pedrin
Pedro
Pedrogo
Pedroncelli
Pedroni
Pedrosa
Pedroso
Pedrotti
Pedroza
Pedrozo
Pedulla
Peduto
Peduzzi
Pee
Peebles
Peecha
Peed
Peeden
Peedin
Peek
Peeks
Peel
Peele
Peeler
Peeling
Peelle
Peelman
Peels
Peeples
Peer
Peerbolt
Peers
Peery
Peerzada
Peet
Peete
Peeters
Peetoom
Peets
Peetz
Peevey
Peevy
Pefanis
Peffer
Pefferkorn
Pefferman
Peffers
Peffley
Peffly
Pegelow
Pegeron
Pegg
Peggs
Pegler
Pegoda
Pegram
Peguero
Pegues
Peguese
Peha
Pehl
Pehler
Pehowic
Pehowich
Pehrson
Peick
Peifer
Peiffer
Peight
Peightal
Peightell
Peil
Pein
Peinado
Peine
Peiper
Peirce
Peirson
Peitz
Peixoto
Pekala
Pekar
Pekara
Pekarek
Pekas
Pekrul
Pel
Pela
Pelaez
Pelak
Pelayo
Pelc
Pelch
Pelchat
Pelcher
Pelczar
Pele
Pelech
Peleg
Peles
Pelfrey
Pelham
Peli
Pelikan
Pelini
Pelino
Pelis
Pelissier
Pelkey
Pelkowski
Pell
Pella
Pellam
Pelland
Pellant
Pelle
Pellecchia
Pellegren
Pellegrin
Pellegrini
Pellegrino
Peller
Pellerin
Pellerito
Pellet
Pelletier
Pelletiu
Pellett
Pelley
Pellham
Pelliccia
Pellicone
Pellietier
Pelligra
Pelligrini
Pelligrino
Pellin
Pellish
Pellissier
Pellitier
Pellitteri
Pellman
Pellom
Pellon
Pellot
Pellow
Pellowski
Pellum
Pelman
Pelnar
Pelo
Peloquin
Pelosi
Peloso
Pelot
Pelote
Pelotte
Pelow
Pelphrey
Pelt
Pelter
Peltier
Pelto
Pelton
Peltz
Peltzer
Peluse
Peluso
Pelyo
Pelz
Pelzel
Pelzer
Pember
Pemberton
Pemble
Pembleton
Pembroke
Pembrook
Pemelton
Pen
Pena
Penado
Penaflor
Penagos
Penaherrera
Penale
Penalosa
Penaloza
Penalver
Penanegra
Penas
Penasa
Penatac
Penate
Penaz
Penberthy
Pencak
Pence
Penceal
Pencek
Pencil
Pendarvis
Pendegraft
Pendelton
Pender
Penderel
Pendergast
Pendergraft
Pendergraph
Pendergrass
Pendergrast
Penders
Pendexter
Pendill
Pendl
Pendleton
Pendley
Pendola
Pendon
Pendrak
Pendry
Penegar
Penepent
Penez
Penfield
Penfold
Peng
Pengelly
Pengra
Penha
Penhall
Penhallurick
Penhollow
Penick
Penigar
Peninger
Penington
Penird
Penisson
Penister
Peniston
Penix
Penkalski
Penkins
Penland
Penley
Penman
Penn
Penna
Pennacchio
Pennachio
Pennant
Pennebaker
Pennel
Pennell
Pennella
Pennelle
Pennello
Penner
Pennewell
Penney
Pennick
Pennie
Pennig
Pennigton
Penniman
Pennimpede
Penning
Penninger
Pennington
Pennino
Pennisi
Pennison
Penniston
Pennix
Pennock
Penny
Pennycuff
Pennypacker
Pennywell
Peno
Penovich
Penoyer
Penquite
Penrice
Penrod
Penrose
Pensa
Pense
Pensick
Pensiero
Pensinger
Pensis
Penski
Pensky
Penso
Penson
Pent
Penta
Pentaris
Pentecost
Pentek
Pentico
Penticoff
Pentland
Penton
Penttila
Pentz
Penuel
Penunuri
Penwarden
Penwell
Penya
Penz
Penza
Penzel
Penzero
Penzien
Peon
People
Peoples
Pepe
Peper
Pepez
Pepin
Pepion
Pepito
Pepitone
Pepka
Peplau
Peplinski
Peppard
Peppas
Peppe
Peppel
Pepper
Pepperman
Peppers
Peppin
Pepple
Peppler
Pequeno
Peques
Pera
Peragine
Peraha
Peral
Perales
Peralez
Peralta
Peralto
Peranio
Peraro
Perault
Peraza
Perazzo
Perce
Percell
Percey
Perch
Perches
Perchinski
Perciballi
Percifield
Perciful
Percival
Percle
Percontino
Percy
Perdew
Perdomo
Perdue
Perdzock
Pere
Perea
Pereda
Peredo
Peredz
Perego
Peregoy
Peregrino
Pereida
Pereira
Pereiro
Perella
Perelman
Perencevich
Perera
Pereria
Peres
Peressini
Peret
Peretti
Peretz
Perey
Pereyda
Pereyra
Perez
Perfater
Perfect
Perfecto
Perfetti
Pergande
Pergerson
Pergola
Pergram
Perham
Peri
Peria
Perich
Perico
Perie
Periera
Perigo
Perilli
Perillo
Perilloux
Perin
Perina
Perine
Perini
Perino
Perish
Perisho
Perkerson
Perkes
Perkey
Perkin
Perking
Perkins
Perkinson
Perkiss
Perko
Perkoski
Perkowski
Perks
Perl
Perla
Perlas
Perler
Perley
Perlich
Perlin
Perlman
Perlmutter
Perloff
Perlow
Perlson
Perlstein
Perman
Permann
Permenter
Perna
Pernell
Pernesky
Perney
Perng
Pernice
Perniciaro
Pernin
Perno
Pernod
Pero
Perocho
Peroddy
Peroff
Perolta
Peron
Perona
Perone
Peroni
Peros
Perot
Perotta
Perotti
Peroutka
Perow
Perozo
Perpall
Perper
Perque
Perr
Perra
Perras
Perrault
Perre
Perreault
Perreira
Perrell
Perrella
Perrelli
Perrenoud
Perrera
Perret
Perrett
Perretta
Perrette
Perretti
Perrez
Perri
Perricone
Perriello
Perrien
Perrier
Perrigan
Perrigo
Perrill
Perrilloux
Perrin
Perrine
Perring
Perrington
Perrino
Perrins
Perriott
Perris
Perrish
Perritt
Perro
Perrodin
Perron
Perrone
Perrot
Perrota
Perrott
Perrotta
Perrotti
Perrow
Perrucci
Perruzza
Perruzzi
Perry
Perryman
Pers
Persad
Persall
Persampieri
Persaud
Persch
Perschall
Perschbacher
Persechino
Pershall
Pershing
Persia
Persichetti
Persico
Persing
Persinger
Persky
Persley
Person
Personette
Personius
Persons
Persson
Persten
Persyn
Pert
Pertea
Pertee
Perteet
Pertsovsky
Pertubal
Pertuit
Peru
Perugini
Perun
Perusse
Peruzzi
Pervine
Pervis
Pery
Perz
Perza
Perzanowski
Perze
Pesa
Pesante
Pesantes
Pesarchick
Pesavento
Pescador
Pescatore
Pesce
Pesch
Peschel
Peschong
Pesek
Pesenti
Pesh
Peshek
Peshlakai
Pesick
Pesicka
Pesin
Pesina
Pesiri
Peskin
Peskind
Pesnell
Pesner
Pesola
Pesqueira
Pesses
Pessin
Pesso
Pessoa
Pessolano
Pesta
Pestana
Pestano
Pester
Pesterfield
Pestka
Pesto
Pestone
Pestoni
Pestronk
Peszynski
Petaccio
Petalcu
Petanick
Petaway
Petch
Petchulis
Pete
Peteet
Petek
Petela
Petell
Peter
Peterka
Peterkin
Peterman
Petermann
Petermeier
Peters
Peterschick
Petersdorf
Petersen
Petersheim
Petersik
Peterson
Petersson
Petesic
Petet
Peteuil
Petges
Petgrave
Peth
Pethtel
Petiet
Petigny
Petillo
Petit
Petite
Petitjean
Petito
Petitt
Petitte
Petitti
Petitto
Petix
Petka
Petko
Petkoff
Petkus
Peto
Petosa
Petr
Petraglia
Petrain
Petrak
Petrakis
Petralba
Petralia
Petramale
Petrarca
Petras
Petrash
Petrauskas
Petre
Petrea
Petrecca
Petree
Petrella
Petrelli
Petrello
Petretti
Petrey
Petri
Petric
Petriccione
Petrich
Petrick
Petricka
Petricone
Petrides
Petrie
Petriello
Petrik
Petrilla
Petrilli
Petrillo
Petrillose
Petrin
Petrina
Petrini
Petrino
Petris
Petrizzo
Petro
Petrocco
Petrocelli
Petrochello
Petroff
Petron
Petrone
Petronella
Petronio
Petronis
Petronzio
Petropoulos
Petropulos
Petros
Petrosino
Petroske
Petroski
Petrosky
Petross
Petrossian
Petrosyan
Petrouits
Petrov
Petrovic
Petrovich
Petrovits
Petrowski
Petrson
Petru
Petruccelli
Petrucci
Petrucco
Petrucelli
Petrulis
Petrullo
Petrunger
Petrus
Petruska
Petrusky
Petruso
Petruzzelli
Petruzzi
Petry
Petsch
Petsche
Pett
Petta
Pettas
Pettaway
Pettay
Pettengill
Petter
Petters
Pettersen
Petterson
Pettersson
Pettes
Pettet
Pettett
Petteway
Pettey
Petti
Pettibon
Pettibone
Petticrew
Pettie
Petties
Pettiford
Pettigrew
Pettigrove
Pettijohn
Pettinato
Pettine
Pettinella
Pettinelli
Pettinger
Pettingill
Pettipas
Pettis
Pettit
Pettitt
Pettiway
Pettner
Petton
Pettrey
Pettry
Petts
Pettus
Pettway
Petty
Pettyjohn
Petula
Petway
Petz
Petzel
Petzold
Petzoldt
Peugh
Pevahouse
Pevehouse
Peveler
Peverini
Peveto
Pevey
Pevez
Pevsner
Pevy
Pew
Pewitt
Pewo
Pexsa
Pexton
Peyatt
Peyer
Peyre
Peyser
Peyton
Pezez
Pezina
Pezley
Pezzano
Pezzetti
Pezzica
Pezzimenti
Pezzullo
Pezzulo
Pezzuti
Pezzuto
Pfaff
Pfaffinger
Pfahl
Pfahler
Pfahlert
Pfalmer
Pfalzgraf
Pfander
Pfannenstein
Pfannenstiel
Pfanstiel
Pfarr
Pfau
Pfautz
Pfeffer
Pfefferkorn
Pfefferle
Pfeifer
Pfeiff
Pfeiffenberge
Pfeiffer
Pfeifle
Pfeil
Pfeister
Pfendler
Pfenning
Pfeuffer
Pfieffer
Pfifer
Pfingsten
Pfirsch
Pfister
Pfisterer
Pflanz
Pfleger
Pfleider
Pfleiderer
Pfleuger
Pflieger
Pfliger
Pflueger
Pflug
Pfluger
Pflugh
Pflughoeft
Pflugrad
Pflugradt
Pflum
Pfnister
Pfohl
Pforr
Pfost
Pfotenhauer
Pfoutz
Pfrogner
Pfrommer
Pfuhl
Pfund
Pfundt
Phagan
Phair
Phalen
Pham
Phan
Phanco
Phaneuf
Phang
Phann
Phanor
Phanord
Phanthanouvon
Phanthauong
Phanthavongsa
Pharao
Phare
Pharel
Phares
Pharis
Phariss
Pharmer
Pharmes
Pharo
Pharr
Pharris
Phatdouang
Phaup
Phay
Phaymany
Phearsdorf
Pheasant
Phebus
Phegley
Phelan
Phelka
Phelp
Phelps
Phelts
Phenes
Phenix
Pheonix
Pherguson
Pherigo
Phernetton
Pherson
Phetphongsy
Phetsanghane
Phetteplace
Phi
Phibbs
Phifer
Philabaum
Philavanh
Philavong
Philbeck
Philben
Philbert
Philbin
Philbrick
Philbrook
Phildor
Philen
Philhower
Philibert
Philio
Philip
Philipose
Philipp
Philippe
Philippi
Philippon
Philipps
Philips
Philipson
Philley
Phillians
Philliber
Phillies
Phillip
Phillipi
Phillippe
Phillippi
Phillippy
Phillips
Phillipson
Phillis
Phillps
Philman
Philmon
Philmore
Philo
Philogene
Philp
Philpot
Philpott
Philpotts
Philps
Philson
Philyaw
Phimpradapsy
Phimsoutham
Phinazee
Phinisee
Phinney
Phippard
Phippen
Phippin
Phipps
Phlegm
Phlieger
Pho
Phoenix
Phoeuk
Phom
Phommajack
Phommaseng
Phommatheth
Phomphithak
Phomsoukha
Phong
Phonharath
Phorng
Phothirath
Phou
Phoubandith
Phoun
Phramany
Phu
Phuaphes
Phuma
Phung
Phuong
Phurrough
Phy
Phyfe
Phyfiher
Pi
Pia
Piacente
Piacenza
Piacitelli
Piacquadio
Pian
Pianalto
Pianka
Piano
Piantanida
Piao
Piascik
Piasecki
Piatak
Piatek
Piatkowski
Piatt
Piatz
Piazza
Pica
Picado
Picard
Picardi
Picardo
Picarello
Picariello
Picaro
Picart
Picasso
Picazo
Piccard
Picchetti
Picchi
Picciano
Piccillo
Piccinich
Piccinini
Piccinone
Piccione
Piccioni
Piccirilli
Piccirillo
Picciuto
Picco
Piccola
Piccoli
Piccolo
Piccolomini
Piccone
Piccuillo
Piceno
Picerni
Picerno
Picetti
Pich
Picha
Pichard
Pichardo
Piche
Picher
Pichette
Pichler
Pichoff
Pichon
Picht
Picini
Pick
Pickar
Pickard
Pickel
Pickell
Pickelsimer
Picken
Pickenpaugh
Pickens
Picker
Pickerel
Pickerell
Pickerill
Pickering
Pickersgill
Pickert
Picket
Picketpin
Pickett
Pickette
Picketts
Pickford
Pickhardt
Picking
Pickings
Pickl
Pickle
Pickler
Pickles
Picklesimer
Pickman
Picknell
Pickney
Pickrel
Pickrell
Pickren
Pickron
Pickup
Pico
Picolet
Picon
Picone
Picot
Picotte
Picou
Picozzi
Picquet
Picton
Picucci
Pidcock
Pidgeon
Pidro
Piearcy
Piech
Piechocki
Piechoski
Piechota
Piechowski
Piecuch
Pieczynski
Piede
Piedigrossi
Piedmont
Piedra
Piedrahita
Piefer
Pieffer
Piegaro
Piehl
Piehler
Piek
Piekarski
Piekos
Piel
Piela
Pieloch
Pielow
Piening
Pienta
Pientka
Piepenbrink
Piepenburg
Pieper
Piepho
Pier
Pierannunzio
Pieratt
Pierce
Pierceall
Piercefield
Piercey
Piercy
Pierdon
Piere
Pieretti
Pierfax
Pieri
Pierini
Piermarini
Piermatteo
Piermont
Pieroni
Pierotti
Pierpoint
Pierpont
Pierre
Pierri
Pierrie
Pierro
Pierron
Pierrot
Pierrott
Piersall
Piersaul
Piersiak
Piersol
Pierson
Piertraccini
Pierzchala
Pies
Piesco
Pieters
Pietig
Pietila
Pietrafesa
Pietras
Pietrini
Pietrok
Pietropaolo
Pietrowicz
Pietrowski
Pietryga
Pietrzak
Pietrzyk
Pietrzykowski
Pietsch
Pietschman
Piette
Piety
Pietz
Pietzsch
Pifer
Piganelli
Pigao
Pigat
Pigeon
Pigford
Pigg
Piggee
Piggie
Piggott
Piggs
Pigler
Pigman
Pigna
Pignataro
Pignatelli
Pignatello
Pignone
Pignotti
Pigott
Pigram
Pigue
Piguet
Pih
Pihl
Pihlaja
Piirto
Pijanowski
Pike
Piker
Pikes
Pikey
Pikkarainen
Pikul
Pikula
Pikus
Pila
Pilakowski
Piland
Pilant
Pilapil
Pilar
Pilarski
Pilarz
Pilat
Pilati
Pilato
Pilbin
Pilch
Pilcher
Pilchowski
Pile
Pileggi
Piles
Pilette
Pilger
Pilgreen
Pilgrim
Pili
Piliero
Pilkenton
Pilkerton
Pilkey
Pilkington
Pilkins
Pilkinton
Pill
Pilla
Pillado
Pillai
Pillar
Pillard
Pillarella
Pille
Piller
Pillers
Pillette
Pilley
Pilling
Pillion
Pillips
Pillitteri
Pillo
Pillon
Pillot
Pilloud
Pillow
Pillsbury
Pilon
Pilot
Pilotte
Pilotti
Pilsner
Pilson
Piltz
Piluso
Pilz
Pim
Pimenta
Pimental
Pimentel
Pimpare
Pimple
Pin
Pina
Pinal
Pinales
Pinard
Pinault
Pinc
Pince
Pinch
Pinchback
Pinchbeck
Pinchock
Pinchon
Pinciaro
Pincince
Pinckard
Pinckley
Pinckney
Pincock
Pincus
Pindell
Pinder
Pine
Pineau
Pineault
Pineda
Pinedo
Pinegar
Pineiro
Pinela
Pinell
Pinelli
Pinello
Pinelo
Pinena
Pineo
Piner
Pinera
Pinero
Pines
Pinet
Pinette
Ping
Pingel
Pinger
Pingitore
Pingleton
Pingree
Pingrey
Pinheiro
Pini
Pinick
Pinilla
Pinion
Pink
Pinkard
Pinke
Pinkelton
Pinkenburg
Pinkerman
Pinkert
Pinkerton
Pinkett
Pinkey
Pinkham
Pinkins
Pinkleton
Pinkley
Pinkney
Pinkos
Pinkowski
Pinks
Pinkstaff
Pinkston
Pinkton
Pinley
Pinn
Pinna
Pinnell
Pinneo
Pinner
Pinnette
Pinney
Pinnick
Pinnix
Pinnock
Pinnow
Pinnt
Pino
Pinon
Pinski
Pinsky
Pinson
Pinsoneault
Pinsonnault
Pinsonneault
Pinta
Pintado
Pintar
Pintea
Pintello
Pinter
Pinto
Pintor
Pintos
Pinuelas
Pinyan
Pinzino
Pinzon
Pinzone
Pio
Pioche
Pioli
Piombino
Pion
Piontek
Piontkowski
Piorkowski
Pioske
Piotrowski
Pipe
Piper
Pipes
Pipher
Pipho
Pipia
Pipilas
Pipkin
Pipkins
Pippen
Pippenger
Pippens
Pipper
Pippert
Pippin
Pippins
Pippitt
Pique
Piquette
Piraino
Pirc
Pires
Pirie
Pirieda
Pirillo
Pirkey
Pirkl
Pirkle
Pirman
Pirner
Pirnie
Piro
Pirog
Pirolli
Pirollo
Pirone
Piros
Piroso
Pirozhkov
Pirre
Pirrello
Pirro
Pirrone
Pirrotta
Pirtle
Pisani
Pisano
Pisarski
Pischke
Pisciotta
Pisciotti
Piscitelli
Piscitello
Pisco
Piscopo
Pisegna
Piselli
Piserchio
Pisha
Pishko
Pishner
Pisicchio
Piske
Piskel
Piskura
Pistelli
Pistilli
Pistole
Pistone
Pistoresi
Pistorius
Pistulka
Pisula
Piszczatowski
Piszczek
Pita
Pitaniello
Pitarresi
Pitassi
Pitcairn
Pitcak
Pitcavage
Pitch
Pitcher
Pitcherello
Pitchford
Pitcock
Pitek
Pitel
Pitfield
Pithan
Pitka
Pitkin
Pitman
Pitmon
Pitner
Pitney
Pitocco
Pitonyak
Pitorak
Pitpitan
Pitre
Pitruzzello
Pitsch
Pitsenbarger
Pitstick
Pitt
Pitta
Pittard
Pittari
Pittelkow
Pittenger
Pitter
Pittillo
Pittinger
Pittman
Pittmann
Pittmon
Pittner
Pitts
Pittsenbarger
Pittsinger
Pittsley
Pituch
Pitz
Pitzen
Pitzer
Piurkowski
Pius
Pivec
Pivin
Piwetz
Piwowar
Pixler
Pixley
Pizana
Pizani
Pizano
Pizarro
Pizer
Pizira
Pizur
Pizza
Pizzano
Pizzaro
Pizzella
Pizzi
Pizzico
Pizzini
Pizzino
Pizzitola
Pizzo
Pizzola
Pizzolato
Pizzulo
Pizzuti
Pizzuto
Pjetrovic
Plaas
Place
Placek
Placencia
Placencio
Placeres
Placha
Plachecki
Placide
Placido
Placino
Plack
Placke
Placker
Plackett
Placko
Placzek
Pladson
Plageman
Plagens
Plagge
Plagman
Plagmann
Plahs
Plain
Plainy
Plair
Plaisance
Plaisted
Plake
Plakke
Plambeck
Plamer
Plamondin
Plamondon
Plan
Plana
Planagan
Planas
Plancarte
Plance
Planck
Plane
Planer
Plank
Plankey
Plansinis
Plant
Plante
Plantenberg
Plantenga
Plantier
Plants
Planty
Plantz
Plascencia
Plasencia
Plaskett
Plasky
Plass
Plasse
Plassman
Plassmann
Plassmeyer
Plaster
Plastow
Plata
Platania
Platas
Plate
Platek
Platenburg
Plater
Platero
Plateros
Plateroti
Plath
Plathe
Platko
Platner
Plato
Platt
Platte
Platten
Platter
Plattner
Platts
Plattsmier
Platz
Platzer
Plauche
Plaugher
Plaut
Plautz
Plavnik
Plaxco
Plaxico
Player
Playford
Playl
Playle
Plaza
Plazza
Pleas
Pleasant
Pleasanton
Pleasants
Pleasent
Pleasure
Pleau
Plecker
Pledger
Pleet
Plegge
Pleil
Pleiman
Pleiss
Pleitez
Plemel
Plemmons
Plemons
Plenskofski
Plenty
Pleppo
Plesant
Plescia
Plese
Plesha
Pleshe
Pleskac
Plesnarski
Pless
Plessinger
Plessis
Plessner
Pletcher
Pletsch
Plett
Pletz
Pleva
Plevin
Plew
Plewa
Plewinski
Plexico
Pliego
Plienis
Plikerd
Pliler
Pliml
Plimpton
Pline
Pliner
Pliska
Plitt
Plocek
Ploch
Plocher
Plocica
Plock
Ploeger
Ploennigs
Ploense
Ploetz
Plohr
Plomma
Plona
Plonka
Ploof
Plosker
Ploskunak
Ploss
Ploszaj
Plotkin
Plotner
Plotnik
Plotrowski
Plott
Plotts
Plotz
Plotzker
Ploude
Plouffe
Plough
Plourd
Plourde
Plover
Plowden
Plowe
Plowman
Pluck
Plude
Plue
Plueger
Pluemer
Plues
Pluff
Pluhar
Pluid
Plum
Pluma
Plumadore
Plumb
Plumbar
Plumber
Plume
Plumer
Plumlee
Plumley
Plummer
Plump
Plumpton
Plungy
Plunk
Plunket
Plunkett
Plush
Pluta
Plutt
Pluviose
Pluvoise
Pluym
Ply
Plyer
Plyler
Plymale
Plymel
Plymire
Plympton
Plys
Pniewski
Po
Poag
Poage
Poague
Poaipuni
Poalino
Poarch
Poat
Pobanz
Poblete
Pobre
Pocai
Pocasangre
Pocchia
Pocekay
Poch
Pochatko
Poche
Pochiba
Pochintesta
Pociask
Pociengel
Pocius
Pock
Pockette
Pocklington
Pockrus
Pocock
Poczobut
Pod
Podany
Podaras
Podbielski
Pode
Podell
Podesta
Podeszwa
Podewils
Podgurski
Podkowka
Podlas
Podmore
Podolak
Podolsky
Podrasky
Podratz
Podraza
Podsiad
Poduska
Podvin
Podwoski
Pody
Poe
Poehlein
Poehler
Poehlman
Poeling
Poellinetz
Poellnitz
Poellot
Poelman
Poeppel
Poeppelman
Poepping
Poepplein
Poer
Poertner
Poeschel
Poeschl
Poet
Poetker
Poette
Poetter
Poetzsch
Pofahl
Poff
Poffenberger
Poffenroth
Pogar
Poggi
Poggio
Pogorelc
Pogozelski
Pogue
Pohl
Pohler
Pohlman
Pohlmann
Pohlson
Pohorilla
Poindexter
Poinelli
Poinsett
Poinsette
Poinson
Point
Pointdexter
Pointe
Pointer
Pointon
Points
Poire
Poirer
Poirier
Poirot
Poirrier
Poisel
Poissant
Poisso
Poisson
Poissonnier
Poister
Poiter
Poitevin
Poitevint
Poitier
Poitra
Poitras
Pok
Pokallas
Poke
Pokoj
Pokora
Pokorney
Pokorny
Pokorski
Pokrzywa
Pokswinski
Pol
Pola
Polacco
Polacek
Polachek
Polack
Polaco
Poladian
Polak
Polakis
Polakoff
Polakowski
Polan
Polanco
Poland
Polanski
Polansky
Polasek
Polashek
Polaski
Polasky
Polchinski
Polcovich
Polcyn
Polczynski
Poldrack
Pole
Poledore
Polee
Polek
Polemeni
Polen
Polera
Poles
Poletski
Poletti
Poley
Poleyestewa
Polfer
Polhamus
Polhemus
Polhill
Poli
Polian
Policar
Policare
Policastri
Policastro
Police
Polich
Policicchio
Policz
Polidore
Polidori
Polidoro
Polikoff
Poliks
Polimeni
Polin
Poling
Polino
Polinski
Polinsky
Polintan
Polio
Poliquin
Polisky
Polisoto
Polit
Politano
Polite
Politi
Politis
Polito
Politowski
Politte
Politz
Polivick
Polivka
Polizio
Polizzi
Poljak
Polk
Polka
Polkinghorn
Poll
Pollacco
Pollack
Pollak
Pollan
Polland
Pollara
Pollard
Pollaro
Pollart
Polle
Pollen
Pollet
Pollett
Polley
Pollica
Pollick
Pollina
Pollinger
Pollins
Pollio
Pollitt
Pollman
Pollmann
Pollnow
Pollo
Pollock
Pollok
Pollom
Pollot
Pollutro
Polly
Polnau
Polo
Poloskey
Polosky
Polovoy
Polowy
Polselli
Polsgrove
Polski
Polsky
Polson
Polster
Polston
Polter
Polton
Poltorak
Poltrock
Polucha
Polumbo
Polverari
Polvino
Polyak
Polycarpe
Polynice
Polzer
Polzin
Poma
Pomainville
Pomales
Pomar
Pomares
Pomarico
Pomberg
Pombo
Pomella
Pomerance
Pomerantz
Pomeranz
Pomerleau
Pomeroy
Pomfret
Pomiecko
Pomilla
Pommer
Pommier
Pomo
Pompa
Pompei
Pompey
Pompi
Pompilio
Pomplun
Pomponi
Pomponio
Pomposo
Pomrenke
Pomroy
Pomykala
Pon
Ponce
Poncedeleon
Poncho
Ponciano
Poncio
Pond
Ponder
Pondexter
Ponds
Pone
Ponessa
Pong
Pongkhamsing
Poniatoski
Poniatowski
Pono
Pons
Ponsler
Pont
Pontarelli
Pontbriand
Ponte
Ponter
Pontes
Ponti
Pontiff
Pontillo
Pontin
Ponting
Pontious
Pontius
Ponto
Ponton
Pontonio
Pontoriero
Pontremoli
Ponyah
Ponzi
Ponzio
Ponzo
Poock
Pool
Poole
Pooler
Pooley
Poolheco
Poon
Pooni
Poor
Poore
Poorman
Poormon
Poort
Poorte
Poortinga
Pooschke
Pooser
Poot
Poovey
Pooyouma
Pop
Popa
Popadiuk
Popat
Pope
Popec
Popejoy
Popek
Popelka
Poper
Popescu
Popham
Popi
Popichak
Popick
Popiel
Popielarczyk
Popik
Popiolek
Popke
Popken
Popkin
Poplar
Poplaski
Poplawski
Poplin
Popoca
Popoff
Popovec
Popovic
Popovich
Popovitch
Popowski
Popp
Poppe
Poppel
Poppell
Poppema
Poppen
Poppenhagen
Popper
Poppert
Popple
Poppleton
Popplewell
Poppo
Popularis
Popwell
Poque
Poquette
Pora
Porada
Porat
Porath
Porcaro
Porcelli
Porcello
Porch
Porche
Porcher
Porchia
Porco
Pore
Poreda
Poree
Porell
Poremba
Poremski
Porep
Porietis
Poro
Porowski
Porras
Porraz
Porrazzo
Porreca
Porrello
Porres
Porrini
Porris
Porritt
Porro
Porst
Port
Porta
Portal
Portalatin
Portales
Portaro
Porte
Portee
Portela
Portell
Portello
Porten
Porteous
Porter
Portera
Porterfield
Portes
Porteus
Porth
Portie
Portier
Portilla
Portillo
Portis
Portland
Portley
Portlock
Portman
Portner
Portney
Portnoff
Portnoy
Porto
Portolese
Portor
Portrum
Ports
Portsche
Portugal
Portune
Portuondo
Portwine
Portwood
Portz
Porzio
Posa
Posada
Posadas
Posas
Posch
Posen
Poser
Posey
Posik
Posis
Poska
Poskey
Poskitt
Poskus
Posley
Posner
Posnick
Pospicil
Pospishil
Pospisil
Poss
Posse
Possehl
Possick
Possinger
Posso
Posson
Post
Postal
Postel
Postell
Postema
Postemski
Posten
Poster
Postert
Posthuma
Posthumus
Postier
Postiglione
Postin
Postle
Postles
Postlethwait
Postlethwaite
Postlewait
Postlewaite
Postley
Postma
Posto
Poston
Postuci
Posusta
Potaczala
Potanovic
Potash
Pote
Poteat
Poteet
Poteete
Potempa
Potenza
Poter
Potes
Potestio
Poth
Pothier
Pothoven
Poths
Potier
Poties
Poto
Potocki
Potocnik
Potolsky
Potra
Potratz
Potsander
Pott
Pottebaum
Potteiger
Pottenger
Potter
Potters
Potterson
Potthast
Potthoff
Pottichen
Pottier
Pottinger
Pottkotter
Pottle
Pottorf
Pottorff
Potts
Potucek
Potulski
Potvin
Pou
Pouch
Pouche
Poucher
Poudrier
Pouge
Pough
Pouk
Poulet
Poulin
Pouliot
Pouliotte
Poulisse
Poullard
Poullion
Poulos
Poulsen
Poulson
Poulter
Poulton
Pouncey
Pouncil
Pouncy
Pound
Pounder
Pounders
Pounds
Poundstone
Poupard
Pour
Pourchot
Pourier
Pourner
Pourvase
Pousson
Poutre
Poux
Pov
Povey
Powal
Powanda
Powderly
Powe
Powel
Powell
Powells
Powelson
Power
Powers
Powis
Powledge
Powlen
Powles
Powless
Powley
Pownall
Pownell
Powroznik
Powsey
Powskey
Poxon
Poydras
Poyer
Poyneer
Poyner
Poynor
Poynter
Poynton
Poyser
Poythress
Pozar
Pozniak
Pozo
Pozos
Pozzi
Pozzo
Pozzobon
Pozzuoli
Prabel
Prabhakar
Prabhakaran
Prach
Pracht
Prada
Pradel
Prader
Pradhan
Pradier
Prado
Prag
Prager
Prahl
Prahm
Praino
Prairie
Prak
Prakash
Prakoth
Praley
Prall
Pralle
Praml
Pramuk
Prang
Prange
Pranger
Prante
Prasad
Prasek
Prashad
Praska
Prasomsack
Prass
Prasser
Prast
Prat
Prata
Pratcher
Prately
Prater
Prather
Prati
Pratico
Pratillo
Pratka
Pratley
Prato
Prator
Prats
Pratt
Pratte
Prattella
Pratten
Prattis
Pratts
Prauner
Prause
Pravata
Prawdzik
Prawl
Pray
Prayer
Praylow
Praytor
Prazak
Prazenica
Prazeres
Prazma
Prchal
Prchlik
Preas
Preast
Preato
Prebish
Preble
Precella
Precht
Prechtel
Prechtl
Preciado
Precise
Precissi
Precourt
Precythe
Preda
Preddy
Predmore
Predom
Predovich
Pree
Preece
Preedom
Preer
Prefontaine
Pregeant
Pregler
Preheim
Prehm
Prehn
Prehoda
Preis
Preisach
Preisel
Preisendorf
Preisinger
Preisler
Preisner
Preiss
Preisser
Preissler
Preissner
Preist
Preister
Preite
Prejean
Prejsnar
Prekker
Preli
Prell
Prellwitz
Prem
Premeaux
Premer
Premo
Prenatt
Prence
Prendergast
Prendes
Prenger
Prentice
Prentis
Prentiss
Prepotente
Presa
Presas
Presby
Prescod
Prescott
Preseren
Presgraves
Presha
Presho
Presiado
President
Preskar
Preskitt
Preslar
Presler
Presley
Preslipsky
Presnal
Presnall
Presnar
Presnell
Press
Pressel
Presser
Pressey
Pressimone
Pressler
Pressley
Pressly
Pressman
Pressnell
Presson
Presswood
Prest
Presta
Prestage
Prester
Presti
Prestia
Prestidge
Prestino
Prestipino
Prestley
Presto
Preston
Prestridge
Prestwich
Prestwood
Presume
Presutti
Prete
Preti
Pretlow
Pretti
Prettner
Pretty
Prettyman
Prety
Pretzel
Pretzer
Preuett
Preuitt
Preus
Preuss
Preusser
Prevatt
Prevatte
Prevento
Prevet
Prevett
Prevette
Previte
Prevo
Prevost
Prevot
Prewer
Prewett
Prewitt
Prey
Preyer
Preyor
Prez
Preza
Preziosi
Prezioso
Prezzia
Prial
Pribbeno
Pribbenow
Pribble
Pribish
Prible
Pribnow
Pribyl
Price
Pricer
Prich
Prichard
Prichett
Prickett
Priddy
Pride
Prideaux
Pridemore
Pridgen
Pridgeon
Pridgett
Pridham
Pridmore
Priebe
Priefert
Priegnitz
Priego
Priem
Prier
Pries
Priesmeyer
Priess
Priest
Priester
Priestley
Priestly
Prieto
Prieur
Priewe
Prigg
Prigge
Prigmore
Prill
Prillaman
Prim
Prima
Primack
Primas
Primavera
Prime
Primeau
Primeaux
Primer
Primes
Primiano
Primm
Primmer
Primo
Primos
Primozich
Primrose
Primus
Prince
Princevalle
Princiotta
Principato
Principe
Prindall
Prindiville
Prindle
Prine
Pring
Pringle
Prinkey
Prinkleton
Prinn
Prins
Printers
Printup
Printy
Printz
Prinz
Prinzi
Prinzing
Prinzivalli
Priode
Priolean
Prioleau
Prioletti
Priolo
Prior
Priore
Prisbrey
Prisco
Prisk
Prisoc
Prisock
Pritchard
Pritchell
Pritcher
Pritchet
Pritchett
Pritt
Pritts
Pritz
Pritzel
Pritzker
Privado
Privalsky
Privateer
Privatsky
Prive
Privett
Privette
Privitera
Privott
Prizio
Prizzi
Pro
Proa
Proano
Probasco
Probert
Probst
Probus
Proby
Procaccini
Procaccino
Procell
Proch
Prochak
Prochaska
Prochazka
Prochnow
Prociuk
Prock
Procknow
Proco
Procopio
Procsal
Procter
Proctor
Prodan
Prodoehl
Proehl
Proenza
Proescher
Profancik
Profera
Profeta
Proffer
Proffit
Proffitt
Profit
Profitt
Progacz
Progl
Prohaska
Prohonic
Proia
Proietto
Prok
Prokes
Prokop
Prokos
Proksch
Prokup
Prom
Promer
Promisco
Promise
Prondzinski
Pronk
Pronovost
Pronto
Proo
Proper
Propes
Prophet
Prophete
Propheter
Prophett
Prophit
Propp
Propper
Propps
Propst
Prosak
Prosch
Proscia
Prose
Prosenick
Prosienski
Prosise
Prosonic
Prospal
Prosper
Prosperi
Prosperie
Prospero
Pross
Prosser
Prost
Protain
Protano
Protas
Protasewich
Prothero
Prothro
Protich
Protin
Proto
Protsman
Prottsman
Protz
Protzman
Proud
Proudfoot
Proue
Proulx
Prouse
Prout
Prouty
Provance
Provazek
Proveaux
Provencal
Provence
Provencher
Provencio
Provent
Provenza
Provenzano
Provenzo
Providence
Province
Provine
Provines
Provino
Provins
Provis
Provitt
Provo
Provorse
Provost
Provosty
Provow
Prow
Prowant
Prowell
Prows
Prowse
Prucha
Pruchnik
Prucnal
Prudden
Prude
Pruden
Prudencio
Prudent
Prudente
Prudhomme
Prudom
Prue
Pruess
Pruessner
Prueter
Pruett
Pruette
Prugh
Pruiett
Pruit
Pruitt
Prukop
Prum
Pruna
Pruneau
Pruneda
Pruner
Prunier
Prunty
Prus
Prusak
Pruse
Prusha
Prusinski
Pruskowski
Pruss
Prust
Pruter
Prutt
Prutzman
Pruyn
Pruyne
Pruzansky
Prvitt
Pry
Prybylski
Pryce
Pryde
Prye
Pryer
Pryor
Prys
Prysock
Pryzgoda
Przedwiecki
Przekop
Przeniczny
Przepiora
Przewozman
Przybycien
Przybyl
Przybyla
Przybylski
Przybysz
Przybyszewski
Przygocki
Psencik
Psilovikos
Psomiades
Psuik
Psuty
Ptacek
Ptak
Ptaschinski
Ptaszynski
Ptomey
Pu
Pua
Public
Puc
Puca
Puccetti
Pucci
Puccia
Pucciarelli
Puccinelli
Puccini
Puccio
Pucella
Puchalla
Puchalski
Pucillo
Pucio
Pucker
Pucket
Puckett
Puckhaber
Puddephatt
Puddy
Pudenz
Pudlinski
Puebla
Puehler
Puello
Puelo
Puent
Puente
Puentes
Puerta
Puertas
Puerto
Puesey
Puett
Puetz
Puff
Puffenbarger
Puffenberger
Puffer
Puffett
Puffinberger
Puffinburger
Puga
Pugeda
Pugel
Pugh
Puglia
Pugliares
Pugliese
Puglisi
Pugmire
Pugsley
Puhala
Puhl
Puhr
Puhrman
Puhuyaoma
Puiatti
Puidokas
Puig
Puita
Pujals
Pujia
Pujol
Pujols
Pulanco
Pulaski
Pulcher
Puleio
Puleo
Pulera
Puletasi
Pulfer
Pulford
Pulfrey
Pulgarin
Pulham
Puliafico
Pulice
Pulido
Pulis
Pulizzi
Pulk
Pulkkinen
Pulkrabek
Pullam
Pullan
Pullano
Pullar
Pullara
Pullem
Pullen
Pullens
Puller
Pulley
Pulliam
Pullian
Pullie
Pullin
Pulling
Pullings
Pullins
Pullis
Pullman
Pullom
Pullon
Pullum
Pullus
Pully
Pulos
Puls
Pulse
Pulsifer
Pulte
Pultorak
Pults
Pultz
Pulver
Pulvermacher
Pulwer
Puma
Pumarejo
Pummel
Pummell
Pummill
Pump
Pumper
Pumphery
Pumphrey
Pun
Puna
Punch
Punches
Pundsack
Pundt
Pung
Punihaole
Punja
Punt
Punter
Puntillo
Punzo
Puorto
Puotinen
Pupa
Pupo
Puppe
Puppo
Puraty
Purce
Purcell
Purcella
Purchase
Purdie
Purdin
Purdom
Purdon
Purdue
Purdum
Purdy
Purfeerst
Purgason
Puri
Purifoy
Purington
Purinton
Purkerson
Purkett
Purkey
Purkhiser
Purkiss
Purl
Purnell
Purol
Purple
Purpora
Purpura
Purrington
Pursel
Pursell
Purser
Pursifull
Pursley
Purslow
Purswell
Purtee
Purtell
Purter
Purtill
Purtle
Purtlebaugh
Purugganan
Purves
Purviance
Purvines
Purvis
Purwin
Puryear
Purzycki
Pusateri
Pusch
Pusey
Push
Pushard
Pushaw
Pushcar
Puskar
Puskarich
Puskas
Pusser
Pust
Putalavage
Putaski
Putcha
Puterbaugh
Puthiyamadam
Puthoff
Putman
Putnal
Putnam
Putney
Putt
Putton
Putty
Putz
Putzel
Putzer
Putzier
Puulei
Puyear
Puz
Puzinski
Puzio
Puzo
Puzon
Py
Pyanowski
Pyatt
Pyburn
Pybus
Pych
Pychardo
Pye
Pyeatt
Pyer
Pyette
Pyfer
Pyfrom
Pyke
Pyland
Pylant
Pyle
Pyles
Pylvainen
Pyne
Pynes
Pyo
Pyon
Pyper
Pyrdum
Pyron
Pyros
Pyscher
Pysher
Pytel
Pytko
Pytlewski
Pytlovany
Pyun
Pywell
Qadeer
Qadir
Qare
Qasba
Qazi
Qian
Qin
Qiu
Qua
Quaas
Quach
Quackenbush
Quade
Quader
Quadnau
Quagliano
Quagliato
Quaglieri
Quaid
Quaife
Quail
Quaile
Quails
Quain
Quaintance
Quakenbush
Quaker
Quale
Qualey
Qualheim
Qualia
Quall
Qualle
Qualls
Quam
Quamme
Quammen
Quan
Quance
Quandel
Quander
Quandt
Quang
Quann
Quanstrum
Quant
Quante
Quaranta
Quaranto
Quaresma
Quarles
Quarnstrom
Quarrell
Quarry
Quartararo
Quartaro
Quarterman
Quartieri
Quartiero
Quarto
Quartucci
Quartuccio
Quasdorf
Quashie
Quashnock
Quast
Quastad
Quates
Quatraro
Quatrevingt
Quattlebaum
Quattrini
Quattro
Quattrocchi
Quattrone
Quave
Quay
Quaye
Quayle
Queal
Quealy
Quear
Quebedeaux
Quebral
Queeley
Queen
Queenan
Queener
Queja
Quelch
Quelette
Quella
Queller
Quellette
Quencer
Quenneville
Quent
Quenzel
Quenzer
Quercia
Quercioli
Quereto
Querido
Querio
Quero
Queros
Querry
Querta
Quertermous
Query
Quesada
Quesenberry
Quesinberry
Quesnel
Quesnell
Quest
Quettant
Quevedo
Quezad
Quezada
Quezaire
Quezergue
Quiambao
Quibodeaux
Quicho
Quick
Quickel
Quickle
Quicksall
Quicksey
Quidas
Quider
Quidley
Quiel
Quiet
Quiett
Quigg
Quiggle
Quigley
Quihuiz
Quijada
Quijano
Quijas
Quilantang
Quiles
Quilici
Quilimaco
Quilindrino
Quill
Quillan
Quillen
Quillens
Quiller
Quilliam
Quilliams
Quillian
Quillin
Quilling
Quillman
Quilter
Quilty
Quimby
Quimet
Quin
Quinalty
Quinby
Quince
Quincel
Quincey
Quinchia
Quinci
Quincy
Quine
Quinerly
Quink
Quinlan
Quinley
Quinlin
Quinlisk
Quinlivan
Quinn
Quinnan
Quinnett
Quinney
Quinnie
Quinoes
Quinones
Quinonez
Quint
Quintal
Quintana
Quintanar
Quintania
Quintanilla
Quintano
Quintard
Quintas
Quintel
Quintela
Quinter
Quintero
Quinteros
Quintin
Quinto
Quinton
Quintona
Quintyne
Quinzi
Quiralte
Quiram
Quirarte
Quire
Quirin
Quirindongo
Quiring
Quirino
Quirion
Quirk
Quirke
Quiroga
Quiros
Quiroz
Quisenberry
Quispe
Quist
Quitedo
Quiterio
Quitero
Quito
Quitter
Quittner
Quitugua
Quituqua
Quiver
Quivers
Quivoz
Quizon
Qunnarath
Quon
Quoss
Quraishi
Qureshi
Ra
Raab
Raabe
Raad
Raap
Raasch
Raatz
Rabadan
Rabago
Rabal
Rabalais
Rabara
Rabasca
Rabassa
Rabb
Rabbe
Rabbitt
Rabe
Rabeck
Rabehl
Rabel
Rabell
Rabello
Rabelo
Rabena
Rabeneck
Rabenhorst
Rabenold
Rabenstein
Raber
Rabern
Rabey
Rabideau
Rabidoux
Rabil
Rabin
Rabine
Rabinovich
Rabinowitz
Rabito
Rabjohn
Rabkin
Rabner
Raboin
Rabold
Rabon
Raborn
Rabren
Rabsatt
Rabuck
Rabun
Raburn
Rabuse
Raby
Racanelli
Racanello
Racano
Racca
Race
Racedo
Racer
Racette
Racey
Rach
Rachal
Rachar
Rachel
Rachell
Rachels
Rachi
Rachlin
Racicot
Racilis
Racina
Racine
Racioppi
Racioppo
Racitano
Raciti
Rack
Rackers
Rackett
Rackham
Racki
Rackley
Rackliffe
Racko
Rackow
Raco
Racz
Raczak
Raczka
Raczkowski
Raczynski
Rad
Rada
Radabaugh
Radaker
Radakovich
Radar
Radatz
Radcliff
Radcliffe
Raddatz
Radde
Radden
Radder
Raddle
Rade
Radebaugh
Radecki
Radej
Radeke
Radel
Radell
Rademacher
Rademaker
Rademan
Raden
Rader
Raderstorf
Radford
Radican
Radice
Radich
Radick
Radics
Radie
Radigan
Radilla
Radin
Radish
Radisovich
Radke
Radle
Radler
Radley
Radlinski
Radloff
Radmacher
Radmall
Radman
Radney
Rado
Radom
Radomski
Radon
Radona
Rados
Radosevich
Radoslovich
Radovich
Radsek
Radsky
Radtke
Raducha
Radue
Raduenz
Radulescu
Radune
Radunz
Radvany
Radwan
Radwanski
Radway
Radwick
Rady
Radzavich
Radziewicz
Radziwon
Rae
Raebel
Raeder
Raef
Raehl
Rael
Raelson
Raemer
Raes
Raeside
Raether
Raethke
Raetz
Rafael
Rafail
Rafala
Rafalko
Rafalski
Rafanan
Rafaniello
Rafel
Rafey
Raff
Raffa
Raffaele
Rafferty
Raffety
Raffield
Raffo
Raffone
Rafi
Rafidi
Rafiq
Rafla
Rafter
Raftery
Rafus
Rafuse
Ragain
Ragains
Ragan
Ragans
Ragar
Ragas
Ragasa
Ragazzo
Ragel
Rager
Raggio
Raggs
Raghunandan
Ragin
Ragins
Ragland
Ragle
Raglin
Raglow
Ragno
Rago
Ragon
Ragone
Ragonese
Ragsdale
Raguay
Ragula
Ragus
Ragusa
Ragusano
Raguso
Rahaim
Rahal
Rahall
Rahama
Rahaman
Rahe
Raheem
Raheja
Rahib
Rahim
Rahimi
Rahl
Rahm
Rahman
Rahmani
Rahmes
Rahming
Rahn
Rahoche
Rahr
Raia
Raible
Raiche
Raid
Raiden
Raider
Raif
Raiford
Raigosa
Raigoza
Raike
Raikes
Rail
Railes
Railey
Railing
Railsback
Raimann
Raimer
Raimo
Raimondi
Raimondo
Raimundo
Rain
Raina
Rainbolt
Rainbott
Rainbow
Raine
Rainer
Raines
Rainey
Rainford
Rainforth
Rainge
Rainha
Rainie
Rainier
Rainone
Rains
Rainville
Rainwater
Rainwaters
Raio
Raiola
Rairdon
Rais
Raisbeck
Raisch
Raisin
Raisler
Raisley
Raisor
Raith
Raithel
Raitt
Raitz
Raj
Raja
Rajala
Rajan
Rajaniemi
Rajaphoumy
Rajaratnam
Rajas
Rajewski
Rajk
Rajtar
Raju
Rajwani
Rak
Rake
Rakel
Raker
Rakers
Rakes
Rakestraw
Rakestrow
Rakich
Rakoci
Rakoczy
Rakoski
Rakow
Rakowski
Rakus
Rakyta
Ralat
Ralbovsky
Raleigh
Raley
Ralko
Rall
Rallis
Rallison
Ralls
Ralon
Ralph
Ralphs
Ralston
Ram
Rama
Ramach
Ramadan
Ramadanovic
Ramagano
Ramage
Ramagos
Ramaker
Ramal
Ramales
Raman
Ramano
Ramariz
Ramaswamy
Ramaudar
Rambeau
Ramberg
Rambert
Rambin
Rambo
Rambousek
Rambus
Ramcharan
Ramcharran
Ramdas
Ramdeo
Rameau
Ramelb
Ramelize
Ramella
Ramelli
Ramento
Ramer
Rameres
Ramerez
Rameriez
Rameriz
Ramero
Rames
Ramesar
Ramesh
Rametta
Ramey
Ramez
Ramgel
Ramie
Ramiez
Ramil
Ramin
Raminez
Ramire
Ramirec
Ramirel
Ramires
Ramirez
Ramiriz
Ramiro
Ramis
Ramiscal
Ramjan
Ramjhon
Ramkissoon
Ramlakhan
Ramlall
Ramler
Ramm
Rammer
Ramming
Ramnarase
Ramnarine
Ramnauth
Ramo
Ramon
Ramone
Ramones
Ramonez
Ramos
Ramotar
Ramoutar
Ramp
Rampa
Rampadarat
Rampersad
Rampey
Ramphal
Rampley
Rampton
Rampulla
Rampy
Ramrez
Ramrirez
Ramroop
Rams
Ramsahai
Ramsaroop
Ramsay
Ramsbottom
Ramsburg
Ramsby
Ramsdale
Ramsdell
Ramsden
Ramser
Ramseur
Ramsey
Ramseyer
Ramsfield
Ramshur
Ramsier
Ramson
Ramsour
Ramstad
Ramsuer
Ramsy
Ramthun
Ramu
Ramundo
Ramus
Ramy
Ran
Rana
Ranah
Ranalli
Ranallo
Ranaudo
Rancatti
Rance
Rances
Ranch
Rancher
Rancifer
Ranck
Rancourt
Rand
Randa
Randahl
Randal
Randall
Randazzo
Randel
Randell
Randgaard
Randhawa
Randklev
Randle
Randleman
Randles
Randlett
Rando
Randol
Randolf
Randoll
Randolph
Randon
Randrup
Rands
Randt
Randy
Randzin
Rane
Raner
Ranes
Raneses
Raney
Ranford
Ranft
Rang
Rangasammy
Range
Rangel
Ranger
Rangitsch
Rangnow
Ranieri
Raniero
Ranildi
Ranjel
Rank
Ranke
Rankhorn
Rankin
Rankins
Ranks
Ranmar
Rann
Rannalli
Rannells
Rannels
Ranney
Ranni
Ranno
Ranos
Ransberger
Ransbottom
Ransburg
Ransdell
Ransford
Ransick
Ransier
Ransler
Ransom
Ransome
Ranson
Ransone
Ransonet
Ranta
Rantanen
Rantz
Ranum
Ranweiler
Rao
Raoof
Rapa
Rapacki
Rapalo
Rapanot
Rapaport
Rape
Rapelyea
Raper
Raphael
Rapier
Rapin
Rapisura
Rapkin
Rapko
Rapkowicz
Rapley
Rapone
Raponi
Rapoport
Raposa
Rapose
Raposo
Rapoza
Rapozo
Rapp
Rappa
Rappaport
Rappe
Rappenecker
Rappl
Rappley
Rappleye
Rappleyea
Rappold
Rapson
Raptis
Rapuano
Raque
Raquel
Rarang
Rarden
Rardin
Rardon
Rarey
Rarick
Raridon
Raring
Rarogal
Rary
Ras
Rasanen
Rasavong
Rasband
Rasberry
Rasbery
Rasbury
Rasch
Rasche
Raschilla
Raschke
Raschko
Rasco
Rascoe
Rascon
Rase
Rasely
Raser
Rasey
Rash
Rashad
Rashada
Rashdi
Rashed
Rasheed
Rasher
Rashid
Rasico
Rasinski
Rask
Raska
Raske
Raskey
Raskin
Rasley
Rasmus
Rasmuson
Rasmussen
Rasmusson
Rasnake
Rasnic
Rasnick
Raso
Rasole
Rasool
Rasor
Rasp
Raspa
Raspberry
Raspotnik
Rassel
Rasset
Rassman
Rassmussen
Rast
Rastegar
Rastelli
Rastetter
Rastogi
Rastorfer
Rasual
Rasul
Rasulo
Rataczak
Rataj
Ratajczak
Ratana
Ratchford
Ratcliff
Ratcliffe
Ratel
Ratelle
Rater
Ratering
Raterman
Ratermann
Rath
Rathai
Rathbone
Rathbum
Rathbun
Rathburn
Rathe
Rathel
Rather
Rathert
Rathfon
Rathgeb
Rathgeber
Rathje
Rathjen
Rathke
Rathman
Rathmann
Rathmanner
Rathmell
Rathrock
Ratigan
Ratkovich
Ratkowski
Ratledge
Ratleff
Ratley
Ratliff
Ratner
Ratsep
Rattan
Rattana
Rattanachane
Rattanasinh
Rattay
Ratte
Rattee
Rattell
Ratterman
Ratterree
Ratti
Rattigan
Rattler
Rattley
Rattliff
Rattner
Rattray
Rattu
Ratulowski
Ratz
Ratzlaff
Ratzloff
Rau
Raub
Raucci
Rauch
Rauchwerger
Rauco
Rauda
Raudales
Raudebaugh
Raudenbush
Rauelo
Rauen
Rauer
Rauf
Raught
Raugust
Rauh
Rauhe
Rauhecker
Rauhuff
Raul
Raulerson
Raulino
Rauls
Raulston
Raum
Rauner
Raup
Raupach
Raupp
Raus
Rausch
Rauschenbach
Rauschenberg
Rauscher
Rause
Rauser
Rausin
Rautenberg
Rautenstrauch
Rauth
Rautio
Rauzman
Rav
Rava
Ravago
Raval
Rave
Ravel
Raveling
Ravelo
Raven
Ravencraft
Ravenel
Ravenell
Ravenelle
Ravenhorst
Ravens
Ravenscraft
Ravenscroft
Raver
Ravert
Ravetti
Ravetto
Ravi
Raviele
Raviscioni
Ravitz
Ravizee
Ravo
Ravotta
Raw
Rawat
Rawding
Rawdon
Rawe
Rawhoof
Rawhouser
Rawi
Rawicki
Rawl
Rawle
Rawles
Rawley
Rawling
Rawlings
Rawlins
Rawlinson
Rawls
Rawson
Rax
Raxter
Ray
Raya
Rayam
Rayas
Raybon
Rayborn
Raybould
Raybourn
Raybuck
Rayburn
Raychard
Raycraft
Raycroft
Raye
Rayer
Rayes
Rayfield
Rayford
Raygosa
Raygoza
Rayhel
Rayl
Rayman
Raymer
Raymo
Raymond
Raymore
Raymos
Raymundo
Rayna
Rayne
Rayner
Raynes
Rayno
Raynolds
Raynor
Raynoso
Rayo
Rayome
Rayos
Rayow
Rayshell
Rayside
Rayson
Raysor
Rayyan
Raz
Raza
Razavi
Razer
Razey
Raziano
Razinger
Razo
Razon
Razor
Razzano
Razze
Re
Rea
Reach
Read
Readdy
Reade
Readenour
Reader
Reading
Readinger
Readnour
Reado
Readus
Ready
Reagan
Reagans
Reagen
Reager
Reagey
Reagh
Reagin
Reagle
Reagon
Reagor
Reaid
Real
Realbuto
Reale
Reali
Realmuto
Ream
Reamer
Reames
Reams
Reamy
Reando
Reaney
Reano
Reaollano
Reap
Reaper
Rear
Rearden
Reardon
Rearick
Reary
Reas
Rease
Reaser
Reash
Reasinger
Reasner
Reason
Reasoner
Reasonover
Reasons
Reasor
Reategui
Reath
Reatherford
Reau
Reauish
Reaume
Reaux
Reavely
Reaver
Reaves
Reavis
Reavish
Reavley
Reay
Reazer
Rebar
Rebeck
Rebeiro
Rebel
Rebeles
Rebell
Rebello
Rebelo
Reber
Rebera
Rebert
Rebholz
Rebich
Rebick
Rebik
Rebillard
Rebman
Rebold
Rebollar
Rebolledo
Rebolloso
Rebuck
Rebuldela
Reburn
Rebusi
Recalde
Recar
Recchia
Recek
Recendez
Rech
Rechel
Recher
Rechichi
Rechkemmer
Recht
Rechtzigel
Recidivi
Recine
Recinos
Recio
Reck
Reckard
Reckart
Recker
Reckers
Reckleben
Reckley
Reckling
Reckner
Recksiek
Recla
Recor
Record
Records
Recore
Rectenwald
Rector
Recuparo
Recupero
Reczek
Red
Reda
Redal
Redbird
Redburn
Redcay
Redcross
Redd
Reddekopp
Reddell
Redden
Redder
Reddic
Reddick
Reddicks
Reddig
Reddin
Redding
Reddinger
Reddington
Reddish
Redditt
Reddix
Reddoch
Reddout
Reddrick
Reddy
Rede
Redeker
Redel
Redell
Redemer
Redenbaugh
Redenius
Redenz
Redepenning
Reder
Redfear
Redfearn
Redfern
Redfield
Redford
Redfox
Redgate
Redhage
Redhead
Redhouse
Redic
Redican
Redick
Redifer
Redig
Rediger
Rediker
Redinbo
Reding
Redinger
Redington
Redish
Rediske
Redkey
Redle
Redler
Redlin
Redline
Redlinger
Redlon
Redman
Redmann
Redmer
Redmon
Redmond
Redner
Rednour
Redo
Redondo
Redpath
Redrick
Redshaw
Redstone
Redus
Redway
Redwine
Redwood
Ree
Reeb
Reeber
Reece
Reech
Reeck
Reed
Reeder
Reedholm
Reeds
Reedus
Reedy
Reef
Reefer
Reeger
Reeh
Reeher
Reek
Reekers
Reekie
Reeks
Reel
Reels
Reem
Reemer
Reen
Reenders
Reents
Reep
Rees
Reese
Reeser
Reesor
Reeter
Reetz
Reeve
Reever
Reevers
Reeves
Refazo
Reff
Reffett
Reffitt
Reffner
Refsal
Refsell
Rega
Regal
Regalado
Regalbuto
Regan
Regans
Regar
Regas
Regehr
Regel
Regelman
Regen
Regener
Regensburg
Reger
Reges
Regester
Reggio
Regier
Regina
Reginal
Reginaldo
Regine
Regino
Regis
Register
Regler
Reglin
Regn
Regner
Regnier
Rego
Regos
Regueira
Regula
Regulski
Regulus
Regusters
Reh
Reha
Rehagen
Rehak
Rehart
Rehbein
Rehberg
Rehberger
Rehbock
Rehder
Reher
Rehfeld
Rehfeldt
Rehfield
Rehkop
Rehl
Rehlander
Rehler
Rehling
Rehm
Rehman
Rehmann
Rehmeier
Rehmer
Rehmert
Rehn
Rehnberg
Rehnborg
Rehnert
Rehnquist
Reho
Rehor
Rehrer
Rehrig
Rehse
Rei
Reial
Reiber
Reibert
Reibman
Reibsome
Reich
Reichard
Reichardt
Reichart
Reiche
Reichel
Reichelderfer
Reichelt
Reichenbach
Reichenback
Reichenberg
Reichert
Reichhardt
Reichle
Reichler
Reichling
Reichman
Reichmann
Reichow
Reick
Reicks
Reid
Reidel
Reidenbach
Reider
Reidhaar
Reidhead
Reidherd
Reidinger
Reidler
Reidling
Reidy
Reier
Reierson
Reif
Reifel
Reifer
Reiff
Reifler
Reifman
Reifschneider
Reifsnider
Reifsnyder
Reifsteck
Reigel
Reiger
Reigh
Reighard
Reighley
Reigle
Reigleman
Reigner
Reigstad
Reihe
Reiher
Reihing
Reihl
Reik
Reikowsky
Reil
Reiland
Reiley
Reiling
Reill
Reilley
Reilly
Reily
Reim
Reiman
Reimann
Reimel
Reimer
Reimers
Reimmer
Reimnitz
Reimold
Reimund
Rein
Reina
Reinard
Reinart
Reinartz
Reinbold
Reinbolt
Reindeau
Reindel
Reinders
Reindl
Reine
Reineccius
Reineck
Reinecke
Reineke
Reineking
Reineman
Reinen
Reiner
Reiners
Reinert
Reines
Reinfeld
Reing
Reinhard
Reinhardt
Reinhart
Reinheimer
Reinhold
Reinholdt
Reinholt
Reinholtz
Reinicke
Reinier
Reiniger
Reining
Reininger
Reinitz
Reinke
Reinkemeyer
Reinken
Reinking
Reinmann
Reinmiller
Reino
Reinoehl
Reinoso
Reinowski
Reins
Reinsch
Reinschmidt
Reinsfelder
Reinsmith
Reinstein
Reinsvold
Reints
Reinwald
Reio
Reis
Reisch
Reischl
Reisdorf
Reise
Reisen
Reisenauer
Reiser
Reisert
Reisher
Reishus
Reisig
Reisin
Reising
Reisinger
Reisling
Reisman
Reisner
Reiss
Reisser
Reissig
Reist
Reistad
Reister
Reistetter
Reiswig
Reisz
Reitan
Reitano
Reitema
Reiten
Reiter
Reiterman
Reith
Reither
Reitler
Reitman
Reitmeier
Reitmeyer
Reitsma
Reitter
Reitz
Reitzel
Reitzes
Reives
Rekas
Rekemeyer
Reker
Reksten
Rekuc
Rekus
Relacion
Relaford
Releford
Relf
Relford
Relic
Reliford
Relihan
Relkin
Rell
Rella
Rellama
Reller
Relles
Rellihan
Relph
Relyea
Remak
Remaklus
Remaley
Remaly
Rembert
Rembold
Remeder
Remedies
Remele
Remenaric
Rementer
Remer
Remerez
Remey
Remfert
Remian
Remiasz
Remick
Remigio
Remillard
Remily
Remington
Remis
Remiszewski
Remke
Remkus
Remley
Remlin
Remlinger
Remme
Remmel
Remmele
Remmen
Remmers
Remmick
Remmie
Remo
Remondet
Remondini
Remos
Rempe
Rempel
Remsberg
Remsburg
Remsen
Remson
Remund
Remus
Remy
Ren
Rena
Renaker
Renard
Renart
Renaud
Renault
Renburg
Rench
Rencher
Rend
Renda
Rendall
Rende
Rendel
Rendell
Render
Renderos
Rendina
Rendino
Rendle
Rendleman
Rendler
Rendon
Rene
Reneau
Renee
Renegar
Renell
Rener
Renert
Renfer
Renfrew
Renfro
Renfroe
Renfrow
Rengel
Rengers
Rengifo
Renick
Renicker
Renier
Renigar
Reninger
Renison
Renk
Renken
Renker
Renkes
Renko
Renn
Renna
Rennaker
Renne
Renneker
Rennell
Rennels
Rennemeyer
Renner
Renney
Rennick
Rennie
Renning
Renninger
Rennix
Renno
Reno
Renolds
Renollet
Renosky
Renouf
Renova
Rens
Rensberger
Rensch
Renschler
Rensen
Renshaw
Rensing
Rentar
Rentas
Renter
Renteria
Rentfro
Rentfrow
Rentie
Renton
Rentoulis
Rentschler
Rentz
Renuart
Renwick
Reny
Renyer
Renz
Renze
Renzelman
Renzi
Renzo
Renzoni
Renzulli
Renzullo
Reola
Reome
Reon
Reopell
Reos
Repaci
Repasky
Repass
Repenning
Reper
Repetowski
Reph
Repine
Repinski
Repka
Repke
Repko
Replenski
Replin
Replogle
Repoff
Reposa
Repp
Reppe
Reppell
Reppert
Reppond
Reppucci
Repress
Reprogle
Repsher
Requa
Requarth
Requena
Rerko
Rerucha
Res
Resch
Reschke
Resecker
Reseigh
Resek
Resendes
Resendez
Resendiz
Resenz
Reser
Resetar
Resh
Reshard
Reshid
Resides
Resler
Resner
Resnick
Resnik
Resnikoff
Resos
Respass
Resper
Respers
Respes
Respess
Respicio
Respress
Ress
Resse
Resseguie
Ressel
Ressler
Rester
Restifo
Restivo
Resto
Restrepo
Restuccia
Resue
Resureccion
Reta
Retamar
Retana
Retchless
Retek
Retersdorf
Reth
Retherford
Rethman
Rethmeier
Retka
Retort
Retta
Rettele
Retter
Retterath
Retterbush
Rettig
Rettinger
Rettke
Rettkowski
Retz
Retzer
Retzlaff
Retzler
Retzloff
Reuben
Reuber
Reudink
Reuer
Reuhl
Reul
Reuland
Reulet
Reus
Reusch
Reuschel
Reusing
Reuss
Reusser
Reusswig
Reust
Reuteler
Reuter
Reuther
Reutlinger
Reutter
Reutzel
Reuven
Revak
Revalee
Revard
Revay
Reveal
Revel
Reveles
Revelez
Revell
Revelle
Revelli
Revello
Revells
Revelo
Revels
Reven
Revera
Revere
Revering
Revermann
Reveron
Reves
Revette
Revier
Revilla
Reville
Revils
Revira
Revis
Revoir
Revolorio
Revord
Rew
Rewakowski
Rewenko
Rewerts
Rewis
Rewitzer
Rex
Rexach
Rexford
Rexroad
Rexroat
Rexrode
Rexwinkle
Rey
Reyburn
Reye
Reyelts
Reyer
Reyers
Reyes
Reyez
Reyman
Reyna
Reynaga
Reynaldo
Reynalds
Reynard
Reynaud
Reyne
Reyner
Reynero
Reynold
Reynolds
Reynoldson
Reynosa
Reynoso
Reynoza
Reynvaan
Reyolds
Reyome
Reys
Reza
Rezac
Rezai
Rezak
Rezek
Rezendes
Rezentes
Reznicek
Reznick
Reznik
Rhame
Rhames
Rhatigan
Rhea
Rhead
Rheault
Rheaume
Rheaves
Rhed
Rhee
Rhees
Rhein
Rheingans
Rheingold
Rheinhardt
Rheinschmidt
Rhem
Rhen
Rheome
Rhett
Rhew
Rhim
Rhine
Rhinebolt
Rhinehardt
Rhinehart
Rhinerson
Rhines
Rho
Rhoad
Rhoades
Rhoads
Rhoan
Rhoda
Rhodarmer
Rhodd
Rhode
Rhodehamel
Rhoden
Rhoderick
Rhodes
Rhodie
Rhodus
Rhody
Rhoe
Rhome
Rhondes
Rhone
Rhoney
Rhorer
Rhoten
Rhoton
Rhude
Rhudy
Rhue
Rhule
Rhum
Rhump
Rhyan
Rhym
Rhyme
Rhymer
Rhymes
Rhynard
Rhyne
Rhyner
Rhynes
Rial
Rials
Rian
Rias
Riase
Riback
Ribao
Ribar
Ribas
Ribaudo
Ribb
Ribbink
Ribble
Ribeiro
Ribera
Riberdy
Ribero
Ribiero
Riblet
Riblett
Ribot
Ribron
Ribsamen
Ricard
Ricardez
Ricardi
Ricardo
Ricardson
Ricaud
Ricca
Riccardi
Riccardo
Riccelli
Ricci
Ricciardelli
Ricciardi
Ricciardone
Riccio
Riccitelli
Ricciuti
Ricco
Rice
Ricenberg
Rich
Richan
Richard
Richards
Richardson
Richardt
Richardville
Richarson
Richart
Richberg
Richbourg
Richburg
Richcreek
Riche
Richel
Richelieu
Richemond
Richens
Richer
Richerds
Richerson
Richert
Riches
Richesin
Richeson
Richey
Richie
Richins
Richison
Richiusa
Richlin
Richman
Richmann
Richmeier
Richmon
Richmond
Richner
Richoux
Richrdson
Richter
Richters
Richwine
Rick
Rickabaugh
Rickard
Rickards
Ricke
Rickel
Rickels
Ricken
Rickenbach
Rickenbacker
Rickenbaker
Rickenbaugh
Ricker
Rickerl
Rickers
Rickerson
Rickert
Ricketson
Rickett
Ricketts
Rickey
Rickford
Rickie
Ricklefs
Rickles
Rickley
Rickman
Rickmon
Rickner
Rickon
Ricks
Rickson
Ricley
Rico
Ricord
Ricotta
Ricucci
Riculfy
Ridall
Riddel
Riddell
Ridder
Ridderhoff
Ridders
Riddick
Riddle
Riddlebarger
Riddleberger
Riddles
Riddley
Riddock
Rideau
Rideaux
Ridel
Ridell
Riden
Ridener
Ridenhour
Ridenour
Ridens
Rideout
Ridep
Rider
Rides
Ridge
Ridgebear
Ridgel
Ridgell
Ridges
Ridgeway
Ridgill
Ridgle
Ridgley
Ridgnal
Ridgway
Riding
Ridinger
Ridings
Ridlen
Ridler
Ridley
Ridling
Ridlon
Ridner
Ridolfi
Ridout
Ridpath
Rieb
Riebau
Riebe
Riebel
Riebeling
Rieben
Rieber
Riebow
Riech
Riechers
Riechman
Rieck
Riecke
Ried
Riede
Riedel
Riedell
Rieder
Riederer
Riedesel
Riedinger
Riedl
Riedle
Riedlinger
Riedman
Riedmayer
Riedy
Rief
Riefer
Rieff
Rieffenberger
Rieffer
Rieg
Riegel
Rieger
Riegle
Riegler
Riehl
Riehle
Riehm
Riek
Rieke
Rieken
Riekena
Rieker
Riekert
Rieks
Riel
Rieland
Rieley
Rielly
Rieman
Riemann
Riemenschneid
Riemer
Riemersma
Riendeau
Rienstra
Rients
Rienzo
Rieper
Riera
Rierson
Ries
Riese
Riesen
Riesenberg
Riesenweber
Rieser
Riesgo
Riesgraf
Riesinger
Rieske
Riesland
Riesner
Riess
Riessen
Riester
Rietdorf
Rieth
Rietschlin
Rietz
Rieu
Rieve
Rieves
Rievley
Riexinger
Rifai
Rife
Rifenbark
Rifenbery
Rifenburg
Riff
Riffe
Riffee
Riffel
Riffle
Riffon
Rifkin
Rigali
Rigano
Rigas
Rigatti
Rigaud
Rigazio
Rigby
Rigdon
Rigel
Rigerman
Rigg
Riggan
Riggans
Riggen
Riggenbach
Riggens
Rigger
Riggers
Riggert
Riggi
Riggie
Riggin
Riggings
Riggins
Riggio
Riggle
Riggleman
Riggles
Riggott
Riggs
Riggsbee
Riggsby
Righetti
Righi
Right
Righter
Righthouse
Rightley
Rightmire
Rightmyer
Rightnour
Rigler
Rigley
Riglos
Rigney
Rigo
Rigoni
Rigotti
Rigsbee
Rigsby
Riha
Rihanek
Riherd
Rihn
Rihner
Riihimaki
Riina
Riippi
Riis
Riise
Rijo
Rijos
Rikard
Rike
Riker
Rile
Riles
Riley
Riliford
Riling
Rill
Riller
Rillera
Rilley
Rillie
Rilling
Rily
Rim
Rima
Rimando
Rimar
Rimbach
Rimbey
Rimel
Rimer
Rimes
Rimi
Rimkus
Rimm
Rimmer
Rimple
Rimson
Rina
Rinaldi
Rinaldis
Rinaldo
Rinard
Rinaudo
Rinauro
Rincan
Rinck
Rincon
Rincones
Rindal
Rinde
Rindels
Rinderer
Rinderknecht
Rinderle
Rindfleisch
Rindler
Rindone
Rine
Rinebarger
Rinebold
Rineer
Rinehardt
Rinehart
Rineheart
Rinehimer
Rinella
Riner
Rines
Riney
Rinfret
Ring
Ringbloom
Ringdahl
Ringeisen
Ringel
Ringelheim
Ringelspaugh
Ringen
Ringenberg
Ringer
Ringering
Ringgenberg
Ringgold
Ringham
Ringhand
Ringhouse
Ringland
Ringle
Ringlein
Ringler
Ringley
Ringman
Ringo
Ringold
Ringquist
Ringrose
Rings
Ringstaff
Ringuette
Ringus
Ringwald
Ringwood
Rini
Riniker
Rininger
Rink
Rinke
Rinkel
Rinkenberger
Rinker
Rinks
Rinkus
Rinn
Rinne
Rinner
Rinnert
Rintharamy
Rio
Riobe
Riofrio
Riogas
Riojas
Riola
Riolo
Rion
Riopel
Riopelle
Riordan
Rios
Rioseco
Rioux
Rioz
Ripa
Ripka
Ripke
Ripley
Ripoll
Ripp
Rippe
Rippee
Rippel
Rippelmeyer
Rippentrop
Rippeon
Ripper
Ripperger
Rippetoe
Rippey
Rippin
Ripple
Ripplinger
Rippon
Rippstein
Rippy
Ripson
Riquelme
Risatti
Risbeck
Risberg
Risby
Riscen
Risch
Rische
Risden
Rise
Riseden
Risen
Risenhoover
Riser
Risewick
Rish
Risha
Rishe
Rishel
Rishell
Risher
Rishor
Rishty
Risi
Risien
Rising
Risinger
Risius
Risk
Riska
Riskalla
Riske
Riskin
Risko
Risler
Risley
Risner
Riso
Rison
Risper
Rispoli
Riss
Rissanen
Risse
Rissell
Risser
Rissler
Rissman
Risso
Rist
Ristaino
Ristau
Rister
Ristig
Risto
Riston
Ristow
Rita
Ritacco
Ritari
Ritch
Ritcher
Ritcheson
Ritchey
Ritchhart
Ritchie
Ritchko
Ritchlin
Ritchotte
Ritell
Ritenour
Riter
Ritmiller
Ritrovato
Ritschard
Ritson
Ritt
Rittenberry
Rittenhouse
Rittenour
Ritter
Ritterbush
Ritthaler
Rittichier
Rittie
Rittinger
Rittle
Ritts
Ritums
Ritz
Ritzel
Ritzer
Ritzert
Ritzie
Ritzke
Ritzman
Rius
Riva
Rivadeneira
Rivadulla
Rival
Rivali
Rivara
Rivard
Rivas
Riveiro
Rivel
Rivelli
Rivello
Rivena
Rivenbark
Rivenberg
Rivenburg
Rivenburgh
River
Rivera
Riveras
Riveria
Riverman
Rivero
Riveroll
Riveron
Riveros
Rivers
Rives
Rivest
Rivet
Rivett
Rivette
Rivie
Riviera
Riviere
Riviezzo
Rivinius
Rivira
Rivkin
Rivlin
Rivord
Rix
Rixie
Rizal
Rizas
Rizer
Rizk
Rizo
Rizor
Rizvi
Rizza
Rizzardi
Rizzardo
Rizzi
Rizzio
Rizzo
Rizzolo
Rizzotto
Rizzuti
Rizzuto
Rm
Ro
Roa
Roach
Roache
Roacho
Roadarmel
Roadcap
Roaden
Roades
Roadruck
Roads
Roady
Roaf
Roal
Roam
Roan
Roane
Roanhorse
Roaoo
Roark
Roarty
Roarx
Roary
Roat
Roatch
Roath
Roats
Rob
Roback
Robaina
Robair
Robak
Robante
Robar
Robards
Robare
Robarge
Robasciotti
Robateau
Robayo
Robb
Robben
Robberson
Robbert
Robbie
Robbin
Robbins
Robbinson
Robblee
Robbs
Robe
Robeck
Robel
Robella
Robello
Robenson
Rober
Roberds
Roberg
Roberge
Roberie
Roberrtson
Robers
Roberson
Roberston
Robert
Roberta
Robertello
Roberti
Roberto
Roberton
Robertos
Roberts
Robertshaw
Robertson
Robes
Robeson
Robey
Robeza
Robichard
Robichau
Robichaud
Robichaux
Robicheau
Robicheaux
Robida
Robideau
Robidoux
Robie
Robillard
Robilotto
Robin
Robinault
Robinett
Robinette
Robins
Robinso
Robinson
Robinsons
Robinzine
Robirds
Robishaw
Robison
Robitaille
Roble
Robledo
Roblee
Robles
Robleto
Robley
Roblez
Roblin
Roblodowski
Roblow
Robnett
Robotham
Robson
Robuck
Robusto
Roby
Robyn
Roca
Rocamora
Rocasah
Rocca
Rocchi
Rocchio
Roccia
Roccio
Rocco
Rocconi
Roch
Rocha
Rochat
Roche
Rocheford
Rochefort
Rochel
Rocheleau
Rochell
Rochelle
Rochenstire
Rocher
Roches
Rochester
Rochez
Rochford
Rochholz
Rochin
Rochkes
Rochlin
Rochlitz
Rocho
Rochon
Rochow
Rock
Rockafellow
Rocke
Rockefeller
Rockelman
Rockenbach
Rockenbaugh
Rocker
Rockers
Rockett
Rockey
Rockford
Rockhill
Rockhold
Rockholt
Rockingham
Rockman
Rockmore
Rockovich
Rocks
Rockstad
Rockwell
Rockwood
Rockymore
Rocle
Rocque
Rocquemore
Rocray
Rod
Roda
Rodabaugh
Rodak
Rodal
Rodamis
Rodan
Rodar
Rodarmel
Rodarta
Rodarte
Rodas
Rodberg
Rodd
Rodda
Roddam
Rodde
Rodden
Roddenberry
Roddey
Roddick
Roddy
Rode
Rodea
Rodebaugh
Rodebush
Rodeen
Rodefer
Rodeheaver
Rodeigues
Rodeiguez
Rodela
Rodell
Rodeman
Rodemeyer
Rodemoyer
Roden
Rodenbaugh
Rodenbeck
Rodenberg
Rodenberger
Rodenbough
Rodenburg
Rodenizer
Roder
Roderick
Roderiques
Roderiquez
Roderman
Rodero
Rodes
Rodewald
Rodger
Rodgers
Rodgerson
Rodges
Rodi
Rodia
Rodibaugh
Rodick
Rodiguez
Rodillas
Rodin
Rodina
Rodine
Rodino
Rodinson
Rodiquez
Rodis
Rodkey
Rodkin
Rodman
Rodney
Rodnguez
Rodocker
Rodolph
Rodregez
Rodregues
Rodreguez
Rodrequez
Rodrguez
Rodrick
Rodricks
Rodriges
Rodrigeuz
Rodrigez
Rodrigo
Rodrigres
Rodrigue
Rodriguel
Rodrigues
Rodriguez
Rodriguiz
Rodrigus
Rodriguz
Rodrique
Rodriques
Rodriquez
Rodriquz
Rodriuez
Rodvold
Rodwell
Rody
Roe
Roeber
Roebke
Roebuck
Roecker
Roede
Roedel
Roeder
Roediger
Roedl
Roefaro
Roeger
Roegge
Roegner
Roehl
Roehler
Roehling
Roehm
Roehr
Roehrenbeck
Roehrich
Roehrick
Roehrig
Roehrman
Roehrs
Roeker
Roekle
Roel
Roelfs
Roell
Roelle
Roelofs
Roemen
Roemer
Roemhild
Roemmich
Roen
Roenigk
Roepke
Roerig
Roering
Roerish
Roers
Roes
Roesch
Roeschley
Roese
Roeser
Roesing
Roeske
Roesler
Roesner
Roesser
Roessing
Roesslein
Roessler
Roessner
Roetcisoender
Roeth
Roethel
Roethle
Roethler
Roets
Roettgen
Roettger
Roetzler
Roever
Roewe
Roff
Roffe
Roffman
Rofkahr
Rog
Rogacion
Rogacki
Rogado
Rogal
Rogala
Rogalski
Rogan
Rogas
Rogel
Rogens
Roger
Rogers
Rogerson
Rogg
Rogge
Roggeman
Roggenbaum
Roggensack
Roggero
Roghair
Rogian
Rogillio
Roginson
Rogish
Rogne
Rogness
Rognstad
Rogoff
Rogol
Rogosky
Rogowicz
Rogowski
Rogriguez
Rogstad
Rogue
Roguemore
Rogugbakaa
Roh
Rohal
Rohaley
Rohan
Rohanna
Rohde
Rohdenburg
Rohe
Rohen
Roher
Rohl
Rohla
Rohlack
Rohland
Rohleder
Rohlf
Rohlfing
Rohlfs
Rohling
Rohlman
Rohloff
Rohm
Rohman
Rohn
Rohner
Rohowetz
Rohr
Rohrbach
Rohrbacher
Rohrback
Rohrbaugh
Rohrdanz
Rohrer
Rohrich
Rohrig
Rohrs
Rohrscheib
Rohs
Rohweder
Rohwer
Roider
Roig
Roiger
Roik
Rois
Roitman
Roja
Rojas
Rojek
Rojero
Rojo
Rojos
Roker
Rokicki
Rokisky
Rokos
Rokosz
Rokus
Rokusek
Rola
Rolack
Rolan
Roland
Rolando
Rolark
Rold
Roldan
Rolek
Rolen
Rolens
Roles
Roley
Rolf
Rolfe
Rolfes
Rolff
Rolfs
Rolfsen
Rolfson
Rolin
Roling
Rolins
Rolison
Roll
Rolla
Rollag
Rolland
Rollans
Rolle
Rollefson
Rollend
Roller
Rollerson
Rolley
Rollf
Rollheiser
Rollie
Rollin
Rollind
Rolling
Rollinger
Rollings
Rollins
Rollinson
Rollison
Rollman
Rollo
Rollock
Rollow
Rolls
Rollyson
Roloff
Rolon
Roloson
Rolph
Rolseth
Rolson
Rolstad
Rolston
Rom
Roma
Romack
Romag
Romagnoli
Romain
Romaine
Roman
Romance
Romanchuk
Romandia
Romane
Romanek
Romanelli
Romanello
Romani
Romaniak
Romanick
Romaniello
Romanik
Romanini
Romaniszyn
Romano
Romanoff
Romanoski
Romanov
Romanowicz
Romanowski
Romans
Romanski
Romansky
Romanson
Romar
Romaro
Romas
Romasanta
Romash
Romay
Rombach
Rombardo
Romberg
Romberger
Rombough
Rombs
Rombult
Rome
Romeiro
Romelus
Romenesko
Romeno
Romeo
Romer
Romera
Romero
Romesburg
Romey
Romie
Romig
Romine
Romines
Rominger
Romiro
Romito
Romjue
Romkema
Romm
Rommel
Rommelfanger
Romness
Romney
Romo
Romon
Romos
Romp
Rompf
Romprey
Romrell
Romriell
Romulus
Ron
Rona
Ronald
Ronan
Ronayne
Ronca
Ronchetti
Ronchetto
Ronco
Roncskevitz
Ronda
Ronde
Rondeau
Rondell
Rondinelli
Rondo
Rondon
Rondy
Rone
Roner
Ronero
Rones
Roney
Ronfeldt
Rong
Rongo
Rongstad
Ronhaar
Ronin
Ronk
Ronn
Ronne
Ronnfeldt
Ronnie
Ronning
Ronquillo
Rons
Ronsani
Ronsini
Ronson
Ronzoni
Rood
Roode
Roof
Roofe
Roofner
Rook
Rookard
Rooke
Rooker
Rooks
Rookstool
Rookwood
Room
Roome
Roon
Rooney
Roop
Roope
Roorda
Roos
Roosa
Roose
Roosevelt
Root
Rooth
Roots
Ropac
Roper
Ropers
Roperto
Ropes
Ropiski
Ropka
Ropp
Roppolo
Roque
Roquemore
Roques
Rorabacher
Rorabaugh
Rorer
Rorex
Rorick
Rorie
Rork
Rorrer
Ros
Rosa
Rosacker
Rosada
Rosado
Rosal
Rosales
Rosalez
Rosamond
Rosan
Rosander
Rosane
Rosano
Rosario
Rosaro
Rosas
Rosasco
Rosati
Rosato
Rosavio
Rosazza
Rosberg
Rosboril
Rosborough
Rosbough
Rosbozom
Rosca
Rosch
Roscigno
Roscioli
Roscoe
Roscorla
Roscow
Roscup
Rose
Rosebaugh
Roseberry
Roseboom
Roseboro
Roseborough
Rosebrock
Rosebrook
Rosebrough
Rosebur
Rosebure
Rosebush
Rosecrans
Rosek
Rosekrans
Rosel
Roseland
Roselius
Rosell
Rosella
Roselle
Roselli
Rosello
Roseman
Rosemond
Rosemore
Rosen
Rosenau
Rosenbalm
Rosenbarger
Rosenbaum
Rosenbeck
Rosenberg
Rosenberger
Rosenberry
Rosenblatt
Rosenbloom
Rosenblum
Rosenbluth
Rosenbrook
Rosenburg
Rosenbush
Rosencrans
Rosencrantz
Rosencranz
Rosendahl
Rosendale
Rosendo
Rosendorf
Rosene
Rosener
Rosenfeld
Rosenfeldt
Rosenfield
Rosengarten
Rosengren
Rosenhagen
Rosenheim
Rosenholm
Rosenkoetter
Rosenkrans
Rosenkranz
Rosenlof
Rosenow
Rosenquist
Rosensteel
Rosenstein
Rosenstock
Rosenthal
Rosenthall
Rosentrance
Rosentrater
Rosenwald
Rosenwinkel
Rosenzweig
Roser
Rosero
Roses
Rosete
Roseth
Rosetta
Rosette
Rosetti
Rosettie
Roseum
Rosewall
Rosewell
Rosh
Roshak
Roshannon
Rosher
Roshia
Rosi
Rosiak
Rosian
Rosica
Rosich
Rosie
Rosiek
Rosier
Rosiles
Rosillo
Rosin
Rosine
Rosing
Rosinski
Rositano
Roskam
Roske
Roskelley
Rosko
Roskop
Roskopf
Roskos
Roskovensky
Roskowinski
Rosky
Rosman
Rosmarin
Rosner
Roso
Rosoff
Rosol
Ross
Rossa
Rossano
Rossbach
Rosse
Rossean
Rosseau
Rosseel
Rossel
Rossell
Rosselle
Rosselli
Rossen
Rosser
Rosseter
Rossetti
Rossetto
Rossey
Rossi
Rossie
Rossignol
Rossin
Rossing
Rossingnol
Rossini
Rossiter
Rossler
Rossman
Rossmann
Rossmiller
Rossnagel
Rosso
Rosson
Rossotto
Rossow
Rossum
Rost
Rostad
Rostek
Rosten
Roston
Rosu
Rosul
Roswell
Roswick
Roszales
Roszel
Roszell
Rota
Rotan
Rotando
Rotanelli
Rotch
Rotchford
Rote
Rotella
Rotelli
Roten
Rotenberg
Rotenberry
Rotering
Rotermund
Rotert
Roth
Rothacher
Rothbart
Rothbauer
Rothberg
Rothchild
Rothe
Rothell
Rothenbach
Rothenberg
Rothenberger
Rothenburger
Rother
Rotherham
Rothermel
Rothermich
Rothery
Rothfeld
Rothfus
Rothfuss
Rothgaber
Rothgeb
Rothgery
Rothhaupt
Rothlisberger
Rothman
Rothmann
Rothmiller
Rothove
Rothrock
Rothschild
Rothstein
Rothweiler
Rothwell
Rotkovecz
Rotkowski
Rotman
Rotner
Rotolo
Roton
Rotondi
Rotondo
Rotramel
Rotruck
Rotstein
Rott
Rottenberg
Rotter
Rottier
Rottinghaus
Rottinghous
Rottman
Rottner
Rotton
Rotty
Rotunda
Rotundo
Rotunno
Rotz
Roubekas
Rouch
Roucoulet
Roudabush
Roudebush
Roudybush
Rouff
Roufs
Rouge
Rougeau
Rougeaux
Rougeot
Rough
Roughen
Rought
Roughton
Rougier
Rouhoff
Rouillard
Rouillier
Rouisse
Roule
Rouleau
Roulette
Roulhac
Roulston
Rouly
Roumeliotis
Round
Roundabush
Rounds
Roundtree
Roundy
Rounkles
Rounsaville
Rounsville
Rountree
Roup
Roupe
Roura
Rourk
Rourke
Rous
Rousch
Rouse
Rousell
Rouselle
Rouser
Rousey
Roush
Rousse
Rousseau
Roussel
Roussell
Rousselle
Roussin
Rousso
Roussos
Rousu
Rout
Route
Routh
Routhier
Routledge
Routon
Routson
Routt
Routte
Routzahn
Routzen
Rouw
Roux
Rouzer
Rouzzo
Rovack
Rovell
Rovella
Rovelto
Rover
Rovere
Rovero
Rovinsky
Rovira
Rovner
Row
Rowald
Rowan
Rowand
Rowback
Rowbotham
Rowbottom
Rowcliffe
Rowden
Rowe
Rowell
Rowels
Rowen
Rower
Rowett
Rowey
Rowland
Rowlands
Rowlee
Rowles
Rowlett
Rowlette
Rowley
Rowling
Rowlins
Rowlison
Rowls
Rowman
Rownd
Rowntree
Rowold
Rowray
Rowse
Rowsell
Rowser
Rowsey
Rowson
Rowton
Rowzee
Rox
Roxas
Roxberry
Roxburgh
Roxbury
Roy
Roya
Royal
Royall
Royals
Royalty
Roybal
Royce
Roye
Royea
Royer
Roylance
Royle
Roys
Roysden
Royse
Royster
Royston
Roytek
Roza
Rozance
Rozanski
Rozar
Rozas
Rozeboom
Rozek
Rozell
Rozelle
Rozema
Rozenberg
Rozga
Rozgonyi
Rozier
Rozman
Rozmus
Roznowski
Rozo
Rozon
Rozycki
Rozzell
Rozzelle
Rozzi
Rua
Ruacho
Ruan
Ruane
Ruano
Ruark
Rubal
Rubalcaba
Rubalcava
Rubalcave
Ruballos
Rubano
Rubarts
Rubash
Rubbo
Rubeck
Rubel
Ruben
Rubenacker
Rubendall
Rubenfeld
Rubenfield
Rubens
Rubenstein
Rubenzer
Rubeo
Rubero
Rubert
Ruberte
Ruberti
Ruberto
Rubi
Rubiano
Rubick
Rubidoux
Rubie
Rubin
Rubinich
Rubino
Rubinoff
Rubinow
Rubins
Rubinson
Rubinstein
Rubio
Rubison
Ruble
Rublee
Rubloff
Rubner
Rubottom
Rubow
Rubright
Rubsam
Rubulcaba
Ruby
Rubyor
Rucci
Ruch
Ruchti
Rucinski
Ruck
Ruckdaschel
Ruckdeschel
Ruckel
Rucker
Ruckey
Rucki
Ruckle
Ruckman
Rucks
Rucky
Rud
Ruda
Rudack
Rudasill
Rudat
Rudd
Ruddell
Rudden
Rudder
Ruddick
Ruddle
Ruddock
Rudduck
Ruddy
Rude
Rudeen
Rudel
Rudell
Ruden
Ruder
Ruderman
Rudes
Rudesill
Rudge
Rudgers
Rudh
Rudi
Rudicil
Rudick
Rudie
Rudig
Rudiger
Rudin
Rudio
Rudis
Rudisail
Rudisell
Rudish
Rudisill
Rudkin
Rudloff
Rudlong
Rudman
Rudney
Rudnick
Rudnicki
Rudnicky
Rudnitski
Rudo
Rudolf
Rudolph
Rudoy
Rudy
Rudzik
Rudzinski
Rue
Rueb
Ruebush
Rueck
Rueckert
Rued
Rueda
Ruedas
Ruediger
Ruedy
Ruef
Rueger
Ruegg
Ruegger
Ruegsegger
Ruehl
Ruehle
Ruehlen
Ruehling
Ruehter
Ruel
Ruelar
Ruelas
Ruell
Ruelle
Rueluas
Ruesch
Ruescher
Ruesga
Ruesink
Ruess
Ruesswick
Ruest
Rueter
Ruether
Ruetz
Ruezga
Ruf
Rufe
Rufenacht
Rufener
Rufer
Ruff
Ruffalo
Ruffaner
Ruffcorn
Ruffel
Ruffell
Ruffer
Ruffin
Ruffing
Ruffini
Ruffino
Ruffins
Ruffner
Ruffo
Ruffolo
Rufi
Rufino
Rufo
Rufus
Rugama
Ruge
Ruger
Rugg
Rugga
Ruggeri
Ruggerio
Ruggero
Ruggiano
Ruggiere
Ruggieri
Ruggiero
Ruggirello
Ruggle
Ruggles
Ruggs
Rugh
Ruh
Ruhenkamp
Ruhl
Ruhland
Ruhle
Ruhlin
Ruhling
Ruhlman
Ruhman
Ruhmann
Ruhn
Ruhnke
Ruhoff
Ruhstorfer
Ruhter
Ruic
Ruiloba
Ruis
Ruise
Ruisi
Ruiter
Ruivo
Ruiz
Rujawitz
Ruka
Rukavina
Ruland
Rulapaugh
Rule
Ruleman
Ruley
Ruliffson
Rulison
Rull
Rullan
Ruller
Rulli
Rullman
Rullo
Rulnick
Rulon
Ruman
Rumbach
Rumbaugh
Rumberger
Rumble
Rumbley
Rumbo
Rumbold
Rumbolt
Rumburd
Rumer
Rumery
Rumfelt
Rumfola
Rumford
Ruminski
Rumler
Rumley
Rummage
Rummans
Rummel
Rummell
Rummer
Rummerfield
Rummler
Rumney
Rumore
Rump
Rumpca
Rumpel
Rumpf
Rumph
Rumphol
Rumple
Rumps
Rumrill
Rumschlag
Rumsey
Runck
Runco
Rund
Rundahl
Rundall
Runde
Rundell
Rundle
Rundlett
Rundquist
Rundstrom
Runels
Runfola
Rung
Runge
Runion
Runions
Runk
Runkel
Runkle
Runnells
Runnels
Runner
Running
Runnion
Runquist
Runswick
Runyan
Runyon
Runyons
Runzler
Ruocco
Ruoff
Ruoho
Ruopoli
Ruopp
Ruot
Ruotolo
Ruozzo
Rupar
Rupard
Rupe
Rupel
Ruper
Rupert
Rupertus
Rupinski
Rupke
Ruple
Rupley
Rupnick
Rupp
Ruppe
Ruppel
Ruppenthal
Ruppert
Rupprecht
Ruprecht
Rupright
Rurup
Rury
Rusak
Rusaw
Rusboldt
Ruscetti
Rusch
Ruschak
Rusche
Ruschel
Ruscher
Ruschmann
Ruschmeyer
Ruscio
Ruscitti
Rusconi
Ruse
Rusek
Rusell
Rusen
Rusert
Rush
Rushanan
Rushdan
Rushe
Rushen
Rushenberg
Rusher
Rushford
Rushforth
Rushia
Rushin
Rushing
Rushiti
Rushlow
Rushman
Rushmore
Rushton
Rushworth
Rusi
Rusich
Rusiecki
Rusin
Rusinko
Rusinski
Rusk
Ruskin
Rusko
Rusley
Rusnak
Russ
Russak
Russaw
Russe
Russek
Russel
Russell
Russello
Russer
Russett
Russey
Russi
Russian
Russin
Russler
Russman
Russnak
Russo
Russom
Russomanno
Russomano
Russon
Russotti
Russotto
Russow
Russum
Russwurm
Rust
Rustad
Rusteberg
Rusteika
Rusten
Rustin
Ruston
Rustrian
Rusu
Ruszala
Ruszkowski
Ruta
Rutan
Rutana
Rutar
Rutecki
Rutenbar
Rutenberg
Ruter
Rutgers
Ruth
Rutheford
Ruthenberg
Ruther
Rutherford
Ruthers
Ruthledge
Ruthman
Ruths
Ruthstrom
Ruthven
Rutiaga
Rutigliano
Rutkin
Rutko
Rutkowski
Rutland
Rutledge
Rutley
Rutman
Ruts
Rutske
Rutski
Rutt
Ruttan
Rutten
Rutter
Ruttinger
Ruttman
Rutty
Rutz
Ruud
Ruuska
Ruvalcaba
Ruvalcava
Ruvo
Ruvolo
Ruwe
Ruwet
Rux
Ruybal
Ruyes
Ruyle
Ruys
Ruyter
Ruyz
Ruz
Ruzbasan
Ruzich
Ruzicka
Ruzicki
Ruzycki
Ruzzo
Rviz
Ryal
Ryals
Ryan
Ryans
Ryant
Ryba
Ryback
Rybacki
Rybak
Rybarczyk
Rybczyk
Ryberg
Rybicki
Rybij
Rybinski
Rybka
Rybolt
Rybowiak
Ryburn
Ryce
Rychlicki
Ryckman
Rycroft
Rydalch
Rydberg
Rydeen
Rydel
Rydelek
Rydell
Ryden
Ryder
Rydin
Rydman
Rydolph
Rydzewski
Rye
Ryea
Ryen
Ryer
Ryerson
Rygalski
Rygg
Rygiel
Rygiewicz
Ryhal
Ryherd
Rykaczewski
Rykard
Ryken
Ryker
Rykert
Rykiel
Rykowski
Ryks
Rylaarsdam
Ryland
Rylander
Rylands
Rylant
Ryle
Rylee
Ryles
Ryley
Ryll
Rylowicz
Ryman
Rymasz
Rymer
Rymes
Rymut
Rynders
Rynearson
Ryneer
Ryner
Rynerson
Rynes
Rynkowski
Rynn
Rynne
Ryon
Rys
Rysanek
Rysavy
Ryser
Rysz
Ryther
Rytuba
Ryu
Ryun
Ryzinski
Rzasa
Rzeczycki
Rzepecki
Rzepka
Rzeszutko
Rzucidlo
Sa
Saa
Saab
Saabatmand
Saad
Saadat
Saadd
Saade
Saadeh
Saager
Saal
Saale
Saalfrank
Saam
Saar
Saarela
Saari
Saas
Saathoff
Saavedra
Saba
Sabad
Sabado
Sabados
Sabagh
Sabaj
Sabal
Sabala
Saballos
Saban
Sabastian
Sabat
Sabata
Sabataso
Sabatelli
Sabater
Sabates
Sabatini
Sabatino
Sabb
Sabbagh
Sabbah
Sabbatini
Sabe
Sabean
Sabedra
Sabeiha
Sabel
Sabella
Sabellico
Saber
Saberi
Sabet
Sabha
Sabi
Sabia
Sabin
Sabina
Sabine
Sabini
Sabino
Sabins
Sabio
Sabir
Sabiston
Sablan
Sable
Sablea
Sables
Sablock
Sablone
Sabo
Sabol
Sabori
Saborido
Saborio
Sabot
Sabota
Sabourin
Sacane
Sacarello
Sacavage
Sacayanan
Sacca
Saccardi
Sacchetti
Sacchi
Sacco
Saccone
Saccucci
Sachar
Sache
Sacher
Saches
Sachetti
Sachez
Sachleben
Sachs
Sachse
Sachtleben
Sack
Sackal
Sackett
Sackey
Sackman
Sackos
Sackrider
Sacks
Sacramed
Sacramento
Sacre
Sada
Sadahiro
Sadak
Sadan
Sadar
Sadat
Sadberry
Sadbury
Saddat
Saddler
Sade
Sadee
Sadeghi
Saden
Sader
Sadger
Sadhra
Sadhu
Sadik
Sadin
Sadiq
Sadler
Sadlier
Sadlon
Sadlow
Sadolsky
Sadorra
Sadoski
Sadow
Sadowski
Sadowsky
Sadri
Sadusky
Sadvary
Sae
Saechao
Saeed
Saefong
Saeger
Saelee
Saelens
Saeler
Saeli
Saemenes
Saenger
Saenphimmacha
Saens
Saenz
Saephan
Saetern
Saeteun
Saether
Saetteurn
Saeturn
Saez
Safa
Safar
Safdeye
Safe
Safer
Saffel
Saffell
Saffer
Saffo
Saffold
Safford
Safi
Safier
Safko
Safley
Safran
Safranek
Safrit
Safron
Saft
Sagal
Sagan
Sagar
Sagaser
Sagastegui
Sagastume
Sagayaga
Sage
Sagedahl
Sagehorn
Sagel
Sagen
Sagendorf
Sager
Sagers
Sages
Saggese
Saggio
Saggione
Sagi
Saglibene
Saglimben
Saglimbeni
Sago
Sagoes
Sagon
Sagona
Sagraves
Sagredo
Sagrera
Sagucio
Saguil
Sagun
Saha
Sahady
Sahagian
Sahagun
Sahara
Sahe
Sahl
Sahlberg
Sahler
Sahli
Sahm
Sahni
Sahota
Sahr
Sahsman
Sahu
Saia
Saice
Saicedo
Said
Saide
Saidi
Saieva
Saik
Saiki
Saile
Sailer
Sailor
Sailors
Sails
Sain
Sainato
Saindon
Saine
Saines
Saini
Sainliere
Saint
Saintamand
Sainte
Saintfleur
Saintignon
Saintlouis
Sainz
Sais
Saisa
Saison
Saito
Saitta
Saiz
Sajdak
Sajor
Sajorda
Sajous
Sajovic
Sak
Saka
Sakaguchi
Sakai
Sakakeeny
Sakal
Sakamaki
Sakamoto
Sakasegawa
Sakash
Sakata
Sake
Sakelaris
Sakic
Sakiestewa
Sakihara
Sakkas
Sakkinen
Sako
Sakoda
Sakon
Sakovitch
Sakowski
Sakry
Saks
Sakshaug
Sakuma
Sakumoto
Sakurai
Sala
Salaam
Salabarria
Salach
Salada
Saladin
Saladino
Salado
Salafia
Salahubdin
Salais
Salaiz
Salak
Salam
Salama
Salamacha
Salamanca
Salameh
Salamon
Salamone
Salamy
Salandy
Salano
Salas
Salasar
Salassi
Salata
Salatino
Salato
Salay
Salaz
Salaza
Salazak
Salazan
Salazar
Salazer
Salb
Salberg
Salce
Salceda
Salcedo
Salcido
Saldana
Saldano
Saldeen
Saldi
Saldibar
Saldivar
Saldvir
Sale
Saleado
Salee
Saleeby
Saleem
Saleh
Saleha
Salehi
Salek
Salem
Saleme
Salemi
Salemo
Salen
Saler
Salera
Salerno
Sales
Salesky
Salesses
Saletta
Salfelder
Salgado
Salge
Salgero
Salguero
Saliba
Salido
Salierno
Salim
Salimas
Salimi
Salin
Salina
Salinas
Salines
Saling
Salis
Salisberry
Salisbury
Saliva
Salizar
Salizzoni
Salk
Salkeld
Sall
Sallach
Sallade
Sallah
Sallas
Sallaz
Salle
Sallee
Saller
Salles
Salley
Sallie
Sallies
Salling
Sallings
Sallis
Sallmen
Salloum
Salls
Sally
Salm
Salman
Salmans
Salmela
Salmen
Salmeron
Salmi
Salminen
Salmon
Salmond
Salmons
Salmonsen
Salmonson
Salo
Salois
Salome
Salomon
Salomone
Salon
Salone
Salonek
Salonia
Saloom
Salos
Salotti
Saloum
Salowitz
Salquero
Salsa
Salsberg
Salsberry
Salsbury
Salsedo
Salser
Salsgiver
Salsman
Salstrom
Salt
Salta
Saltarelli
Salte
Salter
Saltern
Salters
Saltis
Saltman
Saltmarsh
Saltness
Salton
Saltonstall
Saltourides
Salts
Saltsman
Saltus
Saltz
Saltzberg
Saltzgaber
Saltzman
Saluan
Saluja
Salum
Salus
Saluto
Salva
Salvadge
Salvador
Salvadore
Salvage
Salvaggio
Salvant
Salvas
Salvati
Salvatierra
Salvato
Salvatore
Salvatori
Salvature
Salvemini
Salverson
Salvesen
Salveson
Salvetti
Salvey
Salvi
Salvia
Salviejo
Salvietti
Salvino
Salvio
Salvitti
Salvo
Salvucci
Salwasser
Salway
Salyards
Salyer
Salyers
Salz
Salzano
Salzar
Salzberg
Salzer
Salzl
Salzman
Salzmann
Salzwedel
Sam
Sama
Samaan
Samad
Samaha
Samain
Samaniego
Samanlego
Samano
Samantha
Samara
Samaroo
Samas
Samay
Samayoa
Samber
Samberg
Sambor
Samborski
Sambrano
Sambrook
Sambucetti
Samec
Samek
Samela
Samele
Sames
Samet
Samford
Samia
Samick
Samide
Samiec
Samiento
Samii
Samit
Samlal
Samland
Sammarco
Sammartano
Sammartino
Sammer
Sammet
Sammis
Sammon
Sammons
Samms
Sammut
Samo
Samok
Samona
Samons
Samora
Samorano
Samowitz
Samoyoa
Sampaga
Sampaia
Sampair
Sampang
Sampayan
Sampedro
Sampere
Samperi
Sampey
Sampica
Sampieri
Sampilo
Sample
Samples
Sampley
Sampogna
Sampsel
Sampsell
Sampselle
Sampson
Samra
Samrah
Samrov
Sams
Samsel
Samson
Samu
Samudio
Samuel
Samuell
Samuels
Samuelsen
Samuelson
Samul
Samway
Samy
Samyn
San
Sanabria
Sanacore
Sanagustin
Sanantonio
Sanasith
Sanberg
Sanborn
Sanburg
Sance
Sancedo
Sancen
Sances
Sanchec
Sancher
Sanches
Sanchez
Sanchious
Sanchirico
Sancho
Sanchz
Sancken
Sancrant
Sand
Sanda
Sandage
Sandager
Sandahl
Sandall
Sandate
Sandau
Sandavol
Sanday
Sandberg
Sandblom
Sandborg
Sandburg
Sande
Sandeen
Sandefer
Sandefur
Sandel
Sandelin
Sandelius
Sandell
Sandella
Sanden
Sander
Sandercock
Sanderfer
Sanderford
Sanderfur
Sanderlin
Sanderman
Sanders
Sandersen
Sanderson
Sandez
Sandford
Sandgren
Sandhaus
Sandhoff
Sandholm
Sandhop
Sandhu
Sandi
Sandidge
Sandifer
Sandiford
Sandigo
Sandin
Sandine
Sandino
Sandison
Sandlan
Sandland
Sandler
Sandles
Sandlian
Sandlin
Sandling
Sandman
Sandmann
Sandmeier
Sandness
Sando
Sandobal
Sandoe
Sandona
Sandone
Sandor
Sandora
Sandoral
Sandos
Sandoual
Sandoval
Sandovar
Sandow
Sandoz
Sandquist
Sandra
Sandri
Sandridge
Sandrock
Sandrowicz
Sandry
Sands
Sandstede
Sandstedt
Sandstrom
Sandt
Sandus
Sandusky
Sandven
Sandvig
Sandvik
Sandvill
Sandy
Sane
Saneaux
Saner
Sanes
Sanez
Sanfelix
Sanfilippo
Sanfiorenzo
Sanflippo
Sanford
Sanfratello
Sanft
Sang
Sangalli
Sangasy
Sanger
Sanges
Sangh
Sangha
Sanghani
Sanghez
Sanghvi
Sangi
Sangiacomo
Sangren
Sangrey
Sangster
Saniatan
Saniger
Sanipasi
Sanislo
Sanjabi
Sanjose
Sanjuan
Sanjurjo
Sankar
Sankaran
Sankary
Sanke
Sanker
Sankey
Sanko
Sankoff
Sankoh
Sankovich
Sankowski
Sanks
Sanlatte
Sanlucas
Sanluis
Sanmarco
Sanmartin
Sanmiguel
Sann
Sanna
Sannella
Sanner
Sannes
Sannicolas
Sannon
Sannutti
Sano
Sanocki
Sanon
Sanor
Sanos
Sanosyan
Sanots
Sanpaolo
Sanpedro
Sanpson
Sanquenetti
Sanroman
Sans
Sansalone
Sansburn
Sansbury
Sanschagrin
Sanseda
Sanseverino
Sansing
Sansom
Sanson
Sansone
Sansotta
Sansouci
Sansoucie
Sansoucy
Sant
Santa
Santaana
Santacroce
Santacruce
Santacruz
Santaella
Santagata
Santago
Santai
Santaloci
Santalucia
Santamaria
Santamarina
Santana
Santander
Santangelo
Santaniello
Santanna
Santano
Santarelli
Santarpia
Santarsiero
Santee
Santell
Santella
Santellan
Santellana
Santelli
Santeramo
Santerre
Santheson
Santhuff
Santi
Santiago
Santibanez
Santiesteban
Santigo
Santillan
Santillana
Santillanes
Santillanez
Santilli
Santillo
Santilukka
Santin
Santini
Santino
Santio
Santis
Santisteban
Santistevan
Santizo
Santmier
Santmyer
Santo
Santoli
Santolucito
Santomassimo
Santomauro
Santone
Santoni
Santopietro
Santopolo
Santor
Santora
Santore
Santorella
Santorelli
Santoriella
Santoro
Santory
Santos
Santoscoy
Santoy
Santoya
Santoyo
Santrizos
Santrmire
Santti
Santucci
Santulli
Santwire
Santy
Sanville
Sanyaro
Sanz
Sanzenbacher
Sanzo
Sanzone
Sanzotta
Sao
Saous
Sapara
Sapardanis
Saperstein
Sapia
Sapien
Sapienza
Sapinski
Sapko
Sapnu
Saporita
Saporito
Sapp
Sappah
Sappenfield
Sapper
Sappington
Saputo
Sar
Sara
Sarabando
Sarabia
Sarac
Saracco
Saraceno
Saracino
Saraf
Sarafian
Sarafin
Saragosa
Saragusa
Sarah
Saraiva
Saralegui
Saran
Sarani
Saraniti
Sarantakis
Saranzak
Sarao
Saras
Sarate
Sarault
Saravia
Sarazin
Sarbacher
Sarber
Sarchet
Sarchett
Sarcia
Sarcinella
Sarcinelli
Sarcone
Sarconi
Sardella
Sarden
Sardi
Sardin
Sardina
Sardinas
Sardinha
Sardo
Sare
Sarelas
Sarellano
Sarensen
Sarette
Saretto
Sarff
Sargeant
Sargent
Sargetakis
Sargis
Saric
Sarin
Sarinana
Sarinsky
Sario
Saris
Sarisky
Sarjeant
Sarjent
Sark
Sarka
Sarkar
Sarkin
Sarkis
Sarkisian
Sarkissian
Sarkodie
Sarks
Sarles
Sarley
Sarli
Sarlinas
Sarlo
Sarmento
Sarmiento
Sarna
Sarnacki
Sarne
Sarnes
Sarni
Sarnicola
Sarno
Sarnoff
Sarnosky
Sarnowski
Saro
Saroop
Saroukos
Sarp
Sarpy
Sarr
Sarra
Sarracino
Sarraga
Sarratt
Sarrell
Sarrett
Sarria
Sarris
Sarro
Sarsfield
Sarson
Sarsour
Sartain
Sartell
Sarti
Sartin
Sartor
Sartore
Sartorelli
Sartori
Sartorio
Sartoris
Sartorius
Sartwell
Sarullo
Sarvas
Sarver
Sarvey
Sarvis
Sarwar
Sarwary
Sarwinski
Sary
Sarzynski
Sas
Sasahara
Sasaki
Sasala
Sasao
Sasengbong
Sashington
Saska
Sasnett
Sasportas
Sass
Sassaman
Sassano
Sasse
Sasseen
Sasser
Sasseville
Sassman
Sasso
Sasson
Sassone
Sastre
Sasuille
Sat
Satar
Satava
Satawa
Satchel
Satchell
Satcher
Satchwell
Sater
Saterfiel
Saterfield
Sather
Sathiraboot
Sathre
Satiago
Satmary
Sato
Satoe
Satomba
Satow
Satre
Satsky
Sattazahn
Sattel
Satter
Satterfield
Satterlee
Satterley
Satterlund
Satterly
Satterthwaite
Satterwhite
Sattlefield
Sattler
Sattley
Satunas
Saturnio
Satz
Sau
Sauage
Sauber
Sauberan
Sauby
Sauce
Sauceda
Saucedo
Sauceman
Saucer
Sauchez
Saucier
Sauder
Sauders
Sauer
Sauerbry
Sauerhage
Sauers
Sauerwein
Sauger
Saugis
Saul
Sauler
Saulino
Saulnier
Saulo
Saulpaugh
Sauls
Saulsberry
Saulsbery
Saulsbury
Sault
Saulter
Saulters
Saults
Saum
Saumier
Saunas
Saunder
Saunders
Saunier
Saupe
Saur
Sauredo
Saurel
Saurer
Sauret
Saurey
Saurez
Sauriol
Sauro
Sause
Sauseda
Sausedo
Sauser
Sausser
Sauter
Sautner
Sautter
Sauvage
Sauvageau
Sauve
Sauveur
Sava
Savage
Savageau
Savaglio
Savakis
Savala
Savannah
Savant
Savard
Savarese
Savaria
Savarino
Savary
Savas
Savasta
Savastano
Savcedo
Save
Savedra
Savel
Savela
Savell
Savelli
Savells
Savely
Saven
Saver
Saverchenko
Savers
Savery
Savi
Saviano
Savic
Savich
Savickas
Savidge
Savilla
Saville
Savin
Savina
Savinar
Savine
Savini
Savino
Savinon
Savio
Saviola
Savitch
Savitsky
Savitts
Savitz
Savka
Savko
Savo
Savoca
Savocchia
Savoie
Savory
Savoy
Sawada
Sawaia
Sawallich
Sawatzke
Sawatzki
Sawatzky
Sawaya
Sawchuk
Sawczyszyn
Sawdey
Sawdo
Sawer
Sawhill
Sawicki
Sawin
Sawina
Sawinski
Sawka
Sawlivich
Sawney
Sawransky
Sawrey
Sawtell
Sawtelle
Sawyer
Sawyers
Sax
Saxbury
Saxby
Saxe
Saxena
Saxfield
Saxinger
Saxman
Saxon
Saxton
Say
Sayaphon
Sayas
Sayasane
Sayavong
Sayco
Saye
Sayed
Sayegh
Sayer
Sayers
Sayko
Sayle
Saylee
Sayler
Sayles
Sayloe
Saylor
Saylors
Sayman
Sayne
Sayre
Sayres
Saysana
Saysithideth
Saysongkham
Sayward
Sayyed
Sazama
Sbano
Sbarra
Sberna
Sboro
Scaccia
Scacco
Scace
Scachette
Scadden
Scadlock
Scafe
Scaff
Scaffe
Scaffidi
Scafuri
Scafuto
Scaggs
Scaglione
Scagliotti
Scahill
Scaia
Scaiano
Scaife
Scala
Scale
Scales
Scalese
Scalet
Scalf
Scali
Scalia
Scalice
Scalise
Scalisi
Scallan
Scalley
Scallion
Scallon
Scallorn
Scally
Scalzi
Scalzo
Scaman
Scamardo
Scamehorn
Scammahorn
Scammon
Scampoli
Scancarello
Scandalios
Scandalis
Scandrett
Scandura
Scandurra
Scanio
Scanlan
Scanlin
Scanlon
Scannapieco
Scannell
Scanneu
Scantlebury
Scantlen
Scantlin
Scantling
Scappaticci
Scarano
Scarber
Scarberry
Scarboro
Scarborough
Scarbro
Scarbrough
Scarce
Scarcia
Scardina
Scardino
Scarduzio
Scarff
Scarfi
Scarfo
Scarfone
Scargall
Scariano
Scaringe
Scaringi
Scarlata
Scarlato
Scarles
Scarlet
Scarlett
Scarnati
Scarnato
Scarola
Scarp
Scarpa
Scarpaci
Scarpati
Scarpato
Scarpelli
Scarpello
Scarpino
Scarpitta
Scarpitto
Scarpone
Scarr
Scarritt
Scarrow
Scarsdale
Scarsella
Scarset
Scarth
Scarver
Scatenato
Scates
Scattergood
Scatton
Scaturro
Scavetta
Scavo
Scavona
Scavone
Scavotto
Scavuzzo
Scearce
Scee
Scelba
Scelfo
Scelsi
Scelzo
Scerbo
Scercy
Scerra
Schaab
Schaack
Schaad
Schaadt
Schaaf
Schaal
Schaalma
Schaap
Schaar
Schaarschmidt
Schab
Schabacker
Schabbing
Schabel
Schaber
Schaberg
Schabert
Schabes
Schabot
Schabowski
Schacher
Schacherer
Schachsieck
Schacht
Schachter
Schachterle
Schack
Schackow
Schacter
Schad
Schade
Schadegg
Schadel
Schader
Schadle
Schadler
Schadt
Schaecher
Schaedler
Schaefer
Schaefers
Schaeffer
Schaeffler
Schaen
Schaer
Schaetzle
Schaf
Schafer
Schafersman
Schaff
Schaffel
Schaffeld
Schaffer
Schaffert
Schaffhauser
Schaffner
Schaffter
Schaible
Schaich
Schain
Schak
Schakel
Schalk
Schall
Schaller
Schallhorn
Schallig
Schalow
Schamber
Schamberger
Schamburek
Schamel
Schaming
Schammel
Schamp
Schams
Schan
Schanbacher
Schanck
Schandel
Schanding
Schane
Schaneman
Schaner
Schange
Schank
Schanno
Schantini
Schantz
Schanz
Schanzenbach
Schap
Schaper
Schapiro
Schapp
Schappach
Schappell
Schappert
Scharbach
Scharber
Scharbor
Scharbrough
Schardein
Schardt
Scharer
Schares
Scharf
Scharfenberg
Scharff
Scharich
Scharler
Scharmann
Scharmer
Scharnberg
Scharp
Scharpf
Scharping
Scharpman
Scharr
Scharrer
Scharte
Schartz
Scharwath
Schatt
Schattner
Schattschneid
Schatz
Schatzberg
Schatzel
Schatzle
Schatzman
Schau
Schaub
Schaubert
Schaubhut
Schauble
Schaudel
Schauer
Schauf
Schaufelberge
Schaul
Schauland
Schauman
Schaumann
Schaumberg
Schaumburg
Schaunaman
Schaunt
Schaupp
Schaus
Schauwecker
Schavone
Schayer
Scheaffer
Schear
Schearer
Schebel
Schebler
Schech
Schechinger
Schechter
Schechtman
Scheck
Schecter
Schedler
Schee
Scheel
Scheele
Scheeler
Scheer
Scheerer
Scheets
Scheetz
Schefers
Scheff
Scheffel
Scheffer
Scheffert
Scheffler
Scheffrahn
Schegetz
Schehl
Schehr
Schei
Scheib
Scheibe
Scheibelhut
Scheiber
Scheible
Scheiblich
Scheibner
Scheid
Scheide
Scheidecker
Scheidegger
Scheidel
Scheider
Scheiderer
Scheidler
Scheidt
Scheiern
Schein
Scheiner
Scheinost
Scheirman
Scheitlin
Schelb
Schell
Schelle
Schellenberg
Schellenberge
Schellenger
Scheller
Schellermann
Schellhammer
Schellhase
Schellhorn
Schellin
Schelling
Schellman
Schells
Schelp
Scheman
Schember
Schembra
Schembri
Schemm
Schemmel
Schemmer
Schemonia
Schempp
Schenck
Schendel
Schenewerk
Schenfeld
Schenk
Schenkel
Schenkelberg
Schenker
Scheno
Schenz
Schepens
Scheperle
Schepers
Schepis
Schepker
Schepp
Scheppe
Schepper
Scheppke
Scher
Scherb
Scherbarth
Scherbel
Scherbring
Scherer
Scherf
Scherff
Scherich
Scherler
Scherma
Scherman
Schermann
Schermer
Schermerhorn
Scherping
Scherr
Scherrer
Scherrman
Scherschligt
Schertz
Scherz
Scherzer
Schessler
Schetrompf
Schettig
Schettler
Scheu
Scheuer
Scheuerman
Scheuermann
Scheuers
Scheule
Scheulen
Scheumann
Scheunemann
Scheuren
Scheurer
Scheuring
Scheuvront
Scheve
Schewe
Schexnayder
Schey
Scheyer
Schiaffino
Schiano
Schiappa
Schiavi
Schiavo
Schiavone
Schiavoni
Schibi
Schick
Schickedanz
Schickel
Schickler
Schie
Schiebel
Schieber
Schied
Schiedler
Schiefelbein
Schiefen
Schiefer
Schieferstein
Schieffer
Schiel
Schield
Schiele
Schieler
Schielke
Schier
Schierbrock
Schierenbeck
Schiermeier
Schiesher
Schiess
Schiesser
Schiff
Schiffelbein
Schiffer
Schiffert
Schiffler
Schiffman
Schiffmann
Schiffner
Schifko
Schifo
Schikora
Schilawski
Schild
Schilder
Schildgen
Schildknecht
Schildt
Schilk
Schilke
Schill
Schillaci
Schille
Schiller
Schilling
Schillinger
Schillings
Schilmoeller
Schilsky
Schiltz
Schilz
Schimandle
Schimanski
Schimek
Schimel
Schimizzi
Schimke
Schimler
Schimmel
Schimming
Schimpf
Schindel
Schindeldecke
Schindele
Schindewolf
Schindler
Schingeck
Schink
Schinke
Schinkel
Schinker
Schinnell
Schipper
Schippers
Schiraldi
Schiralli
Schirm
Schirmer
Schiro
Schirpke
Schirrmacher
Schirtzinger
Schisler
Schissel
Schissler
Schiveley
Schiver
Schkade
Schlaack
Schlabach
Schlabaugh
Schlabs
Schlachter
Schladweiler
Schlaefer
Schlaefli
Schlaffer
Schlag
Schlagel
Schlager
Schlageter
Schlaht
Schlangen
Schlanger
Schlappi
Schlarb
Schlarbaum
Schlater
Schlather
Schlatter
Schlau
Schlauch
Schlecht
Schlechten
Schleck
Schlecter
Schlee
Schlegel
Schleh
Schlehuber
Schleibaum
Schleich
Schleicher
Schleider
Schleifer
Schleiff
Schleig
Schleimer
Schlein
Schleining
Schleis
Schleisman
Schleker
Schlembach
Schlemmer
Schlender
Schlenger
Schlenker
Schlensker
Schlenz
Schlepp
Schleppenbach
Schlepphorst
Schleppy
Schlereth
Schlesener
Schlesier
Schlesinger
Schlesner
Schlesselman
Schlesser
Schlessman
Schlett
Schlette
Schleuder
Schleusner
Schley
Schlichenmaye
Schlicher
Schlicht
Schlichter
Schlichting
Schlick
Schlicker
Schliep
Schlieper
Schliesser
Schlieter
Schlimmer
Schlindwein
Schlinger
Schlink
Schlinker
Schlipf
Schlipp
Schlissel
Schlitt
Schlitz
Schlitzer
Schlobohm
Schloemann
Schloemer
Schloop
Schlosberg
Schloss
Schlossberg
Schlosser
Schlossman
Schlote
Schlotfeldt
Schlott
Schlotte
Schlotter
Schlotterbeck
Schlotthauer
Schlottman
Schlottmann
Schlotzhauer
Schlueter
Schlumaker
Schlund
Schluneger
Schlup
Schlussel
Schluter
Schmader
Schmahl
Schmal
Schmale
Schmaling
Schmaltz
Schmalz
Schmalzried
Schmand
Schmandt
Schmatz
Schmauder
Schmaus
Schmautz
Schmeckpeper
Schmeeckle
Schmeer
Schmeichel
Schmeider
Schmeidler
Schmeiser
Schmeisser
Schmeling
Schmelmer
Schmelter
Schmeltzer
Schmelz
Schmelzer
Schmelzle
Schmerer
Schmerge
Schmertz
Schmick
Schmid
Schmidbauer
Schmider
Schmidgall
Schmidlin
Schmidt
Schmidtka
Schmidtke
Schmied
Schmieder
Schmiedeskamp
Schmiege
Schmiel
Schmier
Schmierer
Schmiesing
Schmig
Schmille
Schmiot
Schmit
Schmith
Schmitke
Schmitmeyer
Schmits
Schmitt
Schmittou
Schmitz
Schmitzer
Schmoak
Schmoldt
Schmoll
Schmollinger
Schmoyer
Schmuck
Schmucker
Schmuff
Schmuhl
Schmunk
Schmutz
Schmutzler
Schnabel
Schnabl
Schnack
Schnackel
Schnackenberg
Schnader
Schnaible
Schnair
Schnake
Schnakenberg
Schnall
Schnapp
Schnarr
Schnarrs
Schnathorst
Schnautz
Schnebly
Schneck
Schneckloth
Schnee
Schneeberger
Schneekloth
Schneeman
Schneider
Schneiderman
Schneidermann
Schneiders
Schneidman
Schneidmiller
Schneidtmille
Schneiter
Schnelder
Schnell
Schnelle
Schneller
Schnelzer
Schnepel
Schnepf
Schnetter
Schnettler
Schnetzer
Schnibbe
Schnick
Schnicke
Schnickel
Schnider
Schnieder
Schnieders
Schnipper
Schnitker
Schnitman
Schnittker
Schnitz
Schnitzer
Schnitzler
Schnobrich
Schnoke
Schnoor
Schnopp
Schnorbus
Schnorr
Schnuerer
Schnur
Schnurbusch
Schnure
Schnurr
Schnyer
Schober
Schoberg
Schobert
Schoborg
Schoch
Schock
Schockley
Schoderbek
Schoeb
Schoebel
Schoeben
Schoeck
Schoeder
Schoeffler
Schoefield
Schoel
Schoell
Schoeller
Schoellkopf
Schoelman
Schoemaker
Schoeman
Schoemer
Schoen
Schoenbeck
Schoenberg
Schoenberger
Schoenborn
Schoene
Schoeneck
Schoenecker
Schoenegge
Schoeneman
Schoenemann
Schoener
Schoenfeld
Schoenfelder
Schoenfeldt
Schoenhals
Schoenhard
Schoenherr
Schoenhut
Schoenig
Schoening
Schoeninger
Schoenle
Schoenleber
Schoenmaker
Schoenrock
Schoenstein
Schoenthal
Schoenwetter
Schoepf
Schoepfer
Schoepflin
Schoepp
Schoeppner
Schoessow
Schoettle
Schoettmer
Schoewe
Schofell
Schoff
Schoffstall
Schofield
Schofill
Schoggen
Schol
Scholer
Scholes
Scholfield
Scholin
Scholl
Scholle
Scholler
Schollmeier
Schollmeyer
Scholnick
Scholten
Scholtens
Scholtes
Scholtz
Scholz
Scholze
Scholzen
Schomacker
Schomaker
Schomas
Schomberg
Schomburg
Schomer
Schomin
Schommer
Schon
Schonack
Schonaerts
Schonberg
Schonberger
Schone
Schoneck
Schoneman
Schonert
Schones
Schonfeld
Schonhardt
Schoninger
Schons
Schontz
Schoo
Schoof
Schook
School
Schoolcraft
Schooler
Schooley
Schoolfield
Schooling
Schoolman
Schools
Schoon
Schooner
Schoonhoven
Schoonmaker
Schoonover
Schop
Schopflin
Schopmeyer
Schopp
Schoppe
Schopper
Schoppert
Schor
Schorder
Schoreplum
Schorn
Schornick
Schorr
Schorsch
Schorzman
Schossow
Schott
Schou
Schoultz
Schouten
Schouviller
Schouweiler
Schoville
Schow
Schowalter
Schowengerdt
Schrab
Schrack
Schrader
Schradle
Schraeder
Schraff
Schrag
Schrage
Schrager
Schram
Schrameck
Schramek
Schramel
Schramm
Schrandt
Schrank
Schrantz
Schranz
Schraub
Schrauder
Schrauger
Schrawder
Schrayter
Schreacke
Schreader
Schrecengost
Schreck
Schreckengost
Schrecker
Schreckhise
Schrecongost
Schreder
Schreffler
Schreiber
Schreier
Schreifels
Schreimann
Schreiner
Schremp
Schrenk
Schreuder
Schreur
Schreurs
Schreyer
Schriber
Schrick
Schrieber
Schriefer
Schrier
Schriever
Schrimpf
Schrimsher
Schriner
Schriver
Schroader
Schrock
Schroder
Schrodt
Schroedel
Schroeden
Schroeder
Schroedter
Schroen
Schroepfer
Schroeppel
Schroer
Schroeter
Schroff
Schroll
Schrom
Schromen
Schronce
Schroot
Schrope
Schrotenboer
Schroth
Schrott
Schroy
Schroyer
Schrubbe
Schrull
Schrum
Schrumpf
Schrunk
Schrupp
Schryer
Schryver
Schub
Schubach
Schubbe
Schuber
Schubert
Schuble
Schuch
Schuchard
Schuchardt
Schuchart
Schuchat
Schuchman
Schuchmann
Schuck
Schucker
Schuckers
Schuckert
Schuckman
Schudel
Schue
Schuele
Schueler
Schuelke
Schueller
Schuemann
Schueneman
Schuenemann
Schuepfer
Schueren
Schuerholz
Schuering
Schuerman
Schuermann
Schuessler
Schueth
Schuett
Schuette
Schuetz
Schuetze
Schuff
Schuffert
Schug
Schuh
Schuhmacher
Schuhmann
Schuiling
Schuit
Schul
Schuld
Schulder
Schuldt
Schulenberg
Schulenburg
Schuler
Schulist
Schulke
Schulkin
Schull
Schulle
Schuller
Schulman
Schult
Schulte
Schulteis
Schultens
Schulter
Schultes
Schultheis
Schultheiss
Schulthess
Schultz
Schultze
Schulweis
Schulz
Schulze
Schum
Schumacher
Schumachor
Schumacker
Schumaker
Schuman
Schumann
Schumans
Schumer
Schumm
Schummer
Schumpert
Schumucker
Schuneman
Schunemann
Schuner
Schunk
Schunter
Schupbach
Schupp
Schuppenhauer
Schuppert
Schur
Schure
Schurer
Schurg
Schuring
Schurk
Schurkamp
Schurman
Schurr
Schurz
Schussler
Schusted
Schuster
Schusterman
Schustrich
Schut
Schute
Schutjer
Schutt
Schutte
Schutter
Schuttler
Schutz
Schutze
Schutzenhofer
Schutzman
Schuur
Schuyleman
Schuyler
Schwab
Schwabauer
Schwabe
Schwabenbauer
Schwaderer
Schwadron
Schwager
Schwalb
Schwalbe
Schwald
Schwalen
Schwalenberg
Schwall
Schwaller
Schwallie
Schwalm
Schwamberger
Schwan
Schwanbeck
Schwander
Schwandt
Schwanebeck
Schwaner
Schwanke
Schwantd
Schwantes
Schwanz
Schwarcz
Schwark
Schwarm
Schwart
Schwarten
Schwarting
Schwarts
Schwartz
Schwartzbach
Schwartzberg
Schwartze
Schwartzenbur
Schwartzer
Schwartzkopf
Schwartzman
Schwartzwalde
Schwarz
Schwarze
Schwarzenbach
Schwarzenberg
Schwarzer
Schwarzkopf
Schwarzlose
Schwass
Schwebach
Schwebel
Schwebke
Schweda
Schwede
Schweder
Schweer
Schweers
Schwegel
Schweickert
Schweigart
Schweiger
Schweigert
Schweiker
Schweikert
Schweim
Schwein
Schweinberg
Schweiner
Schweinert
Schweinfurth
Schweinsberg
Schweiss
Schweitz
Schweitzer
Schweizer
Schwemm
Schwemmer
Schwenck
Schwend
Schwendeman
Schwendemann
Schwendinger
Schwenk
Schwenke
Schwenneker
Schwent
Schwentker
Schwenzer
Schweppe
Schwer
Schwerd
Schwerdt
Schwerdtfeger
Schwerin
Schwering
Schwertfager
Schwertfeger
Schwertner
Schwery
Schwetz
Schweyen
Schwichtenber
Schwiebert
Schwieger
Schwien
Schwier
Schwieson
Schwiesow
Schwieterman
Schwimmer
Schwind
Schwindt
Schwing
Schwingel
Schwinghammer
Schwingler
Schwinn
Schwipps
Schwisow
Schwister
Schwizer
Schwoerer
Schworm
Schwoyer
Schwuchow
Schwulst
Schy
Sciabica
Sciacca
Sciacchitano
Scialdone
Sciallo
Scialpi
Sciancalepore
Sciandra
Scianna
Sciara
Sciarini
Sciarra
Sciarretta
Sciascia
Sciavillo
Scibetta
Scibilia
Scicchitano
Scicutella
Sciera
Scierka
Scieszka
Scifres
Scigliano
Scimeca
Scinto
Sciola
Scioneaux
Sciortino
Sciotti
Scipio
Scipione
Scipioni
Scircle
Scire
Scisco
Scism
Scites
Sciulli
Sciullo
Sciuto
Scivally
Sclafani
Sclavi
Scobee
Scobey
Scobie
Scoble
Scoby
Scocca
Scofield
Scoggan
Scoggin
Scoggins
Scogin
Scoh
Scola
Scolaro
Scoleri
Scoles
Scolieri
Scollan
Scollard
Scolnik
Scoma
Sconce
Sconiers
Scontras
Sconyers
Scopa
Scopel
Scorca
Scordato
Scordino
Scordo
Score
Scoresby
Scorgie
Scorsone
Scorzelli
Scot
Scothorn
Scotland
Scott
Scotten
Scotti
Scotting
Scotto
Scotton
Scotts
Scotty
Scouller
Scouten
Scovel
Scovell
Scovil
Scovill
Scoville
Scow
Scowden
Scozzafava
Scozzari
Scrabeck
Scranton
Scrape
Screen
Screnci
Screws
Scribellito
Scriber
Scribner
Scrichfield
Scrim
Scrimpsher
Scrimsher
Scripps
Scripter
Scripture
Scritchfield
Scriuner
Scriven
Scrivener
Scrivens
Scriver
Scrivner
Scro
Scrobola
Scroger
Scroggie
Scroggin
Scroggins
Scroggs
Scroggy
Scrogham
Scronce
Scrudato
Scruggs
Scruton
Scsarpisnato
Scucchi
Scudder
Scuderi
Scudero
Scudieri
Scuito
Scull
Scullark
Scullawl
Scullen
Sculley
Scullin
Scullion
Scully
Scungio
Scurci
Scurlock
Scurry
Scurti
Scutt
Scyoc
Sczbecki
Sczygiel
Sdoia
Se
Sea
Seabaugh
Seaberg
Seaberry
Seabert
Seabold
Seabolt
Seaborn
Seabreeze
Seabright
Seabron
Seabrook
Seabrooke
Seabrooks
Seaburg
Seaburn
Seabury
Seacat
Seace
Seachord
Seacord
Seacrest
Seacrist
Seaford
Seaforth
Seager
Seagers
Seagle
Seago
Seagrave
Seagraves
Seagren
Seagroves
Seaholm
Seaholtz
Seahorn
Seajack
Seal
Sealander
Seale
Seales
Sealey
Sealock
Seals
Sealy
Seaman
Seamans
Seamen
Seamon
Seamons
Seamster
Sean
Seaney
Seanez
Seang
Seanger
Seanor
Seaquist
Sear
Seara
Searby
Searcey
Search
Searchfield
Searchwell
Searcy
Seard
Searer
Searfoss
Seargent
Searight
Searing
Searl
Searle
Searles
Searls
Sears
Searson
Seary
Sease
Seashore
Seastrand
Seat
Seate
Seaton
Seats
Seaver
Seavers
Seavey
Seavy
Seaward
Seawell
Seawood
Seawright
Seay
Seba
Sebald
Sebasovich
Sebastian
Sebastiano
Sebastien
Sebastion
Sebben
Sebek
Sebeniecher
Seber
Sebero
Sebers
Sebert
Sebesta
Sebestyen
Sebion
Sebo
Sebold
Sebourn
Sebranek
Sebree
Sebren
Sebring
Sebron
Seburg
Sechang
Sechler
Sechrest
Sechrist
Secker
Seckinger
Seckington
Seckler
Seckletstewa
Seckman
Secky
Second
Secondo
Secor
Secora
Secord
Secore
Secrease
Secrest
Secreto
Secrist
Section
Secunda
Secundo
Seda
Sedam
Sedano
Sedanos
Sedar
Sedberry
Sedbrook
Seddon
Sedenko
Seder
Sedgwick
Sedillo
Sedita
Sedivy
Sedlacek
Sedlachek
Sedlack
Sedlak
Sedlay
Sedler
Sedlock
Sedman
Sedor
Sedore
Sedotal
Sedrakyan
Sedtal
Sedwick
Sedy
See
Seebach
Seebaum
Seeber
Seeberger
Seebold
Seecharan
Seecharran
Seed
Seedborg
Seedorf
Seedorff
Seeds
Seefeld
Seefeldt
Seefried
Seegar
Seegars
Seeger
Seegers
Seegert
Seegmiller
Seegobin
Seehafer
Seeholzer
Seehusen
Seek
Seekamp
Seekell
Seekford
Seekins
Seel
Seelbach
Seelbinder
Seeley
Seelig
Seeliger
Seely
Seelye
Seeman
Seemann
Seemer
Seen
Seeney
Seepersaud
Seering
Seery
Sees
Seese
Seesholtz
Seeton
Seever
Seevers
Seewald
Sefcheck
Sefcik
Sefcovic
Seferovic
Seftick
Sefton
Segal
Segala
Segall
Segalla
Segar
Segarra
Segars
Segawa
Segee
Segel
Segelhorst
Seger
Segerman
Segers
Segerson
Seggerman
Segler
Segner
Sego
Segobia
Segonia
Segota
Segouia
Segovia
Segoviano
Segrave
Segraves
Segrest
Segreto
Segroves
Segui
Seguin
Segundo
Segur
Segura
Seher
Sehgal
Sehl
Sehnert
Sehorn
Sehr
Sehrt
Seiavitch
Seib
Seibel
Seiber
Seiberlich
Seiberling
Seibers
Seibert
Seibold
Seibt
Seid
Seide
Seidel
Seidell
Seiden
Seidenbecker
Seidensticker
Seider
Seiders
Seidita
Seidl
Seidle
Seidler
Seidling
Seidlitz
Seidman
Seidner
Seidt
Seielstad
Seier
Seiersen
Seif
Seifarth
Seifer
Seifert
Seiffert
Seifried
Seifts
Seigart
Seigel
Seiger
Seigfried
Seigle
Seigler
Seigworth
Seikaly
Seikel
Seil
Seiler
Seiley
Seilhamer
Seilheimer
Seilhymer
Seils
Seim
Sein
Seiner
Seip
Seipel
Seiple
Seipp
Seirer
Seise
Seiser
Seisler
Seit
Seiter
Seiters
Seith
Seitz
Seitzinger
Seiver
Seivert
Seiwell
Seiz
Sejkora
Sek
Sekel
Sekerak
Seki
Sekula
Sekulski
Sekuterski
Selakovic
Selan
Selander
Selbe
Selbert
Selbig
Selbo
Selby
Selca
Selden
Selders
Seldin
Seldomridge
Seldon
Sele
Seledon
Seleg
Selem
Selesnick
Selestewa
Seley
Self
Selfe
Selfridge
Selgrade
Selia
Seliba
Selic
Selig
Seliga
Seligman
Seligmann
Seligson
Selim
Selin
Seling
Selinger
Selis
Seliski
Selissen
Selitto
Selk
Selke
Selkey
Selking
Selkirk
Sell
Sella
Sellai
Sellar
Sellards
Sellars
Sellberg
Selle
Selleck
Sellek
Sellen
Seller
Sellers
Selley
Sellick
Sellin
Sellinger
Sellman
Sellmeyer
Sellner
Sells
Selma
Selman
Selmer
Selmon
Selnes
Selover
Selph
Selser
Selsor
Seltrecht
Seltz
Seltzen
Seltzer
Selusi
Selva
Selvage
Selvaggi
Selvaggio
Selvera
Selvester
Selvey
Selvidge
Selvig
Selvy
Selway
Selz
Selzer
Selzler
Semaan
Seman
Semans
Semas
Semasko
Sember
Sembler
Sembrat
Semel
Semen
Semenec
Semenick
Sementilli
Semenza
Semetara
Semidey
Semien
Seminario
Seminole
Semke
Semler
Semmel
Semmens
Semmes
Semmler
Semo
Semon
Semone
Semones
Semonick
Semonis
Semons
Sempek
Semper
Sempertegui
Semple
Semprini
Semrad
Semrau
Semsem
Sen
Sena
Senate
Senato
Senatore
Senavanh
Senay
Sencabaugh
Sendejo
Sender
Senderling
Sendra
Sendro
Seneca
Senecal
Senechal
Senegal
Seneker
Senemounnarat
Senerchia
Senese
Senesenes
Senethavilouk
Seney
Senf
Senff
Senft
Seng
Sengbusch
Senger
Sengstock
Sengun
Sengupta
Sengvilay
Senich
Seniff
Senion
Senior
Senk
Senko
Senn
Senna
Senne
Senneker
Senner
Sennett
Senno
Sennott
Senosk
Sens
Sensabaugh
Sensel
Senseman
Sensenbach
Sensenbrenner
Senseney
Sensenig
Sensibaugh
Sensing
Senske
Sensmeier
Sensor
Senst
Senta
Sentell
Senteno
Senter
Senters
Senti
Sentinella
Sentz
Senz
Seo
Sep
Sepe
Sepeda
Seper
Sephton
Sephus
Sepich
Seppa
Seppala
Seppanen
Seppelt
Seppi
Sept
Septelka
Septer
Septon
Sepulbeda
Sepulueda
Sepulvado
Sepulveda
Sepvlieda
Sequeira
Sequin
Sequra
Ser
Sera
Serabia
Serafin
Serafine
Serafini
Serafino
Seraille
Seraiva
Serandos
Serano
Serapio
Serapion
Serasio
Seratt
Seratti
Serb
Serban
Serbus
Sercovich
Serda
Serdula
Sereda
Seremet
Serena
Serene
Serenil
Sereno
Serens
Seres
Serey
Serfass
Serfling
Serfoss
Serge
Sergeant
Sergent
Sergi
Sergio
Sergovia
Serianni
Serice
Serie
Seright
Sering
Serini
Serino
Serio
Serisky
Serl
Serles
Sermania
Sermeno
Sermersheim
Sermon
Sermons
Serna
Sernas
Sero
Seroka
Serpa
Serpas
Serpe
Serpico
Serr
Serra
Serramo
Serrand
Serrano
Serrant
Serrao
Serrata
Serrato
Serratore
Serratos
Serravalli
Serre
Serrell
Serres
Serret
Serrett
Serrin
Serro
Sers
Sersen
Sert
Sertuche
Serum
Serva
Servais
Servan
Servano
Servant
Servantes
Servantez
Servatius
Serve
Servedio
Servello
Serven
Server
Servey
Servi
Service
Servidio
Serville
Servin
Servino
Servis
Serviss
Servoss
Seryak
Sesareo
Sesay
Sesco
Sesko
Sesler
Sesley
Sesma
Sespinosa
Sessa
Sesser
Sessin
Session
Sessions
Sessler
Sesso
Sessom
Sessoms
Sessum
Sessums
Sester
Sestoso
Seta
Setaro
Setchell
Setera
Seth
Sether
Sethi
Seti
Setias
Setlak
Setler
Setliff
Setlock
Seto
Seton
Setser
Sette
Settecase
Setter
Setterberg
Setterland
Setters
Settimo
Setting
Settino
Settle
Settlemire
Settlemires
Settlemyre
Settler
Settles
Setton
Setty
Setzer
Setzler
Seu
Seubert
Seuell
Seufer
Seufert
Seumanu
Seung
Seurer
Seuss
Seutter
Sevaaetasi
Sevadjian
Sevcik
Sevedge
Sevenbergen
Seveney
Sever
Severa
Severance
Severe
Severi
Severin
Severino
Severn
Severns
Severo
Severs
Severson
Severt
Severtson
Severy
Severyn
Sevey
Sevick
Sevier
Sevigny
Sevilla
Sevillano
Seville
Sevin
Sevy
Sewade
Sewald
Sewall
Seward
Seweall
Sewell
Sewer
Sewester
Sewyerd
Sexauer
Sexson
Sexton
Sey
Seyal
Seyb
Seybert
Seybold
Seydel
Seyer
Seyfarth
Seyfert
Seyfried
Seykora
Seykoski
Seyler
Seyller
Seymer
Seymor
Seymore
Seymour
Seymoure
Seys
Sfatcu
Sfera
Sferra
Sferrazza
Sforza
Sgambati
Sgammato
Sgrignoli
Sgro
Sgroi
Sgueglia
Sha
Shaak
Shabala
Shaban
Shabazz
Shabel
Shaben
Shabot
Shack
Shackelford
Shackelton
Shackett
Shackford
Shackle
Shackleford
Shackleton
Shacklett
Shackley
Shad
Shadazz
Shadburn
Shadd
Shadden
Shadding
Shaddix
Shaddock
Shaddox
Shadduck
Shade
Shader
Shadfar
Shadiack
Shadid
Shadix
Shadle
Shadler
Shadley
Shadoan
Shadow
Shadowens
Shadrick
Shadwell
Shadwick
Shady
Shae
Shaefer
Shaeffer
Shaer
Shafe
Shafer
Shaff
Shaffen
Shaffer
Shaffner
Shaffren
Shaffstall
Shafi
Shafran
Shaftic
Shafto
Shaggy
Shaginaw
Shah
Shahan
Shahbaz
Shaheed
Shaheen
Shahid
Shahim
Shahin
Shahinfar
Shahinian
Shaikh
Shain
Shake
Shaker
Shakespear
Shakespeare
Shakin
Shakir
Shaklee
Shakoor
Shala
Shalam
Shalash
Shalhoub
Shalhoup
Shaline
Shall
Shalla
Shallcross
Shallenberger
Shallow
Shalwani
Sham
Shamapande
Shamas
Shambaugh
Shambley
Shamblin
Shambo
Shambrook
Shamburg
Shamburger
Shamel
Shames
Shami
Shamily
Shamir
Shamlin
Shammaa
Shammah
Shammo
Shamonsky
Shamp
Shampine
Shams
Shamsi
Shamsiddeen
Shan
Shanaa
Shanafelt
Shanahan
Shanberg
Shand
Shandley
Shandro
Shands
Shandy
Shane
Shaner
Shaneyfelt
Shangraw
Shanholtz
Shanholtzer
Shani
Shank
Shanker
Shankin
Shankland
Shankle
Shankles
Shanklin
Shankman
Shanks
Shanley
Shanna
Shanno
Shannon
Shannonhouse
Shanon
Shanor
Shansky
Shantz
Shao
Shapard
Shape
Shaper
Shapero
Shapin
Shapino
Shapiro
Shapleigh
Shapley
Shapouri
Shappard
Shappell
Shappen
Shappy
Shapskinsky
Sharabi
Sharar
Sharber
Sharbono
Share
Shareef
Sharer
Sharf
Shariat
Sharick
Sharif
Shariff
Sharifi
Sharits
Shark
Sharkey
Sharko
Sharley
Sharlin
Sharlow
Sharma
Sharman
Sharon
Sharp
Sharpe
Sharper
Sharperson
Sharpes
Sharpey
Sharples
Sharpless
Sharpley
Sharplin
Sharpnack
Sharps
Sharpsteen
Sharpton
Sharr
Sharrai
Sharrar
Sharrard
Sharratt
Sharrer
Sharrett
Sharrieff
Sharrock
Sharron
Sharrow
Shartle
Shartrand
Sharum
Shary
Shaske
Shasky
Shasteen
Shastri
Shatek
Shatley
Shatrau
Shatswell
Shatt
Shattles
Shatto
Shattuck
Shatz
Shatzer
Shau
Shaub
Shaud
Shauer
Shauf
Shauger
Shaughnessy
Shaul
Shaulis
Shaull
Shave
Shaver
Shavers
Shaw
Shawaiki
Shawber
Shawcroft
Shawe
Shawgo
Shawhan
Shawl
Shawler
Shawley
Shawn
Shawnee
Shawver
Shay
Shayne
Shazier
Shbi
Shea
Shead
Sheaff
Sheaffer
Sheahan
Sheakley
Sheaks
Shealey
Shealy
Sheaman
Shean
Shear
Sheard
Shearer
Sheares
Shearhart
Shearier
Shearin
Shearing
Shearman
Shearn
Shearon
Shears
Sheasby
Sheats
Shebby
Shebchuk
Sheck
Sheckler
Sheckles
Shed
Shedd
Shedden
Shedlock
Shedrick
Sheeder
Sheedy
Sheehan
Sheehy
Sheekey
Sheeks
Sheeler
Sheeley
Sheely
Sheen
Sheer
Sheeran
Sheerer
Sheerin
Sheesley
Sheets
Sheetz
Sheff
Sheffel
Sheffer
Sheffey
Sheffield
Sheffler
Sheffo
Sheftall
Shefte
Shehab
Shehan
Shehane
Shehata
Shehee
Shehorn
Sheidler
Sheikh
Sheil
Sheild
Sheilds
Shein
Sheinbein
Sheinberg
Sheingold
Sheirich
Sheive
Shekarchi
Shekels
Shekey
Sheladia
Shelburn
Shelburne
Shelby
Shelden
Sheldon
Sheldrick
Sheldrup
Shelenberger
Sheler
Sheley
Shelhamer
Shelhorse
Sheline
Shelite
Shelko
Shelkoff
Shell
Shellabarger
Shellenbarger
Shellenberger
Sheller
Shelley
Shellgren
Shellhaas
Shellhamer
Shellhammer
Shellhorn
Shelling
Shellito
Shellman
Shellnut
Shells
Shellum
Shelly
Shelman
Shelmon
Shelnutt
Shelor
Shelp
Shelpman
Shelquist
Shelstad
Shelsy
Shelter
Shelton
Sheltra
Sheltrown
Shelvey
Shelvin
Shelvy
Shely
Sheman
Shemanski
Shemper
Shempert
Shemwell
Shen
Shenassa
Shenberger
Shene
Shenefield
Sheneman
Sheng
Shenk
Shenkel
Shenker
Shenkle
Shenkman
Shenton
Shepard
Shepardson
Shepeard
Sheperd
Shephard
Shepheard
Shepherd
Shepler
Shepley
Shepp
Sheppard
Shepperd
Shepperdson
Shepperson
Shepps
Sher
Sherard
Sherbert
Sherbo
Sherbon
Sherbondy
Sherburn
Sherburne
Sherdon
Shere
Sherer
Sherfey
Sherfield
Sherfy
Sherick
Sheridan
Sheridon
Sherief
Sherif
Sheriff
Sherill
Sherk
Sherle
Sherles
Sherley
Sherlin
Sherling
Sherlock
Sherman
Shermer
Shern
Sheroan
Sherod
Sherow
Sherr
Sherraden
Sherrange
Sherrard
Sherratt
Sherrell
Sherren
Sherrer
Sherretts
Sherrick
Sherril
Sherrill
Sherrin
Sherrock
Sherrod
Sherron
Sherrow
Sherry
Shers
Shertzer
Sherville
Sherwin
Sherwood
Sheskey
Sheston
Sheth
Shetlar
Shetler
Shetley
Shetrawski
Shetrone
Shetter
Shetterly
Shettle
Shettleroe
Shettsline
Shetz
Sheu
Sheumaker
Shevenell
Shevitz
Shevlin
Shew
Sheward
Shewbridge
Shewchuk
Shewmake
Shewmaker
Shey
Shi
Shiba
Shibahara
Shibata
Shibi
Shibles
Shibley
Shibuya
Shick
Shidel
Shideler
Shidemantle
Shider
Shidler
Shido
Shieh
Shiel
Shield
Shields
Shiels
Shier
Shierling
Shiers
Shiever
Shiffer
Shifferd
Shiffler
Shifflet
Shifflett
Shifflette
Shiflet
Shiflett
Shifley
Shifman
Shifrin
Shigematsu
Shigemi
Shigemitsu
Shigeta
Shigley
Shigo
Shih
Shihadeh
Shiiba
Shiigi
Shike
Shikles
Shikuma
Shildneck
Shiley
Shiliata
Shilkuski
Shill
Shilleh
Shiller
Shilling
Shillingburg
Shillinger
Shillingford
Shillings
Shillingsford
Shillito
Shilo
Shiloh
Shilt
Shilts
Shim
Shima
Shimabukuro
Shimada
Shimanuki
Shimaoka
Shimasaki
Shimek
Shimer
Shiminski
Shimizu
Shimko
Shimkus
Shimmel
Shimmin
Shimo
Shimomura
Shimon
Shimonishi
Shimp
Shimshak
Shimsky
Shimura
Shin
Shina
Shinabarger
Shinaberry
Shinabery
Shinall
Shinault
Shindel
Shindle
Shindledecker
Shindler
Shindo
Shindorf
Shine
Shiner
Shines
Shingledecker
Shingler
Shingles
Shingleton
Shingleur
Shinholster
Shininger
Shinkel
Shinkle
Shinko
Shinn
Shinners
Shinney
Shinnick
Shinoda
Shinsel
Shinsky
Shintaku
Shintani
Ship
Shipe
Shipes
Shipler
Shiplet
Shiplett
Shipley
Shipman
Shipmen
Shipp
Shippee
Shippen
Shipper
Shippey
Shipps
Shippy
Shipton
Shipwash
Shira
Shirah
Shirai
Shiraishi
Shirakawa
Shiraki
Shirar
Shird
Shire
Shireman
Shirer
Shires
Shirey
Shirilla
Shiring
Shirk
Shirkey
Shirley
Shiro
Shiroma
Shirota
Shirts
Shirvanian
Shishido
Shisila
Shisler
Shiu
Shive
Shivel
Shively
Shiver
Shiverdecker
Shivers
Shives
Shivley
Shivy
Shiyou
Shkreli
Shmidt
Shoaf
Shoaff
Shoals
Shoat
Shoats
Shobe
Shober
Shock
Shockency
Shockey
Shockley
Shoddie
Shodunke
Shoe
Shoemake
Shoemaker
Shoeman
Shoemate
Shoen
Shoenberger
Shoener
Shofestall
Shoff
Shoffner
Shoffstall
Shofner
Shoger
Shogren
Shoji
Sholar
Sholders
Sholes
Sholette
Sholl
Shollenbarger
Shollenberger
Sholler
Sholtis
Sholty
Shomaker
Shoman
Shomer
Shomin
Shomo
Shon
Shone
Shonerd
Shones
Shongo
Shonk
Shonka
Shonkwiler
Shont
Shonts
Shontz
Shoobridge
Shook
Shoop
Shoopman
Shopbell
Shope
Shopen
Shopp
Shoptaw
Shor
Shorb
Shore
Shores
Shorette
Shorey
Shorkey
Shorr
Shorrock
Short
Shortell
Shorten
Shorter
Shortes
Shortey
Shorthair
Shortino
Shortle
Shortnacy
Shortridge
Shorts
Shortsleeve
Shortt
Shorty
Shost
Shostak
Shotkoski
Shoto
Shott
Shotton
Shotts
Shotwell
Shough
Shoulars
Shoulder
Shoulders
Shouldice
Shoulta
Shoults
Shoultz
Shoumaker
Shoun
Shoup
Shoupe
Shouse
Shouts
Shove
Shover
Shovlin
Show
Showalter
Showden
Showe
Showell
Showen
Showers
Showes
Showman
Shown
Shows
Shoyer
Shrader
Shrake
Shramek
Shrawder
Shreck
Shreckengost
Shreeve
Shreeves
Shreffler
Shrefler
Shreiner
Shren
Shreve
Shreves
Shrewsberry
Shrewsbury
Shrider
Shrier
Shrieves
Shrigley
Shrimplin
Shriner
Shriver
Shrock
Shrode
Shroeder
Shroff
Shroll
Shropshire
Shrout
Shroyer
Shrum
Shry
Shryack
Shryer
Shryock
Shu
Shuart
Shub
Shubeck
Shubert
Shubin
Shubov
Shubrick
Shubrooks
Shuck
Shuckhart
Shue
Shuecraft
Shuemaker
Shuey
Shufelt
Shuff
Shuffield
Shufflebarger
Shuffleburg
Shuffler
Shufford
Shuffstall
Shuford
Shuga
Shugars
Shugart
Shugrue
Shuhi
Shuker
Shukert
Shukla
Shula
Shular
Shulda
Shulenberger
Shuler
Shulick
Shull
Shullick
Shulman
Shulse
Shult
Shulte
Shulthess
Shultis
Shults
Shultz
Shulund
Shulz
Shum
Shumake
Shumaker
Shuman
Shumard
Shumate
Shumay
Shumiloff
Shummon
Shumock
Shumpert
Shumski
Shumsky
Shumway
Shunk
Shunnarah
Shupe
Shupert
Shuping
Shupp
Shuptrine
Shur
Shurak
Shure
Shurgot
Shurkus
Shurley
Shurman
Shurr
Shurtleff
Shurtliff
Shurts
Shurtz
Shuskey
Shusta
Shuster
Shusterman
Shute
Shuter
Shutes
Shutler
Shutt
Shutte
Shutter
Shutters
Shuttlesworth
Shuttleworth
Shutts
Shutty
Shvey
Shwab
Shy
Shybut
Shymske
Shyne
Shyu
Si
Sia
Siad
Sialana
Siami
Sianez
Siangco
Siano
Siaperas
Siar
Sias
Sibal
Sibayan
Sibbald
Sibbett
Sibble
Sibel
Sibell
Sibert
Sibeto
Sibgert
Sibilia
Sibilio
Sibille
Sible
Sibley
Sibounma
Sibrel
Sibrian
Siburt
Sic
Sica
Sicard
Sicari
Sichel
Sicheneder
Sichler
Sichta
Sichting
Sicilia
Sicilian
Siciliano
Sicinski
Sick
Sickafoose
Sickel
Sickels
Sickendick
Sickinger
Sickle
Sickler
Sickles
Sickman
Sickmeir
Sicks
Sicola
Sicotte
Sicurella
Sida
Sidberry
Sidbury
Siddall
Siddell
Siddens
Siddiq
Siddiqi
Siddique
Siddiqui
Siddle
Siddon
Siddons
Siddoway
Side
Sidebottom
Sidelinger
Sidell
Sideman
Sidener
Sider
Siderine
Sideris
Siderman
Siders
Sides
Sidhom
Sidhu
Sidi
Sidle
Sidler
Sidles
Sidley
Sidman
Sidney
Sidor
Sidorowicz
Sidoti
Sidur
Sidwell
Siebe
Siebel
Sieben
Siebenaler
Siebenberg
Siebeneck
Siebens
Siebenthal
Sieber
Sieberg
Siebers
Siebert
Siebold
Sieck
Sieczka
Sieczkowski
Siedel
Siedlecki
Siedlik
Siedner
Siefert
Siefferman
Siefke
Siefken
Siefker
Siefkes
Sieg
Siegal
Siegel
Sieger
Siegers
Siegert
Siegfreid
Siegfried
Siegle
Siegler
Siegmund
Siegrist
Siegwarth
Sieja
Sieker
Sielaff
Sieler
Sieligowski
Sieloff
Sielski
Siem
Siembida
Siemek
Siemens
Siemer
Siemering
Siemers
Sieminski
Siemon
Siemonsma
Siems
Siemsen
Sien
Siena
Sienicki
Sienkiewicz
Sienko
Siepker
Sier
Sieracki
Sieradski
Sieren
Sierer
Siering
Sierra
Sierras
Siers
Siert
Sierzenga
Sietsema
Sietsma
Sietz
Sieve
Sievel
Siever
Sieverding
Sievers
Sieverson
Sievert
Sievertsen
Sieving
Siew
Siewers
Siewert
Sifers
Siffert
Sifford
Sifontes
Siford
Sifre
Sifuentes
Sigafoos
Sigafus
Sigala
Sigars
Sigel
Sigers
Sigg
Siggers
Siggins
Siglar
Sigler
Sigley
Siglin
Siglow
Sigman
Sigmon
Sigmond
Sigmund
Signaigo
Signor
Signore
Signorelli
Signorile
Signorino
Signs
Sigona
Sigrist
Siguenza
Sigurdson
Sigwart
Sigworth
Sikander
Sikarskie
Sikat
Sikel
Siker
Sikes
Siket
Sikkema
Sikkila
Sikkink
Sikora
Sikorra
Sikorski
Sikula
Sil
Silacci
Silago
Silagy
Silano
Silao
Silas
Silbaugh
Silber
Silberberg
Silberg
Silberhorn
Silberman
Silbernagel
Silberstein
Silbert
Silbiger
Silcott
Silcox
Silence
Sileo
Siler
Silerio
Siles
Silevinac
Silfies
Silguero
Silha
Siliado
Siliezar
Silis
Silk
Silkenson
Silker
Silkwood
Sill
Silla
Sillas
Sillavan
Silleman
Siller
Sillery
Silletto
Silliman
Sillitoe
Sillitti
Sillman
Silloway
Sills
Silman
Silmon
Silos
Silovich
Silquero
Silsbee
Silsby
Siltman
Silton
Siluis
Silva
Silvaggio
Silvan
Silvano
Silvas
Silveira
Silver
Silvera
Silverberg
Silverhorn
Silveri
Silveria
Silverio
Silverman
Silvernail
Silvernale
Silverness
Silvers
Silversmith
Silverstein
Silverstone
Silverthorn
Silverthorne
Silvertooth
Silverwood
Silvester
Silvestre
Silvestri
Silvestrini
Silvestro
Silvey
Silvi
Silvia
Silvio
Silvis
Silvius
Sim
Sima
Simank
Simao
Simar
Simard
Simas
Simbeck
Simcheck
Simcic
Simco
Simcock
Simcoe
Simcox
Sime
Simek
Simelton
Simenez
Simens
Simensky
Simenson
Simental
Simeon
Simeona
Simeone
Simer
Simerly
Simers
Simerson
Simes
Simi
Simich
Simien
Simila
Similien
Similton
Simington
Simino
Siminski
Simiskey
Simison
Simister
Simitian
Simkin
Simkins
Simko
Simkowitz
Simkulet
Simler
Simley
Simlick
Simm
Simmelink
Simmens
Simmer
Simmering
Simmerman
Simmers
Simmes
Simmions
Simmoms
Simmon
Simmond
Simmonds
Simmoneau
Simmons
Simms
Simo
Simoens
Simoes
Simokat
Simon
Simoncini
Simonds
Simone
Simoneau
Simoneaux
Simoneavd
Simonelli
Simonet
Simonett
Simonetta
Simonetti
Simonetty
Simoni
Simonian
Simoniello
Simonin
Simonis
Simons
Simonsen
Simonson
Simonton
Simor
Simoson
Simpelo
Simper
Simpers
Simpkin
Simpkins
Simple
Simpler
Simpliciano
Simplot
Simpon
Simpson
Simpton
Simril
Sims
Simser
Simson
Simuel
Simunek
Simunovich
Simzer
Sin
Sina
Sinagra
Sinarath
Sinard
Sinatra
Sincebaugh
Sincell
Sinclair
Sinclaire
Sincock
Sindel
Sindelar
Sinden
Sindlinger
Sindoni
Sindorf
Sindt
Sine
Sineath
Sinegal
Siner
Sines
Sing
Singco
Singeltary
Singelton
Singer
Singerman
Singewald
Singh
Singharath
Singhisen
Single
Singler
Singletary
Singleterry
Singleton
Singley
Singlton
Singo
Sings
Singson
Sington
Singuefield
Sinha
Siniard
Sinibaldi
Sinicki
Sininger
Siniscalchi
Sinisi
Sinistore
Sinitiere
Sink
Sinka
Sinkey
Sinkfield
Sinkiewicz
Sinkler
Sinko
Sinkovich
Sinks
Sinn
Sinner
Sinnett
Sinning
Sinnott
Sinon
Sinopoli
Sinor
Sinotte
Sinquefield
Sinrich
Sins
Sinsabaugh
Sinstack
Sinton
Sinyard
Siok
Sioma
Siona
Sionesini
Siordia
Sipe
Sipes
Siphan
Sipho
Sipkema
Sipla
Siple
Sipler
Sipos
Sipp
Sippel
Sipper
Sippial
Sipple
Sippy
Siprasoeuth
Sipriano
Siptak
Siqueiros
Siracusa
Siracuse
Siragusa
Sirak
Siravo
Sirbaugh
Sircy
Siregar
Sirek
Siren
Sires
Sirhan
Siriani
Sirianni
Siriano
Sirico
Sirignano
Sirin
Sirk
Sirko
Sirkoch
Sirles
Sirls
Sirman
Sirmans
Sirmon
Sirmons
Sirna
Sirnio
Sirois
Siroka
Siroky
Sirolli
Siron
Sirosky
Sirpilla
Sirrine
Sirucek
Siruta
Sirwet
Sis
Sisavath
Sisca
Sischo
Sisco
Sise
Sisemore
Sisk
Siska
Siske
Siskey
Siskin
Siskind
Sisko
Sisler
Sisley
Sisneros
Sisneroz
Sisney
Sisofo
Sisomphou
Sison
Sissac
Sissel
Sissell
Sission
Sissman
Sissom
Sisson
Sista
Sistek
Sisti
Sisto
Sistrunk
Sit
Sita
Sitaca
Sitar
Siter
Sites
Sith
Sither
Sitkiewicz
Sitko
Sitler
Sito
Sitosky
Sitra
Sitsler
Sitt
Sitter
Sitterding
Sitterly
Sitterson
Sitterud
Sittig
Sittloh
Sittman
Sittner
Sitto
Sitton
Sittre
Sitts
Situ
Sitz
Sitze
Sitzes
Sitzler
Sitzman
Siu
Siuda
Siurek
Siva
Sivak
Sival
Sivalia
Sivan
Sivay
Sivels
Siver
Siverd
Siverling
Siverly
Sivers
Siverson
Sivert
Sivertsen
Sivertson
Sivia
Sivic
Sivick
Sivie
Sivik
Sivilay
Sivills
Sivils
Sivley
Sivret
Sivyer
Siwek
Siwicki
Siwiec
Siwik
Siwinski
Six
Sixkiller
Sixon
Sixsmith
Sixt
Sixtos
Sizar
Sizelove
Sizemore
Sizer
Sjaarda
Sjerven
Sjoberg
Sjodin
Sjogren
Sjolander
Sjolund
Sjoquist
Sjostrand
Sjostrom
Sjulstad
Skaar
Skaare
Skabo
Skaer
Skafec
Skaff
Skafidas
Skaflen
Skagen
Skagerberg
Skaggs
Skahan
Skains
Skala
Skalak
Skalecki
Skalicky
Skalka
Skalla
Skalski
Skalsky
Skane
Skanes
Skapura
Skar
Skarda
Skare
Skarke
Skarphol
Skartvedt
Skarupa
Skarzynski
Skates
Skattebo
Skay
Skea
Skeans
Skeele
Skeels
Skeem
Skeen
Skeens
Skees
Skeesick
Skeet
Skeete
Skeeter
Skeeters
Skeets
Skeffington
Skehan
Skeldon
Skelley
Skelly
Skelton
Skemp
Skenandore
Skender
Skene
Skepple
Skerl
Skerrett
Skevofilakas
Skewis
Skiba
Skibbe
Skibicki
Skibinski
Skibisky
Skibo
Skibosh
Skibski
Skidgel
Skidmore
Skiff
Skiffington
Skildum
Skiles
Skill
Skillan
Skillen
Skillern
Skillett
Skillicorn
Skilling
Skillings
Skillington
Skillman
Skillom
Skillpa
Skilton
Skimehorn
Skinkle
Skinnen
Skinner
Skinsacos
Skipper
Skipworth
Skirvin
Skiver
Skjei
Sklar
Sklenar
Sknerski
Skobiak
Skocilich
Skoczen
Skoczylas
Skoff
Skog
Skogen
Skoglund
Skogstad
Skoien
Skok
Skokan
Skokowski
Skold
Skolfield
Skolnick
Skolnik
Skomo
Skomsky
Skonczewski
Skone
Skoog
Skora
Skorcz
Skordahl
Skorepa
Skornia
Skornik
Skorski
Skorupa
Skorupski
Skotnicki
Skousen
Skov
Skovira
Skovlund
Skow
Skowron
Skowronek
Skowronski
Skowyra
Skrabanek
Skradski
Skrebes
Skreen
Skretowicz
Skrine
Skrip
Skripko
Skrobacki
Skroch
Skrocki
Skrzypek
Skrzypinski
Skubik
Skubis
Skufca
Skulski
Skultety
Skupski
Skura
Skurski
Skursky
Skuse
Skutnik
Skutt
Skwara
Skwarek
Skweres
Skyberg
Skye
Skyers
Skyes
Skyles
Slabaugh
Slaboda
Slaby
Slack
Slackman
Slacum
Slade
Sladek
Slader
Sladick
Sladky
Slaff
Slagel
Slager
Slaght
Slagle
Slagowski
Slagter
Slaight
Slain
Slama
Slane
Slaney
Slanina
Slankard
Slanker
Slape
Slappey
Slappy
Slark
Slate
Slaten
Slater
Slates
Slatin
Slatkin
Slaton
Slatten
Slatter
Slattery
Slatton
Slaubaugh
Slaugenhaupt
Slaugh
Slaughenhoupt
Slaughter
Slaughterbeck
Slauson
Slaven
Slavens
Slavick
Slavik
Slavin
Slavinski
Slavis
Slawski
Slawson
Slawter
Slay
Slaybaugh
Slayden
Slaydon
Slaymaker
Slayman
Slayter
Slayton
Sleaford
Slechta
Sledd
Sledge
Sledz
Slee
Sleek
Sleeman
Sleeper
Sleet
Sleeter
Sleeth
Sleger
Sleigh
Sleight
Sleighter
Sleiman
Slemmer
Slemmons
Slemp
Slenker
Slentz
Sleper
Sleppy
Slepski
Slessman
Sletten
Sleva
Slevin
Slezak
Slice
Slicer
Slick
Slicker
Slider
Slife
Slifer
Sliffe
Slifko
Sligar
Sliger
Sligh
Slight
Slightam
Sliker
Slim
Slimak
Sliman
Slimko
Slimmer
Sliney
Slinger
Slingerland
Slingland
Slingluff
Slinkard
Slinker
Slinsky
Slipp
Slipper
Slisz
Sliter
Sliva
Slivka
Sliwa
Sliwinski
Sliz
Sloan
Sloane
Sloanes
Sloas
Sloat
Slobodnik
Slockbower
Slocomb
Slocombe
Slocum
Slocumb
Slodysko
Slogeris
Sloma
Sloman
Slomba
Slomer
Slominski
Slomka
Slomkowski
Slomski
Slonaker
Slone
Slonecker
Slonski
Sloon
Sloop
Slosek
Sloss
Slosser
Slostad
Slot
Slota
Slotemaker
Sloter
Slothower
Slotkin
Slotnick
Slough
Sloup
Slovacek
Slovak
Slover
Slovick
Slovinski
Slovinsky
Slowe
Slowey
Slowik
Slowinski
Slown
Sluder
Sluis
Sluka
Slunaker
Slupe
Slusar
Slusarski
Slusher
Sluski
Sluss
Slusser
Sluter
Slutsky
Slutzky
Sluyter
Sly
Slye
Slyter
Slyton
Smack
Smades
Smail
Smalarz
Smaldone
Smale
Small
Smallen
Smaller
Smalley
Smallidge
Smallin
Smalling
Smallman
Smallmon
Smalls
Smallwood
Smalt
Smaniotto
Smar
Smarr
Smarra
Smarsh
Smart
Smartt
Smathers
Smaw
Smay
Smayda
Smead
Smeal
Smeathers
Smeby
Smeck
Smedes
Smedick
Smedley
Smedsrud
Smee
Smeenk
Smeja
Smejkal
Smelcer
Smelko
Smelley
Smelser
Smeltz
Smeltzer
Smerdon
Smerkar
Smestad
Smetak
Smetana
Smethers
Smialek
Smialowski
Smid
Smida
Smiddy
Smidt
Smiechowski
Smietana
Smigaj
Smigel
Smigiel
Smiglewski
Smiht
Smiler
Smiles
Smiley
Smiling
Smillie
Smily
Smink
Smisek
Smit
Smith
Smithberger
Smithe
Smithee
Smithen
Smither
Smitherman
Smithers
Smithey
Smithhart
Smithheart
Smithhisler
Smithingell
Smithj
Smithmyer
Smithson
Smithwick
Smitley
Smitreski
Smits
Smittle
Smitty
Smitz
Smoak
Smock
Smoke
Smoker
Smola
Smolder
Smoldt
Smolen
Smolenski
Smolensky
Smoley
Smolic
Smolik
Smolinski
Smolinsky
Smolka
Smolko
Smolnicky
Smolski
Smoot
Smoots
Smotherman
Smothers
Smouse
Smrekar
Smsith
Smtih
Smuck
Smucker
Smudrick
Smugala
Smuin
Smulik
Smull
Smullen
Smurthwaite
Smutnick
Smutny
Smutz
Smutzler
Smyer
Smyers
Smykowski
Smylie
Smyly
Smyntek
Smyre
Smyrl
Smyrski
Smyser
Smyth
Smythe
Snachez
Snaders
Snaer
Snair
Snape
Snaples
Snapp
Snare
Snarr
Snater
Snavely
Snay
Snaza
Snead
Snearly
Sneary
Sneath
Sneathen
Snedden
Sneddon
Snedegar
Snedeger
Snedeker
Snee
Sneed
Sneeden
Sneider
Snelgrove
Snell
Snellbaker
Snellen
Snellenberger
Sneller
Snellgrove
Snelling
Snellings
Snellman
Snelson
Snerling
Snethen
Snetsinger
Snetting
Snide
Snider
Sniezek
Sniff
Sniffen
Sniffin
Snipe
Snipes
Snith
Snitker
Snively
Snobeck
Snock
Snodderly
Snoddy
Snode
Snoderly
Snodgrass
Snoke
Snook
Snooks
Snoots
Snoozy
Snopek
Snorden
Snorton
Snover
Snow
Snowball
Snowberger
Snowdeal
Snowden
Snowder
Snowdon
Snowdy
Snowman
Snuffer
Snuggs
Snyder
Snyders
So
Soans
Soape
Soapes
Soard
Soares
Sobania
Sobanski
Sobba
Sobczak
Sobczyk
Sobczynski
Sobe
Sobeck
Sobel
Sobenes
Sober
Soberanes
Soberanis
Soberano
Sobers
Sobery
Sobeski
Sobey
Sobie
Sobiech
Sobieraj
Sobieski
Sobilo
Sobin
Sobina
Soble
Sobol
Soboleski
Sobolewski
Sobolik
Sobon
Sobota
Sobotka
Sobotta
Sobran
Sobrino
Sobrio
Sobrowski
Sobus
Socci
Socha
Sochan
Sochocki
Sochor
Socia
Sockalosky
Sockey
Socks
Sockwell
Socorro
Soda
Sodachanh
Sodano
Sodaro
Sodawasser
Sode
Sodek
Sodeman
Soden
Soder
Soderberg
Soderblom
Sodergren
Soderholm
Soderling
Soderlund
Soderman
Soderquist
Soders
Soderstrom
Sodervick
Sodhi
Sodini
Sodomka
Soechting
Soeder
Soehl
Soellner
Soenksen
Soens
Soesbe
Sofer
Soffa
Soffel
Soffer
Sofia
Sofka
Sofranko
Softich
Softleigh
Soga
Sogge
Sogol
Sohl
Sohm
Sohn
Sohns
Soho
Sohr
Sohrabi
Sohre
Soibelman
Soifer
Soileau
Soiro
Soisson
Soito
Soja
Sojda
Sojka
Sojo
Sojourner
Sok
Sokal
Sokol
Sokolik
Sokoloff
Sokoloski
Sokolowich
Sokolowski
Sokolski
Sokolsky
Sokorai
Sokotowski
Sokul
Sol
Sola
Soladine
Solages
Solaita
Solak
Solan
Solana
Soland
Solanki
Solano
Solar
Solares
Solari
Solarski
Solarz
Solarzano
Solas
Solazar
Solberg
Soldan
Soldano
Soldavini
Soldeo
Solders
Soldner
Soldo
Soldow
Sole
Solecki
Soledad
Solem
Soleman
Soler
Solera
Soles
Solesbee
Soley
Solgovic
Solheim
Solhjem
Solian
Soliani
Solich
Solid
Soliday
Solie
Soliece
Solien
Solies
Solima
Soliman
Solimeno
Solimini
Solina
Solinas
Solinger
Solinski
Solis
Solito
Solivan
Soliz
Solkowitz
Soll
Solla
Sollars
Sollberger
Solle
Sollenberger
Soller
Sollers
Solley
Solliday
Sollie
Sollis
Sollitto
Sollman
Sollock
Sollors
Solly
Solman
Solmonson
Solo
Soloman
Solomen
Solomon
Solomons
Solon
Solonar
Solonika
Solorio
Solorsano
Solorzano
Soloveichik
Solow
Soloway
Solt
Soltani
Soltau
Soltero
Soltes
Soltis
Soltmann
Solton
Soltow
Soltren
Soltys
Solum
Soluri
Solverson
Solverud
Solwold
Solymani
Som
Somalski
Soman
Somani
Somayor
Somdah
Somer
Somera
Somerfield
Somero
Somers
Somerset
Somerville
Somes
Somilleda
Somji
Somma
Sommar
Sommella
Sommer
Sommerdorf
Sommerfeld
Sommerfeldt
Sommerfield
Sommers
Sommerville
Sommese
Sommons
Somo
Somodi
Somogye
Somogyi
Somoza
Somrak
Somsana
Somsy
Somvang
Son
Sondag
Sonday
Sondelski
Sonderegger
Sondergaard
Sonderman
Sonders
Sonderup
Sondheimer
Sondles
Sondrini
Sondrol
Sondrup
Sones
Song
Songco
Songer
Songster
Songy
Soni
Sonia
Sonier
Sonka
Sonkens
Sonkin
Sonnabend
Sonne
Sonneborn
Sonnee
Sonnefeld
Sonnek
Sonnen
Sonnenberg
Sonnenburg
Sonnenfeld
Sonner
Sonnier
Sonntag
Sonny
Sonoda
Sonoski
Sons
Sonsino
Sonsteng
Sonstroem
Sontag
Sonterre
Sontheimer
Sonza
Soo
Sood
Soohoo
Sookoo
Sookram
Soolua
Soomaroo
Soong
Soop
Soorus
Soos
Soose
Sooter
Sooy
Sopata
Sopczak
Soper
Sopha
Sopher
Sophy
Sopko
Soplop
Sopp
Soppe
Soppeland
Soprych
Soptick
Soqui
Sor
Sora
Sorace
Soran
Soratos
Soravilla
Sorbello
Sorber
Sorbera
Sorbo
Sorce
Sordahl
Sordia
Sorel
Sorell
Sorells
Soren
Sorensen
Sorenson
Sorey
Sorg
Sorgatz
Sorge
Sorgente
Sorgi
Sorhaindo
Soria
Soriano
Sorice
Soricelli
Sorin
Sorkin
Sorley
Sorlie
Sorman
Sorn
Sornsen
Soro
Soroa
Soroka
Sorokata
Sorokin
Sorola
Soron
Soros
Sorotzkin
Sorrel
Sorrell
Sorrells
Sorrels
Sorrentino
Sorrick
Sorrow
Sorsby
Sortino
Sortland
Sorto
Sortor
Sortore
Sorum
Sorvig
Sorvillo
Sorzano
Sos
Sosa
Sosaya
Sosbe
Sosbee
Sosby
Soscia
Sosebee
Sosh
Soshnik
Sosinski
Sosinsky
Sosna
Sosnowski
Sossaman
Sossamon
Sosso
Sossong
Sostre
Sota
Sotak
Sotello
Sotelo
Soter
Sotero
Soteros
Sothen
Sothman
Sotiriou
Sotlar
Soto
Sotolo
Sotolongo
Sotomayer
Sotomayor
Sotos
Sottile
Sotto
Sottosanti
Sou
Soucek
Souchet
Soucie
Soucier
Soucy
Souder
Souders
Souers
Souffrant
Souffront
Souhrada
Soukkhavong
Soukup
Soula
Soulard
Soulasinh
Soule
Soulek
Soules
Soulia
Soulier
Souliere
Soulliere
Soult
Soun
Soundara
Souphom
Sour
Sourlis
Sours
Sourwine
Sous
Sousa
Souser
Souter
South
Southall
Southam
Southand
Southard
Southcott
Souther
Southerland
Southerly
Southern
Southers
Southgate
Southmayd
Southward
Southwell
Southwick
Southwood
Southworth
Souto
Souvannakhily
Souvannakhiry
Souvannarith
Souvannasap
Souvannavong
Souza
Sova
Sovak
Sovel
Sovereign
Sovern
Soverns
Sovey
Sovich
Sovie
Sovocool
Sow
Sowa
Sowada
Soward
Sowards
Sowash
Sowden
Sowder
Sowders
Sowell
Sowells
Sowels
Sower
Sowerby
Sowers
Sowinski
Sowl
Sowle
Sox
Soyars
Soyke
Soza
Sozio
Sozzi
Spaar
Spacagna
Space
Spacek
Spach
Spacht
Spachtholz
Spackman
Spada
Spadaccini
Spadafino
Spadafora
Spadafore
Spadard
Spadaro
Spade
Spadea
Spader
Spadlin
Spadoni
Spady
Spaeth
Spafford
Spagna
Spagnola
Spagnoli
Spagnolia
Spagnolo
Spagnuolo
Spahn
Spahr
Spaid
Spaide
Spain
Spainhour
Spainhower
Spake
Spakes
Spalding
Spalinger
Spall
Spalla
Spallina
Spallone
Spalter
Spaman
Span
Spana
Spanbauer
Spancake
Spane
Spanfellner
Spang
Spangenberg
Spanger
Spangle
Spangler
Spanicek
Spaniel
Spanier
Spanish
Spann
Spannaus
Spannbauer
Spanner
Spannuth
Spano
Spanos
Spanski
Spanswick
Spanton
Spar
Spara
Sparacina
Sparacino
Sparacio
Sparaco
Sparano
Spare
Sparger
Spargo
Spargur
Sparhawk
Spark
Sparkes
Sparkman
Sparks
Sparlin
Sparling
Sparr
Sparrow
Spart
Spartichino
Spartin
Spartz
Spasiano
Spatafora
Spatafore
Spataro
Spates
Spath
Spatz
Spaugh
Spaulding
Spaun
Spaur
Spaw
Spayd
Spayer
Spaziani
Spaziano
Speach
Spead
Speagle
Speak
Speake
Speaker
Speakes
Speakman
Speaks
Spear
Speares
Spearin
Spearing
Spearman
Spearmon
Spearow
Spears
Speas
Spease
Specchio
Spece
Specht
Speciale
Speck
Specken
Specking
Speckman
Specter
Spector
Spee
Speece
Speed
Speedy
Speegle
Speelman
Speer
Speers
Spees
Speese
Spegal
Speh
Spehar
Speice
Speich
Speicher
Speidel
Speidell
Speiden
Speier
Speigel
Speight
Speights
Speilman
Speir
Speirs
Speis
Speiser
Speith
Spell
Spella
Spellacy
Spellane
Speller
Spellman
Spells
Spelman
Spelts
Speltz
Spena
Spenard
Spence
Spencer
Spender
Spendlove
Spene
Spengler
Spenner
Spennicchia
Speno
Spenser
Spenst
Spera
Sperandeo
Sperandio
Speranza
Speraw
Sperazza
Sperbeck
Sperber
Sperberg
Sperdute
Sperduti
Sperger
Sperier
Sperka
Sperl
Sperle
Sperlich
Sperling
Spero
Speroni
Speros
Sperow
Sperrey
Sperry
Spessard
Speth
Spettel
Spetter
Spevacek
Spevak
Speyer
Speyrer
Speziale
Spezio
Sphon
Spice
Spicer
Spicher
Spickard
Spicker
Spickerman
Spickler
Spicknall
Spicuzza
Spidel
Spidell
Spidle
Spiece
Spiegel
Spiegelman
Spiegle
Spiegler
Spieker
Spielberg
Spieler
Spielmaker
Spielman
Spielmann
Spielvogel
Spier
Spiering
Spierling
Spiers
Spies
Spiess
Spieth
Spiewak
Spigelman
Spigelmyer
Spight
Spigner
Spigutz
Spika
Spike
Spiker
Spikes
Spilde
Spiliakos
Spilis
Spilker
Spillane
Spille
Spiller
Spillers
Spillett
Spillman
Spilman
Spilski
Spina
Spinale
Spinar
Spinas
Spincic
Spindel
Spindle
Spindler
Spindola
Spine
Spinella
Spinelli
Spinello
Spinetti
Spiney
Spingler
Spingola
Spink
Spinka
Spinks
Spinn
Spinner
Spinney
Spino
Spinola
Spinosa
Spinoso
Spinoza
Spinuzzi
Spiotta
Spira
Spire
Spirek
Spirer
Spires
Spirito
Spirk
Spirko
Spiro
Spiroff
Spirounias
Spiry
Spisak
Spitale
Spiter
Spitler
Spitsberg
Spittle
Spittler
Spitz
Spitzer
Spitznogle
Spiva
Spivack
Spivak
Spivery
Spivey
Spiwak
Spizer
Spizzirri
Splain
Splane
Splatt
Splawn
Splett
Spletzer
Splinter
Splitt
Splonskowski
Spoden
Spoelstra
Spoerer
Spoerl
Spofford
Spohn
Spohnholz
Spohr
Spolar
Spoleti
Spomer
Sponaugle
Spong
Sponholz
Sponseller
Sponsler
Spontak
Spoon
Spoonamore
Spoonemore
Spooner
Spoor
Sporcic
Spore
Sporer
Sporich
Sporle
Sporleder
Sporman
Sporn
Sport
Sports
Sportsman
Sporysz
Sposato
Sposito
Spoth
Spoto
Spotorno
Spotted
Spotts
Spotwood
Spraberry
Spracklen
Spracklin
Spradley
Spradlin
Spradling
Sprafka
Spragg
Spraggins
Spraggs
Spragins
Spragley
Spraglin
Sprague
Sprain
Sprake
Spraker
Sprandel
Sprang
Spranger
Sprankle
Spraque
Spratlen
Spratley
Spratlin
Spratling
Spratt
Spratte
Sprau
Sprauve
Sprawls
Spray
Sprayberry
Sprecher
Spreen
Sprehe
Spreitzer
Spreng
Sprengeler
Sprengelmeyer
Sprenger
Sprenkel
Sprenkle
Sprewell
Sprigg
Spriggins
Spriggle
Spriggs
Spring
Springate
Springe
Springer
Springfield
Springle
Springman
Springmeyer
Springs
Springstead
Springsteen
Springston
Sprinkel
Sprinkle
Sprinkles
Sprinzl
Spritzer
Sproat
Sprock
Sprole
Sproles
Sprong
Sprosty
Sprott
Sprouffske
Sproul
Sproule
Sproull
Sprouls
Sprouse
Sprout
Sprow
Sprowl
Sprowls
Spruance
Spruce
Spruel
Spruell
Spruiell
Spruill
Spruit
Sprung
Sprunger
Sprunk
Sprvill
Spry
Sprygada
Spuck
Spudis
Spueler
Spuhler
Spuler
Spulick
Spunt
Spurbeck
Spurgeon
Spurger
Spurgers
Spurgin
Spurlin
Spurling
Spurlock
Spurr
Spurrier
Spurzem
Spycher
Spyies
Spyrakos
Spyres
Squadrito
Squair
Squarciafico
Square
Squeo
Squibb
Squier
Squiers
Squillace
Squillante
Squines
Squire
Squires
Squitieri
Squyres
Srader
Sramek
Sreaves
Srey
Srinivasan
Srinvasan
Srivastava
Srnsky
Srock
Sroczynski
Sroka
Sroufe
Srour
Srsen
Srsic
Srygley
Staab
Staack
Staadt
Staal
Staats
Staback
Stabb
Stabel
Stabell
Staber
Staberg
Stabile
Stable
Stableford
Stablein
Stabler
Stabley
Stabs
Stace
Stacer
Stacey
Stach
Stachecki
Stachnik
Stachniw
Stachowiak
Stachowicz
Stachowski
Stachura
Stachurski
Stack
Stacken
Stacker
Stackhouse
Stackpole
Stacks
Stacy
Stadden
Stade
Stadel
Stadelman
Stader
Stadheim
Stadick
Stadler
Stadnik
Stadt
Stadther
Stadtlander
Stadtler
Stadtmiller
Stady
Staebell
Staebler
Staehle
Staehler
Staelens
Staenglen
Staff
Staffeld
Staffen
Staffieri
Staffon
Stafford
Stafiej
Stage
Stageman
Stager
Stagers
Stagg
Stagger
Staggers
Staggs
Stagles
Stagliano
Stagman
Stagnaro
Stagner
Stagnitta
Stagnitto
Stagno
Stagowski
Staheli
Stahl
Stahlberg
Stahle
Stahlecker
Stahler
Stahley
Stahlhut
Stahlman
Stahlnecker
Stahly
Stahmer
Stahnke
Stahoski
Stahr
Stai
Staiano
Staib
Staie
Staiger
Stailey
Stain
Stainbach
Stainback
Stainbrook
Staine
Staines
Staino
Stains
Stair
Staires
Stairs
Stake
Stakelin
Stakem
Stakemann
Staker
Stakes
Stakkeland
Stakley
Stakoe
Stalberger
Stalcup
Stalder
Staley
Stalford
Stalker
Stall
Stallard
Stallbaumer
Stallcup
Staller
Stalley
Stalling
Stallings
Stallins
Stallion
Stallman
Stallone
Stallones
Stallons
Stalls
Stallsmith
Stallsworth
Stallworth
Stalma
Stalnaker
Stalter
Stalvey
Stalworth
Stalzer
Stam
Stamand
Stamant
Stamas
Stamatopoulos
Stambach
Stambaugh
Stambough
Stamdifer
Stamenov
Stamer
Stamey
Stamison
Stamm
Stammel
Stammer
Stammler
Stamnos
Stamos
Stamour
Stamp
Stampe
Stamper
Stampka
Stample
Stampley
Stamps
Stan
Stana
Stanage
Stanaland
Stanard
Stanaway
Stanback
Stanbaugh
Stanberry
Stanbery
Stanbrough
Stancato
Stancer
Stancey
Stanchfield
Stanciel
Stancil
Stancill
Stancle
Stancliff
Stanclift
Stanco
Stancombe
Stancoven
Stanczak
Stanczyk
Standaert
Standafer
Standage
Standahl
Standard
Standback
Standberry
Standefer
Standen
Stander
Standerfer
Standerwick
Standeven
Standfield
Standford
Standifer
Standiford
Standifur
Standing
Standish
Standke
Standlee
Standley
Standors
Standre
Standrew
Standridge
Standring
Standrod
Stands
Staneart
Stanek
Stanely
Staner
Stanert
Stanesic
Stanfa
Stanfield
Stanfill
Stanford
Stanforth
Stang
Stanganelli
Stangarone
Stange
Stangel
Stanger
Stangl
Stangle
Stango
Stangroom
Stanhope
Stania
Stanick
Staniec
Stanier
Stanifer
Staniford
Staniforth
Stanis
Stanish
Stanislaw
Stanislawski
Staniszewski
Stank
Stankaitis
Stanke
Stankey
Stankiewicz
Stanko
Stankovic
Stankovich
Stankowitz
Stankus
Stanley
Stanly
Stannard
Stano
Stanojevic
Stanovich
Stanowski
Stanphill
Stansberry
Stansbery
Stansbury
Stansel
Stansell
Stansfield
Stansifer
Stant
Stanton
Stanuszek
Stanway
Stanwick
Stanwood
Stanzak
Stanzione
Stapel
Stapelman
Stapels
Stapelton
Stapf
Staple
Stapleford
Stapler
Staples
Stapleton
Stapley
Staplins
Stapp
Star
Starace
Starbird
Starbuck
Starcevic
Starcevich
Starch
Starcher
Starchman
Starcic
Starck
Stare
Starek
Stargel
Stargell
Starghill
Starich
Starin
Stark
Starke
Starken
Starkes
Starkey
Starkie
Starkman
Starks
Starkson
Starkweather
Starley
Starlin
Starling
Starliper
Starmer
Starn
Starnaud
Starnauld
Starner
Starnes
Starnold
Starns
Starowicz
Starowitz
Starr
Starratt
Starrett
Starrick
Starring
Starritt
Starrs
Starry
Stars
Start
Startin
Startt
Startup
Startz
Starwalt
Starweather
Stary
Starzyk
Starzynski
Stas
Stasa
Staschke
Staser
Stash
Stasiak
Stasik
Stasinos
Stasio
Stasiuk
Stasko
Stasny
Stassen
Stasser
Stassi
Stassinos
Stastny
Stasulis
Staszak
State
Staten
Stater
States
Statham
Stathas
Stathes
Stathis
Stathopoulos
Stathos
Station
Statires
Statler
Staton
Stattelman
Statton
Statum
Statz
Statzer
Staub
Stauber
Staubin
Stauble
Staubs
Stauch
Staude
Staudenmeier
Stauder
Staudinger
Staudt
Staufenberger
Stauffacher
Stauffer
Staum
Staunton
Staup
Stauss
Stautz
Stave
Stavely
Staver
Staves
Stavinoha
Stavis
Stavish
Stavnes
Stavrides
Stavropoulos
Stavros
Stavrositu
Stavrou
Stavsvick
Stawarz
Stawasz
Stawicki
Stay
Stayer
Stayner
Stayrook
Stayter
Stayton
Stazenski
Stcharles
Stchur
Stclair
Stclaire
Stcroix
Stcyr
Stdenis
Stdenny
Stea
Steach
Stead
Steadham
Steadings
Steadman
Steady
Steagall
Steagell
Steakley
Stealey
Stealy
Steans
Stear
Stearman
Stearn
Stearne
Stearnes
Stearns
Stears
Stebbins
Stebe
Steber
Stebner
Stec
Stech
Stecher
Stechlinski
Stechuchak
Steck
Steckel
Steckelberg
Stecker
Stecklair
Stecklein
Steckler
Steckley
Steckline
Steckman
Steczo
Stedman
Stedronsky
Steeb
Steeber
Steeby
Steed
Steedley
Steedman
Steeg
Steege
Steel
Steele
Steeley
Steelman
Steelmon
Steely
Steen
Steenberg
Steenbergen
Steenburg
Steenburgh
Steeneck
Steenhard
Steenhoven
Steenhuis
Steenken
Steenland
Steeno
Steenrod
Steensland
Steenwyk
Steep
Steeples
Steer
Steere
Steerman
Steese
Steever
Steeves
Stefan
Stefanatos
Stefanelli
Stefani
Stefaniak
Stefanich
Stefanick
Stefanik
Stefano
Stefanovich
Stefanow
Stefanowicz
Stefanski
Stefansky
Steff
Steffa
Steffan
Steffani
Steffee
Steffel
Steffen
Steffenhagen
Steffens
Steffensen
Steffensmeier
Steffenson
Steffes
Steffey
Steffler
Stefford
Steffy
Stefka
Stefl
Stegall
Stegeman
Stegemann
Stegent
Steger
Steggeman
Stegmaier
Stegman
Stegmann
Stegner
Stehle
Stehlik
Stehlin
Stehly
Stehney
Stehno
Stehr
Steib
Steibel
Steiber
Steich
Steichen
Steidel
Steider
Steidinger
Steidl
Steidley
Steier
Steiert
Steifle
Steiger
Steigerwald
Steigerwalt
Steighner
Steigman
Steik
Steil
Steiling
Steimer
Steimle
Stein
Steinacker
Steinau
Steinauer
Steinbach
Steinbacher
Steinback
Steinbauer
Steinbaugh
Steinbeck
Steinberg
Steinberger
Steinbock
Steinborn
Steinbrecher
Steinbrenner
Steinbrink
Steinbrook
Steinbruckner
Steinburg
Steindorf
Steine
Steiner
Steinerkert
Steinert
Steines
Steinfeld
Steinfeldt
Steinger
Steinhagen
Steinhardt
Steinhart
Steinharter
Steinhauer
Steinhaus
Steinhauser
Steinhoff
Steinhorst
Steinhour
Steinhouse
Steiniger
Steininger
Steinkamp
Steinke
Steinkellner
Steinkirchner
Steinkraus
Steinkuehler
Steinle
Steinlicht
Steinmacher
Steinman
Steinmann
Steinmeiz
Steinmetz
Steinmeyer
Steinmiller
Steinmuller
Steinour
Steinruck
Steins
Steinway
Steinworth
Steir
Steiskal
Steitz
Steitzer
Stejskal
Steketee
Stelb
Stele
Stelk
Stell
Stella
Stellato
Stelle
Steller
Stellfox
Stellhorn
Stelling
Stellings
Stellmacher
Stellman
Stello
Stellpflug
Stelluti
Stelly
Stelmach
Stelmack
Stelman
Steltenpohl
Stelter
Stelting
Steltzer
Stelzer
Stelzl
Stem
Steman
Stemarie
Stembridge
Stemen
Stemler
Stemm
Stemme
Stemmer
Stemmerman
Stemmler
Stemp
Stempel
Stemper
Stempert
Stempien
Stemple
Sten
Stenback
Stenbeck
Stenberg
Stencel
Stencil
Stendal
Stendeback
Stender
Stene
Stenehjem
Stenerson
Stengel
Stengele
Stenger
Stengle
Stenkamp
Stenman
Stenn
Stenner
Stennett
Stennis
Stenquist
Stenseth
Stensland
Stenslie
Stenslien
Stenson
Stensrud
Stenstrom
Stent
Stentzel
Stenz
Stenzel
Step
Stepan
Stepanek
Stepaniak
Stepanian
Stepanik
Stepanski
Stepchinski
Stephan
Stephanie
Stephano
Stephans
Stephanski
Stephany
Stephco
Stephen
Stephens
Stephensen
Stephenson
Stephson
Stepien
Stepler
Stepleton
Stepney
Stepnoski
Stepnowski
Stepovich
Stepp
Steppe
Steppello
Steppig
Stepps
Stepro
Stepter
Steptoe
Steptore
Ster
Sterba
Sterback
Sterbenz
Sterett
Sterger
Stergios
Sterk
Sterkel
Sterkenburg
Sterker
Sterlace
Sterle
Sterley
Sterlin
Sterling
Sterman
Stermer
Stern
Sternal
Sternberg
Sternberger
Sterner
Sternisha
Sternod
Sterns
Sterpka
Sterr
Sterrett
Sterry
Stetke
Stetler
Stetson
Stettler
Stettner
Stetz
Stetzel
Stetzenbach
Steuart
Steube
Steuber
Steuck
Steudeman
Steuer
Steurer
Steury
Steve
Steven
Stevener
Stevens
Stevenson
Stever
Steverson
Steves
Steveson
Stevey
Stevick
Stevinson
Stevison
Steward
Stewardson
Stewart
Stewarts
Stewert
Steyer
Stezzi
Stfleur
Stflorant
Stford
Stfort
Stgelais
Stgeorge
Stgerard
Stgermain
Stgermaine
Sthilaire
Sthill
Sthole
Stibb
Stibbins
Stice
Stich
Sticher
Sticht
Stichter
Stick
Stickel
Stickels
Sticker
Stickford
Stickfort
Stickland
Stickle
Sticklen
Stickler
Stickles
Stickley
Sticklin
Stickman
Stickney
Stickrath
Stickrod
Stidam
Stidd
Stidham
Stidman
Stidstone
Stieb
Stiebel
Stieber
Stief
Stiefel
Stieff
Stieg
Stiegemeier
Stieger
Stiegler
Stieglitz
Stiegman
Stiehl
Stiehm
Stiel
Stielau
Stiely
Stien
Stiens
Stier
Stierle
Stiern
Stiers
Stierwalt
Stifel
Stiff
Stifflemire
Stiffler
Stifter
Stigall
Stiger
Stigers
Stigger
Stiggers
Stigler
Stigsell
Stika
Stike
Stikeleather
Stile
Stiles
Stilgenbauer
Stiliner
Still
Stillabower
Stille
Stiller
Stilley
Stillie
Stillinger
Stillings
Stillion
Stillions
Stillman
Stills
Stillson
Stillwagon
Stillwell
Stilner
Stilphen
Stilson
Stiltner
Stilts
Stiltz
Stilwagen
Stilwell
Stimac
Stimage
Stiman
Stimer
Stimits
Stimler
Stimmel
Stimmell
Stimpert
Stimple
Stimpson
Stimson
Stimus
Stinar
Stinchcomb
Stinchfield
Stinde
Stindt
Stine
Stinebaugh
Stinebuck
Stinehelfer
Stinehour
Stinemetz
Stiner
Stines
Stinespring
Stinett
Stingel
Stinger
Stingle
Stingley
Stinner
Stinnett
Stinnette
Stinser
Stinson
Stinton
Stipanuk
Stipe
Stipek
Stipes
Stipetich
Stipp
Stippich
Stire
Stires
Stirewalt
Stirgus
Stirk
Stirling
Stirman
Stirn
Stirna
Stirrup
Stitch
Stiteler
Stitely
Stites
Stith
Stitt
Stittgen
Stittsworth
Stitz
Stitzel
Stitzer
Stivanson
Stivason
Stiver
Stivers
Stiverson
Stives
Stjacques
Stjames
Stjean
Stjohn
Stjohns
Stjulian
Stjulien
Stjuste
Stlaurent
Stlawrence
Stlouis
Stlouise
Stlucien
Stmarie
Stmartin
Stmary
Stmichel
Stoa
Stoakley
Stobaugh
Stobb
Stobbe
Stobbs
Stober
Stobie
Stobierski
Stocco
Stock
Stockard
Stockbridge
Stockburger
Stockdale
Stockdill
Stocke
Stockebrand
Stockel
Stocker
Stockert
Stockett
Stockfisch
Stockham
Stockhausen
Stockhoff
Stockholm
Stocki
Stocking
Stockinger
Stockley
Stockman
Stockmaster
Stockner
Stockon
Stocks
Stockstill
Stockton
Stockwell
Stockwin
Stoddard
Stoddart
Stodden
Stodder
Stodgell
Stodghill
Stodola
Stodolski
Stodomingo
Stoeber
Stoeberl
Stoebner
Stoeckel
Stoecker
Stoeckert
Stoecklin
Stoeffler
Stoeger
Stoehr
Stoeke
Stoel
Stoeltzing
Stoen
Stoermer
Stoessel
Stoesser
Stoesz
Stoett
Stoetzel
Stoey
Stofer
Stoff
Stoffa
Stoffel
Stoffels
Stoffer
Stofferahn
Stofferan
Stoffey
Stoffle
Stofflet
Stoffregen
Stofko
Stofsky
Stogden
Stoglin
Stogner
Stogsdill
Stohl
Stohler
Stohlton
Stohr
Stohrer
Stohs
Stoia
Stoiber
Stoica
Stojanovic
Stokan
Stoke
Stokel
Stokely
Stoker
Stokes
Stokey
Stokke
Stoklasa
Stokley
Stolar
Stolarik
Stolarski
Stolarz
Stolberg
Stolcals
Stoldt
Stole
Stolebarger
Stolecki
Stoler
Stolfi
Stoliker
Stolinski
Stoll
Stollar
Stolle
Stoller
Stolley
Stollings
Stollsteimer
Stolly
Stolp
Stolpe
Stolsig
Stolt
Stolte
Stoltenberg
Stoltenburg
Stolts
Stoltz
Stoltzfus
Stoltzman
Stolz
Stolze
Stolzenberg
Stolzenburg
Stombaugh
Stomberg
Stommes
Stone
Stoneback
Stonebarger
Stoneberg
Stoneberger
Stonebraker
Stonebreaker
Stonebrook
Stoneburner
Stonecipher
Stonecypher
Stonefield
Stoneham
Stonehouse
Stoneking
Stonelake
Stoneman
Stoner
Stonerock
Stones
Stonesifer
Stonestreet
Stonewall
Stoney
Stong
Stonge
Stonich
Stonier
Stonis
Stonum
Stoodley
Stookey
Stooks
Stooksbury
Stoop
Stoops
Stoor
Stoos
Stoot
Stoots
Stopa
Stopher
Stopka
Stopp
Stoppel
Stoppenbach
Stoppkotte
Stops
Stopyra
Storage
Storbeck
Storch
Storck
Stordahl
Store
Storer
Stores
Storey
Storie
Storino
Storjohann
Stork
Storks
Storlie
Storm
Storman
Storment
Stormer
Stormes
Stormo
Stormont
Storms
Storniolo
Storozuk
Storr
Storrer
Storrs
Storti
Storto
Storton
Storts
Stortz
Story
Storz
Stoskopf
Stoss
Stotelmyer
Stotesberry
Stotesbury
Stothard
Stothart
Stotko
Stotler
Stotsky
Stott
Stottlar
Stottlemyer
Stotts
Stotz
Stouall
Stouch
Stoud
Stoudamire
Stoudemire
Stoudenmire
Stouder
Stoudmire
Stoudt
Stoudymire
Stouer
Stouffer
Stough
Stoughton
Stours
Stout
Stoutamire
Stoutamyer
Stoute
Stouten
Stoutenburg
Stoutenger
Stoutner
Stoutt
Stoval
Stovall
Stove
Stovel
Stovell
Stover
Stoviak
Stow
Stowbridge
Stowe
Stowell
Stower
Stowers
Stowman
Stoy
Stoyanoff
Stoyanov
Stoyer
Stoyle
Stpaul
Stpeter
Stpeters
Stpierre
Stpierrie
Straathof
Straatmann
Stracener
Strachan
Strachman
Strachn
Strack
Strackbein
Stracke
Stracquatanio
Strada
Strader
Stradford
Stradley
Stradling
Stradtner
Straface
Strahan
Strahin
Strahl
Strahle
Strahm
Straight
Strain
Strait
Straiton
Straka
Strakbein
Straker
Straley
Stram
Strama
Stramel
Stramiello
Stranahan
Stranak
Strand
Strandberg
Strandburg
Strande
Straney
Stranford
Strang
Strange
Stranger
Strangstalien
Strano
Stransky
Strapp
Strasburg
Strasburger
Straseskie
Strassberg
Strassburg
Strassel
Strassell
Strasser
Strassner
Strasters
Stratakos
Strate
Strater
Stratford
Strathman
Strathmann
Strathy
Stratis
Stratman
Straton
Stratos
Stratter
Strattman
Stratton
Stratz
Straub
Straube
Strauch
Strauf
Straugh
Straughan
Straughn
Straughter
Straugter
Strauhal
Straus
Strausbaugh
Strausberg
Strause
Strauser
Strausner
Strauss
Strausser
Strausz
Stravinski
Straw
Strawberry
Strawbridge
Strawder
Strawderman
Strawhorn
Strawn
Straws
Strawser
Strawther
Stray
Strayer
Strayham
Strayhand
Strayhorn
Strazi
Strazisar
Strazza
Strazzullo
Stream
Streams
Streat
Streater
Streb
Strebe
Strebeck
Strebel
Strech
Streck
Strecker
Streczywilk
Stred
Strede
Stredny
Streeby
Streed
Streeper
Street
Streeter
Streetman
Streeton
Streets
Streett
Strefeler
Streff
Strege
Strehl
Strehle
Strehlow
Strei
Streib
Streich
Streicher
Streif
Streifel
Streiff
Streight
Streit
Streitenberge
Streitmatter
Streitnatter
Streitz
Strejan
Strejcek
Strek
Strekas
Strelecki
Streller
Strelow
Strem
Stremcha
Stremel
Stremi
Stremlow
Stremmel
Stremming
Streng
Strenge
Strength
Strenke
Stretch
Stretz
Streu
Streva
Strevel
Strevell
Strevels
Strey
Stribble
Stribley
Stribling
Strick
Stricker
Strickert
Stricklan
Strickland
Stricklen
Strickler
Stricklin
Stricklind
Strickling
Strictland
Strid
Stride
Strider
Stridiron
Strief
Striegel
Strieker
Strieter
Strife
Striffler
Stright
Strike
Striker
Strimback
Strimel
Strimling
Strimple
Strine
String
Stringari
Stringer
Stringfellow
Stringfield
Stringham
Strini
Striplin
Stripling
Strissel
Strite
Stritmater
Strittmater
Strittmatter
Stritzinger
Stritzke
Strizich
Strnad
Strobeck
Strobel
Strobl
Stroble
Strobridge
Strock
Strode
Stroder
Stroebel
Stroede
Stroer
Stroffolino
Strogen
Stroh
Strohbehn
Strohecker
Strohl
Strohm
Strohman
Strohmayer
Strohmeier
Strohmeyer
Strohschein
Stroik
Stroinski
Strojny
Stroker
Strole
Stroll
Strollo
Strom
Stromain
Stroman
Strombeck
Stromberg
Strome
Stromer
Stromme
Stromquist
Stromski
Stromyer
Stronach
Strong
Stroop
Stroope
Stroot
Strop
Strope
Stropes
Stropko
Strople
Stropus
Strose
Strosnider
Stroth
Strother
Strothers
Strothman
Strothmann
Strotman
Strotz
Stroub
Stroud
Strough
Stroup
Stroupe
Strous
Strouse
Strout
Strouth
Strow
Strowbridge
Strowd
Strowder
Strowe
Stroy
Strozewski
Strozier
Strozzi
Strub
Strubbe
Strube
Strubel
Struber
Struble
Struchen
Struck
Struckhoff
Struckman
Struckmann
Strudwick
Struebing
Struggs
Struiksma
Strum
Strumpf
Strunk
Strupp
Struss
Struthers
Strutton
Strutynski
Strutz
Struve
Struyk
Struzik
Struzzi
Strycker
Stryjewski
Stryker
Strysko
Strzalkowski
Strzelczyk
Strzelecki
Strzyzewski
Stsauveur
Stthomas
Stuard
Stuart
Stubbe
Stubbendeck
Stubbert
Stubbins
Stubblefield
Stubbolo
Stubbs
Stubby
Stubenrauch
Stuber
Stubits
Stublaski
Stuble
Stubler
Stubson
Stuchlik
Stuck
Stucke
Stuckel
Stuckemeyer
Stucker
Stuckert
Stuckett
Stuckey
Stucki
Stuckman
Stuckmeyer
Stucky
Stuczynski
Studdard
Studdiford
Studebaker
Student
Studeny
Studer
Studier
Studivant
Studler
Studley
Studmire
Studniarz
Studnicki
Studstill
Studt
Studwell
Study
Studyvance
Studyvin
Studzinski
Stuebe
Stueber
Stueck
Stueckrath
Stuedemann
Stuekerjuerge
Stuemke
Stuenkel
Stuer
Stuermer
Stuesse
Stuessy
Stueve
Stuever
Stuffle
Stufflebeam
Stufflebean
Stuhlsatz
Stuhr
Stukel
Stukenborg
Stukes
Stukowski
Stulce
Stulick
Stull
Stuller
Stults
Stultz
Stum
Stumb
Stumbaugh
Stumbo
Stumer
Stumfoll
Stumm
Stumme
Stump
Stumpe
Stumpf
Stumpff
Stumph
Stumpo
Stumpp
Stunkard
Stupak
Stupar
Stupka
Stupke
Stupp
Sturch
Sturchio
Sturdevant
Sturdivant
Sturdnant
Sturdy
Sturgell
Sturgeon
Sturges
Sturgess
Sturghill
Sturgill
Sturgis
Sturgul
Sturiale
Sturino
Sturk
Sturkey
Sturkie
Sturm
Sturman
Sturmer
Sturms
Sturn
Sturner
Sturrock
Sturrup
Sturtevant
Sturtz
Sturwold
Sturz
Stusse
Stutes
Stutesman
Stuteville
Stutheit
Stutler
Stutsman
Stuttgen
Stutts
Stutz
Stutzman
Stuve
Stuzman
Stvictor
Stvil
Stvrestil
Stwart
Stweart
Styborski
Stych
Styer
Styers
Style
Styler
Styles
Stymiest
Styons
Styron
Stys
Su
Suaava
Sualevai
Suares
Suarez
Suazo
Sub
Subasic
Suben
Suber
Subera
Subert
Subia
Subich
Subido
Subijano
Subler
Sublett
Sublette
Subramanian
Suby
Succar
Succop
Sucgang
Such
Suchan
Suchanek
Sucharski
Sucharzewski
Suchecki
Sucher
Suchla
Suchocki
Suchy
Suckow
Sucre
Sud
Suda
Sudak
Sudan
Sudar
Sudbeck
Sudberry
Sudbrock
Sudbury
Suddarth
Suddath
Sudderth
Suddeth
Suddith
Suddoth
Suddreth
Sudduth
Sudekum
Suder
Suderman
Suders
Sudler
Sudlow
Sudo
Sudol
Sudweeks
Sue
Sueda
Suehs
Suell
Suellentrop
Sueltenfuss
Suen
Suennen
Suentenfuss
Suermann
Suero
Suess
Suet
Sueyoshi
Suffern
Suffield
Suffridge
Suga
Sugabo
Sugahara
Sugai
Sugalski
Suganuma
Sugar
Sugarman
Sugden
Sugerak
Sugerman
Sugg
Suggett
Suggitt
Suggs
Sughroue
Sughrue
Sugiki
Sugimoto
Sugiyama
Suglia
Sugrue
Suh
Suhar
Suhoski
Suhr
Suihkonen
Suing
Suire
Suit
Suite
Suiter
Suitor
Suits
Suitt
Suk
Sukeforth
Sukhram
Sukhu
Sukovaty
Sukovich
Sukup
Sukut
Sul
Sulc
Sulcer
Sule
Sulecki
Suleiman
Sulejmanovski
Sulek
Sulentic
Suleski
Sulfridge
Sulieman
Sulik
Sulikowski
Sulima
Sulin
Sulipizio
Sulit
Sulivan
Sulkowski
Sulla
Sullen
Sullenberger
Sullenger
Sullens
Sulley
Sullinger
Sullins
Sullivan
Sullivant
Sulloway
Sully
Sulouff
Sulser
Sult
Sultaire
Sultan
Sultana
Sultani
Sultemeier
Sulton
Sultzer
Sulyma
Sulzbach
Sulzen
Sulzer
Sulzman
Sum
Suma
Sumabat
Suman
Sumaran
Sumas
Sumatzkuku
Sumaya
Sumbera
Sumbler
Sumbry
Sumera
Sumerall
Sumeriski
Sumerix
Sumerlin
Sumers
Sumey
Sumi
Sumida
Suminski
Sumlar
Sumler
Sumlin
Summa
Summar
Summarell
Summars
Summer
Summerall
Summerfield
Summerford
Summerhays
Summerhill
Summerill
Summerlin
Summerlot
Summerour
Summers
Summerset
Summerson
Summerton
Summerville
Summey
Summitt
Summons
Summy
Sumner
Sumners
Sumney
Sump
Sumpter
Sumption
Sumrall
Sumrell
Sumrow
Sumruld
Sumsion
Sumstad
Sumter
Sun
Sund
Sundahl
Sunday
Sundberg
Sundblad
Sundborg
Sundby
Sunde
Sundeen
Sundell
Sunder
Sunderland
Sunderlin
Sunderman
Sundermeyer
Sundet
Sundholm
Sundin
Sundling
Sundman
Sundquist
Sundseth
Sundstrom
Sundt
Suneson
Sunford
Sung
Sunga
Sunier
Suniga
Sunkel
Sunn
Sunniga
Suns
Sunseri
Sunshine
Sunstrom
Sunyich
Suoboda
Suomela
Suominen
Suon
Suozzi
Suozzo
Super
Supernault
Supernaw
Supino
Supnet
Suppa
Supple
Supplee
Supplice
Suprenant
Supry
Sur
Sura
Surace
Suran
Surano
Surbaugh
Surbella
Surber
Surdam
Suren
Sures
Surette
Surface
Surgeon
Surgoine
Surguy
Suri
Suriano
Suriel
Surina
Surita
Surkamer
Surles
Surls
Surma
Surman
Surminec
Suro
Surowka
Surprenant
Surpris
Surprise
Surra
Surran
Surratt
Surrell
Surrency
Surrett
Surrette
Surrey
Surridge
Survant
Survis
Surwillo
Suryan
Suryanarayana
Susa
Susan
Susana
Susanin
Susany
Susi
Susich
Suskay
Suski
Suskin
Susko
Susla
Susman
Susmilch
Susoev
Susong
Susor
Suss
Sussex
Sussman
Susswein
Sustaire
Sustaita
Sustar
Suszynski
Sutch
Sutcliff
Sutcliffe
Suter
Sutera
Sutfin
Suthar
Suther
Sutherburg
Sutherland
Sutherlin
Suthers
Suthoff
Sutic
Sutkus
Sutler
Sutley
Sutliff
Suto
Sutor
Sutphen
Sutphin
Sutt
Suttee
Suttell
Sutten
Sutter
Sutterfield
Suttie
Suttin
Suttle
Suttles
Sutton
Sutulovich
Sutyak
Suvada
Suwannakintho
Suyama
Suydam
Suydan
Suzuki
Svancara
Svare
Svatek
Svatos
Svay
Svec
Svedin
Svedine
Sveen
Svehla
Svendsen
Svenningsen
Svennungsen
Svensen
Svenson
Sverchek
Svetlak
Svetlik
Svetz
Sveum
Svinth
Svob
Svoboda
Svobodny
Svrcek
Swab
Swabb
Swabe
Swaby
Swackhammer
Swade
Swader
Swadling
Swafford
Swager
Swagerty
Swaggart
Swagger
Swaggert
Swaggerty
Swailes
Swails
Swaim
Swain
Swaine
Swainey
Swainston
Swaisgood
Swait
Swales
Swalley
Swallow
Swallows
Swam
Swamm
Swamp
Swamy
Swan
Swanagan
Swanay
Swanberg
Swancey
Swancutt
Swanda
Swander
Swaner
Swaney
Swanger
Swango
Swanhart
Swanick
Swanigan
Swank
Swanke
Swann
Swanner
Swansbrough
Swansen
Swanson
Swanston
Swanstrom
Swant
Swantak
Swanteck
Swantek
Swantko
Swantner
Swanton
Swanzy
Swapp
Swarat
Swarb
Sward
Swarey
Swaringen
Swarm
Swarn
Swarner
Swarr
Swart
Swarthout
Swartley
Swartout
Swarts
Swartwood
Swartwout
Swartz
Swartzbaugh
Swartzbeck
Swartzel
Swartzell
Swartzendrube
Swartzentrube
Swartzfager
Swartzlander
Swartzman
Swartzmiller
Swartzwelder
Swary
Swasey
Swatek
Swatloski
Swatman
Swatski
Swatsworth
Swatt
Swatzell
Swauger
Swavely
Swayne
Swaynos
Swayze
Swayzer
Sweadner
Sweaney
Sweany
Swearegene
Swearengen
Swearengin
Swearingen
Swearinger
Swearingin
Swearngen
Swearngin
Sweat
Sweatfield
Sweatman
Sweatmon
Sweatt
Sweazey
Sweazy
Swecker
Swed
Sweda
Swedberg
Swede
Swedeen
Swedenburg
Swedlund
Swee
Sweed
Sweeden
Sweeley
Sweely
Sweem
Sween
Sweene
Sweeney
Sweeny
Sweep
Sweere
Sweers
Sweesy
Sweet
Sweeten
Sweetin
Sweeting
Sweetland
Sweetman
Sweeton
Sweets
Sweetser
Sweetwood
Sweezer
Sweezey
Sweezy
Swefford
Sweger
Swehla
Sweigard
Sweigart
Sweigert
Sweis
Sweitzer
Sweley
Swelgart
Swell
Swelt
Swem
Swenceski
Swendsen
Sweney
Swenk
Swenor
Swensen
Swenson
Swensson
Swenton
Swentzel
Swepson
Swerdloff
Swerdlow
Swestka
Swetland
Swetnam
Swets
Swett
Swezey
Swiat
Swiatek
Swiatkowski
Swicegood
Swick
Swickard
Swickheimer
Swicord
Swida
Swider
Swiderski
Swieca
Swiech
Swierczek
Swierczynski
Swierenga
Swierk
Swietoniowski
Swift
Swigart
Swiger
Swigert
Swiggett
Swiggum
Swihart
Swiler
Swille
Swiller
Swilley
Swilling
Swim
Swimm
Swimmer
Swims
Swindall
Swindell
Swinderman
Swindle
Swindler
Swindoll
Swinea
Swineford
Swinehart
Swinerton
Swiney
Swinford
Swing
Swingen
Swinger
Swingle
Swingler
Swink
Swinney
Swinny
Swinson
Swint
Swinton
Swirczek
Swire
Swires
Swirsky
Swisher
Swiss
Swisshelm
Swist
Swistak
Switalski
Switcher
Swithenbank
Switzer
Swoager
Swoap
Swoboda
Swoffer
Swofford
Swogger
Swolley
Swonger
Swonke
Swoope
Swoopes
Swope
Swopes
Swopshire
Swor
Sword
Swords
Swoyer
Swyers
Swygert
Swymer
Sy
Syal
Syas
Sybert
Sybounheuan
Syck
Syddall
Sydner
Sydnes
Sydney
Sydnor
Sydow
Syed
Syer
Syers
Sykes
Sykora
Syktich
Syler
Sylla
Sylney
Sylva
Sylvain
Sylvan
Sylve
Sylver
Sylvest
Sylvester
Sylvestre
Sylvia
Sylvian
Sylvis
Symanski
Symeon
Symes
Symkowick
Symmes
Symmonds
Symon
Symonds
Symons
Symore
Sympson
Synakowski
Synan
Synder
Syndergaard
Syner
Synnott
Synovic
Synowiec
Syon
Syphard
Sypher
Syphers
Sypniewski
Sypolt
Sypult
Syracuse
Syrek
Syrett
Syria
Syring
Syrop
Syrrakos
Syrstad
Sysak
Sysyn
Syta
Sytsma
Syversen
Syverson
Syvertsen
Syzdek
Szabat
Szablewski
Szabo
Szachewicz
Szady
Szaflarski
Szafran
Szafraniec
Szafranski
Szafryk
Szal
Szala
Szalai
Szalankiewicz
Szalay
Szanto
Szarek
Szatkowski
Szczeblewski
Szczepanek
Szczepaniak
Szczepanik
Szczepanski
Szczepkowski
Szczesniak
Szczesny
Szczurek
Szczygiel
Sze
Szekely
Szekula
Szenasi
Szerbin
Szeredy
Szerlong
Szermer
Szerszen
Szesterniak
Szeto
Szewc
Szewczak
Szewczyk
Szigethy
Szilagyi
Szitar
Szklarski
Szlosek
Szmalc
Szmidt
Sznejkowski
Szoc
Szocki
Szoka
Szoke
Szollosi
Szopinski
Szostak
Szot
Szpak
Szuba
Szubinski
Szuch
Szufat
Szulimowski
Szumiesz
Szumigala
Szumilas
Szumny
Szumski
Szuszkiewicz
Szwaja
Szwarc
Szwed
Szweda
Szwede
Szwejbka
Szychowski
Szydlowski
Szymanowski
Szymanski
Szymansky
Szymczak
Szymczyk
Szymkowski
Szymonik
Szymula
Szynkowicz
Szypowski
Szysh
Szyszka
Ta
Taaffe
Taake
Taal
Taback
Tabag
Tabak
Tabar
Tabares
Tabarez
Tabatabai
Tabatt
Tabb
Tabbaa
Tabbert
Tabeling
Taber
Taberski
Tabet
Tabian
Tabicas
Tabin
Tabion
Tabios
Tabisola
Tabisula
Tablada
Tablang
Tabler
Tables
Taboada
Tabolt
Tabon
Tabone
Tabor
Tabora
Taborda
Taborn
Tabron
Tabuena
Tacadina
Tacason
Tacata
Taccariello
Taccetta
Taccone
Tacconi
Tacderan
Tacderen
Tacdol
Tacey
Tachauer
Tacheny
Tack
Tacke
Tacker
Tackes
Tacket
Tackett
Tackette
Tackitt
Tacneau
Tacopino
Tacy
Tada
Tadd
Taddei
Taddeo
Taddio
Taddonio
Tade
Tademy
Tadena
Tadeo
Tadesse
Tadgerson
Tadiello
Tadlock
Tadman
Tadt
Tadych
Taecker
Taegel
Taetzsch
Tafel
Tafelski
Taff
Taffe
Taffer
Tafiti
Taflinger
Tafolla
Tafoya
Tafreshi
Taft
Tafuri
Tag
Tagaban
Tagaca
Tagala
Tagaloe
Tagalog
Tagami
Tagata
Tagg
Taggart
Tagge
Taggert
Taghon
Taglauer
Tagle
Taglialatela
Tagliarini
Tagliavia
Tagliente
Taglieri
Tags
Taguchi
Tague
Tagupa
Taha
Taheri
Tahir
Tahon
Tahu
Tai
Taibi
Taibl
Tail
Taillefer
Taillon
Tailor
Taing
Tainter
Taintor
Taira
Tait
Taitague
Taite
Taitt
Taiwo
Taj
Tajima
Tajiri
Tajudeen
Tak
Takach
Takacs
Takagi
Takahashi
Takai
Takaki
Takala
Takaoka
Takara
Takashima
Takata
Takayama
Takeda
Takehara
Takemoto
Takemura
Takenaka
Taker
Takes
Takeshita
Taketa
Takeuchi
Taki
Takiguchi
Tako
Talaga
Talahytewa
Talamante
Talamantes
Talamantez
Talamas
Talamentez
Talamo
Talarico
Talaro
Talas
Talaska
Talat
Talavera
Talayumptewa
Talbert
Talbot
Talboti
Talbott
Talburt
Talcott
Talent
Talentino
Talerico
Talford
Talhelm
Taliaferro
Talib
Talicska
Taliferro
Taliman
Taliulu
Talk
Talkington
Tall
Tallacksen
Tallada
Talladino
Tallant
Tallarico
Tallas
Tallent
Tallerico
Talleut
Talley
Tallie
Tallis
Tallmadge
Tallman
Tallon
Talluto
Tally
Talmadge
Talmage
Talman
Talone
Talor
Talsky
Talsma
Talton
Talty
Talvy
Talyor
Tam
Tamai
Tamanaha
Tamargo
Tamaro
Tamas
Tamashiro
Tamayo
Tambasco
Tambe
Tamblyn
Tamborlane
Tambunga
Tamburello
Tamburino
Tamburo
Tamburrelli
Tamburri
Tamburrino
Tamburro
Tamer
Tameron
Tames
Tamez
Tami
Tamimi
Tamiya
Tamkin
Tamlin
Tamm
Tammaro
Tammen
Tamminen
Tammo
Tamondong
Tamplin
Tamporello
Tams
Tamulis
Tamura
Tan
Tanabe
Tanaka
Tanberg
Tancer
Tancredi
Tande
Tandetzke
Tandon
Tandus
Tandy
Taneja
Tanen
Tanenbaum
Tanequodle
Taney
Tang
Tangabekyan
Tangari
Tangaro
Tangeman
Tangen
Tangerman
Tangert
Tangney
Tango
Tangredi
Tangren
Tangri
Tanguay
Tanguma
Tanh
Tani
Tanigawa
Taniguchi
Tanikella
Tanimoto
Tanious
Tanis
Tank
Tankard
Tanke
Tanker
Tankersley
Tankersly
Tankesly
Tanks
Tanksley
Tankson
Tankxley
Tann
Tanna
Tannahill
Tannazzo
Tannehill
Tannen
Tannenbaum
Tanner
Tannery
Tanney
Tanniehill
Tannous
Tanon
Tanori
Tanoue
Tanous
Tanouye
Tansey
Tansil
Tanski
Tansley
Tant
Tantillo
Tanton
Tantum
Tanweer
Tanzer
Tanzi
Tanzman
Tanzosch
Tao
Taomoto
Taormina
Tapaha
Tapales
Tapanes
Tapaoan
Tapat
Tape
Taper
Taphous
Tapia
Tapian
Tapija
Tapio
Tapley
Taplin
Tapp
Tappa
Tappan
Tappe
Tappeiner
Tappen
Tappendorf
Tapper
Tappin
Tappis
Taps
Tapscott
Taque
Tara
Tarabokija
Taraborelli
Tarallo
Taran
Tarangelo
Tarango
Tarantino
Taranto
Taras
Taraschke
Tarascio
Tarasuik
Taray
Tarazon
Tarbell
Tarbert
Tarbet
Tarbor
Tarboro
Tarbox
Tarbutton
Tardie
Tardif
Tardiff
Tardio
Tardugno
Tarduno
Tardy
Tarella
Targett
Tarin
Tariq
Tarka
Tarkenton
Tarkey
Tarkington
Tarkowski
Tarleton
Tarley
Tarling
Tarlow
Tarlton
Tarman
Tarmey
Tarner
Tarnoff
Tarnowski
Tarone
Tarpey
Tarpley
Tarpy
Tarquinio
Tarr
Tarran
Tarrance
Tarrant
Tarrants
Tarras
Tarrats
Tarrence
Tarrenis
Tarricone
Tarrien
Tarring
Tarris
Tarro
Tarry
Tarshis
Tarsis
Tarski
Tart
Tartaglia
Tartaglino
Tartaglione
Tartamella
Tartar
Tarte
Tarter
Tartsah
Tartt
Taruc
Taruer
Tarufelli
Tarver
Tarvin
Tarvis
Tarwater
Tarzia
Tasby
Tasch
Taschereau
Taschler
Taschner
Tash
Tashima
Tashiro
Tashjian
Tashman
Tasker
Taskey
Tasler
Tasma
Tassa
Tasse
Tassey
Tassie
Tassin
Tassinari
Tasso
Tasson
Tassone
Tassoni
Tastet
Tasto
Tat
Tata
Tatar
Tataris
Tate
Tatel
Tatem
Tates
Tatevosian
Tatge
Tatham
Tatis
Tatlock
Tatman
Tatnall
Tatom
Taton
Tator
Tatro
Tatsak
Tatsapaugh
Tatsch
Tatsuhara
Tatsuno
Tatsuta
Tatters
Tattersall
Tattershall
Tatton
Tattrie
Tatu
Tatum
Taualii
Tauares
Tauarez
Taub
Taube
Tauber
Taubert
Taublee
Taubman
Taucher
Tauer
Taul
Taula
Taulbee
Taulman
Taunton
Tauras
Taurino
Taus
Tausch
Tauscher
Taussig
Tauteoli
Tautolo
Tautuiaki
Tauzin
Tavakoli
Tavana
Tavano
Tavares
Tavarez
Tavaris
Tave
Tavella
Tavenner
Tavera
Taverab
Taveras
Taverna
Taverner
Tavernia
Tavernier
Taves
Tavira
Tavis
Tavolacci
Tavolario
Tavolieri
Tavorn
Tawil
Tawney
Tawwab
Tawwater
Tay
Tayag
Tayan
Taybron
Taydus
Taylan
Taylar
Tayler
Tayloe
Taylor
Taymon
Tayo
Tayor
Tays
Tayse
Tazelaar
Tazewell
Tazzara
Tchakian
Te
Tea
Teabo
Teach
Teachey
Teachman
Teachout
Teaff
Teaford
Teagarden
Teager
Teagle
Teague
Teagues
Teahan
Teakell
Teal
Tealer
Teall
Teamer
Teano
Teaque
Tear
Teare
Teas
Teasdale
Tease
Teasley
Teaster
Teat
Teater
Teator
Teats
Tebar
Tebay
Tebbe
Tebbetts
Tebbs
Tebeau
Tebo
Tebow
Tecchio
Techaira
Techau
Tecklenburg
Tecson
Tecuanhuey
Tedder
Teddick
Teddy
Teder
Tederous
Tedeschi
Tedesco
Tedesko
Tedford
Tedrick
Tedrow
Tee
Teece
Teed
Teegarden
Teehan
Teehee
Teekasingh
Teel
Teele
Teem
Teemer
Teems
Teepe
Teeple
Teeples
Teer
Tees
Teesdale
Teet
Teeter
Teeters
Teets
Teetz
Tefera
Tefertiller
Teffeteller
Tefft
Tegan
Tegarden
Tegeler
Tegenkamp
Tegethoff
Tegner
Tegtmeier
Tegtmeyer
Tehan
Tehney
Tehrani
Tei
Teich
Teicher
Teichert
Teichman
Teichmann
Teichmiller
Teichrow
Teig
Teigen
Teisberg
Teissedre
Teitel
Teitelbaum
Teitenberg
Teitsort
Teitsworth
Teixeira
Teixeria
Tejada
Tejadilla
Tejeda
Tejedor
Tejeiro
Tejera
Tekautz
Tekell
Tekippe
Teklu
Tekulve
Tela
Telander
Telch
Telchik
Telecky
Telega
Telep
Teles
Telesco
Telfair
Telfer
Telford
Telgen
Telkamp
Tell
Tellado
Telle
Tellefsen
Tellefson
Teller
Telleria
Tellers
Telles
Tellez
Tellier
Tellinghuisen
Tellio
Tellis
Tellman
Tello
Telly
Telman
Telschow
Teltschik
Teman
Temblador
Temby
Temkin
Temme
Temoney
Temores
Temoshenka
Temp
Tempe
Tempel
Tempelton
Tempest
Tempesta
Temple
Templeman
Templer
Temples
Templet
Templeton
Templin
Ten
Tena
Tenaglia
Tenamore
Tenant
Tenario
Tenbrink
Tenbusch
Tencer
Tench
Tencza
Tenda
Tendick
Tenebruso
Tenen
Tenenbaum
Tener
Tenerovich
Tenerowicz
Tenery
Teneyck
Teng
Tengan
Tengben
Tengwall
Tenhaeff
Tenharmsel
Tenhoff
Tenholder
Tenley
Tenn
Tennant
Tennent
Tenner
Tenneson
Tennessee
Tennett
Tenney
Tennies
Tennill
Tennille
Tennis
Tennison
Tennon
Tenny
Tennyson
Teno
Tenofsky
Tenor
Tenore
Tenorio
Tenpas
Tenpenny
Tensley
Tent
Tention
Tentler
Tenuta
Tenzer
Teo
Teodoro
Teoh
Tep
Tepe
Teper
Tepezano
Tepfer
Tepler
Tepley
Teplica
Tepp
Tepper
Tepperberg
Teppo
Teque
Terada
Teramoto
Teran
Terando
Teranishi
Terault
Teravainen
Terazes
Terboss
Terbush
Tercero
Terell
Terepka
Teresa
Teresi
Tereska
Terhaar
Terhar
Terhark
Terheggen
Terherst
Terhorst
Terhune
Teri
Terinoni
Terkelsen
Terlecki
Terlizzi
Terman
Termeer
Termilus
Termini
Ternasky
Ternes
Terney
Ternullo
Tero
Teroganesyan
Terp
Terpening
Terpstra
Terr
Terra
Terracciano
Terrace
Terracina
Terrall
Terrance
Terrano
Terranova
Terrasas
Terrasi
Terrazas
Terre
Terrebonne
Terrel
Terrell
Terrence
Terrero
Terres
Terrett
Terrey
Terrezza
Terri
Terrian
Terrible
Terrien
Terrill
Terrio
Terris
Territo
Terron
Terrone
Terrones
Terronez
Terry
Tersigni
Terstage
Tersteeg
Tertinek
Teruel
Tervo
Tervort
Terwey
Terwillegar
Terwilliger
Terzian
Terzo
Tes
Tesar
Tesauro
Tesch
Teschler
Teschner
Tesh
Teska
Teske
Teskey
Tesler
Teslow
Tesmar
Tesmer
Tesnow
Tesoriero
Tesoro
Tesreau
Tess
Tessendorf
Tesseneer
Tesseyman
Tessier
Tessitore
Tessler
Tessman
Tessmer
Tessner
Test
Testa
Testani
Testen
Tester
Testerman
Testman
Testolin
Teston
Teteak
Teter
Teters
Teti
Tetley
Tetlow
Teto
Tetrault
Tetreau
Tetreault
Tetrick
Tetro
Tetteh
Tetter
Tetterton
Tetu
Tetz
Tetzlaff
Tetzloff
Teufel
Teuscher
Teuteberg
Tevada
Tevebaugh
Teverbaugh
Teves
Tevis
Tevlin
Tew
Tewa
Tewani
Tewari
Tewell
Tewes
Tewksbury
Tewmey
Tewolde
Tews
Texada
Texeira
Texidor
Texiera
Texter
Textor
Teyler
Tezak
Tezeno
Thach
Thacher
Thackaberry
Thacker
Thackeray
Thackery
Thackrey
Thackston
Thackxton
Thaden
Thadison
Thady
Thaemert
Thagard
Thaggard
Thai
Thain
Thake
Thaker
Thakkar
Thakur
Thal
Thalacker
Thaler
Thalheimer
Thall
Thaller
Thalls
Thalman
Thalmann
Tham
Thaman
Thamann
Thames
Thammavong
Thammavongsa
Thammorongsa
Thamphia
Than
Thanas
Thanasouk
Thane
Thanem
Thang
Thangavelu
Thaniel
Thanos
Thanpaeng
Thansamai
Thao
Tharaldson
Tharnish
Tharp
Tharpe
Tharrington
Thatch
Thatcher
Thate
Thau
Thaut
Thavichith
Thaxton
Thay
Thayer
Thayn
Thayne
Theaker
Theall
Theam
Theard
Theaux
Thebeau
Theberge
Thebo
Thede
Theden
Thedford
Thee
Theel
Theeman
Theesfeld
Theil
Theilen
Theiler
Theiling
Theim
Theimer
Thein
Theinert
Theis
Theisen
Theiss
Thelemaque
Thelen
Thelin
Thell
Thelmon
Them
Themot
Then
Thenhaus
Theo
Theobald
Theodoratos
Theodore
Theodoropoulo
Theodorov
Theophilus
Theos
Thepbanthao
Theresa
Theriault
Therien
Theriot
Thero
Theroux
Therrell
Therres
Therriault
Therrien
Therurer
Thesing
Thessing
Thetford
Theuenin
Theule
Theuner
Theunissen
Theurer
Theuret
Theus
Thevenin
Thew
Thews
Thi
Thiara
Thibadeau
Thibaudeau
Thibault
Thibaut
Thibeau
Thibeault
Thibeaux
Thibedeau
Thibert
Thibideau
Thibodaux
Thibodeau
Thibodeaux
Thiboutot
Thicke
Thidphy
Thie
Thiebeault
Thiede
Thieklin
Thiel
Thielbar
Thiele
Thielemann
Thielemier
Thielen
Thielges
Thielman
Thiem
Thieman
Thiemann
Thieme
Thiengtham
Thier
Thierauf
Thierman
Thierry
Thiery
Thies
Thiesfeld
Thiesse
Thiessen
Thigpen
Thigpin
Thilges
Thilking
Thill
Thillet
Thilmony
Thim
Thimmes
Thimmesch
Thingvold
Thiry
Thissen
Thistle
Thistlethwait
Thivener
Thivierge
Thixton
Thoams
Thobbs
Thoben
Thoburn
Thoby
Thode
Thody
Thoe
Thoele
Thoen
Thoene
Thoennes
Thoeny
Thole
Tholen
Thom
Thoma
Thomae
Thoman
Thomann
Thomas
Thomases
Thomason
Thomassen
Thomasson
Thomaston
Thombs
Thome
Thomeczek
Thomen
Thomer
Thomes
Thometz
Thomison
Thomley
Thomlinson
Thomlison
Thommarson
Thompkins
Thompon
Thompsom
Thompson
Thoms
Thomsen
Thomson
Thomspon
Thomure
Thon
Thone
Thonen
Thong
Thongchanh
Thongdy
Thonney
Thor
Thorade
Thoran
Thorburn
Thorell
Thoren
Thoresen
Thoreson
Thorin
Thorington
Thorley
Thormaehlen
Thormahlen
Thorman
Thormer
Thormina
Thorn
Thornberg
Thornberry
Thornborough
Thornborrow
Thornbrough
Thornbrugh
Thornburg
Thornburgh
Thornbury
Thorndike
Thorndyke
Thorne
Thornell
Thorner
Thornes
Thorngren
Thornhill
Thornley
Thornock
Thornquist
Thorns
Thornsberry
Thornsbury
Thornton
Thornwell
Thoroughgood
Thoroughman
Thorp
Thorpe
Thorsen
Thorsness
Thorson
Thorstad
Thorsted
Thorsten
Thorstenson
Thorton
Thouvenel
Thraen
Thrailkill
Thrall
Thramer
Thrams
Thran
Thrapp
Thrash
Thrasher
Threadgill
Threat
Threats
Threatt
Threet
Threets
Threlfall
Threlkeld
Thresher
Thress
Thrift
Thrill
Thro
Throckmorton
Throgmorton
Throndson
Throne
Throneberry
Throneburg
Thronson
Thronton
Throop
Thrope
Throssell
Thrower
Thruman
Thrun
Thrune
Thrush
Thruston
Thruthley
Thu
Thuesen
Thul
Thulin
Thull
Thum
Thuma
Thuman
Thumm
Thunberg
Thundercloud
Thune
Thuney
Thuotte
Thur
Thurau
Thurber
Thurby
Thurgood
Thuringer
Thurlby
Thurlow
Thurm
Thurman
Thurmer
Thurmon
Thurmond
Thurn
Thurner
Thurness
Thurrell
Thursby
Thurston
Thurstonson
Thurton
Thury
Thuss
Thwaites
Thweatt
Thy
Thyberg
Thyfault
Thygerson
Thyne
Thyng
Tian
Tiangco
Tiano
Tibbals
Tibbert
Tibbets
Tibbetts
Tibbit
Tibbits
Tibbitts
Tibbles
Tibbs
Tiberi
Tiberio
Tiblier
Tibolla
Tiboni
Tibor
Tiburcio
Tibwell
Tica
Ticas
Tice
Ticer
Tichacek
Tichenor
Tichi
Tichnell
Tichy
Tick
Tickle
Tickner
Ticknor
Tidball
Tidd
Tidey
Tidmore
Tidrick
Tidrington
Tidwell
Tiede
Tiedeman
Tiedemann
Tiedt
Tiefenauer
Tiefenbrun
Tieger
Tiegs
Tiehen
Tieken
Tielking
Tiell
Tieman
Tiemann
Tiemens
Tiemeyer
Tien
Tienda
Tieng
Tienken
Tier
Tierce
Tierman
Tiernan
Tierney
Tierno
Tieszen
Tiet
Tietge
Tietje
Tietjen
Tietjens
Tietz
Tietze
Tieu
Tiff
Tiffany
Tiffee
Tiffin
Tiffner
Tifft
Tift
Tigano
Tigar
Tiger
Tigerino
Tigert
Tigg
Tigges
Tiggs
Tighe
Tigner
Tigney
Tignor
Tigue
Tijerina
Tijerino
Tijernia
Tijing
Tikkanen
Tilbury
Tilden
Tiley
Tilford
Tilghman
Tilgner
Till
Tillberg
Tillberry
Tille
Tillema
Tilleman
Tiller
Tillery
Tillett
Tilley
Tillie
Tillinghast
Tillis
Tillison
Tillman
Tillmon
Tillotson
Tillou
Tillson
Tilly
Tilman
Tilmon
Tilotta
Tilow
Tilson
Tilt
Tilton
Tilus
Tilzer
Tim
Timar
Timas
Timber
Timberlake
Timberman
Timbers
Timblin
Timbrell
Timbrook
Timbs
Timchak
Timchula
Timenez
Times
Timi
Timinsky
Timko
Timlin
Timm
Timme
Timmel
Timmer
Timmerberg
Timmerman
Timmermann
Timmermans
Timmers
Timmins
Timmis
Timmons
Timmreck
Timms
Timon
Timone
Timonere
Timons
Timoteo
Timothe
Timothy
Timpe
Timper
Timperman
Timpone
Timpson
Tims
Timson
Timus
Tin
Tina
Tinajero
Tinch
Tincher
Tindal
Tindall
Tindel
Tindell
Tinder
Tindle
Tindol
Tine
Tinelli
Tineo
Tiner
Tines
Ting
Tingen
Tinger
Tingey
Tingle
Tingler
Tingley
Tingstrom
Tingwald
Tinin
Tinius
Tinker
Tinkey
Tinkham
Tinkle
Tinklenberg
Tinkler
Tinley
Tinlin
Tinn
Tinnea
Tinneberg
Tinnel
Tinnell
Tinner
Tinnerello
Tinnes
Tinney
Tinnin
Tinnon
Tino
Tinoco
Tinsley
Tinsman
Tinson
Tinstman
Tintinger
Tintle
Tinucci
Tio
Tiogangco
Tiotuico
Tipka
Tipler
Tipold
Tippen
Tippens
Tippery
Tippet
Tippets
Tippett
Tippetts
Tippey
Tippie
Tippin
Tipping
Tippins
Tippit
Tipple
Tipps
Tippy
Tipre
Tipsword
Tipton
Tirabassi
Tirado
Tircuit
Tirey
Tirino
Tirk
Tiro
Tirona
Tirone
Tirpak
Tirrell
Tirri
Tiry
Tisa
Tisby
Tiscareno
Tisch
Tischer
Tischler
Tischner
Tisdal
Tisdale
Tisdel
Tisdell
Tise
Tish
Tisher
Tishler
Tisi
Tisinger
Tiso
Tison
Tisor
Tissot
Tisue
Titch
Titchener
Titcomb
Tith
Titler
Titlow
Titman
Titmus
Tito
Titone
Titsworth
Titterington
Titterness
Tittl
Tittle
Titus
Titze
Titzer
Tiu
Tivar
Tivis
Tiwald
Tix
Tixier
Tiznado
Tizon
Tjaden
Tjandra
Tjarks
Tjelmeland
Tjepkema
Tkach
Tkacik
Tkacz
Tlamka
Tlatelpa
Tlatenchi
Tllo
Tlucek
Tlumacki
To
Toa
Toadvine
Toal
Toala
Toalson
Toan
Toaston
Tobacco
Toback
Toban
Tobar
Tobe
Tobeck
Tober
Tobert
Tobery
Tobey
Tobia
Tobias
Tobiason
Tobiassen
Tobiasson
Tobiasz
Tobin
Tobler
Tobola
Tobolski
Tobon
Toborg
Tobosa
Toboz
Toby
Toca
Tocchio
Tocci
Tocco
Toce
Tocher
Tochterman
Tock
Tockey
Toczek
Tod
Toda
Todahl
Todaro
Todd
Toddy
Todeschi
Todesco
Todhunter
Todisco
Todman
Todor
Todora
Todoroff
Todorovich
Todt
Tody
Toedebusch
Toefield
Toelke
Toelkes
Toelle
Toeller
Toenges
Toenjes
Toepel
Toepfer
Toepke
Toepperwein
Toevs
Toews
Tofanelli
Tofani
Tofflemire
Toffton
Tofil
Tofolla
Toft
Tofte
Togashi
Tognazzini
Tognetti
Togni
Toguchi
Toh
Tohen
Toher
Tohill
Tohonnie
Tointon
Tojo
Tok
Tokar
Tokarski
Tokarz
Tokay
Toki
Tokich
Tokihiro
Tokita
Tokkesdal
Tokley
Tokunaga
Tokuoka
Tola
Tolan
Toland
Tolar
Tolayo
Tolbent
Tolbert
Tolchin
Tolden
Toldness
Tole
Toledano
Toledo
Tolefree
Tolen
Tolentino
Toler
Toles
Toleston
Tolfree
Tolhurst
Tolin
Toline
Toliongco
Toliver
Toll
Tolle
Tollefsen
Tollefson
Tollefsrud
Toller
Tollerson
Tollerud
Tolles
Tolleson
Tollett
Tolley
Tollin
Tollinchi
Tollison
Tolliver
Tollman
Tollner
Tolly
Tolman
Tolmich
Tolmie
Tolomeo
Tolontino
Tolosa
Tolosky
Tolson
Tolston
Tolve
Tolzmann
Tom
Toma
Tomaino
Tomala
Toman
Tomanek
Tomaro
Tomas
Tomasek
Tomaselli
Tomasello
Tomasetti
Tomash
Tomasi
Tomasic
Tomasini
Tomasino
Tomaski
Tomasko
Tomassi
Tomasso
Tomasson
Tomasulo
Tomaszewski
Tomaszycki
Tomb
Tomberlin
Tombleson
Tomblin
Tomblinson
Tombrello
Tombs
Tomczak
Tome
Tomehak
Tomei
Tomek
Tomeldan
Tomer
Tomerlin
Tomes
Tomey
Tomich
Tomichek
Tomidy
Tomilson
Tomisin
Tomita
Tomjack
Tomka
Tomkiewicz
Tomkins
Tomko
Tomkowicz
Tomkus
Tomlin
Tomlinson
Tomlison
Tommasino
Tomme
Tommie
Tommolino
Tomopoulos
Tomory
Tompkin
Tompkins
Tompsett
Tompson
Toms
Tomsche
Tomshack
Tomsic
Tomsich
Tomsick
Tomski
Tomson
Tomspon
Ton
Tonai
Tonas
Tonche
Toncrey
Tonder
Tondre
Tondreau
Tone
Tonelli
Tonelson
Toner
Tones
Tonetti
Toney
Tong
Tongate
Tonge
Tongren
Tongue
Toni
Toniatti
Tonic
Tonini
Tonkin
Tonks
Tonn
Tonnar
Tonne
Tonner
Tonnesen
Tonneson
Tonnessen
Tonozzi
Tonrey
Tonsall
Tonschock
Tonsil
Tontarski
Tonti
Tony
Tonzi
Too
Toodle
Toof
Toohey
Tooke
Tooker
Tookes
Tookmanian
Tooks
Toolan
Toole
Tooles
Tooley
Tools
Toolsiram
Toolson
Tooman
Toombs
Toomer
Toomes
Toomey
Tooms
Toomsen
Toon
Toone
Toop
Toor
Toot
Toothacre
Toothaker
Toothill
Toothman
Tootle
Tooze
Top
Topacio
Topal
Topalian
Tope
Topel
Toper
Topete
Topez
Topham
Topi
Topia
Topick
Topinka
Topliffe
Toplin
Topliss
Toplistky
Toplk
Topness
Topoian
Topolansky
Topolewski
Topolinski
Topolosky
Topolski
Topor
Toporek
Topp
Toppa
Toppah
Toppen
Topper
Toppi
Toppin
Topping
Toppings
Toppins
Topps
Toquinto
Torain
Toran
Torbeck
Torbert
Torbett
Torbit
Torborg
Torbus
Torchia
Torchio
Torda
Tordsen
Torell
Torelli
Torello
Toren
Tores
Torey
Torez
Torgersen
Torgerson
Torgeson
Torgrimson
Torguson
Torian
Toribio
Toriello
Torigian
Torina
Torino
Torivio
Tork
Torkelson
Torkildsen
Torma
Tormey
Torn
Tornabene
Tornatore
Torner
Tornes
Tornese
Torngren
Tornincasa
Torno
Tornow
Tornquist
Toro
Torok
Toromanides
Torongeau
Torp
Torpey
Torra
Torrado
Torrain
Torralba
Torralva
Torrance
Torrano
Torre
Torreblanca
Torrecillas
Torred
Torregrosa
Torregrossa
Torrell
Torrella
Torrence
Torrens
Torrent
Torreon
Torres
Torreson
Torress
Torrey
Torrez
Torri
Torrico
Torrie
Torrijos
Torrillo
Torrion
Torris
Torrisi
Torros
Torruellas
Torry
Torset
Torsiello
Torstrick
Tortelli
Torti
Tortolano
Tortora
Tortorella
Tortorelli
Tortorice
Tortorici
Tortoriello
Tortu
Toruno
Tory
Tosado
Toscani
Toscano
Tosch
Tosches
Tosco
Tosh
Tosi
Tosic
Toso
Tossie
Tosta
Tostado
Tostanoski
Toste
Tosten
Tosti
Tosto
Tota
Totaro
Tote
Toten
Toth
Totherow
Toti
Totin
Toting
Totino
Totman
Toto
Totosz
Tototzintle
Tott
Totten
Totter
Tottingham
Totty
Totzke
Touar
Touart
Touby
Touch
Touchard
Touchet
Touchette
Touchstone
Touchton
Toudle
Tougas
Touhey
Touhy
Toulmin
Toulouse
Toulson
Touma
Touney
Toupe
Toupin
Toups
Toure
Tourigny
Tourikis
Tourtellotte
Tourtelotte
Tourtillott
Tourville
Tousant
Tousey
Tousignant
Tousley
Tousom
Toussaint
Toussand
Toussant
Toussiant
Tout
Touton
Touvell
Tovar
Toves
Tovey
Tovias
Tovmasyan
Tovrea
Tow
Towber
Towe
Towell
Towels
Tower
Towers
Towery
Towey
Towle
Towler
Towlerton
Towles
Towley
Towlson
Town
Towne
Towner
Townes
Townley
Towns
Townsand
Townsel
Townsell
Townsend
Townsley
Townson
Townzen
Towry
Towse
Towsend
Towsley
Towson
Toxey
Toy
Toya
Toyama
Toye
Toyn
Toyne
Toyoshima
Toyota
Tozer
Tozier
Tozloski
Tozzi
Trabazo
Traber
Trabert
Trabold
Trabucco
Trabue
Trac
Trace
Tracewell
Tracey
Trachsel
Trachte
Trachtenberg
Tracy
Traczyk
Trad
Trader
Tradup
Traeger
Traff
Traffanstedt
Trafford
Traficante
Trafton
Trager
Trageser
Tragesser
Trahan
Traher
Trahern
Trahin
Traicoff
Trail
Traill
Trailor
Train
Traina
Trainer
Trainham
Traino
Trainor
Trainum
Traister
Trajillo
Tram
Tramble
Trame
Tramel
Tramell
Tramm
Trammel
Trammell
Trammer
Tramontano
Tramonte
Tramonti
Tramp
Trampe
Tran
Trana
Tranbarger
Trancoso
Trane
Tranel
Traner
Trang
Trani
Trank
Tranmer
Transou
Transue
Trant
Tranter
Trantham
Tranum
Trapalis
Trapanese
Trapani
Trapasso
Trapeni
Traphagen
Trapp
Trapper
Trappey
Trasher
Trask
Trasport
Trass
Traster
Tratar
Trattner
Traub
Traube
Trauernicht
Traugh
Traughber
Traugott
Traum
Traunfeld
Trausch
Trauscht
Traut
Trauth
Trautman
Trautmann
Trautner
Trautwein
Trautz
Traux
Travaglio
Travali
Travelstead
Traver
Travers
Traversa
Traverse
Traverso
Traves
Travieso
Travillian
Travillion
Travino
Travis
Traviss
Traw
Traweek
Trawick
Trax
Traxler
Traxson
Traycheff
Trayer
Trayler
Traylor
Traynham
Traynor
Traywick
Trbovich
Treacy
Treadaway
Treadway
Treadwell
Treakle
Treamer
Treanor
Trear
Trease
Treaster
Treasure
Treat
Trebbe
Trebesch
Trebil
Trebilcock
Trebon
Trecarichi
Trecroci
Tredennick
Treder
Tredinnick
Tredo
Tredway
Tredwell
Treece
Treen
Trees
Treese
Trefethen
Treff
Treffert
Trefry
Treftz
Trefz
Tregan
Treger
Treglia
Trego
Tregoning
Tregre
Treharne
Treherne
Treib
Treiber
Treible
Treichel
Treichler
Treider
Treine
Treinen
Treisch
Treister
Trejo
Trejos
Trela
Treleven
Trell
Trelles
Treloar
Tremain
Tremaine
Tremayne
Trembath
Trembinski
Tremblay
Tremble
Trembley
Trembly
Tremel
Tremelling
Tremillo
Treml
Tremmel
Tremont
Tremore
Tremper
Trenary
Trenbeath
Trench
Trenchard
Trend
Trendell
Trenh
Trenholm
Trenholme
Trenkle
Trennell
Trenor
Trent
Trentacoste
Trentham
Trentinella
Trentini
Trentman
Trento
Trenton
Trentz
Treola
Treon
Trepagnier
Trepanier
Treptow
Tresca
Tresch
Trescott
Tresler
Treso
Tress
Tressel
Tresselt
Tressler
Trest
Trester
Treston
Tresvant
Tretera
Tretheway
Trethewey
Tretina
Treto
Tretola
Trett
Tretter
Trettin
Treusdell
Treutel
Treuter
Trevarthen
Trevathan
Treves
Trevethan
Trevett
Trevey
Trevigne
Trevillian
Trevillion
Trevino
Trevis
Trevisan
Trevisone
Trevithick
Trevizo
Trevor
Trevorrow
Trew
Trewhitt
Trewin
Treworgy
Trexel
Trexler
Trezise
Trezza
Tri
Trial
Triana
Triano
Triarsi
Trias
Tribbett
Tribbey
Tribble
Tribby
Tribe
Trible
Triblett
Tribley
Tribou
Tribue
Tricamo
Tricarico
Trice
Triche
Trichel
Trichell
Trick
Trickel
Trickett
Trickey
Tricoche
Tricoli
Tricomi
Tridenti
Trider
Tridle
Triece
Trieger
Trier
Trieu
Trifero
Triffo
Trifiletti
Trifone
Trigg
Triggs
Trigillo
Trigleth
Triglia
Trigo
Trigueiro
Trigueros
Triguro
Trill
Trillana
Trillas
Triller
Trilli
Trilling
Trillo
Trilt
Trim
Trimarchi
Trimarco
Trimbach
Trimble
Trimboli
Trimino
Trimis
Trimm
Trimmell
Trimmer
Trimnal
Trimnell
Trimpe
Trinca
Trindle
Trine
Tringali
Tringham
Trinh
Trinidad
Trinka
Trinkl
Trinkle
Trinklein
Trinkley
Trinks
Trio
Triola
Triolo
Tripi
Triplet
Triplett
Triplette
Tripodi
Tripoli
Tripp
Trippany
Trippe
Trippel
Trippensee
Trippet
Trippett
Trippi
Tripplett
Trisch
Trischitta
Trisdale
Trish
Triska
Trisler
Tristan
Tritch
Trites
Tritle
Tritsch
Tritt
Tritten
Tritto
Tritz
Trivane
Trivedi
Triveno
Trivett
Trivette
Trivino
Trivisonno
Trivitt
Trizarry
Trnka
Trnong
Trobaugh
Trobough
Trobridge
Trocchio
Troccoli
Troche
Trochesset
Trocinski
Trodden
Troe
Troendle
Troesch
Troester
Troff
Trofholz
Trogdon
Troge
Troglen
Troglin
Trogstad
Troha
Trohanov
Troia
Troiani
Troiano
Troidl
Troike
Troilo
Troise
Troisi
Trojacek
Trojahn
Trojak
Trojan
Trojanovich
Trojanowski
Trojecki
Trojillo
Troke
Trokey
Trolinger
Trolio
Troll
Troller
Trollinger
Trollope
Tromba
Trombetta
Trombino
Tromblay
Tromble
Trombley
Trombly
Tromburg
Trometter
Tromley
Tromp
Trompeter
Tron
Tronaas
Troncoso
Trone
Trongone
Tronnes
Tronstad
Tront
Tronzo
Troop
Troost
Tropea
Tropiano
Tropp
Trosclair
Trosen
Trosien
Trosper
Trossbach
Trost
Trostel
Trostle
Troth
Trotman
Trotochaud
Trott
Trotta
Trotter
Trotti
Trottier
Trotto
Trotty
Trotz
Troublefield
Troung
Troup
Troupe
Trousdale
Trouser
Trout
Troutman
Troutner
Troutt
Trovato
Trover
Trovillion
Trovinger
Trowbridge
Trowel
Trowell
Trower
Trowers
Trowery
Troxel
Troxell
Troxil
Troxler
Troy
Troyan
Troyani
Troyano
Troyer
Truan
Truax
Trube
Trubey
Truby
Trucchi
Trucchio
Trucco
Truchan
Truchon
Trucker
Trucks
Trude
Trudeau
Trudel
Trudell
Trudelle
Truden
Trudgeon
Trudics
Trudillo
Trudnowski
Trudo
Trueax
Trueba
Trueblood
Truehart
Trueheart
Truell
Truelove
Trueluck
Trueman
Truesdale
Truesdell
Truett
Truex
Trufin
Truglia
Truglio
Truhe
Truiolo
Truitt
Trujillo
Truka
Trull
Trulli
Trullinger
Trulock
Trulove
Trulson
Truluck
Truly
Truman
Trumball
Trumbauer
Trumble
Trumbley
Trumbo
Trumbore
Trumbull
Trumm
Trump
Trumper
Trumpower
Trumpp
Trumps
Truncellito
Trundle
Trundy
Truner
Trunk
Trunnell
Trunzo
Truocchio
Truog
Truong
Truont
Trupia
Trupiano
Trupp
Truscott
Trusello
Trush
Trusillo
Truskowski
Trusler
Truslow
Truss
Trussel
Trussell
Trussler
Trusso
Trusty
Truver
Truxell
Truxillo
Truxler
Truxon
Try
Tryba
Trybala
Trybus
Trygg
Tryner
Tryninewski
Trynowski
Tryon
Trypaluk
Trythall
Trytten
Trzaska
Tsai
Tsakonas
Tsan
Tsang
Tsantakis
Tsao
Tsasie
Tsau
Tschache
Tschannen
Tschanz
Tschetter
Tschida
Tschirhart
Tschoepe
Tschumperlin
Tscrious
Tse
Tselee
Tsemetzis
Tseng
Tshudy
Tsiatsos
Tsing
Tsinnie
Tsironis
Tsistinas
Tso
Tsosie
Tsou
Tsu
Tsuboi
Tsuchida
Tsuchiura
Tsuchiya
Tsuda
Tsuha
Tsui
Tsuji
Tsukamoto
Tsukiyama
Tsunoda
Tsuruda
Tsutsui
Tsutsumi
Tsuzuki
Tu
Tua
Tuai
Tuamoheloa
Tuason
Tuazon
Tubaugh
Tubb
Tubbs
Tubby
Tubergen
Tuberman
Tubertini
Tuberville
Tubeszewski
Tubman
Tubolino
Tubville
Tucay
Tucci
Tucciarone
Tuccillo
Tuccio
Tucek
Tuch
Tuchman
Tucholski
Tuchy
Tuck
Tucke
Tucker
Tuckerman
Tuckerson
Tuckett
Tuckey
Tucknott
Tuczynski
Tudela
Tuder
Tudisco
Tudman
Tudor
Tudruj
Tuel
Tuell
Tueller
Tuenge
Tuer
Tuerk
Tuesburg
Tuey
Tufano
Tuff
Tuffey
Tuffin
Tufnell
Tufo
Tuft
Tufte
Tufts
Tugade
Tuggerson
Tuggie
Tuggle
Tuggles
Tugman
Tugwell
Tuholski
Tuia
Tuinstra
Tuite
Tuitt
Tujague
Tukes
Tukis
Tukuafa
Tuley
Tuliau
Tulino
Tulip
Tulis
Tulk
Tull
Tullar
Tuller
Tulley
Tullier
Tullio
Tullis
Tullison
Tullius
Tulloch
Tullock
Tullos
Tully
Tuma
Tuman
Tumaneng
Tumbaga
Tumbleson
Tumbleston
Tumblin
Tumey
Tuminello
Tumlin
Tumlinson
Tumlison
Tumminello
Tumminia
Tummons
Tumolillo
Tumolo
Tumpkin
Tumulty
Tun
Tunby
Tune
Tuner
Tung
Tungate
Tunget
Tunick
Tuning
Tunis
Tunison
Tunks
Tunnell
Tunney
Tunnicliff
Tunon
Tunson
Tunstall
Tuohey
Tuohy
Tuomala
Tuomi
Tuong
Tuorto
Tupa
Tupacyupanqui
Tupaj
Tupick
Tupin
Tuplano
Tuppen
Tupper
Tupy
Tur
Turano
Turansky
Turay
Turbacuski
Turbe
Turben
Turber
Turberville
Turbes
Turbeville
Turbide
Turbin
Turbiner
Turbyfill
Turchetta
Turchi
Turcio
Turcios
Turck
Turco
Turcott
Turcotte
Turdo
Turek
Turell
Turello
Tures
Tureson
Turgeon
Turi
Turiano
Turick
Turinetti
Turja
Turk
Turkasz
Turke
Turkel
Turkin
Turkington
Turkmay
Turko
Turkowski
Turks
Turkus
Turla
Turley
Turli
Turlich
Turlington
Turman
Turmel
Turmelle
Turnage
Turnball
Turnbaugh
Turnbill
Turnblom
Turnbo
Turnbough
Turnbow
Turnbull
Turne
Turneer
Turnell
Turner
Turnes
Turney
Turnham
Turnier
Turnipseed
Turnley
Turnmire
Turnmyre
Turnner
Turnow
Turnpaugh
Turnquist
Turns
Turntine
Turocy
Turomsha
Turowski
Turpen
Turpiano
Turpin
Turrell
Turrentine
Turrey
Turri
Turrie
Turrietta
Turrigiano
Turrill
Turro
Turrubiartes
Turrubiates
Tursi
Turso
Turtle
Turton
Turtura
Turturo
Turturro
Turvaville
Turvey
Turybury
Turzak
Turziano
Tusa
Tuschhoff
Tushoski
Tusing
Tusler
Tussey
Tussing
Tustin
Tustison
Tutaj
Tutas
Tutela
Tuten
Tuter
Tuthill
Tutino
Tutko
Tutoky
Tuton
Tutoni
Tutor
Tutson
Tutt
Tutterow
Tutterrow
Tuttle
Tutton
Tutuska
Tutwiler
Tuukanen
Tuxbury
Tuxhorn
Tuy
Tuzzio
Tuzzo
Tuzzolo
Tvedt
Twaddle
Twait
Twardy
Tweddell
Tweddle
Twedell
Tweden
Twedt
Tweed
Tweedie
Tweedle
Tweedy
Tweet
Twehous
Twellman
Twelves
Twersky
Tweten
Twichell
Twiddy
Twidwell
Twiest
Twiet
Twiford
Twigg
Twiggs
Twilley
Twillie
Twilligear
Twinam
Twine
Twiner
Twining
Twisdale
Twiss
Twisselman
Twist
Twitchell
Twito
Twitt
Twitty
Twogood
Twohatchet
Twohey
Twohig
Twombley
Twombly
Twomey
Tworek
Twyford
Twyman
Twymon
Ty
Tyacke
Tyberg
Tyburski
Tyce
Tycer
Tydeman
Tydings
Tye
Tyer
Tyeryar
Tygart
Tyger
Tyksinski
Tyl
Tyler
Tylman
Tylor
Tylwalk
Tyma
Tymeson
Tyminski
Tymon
Tyms
Tynan
Tyndal
Tyndall
Tyner
Tynes
Tynio
Tynon
Tyo
Tyon
Typhair
Tyra
Tyrance
Tyre
Tyree
Tyrell
Tyrer
Tyrie
Tyrol
Tyron
Tyrone
Tyrrell
Tyrus
Tysarczyk
Tysdal
Tysinger
Tyska
Tyson
Tysor
Tysseling
Tyssens
Tyszko
Tytler
Tyus
Tzeng
Tzeremes
Ubaldo
Uballe
Ubence
Uber
Ubertini
Ubiles
Ubl
Uboldi
Ubry
Uc
Uccellini
Uccello
Ucci
Uccio
Ucha
Uchida
Uchimura
Uchiyama
Uchytil
Udani
Uddin
Ude
Udell
Udicious
Udinsky
Udley
Udo
Udoh
Udy
Uebersax
Uecker
Ueckert
Ueda
Uehara
Ueki
Uelmen
Uemura
Ueno
Uerkwitz
Uffelman
Ufford
Ugaitafa
Ugalde
Ugarte
Ugaz
Ugland
Uglow
Uglum
Ugolini
Uhas
Uhde
Uher
Uhl
Uhlenhopp
Uhlenkott
Uhler
Uhles
Uhlich
Uhlig
Uhlir
Uhlman
Uhm
Uhrhammer
Uhri
Uhrich
Uhrig
Uhrin
Uhrmacher
Uhyrek
Uihlein
Uimari
Uitz
Ujano
Uk
Uken
Ukena
Ukich
Uknown
Ukosata
Ulabarro
Ulanski
Ulatowski
Ulberg
Ulbrich
Ulbricht
Ulcena
Ulch
Uldrich
Uleman
Ulerio
Ulery
Uliano
Ulibarri
Ulich
Ulicki
Ulicnik
Ulisch
Uljevic
Ullah
Ulland
Ullery
Ullman
Ullmann
Ullo
Ulloa
Ullom
Ullrich
Ullum
Ulm
Ulman
Ulmen
Ulmer
Ulrey
Ulrich
Ulrick
Ulsamer
Ulses
Ulseth
Ulsh
Ulshafer
Ulstad
Ultreras
Ultsch
Ultseh
Ulvan
Ulven
Ulwelling
Ulysse
Um
Umali
Umana
Umanzor
Umbach
Umbarger
Umbaugh
Umbdenstock
Umbel
Umbenhauer
Umberger
Umbrell
Umbright
Umeh
Umezawa
Umfleet
Umholtz
Umin
Umland
Umlauf
Umnus
Umphenour
Umphlett
Umphress
Umphrey
Umscheid
Umstead
Unangst
Unavailable
Uncapher
Unch
Unck
Underberg
Undercoffler
Underdahl
Underdown
Underdue
Underhill
Underkoffler
Underkofler
Underland
Underwood
Ung
Unga
Ungar
Ungaro
Unger
Ungerecht
Ungerland
Ungerleider
Ungerman
Unglaub
Unglesbee
Ungvarsky
Uniacke
Unick
Unikel
Union
Unkn
Unknow
Unland
Unnasch
Unnewehr
Unnold
Uno
Unrath
Unrau
Unrein
Unrue
Unruh
Unsell
Unser
Unsicker
Unsworth
Untalan
Unterburger
Unterkofler
Unterman
Unterreiner
Unterseher
Unterzuber
Unthank
Untiedt
Unvarsky
Unverzagt
Unzicker
Unzueta
Uong
Uoy
Upadhyaya
Upchurch
Updegraff
Updegrove
Updike
Updyke
Upham
Uphaus
Uphoff
Uphold
Uplinger
Upmeyer
Upole
Upp
Uppencamp
Uppinghouse
Upright
Upshaw
Upshur
Upson
Uptain
Uptegraft
Uptegrove
Uptgraft
Upthegrove
Uptmor
Upton
Upwall
Ur
Ura
Urabe
Uram
Uran
Uranga
Urankar
Urata
Urbach
Urbaez
Urbain
Urban
Urbancic
Urbanek
Urbani
Urbaniak
Urbanic
Urbanik
Urbano
Urbanski
Urbany
Urbas
Urben
Urbieta
Urbina
Urbine
Urbino
Urby
Urch
Urda
Urdiano
Ure
Uren
Urena
Urenda
Urenio
Ureno
Ureste
Uresti
Ureta
Urey
Urfer
Urguhart
Urhahn
Uriarte
Urias
Uribazo
Uribe
Urich
Urick
Urie
Uriegas
Urik
Urion
Urioste
Uriostegui
Uriostejue
Urive
Urizar
Urlanza
Urlaub
Urman
Urmeneta
Urmos
Urmston
Urness
Urps
Urquhart
Urquides
Urquidez
Urquidi
Urquijo
Urquilla
Urquiza
Urrabazo
Urraca
Urrea
Urreta
Urrey
Urrutia
Urry
Urse
Ursery
Ursiak
Ursini
Ursino
Urso
Ursprung
Ursua
Urtado
Urteaga
Urtiaga
Urtiz
Urton
Urtz
Urueta
Urwin
Urzua
Us
Usack
Uscio
Uselman
Uselton
Usery
Useted
Usher
Ushijima
Ushioda
Usie
Usilton
Usina
Usman
Uson
Usrey
Usry
Ussery
Ustico
Utecht
Uthe
Utley
Utsey
Utsler
Utt
Uttech
Utter
Utterback
Uttley
Utvik
Utz
Utzig
Utzinger
Uutela
Uva
Uvalle
Uvalles
Uxa
Uy
Uyeda
Uyehara
Uyematsu
Uyemura
Uyeno
Uyetake
Uzdygan
Uzee
Uzelac
Uziel
Uzun
Uzzell
Uzzle
Uzzo
Va
Vaca
Vacante
Vacanti
Vacarro
Vacca
Vaccarella
Vaccarello
Vaccarezza
Vaccarino
Vaccaro
Vacchiano
Vacek
Vacha
Vache
Vacher
Vacheresse
Vachon
Vachula
Vaci
Vacio
Vaclavik
Vactor
Vadala
Vadasy
Vaden
Vadenais
Vadlamudi
Vadnais
Vadner
Vaeth
Vaeza
Vafiades
Vafiadis
Vagas
Vaghn
Vaghy
Vagle
Vagliardo
Vaglienty
Vagnier
Vagott
Vagt
Vahena
Vahey
Vahle
Vaid
Vaidya
Vaiko
Vail
Vaile
Vailes
Vaill
Vaillancourt
Vaillencourt
Vails
Vaine
Vainio
Vair
Vais
Vaisman
Vaissiere
Vajda
Vajgrt
Vajnar
Vaka
Vakas
Vakil
Vaksman
Val
Vala
Valadao
Valade
Valadez
Valado
Valaitis
Valakas
Valant
Valasco
Valasek
Valasquez
Valazquez
Valcarcel
Valcho
Valcin
Valcourt
Valderamo
Valderas
Valderrama
Valdes
Valdespino
Valdez
Valdivia
Valdivieso
Valdiviezo
Valdo
Valdovino
Valdovinos
Vale
Valek
Valela
Valen
Valencia
Valenciana
Valenstein
Valensuela
Valent
Valenta
Valente
Valenti
Valentia
Valentin
Valentine
Valentini
Valentino
Valentyn
Valenza
Valenzano
Valenziano
Valenzuela
Valenzula
Valenzvela
Valer
Valera
Valeri
Valeriani
Valeriano
Valerie
Valerino
Valerio
Valerius
Valero
Valery
Vales
Valesquez
Valez
Valgren
Valido
Valiente
Valin
Valine
Valintine
Valiquette
Valis
Valiton
Valk
Valko
Vall
Valla
Valladao
Valladares
Valladolid
Valladores
Vallance
Vallandingham
Vallangeon
Vallar
Vallario
Vallarta
Vallas
Valle
Vallecillo
Vallee
Vallegos
Vallejo
Vallejos
Vallelonga
Vallely
Vallentine
Vallerand
Vallero
Vallery
Valles
Valletta
Vallette
Valley
Vallez
Valli
Vallian
Valliant
Vallie
Vallien
Vallier
Valliere
Vallieres
Vallimont
Vallin
Vallo
Vallon
Vallone
Vallot
Vallotton
Vallow
Valls
Valme
Valois
Valone
Valorie
Valot
Valotta
Valree
Valrey
Valrie
Valseca
Valsin
Valtas
Valtierra
Valvano
Valverde
Valvo
Vampa
Van
Vanabel
Vanacker
Vanacore
Vanaken
Vanakin
Vanallen
Vanaller
Vanalphen
Vanalst
Vanalstin
Vanalstine
Vanalstyne
Vanaman
Vanamburg
Vanamburgh
Vanamerongen
Vanandel
Vanantwerp
Vanaprasert
Vanaria
Vanarsdale
Vanarsdall
Vanartsdalen
Vanasse
Vanasselt
Vanasten
Vanatta
Vanauken
Vanauker
Vanausdal
Vanbebber
Vanbecelaere
Vanbeck
Vanbeek
Vanbelle
Vanbenthuyse
Vanbergen
Vanbeveren
Vanbibber
Vanblarcom
Vanblaricum
Vanboerum
Vanbogelen
Vanboven
Vanbramer
Vanbrocklin
Vanbruggen
Vanbrunt
Vanburen
Vanbuskirk
Vancamp
Vancampen
Vance
Vancheri
Vancil
Vancise
Vancleaf
Vancleave
Vancleve
Vanclief
Vanconant
Vanconey
Vancooten
Vancott
Vancura
Vancuren
Vandaele
Vandagriff
Vandal
Vandale
Vandall
Vandalsen
Vandam
Vandamme
Vandawalker
Vandeberg
Vandebogart
Vandebrake
Vandebrink
Vandee
Vandegraaff
Vandegriff
Vandegrift
Vandehei
Vandehey
Vandekamp
Vandekieft
Vandel
Vandelaare
Vandell
Vandellen
Vandeman
Vandemark
Vandemortel
Vandenacre
Vandenberg
Vandenberge
Vandenbergh
Vandenberghe
Vandenboom
Vandenbos
Vandenbosch
Vandenbrink
Vandenburg
Vandenburgh
Vandenheuvel
Vandeputte
Vanderark
Vanderau
Vanderbeck
Vanderbeek
Vanderberg
Vanderbie
Vanderbilt
Vanderboom
Vanderburg
Vandercook
Vanderen
Vanderford
Vandergiessen
Vandergraph
Vandergriend
Vandergriff
Vandergrift
Vanderheide
Vanderheiden
Vanderheyden
Vanderhoef
Vanderhoff
Vanderhoof
Vanderhoot
Vanderhorst
Vanderhurst
Vanderhyde
Vanderiet
Vanderjagt
Vanderkaaden
Vanderkam
Vanderkar
Vanderkooi
Vanderlaan
Vanderlee
Vanderlinde
Vanderlinden
Vanderlip
Vanderloo
Vandermark
Vandermay
Vandermeer
Vandermeulen
Vandermolen
Vandermoon
Vandernoot
Vanderploeg
Vanderpoel
Vanderpol
Vanderpool
Vanderroest
Vanderschaege
Vanderschel
Vanderschoot
Vanderslice
Vandersloot
Vanderstappen
Vandersteen
Vanderstelt
Vandertuig
Vanderveen
Vanderveer
Vandervelden
Vandervoort
Vandervort
Vanderwal
Vanderwall
Vanderweel
Vanderweerd
Vanderwege
Vanderweide
Vanderwerf
Vanderwerff
Vanderwilt
Vanderwood
Vanderwoude
Vanderwyk
Vanderzanden
Vanderzee
Vanderzwaag
Vandesande
Vandesteeg
Vandesteene
Vandestreek
Vandeusen
Vandevander
Vandevanter
Vandeveble
Vandeveer
Vandevelde
Vandevender
Vandeventer
Vandever
Vandevere
Vandevoorde
Vandevort
Vandevsen
Vandewalker
Vandewalle
Vandewater
Vandeweert
Vandewege
Vandewerker
Vandeyacht
Vandezande
Vandiest
Vandiford
Vandine
Vandinter
Vandis
Vandiver
Vandivier
Vandivort
Vandixon
Vandon
Vandonsel
Vandoren
Vandorien
Vandorn
Vandorp
Vandover
Vandre
Vandresar
Vandriel
Vandrunen
Vandunk
Vandusen
Vanduser
Vanduyn
Vanduyne
Vanduynhoven
Vanduzer
Vandy
Vandyck
Vandygriff
Vandyk
Vandyke
Vandyne
Vane
Vaneaton
Vanecek
Vaneck
Vaneekelen
Vaneffen
Vanegas
Vanegdom
Vanek
Vanelderen
Vanella
Vanelli
Vanepps
Vaneps
Vanert
Vanes
Vaness
Vanetta
Vanetten
Vanevery
Vaneyck
Vanez
Vanfleet
Vanfossan
Vanfossen
Vang
Vangalder
Vangelder
Vangelos
Vangemert
Vangerbig
Vangieson
Vangilder
Vangoff
Vangompel
Vangorden
Vangorder
Vangordon
Vangorp
Vangrouw
Vanguilder
Vangundy
Vangyi
Vanhaitsma
Vanham
Vanhamersveld
Vanhamlin
Vanhamme
Vanhampler
Vanhandel
Vanharlingen
Vanhauen
Vanhecke
Vanhee
Vanheel
Vanhekken
Vanhese
Vanheukelem
Vanheusen
Vanhevel
Vanhise
Vanhoecke
Vanhoesen
Vanhoff
Vanhofwegen
Vanholland
Vanhook
Vanhoose
Vanhooser
Vanhoozer
Vanhoozier
Vanhorn
Vanhorne
Vanhout
Vanhouten
Vanhoutte
Vanhove
Vanhowe
Vanhoy
Vanhulle
Vanhuss
Vanhyning
Vanicek
Vanier
Vaninetti
Vanis
Vanish
Vanisouvong
Vankammen
Vankampen
Vankeuren
Vankilsdonk
Vankirk
Vankleeck
Vankomen
Vankoten
Vanlaar
Vanlaere
Vanlandingham
Vanlaningham
Vanleer
Vanleeuwen
Vanlent
Vanleuvan
Vanleuven
Vanlew
Vanlier
Vanliere
Vanliew
Vanlinden
Vanlith
Vanloan
Vanloh
Vanloo
Vanloon
Vanlue
Vanluven
Vanmaanen
Vanmarter
Vanmatre
Vanmeter
Vanmetre
Vanmiddleswor
Vann
Vannah
Vannaman
Vannatta
Vannatten
Vannatter
Vannelli
Vanner
Vanness
Vannest
Vannette
Vanni
Vannice
Vanniello
Vannorden
Vannorman
Vannorsdell
Vannortwick
Vannostrand
Vannote
Vannover
Vannoy
Vannuck
Vannuland
Vanochten
Vanoflen
Vanoli
Vanolinda
Vanoni
Vanoort
Vanoosten
Vanord
Vanorden
Vanorder
Vanorsdale
Vanorsdol
Vanorsouw
Vanos
Vanosdel
Vanosdol
Vanostberg
Vanostrand
Vanous
Vanoven
Vanover
Vanoy
Vanpatten
Vanpatton
Vanpelt
Vanpoppelen
Vanpoucke
Vanproosdy
Vanputten
Vanriper
Vanroekel
Vanrossum
Vanruiten
Vanruler
Vanry
Vansant
Vanschaick
Vanschoiack
Vanschoick
Vanschoor
Vanschoyck
Vanschuyver
Vansciver
Vanscoik
Vanscoit
Vanscooter
Vanscoter
Vanscoy
Vanscyoc
Vansice
Vansickle
Vansicklin
Vansise
Vanskike
Vanskiver
Vanslander
Vanslooten
Vanslyke
Vansoest
Vanson
Vanstee
Vansteenberg
Vansteenburg
Vansteenhuyse
Vansteenwyk
Vanstone
Vanstrander
Vanstraten
Vanstrom
Vansumeren
Vansyckle
Vant
Vanta
Vantassel
Vantassell
Vanterpool
Vantil
Vantine
Vantol
Vantrease
Vantreese
Vantrump
Vantull
Vantuyl
Vantuyle
Vanuden
Vanvalen
Vanvalkenbur
Vanvalkenburg
Vanveen
Vanveldhuize
Vanvickle
Vanvleck
Vanvleet
Vanvliet
Vanvolkenburg
Vanvolkinburg
Vanvoorhees
Vanvoorhis
Vanvorst
Vanvranken
Vanvuren
Vanwagenen
Vanwagner
Vanwagoner
Vanwart
Vanwassenhove
Vanwechel
Vanweelden
Vanweerd
Vanwert
Vanwey
Vanwhy
Vanwie
Vanwieren
Vanwingerden
Vanwinkle
Vanwoert
Vanwormer
Vanwright
Vanwyck
Vanwye
Vanwyhe
Vanwyk
Vanwyngaarden
Vanyo
Vanzandt
Vanzant
Vanzante
Vanzanten
Vanzee
Vanzie
Vanzile
Vanzyl
Vaquera
Vaquerano
Vaquero
Vaquez
Vara
Varady
Varagona
Varajas
Varakuta
Varanda
Varanese
Varano
Varas
Varaza
Varble
Varcoe
Varda
Vardaman
Vardaro
Vardeman
Varden
Vardy
Varel
Varela
Varella
Varenhorst
Vares
Vareschi
Varesko
Varga
Vargas
Vargason
Varghese
Vargis
Vargo
Vargus
Vari
Varian
Varieur
Varillas
Varin
Vario
Varisco
Varkey
Varland
Varlas
Varley
Varma
Varn
Varnado
Varnadoe
Varnadore
Varnedoe
Varnedore
Varnell
Varner
Varnes
Varney
Varno
Varnon
Varnum
Varon
Varona
Varone
Varos
Varoz
Varquera
Varquez
Varrato
Varrelman
Varriale
Varriano
Varro
Varron
Varrone
Vars
Vartanian
Vartanyan
Varty
Varughese
Varuzzo
Varvel
Varvil
Vas
Vasallo
Vasaure
Vasbinder
Vascocu
Vasconcellos
Vasconcelos
Vascones
Vasconez
Vasek
Vasey
Vasguez
Vashaw
Vasher
Vashon
Vasi
Vasil
Vasilauskas
Vasile
Vasiliou
Vasiloff
Vasilopoulos
Vaske
Vasko
Vasmadjides
Vasos
Vasque
Vasques
Vasquez
Vasquiz
Vass
Vassall
Vassallo
Vassar
Vassel
Vassell
Vassen
Vasser
Vasseur
Vassey
Vassie
Vassil
Vasso
Vassure
Vasta
Vastakis
Vastano
Vastardis
Vastine
Vastola
Vasudevan
Vaszily
Vatalaro
Vatch
Vates
Vath
Vathroder
Vatter
Vatterott
Vattes
Vattikuti
Vaubel
Vaudrain
Vaudreuil
Vaugh
Vaughan
Vaughen
Vaughn
Vaughner
Vaughns
Vaught
Vaulet
Vaulx
Vaupel
Vause
Vauter
Vauters
Vautier
Vautour
Vautrin
Vaux
Vavra
Vavricek
Vavricka
Vavro
Vawter
Vay
Vayda
Vayner
Vayon
Vaz
Vazguez
Vazques
Vazquez
Vazzana
Vbiles
Ve
Vea
Veach
Veader
Veal
Veale
Veals
Vear
Veasey
Veasley
Veasman
Veatch
Veater
Veazey
Veazie
Vebel
Vecchi
Vecchia
Vecchiarelli
Vecchio
Vecchione
Vecellio
Vecino
Vecker
Vedder
Vedia
Vedovelli
Vee
Veeder
Veen
Veeneman
Veenstra
Veer
Veerkamp
Veeser
Vega
Vegar
Vegas
Vegerano
Vegetabile
Vegh
Vegher
Vegter
Vehrenkamp
Vehrs
Veiga
Veigel
Veil
Veile
Veillette
Veilleux
Veillon
Vein
Veino
Veit
Veitch
Veitenheimer
Veith
Veitinger
Veitz
Vejar
Vejarano
Veksler
Vela
Velandia
Velaquez
Velarde
Velardes
Velardi
Velardo
Velasco
Velasques
Velasquez
Velastegui
Velazco
Velazguez
Velazques
Velazquez
Veld
Veldhuizen
Veldkamp
Vele
Velega
Veles
Veleta
Veley
Velez
Velie
Velilla
Velis
Veliz
Velk
Velky
Vella
Vellekamp
Veller
Vellone
Vellucci
Vellutini
Velmontes
Velo
Veloso
Velotta
Velovic
Veloz
Velten
Velthuis
Veltin
Veltkamp
Veltman
Veltre
Veltri
Veltz
Velunza
Velverton
Velzeboer
Velzy
Vemura
Ven
Vena
Venable
Venancio
Venanzi
Venard
Vence
Vences
Vencill
Vendela
Vendelin
Vendetti
Vendig
Venditti
Venditto
Vendrick
Veneable
Venecia
Venegas
Venema
Veneman
Vener
Venerable
Venere
Veneri
Veness
Venetos
Veney
Venezia
Veneziano
Venghaus
Venhorst
Venible
Venice
Venier
Veninga
Venkus
Venn
Vennari
Venne
Venneman
Venner
Venneri
Vennes
Venning
Veno
Venosh
Vensel
Venske
Venskoske
Venson
Vent
Venter
Venters
Venth
Ventimiglia
Vento
Ventola
Venton
Ventors
Ventre
Ventrella
Ventresca
Ventress
Ventrice
Ventris
Ventrone
Ventry
Ventur
Ventura
Venture
Venturella
Venturelli
Venturi
Venturini
Venturino
Venus
Venuti
Venuto
Venzeio
Venzke
Venzon
Venzor
Ver
Vera
Verano
Verant
Veras
Verastequi
Verba
Verbasco
Verbeck
Verbeke
Verbilla
Verbit
Verble
Verbridge
Verburg
Verch
Vercher
Verd
Verde
Verdejo
Verdell
Verderame
Verderber
Verderosa
Verdi
Verdier
Verdiguel
Verdin
Verdine
Verdino
Verdon
Verdone
Verducci
Verdugo
Verdun
Verdusco
Verduzco
Vere
Vereb
Vereen
Verela
Veren
Veres
Verfaille
Verfaillie
Verga
Vergamini
Vergara
Vergari
Verge
Vergeer
Verges
Verghese
Vergin
Vergo
Verhaag
Verhaeghe
Verhagen
Verhague
Verhey
Verheyen
Verhines
Verhoeven
Verhoff
Verhulst
Veriato
Verigan
Verissimo
Verity
Verjan
Verkamp
Verkler
Verkuilen
Verlato
Verley
Verlin
Verlinden
Verling
Verlotte
Verma
Vermeer
Vermeesch
Vermette
Vermeulen
Vermillion
Vermilya
Vermilyea
Vermont
Verna
Vernaglia
Vernazza
Verne
Verner
Vernet
Vernetti
Verni
Vernia
Vernier
Vernola
Vernon
Vernoy
Vero
Veroba
Veroeven
Veron
Verona
Verone
Veronesi
Verplanck
Verra
Verrastro
Verrecchia
Verrell
Verrelli
Verret
Verrett
Verrier
Verrill
Verrilli
Verrone
Verros
Verrue
Verry
Versace
Versage
Versaw
Versele
Verser
Versluis
Verso
Versoza
Versteeg
Versteegh
Verstraete
Vert
Vertiz
Vertrees
Vertucci
Vertz
Verucchi
Verunza
Verville
Verwers
Verzi
Vescio
Vesco
Vescovi
Veselic
Veselka
Vesely
Vesey
Veshedsky
Vesley
Vespa
Vesper
Vesperas
Vesperman
Vespia
Vess
Vessar
Vessel
Vessell
Vessella
Vessels
Vessey
Vest
Vestal
Vester
Vestering
Vetere
Veteto
Veth
Veto
Vetrano
Vetri
Vetsch
Vettel
Vetter
Vetterick
Vetterkind
Veve
Vevea
Veverka
Vey
Veyna
Veys
Veysey
Vezina
Vezza
Via
Viafara
Vial
Viale
Viall
Vialpando
Vian
Viana
Viands
Viano
Viapiano
Viar
Viard
Viars
Vias
Viator
Viau
Vibbard
Vibbert
Vibert
Vicari
Vicario
Vicars
Viccica
Vice
Vicencio
Vicens
Vicent
Vicente
Vicenteno
Vichi
Vichidvongsa
Vicic
Vicini
Vicioso
Vick
Vicker
Vickerman
Vickers
Vickerson
Vickery
Vickey
Vicknair
Vickrey
Vickroy
Vicks
Vicory
Vicoy
Vicsik
Victor
Victorero
Victoria
Victorian
Victorica
Victorin
Victorine
Victorino
Victory
Vicueroa
Vicuna
Vida
Vidaca
Vidal
Vidales
Vidalez
Vidals
Vidana
Vidas
Vidaurri
Videen
Vides
Videtto
Vidinha
Vidler
Vidmar
Vidot
Vidovich
Vidra
Vidrine
Vidrio
Vidro
Vidulich
Vieau
Viebrock
Viegas
Viehman
Vieira
Viejo
Viel
Viele
Vielhauer
Vielle
Vielma
Vielman
Vielmas
Vien
Viener
Viengxay
Vienneau
Viens
Vient
Vientos
Vier
Viera
Viereck
Vierk
Vierling
Viernes
Vierps
Vierra
Viers
Vierthaler
Viesca
Viesselman
Viessman
Vieth
Vieths
Vietor
Viets
Vietti
Vietzke
Vieu
Vieux
View
Vieweg
Vieyra
Vig
Vigario
Vigen
Viger
Viggiani
Viggiano
Vigiano
Vigier
Vigil
Vigilante
Vigilo
Vigliotti
Vigna
Vignarath
Vignaux
Vigne
Vigneau
Vigneault
Vignola
Vignovich
Vigo
Vigor
Vigoren
Vigorito
Vigue
Vigueras
Viguerie
Vigus
Vijayan
Vijil
Vik
Viken
Viker
Vil
Vila
Vilain
Vilandre
Vilanova
Vilar
Vilardi
Vilardo
Vilaro
Vilca
Vilcan
Vilcheck
Vilches
Vilchis
Vildosola
Vile
Vilegas
Vilello
Viles
Vilhauer
Vilkama
Vilkoski
Villa
Villacana
Villacis
Villacorta
Villacrusis
Villada
Villaescusa
Villafana
Villafane
Villaflor
Villafranca
Villafuerte
Villagomez
Villagran
Villagrana
Villaire
Villalba
Villalobas
Villalobos
Villalon
Villalona
Villalouos
Villalovos
Villalpando
Villalta
Villaluazo
Villaluz
Villalva
Villalvazo
Villaman
Villamar
Villamarin
Villamayor
Villamil
Villandry
Villane
Villaneda
Villaneuva
Villaneva
Villani
Villano
Villanova
Villante
Villanueva
Villanvera
Villanveua
Villanveva
Villao
Villapando
Villaplana
Villaquiran
Villar
Villard
Villareal
Villari
Villarin
Villarreal
Villarruel
Villarrvel
Villarta
Villas
Villasana
Villasenor
Villasis
Villata
Villatora
Villatoro
Villaverde
Villavicencio
Ville
Villecus
Villeda
Villega
Villegas
Villela
Villella
Villemarette
Villena
Villenas
Villeneuve
Villerreal
Villescas
Villescaz
Villetas
Villiard
Villicana
Villifana
Villines
Villnave
Villot
Villwock
Vilmont
Viloria
Vilt
Viltz
Vilven
Vimont
Vina
Vinagre
Vinal
Vinall
Vinas
Vince
Vincelette
Vincent
Vincente
Vincenzo
Vinci
Vinciguerra
Vincik
Vinck
Vind
Vindiola
Vine
Vinegar
Viner
Vines
Vinet
Viney
Vineyard
Vinger
Viniard
Viniegra
Vining
Vinion
Vink
Vinke
Vinning
Vinroe
Vinsant
Vinsel
Vinson
Vint
Vinti
Vintila
Vintimilla
Vintinner
Vinton
Vinup
Vinyard
Vinz
Vinzant
Viola
Violante
Violet
Violett
Violetta
Violette
Viorel
Viox
Vipond
Vipperman
Virag
Viramontas
Viramontes
Virani
Virant
Viray
Virden
Virdin
Vire
Virella
Virelli
Viren
Vires
Virga
Virgadamo
Virgel
Virgen
Virgie
Virgil
Virgile
Virgili
Virgilio
Virgin
Virginia
Virgo
Virkler
Virock
Virola
Virostko
Virrey
Virrueta
Virts
Virtue
Viruet
Virula
Virzi
Vis
Visage
Visalli
Visaya
Viscardi
Viscarra
Viscarro
Viscera
Viscia
Visco
Viscome
Visconti
Viscosi
Vise
Visel
Viser
Visher
Visick
Visitacion
Visker
Visnic
Visnocky
Visnosky
Visocsky
Visor
Visosky
Visounnaraj
Visovsky
Visser
Vissering
Vissman
Viste
Visvardis
Vita
Vitagliano
Vital
Vitale
Vitali
Vitalo
Vitaniemi
Vitantonio
Vitanza
Vitatoe
Viteaux
Vitek
Vitela
Vitellaro
Vitelli
Vitello
Viteo
Vitera
Viteri
Vitez
Viti
Vitiello
Vititoe
Vititow
Vitko
Vitkus
Vito
Vitolas
Vitolo
Vitorino
Vitrano
Vitro
Vitt
Vittek
Vittetoe
Vitti
Vittitoe
Vittitow
Vittone
Vittorini
Vittorio
Vittum
Vitucci
Vitullo
Vivanco
Vivar
Vivas
Viveiros
Vivenzio
Viverette
Viveros
Vives
Vivian
Viviani
Viviano
Vivier
Vivino
Vivion
Vivo
Vivolo
Vivona
Vivyan
Vix
Vixay
Vixayack
Vizard
Vizarro
Vizcaino
Vizcarra
Vizcarrondo
Vizena
Vizuete
Vizza
Vizzi
Vizzini
Vlach
Vlahos
Vlahovich
Vlasak
Vlasaty
Vlashi
Vlcek
Vlchek
Vleming
Vliem
Vliet
Vljeric
Vlk
Vlloa
Vo
Voccia
Voce
Vocelka
Voci
Vock
Vocu
Vodder
Vodicka
Vodopich
Voedisch
Voegele
Voegeli
Voeks
Voelkel
Voelker
Voelkerding
Voeller
Voeltner
Voeltz
Voelz
Voetberg
Voetmann
Voetsch
Vogan
Vogds
Voge
Vogel
Vogeler
Vogelgesang
Vogelpohl
Vogelsang
Vogelsberg
Vogelzang
Vogenthaler
Voges
Vogl
Vogland
Vogle
Vogler
Voglund
Vogt
Vogtlin
Vogtman
Vogts
Vogus
Vohs
Voice
Voight
Voights
Voigt
Voigtlander
Voiles
Voisard
Voisin
Voisine
Voisinet
Voit
Voita
Voitier
Vojna
Vojta
Vojtko
Vokes
Volante
Volbert
Volbrecht
Volckmann
Volcko
Vold
Volden
Volek
Volentine
Volesky
Volin
Volino
Volinsky
Voliva
Volk
Volkens
Volker
Volkers
Volkert
Volking
Volkman
Volkmann
Volkmer
Voll
Volland
Vollbrecht
Volle
Vollenweider
Voller
Vollette
Vollick
Vollman
Vollmar
Vollmer
Vollmering
Vollmers
Vollrath
Vollstedt
Vollucci
Volmar
Volmer
Volmink
Volner
Volo
Volpa
Volpe
Volper
Volpert
Volpi
Volpicelli
Volpone
Volstad
Voltaire
Voltin
Voltz
Volz
Vona
Vonallmen
Vonarx
Vonasek
Vonbank
Vonbargen
Vonbraunsberg
Voncannon
Vonderahe
Vonderhaar
Vonderheide
Vonderkell
Vondielingen
Vondohlen
Vondoloski
Vondra
Vondracek
Vondrak
Vondran
Vondrasek
Voner
Vonfelden
Vonfeldt
Vong
Vongal
Vongkhamchanh
Vongkhamphanh
Vongphakdy
Vongsakda
Vongsamphanh
Vongunten
Vongvivath
Vongxay
Vonhagen
Vonholt
Vonk
Vonkrosigk
Vonner
Vonniederhaus
Vonruden
Vonschriltz
Vonseeger
Vonseggern
Vonsoosten
Vonstaden
Vonstein
Vontungeln
Vonwagoner
Voogd
Voong
Voorhees
Voorheis
Voorhes
Voorhies
Voorhis
Vopava
Vora
Voracek
Vorachek
Voran
Vorce
Vore
Vorel
Vorgas
Vorhees
Vorhies
Vorholt
Vories
Voris
Vorkink
Vormelker
Vormwald
Vornes
Voros
Vorpahl
Vorsburgh
Vorse
Vorwald
Vorwaller
Vorwerk
Vos
Vosberg
Vosburg
Vosburgh
Vose
Voshell
Vosika
Voskamp
Voskowsky
Vosmus
Vosper
Vosquez
Voss
Vossen
Vossler
Vost
Vostal
Votaua
Votaw
Vote
Voter
Voth
Voto
Votolato
Votraw
Votsmier
Votta
Vought
Vounas
Vovak
Voves
Vowell
Vowels
Vowles
Voyer
Voyles
Voytek
Vrabel
Vrable
Vrablic
Vradenburg
Vrana
Vranek
Vranes
Vranicar
Vranich
Vrazel
Vrba
Vrbas
Vrbka
Vredenburg
Vredenburgh
Vredeveld
Vreeken
Vreeland
Vreeman
Vreugdenhil
Vrias
Vriens
Vrieze
Vroman
Vroom
Vrooman
Vu
Vuckovich
Vue
Vugteveen
Vuillemot
Vukcevic
Vukelich
Vukelj
Vukich
Vukovich
Vulgamore
Vulgamott
Vulich
Vullo
Vuncannon
Vuolo
Vuong
Vuono
Vuoso
Vuturo
Vuyovich
Vy
Vyas
Vyhnal
Waack
Waag
Waaga
Waage
Waananen
Waas
Wabasha
Wable
Wacaster
Wach
Wachal
Wachob
Wachowiak
Wachowski
Wachs
Wachsman
Wachsmuth
Wacht
Wachtel
Wachter
Wachtler
Wack
Wackenheim
Wackenhut
Wacker
Wackerbarth
Wackerly
Wackman
Waclawski
Wactor
Wacyk
Wada
Wadas
Waddel
Waddell
Wadden
Waddick
Waddill
Wadding
Waddington
Waddle
Waddles
Waddouds
Waddoups
Waddups
Waddy
Wade
Wadel
Wadell
Wademan
Wadford
Wadhams
Wadkins
Wadle
Wadleigh
Wadley
Wadlinger
Wadlington
Wadlow
Wadman
Wadsworth
Wadusky
Wadzinski
Waechter
Waeckerlin
Waegner
Waelti
Waetzig
Waeyaert
Wafer
Waffenschmidt
Waffle
Wafford
Wafula
Wagaman
Waganer
Wagar
Wagatsuma
Wage
Wageman
Wagemann
Wagenaar
Wagenblast
Wagener
Wagenheim
Wagenknecht
Wager
Wagers
Wages
Wagg
Waggaman
Wagganer
Waggener
Waggett
Waggner
Waggoner
Waggy
Wagle
Wagler
Wagley
Wagman
Wagner
Wagnon
Wagnor
Wagon
Wagoner
Wagstaff
Wagster
Waguespack
Wagy
Wah
Wahba
Wahdan
Wahid
Wahington
Wahl
Wahlberg
Wahlen
Wahlenmaier
Wahler
Wahlers
Wahlert
Wahlgren
Wahlman
Wahlquist
Wahlstrom
Wahlund
Wahn
Wahner
Wahoske
Wahpekeche
Wahr
Wahs
Wai
Waiau
Waibel
Waid
Waide
Waidelich
Waiden
Waight
Waiki
Wailes
Wain
Wainer
Wainio
Wainkrantz
Wainman
Wainright
Wainscott
Wainwright
Wair
Wais
Waisanen
Waisath
Waisman
Waisner
Waiss
Wait
Waite
Waiters
Waites
Waithe
Waitkus
Waitman
Waits
Waitz
Wajda
Waka
Wakabayashi
Wakayama
Wake
Wakefield
Wakeford
Wakeham
Wakeland
Wakeley
Wakeling
Wakely
Wakeman
Wakenight
Waker
Wakham
Wakin
Wakins
Wakita
Wakley
Wakula
Wal
Wala
Walat
Walawender
Walberg
Walbert
Walborn
Walbrecht
Walbridge
Walbright
Walburn
Walby
Walch
Walchak
Walchli
Walck
Walcott
Walcutt
Walczak
Walczyk
Walczynski
Wald
Waldal
Waldall
Waldbauer
Walde
Waldeck
Waldecker
Walden
Waldenberg
Waldenmyer
Walder
Walderon
Waldhauser
Waldhoff
Waldie
Walding
Waldman
Waldmann
Waldner
Waldo
Waldoch
Waldock
Waldon
Waldorf
Waldow
Waldram
Waldren
Waldrep
Waldridge
Waldrip
Waldroff
Waldron
Waldroop
Waldrop
Waldrope
Waldroup
Waldrup
Waldschmidt
Waldvogel
Wale
Walega
Walema
Walen
Walenta
Walentoski
Waler
Wales
Waletzko
Waley
Walezak
Walford
Walgren
Walicki
Waligora
Walin
Walinski
Walizer
Walk
Walka
Walke
Walken
Walkenhorst
Walker
Walkers
Walkes
Walking
Walkingstick
Walkington
Walkins
Walkinshaw
Walkley
Walkling
Walkner
Walko
Walkowiak
Walkowski
Walks
Walkup
Wall
Walla
Wallace
Wallach
Wallack
Wallaert
Wallaker
Walland
Wallander
Wallau
Wallbank
Wallberg
Wallbrown
Walle
Walleck
Wallen
Wallenbrock
Wallenda
Wallenstein
Wallentine
Waller
Wallerich
Walles
Wallet
Wallett
Walley
Wallgren
Wallick
Wallie
Wallin
Walling
Wallinga
Wallinger
Wallingford
Wallington
Wallis
Walliser
Walljasper
Wallman
Wallner
Wallo
Walloch
Wallor
Wallravin
Walls
Wallschlaeger
Wallwork
Wally
Walman
Walmer
Walmsley
Waln
Walner
Waloven
Walp
Walper
Walpole
Walquist
Walrath
Walraven
Walrod
Walrond
Walser
Walseth
Walsh
Walshe
Walsingham
Walson
Walstad
Walston
Walstrom
Walstrum
Walsworth
Walt
Waltemath
Waltemeyer
Waltenbaugh
Walter
Walterman
Waltermire
Walters
Walterscheid
Waltersdorf
Waltersheid
Walterson
Walth
Walthall
Walther
Walthers
Waltho
Walthour
Waltjen
Waltman
Waltmann
Waltmon
Waltner
Walto
Walton
Waltos
Waltrip
Walts
Waltz
Waltzer
Walund
Walvatne
Walvoord
Walworth
Walwyn
Walz
Walzer
Walzier
Wamack
Wambach
Wamble
Wamboldt
Wamhoff
Wammack
Wampler
Wampol
Wampole
Wamser
Wamsley
Wan
Wanamaker
Wanat
Wanberg
Wanca
Wanczyk
Wand
Wanda
Wandel
Wandell
Wander
Wanders
Wandersee
Wandler
Wandless
Wandrei
Wandrie
Wands
Wanek
Waneka
Waner
Wang
Wangberg
Wanger
Wangerin
Wangler
Wangstad
Waninger
Wank
Wanke
Wankel
Wanker
Wanko
Wankum
Wanland
Wanlass
Wanless
Wann
Wannamaker
Wannarka
Wanner
Wannlund
Wanous
Wanschek
Wanser
Wansing
Wansitler
Wansley
Want
Wanta
Wantland
Wantuck
Wanty
Wantz
Wanvig
Wanzek
Wanzer
Waples
Wapp
Wappel
War
Warbington
Warboys
Warbritton
Warburg
Warburton
Warchal
Warchol
Ward
Wardall
Warde
Wardell
Warden
Warder
Wardhaugh
Wardian
Wardinsky
Wardlaw
Wardle
Wardlow
Wardman
Wardon
Wardrip
Wardrop
Wardrup
Wardsworth
Wardwell
Ware
Wareham
Wareheim
Warehime
Wareing
Waren
Warens
Wares
Warf
Warfel
Warfield
Warford
Warga
Wargo
Warhol
Warhola
Warholic
Warhurst
Warick
Warila
Wariner
Waring
Wark
Warkentin
Warley
Warlick
Warling
Warlock
Warlow
Warm
Warmack
Warman
Warmath
Warmbier
Warmbrod
Warmbrodt
Warmington
Warmka
Warmoth
Warmuth
Warn
Warnack
Warnasch
Warnberg
Warncke
Warne
Warnecke
Warneka
Warneke
Warnell
Warner
Warnes
Warney
Warnick
Warning
Warnix
Warnke
Warnken
Warnock
Warns
Warnstaff
Warntz
Waroway
Warp
Warpool
Warr
Warran
Warrell
Warren
Warrender
Warrenfeltz
Warrick
Warrilow
Warriner
Warring
Warrington
Warrior
Warrix
Warsager
Warsaw
Warschaw
Warsham
Warshauer
Warshaw
Warsing
Warsme
Warson
Warstler
Wartchow
Wartenberg
Warters
Warth
Warthen
Wartman
Warton
Warwick
Wary
Warzecha
Warzybok
Wascher
Wasco
Wascom
Wasden
Wasem
Waser
Wash
Washabaugh
Washam
Washburn
Washell
Washer
Washing
Washington
Washinski
Washinton
Washko
Washler
Washman
Washmuth
Washnock
Washor
Washpun
Washuk
Washum
Washup
Washurn
Wasicek
Wasielewski
Wasik
Wasilewski
Wasilko
Wasinger
Wasiuta
Waska
Waskey
Waskiewicz
Waskin
Wasko
Waskom
Waskow
Wasmer
Wasmund
Wasmus
Wasmuth
Wasner
Wason
Wasowski
Wasp
Wass
Wassam
Wassel
Wassell
Wassenaar
Wassenberg
Wasser
Wasserman
Wassermann
Wassil
Wassinger
Wassink
Wassman
Wassmann
Wasson
Wassum
Waston
Wasurick
Wasyliszyn
Wasylow
Waszak
Waszkiewicz
Waszmer
Watah
Watahomigie
Watanabe
Watcher
Watchman
Watchorn
Water
Waterbury
Waterer
Waterfall
Waterfield
Waterford
Waterhouse
Waterman
Waters
Waterson
Waterston
Waterworth
Wates
Watford
Wathen
Watkin
Watkins
Watkinson
Watland
Watler
Watley
Watling
Watlington
Watne
Watral
Watring
Watrous
Watrs
Watry
Watsky
Watson
Watt
Watte
Wattenbarger
Wattenberg
Watters
Watterson
Wattigny
Wattles
Wattley
Watton
Watts
Wattson
Watwood
Watzka
Watzke
Wauch
Waud
Wauer
Wauford
Waugaman
Waugh
Waughtal
Waughtel
Wauneka
Wauson
Wauters
Wave
Waver
Waverly
Wavra
Wawers
Wawrzyniak
Wax
Waxler
Waxman
Way
Waybill
Waybright
Waycaster
Waychoff
Waychowsky
Waycott
Wayde
Waye
Wayford
Waygood
Wayland
Wayman
Wayment
Waymer
Waymire
Waymon
Wayne
Wayner
Waynick
Wayns
Ways
Wayson
Wayt
Wayts
Waz
Wdowiak
Weaber
Wead
Weader
Weadon
Weafer
Weagel
Weagle
Weagraff
Weakland
Weaklend
Weakley
Weakly
Weaks
Weal
Wealer
Weant
Wear
Weare
Wearing
Wearly
Wearrien
Wears
Weary
Wease
Weasel
Weast
Weather
Weatherall
Weatherbee
Weatherby
Weatherford
Weatherhead
Weatherholt
Weatherholtz
Weatherill
Weatherington
Weatherley
Weatherly
Weatherman
Weathers
Weathersbee
Weathersby
Weatherspoon
Weatherwax
Weathington
Weaver
Weavers
Weavil
Weaving
Webb
Webber
Webbink
Webbs
Weber
Weberg
Webley
Webre
Webster
Wechselblatt
Wechsler
Wechter
Weck
Weckenborg
Wecker
Weckerly
Weckhorst
Weckman
Weckwerth
Wedd
Weddel
Weddell
Wedderburn
Wedderspoon
Wedding
Weddington
Weddle
Wede
Wedekind
Wedeking
Wedel
Wedell
Wedemeyer
Weder
Wedge
Wedgewood
Wedgeworth
Wedgworth
Wedi
Wedige
Wedin
Wedlock
Wedlow
Wedman
Wedner
Wedo
Wedwick
Wee
Weeber
Weech
Weed
Weeda
Weeden
Weedman
Weedon
Weegar
Weege
Weekes
Weekey
Weekley
Weekly
Weeks
Weelborg
Weeler
Weeman
Weemes
Weemhoff
Weems
Weenum
Weers
Weerts
Weese
Weesner
Weeter
Weeth
Weflen
Wege
Wegener
Weger
Wegge
Weghorst
Wegiel
Weglage
Weglarz
Wegleitner
Wegley
Weglin
Wegman
Wegmann
Wegner
Wegrzyn
Wegweiser
Wehausen
Wehbe
Wehby
Wehe
Wehking
Wehling
Wehmann
Wehmeier
Wehmeyer
Wehn
Wehner
Wehnes
Wehr
Wehrenberg
Wehrheim
Wehring
Wehrle
Wehrley
Wehrli
Wehrly
Wehrman
Wehrmann
Wehrs
Wehrsig
Wehrwein
Wehunt
Wei
Weiand
Weibe
Weibel
Weible
Weich
Weichbrodt
Weichel
Weichman
Weicht
Weick
Weickum
Weida
Weide
Weideman
Weidemann
Weiden
Weidenbach
Weidenheimer
Weider
Weiderhold
Weidert
Weidig
Weidler
Weidman
Weidmann
Weidner
Weidower
Weier
Weig
Weigand
Weigart
Weigel
Weigelt
Weigert
Weight
Weightman
Weigl
Weigle
Weigleb
Weiglein
Weigman
Weigner
Weigold
Weihe
Weiher
Weihl
Weik
Weikal
Weikel
Weiker
Weikert
Weikle
Weil
Weiland
Weilbacher
Weiler
Weill
Weiman
Weimann
Weimar
Weimer
Wein
Weinand
Weinbach
Weinbauer
Weinberg
Weinberger
Weinburg
Weiner
Weinert
Weinfeld
Weinfurter
Weingard
Weingart
Weingarten
Weingartner
Weinger
Weinheimer
Weinhold
Weininger
Weinkauf
Weinland
Weinman
Weinmann
Weinraub
Weinreb
Weinreich
Weinrib
Weinrich
Weins
Weinstein
Weinstock
Weintraub
Weintz
Weinzetl
Weinzierl
Weinzimer
Weinzinger
Weipert
Weir
Weirather
Weirauch
Weirich
Weirick
Weis
Weisbaum
Weisbecker
Weisberg
Weisberger
Weisbrod
Weisdorfer
Weise
Weisel
Weisenberg
Weisenberger
Weisenborn
Weisenburger
Weisend
Weisenfels
Weisenfluh
Weisenhorn
Weisenstein
Weiser
Weisfeld
Weisgarber
Weisgerber
Weishaar
Weishar
Weishaupt
Weisheit
Weisholz
Weisiger
Weisinger
Weiskopf
Weisman
Weismantle
Weismiller
Weisner
Weispfenning
Weiss
Weissberg
Weissbrodt
Weisse
Weissenbach
Weissenborn
Weisser
Weissert
Weissgerber
Weissinger
Weissler
Weissman
Weissmann
Weist
Weisz
Weiszbrod
Weit
Weiter
Weith
Weitkamp
Weitman
Weitnauer
Weitz
Weitze
Weitzel
Weitzman
Weitzner
Wekenborg
Wekenmann
Wela
Welander
Welborn
Welburn
Welby
Welch
Welchel
Welcher
Welchman
Welcome
Weld
Welde
Welden
Welder
Weldin
Welding
Weldon
Weldy
Welfel
Welford
Welk
Welke
Welker
Well
Welland
Wellard
Wellborn
Wellbrock
Welle
Wellen
Wellendorf
Wellenstein
Weller
Welles
Welling
Wellinghoff
Wellings
Wellington
Welliver
Wellman
Wellmann
Wellner
Wellnitz
Wellons
Wells
Wellspeak
Welman
Welms
Welner
Welp
Welsch
Welschmeyer
Welsh
Welshans
Welson
Weltch
Welte
Welter
Welters
Weltha
Welti
Weltmer
Welton
Welty
Weltz
Weltzin
Welz
Welzel
Wemark
Wember
Wemhoff
Wemmer
Wempa
Wempe
Wemple
Wen
Wence
Wenciker
Wenck
Wencl
Wenclawiak
Wend
Wende
Wendel
Wendelberger
Wendelboe
Wendelin
Wendelken
Wendell
Wendeln
Wender
Wenderoth
Wendland
Wendlandt
Wendler
Wendling
Wendolski
Wendorf
Wendorff
Wendroth
Wendt
Wendte
Wendy
Wendzel
Wene
Weneck
Wener
Weng
Wengel
Wenger
Wengerd
Wengert
Wengler
Wengreen
Wengren
Wenig
Weniger
Weninger
Wenk
Wenke
Wenker
Wenman
Wenner
Wennersten
Wenning
Wenninger
Wenrich
Wenrick
Wensel
Wenske
Wenskoski
Wensky
Wensman
Wenstrand
Wenstrom
Went
Wentcell
Wente
Wenthold
Wentland
Wentling
Wentworth
Wentz
Wentzel
Wentzell
Wentzlaff
Wentzloff
Wenz
Wenzel
Wenzell
Wenzinger
Wenzl
Weppler
Werbelow
Werber
Werblow
Werderman
Werdlow
Werger
Wergin
Werk
Werkheiser
Werkhoven
Werking
Werkmeister
Werksman
Werle
Werley
Werline
Werling
Werlinger
Werma
Werme
Wermers
Wermter
Wern
Wernecke
Werner
Wernert
Wernett
Wernex
Wernick
Wernicki
Wernimont
Werning
Wernli
Wernsman
Werntz
Wernz
Wero
Werra
Werre
Werremeyer
Werries
Werring
Werry
Wersal
Wershey
Werst
Werstein
Wert
Wertenberger
Werth
Wertheim
Wertheimer
Werthman
Wertman
Werts
Wertz
Wery
Wesberry
Wesby
Wesch
Wesche
Wescom
Wescott
Wescovich
Wesely
Wesemann
Weser
Weske
Wesler
Wesley
Wesloh
Weslow
Weslowski
Wesly
Wesner
Wesolick
Wesolowski
Wess
Wessel
Wesselhoft
Wesselink
Wessell
Wessells
Wesselman
Wessels
Wessendorf
Wessinger
Wessler
Wessling
Wessman
Wessner
Wesson
West
Westaby
Westad
Westall
Westaway
Westberg
Westberry
Westbrook
Westbrooke
Westbrooks
Westbury
Westby
Westcoat
Westcote
Westcott
Westen
Westenbarger
Westenberger
Westendorf
Westenhaver
Wester
Westerbeck
Westerberg
Westerfeld
Westerfield
Westergaard
Westergard
Westerheide
Westerhof
Westerhoff
Westerhold
Westerholm
Westerling
Westerlund
Westerman
Westermann
Westermark
Westermeier
Western
Westervelt
Westervoorde
Westfahl
Westfall
Westfield
Westgaard
Westgate
Westhoff
Westhouse
Westin
Westlake
Westland
Westler
Westley
Westlie
Westling
Westlund
Westly
Westman
Westmark
Westmeyer
Westmoreland
Westmorland
Weston
Westover
Westpfahl
Westphal
Westphalen
Westra
Westray
Westre
Westrich
Westrick
Westrom
Westrope
Westrum
Westrup
Westry
Westveer
Westwater
Westwood
Wetenkamp
Weter
Wetherald
Wetherbee
Wetherby
Wetherell
Wetherill
Wetherington
Wethern
Wethington
Wethje
Wetklow
Wetmore
Wetsel
Wetselline
Wettach
Wetter
Wetterauer
Wetterer
Wettlaufer
Wettstein
Wetz
Wetzel
Wetzell
Wetzler
Wetzstein
Weuve
Wever
Wewerka
Wexell
Wexler
Wey
Weyand
Weyandt
Weyant
Weydert
Weyer
Weyers
Weygandt
Weyhrauch
Weyker
Weyland
Weyler
Weyman
Weymouth
Weynand
Weyrauch
Weyrick
Whack
Whaite
Whal
Whalan
Whalen
Whaler
Whaley
Whalley
Whaltey
Whan
Whang
Whapham
Wharff
Wharry
Wharton
Whary
Whatcott
Whatley
Whatoname
Wheadon
Wheary
Wheat
Wheatcroft
Wheater
Wheatley
Wheatly
Wheaton
Whedbee
Whedon
Wheeington
Wheelan
Wheeland
Wheeldon
Wheelen
Wheeler
Wheeles
Wheeless
Wheeley
Wheeling
Wheelis
Wheelock
Wheelus
Wheelwright
Wheetley
Whelan
Whelchel
Wheldon
Whelehan
Wheler
Wheless
Whelihan
Wheller
Whelpley
Whelton
Wherley
Wherry
Whetham
Whetsel
Whetsell
Whetstine
Whetstone
Whetten
Whetzel
Whetzell
Whiby
Whichard
Whicker
Whidbee
Whidby
Whidden
Whiddon
Whigham
Whigum
Whilby
Whilden
Whildin
While
Whiles
Whiley
Whillock
Whinery
Whinnery
Whipkey
Whipp
Whippie
Whipple
Whippo
Whipps
Whirley
Whirlow
Whirry
Whisby
Whisenand
Whisenant
Whisenhunt
Whisenton
Whish
Whisker
Whisler
Whisman
Whisnant
Whisner
Whisonant
Whispell
Whisted
Whistle
Whistlehunt
Whistler
Whiston
Whit
Whitacker
Whitacre
Whitaker
Whitbeck
Whitbread
Whitby
Whitcher
Whitchurch
Whitcomb
Whitcome
Whitcraft
White
Whiteaker
Whitebear
Whitebird
Whitebread
Whitecloud
Whitecotton
Whited
Whitefield
Whiteford
Whitegoat
Whitehair
Whitehall
Whitehead
Whitehill
Whitehorn
Whitehorse
Whitehouse
Whitehurst
Whiteis
Whitelaw
Whiteleather
Whiteley
Whitelightnin
Whitelock
Whitelow
Whitely
Whiteman
Whitemarsh
Whitemore
Whiten
Whitenack
Whitener
Whitenton
Whiter
Whiters
Whites
Whitescarver
Whitesel
Whitesell
Whiteside
Whitesides
Whitesinger
Whitewater
Whitey
Whitfield
Whitfill
Whitford
Whitham
Whitheld
Whitherspoon
Whitiker
Whiting
Whitinger
Whitis
Whitker
Whitlach
Whitlatch
Whitledge
Whitler
Whitley
Whitling
Whitlinger
Whitlingum
Whitlock
Whitlow
Whitman
Whitmarsh
Whitmer
Whitmeyer
Whitmire
Whitmore
Whitmoyer
Whitmyre
Whitner
Whitney
Whiton
Whitrock
Whitsel
Whitsell
Whitset
Whitsett
Whitsey
Whitsitt
Whitson
Whitt
Whittaker
Whittall
Whitted
Whitteker
Whittemore
Whitten
Whittenbeck
Whittenberg
Whittenburg
Whittenton
Whitter
Whittet
Whittie
Whittier
Whittiker
Whitting
Whittingham
Whittinghill
Whittington
Whittle
Whittler
Whittlesey
Whittley
Whittman
Whittmore
Whitton
Whittum
Whitty
Whitver
Whitwell
Whitworth
Whobrey
Wholey
Wholly
Whooley
Whooper
Whorley
Whorton
Whtie
Why
Whyard
Whybrew
Whyel
Whyman
Whyms
Whyne
Whysong
Whyte
Wiacek
Wiand
Wiant
Wiater
Wiatr
Wiatrak
Wiatrek
Wiatrowski
Wibbenmeyer
Wibbens
Wibberley
Wiberg
Wibeto
Wible
Wiborg
Wical
Wice
Wicher
Wichern
Wichert
Wichland
Wichman
Wichmann
Wichrowski
Wichterman
Wicinsky
Wick
Wicka
Wickard
Wicke
Wickell
Wickemeyer
Wickenhauser
Wickens
Wicker
Wickers
Wickersham
Wickersheim
Wickert
Wickes
Wickett
Wicketts
Wickey
Wickham
Wickings
Wickizer
Wickkiser
Wickland
Wickliff
Wickliffe
Wicklin
Wickline
Wicklund
Wickman
Wicks
Wickson
Wickstrom
Wickus
Wickware
Wickwire
Wida
Widby
Widder
Widdison
Widdoes
Widdop
Widdows
Widdowson
Wide
Widell
Wideman
Widen
Widener
Wider
Widera
Widerski
Widgeon
Widger
Widhalm
Widick
Widjaja
Widlak
Widmaier
Widman
Widmann
Widmar
Widmark
Widmayer
Widmer
Widner
Widney
Widowski
Widrick
Widrig
Wieand
Wiebe
Wieben
Wieber
Wieberg
Wiebers
Wiebold
Wieboldt
Wiebusch
Wiece
Wiechec
Wiechert
Wiechman
Wiechmann
Wieciech
Wieck
Wieckowski
Wieczorek
Wied
Wiede
Wiedeman
Wiedemann
Wiedenheft
Wieder
Wiederhold
Wiederholt
Wiederin
Wiederstein
Wiederwax
Wiedmaier
Wiedman
Wiedmann
Wiedrich
Wiedyk
Wiegand
Wiegard
Wiegel
Wieger
Wiegert
Wiegman
Wiegmann
Wiehe
Wieland
Wielgasz
Wielgosz
Wielgus
Wieloch
Wielock
Wieman
Wiemann
Wiemer
Wien
Wienandt
Wienberg
Wienecke
Wieneke
Wiener
Wienert
Wienhoff
Wienke
Wiens
Wier
Wierenga
Wierman
Wiers
Wierschem
Wierschen
Wiersema
Wiersma
Wierson
Wiersteiner
Wierzba
Wierzbicki
Wies
Wiese
Wiesehan
Wiesel
Wieseler
Wieseman
Wiesemann
Wiesen
Wieser
Wiesler
Wiesman
Wiesner
Wiesneski
Wiess
Wiest
Wietbrock
Wieting
Wieto
Wietzel
Wiewel
Wiford
Wig
Wigand
Wigboldy
Wigdor
Wigelsworth
Wigen
Wiget
Wigfall
Wigfield
Wigg
Wiggains
Wiggan
Wiggen
Wiggens
Wigger
Wiggers
Wiggett
Wiggin
Wiggington
Wiggins
Wigginton
Wigglesworth
Wiggs
Wigham
Wight
Wightman
Wigington
Wiginton
Wigle
Wiglesworth
Wigley
Wigman
Wignall
Wigner
Wigren
Wigton
Wiinikainen
Wik
Wike
Wikel
Wiker
Wikert
Wikholm
Wikins
Wikle
Wiklund
Wikoff
Wikstrom
Wiktor
Wilabay
Wiland
Wilansky
Wilbanks
Wilber
Wilbers
Wilbert
Wilbon
Wilborn
Wilbourn
Wilbourne
Wilbur
Wilburn
Wilby
Wilch
Wilchek
Wilcher
Wilcinski
Wilcock
Wilcox
Wilcoxen
Wilcoxon
Wilcoxson
Wilcut
Wilcutt
Wilczak
Wilczewski
Wilczynski
Wild
Wilda
Wildauer
Wilday
Wildberger
Wilde
Wildeboer
Wildeisen
Wildeman
Wilden
Wildenberg
Wildenthaler
Wilder
Wilderman
Wildermuth
Wilderson
Wildes
Wildey
Wildfong
Wildhaber
Wildin
Wilding
Wildman
Wildner
Wildoner
Wildrick
Wildridge
Wilds
Wildsmith
Wildt
Wile
Wilebski
Wileczek
Wileman
Wilemon
Wilen
Wilenkin
Wilensky
Wiler
Wiles
Wiley
Wilfahrt
Wilfinger
Wilfong
Wilford
Wilfred
Wilging
Wilgocki
Wilgus
Wilham
Wilhelm
Wilhelmi
Wilhelms
Wilhelmsen
Wilhelmy
Wilhide
Wilhite
Wilhoit
Wilhoite
Wiliams
Wilis
Wilison
Wilk
Wilke
Wilken
Wilkening
Wilkens
Wilkenson
Wilker
Wilkers
Wilkerson
Wilkes
Wilkey
Wilkie
Wilkin
Wilkins
Wilkinson
Wilkison
Wilkoff
Wilkos
Wilkosz
Wilkowitz
Wilks
Wilkson
Wilkus
Will
Willaby
Willadsen
Willaert
Willaims
Willaimson
Willame
Willams
Willamson
Willand
Willard
Willardson
Willars
Willbanks
Willborn
Willcott
Willcox
Willcoxon
Willcutt
Wille
Willeford
Willegal
Willems
Willemsen
Willen
Willenborg
Willenbring
Willenbrink
Willenbrock
Willens
Willer
Willers
Willert
Willes
Willet
Willeto
Willets
Willett
Willette
Willetts
Willey
Willford
Willging
Willhelm
Willhite
Willhoite
Willi
Willia
William
Williama
Williamis
Williamon
Williams
Williamsen
Williamson
Williamston
Willian
Willians
Williar
Williard
Willibrand
Williby
Willick
Willie
Williemae
Willier
Willies
Williford
Willig
Willigar
Willilams
Willimas
Willimon
Willims
Willing
Willinger
Willingham
Willinghurst
Willington
Willinsky
Willis
Willison
Williston
Willits
Willitzer
Williver
Willman
Willmann
Willmarth
Willmert
Willmes
Willmon
Willmore
Willmott
Willms
Willmschen
Willner
Willoby
Willock
Willougby
Willoughby
Willour
Willow
Willrett
Willrich
Wills
Willsey
Willson
Willwerth
Willy
Willyard
Wilm
Wilmarth
Wilmer
Wilmes
Wilmeth
Wilmont
Wilmore
Wilmot
Wilmoth
Wilmott
Wilmouth
Wilner
Wilridge
Wilsen
Wilsey
Wilshire
Wilshusen
Wilson
Wilt
Wiltbank
Wiltberger
Wilterdink
Wiltfong
Wiltgen
Wiltjer
Wilton
Wiltrout
Wilts
Wiltse
Wiltsey
Wiltshire
Wiltsie
Wiltz
Wilund
Wilusz
Wiman
Wimber
Wimberley
Wimberly
Wimbish
Wimble
Wimbley
Wimbrow
Wimbs
Wimbush
Wimer
Wimes
Wimett
Wimmer
Wimpee
Wimpey
Wimpy
Wims
Wimsatt
Win
Winans
Winarski
Winberg
Winberry
Winborn
Winborne
Winburn
Winbush
Wincapaw
Wince
Winch
Winchel
Winchell
Winchenbach
Winchester
Winckler
Wind
Windam
Windauer
Windell
Winder
Winders
Windes
Windfield
Windham
Windholz
Windhorst
Windhurst
Windisch
Windish
Windland
Windle
Windler
Windley
Windly
Windmeyer
Windom
Windon
Windover
Windrow
Windschitl
Windsheimer
Windsor
Windus
Wine
Winebarger
Winebaugh
Wineberg
Winebrenner
Winegar
Winegard
Winegarden
Winegardner
Wineinger
Winek
Wineland
Wineman
Winemiller
Winer
Wines
Winesberry
Winesett
Winesickle
Winett
Winfield
Winford
Winfough
Winfred
Winfree
Winfrey
Wing
Wingard
Wingate
Winge
Wingeier
Wingenter
Winger
Wingerd
Wingerson
Wingert
Wingerter
Winget
Wingett
Wingfield
Wingham
Wingler
Wingo
Wingrove
Wings
Wingstrom
Winham
Winiarski
Winick
Winiecki
Winik
Winikoff
Winingear
Wininger
Wink
Winkel
Winkelbauer
Winkeljohn
Winkelman
Winkelmann
Winkelpleck
Winkels
Winkenwerder
Winker
Winkey
Winkfield
Winkle
Winkleblack
Winkleman
Winklepleck
Winkler
Winkles
Winkley
Winkowski
Winks
Winland
Winley
Winlock
Winn
Winne
Winnegan
Winnen
Winner
Winners
Winnett
Winnewisser
Winney
Winnicki
Winnie
Winnike
Winning
Winninger
Winningham
Winograd
Winokur
Winrich
Winrow
Wins
Winscott
Winsett
Winship
Winski
Winsky
Winslett
Winslette
Winsley
Winslow
Winsman
Winson
Winsor
Winstanley
Winstead
Winsted
Winston
Wint
Winter
Winterberg
Winterbottom
Winterfeld
Winterfeldt
Winterhalter
Winterholler
Winterling
Wintermantel
Wintermute
Winterroth
Winterrowd
Winters
Wintersmith
Wintersteen
Winterstein
Winterton
Winther
Winthrop
Wintjen
Wintle
Winton
Wintringham
Wintz
Winward
Winzelberg
Winzenried
Winzer
Winzler
Wion
Wipf
Wipfli
Wipperfurth
Wippert
Wipprecht
Wirch
Wire
Wirebaugh
Wireman
Wiren
Wires
Wirf
Wirfs
Wirght
Wirick
Wirkkala
Wironen
Wirsing
Wirt
Wirta
Wirtanen
Wirth
Wirtjes
Wirtz
Wirtzfeld
Wisbey
Wisch
Wischman
Wischmann
Wischmeier
Wischmeyer
Wischner
Wiscombe
Wiscount
Wisdom
Wise
Wisecarver
Wisecup
Wisehart
Wiseley
Wisell
Wisely
Wiseman
Wisenbaker
Wisener
Wisenor
Wiser
Wish
Wisham
Wishard
Wishart
Wisher
Wishman
Wishon
Wishum
Wisinger
Wisinski
Wisk
Wiskowski
Wisler
Wisley
Wislocki
Wisman
Wismer
Wisner
Wisneski
Wisnewski
Wisnieski
Wisniewski
Wisniowski
Wisnoski
Wisnosky
Wisnowski
Wison
Wisor
Wisotzkey
Wiss
Wisse
Wisseh
Wissel
Wisseman
Wisser
Wissing
Wissinger
Wissink
Wissler
Wissman
Wissmann
Wist
Wiste
Wisterman
Wiswall
Wiswell
Wisz
Wiszynski
Witaker
Witaszek
Witbeck
Witchard
Witcher
Witchey
Witcraft
Witczak
Witek
Witfield
Witham
Withee
Withem
Withenshaw
Witherbee
Witherell
Witherington
Witherite
Witherow
Withers
Witherspoon
Withey
Withfield
Withiam
Withington
Withrow
Withy
Witkop
Witkowski
Witkowsky
Witkus
Witman
Witmer
Witosky
Witry
Witschi
Witsell
Witt
Wittbrodt
Witte
Wittekind
Wittel
Wittels
Witten
Wittenberg
Wittenborn
Wittenbrink
Wittenburg
Wittenmyer
Witter
Witters
Witterstauter
Witthoeft
Witthoft
Witthuhn
Wittich
Wittie
Wittig
Witting
Wittke
Wittkop
Wittkopp
Wittler
Wittliff
Wittlin
Wittlinger
Wittman
Wittmann
Wittmer
Wittmeyer
Wittnebel
Wittner
Wittrock
Wittrup
Wittry
Witts
Wittstock
Wittstruck
Wittwer
Witty
Witucki
Witvoet
Witwer
Witz
Witzel
Witzke
Wiuff
Wix
Wixom
Wixon
Wixson
Wixted
Wiza
Wizar
Wizwer
Wlach
Wlazlowski
Wloch
Wlodarczyk
Wlodarek
Wlodyka
Wlosinski
Wmith
Wms
Wnek
Wnorowski
Wnuk
Wnukowski
Wobbe
Wobbleton
Wobig
Wobser
Wodarski
Wodicka
Wodskow
Woehl
Woehr
Woehrle
Woelfel
Woelfl
Woelfle
Woelk
Woelke
Woelzlein
Woeppel
Woerner
Woernle
Woessner
Woeste
Woester
Woetzel
Wofford
Wogan
Woge
Wohl
Wohld
Wohlenhaus
Wohler
Wohlers
Wohlert
Wohletz
Wohlfahrt
Wohlfarth
Wohlfeil
Wohlford
Wohlgemuth
Wohlrab
Wohlschlegel
Wohlwend
Wohlwendi
Wohner
Woitowitz
Woiwode
Wojciak
Wojcicki
Wojciechowski
Wojcik
Wojdak
Wojeik
Wojenski
Wojewoda
Wojick
Wojnar
Wojnaroski
Wojner
Wojnicki
Wojnowski
Wojtak
Wojtanik
Wojtanowski
Wojtas
Wojtaszek
Wojtczak
Wojtecki
Wojtkowski
Wojtowich
Wojtowicz
Wokwicz
Wolak
Wolanin
Wolanski
Wolansky
Wolaver
Wolbeck
Wolbert
Wolbrecht
Wolchesky
Wolcott
Wold
Wolden
Woldridge
Woldt
Wolery
Woleslagle
Wolever
Wolf
Wolfard
Wolfe
Wolfenbarger
Wolfenden
Wolfensperger
Wolfer
Wolfert
Wolfertz
Wolff
Wolffe
Wolfgang
Wolfgram
Wolfgramm
Wolfinbarger
Wolfing
Wolfinger
Wolfley
Wolfman
Wolford
Wolfram
Wolfred
Wolfrom
Wolfrum
Wolfsberger
Wolfson
Wolgamot
Wolgast
Wolhok
Wolin
Woline
Wolinski
Woliver
Wolk
Wolke
Wolken
Wolkow
Wolkowiecki
Wolkowski
Woll
Wollam
Wollan
Wollard
Wolle
Wollen
Wollenberg
Wollenburg
Woller
Wollert
Wolley
Wollin
Wollman
Wollmer
Wollmuth
Wollner
Wollschlager
Wollyung
Wolma
Wolman
Wolner
Wolnik
Wolny
Woloszczak
Woloszyn
Wolpe
Wolper
Wolpert
Wolsdorf
Wolsey
Wolske
Wolski
Wolsky
Wolslegel
Wolsted
Wolstenholme
Woltemath
Wolter
Wolters
Wolthuis
Woltjer
Woltman
Woltmann
Woltz
Wolven
Wolverton
Wolvin
Wolz
Wolzen
Womac
Womack
Wombacher
Womble
Wombles
Wombolt
Womeldorf
Womeldorff
Women
Womer
Wommack
Won
Wonder
Wonderling
Wonderly
Wonders
Wondoloski
Wondra
Wong
Wongus
Wonnacott
Wonser
Wonsik
Wontor
Woo
Woock
Wood
Woodal
Woodall
Woodand
Woodard
Woodbeck
Woodberry
Woodbridge
Woodburg
Woodburn
Woodbury
Woodby
Woodcock
Woodcox
Wooddell
Woode
Woodell
Wooden
Woodend
Wooderson
Woodert
Woodfield
Woodfin
Woodfolk
Woodford
Woodfork
Woodgate
Woodham
Woodhams
Woodhead
Woodhouse
Woodhull
Woodie
Woodin
Wooding
Woodington
Woodis
Woodka
Woodke
Woodland
Woodle
Woodlee
Woodley
Woodliff
Woodlin
Woodling
Woodlock
Woodly
Woodman
Woodmancy
Woodmansee
Woodmore
Woodrich
Woodridge
Woodring
Woodrome
Woodroof
Woodrow
Woodruff
Woodrum
Woods
Woodside
Woodsmall
Woodson
Woodward
Woodworth
Woody
Woodyard
Woofter
Wool
Woolard
Woolbright
Woolcock
Woolcott
Wooldridge
Woolem
Woolems
Woolen
Woolery
Woolever
Wooley
Wooleyhan
Woolf
Woolfolk
Woolford
Woolfrey
Woolhiser
Woolhouse
Woollard
Woollen
Woolley
Woolman
Woolridge
Wools
Woolsey
Woolson
Woolstenhulme
Woolston
Woolum
Woolums
Woolverton
Woolwine
Woolworth
Woomer
Woon
Woosley
Wooster
Wootan
Wooten
Wooters
Wooton
Wootten
Wootton
Wooward
Worbington
Worcester
Worchester
Word
Wordell
Worden
Wordlaw
Wordlow
Wordsworth
Worek
Worell
Worf
Worford
Work
Worker
Workinger
Workings
Workman
Workowski
Works
Worland
World
Worlds
Worley
Worlie
Worlow
Worm
Wormack
Worman
Wormely
Wormington
Wormley
Wormuth
Wormwood
Worn
Worner
Worobel
Worosz
Worrall
Worrel
Worrell
Worsell
Worsfold
Worsham
Worsley
Worst
Worstel
Worstell
Worster
Worth
Wortham
Worthan
Worthen
Worthey
Worthing
Worthington
Worthley
Worthy
Wortinger
Wortley
Wortman
Worton
Wortz
Wosher
Wosick
Woskobojnik
Woten
Wotring
Wotton
Woudenberg
Woulard
Woullard
Wouters
Wowk
Woy
Woyahn
Woytek
Woytowich
Woytowicz
Wozney
Wozniak
Woznick
Woznicki
Wozny
Wragg
Wragge
Wraggs
Wraight
Wrape
Wraspir
Wratchford
Wray
Wreath
Wrede
Wreede
Wren
Wrench
Wrenn
Wrenne
Wreyford
Wrich
Wride
Wriedt
Wright
Wrighten
Wrightington
Wrighton
Wrights
Wrightsel
Wrightsman
Wrigley
Wrinkle
Wrinkles
Wrinn
Wrisley
Wriston
Writer
Wrobbel
Wrobel
Wrobleski
Wroblewski
Wrobliski
Wroe
Wrona
Wronski
Wroten
Wrotten
Wrubel
Wruck
Wry
Wryals
Wrye
Wrynn
Wrzesien
Wrzesinski
Wu
Wubbel
Wubben
Wubbena
Wublin
Wubnig
Wucherer
Wuebker
Wuellenweber
Wuensch
Wuensche
Wuerth
Wuertz
Wuerz
Wuest
Wueste
Wuestenberg
Wuitschick
Wujcik
Wulf
Wulff
Wulffraat
Wulfing
Wulkan
Wun
Wunder
Wunderle
Wunderlich
Wunderlin
Wunderly
Wung
Wunner
Wunsch
Wuolle
Wuori
Wurdeman
Wurgler
Wurl
Wurm
Wurst
Wurster
Wurth
Wurts
Wurtz
Wurtzel
Wurz
Wurzbacher
Wurzer
Wussow
Wutzke
Wyand
Wyandt
Wyant
Wyatt
Wybenga
Wyble
Wyborny
Wyche
Wyckoff
Wycoff
Wycuff
Wydeven
Wydler
Wydner
Wydo
Wydra
Wydryck
Wyer
Wyers
Wyett
Wygal
Wygand
Wygant
Wygle
Wyke
Wyker
Wykes
Wykle
Wykoff
Wylam
Wyland
Wylde
Wyler
Wyles
Wylie
Wyllie
Wyly
Wyman
Wymer
Wymore
Wyms
Wynans
Wynder
Wyndham
Wyne
Wyner
Wynes
Wynia
Wynkoop
Wynn
Wynne
Wynott
Wynter
Wyont
Wyre
Wyrich
Wyrick
Wyrosdick
Wyrostek
Wyse
Wysinger
Wysock
Wysocki
Wysong
Wyss
Wytch
Wythe
Wyzard
Wyze
Wzorek
Xaimoungkhoun
Xander
Xang
Xavier
Xayasith
Xayavong
Xia
Xiang
Xiao
Xie
Ximenez
Ximines
Xiong
Xu
Xue
Xyong
Ya
Yablonski
Yablonsky
Yacano
Yacavone
Yaccarino
Yach
Yackel
Yackeren
Yackley
Yacko
Yacono
Yacoub
Yacovone
Yacullo
Yadao
Yaden
Yadon
Yaeger
Yaegle
Yaekel
Yafai
Yafaie
Yafei
Yaffe
Yaftali
Yafuso
Yagecic
Yager
Yaggi
Yagi
Yagin
Yagle
Yago
Yagoda
Yagoudaef
Yagues
Yahl
Yahn
Yahna
Yahne
Yahraus
Yaish
Yaiva
Yake
Yakel
Yaker
Yaklich
Yaklin
Yakow
Yakulis
Yale
Yalon
Yam
Yamada
Yamagata
Yamaguchi
Yamakawa
Yamaki
Yamamoto
Yamanaka
Yamane
Yamanoha
Yamaoka
Yamasaki
Yamashiro
Yamashita
Yamat
Yamauchi
Yamazaki
Yambao
Yambo
Yamin
Yamkosumpa
Yammine
Yamnitz
Yampolsky
Yan
Yanacek
Yanagawa
Yanagi
Yanagida
Yanagihara
Yanai
Yanan
Yance
Yancey
Yanchik
Yancik
Yancy
Yanda
Yandell
Yandle
Yandow
Yandura
Yanek
Yanes
Yanetta
Yaney
Yanez
Yang
Yanik
Yanish
Yanity
Yanke
Yankee
Yankey
Yanko
Yankovich
Yankovitch
Yankovitz
Yankovski
Yann
Yannantuono
Yannayon
Yanni
Yannone
Yannotti
Yannucci
Yannuzzi
Yanoff
Yanofsky
Yanos
Yanosky
Yant
Yantis
Yantz
Yantzer
Yantzi
Yanuaria
Yao
Yap
Yaple
Yapp
Yara
Yarber
Yarberry
Yarboro
Yarborough
Yarbough
Yarbro
Yarbrough
Yard
Yarde
Yardley
Yarger
Yarish
Yark
Yarman
Yarmitsky
Yarn
Yarnall
Yarnell
Yaroch
Yarosh
Yarrell
Yarrington
Yarris
Yarrito
Yarrow
Yarwood
Yarzabal
Yashinski
Yasika
Yasin
Yasinski
Yaskiewicz
Yasso
Yasuda
Yasui
Yasurek
Yasutake
Yasutomi
Yater
Yates
Yatsko
Yattaw
Yau
Yauch
Yauck
Yauger
Yaun
Yavorsky
Yaw
Yawn
Yaws
Yax
Yazdani
Yazzi
Yazzie
Yazzle
Yballe
Ybanez
Ybarbo
Ybarra
Ybarro
Ybos
Ydara
Ye
Yeadon
Yeager
Yeagley
Yeah
Yeakel
Yeakle
Yeakley
Yeaman
Yeamans
Yeaney
Yearby
Yearego
Yeargain
Yeargan
Yeargin
Yearick
Yearicks
Yearling
Yearous
Yearout
Yearsley
Yearta
Yearwood
Yeary
Yeast
Yeasted
Yeater
Yeates
Yeatman
Yeaton
Yeats
Yeatts
Yeboah
Yeck
Yeddo
Yedid
Yedinak
Yee
Yeeloy
Yeend
Yegge
Yeh
Yehl
Yehle
Yeilding
Yeiser
Yeisley
Yekel
Yeldell
Yelder
Yeldon
Yeley
Yelin
Yell
Yelle
Yellen
Yellock
Yellow
Yellowhair
Yelton
Yelverton
Yelvington
Yem
Yemchuk
Yen
Yendell
Yengich
Yenglin
Yengo
Yennard
Yenner
Yenney
Yenor
Yentsch
Yentzer
Yenz
Yeo
Yeoman
Yeomans
Yepes
Yepez
Yepiz
Yepsen
Yerbic
Yerbich
Yerby
Yerdon
Yerena
Yerger
Yergin
Yerhot
Yerian
Yerico
Yerigan
Yerka
Yerke
Yerkes
Yerkey
Yerkovich
Yerly
Yero
Yeropoli
Yerry
Yerton
Yerty
Yeske
Yeskey
Yessios
Yestramski
Yetman
Yetsko
Yett
Yetter
Yetto
Yetzer
Yeubanks
Yeung
Yewell
Yezek
Yglesias
Yi
Yidiaris
Yielding
Yilma
Yim
Yin
Ying
Yingling
Yingst
Yip
Yiu
Ylonen
Yngsdal
Yniguez
Ynocencio
Yo
Yoakum
Yoast
Yobst
Yocham
Yochem
Yochim
Yochum
Yocius
Yock
Yockers
Yockey
Yocom
Yocum
Yoder
Yoders
Yodis
Yoeckel
Yoes
Yoest
Yoh
Yohannes
Yohe
Yohn
Yoho
Yoke
Yokel
Yokely
Yokiel
Yokley
Yokota
Yokoyama
Yokum
Yomes
Yon
Yonamine
Yonan
Yonashiro
Yonce
Yoneda
Yonek
Yonemori
Yonemura
Yoneoka
Yoney
Yoneyama
Yong
Yonge
Yongue
Yonke
Yonker
Yonkers
Yonkoske
Yono
Yonts
Yontz
Yoo
Yoon
Yopp
Yoquelet
Yorck
Yordy
Yore
Yorgey
Yori
Yorio
York
Yorke
Yorker
Yorkey
Yorkman
Yorks
Yorn
Yorton
Yorty
Yoseph
Yoshi
Yoshida
Yoshihara
Yoshikawa
Yoshimori
Yoshimoto
Yoshimura
Yoshina
Yoshino
Yoshioka
Yoshiyama
Yoshizawa
Yoshizumi
Yosko
Yoss
Yost
Yosten
Yother
Yott
Yotter
You
Youd
Youell
Youkanaa
Youker
Youkers
Youket
Youkhana
Youla
Youmans
Youmon
Youn
Younan
Younce
Younes
Young
Youngberg
Youngblood
Youngblut
Youngdahl
Younge
Younger
Youngerman
Youngers
Younghans
Youngkin
Younglas
Younglove
Youngman
Youngquist
Youngren
Youngs
Youngstrom
Younie
Younis
Younker
Younkers
Younkin
Younkins
Youns
Yount
Younts
Youree
Yournet
Yourshaw
Youse
Yousef
Yousif
Yousko
Youssef
Youssefi
Youst
Youtsey
Yovan
Yovanovich
Yovino
Yow
Yowell
Yoxall
Yozamp
Yozzo
Ypina
Yragui
Yray
Yrigollen
Ysaguirre
Ysbrand
Yslas
Yslava
Ysquierdo
Ytuarte
Yu
Yuan
Yuasa
Yucha
Yudell
Yue
Yueh
Yuen
Yuenger
Yuengling
Yuhas
Yuhasz
Yuill
Yuk
Yuki
Yule
Yum
Yumas
Yun
Yunan
Yundt
Yunes
Yung
Yungbluth
Yungclas
Yunk
Yunker
Yunt
Yupe
Yurchak
Yurchiak
Yurek
Yurich
Yuricic
Yurick
Yurkanin
Yurko
Yurkovich
Yurman
Yuro
Yurovic
Yuscak
Yusef
Yusi
Yuska
Yusko
Yust
Yuste
Yusuf
Yutzy
Yuzn
Yvon
Yzaguirre
Yzaquirre
Yzquierdo
Zabala
Zabaneh
Zabarkes
Zabawa
Zabbo
Zabek
Zabel
Zabenko
Zabielski
Zabik
Zabinski
Zabka
Zable
Zablocki
Zablonski
Zabloudil
Zaborac
Zaborowski
Zaborski
Zabriskie
Zabrocki
Zacarias
Zacate
Zaccagnini
Zaccagnino
Zaccaria
Zaccaro
Zacchini
Zacek
Zach
Zachar
Zacharewicz
Zacharia
Zachariades
Zachariah
Zacharias
Zachary
Zacher
Zacherl
Zachery
Zachman
Zachmann
Zachry
Zachter
Zack
Zackery
Zaczek
Zadd
Zade
Zadeh
Zader
Zadina
Zador
Zadora
Zadorozny
Zadow
Zadra
Zadroga
Zadrozny
Zaeske
Zafar
Zaffalon
Zaffina
Zaffino
Zaffuto
Zagacki
Zagami
Zagar
Zagara
Zagel
Zagen
Zager
Zagorac
Zagorski
Zagroba
Zagrodnik
Zagulski
Zahar
Zaharchuk
Zaharek
Zaharis
Zahl
Zahler
Zahm
Zahn
Zahnen
Zahner
Zahniser
Zahnke
Zahnow
Zahorchak
Zahourek
Zahra
Zahradka
Zahradnik
Zahran
Zahri
Zaibel
Zaic
Zaidel
Zaidi
Zaino
Zais
Zaiser
Zaiss
Zaitlin
Zaituna
Zajac
Zajc
Zajdel
Zajicek
Zak
Zakar
Zakarian
Zaker
Zakes
Zaki
Zakowski
Zakrajsek
Zakrzewski
Zakutney
Zalamea
Zalar
Zalazar
Zaldana
Zaldivar
Zale
Zalenski
Zaleski
Zalesky
Zalewski
Zalk
Zall
Zaller
Zaloudek
Zaltz
Zalusky
Zalwsky
Zam
Zamacona
Zaman
Zamarripa
Zamarron
Zambarano
Zambelli
Zambito
Zambo
Zamborano
Zamborsky
Zambotti
Zambrana
Zambrano
Zammetti
Zammiello
Zamor
Zamora
Zamorano
Zamoro
Zamostny
Zampaglione
Zamparini
Zampedri
Zampella
Zamperini
Zampieri
Zamudio
Zamzam
Zamzow
Zan
Zana
Zanardi
Zanayed
Zancanella
Zanchez
Zanchi
Zanco
Zand
Zander
Zanderigo
Zanders
Zane
Zanella
Zaner
Zanes
Zaneski
Zanetti
Zanfardino
Zang
Zangara
Zangari
Zange
Zangger
Zanghi
Zangl
Zani
Zaniboni
Zanin
Zanini
Zanis
Zank
Zanni
Zannini
Zannino
Zanola
Zanotti
Zant
Zanter
Zantow
Zanueta
Zapalac
Zapanta
Zapata
Zapatas
Zapatero
Zapato
Zapel
Zapf
Zapico
Zapien
Zapoticky
Zapp
Zappa
Zappala
Zappavigna
Zappia
Zappile
Zappolo
Zappone
Zappulla
Zar
Zaragosa
Zaragoza
Zarate
Zarazua
Zarco
Zarcone
Zarebski
Zarek
Zarella
Zaremba
Zaremski
Zaren
Zaretsky
Zari
Zarilla
Zarillo
Zarin
Zaring
Zaritsky
Zarkin
Zarlenga
Zarlengo
Zarling
Zarlingo
Zarn
Zarnick
Zaro
Zarozinski
Zarr
Zarrabi
Zarraluqui
Zarrella
Zarriello
Zarrillo
Zarrineh
Zarro
Zart
Zartman
Zaruba
Zarucki
Zarycki
Zarzuela
Zarzycki
Zaspel
Zasso
Zastawny
Zastrow
Zatarain
Zatko
Zatorski
Zauala
Zaucha
Zaugg
Zaunbrecher
Zauner
Zausch
Zavacky
Zavadoski
Zavala
Zavaleta
Zavalza
Zavasky
Zavatson
Zavattieri
Zavcedo
Zaverl
Zavesky
Zavitz
Zavodny
Zawacki
Zawadzki
Zawasky
Zawislak
Zawistowski
Zaxas
Zaya
Zayac
Zayas
Zayicek
Zaza
Zazozdor
Zazueta
Zazula
Zbell
Zbierski
Zbikowski
Zbinden
Zboral
Zbranek
Zdanowicz
Zdenek
Zdon
Zdrojkowski
Zea
Zeagler
Zeals
Zeanah
Zearfoss
Zeavala
Zebel
Zebell
Zebley
Zebracki
Zebrowski
Zecca
Zeccardi
Zecchini
Zech
Zecher
Zeches
Zechiel
Zechman
Zeck
Zeckzer
Zedaker
Zedian
Zediker
Zee
Zeeb
Zeegers
Zeek
Zeeman
Zeff
Zega
Zegar
Zegarelli
Zegarra
Zeger
Zeh
Zehe
Zehender
Zeherquist
Zehnder
Zehner
Zehnpfennig
Zehr
Zehrbach
Zehrer
Zehring
Zeidan
Zeiders
Zeidler
Zeidman
Zeier
Zeiger
Zeigler
Zeiler
Zeilinger
Zeilman
Zeimantz
Zeimet
Zeimetz
Zeiner
Zeinert
Zeis
Zeise
Zeiser
Zeisler
Zeiss
Zeitler
Zeitlin
Zeitz
Zekria
Zelada
Zelasco
Zelasko
Zelaya
Zelazo
Zeldin
Zele
Zelechowski
Zeledon
Zelek
Zelenka
Zelenko
Zelenski
Zeleny
Zeleznik
Zeliff
Zelinka
Zelinski
Zelinsky
Zelkin
Zelkind
Zelko
Zell
Zella
Zellars
Zelle
Zellefrow
Zeller
Zellers
Zellinger
Zellman
Zellmann
Zellmer
Zellner
Zellous
Zelman
Zelmar
Zelnick
Zelonis
Zeltmann
Zeltner
Zema
Zemaitis
Zeman
Zematis
Zembower
Zeme
Zemel
Zeminski
Zemjanis
Zemke
Zemlicka
Zemon
Zempel
Zena
Zenbaver
Zendejas
Zender
Zener
Zeng
Zenger
Zeni
Zenisek
Zenk
Zenke
Zenker
Zenner
Zeno
Zenon
Zenor
Zens
Zent
Zenteno
Zentgraf
Zentner
Zents
Zentz
Zenz
Zenzen
Zeoli
Zeolla
Zepeda
Zepf
Zephier
Zephyr
Zepka
Zepp
Zera
Zeran
Zerangue
Zerba
Zerbe
Zerbel
Zerby
Zercher
Zerck
Zerger
Zerhusen
Zeringue
Zerkle
Zerko
Zermeno
Zerom
Zerphey
Zerr
Zerring
Zertuche
Zervas
Zervos
Zerzan
Zesati
Zeschke
Zetes
Zetina
Zetino
Zeto
Zets
Zettel
Zettlemoyer
Zettler
Zetzer
Zeuner
Zevallos
Zevenbergen
Zeyadeh
Zeyer
Zezima
Zgoda
Zhanel
Zhang
Zhao
Zhen
Zheng
Zhong
Zhou
Zhu
Zhuang
Zia
Ziad
Ziada
Ziadie
Ziak
Zibell
Zibelli
Zibert
Zic
Zicafoose
Zicari
Ziccardi
Zich
Zicherman
Zick
Zickefoose
Zicker
Zickler
Zickuhr
Zide
Zidek
Zidzik
Zieba
Ziebart
Ziebarth
Ziebell
Zieber
Ziebert
Ziebol
Ziebold
Ziech
Ziedan
Zieg
Ziegel
Ziegelbauer
Ziegenbein
Ziegenfuss
Ziegenhagen
Zieger
Zieglen
Ziegler
Ziego
Ziehm
Ziek
Ziel
Zieler
Zielesch
Zielinski
Zielke
Zielonka
Zielonko
Zieman
Ziemann
Ziemba
Ziemer
Ziemke
Ziems
Ziemski
Zien
Ziencina
Zientara
Zientek
Zier
Zierden
Zierdt
Zierenberg
Zierer
Zierk
Zierke
Ziernicki
Zieschang
Ziesemer
Zieser
Zieske
Ziesman
Ziesmer
Zietlow
Zietz
Ziff
Zigich
Ziglar
Zigler
Zigmond
Zigomalas
Zihal
Zike
Ziko
Zilahi
Ziler
Zilk
Zilka
Zill
Zilla
Ziller
Zilliox
Zillman
Zillmer
Zills
Zilnicki
Zima
Ziman
Zimba
Zimbelman
Zimerman
Zimick
Ziminski
Zimit
Zimlich
Zimm
Zimmel
Zimmer
Zimmerebner
Zimmerer
Zimmerle
Zimmerli
Zimmerly
Zimmerman
Zimmermann
Zin
Zinck
Zincke
Zinda
Zindel
Zindell
Zingale
Zingarelli
Zingaro
Zinger
Zingg
Zingler
Zingone
Ziniewicz
Zink
Zinke
Zinkievich
Zinkl
Zinn
Zinner
Zinni
Zinno
Zins
Zinser
Zinsli
Zinsmeister
Zinter
Zinz
Zinzow
Ziobro
Ziola
Ziolkowski
Zion
Zipay
Zipf
Zipfel
Zipkin
Zipp
Zippe
Zipperer
Zipse
Ziraldo
Zirbel
Zircher
Zirin
Zirk
Zirker
Zirkind
Zirkle
Zirkles
Zisk
Ziska
Zisser
Zissler
Zita
Ziter
Zito
Zittel
Zitzelberger
Zitzloff
Zitzmann
Zitzow
Ziv
Ziyad
Zizza
Zizzo
Zlaten
Zlatkin
Zlotnick
Zlotnik
Zmek
Zmich
Zmiejko
Zmijewski
Zmolek
Zmuda
Znidarsic
Zobel
Zobell
Zoch
Zocklein
Zoda
Zodrow
Zody
Zoebisch
Zoelle
Zoeller
Zoellick
Zoellner
Zogby
Zogg
Zoglmann
Zogopoulos
Zohn
Zola
Zoldak
Zoldesy
Zolezzi
Zolinas
Zolinski
Zoll
Zolla
Zollar
Zollars
Zoller
Zollicoffer
Zollinger
Zollman
Zollner
Zollo
Zolman
Zolnoske
Zolocsik
Zolondek
Zoltek
Zolty
Zomberg
Zombo
Zombory
Zombro
Zomer
Zomora
Zomorodi
Zona
Zondlo
Zone
Zonia
Zonker
Zook
Zoquier
Zorc
Zordan
Zorens
Zorich
Zorilla
Zorko
Zorman
Zorn
Zornes
Zorns
Zoroiwchak
Zorra
Zorrilla
Zortman
Zorzi
Zosel
Zoss
Zotos
Zotti
Zottola
Zou
Zoucha
Zoulek
Zoumis
Zourkos
Zoutte
Zozaya
Zrake
Zrimsek
Zsadanyi
Zschoche
Zsohar
Zuanich
Zuazo
Zubek
Zuber
Zuberbuhler
Zubia
Zubiate
Zubik
Zubizarreta
Zubke
Zubris
Zubrowski
Zubrzycki
Zucca
Zuccarelli
Zuccaro
Zucchetto
Zucco
Zucconi
Zuch
Zuchara
Zuchelkowski
Zuchowski
Zuck
Zucker
Zuckerberg
Zuckerman
Zuckerwar
Zuclich
Zuehl
Zuehlke
Zuehls
Zuehlsdorff
Zuelke
Zuercher
Zuerlein
Zufall
Zufelt
Zugg
Zuhlke
Zuidema
Zuk
Zukas
Zukerman
Zukof
Zukor
Zukoski
Zukowski
Zukowsky
Zulauf
Zuleger
Zulfer
Zulkowski
Zullig
Zullinger
Zullo
Zuluaga
Zumalt
Zumaya
Zumba
Zumbach
Zumbo
Zumbrennen
Zumbrunnen
Zummo
Zumot
Zumpano
Zumpfe
Zumsteg
Zumstein
Zumwalt
Zundel
Zunich
Zuniega
Zuniga
Zunino
Zunker
Zuno
Zupan
Zupancic
Zupfer
Zupp
Zuppa
Zurasky
Zurawik
Zurawski
Zurcher
Zurek
Zurheide
Zurich
Zurin
Zurita
Zurkuhlen
Zurkus
Zurmiller
Zurn
Zuro
Zurovec
Zurowski
Zusman
Zutell
Zutter
Zuver
Zuvich
Zuwkowski
Zuziak
Zvorsky
Zwack
Zwagerman
Zwahlen
Zwanzig
Zwart
Zweier
Zweifel
Zweig
Zwerschke
Zwick
Zwicker
Zwickl
Zwiebel
Zwiefel
Zwiefelhofer
Zwiener
Zwigart
Zwilling
Zwinger
Zwingman
Zwolak
Zwolensky
Zwolinski
Zwolski
Zybia
Zych
Zygmont
Zyla
Zylka
Zylstra
Zymowski
Zynda
Zysett
Zysk
Zyskowski
Zywiec
tools\dbatools\bin\dbatools-buildref-index.json
{
    "LastUpdated": "2018-12-19T00:00:00",
    "Data": [
    {
        "Version":  "8.0.47",
        "Name": "2000"
    },
    {
        "Version":  "8.0.78"
    },
    {
        "Version":  "8.0.100"
    },
    {
        "Version":  "8.0.190"
    },
    {
        "SP":  "RTM",
        "Version":  "8.0.194",
        "SupportedUntil":  "2000-11-30T00:00:00"
    },
    {
        "Version":  "8.0.204",
        "KBList":  "274329"
    },
    {
        "Version":  "8.0.205",
        "KBList":  "274330"
    },
    {
        "Version":  "8.0.210",
        "KBList":  "275900"
    },
    {
        "Version":  "8.0.211",
        "KBList":  "276329"
    },
    {
        "Version":  "8.0.217",
        "KBList":  "279293"
    },
    {
        "Version":  "8.0.218",
        "KBList":  "279183"
    },
    {
        "Version":  "8.0.222",
        "KBList":  "281769"
    },
    {
        "Version":  "8.0.223",
        "KBList":  "280380"
    },
    {
        "Version":  "8.0.225",
        "KBList":  "281663"
    },
    {
        "Version":  "8.0.226",
        "KBList":  "278239"
    },
    {
        "Version":  "8.0.231",
        "KBList":  "282279"
    },
    {
        "Version":  "8.0.233",
        "KBList":  "282416"
    },
    {
        "Version":  "8.0.239",
        "KBList":  "285290"
    },
    {
        "Version":  "8.0.249",
        "KBList":  "288122"
    },
    {
        "Version":  "8.0.250",
        "KBList":  "291683"
    },
    {
        "Version":  "8.0.251",
        "KBList":  "300194"
    },
    {
        "Version":  "8.0.287",
        "KBList":  "297209"
    },
    {
        "Version":  "8.0.296",
        "KBList":  "299717"
    },
    {
        "SP":  "SP1",
        "Version":  "8.0.384",
        "SupportedUntil":  "2002-02-28T00:00:00",
        "KBList":  "306908"
    },
    {
        "Version":  "8.0.428",
        "KBList":  "304850"
    },
    {
        "Version":  "8.0.443",
        "KBList":  "307538"
    },
    {
        "Version":  "8.0.444",
        "KBList":  [
                       "307655",
                       "30754"
                   ]
    },
    {
        "Version":  "8.0.452",
        "KBList":  "308547"
    },
    {
        "Version":  "8.0.469",
        "KBList":  "313005"
    },
    {
        "Version":  "8.0.471",
        "KBList":  "313302"
    },
    {
        "Version":  "8.0.473",
        "KBList":  "314003"
    },
    {
        "Version":  "8.0.474",
        "KBList":  "315395"
    },
    {
        "Version":  "8.0.475"
    },
    {
        "SP":  "SP2",
        "Version":  "8.0.532",
        "SupportedUntil":  "2003-04-07T00:00:00",
        "KBList":  "306908"
    },
    {
        "Version":  "8.0.534",
        "KBList":  "306908"
    },
    {
        "Version":  "8.0.552",
        "KBList":  [
                       "313002",
                       "313005"
                   ]
    },
    {
        "Version":  "8.0.558",
        "KBList":  [
                       "314003",
                       "315395"
                   ]
    },
    {
        "Version":  "8.0.561"
    },
    {
        "Version":  "8.0.568",
        "KBList":  "317748"
    },
    {
        "Version":  "8.0.578",
        "KBList":  [
                       "318405",
                       "317979"
                   ]
    },
    {
        "Version":  "8.0.584",
        "KBList":  "318530"
    },
    {
        "Version":  "8.0.594",
        "KBList":  [
                       "356774",
                       "319477"
                   ]
    },
    {
        "Version":  "8.0.599",
        "KBList":  "319869"
    },
    {
        "Version":  "8.0.604"
    },
    {
        "Version":  "8.0.608",
        "KBList":  "319507"
    },
    {
        "Version":  "8.0.644",
        "KBList":  "324186"
    },
    {
        "Version":  "8.0.650",
        "KBList":  "322853"
    },
    {
        "Version":  "8.0.652",
        "KBList":  "810010"
    },
    {
        "Version":  "8.0.655"
    },
    {
        "Version":  "8.0.661",
        "KBList":  "326999"
    },
    {
        "Version":  "8.0.665"
    },
    {
        "Version":  "8.0.667"
    },
    {
        "Version":  "8.0.678",
        "KBList":  "328354"
    },
    {
        "Version":  "8.0.679",
        "KBList":  "316333"
    },
    {
        "Version":  "8.0.682",
        "KBList":  "319851"
    },
    {
        "Version":  "8.0.686",
        "KBList":  "316333"
    },
    {
        "Version":  "8.0.688",
        "KBList":  "329487"
    },
    {
        "Version":  "8.0.689",
        "KBList":  "329499"
    },
    {
        "Version":  "8.0.690",
        "KBList":  "311104"
    },
    {
        "Version":  "8.0.693",
        "KBList":  "330212"
    },
    {
        "Version":  "8.0.695",
        "KBList":  [
                       "331965",
                       "331855"
                   ]
    },
    {
        "Version":  "8.0.696",
        "KBList":  [
                       "810052",
                       "810072"
                   ]
    },
    {
        "Version":  "8.0.700",
        "KBList":  "810072"
    },
    {
        "Version":  "8.0.701",
        "KBList":  [
                       "810163",
                       "810026"
                   ]
    },
    {
        "Version":  "8.0.702",
        "KBList":  "328551"
    },
    {
        "Version":  "8.0.703",
        "KBList":  "810526"
    },
    {
        "Version":  "8.0.705",
        "KBList":  "810920"
    },
    {
        "Version":  "8.0.710",
        "KBList":  "811052"
    },
    {
        "Version":  "8.0.713",
        "KBList":  "811205"
    },
    {
        "Version":  "8.0.714",
        "KBList":  "811478"
    },
    {
        "Version":  "8.0.715",
        "KBList":  [
                       "810688",
                       "811611"
                   ]
    },
    {
        "Version":  "8.0.718",
        "KBList":  "811703"
    },
    {
        "Version":  "8.0.721",
        "KBList":  [
                       "812393",
                       "81225"
                   ]
    },
    {
        "Version":  "8.0.723",
        "KBList":  "812798"
    },
    {
        "Version":  "8.0.725",
        "KBList":  [
                       "813494",
                       "812995"
                   ]
    },
    {
        "Version":  "8.0.728",
        "KBList":  "814460"
    },
    {
        "Version":  "8.0.730",
        "KBList":  "813769"
    },
    {
        "Version":  "8.0.733",
        "KBList":  "813759"
    },
    {
        "Version":  "8.0.735",
        "KBList":  "814889"
    },
    {
        "Version":  "8.0.736",
        "KBList":  "816937"
    },
    {
        "Version":  "8.0.741",
        "KBList":  "818096"
    },
    {
        "Version":  "8.0.743",
        "KBList":  [
                       "818406",
                       "818763"
                   ]
    },
    {
        "SP":  "SP3",
        "Version":  "8.0.760",
        "SupportedUntil":  "2007-07-10T00:00:00",
        "KBList":  "306908"
    },
    {
        "Version":  "8.0.762",
        "KBList":  "814032"
    },
    {
        "Version":  "8.0.763",
        "KBList":  "814113"
    },
    {
        "Version":  "8.0.765",
        "KBList":  [
                       "811611",
                       "810688",
                       "810163",
                       "813769"
                   ]
    },
    {
        "Version":  "8.0.769",
        "KBList":  [
                       "814892",
                       "814889"
                   ]
    },
    {
        "Version":  "8.0.775",
        "KBList":  "815115"
    },
    {
        "Version":  "8.0.779",
        "KBList":  "814035"
    },
    {
        "Version":  "8.0.780",
        "KBList":  [
                       "816084",
                       "816039",
                       "801185"
                   ]
    },
    {
        "Version":  "8.0.781",
        "KBList":  "815057"
    },
    {
        "Version":  "8.0.788",
        "KBList":  "816985"
    },
    {
        "Version":  "8.0.789",
        "KBList":  "816840"
    },
    {
        "Version":  "8.0.790",
        "KBList":  "817081"
    },
    {
        "Version":  "8.0.791",
        "KBList":  "815249"
    },
    {
        "Version":  "8.0.794",
        "KBList":  [
                       "817709",
                       "816440",
                       "813524",
                       "817464"
                   ]
    },
    {
        "Version":  "8.0.798",
        "KBList":  "817464"
    },
    {
        "Version":  "8.0.800",
        "KBList":  [
                       "818188",
                       "818097"
                   ]
    },
    {
        "Version":  "8.0.801",
        "KBList":  "181540"
    },
    {
        "Version":  "8.0.804",
        "KBList":  "818729"
    },
    {
        "Version":  "8.0.807",
        "KBList":  "818899"
    },
    {
        "Version":  "8.0.811",
        "KBList":  [
                       "891662",
                       "819248",
                       "818897"
                   ]
    },
    {
        "Version":  "8.0.814",
        "KBList":  "819662"
    },
    {
        "Version":  "8.0.816",
        "KBList":  "818766"
    },
    {
        "Version":  "8.0.818",
        "KBList":  [
                       "821280",
                       "826161",
                       "821277"
                   ]
    },
    {
        "Version":  "8.0.819",
        "KBList":  "826161"
    },
    {
        "Version":  "8.0.837",
        "KBList":  [
                       "823514",
                       "821740",
                       "821548",
                       "821741",
                       "820788"
                   ]
    },
    {
        "Version":  "8.0.839",
        "KBList":  [
                       "824027",
                       "823877"
                   ]
    },
    {
        "Version":  "8.0.840",
        "KBList":  "319477"
    },
    {
        "Version":  "8.0.841",
        "KBList":  "825225"
    },
    {
        "Version":  "8.0.842",
        "KBList":  "825043"
    },
    {
        "Version":  "8.0.844",
        "KBList":  "826080"
    },
    {
        "Version":  "8.0.845",
        "KBList":  [
                       "825854",
                       "826364"
                   ]
    },
    {
        "Version":  "8.0.847",
        "KBList":  "826433"
    },
    {
        "Version":  "8.0.848",
        "KBList":  "826822"
    },
    {
        "Version":  "8.0.850",
        "KBList":  [
                       "826906",
                       "826815",
                       "826860"
                   ]
    },
    {
        "Version":  "8.0.851",
        "KBList":  "826754"
    },
    {
        "Version":  "8.0.852",
        "KBList":  [
                       "827954",
                       "830466"
                   ]
    },
    {
        "Version":  "8.0.854",
        "KBList":  "828699"
    },
    {
        "Version":  "8.0.856",
        "KBList":  "828096"
    },
    {
        "Version":  "8.0.857",
        "KBList":  [
                       "828308",
                       "827714",
                       "828017"
                   ]
    },
    {
        "Version":  "8.0.858",
        "KBList":  "828637"
    },
    {
        "Version":  "8.0.859",
        "KBList":  "821334"
    },
    {
        "Version":  "8.0.863",
        "KBList":  [
                       "829444",
                       "829205"
                   ]
    },
    {
        "Version":  "8.0.865",
        "KBList":  [
                       "828945",
                       "830395"
                   ]
    },
    {
        "Version":  "8.0.866",
        "KBList":  "830366"
    },
    {
        "Version":  "8.0.869",
        "KBList":  "830588"
    },
    {
        "Version":  "8.0.870",
        "KBList":  "830262"
    },
    {
        "Version":  "8.0.871",
        "KBList":  [
                       "830860",
                       "830767"
                   ]
    },
    {
        "Version":  "8.0.873",
        "KBList":  "830887"
    },
    {
        "Version":  "8.0.876",
        "KBList":  [
                       "831997",
                       "830912"
                   ]
    },
    {
        "Version":  "8.0.878",
        "KBList":  "831950"
    },
    {
        "Version":  "8.0.879",
        "KBList":  "832977"
    },
    {
        "Version":  "8.0.891",
        "KBList":  "836141"
    },
    {
        "Version":  "8.0.892",
        "KBList":  "833710"
    },
    {
        "Version":  "8.0.904",
        "KBList":  "834453"
    },
    {
        "Version":  "8.0.908",
        "KBList":  "834290"
    },
    {
        "Version":  "8.0.910",
        "KBList":  "834798"
    },
    {
        "Version":  "8.0.911",
        "KBList":  "837957"
    },
    {
        "Version":  "8.0.913",
        "KBList":  "836651"
    },
    {
        "Version":  "8.0.915",
        "KBList":  "837401"
    },
    {
        "Version":  "8.0.916",
        "KBList":  "317989"
    },
    {
        "Version":  "8.0.919",
        "KBList":  "837957"
    },
    {
        "Version":  "8.0.922",
        "KBList":  "837970"
    },
    {
        "Version":  "8.0.923",
        "KBList":  "838460"
    },
    {
        "Version":  "8.0.926",
        "KBList":  "839523"
    },
    {
        "Version":  "8.0.927",
        "KBList":  "839688"
    },
    {
        "Version":  "8.0.928",
        "KBList":  "839589"
    },
    {
        "Version":  "8.0.929",
        "KBList":  "839529"
    },
    {
        "Version":  "8.0.933",
        "KBList":  "840856"
    },
    {
        "Version":  "8.0.934",
        "KBList":  "841404"
    },
    {
        "Version":  "8.0.935",
        "KBList":  "841404"
    },
    {
        "Version":  "8.0.936",
        "KBList":  "841627"
    },
    {
        "Version":  "8.0.937",
        "KBList":  "841776"
    },
    {
        "Version":  "8.0.944",
        "KBList":  "839280"
    },
    {
        "Version":  "8.0.948",
        "KBList":  "843263"
    },
    {
        "Version":  "8.0.949",
        "KBList":  "843266"
    },
    {
        "Version":  "8.0.952",
        "KBList":  [
                       "867880",
                       "867879",
                       "867878"
                   ]
    },
    {
        "Version":  "8.0.954",
        "KBList":  "843282"
    },
    {
        "Version":  "8.0.955",
        "KBList":  "867798"
    },
    {
        "Version":  "8.0.957",
        "KBList":  "870994"
    },
    {
        "Version":  "8.0.959",
        "KBList":  "878500"
    },
    {
        "Version":  "8.0.961",
        "KBList":  "873446"
    },
    {
        "Version":  "8.0.962",
        "KBList":  "883415"
    },
    {
        "Version":  "8.0.967",
        "KBList":  "878501"
    },
    {
        "Version":  "8.0.970",
        "KBList":  "872842"
    },
    {
        "Version":  "8.0.972",
        "KBList":  "885290"
    },
    {
        "Version":  "8.0.973",
        "KBList":  "884554"
    },
    {
        "Version":  "8.0.977",
        "KBList":  "888007"
    },
    {
        "Version":  "8.0.980",
        "KBList":  "887974"
    },
    {
        "Version":  "8.0.985",
        "KBList":  "889239"
    },
    {
        "Version":  "8.0.988",
        "KBList":  "889166"
    },
    {
        "Version":  "8.0.990",
        "KBList":  "890200"
    },
    {
        "Version":  "8.0.991",
        "KBList":  "889314"
    },
    {
        "Version":  "8.0.993",
        "KBList":  [
                       "890742",
                       "888444",
                       "890925"
                   ]
    },
    {
        "Version":  "8.0.994",
        "KBList":  [
                       "890767",
                       "890768",
                       "890942"
                   ]
    },
    {
        "Version":  "8.0.996",
        "KBList":  [
                       "891268",
                       "891017"
                   ]
    },
    {
        "Version":  "8.0.997",
        "KBList":  "891311"
    },
    {
        "Version":  "8.0.1000",
        "KBList":  "891585"
    },
    {
        "Version":  "8.0.1001",
        "KBList":  "892205"
    },
    {
        "Version":  "8.0.1003",
        "KBList":  "892923"
    },
    {
        "Version":  "8.0.1007",
        "KBList":  "893312"
    },
    {
        "Version":  "8.0.1009",
        "KBList":  "894257"
    },
    {
        "Version":  "8.0.1013",
        "KBList":  "891866"
    },
    {
        "Version":  "8.0.1014",
        "KBList":  [
                       "895187",
                       "895123"
                   ]
    },
    {
        "Version":  "8.0.1017",
        "KBList":  "896425"
    },
    {
        "Version":  "8.0.1019",
        "KBList":  "897572"
    },
    {
        "Version":  "8.0.1020",
        "KBList":  "896985"
    },
    {
        "Version":  "8.0.1021",
        "KBList":  "887700"
    },
    {
        "Version":  "8.0.1024",
        "KBList":  "898709"
    },
    {
        "Version":  "8.0.1025",
        "KBList":  [
                       "899430",
                       "899428"
                   ]
    },
    {
        "Version":  "8.0.1027",
        "KBList":  "900416"
    },
    {
        "Version":  "8.0.1029",
        "KBList":  "902852"
    },
    {
        "Version":  "8.0.1034",
        "KBList":  "915328"
    },
    {
        "Version":  "8.0.1035",
        "KBList":  "917593"
    },
    {
        "Version":  "8.0.1036",
        "KBList":  "929410"
    },
    {
        "Version":  "8.0.1037",
        "KBList":  "930484"
    },
    {
        "Version":  "8.0.1077",
        "KBList":  "983814"
    },
    {
        "Version":  "8.0.1547",
        "KBList":  "899410"
    },
    {
        "Version":  "8.0.2026"
    },
    {
        "SP":  [
                   "SP4",
                   "LATEST"
               ],
        "Version":  "8.0.2039",
        "SupportedUntil":  "2013-04-09T00:00:00",
        "KBList":  "306908"
    },
    {
        "Version":  "8.0.2040",
        "KBList":  "899761"
    },
    {
        "Version":  "8.0.2050",
        "KBList":  [
                       "941203",
                       "94811"
                   ]
    },
    {
        "Version":  "8.0.2055",
        "KBList":  "959240"
    },
    {
        "Version":  "8.0.2145",
        "KBList":  [
                       "826906",
                       "836651"
                   ]
    },
    {
        "Version":  "8.0.2147",
        "KBList":  "899410"
    },
    {
        "Version":  "8.0.2148",
        "KBList":  [
                       "899430",
                       "899431",
                       "900390",
                       "900404",
                       "901212",
                       "902150",
                       "902955"
                   ]
    },
    {
        "Version":  "8.0.2151",
        "KBList":  [
                       "903742",
                       "904244"
                   ]
    },
    {
        "Version":  "8.0.2156"
    },
    {
        "Version":  "8.0.2159",
        "KBList":  "907250"
    },
    {
        "Version":  "8.0.2162",
        "KBList":  "904660"
    },
    {
        "Version":  "8.0.2166",
        "KBList":  "909734"
    },
    {
        "Version":  "8.0.2168",
        "KBList":  "907813"
    },
    {
        "Version":  "8.0.2171",
        "KBList":  "909369"
    },
    {
        "Version":  "8.0.2172",
        "KBList":  "910707"
    },
    {
        "Version":  "8.0.2175",
        "KBList":  "911678"
    },
    {
        "Version":  "8.0.2180",
        "KBList":  [
                       "913684",
                       "913789"
                   ]
    },
    {
        "Version":  "8.0.2187",
        "KBList":  [
                       "916287",
                       "914384",
                       "898709",
                       "915065",
                       "915340"
                   ]
    },
    {
        "Version":  "8.0.2189",
        "KBList":  [
                       "916652",
                       "913438"
                   ]
    },
    {
        "Version":  "8.0.2191",
        "KBList":  [
                       "826906",
                       "836651"
                   ]
    },
    {
        "Version":  "8.0.2192",
        "KBList":  "917606"
    },
    {
        "Version":  "8.0.2194",
        "KBList":  [
                       "917972",
                       "917565"
                   ]
    },
    {
        "Version":  "8.0.2196",
        "KBList":  "919165"
    },
    {
        "Version":  "8.0.2197",
        "KBList":  [
                       "919133",
                       "919068",
                       "919399"
                   ]
    },
    {
        "Version":  "8.0.2199",
        "KBList":  "919221"
    },
    {
        "Version":  "8.0.2201",
        "KBList":  "920930"
    },
    {
        "Version":  "8.0.2207",
        "KBList":  "923344"
    },
    {
        "Version":  "8.0.2209",
        "KBList":  "923797"
    },
    {
        "Version":  "8.0.2215",
        "KBList":  [
                       "924662",
                       "923563",
                       "923796"
                   ]
    },
    {
        "Version":  "8.0.2217",
        "KBList":  "924664"
    },
    {
        "Version":  "8.0.2218",
        "KBList":  "925297"
    },
    {
        "Version":  "8.0.2223",
        "KBList":  [
                       "925678",
                       "925419"
                   ]
    },
    {
        "Version":  "8.0.2226",
        "KBList":  [
                       "925684",
                       "925732"
                   ]
    },
    {
        "Version":  "8.0.2229",
        "KBList":  "927186"
    },
    {
        "Version":  "8.0.2231",
        "KBList":  "928079"
    },
    {
        "Version":  "8.0.2232",
        "KBList":  "928568"
    },
    {
        "Version":  "8.0.2234",
        "KBList":  [
                       "929440",
                       "929131"
                   ]
    },
    {
        "Version":  "8.0.2236",
        "KBList":  "930484"
    },
    {
        "Version":  "8.0.2238",
        "KBList":  "931932"
    },
    {
        "Version":  "8.0.2242",
        "KBList":  "929131"
    },
    {
        "Version":  "8.0.2244",
        "KBList":  "934203"
    },
    {
        "Version":  "8.0.2245",
        "KBList":  "933573"
    },
    {
        "Version":  "8.0.2246",
        "KBList":  "935465"
    },
    {
        "Version":  "8.0.2248",
        "KBList":  "935950"
    },
    {
        "Version":  "8.0.2249",
        "KBList":  "936232"
    },
    {
        "Version":  "8.0.2253",
        "KBList":  "939317"
    },
    {
        "Version":  "8.0.2265",
        "KBList":  "944985"
    },
    {
        "Version":  "8.0.2271",
        "KBList":  "946584"
    },
    {
        "Version":  "8.0.2273",
        "KBList":  [
                       "941203",
                       "948111"
                   ]
    },
    {
        "Version":  "8.0.2279",
        "KBList":  "959678"
    },
    {
        "Version":  "8.0.2282",
        "KBList":  "960083"
    },
    {
        "Version":  "8.0.2283",
        "KBList":  "971524"
    },
    {
        "Version":  "8.0.2301",
        "KBList":  "983809"
    },
    {
        "Version":  "8.0.2305",
        "KBList":  "983811"
    },
    {
        "Version":  "9.0.0",
        "Name": "2005"
    },
    {
        "SP":  "RTM",
        "Version":  "9.0.1399",
        "SupportedUntil":  "2007-07-10T00:00:00"
    },
    {
        "Version":  "9.0.1406",
        "KBList":  "932557"
    },
    {
        "Version":  "9.0.1500",
        "KBList":  "910416"
    },
    {
        "Version":  "9.0.1502",
        "KBList":  "915793"
    },
    {
        "Version":  "9.0.1503",
        "KBList":  "911662"
    },
    {
        "Version":  "9.0.1514",
        "KBList":  "912471"
    },
    {
        "Version":  "9.0.1518",
        "KBList":  [
                       "913371",
                       "912472",
                       "913941"
                   ]
    },
    {
        "Version":  "9.0.1519",
        "KBList":  "913494"
    },
    {
        "Version":  "9.0.1528",
        "KBList":  [
                       "915122",
                       "915306",
                       "915307",
                       "915308",
                       "915309"
                   ]
    },
    {
        "Version":  "9.0.1531",
        "KBList":  "915918"
    },
    {
        "Version":  "9.0.1532",
        "KBList":  "916046"
    },
    {
        "Version":  "9.0.1533",
        "KBList":  "916086"
    },
    {
        "Version":  "9.0.1534",
        "KBList":  "916706"
    },
    {
        "Version":  "9.0.1536",
        "KBList":  "917016"
    },
    {
        "Version":  "9.0.1538",
        "KBList":  "917824"
    },
    {
        "Version":  "9.0.1539",
        "KBList":  "917738"
    },
    {
        "Version":  "9.0.1541",
        "KBList":  [
                       "917971",
                       "917888"
                   ]
    },
    {
        "Version":  "9.0.1545",
        "KBList":  "917905"
    },
    {
        "Version":  "9.0.1547",
        "KBList":  "918276"
    },
    {
        "Version":  "9.0.1550",
        "KBList":  [
                       "921106",
                       "917887"
                   ]
    },
    {
        "Version":  "9.0.1551",
        "KBList":  [
                       "922804",
                       "922527"
                   ]
    },
    {
        "Version":  "9.0.1554",
        "KBList":  "926292"
    },
    {
        "Version":  "9.0.1558",
        "KBList":  "926493"
    },
    {
        "Version":  "9.0.1561",
        "KBList":  "932556"
    },
    {
        "Version":  "9.0.2029"
    },
    {
        "Version":  "9.0.2040"
    },
    {
        "SP":  "SP1",
        "Version":  "9.0.2047",
        "SupportedUntil":  "2008-04-08T00:00:00",
        "KBList":  "913090"
    },
    {
        "Version":  "9.0.2050",
        "KBList":  "932555"
    },
    {
        "Version":  "9.0.2153",
        "KBList":  [
                       "919224",
                       "918222"
                   ]
    },
    {
        "Version":  "9.0.2156",
        "KBList":  "919611"
    },
    {
        "Version":  "9.0.2164",
        "KBList":  [
                       "919775",
                       "919636",
                       "918882",
                       "920206",
                       "921003",
                       "919929",
                       "920347",
                       "920346",
                       "919243"
                   ]
    },
    {
        "Version":  "9.0.2167",
        "KBList":  "920974"
    },
    {
        "Version":  "9.0.2174",
        "KBList":  "922063"
    },
    {
        "Version":  "9.0.2175",
        "KBList":  [
                       "921536",
                       "922438",
                       "922578",
                       "917905",
                       "921395"
                   ]
    },
    {
        "Version":  "9.0.2176",
        "KBList":  [
                       "923296",
                       "922594"
                   ]
    },
    {
        "Version":  "9.0.2181",
        "KBList":  [
                       "923634",
                       "923605"
                   ]
    },
    {
        "Version":  "9.0.2187",
        "KBList":  "923849"
    },
    {
        "Version":  "9.0.2189",
        "KBList":  "925153"
    },
    {
        "Version":  "9.0.2190",
        "KBList":  "925227"
    },
    {
        "Version":  "9.0.2191",
        "KBList":  "925135"
    },
    {
        "Version":  "9.0.2192",
        "KBList":  [
                       "925335",
                       "924954"
                   ]
    },
    {
        "Version":  "9.0.2194",
        "KBList":  "925744"
    },
    {
        "Version":  "9.0.2195",
        "KBList":  "926240"
    },
    {
        "Version":  "9.0.2196",
        "KBList":  [
                       "926335",
                       "926285"
                   ]
    },
    {
        "Version":  "9.0.2198",
        "KBList":  [
                       "925277",
                       "924808",
                       "926611",
                       "926773",
                       "926612",
                       "924624",
                       "924807",
                       "926106",
                       "926613"
                   ]
    },
    {
        "Version":  "9.0.2201",
        "KBList":  "927289"
    },
    {
        "Version":  "9.0.2202",
        "KBList":  "927643"
    },
    {
        "Version":  "9.0.2206",
        "KBList":  [
                       "928529",
                       "926493",
                       "928537",
                       "928083"
                   ]
    },
    {
        "Version":  "9.0.2207",
        "KBList":  [
                       "928789",
                       "928732",
                       "928394"
                   ]
    },
    {
        "Version":  "9.0.2208",
        "KBList":  "929179"
    },
    {
        "Version":  "9.0.2209",
        "KBList":  "929278"
    },
    {
        "Version":  "9.0.2211",
        "KBList":  [
                       "930283",
                       "930284"
                   ]
    },
    {
        "Version":  "9.0.2214",
        "KBList":  [
                       "929240",
                       "930505"
                   ]
    },
    {
        "Version":  "9.0.2216",
        "KBList":  "931821"
    },
    {
        "Version":  "9.0.2218",
        "KBList":  "931843"
    },
    {
        "Version":  "9.0.2219",
        "KBList":  "932115"
    },
    {
        "Version":  "9.0.2221",
        "KBList":  "931593"
    },
    {
        "Version":  "9.0.2223",
        "KBList":  "932393"
    },
    {
        "Version":  "9.0.2226",
        "KBList":  [
                       "933762",
                       "934065"
                   ]
    },
    {
        "Version":  "9.0.2227",
        "KBList":  "933265"
    },
    {
        "Version":  "9.0.2229",
        "KBList":  "935446"
    },
    {
        "Version":  "9.0.2230",
        "KBList":  "936179"
    },
    {
        "Version":  "9.0.2231",
        "KBList":  "934812"
    },
    {
        "Version":  "9.0.2232",
        "KBList":  "937277"
    },
    {
        "Version":  "9.0.2233",
        "KBList":  [
                       "937544",
                       "933499",
                       "937545"
                   ]
    },
    {
        "Version":  "9.0.2234",
        "KBList":  "937343"
    },
    {
        "Version":  "9.0.2236",
        "KBList":  [
                       "940286",
                       "940287"
                   ]
    },
    {
        "Version":  "9.0.2237",
        "KBList":  "940719"
    },
    {
        "Version":  "9.0.2239",
        "KBList":  "940961"
    },
    {
        "Version":  "9.0.2242",
        "KBList":  [
                       "943888",
                       "943389"
                   ]
    },
    {
        "Version":  "9.0.2243",
        "KBList":  "944968"
    },
    {
        "Version":  "9.0.2245",
        "KBList":  "933573"
    },
    {
        "Version":  "9.0.2249",
        "KBList":  "948344"
    },
    {
        "Version":  "9.0.3026",
        "KBList":  "929376"
    },
    {
        "Version":  "9.0.3027"
    },
    {
        "Version":  "9.0.3033"
    },
    {
        "SP":  "SP2",
        "Version":  "9.0.3042",
        "SupportedUntil":  "2010-01-12T00:00:00",
        "KBList":  "921896"
    },
    {
        "Version":  "9.0.3043",
        "KBList":  "933508"
    },
    {
        "Version":  "9.0.3050",
        "KBList":  "933508"
    },
    {
        "Version":  "9.0.3054",
        "KBList":  "934458"
    },
    {
        "Version":  "9.0.3068",
        "KBList":  "948109"
    },
    {
        "Version":  "9.0.3073",
        "KBList":  "954606"
    },
    {
        "Version":  "9.0.3077",
        "KBList":  "959420"
    },
    {
        "Version":  "9.0.3080",
        "KBList":  "970895"
    },
    {
        "Version":  "9.0.3152"
    },
    {
        "Version":  "9.0.3153",
        "KBList":  "937137"
    },
    {
        "Version":  "9.0.3154",
        "KBList":  "937137"
    },
    {
        "Version":  "9.0.3155",
        "KBList":  "937137"
    },
    {
        "Version":  "9.0.3156"
    },
    {
        "Version":  "9.0.3159"
    },
    {
        "Version":  "9.0.3161",
        "CU":  "CU1"
    },
    {
        "Version":  "9.0.3162",
        "KBList":  "937137"
    },
    {
        "Version":  "9.0.3166",
        "KBList":  "937137"
    },
    {
        "Version":  "9.0.3169",
        "KBList":  "937137"
    },
    {
        "Version":  "9.0.3171",
        "KBList":  "937745"
    },
    {
        "Version":  "9.0.3175",
        "CU":  "CU2"
    },
    {
        "Version":  "9.0.3177",
        "KBList":  "937137"
    },
    {
        "Version":  "9.0.3178",
        "KBList":  "937137"
    },
    {
        "Version":  "9.0.3179",
        "KBList":  "937137"
    },
    {
        "Version":  "9.0.3180",
        "KBList":  "939942"
    },
    {
        "Version":  "9.0.3182",
        "KBList":  "937137"
    },
    {
        "Version":  "9.0.3186",
        "CU":  "CU3"
    },
    {
        "Version":  "9.0.3194",
        "KBList":  "937137"
    },
    {
        "Version":  "9.0.3195"
    },
    {
        "Version":  "9.0.3200",
        "CU":  "CU4"
    },
    {
        "Version":  "9.0.3203",
        "KBList":  "937137"
    },
    {
        "Version":  "9.0.3205",
        "KBList":  "937137"
    },
    {
        "Version":  "9.0.3206"
    },
    {
        "Version":  "9.0.3208"
    },
    {
        "Version":  "9.0.3209"
    },
    {
        "Version":  "9.0.3215",
        "CU":  "CU5"
    },
    {
        "Version":  "9.0.3221",
        "KBList":  [
                       "942908",
                       "945442",
                       "945443",
                       "945916"
                   ]
    },
    {
        "Version":  "9.0.3222",
        "KBList":  [
                       "945640",
                       "945641",
                       "947196",
                       "947197"
                   ]
    },
    {
        "Version":  "9.0.3224",
        "KBList":  "947463"
    },
    {
        "Version":  "9.0.3228",
        "CU":  "CU6"
    },
    {
        "Version":  "9.0.3230",
        "KBList":  "949199"
    },
    {
        "Version":  "9.0.3231",
        "KBList":  [
                       "949595",
                       "949687"
                   ]
    },
    {
        "Version":  "9.0.3232",
        "KBList":  "949959"
    },
    {
        "Version":  "9.0.3233",
        "KBList":  "948108"
    },
    {
        "Version":  "9.0.3235",
        "KBList":  "950189"
    },
    {
        "Version":  "9.0.3239",
        "CU":  "CU7"
    },
    {
        "Version":  "9.0.3240",
        "KBList":  "951204"
    },
    {
        "Version":  "9.0.3242",
        "KBList":  "951190"
    },
    {
        "Version":  "9.0.3244",
        "KBList":  "952330"
    },
    {
        "Version":  "9.0.3246",
        "KBList":  "952233"
    },
    {
        "CU":  "CU8",
        "Version":  "9.0.3257",
        "KBList":  "951217"
    },
    {
        "Version":  "9.0.3259",
        "KBList":  [
                       "954669",
                       "954831"
                   ]
    },
    {
        "Version":  "9.0.3260",
        "KBList":  "954950"
    },
    {
        "Version":  "9.0.3282",
        "CU":  "CU9"
    },
    {
        "Version":  "9.0.3294",
        "CU":  "CU10"
    },
    {
        "CU":  "CU11",
        "Version":  "9.0.3301",
        "KBList":  "958735"
    },
    {
        "Version":  "9.0.3302",
        "KBList":  [
                       "961479",
                       "961648"
                   ]
    },
    {
        "Version":  "9.0.3303",
        "KBList":  "962290"
    },
    {
        "Version":  "9.0.3310",
        "KBList":  "960090"
    },
    {
        "CU":  "CU12",
        "Version":  "9.0.3315",
        "KBList":  "962970"
    },
    {
        "Version":  "9.0.3318",
        "KBList":  "967199"
    },
    {
        "Version":  "9.0.3320",
        "KBList":  "969142"
    },
    {
        "CU":  "CU13",
        "Version":  "9.0.3325",
        "KBList":  "967908"
    },
    {
        "Version":  "9.0.3327",
        "CU":  "CU14"
    },
    {
        "CU":  "CU15",
        "Version":  "9.0.3328",
        "KBList":  "970278"
    },
    {
        "Version":  "9.0.3353",
        "KBList":  "970896"
    },
    {
        "CU":  "CU16",
        "Version":  "9.0.3355",
        "KBList":  "974647"
    },
    {
        "CU":  "CU17",
        "Version":  "9.0.3356",
        "KBList":  "976952"
    },
    {
        "Version":  "9.0.4028"
    },
    {
        "SP":  "SP3",
        "Version":  "9.0.4035",
        "SupportedUntil":  "2012-01-10T00:00:00"
    },
    {
        "Version":  "9.0.4053",
        "KBList":  "970892"
    },
    {
        "Version":  "9.0.4060",
        "KBList":  "2494113"
    },
    {
        "Version":  "9.0.4207",
        "CU":  "CU1"
    },
    {
        "Version":  "9.0.4211",
        "CU":  "CU2"
    },
    {
        "Version":  "9.0.4216",
        "KBList":  "967101"
    },
    {
        "CU":  "CU3",
        "Version":  "9.0.4220",
        "KBList":  "967909"
    },
    {
        "Version":  "9.0.4224",
        "KBList":  "917606"
    },
    {
        "Version":  "9.0.4226",
        "CU":  "CU4"
    },
    {
        "CU":  "CU5",
        "Version":  "9.0.4230",
        "KBList":  "972511"
    },
    {
        "Version":  "9.0.4262",
        "KBList":  "970894"
    },
    {
        "CU":  "CU6",
        "Version":  "9.0.4266",
        "KBList":  "974648"
    },
    {
        "Version":  "9.0.4268",
        "KBList":  "977151"
    },
    {
        "CU":  "CU7",
        "Version":  "9.0.4273",
        "KBList":  "976951"
    },
    {
        "CU":  "CU8",
        "Version":  "9.0.4285",
        "KBList":  "978915"
    },
    {
        "CU":  "CU9",
        "Version":  "9.0.4294",
        "KBList":  "980176"
    },
    {
        "CU":  "CU10",
        "Version":  "9.0.4305",
        "KBList":  "983329"
    },
    {
        "CU":  "CU11",
        "Version":  "9.0.4309",
        "KBList":  "2258854"
    },
    {
        "CU":  "CU12",
        "Version":  "9.0.4311",
        "KBList":  "2345449"
    },
    {
        "CU":  "CU13",
        "Version":  "9.0.4315",
        "KBList":  "2438344"
    },
    {
        "CU":  "CU14",
        "Version":  "9.0.4317",
        "KBList":  "2489375"
    },
    {
        "CU":  "CU15",
        "Version":  "9.0.4325",
        "KBList":  "2507766"
    },
    {
        "Version":  "9.0.4340",
        "KBList":  "2494112"
    },
    {
        "Version":  "9.0.4912"
    },
    {
        "SP":  [
                   "SP4",
                   "LATEST"
               ],
        "Version":  "9.0.5000",
        "SupportedUntil":  "2016-04-12T00:00:00",
        "KBList":  "2463332"
    },
    {
        "Version":  "9.0.5057",
        "KBList":  "2494120"
    },
    {
        "Version":  "9.0.5069",
        "KBList":  "2716429"
    },
    {
        "CU":  "CU1",
        "Version":  "9.0.5254",
        "KBList":  "2464079"
    },
    {
        "CU":  "CU2",
        "Version":  "9.0.5259",
        "KBList":  "2489409"
    },
    {
        "CU":  "CU3",
        "Version":  "9.0.5266",
        "KBList":  "2507769"
    },
    {
        "Version":  "9.0.5292",
        "KBList":  "2494123"
    },
    {
        "Version":  "9.0.5294",
        "KBList":  "2572407"
    },
    {
        "Version":  "9.0.5295",
        "KBList":  "2598903"
    },
    {
        "Version":  "9.0.5296",
        "KBList":  "2615425"
    },
    {
        "Version":  "9.0.5324",
        "KBList":  "2716427"
    },
    {
        "Version":  "10.0.0",
        "Name": "2008"
    },
    {
        "Version":  "10.0.1019"
    },
    {
        "Version":  "10.0.1049"
    },
    {
        "Version":  "10.0.1075"
    },
    {
        "Version":  "10.0.1300"
    },
    {
        "Version":  "10.0.1442"
    },
    {
        "SP":  "RTM",
        "Version":  "10.0.1600",
        "SupportedUntil":  "2010-04-13T00:00:00"
    },
    {
        "Version":  "10.0.1750",
        "KBList":  "956718"
    },
    {
        "Version":  "10.0.1755",
        "KBList":  "957387"
    },
    {
        "CU":  "CU1",
        "Version":  "10.0.1763",
        "KBList":  "956717"
    },
    {
        "Version":  "10.0.1767",
        "KBList":  "958208"
    },
    {
        "Version":  "10.0.1771",
        "KBList":  "958611"
    },
    {
        "CU":  "CU2",
        "Version":  "10.0.1779",
        "KBList":  "958186"
    },
    {
        "CU":  "CU3",
        "Version":  "10.0.1787",
        "KBList":  "960484"
    },
    {
        "CU":  "CU4",
        "Version":  "10.0.1798",
        "KBList":  "963036"
    },
    {
        "CU":  "CU5",
        "Version":  "10.0.1806",
        "KBList":  "969531"
    },
    {
        "CU":  "CU6",
        "Version":  "10.0.1812",
        "KBList":  "971490"
    },
    {
        "CU":  "CU7",
        "Version":  "10.0.1818",
        "KBList":  "973601"
    },
    {
        "CU":  "CU8",
        "Version":  "10.0.1823",
        "KBList":  "975976"
    },
    {
        "CU":  "CU9",
        "Version":  "10.0.1828",
        "KBList":  "977444"
    },
    {
        "CU":  "CU10",
        "Version":  "10.0.1835",
        "KBList":  "979064"
    },
    {
        "Version":  "10.0.2520",
        "KBList":  "968369"
    },
    {
        "SP":  "SP1",
        "Version":  "10.0.2531",
        "SupportedUntil":  "2011-10-11T00:00:00",
        "KBList":  "968369"
    },
    {
        "Version":  "10.0.2573",
        "KBList":  "2494096"
    },
    {
        "CU":  "CU1",
        "Version":  "10.0.2710",
        "KBList":  "969099"
    },
    {
        "Version":  "10.0.2712",
        "KBList":  "970507"
    },
    {
        "CU":  "CU2",
        "Version":  "10.0.2714",
        "KBList":  "970315"
    },
    {
        "CU":  "CU3",
        "Version":  "10.0.2723",
        "KBList":  "971491"
    },
    {
        "CU":  "CU4",
        "Version":  "10.0.2734",
        "KBList":  "973602"
    },
    {
        "Version":  "10.0.2740",
        "KBList":  "976761"
    },
    {
        "CU":  "CU5",
        "Version":  "10.0.2746",
        "KBList":  "975977"
    },
    {
        "CU":  "CU6",
        "Version":  "10.0.2757",
        "KBList":  "977443"
    },
    {
        "CU":  "CU7",
        "Version":  "10.0.2766",
        "KBList":  "979065"
    },
    {
        "CU":  "CU8",
        "Version":  "10.0.2775",
        "KBList":  "981702"
    },
    {
        "Version":  "10.0.2787",
        "KBList":  "2231277"
    },
    {
        "CU":  "CU9",
        "Version":  "10.0.2789",
        "KBList":  "2083921"
    },
    {
        "CU":  "CU10",
        "Version":  "10.0.2799",
        "KBList":  "2279604"
    },
    {
        "CU":  "CU11",
        "Version":  "10.0.2804",
        "KBList":  "2413738"
    },
    {
        "CU":  "CU12",
        "Version":  "10.0.2808",
        "KBList":  "2467236"
    },
    {
        "CU":  "CU13",
        "Version":  "10.0.2816",
        "KBList":  "2497673"
    },
    {
        "CU":  "CU14",
        "Version":  "10.0.2821",
        "KBList":  "2527187"
    },
    {
        "Version":  "10.0.2841"
    },
    {
        "CU":  "CU15",
        "Version":  "10.0.2847",
        "KBList":  "2555406"
    },
    {
        "CU":  "CU16",
        "Version":  "10.0.2850",
        "KBList":  "2582282"
    },
    {
        "Version":  "10.0.3798",
        "KBList":  "979450"
    },
    {
        "SP":  "SP2",
        "Version":  "10.0.4000",
        "SupportedUntil":  "2012-10-09T00:00:00",
        "KBList":  "979450"
    },
    {
        "Version":  "10.0.4064",
        "KBList":  "2494088"
    },
    {
        "Version":  "10.0.4067",
        "KBList":  "2716434"
    },
    {
        "CU":  "CU1",
        "Version":  "10.0.4266",
        "KBList":  "2289254"
    },
    {
        "CU":  "CU2",
        "Version":  "10.0.4272",
        "KBList":  "2467239"
    },
    {
        "CU":  "CU3",
        "Version":  "10.0.4279",
        "KBList":  "2498535"
    },
    {
        "CU":  "CU4",
        "Version":  "10.0.4285",
        "KBList":  "2527180"
    },
    {
        "CU":  "CU5",
        "Version":  "10.0.4316",
        "KBList":  "2555408"
    },
    {
        "CU":  "CU6",
        "Version":  "10.0.4321",
        "KBList":  "2582285"
    },
    {
        "CU":  "CU7",
        "Version":  "10.0.4323",
        "KBList":  "2617148"
    },
    {
        "CU":  "CU8",
        "Version":  "10.0.4326",
        "KBList":  "2648096"
    },
    {
        "CU":  "CU9",
        "Version":  "10.0.4330",
        "KBList":  "2402659"
    },
    {
        "CU":  "CU10",
        "Version":  "10.0.4332",
        "KBList":  "2696625"
    },
    {
        "CU":  "CU11",
        "Version":  "10.0.4333",
        "KBList":  "2715951"
    },
    {
        "Version":  "10.0.4371",
        "KBList":  "2716433"
    },
    {
        "Version":  "10.0.5416",
        "KBList":  "2546945"
    },
    {
        "SP":  "SP3",
        "Version":  "10.0.5500",
        "SupportedUntil":  "2015-10-13T00:00:00",
        "KBList":  "2546951"
    },
    {
        "Version":  "10.0.5512",
        "KBList":  "2716436"
    },
    {
        "Version":  "10.0.5520",
        "KBList":  "2977321"
    },
    {
        "Version":  "10.0.5538",
        "KBList":  "3045305"
    },
    {
        "Version":  "10.0.5544",
        "KBList":  "3135244"
    },
    {
        "CU":  "CU1",
        "Version":  "10.0.5766",
        "KBList":  "2617146"
    },
    {
        "CU":  "CU2",
        "Version":  "10.0.5768",
        "KBList":  "2633143"
    },
    {
        "CU":  "CU3",
        "Version":  "10.0.5770",
        "KBList":  "2648098"
    },
    {
        "CU":  "CU4",
        "Version":  "10.0.5775",
        "KBList":  "2673383"
    },
    {
        "CU":  "CU5",
        "Version":  "10.0.5785",
        "KBList":  "2696626"
    },
    {
        "CU":  "CU6",
        "Version":  "10.0.5788",
        "KBList":  "271953"
    },
    {
        "CU":  "CU7",
        "Version":  "10.0.5794",
        "KBList":  "2738350"
    },
    {
        "Version":  "10.0.5826",
        "KBList":  "2716435"
    },
    {
        "CU":  "CU8",
        "Version":  "10.0.5828",
        "KBList":  "2771833"
    },
    {
        "CU":  "CU9",
        "Version":  "10.0.5829",
        "KBList":  "2799883"
    },
    {
        "Version":  "10.0.5835",
        "KBList":  "2814783"
    },
    {
        "CU":  "CU10",
        "Version":  "10.0.5840",
        "KBList":  "2834048"
    },
    {
        "CU":  "CU11",
        "Version":  "10.0.5841",
        "KBList":  "2834048"
    },
    {
        "CU":  "CU12",
        "Version":  "10.0.5844",
        "KBList":  "2863205"
    },
    {
        "CU":  "CU13",
        "Version":  "10.0.5846",
        "KBList":  "2880350"
    },
    {
        "CU":  "CU14",
        "Version":  "10.0.5848",
        "KBList":  "2893410"
    },
    {
        "CU":  "CU15",
        "Version":  "10.0.5850",
        "KBList":  "2923520"
    },
    {
        "CU":  "CU16",
        "Version":  "10.0.5852",
        "KBList":  "2936421"
    },
    {
        "CU":  "CU17",
        "Version":  "10.0.5861",
        "KBList":  "2958696"
    },
    {
        "Version":  "10.0.5867",
        "KBList":  "2877204"
    },
    {
        "Version":  "10.0.5869",
        "KBList":  "2977322"
    },
    {
        "Version":  "10.0.5890",
        "KBList":  "3045303"
    },
    {
        "Version":  "10.0.5894",
        "KBList":  "3135244"
    },
    {
        "SP":  [
                   "SP4",
                   "LATEST"
               ],
        "Version":  "10.0.6000",
        "SupportedUntil":  "2019-07-09T00:00:00",
        "KBList":  "2979596"
    },
    {
        "Version":  "10.0.6241",
        "KBList":  "3045311"
    },
    {
        "Version":  "10.0.6526",
        "KBList":  "3034373"
    },
    {
        "Version":  "10.0.6535",
        "KBList":  "3045308"
    },
    {
        "Version":  "10.0.6543",
        "KBList":  "3135244"
    },
    {
        "Version":  "10.0.6547",
        "KBList":  "3146034"
    },
    {
        "Version": "10.0.6556",
        "KBList": "4057114"
    },
    {
        "Version":  "10.50.1092",
        "Name": "2008R2"
    },
    {
        "Version":  "10.50.1352"
    },
    {
        "SP":  "RTM",
        "Version":  "10.50.1600",
        "SupportedUntil":  "2012-07-10T00:00:00"
    },
    {
        "Version":  "10.50.1617",
        "KBList":  "2494088"
    },
    {
        "CU":  "CU1",
        "Version":  "10.50.1702",
        "KBList":  "981355"
    },
    {
        "CU":  "CU2",
        "Version":  "10.50.1720",
        "KBList":  "2072493"
    },
    {
        "CU":  "CU3",
        "Version":  "10.50.1734",
        "KBList":  "2261464"
    },
    {
        "CU":  "CU4",
        "Version":  "10.50.1746",
        "KBList":  "2345451"
    },
    {
        "CU":  "CU5",
        "Version":  "10.50.1753",
        "KBList":  "2438347"
    },
    {
        "CU":  "CU6",
        "Version":  "10.50.1765",
        "KBList":  "2489376"
    },
    {
        "Version":  "10.50.1769",
        "KBList":  "2520808"
    },
    {
        "CU":  "CU7",
        "Version":  "10.50.1777",
        "KBList":  "2507770"
    },
    {
        "Version":  "10.50.1790",
        "KBList":  "2494086"
    },
    {
        "CU":  "CU8",
        "Version":  "10.50.1797",
        "KBList":  "2534352"
    },
    {
        "Version":  "10.50.1804",
        "KBList":  "2567713"
    },
    {
        "CU":  "CU9",
        "Version":  "10.50.1807",
        "KBList":  "2591746"
    },
    {
        "CU":  "CU10",
        "Version":  "10.50.1809",
        "KBList":  "2633145"
    },
    {
        "CU":  "CU11",
        "Version":  "10.50.1810",
        "KBList":  "2659692"
    },
    {
        "CU":  "CU12",
        "Version":  "10.50.1815",
        "KBList":  "2679366"
    },
    {
        "CU":  "CU13",
        "Version":  "10.50.1817",
        "KBList":  "2703280"
    },
    {
        "CU":  "CU14",
        "Version":  "10.50.2425",
        "KBList":  "2463333"
    },
    {
        "SP":  "SP1",
        "Version":  "10.50.2500",
        "SupportedUntil":  "2013-10-08T00:00:00",
        "KBList":  "2528583"
    },
    {
        "Version":  "10.50.2550",
        "KBList":  "27116440"
    },
    {
        "CU":  "CU1",
        "Version":  "10.50.2769",
        "KBList":  "2544793"
    },
    {
        "CU":  "CU2",
        "Version":  "10.50.2772",
        "KBList":  "2567714"
    },
    {
        "Version":  "10.50.2776"
    },
    {
        "CU":  "CU3",
        "Version":  "10.50.2789",
        "KBList":  "2591748"
    },
    {
        "CU":  "CU4",
        "Version":  "10.50.2796",
        "KBList":  "2633146"
    },
    {
        "Version":  "10.50.2799"
    },
    {
        "CU":  "CU5",
        "Version":  "10.50.2806",
        "KBList":  "2659694"
    },
    {
        "Version":  "10.50.2807"
    },
    {
        "CU":  "CU6",
        "Version":  "10.50.2811",
        "KBList":  "2679367"
    },
    {
        "CU":  "CU7",
        "Version":  "10.50.2817",
        "KBList":  "2703282"
    },
    {
        "CU":  "CU8",
        "Version":  "10.50.2822",
        "KBList":  "2723743"
    },
    {
        "Version":  "10.50.2861",
        "KBList":  "2716439"
    },
    {
        "CU":  "CU9",
        "Version":  "10.50.2866",
        "KBList":  "2756574"
    },
    {
        "CU":  "CU10",
        "Version":  "10.50.2868",
        "KBList":  "2783135"
    },
    {
        "CU":  "CU11",
        "Version":  "10.50.2869",
        "KBList":  "2812683"
    },
    {
        "CU":  "CU12",
        "Version":  "10.50.2874",
        "KBList":  "2828727"
    },
    {
        "CU":  "CU13",
        "Version":  "10.50.2876",
        "KBList":  "2855792"
    },
    {
        "Version":  "10.50.2881",
        "KBList":  "2868244"
    },
    {
        "Version":  "10.50.3720",
        "KBList":  "2630455"
    },
    {
        "SP":  "SP2",
        "Version":  "10.50.4000",
        "SupportedUntil":  "2015-10-13T00:00:00",
        "KBList":  "2630458"
    },
    {
        "Version":  "10.50.4033",
        "KBList":  "2977320"
    },
    {
        "Version":  "10.50.4042",
        "KBList":  "3045313"
    },
    {
        "CU":  "CU1",
        "Version":  "10.50.4260",
        "KBList":  "2720425"
    },
    {
        "CU":  "CU2",
        "Version":  "10.50.4263",
        "KBList":  "2740411"
    },
    {
        "CU":  "CU3",
        "Version":  "10.50.4266",
        "KBList":  "2754552"
    },
    {
        "CU":  "CU4",
        "Version":  "10.50.4270",
        "KBList":  "2777358"
    },
    {
        "CU":  "CU5",
        "Version":  "10.50.4276",
        "KBList":  "2797460"
    },
    {
        "Version":  "10.50.4279",
        "KBList":  "2830140"
    },
    {
        "CU":  "CU6",
        "Version":  "10.50.4285",
        "KBList":  "2830140"
    },
    {
        "CU":  "CU7",
        "Version":  "10.50.4286",
        "KBList":  "2844090"
    },
    {
        "CU":  "CU8",
        "Version":  "10.50.4290",
        "KBList":  "2871401"
    },
    {
        "CU":  "CU9",
        "Version":  "10.50.4295",
        "KBList":  "2887606"
    },
    {
        "CU":  "CU10",
        "Version":  "10.50.4297",
        "KBList":  "2908087"
    },
    {
        "CU":  "CU11",
        "Version":  "10.50.4302",
        "KBList":  "2926028"
    },
    {
        "CU":  "CU12",
        "Version":  "10.50.4305",
        "KBList":  "2938478"
    },
    {
        "CU":  "CU13",
        "Version":  "10.50.4319",
        "KBList":  "2967540"
    },
    {
        "Version":  "10.50.4339",
        "KBList":  "3045312"
    },
    {
        "Version":  "10.50.4343",
        "KBList":  "3135244"
    },
    {
        "SP":  [
                   "SP3",
                   "LATEST"
               ],
        "Version":  "10.50.6000",
        "SupportedUntil":  "2019-07-09T00:00:00",
        "KBList":  "2979597"
    },
    {
        "Version":  "10.50.6220",
        "KBList":  "3045316"
    },
    {
        "Version":  "10.50.6525",
        "KBList":  "3033860"
    },
    {
        "Version":  "10.50.6529",
        "KBList":  "3045314"
    },
    {
        "Version":  "10.50.6537",
        "KBList":  "3135244"
    },
    {
        "Version":  "10.50.6542",
        "KBList":  "3146034"
    },
    {
        "Version": "10.50.6560",
        "KBList": "4057113"
    },
    {
        "Version":  "11.0.1103",
        "Name": "2012"
    },
    {
        "Version":  "11.0.1440"
    },
    {
        "Version":  "11.0.1750"
    },
    {
        "Version":  "11.0.1913"
    },
    {
        "SP":  "RTM",
        "Version":  "11.0.2100",
        "SupportedUntil":  "2014-01-14T00:00:00"
    },
    {
        "Version":  "11.0.2214",
        "KBList":  "2685308"
    },
    {
        "Version":  "11.0.2218",
        "KBList":  "2716442"
    },
    {
        "CU":  "CU1",
        "Version":  "11.0.2316",
        "KBList":  "2679368"
    },
    {
        "CU":  "CU2",
        "Version":  "11.0.2325",
        "KBList":  "2703275"
    },
    {
        "CU":  "CU3",
        "Version":  "11.0.2332",
        "KBList":  "2723749"
    },
    {
        "Version":  "11.0.2376",
        "KBList":  "2716441"
    },
    {
        "CU":  "CU4",
        "Version":  "11.0.2383",
        "KBList":  "2758687"
    },
    {
        "CU":  "CU5",
        "Version":  "11.0.2395",
        "KBList":  "2777772"
    },
    {
        "CU":  "CU6",
        "Version":  "11.0.2401",
        "KBList":  "2728897"
    },
    {
        "CU":  "CU7",
        "Version":  "11.0.2405",
        "KBList":  "2823247"
    },
    {
        "CU":  "CU8",
        "Version":  "11.0.2410",
        "KBList":  "2844205"
    },
    {
        "CU":  "CU9",
        "Version":  "11.0.2419",
        "KBList":  "2867319"
    },
    {
        "CU":  "CU10",
        "Version":  "11.0.2420",
        "KBList":  "2891666"
    },
    {
        "CU":  "CU11",
        "Version":  "11.0.2424",
        "KBList":  "2908007"
    },
    {
        "Version":  "11.0.2809"
    },
    {
        "Version":  "11.0.2845"
    },
    {
        "SP":  "SP1",
        "Version":  "11.0.3000",
        "SupportedUntil":  "2015-07-14T00:00:00",
        "KBList":  "2674319"
    },
    {
        "Version":  "11.0.3128",
        "KBList":  "2793634"
    },
    {
        "Version":  "11.0.3153",
        "KBList":  "2977326"
    },
    {
        "Version":  "11.0.3156",
        "KBList":  "3045318"
    },
    {
        "CU":  "CU1",
        "Version":  "11.0.3321",
        "KBList":  "2765331"
    },
    {
        "Version":  "11.0.3335",
        "KBList":  "2800050"
    },
    {
        "CU":  "CU2",
        "Version":  "11.0.3339",
        "KBList":  "2790947"
    },
    {
        "CU":  "CU3",
        "Version":  "11.0.3349",
        "KBList":  "2812412"
    },
    {
        "Version":  "11.0.3350",
        "KBList":  "2832017"
    },
    {
        "CU":  "CU4",
        "Version":  "11.0.3368",
        "KBList":  "2833645"
    },
    {
        "CU":  "CU5",
        "Version":  "11.0.3373",
        "KBList":  "2861107"
    },
    {
        "CU":  "CU6",
        "Version":  "11.0.3381",
        "KBList":  "2874879"
    },
    {
        "CU":  "CU7",
        "Version":  "11.0.3393",
        "KBList":  "2894115"
    },
    {
        "CU":  "CU8",
        "Version":  "11.0.3401",
        "KBList":  "2917531"
    },
    {
        "CU":  "CU9",
        "Version":  "11.0.3412",
        "KBList":  "2931078"
    },
    {
        "CU":  "CU10",
        "Version":  "11.0.3431",
        "KBList":  "2954099"
    },
    {
        "Version":  "11.0.3437",
        "KBList":  "2969896"
    },
    {
        "CU":  "CU11",
        "Version":  "11.0.3449",
        "KBList":  "2975396"
    },
    {
        "CU":  "CU12",
        "Version":  "11.0.3460",
        "KBList":  "2977325"
    },
    {
        "CU":  "CU13",
        "Version":  "11.0.3470",
        "KBList":  "2991533"
    },
    {
        "Version":  "11.0.3482",
        "KBList":  "3002044"
    },
    {
        "CU":  "CU14",
        "Version":  "11.0.3486",
        "KBList":  "3023636"
    },
    {
        "CU":  "CU15",
        "Version":  "11.0.3487",
        "KBList":  "3038001"
    },
    {
        "CU":  "CU16",
        "Version":  "11.0.3492",
        "KBList":  "3052476"
    },
    {
        "Version":  "11.0.3513",
        "KBList":  "3045317"
    },
    {
        "SP":  "SP2",
        "Version":  "11.0.5058",
        "SupportedUntil":  "2017-01-10T00:00:00",
        "KBList":  "2958429"
    },
    {
        "Version":  "11.0.5343",
        "KBList":  "3045321"
    },
    {
        "Version":  "11.0.5352",
        "KBList":  "3135244"
    },
    {
        "Version":  "11.0.5388",
        "KBList":  "3194719"
    },
    {
        "Version":  "11.0.5522",
        "KBList":  "2969896"
    },
    {
        "CU":  "CU1",
        "Version":  "11.0.5532",
        "KBList":  "2976982"
    },
    {
        "CU":  "CU2",
        "Version":  "11.0.5548",
        "KBList":  "2983175"
    },
    {
        "CU":  "CU3",
        "Version":  "11.0.5556",
        "KBList":  "3002049"
    },
    {
        "CU":  "CU4",
        "Version":  "11.0.5569",
        "KBList":  "3007556"
    },
    {
        "Version":  "11.0.5571",
        "KBList":  "3034679"
    },
    {
        "CU":  "CU5",
        "Version":  "11.0.5582",
        "KBList":  "3037255"
    },
    {
        "CU":  "CU6",
        "Version":  "11.0.5592",
        "KBList":  "3052468"
    },
    {
        "Version":  "11.0.5613",
        "KBList":  "3045319"
    },
    {
        "CU":  "CU7",
        "Version":  "11.0.5623",
        "KBList":  "3072100"
    },
    {
        "Version":  "11.0.5629",
        "KBList":  "3087872"
    },
    {
        "CU":  "CU8",
        "Version":  "11.0.5634",
        "KBList":  "3082561"
    },
    {
        "Version":  "11.0.5636",
        "KBList":  "3097636"
    },
    {
        "CU":  "CU9",
        "Version":  "11.0.5641",
        "KBList":  "3098512"
    },
    {
        "CU":  "CU10",
        "Version":  "11.0.5644",
        "KBList":  "3120313"
    },
    {
        "CU":  "CU11",
        "Version":  "11.0.5646",
        "KBList":  "3137745"
    },
    {
        "CU":  "CU12",
        "Version":  "11.0.5649",
        "KBList":  "3152637"
    },
    {
        "CU":  "CU13",
        "Version":  "11.0.5655",
        "KBList":  "3165266"
    },
    {
        "CU":  "CU14",
        "Version":  "11.0.5657",
        "KBList":  "3180914"
    },
    {
        "CU":  "CU15",
        "Version":  "11.0.5676",
        "KBList":  [
                       "3205416",
                       "3194725"
                   ]
    },
    {
        "CU":  "CU16",
        "Version":  "11.0.5678",
        "KBList":  "3205054"
    },
    {
        "SP":  "SP3",
        "Version":  "11.0.6020",
        "SupportedUntil":  "2018-10-09T00:00:00",
        "KBList":  "3072779"
    },
    {
        "Version":  "11.0.6216",
        "KBList":  "3135244"
    },
    {
        "Version":  "11.0.6248",
        "KBList":  "3194721"
    },
    {
       "Version":  "11.0.6251",
       "KBList":  "4019092"
    },
    {
        "Version": "11.0.6260",
        "KBList": "4057115"
    },
    {
        "CU":  "CU1",
        "Version":  "11.0.6518",
        "KBList":  "3123299"
    },
    {
        "CU":  "CU2",
        "Version":  "11.0.6523",
        "KBList":  "3137746"
    },
    {
        "CU":  "CU3",
        "Version":  "11.0.6537",
        "KBList":  "3152635"
    },
    {
        "CU":  "CU4",
        "Version":  "11.0.6540",
        "KBList":  "3165264"
    },
    {
        "CU":  "CU5",
        "Version":  "11.0.6544",
        "KBList":  "3180915"
    },
    {
        "CU":  "CU6",
        "Version":  "11.0.6567",
        "KBList":  [
                       "3194992",
                       "3194724"
                   ]
    },
    {
        "CU":  "CU7",
        "Version":  "11.0.6579",
        "KBList":  "3205051"
    },
    {
        "CU":  "CU8",
        "Version":  "11.0.6594",
        "KBList":  "4013104"
    },
    {
        "CU":  "CU9",
        "Version":  "11.0.6598",
        "KBList":  "4016762"
    },
    {
        "CU":  "CU10",
        "Version":  "11.0.6607",
        "KBList":  [
                       "4025925",
                       "4019090"
                   ]
    },
    {
        "Version":  "11.0.6615",
        "KBList":  "4057121"
    },
    {
        "SP":  [
                   "SP4",
                   "LATEST"
               ],
        "SupportedUntil":  "2022-07-12T00:00:00",
        "Version":  "11.0.7001",
        "KBList":  "4018073"
    },
    {
        "Version": "11.0.7462",
        "KBList": "4057116"
    },
    {
        "Version": "11.0.7469",
        "KBList": "4091266"
    },
    {
        "Version":  "12.0.1524",
        "Name": "2014"
    },
    {
        "SP":  "RTM",
        "Version":  "12.0.2000",
        "SupportedUntil":  "2016-07-12T00:00:00"
    },
    {
        "Version":  "12.0.2254",
        "KBList":  "2977315"
    },
    {
        "Version":  "12.0.2269",
        "KBList":  "3045324"
    },
    {
        "Version":  "12.0.2271"
    },
    {
        "CU":  "CU1",
        "Version":  "12.0.2342",
        "KBList":  "2931693"
    },
    {
        "CU":  "CU2",
        "Version":  "12.0.2370",
        "KBList":  "2967546"
    },
    {
        "Version":  "12.0.2381",
        "KBList":  "2977316"
    },
    {
        "CU":  "CU3",
        "Version":  "12.0.2402",
        "KBList":  "2984923"
    },
    {
        "Version":  "12.0.2405",
        "KBList":  "2999809"
    },
    {
        "Version":  "12.0.2423",
        "KBList":  "3007050"
    },
    {
        "CU":  "CU4",
        "Version":  "12.0.2430",
        "KBList":  "2999197"
    },
    {
        "Version":  "12.0.2436",
        "KBList":  "3014867"
    },
    {
        "CU":  "CU5",
        "Version":  "12.0.2456",
        "KBList":  "3011055"
    },
    {
        "Version":  "12.0.2464",
        "KBList":  "3024815"
    },
    {
        "Version":  "12.0.2472",
        "KBList":  "3032087"
    },
    {
        "Version":  "12.0.2474",
        "KBList":  "3034679"
    },
    {
        "CU":  "CU6",
        "Version":  "12.0.2480",
        "KBList":  "3031047"
    },
    {
        "Version":  "12.0.2485",
        "KBList":  "3043788"
    },
    {
        "Version":  "12.0.2488",
        "KBList":  "3048751"
    },
    {
        "CU":  "CU7",
        "Version":  "12.0.2495",
        "KBList":  "3046038"
    },
    {
        "Version":  "12.0.2504",
        "KBList":  [
                       "3058512",
                       "2999809"
                   ]
    },
    {
        "Version":  "12.0.2505",
        "KBList":  "3052167"
    },
    {
        "Version":  "12.0.2506",
        "KBList":  "3063054"
    },
    {
        "CU":  "CU8",
        "Version":  "12.0.2546",
        "KBList":  "3067836"
    },
    {
        "Version":  "12.0.2548",
        "KBList":  "3045323"
    },
    {
        "CU":  "CU9",
        "Version":  "12.0.2553",
        "KBList":  "3075949"
    },
    {
        "CU":  "CU10",
        "Version":  "12.0.2556",
        "KBList":  "3094220"
    },
    {
        "CU":  "CU11",
        "Version":  "12.0.2560",
        "KBList":  "3106659"
    },
    {
        "CU":  "CU12",
        "Version":  "12.0.2564",
        "KBList":  "3130923"
    },
    {
        "CU":  "CU13",
        "Version":  "12.0.2568",
        "KBList":  "3144517"
    },
    {
        "CU":  "CU14",
        "Version":  "12.0.2569",
        "KBList":  "3158271"
    },
    {
        "SP":  "SP1",
        "Version":  "12.0.4100",
        "SupportedUntil":  "2017-10-10T00:00:00",
        "KBList":  "3058865"
    },
    {
        "Version":  "12.0.4213",
        "KBList":  "3070446"
    },
    {
        "Version":  "12.0.4219"
    },
    {
        "Version":  "12.0.4232",
        "KBList":  "3194720"
    },
    {
        "Version":  "12.0.4237",
        "KBList":  "4019091"
    },
    {
        "CU":  "CU1",
        "Version":  "12.0.4416",
        "KBList":  "3067839"
    },
    {
        "Version":  "12.0.4419",
        "KBList":  "3078973"
    },
    {
        "CU":  "CU2",
        "Version":  "12.0.4422",
        "KBList":  "3075950"
    },
    {
        "CU":  "CU3",
        "Version":  "12.0.4427",
        "KBList":  "3094221"
    },
    {
        "Version":  "12.0.4432",
        "KBList":  [
                       "3097972",
                       "319472"
                   ]
    },
    {
        "Version":  "12.0.4433",
        "KBList":  "3119148"
    },
    {
        "CU":  "CU4",
        "Version":  "12.0.4436",
        "KBList":  "3106660"
    },
    {
        "Version":  "12.0.4437",
        "KBList":  "3130999"
    },
    {
        "CU":  "CU5",
        "Version":  "12.0.4439",
        "KBList":  "3130926"
    },
    {
        "Version":  "12.0.4449",
        "KBList":  "3144524"
    },
    {
        "CU":  "CU6",
        "Version":  "12.0.4457",
        "KBList":  "3167392"
    },
    {
        "CU":  "CU7",
        "Version":  "12.0.4459",
        "KBList":  "3162659"
    },
    {
        "Version":  "12.0.4463",
        "KBList":  "3174370"
    },
    {
        "CU":  "CU8",
        "Version":  "12.0.4468",
        "KBList":  "917606"
    },
    {
        "CU":  "CU9",
        "Version":  "12.0.4474",
        "KBList":  "3186964"
    },
    {
        "Version":  "12.0.4487",
        "KBList":  "3194722"
    },
    {
        "CU":  "CU10",
        "Version":  "12.0.4491",
        "KBList":  "3204399"
    },
    {
        "Version":  "12.0.4502",
        "CU":  "CU11",
        "KBList":  "4010392"
    },
    {
        "Version":  "12.0.4511",
        "CU":  "CU12",
        "KBList":  "4017793"
    },
    {
        "Version":  "12.0.4522",
        "CU":  "CU13",
        "KBList":  [
                       "4019099",
                       "4032542"
                   ]
    },
    {
        "SP":  "SP2",
        "Version":  "12.0.5000",
        "SupportedUntil":  "2024-07-09T00:00:00",
        "KBList":  "3171021"
    },
    {
        "Version":  "12.0.5203",
        "KBList":  "3194714"
    },
    {
        "Version": "12.0.5207",
        "KBList": "4019093"
    },
    {
        "Version": "12.0.5214",
        "KBList": "4057120"
    },
    {
        "CU":  "CU1",
        "Version":  "12.0.5511",
        "KBList":  "3178925"
    },
    {
        "CU":  "CU2",
        "Version":  "12.0.5522",
        "KBList":  "3188778"
    },
    {
        "Version":  "12.0.5532",
        "KBList":  "3194718"
    },
    {
        "CU":  "CU3",
        "Version":  "12.0.5538",
        "KBList":  "3204388"
    },
    {
        "CU":  "CU4",
        "Version":  "12.0.5540",
        "KBList":  "4010394"
    },
    {
        "CU":  "CU5",
        "Version":  "12.0.5546",
        "KBList":  "4013098"
    },
    {
        "Version":  "12.0.5553",
        "CU":  "CU6",
        "KBList":  [
                       "4019094",
                       "4036996"
                   ]
    },
    {
        "CU":  "CU7",
        "Version":  "12.0.5556",
        "KBList":  "4032541"
    },
    {
        "CU":  "CU8",
        "Version":  "12.0.5557",
        "KBList":  "4037356"
    },
    {
        "CU": "CU9",
        "Version": "12.0.5563",
        "KBList": "4055557"
    },
    {
        "CU": "CU10",
        "Version": "12.0.5571",
        "KBList": "4052725"
    },
    {
        "CU": "CU11",
        "Version": "12.0.5579",
        "KBList": "4077063"
    },
    {
        "CU": "CU12",
        "Version": "12.0.5589",
        "KBList": "4130489"
    },
    {
        "CU": "CU13",
        "Version": "12.0.5590",
        "KBList": "4456287"
    },
    {
        "CU": "CU14",
        "Version": "12.0.5600",
        "KBList": "4459860"
    },
    {
        "CU": "CU15",
        "Version": "12.0.5605",
        "KBList": "4469137"
    },
    {
        "SP": [
            "SP3",
            "LATEST"
        ],
        "Version": "12.0.6024",
        "SupportedUntil": "2019-09-07T00:00:00",
        "KBList": "4022619"
    },
    {
        "CU": "CU1",
        "Version": "12.0.6205",
        "KBList": "4470220"
    },
    {
        "Version":  "13.0.200",
        "Name": "2016"
    },
    {
        "Version":  "13.0.300"
    },
    {
        "Version":  "13.0.407"
    },
    {
        "Version":  "13.0.500"
    },
    {
        "Version":  "13.0.600"
    },
    {
        "Version":  "13.0.700"
    },
    {
        "Version":  "13.0.800"
    },
    {
        "Version":  "13.0.900"
    },
    {
        "Version":  "13.0.1000"
    },
    {
        "Version":  "13.0.1100"
    },
    {
        "Version":  "13.0.1200"
    },
    {
        "Version":  "13.0.1250"
    },
    {
        "Version":  "13.0.1300"
    },
    {
        "Version":  "13.0.1400"
    },
    {
        "SP":  "RTM",
        "Version":  "13.0.1601",
        "SupportedUntil":  "2018-01-09T00:00:00"
    },
    {
        "Version":  "13.0.1708",
        "KBList":  "3164398"
    },
    {
        "Version":  "13.0.1722",
        "KBList":  "3194716"
    },
    {
        "Version":  "13.0.1728",
        "KBList":  "3210111"
    },
    {
        "Version":  "13.0.1742",
        "KBList":  "4019088"
    },
    {
        "Version": "13.0.1745",
        "KBList": "4058560"
    },
    {
        "CU":  "CU1",
        "Version":  "13.0.2149",
        "KBList":  "3164674"
    },
    {
        "CU":  "CU2",
        "Version":  "13.0.2164",
        "KBList":  "3182270"
    },
    {
        "Version":  "13.0.2169",
        "KBList":  "3195813"
    },
    {
        "Version":  "13.0.2170",
        "KBList":  "3199171"
    },
    {
        "CU":  "CU3",
        "Version":  "13.0.2186",
        "KBList":  [
                       "3205413",
                       "3194717"
                   ]
    },
    {
        "Version":  "13.0.2190",
        "KBList":  "3210110"
    },
    {
        "CU":  "CU4",
        "Version":  "13.0.2193",
        "KBList":  "3205052"
    },
    {
        "CU":  "CU5",
        "Version":  "13.0.2197",
        "KBList":  "4013105"
    },
    {
        "CU":  "CU6",
        "Version":  "13.0.2204",
        "KBList":  "4019914"
    },
    {
        "Version":  "13.0.2210",
        "CU":  "CU7",
        "KBList":  [
                       "4024304",
                       "4019086"
                   ]
    },
    {
        "CU":  "CU8",
        "Version":  "13.0.2213",
        "KBList":  "4040713"
    },
    {
        "CU": "CU9",
        "Version": "13.0.2216",
        "KBList": "4037357"
    },
    {
        "Version": "13.0.2218",
        "KBList": "4058559"
    },
    {
        "SP":  "SP1",
        "Version":  "13.0.4001",
        "SupportedUntil":  "2019-09-07T00:00:00",
        "KBList":  "3182545"
    },
    {
        "Version":  "13.0.4199",
        "KBList":  "3207512"
    },
    {
        "Version":  "13.0.4202",
        "KBList":  "3210089"
    },
    {
        "Version": "13.0.4206",
        "KBList": "4019089"
    },
    {
        "Version": "13.0.4210",
        "KBList": "4057118"
    },
    {
        "Version": "13.0.4224",
        "KBList": "4458842"
    },
    {
        "CU":  "CU1",
        "Version":  "13.0.4411",
        "KBList":  "3208177"
    },
    {
        "CU":  "CU2",
        "Version":  "13.0.4422",
        "KBList":  "4013106"
    },
    {
        "CU":  "CU3",
        "Version":  "13.0.4435",
        "KBList":  "4019916"
    },
    {
        "Version":  "13.0.4446",
        "CU":  "CU4",
        "KBList":  [
                       "4024305",
                       "4019095"
                   ]
    },
    {
        "CU":  "CU5",
        "Version":  "13.0.4451",
        "KBList":  "4040714"
    },
    {
        "CU": "CU6",
        "Version": "13.0.4457",
        "KBList": "4037354"
    },
    {
        "CU": "CU7",
        "Version": "13.0.4466",
        "KBList": "4057119"
    },
    {
        "CU": "CU8",
        "Version": "13.0.4474",
        "KBList": "4077064"
    },
    {
        "CU": "CU9",
        "Version": "13.0.4502",
        "KBList": "4100997"
    },
    {
        "CU": "CU10",
        "Version": "13.0.4514",
        "KBList": "4341569"
    },
    {
        "Version": "13.0.4522",
        "KBList": "4293808"
    },
    {
        "CU": "CU11",
        "Version": "13.0.4528",
        "KBList": "4459676"
    },
    {
        "CU": "CU12",
        "Version": "13.0.4541",
        "KBList": "4464343"
    },
    {
        "SP": [
            "SP2",
            "LATEST"
        ],
        "Version": "13.0.5026",
        "SupportedUntil": "2026-07-14T00:00:00",
        "KBList": "4052908"
    },
    {
        "Version": "13.0.5081",
        "KBList": "4293802"
    },
    {
        "CU": "CU1",
        "Version": "13.0.5149",
        "KBList": "4135048"
    },
    {
        "CU": "CU2",
        "Version": "13.0.5153",
        "KBList": "4340355"
    },
    {
        "Version": "13.0.5161",
        "KBList": "4293807"
    },
    {
        "Version": "13.0.5201",
        "KBList": "4458621"
    },
    {
        "CU": "CU3",
        "Version": "13.0.5216",
        "KBList": "4458871"
    },
    {
        "CU": "CU4",
        "Version": "13.0.5233",
        "KBList": "4464106"
    },
    {
        "Version":  "14.0.1",
        "Name": "2017"
    },
    {
        "Version":  "14.0.100"
    },
    {
        "Version":  "14.0.200"
    },
    {
        "Version":  "14.0.304"
    },
    {
        "Version":  "14.0.405"
    },
    {
        "Version":  "14.0.500"
    },
    {
        "Version":  "14.0.600"
    },
    {
        "Version":  "14.0.800"
    },
    {
        "Version":  "14.0.900"
    },
    {
        "SP":  [
                   "RTM",
                   "LATEST"
               ],
        "Version":  "14.0.1000",
        "SupportedUntil":  "2027-10-12T00:00:00"
    },
    {
        "Version": "14.0.2000",
        "KBList": "4057122"
    },
    {
        "Version": "14.0.2002",
        "KBList": "4293803"
    },
    {
        "CU":  "CU1",
        "Version":  "14.0.3006",
        "KBList":  "4038634"
    },
    {
        "CU": "CU2",
        "Version": "14.0.3008",
        "KBList": "4052574"
    },
    {
        "CU": "CU3",
        "Version": "14.0.3015",
        "KBList": "4052987"
    },
    {
        "CU": "CU4",
        "Version": "14.0.3022",
        "KBList": "4056498"
    },
    {
        "CU": "CU5",
        "Version": "14.0.3023",
        "KBList": "4092643"
    },
    {
        "CU": "CU6",
        "Version": "14.0.3025",
        "KBList": "4101464"
    },
    {
        "CU": "CU7",
        "Version": "14.0.3026",
        "KBList": "4229789"
    },
    {
        "CU": "CU8",
        "Version": "14.0.3029",
        "KBList": "4338363"
    },
    {
        "CU": "CU9",
        "Version": "14.0.3030",
        "KBList": "4341265"
    },
    {
        "Version": "14.0.3035",
        "KBList": "4293805"
    },
    {
        "CU": "CU10",
        "Version": "14.0.3037",
        "KBList": "4293805"
    },
    {
        "CU": "CU11",
        "Version": "14.0.3038",
        "KBList": "4462262"
    },
    {
        "CU": "CU12",
        "Version": "14.0.3045",
        "KBList": "4464082"
    },
    {
        "CU": "CU13",
        "Version": "14.0.3048",
        "KBList": "4466404"
    }
    ]
}
tools\dbatools\bin\dbatools-index.json
[
    {
        "Name":  "Add-DbaAgDatabase",
        "Description":  "Adds a database to an availability group on a SQL Server instance.\n\nBefore joining the replica databases to the availablity group, the databases will be initialized with automatic seeding or full/log backup.",
        "Tags":  [
                     "AvailabilityGroup",
                     "HA",
                     "AG"
                 ],
        "Synopsis":  "Adds a database to an availability group on a SQL Server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Add-DbaAgDatabase",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Add-DbaAgDatabase",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eAdd-DbaAgDatabase -SqlInstance sql2017a -AvailabilityGroup ag1 -Database db1, db2 -Confirm\nAdds db1 and db2 to ag1 on sql2017a. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2017a | Out-GridView -Passthru | Add-DbaAgDatabase -AvailabilityGroup ag1\nAdds selected databases from sql2017a to ag1\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbSharePoint -SqlInstance sqlcluster | Add-DbaAgDatabase -AvailabilityGroup SharePoint\nAdds SharePoint databases as found in SharePoint_Config on sqlcluster to ag1 on sqlcluster\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbSharePoint -SqlInstance sqlcluster -ConfigDatabase SharePoint_Config_2019 | Add-DbaAgDatabase -AvailabilityGroup SharePoint\nAdds SharePoint databases as found in SharePoint_Config_2019 on sqlcluster to ag1 on sqlcluster",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.\nThis should be the primary replica.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityGroup",
                           "The availability group where the databases will be added.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database or databases to add.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Secondary",
                           "Not required - the command will figure this out. But if you\u0027d like to be explicit about replicas, this will help.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SecondarySqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaDatabase, Get-DbaDbSharePoint and more.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SeedingMode",
                           "Specifies how the secondary replica will be initially seeded.\nAutomatic enables direct seeding. This method will seed the secondary replica over the network. This method does not require you to backup and restore a copy of the primary database on the replica.\nManual requires you to create a backup of the database on the primary replica and manually restore that backup on the secondary replica.\nIf not specified, the setting from the availability group replica will be used. Otherwise the setting will be updated.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SharedPath",
                           "The network share where the backups will be backed up and restored from.\nEach SQL Server service account must have access to this share.\nNOTE: If a backup / restore is performed, the backups will be left in tact on the network share.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "UseLastBackup",
                           "Use the last full backup of database.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Add-DbaAgDatabase [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-AvailabilityGroup] \u003cString\u003e [[-Database] \u003cString[]\u003e] [[-Secondary] \u003cDbaInstanceParameter[]\u003e] [[-SecondarySqlCredential] \u003cPSCredential\u003e] [[-InputObject] \u003cDatabase[]\u003e] [[-SeedingMode] \u003cString\u003e] [[-SharedPath] \u003cString\u003e] [-UseLastBackup] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Add-DbaAgListener",
        "Description":  "Adds a listener to an availability group on a SQL Server instance.",
        "Tags":  [
                     "AvailabilityGroup",
                     "HA",
                     "AG"
                 ],
        "Synopsis":  "Adds a listener to an availability group on a SQL Server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Add-DbaAgListener",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Add-DbaAgListener",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eAdd-DbaAgListener -SqlInstance sql2017 -AvailabilityGroup SharePoint -IPAddress 10.0.20.20\nCreates a listener on 10.0.20.20 port 1433 for the SharePoint availability group on sql2017.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2017 -AvailabilityGroup availabilitygroup1 | Add-DbaAgListener -Dhcp\nCreates a listener on port 1433 with a dynamic IP for the group1 availability group on sql2017.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityGroup",
                           "The Availability Group to which a listener will be bestowed upon.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IPAddress",
                           "Sets the IP address of the availability group listener.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SubnetMask",
                           "Sets the subnet IP mask of the availability group listener. Defaults to 255.255.255.0.",
                           "",
                           false,
                           "false",
                           "255.255.255.0"
                       ],
                       [
                           "Port",
                           "Sets the port number used to communicate with the availability group. Defaults to 1433.",
                           "",
                           false,
                           "false",
                           "1433"
                       ],
                       [
                           "Dhcp",
                           "Indicates whether the listener uses DHCP.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Passthru",
                           "Don\u0027t create the listener, just pass thru an object that can be further customized before creation.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaAvailabilityGroup",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Add-DbaAgListener [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-IPAddress] \u003cIPAddress\u003e] [[-SubnetMask] \u003cIPAddress\u003e] [[-Port] \u003cInt32\u003e] [-Dhcp] [-Passthru] [[-InputObject] \u003cAvailabilityGroup[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Add-DbaAgReplica",
        "Description":  "Adds a replica to an availability group on a SQL Server instance.\n\nAutomatically creates a database mirroring endpoint if required.",
        "Tags":  [
                     "AvailabilityGroup",
                     "HA",
                     "AG"
                 ],
        "Synopsis":  "Adds a replica to an availability group on a SQL Server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Add-DbaAgReplica",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Add-DbaAgReplica",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2017a -AvailabilityGroup SharePoint | Add-DbaAgReplica -SqlInstance sql2017b\nAdds sql2017b to the SharePoint availability group on sql2017a\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2017a -AvailabilityGroup SharePoint | Add-DbaAgReplica -SqlInstance sql2017b -FailoverMode Manual\nAdds sql2017b to the SharePoint availability group on sql2017a with a manual failover mode.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "The name of the replica. Defaults to the SQL Server instance name.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityMode",
                           "Sets the availability mode of the availability group replica. Options are: AsynchronousCommit and SynchronousCommit. SynchronousCommit is default.",
                           "",
                           false,
                           "false",
                           "SynchronousCommit"
                       ],
                       [
                           "FailoverMode",
                           "Sets the failover mode of the availability group replica. Options are Automatic and Manual. Automatic is default.",
                           "",
                           false,
                           "false",
                           "Automatic"
                       ],
                       [
                           "BackupPriority",
                           "Sets the backup priority availability group replica. Default is 50.",
                           "",
                           false,
                           "false",
                           "50"
                       ],
                       [
                           "ConnectionModeInPrimaryRole",
                           "Specifies the connection intent modes of an Availability Replica in primary role. AllowAllConnections by default.",
                           "",
                           false,
                           "false",
                           "AllowAllConnections"
                       ],
                       [
                           "ConnectionModeInSecondaryRole",
                           "Specifies the connection modes of an Availability Replica in secondary role. AllowAllConnections by default.",
                           "",
                           false,
                           "false",
                           "AllowAllConnections"
                       ],
                       [
                           "SeedingMode",
                           "Specifies how the secondary replica will be initially seeded.\nAutomatic enables direct seeding. This method will seed the secondary replica over the network. This method does not require you to backup and restore a copy of the primary database on the replica.\nManual requires you to create a backup of the database on the primary replica and manually restore that backup on the secondary replica.",
                           "",
                           false,
                           "false",
                           "Automatic"
                       ],
                       [
                           "Endpoint",
                           "By default, this command will attempt to find a DatabaseMirror endpoint. If one does not exist, it will create it.\nIf an endpoint must be created, the name \"hadr_endpoint\" will be used. If an alternative is preferred, use Endpoint.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Passthru",
                           "Don\u0027t create the replica, just pass thru an object that can be further customized before creation.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ReadonlyRoutingConnectionUrl",
                           "Sets the read only routing connection url for the availability replica.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Certificate",
                           "Specifies that the endpoint is to authenticate the connection using the certificate specified by certificate_name to establish identity for authorization.\nThe far endpoint must have a certificate with the public key matching the private key of the specified certificate.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaAvailabilityGroup.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Add-DbaAgReplica [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString\u003e] [[-AvailabilityMode] \u003cString\u003e] [[-FailoverMode] \u003cString\u003e] [[-BackupPriority] \u003cInt32\u003e] [[-ConnectionModeInPrimaryRole] \u003cString\u003e] [[-ConnectionModeInSecondaryRole] \u003cString\u003e] [[-SeedingMode] \u003cString\u003e] [[-Endpoint] \u003cString\u003e] [-Passthru] [[-ReadonlyRoutingConnectionUrl] \u003cString\u003e] [[-Certificate] \u003cString\u003e] [-InputObject] \u003cAvailabilityGroup\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Add-DbaCmsRegServer",
        "Description":  "Adds registered servers to SQL Server Central Management Server (CMS). If you need more flexiblity, look into Import-DbaCmsRegServer which\naccepts multiple kinds of input and allows you to add reg servers from different CMSes.",
        "Tags":  [
                     "RegisteredServer",
                     "CMS"
                 ],
        "Synopsis":  "Adds registered servers to SQL Server Central Management Server (CMS)",
        "Alias":  "Add-DbaRegisteredServer",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Add-DbaCmsRegServer",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Add-DbaCmsRegServer",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eAdd-DbaCmsRegServer -SqlInstance sql2008 -ServerName sql01\nCreates a registered server on sql2008\u0027s CMS which points to the SQL Server, sql01. When scrolling in CMS, the name \"sql01\" will be visible.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eAdd-DbaCmsRegServer -SqlInstance sql2008 -ServerName sql01 -Name \"The 2008 Clustered Instance\" -Description \"HR\u0027s Dedicated SharePoint instance\"\nCreates a registered server on sql2008\u0027s CMS which points to the SQL Server, sql01. When scrolling in CMS, \"The 2008 Clustered Instance\" will be visible.\r\nClearly this is hard to explain ;)\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eAdd-DbaCmsRegServer -SqlInstance sql2008 -ServerName sql01 -Group hr\\Seattle\nCreates a registered server on sql2008\u0027s CMS which points to the SQL Server, sql01. When scrolling in CMS, the name \"sql01\" will be visible within the Seattle group which is in the hr group.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServerGroup -SqlInstance sql2008 -Group hr\\Seattle | Add-DbaCmsRegServer -ServerName sql01111\nCreates a registered server on sql2008\u0027s CMS which points to the SQL Server, sql01. When scrolling in CMS, the name \"sql01\" will be visible within the Seattle group which is in the hr group.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ServerName",
                           "Server Name is the actual SQL instance name (labeled Server Name)",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "Name is basically the nickname in SSMS CMS interface (labeled Registered Server Name)",
                           "",
                           false,
                           "false",
                           "$ServerName"
                       ],
                       [
                           "Description",
                           "Adds a description for the registered server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Group",
                           "Adds the registered server to a specific group.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows the piping of a registered server group",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Add-DbaCmsRegServer [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-ServerName] \u003cString\u003e [[-Name] \u003cString\u003e] [[-Description] \u003cString\u003e] [[-Group] \u003cObject\u003e] [[-InputObject] \u003cServerGroup[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Add-DbaCmsRegServerGroup",
        "Description":  "Adds registered server groups to SQL Server Central Management Server (CMS). If you need more flexibility, look into Import-DbaCmsRegServer which accepts multiple kinds of input and allows you to add reg servers and groups from different CMS.",
        "Tags":  [
                     "RegisteredServer",
                     "CMS"
                 ],
        "Synopsis":  "Adds registered server groups to SQL Server Central Management Server (CMS)",
        "Alias":  "Add-DbaRegisteredServerGroup",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Add-DbaCmsRegServerGroup",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Add-DbaCmsRegServerGroup",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eAdd-DbaCmsRegServerGroup -SqlInstance sql2012 -Name HR\nCreates a registered server group called HR, in the root of sql2012\u0027s CMS\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eAdd-DbaCmsRegServerGroup -SqlInstance sql2012, sql2014 -Name sub-folder -Group HR\nCreates a registered server group on sql2012 and sql2014 called sub-folder within the HR group\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServerGroup -SqlInstance sql2012, sql2014 -Group HR | Add-DbaCmsRegServerGroup -Name sub-folder\nCreates a registered server group on sql2012 and sql2014 called sub-folder within the HR group of each server",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "The name of the registered server group",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Description",
                           "The description for the registered server group",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Group",
                           "The SQL Server Central Management Server group. If no groups are specified, the new group will be created at the root.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows results from Get-DbaCmsRegServerGroup to be piped in",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Add-DbaCmsRegServerGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-Name] \u003cString\u003e [[-Description] \u003cString\u003e] [[-Group] \u003cString\u003e] [[-InputObject] \u003cServerGroup[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Add-DbaComputerCertificate",
        "Description":  "Adds a computer certificate from a local or remote computer.",
        "Tags":  "Certificate",
        "Synopsis":  "Adds a computer certificate - useful for older systems.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Add-DbaComputerCertificate",
        "Availability":  "Windows only",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eAdd-DbaComputerCertificate -ComputerName Server1 -Path C:\\temp\\cert.cer\nAdds the local C:\\temp\\cert.cer to the remote server Server1 in LocalMachine\\My (Personal).\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eAdd-DbaComputerCertificate -Path C:\\temp\\cert.cer\nAdds the local C:\\temp\\cert.cer to the local computer\u0027s LocalMachine\\My (Personal) certificate store.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target SQL Server instance or instances. Defaults to localhost.",
                           "ServerInstance,SqlServer,SqlInstance",
                           false,
                           "false",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to $ComputerName using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SecurePassword",
                           "The password for the certificate, if it is password protected.",
                           "Password",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Certificate",
                           "The target certificate object.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Path",
                           "The local path to the target certificate object.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Store",
                           "Certificate store. Default is LocalMachine.",
                           "",
                           false,
                           "false",
                           "LocalMachine"
                       ],
                       [
                           "Folder",
                           "Certificate folder. Default is My (Personal).",
                           "",
                           false,
                           "false",
                           "My"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Add-DbaComputerCertificate [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-SecurePassword] \u003cSecureString\u003e] [[-Certificate] \u003cX509Certificate2[]\u003e] [[-Path] \u003cString\u003e] [[-Store] \u003cString\u003e] [[-Folder] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Add-DbaDbMirrorMonitor",
        "Description":  "Creates a database mirroring monitor job that periodically updates the mirroring status for every mirrored database on the server instance.\n\nBasically executes sp_dbmmonitoraddmonitoring.",
        "Tags":  [
                     "Mirror",
                     "HA"
                 ],
        "Synopsis":  "Creates a database mirroring monitor job that periodically updates the mirroring status for every mirrored database on the server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Add-DbaDbMirrorMonitor",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Add-DbaDbMirrorMonitor",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eAdd-DbaDbMirrorMonitor -SqlInstance sql2008, sql2012\nCreates a database mirroring monitor job that periodically updates the mirroring status for every mirrored database on sql2008 and sql2012.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternate Windows or SQL Login Authentication. Accepts credential objects (Get-Credential).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Add-DbaDbMirrorMonitor [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Add-DbaPfDataCollectorCounter",
        "Description":  "Adds a Performance Data Collector Counter.",
        "Tags":  "PerfMon",
        "Synopsis":  "Adds a Performance Data Collector Counter.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Add-DbaPfDataCollectorCounter",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Add-DbaPfDataCollectorCounter",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eAdd-DbaPfDataCollectorCounter -ComputerName sql2017 -CollectorSet \u0027System Correlation\u0027 -Collector DataCollector01  -Counter \u0027\\LogicalDisk(*)\\Avg. Disk Queue Length\u0027\nAdds the \u0027\\LogicalDisk(*)\\Avg. Disk Queue Length\u0027 counter within the DataCollector01 collector within the System Correlation collector set on sql2017.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollector | Out-GridView -PassThru | Add-DbaPfDataCollectorCounter -Counter \u0027\\LogicalDisk(*)\\Avg. Disk Queue Length\u0027 -Confirm\nAllows you to select which Data Collector you\u0027d like to add the counter \u0027\\LogicalDisk(*)\\Avg. Disk Queue Length\u0027 on localhost and prompts for confirmation.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer. Defaults to localhost.",
                           "",
                           false,
                           "false",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to $ComputerName using alternative credentials. To use:\n$cred = Get-Credential, then pass $cred object to the -Credential parameter.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CollectorSet",
                           "The Collector Set name.",
                           "DataCollectorSet",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Collector",
                           "The Collector name.",
                           "DataCollector",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Counter",
                           "The Counter name. This must be in the form of \u0027\\Processor(_Total)\\% Processor Time\u0027.",
                           "Name",
                           true,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "InputObject",
                           "Accepts the object output by Get-DbaPfDataCollector via the pipeline.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Add-DbaPfDataCollectorCounter [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CollectorSet] \u003cString[]\u003e] [[-Collector] \u003cString[]\u003e] [-Counter] \u003cObject[]\u003e [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Backup-DbaDatabase",
        "Description":  "Performs a backup of a specified type of 1 or more databases on a single SQL Server Instance. These backups may be Full, Differential or Transaction log backups.",
        "Tags":  [
                     "DisasterRecovery",
                     "Backup",
                     "Restore"
                 ],
        "Synopsis":  "Backup one or more SQL Sever databases from a single SQL Server SqlInstance.",
        "Alias":  "",
        "Author":  "Stuart Moore (@napalmgram), stuart-moore.com",
        "CommandName":  "Backup-DbaDatabase",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eBackup-DbaDatabase -SqlInstance Server1 -Database HR, Finance\nThis will perform a full database backup on the databases HR and Finance on SQL Server Instance Server1 to Server1 default backup directory.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eBackup-DbaDatabase -SqlInstance sql2016 -BackupDirectory C:\\temp -Database AdventureWorks2014 -Type Full\nBacks up AdventureWorks2014 to sql2016 C:\\temp folder.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eBackup-DbaDatabase -SqlInstance sql2016 -AzureBaseUrl https://dbatoolsaz.blob.core.windows.net/azbackups/ -AzureCredential dbatoolscred -Type Full -CreateFolder\nPerforms a full backup of all databases on the sql2016 instance to their own containers under the https://dbatoolsaz.blob.core.windows.net/azbackups/ container on Azure blog storage using the sql \r\ncredential \"dbatoolscred\" registered on the sql2016 instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eBackup-DbaDatabase -SqlInstance sql2016 -AzureBaseUrl https://dbatoolsaz.blob.core.windows.net/azbackups/  -Type Full\nPerforms a full backup of all databases on the sql2016 instance to the https://dbatoolsaz.blob.core.windows.net/azbackups/ container on Azure blog storage using the Shared Access Signature sql \r\ncredential \"https://dbatoolsaz.blob.core.windows.net/azbackups\" registered on the sql2016 instance.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eBackup-Dbadatabase -SqlInstance Server1\\Prod -Database db1 -BackupDirectory \\\\filestore\\backups\\servername\\instancename\\dbname\\backuptype -Type Full -ReplaceInName\nPerforms a full backup of db1 into the folder \\\\filestore\\backups\\server1\\prod\\db1\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eBackup-Dbadatabase -SqlInstance Server1\\Prod -BackupDirectory \\\\filestore\\backups\\servername\\instancename\\dbname\\backuptype -BackupFileName dbname-backuptype-timestamp.trn -Type Log \r\n-ReplaceInName\nPerforms a log backup for every database. For the database db1 this would results in backup files in \\\\filestore\\backups\\server1\\prod\\db1\\Log\\db1-log-31102018.trn\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eBackup-DbaDatabase -SqlInstance Sql2017 -Database master -BackupFileName NUL\nPerforms a backup of master, but sends the output to the NUL device (ie; throws it away)",
        "Params":  [
                       [
                           "SqlInstance",
                           "The SQL Server instance hosting the databases to be backed up.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Credentials to connect to the SQL Server instance if the calling user does not have permission.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process. This list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude. This list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "BackupDirectory",
                           "Path in which to place the backup files. If not specified, the backups will be placed in the default backup location for SqlInstance.\r\nIf multiple paths are specified, the backups will be striped across these locations. This will overwrite the FileCount option.\nIf the path does not exist, Sql Server will attempt to create it. Folders are created by the Sql Instance, and checks will be made for write permissions.\nFile Names with be suffixed with x-of-y to enable identifying striped sets, where y is the number of files in the set and x ranges from 1 to y.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "BackupFileName",
                           "The name of the file to backup to. This is only accepted for single database backups.\r\nIf no name is specified then the backup files will be named DatabaseName_yyyyMMddHHmm (i.e. \"Database1_201714022131\") with the appropriate extension.\nIf the same name is used repeatedly, SQL Server will add backups to the same file at an incrementing position.\nSQL Server needs permissions to write to the specified location. Path names are based on the SQL Server (C:\\ is the C drive on the SQL Server, not the machine running the script).\nPassing in NUL as the BackupFileName will backup to the NUL: device",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ReplaceInName",
                           "If this switch is set, the following list of strings will be replaced in the BackupFileName and BackupDirectory strings:\r\n    instancename - will be replaced with the instance Name\r\n    servername - will be replaced with the server name\r\n    dbname - will be replaced with the database name\r\n    timestamp - will be replaced with the timestamp (either the default, or the format provided)\r\n    backuptype - will be replaced with Full, Log or Differential as appropriate",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "CopyOnly",
                           "If this switch is enabled, CopyOnly backups will be taken. By default function performs a normal backup, these backups interfere with the restore chain of the database. CopyOnly backups will not \r\ninterfere with the restore chain of the database.\nFor more details please refer to this MSDN article - https://msdn.microsoft.com/en-us/library/ms191495.aspx",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Type",
                           "The type of SQL Server backup to perform. Accepted values are \"Full\", \"Log\", \"Differential\", \"Diff\", \"Database\"",
                           "",
                           false,
                           "false",
                           "Database"
                       ],
                       [
                           "InputObject",
                           "Internal parameter",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "CreateFolder",
                           "If this switch is enabled, each database will be backed up into a separate folder on each of the paths specified by BackupDirectory.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "FileCount",
                           "This is the number of striped copies of the backups you wish to create.    This value is overwritten if you specify multiple Backup Directories.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "CompressBackup",
                           "If this switch is enabled, the function will try to perform a compressed backup if supported by the version and edition of SQL Server. Otherwise, this function will use the server(s) default setting \r\nfor compression.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Checksum",
                           "If this switch is enabled, the backup checksum will be calculated.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Verify",
                           "If this switch is enabled, the backup will be verified by running a RESTORE VERIFYONLY against the SqlInstance",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "MaxTransferSize",
                           "Sets the size of the unit of transfer. Values must be a multiple of 64kb.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "BlockSize",
                           "Specifies the block size to use. Must be one of 0.5KB, 1KB, 2KB, 4KB, 8KB, 16KB, 32KB or 64KB. This can be specified in bytes.\r\nRefer to https://msdn.microsoft.com/en-us/library/ms178615.aspx for more detail",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "BufferCount",
                           "Number of I/O buffers to use to perform the operation.\r\nRefer to https://msdn.microsoft.com/en-us/library/ms178615.aspx for more detail",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "AzureBaseUrl",
                           "The URL to the base container of an Azure Storage account to write backups to.\nIf specified, the only other parameters than can be used are \"NoCopyOnly\", \"Type\", \"CompressBackup\", \"Checksum\", \"Verify\", \"AzureCredential\", \"CreateFolder\".",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AzureCredential",
                           "The name of the credential on the SQL instance that can write to the AzureBaseUrl, only needed if using Storage access keys\r\nIf using SAS credentials, the command will look for a credential with a name matching the AzureBaseUrl",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NoRecovery",
                           "This is passed in to perform a tail log backup if needed",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "BuildPath",
                           "By default this command will not attempt to create missing paths, this switch will change the behaviour so that it will",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WithFormat",
                           "Formats the media as the first step of the backup operation. NOTE: This will set Initialize and SkipTapeHeader to $true.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Initialize",
                           "Initializes the media as part of the backup operation.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "SkipTapeHeader",
                           "Initializes the media as part of the backup operation.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "TimeStampFormat",
                           "By default the command timestamps backups using the format yyyyMMddHHmm. Using this parameter this can be overridden. The timestamp format should be defined using the Get-Date formats, illegal \r\nformats will cause an error to be thrown",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IgnoreFileChecks",
                           "This switch stops the function from checking for the validity of paths. This can be useful if SQL Server only has read access to the backup area.\r\nNote, that as we cannot check the path you may well end up with errors.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "OutputScriptOnly",
                           "Switch causes only the T-SQL script for the backup to be generated. Will not create any paths if they do not exist",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Backup-DbaDatabase [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-BackupDirectory \u003cString[]\u003e] [-BackupFileName \u003cString\u003e] [-ReplaceInName] [-CopyOnly] [-Type \u003cString\u003e] [-CreateFolder] [-FileCount \u003cInt32\u003e] [-CompressBackup] [-Checksum] [-Verify] [-MaxTransferSize \u003cInt32\u003e] [-BlockSize \u003cInt32\u003e] [-BufferCount \u003cInt32\u003e] [-AzureBaseUrl \u003cString\u003e] [-AzureCredential \u003cString\u003e] [-NoRecovery] [-BuildPath] [-WithFormat] [-Initialize] [-SkipTapeHeader] [-TimeStampFormat \u003cString\u003e] [-IgnoreFileChecks] [-OutputScriptOnly] [-EnableException] [-WhatIf] [-Confirm] \r\n[\u003cCommonParameters\u003e]\nBackup-DbaDatabase -SqlInstance \u003cDbaInstanceParameter\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-BackupDirectory \u003cString[]\u003e] [-BackupFileName \u003cString\u003e] [-ReplaceInName] [-CopyOnly] [-Type \u003cString\u003e] [-CreateFolder] [-FileCount \u003cInt32\u003e] [-CompressBackup] [-Checksum] [-Verify] [-MaxTransferSize \u003cInt32\u003e] [-BlockSize \u003cInt32\u003e] [-BufferCount \u003cInt32\u003e] [-AzureBaseUrl \u003cString\u003e] [-AzureCredential \u003cString\u003e] [-NoRecovery] [-BuildPath] [-WithFormat] [-Initialize] [-SkipTapeHeader] [-TimeStampFormat \u003cString\u003e] [-IgnoreFileChecks] [-OutputScriptOnly] \r\n[-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nBackup-DbaDatabase [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-BackupDirectory \u003cString[]\u003e] [-BackupFileName \u003cString\u003e] [-ReplaceInName] [-CopyOnly] [-Type \u003cString\u003e] -InputObject \u003cObject[]\u003e [-CreateFolder] [-FileCount \u003cInt32\u003e] [-CompressBackup] [-Checksum] [-Verify] [-MaxTransferSize \u003cInt32\u003e] [-BlockSize \u003cInt32\u003e] [-BufferCount \u003cInt32\u003e] [-AzureBaseUrl \u003cString\u003e] [-AzureCredential \u003cString\u003e] [-NoRecovery] [-BuildPath] [-WithFormat] [-Initialize] [-SkipTapeHeader] [-TimeStampFormat \u003cString\u003e] [-IgnoreFileChecks] [-OutputScriptOnly] [-EnableException] \r\n[-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Backup-DbaDbCertificate",
        "Description":  "Exports database certificates from SQL Server using SMO and outputs the .cer and .pvk files.",
        "Tags":  [
                     "Migration",
                     "Certificate"
                 ],
        "Synopsis":  "Exports database certificates from SQL Server using SMO.",
        "Alias":  "Backup-DbaDatabaseCertificate",
        "Author":  "Jess Pomfret (@jpomfret)",
        "CommandName":  "Backup-DbaDbCertificate",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eBackup-DbaDbCertificate -SqlInstance Server1\nExports all the certificates on the specified SQL Server to the default data path for the instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Backup-DbaDbCertificate -SqlInstance Server1 -SqlCredential $cred\nConnects using sqladmin credential and exports all the certificates on the specified SQL Server to the default data path for the instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eBackup-DbaDbCertificate -SqlInstance Server1 -Certificate Certificate1\nExports only the certificate named Certificate1 on the specified SQL Server to the default data path for the instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eBackup-DbaDbCertificate -SqlInstance Server1 -Database AdventureWorks\nExports only the certificates for AdventureWorks on the specified SQL Server to the default data path for the instance.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eBackup-DbaDbCertificate -SqlInstance Server1 -ExcludeDatabase AdventureWorks\nExports all certificates except those for AdventureWorks on the specified SQL Server to the default data path for the instance.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eBackup-DbaDbCertificate -SqlInstance Server1 -Path \\\\Server1\\Certificates -EncryptionPassword (ConvertTo-SecureString -force -AsPlainText GoodPass1234!!)\nExports all the certificates and private keys on the specified SQL Server.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$EncryptionPassword = ConvertTo-SecureString -AsPlainText \"GoodPass1234!!\" -force\nPS C:\\\u003e $DecryptionPassword = ConvertTo-SecureString -AsPlainText \"Password4567!!\" -force\r\nPS C:\\\u003e Backup-DbaDbCertificate -SqlInstance Server1 -EncryptionPassword $EncryptionPassword -DecryptionPassword $DecryptionPassword\nExports all the certificates on the specified SQL Server using the supplied DecryptionPassword, since an EncryptionPassword is specified private keys are also exported.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eBackup-DbaDbCertificate -SqlInstance Server1 -Path \\\\Server1\\Certificates\nExports all certificates on the specified SQL Server to the specified path.\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eBackup-DbaDbCertificate -SqlInstance Server1 -Suffix DbaTools\nExports all certificates on the specified SQL Server to the specified path, appends DbaTools to the end of the filenames.\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003eGet-DbaDbCertificate -SqlInstance sql2016 | Backup-DbaDbCertificate\nExports all certificates found on sql2016 to the default data directory.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Certificate",
                           "Exports certificate that matches the name(s).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Exports the encryptor for specific database(s).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Database(s) to skip when exporting encryptors.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EncryptionPassword",
                           "A string value that specifies the system path to encrypt the private key.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DecryptionPassword",
                           "A string value that specifies the system path to decrypt the private key.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "The path to output the files to. The path is relative to the SQL Server itself. If no path is specified, the default data directory will be used.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Suffix",
                           "The suffix of the filename of the exported certificate.",
                           "",
                           false,
                           "false",
                           "\"$(Get-Date -format \u0027yyyyMMddHHmmssms\u0027)\""
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaDbCertificate",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Backup-DbaDbCertificate [-SqlCredential \u003cPSCredential\u003e] [-EncryptionPassword \u003cSecureString\u003e] [-DecryptionPassword \u003cSecureString\u003e] [-Path \u003cFileInfo\u003e] [-Suffix \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nBackup-DbaDbCertificate -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Certificate \u003cObject[]\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-EncryptionPassword \u003cSecureString\u003e] [-DecryptionPassword \u003cSecureString\u003e] [-Path \u003cFileInfo\u003e] [-Suffix \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nBackup-DbaDbCertificate [-SqlCredential \u003cPSCredential\u003e] [-EncryptionPassword \u003cSecureString\u003e] [-DecryptionPassword \u003cSecureString\u003e] [-Path \u003cFileInfo\u003e] [-Suffix \u003cString\u003e] [-InputObject \u003cCertificate[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Backup-DbaDbMasterKey",
        "Description":  "Backs up specified database master key.",
        "Tags":  [
                     "Certificate",
                     "Database"
                 ],
        "Synopsis":  "Backs up specified database master key.",
        "Alias":  "Backup-DbaDatabaseMasterKey",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Backup-DbaDbMasterKey",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eBackup-DbaDbMasterKey -SqlInstance server1\\sql2016\n```\r\nComputerName : SERVER1\r\nInstanceName : SQL2016\r\nSqlInstance  : SERVER1\\SQL2016\r\nDatabase     : master\r\nFilename     : E:\\MSSQL13.SQL2016\\MSSQL\\Backup\\server1$sql2016-master-20170614162311.key\r\nStatus       : Success\r\n```\nPrompts for export password, then logs into server1\\sql2016 with Windows credentials then backs up all database keys to the default backup directory.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eBackup-DbaDbMasterKey -SqlInstance Server1 -Database db1 -Path \\\\nas\\sqlbackups\\keys\nLogs into sql2016 with Windows credentials then backs up db1\u0027s keys to the \\\\nas\\sqlbackups\\keys directory.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to SQL Server using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Credential",
                           "Pass a credential object for the password",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Backup master key from specific database(s).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SecurePassword",
                           "The password to encrypt the exported key. This must be a SecureString.",
                           "Password",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "The directory to export the key. If no path is specified, the default backup directory for the instance will be used.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Database object piped in from Get-DbaDatabase",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Backup-DbaDbMasterKey [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-SecurePassword] \u003cSecureString\u003e] [[-Path] \u003cString\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Clear-DbaConnectionPool",
        "Description":  "This command resets (or empties) the connection pool.\n\nIf there are connections in use at the time of the call, they are marked appropriately and will be discarded (instead of being returned to the pool) when Close() is called on them.\n\nRef: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.clearallpools(v=vs.110).aspx",
        "Tags":  "Connection",
        "Synopsis":  "Resets (or empties) the connection pool.",
        "Alias":  "Clear-DbaSqlConnectionPool",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Clear-DbaConnectionPool",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Clear-DbaConnectionPool",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eClear-DbaConnectionPool\nClears all local connection pools.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eClear-DbaConnectionPool -ComputerName workstation27\nClears all connection pools on workstation27.",
        "Params":  [
                       [
                           "ComputerName",
                           "Target computer(s). If no computer name is specified, the local computer is targeted.",
                           "cn,host,Server",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Alternate credential object to use for accessing the target computer(s).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Clear-DbaConnectionPool [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Clear-DbaLatchStatistics",
        "Description":  "Reset the aggregated statistics - basically just executes DBCC SQLPERF (N\u0027sys.dm_os_latch_stats\u0027, CLEAR)",
        "Tags":  [
                     "LatchStatistic",
                     "Waits"
                 ],
        "Synopsis":  "Clears Latch Statistics",
        "Alias":  "",
        "Author":  "Patrick Flynn (@sqllensman)",
        "CommandName":  "Clear-DbaLatchStatistics",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Clear-DbaLatchStatistics",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eClear-DbaLatchStatistics -SqlInstance sql2008, sqlserver2012\nAfter confirmation, clears latch statistics on servers sql2008 and sqlserver2012\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eClear-DbaLatchStatistics -SqlInstance sql2008, sqlserver2012 -Confirm:$false\nClears latch statistics on servers sql2008 and sqlserver2012, without prompting\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027sql2008\u0027,\u0027sqlserver2012\u0027 | Clear-DbaLatchStatistics\nAfter confirmation, clears latch statistics on servers sql2008 and sqlserver2012\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Clear-DbaLatchStatistics -SqlInstance sql2008 -SqlCredential $cred\nConnects using sqladmin credential and clears latch statistics on servers sql2008 and sqlserver2012",
        "Params":  [
                       [
                           "SqlInstance",
                           "Allows you to specify a comma separated list of servers to query.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Clear-DbaLatchStatistics [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Clear-DbaPlanCache",
        "Description":  "Checks ad-hoc and prepared plan cache for each database, if over 100 MBs removes from the cache.\n\nThis command automates that process.\n\nReferences: https://www.sqlskills.com/blogs/kimberly/plan-cache-adhoc-workloads-and-clearing-the-single-use-plan-cache-bloat/",
        "Tags":  "Memory",
        "Synopsis":  "Removes ad-hoc and prepared plan caches is single use plans are over defined threshold.",
        "Alias":  "",
        "Author":  "Tracy Boggiano, databasesuperhero.com",
        "CommandName":  "Clear-DbaPlanCache",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Clear-DbaPlanCache",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eClear-DbaPlanCache -SqlInstance sql2017 -Threshold 200\nLogs into the SQL Server instance \"sql2017\" and removes plan caches if over 200 MB.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eClear-DbaPlanCache -SqlInstance sql2017 -SqlCredential sqladmin\nLogs into the SQL instance using the SQL Login \u0027sqladmin\u0027 and then Windows instance as \u0027ad\\sqldba\u0027\r\nand removes if Threshold over 100 MB.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaInstance -ComputerName localhost | Get-DbaPlanCache | Clear-DbaPlanCache -Threshold 200\nScans localhost for instances using the browser service, traverses all instances and gets the plan cache for each, clears them out if they are above 200 MB.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer,SqlServers",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Threshold",
                           "Memory used threshold.",
                           "",
                           false,
                           "false",
                           "100"
                       ],
                       [
                           "InputObject",
                           "Enables results to be piped in from Get-DbaPlanCache.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Clear-DbaPlanCache [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Threshold] \u003cInt32\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Clear-DbaWaitStatistics",
        "Description":  "Reset the aggregated statistics - basically just executes DBCC SQLPERF (N\u0027sys.dm_os_wait_stats\u0027, CLEAR)",
        "Tags":  [
                     "WaitStatistic",
                     "Waits"
                 ],
        "Synopsis":  "Clears wait statistics",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl)",
        "CommandName":  "Clear-DbaWaitStatistics",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Clear-DbaWaitStatistics",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eClear-DbaWaitStatistics -SqlInstance sql2008, sqlserver2012\nAfter confirmation, clears wait stats on servers sql2008 and sqlserver2012\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eClear-DbaWaitStatistics -SqlInstance sql2008, sqlserver2012 -Confirm:$false\nClears wait stats on servers sql2008 and sqlserver2012, without prompting",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Clear-DbaWaitStatistics [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Connect-DbaInstance",
        "Description":  "This command is robust because it initializes properties that do not cause enumeration by default. It also supports both Windows and SQL Server authentication methods, and detects which to use based upon the provided credentials.\n\nBy default, this command also sets the connection\u0027s ApplicationName property  to \"dbatools PowerShell module - dbatools.io - custom connection\". If you\u0027re doing anything that requires profiling, you can look for this client name.\n\nAlternatively, you can pass in whichever client name you\u0027d like using the -ClientName parameter. There are a ton of other parameters for you to explore as well.\n\nSee https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx\nand https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.aspx,\nand https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx\n\nTo execute SQL commands, you can use $server.ConnectionContext.ExecuteReader($sql) or $server.Databases[\u0027master\u0027].ExecuteNonQuery($sql)",
        "Tags":  [
                     "Connect",
                     "Connection"
                 ],
        "Synopsis":  "Creates a robust SMO SQL Server object.",
        "Alias":  "Connect-DbaServer,Get-DbaInstance",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Connect-DbaInstance",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Connect-DbaInstance",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eConnect-DbaInstance -SqlInstance sql2014\nCreates an SMO Server object that connects using Windows Authentication\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$wincred = Get-Credential ad\\sqladmin\nPS C:\\\u003e Connect-DbaInstance -SqlInstance sql2014 -SqlCredential $wincred\nCreates an SMO Server object that connects using alternative Windows credentials\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$sqlcred = Get-Credential sqladmin\nPS C:\\\u003e $server = Connect-DbaInstance -SqlInstance sql2014 -SqlCredential $sqlcred\nLogin to sql2014 as SQL login sqladmin.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance -SqlInstance sql2014 -ClientName \"my connection\"\nCreates an SMO Server object that connects using Windows Authentication and uses the client name \"my connection\". So when you open up profiler or use extended events, you can search for \"my \r\nconnection\".\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance -SqlInstance sql2014 -AppendConnectionString \"Packet Size=4096;AttachDbFilename=C:\\MyFolder\\MyDataFile.mdf;User Instance=true;\"\nCreates an SMO Server object that connects to sql2014 using Windows Authentication, then it sets the packet size (this can also be done via -PacketSize) and other connection attributes.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance -SqlInstance sql2014 -NetworkProtocol TcpIp -MultiSubnetFailover\nCreates an SMO Server object that connects using Windows Authentication that uses TCP/IP and has MultiSubnetFailover enabled.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance sql2016 -ApplicationIntent ReadOnly\nConnects with ReadOnly ApplicationIntent.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Credential object used to connect to the SQL Server Instance as a different user. This can be a Windows or SQL Server account. Windows users are determined by the existence of a backslash, so if you \r\nare intending to use an alternative Windows connection instead of a SQL login, ensure it contains a backslash.",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process. This list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AccessToken",
                           "Gets or sets the access token for the connection.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ApplicationIntent",
                           "Declares the application workload type when connecting to a server.\nValid values are \"ReadOnly\" and \"ReadWrite\".",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "BatchSeparator",
                           "A string to separate groups of SQL statements being executed. By default, this is \"GO\".",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ClientName",
                           "By default, this command sets the client\u0027s ApplicationName property to \"dbatools PowerShell module - dbatools.io - custom connection\" if you\u0027re doing anything that requires profiling, you can look \r\nfor this client name. Using -ClientName allows you to set your own custom client application name.",
                           "",
                           false,
                           "false",
                           "dbatools PowerShell module - dbatools.io - custom connection"
                       ],
                       [
                           "ConnectTimeout",
                           "The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error.\nValid values are integers between 0 and 2147483647.\nWhen opening a connection to a Azure SQL Database, set the connection timeout to 30 seconds.",
                           "",
                           false,
                           "false",
                           "([Sqlcollaborative.Dbatools.Connection.ConnectionHost]::SqlConnectionTimeout)"
                       ],
                       [
                           "EncryptConnection",
                           "If this switch is enabled, SQL Server uses SSL encryption for all data sent between the client and server if the server has a certificate installed.\nFor more information, see Connection String Syntax. https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/connection-string-syntax\nBeginning in .NET Framework 4.5, when TrustServerCertificate is false and Encrypt is true, the server name (or IP address) in a SQL Server SSL certificate must exactly match the server name (or IP \r\naddress) specified in the connection string. Otherwise, the connection attempt will fail. For information about support for certificates whose subject starts with a wildcard character (*), see \r\nAccepted wildcards used by server certificates for server authentication. https://support.microsoft.com/en-us/help/258858/accepted-wildcards-used-by-server-certificates-for-server-authenticati",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "FailoverPartner",
                           "The name of the failover partner server where database mirroring is configured.\nIf the value of this key is \"\" (an empty string), then Initial Catalog must be present in the connection string, and its value must not be \"\".\nThe server name can be 128 characters or less.\nIf you specify a failover partner but the failover partner server is not configured for database mirroring and the primary server (specified with the Server keyword) is not available, then the \r\nconnection will fail.\nIf you specify a failover partner and the primary server is not configured for database mirroring, the connection to the primary server (specified with the Server keyword) will succeed if the primary \r\nserver is available.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "LockTimeout",
                           "Sets the time in seconds required for the connection to time out when the current transaction is locked.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "MaxPoolSize",
                           "Sets the maximum number of connections allowed in the connection pool for this specific connection string.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "MinPoolSize",
                           "Sets the minimum number of connections allowed in the connection pool for this specific connection string.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "MultipleActiveResultSets",
                           "If this switch is enabled, an application can maintain multiple active result sets (MARS).\nIf this switch is not enabled, an application must process or cancel all result sets from one batch before it can execute any other batch on that connection.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "MultiSubnetFailover",
                           "If this switch is enabled, and your application is connecting to an AlwaysOn availability group (AG) on different subnets, detection of and connection to the currently active server will be faster. \r\nFor more information about SqlClient support for Always On Availability Groups, see \r\nhttps://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/sqlclient-support-for-high-availability-disaster-recovery",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NetworkProtocol",
                           "Explicitly sets the network protocol used to connect to the server.\nValid values are \"TcpIp\",\"NamedPipes\",\"Multiprotocol\",\"AppleTalk\",\"BanyanVines\",\"Via\",\"SharedMemory\" and \"NWLinkIpxSpx\"",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NonPooledConnection",
                           "If this switch is enabled, a non-pooled connection will be requested.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "PacketSize",
                           "Sets the size in bytes of the network packets used to communicate with an instance of SQL Server. Must match at server.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "PooledConnectionLifetime",
                           "When a connection is returned to the pool, its creation time is compared with the current time and the connection is destroyed if that time span (in seconds) exceeds the value specified by Connection \r\nLifetime. This is useful in clustered configurations to force load balancing between a running server and a server just brought online.\nA value of zero (0) causes pooled connections to have the maximum connection timeout.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "SqlExecutionModes",
                           "The SqlExecutionModes enumeration contains values that are used to specify whether the commands sent to the referenced connection to the server are executed immediately or saved in a buffer.\nValid values include \"CaptureSql\", \"ExecuteAndCaptureSql\" and \"ExecuteSql\".",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "StatementTimeout",
                           "Sets the number of seconds a statement is given to run before failing with a timeout error.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "TrustServerCertificate",
                           "When this switch is enabled, the channel will be encrypted while bypassing walking the certificate chain to validate trust.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WorkstationId",
                           "Sets the name of the workstation connecting to SQL Server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AppendConnectionString",
                           "Appends to the current connection string. Note that you cannot pass authentication information using this method. Use -SqlInstance and optionally -SqlCredential to set authentication information.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlConnectionOnly",
                           "Instead of returning a rich SMO server object, this command will only return a SqlConnection object when setting this switch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DisableException",
                           "By default in most of our commands, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\nThis command, however, gifts you  with \"sea of red\" exceptions, by default, because it is useful for advanced scripting.\nUsing this switch turns our \"nice by default\" feature on which makes errors into pretty warnings.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Connect-DbaInstance [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-AccessToken] \u003cString\u003e] [[-ApplicationIntent] \u003cString\u003e] [[-BatchSeparator] \u003cString\u003e] [[-ClientName] \u003cString\u003e] [[-ConnectTimeout] \u003cInt32\u003e] [-EncryptConnection] [[-FailoverPartner] \u003cString\u003e] [[-LockTimeout] \u003cInt32\u003e] [[-MaxPoolSize] \u003cInt32\u003e] [[-MinPoolSize] \u003cInt32\u003e] [-MultipleActiveResultSets] [-MultiSubnetFailover] [[-NetworkProtocol] \u003cString\u003e] [-NonPooledConnection] [[-PacketSize] \u003cInt32\u003e] [[-PooledConnectionLifetime] \u003cInt32\u003e] [[-SqlExecutionModes] \u003cString\u003e] \r\n[[-StatementTimeout] \u003cInt32\u003e] [-TrustServerCertificate] [[-WorkstationId] \u003cString\u003e] [[-AppendConnectionString] \u003cString\u003e] [-SqlConnectionOnly] [-DisableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "ConvertTo-DbaDataTable",
        "Description":  "Creates a DataTable based on an object\u0027s properties. This allows you to easily write to SQL Server tables.\n\nThanks to Chad Miller, this is based on his script. https://gallery.technet.microsoft.com/scriptcenter/4208a159-a52e-4b99-83d4-8048468d29dd\n\nIf the attempt to convert to data table fails, try the -Raw parameter for less accurate datatype detection.",
        "Tags":  [
                     "DataTable",
                     "Table",
                     "Data"
                 ],
        "Synopsis":  "Creates a DataTable for an object.",
        "Alias":  "Out-DbaDataTable",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "ConvertTo-DbaDataTable",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/ConvertTo-DbaDataTable",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-Service | ConvertTo-DbaDataTable\nCreates a DataTable from the output of Get-Service.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eConvertTo-DbaDataTable -InputObject $csv.cheesetypes\nCreates a DataTable from the CSV object $csv.cheesetypes.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$dblist | ConvertTo-DbaDataTable\nCreates a DataTable from the $dblist object passed in via pipeline.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-Process | ConvertTo-DbaDataTable -TimeSpanType TotalSeconds\nCreates a DataTable with the running processes and converts any TimeSpan property to TotalSeconds.",
        "Params":  [
                       [
                           "InputObject",
                           "The object to transform into a DataTable.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "TimeSpanType",
                           "Specifies the type to convert TimeSpan objects into. Default is \u0027TotalMilliseconds\u0027. Valid options are: \u0027Ticks\u0027, \u0027TotalDays\u0027, \u0027TotalHours\u0027, \u0027TotalMinutes\u0027, \u0027TotalSeconds\u0027, \u0027TotalMilliseconds\u0027, and \r\n\u0027String\u0027.",
                           "",
                           false,
                           "false",
                           "TotalMilliseconds"
                       ],
                       [
                           "SizeType",
                           "Specifies the type to convert DbaSize objects to. Default is \u0027Int64\u0027. Valid options are \u0027Int32\u0027, \u0027Int64\u0027, and \u0027String\u0027.",
                           "",
                           false,
                           "false",
                           "Int64"
                       ],
                       [
                           "IgnoreNull",
                           "If this switch is enabled, objects with null values will be ignored (empty rows will be added by default).",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Raw",
                           "If this switch is enabled, the DataTable will be created with strings. No attempt will be made to parse/determine data types.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "ConvertTo-DbaDataTable [-InputObject] \u003cPSObject[]\u003e [[-TimeSpanType] \u003cString\u003e] [-SizeType \u003cString\u003e] [-IgnoreNull] [-Raw] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "ConvertTo-DbaTimeline",
        "Description":  "This function accepts input as pipeline from the following dbatools functions:\nGet-DbaAgentJobHistory\nGet-DbaBackupHistory\n(more to come...)\nAnd generates Bootstrap based, HTML file with Google Chart Timeline",
        "Tags":  "Chart",
        "Synopsis":  "Converts InputObject to a html timeline using Google Chart",
        "Alias":  "",
        "Author":  "Marcin Gminski (@marcingminski)",
        "CommandName":  "ConvertTo-DbaTimeline",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/ConvertTo-DbaTimeline",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentJobHistory -SqlInstance sql-1 -StartDate \u00272018-08-13 00:00\u0027 -EndDate \u00272018-08-13 23:59\u0027 -ExcludeJobSteps | ConvertTo-DbaTimeline | Out-File C:\\temp\\DbaAgentJobHistory.html \r\n-Encoding ASCII\nCreates an output file containing a pretty timeline for all of the agent job history results for sql-1 the whole day of 2018-08-13\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sqlcm | Get-DbaBackupHistory -Since \u00272018-08-13 00:00\u0027 | ConvertTo-DbaTimeline | Out-File C:\\temp\\DbaBackupHistory.html -Encoding ASCII\nCreates an output file containing a pretty timeline for the agent job history since 2018-08-13 for all of the registered servers on sqlcm\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$messageParameters = @{\n\u003e\u003e Subject = \"Backup history for sql2017 and sql2016\"\r\n\u003e\u003e Body = Get-DbaBackupHistory -SqlInstance sql2017, sql2016 -Since \u00272018-08-13 00:00\u0027 | ConvertTo-DbaTimeline\r\n\u003e\u003e From = \"[email protected]\"\r\n\u003e\u003e To = \"[email protected]\"\r\n\u003e\u003e SmtpServer = \"smtp.ad.local\"\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Send-MailMessage @messageParameters -BodyAsHtml\nSends an email to [email protected] with the results of Get-DbaBackupHistory. Note that viewing these reports may not be supported in all email clients.",
        "Params":  [
                       [
                           "InputObject",
                           "Pipe input, must an output from the above functions.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "ConvertTo-DbaTimeline [-InputObject] \u003cObject[]\u003e [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "ConvertTo-DbaXESession",
        "Description":  "Uses a slightly modified version of sp_SQLskills_ConvertTraceToExtendedEvents.sql to convert Traces to Extended Events.\n\nT-SQL code by: Jonathan M. Kehayias, SQLskills.com. T-SQL can be found in this module directory and at\nhttps://www.sqlskills.com/blogs/jonathan/converting-sql-trace-to-extended-events-in-sql-server-2012/",
        "Tags":  [
                     "Trace",
                     "ExtendedEvent"
                 ],
        "Synopsis":  "Uses a slightly modified version of sp_SQLskills_ConvertTraceToExtendedEvents.sql to convert Traces to Extended Events.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "ConvertTo-DbaXESession",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaTrace -SqlInstance sql2017, sql2012 | Where Id -eq 2 | ConvertTo-DbaXESession -Name \u0027Test\u0027\nConverts Trace with ID 2 to a Session named Test on SQL Server instances named sql2017 and sql2012 and creates the Session on each respective server.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaTrace -SqlInstance sql2014 | Out-GridView -PassThru | ConvertTo-DbaXESession -Name \u0027Test\u0027 | Start-DbaXESession\nConverts selected traces on sql2014 to sessions, creates the session, and starts it.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaTrace -SqlInstance sql2014 | Where Id -eq 1 | ConvertTo-DbaXESession -Name \u0027Test\u0027 -OutputScriptOnly\nConverts trace ID 1 on sql2014 to an Extended Event and outputs the resulting T-SQL.",
        "Params":  [
                       [
                           "InputObject",
                           "Specifies a Trace object output by Get-DbaTrace.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Name",
                           "The name of the Trace to convert. If the name exists, characters will be appended to it.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "OutputScriptOnly",
                           "Outputs the T-SQL script to create the XE session and does not execute it.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "ConvertTo-DbaXESession [-InputObject] \u003cObject[]\u003e [-Name] \u003cString\u003e [-OutputScriptOnly] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaAgentAlert",
        "Description":  "By default, all alerts are copied. The -Alert parameter is auto-populated for command-line completion and can be used to copy only specific alerts.\n\nIf the alert already exists on the destination, it will be skipped unless -Force is used.",
        "Tags":  [
                     "Migration",
                     "Agent"
                 ],
        "Synopsis":  "Copy-DbaAgentAlert migrates alerts from one SQL Server to another.",
        "Alias":  "Copy-SqlAlert",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaAgentAlert",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaAgentAlert",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaAgentAlert -Source sqlserver2014a -Destination sqlcluster\nCopies all alerts from sqlserver2014a to sqlcluster using Windows credentials. If alerts with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaAgentAlert -Source sqlserver2014a -Destination sqlcluster -Alert PSAlert -SourceSqlCredential $cred -Force\nCopies a only the alert named PSAlert from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If an alert with the same name exists on \r\nsqlcluster, it will be dropped and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaAgentAlert -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Alert",
                           "The alert(s) to process. This list is auto-populated from the server. If unspecified, all alerts will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeAlert",
                           "The alert(s) to exclude. This list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IncludeDefaults",
                           "Copy SQL Agent defaults such as FailSafeEmailAddress, ForwardingServer, and PagerSubjectTemplate.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "If this switch is enabled, the Alert will be dropped and recreated on Destination.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaAgentAlert [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Alert] \u003cObject[]\u003e] [[-ExcludeAlert] \u003cObject[]\u003e] [-IncludeDefaults] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaAgentJob",
        "Description":  "By default, all jobs are copied. The -Job parameter is auto-populated for command-line completion and can be used to copy only specific jobs.\n\nIf the job already exists on the destination, it will be skipped unless -Force is used.",
        "Tags":  [
                     "Migration",
                     "Agent",
                     "Job"
                 ],
        "Synopsis":  "Copy-DbaAgentJob migrates jobs from one SQL Server to another.",
        "Alias":  "Copy-SqlJob",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaAgentJob",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaAgentJob",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaAgentJob -Source sqlserver2014a -Destination sqlcluster\nCopies all jobs from sqlserver2014a to sqlcluster, using Windows credentials. If jobs with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaAgentJob -Source sqlserver2014a -Destination sqlcluster -Job PSJob -SourceSqlCredential $cred -Force\nCopies a single job, the PSJob job from sqlserver2014a to sqlcluster, using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If a job with the same name exists on \r\nsqlcluster, it will be dropped and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaAgentJob -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance sqlserver2014a | Where-Object Category -eq \"Report Server\" | ForEach-Object {Copy-DbaAgentJob -Source $_.SqlInstance -Job $_.Name -Destination sqlserver2014b}\nCopies all SSRS jobs (subscriptions) from AlwaysOn Primary SQL instance sqlserver2014a to AlwaysOn Secondary SQL instance sqlserver2014b",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Job",
                           "The job(s) to process. This list is auto-populated from the server. If unspecified, all jobs will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeJob",
                           "The job(s) to exclude. This list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DisableOnSource",
                           "If this switch is enabled, the job will be disabled on the source server.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DisableOnDestination",
                           "If this switch is enabled, the newly migrated job will be disabled on the destination server.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "If this switch is enabled, the Job will be dropped and recreated on Destination.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaAgentJob [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Job] \u003cObject[]\u003e] [[-ExcludeJob] \u003cObject[]\u003e] [-DisableOnSource] [-DisableOnDestination] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaAgentJobCategory",
        "Description":  "By default, all SQL Agent categories for Jobs, Operators and Alerts are copied.\n\nThe -OperatorCategories parameter is auto-populated for command-line completion and can be used to copy only specific operator categories.\nThe -AgentCategories parameter is auto-populated for command-line completion and can be used to copy only specific agent categories.\nThe -JobCategories parameter is auto-populated for command-line completion and can be used to copy only specific job categories.\n\nIf the category already exists on the destination, it will be skipped unless -Force is used.",
        "Tags":  [
                     "Migration",
                     "Agent"
                 ],
        "Synopsis":  "Copy-DbaAgentJobCategory migrates SQL Agent categories from one SQL Server to another. This is similar to sp_add_category.\n\nhttps://msdn.microsoft.com/en-us/library/ms181597.aspx",
        "Alias":  "Copy-DbaAgentCategory,Copy-SqlAgentCategory",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaAgentJobCategory",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaAgentJobCategory",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaAgentJobCategory -Source sqlserver2014a -Destination sqlcluster\nCopies all operator categories from sqlserver2014a to sqlcluster using Windows authentication. If operator categories with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaAgentJobCategory -Source sqlserver2014a -Destination sqlcluster -OperatorCategory PSOperator -SourceSqlCredential $cred -Force\nCopies a single operator category, the PSOperator operator category from sqlserver2014a to sqlcluster using SQL credentials to authenticate to sqlserver2014a and Windows credentials for sqlcluster. \r\nIf an operator category with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaAgentJobCategory -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CategoryType",
                           "Specifies the Category Type to migrate. Valid options are \"Job\", \"Alert\" and \"Operator\". When CategoryType is specified, all categories from the selected type will be migrated. For granular \r\nmigrations, use the three parameters below.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "JobCategory",
                           "This parameter is auto-populated for command-line completion and can be used to copy only specific job categories.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AgentCategory",
                           "This parameter is auto-populated for command-line completion and can be used to copy only specific agent categories.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "OperatorCategory",
                           "This parameter is auto-populated for command-line completion and can be used to copy only specific operator categories.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, the Category will be dropped and recreated on Destination.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaAgentJobCategory -Source \u003cDbaInstanceParameter\u003e [-SourceSqlCredential \u003cPSCredential\u003e] -Destination \u003cDbaInstanceParameter[]\u003e [-DestinationSqlCredential \u003cPSCredential\u003e] [-JobCategory \u003cString[]\u003e] [-AgentCategory \u003cString[]\u003e] [-OperatorCategory \u003cString[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nCopy-DbaAgentJobCategory -Source \u003cDbaInstanceParameter\u003e [-SourceSqlCredential \u003cPSCredential\u003e] -Destination \u003cDbaInstanceParameter[]\u003e [-DestinationSqlCredential \u003cPSCredential\u003e] [-CategoryType \u003cString[]\u003e] [-JobCategory \u003cString[]\u003e] [-AgentCategory \u003cString[]\u003e] [-OperatorCategory \u003cString[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaAgentOperator",
        "Description":  "By default, all operators are copied. The -Operators parameter is auto-populated for command-line completion and can be used to copy only specific operators.\n\nIf the associated credentials for the operator do not exist on the destination, it will be skipped. If the operator already exists on the destination, it will be skipped unless -Force is used.",
        "Tags":  [
                     "Migration",
                     "Agent",
                     "Operator"
                 ],
        "Synopsis":  "Copy-DbaAgentOperator migrates operators from one SQL Server to another.",
        "Alias":  "Copy-SqlOperator",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaAgentOperator",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaAgentOperator",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaAgentOperator -Source sqlserver2014a -Destination sqlcluster\nCopies all operators from sqlserver2014a to sqlcluster using Windows credentials. If operators with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaAgentOperator -Source sqlserver2014a -Destination sqlcluster -Operator PSOperator -SourceSqlCredential $cred -Force\nCopies only the PSOperator operator from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If an operator with the same name exists on \r\nsqlcluster, it will be dropped and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaAgentOperator -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Operator",
                           "The operator(s) to process. This list is auto-populated from the server. If unspecified, all operators will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeOperator",
                           "The operators(s) to exclude. This list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, the Operator will be dropped and recreated on Destination.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaAgentOperator [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Operator] \u003cObject[]\u003e] [[-ExcludeOperator] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaAgentProxy",
        "Description":  "By default, all proxy accounts are copied. The -ProxyAccounts parameter is auto-populated for command-line completion and can be used to copy only specific proxy accounts.\n\nIf the associated credential for the account does not exist on the destination, it will be skipped. If the proxy account already exists on the destination, it will be skipped unless -Force is used.",
        "Tags":  [
                     "Migration",
                     "Agent"
                 ],
        "Synopsis":  "Copy-DbaAgentProxy migrates proxy accounts from one SQL Server to another.",
        "Alias":  "Copy-DbaAgentProxyAccount,Copy-SqlProxyAccount",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaAgentProxy",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaAgentProxy",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaAgentProxy -Source sqlserver2014a -Destination sqlcluster\nCopies all proxy accounts from sqlserver2014a to sqlcluster using Windows credentials. If proxy accounts with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaAgentProxy -Source sqlserver2014a -Destination sqlcluster -ProxyAccount PSProxy -SourceSqlCredential $cred -Force\nCopies only the PSProxy proxy account from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If a proxy account with the same name exists \r\non sqlcluster, it will be dropped and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaAgentProxy -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ProxyAccount",
                           "Only migrate specific proxy accounts",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeProxyAccount",
                           "Migrate all proxy accounts except the ones explicitly excluded",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, the Operator will be dropped and recreated on Destination.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaAgentProxy [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-ProxyAccount] \u003cString[]\u003e] [[-ExcludeProxyAccount] \u003cString[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaAgentSchedule",
        "Description":  "All shared job schedules are copied.\n\nIf the associated credential for the account does not exist on the destination, it will be skipped. If the shared job schedule already exists on the destination, it will be skipped unless -Force is used.",
        "Tags":  [
                     "Migration",
                     "Agent"
                 ],
        "Synopsis":  "Copy-DbaAgentSchedule migrates shared job schedules from one SQL Server to another.",
        "Alias":  "Copy-DbaAgentSharedSchedule,Copy-SqlSharedSchedule",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaAgentSchedule",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaAgentSchedule",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaAgentSchedule -Source sqlserver2014a -Destination sqlcluster\nCopies all shared job schedules from sqlserver2014a to sqlcluster using Windows credentials. If shared job schedules with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaAgentSchedule -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, the Operator will be dropped and recreated on Destination.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaAgentSchedule [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaAgentServer",
        "Description":  "A wrapper function that calls the associated Copy command for each of the object types seen in SSMS under SQL Server Agent. This also copies all of the the SQL Agent properties (job history max rows, DBMail profile name, etc.).\n\nYou must have sysadmin access and server version must be SQL Server version 2000 or greater.",
        "Tags":  [
                     "Migration",
                     "SqlServerAgent",
                     "SqlAgent"
                 ],
        "Synopsis":  "Copy SQL Server Agent from one server to another.",
        "Alias":  "Copy-DbaSqlServerAgent,Copy-SqlServerAgent",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaAgentServer",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaAgentServer",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaAgentServer -Source sqlserver2014a -Destination sqlcluster\nCopies all job server objects from sqlserver2014a to sqlcluster using Windows credentials for authentication. If job objects with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaAgentServer -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred\nCopies all job objects from sqlserver2014a to sqlcluster using SQL credentials to authentication to sqlserver2014a and Windows credentials to authenticate to sqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaAgentServer -Source sqlserver2014a -Destination sqlcluster -WhatIf\nShows what would happen if the command were executed.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DisableJobsOnDestination",
                           "If this switch is enabled, the jobs will be disabled on Destination after copying.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DisableJobsOnSource",
                           "If this switch is enabled, the jobs will be disabled on Source after copying.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "If this switch is enabled, existing objects on Destination with matching names from Source will be dropped, then copied.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaAgentServer [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [-DisableJobsOnDestination] [-DisableJobsOnSource] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaBackupDevice",
        "Description":  "Backups are migrated using Admin shares. If the destination directory does not exist, SQL Server\u0027s default backup directory will be used.\n\nIf a backup device with same name exists on destination, it will not be dropped and recreated unless -Force is used.",
        "Tags":  [
                     "Migration",
                     "Backup"
                 ],
        "Synopsis":  "Copies backup devices one by one. Copies both SQL code and the backup file itself.",
        "Alias":  "Copy-SqlBackupDevice",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaBackupDevice",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Copy-DbaBackupDevice",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaBackupDevice -Source sqlserver2014a -Destination sqlcluster\nCopies all server backup devices from sqlserver2014a to sqlcluster using Windows credentials. If backup devices with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaBackupDevice -Source sqlserver2014a -Destination sqlcluster -BackupDevice backup01 -SourceSqlCredential $cred -Force\nCopies only the backup device named backup01 from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a    and Windows credentials for sqlcluster. If a backup device with the same \r\nname exists on sqlcluster, it will be dropped and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaBackupDevice -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "BackupDevice",
                           "BackupDevice to be copied. Auto-populated list of devices. If not provided all BackupDevice(s) will be copied.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, backup device(s) will be dropped and recreated if they already exists on destination.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaBackupDevice [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-BackupDevice] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaCmsRegServer",
        "Description":  "Copy-DbaCmsRegServer copies all groups, subgroups, and server instances from one SQL Server to another.",
        "Tags":  "Migration",
        "Synopsis":  "Migrates SQL Server Central Management groups and server instances from one SQL Server to another.",
        "Alias":  "Copy-DbaCentralManagementServer,Copy-SqlCentralManagementServer",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaCmsRegServer",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaCmsRegServer",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaCmsRegServer -Source sqlserver2014a -Destination sqlcluster\nAll groups, subgroups, and server instances are copied from sqlserver2014a CMS to sqlcluster CMS.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaCmsRegServer -Source sqlserver2014a -Destination sqlcluster -Group Group1,Group3\nTop-level groups Group1 and Group3 along with their subgroups and server instances are copied from sqlserver to sqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaCmsRegServer -Source sqlserver2014a -Destination sqlcluster -Group Group1,Group3 -SwitchServerName -SourceSqlCredential $SourceSqlCredential -DestinationSqlCredential \r\n$DestinationSqlCredential\nTop-level groups Group1 and Group3 along with their subgroups and server instances are copied from sqlserver to sqlcluster. When adding sql instances to sqlcluster, if the server name of the \r\nmigrating instance is \"sqlcluster\", it will be switched to \"sqlserver\".\nIf SwitchServerName is not specified, \"sqlcluster\" will be skipped.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Group",
                           "This is an auto-populated array that contains your Central Management Server top-level groups on Source. You can specify one, many or none.\nIf Group is not specified, all groups in your Central Management Server will be copied.",
                           "CMSGroup",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SwitchServerName",
                           "If this switch is enabled, all instance names will be changed from Source to Destination.\nCentral Management Server does not allow you to add a shared registered server with the same name as the Configuration Server.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "If this switch is enabled, group(s) will be dropped and recreated if they already exists on destination.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaCmsRegServer [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Group] \u003cString[]\u003e] [-SwitchServerName] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaCredential",
        "Description":  "By using password decryption techniques provided by Antti Rantasaari (NetSPI, 2014), this script migrates SQL Server Credentials from one server to another while maintaining username and password.\n\nCredit: https://blog.netspi.com/decrypting-mssql-database-link-server-passwords/",
        "Tags":  [
                     "WSMan",
                     "Migration"
                 ],
        "Synopsis":  "Copy-DbaCredential migrates SQL Server Credentials from one SQL Server to another while maintaining Credential passwords.",
        "Alias":  "Copy-SqlCredential",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaCredential",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Copy-DbaCredential",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaCredential -Source sqlserver2014a -Destination sqlcluster\nCopies all SQL Server Credentials on sqlserver2014a to sqlcluster. If Credentials exist on destination, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaCredential -Source sqlserver2014a -Destination sqlcluster -Name \"PowerShell Proxy Account\" -Force\nCopies over one SQL Server Credential (PowerShell Proxy Account) from sqlserver to sqlcluster. If the Credential already exists on the destination, it will be dropped and recreated.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Credential",
                           "This command requires access to the Windows OS via PowerShell remoting. Use this credential to connect to Windows using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "Only include specific names\r\nNote: if spaces exist in the credential name, you will have to type \"\" or \u0027\u0027 around it.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeName",
                           "Excluded credential names",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Identity",
                           "Only include specific identities\r\nNote: if spaces exist in the credential identity, you will have to type \"\" or \u0027\u0027 around it.",
                           "CredentialIdentity",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeIdentity",
                           "Excluded identities",
                           "ExcludeCredentialIdentity",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, the Credential will be dropped and recreated if it already exists on Destination.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaCredential [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString[]\u003e] [[-ExcludeName] \u003cString[]\u003e] [[-Identity] \u003cString[]\u003e] [[-ExcludeIdentity] \u003cString[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaCustomError",
        "Description":  "By default, all custom errors are copied. The -CustomError parameter is auto-populated for command-line completion and can be used to copy only specific custom errors.\n\nIf the custom error already exists on the destination, it will be skipped unless -Force is used. The us_english version must be created first. If you drop the us_english version, all the other languages will be dropped for that specific ID as well.",
        "Tags":  [
                     "Migration",
                     "CustomError"
                 ],
        "Synopsis":  "Copy-DbaCustomError migrates custom errors (user defined messages), by the custom error ID, from one SQL Server to another.",
        "Alias":  "Copy-SqlCustomError",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaCustomError",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaCustomError",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaCustomError -Source sqlserver2014a -Destination sqlcluster\nCopies all server custom errors from sqlserver2014a to sqlcluster using Windows credentials. If custom errors with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaCustomError -Source sqlserver2014a -SourceSqlCredential $scred -Destination sqlcluster -DestinationSqlCredential $dcred -CustomError 60000 -Force\nCopies only the custom error with ID number 60000 from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If a custom error with the same \r\nname exists on sqlcluster, it will be updated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaCustomError -Source sqlserver2014a -Destination sqlcluster -ExcludeCustomError 60000 -Force\nCopies all the custom errors found on sqlserver2014a except the custom error with ID number 60000 to sqlcluster. If a custom error with the same name exists on sqlcluster, it will be updated because \r\n-Force was used.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaCustomError -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CustomError",
                           "The custom error(s) to process. This list is auto-populated from the server. If unspecified, all custom errors will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeCustomError",
                           "The custom error(s) to exclude. This list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, the custom error will be dropped and recreated if it already exists on Destination.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaCustomError [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-CustomError] \u003cObject[]\u003e] [[-ExcludeCustomError] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaDatabase",
        "Description":  "This script provides the ability to migrate databases using detach/copy/attach or backup/restore. This script works with named instances, clusters and SQL Server Express Edition.\n\nBy default, databases will be migrated to the destination SQL Server\u0027s default data and log directories. You can override this by specifying -ReuseSourceFolderStructure. Filestreams and filegroups are also migrated. Safety is emphasized.",
        "Tags":  [
                     "Migration",
                     "Backup",
                     "Restore"
                 ],
        "Synopsis":  "Migrates SQL Server databases from one SQL Server to another.",
        "Alias":  "Copy-SqlDatabase",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaDatabase",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaDatabase",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaDatabase -Source sql2014a -Destination sql2014b -Database TestDB -BackupRestore -SharedPath \\\\fileshare\\sql\\migration\nMigrates a single user database TestDB using Backup and restore from instance sql2014a to sql2014b. Backup files are stored in \\\\fileshare\\sql\\migration.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaDatabase -Source sql2012 -Destination sql2014, sql2016 -DetachAttach -Reattach\nDatabases will be migrated from sql2012 to both sql2014 and sql2016 using the detach/copy files/attach method.The following will be performed: kick all users out of the database, detach all data/log \r\nfiles, move files across the network over an admin share (\\\\SqlSERVER\\M$\\MSSql...), attach file on destination server, reattach at source. If the database files (*.mdf, *.ndf, *.ldf) on *destination* \r\nexist and aren\u0027t in use, they will be overwritten.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaDatabase -Source sql2014a -Destination sqlcluster, sql2016 -BackupRestore -UseLastBackup -Force\nMigrates all user databases to sqlcluster and sql2016 using the last Full, Diff and Log backups from sql204a. If the databases exists on the destinations, they will be dropped prior to attach.\nNote that the backups must exist in a location accessible by all destination servers, such a network share.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaDatabase -Source sql2014a -Destination sqlcluster -ExcludeDatabase Northwind, pubs -IncludeSupportDbs -Force -BackupRestore -SharedPath \\\\fileshare\\sql\\migration\nMigrates all user databases except for Northwind and pubs by using backup/restore (copy-only). Backup files are stored in \\\\fileshare\\sql\\migration. If the database exists on the destination, it will \r\nbe dropped prior to attach.\nIt also includes the support databases (ReportServer, ReportServerTempDb, distribution).",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You may specify multiple servers.\nNote that when using -BackupRestore with multiple servers, the backup will only be performed once and backups will be deleted at the end (if you didn\u0027t specify -NoBackupCleanup).\nWhen using -DetachAttach with multiple servers, -Reattach must be specified.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Migrates only specified databases. This list is auto-populated from the server for tab completion. Multiple databases may be specified as a collection.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Excludes specified databases when performing -AllDatabases migrations. This list is auto-populated from the Source for tab completion.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AllDatabases",
                           "If this switch is enabled, all user databases will be migrated. System and support databases will not be migrated. Requires -BackupRestore or -DetachAttach.",
                           "All",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "BackupRestore",
                           "If this switch is enabled, the copy-only backup and restore method will be used to migrate the database(s). This method requires that you specify -SharedPath in a valid UNC format (\\\\server\\share).\nBackups will be immediately deleted after use unless -NoBackupCleanup is specified.",
                           "",
                           true,
                           "false",
                           "False"
                       ],
                       [
                           "SharedPath",
                           "Specifies the network location for the backup files. The SQL Server service accounts must have read/write permission on this path.",
                           "NetworkShare",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "WithReplace",
                           "If this switch is enabled, the restore is executed with WITH REPLACE.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NoRecovery",
                           "If this switch is enabled, the restore is executed with WITH NORECOVERY. Ideal for staging.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NoBackupCleanup",
                           "If this switch is enabled, backups generated by this cmdlet will not be deleted after they are restored. The default behavior is to delete these backups.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NumberFiles",
                           "Number of files to split the backup. Default is 3.",
                           "",
                           false,
                           "false",
                           "3"
                       ],
                       [
                           "DetachAttach",
                           "If this switch is enabled, the detach/copy/attach method is used to perform database migrations. No files are deleted on Source. If Destination attachment fails, the Source database will be \r\nreattached. File copies are performed over administrative shares (\\\\server\\x$\\mssql) using BITS. If a database is being mirrored, the mirror will be broken prior to migration.",
                           "",
                           true,
                           "false",
                           "False"
                       ],
                       [
                           "Reattach",
                           "If this switch is enabled, all databases are reattached to Source after DetachAttach migration.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "SetSourceReadOnly",
                           "If this switch is enabled, all migrated databases are set to ReadOnly on Source prior to detach/attach \u0026 backup/restore.\nIf -Reattach is used, databases are set to read-only after reattaching.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ReuseSourceFolderStructure",
                           "If this switch is enabled, databases will be migrated to a data and log directory structure on Destination mirroring that used on Source. By default, the default data and log directories for \r\nDestination will be used when the databases are migrated.\nThe structure on Source  will be kept exactly, so consider this if you\u0027re migrating between different versions and use part of Microsoft\u0027s default Sql structure (MSSql12.INSTANCE, etc)\nTo reuse Destination folder structure, use the  -WithReplace switch.",
                           "ReuseFolderStructure",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IncludeSupportDbs",
                           "If this switch is enabled, ReportServer, ReportServerTempDb, SSISDB, and distribution databases will be copied if they exist on Source. A log file named $SOURCE-$destinstance-$date-Sqls.csv will be \r\nwritten to the current directory.\nUse of this switch requires -BackupRestore or -DetachAttach as well.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "UseLastBackup",
                           "Use the last full, diff and logs instead of performing backups. Note that the backups must exist in a location accessible by all destination servers, such a network share.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Continue",
                           "If specified, will to attempt to restore transaction log backups on top of existing database(s) in Recovering or Standby states. Only usable with -UseLastBackup",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Enables piped input from Get-DbaDatabase",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "NoCopyOnly",
                           "If this switch is enabled, backups will be taken without COPY_ONLY. This will break the LSN backup chain, which will interfere with the restore chain of the database.\nBy default this switch is disabled, so backups will be taken with COPY_ONLY. This will preserve the LSN backup chain.\nFor more details please refer to this MSDN article - https://msdn.microsoft.com/en-us/library/ms191495.aspx",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "SetSourceOffline",
                           "If this switch is enabled, the Source database will be set to Offline after being copied.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NewName",
                           "If a single database is being copied, this will be used to rename the database during the copy process. Any occurrence of the original database name in the physical file names will be replaced with \r\nNewName\r\nIf specified with multiple databases a warning will be raised and the copy stopped\nThis option is mutually exclusive of Prefix",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Prefix",
                           "All copied database names and physical files will be prefixed with this string\nThis option is mutually exclusive of NewName",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, existing databases on Destination with matching names from Source will be dropped. If using -DetachReattach, mirrors will be broken and the database(s) dropped from \r\nAvailability Groups.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaDatabase [-Source \u003cDbaInstanceParameter\u003e] [-SourceSqlCredential \u003cPSCredential\u003e] -Destination \u003cDbaInstanceParameter[]\u003e [-DestinationSqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllDatabases] -BackupRestore [-SharedPath \u003cString\u003e] [-WithReplace] [-NoRecovery] [-NoBackupCleanup] [-NumberFiles \u003cInt32\u003e] [-SetSourceReadOnly] [-ReuseSourceFolderStructure] [-IncludeSupportDbs] [-UseLastBackup] [-Continue] [-InputObject \u003cDatabase[]\u003e] [-NoCopyOnly] [-SetSourceOffline] [-NewName \u003cString\u003e] [-Prefix \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] \r\n[\u003cCommonParameters\u003e]\nCopy-DbaDatabase [-Source \u003cDbaInstanceParameter\u003e] [-SourceSqlCredential \u003cPSCredential\u003e] -Destination \u003cDbaInstanceParameter[]\u003e [-DestinationSqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllDatabases] -DetachAttach [-Reattach] [-SetSourceReadOnly] [-ReuseSourceFolderStructure] [-IncludeSupportDbs] [-InputObject \u003cDatabase[]\u003e] [-NoCopyOnly] [-SetSourceOffline] [-NewName \u003cString\u003e] [-Prefix \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaDataCollector",
        "Description":  "By default, all data collector objects are migrated. If the object already exists on the destination, it will be skipped unless -Force is used.\n\nThe -CollectionSet parameter is auto-populated for command-line completion and can be used to copy only specific objects.",
        "Tags":  [
                     "Migration",
                     "DataCollection"
                 ],
        "Synopsis":  "Migrates user SQL Data Collector collection sets. SQL Data Collector configuration is on the agenda, but it\u0027s hard.",
        "Alias":  "Copy-DbaSqlDataCollector,Copy-SqlDataCollector",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaDataCollector",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Copy-DbaDataCollector",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaDataCollector -Source sqlserver2014a -Destination sqlcluster\nCopies all Data Collector Objects and Configurations from sqlserver2014a to sqlcluster, using Windows credentials.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaDataCollector -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred\nCopies all Data Collector Objects and Configurations from sqlserver2014a to sqlcluster, using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaDataCollector -Source sqlserver2014a -Destination sqlcluster -WhatIf\nShows what would happen if the command were executed.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaDataCollector -Source sqlserver2014a -Destination sqlcluster -CollectionSet \u0027Server Activity\u0027, \u0027Table Usage Analysis\u0027\nCopies two Collection Sets, Server Activity and Table Usage Analysis, from sqlserver2014a to sqlcluster.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2008 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination Sql Server. You must have sysadmin access and server version must be SQL Server version 2008 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CollectionSet",
                           "The collection set(s) to process - this list is auto-populated from the server. If unspecified, all collection sets will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeCollectionSet",
                           "The collection set(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NoServerReconfig",
                           "Upcoming parameter to enable server reconfiguration",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "If collection sets exists on destination server, it will be dropped and recreated.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaDataCollector [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-CollectionSet] \u003cObject[]\u003e] [[-ExcludeCollectionSet] \u003cObject[]\u003e] [-NoServerReconfig] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaDbAssembly",
        "Description":  "By default, all assemblies are copied.\n\nIf the assembly already exists on the destination, it will be skipped unless -Force is used.\n\nThis script does not yet copy dependencies or dependent objects.",
        "Tags":  [
                     "Migration",
                     "Assembly"
                 ],
        "Synopsis":  "Copy-DbaDbAssembly migrates assemblies from one SQL Server to another.",
        "Alias":  "Copy-DbaDatabaseAssembly,Copy-SqlDatabaseAssembly",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaDbAssembly",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "http://dbatools.io/Get-SqlDatabaseAssembly",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaDbAssembly -Source sqlserver2014a -Destination sqlcluster\nCopies all assemblies from sqlserver2014a to sqlcluster using Windows credentials. If assemblies with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaDbAssembly -Source sqlserver2014a -Destination sqlcluster -Assembly dbname.assemblyname, dbname3.anotherassembly -SourceSqlCredential $cred -Force\nCopies two assemblies, the dbname.assemblyname and dbname3.anotherassembly from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If an \r\nassembly with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used.\nIn this example, anotherassembly will be copied to the dbname3 database on the server sqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaDbAssembly -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Assembly",
                           "The assembly(ies) to process. This list is auto-populated from the server. If unspecified, all assemblies will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeAssembly",
                           "The assembly(ies) to exclude. This list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, existing assemblies on Destination with matching names from Source will be dropped.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaDbAssembly [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Assembly] \u003cObject[]\u003e] [[-ExcludeAssembly] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaDbMail",
        "Description":  "By default, all mail configurations for Profiles, Accounts, Mail Servers and Configs are copied.",
        "Tags":  [
                     "Migration",
                     "Mail"
                 ],
        "Synopsis":  "Migrates Mail Profiles, Accounts, Mail Servers and Mail Server Configs from one SQL Server to another.",
        "Alias":  "Copy-DbaDatabaseMail,Copy-SqlDatabaseMail",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaDbMail",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaDbMail",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaDbMail -Source sqlserver2014a -Destination sqlcluster\nCopies all database mail objects from sqlserver2014a to sqlcluster using Windows credentials. If database mail objects with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaDbMail -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred\nCopies all database mail objects from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaDbMail -Source sqlserver2014a -Destination sqlcluster -WhatIf\nShows what would happen if the command were executed.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaDbMail -Source sqlserver2014a -Destination sqlcluster -EnableException\nPerforms execution of function, and will throw a terminating exception if something breaks",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Type",
                           "Specifies the object type to migrate. Valid options are \"Job\", \"Alert\" and \"Operator\". When Type is specified, all categories from the selected type will be migrated.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, existing objects on Destination with matching names from Source will be dropped.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaDbMail -Source \u003cDbaInstanceParameter\u003e -Destination \u003cDbaInstanceParameter[]\u003e [-SourceSqlCredential \u003cPSCredential\u003e] [-DestinationSqlCredential \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nCopy-DbaDbMail -Source \u003cDbaInstanceParameter\u003e -Destination \u003cDbaInstanceParameter[]\u003e [-Type \u003cString[]\u003e] [-SourceSqlCredential \u003cPSCredential\u003e] [-DestinationSqlCredential \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaDbQueryStoreOption",
        "Description":  "Copies the configuration of a Query Store enabled database and sets the copied configuration on other databases.",
        "Tags":  "QueryStore",
        "Synopsis":  "Copies the configuration of a Query Store enabled database and sets the copied configuration on other databases.",
        "Alias":  "Copy-DbaQueryStoreConfig",
        "Author":  "Enrico van de Laar (@evdlaar)",
        "CommandName":  "Copy-DbaDbQueryStoreOption",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-QueryStoreConfig",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaDbQueryStoreOption -Source ServerA\\SQL -SourceDatabase AdventureWorks -Destination ServerB\\SQL -AllDatabases\nCopy the Query Store configuration of the AdventureWorks database in the ServerA\\SQL instance and apply it on all user databases in the ServerB\\SQL Instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaDbQueryStoreOption -Source ServerA\\SQL -SourceDatabase AdventureWorks -Destination ServerB\\SQL -DestinationDatabase WorldWideTraders\nCopy the Query Store configuration of the AdventureWorks database in the ServerA\\SQL instance and apply it to the WorldWideTraders database in the ServerB\\SQL Instance.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2016 or higher.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SourceDatabase",
                           "Specifies the database to copy the Query Store configuration from.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2016 or higher.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DestinationDatabase",
                           "Specifies a list of databases that will receive a copy of the Query Store configuration of the SourceDatabase.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Exclude",
                           "Specifies a list of databases which will NOT receive a copy of the Query Store configuration.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AllDatabases",
                           "If this switch is enabled, the Query Store configuration will be copied to all databases on the destination instance.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaDbQueryStoreOption [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-SourceDatabase] \u003cObject\u003e [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-DestinationDatabase] \u003cObject[]\u003e] [[-Exclude] \u003cObject[]\u003e] [-AllDatabases] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaDbTableData",
        "Description":  "Copies data between SQL Server tables using SQL Bulk Copy.\nThe same can be achieved also doing\n$sourcetable = Invoke-DbaQuery -SqlInstance instance1 ... -As DataTable\nWrite-DbaDataTable -SqlInstance ... -InputObject $sourcetable\nbut it will force buffering the contents on the table in memory (high RAM usage for large tables).\nWith this function, a streaming copy will be done in the most speedy and least resource-intensive way.",
        "Tags":  "Migration",
        "Synopsis":  "Copies data between SQL Server tables.",
        "Alias":  "Copy-DbaTableData",
        "Author":  "Simone Bizzotto (@niphlod)",
        "CommandName":  "Copy-DbaDbTableData",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaDbTableData",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaDbTableData -SqlInstance sql1 -Destination sql2 -Database dbatools_from -Table dbo.test_table\nCopies all the data from table dbo.test_table in database dbatools_from on sql1 to table test_table in database dbatools_from on sql2.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaDbTableData -SqlInstance sql1 -Destination sql2 -Database dbatools_from -DestinationDatabase dbatools_dest -Table [Schema].[test table]\nCopies all the data from table [Schema].[test table] in database dbatools_from on sql1 to table [Schema].[test table] in database dbatools_dest on sql2\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance sql1 -Database tempdb -Table tb1, tb2 | Copy-DbaDbTableData -DestinationTable tb3\nCopies all data from tables tb1 and tb2 in tempdb on sql1 to tb3 in tempdb on sql1\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance sql1 -Database tempdb -Table tb1, tb2 | Copy-DbaDbTableData -Destination sql2\nCopies data from tbl1 in tempdb on sql1 to tbl1 in tempdb on sql2\r\nthen\r\nCopies data from tbl2 in tempdb on sql1 to tbl2 in tempdb on sql2\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eCopy-DbaDbTableData -SqlInstance sql1 -Destination sql2 -Database dbatools_from -Table test_table -KeepIdentity -Truncate\nCopies all the data in table test_table from sql1 to sql2, using the database dbatools_from, keeping identity columns and truncating the destination\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e SourceSqlInstance = \u0027sql1\u0027\r\n\u003e\u003e DestinationSqlInstance = \u0027sql2\u0027\r\n\u003e\u003e Database = \u0027dbatools_from\u0027\r\n\u003e\u003e DestinationDatabase = \u0027dbatools_dest\u0027\r\n\u003e\u003e Table = \u0027[Schema].[Table]\u0027\r\n\u003e\u003e DestinationTable = \u0027[dbo].[Table.Copy]\u0027\r\n\u003e\u003e KeepIdentity = $true\r\n\u003e\u003e KeepNulls = $true\r\n\u003e\u003e Truncate = $true\r\n\u003e\u003e BatchSize = 10000\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Copy-DbaDbTableData @params\nCopies all the data from table [Schema].[Table] in database dbatools_from on sql1 to table [dbo].[Table.Copy] in database dbatools_dest on sql2\r\nKeeps identity columns and Nulls, truncates the destination and processes in BatchSize of 10000.",
        "Params":  [
                       [
                           "SqlInstance",
                           "Source SQL Server.You must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "ServerInstance,SqlServer,Source",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination Sql Server. You must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database to copy the table from.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DestinationDatabase",
                           "The database to copy the table to. If not specified, it is assumed to be the same of Database",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Table",
                           "Define a specific table you would like to use as source. You can specify a three-part name like db.sch.tbl.\r\nIf the object has special characters please wrap them in square brackets [ ].\r\nThis dbo.First.Table will try to find table named \u0027Table\u0027 on schema \u0027First\u0027 and database \u0027dbo\u0027.\r\nThe correct way to find table named \u0027First.Table\u0027 on schema \u0027dbo\u0027 is passing dbo.[First.Table]",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Query",
                           "If you want to copy only a portion of a table or selected tables, specify the query.\r\nEnsure to select all required columns. Calculated Columns or columns with default values may be excluded.\r\nThe tablename should be a full three-part name in form [Database].[Schema].[Table]",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AutoCreateTable",
                           "Creates the destination table if it does not already exist, based off of the \"Export...\" script of the source table.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "BatchSize",
                           "The BatchSize for the import defaults to 5000.",
                           "",
                           false,
                           "false",
                           "50000"
                       ],
                       [
                           "NotifyAfter",
                           "Sets the option to show the notification after so many rows of import",
                           "",
                           false,
                           "false",
                           "5000"
                       ],
                       [
                           "DestinationTable",
                           "The table you want to use as destination. If not specified, it is assumed to be the same of Table",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NoTableLock",
                           "If this switch is enabled, a table lock (TABLOCK) will not be placed on the destination table. By default, this operation will lock the destination table while running.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "CheckConstraints",
                           "If this switch is enabled, the SqlBulkCopy option to process check constraints will be enabled.\nPer Microsoft \"Check constraints while data is being inserted. By default, constraints are not checked.\"",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "FireTriggers",
                           "If this switch is enabled, the SqlBulkCopy option to fire insert triggers will be enabled.\nPer Microsoft \"When specified, cause the server to fire the insert triggers for the rows being inserted into the Database.\"",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "KeepIdentity",
                           "If this switch is enabled, the SqlBulkCopy option to preserve source identity values will be enabled.\nPer Microsoft \"Preserve source identity values. When not specified, identity values are assigned by the destination.\"",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "KeepNulls",
                           "If this switch is enabled, the SqlBulkCopy option to preserve NULL values will be enabled.\nPer Microsoft \"Preserve null values in the destination table regardless of the settings for default values. When not specified, null values are replaced by default values where applicable.\"",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Truncate",
                           "If this switch is enabled, the destination table will be truncated after prompting for confirmation.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "bulkCopyTimeOut",
                           "Value in seconds for the BulkCopy operations timeout. The default is 30 seconds.",
                           "",
                           false,
                           "false",
                           "5000"
                       ],
                       [
                           "InputObject",
                           "Enables piping of Table objects from Get-DbaDbTable",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaDbTableData [[-SqlInstance] \u003cDbaInstanceParameter\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Destination] \u003cDbaInstanceParameter[]\u003e] [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [[-DestinationDatabase] \u003cString\u003e] [[-Table] \u003cString[]\u003e] [[-Query] \u003cString\u003e] [-AutoCreateTable] [[-BatchSize] \u003cInt32\u003e] [[-NotifyAfter] \u003cInt32\u003e] [[-DestinationTable] \u003cString\u003e] [-NoTableLock] [-CheckConstraints] [-FireTriggers] [-KeepIdentity] [-KeepNulls] [-Truncate] [[-bulkCopyTimeOut] \u003cInt32\u003e] [[-InputObject] \u003cTable[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaEndpoint",
        "Description":  "By default, all endpoints are copied.\n\nIf the endpoint already exists on the destination, it will be skipped unless -Force is used.",
        "Tags":  [
                     "Migration",
                     "Endpoint"
                 ],
        "Synopsis":  "Copy-DbaEndpoint migrates server endpoints from one SQL Server to another.",
        "Alias":  "Copy-SqlEndpoint",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaEndpoint",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaEndpoint",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaEndpoint -Source sqlserver2014a -Destination sqlcluster\nCopies all server endpoints from sqlserver2014a to sqlcluster, using Windows credentials. If endpoints with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaEndpoint -Source sqlserver2014a -SourceSqlCredential $cred -Destination sqlcluster -Endpoint tg_noDbDrop -Force\nCopies only the tg_noDbDrop endpoint from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If an endpoint with the same name exists on \r\nsqlcluster, it will be dropped and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaEndpoint -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Endpoint",
                           "The endpoint(s) to process. This list is auto-populated from the server. If unspecified, all endpoints will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeEndpoint",
                           "The endpoint(s) to exclude. This list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, existing endpoints on Destination with matching names from Source will be dropped.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaEndpoint [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Endpoint] \u003cObject[]\u003e] [[-ExcludeEndpoint] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaLinkedServer",
        "Description":  "By using password decryption techniques provided by Antti Rantasaari (NetSPI, 2014), this script migrates SQL Server Linked Servers from one server to another, while maintaining username and password.\n\nCredit: https://blog.netspi.com/decrypting-mssql-database-link-server-passwords/",
        "Tags":  [
                     "WSMan",
                     "Migration",
                     "LinkedServer"
                 ],
        "Synopsis":  "Copy-DbaLinkedServer migrates Linked Servers from one SQL Server to another. Linked Server logins and passwords are migrated as well.",
        "Alias":  "Copy-SqlLinkedServer",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaLinkedServer",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Copy-DbaLinkedServer",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaLinkedServer -Source sqlserver2014a -Destination sqlcluster\nCopies all SQL Server Linked Servers on sqlserver2014a to sqlcluster. If Linked Server exists on destination, it will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaLinkedServer -Source sqlserver2014a -Destination sqlcluster -LinkedServer SQL2K5,SQL2k -Force\nCopies over two SQL Server Linked Servers (SQL2K and SQL2K2) from sqlserver to sqlcluster. If the credential already exists on the destination, it will be dropped.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server (2005 and above). You must have sysadmin access to both SQL Server and Windows.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server (2005 and above). You must have sysadmin access to both SQL Server and Windows.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "LinkedServer",
                           "The linked server(s) to process - this list is auto-populated from the server. If unspecified, all linked servers will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeLinkedServer",
                           "The linked server(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "UpgradeSqlClient",
                           "Upgrade any SqlClient Linked Server to the current Version",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "By default, if a Linked Server exists on the source and destination, the Linked Server is not copied over. Specifying -force will drop and recreate the Linked Server on the Destination server.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaLinkedServer [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-LinkedServer] \u003cObject[]\u003e] [[-ExcludeLinkedServer] \u003cObject[]\u003e] [-UpgradeSqlClient] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaLogin",
        "Description":  "SQL Server 2000: Migrates logins with SIDs, passwords, server roles and database roles.\n\nSQL Server 2005 \u0026 newer: Migrates logins with SIDs, passwords, defaultdb, server roles \u0026 securables, database permissions \u0026 securables, login attributes (enforce password policy, expiration, etc.)\n\nThe login hash algorithm changed in SQL Server 2012, and is not backwards compatible with previous SQL Server versions. This means that while SQL Server 2000 logins can be migrated to SQL Server 2012, logins created in SQL Server 2012 can only be migrated to SQL Server 2012 and above.",
        "Tags":  [
                     "Migration",
                     "Login"
                 ],
        "Synopsis":  "Migrates logins from source to destination SQL Servers. Supports SQL Server versions 2000 and newer.",
        "Alias":  "Copy-SqlLogin",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaLogin",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaLogin",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaLogin -Source sqlserver2014a -Destination sqlcluster -Force\nCopies all logins from Source Destination. If a SQL Login on Source exists on the Destination, the Login on Destination will be dropped and recreated.\nIf active connections are found for a login, the copy of that Login will fail as it cannot be dropped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaLogin -Source sqlserver2014a -Destination sqlcluster -Force -KillActiveConnection\nCopies all logins from Source Destination. If a SQL Login on Source exists on the Destination, the Login on Destination will be dropped and recreated.\nIf any active connections are found they will be killed.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaLogin -Source sqlserver2014a -Destination sqlcluster -ExcludeLogin realcajun -SourceSqlCredential $scred -DestinationSqlCredential $dcred\nCopies all Logins from Source to Destination except for realcajun using SQL Authentication to connect to both instances.\nIf a Login already exists on the destination, it will not be migrated.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaLogin -Source sqlserver2014a -Destination sqlcluster -Login realcajun, netnerds -force\nCopies ONLY Logins netnerds and realcajun. If Login realcajun or netnerds exists on Destination, the existing Login(s) will be dropped and recreated.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eCopy-DbaLogin -Source sqlserver2014a -Destination sqlcluster -SyncOnly\nSyncs only SQL Server login permissions, roles, etc. Does not add or drop logins or users.\nIf a matching Login does not exist on Destination, the Login will be skipped.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eCopy-DbaLogin -LoginRenameHashtable @{ \"PreviousUser\" = \"newlogin\" } -Source $Sql01 -Destination Localhost -SourceSqlCredential $sqlcred\nCopies PreviousUser and then renames it to newlogin.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 | Out-GridView -Passthru | Copy-DbaLogin -Destination sql2017\nDisplays all available logins on sql2016 in a grid view, then copies all selected logins to sql2017.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Login",
                           "The login(s) to process. Options for this list are auto-populated from the server. If unspecified, all logins will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeLogin",
                           "The login(s) to exclude. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeSystemLogins",
                           "If this switch is enabled, NT SERVICE accounts will be skipped.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "SyncOnly",
                           "If this switch is enabled, only SQL Server login permissions, roles, etc. will be synced. Logins and users will not be added or dropped.  If a matching Login does not exist on the destination, the \r\nLogin will be skipped.\r\nCredential removal is not currently supported for this parameter.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "SyncSaName",
                           "If this switch is enabled, the name of the sa account will be synced between Source and Destination",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "OutFile",
                           "Calls Export-DbaLogin and exports all logins to a T-SQL formatted file. This does not perform a copy, so no destination is required.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Takes the parameters required from a Login object that has been piped into the command",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "LoginRenameHashtable",
                           "Pass a hash table into this parameter to be passed into Rename-DbaLogin to update the Login and mappings after the Login is completed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "KillActiveConnection",
                           "If this switch and -Force are enabled, all active connections and sessions on Destination will be killed.\nA login cannot be dropped when it has active connections on the instance.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "If this switch is enabled, the Login(s) will be dropped and recreated on Destination. Logins that own Agent jobs cannot be dropped at this time.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ExcludePermissionSync",
                           "Skips permission syncs",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaLogin [-SourceSqlCredential \u003cPSCredential\u003e] -Destination \u003cDbaInstanceParameter[]\u003e [-DestinationSqlCredential \u003cPSCredential\u003e] [-Login \u003cObject[]\u003e] [-ExcludeLogin \u003cObject[]\u003e] [-ExcludeSystemLogins] [-SyncOnly] [-LoginRenameHashtable \u003cHashtable\u003e] [-KillActiveConnection] [-Force] [-ExcludePermissionSync] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nCopy-DbaLogin -Source \u003cDbaInstanceParameter\u003e [-SourceSqlCredential \u003cPSCredential\u003e] -Destination \u003cDbaInstanceParameter[]\u003e [-DestinationSqlCredential \u003cPSCredential\u003e] [-Login \u003cObject[]\u003e] [-ExcludeLogin \u003cObject[]\u003e] [-ExcludeSystemLogins] [-SyncOnly] [-SyncSaName] [-LoginRenameHashtable \u003cHashtable\u003e] [-KillActiveConnection] [-Force] [-ExcludePermissionSync] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nCopy-DbaLogin [-SourceSqlCredential \u003cPSCredential\u003e] -Destination \u003cDbaInstanceParameter[]\u003e [-DestinationSqlCredential \u003cPSCredential\u003e] [-Login \u003cObject[]\u003e] [-ExcludeLogin \u003cObject[]\u003e] [-ExcludeSystemLogins] [-SyncOnly] [-SyncSaName] [-LoginRenameHashtable \u003cHashtable\u003e] [-KillActiveConnection] [-Force] [-ExcludePermissionSync] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nCopy-DbaLogin [-SourceSqlCredential \u003cPSCredential\u003e] -Destination \u003cDbaInstanceParameter[]\u003e [-DestinationSqlCredential \u003cPSCredential\u003e] [-Login \u003cObject[]\u003e] [-ExcludeLogin \u003cObject[]\u003e] [-ExcludeSystemLogins] [-SyncOnly] -OutFile \u003cString\u003e [-LoginRenameHashtable \u003cHashtable\u003e] [-KillActiveConnection] [-Force] [-ExcludePermissionSync] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nCopy-DbaLogin [-SourceSqlCredential \u003cPSCredential\u003e] -Destination \u003cDbaInstanceParameter[]\u003e [-DestinationSqlCredential \u003cPSCredential\u003e] [-Login \u003cObject[]\u003e] [-ExcludeLogin \u003cObject[]\u003e] [-ExcludeSystemLogins] [-SyncOnly] [-InputObject \u003cObject\u003e] [-LoginRenameHashtable \u003cHashtable\u003e] [-KillActiveConnection] [-Force] [-ExcludePermissionSync] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaPolicyManagement",
        "Description":  "By default, all policies and conditions are copied. If an object already exist on the destination, it will be skipped unless -Force is used.\n\nThe -Policy and -Condition parameters are auto-populated for command-line completion and can be used to copy only specific objects.",
        "Tags":  "Migration",
        "Synopsis":  "Migrates SQL Policy Based Management Objects, including both policies and conditions.",
        "Alias":  "Copy-DbaSqlPolicyManagement,Copy-SqlPolicyManagement",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaPolicyManagement",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Copy-DbaPolicyManagement",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaPolicyManagement -Source sqlserver2014a -Destination sqlcluster\nCopies all policies and conditions from sqlserver2014a to sqlcluster, using Windows credentials.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaPolicyManagement -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred\nCopies all policies and conditions from sqlserver2014a to sqlcluster, using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaPolicyManagement -Source sqlserver2014a -Destination sqlcluster -WhatIf\nShows what would happen if the command were executed.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaPolicyManagement -Source sqlserver2014a -Destination sqlcluster -Policy \u0027xp_cmdshell must be disabled\u0027\nCopies only one policy, \u0027xp_cmdshell must be disabled\u0027 from sqlserver2014a to sqlcluster. No conditions are migrated.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server.You must have sysadmin access and server version must be SQL Server version 2008 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination Sql Server. You must have sysadmin access and server version must be SQL Server version 2008 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Policy",
                           "The policy(ies) to process - this list is auto-populated from the server. If unspecified, all policies will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludePolicy",
                           "The policy(ies) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Condition",
                           "The condition(s) to process - this list is auto-populated from the server. If unspecified, all conditions will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeCondition",
                           "The condition(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If policies exists on destination server, it will be dropped and recreated.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaPolicyManagement [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Policy] \u003cObject[]\u003e] [[-ExcludePolicy] \u003cObject[]\u003e] [[-Condition] \u003cObject[]\u003e] [[-ExcludeCondition] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaResourceGovernor",
        "Description":  "By default, all non-system resource pools are migrated. If the pool already exists on the destination, it will be skipped unless -Force is used.\n\nThe -ResourcePool parameter is auto-populated for command-line completion and can be used to copy only specific objects.",
        "Tags":  [
                     "Migration",
                     "ResourceGovernor"
                 ],
        "Synopsis":  "Migrates Resource Pools",
        "Alias":  "Copy-SqlResourceGovernor",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaResourceGovernor",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaResourceGovernor",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaResourceGovernor -Source sqlserver2014a -Destination sqlcluster\nCopies all all non-system resource pools from sqlserver2014a to sqlcluster using Windows credentials to connect to the SQL Server instances..\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaResourceGovernor -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred\nCopies all all non-system resource pools from sqlserver2014a to sqlcluster using SQL credentials to connect to sqlserver2014a and Windows credentials to connect to sqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaResourceGovernor -Source sqlserver2014a -Destination sqlcluster -WhatIf\nShows what would happen if the command were executed.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2008 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2008 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ResourcePool",
                           "Specifies the resource pool(s) to process. Options for this list are auto-populated from the server. If unspecified, all resource pools will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeResourcePool",
                           "Specifies the resource pool(s) to exclude. Options for this list are auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, the policies will be dropped and recreated on Destination.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaResourceGovernor [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-ResourcePool] \u003cObject[]\u003e] [[-ExcludeResourcePool] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaServerAudit",
        "Description":  "By default, all audits are copied. The -Audit parameter is auto-populated for command-line completion and can be used to copy only specific audits.\n\nIf the audit already exists on the destination, it will be skipped unless -Force is used.",
        "Tags":  "Migration",
        "Synopsis":  "Copy-DbaServerAudit migrates server audits from one SQL Server to another.",
        "Alias":  "Copy-SqlAudit",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaServerAudit",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaServerAudit",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaServerAudit -Source sqlserver2014a -Destination sqlcluster\nCopies all server audits from sqlserver2014a to sqlcluster, using Windows credentials. If audits with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaServerAudit -Source sqlserver2014a -Destination sqlcluster -Audit tg_noDbDrop -SourceSqlCredential $cred -Force\nCopies a single audit, the tg_noDbDrop audit from sqlserver2014a to sqlcluster, using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If an audit with the same name exists \r\non sqlcluster, it will be dropped and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaServerAudit -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaServerAudit -Source sqlserver-0 -Destination sqlserver-1 -Audit audit1 -Path \u0027C:\\audit1\u0027\nCopies audit audit1 from sqlserver-0 to sqlserver-1. The file path on sqlserver-1 will be set to \u0027C:\\audit1\u0027.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Audit",
                           "The audit(s) to process. Options for this list are auto-populated from the server. If unspecified, all audits will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeAudit",
                           "The audit(s) to exclude. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "Destination file path. If not specified, the file path of the source will be used (or the default data directory).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, the audits will be dropped and recreated on Destination.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaServerAudit [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Audit] \u003cObject[]\u003e] [[-ExcludeAudit] \u003cObject[]\u003e] [[-Path] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaServerAuditSpecification",
        "Description":  "By default, all audits are copied. The -AuditSpecification parameter is auto-populated for command-line completion and can be used to copy only specific audits.\n\nIf the audit specification already exists on the destination, it will be skipped unless -Force is used.",
        "Tags":  [
                     "Migration",
                     "ServerAudit",
                     "AuditSpecification"
                 ],
        "Synopsis":  "Copy-DbaServerAuditSpecification migrates server audit specifications from one SQL Server to another.",
        "Alias":  "Copy-SqlAuditSpecification",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaServerAuditSpecification",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaServerAuditSpecification",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaServerAuditSpecification -Source sqlserver2014a -Destination sqlcluster\nCopies all server audits from sqlserver2014a to sqlcluster using Windows credentials to connect. If audits with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaServerAuditSpecification -Source sqlserver2014a -Destination sqlcluster -AuditSpecification tg_noDbDrop -SourceSqlCredential $cred -Force\nCopies a single audit, the tg_noDbDrop audit from sqlserver2014a to sqlcluster using SQL credentials to connect to sqlserver2014a and Windows credentials to connect to sqlcluster. If an audit \r\nspecification with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaServerAuditSpecification -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AuditSpecification",
                           "The Server Audit Specification(s) to process. Options for this list are auto-populated from the server. If unspecified, all Server Audit Specifications will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeAuditSpecification",
                           "The Server Audit Specification(s) to exclude. Options for this list are auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, the Audits Specifications will be dropped and recreated on Destination.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaServerAuditSpecification [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-AuditSpecification] \u003cObject[]\u003e] [[-ExcludeAuditSpecification] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaServerTrigger",
        "Description":  "By default, all triggers are copied. The -ServerTrigger parameter is auto-populated for command-line completion and can be used to copy only specific triggers.\n\nIf the trigger already exists on the destination, it will be skipped unless -Force is used.",
        "Tags":  "Migration",
        "Synopsis":  "Copy-DbaServerTrigger migrates server triggers from one SQL Server to another.",
        "Alias":  "Copy-SqlServerTrigger",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaServerTrigger",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaServerTrigger",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaServerTrigger -Source sqlserver2014a -Destination sqlcluster\nCopies all server triggers from sqlserver2014a to sqlcluster, using Windows credentials. If triggers with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaServerTrigger -Source sqlserver2014a -Destination sqlcluster -ServerTrigger tg_noDbDrop -SourceSqlCredential $cred -Force\nCopies a single trigger, the tg_noDbDrop trigger from sqlserver2014a to sqlcluster, using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If a trigger with the same name \r\nexists on sqlcluster, it will be dropped and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaServerTrigger -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server.You must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination Sql Server. You must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ServerTrigger",
                           "The Server Trigger(s) to process - this list is auto-populated from the server. If unspecified, all Server Triggers will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeServerTrigger",
                           "The Server Trigger(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "Drops and recreates the Trigger if it exists",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaServerTrigger [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-ServerTrigger] \u003cObject[]\u003e] [[-ExcludeServerTrigger] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaSpConfigure",
        "Description":  "By default, all configuration values are copied. The -ConfigName parameter is auto-populated for command-line completion and can be used to copy only specific configs.",
        "Tags":  [
                     "Migration",
                     "Configure",
                     "SpConfigure"
                 ],
        "Synopsis":  "Copy-DbaSpConfigure migrates configuration values from one SQL Server to another.",
        "Alias":  "Copy-SqlSpConfigure",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaSpConfigure",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaSpConfigure",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaSpConfigure -Source sqlserver2014a -Destination sqlcluster\nCopies all sp_configure settings from sqlserver2014a to sqlcluster\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaSpConfigure -Source sqlserver2014a -Destination sqlcluster -ConfigName DefaultBackupCompression, IsSqlClrEnabled -SourceSqlCredential $cred\nCopies the values for IsSqlClrEnabled and DefaultBackupCompression from sqlserver2014a to sqlcluster using SQL credentials to authenticate to sqlserver2014a and Windows credentials to authenticate to \r\nsqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaSpConfigure -Source sqlserver2014a -Destination sqlcluster -ExcludeConfigName DefaultBackupCompression, IsSqlClrEnabled\nCopies all configs except for IsSqlClrEnabled and DefaultBackupCompression, from sqlserver2014a to sqlcluster.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaSpConfigure -Source sqlserver2014a -Destination sqlcluster -WhatIf\nShows what would happen if the command were executed.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ConfigName",
                           "Specifies the configuration setting to process. Options for this list are auto-populated from the server. If unspecified, all ConfigNames will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeConfigName",
                           "Specifies the configuration settings to exclude. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaSpConfigure [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-ConfigName] \u003cObject[]\u003e] [[-ExcludeConfigName] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaSsisCatalog",
        "Description":  "By default, all folders, projects, and environments are copied. The -Project parameter can be specified to copy only one project, if desired.\n\nThe parameters get more granular from the Folder level. For example, specifying -Folder will only deploy projects/environments from within that folder.",
        "Tags":  [
                     "Migration",
                     "SSIS"
                 ],
        "Synopsis":  "Copy-DbaSsisCatalog migrates Folders, SSIS projects, and environments from one SQL Server to another.",
        "Alias":  "Copy-SqlSsisCatalog",
        "Author":  "Phil Schwartz (philschwartz.me, @pschwartzzz)",
        "CommandName":  "Copy-DbaSsisCatalog",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Copy-DbaSsisCatalog",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaSsisCatalog -Source sqlserver2014a -Destination sqlcluster\nCopies all folders, environments and SSIS Projects from sqlserver2014a to sqlcluster, using Windows credentials to authenticate to both instances. If folders with the same name exist on the \r\ndestination they will be skipped, but projects will be redeployed.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaSsisCatalog -Source sqlserver2014a -Destination sqlcluster -Project Archive_Tables -SourceSqlCredential $cred -Force\nCopies a single Project, the Archive_Tables Project, from sqlserver2014a to sqlcluster using SQL credentials to authenticate to sqlserver2014a and Windows credentials to authenticate to sqlcluster. \r\nIf a Project with the same name exists on sqlcluster, it will be deleted and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaSsisCatalog -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$SecurePW = Read-Host \"Enter password\" -AsSecureString\nPS C:\\\u003e Copy-DbaSsisCatalog -Source sqlserver2014a -Destination sqlcluster -CreateCatalogPassword $SecurePW\nDeploy entire SSIS catalog to an instance without a destination catalog. User prompts for creating the catalog on Destination will be bypassed.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2012 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2012 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Project",
                           "Specifies a source Project name.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Folder",
                           "Specifies a source folder name.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Environment",
                           "Specifies an environment to copy.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CreateCatalogPassword",
                           "Specifies a secure string to use in creating an SSISDB catalog on Destination. If this is specified, prompts for the password will be skipped.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableSqlClr",
                           "If this switch is enabled and Destination does not have the SQL CLR configuration option enabled, user prompts for enabling it on Destination will be skipped. SQL CLR is required for SSISDB.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "If this switch is enabled, the SSIS Catalog will be dropped and recreated on Destination if it already exists.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaSsisCatalog [-Source] \u003cDbaInstanceParameter\u003e [-Destination] \u003cDbaInstanceParameter[]\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Project] \u003cString\u003e] [[-Folder] \u003cString\u003e] [[-Environment] \u003cString\u003e] [[-CreateCatalogPassword] \u003cSecureString\u003e] [-EnableSqlClr] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaSysDbUserObject",
        "Description":  "Imports all user objects found in source SQL Server\u0027s master, msdb and model databases to the destination. This is useful because many DBAs store backup/maintenance procs/tables/triggers/etc (among other things) in master or msdb.\n\nIt is also useful for migrating objects within the model database.",
        "Tags":  [
                     "Migration",
                     "SystemDatabase",
                     "UserObject"
                 ],
        "Synopsis":  "Imports all user objects found in source SQL Server\u0027s master, msdb and model databases to the destination.",
        "Alias":  "Copy-SqlSysDbUserObjects",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaSysDbUserObject",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaSysDbUserObject",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaSysDbUserObject -Source $sourceServer -Destination $destserver\nCopies user objects from source to destination",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "Drop destination objects first. Has no effect if you use Classic. This doesn\u0027t work really well, honestly.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Classic",
                           "Perform the migration the old way",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaSysDbUserObject [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [-Force] [-Classic] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaXESession",
        "Description":  "Migrates SQL Extended Event Sessions except the two default sessions, AlwaysOn_health and system_health.\n\nBy default, all non-system Extended Events are migrated.",
        "Tags":  [
                     "Migration",
                     "ExtendedEvent",
                     "XEvent"
                 ],
        "Synopsis":  "Migrates SQL Extended Event Sessions except the two default sessions, AlwaysOn_health and system_health.",
        "Alias":  "Copy-DbaExtendedEvent,Copy-SqlExtendedEvent",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaXESession",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaXESession",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaXESession -Source sqlserver2014a -Destination sqlcluster\nCopies all Extended Event sessions from sqlserver2014a to sqlcluster using Windows credentials.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaXESession -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred\nCopies all Extended Event sessions from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaXESession -Source sqlserver2014a -Destination sqlcluster -WhatIf\nShows what would happen if the command were executed.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaXESession -Source sqlserver2014a -Destination sqlcluster -XeSession CheckQueries, MonitorUserDefinedException\nCopies only the Extended Events named CheckQueries and MonitorUserDefinedException from sqlserver2014a to sqlcluster.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "XeSession",
                           "The Extended Event Session(s) to process. This list is auto-populated from the server. If unspecified, all Extended Event Sessions will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeXeSession",
                           "The Extended Event Session(s) to exclude. This list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, existing Extended Events sessions on Destination with matching names from Source will be dropped.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Copy-DbaXESession [-Source] \u003cDbaInstanceParameter\u003e [-Destination] \u003cDbaInstanceParameter[]\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-XeSession] \u003cObject[]\u003e] [[-ExcludeXeSession] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Copy-DbaXESessionTemplate",
        "Description":  "Copies non-Microsoft templates from the dbatools template repository (\\bin\\xetemplates\\) to $home\\Documents\\SQL Server Management Studio\\Templates\\XEventTemplates.\n\nUseful for when you want to use the SSMS GUI.",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "Copies non-Microsoft templates from the dbatools template repository (\\bin\\xetemplates\\) to $home\\Documents\\SQL Server Management Studio\\Templates\\XEventTemplates.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Copy-DbaXESessionTemplate",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Copy-DbaXESessionTemplate",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaXESessionTemplate\nCopies non-Microsoft templates from the dbatools template repository (\\bin\\xetemplates\\) to $home\\Documents\\SQL Server Management Studio\\Templates\\XEventTemplates.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaXESessionTemplate -Path C:\\temp\\xetemplates\nCopies your templates from C:\\temp\\xetemplates to $home\\Documents\\SQL Server Management Studio\\Templates\\XEventTemplates.",
        "Params":  [
                       [
                           "Path",
                           "The path to the template directory. Defaults to the dbatools template repository (\\bin\\xetemplates\\).",
                           "",
                           false,
                           "false",
                           "\"$script:PSModuleRoot\\bin\\xetemplates\""
                       ],
                       [
                           "Destination",
                           "Path to the Destination directory, defaults to $home\\Documents\\SQL Server Management Studio\\Templates\\XEventTemplates.",
                           "",
                           false,
                           "false",
                           "\"$home\\Documents\\SQL Server Management Studio\\Templates\\XEventTemplates\""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Copy-DbaXESessionTemplate [[-Path] \u003cString[]\u003e] [[-Destination] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Disable-DbaAgHadr",
        "Description":  "In order to build an AG a cluster has to be built and then the Hadr enabled for the SQL Server\nservice. This function disables that feature for the SQL Server service.",
        "Tags":  [
                     "Hadr",
                     "AG",
                     "AvailabilityGroup"
                 ],
        "Synopsis":  "Disables the Hadr service setting on the specified SQL Server.",
        "Alias":  "",
        "Author":  "Shawn Melton (@wsmelton), http://wsmelton.github.io",
        "CommandName":  "Disable-DbaAgHadr",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Disable-DbaAgHadr",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eDisable-DbaAgHadr -SqlInstance sql2016\nSets Hadr service to disabled for the instance sql2016 but changes will not be applied until the next time the server restarts.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eDisable-DbaAgHadr -SqlInstance sql2016 -Force\nSets Hadr service to disabled for the instance sql2016, and restart the service to apply the change.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eDisable-DbaAgHadr -SqlInstance sql2012\\dev1 -Force\nSets Hadr service to disabled for the instance dev1 on sq2012, and restart the service to apply the change.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Credential",
                           "Credential object used to connect to the Windows server as a different user",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "Will restart SQL Server and SQL Server Agent service to apply the change.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Disable-DbaAgHadr [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Disable-DbaFilestream",
        "Description":  "Connects to the specified SQL Server instances, and sets the status of the FileStream feature to the required value\n\nTo perform the action, the SQL Server instance must be restarted. By default we will prompt for confirmation for this action, this can be overridden with the -Force switch",
        "Tags":  "Filestream",
        "Synopsis":  "Sets the status of FileStream on specified SQL Server instances both at the server level and the instance level",
        "Alias":  "",
        "Author":  "Stuart Moore ( @napalmgram ) | Chrissy LeMaire ( @cl )",
        "CommandName":  "Disable-DbaFilestream",
        "Availability":  "Windows only",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eDisable-DbaFilestream -SqlInstance server1\\instance2\nPrompts for confirmation. Disables filestream on the service and instance levels.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eDisable-DbaFilestream -SqlInstance server1\\instance2 -Confirm:$false\nDoes not prompt for confirmation. Disables filestream on the service and instance levels.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaFilestream -SqlInstance server1\\instance2, server5\\instance5, prod\\hr | Where-Object InstanceAccessLevel -gt 0 | Disable-DbaFilestream -Force\nUsing this pipeline you can scan a range of SQL instances and disable filestream on only those on which it\u0027s enabled.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Defaults to localhost.",
                           "",
                           true,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "Credential",
                           "Login to the target server using alternative credentials.",
                           "",
                           false,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "Force",
                           "Restart SQL Instance after changes. Use this parameter with care as it overrides whatif.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command runs. The command is not run unless Force is specified.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before running the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Disable-DbaFilestream [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Disable-DbaForceNetworkEncryption",
        "Description":  "Disables Force Encryption for a SQL Server instance. Note that this requires access to the Windows Server, not the SQL instance itself.\n\nThis setting is found in Configuration Manager.",
        "Tags":  "Certificate",
        "Synopsis":  "Disables Force Encryption for a SQL Server instance",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Disable-DbaForceNetworkEncryption",
        "Availability":  "Windows only",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eDisable-DbaForceNetworkEncryption\nDisables Force Encryption on the default (MSSQLSERVER) instance on localhost - requires (and checks for) RunAs admin.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eDisable-DbaForceNetworkEncryption -SqlInstance sql01\\SQL2008R2SP2\nDisables Force Network Encryption for the SQL2008R2SP2 on sql01. Uses Windows Credentials to both login and modify the registry.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eDisable-DbaForceNetworkEncryption -SqlInstance sql01\\SQL2008R2SP2 -WhatIf\nShows what would happen if the command were executed.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Defaults to localhost.",
                           "ServerInstance,SqlServer,ComputerName",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to the computer (not SQL Server instance) using alternative Windows credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Disable-DbaForceNetworkEncryption [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Disable-DbaTraceFlag",
        "Description":  "The function will disable a Trace Flag that is currently running globally on the SQL Server instance(s) listed",
        "Tags":  [
                     "TraceFlag",
                     "DBCC"
                 ],
        "Synopsis":  "Disable a Global Trace Flag that is currently running",
        "Alias":  "",
        "Author":  "Garry Bargsley (@gbargsley), http://blog.garrybargsley.com",
        "CommandName":  "Disable-DbaTraceFlag",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Disable-DbaTraceFlag",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eDisable-DbaTraceFlag -SqlInstance sql2016 -TraceFlag 3226\nDisable the globally running trace flag 3226 on SQL Server instance sql2016",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "TraceFlag",
                           "Trace flag number to enable globally",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Disable-DbaTraceFlag [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -TraceFlag \u003cInt32[]\u003e [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Dismount-DbaDatabase",
        "Description":  "This command detaches one or more SQL Server databases. If necessary, -Force can be used to break mirrors and remove databases from availability groups prior to detaching.",
        "Tags":  "Database",
        "Synopsis":  "Detach a SQL Server Database.",
        "Alias":  "Detach-DbaDatabase",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Dismount-DbaDatabase",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Dismount-DbaDatabase",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eDetach-DbaDatabase -SqlInstance sql2016b -Database SharePoint_Config, WSS_Logging\nDetaches SharePoint_Config and WSS_Logging from sql2016b\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016b -Database \u0027PerformancePoint Service Application_10032db0fa0041df8f913f558a5dc0d4\u0027 | Detach-DbaDatabase -Force\nDetaches \u0027PerformancePoint Service Application_10032db0fa0041df8f913f558a5dc0d4\u0027 from sql2016b. Since Force was specified, if the database is part of mirror, the mirror will be broken prior to \r\ndetaching.\nIf the database is part of an Availability Group, it will first be dropped prior to detachment.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016b -Database WSS_Logging | Detach-DbaDatabase -Force -WhatIf\nShows what would happen if the command were to execute (without actually executing the detach/break/remove commands).",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to detach.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "A collection of databases (such as returned by Get-DbaDatabase), to be detached.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "UpdateStatistics",
                           "If this switch is enabled, statistics for the database will be updated prior to detaching it.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "If this switch is enabled and the database is part of a mirror, the mirror will be broken. If the database is part of an Availability Group, it will be removed from the AG.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Dismount-DbaDatabase [-SqlCredential \u003cPSCredential\u003e] [-UpdateStatistics] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nDismount-DbaDatabase -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -Database \u003cString[]\u003e [-UpdateStatistics] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nDismount-DbaDatabase [-SqlCredential \u003cPSCredential\u003e] -InputObject \u003cDatabase[]\u003e [-UpdateStatistics] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Enable-DbaAgHadr",
        "Description":  "In order to build an AG a cluster has to be built and then the Hadr enabled for the SQL Server\nservice. This function enables that feature for the SQL Server service.",
        "Tags":  [
                     "Hadr",
                     "HA",
                     "AG",
                     "AvailabilityGroup"
                 ],
        "Synopsis":  "Enables the Hadr service setting on the specified SQL Server.",
        "Alias":  "",
        "Author":  "Shawn Melton (@wsmelton), http://wsmelton.github.io",
        "CommandName":  "Enable-DbaAgHadr",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Enable-DbaAgHadr",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eEnable-DbaAgHadr -SqlInstance sql2016\nSets Hadr service to enabled for the instance sql2016 but changes will not be applied until the next time the server restarts.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eEnable-DbaAgHadr -SqlInstance sql2016 -Force\nSets Hadr service to enabled for the instance sql2016, and restart the service to apply the change.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eEnable-DbaAgHadr -SqlInstance sql2012\\dev1 -Force\nSets Hadr service to disabled for the instance dev1 on sq2012, and restart the service to apply the change.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Credential",
                           "Credential object used to connect to the Windows server as a different user",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "Will restart SQL Server and SQL Server Agent service to apply the change.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Enable-DbaAgHadr [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Enable-DbaFilestream",
        "Description":  "Connects to the specified SQL Server instances, and Enables the FileStream feature to the required value\n\nTo perform the action, the SQL Server instance must be restarted. By default we will prompt for confirmation for this action, this can be overridden with the -Force switch",
        "Tags":  "Filestream",
        "Synopsis":  "Enables FileStream on specified SQL Server instances",
        "Alias":  "",
        "Author":  "Stuart Moore ( @napalmgram ) | Chrissy LeMaire ( @cl )",
        "CommandName":  "Enable-DbaFilestream",
        "Availability":  "Windows only",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eEnable-DbaFilestream -SqlInstance server1\\instance2 -FileStreamLevel TSql\nPS C:\\\u003e Enable-DbaFilestream -SqlInstance server1\\instance2 -FileStreamLevel 1\nThese commands are functionally equivalent, both will set Filestream level on server1\\instance2 to T-Sql Only\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaFilestream -SqlInstance server1\\instance2, server5\\instance5, prod\\hr | Where-Object InstanceAccessLevel -eq 0 | Enable-DbaFilestream -FileStreamLevel TSqlIoStreamingRemoteClient -Force\nUsing this pipeline you can scan a range of SQL instances and enable filestream on only those on which it\u0027s disabled.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Defaults to localhost.",
                           "",
                           true,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "Credential",
                           "Login to the target server using alternative credentials.",
                           "",
                           false,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "FileStreamLevel",
                           "The level to of FileStream to be enabled:\r\n1 or TSql - T-Sql Access Only\r\n2 or TSqlIoStreaming - T-Sql and Win32 access enabled\r\n3 or TSqlIoStreamingRemoteClient T-Sql, Win32 and Remote access enabled",
                           "",
                           false,
                           "false",
                           "1"
                       ],
                       [
                           "ShareName",
                           "Specifies the Windows file share name to be used for storing the FILESTREAM data.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "Restart SQL Instance after changes. Use this parameter with care as it overrides whatif.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command runs. The command is not run unless Force is specified.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before running the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Enable-DbaFilestream [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-FileStreamLevel] \u003cString\u003e] [[-ShareName] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Enable-DbaForceNetworkEncryption",
        "Description":  "Enables Force Encryption for a SQL Server instance. Note that this requires access to the Windows Server, not the SQL instance itself.\n\nThis setting is found in Configuration Manager.",
        "Tags":  [
                     "Certificate",
                     "Encryption"
                 ],
        "Synopsis":  "Enables Force Encryption for a SQL Server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Enable-DbaForceNetworkEncryption",
        "Availability":  "Windows only",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eEnable-DbaForceNetworkEncryption\nEnables Force Encryption on the default (MSSQLSERVER) instance on localhost. Requires (and checks for) RunAs admin.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eEnable-DbaForceNetworkEncryption -SqlInstance sql01\\SQL2008R2SP2\nEnables Force Network Encryption for the SQL2008R2SP2 on sql01. Uses Windows Credentials to both connect and modify the registry.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eEnable-DbaForceNetworkEncryption -SqlInstance sql01\\SQL2008R2SP2 -WhatIf\nShows what would happen if the command were executed.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer,ComputerName",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to the computer (not SQL Server instance) using alternative Windows credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Enable-DbaForceNetworkEncryption [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Enable-DbaTraceFlag",
        "Description":  "The function will set one or multiple trace flags on the SQL Server instance(s) listed",
        "Tags":  [
                     "TraceFlag",
                     "DBCC"
                 ],
        "Synopsis":  "Enable Global Trace Flag(s)",
        "Alias":  "",
        "Author":  "Garry Bargsley (@gbargsley), http://blog.garrybargsley.com",
        "CommandName":  "Enable-DbaTraceFlag",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Enable-DbaTraceFlag",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eEnable-DbaTraceFlag -SqlInstance sql2016 -TraceFlag 3226\nEnable the trace flag 3226 on SQL Server instance sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eEnable-DbaTraceFlag -SqlInstance sql2016 -TraceFlag 1117, 1118\nEnable multiple trace flags on SQL Server instance sql2016",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "TraceFlag",
                           "Trace flag number(s) to enable globally",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Enable-DbaTraceFlag [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -TraceFlag \u003cInt32[]\u003e [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Expand-DbaDbLogFile",
        "Description":  "As you may already know, having a transaction log file with too many Virtual Log Files (VLFs) can hurt your database performance in many ways.\n\nExample:\nToo many VLFs can cause transaction log backups to slow down and can also slow down database recovery and, in extreme cases, even impact insert/update/delete performance.\n\nReferences:\nhttp://www.sqlskills.com/blogs/kimberly/transaction-log-vlfs-too-many-or-too-few/\nhttp://blogs.msdn.com/b/saponsqlserver/archive/2012/02/22/too-many-virtual-log-files-vlfs-can-cause-slow-database-recovery.aspx\nhttp://www.brentozar.com/blitz/high-virtual-log-file-vlf-count/\n\nIn order to get rid of this fragmentation we need to grow the file taking the following into consideration:\n- How many VLFs are created when we perform a grow operation or when an auto-grow is invoked?\n\nNote: In SQL Server 2014 this algorithm has changed (http://www.sqlskills.com/blogs/paul/important-change-vlf-creation-algorithm-sql-server-2014/)\n\nAttention:\nWe are growing in MB instead of GB because of known issue prior to SQL 2012:\nMore detail here:\nhttp://www.sqlskills.com/BLOGS/PAUL/post/Bug-log-file-growth-broken-for-multiples-of-4GB.aspx\nand\nhttp://connect.microsoft.com/SqlInstance/feedback/details/481594/log-growth-not-working-properly-with-specific-growth-sizes-vlfs-also-not-created-appropriately\nor\nhttps://connect.microsoft.com/SqlInstance/feedback/details/357502/transaction-log-file-size-will-not-grow-exactly-4gb-when-filegrowth-4gb\n\nUnderstanding related problems:\nhttp://www.sqlskills.com/blogs/kimberly/transaction-log-vlfs-too-many-or-too-few/\nhttp://blogs.msdn.com/b/saponsqlserver/archive/2012/02/22/too-many-virtual-log-files-vlfs-can-cause-slow-database-recovery.aspx\nhttp://www.brentozar.com/blitz/high-virtual-log-file-vlf-count/\n\nKnown bug before SQL Server 2012\nhttp://www.sqlskills.com/BLOGS/PAUL/post/Bug-log-file-growth-broken-for-multiples-of-4GB.aspx\nhttp://connect.microsoft.com/SqlInstance/feedback/details/481594/log-growth-not-working-properly-with-specific-growth-sizes-vlfs-also-not-created-appropriately\nhttps://connect.microsoft.com/SqlInstance/feedback/details/357502/transaction-log-file-size-will-not-grow-exactly-4gb-when-filegrowth-4gb\n\nHow it works?\nThe transaction log will grow in chunks until it reaches the desired size.\nExample: If you have a log file with 8192MB and you say that the target size is 81920MB (80GB) it will grow in chunks of 8192MB until it reaches 81920MB. 8192 -\u003e 16384 -\u003e 24576 ... 73728 -\u003e 81920",
        "Tags":  [
                     "Storage",
                     "Backup"
                 ],
        "Synopsis":  "This command will help you to automatically grow your transaction log  file in a responsible way (preventing the generation of too many VLFs).",
        "Alias":  "Expand-DbaTLogResponsibly,Expand-SqlTLogResponsibly",
        "Author":  "Claudio Silva (@ClaudioESSilva)",
        "CommandName":  "Expand-DbaDbLogFile",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Expand-DbaDbLogFile",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExpand-DbaDbLogFile -SqlInstance sqlcluster -Database db1 -TargetLogSize 50000\nGrows the transaction log for database db1 on sqlcluster to 50000 MB and calculates the increment size.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExpand-DbaDbLogFile -SqlInstance sqlcluster -Database db1, db2 -TargetLogSize 10000 -IncrementSize 200\nGrows the transaction logs for databases db1 and db2 on sqlcluster to 1000MB and sets the growth increment to 200MB.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eExpand-DbaDbLogFile -SqlInstance sqlcluster -Database db1 -TargetLogSize 10000 -LogFileId 9\nGrows the transaction log file  with FileId 9 of the db1 database on sqlcluster instance to 10000MB.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eExpand-DbaDbLogFile -SqlInstance sqlcluster -Database (Get-Content D:\\DBs.txt) -TargetLogSize 50000\nGrows the transaction log of the databases specified in the file \u0027D:\\DBs.txt\u0027 on sqlcluster instance to 50000MB.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eExpand-DbaDbLogFile -SqlInstance SqlInstance -Database db1,db2 -TargetLogSize 100 -IncrementSize 10 -ShrinkLogFile -ShrinkSize 10 -BackupDirectory R:\\MSSQL\\Backup\nGrows the transaction logs for databases db1 and db2 on SQL server SQLInstance to 100MB, sets the incremental growth to 10MB, shrinks the transaction log to 10MB and uses the directory \r\nR:\\MSSQL\\Backup for the required backups.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "TargetLogSize",
                           "Specifies the target size of the transaction log file in megabytes.",
                           "TargetLogSizeMB",
                           true,
                           "false",
                           "0"
                       ],
                       [
                           "IncrementSize",
                           "Specifies the amount the transaction log should grow in megabytes. If this value differs from the suggested value based on your TargetLogSize, you will be prompted to confirm your choice.\nThis value will be calculated if not specified.",
                           "IncrementSizeMB",
                           false,
                           "false",
                           "-1"
                       ],
                       [
                           "LogFileId",
                           "Specifies the file number(s) of additional transaction log files to grow.\nIf this value is not specified, only the first transaction log file will be processed.",
                           "",
                           false,
                           "false",
                           "-1"
                       ],
                       [
                           "ShrinkLogFile",
                           "If this switch is enabled, your transaction log files will be shrunk.",
                           "",
                           true,
                           "false",
                           "False"
                       ],
                       [
                           "ShrinkSize",
                           "Specifies the target size of the transaction log file for the shrink operation in megabytes.",
                           "ShrinkSizeMB",
                           true,
                           "false",
                           "0"
                       ],
                       [
                           "BackupDirectory",
                           "Specifies the location of your backups. Backups must be performed to shrink the transaction log.\nIf this value is not specified, the SQL Server instance\u0027s default backup directory will be used.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDiskSpaceValidation",
                           "If this switch is enabled, the validation for enough disk space using Get-DbaDiskSpace command will be skipped.\r\nThis can be useful when you know that you have enough space to grow your TLog but you don\u0027t have PowerShell Remoting enabled to validate it.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Expand-DbaDbLogFile [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-TargetLogSize] \u003cInt32\u003e [[-IncrementSize] \u003cInt32\u003e] [[-LogFileId] \u003cInt32\u003e] [-ExcludeDiskSpaceValidation] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nExpand-DbaDbLogFile [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-TargetLogSize] \u003cInt32\u003e [[-IncrementSize] \u003cInt32\u003e] [[-LogFileId] \u003cInt32\u003e] [-ShrinkLogFile] [-ShrinkSize] \u003cInt32\u003e [[-BackupDirectory] \u003cString\u003e] [-ExcludeDiskSpaceValidation] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Export-DbaAvailabilityGroup",
        "Description":  "Exports SQL Server Availability Groups creation scripts to a T-SQL file. This is a function that is not available in SSMS.",
        "Tags":  [
                     "Hadr",
                     "HA",
                     "AG",
                     "AvailabilityGroup"
                 ],
        "Synopsis":  "Exports SQL Server Availability Groups to a T-SQL file.",
        "Alias":  "",
        "Author":  "Chris Sommer (@cjsommer), cjsommer.com",
        "CommandName":  "Export-DbaAvailabilityGroup",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Export-DbaAvailabilityGroup",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaAvailabilityGroup -SqlInstance sql2012\nExports all Availability Groups from SQL server \"sql2012\". Output scripts are written to the Documents\\SqlAgExports directory by default.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExport-DbaAvailabilityGroup -SqlInstance sql2012 -Path C:\\temp\\availability_group_exports\nExports all Availability Groups from SQL server \"sql2012\". Output scripts are written to the C:\\temp\\availability_group_exports directory.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eExport-DbaAvailabilityGroup -SqlInstance sql2012 -Path \u0027C:\\dir with spaces\\availability_group_exports\u0027 -AvailabilityGroup AG1,AG2\nExports Availability Groups AG1 and AG2 from SQL server \"sql2012\". Output scripts are written to the C:\\dir with spaces\\availability_group_exports directory.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eExport-DbaAvailabilityGroup -SqlInstance sql2014 -Path C:\\temp\\availability_group_exports -NoClobber\nExports all Availability Groups from SQL server \"sql2014\". Output scripts are written to the C:\\temp\\availability_group_exports directory. If the export file already exists it will not be overwritten.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. SQL Server 2012 and above supported.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityGroup",
                           "The Availability Group(s) to export - this list is auto-populated from the server. If unspecified, all logins will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeAvailabilityGroup",
                           "The Availability Group(s) to exclude - this list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "The directory name where the output files will be written. A sub directory with the format \u0027ServerName$InstanceName\u0027 will be created. A T-SQL scripts named \u0027AGName.sql\u0027 will be created under this \r\nsubdirectory for each scripted Availability Group.",
                           "OutputLocation,FilePath",
                           false,
                           "false",
                           "\"$([Environment]::GetFolderPath(\"MyDocuments\"))\\SqlAgExport\""
                       ],
                       [
                           "NoClobber",
                           "Do not overwrite existing export files.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows you what it\u0027d output if you were to run the command",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Confirms each step/line of output",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Export-DbaAvailabilityGroup [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cObject[]\u003e] [[-ExcludeAvailabilityGroup] \u003cObject[]\u003e] [[-Path] \u003cString\u003e] [-NoClobber] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Export-DbaCmsRegServer",
        "Description":  "Exports registered servers and registered server groups to file",
        "Tags":  [
                     "RegisteredServer",
                     "CMS"
                 ],
        "Synopsis":  "Exports registered servers and registered server groups to file",
        "Alias":  "Export-DbaRegisteredServer",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Export-DbaCmsRegServer",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Export-DbaCmsRegServer",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaCmsRegServer -SqlInstance sql2008\nExports all Registered Server and Registered Server Groups on sql2008 to an automatically generated file name in the current directory\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sql2008, sql2012 | Export-DbaCmsRegServer\nExports all registered servers on sql2008 and sql2012. Warning - each one will have its own individual file. Consider piping groups.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServerGroup -SqlInstance sql2008, sql2012 | Export-DbaCmsRegServer\nExports all registered servers on sql2008 and sql2012, organized by group.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaCmsRegServer, Get-DbaCmsRegServerGroup, CSVs and other objects.\nIf importing from CSV or other object, a column named ServerName is required. Optional columns include Name, Description and Group.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Path",
                           "The path to the exported file. If no path is specified, one will be created.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CredentialPersistenceType",
                           "Used to specify how the login and passwords are persisted. Valid values include None, PersistLoginName and PersistLoginNameAndPassword.",
                           "",
                           false,
                           "false",
                           "None"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Export-DbaCmsRegServer [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-InputObject] \u003cObject[]\u003e] [[-Path] \u003cString\u003e] [[-CredentialPersistenceType] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Export-DbaCredential",
        "Description":  "Exports credentials INCLUDING PASSWORDS, unless specified otherwise, to sql file.\n\nRequires remote Windows access if exporting the password.",
        "Tags":  "Credential",
        "Synopsis":  "Exports credentials INCLUDING PASSWORDS, unless specified otherwise, to sql file.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Export-DbaCredential",
        "Availability":  "Windows only",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaCredential -SqlInstance sql2017 -Path C:\\temp\\cred.sql\nExports credentials, including passwords, from sql2017 to the file C:\\temp\\cred.sql",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Identity",
                           "The credentials to export. If unspecified, all credentials will be exported.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Credential",
                           "Login to the target OS using alternative credentials. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "The path to the exported sql file.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludePassword",
                           "Exports the SQL credential without any sensitive information.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Append",
                           "Append to Path",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Allow credentials to be piped in from Get-DbaCredential",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Export-DbaCredential [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-Identity] \u003cString[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Path] \u003cString\u003e] [-ExcludePassword] [-Append] [[-InputObject] \u003cCredential[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Export-DbaDacPackage",
        "Description":  "Using SQLPackage, export a dacpac from an instance of SQL Server.\n\nNote - Extract from SQL Server is notoriously flaky - for example if you have three part references to external databases it will not work.\n\nFor help with the extract action parameters and properties, refer to https://msdn.microsoft.com/en-us/library/hh550080(v=vs.103).aspx",
        "Tags":  [
                     "Migration",
                     "Database",
                     "Dacpac"
                 ],
        "Synopsis":  "Exports a dacpac from a server.",
        "Alias":  "Export-DbaDacpac",
        "Author":  "Richie lee (@richiebzzzt)",
        "CommandName":  "Export-DbaDacPackage",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Export-DbaDacPackage",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaDacPackage -SqlInstance sql2016 -Database SharePoint_Config\nExports the dacpac for SharePoint_Config on sql2016 to $home\\Documents\\SharePoint_Config.dacpac\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$options = New-DbaDacOption -Type Dacpac -Action Export\nPS C:\\\u003e $options.ExtractAllTableData = $true\r\nPS C:\\\u003e $options.CommandTimeout = 0\r\nPS C:\\\u003e Export-DbaDacPackage -SqlInstance sql2016 -Database DB1 -Options $options\nUses DacOption object to set the CommandTimeout to 0 then extracts the dacpac for DB1 on sql2016 to $home\\Documents\\DB1.dacpac including all table data.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eExport-DbaDacPackage -SqlInstance sql2016 -AllUserDatabases -ExcludeDatabase \"DBMaintenance\",\"DBMonitoring\" C:\\temp\nExports dacpac packages for all USER databases, excluding \"DBMaintenance\" \u0026 \"DBMonitoring\", on sql2016 and saves them to C:\\temp\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$moreparams = \"/OverwriteFiles:$true /Quiet:$true\"\nPS C:\\\u003e Export-DbaDacPackage -SqlInstance sql2016 -Database SharePoint_Config -Path C:\\temp -ExtendedParameters $moreparams\nUsing extended parameters to over-write the files and performs the extraction in quiet mode. Uses command line instead of SMO behind the scenes.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to servers using alternative logins instead Integrated, accepts Credential object created by Get-Credential",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AllUserDatabases",
                           "Run command against all user databases",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Path",
                           "The directory where the .dacpac files will be exported to. Defaults to documents.",
                           "",
                           false,
                           "false",
                           "\"$home\\Documents\""
                       ],
                       [
                           "DacOption",
                           "Export options for a corresponding export type. Can be created by New-DbaDacOption -Type Dacpac | Bacpac",
                           "ExtractOptions,ExportOptions,DacExtractOptions,DacExportOptions,Options,Option",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExtendedParameters",
                           "Optional parameters used to extract the DACPAC. More information can be found at\r\nhttps://msdn.microsoft.com/en-us/library/hh550080.aspx",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExtendedProperties",
                           "Optional properties used to extract the DACPAC. More information can be found at\r\nhttps://msdn.microsoft.com/en-us/library/hh550080.aspx",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Type",
                           "Selecting the type of the export: Dacpac (default) or Bacpac.",
                           "",
                           false,
                           "false",
                           "Dacpac"
                       ],
                       [
                           "Table",
                           "List of the tables to include into the export. Should be provided as an array of strings: dbo.Table1, Table2, Schema1.Table3.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Export-DbaDacPackage -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllUserDatabases] [-Path \u003cString\u003e] [-DacOption \u003cObject\u003e] [-Type \u003cString\u003e] [-Table \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]\nExport-DbaDacPackage -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllUserDatabases] [-Path \u003cString\u003e] [-ExtendedParameters \u003cString\u003e] [-ExtendedProperties \u003cString\u003e] [-Type \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Export-DbaDiagnosticQuery",
        "Description":  "The default output format of Invoke-DbaDiagnosticQuery is a custom object. It can also output to CSV and Excel.\nHowever, CSV output can generate a lot of files and Excel output depends on the ImportExcel module by Doug Finke (https://github.com/dfinke/ImportExcel)\nExport-DbaDiagnosticQuery can be used to convert from the default export type to the other available export types.",
        "Tags":  "Query",
        "Synopsis":  "Export-DbaDiagnosticQuery can convert output generated by Invoke-DbaDiagnosticQuery to CSV or Excel",
        "Alias":  "",
        "Author":  "Andre Kamman (@AndreKamman), http://clouddba.io",
        "CommandName":  "Export-DbaDiagnosticQuery",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Export-DbaDiagnosticQuery",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDiagnosticQuery -SqlInstance sql2016 | Export-DbaDiagnosticQuery -Path c:\\temp\nConverts output from Invoke-DbaDiagnosticQuery to multiple CSV files\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$output = Invoke-DbaDiagnosticQuery -SqlInstance sql2016\nPS C:\\\u003e Export-DbaDiagnosticQuery -InputObject $output -ConvertTo Excel\nConverts output from Invoke-DbaDiagnosticQuery to Excel worksheet(s) in the Documents folder",
        "Params":  [
                       [
                           "InputObject",
                           "Specifies the objects to convert",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "ConvertTo",
                           "Specifies the output type. Valid choices are Excel and CSV. CSV is the default.",
                           "",
                           false,
                           "false",
                           "Csv"
                       ],
                       [
                           "Path",
                           "Specifies the path to the output files.",
                           "",
                           false,
                           "false",
                           "[Environment]::GetFolderPath(\"mydocuments\")"
                       ],
                       [
                           "Suffix",
                           "Suffix for the filename. It\u0027s datetime by default.",
                           "",
                           false,
                           "false",
                           "\"$(Get-Date -format \u0027yyyyMMddHHmmssms\u0027)\""
                       ],
                       [
                           "NoPlanExport",
                           "Use this switch to suppress exporting of .sqlplan files",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NoQueryExport",
                           "Use this switch to suppress exporting of .sql files",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Export-DbaDiagnosticQuery [-InputObject] \u003cObject[]\u003e [[-ConvertTo] \u003cString\u003e] [[-Path] \u003cFileInfo\u003e] [[-Suffix] \u003cString\u003e] [-NoPlanExport] [-NoQueryExport] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Export-DbaExecutionPlan",
        "Description":  "Exports execution plans to disk. Can pipe from Get-DbaExecutionPlan\n\nThanks to\nhttps://www.simple-talk.com/sql/t-sql-programming/dmvs-for-query-plan-metadata/\nand\nhttp://www.scarydba.com/2017/02/13/export-plans-cache-sqlplan-file/\nfor the idea and query.",
        "Tags":  [
                     "Performance",
                     "ExecutionPlan"
                 ],
        "Synopsis":  "Exports execution plans to disk.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Export-DbaExecutionPlan",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Export-DbaExecutionPlan",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaExecutionPlan -SqlInstance sqlserver2014a -Path C:\\Temp\nExports all execution plans for sqlserver2014a. Files saved in to C:\\Temp\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExport-DbaExecutionPlan -SqlInstance sqlserver2014a -Database db1, db2 -SinceLastExecution \u00272016-07-01 10:47:00\u0027 -Path C:\\Temp\nExports all execution plans for databases db1 and db2 on sqlserver2014a since July 1, 2016 at 10:47 AM. Files saved in to C:\\Temp\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaExecutionPlan -SqlInstance sqlserver2014a | Export-DbaExecutionPlan -Path C:\\Temp\nGets all execution plans for sqlserver2014a. Using Pipeline exports them all to C:\\Temp\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaExecutionPlan -SqlInstance sqlserver2014a | Export-DbaExecutionPlan -Path C:\\Temp -WhatIf\nGets all execution plans for sqlserver2014a. Then shows what would happen if the results where piped to Export-DbaExecutionPlan",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Credential object used to connect to the SQL Server as a different user",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "The directory where all of the sqlxml files will be exported",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SinceCreation",
                           "Datetime object used to narrow the results to a date",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SinceLastExecution",
                           "Datetime object used to narrow the results to a date",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "PipedObject",
                           "Internal parameter",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Export-DbaExecutionPlan [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nExport-DbaExecutionPlan -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] -Path \u003cString\u003e [-SinceCreation \u003cDateTime\u003e] [-SinceLastExecution \u003cDateTime\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nExport-DbaExecutionPlan [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] -Path \u003cString\u003e -PipedObject \u003cObject[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Export-DbaInstance",
        "Description":  "Export-DbaInstance consolidates most of the export scripts in dbatools into one command.\n\nThis is useful when you\u0027re looking to Export entire instances. It less flexible than using the underlying functions.\nThink of it as an easy button. Unless an -Exclude is specified, it exports:\n\nAll database restore scripts.\nAll logins.\nAll database mail objects.\nAll credentials.\nAll objects within the Job Server (SQL Agent).\nAll linked servers.\nAll groups and servers within Central Management Server.\nAll SQL Server configuration objects (everything in sp_configure).\nAll user objects in system databases.\nAll system triggers.\nAll system backup devices.\nAll Audits.\nAll Endpoints.\nAll Extended Events.\nAll Policy Management objects.\nAll Resource Governor objects.\nAll Server Audit Specifications.\nAll Custom Errors (User Defined Messages).\nAll Server Roles.\nAll Availability Groups.",
        "Tags":  "Export",
        "Synopsis":  "Exports SQL Server *ALL* database restore scripts, logins, database mail profiles/accounts, credentials, SQL Agent objects, linked servers,\nCentral Management Server objects, server configuration settings (sp_configure), user objects in systems databases,\nsystem triggers and backup devices from one SQL Server to another.\n\nFor more granular control, please use one of the -Exclude parameters and use the other functions available within the dbatools module.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Export-DbaInstance",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Export-DbaInstance",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaInstance -SqlInstance sqlserver\\instance\nAll databases, logins, job objects and sp_configure options will be exported from\r\nsqlserver\\instance to an automatically generated folder name in Documents.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExport-DbaInstance -SqlInstance sqlcluster -Exclude Databases, Logins -Path C:\\dr\\sqlcluster\nExports everything but logins and database restore scripts to C:\\dr\\sqlcluster",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instances",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Credential",
                           "Alternative Windows credentials for exporting Linked Servers and Credentials. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "The path to the export file",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NoRecovery",
                           "If this switch is used, databases will be left in the No Recovery state to enable further backups to be added.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IncludeDbMasterKey",
                           "Exports the db master key then logs into the server to copy it to the $Path",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Exclude",
                           "Exclude one or more objects to export\nDatabases\r\nLogins\r\nAgentServer\r\nCredentials\r\nLinkedServers\r\nSpConfigure\r\nCentralManagementServer\r\nDatabaseMail\r\nSysDbUserObjects\r\nSystemTriggers\r\nBackupDevices\r\nAudits\r\nEndpoints\r\nExtendedEvents\r\nPolicyManagement\r\nResourceGovernor\r\nServerAuditSpecifications\r\nCustomErrors\r\nServerRoles\r\nAvailabilityGroups\r\nReplicationSettings",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "BatchSeparator",
                           "Batch separator for scripting output. \"GO\" by default.",
                           "",
                           false,
                           "false",
                           "GO"
                       ],
                       [
                           "ScriptingOption",
                           "Add scripting options to scripting output for all objects except Registered Servers and Extended Events.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Export-DbaInstance [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Path] \u003cString\u003e] [-NoRecovery] [-IncludeDbMasterKey] [[-Exclude] \u003cString[]\u003e] [[-BatchSeparator] \u003cString\u003e] [[-ScriptingOption] \u003cScriptingOptions\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Export-DbaLinkedServer",
        "Description":  "Exports linked servers INCLUDING PASSWORDS, unless specified otherwise, to sql file.\n\nRequires remote Windows access if exporting the password.",
        "Tags":  "LinkedServer",
        "Synopsis":  "Exports linked servers INCLUDING PASSWORDS, unless specified otherwise, to sql file.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Export-DbaLinkedServer",
        "Availability":  "Windows only",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaLinkedServer -SqlInstance sql2017 -Path C:\\temp\\ls.sql\nExports the linked servers, including passwords, from sql2017 to the file C:\\temp\\ls.sql\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExport-DbaLinkedServer -SqlInstance sql2017 -Path C:\\temp\\ls.sql -ExcludePassword\nExports the linked servers, without passwords, from sql2017 to the file C:\\temp\\ls.sql",
        "Params":  [
                       [
                           "SqlInstance",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2005 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "LinkedServer",
                           "The linked server(s) to export. If unspecified, all linked servers will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative linked servers. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Credential",
                           "Login to the target OS using alternative linked servers. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "The path to the exported sql file.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludePassword",
                           "Exports the linked server without any sensitive information.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Append",
                           "Append to Path",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Allow credentials to be piped in from Get-DbaLinkedServer",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Export-DbaLinkedServer [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-LinkedServer] \u003cString[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Path] \u003cString\u003e] [-ExcludePassword] [-Append] [[-InputObject] \u003cLinkedServer[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Export-DbaLogin",
        "Description":  "Exports Windows and SQL Logins to a T-SQL file. Export includes login, SID, password, default database, default language, server permissions, server roles, db permissions, db roles.",
        "Tags":  [
                     "Export",
                     "Login"
                 ],
        "Synopsis":  "Exports Windows and SQL Logins to a T-SQL file. Export includes login, SID, password, default database, default language, server permissions, server roles, db permissions, db roles.",
        "Alias":  "Export-SqlLogin",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Export-DbaLogin",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Export-DbaLogin",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaLogin -SqlInstance sql2005 -Path C:\\temp\\sql2005-logins.sql\nExports the logins for SQL Server \"sql2005\" and writes them to the file \"C:\\temp\\sql2005-logins.sql\"\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExport-DbaLogin -SqlInstance sqlserver2014a -ExcludeLogin realcajun -SqlCredential $scred -Path C:\\temp\\logins.sql -Append\nAuthenticates to sqlserver2014a using SQL Authentication. Exports all logins except for realcajun to C:\\temp\\logins.sql, and appends to the file if it exists. If not, the file will be created.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eExport-DbaLogin -SqlInstance sqlserver2014a -Login realcajun, netnerds -Path C:\\temp\\logins.sql\nExports ONLY logins netnerds and realcajun FROM sqlserver2014a to the file  C:\\temp\\logins.sql\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eExport-DbaLogin -SqlInstance sqlserver2014a -Login realcajun, netnerds -Database HR, Accounting\nExports ONLY logins netnerds and realcajun FROM sqlserver2014a with the permissions on databases HR and Accounting\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eExport-DbaLogin -SqlInstance sqlserver2008 -Login realcajun, netnerds -Path C:\\temp\\login.sql -ExcludeGoBatchSeparator\nExports ONLY logins netnerds and realcajun FROM sqlserver2008 server, to the C:\\temp\\login.sql file without the \u0027GO\u0027 batch separator.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eExport-DbaLogin -SqlInstance sqlserver2008 -Login realcajun -Path C:\\temp\\users.sql -DestinationVersion SQLServer2016\nExports login realcajun from sqlserver2008 to the file C:\\temp\\users.sql with syntax to run on SQL Server 2016",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. SQL Server 2000 and above supported.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Login",
                           "The login(s) to process. Options for this list are auto-populated from the server. If unspecified, all logins will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeLogin",
                           "The login(s) to exclude. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "The file to write to.",
                           "OutFile,FilePath,FileName",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NoClobber",
                           "If this switch is enabled, a file already existing at the path specified by Path will not be overwritten.",
                           "NoOverwrite",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Append",
                           "If this switch is enabled, content will be appended to a file already existing at the path specified by Path. If the file does not exist, it will be created.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ExcludeDatabases",
                           "If this switch is enabled, mappings for databases will not be exported.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ExcludeJobs",
                           "If this switch is enabled, Agent job ownership will not be exported.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ExcludeGoBatchSeparator",
                           "If specified, will NOT script the \u0027GO\u0027 batch separator.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DestinationVersion",
                           "To say to which version the script should be generated. If not specified will use instance major version.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Export-DbaLogin [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Login] \u003cObject[]\u003e] [[-ExcludeLogin] \u003cObject[]\u003e] [[-Database] \u003cObject[]\u003e] [[-Path] \u003cString\u003e] [-NoClobber] [-Append] [-ExcludeDatabases] [-ExcludeJobs] [-EnableException] [-ExcludeGoBatchSeparator] [[-DestinationVersion] \u003cString\u003e] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Export-DbaPfDataCollectorSetTemplate",
        "Description":  "Exports a Data Collector Set XML Template from Get-DbaPfDataCollectorSet. Exports to \"$home\\Documents\\Performance Monitor Templates\" by default.",
        "Tags":  [
                     "Performance",
                     "DataCollector"
                 ],
        "Synopsis":  "Exports a new Data Collector Set XML Template.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Export-DbaPfDataCollectorSetTemplate",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Export-DbaPfDataCollectorSetTemplate",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaPfDataCollectorSetTemplate -ComputerName sql2017 -Path C:\\temp\\pf\nExports all data collector sets from to the C:\\temp\\pf folder.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet ComputerName sql2017 -CollectorSet \u0027System Correlation\u0027 | Export-DbaPfDataCollectorSetTemplate -Path C:\\temp\nExports the \u0027System Correlation\u0027 data collector set from sql2017 to C:\\temp.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer. Defaults to localhost.",
                           "",
                           false,
                           "false",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to $ComputerName using alternative credentials. To use:\n$cred = Get-Credential, then pass $cred object to the -Credential parameter.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CollectorSet",
                           "The name of the collector set(s) to export.",
                           "DataCollectorSet",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "The path to export the file. Can be .xml or directory.",
                           "",
                           false,
                           "false",
                           "\"$home\\Documents\\Performance Monitor Templates\""
                       ],
                       [
                           "InputObject",
                           "Accepts the object output by Get-DbaPfDataCollectorSetTemplate via the pipeline.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Export-DbaPfDataCollectorSetTemplate [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CollectorSet] \u003cString[]\u003e] [[-Path] \u003cString\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Export-DbaRepServerSetting",
        "Description":  "Exports replication server settings to file.",
        "Tags":  "Replication",
        "Synopsis":  "Exports replication server settings to file.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Export-DbaRepServerSetting",
        "Availability":  "Windows only",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaRepServerSetting -SqlInstance sql2017 -Path C:\\temp\\replication.sql\nExports the replication settings on sql2017 to the file C:\\temp\\replication.sql\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRepServer -SqlInstance sql2017 | Export-DbaRepServerSettings -Path C:\\temp\\replication.sql\nExports the replication settings on sql2017 to the file C:\\temp\\replication.sql",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "Specifies the path to a file which will contain the output.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ScriptOption",
                           "Not real sure how to use this yet",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows piping from Get-DbaRepServer",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Encoding",
                           "Specifies the file encoding. The default is UTF8.\nValid values are:\r\n-- ASCII: Uses the encoding for the ASCII (7-bit) character set.\r\n-- BigEndianUnicode: Encodes in UTF-16 format using the big-endian byte order.\r\n-- Byte: Encodes a set of characters into a sequence of bytes.\r\n-- String: Uses the encoding type for a string.\r\n-- Unicode: Encodes in UTF-16 format using the little-endian byte order.\r\n-- UTF7: Encodes in UTF-7 format.\r\n-- UTF8: Encodes in UTF-8 format.\r\n-- Unknown: The encoding type is unknown or invalid. The data can be treated as binary.",
                           "",
                           false,
                           "false",
                           "UTF8"
                       ],
                       [
                           "Passthru",
                           "Output script to console",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NoClobber",
                           "Do not overwrite file",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Append",
                           "Append to file",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Export-DbaRepServerSetting [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Path] \u003cString\u003e] [[-ScriptOption] \u003cObject[]\u003e] [[-InputObject] \u003cReplicationServer[]\u003e] [[-Encoding] \u003cString\u003e] [-Passthru] [-NoClobber] [-Append] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Export-DbaScript",
        "Description":  "Exports scripts from SQL Management Objects",
        "Tags":  [
                     "Migration",
                     "Backup",
                     "Export"
                 ],
        "Synopsis":  "Exports scripts from SQL Management Objects (SMO)",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Export-DbaScript",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Export-DbaScript",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance sql2016 | Export-DbaScript\nExports all jobs on the SQL Server sql2016 instance using a trusted connection - automatically determines filename as .\\sql2016-Job-Export-date.sql\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance sql2016 | Export-DbaScript -Path C:\\temp\\export.sql -Append\nExports all jobs on the SQL Server sql2016 instance using a trusted connection - Will append the output to the file C:\\temp\\export.sql if it already exists\r\nScript does not include Batch Separator and will not compile\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance sql2016 -Database MyDatabase -Table \u0027dbo.Table1\u0027, \u0027dbo.Table2\u0027 -SqlCredential sqladmin | Export-DbaScript -Path C:\\temp\\export.sql\nExports only script for \u0027dbo.Table1\u0027 and \u0027dbo.Table2\u0027 in MyDatabase to C:temp\\export.sql and uses the SQL login \"sqladmin\" to login to sql2016\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance sql2016 -Job syspolicy_purge_history, \u0027Hourly Log Backups\u0027 -SqlCredential sqladmin | Export-DbaScript -Path C:\\temp\\export.sql -NoPrefix\nExports only syspolicy_purge_history and \u0027Hourly Log Backups\u0027 to C:temp\\export.sql and uses the SQL login \"sqladmin\" to login to sql2016\r\nSuppress the output of a Prefix\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$options = New-DbaScriptingOption\nPS C:\\\u003e $options.ScriptSchema = $true\r\nPS C:\\\u003e $options.IncludeDatabaseContext  = $true\r\nPS C:\\\u003e $options.IncludeHeaders = $false\r\nPS C:\\\u003e $Options.NoCommandTerminator = $false\r\nPS C:\\\u003e $Options.ScriptBatchTerminator = $true\r\nPS C:\\\u003e $Options.AnsiFile = $true\r\nPS C:\\\u003e Get-DbaAgentJob -SqlInstance sql2016 -Job syspolicy_purge_history, \u0027Hourly Log Backups\u0027 -SqlCredential sqladmin | Export-DbaScript -Path C:\\temp\\export.sql -ScriptingOptionsObject $options\nExports only syspolicy_purge_history and \u0027Hourly Log Backups\u0027 to C:temp\\export.sql and uses the SQL login \"sqladmin\" to login to sql2016\r\nAppends a batch separator at end of each script.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance sql2014 | Export-DbaScript -Passthru | ForEach-Object { $_.Replace(\u0027sql2014\u0027,\u0027sql2016\u0027) } | Set-Content -Path C:\\temp\\export.sql\nExports jobs and replaces all instances of the servername \"sql2014\" with \"sql2016\" then writes to C:\\temp\\export.sql\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$options = New-DbaScriptingOption\nPS C:\\\u003e $options.ScriptSchema = $true\r\nPS C:\\\u003e $options.IncludeDatabaseContext  = $true\r\nPS C:\\\u003e $options.IncludeHeaders = $false\r\nPS C:\\\u003e $Options.NoCommandTerminator = $false\r\nPS C:\\\u003e $Options.ScriptBatchTerminator = $true\r\nPS C:\\\u003e $Options.AnsiFile = $true\r\nPS C:\\\u003e $Databases = Get-DbaDatabase -SqlInstance sql2016 -ExcludeDatabase master, model, msdb, tempdb\r\nPS C:\\\u003e foreach ($db in $Databases) {\r\n\u003e\u003e        Export-DbaScript -InputObject $db -Path C:\\temp\\export.sql -Append -Encoding UTF8 -ScriptingOptionsObject $options -NoPrefix\r\n\u003e\u003e }\nExports Script for each database on sql2016 excluding system databases\r\nUses Scripting options to ensure Batch Terminator is set\r\nWill append the output to the file C:\\temp\\export.sql if it already exists",
        "Params":  [
                       [
                           "InputObject",
                           "A SQL Management Object such as the one returned from Get-DbaLogin",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "ScriptingOptionsObject",
                           "An SMO Scripting Object that can be used to customize the output - see New-DbaScriptingOption",
                           "ScriptingOptionObject",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "The output filename and location. If no path is specified, one will be created. If the file already exists, the output will be appended.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Encoding",
                           "Specifies the file encoding. The default is UTF8.\nValid values are:\r\n-- ASCII: Uses the encoding for the ASCII (7-bit) character set.\r\n-- BigEndianUnicode: Encodes in UTF-16 format using the big-endian byte order.\r\n-- Byte: Encodes a set of characters into a sequence of bytes.\r\n-- String: Uses the encoding type for a string.\r\n-- Unicode: Encodes in UTF-16 format using the little-endian byte order.\r\n-- UTF7: Encodes in UTF-7 format.\r\n-- UTF8: Encodes in UTF-8 format.\r\n-- Unknown: The encoding type is unknown or invalid. The data can be treated as binary.",
                           "",
                           false,
                           "false",
                           "UTF8"
                       ],
                       [
                           "BatchSeparator",
                           "Specifies the Batch Separator to use. Default is None",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NoPrefix",
                           "Do not include a Prefix",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Passthru",
                           "Output script to console",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NoClobber",
                           "Do not overwrite file",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Append",
                           "Append to file",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Export-DbaScript [-InputObject] \u003cObject[]\u003e [[-ScriptingOptionsObject] \u003cScriptingOptions\u003e] [[-Path] \u003cString\u003e] [[-Encoding] \u003cString\u003e] [[-BatchSeparator] \u003cString\u003e] [-NoPrefix] [-Passthru] [-NoClobber] [-Append] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Export-DbaSpConfigure",
        "Description":  "Exports advanced sp_configure global configuration options to sql file.",
        "Tags":  [
                     "SpConfig",
                     "Configure",
                     "Configuration"
                 ],
        "Synopsis":  "Exports advanced sp_configure global configuration options to sql file.",
        "Alias":  "Export-SqlSpConfigure",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Export-DbaSpConfigure",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Export-DbaSpConfigure",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaSpConfigure -SqlInstance sourceserver\nExports the SPConfigure settings on sourceserver. As no Path was defined outputs to My Documents folder with default name format of Servername-MMDDYYYYhhmmss-sp_configure.sql\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExport-DbaSpConfigure -SqlInstance sourceserver -Path C:\\temp\nExports the SPConfigure settings on sourceserver to the directory C:\\temp using the default name format\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Export-DbaSpConfigure -SqlInstance sourceserver -SqlCredential $cred -Path C:\\temp\\sp_configure.sql\nExports the SPConfigure settings on sourceserver to the file C:\\temp\\sp_configure.sql. Uses SQL Authentication to connect. Will require SysAdmin rights if needs to set \u0027show advanced options\u0027\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027Server1\u0027, \u0027Server2\u0027 | Export-DbaSpConfigure -Path C:\\temp\\configure.sql\nExports the SPConfigure settings for Server1 and Server2 using pipeline. As more than 1 Server adds prefix of Servername and date to the file name and saves to file like  \r\nC:\\temp\\Servername-MMDDYYYYhhmmss-configure.sql",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input.\r\nYou must have sysadmin access if needs to set \u0027show advanced options\u0027 to 1 and server version must be SQL Server version 2005 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "Specifies the path to a file which will contain the sp_configure queries necessary to replicate the configuration settings on another instance. This file is suitable for input into \r\nImport-DbaSPConfigure.\r\nIf not specified will output to My Documents folder with default name of ServerName-MMDDYYYYhhmmss-sp_configure.sql\r\nIf a directory is passed then uses default name of ServerName-MMDDYYYYhhmmss-sp_configure.sql",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Export-DbaSpConfigure [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Path] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Export-DbatoolsConfig",
        "Description":  "Exports configuration items to a Json file.",
        "Synopsis":  "Exports configuration items to a Json file.",
        "Alias":  "",
        "CommandName":  "Export-DbatoolsConfig",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbatoolsConfig | Export-DbatoolsConfig -OutPath \u0027~/export.json\u0027\nExports all current settings to json.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExport-DbatoolsConfig -Module message -OutPath \u0027~/export.json\u0027 -SkipUnchanged\nExports all settings of the module \u0027message\u0027 that are no longer the original default values to json.",
        "Params":  [
                       [
                           "FullName",
                           "Select the configuration objects to export by filtering by their full name.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Module",
                           "Select the configuration objects to export by filtering by their module name.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "Select the configuration objects to export by filtering by their name.",
                           "",
                           false,
                           "false",
                           "*"
                       ],
                       [
                           "Config",
                           "The configuration object(s) to export.\r\nReturned by Get-DbatoolsConfig.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "ModuleName",
                           "Exports all configuration pertinent to a module to a predefined path.\r\nExported configuration items include all settings marked as \u0027ModuleExport\u0027 that have been changed from the default value.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "ModuleVersion",
                           "The configuration version of the module-settings to write.",
                           "",
                           false,
                           "false",
                           "1"
                       ],
                       [
                           "Scope",
                           "Which predefined path to write module specific settings to.\r\nOnly file scopes are considered.\r\nBy default it writes to the suer profile.",
                           "",
                           false,
                           "false",
                           "FileUserShared"
                       ],
                       [
                           "OutPath",
                           "The path (filename included) to export to.\r\nWill fail if the folder does not exist, will overwrite the file if it exists.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SkipUnchanged",
                           "If set, configuration objects whose value was not changed from its original value will not be exported.\r\n(Note: Settings that were updated with the same value as the original default will still be considered changed)",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "This parameters disables user-friendly warnings and enables the throwing of exceptions.\r\nThis is less user friendly, but allows catching exceptions in calling scripts.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Export-DbatoolsConfig [-FullName] \u003cString\u003e [-OutPath] \u003cString\u003e [-SkipUnchanged] [-EnableException] [\u003cCommonParameters\u003e]\nExport-DbatoolsConfig [-Module] \u003cString\u003e [[-Name] \u003cString\u003e] [-OutPath] \u003cString\u003e [-SkipUnchanged] [-EnableException] [\u003cCommonParameters\u003e]\nExport-DbatoolsConfig [-Config] \u003cConfig[]\u003e [-OutPath] \u003cString\u003e [-SkipUnchanged] [-EnableException] [\u003cCommonParameters\u003e]\nExport-DbatoolsConfig -ModuleName \u003cString\u003e [-ModuleVersion \u003cInt32\u003e] [-Scope {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [-SkipUnchanged] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Export-DbaUser",
        "Description":  "Exports users creation and its permissions to a T-SQL file or host. Export includes user, create and add to role(s), database level permissions, object level permissions.",
        "Tags":  [
                     "User",
                     "Export"
                 ],
        "Synopsis":  "Exports users creation and its permissions to a T-SQL file or host.",
        "Alias":  "Export-SqlUser",
        "Author":  "Claudio Silva (@ClaudioESSilva)",
        "CommandName":  "Export-DbaUser",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Export-DbaUser",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaUser -SqlInstance sql2005 -Path C:\\temp\\sql2005-users.sql\nExports SQL for the users in server \"sql2005\" and writes them to the file \"C:\\temp\\sql2005-users.sql\"\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExport-DbaUser -SqlInstance sqlserver2014a $scred -Path C:\\temp\\users.sql -Append\nAuthenticates to sqlserver2014a using SQL Authentication. Exports all users to C:\\temp\\users.sql, and appends to the file if it exists. If not, the file will be created.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eExport-DbaUser -SqlInstance sqlserver2014a -User User1, User2 -Path C:\\temp\\users.sql\nExports ONLY users User1 and User2 from sqlserver2014a to the file  C:\\temp\\users.sql\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eExport-DbaUser -SqlInstance sqlserver2008 -User User1 -Path C:\\temp\\users.sql -DestinationVersion SQLServer2016\nExports user User1 from sqlserver2008 to the file C:\\temp\\users.sql with syntax to run on SQL Server 2016\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eExport-DbaUser -SqlInstance sqlserver2008 -Database db1,db2 -Path C:\\temp\\users.sql\nExports ONLY users from db1 and db2 database on sqlserver2008 server, to the C:\\temp\\users.sql file.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$options = New-DbaScriptingOption\nPS C:\\\u003e $options.ScriptDrops = $false\r\nPS C:\\\u003e $options.WithDependencies = $true\r\nPS C:\\\u003e Export-DbaUser -SqlInstance sqlserver2008 -Database db1,db2 -Path C:\\temp\\users.sql -ScriptingOptionsObject $options\nExports ONLY users from db1 and db2 database on sqlserver2008 server, to the C:\\temp\\users.sql file.\r\nIt will not script drops but will script dependencies.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eExport-DbaUser -SqlInstance sqlserver2008 -Database db1,db2 -Path C:\\temp\\users.sql -ExcludeGoBatchSeparator\nExports ONLY users from db1 and db2 database on sqlserver2008 server, to the C:\\temp\\users.sql file without the \u0027GO\u0027 batch separator.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. SQL Server 2000 and above supported.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to servers using alternative credentials\n$scred = Get-Credential, then pass $scred object to the -SqlCredential parameter\nWindows Authentication will be used if SqlCredential is not specified",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "User",
                           "Export only the specified database user(s). If not specified will export all users from the database(s)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DestinationVersion",
                           "To say to which version the script should be generated. If not specified will use database compatibility level",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "Specifies the full path of a file to write the script to.",
                           "OutFile,FilePath,FileName",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NoClobber",
                           "Do not overwrite file",
                           "NoOverwrite",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Append",
                           "Append to file",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ScriptingOptionsObject",
                           "A Microsoft.SqlServer.Management.Smo.ScriptingOptions object with the options that you want to use to generate the t-sql script.\r\nYou can use the NEw-DbaScriptingOption to generate it.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeGoBatchSeparator",
                           "If specified, will NOT script the \u0027GO\u0027 batch separator.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Export-DbaUser [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-User] \u003cObject[]\u003e] [[-DestinationVersion] \u003cString\u003e] [[-Path] \u003cString\u003e] [-NoClobber] [-Append] [-EnableException] [[-ScriptingOptionsObject] \u003cScriptingOptions\u003e] [-ExcludeGoBatchSeparator] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Export-DbaXECsv",
        "Description":  "Exports Extended Events to a CSV file.",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "Exports Extended Events to a CSV file.",
        "Alias":  "",
        "Author":  "Gianluca Sartori (@spaghettidba)",
        "CommandName":  "Export-DbaXECsv",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Export-DbaXECsv",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-ChildItem -Path C:\\temp\\sample.xel | Export-DbaXECsv -Path c:\\temp\\sample.csv\nWrites Extended Events data to the file \"C:\\temp\\events.csv\".\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sql2014 -Session deadlocks | Export-DbaXECsv -Path c:\\temp\\events.csv\nWrites Extended Events data to the file \"C:\\temp\\events.csv\".",
        "Params":  [
                       [
                           "InputObject",
                           "Allows Piping",
                           "FullName",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Path",
                           "Specifies the InputObject to the output CSV file",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Export-DbaXECsv [-InputObject] \u003cObject[]\u003e [-Path] \u003cString\u003e [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Export-DbaXESessionTemplate",
        "Description":  "Exports an XESession XML Template either from the Target SQL Server or XE Session(s) output by Get-DbaXESession. Exports to \"$home\\Documents\\SQL Server Management Studio\\Templates\\XEventTemplates\" by default",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "Exports an XESession XML Template using XE Session(s) output by Get-DbaXESession",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Export-DbaXESessionTemplate",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Export-DbaXESessionTemplate",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaXESessionTemplate -SqlInstance sql2017 -Path C:\\temp\\xe\nExports an XESession XML Template for all Extended Event Sessions on sql2017 to the C:\\temp\\xe folder.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sql2017 -Session system_health | Export-DbaXESessionTemplate -Path C:\\temp\\xe\nGets the system_health Extended Events Session from sql2017 and then exports as an XESession XML Template to C:\\temp\\xe",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Session",
                           "The Name of the session(s) to export.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "The path to export the file into. Can be .xml or directory.",
                           "",
                           false,
                           "false",
                           "\"$home\\Documents\\SQL Server Management Studio\\Templates\\XEventTemplates\""
                       ],
                       [
                           "InputObject",
                           "Specifies an XE Session output by Get-DbaXESession.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Export-DbaXESessionTemplate [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Session] \u003cObject[]\u003e] [[-Path] \u003cString\u003e] [[-InputObject] \u003cSession[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Find-DbaAgentJob",
        "Description":  "This command filters SQL Agent jobs giving the DBA a list of jobs that may need attention or could possibly be options for removal.",
        "Tags":  [
                     "Agent",
                     "Job"
                 ],
        "Synopsis":  "Find-DbaAgentJob finds agent jobs that fit certain search filters.",
        "Alias":  "",
        "Author":  "Stephen Bennett (https://sqlnotesfromtheunderground.wordpress.com/)",
        "CommandName":  "Find-DbaAgentJob",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Find-DbaAgentJob",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaAgentJob -SqlInstance Dev01 -JobName *backup*\nReturns all agent job(s) that have backup in the name\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaAgentJob -SqlInstance Dev01, Dev02 -JobName Mybackup\nReturns all agent job(s) that are named exactly Mybackup\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaAgentJob -SqlInstance Dev01 -LastUsed 10\nReturns all agent job(s) that have not ran in 10 days\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eFind-DbaAgentJob -SqlInstance Dev01 -IsDisabled -IsNoEmailNotification -IsNotScheduled\nReturns all agent job(s) that are either disabled, have no email notification or don\u0027t have a schedule. returned with detail\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$servers | Find-DbaAgentJob -IsFailed | Start-DbaAgentJob\nFinds all failed job then starts them. Consider using a -WhatIf at the end of Start-DbaAgentJob to see what it\u0027ll do first\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eFind-DbaAgentJob -SqlInstance Dev01 -LastUsed 10 -Exclude \"Yearly - RollUp Workload\", \"SMS - Notification\"\nReturns all agent jobs that have not ran in the last 10 days ignoring jobs \"Yearly - RollUp Workload\" and \"SMS - Notification\"\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eFind-DbaAgentJob -SqlInstance Dev01 -Category \"REPL-Distribution\", \"REPL-Snapshot\" | Format-Table -AutoSize -Wrap\nReturns all job/s on Dev01 that are in either category \"REPL-Distribution\" or \"REPL-Snapshot\"\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eFind-DbaAgentJob -SqlInstance Dev01, Dev02 -IsFailed -Since \u00272016-07-01 10:47:00\u0027\nReturns all agent job(s) on Dev01 and Dev02 that have failed since July of 2016 (and still have history in msdb)\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance CMSServer -Group Production | Find-DbaAgentJob -Disabled -IsNotScheduled | Format-Table -AutoSize -Wrap\nQueries CMS server to return all SQL instances in the Production folder and then list out all agent jobs that have either been disabled or have no schedule.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "JobName",
                           "Filter agent jobs to only the name(s) you list.\r\nSupports regular expression (e.g. MyJob*) being passed in.",
                           "Name",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeJobName",
                           "Allows you to enter an array of agent job names to ignore",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "StepName",
                           "Filter based on StepName.\r\nSupports regular expression (e.g. MyJob*) being passed in.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "LastUsed",
                           "Find all jobs that havent ran in the INT number of previous day(s)",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "IsDisabled",
                           "Find all jobs that are disabled",
                           "Disabled",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IsFailed",
                           "Find all jobs that have failed",
                           "Failed",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IsNotScheduled",
                           "Find all jobs with no schedule assigned",
                           "NoSchedule",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IsNoEmailNotification",
                           "Find all jobs without email notification configured",
                           "NoEmailNotification",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Category",
                           "Filter based on agent job categories",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Owner",
                           "Filter based on owner of the job/s",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Since",
                           "Datetime object used to narrow the results to a date",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Find-DbaAgentJob [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-JobName \u003cString[]\u003e] [-ExcludeJobName \u003cString[]\u003e] [-StepName \u003cString[]\u003e] [-LastUsed \u003cInt32\u003e] [-IsDisabled] [-IsFailed] [-IsNotScheduled] [-IsNoEmailNotification] [-Category \u003cString[]\u003e] [-Owner \u003cString\u003e] [-Since \u003cDateTime\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Find-DbaBackup",
        "Description":  "Provides all of the same functionality for finding SQL backups to remove from disk as a standard maintenance plan would.\n\nAs an addition you have the ability to check the Archive bit on files before deletion. This will allow you to ensure backups have been archived to your archive location before removal.",
        "Tags":  "Backup",
        "Synopsis":  "Finds SQL Server backups on disk.",
        "Alias":  "",
        "Author":  "Chris Sommer (@cjsommer), www.cjsommer.com",
        "CommandName":  "Find-DbaBackup",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Find-DbaBackup",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaBackup -Path \u0027C:\\MSSQL\\SQL Backup\\\u0027 -BackupFileExtension trn -RetentionPeriod 48h\nSearches for all trn files in C:\\MSSQL\\SQL Backup\\ and all subdirectories that are more than 48 hours old will be included.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaBackup -Path \u0027C:\\MSSQL\\Backup\\\u0027 -BackupFileExtension bak -RetentionPeriod 7d -CheckArchiveBit\nSearches for all bak files in C:\\MSSQL\\Backup\\ and all subdirectories that are more than 7 days old will be included, but only if the files have been backed up to another location as verified by \r\nchecking the Archive bit.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaBackup -Path \u0027\\\\SQL2014\\Backup\\\u0027 -BackupFileExtension bak -RetentionPeriod 24h | Remove-Item -Verbose\nSearches for all bak files in \\\\SQL2014\\Backup\\ and all subdirectories that are more than 24 hours old and deletes only those files with verbose message.",
        "Params":  [
                       [
                           "Path",
                           "Specifies the name of the base level folder to search for backup files.",
                           "BackupFolder",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "BackupFileExtension",
                           "Specifies the filename extension of the backup files you wish to find (typically \u0027bak\u0027, \u0027trn\u0027 or \u0027log\u0027). Do not include the period.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "RetentionPeriod",
                           "Specifies the retention period for backup files. Correct format is ##U.\n## is the retention value and must be an integer value\r\nU signifies the units where the valid units are:\r\nh = hours\r\nd = days\r\nw = weeks\r\nm = months\nFormatting Examples:\r\n\u002748h\u0027 = 48 hours\r\n\u00277d\u0027 = 7 days\r\n\u00274w\u0027 = 4 weeks\r\n\u00271m\u0027 = 1 month",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "CheckArchiveBit",
                           "If this switch is enabled, the filesystem Archive bit is checked.\r\nIf this bit is set (which translates to \"it has not been backed up to another location yet\"), the file won\u0027t be included.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Find-DbaBackup [-Path] \u003cString\u003e [-BackupFileExtension] \u003cString\u003e [-RetentionPeriod] \u003cString\u003e [-CheckArchiveBit] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Find-DbaCommand",
        "Description":  "Finds dbatools commands searching through the inline help text, building a consolidated json index and querying it because Get-Help is too slow",
        "Tags":  [
                     "Find",
                     "Help",
                     "Command"
                 ],
        "Synopsis":  "Finds dbatools commands searching through the inline help text",
        "Alias":  "",
        "Author":  "Simone Bizzotto (@niphlod)",
        "CommandName":  "Find-DbaCommand",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Find-DbaCommand",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaCommand \"snapshot\"\nFor lazy typers: finds all commands searching the entire help for \"snapshot\"\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaCommand -Pattern \"snapshot\"\nFor rigorous typers: finds all commands searching the entire help for \"snapshot\"\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaCommand -Tag copy\nFinds all commands tagged with \"copy\"\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eFind-DbaCommand -Tag copy,user\nFinds all commands tagged with BOTH \"copy\" and \"user\"\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eFind-DbaCommand -Author chrissy\nFinds every command whose author contains our beloved \"chrissy\"\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eFind-DbaCommand -Author chrissy -Tag copy\nFinds every command whose author contains our beloved \"chrissy\" and it tagged as \"copy\"\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eFind-DbaCommand -Pattern snapshot -Rebuild\nFinds all commands searching the entire help for \"snapshot\", rebuilding the index (good for developers)",
        "Params":  [
                       [
                           "Pattern",
                           "Searches help for all commands in dbatools for the specified pattern and displays all results",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Tag",
                           "Finds all commands tagged with this auto-populated tag",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Author",
                           "Finds all commands tagged with this author",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "MinimumVersion",
                           "Finds all commands tagged with this auto-populated minimum version",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "MaximumVersion",
                           "Finds all commands tagged with this auto-populated maximum version",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Rebuild",
                           "Rebuilds the index",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Displays what would happen if the command is run",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Confirms overwrite of index",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Find-DbaCommand [[-Pattern] \u003cString\u003e] [[-Tag] \u003cString[]\u003e] [[-Author] \u003cString\u003e] [[-MinimumVersion] \u003cString\u003e] [[-MaximumVersion] \u003cString\u003e] [-Rebuild] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Find-DbaDatabase",
        "Description":  "Allows you to search SQL Server instances for database that have either the same name, owner or service broker guid.\n\nThere a several reasons for the service broker guid not matching on a restored database primarily using alter database new broker. or turn off broker to return a guid of 0000-0000-0000-0000.",
        "Tags":  "Database",
        "Synopsis":  "Find database/s on multiple servers that match criteria you input",
        "Alias":  "",
        "Author":  "Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/",
        "CommandName":  "Find-DbaDatabase",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Find-DbaDatabase",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaDatabase -SqlInstance \"DEV01\", \"DEV02\", \"UAT01\", \"UAT02\", \"PROD01\", \"PROD02\" -Pattern Report\nReturns all database from the SqlInstances that have a database with Report in the name\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaDatabase -SqlInstance \"DEV01\", \"DEV02\", \"UAT01\", \"UAT02\", \"PROD01\", \"PROD02\" -Pattern TestDB -Exact | Select-Object *\nReturns all database from the SqlInstances that have a database named TestDB with a detailed output.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaDatabase -SqlInstance \"DEV01\", \"DEV02\", \"UAT01\", \"UAT02\", \"PROD01\", \"PROD02\" -Property ServiceBrokerGuid -Pattern \u0027-faeb-495a-9898-f25a782835f5\u0027 | Select-Object *\nReturns all database from the SqlInstances that have the same Service Broker GUID with a detailed output",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Credential object used to connect to the SQL Server as a different user",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Property",
                           "What you would like to search on. Either Database Name, Owner, or Service Broker GUID. Database name is the default.",
                           "",
                           false,
                           "false",
                           "Name"
                       ],
                       [
                           "Pattern",
                           "Value that is searched for. This is a regular expression match but you can just use a plain ol string like \u0027dbareports\u0027",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Exact",
                           "Search for an exact match instead of a pattern",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Detailed",
                           "Output all properties, will be depreciated in 1.0.0 release.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Find-DbaDatabase [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Property] \u003cString\u003e] [-Pattern] \u003cString\u003e [-Exact] [-Detailed] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Find-DbaDbGrowthEvent",
        "Description":  "Finds any database AutoGrow events in the Default Trace.\n\nThe following events are included:\n92 - Data File Auto Grow\n93 - Log File Auto Grow\n94 - Data File Auto Shrink\n95 - Log File Auto Shrink",
        "Tags":  [
                     "AutoGrow",
                     "Growth",
                     "Database"
                 ],
        "Synopsis":  "Finds any database AutoGrow events in the Default Trace.",
        "Alias":  "Find-DbaDatabaseGrowthEvent",
        "Author":  "Aaron Nelson",
        "CommandName":  "Find-DbaDbGrowthEvent",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Find-DbaDatabaseGrowthEvent",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaDatabaseGrowthEvent -SqlInstance localhost\nReturns any database AutoGrow events in the Default Trace with UTC time for the instance for every database on the localhost instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaDatabaseGrowthEvent -SqlInstance localhost -UseLocalTime\nReturns any database AutoGrow events in the Default Trace with the local time of the instance for every database on the localhost instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaDatabaseGrowthEvent -SqlInstance ServerA\\SQL2016, ServerA\\SQL2014\nReturns any database AutoGrow events in the Default Traces for every database on ServerA\\sql2016 \u0026 ServerA\\SQL2014.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eFind-DbaDatabaseGrowthEvent -SqlInstance ServerA\\SQL2016 | Format-Table -AutoSize -Wrap\nReturns any database AutoGrow events in the Default Trace for every database on the ServerA\\SQL2016 instance in a table format.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eFind-DbaDatabaseGrowthEvent -SqlInstance ServerA\\SQL2016 -EventType Shrink\nReturns any database Auto Shrink events in the Default Trace for every database on the ServerA\\SQL2016 instance.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eFind-DbaDatabaseGrowthEvent -SqlInstance ServerA\\SQL2016 -EventType Growth -FileType Data\nReturns any database Auto Growth events on data files in the Default Trace for every database on the ServerA\\SQL2016 instance.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EventType",
                           "Provide a filter on growth event type to filter the results.\nAllowed values: Growth, Shrink",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "FileType",
                           "Provide a filter on file type to filter the results.\nAllowed values: Data, Log",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "UseLocalTime",
                           "Return the local time of the instance instead of converting to UTC.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Find-DbaDbGrowthEvent [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-EventType] \u003cString\u003e] [[-FileType] \u003cString\u003e] [-UseLocalTime] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Find-DbaDbUnusedIndex",
        "Description":  "This command will help you to find Unused indexes on a database or a list of databases\n\nFor now only supported for CLUSTERED and NONCLUSTERED indexes",
        "Tags":  "Index",
        "Synopsis":  "Find unused indexes",
        "Alias":  "Find-SqlUnusedIndex",
        "Author":  "Aaron Nelson (@SQLvariant), SQLvariant.com",
        "CommandName":  "Find-DbaDbUnusedIndex",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Find-DbaDbUnusedIndex",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaDbUnusedIndex -SqlInstance sql2016 -Database db1, db2\nFinds unused databases on db1 and db2 on sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaDbUnusedIndex -SqlInstance sql2016 -SqlCredential $cred\nFinds unused databases on db1 and db2 on sql2016 using SQL Authentication to connect to the server\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016 | Find-DbaDbUnusedIndex\nFinds unused databases on all databases on sql2016",
        "Params":  [
                       [
                           "SqlInstance",
                           "The SQL Server you want to check for unused indexes.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IgnoreUptime",
                           "Less than 7 days uptime can mean that analysis of unused indexes is unreliable, and normally no results will be returned. By setting this option results will be returned even if the Instance has been \r\nrunning for less that 7 days.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaDatabase",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Find-DbaDbUnusedIndex [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-IgnoreUptime] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Find-DbaDisabledIndex",
        "Description":  "This command will help you to find disabled indexes on a database or a list of databases.",
        "Tags":  "Index",
        "Synopsis":  "Find Disabled indexes",
        "Alias":  "",
        "Author":  "Jason Squires, sqlnotnull.com",
        "CommandName":  "Find-DbaDisabledIndex",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Find-DbadisabledIndex",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaDisabledIndex -SqlInstance sql2005\nGenerates the SQL statements to drop the selected disabled indexes on server \"sql2005\".\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaDisabledIndex -SqlInstance sqlserver2016 -SqlCredential $cred\nGenerates the SQL statements to drop the selected disabled indexes on server \"sqlserver2016\", using SQL Authentication to connect to the database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaDisabledIndex -SqlInstance sqlserver2016 -Database db1, db2\nGenerates the SQL Statement to drop selected indexes in databases db1 \u0026 db2 on server \"sqlserver2016\".\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eFind-DbaDisabledIndex -SqlInstance sqlserver2016\nGenerates the SQL statements to drop selected indexes on all user databases.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NoClobber",
                           "If this switch is enabled, the output file will not be overwritten.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Append",
                           "If this switch is enabled, content will be appended to the output file.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Find-DbaDisabledIndex [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-NoClobber] [-Append] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Find-DbaDuplicateIndex",
        "Description":  "This command will help you to find duplicate and overlapping indexes on a database or a list of databases.\n\nOn SQL Server 2008 and higher, the IsFiltered property will also be checked\n\nOnly supports CLUSTERED and NONCLUSTERED indexes.\n\nOutput:\nTableName\nIndexName\nKeyColumns\nIncludedColumns\nIndexSizeMB\nIndexType\nCompressionDescription (When 2008+)\n[RowCount]\nIsDisabled\nIsFiltered (When 2008+)",
        "Tags":  "Index",
        "Synopsis":  "Find duplicate and overlapping indexes.",
        "Alias":  "Find-SqlDuplicateIndex",
        "Author":  "Claudio Silva (@ClaudioESSilva)",
        "CommandName":  "Find-DbaDuplicateIndex",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Find-DbaDuplicateIndex",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaDuplicateIndex -SqlInstance sql2005\nReturns duplicate indexes found on sql2005\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaDuplicateIndex -SqlInstance sql2017 -SqlCredential sqladmin\nFinds exact duplicate indexes on all user databases present on sql2017, using SQL authentication.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaDuplicateIndex -SqlInstance sql2017 -Database db1, db2\nFinds exact duplicate indexes on the db1 and db2 databases.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eFind-DbaDuplicateIndex -SqlInstance sql2017 -IncludeOverlapping\nFinds both duplicate and overlapping indexes on all user databases.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IncludeOverlapping",
                           "If this switch is enabled, indexes which are partially duplicated will be returned.\nExample: If the first key column is the same between two indexes, but one has included columns and the other not, this will be shown.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Find-DbaDuplicateIndex [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [-IncludeOverlapping] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Find-DbaInstance",
        "Description":  "This function searches for SQL Server Instances.\n\nIt supports a variety of scans for this purpose which can be separated in two categories:\n- Discovery\n- Scan\n\nDiscovery:\nThis is where it compiles a list of computers / addresses to check.\nIt supports several methods of generating such lists (including Active Directory lookup or IP Ranges), but also supports specifying a list of computers to check.\n- For details on discovery, see the documentation on the \u0027-DiscoveryType\u0027 parameter\n- For details on explicitly providing a list, see the documentation on the \u0027-ComputerName\u0027 parameter\n\nScan:\nOnce a list of computers has been provided, this command will execute a variety of actions to determine any instances present for each of them.\nThis is described in more detail in the documentation on the \u0027-ScanType\u0027 parameter.\nAdditional parameters allow more granular control over individual scans (e.g. Credentials to use).\n\nNote on logging and auditing:\nThe Discovery phase is un-problematic since it is non-intrusive, however during the scan phase, all targeted computers may be accessed repeatedly.\nThis may cause issues with security teams, due to many logon events and possibly failed authentication.\nThis action constitutes a network scan, which may be illegal depending on the nation you are in and whether you own the network you scan.\nIf you are unsure whether you may use this command in your environment, check the detailed description on the \u0027-ScanType\u0027 parameter and contact your IT security team for advice.",
        "Tags":  [
                     "Instance",
                     "Connect",
                     "SqlServer"
                 ],
        "Synopsis":  "Search for SQL Server Instances.",
        "Alias":  "",
        "Author":  "Scott Sutherland, 2018 NetSPI | Friedrich Weinmann (@FredWeinmann)",
        "CommandName":  "Find-DbaInstance",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Find-DbaInstance",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaInstance -DiscoveryType Domain, DataSourceEnumeration\nPerforms a network search for SQL Instances by:\r\n- Looking up the Service Principal Names of computers in active directory\r\n- Using the UDP broadcast based auto-discovery of SSMS\r\nAfter that it will extensively scan all hosts thus discovered for instances.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaInstance -DiscoveryType All\nPerforms a network search for SQL Instances, using all discovery protocols:\r\n- Active directory search for Service Principal Names\r\n- SQL Instance Enumeration (same as SSMS does)\r\n- All IPAddresses in the current computer\u0027s subnets of all connected network interfaces\r\nNote: This scan will take a long time, due to including the IP Scan\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-ADComputer -Filter \"*\" | Find-DbaInstance\nScans all computers in the domain for SQL Instances, using a deep probe:\r\n- Tries resolving the name in DNS\r\n- Tries pinging the computer\r\n- Tries listing all SQL Services using CIM/WMI\r\n- Tries discovering all instances via the browser service\r\n- Tries connecting to the default TCP Port (1433)\r\n- Tries connecting to the TCP port of each discovered instance\r\n- Tries to establish a SQL connection to the server using default windows credentials\r\n- Tries looking up the Service Principal Names for each instance\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-Content .\\servers.txt | Find-DbaInstance -SqlCredential $cred -ScanType Browser, SqlConnect\nReads all servers from the servers.txt file (one server per line),\r\nthen scans each of them for instances using the browser service\r\nand finally attempts to connect to each instance found using the specified credentials.\r\nthen scans each of them for instances using the browser service and SqlService\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eFind-DbaInstance -ComputerName localhost | Get-DbaDatabase | Format-Table -Wrap\nScans localhost for instances using the browser service, traverses all instances for all databases and displays all information in a formatted table.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eFind-DbaInstance -ComputerName localhost | Get-DbaDatabase | Select-Object SqlInstance, Name, Status, RecoveryModel, SizeMB, Compatibility, Owner, LastFullBackup, LastDiffBackup, LastLogBackup \r\n| Format-Table -Wrap\nScans localhost for instances using the browser service, traverses all instances for all databases and displays a subset of the important information in a formatted table.\nUsing this method reguarly is not recommended. Use Get-DbaService or Get-DbaCmsRegServer instead.",
        "Params":  [
                       [
                           "ComputerName",
                           "The computer to scan. Can be a variety of input types, including text or the output of Get-ADComputer.\r\nAny extra instance information (such as connection strings or live sql server connections) beyond the computername will be discarded.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "DiscoveryType",
                           "The mechanisms to be used to discover instances.\r\nSupports any combination of:\r\n- Service Principal Name lookup (\u0027Domain\u0027; from Active Directory)\r\n- SQL Instance Enumeration (\u0027DataSourceEnumeration\u0027; same as SSMS uses)\r\n- IP Address range (\u0027IPRange\u0027; all IP Addresses will be scanned)\nSPN Lookup:\r\nThe function tries to connect active directory to look up all computers with registered SQL Instances.\r\nNot all instances need to be registered properly, making this not 100% reliable.\r\nBy default, your nearest Domain Controller is contacted for this scan.\r\nHowever it is possible to explicitly state the DC to contact using its DistinguishedName and the \u0027-DomainController\u0027 parameter.\r\nIf credentials were specified using the \u0027-Credential\u0027 parameter, those same credentials are used to perform this lookup, allowing the scan of other domains.\nSQL Instance Enumeration:\r\nThis uses the default UDP Broadcast based instance enumeration used by SSMS to detect instances.\r\nNote that the result from this is not used in the actual scan, but only to compile a list of computers to scan.\r\nTo enable the same results for the scan, ensure that the \u0027Browser\u0027 scan is enabled.\nIP Address range:\r\nThis \u0027Discovery\u0027 uses a range of IPAddresses and simply passes them on to be tested.\r\nSee the \u0027Description\u0027 part of help on security issues of network scanning.\r\nBy default, it will enumerate all ethernet network adapters on the local computer and scan the entire subnet they are on.\r\nBy using the \u0027-IpAddress\u0027 parameter, custom network ranges can be specified.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Credential",
                           "The credentials to use on windows network connection.\r\nThese credentials are used for:\r\n- Contact to domain controllers for SPN lookups (only if explicit Domain Controller is specified)\r\n- CIM/WMI contact to the scanned computers during the scan phase (see the \u0027-ScanType\u0027 parameter documentation on affected scans).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "The credentials used to connect to SqlInstances to during the scan phase.\r\nSee the \u0027-ScanType\u0027 parameter documentation on affected scans.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ScanType",
                           "The scans are the individual methods used to retrieve information about the scanned computer and any potentially installed instances.\r\nThis parameter is optional, by default all scans except for establishing an actual SQL connection are performed.\r\nScans can be specified in any arbitrary combination, however at least one instance detecting scan needs to be specified in order for data to be returned.\nScans:\r\n Browser\r\n- Tries discovering all instances via the browser service\r\n- This scan detects instances.\nSQLService\r\n- Tries listing all SQL Services using CIM/WMI\r\n- This scan uses credentials specified in the \u0027-Credential\u0027 parameter if any.\r\n- This scan detects instances.\r\n- Success in this scan guarantees high confidence (See parameter \u0027-MinimumConfidence\u0027 for details).\nSPN\r\n- Tries looking up the Service Principal Names for each instance\r\n- Will use the nearest Domain Controller by default\r\n- Target a specific domain controller using the \u0027-DomainController\u0027 parameter\r\n- If using the \u0027-DomainController\u0027 parameter, use the \u0027-Credential\u0027 parameter to specify the credentials used to connect\nTCPPort\r\n- Tries connecting to the TCP Ports.\r\n- By default, port 1433 is connected to.\r\n- The parameter \u0027-TCPPort\u0027 can be used to provide a list of port numbers to scan.\r\n- This scan detects possible instances. Since other services might bind to a given port, this is not the most reliable test.\r\n- This scan is also used to validate found SPNs if both scans are used in combination\nDNSResolve\r\n- Tries resolving the computername in DNS\nPing\r\n- Tries pinging the computer. Failure will NOT terminate scans.\nSqlConnect\r\n- Tries to establish a SQL connection to the server\r\n- Uses windows credentials by default\r\n- Specify custom credentials using the \u0027-SqlCredential\u0027 parameter\r\n- This scan is not used by default\r\n- Success in this scan guarantees high confidence (See parameter \u0027-MinimumConfidence\u0027 for details).\nAll\r\n- All of the above",
                           "",
                           false,
                           "false",
                           "Default"
                       ],
                       [
                           "IpAddress",
                           "This parameter can be used to override the defaults for the IPRange discovery.\r\nThis parameter accepts a list of strings supporting any combination of:\r\n- Plain IP Addresses (e.g.: \"10.1.1.1\")\r\n- IP Address Ranges (e.g.: \"10.1.1.1-10.1.1.5\")\r\n- IP Address \u0026 Subnet Mask (e.g.: \"10.1.1.1/255.255.255.0\")\r\n- IP Address \u0026 Subnet Length: (e.g.: \"10.1.1.1/24)\r\nOverlapping addresses will not result in duplicate scans.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DomainController",
                           "The domain controller to contact for SPN lookups / searches.\r\nUses the credentials from the \u0027-Credential\u0027 parameter if specified.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "TCPPort",
                           "The ports to scan in the TCP Port Scan method.\r\nDefaults to 1433.",
                           "",
                           false,
                           "false",
                           "1433"
                       ],
                       [
                           "MinimumConfidence",
                           "This command tries to discover instances, which isn\u0027t always a sure thing.\r\nDepending on the number and type of scans completed, we have different levels of confidence in our results.\r\nBy default, we will return anything that we have at least a low confidence of being an instance.\r\nThese are the confidence levels we support and how they are determined:\r\n- High: Established SQL Connection (including rejection for bad credentials) or service scan.\r\n- Medium: Browser reply or a combination of TCPConnect _and_ SPN test.\r\n- Low: Either TCPConnect _or_ SPN\r\n- None: Computer existence could be verified, but no sign of an SQL Instance",
                           "",
                           false,
                           "false",
                           "Low"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Find-DbaInstance -ComputerName \u003cDbaInstanceParameter[]\u003e [-Credential \u003cPSCredential\u003e] [-SqlCredential \u003cPSCredential\u003e] [-ScanType {TCPPort | SqlConnect | SqlService | DNSResolve | SPN | Browser | Ping | Default | All}] [-DomainController \u003cString\u003e] [-TCPPort \u003cInt32[]\u003e] [-MinimumConfidence {None | Low | Medium | High}] [-EnableException] [\u003cCommonParameters\u003e]\nFind-DbaInstance -DiscoveryType {IPRange | Domain | DataSourceEnumeration | All} [-Credential \u003cPSCredential\u003e] [-SqlCredential \u003cPSCredential\u003e] [-ScanType {TCPPort | SqlConnect | SqlService | DNSResolve | SPN | Browser | Ping | Default | All}] [-IpAddress \u003cString[]\u003e] [-DomainController \u003cString\u003e] [-TCPPort \u003cInt32[]\u003e] [-MinimumConfidence {None | Low | Medium | High}] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Find-DbaLoginInGroup",
        "Description":  "Outputs all the active directory groups members for a server, or limits it to find a specific AD user in the groups",
        "Tags":  [
                     "Login",
                     "Group",
                     "Security"
                 ],
        "Synopsis":  "Finds Logins in Active Directory groups that have logins on the SQL Instance.",
        "Alias":  "",
        "Author":  "Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/ | Simone Bizzotto (@niphlod)",
        "CommandName":  "Find-DbaLoginInGroup",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Find-DbaLoginInGroup",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaLoginInGroup -SqlInstance DEV01 -Login \"MyDomain\\Stephen.Bennett\"\nReturns all active directory groups with logins on Sql Instance DEV01 that contain the AD user Stephen.Bennett.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaLoginInGroup -SqlInstance DEV01\nReturns all active directory users within all windows AD groups that have logins on the instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaLoginInGroup -SqlInstance DEV01 | Where-Object Login -like \u0027*stephen*\u0027\nReturns all active directory users within all windows AD groups that have logins on the instance whose login contains \"stephen\"",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "PSCredential object to connect under. If not specified, current Windows login will be used.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Login",
                           "Find all AD Groups used on the instance that an individual login is a member of.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Find-DbaLoginInGroup [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Login] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Find-DbaOrphanedFile",
        "Description":  "This command searches all directories associated with SQL database files for database files that are not currently in use by the SQL Server instance.\n\nBy default, it looks for orphaned .mdf, .ldf and .ndf files in the root\\data directory, the default data path, the default log path, the system paths and any directory in use by any attached directory.\n\nYou can specify additional filetypes using the -FileType parameter, and additional paths to search using the -Path parameter.",
        "Tags":  [
                     "Orphan",
                     "Database",
                     "DatabaseFile"
                 ],
        "Synopsis":  "Find-DbaOrphanedFile finds orphaned database files. Orphaned database files are files not associated with any attached database.",
        "Alias":  "",
        "Author":  "Sander Stad (@sqlstad), sqlstad.nl",
        "CommandName":  "Find-DbaOrphanedFile",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Find-DbaOrphanedFile",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaOrphanedFile -SqlInstance sqlserver2014a\nConnects to sqlserver2014a, authenticating with Windows credentials, and searches for orphaned files. Returns server name, local filename, and unc path to file.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaOrphanedFile -SqlInstance sqlserver2014a -SqlCredential $cred\nConnects to sqlserver2014a, authenticating with SQL Server authentication, and searches for orphaned files. Returns server name, local filename, and unc path to file.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaOrphanedFile -SqlInstance sql2014 -Path \u0027E:\\Dir1\u0027, \u0027E:\\Dir2\u0027\nFinds the orphaned files in \"E:\\Dir1\" and \"E:Dir2\" in addition to the default directories.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eFind-DbaOrphanedFile -SqlInstance sql2014 -LocalOnly\nReturns only the local file paths for orphaned files.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eFind-DbaOrphanedFile -SqlInstance sql2014 -RemoteOnly\nReturns only the remote file path for orphaned files.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eFind-DbaOrphanedFile -SqlInstance sql2014, sql2016 -FileType fsf, mld\nFinds the orphaned ending with \".fsf\" and \".mld\" in addition to the default filetypes \".mdf\", \".ldf\", \".ndf\" for both the servers sql2014 and sql2016.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "Specifies one or more directories to search in addition to the default data and log directories.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "FileType",
                           "Specifies file extensions other than mdf, ldf and ndf to search for. Do not include the dot (\".\") when specifying the extension.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "LocalOnly",
                           "If this switch is enabled, only local filenames will be returned. Using this switch with multiple servers is not recommended since it does not return the associated server name.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "RemoteOnly",
                           "If this switch is enabled, only remote filenames will be returned.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Find-DbaOrphanedFile [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Path] \u003cString[]\u003e] [[-FileType] \u003cString[]\u003e] [-LocalOnly] [-RemoteOnly] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Find-DbaSimilarTable",
        "Description":  "This function can either run against specific databases or all databases searching all/specific tables and views including in system databases.\nTypically one would use this to find for example archive version(s) of a table whose structures are similar.\nThis can also be used to find tables/views that are very similar to a given table/view structure to see where a table/view might be used.\n\nMore information can be found here: https://sqljana.wordpress.com/2017/03/31/sql-server-find-tables-with-similar-table-structure/",
        "Tags":  "Table",
        "Synopsis":  "Returns all tables/views that are similar in structure by comparing the column names of matching and matched tables/views",
        "Alias":  "",
        "Author":  "Jana Sattainathan (@SQLJana), http://sqljana.wordpress.com",
        "CommandName":  "Find-DbaSimilarTable",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Find-DbaSimilarTable",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaSimilarTable -SqlInstance DEV01\nSearches all user database tables and views for each, returns all tables or views with their matching tables/views and match percent\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaSimilarTable -SqlInstance DEV01 -Database AdventureWorks\nSearches AdventureWorks database and lists tables/views and their corresponding matching tables/views with match percent\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaSimilarTable -SqlInstance DEV01 -Database AdventureWorks -SchemaName HumanResource\nSearches AdventureWorks database and lists tables/views in the HumanResource schema with their corresponding matching tables/views with match percent\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eFind-DbaSimilarTable -SqlInstance DEV01 -Database AdventureWorks -SchemaName HumanResource -Table Employee\nSearches AdventureWorks database and lists tables/views in the HumanResource schema and table Employee with its corresponding matching tables/views with match percent\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eFind-DbaSimilarTable -SqlInstance DEV01 -Database AdventureWorks -MatchPercentThreshold 60\nSearches AdventureWorks database and lists all tables/views with its corresponding matching tables/views with match percent greater than or equal to 60",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SchemaName",
                           "If you are looking in a specific schema whose table structures is to be used as reference structure, provide the name of the schema.\r\nIf no schema is provided, looks at all schemas",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "TableName",
                           "If you are looking in a specific table whose structure is to be used as reference structure, provide the name of the table.\r\nIf no table is provided, looks at all tables\r\nIf the table name exists in multiple schemas, all of them would qualify",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeViews",
                           "By default, views are included. You can exclude them by setting this switch to $false\r\nThis excludes views in both matching and matched list",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IncludeSystemDatabases",
                           "By default system databases are ignored but you can include them within the search using this parameter",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "MatchPercentThreshold",
                           "The minimum percentage of column names that should match between the matching and matched objects.\r\nEntries with no matches are eliminated",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Find-DbaSimilarTable [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-SchemaName \u003cString\u003e] [-TableName \u003cString\u003e] [-ExcludeViews] [-IncludeSystemDatabases] [-MatchPercentThreshold \u003cInt32\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Find-DbaStoredProcedure",
        "Description":  "This function can either run against specific databases or all databases searching all user or user and system stored procedures.",
        "Tags":  [
                     "StoredProcedure",
                     "Proc"
                 ],
        "Synopsis":  "Returns all stored procedures that contain a specific case-insensitive string or regex pattern.",
        "Alias":  "",
        "Author":  "Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/",
        "CommandName":  "Find-DbaStoredProcedure",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Find-DbaStoredProcedure",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaStoredProcedure -SqlInstance DEV01 -Pattern whatever\nSearches all user databases stored procedures for \"whatever\" in the text body\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaStoredProcedure -SqlInstance sql2016 -Pattern \u0027\\w+@\\w+\\.\\w+\u0027\nSearches all databases for all stored procedures that contain a valid email pattern in the text body\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaStoredProcedure -SqlInstance DEV01 -Database MyDB -Pattern \u0027some string\u0027 -Verbose\nSearches in \"mydb\" database stored procedures for \"some string\" in the text body\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eFind-DbaStoredProcedure -SqlInstance sql2016 -Database MyDB -Pattern RUNTIME -IncludeSystemObjects\nSearches in \"mydb\" database stored procedures for \"runtime\" in the text body",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Pattern",
                           "String pattern that you want to search for in the stored procedure text body",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "IncludeSystemObjects",
                           "By default, system stored procedures are ignored but you can include them within the search using this parameter.\nWarning - this will likely make it super slow if you run it on all databases.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IncludeSystemDatabases",
                           "By default system databases are ignored but you can include them within the search using this parameter",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Find-DbaStoredProcedure [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] -Pattern \u003cString\u003e [-IncludeSystemObjects] [-IncludeSystemDatabases] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Find-DbaTrigger",
        "Description":  "This function search on Instance, Database and Object level.\nIf you specify one or more databases, search on Server level will not be preformed.",
        "Tags":  "Trigger",
        "Synopsis":  "Returns all triggers that contain a specific case-insensitive string or regex pattern.",
        "Alias":  "",
        "Author":  "Claudio Silva (@ClaudioESSilva)",
        "CommandName":  "Find-DbaTrigger",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Find-DbaTrigger",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaTrigger -SqlInstance DEV01 -Pattern whatever\nSearches all user databases triggers for \"whatever\" in the text body\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaTrigger -SqlInstance sql2016 -Pattern \u0027\\w+@\\w+\\.\\w+\u0027\nSearches all databases for all triggers that contain a valid email pattern in the text body\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaTrigger -SqlInstance DEV01 -Database MyDB -Pattern \u0027some string\u0027 -Verbose\nSearches in \"mydb\" database triggers for \"some string\" in the text body\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eFind-DbaTrigger -SqlInstance sql2016 -Database MyDB -Pattern RUNTIME -IncludeSystemObjects\nSearches in \"mydb\" database triggers for \"runtime\" in the text body",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Pattern",
                           "String pattern that you want to search for in the trigger text body",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "TriggerLevel",
                           "Allows specify the trigger level that you want to search. By default is All (Server, Database, Object).",
                           "",
                           false,
                           "false",
                           "All"
                       ],
                       [
                           "IncludeSystemObjects",
                           "By default, system triggers are ignored but you can include them within the search using this parameter.\nWarning - this will likely make it super slow if you run it on all databases.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IncludeSystemDatabases",
                           "By default system databases are ignored but you can include them within the search using this parameter",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Find-DbaTrigger [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] -Pattern \u003cString\u003e [-TriggerLevel \u003cString\u003e] [-IncludeSystemObjects] [-IncludeSystemDatabases] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Find-DbaUserObject",
        "Description":  "Looks at the below list of objects to see if they are either owned by a user or a specific user (using the parameter -Pattern)\nDatabase Owner\nAgent Job Owner\nUsed in Credential\nUSed in Proxy\nSQL Agent Steps using a Proxy\nEndpoints\nServer Roles\nDatabase Schemas\nDatabase Roles\nDatabase Assembles\nDatabase Synonyms",
        "Tags":  "Object",
        "Synopsis":  "Searches SQL Server to find user-owned objects (i.e. not dbo or sa) or for any object owned by a specific user specified by the Pattern parameter.",
        "Alias":  "",
        "Author":  "Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/",
        "CommandName":  "Find-DbaUserObject",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Find-DbaUserObject",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaUserObject -SqlInstance DEV01 -Pattern ad\\stephen\nSearches user objects for owner ad\\stephen\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaUserObject -SqlInstance DEV01 -Verbose\nShows all user owned (non-sa, non-dbo) objects and verbose output",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input",
                           "ServerInstance,SqlServer,SqlInstances",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Pattern",
                           "The regex pattern that the command will search for",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Find-DbaUserObject [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Pattern \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Find-DbaView",
        "Description":  "This function can either run against specific databases or all databases searching all user or user and system views.",
        "Tags":  "View",
        "Synopsis":  "Returns all views that contain a specific case-insensitive string or regex pattern.",
        "Alias":  "",
        "Author":  "Claudio Silva  (@ClaudioESSilva)",
        "CommandName":  "Find-DbaView",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Find-DbaView",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaView -SqlInstance DEV01 -Pattern whatever\nSearches all user databases views for \"whatever\" in the text body\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaView -SqlInstance sql2016 -Pattern \u0027\\w+@\\w+\\.\\w+\u0027\nSearches all databases for all views that contain a valid email pattern in the text body\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaView -SqlInstance DEV01 -Database MyDB -Pattern \u0027some string\u0027 -Verbose\nSearches in \"mydb\" database views for \"some string\" in the text body\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eFind-DbaView -SqlInstance sql2016 -Database MyDB -Pattern RUNTIME -IncludeSystemObjects\nSearches in \"mydb\" database views for \"runtime\" in the text body",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Pattern",
                           "String pattern that you want to search for in the view text body",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "IncludeSystemObjects",
                           "By default, system views are ignored but you can include them within the search using this parameter.\nWarning - this will likely make it super slow if you run it on all databases.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IncludeSystemDatabases",
                           "By default system databases are ignored but you can include them within the search using this parameter",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Find-DbaView [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] -Pattern \u003cString\u003e [-IncludeSystemObjects] [-IncludeSystemDatabases] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Format-DbaBackupInformation",
        "Description":  "Performs various mapping on Backup History, ready restoring\nOptions include changing restore paths, backup paths, database name and many others",
        "Tags":  [
                     "DisasterRecovery",
                     "Backup",
                     "Restore"
                 ],
        "Synopsis":  "Transforms the data in a dbatools BackupHistory object for a restore",
        "Alias":  "",
        "Author":  "Stuart Moore (@napalmgram), stuart-moore.com",
        "CommandName":  "Format-DbaBackupInformation",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Format-DbaBackupInformation",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$History | Format-DbaBackupInformation -ReplaceDatabaseName NewDb\nChanges as database name references to NewDb, both in the database name and any restore paths. Note, this will fail if the BackupHistory object contains backups for more than 1 database\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$History | Format-DbaBackupInformation -ReplaceDatabaseName @{\u0027OldB\u0027=\u0027NewDb\u0027;\u0027ProdHr\u0027=\u0027DevHr\u0027}\nWill change all occurrences of original database name in the backup history (names and restore paths) using the mapping in the hashtable.\r\nIn this example any occurrence of OldDb will be replaced with NewDb and ProdHr with DevPR\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$History | Format-DbaBackupInformation -DataFileDirectory \u0027D:\\DataFiles\\\u0027 -LogFileDirectory \u0027E:\\LogFiles\\\nThis example with change the restore path for all data files (everything that is not a log file) to d:\\datafiles\r\nAnd all Transaction Log files will be restored to E:\\Logfiles\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$History | Format-DbaBackupInformation -RebaseBackupFolder f:\\backups\nThis example changes the location that SQL Server will look for the backups. This is useful if you\u0027ve moved the backups to a different location",
        "Params":  [
                       [
                           "BackupHistory",
                           "A dbatools backupHistory object, normally this will have been created using Select-DbaBackupInformation",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "ReplaceDatabaseName",
                           "If a single value is provided, this will be replaced do all occurrences a database name\r\nIf a Hashtable is passed in, each database name mention will be replaced as specified. If a database\u0027s name does not appear it will not be replace\r\nDatabaseName will also be replaced where it  occurs in the file paths of data and log files.\r\nPlease note, that this won\u0027t change the Logical Names of data files, that has to be done with a separate Alter DB call",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ReplaceDbNameInFile",
                           "If set, will replace the old database name with the new name if it occurs in the file name",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DataFileDirectory",
                           "This will move ALL restored files to this location during the restore",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "LogFileDirectory",
                           "This will move all log files to this location, overriding DataFileDirectory",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DestinationFileStreamDirectory",
                           "This move the FileStream folder and contents to the new location, overriding DataFileDirectory",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DatabaseNamePrefix",
                           "This string will be prefixed to all restored database\u0027s name",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DatabaseFilePrefix",
                           "A string that will be prefixed to every file restored",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DatabaseFileSuffix",
                           "A string that will be suffixed to every file restored",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RebaseBackupFolder",
                           "Use this to rebase where your backups are stored.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Continue",
                           "Indicates that this is a continuing restore",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "FileMapping",
                           "A hashtable that can be used to move specific files to a location.\r\n`$FileMapping = @{\u0027DataFile1\u0027=\u0027c:\\restoredfiles\\Datafile1.mdf\u0027;\u0027DataFile3\u0027=\u0027d:\\DataFile3.mdf\u0027}`\r\nAnd files not specified in the mapping will be restored to their original location\r\nThis Parameter is exclusive with DestinationDataDirectory\r\nIf specified, this will override any other file renaming/relocation options.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "PathSep",
                           "By default is Windows\u0027s style (`\\`) but you can pass also, e.g., `/` for Unix\u0027s style paths",
                           "",
                           false,
                           "false",
                           "\\"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Format-DbaBackupInformation [-BackupHistory] \u003cObject[]\u003e [[-ReplaceDatabaseName] \u003cObject\u003e] [-ReplaceDbNameInFile] [[-DataFileDirectory] \u003cString\u003e] [[-LogFileDirectory] \u003cString\u003e] [[-DestinationFileStreamDirectory] \u003cString\u003e] [[-DatabaseNamePrefix] \u003cString\u003e] [[-DatabaseFilePrefix] \u003cString\u003e] [[-DatabaseFileSuffix] \u003cString\u003e] [[-RebaseBackupFolder] \u003cString\u003e] [-Continue] [[-FileMapping] \u003cHashtable\u003e] [[-PathSep] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaAgDatabase",
        "Description":  "Gets availability group databases from a SQL Server instance.\n\nDefault view provides most common set of properties for information on the database in an availability group.\n\nInformation returned on the database will be specific to that replica, whether it is primary or a secondary.",
        "Tags":  [
                     "Hadr",
                     "HA",
                     "AG",
                     "AvailabilityGroup",
                     "Replica"
                 ],
        "Synopsis":  "Gets availability group databases from a SQL Server instance.",
        "Alias":  "",
        "Author":  "Shawn Melton (@wsmelton), https://wsmelton.github.io",
        "CommandName":  "Get-DbaAgDatabase",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaAgDatabase",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgDatabase -SqlInstance sql2017a\nReturns all the databases in each availability group found on sql2017a\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgDatabase -SqlInstance sql2017a -AvailabilityGroup AG101\nReturns all the databases in the availability group AG101 on sql2017a\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sqlcluster -AvailabilityGroup SharePoint -Database Sharepoint_Config | Get-DbaAgDatabase\nReturns the database Sharepoint_Config found in the availability group SharePoint on server sqlcluster",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityGroup",
                           "Specify the availability groups to query.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specify the database or databases to return. This list is auto-populated from the server for tab completion. Multiple databases can be specified. If none are specified all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piped input from Get-DbaAvailabilityGroup.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaAgDatabase [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cAvailabilityGroup[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaAgentAlert",
        "Description":  "This function returns SQL Agent alerts.",
        "Tags":  [
                     "Agent",
                     "SMO"
                 ],
        "Synopsis":  "Returns all SQL Agent alerts on a SQL Server Agent.",
        "Alias":  "",
        "Author":  "Klaas Vandenberghe (@PowerDBAKlaas)",
        "CommandName":  "Get-DbaAgentAlert",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaAgentAlert",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentAlert -SqlInstance ServerA,ServerB\\instanceB\nReturns all SQL Agent alerts on serverA and serverB\\instanceB\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027serverA\u0027,\u0027serverB\\instanceB\u0027 | Get-DbaAgentAlert\nReturns all SQL Agent alerts  on serverA and serverB\\instanceB",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,Instance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaAgentAlert [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaAgentJob",
        "Description":  "The Get-DbaAgentJob returns connected SMO object for SQL Agent Job information for each instance(s) of SQL Server.",
        "Tags":  [
                     "Job",
                     "Agent"
                 ],
        "Synopsis":  "Gets SQL Agent Job information for each instance(s) of SQL Server.",
        "Alias":  "",
        "Author":  "Garry Bargsley (@gbargsley), http://blog.garrybargsley.com",
        "CommandName":  "Get-DbaAgentJob",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaAgentJob",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance localhost\nReturns all SQL Agent Jobs on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance localhost, sql2016\nReturns all SQl Agent Jobs for the local and sql2016 SQL Server instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance localhost -Job BackupData, BackupDiff\nReturns all SQL Agent Jobs named BackupData and BackupDiff from the local SQL Server instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance localhost -ExcludeJob BackupDiff\nReturns all SQl Agent Jobs for the local SQL Server instances, except the BackupDiff Job.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance localhost -ExcludeDisabledJobs\nReturns all SQl Agent Jobs for the local SQL Server instances, excluding the disabled jobs.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$servers | Get-DbaAgentJob | Out-GridView -PassThru | Start-DbaAgentJob -WhatIf\nFind all of your Jobs from SQL Server instances in the $servers collection, select the jobs you want to start then see jobs would start if you ran Start-DbaAgentJob\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance sqlserver2014a | Where-Object Category -eq \"Report Server\" | Export-DbaScript -Path \"C:\\temp\\sqlserver2014a_SSRSJobs.sql\"\nExports all SSRS jobs from SQL instance sqlserver2014a to a file.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Job",
                           "The job(s) to process - this list is auto-populated from the server. If unspecified, all jobs will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeJob",
                           "The job(s) to exclude - this list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Return jobs with T-SQL job steps associated with specific databases",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Category",
                           "Return jobs associated with specific category",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDisabledJobs",
                           "Switch will exclude disabled jobs from the output.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaAgentJob [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cString[]\u003e] [-ExcludeJob \u003cString[]\u003e] [-Database \u003cString[]\u003e] [-Category \u003cString[]\u003e] [-ExcludeDisabledJobs] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaAgentJobCategory",
        "Description":  "Get-DbaAgentJobCategory makes it possible to retrieve the job categories.",
        "Tags":  [
                     "Agent",
                     "Job",
                     "JobCategory"
                 ],
        "Synopsis":  "Get-DbaAgentJobCategory retrieves the job categories.",
        "Alias":  "Get-DbaJobCategory",
        "Author":  "Sander Stad (@sqlstad), sqlstad.nl",
        "CommandName":  "Get-DbaAgentJobCategory",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaAgentJobCategory",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentJobCategory -SqlInstance sql1\nReturn all the job categories.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentJobCategory -SqlInstance sql1 -Category \u0027Log Shipping\u0027\nReturn all the job categories that have the name \u0027Log Shipping\u0027.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgentJobCategory -SqlInstance sstad-pc -CategoryType MultiServerJob\nReturn all the job categories that have a type MultiServerJob.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Category",
                           "The name of the category to filter out. If no category is used all categories will be returned.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CategoryType",
                           "The type of category. This can be \"LocalJob\", \"MultiServerJob\" or \"None\".\r\nIf no category is used all categories types will be returned.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "The force parameter will ignore some errors in the parameters and assume defaults.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaAgentJobCategory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Category] \u003cString[]\u003e] [[-CategoryType] \u003cString\u003e] [-Force] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaAgentJobHistory",
        "Description":  "Get-DbaAgentJobHistory returns all information on the executions still available on each instance(s) of SQL Server submitted.\nThe cleanup of SQL Agent history determines how many records are kept.\n\nhttps://msdn.microsoft.com/en-us/library/ms201680.aspx\nhttps://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.agent.jobhistoryfilter(v=sql.120).aspx",
        "Tags":  [
                     "Job",
                     "Agent"
                 ],
        "Synopsis":  "Gets execution history of SQL Agent Job on instance(s) of SQL Server.",
        "Alias":  "",
        "Author":  "Klaas Vandenberghe (@PowerDbaKlaas) | Simone Bizzotto (@niphold)",
        "CommandName":  "Get-DbaAgentJobHistory",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaAgentJobHistory",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentJobHistory -SqlInstance localhost\nReturns all SQL Agent Job execution results on the local default SQL Server instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentJobHistory -SqlInstance localhost, sql2016\nReturns all SQL Agent Job execution results for the local and sql2016 SQL Server instances.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\\Inst2K17\u0027 | Get-DbaAgentJobHistory\nReturns all SQL Agent Job execution results for sql1 and sql2\\Inst2K17.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAgentJobHistory -SqlInstance sql2\\Inst2K17 | Select-Object *\nReturns all properties for all SQl Agent Job execution results on sql2\\Inst2K17.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaAgentJobHistory -SqlInstance sql2\\Inst2K17 -Job \u0027Output File Cleanup\u0027\nReturns all properties for all SQl Agent Job execution results of the \u0027Output File Cleanup\u0027 job on sql2\\Inst2K17.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaAgentJobHistory -SqlInstance sql2\\Inst2K17 -Job \u0027Output File Cleanup\u0027 -WithOutputFile\nReturns all properties for all SQl Agent Job execution results of the \u0027Output File Cleanup\u0027 job on sql2\\Inst2K17,\r\nwith additional properties that show the output filename path\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaAgentJobHistory -SqlInstance sql2\\Inst2K17 -ExcludeJobSteps\nReturns the SQL Agent Job execution results for the whole jobs on sql2\\Inst2K17, leaving out job step execution results.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eGet-DbaAgentJobHistory -SqlInstance sql2\\Inst2K17 -StartDate \u00272017-05-22\u0027 -EndDate \u00272017-05-23 12:30:00\u0027\nReturns the SQL Agent Job execution results between 2017/05/22 00:00:00 and 2017/05/23 12:30:00 on sql2\\Inst2K17.\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance sql2016 | Where-Object Name -Match backup | Get-DbaAgentJobHistory\nGets all jobs with the name that match the regex pattern \"backup\" and then gets the job history from those. You can also use -Like *backup* in this example.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Job",
                           "The name of the job from which the history is wanted. If unspecified, all jobs will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeJob",
                           "The job(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "StartDate",
                           "The DateTime starting from which the history is wanted. If unspecified, all available records will be processed.",
                           "",
                           false,
                           "false",
                           "1900-01-01"
                       ],
                       [
                           "EndDate",
                           "The DateTime before which the history is wanted. If unspecified, all available records will be processed.",
                           "",
                           false,
                           "false",
                           "$(Get-Date)"
                       ],
                       [
                           "ExcludeJobSteps",
                           "Use this switch to discard all job steps, and return only the job totals",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WithOutputFile",
                           "Use this switch to retrieve the output file (only if you want step details). Bonus points, we handle the quirks\r\nof SQL Agent tokens to the best of our knowledge (https://technet.microsoft.com/it-it/library/ms175575(v=sql.110).aspx)",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "JobCollection",
                           "An array of SMO jobs",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaAgentJobHistory [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cObject[]\u003e] [-ExcludeJob \u003cObject[]\u003e] [-StartDate \u003cDateTime\u003e] [-EndDate \u003cDateTime\u003e] [-ExcludeJobSteps] [-WithOutputFile] [-EnableException] [\u003cCommonParameters\u003e]\nGet-DbaAgentJobHistory -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cObject[]\u003e] [-ExcludeJob \u003cObject[]\u003e] [-StartDate \u003cDateTime\u003e] [-EndDate \u003cDateTime\u003e] [-ExcludeJobSteps] [-WithOutputFile] [-EnableException] [\u003cCommonParameters\u003e]\nGet-DbaAgentJobHistory [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cObject[]\u003e] [-ExcludeJob \u003cObject[]\u003e] [-StartDate \u003cDateTime\u003e] [-EndDate \u003cDateTime\u003e] [-ExcludeJobSteps] [-WithOutputFile] -JobCollection \u003cJob\u003e [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaAgentJobOutputFile",
        "Description":  "This function returns for one or more SQL Instances the output file value for each step of one or many agent job with the Job Names\nprovided dynamically. It will not return anything if there is no Output File",
        "Tags":  [
                     "Agent",
                     "Job"
                 ],
        "Synopsis":  "Returns the Output File for each step of one or many agent job with the Job Names provided dynamically if\nrequired for one or more SQL Instances",
        "Alias":  "",
        "Author":  "Rob Sewell (https://sqldbawithabeard.com) | Simone Bizzotto (@niphold)",
        "CommandName":  "Get-DbaAgentJobOutputFile",
        "Availability":  "Windows only",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentJobOutputFile -SqlInstance SERVERNAME -Job \u0027The Agent Job\u0027\nThis will return the configured paths to the output files for each of the job step of the The Agent Job Job\r\non the SERVERNAME instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentJobOutputFile -SqlInstance SERVERNAME\nThis will return the configured paths to the output files for each of the job step of all the Agent Jobs\r\non the SERVERNAME instance\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgentJobOutputFile -SqlInstance SERVERNAME,SERVERNAME2 -Job \u0027The Agent Job\u0027\nThis will return the configured paths to the output files for each of the job step of the The Agent Job Job\r\non the SERVERNAME instance and SERVERNAME2\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$Servers = \u0027SERVER\u0027,\u0027SERVER\\INSTANCE1\u0027\nGet-DbaAgentJobOutputFile -SqlInstance $Servers -Job \u0027The Agent Job\u0027 -OpenFile\nThis will return the configured paths to the output files for each of the job step of the The Agent Job Job\r\non the SERVER instance and the SERVER\\INSTANCE1 and open the files if they are available\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaAgentJobOutputFile -SqlInstance SERVERNAME  | Out-GridView\nThis will return the configured paths to the output files for each of the job step of all the Agent Jobs\r\non the SERVERNAME instance and Pipe them to Out-GridView\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e(Get-DbaAgentJobOutputFile -SqlInstance SERVERNAME | Out-GridView -PassThru).FileName | Invoke-Item\nThis will return the configured paths to the output files for each of the job step of all the Agent Jobs\r\non the SERVERNAME instance and Pipe them to Out-GridView and enable you to choose the output\r\nfile and open it\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaAgentJobOutputFile -SqlInstance SERVERNAME -Verbose\nThis will return the configured paths to the output files for each of the job step of all the Agent Jobs\r\non the SERVERNAME instance and also show the job steps without an output file",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue, ByPropertyName)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Credential object used to connect to the SQL Server as a different user be it Windows or SQL Server. Windows users are determined by the existence of a backslash, so if you are intending to use an \r\nalternative Windows connection instead of a SQL login, ensure it contains a backslash.",
                           "",
                           false,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "Job",
                           "The job(s) to process - this list is auto-populated from the server. If unspecified, all jobs will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeJob",
                           "The job(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaAgentJobOutputFile [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Job \u003cObject[]\u003e] [-ExcludeJob \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaAgentJobStep",
        "Description":  "The Get-DbaAgentJobStep returns connected SMO object for SQL Agent Job Step for each instance(s) of SQL Server.",
        "Tags":  [
                     "Job",
                     "Agent"
                 ],
        "Synopsis":  "Gets SQL Agent Job Step information for each instance(s) of SQL Server.",
        "Alias":  "",
        "Author":  "Klaas Vandenberghe (@PowerDbaKlaas), http://powerdba.eu",
        "CommandName":  "Get-DbaAgentJobStep",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaAgentJobStep",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentJobStep -SqlInstance localhost\nReturns all SQL Agent Job Steps on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentJobStep -SqlInstance localhost, sql2016\nReturns all SQL Agent Job Steps for the local and sql2016 SQL Server instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgentJobStep -SqlInstance localhost -Job BackupData, BackupDiff\nReturns all SQL Agent Job Steps for the jobs named BackupData and BackupDiff from the local SQL Server instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAgentJobStep -SqlInstance localhost -ExcludeJob BackupDiff\nReturns all SQL Agent Job Steps for the local SQL Server instances, except for the BackupDiff Job.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaAgentJobStep -SqlInstance localhost -ExcludeDisabledJobs\nReturns all SQL Agent Job Steps for the local SQL Server instances, excluding the disabled jobs.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$servers | Get-DbaAgentJobStep\nFind all of your Job Steps from SQL Server instances in the $servers collection",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Job",
                           "The job(s) to process - this list is auto-populated from the server. If unspecified, all jobs will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeJob",
                           "The job(s) to exclude - this list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDisabledJobs",
                           "Switch will exclude disabled jobs from the output.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaAgentJobStep [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cObject[]\u003e] [-ExcludeJob \u003cObject[]\u003e] [-ExcludeDisabledJobs] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaAgentLog",
        "Description":  "Gets the \"SQL Agent Error Log\" of an instance. Returns all 10 error logs by default.",
        "Tags":  "Logging",
        "Synopsis":  "Gets the \"SQL Agent Error Log\" of an instance",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaAgentLog",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaAgentLog",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentLog -SqlInstance sql01\\sharepoint\nReturns the entire error log for the SQL Agent on sql01\\sharepoint\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentLog -SqlInstance sql01\\sharepoint -LogNumber 3, 6\nReturns log numbers 3 and 6 for the SQL Agent on sql01\\sharepoint\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\"\nPS C:\\\u003e $servers | Get-DbaAgentLog -LogNumber 0\nReturns the most recent SQL Agent error logs for \"sql2014\",\"sql2016\" and \"sqlcluster\\sharepoint\"",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "LogNumber",
                           "An Int32 value that specifies the index number of the error log required. Error logs are listed 0 through 9 where 0 is the current error log and 9 is the oldest.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaAgentLog [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-LogNumber] \u003cInt32[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaAgentOperator",
        "Description":  "This function returns SQL Agent operators.",
        "Tags":  [
                     "Agent",
                     "Operator"
                 ],
        "Synopsis":  "Returns all SQL Agent operators on a SQL Server Agent.",
        "Alias":  "",
        "Author":  "Klaas Vandenberghe (@PowerDBAKlaas)",
        "CommandName":  "Get-DbaAgentOperator",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaAgentOperator",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentOperator -SqlInstance ServerA,ServerB\\instanceB\nReturns any SQL Agent operators on serverA and serverB\\instanceB\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027ServerA\u0027,\u0027ServerB\\instanceB\u0027 | Get-DbaAgentOperator\nReturns all SQL Agent operators  on serverA and serverB\\instanceB\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgentOperator -SqlInstance ServerA -Operator Dba1,Dba2\nReturns only the SQL Agent Operators Dba1 and Dba2 on ServerA.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAgentOperator -SqlInstance ServerA,ServerB -ExcludeOperator Dba3\nReturns all the SQL Agent operators on ServerA and ServerB, except the Dba3 operator.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Operator",
                           "The operator(s) to process - this list is auto-populated from the server. If unspecified, all operators will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeOperator",
                           "The operator(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaAgentOperator [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Operator \u003cObject[]\u003e] [-ExcludeOperator \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaAgentProxy",
        "Description":  "This function returns SQL Agent proxies.",
        "Tags":  [
                     "Agent",
                     "SMO"
                 ],
        "Synopsis":  "Returns all SQL Agent proxies on a SQL Server Agent.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaAgentProxy",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaAgentProxy",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentProxy -SqlInstance ServerA,ServerB\\instanceB\nReturns all SQL Agent proxies on serverA and serverB\\instanceB\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027serverA\u0027,\u0027serverB\\instanceB\u0027 | Get-DbaAgentProxy\nReturns all SQL Agent proxies  on serverA and serverB\\instanceB",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,Instance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Proxy",
                           "The proxy to process - this list is auto-populated from the server. If unspecified, all proxies will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaAgentProxy [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Proxy \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaAgentSchedule",
        "Description":  "This function returns SQL Agent Shared Schedules.",
        "Tags":  [
                     "Agent",
                     "Schedule"
                 ],
        "Synopsis":  "Returns all SQL Agent Shared Schedules on a SQL Server Agent.",
        "Alias":  "",
        "Author":  "Chris McKeown (@devopsfu), http://www.devopsfu.com",
        "CommandName":  "Get-DbaAgentSchedule",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaAgentSchedule",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentSchedule -SqlInstance localhost\nReturns all SQL Agent Shared Schedules on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentSchedule -SqlInstance localhost, sql2016\nReturns all SQL Agent Shared Schedules for the local and sql2016 SQL Server instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgentSchedule -SqlInstance sql2016 -Schedule \"Maintenance10min\",\"Maintenance60min\"\nReturns the \"Maintenance10min\" \u0026 \"Maintenance60min\" schedules from the sql2016 SQL Server instance",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,Instance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Schedule",
                           "Parameter to filter the schedules returned",
                           "Schedules",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaAgentSchedule [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-Schedule \u003cObject[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaAgentServer",
        "Description":  "The Get-DbaAgentServer returns connected SMO object for SQL Agent Server information for each instance(s) of SQL Server.",
        "Tags":  [
                     "Job",
                     "Agent"
                 ],
        "Synopsis":  "Gets SQL Agent Server information for each instance(s) of SQL Server.",
        "Alias":  "",
        "Author":  "Cláudio Silva (@claudioessilva), https://claudioessilva.eu",
        "CommandName":  "Get-DbaAgentServer",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaAgentServer",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentServer -SqlInstance localhost\nReturns SQL Agent Server on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentServer -SqlInstance localhost, sql2016\nReturns SQL Agent Servers for the localhost and sql2016 SQL Server instances",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaAgentServer [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaAgHadr",
        "Description":  "Gets the Hadr setting, from the service level, and returns true or false for the specified SQL Server instance.",
        "Tags":  [
                     "Hadr",
                     "HA",
                     "AG",
                     "AvailabilityGroup"
                 ],
        "Synopsis":  "Gets the Hadr service setting on the specified SQL Server instance.",
        "Alias":  "",
        "Author":  "Shawn Melton (@wsmelton), http://wsmelton.github.io",
        "CommandName":  "Get-DbaAgHadr",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaAgHadr",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgHadr -SqlInstance sql2016\nReturns a status of the Hadr setting for sql2016 SQL Server instance.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaAgHadr [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaAgListener",
        "Description":  "Returns availability group listeners.",
        "Tags":  [
                     "AG",
                     "HA",
                     "AvailabilityGroup",
                     "Listener"
                 ],
        "Synopsis":  "Returns availability group listeners.",
        "Alias":  "",
        "Author":  "Viorel Ciucu (@viorelciucu)",
        "CommandName":  "Get-DbaAgListener",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaAgListener",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgListener -SqlInstance sql2017a\nReturns all listeners found on sql2017a\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgListener -SqlInstance sql2017a -AvailabilityGroup AG-a\nReturns all listeners found on sql2017a on sql2017a for the availability group AG-a\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2017a -AvailabilityGroup OPP | Get-DbaAgListener\nReturns all listeners found on sql2017a on sql2017a for the availability group OPP",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityGroup",
                           "Specify the availability groups to query.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Listener",
                           "Return only specific listeners.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piped input from Get-DbaAvailabilityGroup.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaAgListener [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-Listener] \u003cString[]\u003e] [[-InputObject] \u003cAvailabilityGroup[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaAgReplica",
        "Description":  "Returns the availability group replica object found on the server.",
        "Tags":  [
                     "AG",
                     "HA",
                     "AvailabilityGroup",
                     "Replica"
                 ],
        "Synopsis":  "Returns the availability group replica object found on the server.",
        "Alias":  "",
        "Author":  "Shawn Melton (@wsmelton) | Chrissy LeMaire (@cl)",
        "CommandName":  "Get-DbaAgReplica",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaAgReplica",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgReplica -SqlInstance sql2017a\nReturns basic information on all the availability group replicas found on sql2017a\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgReplica -SqlInstance sql2017a -AvailabilityGroup SharePoint\nShows basic information on the replicas found on availability group SharePoint on sql2017a\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgReplica -SqlInstance sql2017a | Select-Object *\nReturns full object properties on all availability group replicas found on sql2017a",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityGroup",
                           "Specify the availability groups to query.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Replica",
                           "Return only specific replicas.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piped input from Get-DbaAvailabilityGroup.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaAgReplica [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-Replica] \u003cString[]\u003e] [[-InputObject] \u003cAvailabilityGroup[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaAvailabilityGroup",
        "Description":  "Returns availability group objects from a SQL Server instance.\n\nDefault view provides most common set of properties for information on the Availability Group(s).",
        "Tags":  [
                     "Hadr",
                     "HA",
                     "AG",
                     "AvailabilityGroup"
                 ],
        "Synopsis":  "Returns availability group objects from a SQL Server instance.",
        "Alias":  "",
        "Author":  "Shawn Melton (@wsmelton) | Chrissy LeMaire (@cl)",
        "CommandName":  "Get-DbaAvailabilityGroup",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaAvailabilityGroup",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sqlserver2014a\nReturns basic information on all the Availability Group(s) found on sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sqlserver2014a -AvailabilityGroup AG-a\nShows basic information on the Availability Group AG-a on sqlserver2014a.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sqlserver2014a | Select *\nReturns full object properties on all Availability Group(s) on sqlserver2014a.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sqlserver2014a | Select-Object -ExpandProperty PrimaryReplicaServerName\nReturns the SQL Server instancename of the primary replica as a string\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sqlserver2014a -AvailabilityGroup AG-a -IsPrimary\nReturns true/false if the server, sqlserver2014a, is the primary replica for AG-a Availability Group.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2012 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityGroup",
                           "Return only specific availability groups.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IsPrimary",
                           "If this switch is enabled, a boolean indicating whether SqlInstance is the Primary replica in the AG is returned.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaAvailabilityGroup [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [-IsPrimary] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaAvailableCollation",
        "Description":  "The Get-DbaAvailableCollation function returns the list of collations available on each SQL Server.\nOnly the connect permission is required to get this information.",
        "Tags":  [
                     "Collation",
                     "Configuration"
                 ],
        "Synopsis":  "Function to get available collations for a given SQL Server",
        "Alias":  "",
        "Author":  "Bryan Hamby (@galador)",
        "CommandName":  "Get-DbaAvailableCollation",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaAvailableCollation",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAvailableCollation -SqlInstance sql2016\nGets all the collations from server sql2016 using NT authentication",
        "Params":  [
                       [
                           "SqlInstance",
                           "TThe target SQL Server instance or instances. Only connect permission is required.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaAvailableCollation [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaBackupDevice",
        "Description":  "The Get-DbaBackupDevice command gets SQL Backup Device information for each instance(s) of SQL Server.",
        "Tags":  "Backup",
        "Synopsis":  "Gets SQL Backup Device information for each instance(s) of SQL Server.",
        "Alias":  "",
        "Author":  "Garry Bargsley (@gbargsley), http://blog.garrybargsley.com",
        "CommandName":  "Get-DbaBackupDevice",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaBackupDevice",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaBackupDevice -SqlInstance localhost\nReturns all Backup Devices on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaBackupDevice -SqlInstance localhost, sql2016\nReturns all Backup Devices for the local and sql2016 SQL Server instances",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaBackupDevice [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaBackupHistory",
        "Description":  "Returns backup history details for some or all databases on a SQL Server.\n\nYou can even get detailed information (including file path) for latest full, differential and log files.\n\nBackups taken with the CopyOnly option will NOT be returned, unless the IncludeCopyOnly switch is present\n\nReference: http://www.sqlhub.com/2011/07/find-your-backup-history-in-sql-server.html",
        "Tags":  [
                     "DisasterRecovery",
                     "Backup"
                 ],
        "Synopsis":  "Returns backup history details for databases on a SQL Server.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl) | Stuart Moore (@napalmgram)",
        "CommandName":  "Get-DbaBackupHistory",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaBackupHistory",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaBackupHistory -SqlInstance SqlInstance2014a\nReturns server name, database, username, backup type, date for all database backups still in msdb history on SqlInstance2014a. This may return many rows; consider using filters that are included in \r\nother examples.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nGet-DbaBackupHistory -SqlInstance SqlInstance2014a -SqlCredential $cred\nDoes the same as above but connect to SqlInstance2014a as SQL user \"sqladmin\"\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaBackupHistory -SqlInstance SqlInstance2014a -Database db1, db2 -Since \u00272016-07-01 10:47:00\u0027\nReturns backup information only for databases db1 and db2 on SqlInstance2014a since July 1, 2016 at 10:47 AM.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014, pubs -Force | Format-Table\nReturns information only for AdventureWorks2014 and pubs and formats the results as a table.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014 -Last\nReturns information about the most recent full, differential and log backups for AdventureWorks2014 on sql2014.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014 -Last -DeviceType Disk\nReturns information about the most recent full, differential and log backups for AdventureWorks2014 on sql2014, but only for backups to disk.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014 -Last -DeviceType 148,107\nReturns information about the most recent full, differential and log backups for AdventureWorks2014 on sql2014, but only for backups with device_type 148 and 107.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eGet-DbaBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014 -LastFull\nReturns information about the most recent full backup for AdventureWorks2014 on sql2014.\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eGet-DbaBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014 -Type Full\nReturns information about all Full backups for AdventureWorks2014 on sql2014.\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sql2016 | Get-DbaBackupHistory\nReturns database backup information for every database on every server listed in the Central Management Server on sql2016.\n-------------------------- EXAMPLE 11 --------------------------\nPS C:\\\u003eGet-DbaBackupHistory -SqlInstance SqlInstance2014a, sql2016 -Force\nReturns detailed backup history for all databases on SqlInstance2014a and sql2016.\n-------------------------- EXAMPLE 12 --------------------------\nPS C:\\\u003eGet-DbaBackupHistory -SqlInstance sql2016 -Database db1 -RecoveryFork 38e5e84a-3557-4643-a5d5-eed607bef9c6 -Last\nIf db1 has multiple recovery forks, specifying the RecoveryFork GUID will restrict the search to that fork.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Credential object used to connect to the SQL Server Instance as a different user. This can be a Windows or SQL Server account. Windows users are determined by the existence of a backslash, so if you \r\nare intending to use an alternative Windows connection instead of a SQL login, ensure it contains a backslash.",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies one or more database(s) to process. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies one or more database(s) to exclude from processing.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IncludeCopyOnly",
                           "By default Get-DbaBackupHistory will ignore backups taken with the CopyOnly option. This switch will include them",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "If this switch is enabled, a large amount of information is returned, similar to what SQL Server itself returns.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Since",
                           "Specifies a DateTime object to use as the starting point for the search for backups.",
                           "",
                           false,
                           "false",
                           "(Get-Date \u002701/01/1970\u0027)"
                       ],
                       [
                           "RecoveryFork",
                           "Specifies the Recovery Fork you want backup history for",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Last",
                           "If this switch is enabled, the most recent full chain of full, diff and log backup sets is returned.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "LastFull",
                           "If this switch is enabled, the most recent full backup set is returned.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "LastDiff",
                           "If this switch is enabled, the most recent differential backup set is returned.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "LastLog",
                           "If this switch is enabled, the most recent log backup is returned.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DeviceType",
                           "Specifies a filter for backup sets based on DeviceTypes. Valid options are \u0027Disk\u0027,\u0027Permanent Disk Device\u0027, \u0027Tape\u0027, \u0027Permanent Tape Device\u0027,\u0027Pipe\u0027,\u0027Permanent Pipe Device\u0027,\u0027Virtual Device\u0027, in addition \r\nto custom integers for your own DeviceTypes.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Raw",
                           "If this switch is enabled, one object per backup file is returned. Otherwise, media sets (striped backups across multiple files) will be grouped into a single return object.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "LastLsn",
                           "Specifies a minimum LSN to use in filtering backup history. Only backups with an LSN greater than this value will be returned, which helps speed the retrieval process.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Type",
                           "Specifies one or more types of backups to return. Valid options are \u0027Full\u0027, \u0027Log\u0027, \u0027Differential\u0027, \u0027File\u0027, \u0027Differential File\u0027, \u0027Partial Full\u0027, and \u0027Partial Differential\u0027. Otherwise, all types of \r\nbackups will be returned unless one of the -Last* switches is enabled.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaBackupHistory -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-IncludeCopyOnly] [-Since \u003cDateTime\u003e] [-RecoveryFork \u003cString\u003e] [-DeviceType \u003cString[]\u003e] [-Raw] [-LastLsn \u003cBigInteger\u003e] [-Type \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]\nGet-DbaBackupHistory -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-IncludeCopyOnly] [-Force] [-Since \u003cDateTime\u003e] [-RecoveryFork \u003cString\u003e] [-DeviceType \u003cString[]\u003e] [-Raw] [-LastLsn \u003cBigInteger\u003e] [-Type \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]\nGet-DbaBackupHistory -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-IncludeCopyOnly] [-Since \u003cDateTime\u003e] [-RecoveryFork \u003cString\u003e] [-Last] [-LastFull] [-LastDiff] [-LastLog] [-DeviceType \u003cString[]\u003e] [-Raw] [-LastLsn \u003cBigInteger\u003e] [-Type \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaBackupInformation",
        "Description":  "Upon being passed a list of potential backups files this command will scan the files, select those that contain SQL Server\nbackup sets. It will then filter those files down to a set\n\nThe function defaults to working on a remote instance. This means that all paths passed in must be relative to the remote instance.\nXpDirTree will be used to perform the file scans\n\nVarious means can be used to pass in a list of files to be considered. The default is to non recursively scan the folder\npassed in.",
        "Tags":  [
                     "DisasterRecovery",
                     "Backup",
                     "Restore"
                 ],
        "Synopsis":  "Scan backup files and creates a set, compatible with Restore-DbaDatabase",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl) | Stuart Moore (@napalmgram)",
        "CommandName":  "Get-DbaBackupInformation",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaBackupInformation",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaBackupInformation -SqlInstance Server1 -Path c:\\backups\\ -DirectoryRecurse\nWill use the Server1 instance to recursively read all backup files under c:\\backups, and return a dbatools BackupHistory object\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaBackupInformation -SqlInstance Server1 -Path c:\\backups\\ -DirectoryRecurse -ExportPath c:\\store\\BackupHistory.xml\nPS C:\\\u003e robocopy c:\\store\\ \\\\remoteMachine\\C$\\store\\ BackupHistory.xml\r\nPS C:\\\u003e Get-DbaBackupInformation -Import -Path  c:\\store\\BackupHistory.xml | Restore-DbaDatabase -SqlInstance Server2 -TrustDbBackupHistory\nThis example creates backup history output from server1 and copies the file to the remote machine in order to preserve backup history. It is then used to restore the databases onto server2.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaBackupInformation -SqlInstance Server1 -Path c:\\backups\\ -DirectoryRecurse -ExportPath C:\\store\\BackupHistory.xml -PassThru | Restore-DbaDatabase -SqlInstance Server2 \r\n-TrustDbBackupHistory\nIn this example we gather backup information, export it to an xml file, and then pass it on through to Restore-DbaDatabase.\r\nThis allows us to repeat the restore without having to scan all the backup files again\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-ChildItem c:\\backups\\ -recurse -files | Where-Object {$_.extension -in (\u0027.bak\u0027,\u0027.trn\u0027) -and $_.LastWriteTime -gt (get-date).AddMonths(-1)} | Get-DbaBackupInformation -SqlInstance Server1 \r\n-ExportPath C:\\backupHistory.xml\nThis lets you keep a record of all backup history from the last month on hand to speed up refreshes\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\\\network\\backups\nPS C:\\\u003e $Backups += Get-DbaBackupInformation -SqlInstance Server2 -NoXpDirTree -Path c:\\backups\nScan the unc folder \\\\network\\backups with Server1, and then scan the C:\\backups folder on\r\nServer2 not using xp_dirtree, adding the results to the first set.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\\\network\\backups -MaintenanceSolution\nWhen MaintenanceSolution is indicated we know we are dealing with the output from Ola Hallengren backup scripts. So we make sure that a FULL folder exists in the first level of Path, if not we \r\nshortcut scanning all the files as we have nothing to work with\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\\\network\\backups -MaintenanceSolution -IgnoreLogBackup\nAs we know we are dealing with an Ola Hallengren style backup folder from the MaintenanceSolution switch, when IgnoreLogBackup is also included we can ignore the LOG folder to skip any scanning of \r\nlog backups. Note this also means they WON\u0027T be restored",
        "Params":  [
                       [
                           "Path",
                           "Path to SQL Server backup files.\nPaths passed in as strings will be scanned using the desired method, default is a non recursive folder scan\r\nAccepts multiple paths separated by \u0027,\u0027\nOr it can consist of FileInfo objects, such as the output of Get-ChildItem or Get-Item. This allows you to work with\r\nyour own file structures as needed",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlInstance",
                           "The SQL Server instance to be used to read the headers of the backup files",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DatabaseName",
                           "An array of Database Names to filter by. If empty all databases are returned.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SourceInstance",
                           "If provided only backup originating from this destination will be returned. This SQL instance will not be connected to or involved in this work",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NoXpDirTree",
                           "If this switch is set, then Files will be parsed as locally files. This can cause failures if the running user can see files that the parsing SQL Instance cannot",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DirectoryRecurse",
                           "If specified the provided path/directory will be traversed (only applies if not using XpDirTree)",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "Replaces user friendly yellow warnings with bloody red exceptions of doom!\r\nUse this if you want the function to throw terminating errors you want to catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "MaintenanceSolution",
                           "This switch tells the function that the folder is the root of a Ola Hallengren backup folder",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IgnoreLogBackup",
                           "This switch only works with the MaintenanceSolution switch. With an Ola Hallengren style backup we can be sure that the LOG folder contains only log backups and skip it.\r\nFor all other scenarios we need to read the file headers to be sure.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ExportPath",
                           "If specified the output will export via CliXml format to the specified file. This allows you to store the backup history object for later usage, or move it between computers",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AzureCredential",
                           "The name of the SQL Server credential to be used if restoring from an Azure hosted backup",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Import",
                           "When specified along with a path the command will import a previously exported BackupHistory object from an xml file.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Anonymise",
                           "If specified we will output the results with ComputerName, InstanceName, Database, UserName, Paths, and Logical and Physical Names hashed out\r\nThis options is mainly for use if we need you to submit details for fault finding to the dbatools team",
                           "Anonymize",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NoClobber",
                           "If specified will stop Export from overwriting an existing file, the default is to overwrite",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "PassThru",
                           "When data is exported the cmdlet will return no other output, this switch means it will also return the normal output which can be then piped into another command",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaBackupInformation -Path \u003cObject[]\u003e -SqlInstance \u003cDbaInstanceParameter\u003e [-SqlCredential \u003cPSCredential\u003e] [-DatabaseName \u003cString[]\u003e] [-SourceInstance \u003cString[]\u003e] [-NoXpDirTree] [-DirectoryRecurse] [-EnableException] [-MaintenanceSolution] [-IgnoreLogBackup] [-ExportPath \u003cString\u003e] [-AzureCredential \u003cString\u003e] [-Anonymise] [-NoClobber] [-PassThru] [\u003cCommonParameters\u003e]\nGet-DbaBackupInformation -Path \u003cObject[]\u003e [-DatabaseName \u003cString[]\u003e] [-SourceInstance \u003cString[]\u003e] [-EnableException] [-MaintenanceSolution] [-IgnoreLogBackup] [-ExportPath \u003cString\u003e] [-AzureCredential \u003cString\u003e] [-Import] [-Anonymise] [-NoClobber] [-PassThru] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaBuildReference",
        "Description":  "Returns info about the specific build of a SQL instance, including the SP, the CU and the reference KB, wherever possible.\nIt also includes End Of Support dates as specified on Microsoft Life Cycle Policy",
        "Tags":  "SqlBuild",
        "Synopsis":  "Returns SQL Server Build infos on a SQL instance",
        "Alias":  "Get-DbaSqlBuildReference",
        "Author":  "Simone Bizzotto (@niphold) | Friedrich Weinmann (@FredWeinmann)",
        "CommandName":  "Get-DbaBuildReference",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaBuildReference",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaBuildReference -Build \"12.00.4502\"\nReturns information about a build identified by  \"12.00.4502\" (which is SQL 2014 with SP1 and CU11)\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaBuildReference -Build \"12.00.4502\" -Update\nReturns information about a build trying to fetch the most up to date index online. When the online version is newer, the local one gets overwritten\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaBuildReference -Build \"12.0.4502\",\"10.50.4260\"\nReturns information builds identified by these versions strings\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sqlserver2014a | Get-DbaBuildReference\nIntegrate with other cmdlets to have builds checked for all your registered servers on sqlserver2014a",
        "Params":  [
                       [
                           "Build",
                           "Instead of connecting to a real instance, pass a string identifying the build to get the info back.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Kb",
                           "Get a KB information based on its number. Supported format: KBXXXXXX, or simply XXXXXX.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "MajorVersion",
                           "Get a KB information based on SQL Server version. Can be refined further by -ServicePack and -CumulativeUpdate parameters.\r\nExamples: SQL2008 | 2008R2 | 2016",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ServicePack",
                           "Get a KB information based on SQL Server Service Pack version. Can be refined further by -CumulativeUpdate parameter.\r\nExamples: SP0 | 2 | RTM",
                           "SP",
                           false,
                           "false",
                           "RTM"
                       ],
                       [
                           "CumulativeUpdate",
                           "Get a KB information based on SQL Server Cumulative Update version.\r\n Examples: CU0 | CU13 | CU0",
                           "CU",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlInstance",
                           "Target any number of instances, in order to return their build state.",
                           "ServerInstance,SqlServer",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "When connecting to an instance, use the credentials specified.",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Update",
                           "Looks online for the most up to date reference, replacing the local one.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaBuildReference [[-Build] \u003cVersion[]\u003e] [[-Kb] \u003cString[]\u003e] [[-MajorVersion] \u003cString\u003e] [[-ServicePack] \u003cString\u003e] [[-CumulativeUpdate] \u003cString\u003e] [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-Update] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaClientAlias",
        "Description":  "Gets SQL Server alias by reading HKLM:\\SOFTWARE\\Microsoft\\MSSQLServer\\Client",
        "Tags":  "Alias",
        "Synopsis":  "Gets any SQL Server alias for the specified server(s)",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaClientAlias",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaClientAlias",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaClientAlias\nGets all SQL Server client aliases on the local computer\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaClientAlias -ComputerName workstationx\nGets all SQL Server client aliases on Workstationx\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaClientAlias -ComputerName workstationx -Credential ad\\sqldba\nLogs into workstationx as ad\\sqldba then retrieves all SQL Server client aliases on Workstationx\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027Server1\u0027, \u0027Server2\u0027 | Get-DbaClientAlias\nGets all SQL Server client aliases on Server1 and Server2",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer where the alias has been created",
                           "",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to remote computers using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaClientAlias [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaClientProtocol",
        "Description":  "Gets the SQL Server related client protocols on one or more computers.\n\nRequires Local Admin rights on destination computer(s).\nThe client protocols can be enabled and disabled when retrieved via WSMan.",
        "Tags":  "Protocol",
        "Synopsis":  "Gets the SQL Server related client protocols on a computer.",
        "Alias":  "",
        "Author":  "Klaas Vandenberghe (@PowerDBAKlaas)",
        "CommandName":  "Get-DbaClientProtocol",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaClientProtocol",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaClientProtocol -ComputerName sqlserver2014a\nGets the SQL Server related client protocols on computer sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\u0027,\u0027sql3\u0027 | Get-DbaClientProtocol\nGets the SQL Server related client protocols on computers sql1, sql2 and sql3.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaClientProtocol -ComputerName sql1,sql2 | Out-GridView\nGets the SQL Server related client protocols on computers sql1 and sql2, and shows them in a grid view.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e(Get-DbaClientProtocol -ComputerName sql2 | Where { $_.DisplayName = \u0027via\u0027 }).Disable()\nDisables the VIA ClientNetworkProtocol on computer sql2.\r\nIf successful, return code 0 is shown.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target SQL Server instance or instances.",
                           "cn,host,Server",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Credential object used to connect to the computer as a different user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaClientProtocol [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaCmConnection",
        "Description":  "Retrieves windows management connections from the cache",
        "Tags":  [
                     "ComputerManagement",
                     "CIM"
                 ],
        "Synopsis":  "Retrieves windows management connections from the cache",
        "Alias":  "",
        "Author":  "Friedrich Weinmann (@FredWeinmann)",
        "CommandName":  "Get-DbaCmConnection",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaCmConnection",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaCmConnection\nList all cached connections.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCmConnection sql2014\nList the cached connection - if any - to the server sql2014.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaCmConnection -UserName \"*charles*\"\nList all cached connection that use a username containing \"charles\" as default or override credentials.",
        "Params":  [
                       [
                           "ComputerName",
                           "The computername to ComputerName for.",
                           "Filter",
                           false,
                           "true (ByValue)",
                           "*"
                       ],
                       [
                           "UserName",
                           "Username on credentials to look for. Will not find connections using the default windows credentials.",
                           "",
                           false,
                           "false",
                           "*"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaCmConnection [[-ComputerName] \u003cString[]\u003e] [-UserName \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaCmObject",
        "Description":  "This function centralizes all requests for information retrieved from Get-WmiObject or Get-CimInstance.\nIt uses different protocols as available in this order:\n- Cim over WinRM\n- Cim over DCOM\n- Wmi\n- Wmi over PowerShell Remoting\nIt remembers channels that didn\u0027t work and will henceforth avoid them. It remembers invalid credentials and will avoid reusing them.\nMuch of its behavior can be configured using Test-DbaCmConnection.",
        "Tags":  [
                     "ComputerManagement",
                     "CIM"
                 ],
        "Synopsis":  "Retrieves Wmi/Cim-Style information from computers.",
        "Alias":  "",
        "Author":  "Friedrich Weinmann (@FredWeinmann)",
        "CommandName":  "Get-DbaCmObject",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaCmObject",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaCmObject win32_OperatingSystem\nRetrieves the common operating system information from the local computer.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCmObject -Computername \"sql2014\" -ClassName Win32_OperatingSystem -Credential $cred -DoNotUse CimRM\nRetrieves the common operating system information from the server sql2014.\r\nIt will use the Credentials stored in $cred to connect, unless they are known to not work, in which case they will default to windows credentials (unless another default has been set).",
        "Params":  [
                       [
                           "ClassName",
                           "The name of the class to retrieve.",
                           "Class",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Query",
                           "The Wmi/Cim query tu run against the server.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "ComputerName",
                           "The computer(s) to connect to. Defaults to localhost.",
                           "",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Credentials to use. Invalid credentials will be stored in a credentials cache and not be reused.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Namespace",
                           "The namespace of the class to use.",
                           "",
                           false,
                           "false",
                           "root\\cimv2"
                       ],
                       [
                           "DoNotUse",
                           "Connection Protocols that should not be used.",
                           "",
                           false,
                           "false",
                           "None"
                       ],
                       [
                           "Force",
                           "Overrides some checks that might otherwise halt execution as a precaution\r\n- Ignores timeout on bad connections",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "SilentlyContinue",
                           "Use in conjunction with the -EnableException switch.\r\nBy default, Get-DbaCmObject will throw a terminating exception when connecting to a target is impossible in exception enabled mode.\r\nSetting this switch will cause it write a non-terminating exception and continue with the next computer.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaCmObject [-ClassName] \u003cString\u003e [-ComputerName \u003cDbaCmConnectionParameter[]\u003e] [-Credential \u003cPSCredential\u003e] [-Namespace \u003cString\u003e] [-DoNotUse {None | CimRM | CimDCOM | Wmi | PowerShellRemoting}] [-Force] [-SilentlyContinue] [-EnableException] [\u003cCommonParameters\u003e]\nGet-DbaCmObject [-Query] \u003cString\u003e [-ComputerName \u003cDbaCmConnectionParameter[]\u003e] [-Credential \u003cPSCredential\u003e] [-Namespace \u003cString\u003e] [-DoNotUse {None | CimRM | CimDCOM | Wmi | PowerShellRemoting}] [-Force] [-SilentlyContinue] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaCmsRegServer",
        "Description":  "Returns an array of servers found in the CMS.",
        "Tags":  [
                     "RegisteredServer",
                     "CMS"
                 ],
        "Synopsis":  "Gets list of SQL Server objects stored in SQL Server Central Management Server (CMS).",
        "Alias":  "Get-DbaCmsRegServerName,Get-DbaRegisteredServer,Get-SqlRegisteredServerName",
        "Author":  "Bryan Hamby (@galador)",
        "CommandName":  "Get-DbaCmsRegServer",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaCmsRegServer",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sqlserver2014a\nGets a list of servers from the CMS on sqlserver2014a, using Windows Credentials.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sqlserver2014a -IncludeSelf\nGets a list of servers from the CMS on sqlserver2014a and includes sqlserver2014a in the output results.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sqlserver2014a -SqlCredential $credential | Select-Object -Unique -ExpandProperty ServerName\nReturns only the server names from the CMS on sqlserver2014a, using SQL Authentication to authenticate to the server.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sqlserver2014a -Group HR, Accounting\nGets a list of servers in the HR and Accounting groups from the CMS on sqlserver2014a.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sqlserver2014a -Group HR\\Development\nReturns a list of servers in the HR and sub-group Development from the CMS on sqlserver2014a.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "Specifies one or more names to include. Name is the visible name in SSMS CMS interface (labeled Registered Server Name)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ServerName",
                           "Specifies one or more server names to include. Server Name is the actual instance name (labeled Server Name)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Group",
                           "Specifies one or more groups to include from SQL Server Central Management Server.",
                           "Groups",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeGroup",
                           "Specifies one or more Central Management Server groups to exclude.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Id",
                           "Get server by Id(s)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IncludeSelf",
                           "If this switch is enabled, the CMS server itself will be included in the results, along with all other Registered Servers.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ExcludeCmsServer",
                           "Deprecated, now follows the Microsoft convention of not including it by default. If you\u0027d like to include the CMS Server, use -IncludeSelf",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ResolveNetworkName",
                           "If this switch is enabled, the NetBIOS name and IP address(es) of each server will be returned.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaCmsRegServer [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString[]\u003e] [[-ServerName] \u003cString[]\u003e] [[-Group] \u003cObject[]\u003e] [[-ExcludeGroup] \u003cObject[]\u003e] [[-Id] \u003cInt32[]\u003e] [-IncludeSelf] [-ExcludeCmsServer] [-ResolveNetworkName] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaCmsRegServerGroup",
        "Description":  "Returns an array of Server Groups found in the CMS.",
        "Tags":  [
                     "RegisteredServer",
                     "CMS"
                 ],
        "Synopsis":  "Gets list of Server Groups objects stored in SQL Server Central Management Server (CMS).",
        "Alias":  "Get-DbaRegisteredServerGroup",
        "Author":  "Tony Wilhelm (@tonywsql)",
        "CommandName":  "Get-DbaCmsRegServerGroup",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaCmsRegServerGroup",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServerGroup -SqlInstance sqlserver2014a\nGets the top level groups from the CMS on sqlserver2014a, using Windows Credentials.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServerGroup -SqlInstance sqlserver2014a -SqlCredential $credential\nGets the top level groups from the CMS on sqlserver2014a, using alternative credentials to authenticate to the server.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServerGroup -SqlInstance sqlserver2014a -Group HR, Accounting\nGets the HR and Accounting groups from the CMS on sqlserver2014a.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServerGroup -SqlInstance sqlserver2014a -Group HR\\Development\nReturns the sub-group Development of the HR group from the CMS on sqlserver2014a.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Group",
                           "Specifies one or more groups to include from SQL Server Central Management Server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeGroup",
                           "Specifies one or more Central Management Server groups to exclude.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Id",
                           "Get group by Id(s). This parameter only works if the group has a registered server in it.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaCmsRegServerGroup [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Group] \u003cObject[]\u003e] [[-ExcludeGroup] \u003cObject[]\u003e] [[-Id] \u003cInt32[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaCmsRegServerStore",
        "Description":  "Returns a SQL Server Registered Server Store object - useful for working with Central Management Store",
        "Tags":  [
                     "RegisteredServer",
                     "CMS"
                 ],
        "Synopsis":  "Returns a SQL Server Registered Server Store Object",
        "Alias":  "Get-DbaRegisteredServerStore",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaCmsRegServerStore",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaCmsRegServerStore",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServerStore -SqlInstance sqlserver2014a\nReturns a SQL Server Registered Server Store Object from sqlserver2014a\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServerStore -SqlInstance sqlserver2014a -SqlCredential sqladmin\nReturns a SQL Server Registered Server Store Object from sqlserver2014a  by logging in with the sqladmin login",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaCmsRegServerStore [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaComputerCertificate",
        "Description":  "Gets computer certificates on localhost that are candidates for using with SQL Server\u0027s network encryption",
        "Tags":  "Certificate",
        "Synopsis":  "Simplifies finding computer certificates that are candidates for using with SQL Server\u0027s network encryption",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaComputerCertificate",
        "Availability":  "Windows only",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaComputerCertificate\nGets computer certificates on localhost that are candidates for using with SQL Server\u0027s network encryption\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaComputerCertificate -ComputerName sql2016\nGets computer certificates on sql2016 that are candidates for using with SQL Server\u0027s network encryption\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaComputerCertificate -ComputerName sql2016 -Thumbprint 8123472E32AB412ED4288888B83811DB8F504DED, 04BFF8B3679BB01A986E097868D8D494D70A46D6\nGets computer certificates on sql2016 that match thumbprints 8123472E32AB412ED4288888B83811DB8F504DED or 04BFF8B3679BB01A986E097868D8D494D70A46D6",
        "Params":  [
                       [
                           "ComputerName",
                           "The target SQL Server instance or instances. Defaults to localhost. If target is a cluster, you must specify the distinct nodes.",
                           "ServerInstance,SqlServer,SqlInstance",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to $ComputerName using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Store",
                           "Certificate store - defaults to LocalMachine",
                           "",
                           false,
                           "false",
                           "LocalMachine"
                       ],
                       [
                           "Folder",
                           "Certificate folder - defaults to My (Personal)",
                           "",
                           false,
                           "false",
                           "My"
                       ],
                       [
                           "Path",
                           "The path to a certificate - basically changes the path into a certificate object",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Thumbprint",
                           "Return certificate based on thumbprint",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaComputerCertificate [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Store] \u003cString\u003e] [[-Folder] \u003cString\u003e] [[-Path] \u003cString\u003e] [[-Thumbprint] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaComputerSystem",
        "Description":  "Gets computer system information from the server and returns as an object.",
        "Tags":  "ServerInfo",
        "Synopsis":  "Gets computer system information from the server.",
        "Alias":  "",
        "Author":  "Shawn Melton (@wsmelton), https://wsmelton.github.io",
        "CommandName":  "Get-DbaComputerSystem",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaComputerSystem",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaComputerSystem\nReturns information about the local computer\u0027s computer system\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaComputerSystem -ComputerName sql2016\nReturns information about the sql2016\u0027s computer system\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaComputerSystem -ComputerName sql2016 -IncludeAws\nReturns information about the sql2016\u0027s computer system and includes additional properties around the EC2 instance.",
        "Params":  [
                       [
                           "ComputerName",
                           "Target computer(s). If no computer name is specified, the local computer is targeted",
                           "cn,host,Server",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Alternate credential object to use for accessing the target computer(s).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IncludeAws",
                           "If computer is hosted in AWS Infrastructure as a Service (IaaS), additional information will be included.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaComputerSystem [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-IncludeAws] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaConnection",
        "Description":  "Returns a bunch of information from dm_exec_connections which, according to Microsoft:\n\"Returns information about the connections established to this instance of SQL Server and the details of each connection. Returns server wide connection information for SQL Server. Returns current database connection information for SQL Database.\"",
        "Tags":  "Connection",
        "Synopsis":  "Returns a bunch of information from dm_exec_connections.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaConnection",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaConnection",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaConnection -SqlInstance sql2016, sql2017\nReturns client connection information from sql2016 and sql2017",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server(s) must be SQL Server 2005 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential,Cred",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaConnection [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaCpuRingBuffer",
        "Description":  "This command is based off of Glen Berry\u0027s diagnostic query for average CPU\n\nThe sys.dm_os_ring_buffers stores the average CPU utilization history\nby the current instance of SQL Server, plus the summed average CPU utilization\nby all other processes on your machine are captured in one minute increments\nfor the past 256 minutes.\n\nReference: https://www.sqlskills.com/blogs/glenn/sql-server-diagnostic-information-queries-detailed-day-16//",
        "Tags":  "CPU",
        "Synopsis":  "Collects CPU data from sys.dm_os_ring_buffers.  Works on SQL Server 2005 and above.",
        "Alias":  "",
        "Author":  "Patrick Flynn (@sqllensman)",
        "CommandName":  "Get-DbaCpuRingBuffer",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaCpuRingBuffer",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaCpuRingBuffer -SqlInstance sql2008, sqlserver2012\nGets CPU Statistics from sys.dm_os_ring_buffers for servers sql2008 and sqlserver2012 for last 60 minutes.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCpuRingBuffer -SqlInstance sql2008 -CollectionMinutes 240\nGets CPU Statistics from sys.dm_os_ring_buffers for server sql2008 for last 240 minutes\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$output = Get-DbaCpuRingBuffer -SqlInstance sql2008 -CollectionMinutes 240 | Select * | ConvertTo-DbaDataTable\nGets CPU Statistics from sys.dm_os_ring_buffers for server sql2008 for last 240 minutes into a Data Table.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027sql2008\u0027,\u0027sql2012\u0027 | Get-DbaCpuRingBuffer\nGets CPU Statistics from sys.dm_os_ring_buffers for servers sql2008 and sqlserver2012\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaCpuRingBuffer -SqlInstance sql2008 -SqlCredential $cred\nConnects using sqladmin credential and returns CPU Statistics from sys.dm_os_ring_buffers from sql2008",
        "Params":  [
                       [
                           "SqlInstance",
                           "Allows you to specify a comma separated list of servers to query.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted. To use:\r\n$cred = Get-Credential, this pass this $cred to the param.\nWindows Authentication will be used if DestinationSqlCredential is not specified. To connect as a different Windows user, run PowerShell as that user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CollectionMinutes",
                           "Allows you to specify a Collection Period in Minutes. Default is 60 minutes",
                           "",
                           false,
                           "false",
                           "60"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaCpuRingBuffer [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-CollectionMinutes] \u003cInt32\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaCpuUsage",
        "Description":  "\"If there are a lot of processes running on your instance and the CPU is very high,\nthen it\u0027s hard to find the exact process eating up your CPU using just the SQL Server\ntools. One way to correlate the data between what is running within SQL Server and at\nthe Windows level is to use SPID and KPID values to get the exact process.\"\n\nThis command automates that process.\n\nReferences: https://www.mssqltips.com/sqlservertip/2454/how-to-find-out-how-much-cpu-a-sql-server-process-is-really-using/\n\nNote: This command returns results from all SQL instances on the destination server but the process\ncolumn is specific to -SqlInstance passed.",
        "Tags":  "CPU",
        "Synopsis":  "Provides detailed CPU usage information about a SQL Server\u0027s process",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaCpuUsage",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaCpuUsage",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaCpuUsage -SqlInstance sql2017\nLogs into the SQL Server instance \"sql2017\" and also the Computer itself (via WMI) to gather information\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$usage = Get-DbaCpuUsage -SqlInstance sql2017\nPS C:\\\u003e $usage.Process\nExplores the processes (from Get-DbaProcess) associated with the usage results\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaCpuUsage -SqlInstance sql2017 -SqlCredential sqladmin -Credential ad\\sqldba\nLogs into the SQL instance using the SQL Login \u0027sqladmin\u0027 and then Windows instance as \u0027ad\\sqldba\u0027",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to the SQL instance using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Credential",
                           "Allows you to login to the Windows Server using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Threshold",
                           "CPU threshold.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaCpuUsage [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Threshold] \u003cInt32\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaCredential",
        "Description":  "The Get-DbaCredential command gets SQL Credential information for each instance(s) of SQL Server.",
        "Tags":  "Credential",
        "Synopsis":  "Gets SQL Credential information for each instance(s) of SQL Server.",
        "Alias":  "",
        "Author":  "Garry Bargsley (@gbargsley), http://blog.garrybargsley.com",
        "CommandName":  "Get-DbaCredential",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaCredential",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaCredential -SqlInstance localhost\nReturns all SQL Credentials on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCredential -SqlInstance localhost, sql2016 -Name \u0027PowerShell Proxy\u0027\nReturns the SQL Credentials named \u0027PowerShell Proxy\u0027 for the local and sql2016 SQL Server instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaCredential -SqlInstance localhost, sql2016 -Identity ad\\powershell\nReturns the SQL Credentials for the account \u0027ad\\powershell\u0027 on the local and sql2016 SQL Server instances",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "Only include specific names\r\nNote: if spaces exist in the credential name, you will have to type \"\" or \u0027\u0027 around it.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeName",
                           "Excluded credential names",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Identity",
                           "Only include specific identities\r\nNote: if spaces exist in the credential identity, you will have to type \"\" or \u0027\u0027 around it.",
                           "CredentialIdentity",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeIdentity",
                           "Excluded identities",
                           "ExcludeCredentialIdentity",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaCredential [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Name \u003cString[]\u003e] [-ExcludeName \u003cString[]\u003e] [-Identity \u003cString[]\u003e] [-ExcludeIdentity \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaCustomError",
        "Description":  "The Get-DbaCustomError command gets SQL Custom Error Message information for each instance(s) of SQL Server.",
        "Tags":  [
                     "Error",
                     "CustomError"
                 ],
        "Synopsis":  "Gets SQL Custom Error Message information for each instance(s) of SQL Server.",
        "Alias":  "",
        "Author":  "Garry Bargsley (@gbargsley), http://blog.garrybargsley.com",
        "CommandName":  "Get-DbaCustomError",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaCustomError",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaCustomError -SqlInstance localhost\nReturns all Custom Error Message(s) on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCustomError -SqlInstance localhost, sql2016\nReturns all Custom Error Message(s) for the local and sql2016 SQL Server instances",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaCustomError [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDatabase",
        "Description":  "The Get-DbaDatabase command gets SQL database information for each database that is present on the target instance(s) of\nSQL Server. If the name of the database is provided, the command will return only the specific database information.",
        "Tags":  "Database",
        "Synopsis":  "Gets SQL Database information for each database that is present on the target instance(s) of SQL Server.",
        "Alias":  "",
        "Author":  "Garry Bargsley (@gbargsley), http://blog.garrybargsley.com | Klaas Vandenberghe (@PowerDbaKlaas) | Simone Bizzotto ( @niphlod )",
        "CommandName":  "Get-DbaDatabase",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDatabase",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance localhost\nReturns all databases on the local default SQL Server instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance localhost -ExcludeUser\nReturns only the system databases on the local default SQL Server instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance localhost -ExcludeSystem\nReturns only the user databases on the local default SQL Server instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027localhost\u0027,\u0027sql2016\u0027 | Get-DbaDatabase\nReturns databases on multiple instances piped into the function.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance SQL1\\SQLExpress -RecoveryModel full,Simple\nReturns only the user databases in Full or Simple recovery model from SQL Server instance SQL1\\SQLExpress.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance SQL1\\SQLExpress -Status Normal\nReturns only the user databases with status \u0027normal\u0027 from SQL Server instance SQL1\\SQLExpress.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance SQL1\\SQLExpress -IncludeLastUsed\nReturns the databases from SQL Server instance SQL1\\SQLExpress and includes the last used information\r\nfrom the sys.dm_db_index_usage_stats DMV.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance SQL1\\SQLExpress,SQL2 -ExcludeDatabase model,master\nReturns all databases except master and model from SQL Server instances SQL1\\SQLExpress and SQL2.\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance SQL1\\SQLExpress,SQL2 -Encrypted\nReturns only databases using TDE from SQL Server instances SQL1\\SQLExpress and SQL2.\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance SQL1\\SQLExpress,SQL2 -Access ReadOnly\nReturns only read only databases from SQL Server instances SQL1\\SQLExpress and SQL2.\n-------------------------- EXAMPLE 11 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance SQL2,SQL3 -Database OneDB,OtherDB\nReturns databases \u0027OneDb\u0027 and \u0027OtherDB\u0027 from SQL Server instances SQL2 and SQL3 if databases by those names exist on those instances.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Defaults to localhost.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies one or more database(s) to process. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies one or more database(s) to exclude from processing.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeUser",
                           "If this switch is enabled, only databases which are not User databases will be processed.\nThis parameter cannot be used with -ExcludeSystem.",
                           "SystemDbOnly,NoUserDb,ExcludeAllUserDb",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ExcludeSystem",
                           "If this switch is enabled, only databases which are not System databases will be processed.\nThis parameter cannot be used with -ExcludeUser.",
                           "UserDbOnly,NoSystemDb,ExcludeAllSystemDb",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Owner",
                           "Specifies one or more database owners. Only databases owned by the listed owner(s) will be returned.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Encrypted",
                           "If this switch is enabled, only databases which have Transparent Data Encryption (TDE) enabled will be returned.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Status",
                           "Specifies one or more database statuses to filter on. Only databases in the status(es) listed will be returned. Valid options for this parameter are \u0027Emergency\u0027, \u0027Normal\u0027, \u0027Offline\u0027, \u0027Recovering\u0027, \r\n\u0027Restoring\u0027, \u0027Standby\u0027, and \u0027Suspect\u0027.",
                           "",
                           false,
                           "false",
                           "@(\u0027EmergencyMode\u0027, \u0027Normal\u0027, \u0027Offline\u0027, \u0027Recovering\u0027, \u0027Restoring\u0027, \u0027Standby\u0027, \u0027Suspect\u0027)"
                       ],
                       [
                           "Access",
                           "Filters databases returned by their access type. Valid options for this parameter are \u0027ReadOnly\u0027 and \u0027ReadWrite\u0027. If omitted, no filtering is performed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RecoveryModel",
                           "Filters databases returned by their recovery model. Valid options for this parameter are \u0027Full\u0027, \u0027Simple\u0027, and \u0027BulkLogged\u0027.",
                           "",
                           false,
                           "false",
                           "@(\u0027Full\u0027, \u0027Simple\u0027, \u0027BulkLogged\u0027)"
                       ],
                       [
                           "NoFullBackup",
                           "If this switch is enabled, only databases without a full backup recorded by SQL Server will be returned. This will also indicate which of these databases only have CopyOnly full backups.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NoFullBackupSince",
                           "Only databases which haven\u0027t had a full backup since the specified DateTime will be returned.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NoLogBackup",
                           "If this switch is enabled, only databases without a log backup recorded by SQL Server will be returned. This will also indicate which of these databases only have CopyOnly log backups.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NoLogBackupSince",
                           "Only databases which haven\u0027t had a log backup since the specified DateTime will be returned.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IncludeLastUsed",
                           "If this switch is enabled, the last used read \u0026 write times for each database will be returned. This data is retrieved from sys.dm_db_index_usage_stats which is reset when SQL Server is restarted.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "OnlyAccessible",
                           "If this switch is enabled, only accessible databases are returned (huge speedup in SMO enumeration)",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDatabase [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-ExcludeUser] [-ExcludeSystem] [-Owner \u003cString[]\u003e] [-Encrypted] [-Status \u003cString[]\u003e] [-Access \u003cString\u003e] [-RecoveryModel \u003cString[]\u003e] [-NoFullBackup] [-NoFullBackupSince \u003cDateTime\u003e] [-NoLogBackup] [-NoLogBackupSince \u003cDateTime\u003e] [-EnableException] [-IncludeLastUsed] [-OnlyAccessible] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbAssembly",
        "Description":  "The Get-DbaDbAssembly command gets SQL Database Assembly information for each instance(s) of SQL Server.",
        "Tags":  [
                     "Assembly",
                     "Database"
                 ],
        "Synopsis":  "Gets SQL Database Assembly information for each instance(s) of SQL Server.",
        "Alias":  "Get-DbaDatabaseAssembly",
        "Author":  "Garry Bargsley (@gbargsley), http://blog.garrybargsley.com",
        "CommandName":  "Get-DbaDbAssembly",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbAssembly",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbAssembly -SqlInstance localhost\nReturns all Database Assembly on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbAssembly -SqlInstance localhost, sql2016\nReturns all Database Assembly for the local and sql2016 SQL Server instances",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbAssembly [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbccHelp",
        "Description":  "Returns the results of DBCC HELP\n\nRead more:\n    - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-help-transact-sql",
        "Tags":  "DBCC",
        "Synopsis":  "Execution of Database Console Command DBCC HELP",
        "Alias":  "",
        "Author":  "Patrick Flynn (@sqllensman)",
        "CommandName":  "Get-DbaDbccHelp",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbccUserOptions",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbccHelp -SqlInstance SQLInstance -Statement FREESYSTEMCACHE -Verbose | Format-List\nRuns the command DBCC HELP(FREESYSTEMCACHE) WITH NO_INFOMSGS against the SQL Server instance SQLInstance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbccHelp -SqlInstance LensmanSB -Statement WritePage -IncludeUndocumented | Format-List\nSets TraeFlag 2588 on for session and then runs the command DBCC HELP(WritePage) WITH NO_INFOMSGS against the SQL Server instance SQLInstance",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Statement",
                           "Is the name of the DBCC command for which to receive syntax information.\r\nProvide only the part of the DBCC command that follows DBCC,\r\n    for example, CHECKDB instead of DBCC CHECKDB.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IncludeUndocumented",
                           "Allows getting help for undocumented DBCC commands. Requires Traceflag 2588\r\nThis only works for SQL Server 2005 or Higher",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbccHelp [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Statement] \u003cString\u003e] [-IncludeUndocumented] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbccMemoryStatus",
        "Description":  "This command is used to run the DBCC MEMORYSTATUS comand and collect results in a single usable recordset\n\nReference:\n    - https://blogs.msdn.microsoft.com/timchapman/2012/08/16/how-to-parse-dbcc-memorystatus-via-powershell/\n    - https://support.microsoft.com/en-us/help/907877/how-to-use-the-dbcc-memorystatus-command-to-monitor-memory-usage-on-sq",
        "Tags":  [
                     "DBCC",
                     "Memory"
                 ],
        "Synopsis":  "Gets the results of DBCC MEMORYSTATUS.  Works on SQL Server 2000-2019.",
        "Alias":  "",
        "Author":  "Patrick Flynn (@sqllensman)",
        "CommandName":  "Get-DbaDbccMemoryStatus",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaMemoryStatus",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbccMemoryStatus -SqlInstance sqlcluster, sqlserver2012\nGet output of DBCC MEMORYSTATUS for instances \"sqlcluster\" and \"sqlserver2012\". Returns results in a single recordset.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sqlcluster | Get-DbaDbccMemoryStatus\nGet output of DBCC MEMORYSTATUS for all servers in Server Central Management Server",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbccMemoryStatus [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbccProcCache",
        "Description":  "Returns the results of DBCC PROCCACHE\n\nRead more:\n    - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-proccache-transact-sql",
        "Tags":  "DBCC",
        "Synopsis":  "Execution of Database Console Command DBCC PROCCACHE",
        "Alias":  "",
        "Author":  "Patrick Flynn (@sqllensman)",
        "CommandName":  "Get-DbaDbccProcCache",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbccProcCache",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbccProcCache -SqlInstance Server1\nGet results of DBCC PROCCACHE for Instance Server1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbccProcCache\nGet results of DBCC PROCCACHE for Instances Sql1 and Sql2/sqlexpress\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaDbccProcCache -SqlInstance Server1 -SqlCredential $cred\nConnects using sqladmin credential and gets results of DBCC PROCCACHE for Instance Server1",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbccProcCache [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbccSessionBuffer",
        "Description":  "Returns the results of DBCC INPUTBUFFER or DBCC OUTPUTBUFFER for input sessions\n\nRead more:\n    - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-inputbuffer-transact-sql\n    - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-outputbuffer-transact-sql",
        "Tags":  "DBCC",
        "Synopsis":  "Gets result of Database Console Command DBCC INPUTBUFFER  or DBCC OUTPUTBUFFER",
        "Alias":  "",
        "Author":  "Patrick Flynn (@sqllensman)",
        "CommandName":  "Get-DbaDbccSessionBuffer",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbccSessionBuffer",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbccSessionBuffer -SqlInstance Server1 -Operation InputBuffer -SessionId 51\nGet results of DBCC INPUTBUFFER(51) for Instance Server1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbccSessionBuffer -SqlInstance Server1 -Operation OutputBuffer -SessionId 51, 52\nGet results of DBCC OUTPUTBUFFER for SessionId\u0027s 51 and 52 for Instance Server1\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbccSessionBuffer -SqlInstance Server1 -Operation InputBuffer -SessionId 51 -RequestId 0\nGet results of DBCC INPUTBUFFER(51,0) for Instance Server1\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbccSessionBuffer -SqlInstance Server1 -Operation OutputBuffer -SessionId 51 -RequestId 0\nGet results of DBCC OUTPUTBUFFER(51,0) for Instance Server1\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbccSessionBuffer -Operation InputBuffer -All\nGet results of DBCC INPUTBUFFER for all user sessions for the instances Sql1 and Sql2/sqlexpress\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbccSessionBuffer -Operation OutputBuffer -All\nGet results of DBCC OUTPUTBUFFER for all user sessions for the instances Sql1 and Sql2/sqlexpress\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaDbccSessionBuffer -SqlInstance Server1 -SqlCredential $cred -Operation InputBuffer -SessionId 51 -RequestId 0\nConnects using sqladmin credential and gets results of DBCC INPUTBUFFER(51,0) for Instance Server1\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaDbccSessionBuffer -SqlInstance Server1 -SqlCredential $cred -Operation OutputBuffer -SessionId 51 -RequestId 0\nConnects using sqladmin credential and gets results of DBCC OUTPUTBUFFER(51,0) for Instance Server1",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Operation",
                           "DBCC Operation to execute - either InputBuffer or OutputBuffer",
                           "",
                           false,
                           "false",
                           "InputBuffer"
                       ],
                       [
                           "SessionId",
                           "The Session ID(s) to use to get current input or output buffer.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RequestId",
                           "Is the exact request (batch) to search for within the current session\r\nThe following query returns request_id:\nSELECT request_id\r\nFROM sys.dm_exec_requests\r\nWHERE session_id = @@spid;",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "All",
                           "If this switch is enabled, results for all User Sessions will be retreived\r\nThis overides any values for SessionId or RequestId",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbccSessionBuffer [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Operation] \u003cString\u003e] [[-SessionId] \u003cInt32[]\u003e] [[-RequestId] \u003cInt32\u003e] [-All] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbccStatistic",
        "Description":  "Executes the command DBCC SHOW_STATISTICS against defined objects and returns results\n\nReclaims space from dropped variable-length columns in tables or indexed views\n\nRead more:\n    - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-cleantable-transact-sql",
        "Tags":  [
                     "DBCC",
                     "Statistics"
                 ],
        "Synopsis":  "Execution of Database Console Command DBCC SHOW_STATISTICS",
        "Alias":  "",
        "Author":  "Patrick Flynn (@sqllensman)",
        "CommandName":  "Get-DbaDbccStatistic",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbccStatistic",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbccStatistic -SqlInstance SQLServer2017\nWill run the statement SHOW_STATISTICS WITH STAT_HEADER against all Statistics on all User Tables or views for every accessible database on instance SQLServer2017. Connects using Windows \r\nAuthentication.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbccStatistic -SqlInstance SQLServer2017 -Database MyDb -Option DensityVector\nWill run the statement SHOW_STATISTICS WITH DENSITY_VECTOR against all Statistics on all User Tables or views for database MyDb on instance SQLServer2017. Connects using Windows Authentication.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaDbccStatistic -SqlInstance SQLServer2017 -SqlCredential $cred -Database MyDb -Object UserTable -Option Histogram\nWill run the statement SHOW_STATISTICS WITH HISTOGRAM against all Statistics on table UserTable for database MyDb on instance SQLServer2017. Connects using sqladmin credential.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbccStatistic -SqlInstance SQLServer2017 -Database MyDb -Object \u0027dbo.UserTable\u0027 -Target MyStatistic -Option StatsStream\nRuns the statement SHOW_STATISTICS(\u0027dbo.UserTable\u0027, \u0027MyStatistic\u0027) WITH STATS_STREAM against database MyDb on instances Sql1 and Sql2/sqlexpress. Connects using Windows Authentication.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Object",
                           "The table or indexed view for which to display statistics information.\r\nAny two part object name should be formatted as \u0027Schema.ObjectName\u0027",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Target",
                           "Name of the index, statistics, or column for which to display statistics information.\r\nTarget can be enclosed in brackets, single quotes, double quotes, or no quotes",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Option",
                           "Used to limit the result sets returned by the statement to the specified option.\r\nOptions are \u0027StatHeader\u0027, \u0027DensityVector\u0027, \u0027Histogram\u0027, \u0027StatsStream\u0027\r\nDefault of StatHeader",
                           "",
                           false,
                           "false",
                           "StatHeader"
                       ],
                       [
                           "NoInformationalMessages",
                           "Suppresses all informational messages.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbccStatistic [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Object] \u003cString\u003e] [[-Target] \u003cString\u003e] [[-Option] \u003cString\u003e] [-NoInformationalMessages] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbccUserOption",
        "Description":  "Returns the results of DBCC USEROPTIONS\n\nRead more:\n    - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-useroptions-transact-sql",
        "Tags":  "DBCC",
        "Synopsis":  "Execution of Database Console Command DBCC USEROPTIONS",
        "Alias":  "",
        "Author":  "Patrick Flynn (@sqllensman)",
        "CommandName":  "Get-DbaDbccUserOption",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbccUserOptions",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbccUserOptions -SqlInstance Server1\nGet results of DBCC USEROPTIONS for Instance Server1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbccUserOptions\nGet results of DBCC USEROPTIONS for Instances Sql1 and Sql2/sqlexpress\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaDbccUserOptions -SqlInstance Server1 -SqlCredential $cred\nConnects using sqladmin credential and gets results of DBCC USEROPTIONS for Instance Server1\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbccUserOptions -SqlInstance Server1 -Option ansi_nulls, ansi_warnings, datefirst\nGets results of DBCC USEROPTIONS for Instance Server1. Only display results for the options ansi_nulls, ansi_warnings, datefirst",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Option",
                           "Return only specific options. Returns all results if not specified.\r\nAccepts any values in set \u0027ansi_null_dflt_on\u0027, \u0027ansi_nulls\u0027, \u0027ansi_padding\u0027, \u0027ansi_warnings\u0027, \u0027arithabort\u0027, \u0027concat_null_yields_null\u0027, \u0027datefirst\u0027, \u0027dateformat\u0027, \u0027isolation level\u0027, \u0027language\u0027, \r\n\u0027lock_timeout\u0027, \u0027quoted_identifier\u0027, \u0027textsize\u0027",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbccUserOption [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Option] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbCertificate",
        "Description":  "Gets database certificates",
        "Tags":  "Certificate",
        "Synopsis":  "Gets database certificates",
        "Alias":  "Get-DbaDatabaseCertificate",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaDbCertificate",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbCertificate -SqlInstance sql2016\nGets all certificates\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbCertificate -SqlInstance Server1 -Database db1\nGets the certificate for the db1 database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbCertificate -SqlInstance Server1 -Database db1 -Certificate cert1\nGets the cert1 certificate within the db1 database\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbCertificate -SqlInstance Server1 -Database db1 -Subject \u0027Availability Group Cert\u0027\nGets the cert1 certificate within the db1 database",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to SQL Server using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Get certificate from specific database",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Database(s) to ignore when retrieving certificates",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Certificate",
                           "Get specific certificate by name",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Subject",
                           "sometimes it\u0027s text, other times cert",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaDatabase",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbCertificate [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-Certificate] \u003cObject[]\u003e] [[-Subject] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbCheckConstraint",
        "Description":  "Gets database Checks constraints.",
        "Tags":  "Database",
        "Synopsis":  "Gets database Check constraints.",
        "Alias":  "",
        "Author":  "Claudio Silva (@ClaudioESSilva), https://claudioessilva.eu",
        "CommandName":  "Get-DbaDbCheckConstraint",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbCheckConstraint -SqlInstance sql2016\nGets all database check constraints.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbCheckConstraint -SqlInstance Server1 -Database db1\nGets the check constraints for the db1 database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbCheckConstraint -SqlInstance Server1 -ExcludeDatabase db1\nGets the check constraints for all databases except db1.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbCheckConstraint -SqlInstance Server1 -ExcludeSystemTable\nGets the check constraints for all databases that are not system objects.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbCheckConstraint\nGets the check constraints for the databases on Sql1 and Sql2/sqlexpress.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to SQL Server using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "To get Checks from specific database(s)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeSystemTable",
                           "This switch removes all system objects from the table collection",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbCheckConstraint [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-ExcludeSystemTable] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbCompatibility",
        "Description":  "Get the current database compatibility level for all databases on a server or list of databases passed in to the function.",
        "Tags":  [
                     "Compatibility",
                     "Database"
                 ],
        "Synopsis":  "Displays the compatibility level for SQL Server databases.",
        "Alias":  "",
        "Author":  "Garry Bargsley, http://blog.garrybargsley.com/",
        "CommandName":  "Get-DbaDbCompatibility",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbCompatibility",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbCompatibility -SqlInstance localhost\\sql2017\nDisplays database compatibility level for all user databases on server localhost\\sql2017\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbCompatibility -SqlInstance localhost\\sql2017 -Database Test\nDisplays database compatibility level for database Test on server localhost\\sql2017",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "SqlCredential object used to connect to the SQL Server as a different user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database or databases to process. If unspecified, all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "A collection of databases (such as returned by Get-DbaDatabase)",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbCompatibility [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbCompression",
        "Description":  "This function gets the current size and compression for all objects in the specified database(s), if no database is specified it will return all objects in all user databases.",
        "Tags":  [
                     "Compression",
                     "Table",
                     "Database"
                 ],
        "Synopsis":  "Gets tables and indexes size and current compression settings.",
        "Alias":  "",
        "Author":  "Jess Pomfret (@jpomfret), jesspomfret.com",
        "CommandName":  "Get-DbaDbCompression",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbCompression -SqlInstance localhost\nReturns objects size and current compression level for all user databases.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbCompression -SqlInstance localhost -Database TestDatabase\nReturns objects size and current compression level for objects within the TestDatabase database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbCompression -SqlInstance localhost -ExcludeDatabase TestDatabases\nReturns objects size and current compression level for objects in all databases except the TestDatabase database.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto populated from the server. If unspecified, all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbCompression [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbDbccOpenTran",
        "Description":  "Executes the command DBCC OPENTRAN against the requested databases\n\nDisplays information about the oldest active transaction and\nthe oldest distributed and nondistributed replicated transactions, if any,\nwithin the transaction log of the specified database\n\nRead more:\n    - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-opentran-transact-sql",
        "Tags":  "DBCC",
        "Synopsis":  "Execution of Database Console Command DBCC OPENTRAN",
        "Alias":  "",
        "Author":  "Patrick Flynn (@sqllensman)",
        "CommandName":  "Get-DbaDbDbccOpenTran",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbDbccOpenTran",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbDbccOpenTran -SqlInstance SQLServer2017\nConnects to instance SqlServer2017 using Windows Authentication and runs the command DBCC OPENTRAN WITH TABLERESULTS, NO_INFOMSGS against each database.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbDbccOpenTran -SqlInstance SQLServer2017 -Database CurrentDB\nConnects to instance SqlServer2017 using Windows Authentication and runs the command DBCC OPENTRAN(CurrentDB) WITH TABLERESULTS, NO_INFOMSGS against the CurrentDB database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e \u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbDbccOpenTran -SqlCredential $cred\nConnects to instances Sql1 and Sql2/sqlexpress using sqladmin credential and runs the command DBCC OPENTRAN WITH TABLERESULTS, NO_INFOMSGS against each database.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process. If unspecified, all databases will be processed.\r\nThe Name or Id of a database can be specified\r\nDatabase names must comply with the rules for identifiers.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbDbccOpenTran [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbEncryption",
        "Description":  "Shows if a database has Transparent Data Encryption (TDE), any certificates, asymmetric keys or symmetric keys with details for each.",
        "Tags":  [
                     "Encryption",
                     "Database"
                 ],
        "Synopsis":  "Returns a summary of encryption used on databases passed to it.",
        "Alias":  "Get-DbaDatabaseEncryption",
        "Author":  "Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/",
        "CommandName":  "Get-DbaDbEncryption",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbEncryption",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbEncryption -SqlInstance DEV01\nList all encryption found on the instance by database\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbEncryption -SqlInstance DEV01 -Database MyDB\nList all encryption found for the MyDB database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbEncryption -SqlInstance DEV01 -ExcludeDatabase MyDB\nList all encryption found for all databases except MyDB.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbEncryption -SqlInstance DEV01 -IncludeSystemDBs\nList all encryption found for all databases including the system databases.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IncludeSystemDBs",
                           "Switch parameter that when used will display system database information.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbEncryption [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-IncludeSystemDBs] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbExtentDiff",
        "Description":  "This is only an implementation of the script created by Paul S. Randal to find what percentage of a database has changed since the last full backup.\nhttps://www.sqlskills.com/blogs/paul/new-script-how-much-of-the-database-has-changed-since-the-last-full-backup/",
        "Tags":  [
                     "Backup",
                     "Database"
                 ],
        "Synopsis":  "What percentage of a database has changed since the last full backup",
        "Alias":  "",
        "Author":  "Viorel Ciucu, cviorel.com",
        "CommandName":  "Get-DbaDbExtentDiff",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "http://dbatools.io/Get-DbaDbExtentDiff",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbExtentDiff -SqlInstance SQL2016 -Database DBA\nGet the changes for the DBA database.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$Cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaDbExtentDiff -SqlInstance SQL2017N1, SQL2017N2, SQL2016 -Database DB01 -SqlCredential $Cred\nGet the changes for the DB01 database on multiple servers.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbExtentDiff [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbFeatureUsage",
        "Description":  "Shows features that are enabled in the database but not supported on all editions of SQL Server.\n\nBasically checks for Enterprise feature usage.\n\nThis feature must be removed before the database can be migrated to all available editions of SQL Server.",
        "Tags":  "Deprecated",
        "Synopsis":  "Shows features that are enabled in the database but not supported on all editions of SQL Server. Basically checks for Enterprise feature usage.",
        "Alias":  "",
        "Author":  "Brandon Abshire, netnerds.net",
        "CommandName":  "Get-DbaDbFeatureUsage",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbFeatureUsage",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2008 -Database testdb, db2 | Get-DbaDbFeatureUsage\nShows features that are enabled in the testdb and db2 databases but\r\nnot supported on the all the editions of SQL Server.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance",
                           "ServerInstance,SqlServer,SqlServers",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternate Windows or SQL Login Authentication. Accepts credential objects (Get-Credential).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "A collection of databases (such as returned by Get-DbaDatabase), to be tested.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbFeatureUsage [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbFile",
        "Description":  "Returns detailed information about database files. Does not use SMO - SMO causes enumeration and this command avoids that.",
        "Tags":  "Database",
        "Synopsis":  "Returns detailed information about database files.",
        "Alias":  "Get-DbaDatabaseFile",
        "Author":  "Stuart Moore (@napalmgram), stuart-moore.com",
        "CommandName":  "Get-DbaDbFile",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbFile -SqlInstance sql2016\nWill return an object containing all file groups and their contained files for every database on the sql2016 SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbFile -SqlInstance sql2016 -Database Impromptu\nWill return an object containing all file groups and their contained files for the Impromptu Database on the sql2016 SQL Server instance\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbFile -SqlInstance sql2016 -Database Impromptu, Trading\nWill return an object containing all file groups and their contained files for the Impromptu and Trading databases on the sql2016 SQL Server instance\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016 -Database Impromptu, Trading | Get-DbaDbFile\nWill accept piped input from Get-DbaDatabase and return an object containing all file groups and their contained files for the Impromptu and Trading databases on the sql2016 SQL Server instance",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Credentials to connect to the SQL Server instance if the calling user doesn\u0027t have permission",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "A piped collection of database objects",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbFile [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbForeignKey",
        "Description":  "Gets database Foreign Keys.",
        "Tags":  [
                     "Database",
                     "ForeignKey",
                     "Table"
                 ],
        "Synopsis":  "Gets database Foreign Keys.",
        "Alias":  "",
        "Author":  "Claudio Silva (@ClaudioESSilva), https://claudioessilva.eu",
        "CommandName":  "Get-DbaDbForeignKey",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbForeignKey -SqlInstance sql2016\nGets all database Foreign Keys.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbForeignKey -SqlInstance Server1 -Database db1\nGets the Foreign Keys for the db1 database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbForeignKey -SqlInstance Server1 -ExcludeDatabase db1\nGets the Foreign Keys for all databases except db1.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbForeignKey -SqlInstance Server1 -ExcludeSystemTable\nGets the Foreign Keys from all tables that are not system objects from all databases.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbForeignKey\nGets the Foreign Keys for the databases on Sql1 and Sql2/sqlexpress.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to SQL Server using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "To get Foreign Keys from specific database(s)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeSystemTable",
                           "This switch removes all system objects from the tables collection",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbForeignKey [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-ExcludeSystemTable] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbLogShipError",
        "Description":  "When your log shipping fails it\u0027s sometimes hard to see why is fails.\nUsing this function you\u0027ll be able to find out what went wrong in a short amount of time.",
        "Tags":  "LogShipping",
        "Synopsis":  "Get-DbaDbLogShipError returns all the log shipping errors that occurred",
        "Alias":  "Get-DbaLogShippingError",
        "Author":  "Sander Stad (@sqlstad), sqlstad.nl",
        "CommandName":  "Get-DbaDbLogShipError",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbLogShipError",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbLogShipError -SqlInstance sql1\nGet all the log shipping errors that occurred\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbLogShipError -SqlInstance sql1 -Action Backup\nGet the errors that have something to do with the backup of the databases\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbLogShipError -SqlInstance sql1 -Secondary\nGet the errors that occurred on the secondary instance.\r\nThis will return the copy of the restore actions because those only occur on the secondary instance\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbLogShipError -SqlInstance sql1 -DateTimeFrom \"01/05/2018\"\nGet the errors that have occurred from \"01/05/2018\". This can also be of format \"yyyy-MM-dd\"\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDbLogShipError -SqlInstance sql1 -Secondary -DateTimeFrom \"01/05/2018\" -DateTimeTo \"2018-01-07\"\nGet the errors that have occurred between \"01/05/2018\" and \"01/07/2018\".\r\nSee that is doesn\u0027t matter how the date is represented.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Allows you to filter the results to only return the databases you\u0027re interested in. This can be one or more values separated by commas.\r\nThis is not a wildcard and should be the exact database name. See examples for more info.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Allows you to filter the results to only return the databases you\u0027re not interested in. This can be one or more values separated by commas.\r\nThis is not a wildcard and should be the exact database name.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Action",
                           "Filter to get the log shipping action that has occurred like Backup, Copy, Restore.\r\nBy default all the actions are returned.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DateTimeFrom",
                           "Filter the results based on the date starting from datetime X",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DateTimeTo",
                           "Filter the results based on the date ending with datetime X",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Primary",
                           "Allows to filter the results to only return values that apply to the primary instance.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Secondary",
                           "Allows to filter the results to only return values that apply to the secondary instance.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbLogShipError [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-Action] \u003cString[]\u003e] [[-DateTimeFrom] \u003cDateTime\u003e] [[-DateTimeTo] \u003cDateTime\u003e] [-Primary] [-Secondary] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbMail",
        "Description":  "Gets the database mail from SQL Server",
        "Tags":  [
                     "DatabaseMail",
                     "DBMail",
                     "Mail"
                 ],
        "Synopsis":  "Gets the database mail from SQL Server",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaDbMail",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbMail",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMail -SqlInstance sql01\\sharepoint\nReturns the db mail server object on sql01\\sharepoint\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMail -SqlInstance sql01\\sharepoint | Select *\nReturns the db mail server object on sql01\\sharepoint then return a bunch more columns\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\"\nPS C:\\\u003e $servers | Get-DbaDbMail\nReturns the db mail server object for \"sql2014\",\"sql2016\" and \"sqlcluster\\sharepoint\"",
        "Params":  [
                       [
                           "SqlInstance",
                           "TThe target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbMail [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbMailAccount",
        "Description":  "Gets database mail accounts from SQL Server",
        "Tags":  [
                     "DatabaseMail",
                     "DbMail",
                     "Mail"
                 ],
        "Synopsis":  "Gets database mail accounts from SQL Server",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaDbMailAccount",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbMailAccount",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMailAccount -SqlInstance sql01\\sharepoint\nReturns Database Mail accounts on sql01\\sharepoint\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMailAccount -SqlInstance sql01\\sharepoint -Account \u0027The DBA Team\u0027\nReturns The DBA Team Database Mail account from sql01\\sharepoint\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbMailAccount -SqlInstance sql01\\sharepoint | Select *\nReturns the Database Mail accounts on sql01\\sharepoint then return a bunch more columns\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\"\nPS C:\\\u003e $servers | Get-DbaDbMail | Get-DbaDbMailAccount\nReturns the Database Mail accounts for \"sql2014\",\"sql2016\" and \"sqlcluster\\sharepoint\"",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Account",
                           "Specifies one or more account(s) to get. If unspecified, all accounts will be returned.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeAccount",
                           "Specifies one or more account(s) to exclude.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Accepts pipeline input from Get-DbaDbMail",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbMailAccount [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Account] \u003cString[]\u003e] [[-ExcludeAccount] \u003cString[]\u003e] [[-InputObject] \u003cSqlMail[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbMailConfig",
        "Description":  "Gets database mail configs from SQL Server",
        "Tags":  [
                     "DatabaseMail",
                     "DBMail",
                     "Mail"
                 ],
        "Synopsis":  "Gets database mail configs from SQL Server",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaDbMailConfig",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbMailConfig",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMailConfig -SqlInstance sql01\\sharepoint\nReturns DBMail configs on sql01\\sharepoint\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMailConfig -SqlInstance sql01\\sharepoint -Name ProhibitedExtensions\nReturns the ProhibitedExtensions configuration on sql01\\sharepoint\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbMailConfig -SqlInstance sql01\\sharepoint | Select *\nReturns the DBMail configs on sql01\\sharepoint then return a bunch more columns\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\"\nPS C:\\\u003e $servers | Get-DbaDbMail | Get-DbaDbMailConfig\nReturns the DBMail configs for \"sql2014\",\"sql2016\" and \"sqlcluster\\sharepoint\"",
        "Params":  [
                       [
                           "SqlInstance",
                           "TThe target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "Specifies one or more config(s) to get. If unspecified, all configs will be returned.",
                           "Config,ConfigName",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Accepts pipeline input from Get-DbaDbMail",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbMailConfig [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString[]\u003e] [[-InputObject] \u003cSqlMail[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbMailHistory",
        "Description":  "Gets the history of mail sent from a SQL instance",
        "Tags":  [
                     "DatabaseMail",
                     "DBMail",
                     "Mail"
                 ],
        "Synopsis":  "Gets the history of mail sent from a SQL instance",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaDbMailHistory",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbMailHistory",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMailHistory -SqlInstance sql01\\sharepoint\nReturns the entire DBMail history on sql01\\sharepoint\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMailHistory -SqlInstance sql01\\sharepoint | Select *\nReturns the entire DBMail history on sql01\\sharepoint then return a bunch more columns\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\"\nPS C:\\\u003e $servers | Get-DbaDbMailHistory\nReturns the all DBMail history for \"sql2014\",\"sql2016\" and \"sqlcluster\\sharepoint\"",
        "Params":  [
                       [
                           "SqlInstance",
                           "TThe target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Since",
                           "Datetime object used to narrow the results to the send request date",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Status",
                           "Narrow the results by status. Valid values include Unsent, Sent, Failed and Retrying",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbMailHistory [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Since] \u003cDateTime\u003e] [[-Status] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbMailLog",
        "Description":  "Gets the DBMail log from a SQL instance",
        "Tags":  [
                     "DatabaseMail",
                     "DBMail",
                     "Mail"
                 ],
        "Synopsis":  "Gets the DBMail log from a SQL instance",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaDbMailLog",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbMailLog",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMailLog -SqlInstance sql01\\sharepoint\nReturns the entire DBMail log on sql01\\sharepoint\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMailLog -SqlInstance sql01\\sharepoint | Select *\nReturns the entire DBMail log on sql01\\sharepoint, includes all returned information.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\"\nPS C:\\\u003e $servers | Get-DbaDbMailLog -Type Error, Information\nReturns only the Error and Information DBMail log for \"sql2014\",\"sql2016\" and \"sqlcluster\\sharepoint\"",
        "Params":  [
                       [
                           "SqlInstance",
                           "TThe target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Since",
                           "Datetime object used to narrow the results to the send request date",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Type",
                           "Narrow the results by type. Valid values include Error, Warning, Success, Information, Internal",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbMailLog [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Since] \u003cDateTime\u003e] [[-Type] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbMailProfile",
        "Description":  "Gets database mail profiles from SQL Server",
        "Tags":  [
                     "DatabaseMail",
                     "DBMail",
                     "Mail"
                 ],
        "Synopsis":  "Gets database mail profiles from SQL Server",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaDbMailProfile",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbMailProfile",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMailProfile -SqlInstance sql01\\sharepoint\nReturns DBMail profiles on sql01\\sharepoint\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMailProfile -SqlInstance sql01\\sharepoint -Profile \u0027The DBA Team\u0027\nReturns The DBA Team DBMail profile from sql01\\sharepoint\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbMailProfile -SqlInstance sql01\\sharepoint | Select *\nReturns the DBMail profiles on sql01\\sharepoint then return a bunch more columns\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\"\nPS C:\\\u003e $servers | Get-DbaDbMail | Get-DbaDbMailProfile\nReturns the DBMail profiles for \"sql2014\",\"sql2016\" and \"sqlcluster\\sharepoint\"",
        "Params":  [
                       [
                           "SqlInstance",
                           "TThe target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Profile",
                           "Specifies one or more profile(s) to get. If unspecified, all profiles will be returned.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeProfile",
                           "Specifies one or more profile(s) to exclude.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Accepts pipeline input from Get-DbaDbMail",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbMailProfile [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Profile] \u003cString[]\u003e] [[-ExcludeProfile] \u003cString[]\u003e] [[-InputObject] \u003cSqlMail[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbMailServer",
        "Description":  "Gets database mail servers from SQL Server",
        "Tags":  [
                     "DatabaseMail",
                     "DBMail",
                     "Mail"
                 ],
        "Synopsis":  "Gets database mail servers from SQL Server",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaDbMailServer",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbMailServer",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMailServer -SqlInstance sql01\\sharepoint\nReturns all DBMail servers on sql01\\sharepoint\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMailServer -SqlInstance sql01\\sharepoint -Server DbaTeam\nReturns The DBA Team DBMail server from sql01\\sharepoint\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbMailServer -SqlInstance sql01\\sharepoint | Select *\nReturns the DBMail servers on sql01\\sharepoint then return a bunch more columns\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\"\nPS C:\\\u003e $servers | Get-DbaDbMail | Get-DbaDbMailServer\nReturns the DBMail servers for \"sql2014\",\"sql2016\" and \"sqlcluster\\sharepoint\"",
        "Params":  [
                       [
                           "SqlInstance",
                           "TThe target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Server",
                           "Specifies one or more server(s) to get. If unspecified, all servers will be returned.",
                           "Name",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Account",
                           "Get only the mail server associated with specific accounts",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Accepts pipeline input from Get-DbaDbMail",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbMailServer [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Server] \u003cString[]\u003e] [[-Account] \u003cString[]\u003e] [[-InputObject] \u003cSqlMail[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbMasterKey",
        "Description":  "Gets specified database master key",
        "Tags":  [
                     "Certificate",
                     "Database"
                 ],
        "Synopsis":  "Gets specified database master key",
        "Alias":  "Get-DbaDatabaseMasterKey",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaDbMasterKey",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMasterKey -SqlInstance sql2016\nGets all master database keys\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMasterKey -SqlInstance Server1 -Database db1\nGets the master key for the db1 database",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to SQL Server using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Get master key from specific database",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Database object piped in from Get-DbaDatabase",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbMasterKey [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbMemoryUsage",
        "Description":  "This command can be utilized to determine which databases on a given instance are consuming buffer pool memory.\n\nThis command is based on query provided by Aaron Bertrand.\nReference: https://www.mssqltips.com/sqlservertip/2393/determine-sql-server-memory-use-by-database-and-object/",
        "Tags":  [
                     "Memory",
                     "Database"
                 ],
        "Synopsis":  "Determine buffer pool usage by database.",
        "Alias":  "",
        "Author":  "Shawn Melton (@wsmelton), https://wsmelton.github.io",
        "CommandName":  "Get-DbaDbMemoryUsage",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbMemoryUsage",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMemoryUsage -SqlInstance sqlserver2014a\nReturns the buffer pool consumption for all user databases\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMemoryUsage -SqlInstance sqlserver2014a -IncludeSystemDb\nReturns the buffer pool consumption for all user databases and system databases\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbMemoryUsage -SqlInstance sql1 -IncludeSystemDb -Database tempdb\nReturns the buffer pool consumption for tempdb database only\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbMemoryUsage -SqlInstance sql2 -IncludeSystemDb -Exclude \u0027master\u0027,\u0027model\u0027,\u0027msdb\u0027,\u0027ResourceDb\u0027\nReturns the buffer pool consumption for all user databases and tempdb database",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "",
                           false,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IncludeSystemDb",
                           "Switch to have the output include system database memory consumption.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbMemoryUsage [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-IncludeSystemDb] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbMirror",
        "Description":  "Gets properties of database mirrors and mirror witnesses.",
        "Tags":  [
                     "Mirror",
                     "HA"
                 ],
        "Synopsis":  "Gets properties of database mirrors and mirror witnesses.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaDbMirror",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbMirror",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMirror -SqlInstance localhost\nGets properties of database mirrors and mirror witnesses on localhost\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMirror -SqlInstance localhost, sql2016\nGets properties of database mirrors and mirror witnesses on localhost and sql2016 SQL Server instances",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbMirror [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbMirrorMonitor",
        "Description":  "Returns status rows for a monitored database from the status table in which database mirroring monitoring history is stored and allows you to choose whether the procedure obtains the latest status beforehand.\n\nBasically executes sp_dbmmonitorresults.",
        "Tags":  [
                     "Mirror",
                     "HA"
                 ],
        "Synopsis":  "Returns status rows for a monitored database from the status table in which database mirroring monitoring history is stored and allows you to choose whether the procedure obtains the latest status beforehand.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaDbMirrorMonitor",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbMirrorMonitor",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMirrorMonitor -SqlInstance sql2008, sql2012\nReturns last two hours\u0027 worth of status rows for a monitored database from the status table on sql2008 and sql2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMirrorMonitor -SqlInstance sql2005 -LimitResults LastDay -Update\nUpdates monitor stats then returns the last 24 hours worth of status rows for a monitored database from the status table on sql2008 and sql2012.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternate Windows or SQL Login Authentication. Accepts credential objects (Get-Credential).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The target database.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows piping from Get-DbaDatabase.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Update",
                           "Updates the status for the database by calling sp_dbmmonitorupdate before computing the results.\r\nHowever, if the status table has been updated within the previous 15 seconds, or the user is not a member of the sysadmin fixed server role, the command runs without updating the status.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "LimitResults",
                           "Limit results. Defaults to last two hours.\nOptions include:\r\nLastRow\r\nLastTwoHours\r\nLastFourHours\r\nLastEightHours\r\nLastDay\r\nLastTwoDays\r\nLast100Rows\r\nLast500Rows\r\nLast1000Rows\r\nLast1000000Rows",
                           "",
                           false,
                           "false",
                           "LastTwoHours"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbMirrorMonitor [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-Update] [[-LimitResults] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbOrphanUser",
        "Description":  "An orphan user is defined by a user that does not have their matching login. (Login property = \"\").",
        "Tags":  [
                     "Orphan",
                     "Database",
                     "User",
                     "Security",
                     "Login"
                 ],
        "Synopsis":  "Get orphaned users.",
        "Alias":  "Get-DbaOrphanUser",
        "Author":  "Claudio Silva (@ClaudioESSilva) | Garry Bargsley (@gbargsley) | Simone Bizzotto (@niphlod)",
        "CommandName":  "Get-DbaDbOrphanUser",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbOrphanUser",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbOrphanUser -SqlInstance localhost\\sql2016\nFinds all orphan users without matching Logins in all databases present on server \u0027localhost\\sql2016\u0027.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbOrphanUser -SqlInstance localhost\\sql2016 -SqlCredential $cred\nFinds all orphan users without matching Logins in all databases present on server \u0027localhost\\sql2016\u0027. SQL Server authentication will be used in connecting to the server.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbOrphanUser -SqlInstance localhost\\sql2016 -Database db1\nFinds orphan users without matching Logins in the db1 database present on server \u0027localhost\\sql2016\u0027.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbOrphanUser [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbPageInfo",
        "Description":  "Get-DbaDbPageInfo is able to return information about the pages in a database.\nIt\u0027s possible to return the information for multiple databases and filter on specific databases, schemas and tables.",
        "Tags":  [
                     "Database",
                     "Page"
                 ],
        "Synopsis":  "Get-DbaDbPageInfo will return page information for a database",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaDbPageInfo",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbPageInfo",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eet-DbaDbPageInfo -SqlInstance sql2017\nReturns page information for all databases on sql2017\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbPageInfo -SqlInstance sql2017, sql2016 -Database testdb\nReturns page information for the testdb on sql2017 and sql2016\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers | Get-DbaDatabase -Database testdb | Get-DbaDbPageInfo\nReturns page information for the testdb on all $servers",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Filter to only get specific databases",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Schema",
                           "Filter to only get specific schemas",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Table",
                           "Filter to only get specific tables",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaDatabase",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbPageInfo [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Schema] \u003cString[]\u003e] [[-Table] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbPartitionFunction",
        "Description":  "Gets database Partition Functions",
        "Tags":  "Database",
        "Synopsis":  "Gets database Partition Functions",
        "Alias":  "Get-DbaDatabasePartitionFunction",
        "Author":  "Klaas Vandenberghe ( @PowerDbaKlaas )",
        "CommandName":  "Get-DbaDbPartitionFunction",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbPartitionFunction -SqlInstance sql2016\nGets all database Partition Functions\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbPartitionFunction -SqlInstance Server1 -Database db1\nGets the Partition Functions for the db1 database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbPartitionFunction -SqlInstance Server1 -ExcludeDatabase db1\nGets the Partition Functions for all databases except db1\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbPartitionFunction\nGets the Partition Functions for the databases on Sql1 and Sql2/sqlexpress",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to SQL Server using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "To get users from specific database(s)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbPartitionFunction [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbPartitionScheme",
        "Description":  "Gets database Partition Schemes",
        "Tags":  "Database",
        "Synopsis":  "Gets database Partition Schemes",
        "Alias":  "Get-DbaDatabasePartitionScheme",
        "Author":  "Klaas Vandenberghe (@PowerDbaKlaas)",
        "CommandName":  "Get-DbaDbPartitionScheme",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbPartitionScheme -SqlInstance sql2016\nGets all database Partition Schemes\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbPartitionScheme -SqlInstance Server1 -Database db1\nGets the Partition Schemes for the db1 database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbPartitionScheme -SqlInstance Server1 -ExcludeDatabase db1\nGets the Partition Schemes for all databases except db1\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbPartitionScheme\nGets the Partition Schemes for the databases on Sql1 and Sql2/sqlexpress",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to SQL Server using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "To get users from specific database(s)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbPartitionScheme [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbQueryStoreOption",
        "Description":  "Retrieves and returns the Query Store configuration for every database that has the Query Store feature enabled.",
        "Tags":  "QueryStore",
        "Synopsis":  "Get the Query Store configuration for Query Store enabled databases.",
        "Alias":  "Get-DbaDbQueryStoreOptions,Get-DbaQueryStoreConfig",
        "Author":  "Enrico van de Laar (@evdlaar) | Klaas Vandenberghe (@PowerDBAKlaas)",
        "CommandName":  "Get-DbaDbQueryStoreOption",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaQueryStoreOptions",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbQueryStoreOption -SqlInstance ServerA\\sql\nReturns Query Store configuration settings for every database on the ServerA\\sql instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbQueryStoreOption -SqlInstance ServerA\\sql | Where-Object {$_.ActualState -eq \"ReadWrite\"}\nReturns the Query Store configuration for all databases on ServerA\\sql where the Query Store feature is in Read/Write mode.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbQueryStoreOption -SqlInstance localhost | format-table -AutoSize -Wrap\nReturns Query Store configuration settings for every database on the ServerA\\sql instance inside a table format.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "SqlCredential object used to connect to the SQL Server as a different user.",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbQueryStoreOption [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbRecoveryModel",
        "Description":  "Get-DbaDbRecoveryModel displays the Recovery Model for all databases. This is the default, you can filter using -Database, -ExcludeDatabase, -RecoveryModel",
        "Tags":  [
                     "Recovery",
                     "RecoveryModel",
                     "Simple",
                     "Full",
                     "Bulk",
                     "BulkLogged"
                 ],
        "Synopsis":  "Get-DbaDbRecoveryModel displays the Recovery Model.",
        "Alias":  "",
        "Author":  "Viorel Ciucu (@viorelciucu), https://www.cviorel.com",
        "CommandName":  "Get-DbaDbRecoveryModel",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbRecoveryModel",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbRecoveryModel -SqlInstance sql2014 -RecoveryModel BulkLogged -Verbose\nGets all databases on SQL Server instance sql2014 having RecoveryModel set to BulkLogged.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbRecoveryModel -SqlInstance sql2014 -Database TestDB\nGets recovery model information for TestDB. If TestDB does not exist on the instance nothing is returned.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RecoveryModel",
                           "Filters the output based on Recovery Model. Valid options are Simple, Full and BulkLogged\nDetails about the recovery models can be found here:\r\nhttps://docs.microsoft.com/en-us/sql/relational-databases/backup-restore/recovery-models-sql-server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. if unspecified, all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbRecoveryModel [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-RecoveryModel] \u003cString[]\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbRestoreHistory",
        "Description":  "By default, this command will return the server name, database, username, restore type, date, from file and to files.\n\nThanks to https://www.mssqltips.com/SqlInstancetip/1724/when-was-the-last-time-your-sql-server-database-was-restored/ for the query and https://sqlstudies.com/2016/07/27/when-was-this-database-restored/ for the idea.",
        "Tags":  [
                     "DisasterRecovery",
                     "Backup",
                     "Restore"
                 ],
        "Synopsis":  "Returns restore history details for databases on a SQL Server.",
        "Alias":  "Get-DbaRestoreHistory",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaDbRestoreHistory",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbRestoreHistory",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbRestoreHistory -SqlInstance sql2016\nReturns server name, database, username, restore type, date for all restored databases on sql2016.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbRestoreHistory -SqlInstance sql2016 -Database db1, db2 -Since \u00272016-07-01 10:47:00\u0027\nReturns restore information only for databases db1 and db2 on sql2016 since July 1, 2016 at 10:47 AM.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbRestoreHistory -SqlInstance sql2014, sql2016 -Exclude db1\nReturns restore information for all databases except db1 on sql2014 and sql2016.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaDbRestoreHistory -SqlInstance sql2014 -Database AdventureWorks2014, pubs -SqlCredential $cred | Format-Table\nReturns database restore information for AdventureWorks2014 and pubs database on sql2014, connects using SQL Authentication via sqladmin account. Formats the data as a table.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sql2016 | Get-DbaDbRestoreHistory\nReturns database restore information for every database on every server listed in the Central Management Server on sql2016.",
        "Params":  [
                       [
                           "SqlInstance",
                           "Specifies the SQL Server instance(s) to operate on. Requires SQL Server 2005 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Since",
                           "Specifies a datetime to use as the starting point for searching backup history.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "Deprecated.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Last",
                           "If this switch is enabled, the last restore action performed on each database is returned.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbRestoreHistory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-Since] \u003cDateTime\u003e] [-Force] [-Last] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbRoleMember",
        "Description":  "The Get-DbaDbRoleMember returns connected SMO object for database roles for each instance(s) of SQL Server.",
        "Tags":  [
                     "Role",
                     "Database",
                     "Security",
                     "Login"
                 ],
        "Synopsis":  "Get members of database roles for each instance(s) of SQL Server.",
        "Alias":  "Get-DbaRoleMember",
        "Author":  "Klaas Vandenberghe (@PowerDBAKlaas)",
        "CommandName":  "Get-DbaDbRoleMember",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbRoleMember",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbRoleMember -SqlInstance localhost\nReturns all members of all database roles on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbRoleMember -SqlInstance localhost, sql2016\nReturns all members of all database roles on the local and sql2016 SQL Server instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers = Get-Content C:\\servers.txt\nPS C:\\\u003e $servers | Get-DbaDbRoleMember\nReturns all members of all database roles for every server in C:\\servers.txt\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbRoleMember -SqlInstance localhost -Database msdb\nReturns non-system members of all roles in the msdb database on localhost.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDbRoleMember -SqlInstance localhost -Database msdb -IncludeSystemUser -ExcludeFixedRole\nReturns all members of non-fixed roles in the msdb database on localhost.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaDbRoleMember -SqlInstance localhost -Database msdb -Role \u0027db_owner\u0027\nReturns all members of the db_owner role in the msdb database on localhost.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternate Windows or SQL Login Authentication. Accepts credential objects (Get-Credential).",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process. This list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude. This list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Role",
                           "The role(s) to process. If unspecified, all roles will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeRole",
                           "The role(s) to exclude.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeFixedRole",
                           "Excludes all members of fixed roles.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IncludeSystemUser",
                           "Includes system users. By default system users are not included.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbRoleMember [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cString[]\u003e] [-ExcludeDatabase \u003cString[]\u003e] [-Role \u003cString[]\u003e] [-ExcludeRole \u003cString[]\u003e] [-ExcludeFixedRole] [-IncludeSystemUser] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbSharePoint",
        "Description":  "Returns databases that are part of a SharePoint Farm, as found in the SharePoint Configuration database.\n\nBy default, this command checks SharePoint_Config. To use an alternate database, use the ConfigDatabase parameter.",
        "Tags":  "SharePoint",
        "Synopsis":  "Returns databases that are part of a SharePoint Farm.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaDbSharePoint",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbSharePoint",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbSharePoint -SqlInstance sqlcluster\nReturns databases that are part of a SharePoint Farm, as found in SharePoint_Config on sqlcluster\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sqlcluster -Database SharePoint_Config_2016 | Get-DbaDbSharePoint\nReturns databases that are part of a SharePoint Farm, as found in SharePoint_Config_2016 on sqlcluster",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternate Windows or SQL Login Authentication. Accepts credential objects (Get-Credential).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ConfigDatabase",
                           "The name of the SharePoint Configuration database. Defaults to SharePoint_Config.",
                           "",
                           false,
                           "false",
                           "SharePoint_Config"
                       ],
                       [
                           "InputObject",
                           "Allows piping from Get-DbaDatabase.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbSharePoint [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-ConfigDatabase] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbSnapshot",
        "Description":  "Retrieves the list of database snapshot available, along with their base (the db they are the snapshot of) and creation time",
        "Tags":  "Snapshot",
        "Synopsis":  "Get database snapshots with details",
        "Alias":  "Get-DbaDatabaseSnapshot",
        "Author":  "Simone Bizzotto (@niphlod)",
        "CommandName":  "Get-DbaDbSnapshot",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbSnapshot",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbSnapshot -SqlInstance sqlserver2014a\nReturns a custom object displaying Server, Database, DatabaseCreated, SnapshotOf, SizeMB, DatabaseCreated\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbSnapshot -SqlInstance sqlserver2014a -Database HR, Accounting\nReturns information for database snapshots having HR and Accounting as base dbs\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbSnapshot -SqlInstance sqlserver2014a -Snapshot HR_snapshot, Accounting_snapshot\nReturns information for database snapshots HR_snapshot and Accounting_snapshot",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Credential object used to connect to the SQL Server as a different user",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Return information for only specific databases",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Snapshot",
                           "Return information for only specific snapshots",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeSnapshot",
                           "The snapshot(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbSnapshot [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-Snapshot] \u003cObject[]\u003e] [[-ExcludeSnapshot] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbSpace",
        "Description":  "This function returns database file space information for a SQL Instance or group of SQL Instances. Information is based on a query against sys.database_files and the FILEPROPERTY function to query and return information.\n\nFile free space script borrowed and modified from Glenn Berry\u0027s DMV scripts (http://www.sqlskills.com/blogs/glenn/category/dmv-queries/)",
        "Tags":  [
                     "Database",
                     "Space",
                     "Storage"
                 ],
        "Synopsis":  "Returns database file space information for database files on a SQL instance.",
        "Alias":  "Get-DbaDatabaseFreeSpace,Get-DbaDatabaseSpace",
        "Author":  "Michael Fal (@Mike_Fal), http://mikefal.net",
        "CommandName":  "Get-DbaDbSpace",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbSpace",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbSpace -SqlInstance localhost\nReturns all user database files and free space information for the localhost.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbSpace -SqlInstance localhost | Where-Object {$_.PercentUsed -gt 80}\nReturns all user database files and free space information for the local host. Filters the output object by any files that have a percent used of greater than 80%.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027localhost\u0027,\u0027localhost\\namedinstance\u0027 | Get-DbaDbSpace\nReturns all user database files and free space information for the localhost and localhost\\namedinstance SQL Server instances. Processes data via the pipeline.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbSpace -SqlInstance localhost -Database db1, db2 | Where-Object { $_.SpaceUntilMaxSize.Megabyte -lt 1 }\nReturns database files and free space information for the db1 and db2 on localhost where there is only 1MB left until the space is maxed out\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDbSpace -SqlInstance localhost -Database db1, db2 | Where-Object { $_.SpaceUntilMaxSize.Gigabyte -lt 1 }\nReturns database files and free space information for the db1 and db2 on localhost where there is only 1GB left until the space is maxed out",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IncludeSystemDBs",
                           "If this switch is enabled, system databases will be processed. By default, only user databases are processed.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "A piped collection of database objects from Get-DbaDatabase",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbSpace [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [-IncludeSystemDBs] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbState",
        "Description":  "Gets some common \"states\" on databases:\n- \"RW\" options : READ_ONLY or READ_WRITE\n- \"Status\" options : ONLINE, OFFLINE, EMERGENCY, RESTORING\n- \"Access\" options : SINGLE_USER, RESTRICTED_USER, MULTI_USER\n\nReturns an object with SqlInstance, Database, RW, Status, Access",
        "Tags":  "Database",
        "Synopsis":  "Gets various options for databases, hereby called \"states\"",
        "Alias":  "Get-DbaDatabaseState",
        "Author":  "Simone Bizzotto (@niphold)",
        "CommandName":  "Get-DbaDbState",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbState",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbState -SqlInstance sqlserver2014a\nGets options for all databases of the sqlserver2014a instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbState -SqlInstance sqlserver2014a -Database HR, Accounting\nGets options for both HR and Accounting database of the sqlserver2014a instance\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbState -SqlInstance sqlserver2014a -Exclude HR\nGets options for all databases of the sqlserver2014a instance except HR\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027sqlserver2014a\u0027, \u0027sqlserver2014b\u0027 | Get-DbaDbState\nGets options for all databases of sqlserver2014a and sqlserver2014b instances",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Credential object used to connect to the SQL Server as a different user",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbState [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbStoredProcedure",
        "Description":  "Gets database Stored Procedures",
        "Tags":  [
                     "Database",
                     "StoredProcedure",
                     "Proc"
                 ],
        "Synopsis":  "Gets database Stored Procedures",
        "Alias":  "",
        "Author":  "Klaas Vandenberghe (@PowerDbaKlaas)",
        "CommandName":  "Get-DbaDbStoredProcedure",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbStoredProcedure -SqlInstance sql2016\nGets all database Stored Procedures\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbStoredProcedure -SqlInstance Server1 -Database db1\nGets the Stored Procedures for the db1 database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbStoredProcedure -SqlInstance Server1 -ExcludeDatabase db1\nGets the Stored Procedures for all databases except db1\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbStoredProcedure -SqlInstance Server1 -ExcludeSystemSp\nGets the Stored Procedures for all databases that are not system objects\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbStoredProcedure\nGets the Stored Procedures for the databases on Sql1 and Sql2/sqlexpress",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to SQL Server using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "To get Stored Procedures from specific database(s)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeSystemSp",
                           "This switch removes all system objects from the Stored Procedure collection",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbStoredProcedure [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-ExcludeSystemSp] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbTable",
        "Description":  "Shows table information around table row and data sizes and if it has any table type information.",
        "Tags":  [
                     "Database",
                     "Tables"
                 ],
        "Synopsis":  "Returns a summary of information on the tables",
        "Alias":  "Get-DbaTable",
        "Author":  "Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/",
        "CommandName":  "Get-DbaDbTable",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbTable",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance DEV01 -Database Test1\nReturn all tables in the Test1 database\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance DEV01 -Database MyDB -Table MyTable\nReturn only information on the table MyTable from the database MyDB\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance DEV01 -Table MyTable\nReturns information on table called MyTable if it exists in any database on the server, under any schema\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance DEV01 -Table dbo.[First.Table]\nReturns information on table called First.Table on schema dbo if it exists in any database on the server\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\u0027localhost\u0027,\u0027localhost\\namedinstance\u0027 | Get-DbaDbTable -Database DBA -Table Commandlog\nReturns information on the CommandLog table in the DBA database on both instances localhost and the named instance localhost\\namedinstance\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance DEV01 -Table \"[[DbName]]].[Schema.With.Dots].[`\"[Process]]`\"]\" -Verbose\nFor the instance Dev01 Returns information for a table named: \"[Process]\" in schema named: Schema.With.Dots in database named: [DbName]\r\nThe Table name, Schema name and Database name must be wrapped in square brackets [ ]\r\nSpecial charcters like \" must be escaped by a ` charcter.\r\nIn addition any actual instance of the ] character must be escaped by being duplicated.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IncludeSystemDBs",
                           "Switch parameter that when used will display system database information",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Table",
                           "Define a specific table you would like to query. You can specify up to three-part name like db.sch.tbl.\nIf the object has special characters please wrap them in square brackets [ ].\r\nUsing dbo.First.Table will try to find table named \u0027Table\u0027 on schema \u0027First\u0027 and database \u0027dbo\u0027.\r\nThe correct way to find table named \u0027First.Table\u0027 on schema \u0027dbo\u0027 is by passing dbo.[First.Table]\r\nAny actual usage of the ] must be escaped by duplicating the ] character.\r\nThe correct way to find a table Name] in schema Schema.Name is by passing [Schema.Name].[Name]]]",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbTable [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-IncludeSystemDBs] [[-Table] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbTrigger",
        "Description":  "Get all existing database triggers on one or more SQL instances.",
        "Tags":  [
                     "Database",
                     "Trigger"
                 ],
        "Synopsis":  "Get all existing database triggers on one or more SQL instances.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaDbTrigger",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbTrigger",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbTrigger -SqlInstance sql2017\nReturns all database triggers\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2017 -Database supa | Get-DbaDbTrigger\nReturns all triggers for database supa on sql2017\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbTrigger -SqlInstance sql2017 -Database supa\nReturns all triggers for database supa on sql2017",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "SqlCredential object used to connect to the SQL Server as a different user.",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allow pipedline input from Get-DbaDatabase",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/ca",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbTrigger [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbUdf",
        "Description":  "Gets database User Defined Functions",
        "Tags":  [
                     "Security",
                     "Database"
                 ],
        "Synopsis":  "Gets database User Defined Functions",
        "Alias":  "Get-DbaDatabaseUdf",
        "Author":  "Klaas Vandenberghe (@PowerDbaKlaas)",
        "CommandName":  "Get-DbaDbUdf",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbUdf -SqlInstance sql2016\nGets all database User Defined Functions\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbUdf -SqlInstance Server1 -Database db1\nGets the User Defined Functions for the db1 database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbUdf -SqlInstance Server1 -ExcludeDatabase db1\nGets the User Defined Functions for all databases except db1\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbUdf -SqlInstance Server1 -ExcludeSystemUdf\nGets the User Defined Functions for all databases that are not system objects (there can be 100+ system User Defined Functions in each DB)\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbUdf\nGets the User Defined Functions for the databases on Sql1 and Sql2/sqlexpress",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to SQL Server using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "To get User Defined Functions from specific database(s)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeSystemUdf",
                           "This switch removes all system objects from the UDF collection",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbUdf [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-ExcludeSystemUdf] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbUser",
        "Description":  "Gets database users",
        "Tags":  [
                     "Security",
                     "Database"
                 ],
        "Synopsis":  "Gets database users",
        "Alias":  "Get-DbaDatabaseUser",
        "Author":  "Klaas Vandenberghe (@PowerDbaKlaas)",
        "CommandName":  "Get-DbaDbUser",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbUser -SqlInstance sql2016\nGets all database users\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbUser -SqlInstance Server1 -Database db1\nGets the users for the db1 database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbUser -SqlInstance Server1 -ExcludeDatabase db1\nGets the users for all databases except db1\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbUser -SqlInstance Server1 -ExcludeSystemUser\nGets the users for all databases that are not system objects, like \u0027dbo\u0027, \u0027guest\u0027 or \u0027INFORMATION_SCHEMA\u0027\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbUser\nGets the users for the databases on Sql1 and Sql2/sqlexpress",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to SQL Server using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "To get users from specific database(s)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeSystemUser",
                           "This switch removes all system objects from the user collection",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbUser [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-ExcludeSystemUser] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbView",
        "Description":  "Gets database views for each SqlInstance.",
        "Tags":  [
                     "Security",
                     "Database"
                 ],
        "Synopsis":  "Gets database views for each SqlInstance.",
        "Alias":  "Get-DbaDatabaseView",
        "Author":  "Klaas Vandenberghe (@PowerDbaKlaas)",
        "CommandName":  "Get-DbaDbView",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbView -SqlInstance sql2016\nGets all database views\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbView -SqlInstance Server1 -Database db1\nGets the views for the db1 database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbView -SqlInstance Server1 -ExcludeDatabase db1\nGets the views for all databases except db1\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbView -SqlInstance Server1 -ExcludeSystemView\nGets the views for all databases that are not system objects (there can be 400+ system views in each DB)\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbView\nGets the views for the databases on Sql1 and Sql2/sqlexpress",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "To get views from specific database(s) - this list is auto populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeSystemView",
                           "This switch removes all system objects from the view collection.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbView [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-ExcludeSystemView] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDbVirtualLogFile",
        "Description":  "Having a transaction log file with too many virtual log files (VLFs) can hurt database performance.\n\nToo many VLFs can cause transaction log backups to slow down and can also slow down database recovery and, in extreme cases, even affect insert/update/delete performance.\n\nReferences:\nhttp://www.sqlskills.com/blogs/kimberly/transaction-log-vlfs-too-many-or-too-few/\nhttp://blogs.msdn.com/b/saponsqlserver/archive/2012/02/22/too-many-virtual-log-files-vlfs-can-cause-slow-database-recovery.aspx\n\nIf you\u0027ve got a high number of VLFs, you can use Expand-SqlTLogResponsibly to reduce the number.",
        "Tags":  [
                     "VLF",
                     "Database",
                     "LogFile"
                 ],
        "Synopsis":  "Returns database virtual log file information for database files on a SQL instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaDbVirtualLogFile",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDbVirtualLogFile",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbVirtualLogFile -SqlInstance sqlcluster\nReturns all user database virtual log file details for the sqlcluster instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbVirtualLogFile -SqlInstance sqlserver | Group-Object -Property Database | Where-Object Count -gt 50\nReturns user databases that have 50 or more VLFs.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027sqlserver\u0027,\u0027sqlcluster\u0027 | Get-DbaDbVirtualLogFile\nReturns all VLF information for the sqlserver and sqlcluster SQL Server instances. Processes data via the pipeline.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbVirtualLogFile -SqlInstance sqlcluster -Database db1, db2\nReturns the VLF counts for the db1 and db2 databases on sqlcluster.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IncludeSystemDBs",
                           "If this switch is enabled, system database information will be displayed.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDbVirtualLogFile [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-IncludeSystemDBs] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDefaultPath",
        "Description":  "Gets the default SQL Server paths for data, logs and backups",
        "Tags":  "Config",
        "Synopsis":  "Gets the default SQL Server paths for data, logs and backups",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaDefaultPath",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDefaultPath",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDefaultPath -SqlInstance sql01\\sharepoint\nReturns the default file paths for sql01\\sharepoint\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\"\nPS C:\\\u003e $servers | Get-DbaDefaultPath\nReturns the default file paths for \"sql2014\",\"sql2016\" and \"sqlcluster\\sharepoint\"",
        "Params":  [
                       [
                           "SqlInstance",
                           "TThe target SQL Server instance or instances.",
                           "ServerInstance,Instance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDefaultPath [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDependency",
        "Description":  "This function recursively finds all objects that depends on the input.\nIt will then retrieve rich information from them, including their creation scripts and the order in which it should be applied.\n\nBy using the \u0027Parents\u0027 switch, the function will instead retrieve all items that the input depends on (including their creation scripts).\n\nFor more details on dependency, see:\nhttps://technet.microsoft.com/en-us/library/ms345449(v=sql.105).aspx",
        "Tags":  [
                     "Database",
                     "Dependent",
                     "Dependency",
                     "Object"
                 ],
        "Synopsis":  "Finds object dependencies and their relevant creation scripts.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaDependency",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDependency",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$table = (Get-DbaDatabase -SqlInstance sql2012 -Database Northwind).tables | Where Name -eq Customers\nPS C:\\\u003e $table | Get-DbaDependency\nReturns everything that depends on the \"Customers\" table",
        "Params":  [
                       [
                           "InputObject",
                           "The SMO object to parse",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "AllowSystemObjects",
                           "Normally, system objects are ignored by this function as dependencies.\r\nThis switch overrides that behavior.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Parents",
                           "Causes the function to retrieve all objects that the input depends on, rather than retrieving everything that depends on the input.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IncludeSelf",
                           "Includes the object whose dependencies are retrieves itself.\r\nUseful when exporting an entire logic structure in order to recreate it in another database.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDependency [[-InputObject] \u003cObject\u003e] [-AllowSystemObjects] [-Parents] [-IncludeSelf] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDeprecatedFeature",
        "Description":  "Displays information relating to deprecated features for SQL Server 2005 and above.",
        "Tags":  "Deprecated",
        "Synopsis":  "Displays information relating to deprecated features for SQL Server 2005 and above.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaDeprecatedFeature",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDeprecatedFeature",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDeprecatedFeature -SqlInstance sql2008, sqlserver2012\nCheck deprecated features for all databases on the servers sql2008 and sqlserver2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDeprecatedFeature -SqlInstance sql2008\nCheck deprecated features on server sql2008.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternate Windows or SQL Login Authentication. Accepts credential objects (Get-Credential).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDeprecatedFeature [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDetachedDatabaseInfo",
        "Description":  "Gathers the following information from detached database files: database name, SQL Server version (compatibility level), collation, and file structure.\n\n\"Data files\" and \"Log file\" report the structure of the data and log files as they were when the database was detached. \"Database version\" is the compatibility level.\n\nMDF files are most easily read by using a SQL Server to interpret them. Because of this, you must specify a SQL Server and the path must be relative to the SQL Server.",
        "Tags":  [
                     "Database",
                     "Detach"
                 ],
        "Synopsis":  "Get detailed information about detached SQL Server database files.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaDetachedDatabaseInfo",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDetachedDatabaseInfo",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDetachedDatabaseInfo -SqlInstance sql2016 -Path M:\\Archive\\mydb.mdf\nReturns information about the detached database file M:\\Archive\\mydb.mdf using the SQL Server instance sql2016. The M drive is relative to the SQL Server instance.",
        "Params":  [
                       [
                           "SqlInstance",
                           "Source SQL Server. This instance must be online and is required to parse the information contained with in the detached database file.\nThis function will not attach the database file, it will only use SQL Server to read its contents.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "Specifies the path to the MDF file to be read. This path must be readable by the SQL Server service account. Ideally, the MDF will be located on the SQL Server itself, or on a network share to which \r\nthe SQL Server service account has access.",
                           "Mdf",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Get-DbaDetachedDatabaseInfo [-SqlInstance] \u003cDbaInstanceParameter\u003e [-Path] \u003cString\u003e [[-SqlCredential] \u003cPSCredential\u003e] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDiskSpace",
        "Description":  "Returns a custom object with server name, name of disk, label of disk, total size, free size, percent free, block size and filesystem.\n\nBy default, this function only shows drives of types 2 and 3 (removable disk and local disk).\n\nRequires Windows administrator access on SQL Servers",
        "Tags":  [
                     "Storage",
                     "Disk"
                 ],
        "Synopsis":  "Displays disk information for all local disk on a server.",
        "Alias":  "Get-DiskSpace",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net | Jakob Bindslet",
        "CommandName":  "Get-DbaDiskSpace",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaDiskSpace",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDiskSpace -ComputerName srv0042\nGet disk space for the server srv0042.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDiskSpace -ComputerName srv0042 -Unit MB\nGet disk space for the server srv0042 and displays in megabytes (MB).\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDiskSpace -ComputerName srv0042, srv0007 -Unit TB\nGet disk space from two servers and displays in terabytes (TB).\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDiskSpace -ComputerName srv0042 -Force\nGet all disk and volume space information.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDiskSpace -ComputerName srv0042 -ExcludeDrive \u0027C:\\\u0027\nGet all disk and volume space information.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer. Defaults to localhost.",
                           "ServerInstance,SqlInstance,SqlServer",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Credential object used to connect to the computer as a different user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Unit",
                           "This parameter has been deprecated and will be removed in 1.0.0\r\nAll properties previously generated through this command are present at the same time, but hidden by default.",
                           "",
                           false,
                           "false",
                           "GB"
                       ],
                       [
                           "CheckForSql",
                           "If this switch is enabled, disks will be checked for SQL Server data and log files. Windows Authentication is always used for this.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDrive",
                           "Filter out drives - format is C:\\",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CheckFragmentation",
                           "If this switch is enabled, fragmentation of all filesystems will be checked.\nThis will increase the runtime of the function by seconds or even minutes per volume.",
                           "Detailed,AllDrives",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "Enabling this switch will cause the command to include ALL drives.\r\nBy default, only local disks and removable disks are shown, and hidden volumes are excluded.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDiskSpace [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Unit] \u003cString\u003e] [-CheckForSql] [[-SqlCredential] \u003cPSCredential\u003e] [[-ExcludeDrive] \u003cString[]\u003e] [-CheckFragmentation] [-Force] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaDump",
        "Description":  "The type of dump included in the search include minidump, all-thread dump, or a full dump.  The files have an extendion of .mdmp.",
        "Tags":  [
                     "Engine",
                     "Corruption"
                 ],
        "Synopsis":  "Locate a SQL Server that has generated any memory dump files.",
        "Alias":  "",
        "Author":  "Garry Bargsley (@gbargsley), http://blog.garrybargsley.com",
        "CommandName":  "Get-DbaDump",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaDump",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDump -SqlInstance sql2016\nShows the detailed information for memory dump(s) located on sql2016 instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDump -SqlInstance sql2016 -SqlCredential sqladmin\nShows the detailed information for memory dump(s) located on sql2016 instance. Logs into the SQL Server using the SQL login \u0027sqladmin\u0027",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaDump [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaEndpoint",
        "Description":  "Returns endpoint objects from a SQL Server instance.",
        "Tags":  "Endpoint",
        "Synopsis":  "Returns endpoint objects from a SQL Server instance.",
        "Alias":  "",
        "Author":  "Garry Bargsley (@gbargsley), http://blog.garrybargsley.com",
        "CommandName":  "Get-DbaEndpoint",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaEndpoint",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaEndpoint -SqlInstance localhost\nReturns all endpoints on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaEndpoint -SqlInstance localhost, sql2016\nReturns all endpoints for the local and sql2016 SQL Server instances",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Endpoint",
                           "Return only specific endpoints.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Type",
                           "Return only specific types of endpoints. Options include: DatabaseMirroring, ServiceBroker, Soap, and TSql.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaEndpoint [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Endpoint \u003cString[]\u003e] [-Type \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaErrorLog",
        "Description":  "Gets the \"SQL Error Log\" of an instance. Returns all 10 error logs by default.",
        "Tags":  [
                     "Instance",
                     "ErrorLog"
                 ],
        "Synopsis":  "Gets the \"SQL Error Log\" of an instance",
        "Alias":  "Get-DbaLog",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaErrorLog",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaErrorLog",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaErrorLog -SqlInstance sql01\\sharepoint\nReturns every log entry from sql01\\sharepoint SQL Server instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaErrorLog -SqlInstance sql01\\sharepoint -LogNumber 3, 6\nReturns all log entries for log number 3 and 6 on sql01\\sharepoint SQL Server instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaErrorLog -SqlInstance sql01\\sharepoint -Source Logon\nReturns every log entry, with a source of Logon, from sql01\\sharepoint SQL Server instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaErrorLog -SqlInstance sql01\\sharepoint -LogNumber 3 -Text \"login failed\"\nReturns every log entry for log number 3, with \"login failed\" in the text, from sql01\\sharepoint SQL Server instance.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\"\nPS C:\\\u003e $servers | Get-DbaErrorLog -LogNumber 0\nReturns the most recent SQL Server error logs for \"sql2014\",\"sql2016\" and \"sqlcluster\\sharepoint\"\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaErrorLog -SqlInstance sql01\\sharepoint -After \u00272016-11-14 00:00:00\u0027\nReturns every log entry found after the date 14 November 2016 from sql101\\sharepoint SQL Server instance.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaErrorLog -SqlInstance sql01\\sharepoint -Before \u00272016-08-16 00:00:00\u0027\nReturns every log entry found before the date 16 August 2016 from sql101\\sharepoint SQL Server instance.",
        "Params":  [
                       [
                           "SqlInstance",
                           "TThe target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "LogNumber",
                           "An Int32 value that specifies the index number of the error log required.\r\nError logs are listed 0 through 99, where 0 is the current error log and 99 is potential oldest log file.\nSQL Server errorlog rollover defaults to 6, but can be increased to 99. https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/scm-services-configure-sql-server-error-logs",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Source",
                           "Filter results based on the Source of the error (e.g. Logon, Server, etc.)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Text",
                           "Filter results based on a pattern of text (e.g. \"login failed\", \"error: 12345\").",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "After",
                           "Filter the results based on datetime value.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Before",
                           "Filter the results based on datetime value.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaErrorLog [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-LogNumber] \u003cInt32[]\u003e] [[-Source] \u003cObject[]\u003e] [[-Text] \u003cString\u003e] [[-After] \u003cDateTime\u003e] [[-Before] \u003cDateTime\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaErrorLogConfig",
        "Description":  "Pulls the configuration for the ErrorLog on a given SQL Server instance.\n\nIncludes error log path, number of log files configured and size (SQL Server 2012+ only)",
        "Tags":  [
                     "Instance",
                     "ErrorLog"
                 ],
        "Synopsis":  "Pulls the configuration for the ErrorLog on a given SQL Server instance",
        "Alias":  "",
        "Author":  "Shawn Melton (@wsmelton), https://wsmelton.github.io",
        "CommandName":  "Get-DbaErrorLogConfig",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaErrorLogConfig",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaErrorLogConfig -SqlInstance server2017,server2014\nReturns error log configuration for server2017 and server2014",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaErrorLogConfig [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaEstimatedCompletionTime",
        "Description":  "Gets execution and estimated completion time information for queries\n\nPercent complete will show for the following commands\n\nALTER INDEX REORGANIZE\nAUTO_SHRINK option with ALTER DATABASE\nBACKUP DATABASE\nDBCC CHECKDB\nDBCC CHECKFILEGROUP\nDBCC CHECKTABLE\nDBCC INDEXDEFRAG\nDBCC SHRINKDATABASE\nDBCC SHRINKFILE\nRECOVERY\nRESTORE DATABASE\nROLLBACK\nTDE ENCRYPTION\n\nFor additional information, check out https://blogs.sentryone.com/loriedwards/patience-dm-exec-requests/ and https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-exec-requests-transact-sql",
        "Tags":  "Database",
        "Synopsis":  "Gets execution and estimated completion time information for queries",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaEstimatedCompletionTime",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaEstimatedCompletionTime",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaEstimatedCompletionTime -SqlInstance sql2016\nGets estimated completion times for queries performed against the entire server\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaEstimatedCompletionTime -SqlInstance sql2016 | Select *\nGets estimated completion times for queries performed against the entire server PLUS the SQL query text of each command\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaEstimatedCompletionTime -SqlInstance sql2016 | Where-Object { $_.Text -match \u0027somequerytext\u0027 }\nGets results for commands whose queries only match specific text (match is like LIKE but way more powerful)\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaEstimatedCompletionTime -SqlInstance sql2016 -Database Northwind,pubs,Adventureworks2014\nGets estimated completion times for queries performed against the Northwind, pubs, and Adventureworks2014 databases",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "SqlCredential object used to connect to the SQL Server as a different user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaEstimatedCompletionTime [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaExecutionPlan",
        "Description":  "Gets execution plans and metadata. Can pipe to Export-DbaExecutionPlan\n\nThanks to following for the queries:\nhttps://www.simple-talk.com/sql/t-sql-programming/dmvs-for-query-plan-metadata/\nhttp://www.scarydba.com/2017/02/13/export-plans-cache-sqlplan-file/",
        "Tags":  "Performance",
        "Synopsis":  "Gets execution plans and metadata",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaExecutionPlan",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaExecutionPlan",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaExecutionPlan -SqlInstance sqlserver2014a\nGets all execution plans on  sqlserver2014a\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaExecutionPlan -SqlInstance sqlserver2014a -Database db1, db2 -SinceLastExecution \u00272016-07-01 10:47:00\u0027\nGets all execution plans for databases db1 and db2 on sqlserver2014a since July 1, 2016 at 10:47 AM.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaExecutionPlan -SqlInstance sqlserver2014a, sql2016 -Exclude db1 | Format-Table\nGets execution plan info for all databases except db1 on sqlserver2014a and sql2016 and makes the output pretty\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaExecutionPlan -SqlInstance sql2014 -Database AdventureWorks2014, pubs -Force\nGets super detailed information for execution plans on only for AdventureWorks2014 and pubs\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$servers = \"sqlserver2014a\",\"sql2016t\"\nPS C:\\\u003e $servers | Get-DbaExecutionPlan -Force\nGets super detailed information for execution plans on sqlserver2014a and sql2016",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Credential object used to connect to the SQL Server as a different user",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Return execution plans and metadata for only specific databases.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Return execution plans and metadata for all but these specific databases",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SinceCreation",
                           "Datetime object used to narrow the results to a date",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SinceLastExecution",
                           "Datetime object used to narrow the results to a date",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeEmptyQueryPlan",
                           "Exclude results with empty query plan",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "Returns a ton of raw information about the execution plans",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaExecutionPlan [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-SinceCreation] \u003cDateTime\u003e] [[-SinceLastExecution] \u003cDateTime\u003e] [-ExcludeEmptyQueryPlan] [-Force] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaFeature",
        "Description":  "Runs the SQL Server feature discovery report (setup.exe /Action=RunDiscovery)\n\nInspired by Dave Mason\u0027s (@BeginTry) post at\nhttps://itsalljustelectrons.blogspot.be/2018/04/SQL-Server-Discovery-Report.html\n\nAssumptions:\n1. The sub-folder \"Microsoft SQL Server\" exists in $env:ProgramFiles,\neven if SQL was installed to a non-default path. This has been\nverified on SQL 2008R2 and SQL 2012. Further verification may be needed.\n2. The discovery report displays installed components for the version of SQL\nServer associated with setup.exe, along with installed components of all\nlesser versions of SQL Server that are installed.",
        "Tags":  [
                     "Feature",
                     "Component"
                 ],
        "Synopsis":  "Runs the SQL Server feature discovery report (setup.exe /Action=RunDiscovery)",
        "Alias":  "Get-DbaSqlFeature",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaFeature",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaFeature",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaFeature -ComputerName sql2017, sql2016, sql2005\nGets all SQL Server features for all instances on sql2017, sql2016 and sql2005.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaFeature -Verbose\nGets all SQL Server features for all instances on localhost. Outputs to screen if no instances are found.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaFeature -ComputerName sql2017 -Credential ad\\sqldba\nGets all SQL Server features for all instances on sql2017 using the ad\\sqladmin credential (which has access to the Windows Server).",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer. If the target is not localhost, it must have PowerShell remoting enabled.\nNote that this is not the SqlInstance, but rather the ComputerName",
                           "",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to servers using alternative credentials. To use:\n$cred = Get-Credential, then pass $cred object to the -Credential parameter.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaFeature [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaFile",
        "Description":  "This command searches all specified directories, allowing a DBA to see file information on a server without direct access\n\nYou can filter by extension using the -FileType parameter. By default, the default data directory will be returned. You can provide and additional paths to search using the -Path parameter.\n\nThanks to serg-52 for the query:  https://www.sqlservercentral.com/Forums/Topic1642213-391-1.aspx",
        "Tags":  "Discovery",
        "Synopsis":  "Get-DbaFile finds files in any directory specified on a remote SQL Server",
        "Alias":  "",
        "Author":  "Brandon Abshire, netnerds.net",
        "CommandName":  "Get-DbaFile",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaFile",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaFile -SqlInstance sqlserver2014a -Path E:\\Dir1\nLogs into the SQL Server \"sqlserver2014a\" using Windows credentials and searches E:\\Dir for all files\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaFile -SqlInstance sqlserver2014a -SqlCredential $cred -Path \u0027E:\\sql files\u0027\nLogs into the SQL Server \"sqlserver2014a\" using alternative credentials and returns all files in \u0027E:\\sql files\u0027\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$all = Get-DbaDefaultPath -SqlInstance sql2014\nPS C:\\\u003e Get-DbaFile -SqlInstance sql2014 -Path $all.Data, $all.Log, $all.Backup -Depth 3\nReturns the files in the default data, log and backup directories on sql2014, 3 directories deep (recursively).\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaFile -SqlInstance sql2014 -Path \u0027E:\\Dir1\u0027, \u0027E:\\Dir2\u0027\nReturns the files in \"E:\\Dir1\" and \"E:Dir2\" on sql2014\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaFile -SqlInstance sql2014, sql2016 -Path \u0027E:\\Dir1\u0027 -FileType fsf, mld\nFinds files in E:\\Dir1 ending with \".fsf\" and \".mld\" for both the servers sql2014 and sql2016.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to servers using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "Used to specify extra directories to search in addition to the default data directory.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "FileType",
                           "Used to specify filter by filetype. No dot required, just pass the extension.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Depth",
                           "Used to specify recursive folder depth.  Default is 1, non-recursive.",
                           "",
                           false,
                           "false",
                           "1"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaFile [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Path] \u003cString[]\u003e] [[-FileType] \u003cString[]\u003e] [[-Depth] \u003cInt32\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaFilestream",
        "Description":  "Returns the status of Filestream on specified SQL Server for both the Service and Instance levels.",
        "Tags":  "Filestream",
        "Synopsis":  "Returns the status of Filestream on specified SQL Server for both the Service and Instance levels.",
        "Alias":  "",
        "Author":  "Stuart Moore ( @napalmgram ) | Chrissy LeMaire ( @cl )",
        "CommandName":  "Get-DbaFilestream",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaFilestream",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaFilestream -SqlInstance server1\\instance2\nWill return the status of Filestream configuration for the service and instance server1\\instance2\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaFilestream -SqlInstance server1\\instance2 -SqlCredential sqladmin\nPrompts for the password to the SQL Login \"sqladmin\" then returns the status of Filestream configuration for the service and instance server1\\instance2",
        "Params":  [
                       [
                           "SqlInstance",
                           "SQL Server name or SMO object representing the SQL Server to connect to. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Credential",
                           "Login to the target Windows server using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaFilestream [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaForceNetworkEncryption",
        "Description":  "Gets Force Encryption settings for a SQL Server instance. Note that this requires access to the Windows Server - not the SQL instance itself.\n\nThis setting is found in Configuration Manager.",
        "Tags":  "Certificate",
        "Synopsis":  "Gets Force Encryption settings for a SQL Server instance",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaForceNetworkEncryption",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaForceNetworkEncryption",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaForceNetworkEncryption\nGets Force Encryption properties on the default (MSSQLSERVER) instance on localhost - requires (and checks for) RunAs admin.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaForceNetworkEncryption -SqlInstance sql01\\SQL2008R2SP2\nGets Force Network Encryption for the SQL2008R2SP2 on sql01. Uses Windows Credentials to both login and view the registry.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Defaults to localhost.",
                           "ServerInstance,SqlServer,ComputerName",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to the computer (not sql instance) using alternative Windows credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaForceNetworkEncryption [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaHelpIndex",
        "Description":  "This function will return detailed information on indexes (and optionally statistics) for all indexes in a database, or a given index should one be passed along.\nAs this uses SQL Server DMVs to access the data it will only work in 2005 and up (sorry folks still running SQL Server 2000).\nFor performance reasons certain statistics information will not be returned from SQL Server 2005 if an ObjectName is not provided.\n\nThe data includes:\n- ObjectName: the table containing the index\n- IndexType: clustered/non-clustered/columnstore and whether the index is unique/primary key\n- KeyColumns: the key columns of the index\n- IncludeColumns: any include columns in the index\n- FilterDefinition: any filter that may have been used in the index\n- DataCompression: row/page/none depending upon whether or not compression has been used\n- IndexReads: the number of reads of the index since last restart or index rebuild\n- IndexUpdates: the number of writes to the index since last restart or index rebuild\n- SizeKB: the size the index in KB\n- IndexRows: the number of the rows in the index (note filtered indexes will have fewer rows than exist in the table)\n- IndexLookups: the number of lookups that have been performed (only applicable for the heap or clustered index)\n- MostRecentlyUsed: when the index was most recently queried (default to 1900 for when never read)\n- StatsSampleRows: the number of rows queried when the statistics were built/rebuilt (not included in SQL Server 2005 unless ObjectName is specified)\n- StatsRowMods: the number of changes to the statistics since the last rebuild\n- HistogramSteps: the number of steps in the statistics histogram (not included in SQL Server 2005 unless ObjectName is specified)\n- StatsLastUpdated: when the statistics were last rebuilt (not included in SQL Server 2005 unless ObjectName is specified)",
        "Tags":  "Index",
        "Synopsis":  "Returns size, row and configuration information for indexes in databases.",
        "Alias":  "",
        "Author":  "Nic Cain, https://sirsql.net/",
        "CommandName":  "Get-DbaHelpIndex",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaHelpIndex",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaHelpIndex -SqlInstance localhost -Database MyDB\nReturns information on all indexes on the MyDB database on the localhost.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaHelpIndex -SqlInstance localhost -Database MyDB,MyDB2\nReturns information on all indexes on the MyDB \u0026 MyDB2 databases.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaHelpIndex -SqlInstance localhost -Database MyDB -ObjectName dbo.Table1\nReturns index information on the object dbo.Table1 in the database MyDB.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaHelpIndex -SqlInstance localhost -Database MyDB -ObjectName dbo.Table1 -IncludeStats\nReturns information on the indexes and statistics for the table dbo.Table1 in the MyDB database.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaHelpIndex -SqlInstance localhost -Database MyDB -ObjectName dbo.Table1 -IncludeDataTypes\nReturns the index information for the table dbo.Table1 in the MyDB database, and includes the data types for the key and include columns.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaHelpIndex -SqlInstance localhost -Database MyDB -ObjectName dbo.Table1 -Raw\nReturns the index information for the table dbo.Table1 in the MyDB database, and returns the numerical data without localized separators.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaHelpIndex -SqlInstance localhost -Database MyDB -IncludeStats -Raw\nReturns the index information for all indexes in the MyDB database as well as their statistics, and formats the numerical data without localized separators.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eGet-DbaHelpIndex -SqlInstance localhost -Database MyDB -IncludeFragmentation\nReturns the index information for all indexes in the MyDB database as well as their fragmentation\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2017 -Database MyDB | Get-DbaHelpIndex\nReturns the index information for all indexes in the MyDB database",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process. This list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude. This list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows piping from Get-DbaDatabase",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "ObjectName",
                           "The name of a table for which you want to obtain the index information. If the two part naming convention for an object is not used it will use the default schema for the executing user. If not \r\npassed it will return data on all indexes in a given database.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IncludeStats",
                           "If this switch is enabled, statistics as well as indexes will be returned in the output (statistics information such as the StatsRowMods will always be returned for indexes).",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IncludeDataTypes",
                           "If this switch is enabled, the output will include the data type of each column that makes up a part of the index definition (key and include columns).",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Raw",
                           "If this switch is enabled, results may be less user-readable but more suitable for processing by other code.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IncludeFragmentation",
                           "If this switch is enabled, the output will include fragmentation information.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaHelpIndex [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [[-ObjectName] \u003cString\u003e] [-IncludeStats] [-IncludeDataTypes] [-Raw] [-IncludeFragmentation] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaInstanceProperty",
        "Description":  "The Get-DbaInstanceProperty command gets SQL Server instance properties from the SMO object sqlserver.",
        "Tags":  [
                     "Instance",
                     "Configure",
                     "Configuration"
                 ],
        "Synopsis":  "Gets SQL Server instance properties of one or more instance(s) of SQL Server.",
        "Alias":  "Get-DbaSqlInstanceProperty",
        "Author":  "Klaas Vandenberghe (@powerdbaklaas)",
        "CommandName":  "Get-DbaInstanceProperty",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaInstanceProperty",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaInstanceProperty -SqlInstance localhost\nReturns SQL Server instance properties on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaInstanceProperty -SqlInstance sql2, sql4\\sqlexpress\nReturns SQL Server instance properties on default instance on sql2 and sqlexpress instance on sql4\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027sql2\u0027,\u0027sql4\u0027 | Get-DbaInstanceProperty\nReturns SQL Server instance properties on sql2 and sql4\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaInstanceProperty -SqlInstance sql2,sql4 -InstanceProperty DefaultFile\nReturns SQL Server instance property DefaultFile on instance sql2 and sql4\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaInstanceProperty -SqlInstance sql2,sql4 -ExcludeInstanceProperty DefaultFile\nReturns all SQL Server instance properties except DefaultFile on instance sql2 and sql4\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaInstanceProperty -SqlInstance sql2 -SqlCredential $cred\nConnects using sqladmin credential and returns SQL Server instance properties from sql2",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InstanceProperty",
                           "SQL Server instance property(ies) to include.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeInstanceProperty",
                           "SQL Server instance property(ies) to exclude.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaInstanceProperty [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-InstanceProperty \u003cObject[]\u003e] [-ExcludeInstanceProperty \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaInstanceUserOption",
        "Description":  "The Get-DbaInstanceUserOption command gets SQL Instance user options from the SMO object sqlserver.",
        "Tags":  [
                     "Instance",
                     "Configure",
                     "UserOption"
                 ],
        "Synopsis":  "Gets SQL Instance user options of one or more instance(s) of SQL Server.",
        "Alias":  "Get-DbaSqlInstanceUserOption",
        "Author":  "Klaas Vandenberghe (@powerdbaklaas)",
        "CommandName":  "Get-DbaInstanceUserOption",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaInstanceUserOption",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaInstanceUserOption -SqlInstance localhost\nReturns SQL Instance user options on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaInstanceUserOption -SqlInstance sql2, sql4\\sqlexpress\nReturns SQL Instance user options on default instance on sql2 and sqlexpress instance on sql4\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027sql2\u0027,\u0027sql4\u0027 | Get-DbaInstanceUserOption\nReturns SQL Instance user options on sql2 and sql4",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.\r\nThis can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaInstanceUserOption [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaIoLatency",
        "Description":  "This command is based off of Paul Randal\u0027s post \"Advanced SQL Server performance tuning\"\n\nReturns both raw and aggregate information\n\nReference:  https://www.sqlskills.com/blogs/paul/how-to-examine-io-subsystem-latencies-from-within-sql-server/\n            https://www.sqlskills.com/blogs/paul/capturing-io-latencies-period-time/",
        "Tags":  "IOLatency",
        "Synopsis":  "Displays IO subsystem latency statistics from sys.dm_io_virtual_file_stats.  Works on SQL Server 2005 and above.",
        "Alias":  "",
        "Author":  "Patrick Flynn (@sqllensman)",
        "CommandName":  "Get-DbaIoLatency",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaIoLatency",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaIoLatency -SqlInstance sql2008, sqlserver2012\nGet IO subsystem latency statistics for servers sql2008 and sqlserver2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$output = Get-DbaIoLatency -SqlInstance sql2008 | Select * | ConvertTo-DbaDataTable\nCollects all IO subsystem latency statistics on server sql2008 into a Data Table.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027sql2008\u0027,\u0027sqlserver2012\u0027 | Get-DbaIoLatency\nGet IO subsystem latency statistics for servers sql2008 and sqlserver2012 via pipline\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaIoLatency -SqlInstance sql2008 -SqlCredential $cred\nConnects using sqladmin credential and returns IO subsystem latency statistics from sql2008",
        "Params":  [
                       [
                           "SqlInstance",
                           "The SQL Server instance. Server version must be SQL Server version 2008 or higher.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaIoLatency [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaLastBackup",
        "Description":  "Retrieves and compares the date/time for the last known backups, as well as the creation date/time for the database.\n\nDefault output includes columns Server, Database, RecoveryModel, LastFullBackup, LastDiffBackup, LastLogBackup, SinceFull, SinceDiff, SinceLog, Status, DatabaseCreated, DaysSinceDbCreated.",
        "Tags":  [
                     "DisasterRecovery",
                     "Backup"
                 ],
        "Synopsis":  "Get date/time for last known backups of databases.",
        "Alias":  "",
        "Author":  "Klaas Vandenberghe (@PowerDBAKlaas)",
        "CommandName":  "Get-DbaLastBackup",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaLastBackup",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaLastBackup -SqlInstance ServerA\\sql987\nReturns a custom object displaying Server, Database, RecoveryModel, LastFullBackup, LastDiffBackup, LastLogBackup, SinceFull, SinceDiff, SinceLog, Status, DatabaseCreated, DaysSinceDbCreated\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaLastBackup -SqlInstance ServerA\\sql987\nReturns a custom object with Server name, Database name, and the date the last time backups were performed.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaLastBackup -SqlInstance ServerA\\sql987 | Select *\nReturns a custom object with Server name, Database name, and the date the last time backups were performed, and also recoverymodel and calculations on how long ago backups were taken and what the \r\nstatus is.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaLastBackup -SqlInstance ServerA\\sql987 | Select * | Out-Gridview\nReturns a gridview displaying Server, Database, RecoveryModel, LastFullBackup, LastDiffBackup, LastLogBackup, SinceFull, SinceDiff, SinceLog, Status, DatabaseCreated, DaysSinceDbCreated.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies one or more database(s) to process. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies one or more database(s) to exclude from processing.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "If this switch is enabled exceptions will be thrown to the caller, which will need to perform its own exception processing. Otherwise, the function will try to catch the exception, interpret it and \r\nprovide a friendly error message.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaLastBackup [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaLastGoodCheckDb",
        "Description":  "Retrieves and compares the date/time for the last known good DBCC CHECKDB, as well as the creation date/time for the database.\n\nThis function supports SQL Server 2005 and higher.\n\nPlease note that this script uses the DBCC DBINFO() WITH TABLERESULTS. DBCC DBINFO has several known weak points, such as:\n- DBCC DBINFO is an undocumented feature/command.\n- The LastKnowGood timestamp is updated when a DBCC CHECKFILEGROUP is performed.\n- The LastKnowGood timestamp is updated when a DBCC CHECKDB WITH PHYSICAL_ONLY is performed.\n- The LastKnowGood timestamp does not get updated when a database in READ_ONLY.\n\nAn empty ($null) LastGoodCheckDb result indicates that a good DBCC CHECKDB has never been performed.\n\nSQL Server 2008R2 has a \"bug\" that causes each databases to possess two dbi_dbccLastKnownGood fields, instead of the normal one.\n\nThis script will only display this function to only display the newest timestamp. If -Verbose is specified, the function will announce every time more than one dbi_dbccLastKnownGood fields is encountered.",
        "Tags":  [
                     "CHECKDB",
                     "Database"
                 ],
        "Synopsis":  "Get date/time for last known good DBCC CHECKDB",
        "Alias":  "",
        "Author":  "Jakob Bindslet ([email protected])",
        "CommandName":  "Get-DbaLastGoodCheckDb",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaLastGoodCheckDb",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaLastGoodCheckDb -SqlInstance ServerA\\sql987\nReturns a custom object displaying Server, Database, DatabaseCreated, LastGoodCheckDb, DaysSinceDbCreated, DaysSinceLastGoodCheckDb, Status and DataPurityEnabled\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaLastGoodCheckDb -SqlInstance ServerA\\sql987 -SqlCredential sqladmin | Format-Table -AutoSize\nReturns a formatted table displaying Server, Database, DatabaseCreated, LastGoodCheckDb, DaysSinceDbCreated, DaysSinceLastGoodCheckDb, Status and DataPurityEnabled. Authenticates using SQL Server \r\nauthentication.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaLastGoodCheckDb -SqlInstance sql2016 -ExcludeDatabase \"TempDB\" | Format-Table -AutoSize\nReturns a formatted table displaying Server, Database, DatabaseCreated, LastGoodCheckDb, DaysSinceDbCreated, DaysSinceLastGoodCheckDb, Status and DataPurityEnabled. All databases except for \"TempDB\" \r\nwill be displayed in the output.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Defaults to localhost.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies one or more database(s) to process. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies one or more database(s) to exclude from processing.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaLastGoodCheckDb [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaLatchStatistic",
        "Description":  "This command is based off of Paul Randal\u0027s post \"Advanced SQL Server performance tuning\"\n\nReturns:\n        LatchClass\n        WaitSeconds\n        WaitCount\n        Percentage\n        AverageWaitSeconds\n        URL\n\nReference:  https://www.sqlskills.com/blogs/paul/advanced-performance-troubleshooting-waits-latches-spinlocks/\n            https://www.sqlskills.com/blogs/paul/most-common-latch-classes-and-what-they-mean/",
        "Tags":  [
                     "LatchStatistics",
                     "Waits"
                 ],
        "Synopsis":  "Displays latch statistics from sys.dm_os_latch_stats",
        "Alias":  "",
        "Author":  "Patrick Flynn (@sqllensman)",
        "CommandName":  "Get-DbaLatchStatistic",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaLatchStatistic",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaLatchStatistic -SqlInstance sql2008, sqlserver2012\nCheck latch statistics for servers sql2008 and sqlserver2012\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaLatchStatistic -SqlInstance sql2008 -Threshold 98\nCheck latch statistics on server sql2008 for thresholds above 98%\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$output = Get-DbaLatchStatistic -SqlInstance sql2008 -Threshold 100 | Select * | ConvertTo-DbaDataTable\nCollects all latch statistics on server sql2008 into a Data Table.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027sql2008\u0027,\u0027sqlserver2012\u0027 | Get-DbaLatchStatistic\nGet latch statistics for servers sql2008 and sqlserver2012 via pipline\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaLatchStatistic -SqlInstance sql2008 -SqlCredential $cred\nConnects using sqladmin credential and returns latch statistics from sql2008\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$output = Get-DbaLatchStatistic -SqlInstance sql2008\nPS C:\\\u003e $output\r\nPS C:\\\u003e foreach ($row in ($output | Sort-Object -Unique Url)) { Start-Process ($row).Url }\nDisplays the output then loads the associated sqlskills website for each result. Opens one tab per unique URL.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The SQL Server instance. Server version must be SQL Server version 2005 or higher.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Threshold",
                           "Threshold, in percentage of all latch stats on the system. Default per Paul\u0027s post is 95%.",
                           "",
                           false,
                           "false",
                           "95"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaLatchStatistic [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Threshold] \u003cInt32\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaLinkedServer",
        "Description":  "Retrieves information about each linked server on the instance(s).",
        "Tags":  [
                     "LinkedServer",
                     "Linked"
                 ],
        "Synopsis":  "Gets all linked servers and a summary of information from the linked servers listed.",
        "Alias":  "",
        "Author":  "Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/",
        "CommandName":  "Get-DbaLinkedServer",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaLinkedServer",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaLinkedServer -SqlInstance DEV01\nReturns all linked servers for the SQL Server instance DEV01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance DEV01 -Group SQLDEV | Get-DbaLinkedServer | Out-GridView\nReturns all linked servers for a group of servers from SQL Server Central Management Server (CMS). Send output to GridView.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "LinkedServer",
                           "The linked server(s) to process - this list is auto-populated from the server. If unspecified, all linked servers will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeLinkedServer",
                           "The linked server(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaLinkedServer [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-LinkedServer] \u003cObject[]\u003e] [[-ExcludeLinkedServer] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaLocaleSetting",
        "Description":  "Gets the Locale settings on one or more computers.\n\nRequires Local Admin rights on destination computer(s).",
        "Tags":  "OS",
        "Synopsis":  "Gets the Locale settings on a computer.",
        "Alias":  "",
        "Author":  "Klaas Vandenberghe (@PowerDBAKlaas)",
        "CommandName":  "Get-DbaLocaleSetting",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaLocaleSetting",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaLocaleSetting -ComputerName sqlserver2014a\nGets the Locale settings on computer sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\u0027,\u0027sql3\u0027 | Get-DbaLocaleSetting\nGets the Locale settings on computers sql1, sql2 and sql3.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaLocaleSetting -ComputerName sql1,sql2 -SqlCredential $credential | Out-Gridview\nGets the Locale settings on computers sql1 and sql2 using SQL Authentication to authenticate to the servers, and shows them in a grid view.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target SQL Server instance or instances.",
                           "cn,host,Server",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Credential object used to connect to the computer as a different user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaLocaleSetting [[-ComputerName] \u003cString[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaLogin",
        "Description":  "The Get-DbaLogin function returns an SMO Login object for the logins passed, if there are no users passed it will return all logins.",
        "Tags":  [
                     "Login",
                     "Security"
                 ],
        "Synopsis":  "Function to get an SMO login object of the logins for a given SQL Server instance. Takes a server object from the pipeline.",
        "Alias":  "",
        "Author":  "Mitchell Hamann (@SirCaptainMitch) | Rob Sewell (@SQLDBaWithBeard)",
        "CommandName":  "Get-DbaLogin",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaLogin",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016\nGets all the logins from server sql2016 using NT authentication and returns the SMO login objects\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 -SqlCredential $sqlcred\nGets all the logins for a given SQL Server using a passed credential object and returns the SMO login objects\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 -SqlCredential $sqlcred -Login dbatoolsuser,TheCaptain\nGet specific logins from server sql2016 returned as SMO login objects.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 -IncludeFilter \u0027##*\u0027,\u0027NT *\u0027\nGet all user objects from server sql2016 beginning with \u0027##\u0027 or \u0027NT \u0027, returned as SMO login objects.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 -ExcludeLogin dbatoolsuser\nGet all user objects from server sql2016 except the login dbatoolsuser, returned as SMO login objects.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 -Type Windows\nGet all user objects from server sql2016 that are Windows Logins\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 -Type Windows -IncludeFilter *Rob*\nGet all user objects from server sql2016 that are Windows Logins and have Rob in the name\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 -Type SQL\nGet all user objects from server sql2016 that are SQL Logins\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 -Type SQL -IncludeFilter *Rob*\nGet all user objects from server sql2016 that are SQL Logins and have Rob in the name\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 -ExcludeSystemLogin\nGet all user objects from server sql2016 that are not system objects\n-------------------------- EXAMPLE 11 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 -ExcludeFilter \u0027##*\u0027,\u0027NT *\u0027\nGet all user objects from server sql2016 except any beginning with \u0027##\u0027 or \u0027NT \u0027, returned as SMO login objects.\n-------------------------- EXAMPLE 12 --------------------------\nPS C:\\\u003e\u0027sql2016\u0027, \u0027sql2014\u0027 | Get-DbaLogin -SqlCredential $sqlcred\nUsing Get-DbaLogin on the pipeline, you can also specify which names you would like with -Login.\n-------------------------- EXAMPLE 13 --------------------------\nPS C:\\\u003e\u0027sql2016\u0027, \u0027sql2014\u0027 | Get-DbaLogin -SqlCredential $sqlcred -Locked\nUsing Get-DbaLogin on the pipeline to get all locked logins on servers sql2016 and sql2014.\n-------------------------- EXAMPLE 14 --------------------------\nPS C:\\\u003e\u0027sql2016\u0027, \u0027sql2014\u0027 | Get-DbaLogin -SqlCredential $sqlcred -HasAccess -Disabled\nUsing Get-DbaLogin on the pipeline to get all Disabled logins that have access on servers sql2016 or sql2014.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Login",
                           "The login(s) to process - this list is auto-populated from the server. If unspecified, all logins will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IncludeFilter",
                           "A list of logins to include - accepts wildcard patterns",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeLogin",
                           "The login(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeFilter",
                           "A list of logins to exclude - accepts wildcard patterns",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeSystemLogin",
                           "A Switch to remove System Logins from the output.",
                           "ExcludeSystemLogins",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Type",
                           "Filters logins by their type. Valid options are Windows and SQL.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "HasAccess",
                           "A Switch to return Logins that have access to the instance of SQL Server.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "SqlLogins",
                           "Deprecated. Please use -Type SQL",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WindowsLogins",
                           "Deprecated. Please use -Type Windows.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Locked",
                           "A Switch to return locked Logins.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Disabled",
                           "A Switch to return disabled Logins.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaLogin [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Login \u003cObject[]\u003e] [-IncludeFilter \u003cObject[]\u003e] [-ExcludeLogin \u003cObject[]\u003e] [-ExcludeFilter \u003cObject[]\u003e] [-ExcludeSystemLogin] [-Type \u003cString\u003e] [-HasAccess] [-SqlLogins] [-WindowsLogins] [-Locked] [-Disabled] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaMaintenanceSolutionLog",
        "Description":  "Ola wrote a .sql script to get the content from the commandLog table. However, if LogToTable=\u0027N\u0027, there will be no logging in that table. This function reads the text files that are written in the SQL Instance\u0027s Log directory.",
        "Tags":  [
                     "Ola",
                     "Maintenance"
                 ],
        "Synopsis":  "Reads the log files generated by the IndexOptimize Agent Job from Ola Hallengren\u0027s MaintenanceSolution.",
        "Alias":  "",
        "Author":  "Klaas Vandenberghe (@powerdbaklaas) | Simone Bizzotto ( @niphlod )",
        "CommandName":  "Get-DbaMaintenanceSolutionLog",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaMaintenanceSolutionLog",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaMaintenanceSolutionLog -SqlInstance sqlserver2014a\nGets the outcome of the IndexOptimize job on sql instance sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaMaintenanceSolutionLog -SqlInstance sqlserver2014a -SqlCredential $credential\nGets the outcome of the IndexOptimize job on sqlserver2014a, using SQL Authentication.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027sqlserver2014a\u0027, \u0027sqlserver2020test\u0027 | Get-DbaMaintenanceSolutionLog\nGets the outcome of the IndexOptimize job on sqlserver2014a and sqlserver2020test.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaMaintenanceSolutionLog -SqlInstance sqlserver2014a -Path \u0027D:\\logs\\maintenancesolution\\\u0027\nGets the outcome of the IndexOptimize job on sqlserver2014a, reading the log files in their custom location.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaMaintenanceSolutionLog -SqlInstance sqlserver2014a -Since \u00272017-07-18\u0027\nGets the outcome of the IndexOptimize job on sqlserver2014a, starting from july 18, 2017.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaMaintenanceSolutionLog -SqlInstance sqlserver2014a -LogType IndexOptimize\nGets the outcome of the IndexOptimize job on sqlserver2014a, the other options are not yet available! sorry",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "LogType",
                           "Accepts \u0027IndexOptimize\u0027, \u0027DatabaseBackup\u0027, \u0027DatabaseIntegrityCheck\u0027. ATM only IndexOptimize parsing is available",
                           "",
                           false,
                           "false",
                           "IndexOptimize"
                       ],
                       [
                           "Since",
                           "Consider only files generated since this date",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "Where to search for log files. By default it\u0027s the SQL instance errorlogpath path",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaMaintenanceSolutionLog [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-LogType] \u003cString[]\u003e] [[-Since] \u003cDateTime\u003e] [[-Path] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaManagementObject",
        "Description":  "The Get-DbaManagementObject returns an object with the Version and the\nAdd-Type Load Template for each version on the server.",
        "Tags":  "SMO",
        "Synopsis":  "Gets SQL Mangaement Object versions installed on the machine.",
        "Alias":  "Get-DbaSqlManagementObject",
        "Author":  "Ben Miller (@DBAduck), http://dbaduck.com",
        "CommandName":  "Get-DbaManagementObject",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaManagementObject",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaManagementObject\nReturns all versions of SMO on the computer\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaManagementObject -VersionNumber 13\nReturns just the version specified. If the version does not exist then it will return nothing.",
        "Params":  [
                       [
                           "ComputerName",
                           "The name of the Windows Server(s) you would like to check.",
                           "ServerInstance,SqlServer,SqlInstance",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "This command uses Windows credentials. This parameter allows you to connect remotely as a different user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "VersionNumber",
                           "This is the specific version number you are looking for. The function will look\r\nfor that version only.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaManagementObject [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-VersionNumber] \u003cInt32\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaMaxMemory",
        "Description":  "This command retrieves the SQL Server \u0027Max Server Memory\u0027 configuration setting as well as the total physical installed on the server.\n\nResults are turned in megabytes (MB).",
        "Tags":  [
                     "MaxMemory",
                     "Memory"
                 ],
        "Synopsis":  "Gets the \u0027Max Server Memory\u0027 configuration setting and the memory of the server.  Works on SQL Server 2000-2014.",
        "Alias":  "Get-SqlMaxMemory",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaMaxMemory",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaMaxMemory",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaMaxMemory -SqlInstance sqlcluster, sqlserver2012\nGet memory settings for instances \"sqlcluster\" and \"sqlserver2012\". Returns results in megabytes (MB).\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sqlcluster | Get-DbaMaxMemory | Where-Object { $_.MaxValue -gt $_.Total }\nFind all servers in Server Central Management Server that have \u0027Max Server Memory\u0027 set to higher than the total memory of the server (think 2147483647)\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaInstance -ComputerName localhost | Get-DbaMaxMemory | Format-Table -AutoSize\nScans localhost for instances using the browser service, traverses all instances and displays memory settings in a formatted table.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaMaxMemory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaMemoryCondition",
        "Description":  "The information from SQL Server ring buffers can be used to determine the memory conditions on the server when paging occurs.\n\nThis command is based on a query provided by Microsoft support.\nReference KB article: https://support.microsoft.com/en-us/help/918483/how-to-reduce-paging-of-buffer-pool-memory-in-the-64-bit-version-of-sq",
        "Tags":  "Memory",
        "Synopsis":  "Determine the memory conditions from SQL Server ring buffers.",
        "Alias":  "",
        "Author":  "IJeb Reitsma",
        "CommandName":  "Get-DbaMemoryCondition",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaMemoryCondition",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaMemoryCondition -SqlInstance sqlserver2014a\nReturns the memory conditions for the selected instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sqlserver2014a -Group GroupName | Get-DbaMemoryCondition | Out-GridView\nReturns the memory conditions for a group of servers from SQL Server Central Management Server (CMS). Send output to GridView.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaMemoryCondition [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaMemoryUsage",
        "Description":  "Retrieves the amount of memory per performance counter. Default output includes columns Server, counter instance, counter, number of pages, memory in KB, memory in MB\nSSAS and SSIS are included.\n\nSSRS does not have memory counters, only memory shrinks and memory pressure state.\n\nThis function requires local admin role on the targeted computers.",
        "Tags":  "Memory",
        "Synopsis":  "Get amount of memory in use by *all* SQL Server components and instances",
        "Alias":  "",
        "Author":  "Klaas Vandenberghe (@PowerDBAKlaas)",
        "CommandName":  "Get-DbaMemoryUsage",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaMemoryUsage",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaMemoryUsage -ComputerName sql2017\nReturns a custom object displaying Server, counter instance, counter, number of pages, memory\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaMemoryUsage -ComputerName sql2017\\sqlexpress -SqlCredential sqladmin | Where-Object { $_.Memory.Megabyte -gt 100 }\nLogs into the sql2017\\sqlexpress as sqladmin using SQL Authentication then returns results only where memory exceeds 100 MB\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers | Get-DbaMemoryUsage | Out-Gridview\nGets results from an array of $servers then diplays them in a gridview.",
        "Params":  [
                       [
                           "ComputerName",
                           "The Windows Server that you are connecting to. Note that this will return all instances, but Out-GridView makes it easy to filter to specific instances.",
                           "Host,cn,Server",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Credential object used to connect to the SQL Server as a different user",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaMemoryUsage [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaModule",
        "Description":  "Quickly find modules (Stored Procs, Functions, Views, Constraints, Rules, Triggers, etc) that have been modified in a database, or across all databases.\nResults will exclude the module definition, but can be queried explicitly.",
        "Tags":  [
                     "StoredProcedure",
                     "Trigger"
                 ],
        "Synopsis":  "Displays all objects in sys.sys_modules after specified modification date.  Works on SQL Server 2008 and above.",
        "Alias":  "Get-DbaSqlModule",
        "Author":  "Brandon Abshire, netnerds.net",
        "CommandName":  "Get-DbaModule",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaModule",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaModule -SqlInstance sql2008, sqlserver2012\nReturn all modules for servers sql2008 and sqlserver2012 sorted by Database, Modify_Date ASC.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaModule -SqlInstance sql2008, sqlserver2012 | Select *\nShows hidden definition column (informative wall of text).\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaModule -SqlInstance sql2008 -Database TestDB -ModifiedSince \"2017-01-01 10:00:00\"\nReturn all modules on server sql2008 for only the TestDB database with a modified date after 1 January 2017 10:00:00 AM.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaModule -SqlInstance sql2008 -Type View, Trigger, ScalarFunction\nReturn all modules on server sql2008 for all databases that are triggers, views or scalar functions.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ModifiedSince",
                           "DateTime value to use as minimum modified date of module.",
                           "",
                           false,
                           "false",
                           "1900-01-01"
                       ],
                       [
                           "Type",
                           "Limit by specific type of module. Valid choices include: View, TableValuedFunction, DefaultConstraint, StoredProcedure, Rule, InlineTableValuedFunction, Trigger, ScalarFunction",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeSystemDatabases",
                           "Allows you to suppress output on system databases",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ExcludeSystemObjects",
                           "Allows you to suppress output on system objects",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaModule [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-ModifiedSince] \u003cDateTime\u003e] [[-Type] \u003cString[]\u003e] [-ExcludeSystemDatabases] [-ExcludeSystemObjects] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaMsdtc",
        "Description":  "Returns a custom object with Computer name, state of the MSDTC Service, security settings of MSDTC and CID\u0027s\n\nRequires: Windows administrator access on Servers",
        "Tags":  [
                     "Msdtc",
                     "dtc"
                 ],
        "Synopsis":  "Displays information about the Distributed Transaction Coordinator (MSDTC) on a server",
        "Alias":  "",
        "Author":  "Klaas Vandenberghe (@powerdbaklaas)",
        "CommandName":  "Get-DbaMsdtc",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaMsdtc",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaMsdtc -ComputerName srv0042\nGet DTC status for the server srv0042\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$Computers = (Get-Content D:\\configfiles\\SQL\\MySQLInstances.txt | % {$_.split(\u0027\\\u0027)[0]})\nPS C:\\\u003e $Computers | Get-DbaMsdtc\nGet DTC status for all the computers in a .txt file\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaMsdtc -Computername $Computers | where { $_.dtcservicestate -ne \u0027running\u0027 }\nGet DTC status for all the computers where the MSDTC Service is not running\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaMsdtc -ComputerName srv0042 | Out-Gridview\nGet DTC status for the computer srv0042 and show in a grid view",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer.",
                           "cn,host,Server",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ]
                   ],
        "Syntax":  "Get-DbaMsdtc [[-ComputerName] \u003cString[]\u003e] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaNetworkActivity",
        "Description":  "Gets the Current traffic on every Network Interface on a computer.\nSee https://msdn.microsoft.com/en-us/library/aa394293(v=vs.85).aspx\n\nRequires Local Admin rights on destination computer(s).",
        "Tags":  "Network",
        "Synopsis":  "Gets the Current traffic on every Network Interface on a computer.",
        "Alias":  "",
        "Author":  "Klaas Vandenberghe (@PowerDBAKlaas)",
        "CommandName":  "Get-DbaNetworkActivity",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaNetworkActivity",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaNetworkActivity -ComputerName sqlserver2014a\nGets the Current traffic on every Network Interface on computer sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\u0027,\u0027sql3\u0027 | Get-DbaNetworkActivity\nGets the Current traffic on every Network Interface on computers sql1, sql2 and sql3.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaNetworkActivity -ComputerName sql1,sql2 | Out-Gridview\nGets the Current traffic on every Network Interface on computers sql1 and sql2, and shows them in a grid view.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target SQL Server instance or instances.",
                           "cn,host,Server",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Credential object used to connect to the computer as a different user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaNetworkActivity [[-ComputerName] \u003cString[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaNetworkCertificate",
        "Description":  "Gets computer certificates on localhost that are candidates for using with SQL Server\u0027s network encryption",
        "Tags":  "Certificate",
        "Synopsis":  "Simplifies finding computer certificates that are candidates for using with SQL Server\u0027s network encryption",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaNetworkCertificate",
        "Availability":  "Windows only",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaNetworkCertificate\nGets computer certificates on localhost that are candidates for using with SQL Server\u0027s network encryption\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaNetworkCertificate -ComputerName sql2016\nGets computer certificates on sql2016 that are being used for SQL Server network encryption",
        "Params":  [
                       [
                           "ComputerName",
                           "The target SQL Server instance or instances. Defaults to localhost. If target is a cluster, you must specify the distinct nodes.",
                           "ServerInstance,SqlServer,SqlInstance",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to $ComputerName using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaNetworkCertificate [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaOpenTransaction",
        "Description":  "This command is based on open transaction script published by Paul Randal.\nReference: https://www.sqlskills.com/blogs/paul/script-open-transactions-with-text-and-plans/",
        "Tags":  [
                     "Database",
                     "Process",
                     "Session",
                     "ActivityMonitor"
                 ],
        "Synopsis":  "Displays all open transactions.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaOpenTransaction",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaOpenTransaction",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaOpenTransaction -SqlInstance sqlserver2014a\nReturns open transactions for sqlserver2014a\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaOpenTransaction -SqlInstance sqlserver2014a -SqlCredential sqladmin\nLogs into sqlserver2014a using the login \"sqladmin\"",
        "Params":  [
                       [
                           "SqlInstance",
                           "The SQL Server instance",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Connect using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaOpenTransaction [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaOperatingSystem",
        "Description":  "Gets operating system information from the server and returns as an object.",
        "Tags":  [
                     "ServerInfo",
                     "OperatingSystem"
                 ],
        "Synopsis":  "Gets operating system information from the server.",
        "Alias":  "",
        "Author":  "Shawn Melton (@wsmelton), https://wsmelton.github.io",
        "CommandName":  "Get-DbaOperatingSystem",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaOperatingSystem",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaOperatingSystem\nReturns information about the local computer\u0027s operating system\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaOperatingSystem -ComputerName sql2016\nReturns information about the sql2016\u0027s operating system\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$wincred = Get-Credential ad\\sqladmin\nPS C:\\\u003e \u0027sql2016\u0027, \u0027sql2017\u0027 | Get-DbaOperatingSystem -Credential $wincred\nReturns information about the sql2016 and sql2017 operating systems using alternative Windows credentials\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-Content .\\servers.txt | Get-DbaOperatingSystem\nReturns information about all the servers operating system that are stored in the file. Every line in the file can only contain one hostname for a server.",
        "Params":  [
                       [
                           "ComputerName",
                           "Target computer(s). If no computer name is specified, the local computer is targeted",
                           "cn,host,Server",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Alternate credential object to use for accessing the target computer(s).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaOperatingSystem [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaPageFileSetting",
        "Description":  "This command uses CIM (or other, related computer management tools) to detect the page file configuration of the target computer(s).\n\nNote that this may require local administrator privileges for the relevant computers.",
        "Tags":  "CIM",
        "Synopsis":  "Returns information on the page file configuration of the target computer.",
        "Alias":  "",
        "Author":  "Klaas Vandenberghe (@PowerDBAKlaas)",
        "CommandName":  "Get-DbaPageFileSetting",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaPageFileSetting",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPageFileSetting -ComputerName ServerA,ServerB\nReturns a custom object displaying ComputerName, AutoPageFile, FileName, Status, LastModified, LastAccessed, AllocatedBaseSize, InitialSize, MaximumSize, PeakUsage, CurrentUsage  for ServerA and \r\nServerB\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027ServerA\u0027 | Get-DbaPageFileSetting\nReturns a custom object displaying ComputerName, AutoPageFile, FileName, Status, LastModified, LastAccessed, AllocatedBaseSize, InitialSize, MaximumSize, PeakUsage, CurrentUsage  for ServerA",
        "Params":  [
                       [
                           "ComputerName",
                           "The target SQL Server instance or instances.\r\nThis can be the name of a computer, a SMO object, an IP address, an AD Computer object, a connection string or a SQL Instance.",
                           "cn,host,ServerInstance,Server,SqlServer",
                           false,
                           "true (ByValue, ByPropertyName)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Credential object used to connect to the Computer as a different user",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaPageFileSetting [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [-Credential \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaPbmCategory",
        "Description":  "Returns policy categories from policy based management from an instance.",
        "Tags":  [
                     "Policy",
                     "PolicyBasedManagement",
                     "PBM"
                 ],
        "Synopsis":  "Returns policy categories from policy based management from an instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaPbmCategory",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaPbmCategory",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPbmCategory -SqlInstance sql2016\nReturns all policy categories from the sql2016 PBM server\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPbmCategory -SqlInstance sql2016 -SqlCredential $cred\nUses a credential $cred to connect and return all policy categories from the sql2016 PBM server",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Category",
                           "Filters results to only show specific condition",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows piping from Get-DbaPbmStore",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "ExcludeSystemObject",
                           "By default system objects are include. Use this parameter to exclude them.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaPbmCategory [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Category] \u003cString[]\u003e] [[-InputObject] \u003cPolicyStore[]\u003e] [-ExcludeSystemObject] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaPbmCategorySubscription",
        "Description":  "Returns policy category subscriptions from policy based management from an instance.",
        "Tags":  [
                     "Policy",
                     "PolicyBasedManagement",
                     "PBM"
                 ],
        "Synopsis":  "Returns policy category subscriptions from policy based management from an instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaPbmCategorySubscription",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaPbmCategorySubscription",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPbmCategorySubscription -SqlInstance sql2016\nReturns all policy category subscriptions from the sql2016 PBM server\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPbmCategorySubscription -SqlInstance sql2016 -SqlCredential $cred\nUses a credential $cred to connect and return all policy category subscriptions from the sql2016 PBM server",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows piping from Get-DbaPbmStore",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaPbmCategorySubscription [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-InputObject] \u003cPolicyStore[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaPbmCondition",
        "Description":  "Returns conditions from policy based management from an instance.",
        "Tags":  [
                     "Policy",
                     "PolicyBasedManagement",
                     "PBM"
                 ],
        "Synopsis":  "Returns conditions from policy based management from an instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaPbmCondition",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaPbmCondition",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPbmCondition -SqlInstance sql2016\nReturns all conditions from the sql2016 PBM server\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPbmCondition -SqlInstance sql2016 -SqlCredential $cred\nUses a credential $cred to connect and return all conditions from the sql2016 PBM server",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Condition",
                           "Filters results to only show specific condition",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows piping from Get-DbaPbmStore",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "IncludeSystemObject",
                           "By default system objects are filtered out. Use this parameter to include them.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaPbmCondition [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Condition] \u003cString[]\u003e] [[-InputObject] \u003cPolicyStore[]\u003e] [-IncludeSystemObject] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaPbmObjectSet",
        "Description":  "Returns object sets from policy based management.",
        "Tags":  [
                     "Policy",
                     "PolicyBasedManagement",
                     "PBM"
                 ],
        "Synopsis":  "Returns object sets from policy based management.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaPbmObjectSet",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaPbmObjectSet",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPbmObjectSet -SqlInstance sql2016\nReturns all object sets from the sql2016 PBM instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPbmObjectSet -SqlInstance sql2016 -SqlCredential $cred\nUses a credential $cred to connect and return all object sets from the sql2016 PBM instance",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ObjectSet",
                           "Filters results to only show specific object set",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows piping from Get-DbaPbmStore",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "IncludeSystemObject",
                           "By default system objects are filtered out. Use this parameter to include them.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaPbmObjectSet [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-ObjectSet] \u003cString[]\u003e] [[-InputObject] \u003cPolicyStore[]\u003e] [-IncludeSystemObject] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaPbmPolicy",
        "Description":  "Returns details of policies with the option to filter on Category and SystemObjects.",
        "Tags":  [
                     "Policy",
                     "PolicyBasedManagement",
                     "PBM"
                 ],
        "Synopsis":  "Returns policies from Policy-Based Management from an instance.",
        "Alias":  "Get-DbaPolicy",
        "Author":  "Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/",
        "CommandName":  "Get-DbaPbmPolicy",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaPbmPolicy",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPbmPolicy -SqlInstance sql2016\nReturns all policies from sql2016 server\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPbmPolicy -SqlInstance sql2016 -SqlCredential $cred\nUses a credential $cred to connect and return all policies from sql2016 instance\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPbmPolicy -SqlInstance sql2016 -Category MorningCheck\nReturns all policies from sql2016 server that part of the PolicyCategory MorningCheck",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Policy",
                           "Filters results to only show specific policy",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Category",
                           "Filters results to only show policies in the category selected",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows piping from Get-DbaPbmStore",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "IncludeSystemObject",
                           "By default system objects are filtered out. Use this parameter to INCLUDE them .",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaPbmPolicy [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Policy] \u003cString[]\u003e] [[-Category] \u003cString[]\u003e] [[-InputObject] \u003cPolicyStore[]\u003e] [-IncludeSystemObject] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaPbmStore",
        "Description":  "Returns the policy based management store.",
        "Tags":  [
                     "Policy",
                     "PolicyBasedManagement",
                     "PBM"
                 ],
        "Synopsis":  "Returns the policy based management store.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaPbmStore",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaPbmStore",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPbmStore -SqlInstance sql2016\nReturn the policy store from the sql2016 instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPbmStore -SqlInstance sql2016 -SqlCredential $cred\nUses a credential $cred to connect and return the policy store from the sql2016 instance",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaPbmStore [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaPermission",
        "Description":  "Retrieves a list of permissions\n\nPermissions link principals to securables.\nPrincipals exist on Windows, Instance and Database level.\nSecurables exist on Instance and Database level.\nA permission state can be GRANT, DENY or REVOKE.\nThe permission type can be SELECT, CONNECT, EXECUTE and more.\n\nSee https://msdn.microsoft.com/en-us/library/ms191291.aspx for more information",
        "Tags":  [
                     "Permissions",
                     "Databases"
                 ],
        "Synopsis":  "Get a list of Server and Database level permissions",
        "Alias":  "",
        "Author":  "Klaas Vandenberghe (@PowerDBAKlaas)",
        "CommandName":  "Get-DbaPermission",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaPermission",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPermission -SqlInstance ServerA\\sql987\nReturns a custom object with Server name, Database name, permission state, permission type, grantee and securable.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPermission -SqlInstance ServerA\\sql987 | Format-Table -AutoSize\nReturns a formatted table displaying Server, Database, permission state, permission type, grantee, granteetype, securable and securabletype.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPermission -SqlInstance ServerA\\sql987 -ExcludeSystemObjects -IncludeServerLevel\nReturns a custom object with Server name, Database name, permission state, permission type, grantee and securable\r\nin all databases and on the server level, but not on system securables.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaPermission -SqlInstance sql2016 -Database master\nReturns a custom object with permissions for the master database.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Defaults to localhost.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies one or more database(s) to process. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies one or more database(s) to exclude from processing.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IncludeServerLevel",
                           "If this switch is enabled, information about Server Level Permissions will be output.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ExcludeSystemObjects",
                           "If this switch is enabled, permissions on system securables will be excluded.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "If this switch is enabled exceptions will be thrown to the caller, which will need to perform its own exception processing. Otherwise, the function will try to catch the exception, interpret it and \r\nprovide a friendly error message.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaPermission [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-IncludeServerLevel] [-ExcludeSystemObjects] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaPfAvailableCounter",
        "Description":  "Gathers list of all available counters on local or remote machines. Note, if you pass a credential object, it will be included in the output for easy reuse in your next piped command.\n\nThanks to Daniel Streefkerk for this super fast way of counters\nhttps://daniel.streefkerkonline.com/2016/02/18/use-powershell-to-list-all-windows-performance-counters-and-their-numeric-ids",
        "Tags":  [
                     "Performance",
                     "DataCollector",
                     "PerfCounter"
                 ],
        "Synopsis":  "Gathers list of all available counters on local or remote machines.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaPfAvailableCounter",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaPfAvailableCounter",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPfAvailableCounter\nGets all available counters on the local machine.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPfAvailableCounter -Pattern *sql*\nGets all counters matching sql on the local machine.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPfAvailableCounter -ComputerName sql2017 -Pattern *sql*\nGets all counters matching sql on the remote server sql2017.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaPfAvailableCounter -Pattern *sql*\nGets all counters matching sql on the local machine.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaPfAvailableCounter -Pattern *sql* | Add-DbaPfDataCollectorCounter -CollectorSet \u0027Test Collector Set\u0027 -Collector DataCollector01\nAdds all counters matching \"sql\" to the DataCollector01 within the \u0027Test Collector Set\u0027 CollectorSet.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer. Defaults to localhost.",
                           "",
                           false,
                           "false",
                           "$env:ComputerName"
                       ],
                       [
                           "Credential",
                           "Allows you to login to servers using alternative credentials. To use:\n$scred = Get-Credential, then pass $scred object to the -Credential parameter.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Pattern",
                           "Specify a pattern for filtering.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaPfAvailableCounter [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Pattern] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaPfDataCollector",
        "Description":  "Gets Performance Monitor Data Collectors.",
        "Tags":  [
                     "Performance",
                     "DataCollector",
                     "PerfCounter"
                 ],
        "Synopsis":  "Gets Performance Monitor Data Collectors.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaPfDataCollector",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaPfDataCollector",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollector\nGets all Collectors on localhost.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollector -ComputerName sql2017\nGets all Collectors on sql2017.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollector -ComputerName sql2017, sql2016 -Credential ad\\sqldba -CollectorSet \u0027System Correlation\u0027\nGets all Collectors for the \u0027System Correlation\u0027 CollectorSet on sql2017 and sql2016 using alternative credentials.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet -CollectorSet \u0027System Correlation\u0027 | Get-DbaPfDataCollector\nGets all Collectors for the \u0027System Correlation\u0027 CollectorSet.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer. Defaults to localhost.",
                           "",
                           false,
                           "false",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to servers using alternative credentials. To use:\n$scred = Get-Credential, then pass $scred object to the -Credential parameter.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CollectorSet",
                           "The Collector Set name.",
                           "DataCollectorSet",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Collector",
                           "The Collector name.",
                           "DataCollector",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Accepts the object output by Get-DbaPfDataCollectorSet via the pipeline.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaPfDataCollector [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CollectorSet] \u003cString[]\u003e] [[-Collector] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaPfDataCollectorCounter",
        "Description":  "Gets Performance Counters.",
        "Tags":  [
                     "Performance",
                     "DataCollector",
                     "PerfCounter"
                 ],
        "Synopsis":  "Gets Performance Counters.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaPfDataCollectorCounter",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaPfDataCollectorCounter",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorCounter\nGets all counters for all Collector Sets on localhost.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorCounter -ComputerName sql2017\nGets all counters for all Collector Sets on  on sql2017.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorCounter -ComputerName sql2017 -Counter \u0027\\Processor(_Total)\\% Processor Time\u0027\nGets the \u0027\\Processor(_Total)\\% Processor Time\u0027 counter on sql2017.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorCounter -ComputerName sql2017, sql2016 -Credential ad\\sqldba -CollectorSet \u0027System Correlation\u0027\nGets all counters for the \u0027System Correlation\u0027 CollectorSet on sql2017 and sql2016 using alternative credentials.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet -CollectorSet \u0027System Correlation\u0027 | Get-DbaPfDataCollector | Get-DbaPfDataCollectorCounter\nGets all counters for the \u0027System Correlation\u0027 CollectorSet.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer. Defaults to localhost.",
                           "",
                           false,
                           "false",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to servers using alternative credentials. To use:\n$scred = Get-Credential, then pass $scred object to the -Credential parameter.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CollectorSet",
                           "The Collector Set name.",
                           "DataCollectorSet",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Collector",
                           "The Collector name.",
                           "DataCollector",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Counter",
                           "The Counter name to capture. This must be in the form of \u0027\\Processor(_Total)\\% Processor Time\u0027.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Accepts the object output by Get-DbaPfDataCollectorSet via the pipeline.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaPfDataCollectorCounter [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CollectorSet] \u003cString[]\u003e] [[-Collector] \u003cString[]\u003e] [[-Counter] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaPfDataCollectorCounterSample",
        "Description":  "Gets Performance Counter Samples.",
        "Tags":  [
                     "Performance",
                     "DataCollector",
                     "PerfCounter"
                 ],
        "Synopsis":  "Gets Performance Counter Samples.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaPfDataCollectorCounterSample",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaPfDataCollectorCounterSample",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorCounterSample\nGets a single sample for all counters for all Collector Sets on localhost.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorCounterSample -Counter \u0027\\Processor(_Total)\\% Processor Time\u0027\nGets a single sample for all counters for all Collector Sets on localhost.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorCounter -ComputerName sql2017, sql2016 | Out-GridView -PassThru | Get-DbaPfDataCollectorCounterSample -MaxSamples 10\nGets 10 samples for all counters for all Collector Sets for servers sql2016 and sql2017.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorCounterSample -ComputerName sql2017\nGets a single sample for all counters for all Collector Sets on sql2017.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorCounterSample -ComputerName sql2017, sql2016 -Credential ad\\sqldba -CollectorSet \u0027System Correlation\u0027\nGets a single sample for all counters for the \u0027System Correlation\u0027 CollectorSet on sql2017 and sql2016 using alternative credentials.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorCounterSample -CollectorSet \u0027System Correlation\u0027\nGets a single sample for all counters for the \u0027System Correlation\u0027 CollectorSet.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer. Defaults to localhost.",
                           "",
                           false,
                           "false",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to servers using alternative credentials. To use:\n$scred = Get-Credential, then pass $scred object to the -Credential parameter.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CollectorSet",
                           "The Collector Set name.",
                           "DataCollectorSet",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Collector",
                           "The Collector name.",
                           "DataCollector",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Counter",
                           "The Counter name. This must be in the form of \u0027\\Processor(_Total)\\% Processor Time\u0027.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Continuous",
                           "If this switch is enabled, samples will be retrieved continuously until you press CTRL+C. By default, this command gets only one counter sample. You can use the SampleInterval parameter to set the \r\ninterval for continuous sampling.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ListSet",
                           "Gets the specified performance counter sets on the computers. Enter the names of the counter sets. Wildcards are permitted.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "MaxSamples",
                           "Specifies the number of samples to get from each counter. The default is 1 sample. To get samples continuously (no maximum sample size), use the Continuous parameter.\nTo collect a very large data set, consider running a Get-DbaPfDataCollectorCounterSample command as a Windows PowerShell background job.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "SampleInterval",
                           "Specifies the time between samples in seconds. The minimum value and the default value are 1 second.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "InputObject",
                           "Accepts the object output by Get-DbaPfDataCollectorCounter via the pipeline.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaPfDataCollectorCounterSample [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CollectorSet] \u003cString[]\u003e] [[-Collector] \u003cString[]\u003e] [[-Counter] \u003cString[]\u003e] [-Continuous] [[-ListSet]] [[-MaxSamples] \u003cInt32\u003e] [[-SampleInterval] \u003cInt32\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaPfDataCollectorSet",
        "Description":  "Gets Performance Monitor Data Collector Set.",
        "Tags":  [
                     "Performance",
                     "DataCollector",
                     "PerfCounter"
                 ],
        "Synopsis":  "Gets Performance Monitor Data Collector Set.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaPfDataCollectorSet",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaPfDataCollectorSet",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet\nGets all Collector Sets on localhost.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet -ComputerName sql2017\nGets all Collector Sets on sql2017.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet -ComputerName sql2017 -Credential ad\\sqldba -CollectorSet \u0027System Correlation\u0027\nGets the \u0027System Correlation\u0027 CollectorSet on sql2017 using alternative credentials.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet | Select-Object *\nDisplays extra columns and also exposes the original COM object in DataCollectorSetObject.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer. Defaults to localhost.",
                           "",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to servers using alternative credentials. To use:\n$scred = Get-Credential, then pass $scred object to the -Credential parameter.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CollectorSet",
                           "The Collector set name.",
                           "DataCollectorSet",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaPfDataCollectorSet [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CollectorSet] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaPfDataCollectorSetTemplate",
        "Description":  "Parses Perf Monitor XML templates. Defaults to parsing templates in the dbatools template repository (\\bin\\perfmontemplates\\).",
        "Tags":  [
                     "Performance",
                     "DataCollector",
                     "PerfCounter"
                 ],
        "Synopsis":  "Parses Perf Monitor templates. Defaults to parsing templates in the dbatools template repository (\\bin\\perfmontemplates\\).",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaPfDataCollectorSetTemplate",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaPfDataCollectorSetTemplate",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSetTemplate\nReturns information about all the templates in the local dbatools repository.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSetTemplate | Out-GridView -PassThru | Import-DbaPfDataCollectorSetTemplate -ComputerName sql2017 | Start-DbaPfDataCollectorSet\nAllows you to select a template, then deploys it to sql2017 and immediately starts the DataCollectorSet.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSetTemplate | Select-Object *\nReturns more information about the template, including the full path/filename.",
        "Params":  [
                       [
                           "Path",
                           "The path to the template directory. Defaults to the dbatools template repository (\\bin\\perfmontemplates\\).",
                           "",
                           false,
                           "false",
                           "\"$script:PSModuleRoot\\bin\\perfmontemplates\\collectorsets\""
                       ],
                       [
                           "Pattern",
                           "Specify a pattern for filtering. Alternatively, you can use Out-GridView -Passthru to select objects and pipe them to Import-DbaPfDataCollectorSetTemplate.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Template",
                           "Specifies one or more of the templates provided by dbatools. Press tab to cycle through the list to the options.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaPfDataCollectorSetTemplate [[-Path] \u003cString[]\u003e] [[-Pattern] \u003cString\u003e] [[-Template] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaPlanCache",
        "Description":  "Checks adhoc and prepared plan cache for each database, if over 100 MB you should consider using Remove-DbaQueryPlan to clear the plan caches or turning on \"optimize for adhoc workloads\" configuration if running 2008 or later.\n\nReferences: https://www.sqlskills.com/blogs/kimberly/plan-cache-adhoc-workloads-and-clearing-the-single-use-plan-cache-bloat/\n\nNote: This command returns results from all SQL server instances on the destination server but the process column is specific to -SqlInstance passed.",
        "Tags":  "Memory",
        "Synopsis":  "Provides information about adhoc and prepared plan cache usage",
        "Alias":  "",
        "Author":  "Tracy Boggiano, databasesuperhero.com",
        "CommandName":  "Get-DbaPlanCache",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaPlanCache",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPlanCache -SqlInstance sql2017\nReturns the single use plan cache usage information for SQL Server instance 2017\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPlanCache -SqlInstance sql2017 -SqlCredential sqladmin\nReturns the single use plan cache usage information for SQL Server instance 2017 using login \u0027sqladmin\u0027",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaPlanCache [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaPowerPlan",
        "Description":  "Gets the Power Plan settings on a computer against best practices recommendations.",
        "Tags":  "PowerPlan",
        "Synopsis":  "Gets the Power Plan settings for compliance with best practices, which recommend High Performance for SQL Server.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaPowerPlan",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaPowerPlan",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPowerPlan -ComputerName sql2017\nGets the Power Plan settings for sql2017\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPowerPlan -ComputerName sql2017 -Credential ad\\admin\nGets the Power Plan settings for sql2017 using an alternative credential",
        "Params":  [
                       [
                           "ComputerName",
                           "The server(s) to check Power Plan settings on.",
                           "ServerInstance,SqlServer,SqlInstance",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Credential",
                           "Specifies a PSCredential object to use in authenticating to the server(s), instead of the current user account.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaPowerPlan [-ComputerName] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaPrivilege",
        "Description":  "Gets the users with local privileges \u0027Lock Pages in Memory\u0027, \u0027Instant File Initialization\u0027, \u0027Logon as Batch\u0027 on one or more computers.\n\nRequires Local Admin rights on destination computer(s).",
        "Tags":  "Privilege",
        "Synopsis":  "Gets the users with local privileges on one or more computers.",
        "Alias":  "",
        "Author":  "Klaas Vandenberghe (@PowerDBAKlaas)",
        "CommandName":  "Get-DbaPrivilege",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaPrivilege",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPrivilege -ComputerName sqlserver2014a\nGets the local privileges on computer sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\u0027,\u0027sql3\u0027 | Get-DbaPrivilege\nGets the local privileges on computers sql1, sql2 and sql3.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPrivilege -ComputerName sql1,sql2 | Out-GridView\nGets the local privileges on computers sql1 and sql2, and shows them in a grid view.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target SQL Server instance or instances.",
                           "cn,host,Server",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Credential object used to connect to the computer as a different user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaPrivilege [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaProcess",
        "Description":  "This command displays processes associated with a spid, login, host, program or database.\n\nThanks to Michael J Swart at https://sqlperformance.com/2017/07/sql-performance/find-database-connection-leaks for the query to get the last executed SQL statement, minutesasleep and host process ID.",
        "Tags":  [
                     "Process",
                     "Session",
                     "ActivityMonitor"
                 ],
        "Synopsis":  "This command displays SQL Server processes.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaProcess",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaProcess",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaProcess -SqlInstance sqlserver2014a -Login base\\ctrlb, sa\nShows information about the processes for base\\ctrlb and sa on sqlserver2014a. Windows Authentication is used in connecting to sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaProcess -SqlInstance sqlserver2014a -SqlCredential $credential -Spid 56, 77\nShows information about the processes for spid 56 and 57. Uses alternative (SQL or Windows) credentials to authenticate to sqlserver2014a.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaProcess -SqlInstance sqlserver2014a -Program \u0027Microsoft SQL Server Management Studio\u0027\nShows information about the processes that were created in Microsoft SQL Server Management Studio.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaProcess -SqlInstance sqlserver2014a -Host workstationx, server100\nShows information about the processes that were initiated by hosts (computers/clients) workstationx and server 1000.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Spid",
                           "Specifies one or more process IDs (Spid) to be displayed. Options for this parameter are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeSpid",
                           "Specifies one ore more process IDs to exclude from display. Options for this parameter are auto-populated from the server.\nThis is the last filter to run, so even if a Spid matches another filter, it will be excluded by this filter.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies one or more databases with active processes to look for. Options for this parameter are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Login",
                           "Specifies one or more Login names with active processes to look for. Options for this parameter are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Hostname",
                           "Specifies one or more hostnames with active processes to look for. Options for this parameter are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Program",
                           "Specifies one or more program names with active processes to look for. Options for this parameter are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeSystemSpids",
                           "If this switch is enabled, system Spids will be ignored.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaProcess [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Spid] \u003cInt32[]\u003e] [[-ExcludeSpid] \u003cInt32[]\u003e] [[-Database] \u003cString[]\u003e] [[-Login] \u003cString[]\u003e] [[-Hostname] \u003cString[]\u003e] [[-Program] \u003cString[]\u003e] [-ExcludeSystemSpids] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaProductKey",
        "Description":  "This command find the product key for all installed instances. Clustered instances are supported as well.\n\nUses key decoder by Jakob Bindslet (http://goo.gl/1jiwcB)",
        "Tags":  "ProductKey",
        "Synopsis":  "Gets SQL Server Product Keys from local or destination SQL Servers. Works with SQL Server 2005-2017",
        "Alias":  "Get-DbaSqlProductKey,Get-SqlServerKey",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaProductKey",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaProductKey",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaProductKey -ComputerName winxp, sqlservera, sqlserver2014a, win2k8\nGets SQL Server versions, editions and product keys for all instances within each server or workstation.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target SQL Server instance or instances.",
                           "SqlInstance",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "This command logs into the SQL instance to gather additional information.\nUse this parameter to connect to the discovered SQL instances using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Credential",
                           "Login to the target Windows instance using alternative credentials. Windows Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaProductKey [-ComputerName] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaQueryExecutionTime",
        "Description":  "Quickly find slow query executions within a database.  Results will include stored procedures and individual SQL statements.",
        "Tags":  [
                     "Query",
                     "Performance"
                 ],
        "Synopsis":  "Displays Stored Procedures and Ad hoc queries with the highest execution times.  Works on SQL Server 2008 and above.",
        "Alias":  "",
        "Author":  "Brandon Abshire, netnerds.net",
        "CommandName":  "Get-DbaQueryExecutionTime",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaQueryExecutionTime",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaQueryExecutionTime -SqlInstance sql2008, sqlserver2012\nReturn the top 100 slowest stored procedures or statements for servers sql2008 and sqlserver2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaQueryExecutionTime -SqlInstance sql2008 -Database TestDB\nReturn the top 100 slowest stored procedures or statements on server sql2008 for only the TestDB database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaQueryExecutionTime -SqlInstance sql2008 -Database TestDB -MaxResultsPerDb 100 -MinExecs 200 -MinExecMs 1000\nReturn the top 100 slowest stored procedures or statements on server sql2008 for only the TestDB database, limiting results to queries with more than 200 total executions and an execution time over \r\n1000ms or higher.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "MaxResultsPerDb",
                           "Allows you to limit the number of results returned, as many systems can have very large amounts of query plans.  Default value is 100 results.",
                           "",
                           false,
                           "false",
                           "100"
                       ],
                       [
                           "MinExecs",
                           "Allows you to limit the scope to queries that have been executed a minimum number of time. Default value is 100 executions.",
                           "",
                           false,
                           "false",
                           "100"
                       ],
                       [
                           "MinExecMs",
                           "Allows you to limit the scope to queries with a specified average execution time.  Default value is 500 (ms).",
                           "",
                           false,
                           "false",
                           "500"
                       ],
                       [
                           "ExcludeSystem",
                           "Allows you to suppress output on system databases",
                           "ExcludeSystemDatabases",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaQueryExecutionTime [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [[-MaxResultsPerDb] \u003cInt32\u003e] [[-MinExecs] \u003cInt32\u003e] [[-MinExecMs] \u003cInt32\u003e] [[-ExcludeSystem]] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaRegistryRoot",
        "Description":  "Uses SQL WMI to find the Registry Root of each SQL Server instance on a computer",
        "Tags":  [
                     "Configuration",
                     "Registry"
                 ],
        "Synopsis":  "Uses SQL WMI to find the Registry Root of each SQL Server instance on a computer",
        "Alias":  "Get-DbaSqlRegistryRoot",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaRegistryRoot",
        "Availability":  "Windows only",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaRegistryRoot\nGets the registry root for all instances on localhost\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRegistryRoot -ComputerName server1\nGets the registry root for all instances on server1",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer. This is not a SQL Server service, though if you pass a named SQL instance, it\u0027ll parse properly down to the computer name",
                           "",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to $ComputerName using alternative Windows credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaRegistryRoot [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaRepDistributor",
        "Description":  "This function locates and enumerates distributor information for a given SQL Server instance.",
        "Tags":  "Replication",
        "Synopsis":  "Gets the information about a replication distributor for a given SQL Server instance.",
        "Alias":  "Get-DbaDistributor",
        "Author":  "William Durkin (@sql_williamd)",
        "CommandName":  "Get-DbaRepDistributor",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaRepDistributor",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaRepDistributor -SqlInstance sql2008, sqlserver2012\nRetrieve distributor information for servers sql2008 and sqlserver2012.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaRepDistributor [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaRepPublication",
        "Description":  "Quickly find all transactional, merge, and snapshot publications on a specific server or database.",
        "Tags":  "Replication",
        "Synopsis":  "Displays all publications for a server or database.",
        "Alias":  "",
        "Author":  "Colin Douglas",
        "CommandName":  "Get-DbaRepPublication",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaRepPublication",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaRepPublication -SqlInstance sql2008, sqlserver2012\nReturn all publications for servers sql2008 and sqlserver2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRepPublication -SqlInstance sql2008 -Database TestDB\nReturn all publications on server sql2008 for only the TestDB database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaRepPublication -SqlInstance sql2008 -PublicationType Transactional\nReturn all publications on server sql2008 for all databases that have Transactional publications",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process. If unspecified, all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "PublicationType",
                           "Limit by specific type of publication. Valid choices include: Transactional, Merge, Snapshot",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "byng this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaRepPublication [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-Database] \u003cObject[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-PublicationType] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaRepServer",
        "Description":  "Gets a replication server object",
        "Tags":  "Replication",
        "Synopsis":  "Gets a replication server object",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaRepServer",
        "Availability":  "Windows only",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaRepServer -SqlInstance sql2016\nGets the replication server object for sql2016 using Windows authentication\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRepServer -SqlInstance sql2016 -SqlCredential repadmin\nGets the replication server object for sql2016 using SQL authentication",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaRepServer [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaResourceGovernor",
        "Description":  "Gets the Resource Governor object",
        "Tags":  "ResourceGovernor",
        "Synopsis":  "Gets the Resource Governor object",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaResourceGovernor",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaResourceGovernor",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaResourceGovernor -SqlInstance sql2016\nGets the resource governor object of the SqlInstance sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaResourceGovernor\nGets the resource governor object on Sql1 and Sql2/sqlexpress instances",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to SQL Server using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaResourceGovernor [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaRgClassifierFunction",
        "Description":  "Gets the Resource Governor custom classifier Function which is used for customize the workload groups usage",
        "Tags":  [
                     "Migration",
                     "ResourceGovernor"
                 ],
        "Synopsis":  "Gets the Resource Governor custom classifier Function",
        "Alias":  "",
        "Author":  "Alessandro Alpi (@suxstellino), alessandroalpi.blog",
        "CommandName":  "Get-DbaRgClassifierFunction",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaRgClassifierFunction",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaRgClassifierFunction -SqlInstance sql2016\nGets the classifier function from sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaResourceGovernor | Get-DbaRgClassifierFunction\nGets the classifier function object on Sql1 and Sql2/sqlexpress instances",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to SQL Server using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows input to be piped from Get-DbaResourceGovernor",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaRgClassifierFunction [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-InputObject] \u003cResourceGovernor[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaRgResourcePool",
        "Description":  "Gets Resource Governor Pool objects, including internal or external",
        "Tags":  "ResourceGovernor",
        "Synopsis":  "Gets Resource Governor Pool objects, including internal or external",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaRgResourcePool",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaRgResourcePool",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaRgResourcePool -SqlInstance sql2016\nGets the internal resource pools on sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaResourceGovernor | Get-DbaRgResourcePool\nGets the internal resource pools on Sql1 and Sql2/sqlexpress instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaResourceGovernor | Get-DbaRgResourcePool -Type External\nGets the external resource pools on Sql1 and Sql2/sqlexpress instances",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to SQL Server using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Type",
                           "Internal or External",
                           "",
                           false,
                           "false",
                           "Internal"
                       ],
                       [
                           "InputObject",
                           "Allows input to be piped from Get-DbaResourceGovernor",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaRgResourcePool [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Type] \u003cString\u003e] [[-InputObject] \u003cResourceGovernor[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaRgWorkloadGroup",
        "Description":  "Gets all Resource Governor Pool objects, including both internal and external",
        "Tags":  "ResourceGovernor",
        "Synopsis":  "Gets all Resource Governor Pool objects, including both internal and external",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaRgWorkloadGroup",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaRgWorkloadGroup",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaRgWorkloadGroup -SqlInstance sql2017\nGets the workload groups on sql2017\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaResourceGovernor -SqlInstance sql2017 | Get-DbaRgResourcePool | Get-DbaRgWorkloadGroup\nGets the workload groups on sql2017",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to SQL Server using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows input to be piped from Get-DbaRgResourcePool",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaRgWorkloadGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-InputObject] \u003cResourcePool[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaRunningJob",
        "Description":  "This function returns agent jobs that active on the SQL Server instance when calling the command",
        "Tags":  [
                     "Agent",
                     "Job"
                 ],
        "Synopsis":  "Returns all non-idle Agent jobs running on the server",
        "Alias":  "",
        "Author":  "Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/",
        "CommandName":  "Get-DbaRunningJob",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaRunningJob",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaRunningJob -SqlInstance sql2017\nReturns any active jobs on sql2017\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance sql2017, sql2019 | Get-DbaRunningJob\nReturns all active jobs on multiple instances piped into the function.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers | Get-DbaRunningJob\nReturns all active jobs on multiple instances piped into the function.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piped input from Get-DbaAgentJob",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaRunningJob [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-InputObject] \u003cJob[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaSchemaChangeHistory",
        "Description":  "Queries the default system trace for any DDL changes in the specified time frame\nOnly works with SQL 2005 and later, as the system trace didn\u0027t exist before then",
        "Tags":  [
                     "Migration",
                     "Backup",
                     "Database"
                 ],
        "Synopsis":  "Gets DDL changes logged in the system trace.",
        "Alias":  "",
        "Author":  "Stuart Moore (@napalmgram - http://stuart-moore.com)",
        "CommandName":  "Get-DbaSchemaChangeHistory",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaSchemaChangeHistory",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaSchemaChangeHistory -SqlInstance localhost\nReturns all DDL changes made in all databases on the SQL Server instance localhost since the system trace began\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaSchemaChangeHistory -SqlInstance localhost -Since (Get-Date).AddDays(-7)\nReturns all DDL changes made in all databases on the SQL Server instance localhost in the last 7 days\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaSchemaChangeHistory -SqlInstance localhost -Database Finance, Prod -Since (Get-Date).AddDays(-7)\nReturns all DDL changes made in the Prod and Finance databases on the SQL Server instance localhost in the last 7 days\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaSchemaChangeHistory -SqlInstance localhost -Database Finance -Object AccountsTable -Since (Get-Date).AddDays(-7)\nReturns all DDL changes made  to the AccountsTable object in the Finance database on the SQL Server instance localhost in the last 7 days",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Since",
                           "A date from which DDL changes should be returned. Default is to start at the beginning of the current trace file",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Object",
                           "The name of a SQL Server object you want to look for changes on",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaSchemaChangeHistory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-Since \u003cDbaDateTime\u003e] [-Object \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaServerAudit",
        "Description":  "The Get-DbaServerAudit command gets SQL Security Audit information for each instance(s) of SQL Server.",
        "Tags":  [
                     "Audit",
                     "Security",
                     "SqlAudit"
                 ],
        "Synopsis":  "Gets SQL Security Audit information for each instance(s) of SQL Server.",
        "Alias":  "",
        "Author":  "Garry Bargsley (@gbargsley), http://blog.garrybargsley.com",
        "CommandName":  "Get-DbaServerAudit",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaServerAudit",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaServerAudit -SqlInstance localhost\nReturns all Security Audits on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaServerAudit -SqlInstance localhost, sql2016\nReturns all Security Audits for the local and sql2016 SQL Server instances",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Audit",
                           "Return only specific audits",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeAudit",
                           "Exclude specific audits",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaServerAudit [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Audit \u003cString[]\u003e] [-ExcludeAudit \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaServerAuditSpecification",
        "Description":  "The Get-DbaServerAuditSpecification command gets SQL Security Audit Specification information for each instance(s) of SQL Server.",
        "Tags":  [
                     "Audit",
                     "Security",
                     "SqlAudit"
                 ],
        "Synopsis":  "Gets SQL Security Audit Specification information for each instance(s) of SQL Server.",
        "Alias":  "",
        "Author":  "Garry Bargsley (@gbargsley), http://blog.garrybargsley.com",
        "CommandName":  "Get-DbaServerAuditSpecification",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaServerAuditSpecification",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaServerAuditSpecification -SqlInstance localhost\nReturns all Security Audit Specifications on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaServerAuditSpecification -SqlInstance localhost, sql2016\nReturns all Security Audit Specifications for the local and sql2016 SQL Server instances",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaServerAuditSpecification [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaServerInstallDate",
        "Description":  "This command returns:\nSqlInstallDate\nWindowsInstallDate (use -IncludeWindows)",
        "Tags":  "Install",
        "Synopsis":  "Returns the install date of a SQL Instance and Windows Server.",
        "Alias":  "",
        "Author":  "Mitchell Hamann (@SirCaptainMitch), mitchellhamann.com",
        "CommandName":  "Get-DbaServerInstallDate",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaServerInstallDate",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaServerInstallDate -SqlInstance SqlBox1\\Instance2\nReturns an object with SQL Instance Install date as a string.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaServerInstallDate -SqlInstance winserver\\sqlexpress, sql2016\nReturns an object with SQL Instance Install date as a string for both SQLInstances that are passed to the cmdlet.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027sqlserver2014a\u0027, \u0027sql2016\u0027 | Get-DbaServerInstallDate\nReturns an object with SQL Instance Install date as a string for both SQLInstances that are passed to the cmdlet via the pipeline.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaServerInstallDate -SqlInstance sqlserver2014a, sql2016 -IncludeWindows\nReturns an object with the Windows Install date and the SQL install date as a string.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sql2014 | Get-DbaServerInstallDate\nReturns an object with SQL Instance install date as a string for every server listed in the Central Management Server on sql2014",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer,ComputerName",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Credential object used to connect to the SQL Server using SQL Authentication as a different user",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Credential",
                           "Credential object used to connect to the SQL Server as a different Windows user",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IncludeWindows",
                           "Includes the Windows Server Install date information",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaServerInstallDate [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [-IncludeWindows] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaServerProtocol",
        "Description":  "Gets the SQL Server related server protocols on one or more computers.\n\nRequires Local Admin rights on destination computer(s).\nThe server protocols can be enabled and disabled when retrieved via WSMan.",
        "Tags":  "Protocol",
        "Synopsis":  "Gets the SQL Server related server protocols on a computer.",
        "Alias":  "",
        "Author":  "Klaas Vandenberghe ( @PowerDBAKlaas )",
        "CommandName":  "Get-DbaServerProtocol",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaServerProtocol",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaServerProtocol -ComputerName sqlserver2014a\nGets the SQL Server related server protocols on computer sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\u0027,\u0027sql3\u0027 | Get-DbaServerProtocol\nGets the SQL Server related server protocols on computers sql1, sql2 and sql3.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaServerProtocol -ComputerName sql1,sql2 | Out-GridView\nGets the SQL Server related server protocols on computers sql1 and sql2, and shows them in a grid view.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e(Get-DbaServerProtocol -ComputerName sql1 | Where { $_.DisplayName = \u0027via\u0027 }).Disable()\nDisables the VIA ServerNetworkProtocol on computer sql1.\r\nIf successful, return code 0 is shown.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target SQL Server instance or instances.",
                           "cn,host,Server",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Credential object used to connect to the computer as a different user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaServerProtocol [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaServerRole",
        "Description":  "Gets the list of server-level roles for SQL Server instance.",
        "Tags":  [
                     "ServerRole",
                     "Security"
                 ],
        "Synopsis":  "Gets the list of server-level roles.",
        "Alias":  "",
        "Author":  "Shawn Melton (@wsmelton)",
        "CommandName":  "Get-DbaServerRole",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaServerRole",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaServerRole -SqlInstance sql2016a\nOutputs list of server-level roles for sql2016a instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaServerRole -SqlInstance sql2017a -ExcludeFixedRole\nOutputs the server-level role(s) that are not fixed roles on sql2017a instance.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2005 or higher.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ServerRole",
                           "Server-Level role to filter results to that role only.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeServerRole",
                           "Server-Level role to exclude from results.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeFixedRole",
                           "Filter the fixed server-level roles. Only applies to SQL Server 2017 that supports creation of server-level roles.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because \r\nit basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaServerRole [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-ServerRole \u003cString[]\u003e] [-ExcludeServerRole \u003cString[]\u003e] [-ExcludeFixedRole] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaServerRoleMember",
        "Description":  "The Get-DbaServerRoleMember returns connected SMO object for server roles for each instance(s) of SQL Server.",
        "Tags":  [
                     "ServerRole",
                     "Security",
                     "Login"
                 ],
        "Synopsis":  "Get members of server roles for each instance(s) of SQL Server.",
        "Alias":  "",
        "Author":  "Klaas Vandenberghe (@PowerDBAKlaas)",
        "CommandName":  "Get-DbaServerRoleMember",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaServerRoleMember",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaServerRoleMember -SqlInstance localhost\nReturns all members of all server roles on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaServerRoleMember -SqlInstance localhost, sql2016\nReturns all members of all server roles on the local and sql2016 SQL Server instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers = Get-Content C:\\servers.txt\nPS C:\\\u003e $servers | Get-DbaServerRoleMember\nReturns all members of all server roles for every server in C:\\servers.txt\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaServerRoleMember -SqlInstance localhost -ServerRole \u0027sysadmin\u0027, \u0027dbcreator\u0027\nReturns all members of the sysadmin or dbcreator roles on localhost.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaServerRoleMember -SqlInstance localhost -ExcludeServerRole \u0027sysadmin\u0027\nReturns all members of server-level roles other than sysadmin.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaServerRoleMember -SqlInstance sql2017a -ExcludeFixedRole\nReturns all members of server-level role(s) that are not fixed roles on sql2017a instance.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaServerRoleMember -SqlInstance localhost -Login \u0027MyFriendlyDeveloper\u0027\nReturns all server-level role(s) for the MyFriendlyDeveloper login on localhost.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternate Windows or SQL Login Authentication. Accepts credential objects (Get-Credential).",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ServerRole",
                           "The role(s) to process. If unspecified, all roles will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeServerRole",
                           "The role(s) to exclude.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Login",
                           "The login(s) to process. If unspecified, all logins will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeFixedRole",
                           "Filter the fixed server-level roles. Only applies to SQL Server 2017 that supports creation of server-level roles.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaServerRoleMember [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-ServerRole \u003cString[]\u003e] [-ExcludeServerRole \u003cString[]\u003e] [-Login \u003cObject[]\u003e] [-ExcludeFixedRole] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaServerTrigger",
        "Description":  "Get all existing server triggers on one or more SQL instances.",
        "Tags":  [
                     "Database",
                     "Trigger"
                 ],
        "Synopsis":  "Get all existing server triggers on one or more SQL instances.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaServerTrigger",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaServerTrigger",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaServerTrigger -SqlInstance sql2017\nReturns all server triggers on sql2017",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "SqlCredential object used to connect to the SQL Server as a different user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaServerTrigger [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaService",
        "Description":  "Gets the SQL Server related services on one or more computers.\n\nRequires Local Admin rights on destination computer(s).",
        "Tags":  [
                     "Service",
                     "SqlServer",
                     "Instance",
                     "Connect"
                 ],
        "Synopsis":  "Gets the SQL Server related services on a computer.",
        "Alias":  "Get-DbaSqlService",
        "Author":  "Klaas Vandenberghe ( @PowerDBAKlaas )",
        "CommandName":  "Get-DbaService",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaService",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaService -ComputerName sqlserver2014a\nGets the SQL Server related services on computer sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\u0027,\u0027sql3\u0027 | Get-DbaService -AdvancedProperties\nGets the SQL Server related services on computers sql1, sql2 and sql3. Includes Advanced Properties from the SqlServiceAdvancedProperty Namespace\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$cred = Get-Credential WindowsUser\nPS C:\\\u003e Get-DbaService -ComputerName sql1,sql2 -Credential $cred  | Out-GridView\nGets the SQL Server related services on computers sql1 and sql2 via the user WindowsUser, and shows them in a grid view.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaService -ComputerName sql1,sql2 -InstanceName MSSQLSERVER\nGets the SQL Server related services related to the default instance MSSQLSERVER on computers sql1 and sql2.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaService -ComputerName $MyServers -Type SSRS\nGets the SQL Server related services of type \"SSRS\" (Reporting Services) on computers in the variable MyServers.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$MyServers =  Get-Content .\\servers.txt\nPS C:\\\u003e Get-DbaService -ComputerName $MyServers -ServiceName MSSQLSERVER,SQLSERVERAGENT\nGets the SQL Server related services with ServiceName MSSQLSERVER or SQLSERVERAGENT  for all the servers that are stored in the file. Every line in the file can only contain one hostname for a server.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$services = Get-DbaService -ComputerName sql1 -Type Agent,Engine\nPS C:\\\u003e $services.ChangeStartMode(\u0027Manual\u0027)\nGets the SQL Server related services of types Sql Agent and DB Engine on computer sql1 and changes their startup mode to \u0027Manual\u0027.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e(Get-DbaService -ComputerName sql1 -Type Engine).Restart($true)\nCalls a Restart method for each Engine service on computer sql1.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target SQL Server instance or instances.",
                           "cn,host,Server",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "InstanceName",
                           "Only returns services that belong to the specific instances.",
                           "Instance",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Credential",
                           "Credential object used to connect to the computer as a different user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Type",
                           "Use -Type to collect only services of the desired SqlServiceType.\r\nCan be one of the following: \"Agent\",\"Browser\",\"Engine\",\"FullText\",\"SSAS\",\"SSIS\",\"SSRS\", \"PolyBase\"",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ServiceName",
                           "Can be used to specify service names explicitly, without looking for service types/instances.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AdvancedProperties",
                           "Collect additional properties from the SqlServiceAdvancedProperty Namespace\r\nThis collects information about Version, Service Pack Level\", SkuName, Clustered status and the Cluster Service Name\r\nThis adds additional overhead to the command.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaService [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [-InstanceName \u003cString[]\u003e] [-Credential \u003cPSCredential\u003e] [-Type \u003cString[]\u003e] [-AdvancedProperties] [-EnableException] [\u003cCommonParameters\u003e]\nGet-DbaService [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [-Credential \u003cPSCredential\u003e] [-ServiceName \u003cString[]\u003e] [-AdvancedProperties] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaSpConfigure",
        "Description":  "This function returns server level system configuration (sys.configuration/sp_configure) information. The information is gathered through SMO Configuration.Properties.\nThe data includes the default value for each configuration, for quick identification of values that may have been changed.",
        "Tags":  [
                     "SpConfig",
                     "Configure",
                     "Configuration"
                 ],
        "Synopsis":  "Returns all server level system configuration (sys.configuration/sp_configure) information",
        "Alias":  "",
        "Author":  "Nic Cain, https://sirsql.net/",
        "CommandName":  "Get-DbaSpConfigure",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaSpConfigure",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaSpConfigure -SqlInstance localhost\nReturns all system configuration information on the localhost.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027localhost\u0027,\u0027localhost\\namedinstance\u0027 | Get-DbaSpConfigure\nReturns system configuration information on multiple instances piped into the function\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaSpConfigure -SqlInstance sql2012 -Name \u0027max server memory (MB)\u0027\nReturns only the system configuration for MaxServerMemory on sql2012.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaSpConfigure -SqlInstance sql2012 -ExcludeName \u0027max server memory (MB)\u0027, RemoteAccess | Out-GridView\nReturns system configuration information on sql2012 but excludes for max server memory (MB) and remote access. Values returned in grid view\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$cred = Get-Credential SqlCredential\nPS C:\\\u003e \u0027sql2012\u0027 | Get-DbaSpConfigure -SqlCredential $cred -Name RemoteAccess, \u0027max server memory (MB)\u0027 -ExcludeName \u0027remote access\u0027 | Out-GridView\nReturns system configuration information on sql2012 using SQL Server Authentication. Only MaxServerMemory is returned as RemoteAccess was also excluded.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "Return only specific configurations. Name can be either values from (sys.configuration/sp_configure) or from SMO object",
                           "Config,ConfigName",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeName",
                           "Exclude specific configurations. Name can be either values from (sys.configuration/sp_configure) or from SMO object",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaSpConfigure [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Name \u003cString[]\u003e] [-ExcludeName \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaSpinLockStatistic",
        "Description":  "This command is based off of Paul Randal\u0027s post \"Advanced SQL Server performance tuning\"\n\nReturns:\n        SpinLockName\n        Collisions\n        Spins\n        SpinsPerCollision\n        SleepTime\n        Backoffs\n\nReference:  https://www.sqlskills.com/blogs/paul/advanced-performance-troubleshooting-waits-latches-spinlocks/",
        "Tags":  [
                     "SpinLockStatistics",
                     "Waits"
                 ],
        "Synopsis":  "Displays information from sys.dm_os_spinlock_stats.  Works on SQL Server 2008 and above.",
        "Alias":  "",
        "Author":  "Patrick Flynn (@sqllensman)",
        "CommandName":  "Get-DbaSpinLockStatistic",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaSpinLockStatistic",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaSpinLockStatistic -SqlInstance sql2008, sqlserver2012\nGet SpinLock Statistics for servers sql2008 and sqlserver2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$output = Get-DbaSpinLockStatistic -SqlInstance sql2008 | Select * | ConvertTo-DbaDataTable\nCollects all SpinLock Statistics on server sql2008 into a Data Table.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027sql2008\u0027,\u0027sqlserver2012\u0027 | Get-DbaSpinLockStatistic\nGet SpinLock Statistics for servers sql2008 and sqlserver2012 via pipline\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaSpinLockStatistic -SqlInstance sql2008 -SqlCredential $cred\nConnects using sqladmin credential and returns SpinLock Statistics from sql2008",
        "Params":  [
                       [
                           "SqlInstance",
                           "The SQL Server instance. Server version must be SQL Server version 2008 or higher.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaSpinLockStatistic [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaSpn",
        "Description":  "Get a list of set SPNs. SPNs are set at the AD account level. You can either retrieve set SPNs for a computer, or any SPNs set for\na given active directory account. You can query one, or both. You\u0027ll get a list of every SPN found for either search term.",
        "Tags":  "SPN",
        "Synopsis":  "Returns a list of set service principal names for a given computer/AD account",
        "Alias":  "",
        "Author":  "Drew Furgiuele (@pittfurg), http://www.port1433.com",
        "CommandName":  "Get-DbaSpn",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaSpn",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaSpn -ComputerName SQLSERVERA -Credential ad\\sqldba\nReturns a custom object with SearchTerm (ServerName) and the SPNs that were found\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaSpn -AccountName domain\\account -Credential ad\\sqldba\nReturns a custom object with SearchTerm (domain account) and the SPNs that were found\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaSpn -ComputerName SQLSERVERA,SQLSERVERB -Credential ad\\sqldba\nReturns a custom object with SearchTerm (ServerName) and the SPNs that were found for multiple computers",
        "Params":  [
                       [
                           "ComputerName",
                           "The servers you want to return set SPNs for. This is defaulted automatically to localhost.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "AccountName",
                           "The accounts you want to retrieve set SPNs for.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Credential",
                           "User credential to connect to the remote servers or active directory.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaSpn [[-ComputerName] \u003cString[]\u003e] [[-AccountName] \u003cString[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaSsisEnvironmentVariable",
        "Description":  "This command gets all variables from specified environment from SSIS Catalog. All sensitive values are decrypted.\nThe function communicates directly with SSISDB database, \"SQL Server Integration Services\" service isn\u0027t queried there.\nEach parameter (besides SqlInstance and SqlCredential) acts as the filter to only include or exclude particular element",
        "Tags":  [
                     "SSIS",
                     "SSISDB",
                     "Variable"
                 ],
        "Synopsis":  "This command gets specified SSIS Environment and all its variables",
        "Alias":  "",
        "Author":  "Bartosz Ratajczyk (@b_ratajczyk)",
        "CommandName":  "Get-DbaSsisEnvironmentVariable",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaSsisEnvironmentVariable",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaSsisEnvironmentVariable -SqlInstance localhost -Environment DEV -Folder DWH_ETL\nGets variables of \u0027DEV\u0027 environment located in \u0027DWH_ETL\u0027 folder on \u0027localhost\u0027 Server\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaSsisEnvironmentVariable -SqlInstance localhost -Environment DEV -Folder DWH_ETL, DEV2, QA\nGets variables of \u0027DEV\u0027 environment(s) located in folders \u0027DWH_ETL\u0027, \u0027DEV2\u0027 and \u0027QA\u0027 on \u0027localhost\u0027 server\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaSsisEnvironmentVariable -SqlInstance localhost -Environment DEV -FolderExclude DWH_ETL, DEV2, QA\nGets variables of \u0027DEV\u0027 environments located in folders other than \u0027DWH_ETL\u0027, \u0027DEV2\u0027 and \u0027QA\u0027 on \u0027localhost\u0027 server\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaSsisEnvironmentVariable -SqlInstance localhost -Environment DEV, PROD -Folder DWH_ETL, DEV2, QA\nGets variables of \u0027DEV\u0027 and \u0027PROD\u0027 environment(s) located in folders \u0027DWH_ETL\u0027, \u0027DEV2\u0027 and \u0027QA\u0027 on \u0027localhost\u0027 server\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaSsisEnvironmentVariable -SqlInstance localhost -EnvironmentExclude DEV, PROD -Folder DWH_ETL, DEV2, QA\nGets variables of environments other than \u0027DEV\u0027 and \u0027PROD\u0027 located in folders \u0027DWH_ETL\u0027, \u0027DEV2\u0027 and \u0027QA\u0027 on \u0027localhost\u0027 server\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaSsisEnvironmentVariable -SqlInstance localhost -EnvironmentExclude DEV, PROD -FolderExclude DWH_ETL, DEV2, QA\nGets variables of environments other than \u0027DEV\u0027 and \u0027PROD\u0027 located in folders other than \u0027DWH_ETL\u0027, \u0027DEV2\u0027 and \u0027QA\u0027 on \u0027localhost\u0027 server\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e\u0027localhost\u0027 | Get-DbaSsisEnvironmentVariable -EnvironmentExclude DEV, PROD\nGets all SSIS environments except \u0027DEV\u0027 and \u0027PROD\u0027 from \u0027localhost\u0027 server. The server name comes from pipeline\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e\u0027SRV1\u0027, \u0027SRV3\u0027 | Get-DbaSsisEnvironmentVariable\nGets all SSIS environments from \u0027SRV1\u0027 and \u0027SRV3\u0027 servers. The server\u0027s names come from pipeline\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003e\u0027SRV1\u0027, \u0027SRV2\u0027 | Get-DbaSsisEnvironmentVariable DEV | Out-GridView\nGets all variables from \u0027DEV\u0027 Environment(s) on servers \u0027SRV1\u0027 and \u0027SRV2\u0027 and outputs it as the GridView.\r\nThe server names come from the pipeline.\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003e\u0027localhost\u0027 | Get-DbaSsisEnvironmentVariable -EnvironmentExclude DEV, PROD | Select-Object -Property Name, Value | Where-Object {$_.Name -match \u0027^a\u0027} | Out-GridView\nGets all variables from Environments other than \u0027DEV\u0027 and \u0027PROD\u0027 on \u0027localhost\u0027 server,\r\nselects Name and Value properties for variables that names start with letter \u0027a\u0027 and outputs it as the GridView",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.\r\nThis can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.",
                           "SqlServer,ServerInstance",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Environment",
                           "The SSIS Environments names that we want to get variables from",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnvironmentExclude",
                           "The SSIS Environments to exclude. Acts as a filter for environments, best used without \u0027Environment\u0027 parameter\r\nto get variables for all environments but excluded ones",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Folder",
                           "The Folders names that contain the environments",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "FolderExclude",
                           "The Folders names to exclude. Acts as a filter for folders containing environments, best user without \u0027Folder\u0027 parameter\r\nto get variables for all folders but excluded ones",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaSsisEnvironmentVariable [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Environment] \u003cObject[]\u003e] [[-EnvironmentExclude] \u003cObject[]\u003e] [[-Folder] \u003cObject[]\u003e] [[-FolderExclude] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaSsisExecutionHistory",
        "Description":  "This command gets execution history for SSIS executison given one or more instances and can be filtered by Project, Environment,Folder or Status.",
        "Tags":  [
                     "Migration",
                     "SSIS"
                 ],
        "Synopsis":  "Get-DbaSsisHistory Retreives SSIS project and package execution History, and environments from one SQL Server to another.",
        "Alias":  "",
        "Author":  "Chris Tucker (@ChrisTuc47368095)",
        "CommandName":  "Get-DbaSsisExecutionHistory",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaSsisExecutionHistory",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaSsisExecutionHistory -SqlInstance SMTQ01 -Folder SMTQ_PRC\nGet all history items for SMTQ01 in folder SMTQ_PRC.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaSsisExecutionHistory -SqlInstance SMTQ01 -Status Failed,Cancelled\nGets all failed or canceled executions for SMTQ01.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaSsisExecutionHistory -SqlInstance SMTQ01,SMTQ02 -Status Failed,Cancelled -Whatif\nShows what would happen if the command were executed and would return the SQL statement that would be executed per instance.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.\r\nThis can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Since",
                           "Datetime object used to narrow the results to a date",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Status",
                           "Specifies a filter by status (created,running,cancelled,failed,pending,halted,succeeded,stopping,completed)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Project",
                           "Specifies a filter by project",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Folder",
                           "Specifies a filter by folder",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Environment",
                           "Specifies a filter by environment",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaSsisExecutionHistory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Since] \u003cDateTime\u003e] [[-Status] \u003cString[]\u003e] [[-Project] \u003cString[]\u003e] [[-Folder] \u003cString[]\u003e] [[-Environment] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaStartupParameter",
        "Description":  "Displays values for a detailed list of SQL Server Startup Parameters including Master Data Path, Master Log path, Error Log, Trace Flags, Parameter String and much more.\n\nThis command relies on remote Windows Server (SQL WMI/WinRm) access. You can pass alternative Windows credentials by using the -Credential parameter.\n\nSee https://msdn.microsoft.com/en-us/library/ms190737.aspx for more information.",
        "Tags":  [
                     "WSMan",
                     "SQLWMI",
                     "Memory"
                 ],
        "Synopsis":  "Displays values for a detailed list of SQL Server Startup Parameters.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaStartupParameter",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaStartupParameter",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaStartupParameter -SqlInstance sql2014\nLogs into SQL WMI as the current user then displays the values for numerous startup parameters.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$wincred = Get-Credential ad\\sqladmin\nPS C:\\\u003e Get-DbaStartupParameter -SqlInstance sql2014 -Credential $wincred -Simple\nLogs in to WMI using the ad\\sqladmin credential and gathers simplified information about the SQL Server Startup Parameters.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Credential",
                           "Allows you to login to servers using alternate Windows credentials.\n$scred = Get-Credential, then pass $scred object to the -Credential parameter.",
                           "SqlCredential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Simple",
                           "If this switch is enabled, simplified output will be produced including only Server, Master Data Path, Master Log path, ErrorLog, TraceFlags and ParameterString.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "If this switch is enabled, exceptions will be thrown to the caller, which will need to perform its own exception processing. Otherwise, the function will try to catch the exception, interpret it and \r\nprovide a friendly error message.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaStartupParameter [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [-Simple] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaSuspectPage",
        "Description":  "This function returns any records that were stored due to suspect pages in databases on a SQL Server Instance.",
        "Tags":  [
                     "Pages",
                     "DBCC"
                 ],
        "Synopsis":  "Returns data that is stored in SQL for Suspect Pages on the specified SQL Server Instance",
        "Alias":  "",
        "Author":  "Garry Bargsley (@gbargsley), http://blog.garrybargsley.com",
        "CommandName":  "Get-DbaSuspectPage",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaSuspectPage -SqlInstance sql2016\nRetrieve any records stored for Suspect Pages on the sql2016 SQL Server.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaSuspectPage -SqlInstance sql2016 -Database Test\nRetrieve any records stored for Suspect Pages on the sql2016 SQL Server and the Test database only.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Database",
                           "The database to return. If unspecified, all records will be returned.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "A credential to use to connect to the SQL Instance rather than using Windows Authentication",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaSuspectPage [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-Database \u003cObject\u003e] [-SqlCredential \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaTcpPort",
        "Description":  "By default, this function returns just the TCP port used by the specified SQL Server.\n\nIf -All is specified, the server name, IPAddress (ipv4 and ipv6), port number and an indicator of whether or not the port assignment is static are returned.\n\nRemote sqlwmi is used by default. If this doesn\u0027t work, then remoting is used. If neither work, it defaults to T-SQL which can provide only the port.",
        "Tags":  [
                     "SQLWMI",
                     "tcp"
                 ],
        "Synopsis":  "Returns the TCP port used by the specified SQL Server.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaTcpPort",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaTcpPort",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaTcpPort -SqlInstance sqlserver2014a\nReturns just the port number for the default instance on sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaTcpPort -SqlInstance winserver\\sqlexpress, sql2016\nReturns an object with server name and port number for the sqlexpress on winserver and the default instance on sql2016.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaTcpPort -SqlInstance sqlserver2014a, sql2016 -All\nReturns an object with server name, IPAddress (ipv4 and ipv6), port and static ($true/$false) for sqlserver2014a and sql2016.\nRemote sqlwmi is used by default. If this doesn\u0027t work, then remoting is used. If neither work, it defaults to T-SQL which can provide only the port.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sql2014 | Get-DbaTcpPort -ExcludeIpv6 -All\nReturns an object with server name, IPAddress (just ipv4), port and static ($true/$false) for every server listed in the Central Management Server on sql2014.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to connect to servers using alternate Windows credentials\n$scred = Get-Credential, then pass $scred object to the -SqlCredential parameter.",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Detailed",
                           "Output all properties, will be deprecated in 1.0.0 release. Use All instead.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "All",
                           "If this switch is enabled, an object with server name, IPAddress (ipv4 and ipv6), port and static ($true/$false) for one or more SQL Servers is returned.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ExcludeIpv6",
                           "If this switch is enabled, IPv6 information is excluded from All output.",
                           "Ipv4",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaTcpPort [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Detailed] [-All] [-ExcludeIpv6] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaTempdbUsage",
        "Description":  "This function queries DMVs for running sessions using tempdb and returns results if those sessions have user or internal space allocated or deallocated against them.",
        "Tags":  [
                     "Tempdb",
                     "Space"
                 ],
        "Synopsis":  "Gets Tempdb usage for running queries.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaTempdbUsage",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaTempdbUsage",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaTempdbUsage -SqlInstance localhost\\SQLDEV2K14\nGets tempdb usage for localhost\\SQLDEV2K14",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "If you want to use alternative credentials to connect to the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaTempdbUsage [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbatoolsConfig",
        "Description":  "Retrieves configuration elements by name.\nCan be used to search the existing configuration list.",
        "Tags":  [
                     "Config",
                     "Module"
                 ],
        "Synopsis":  "Retrieves configuration elements by name.",
        "Alias":  "Get-DbaConfig",
        "Author":  "Friedrich Weinmann (@FredWeinmann)",
        "CommandName":  "Get-DbatoolsConfig",
        "Availability":  "Windows only",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbatoolsConfig \u0027Mail.To\u0027\nRetrieves the configuration element for the key \"Mail.To\"\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbatoolsConfig -Force\nRetrieve all configuration elements from all modules, even hidden ones.",
        "Params":  [
                       [
                           "FullName",
                           "Default: \"*\"\r\nSearch for configurations using the full name",
                           "",
                           false,
                           "false",
                           "*"
                       ],
                       [
                           "Name",
                           "Default: \"*\"\r\nThe name of the configuration element(s) to retrieve.\r\nMay be any string, supports wildcards.",
                           "",
                           false,
                           "false",
                           "*"
                       ],
                       [
                           "Module",
                           "Default: \"*\"\r\nSearch configuration by module.",
                           "",
                           false,
                           "false",
                           "*"
                       ],
                       [
                           "Force",
                           "Overrides the default behavior and also displays hidden configuration values.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbatoolsConfig [[-FullName] \u003cString\u003e] [-Force] [\u003cCommonParameters\u003e]\nGet-DbatoolsConfig [[-Name] \u003cString\u003e] [[-Module] \u003cString\u003e] [-Force] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbatoolsConfigValue",
        "Description":  "Returns the configuration value stored under the specified name.\nIt requires the full name (\u003cModule\u003e.\u003cName\u003e) and is usually only called by functions.",
        "Tags":  [
                     "Config",
                     "Module"
                 ],
        "Synopsis":  "Returns the configuration value stored under the specified name.",
        "Alias":  "Get-DbaConfigValue",
        "Author":  "Friedrich Weinmann (@FredWeinmann)",
        "CommandName":  "Get-DbatoolsConfigValue",
        "Availability":  "Windows only",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbatoolsConfigValue -Name \u0027System.MailServer\u0027\nReturns the configured value that was assigned to the key \u0027System.MailServer\u0027\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbatoolsConfigValue -Name \u0027Default.CoffeeMilk\u0027 -Fallback 0\nReturns the configured value for \u0027Default.CoffeeMilk\u0027. If no such value is configured, it returns \u00270\u0027 instead.",
        "Params":  [
                       [
                           "FullName",
                           "The full name (\u003cModule\u003e.\u003cName\u003e) of the configured value to return.",
                           "Name",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Fallback",
                           "A fallback value to use, if no value was registered to a specific configuration element.\r\nThis basically is a default value that only applies on a \"per call\" basis, rather than a system-wide default.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NotNull",
                           "By default, this function returns null if one tries to retrieve the value from either a Configuration that does not exist or a Configuration whose value was set to null.\r\nHowever, sometimes it may be important that some value was returned.\r\nBy specifying this parameter, the function will throw an error if no value was found at all.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbatoolsConfigValue [-FullName] \u003cString\u003e [[-Fallback] \u003cObject\u003e] [-NotNull] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbatoolsLog",
        "Description":  "Returns log entries for dbatools. Handy when debugging or developing a script using it.",
        "Tags":  "Debug",
        "Synopsis":  "Returns log entries for dbatools",
        "Alias":  "",
        "Author":  "Friedrich Weinmann (@FredWeinmann)",
        "CommandName":  "Get-DbatoolsLog",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbatoolsLog",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbatoolsLog\nReturns all log entries currently in memory.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbatoolsLog -Target \"a\" -Last 1 -Skip 1\nReturns all log entries that targeted the object \"a\" in the second last execution sent.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbatoolsLog -Tag \"fail\" -Last 5\nReturns all log entries within the last 5 executions that contained the tag \"fail\"",
        "Params":  [
                       [
                           "FunctionName",
                           "Default: \"*\"\r\nOnly messages written by similar functions will be returned.",
                           "",
                           false,
                           "false",
                           "*"
                       ],
                       [
                           "ModuleName",
                           "Default: \"*\"\r\nOnly messages written by commands from similar modules will be returned.",
                           "",
                           false,
                           "false",
                           "*"
                       ],
                       [
                           "Target",
                           "Only messags handling the specified target will be returned.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Tag",
                           "Only messages containing one of these tags will be returned.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Last",
                           "Only messages written by the last X executions will be returned.\r\nUses Get-History to determine execution. Ignores Get-message commands.\r\nBy default, this will also include messages from other runspaces. If your command executes in parallel, that\u0027s useful.\r\nIf it doesn\u0027t and you were offloading executions to other runspaces, consider also filtering by runspace using \u0027-Runspace\u0027",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "Skip",
                           "How many executions to skip when specifying \u0027-Last\u0027.\r\nHas no effect without the \u0027-Last\u0027 parameter.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "Runspace",
                           "The guid of the runspace to return messages from.\r\nBy default, messages from all runspaces are returned.\r\nRun the following line to see the list of guids:\nGet-Runspace | ft Id, Name, InstanceId -Autosize",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Level",
                           "Limit the message selection by level.\r\nMessage levels have a numeric value, making it easier to select a range:\n-Level (1..6)\nWill select the first 6 levels (Critical - SomewhatVerbose).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Raw",
                           "By default, messages such as SQL statements are flattened. Use raw to see the output without flattened formatting.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Errors",
                           "Instead of log entries, the error entries will be retrieved",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbatoolsLog [[-FunctionName] \u003cString\u003e] [[-ModuleName] \u003cString\u003e] [[-Target] \u003cObject\u003e] [[-Tag] \u003cString[]\u003e] [[-Last] \u003cInt32\u003e] [[-Skip] \u003cInt32\u003e] [[-Runspace] \u003cGuid\u003e] [[-Level] {Critical | Important | Output | Significant | VeryVerbose | Verbose | SomewhatVerbose | System | Debug | InternalComment | Warning}] [-Raw] [-Errors] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaTopResourceUsage",
        "Description":  "Returns the top 20 resource consumers for cached queries based on four different metrics: duration, frequency, IO, and CPU.\n\nThis command is based off of queries provided by Michael J. Swart at http://michaeljswart.com/go/Top20\n\nPer Michael: \"I\u0027ve posted queries like this before, and others have written many other versions of this query. All these queries are based on sys.dm_exec_query_stats.\"",
        "Tags":  [
                     "Query",
                     "Performance"
                 ],
        "Synopsis":  "Returns the top 20 resource consumers for cached queries based on four different metrics: duration, frequency, IO, and CPU.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaTopResourceUsage",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaTopResourceUsage",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaTopResourceUsage -SqlInstance sql2008, sql2012\nReturn the 80 (20 x 4 types) top usage results by duration, frequency, IO, and CPU servers for servers sql2008 and sql2012\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaTopResourceUsage -SqlInstance sql2008 -Type Duration, Frequency -Database TestDB\nReturn the highest usage by duration (top 20) and frequency (top 20) for the TestDB on sql2008\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaTopResourceUsage -SqlInstance sql2016 -Limit 30\nReturn the highest usage by duration (top 30) and frequency (top 30) for the TestDB on sql2016\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaTopResourceUsage -SqlInstance sql2008, sql2012 -ExcludeSystem\nReturn the 80 (20 x 4 types) top usage results by duration, frequency, IO, and CPU servers for servers sql2008 and sql2012 without any System Objects\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaTopResourceUsage -SqlInstance sql2016| Select-Object *\nReturn all the columns plus the QueryPlan column",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Type",
                           "By default, all Types run but you can specify one or more of the following: Duration, Frequency, IO, or CPU",
                           "",
                           false,
                           "false",
                           "All"
                       ],
                       [
                           "Limit",
                           "By default, these query the Top 20 worst offenders (though more than 20 results can be returned if each of the top 20 have more than 1 subsequent result)",
                           "",
                           false,
                           "false",
                           "20"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ExcludeSystem",
                           "This will exclude system objects like replication procedures from being returned.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaTopResourceUsage [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-Type \u003cString[]\u003e] [-Limit \u003cInt32\u003e] [-EnableException] [-ExcludeSystem] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaTrace",
        "Description":  "This function returns a list of traces on a SQL Server instance and identifies the default trace file",
        "Tags":  [
                     "Security",
                     "Trace"
                 ],
        "Synopsis":  "Gets a list of trace(s) from specified SQL Server Instance",
        "Alias":  "Get-DbaTraceFile",
        "Author":  "Garry Bargsley (@gbargsley), http://blog.garrybargsley.com",
        "CommandName":  "Get-DbaTrace",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaTrace -SqlInstance sql2016\nLists all the trace files on the sql2016 SQL Server.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaTrace -SqlInstance sql2016 -Default\nLists the default trace information on the sql2016 SQL Server.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "A credential to use to connect to the SQL Instance rather than using Windows Authentication",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Id",
                           "The id(s) of the Trace",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Default",
                           "Switch that will only return the information for the default system trace",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaTrace [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Id \u003cInt32[]\u003e] [-Default] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaTraceFlag",
        "Description":  "Returns Trace Flags that are enabled globally on each instance(s) of SQL Server as an object.",
        "Tags":  [
                     "TraceFlag",
                     "DBCC"
                 ],
        "Synopsis":  "Get global Trace Flag(s) information for each instance(s) of SQL Server.",
        "Alias":  "",
        "Author":  "Kevin Bullen (@sqlpadawan)",
        "CommandName":  "Get-DbaTraceFlag",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaTraceFlag",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaTraceFlag -SqlInstance localhost\nReturns all Trace Flag information on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaTraceFlag -SqlInstance localhost, sql2016\nReturns all Trace Flag(s) for the local and sql2016 SQL Server instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaTraceFlag -SqlInstance localhost -TraceFlag 4199,3205\nReturns Trace Flag status for TF 4199 and 3205 for the local SQL Server instance if they are enabled.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "TraceFlag",
                           "Use this switch to filter to a specific Trace Flag.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaTraceFlag [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-TraceFlag \u003cInt32[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaUptime",
        "Description":  "By default, this command returns for each SQL Server instance passed in:\nSQL Instance last startup time, Uptime as a PS TimeSpan, Uptime as a formatted string\nHosting Windows server last startup time, Uptime as a PS TimeSpan, Uptime as a formatted string",
        "Tags":  "CIM",
        "Synopsis":  "Returns the uptime of the SQL Server instance, and if required the hosting windows server",
        "Alias":  "",
        "Author":  "Stuart Moore (@napalmgram), stuart-moore.com",
        "CommandName":  "Get-DbaUptime",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaUptime",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaUptime -SqlInstance SqlBox1\\Instance2\nReturns an object with SQL Server start time, uptime as TimeSpan object, uptime as a string, and Windows host boot time, host uptime as TimeSpan objects and host uptime as a string for the sqlexpress \r\ninstance on winserver\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaUptime -SqlInstance winserver\\sqlexpress, sql2016\nReturns an object with SQL Server start time, uptime as TimeSpan object, uptime as a string, and Windows host boot time, host uptime as TimeSpan objects and host uptime as a string for the sqlexpress \r\ninstance on host winserver  and the default instance on host sql2016\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sql2014 | Get-DbaUptime\nReturns an object with SQL Server start time, uptime as TimeSpan object, uptime as a string, and Windows host boot time, host uptime as TimeSpan objects and host uptime as a string for every server \r\nlisted in the Central Management Server on sql2014",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer,ComputerName",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to servers using SQL Logins instead of Windows Authentication (AKA Integrated or Trusted). To use:\n$scred = Get-Credential, then pass $scred object to the -SqlCredential parameter.\nWindows Authentication will be used if SqlCredential is not specified. SQL Server does not accept Windows credentials being passed as credentials.\nTo connect to SQL Server as a different Windows user, run PowerShell as that user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Credential",
                           "Allows you to login to the computer (not SQL Server instance) using alternative Windows credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaUptime [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaUserPermission",
        "Description":  "This command will display all server logins, server level securable, database logins and database securables.\n\nDISA STIG implementators will find this command useful as it uses Permissions.sql provided by DISA.\n\nNote that if you Ctrl-C out of this command and end it prematurely, it will leave behind a STIG schema in tempdb.",
        "Tags":  [
                     "Discovery",
                     "Permissions",
                     "Security"
                 ],
        "Synopsis":  "Displays detailed permissions information for the server and database roles and securables.",
        "Alias":  "Get-DbaUserLevelPermission",
        "Author":  "Brandon Abshire, netnerds.net",
        "CommandName":  "Get-DbaUserPermission",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaUserPermission",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaUserPermission -SqlInstance sql2008, sqlserver2012\nCheck server and database permissions for servers sql2008 and sqlserver2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaUserPermission -SqlInstance sql2008 -Database TestDB\nCheck server and database permissions on server sql2008 for only the TestDB database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaUserPermission -SqlInstance sql2008 -Database TestDB -IncludePublicGuest -IncludeSystemObjects\nCheck server and database permissions on server sql2008 for only the TestDB database,\r\nincluding public and guest grants, and sys schema objects.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeSystemDatabase",
                           "Allows you to suppress output on system databases",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IncludePublicGuest",
                           "Allows you to include output for public and guest grants.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IncludeSystemObjects",
                           "Allows you to include output on sys schema objects.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaUserPermission [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [[-ExcludeSystemDatabase]] [-IncludePublicGuest] [-IncludeSystemObjects] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaWaitingTask",
        "Description":  "This command is based on waiting task T-SQL script published by Paul Randal.\nReference: https://www.sqlskills.com/blogs/paul/updated-sys-dm_os_waiting_tasks-script-2/",
        "Tags":  [
                     "Waits",
                     "Task",
                     "WaitTask"
                 ],
        "Synopsis":  "Displays waiting task.",
        "Alias":  "",
        "Author":  "Shawn Melton (@wsmelton), https://wsmelton.github.io",
        "CommandName":  "Get-DbaWaitingTask",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaWaitingTask",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWaitingTask -SqlInstance sqlserver2014a\nReturns the waiting task for all sessions on sqlserver2014a\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaWaitingTask -SqlInstance sqlserver2014a -IncludeSystemSpid\nReturns the waiting task for all sessions (user and system) on sqlserver2014a",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server version must be SQL Server version XXXX or higher.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Spid",
                           "Find the waiting task of one or more specific process ids",
                           "",
                           false,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "IncludeSystemSpid",
                           "If this switch is enabled, the output will include the system sessions.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaWaitingTask [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Spid \u003cObject[]\u003e] [-IncludeSystemSpid] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaWaitResource",
        "Description":  "Given a wait resource in the form of \u0027PAGE: 10:1:9180084\u0027 returns the database, data file and the system object which is being waited up.\n\nGiven a wait resource in the form of \u0027KEY: 7:35457594073541168 (de21f92a1572)\u0027, returns the database, object and index that is being waited on, With the -row switch the row data will also be returned.",
        "Tags":  [
                     "Pages",
                     "DBCC"
                 ],
        "Synopsis":  "Returns the resource being waited upon",
        "Alias":  "",
        "Author":  "Stuart Moore (@napalmgram), stuart-moore.com",
        "CommandName":  "Get-DbaWaitResource",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaWaitResource",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWaitResource -SqlInstance server1 -WaitResource \u0027PAGE: 10:1:9180084\u0027\nWill return an object containing; database name, data file name, schema name and the object which owns the resource\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaWaitResource -SqlInstance server2 -WaitResource \u0027KEY: 7:35457594073541168 (de21f92a1572)\u0027\nWill return an object containing; database name, schema name and index name which is being waited on.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaWaitResource -SqlInstance server2 -WaitResource \u0027KEY: 7:35457594073541168 (de21f92a1572)\u0027 -row\nWill return an object containing; database name, schema name and index name which is being waited on, and in addition the contents of the locked row at the time the command is run.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "WaitResource",
                           "The wait resource value as supplied in sys.dm_exec_requests",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Row",
                           "If this switch provided also returns the value of the row being waited on with KEY wait resources",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "Replaces user friendly yellow warnings with bloody red exceptions of doom!\r\nUse this if you want the function to throw terminating errors you want to catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaWaitResource [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-WaitResource] \u003cString\u003e [-Row] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaWaitStatistic",
        "Description":  "This command is based off of Paul Randal\u0027s post \"Wait statistics, or please tell me where it hurts\"\n\nReturns:\nWaitType\nCategory\nWaitSeconds\nResourceSeconds\nSignalSeconds\nWaitCount\nPercentage\nAverageWaitSeconds\nAverageResourceSeconds\nAverageSignalSeconds\nURL\n\nReference: https://www.sqlskills.com/blogs/paul/wait-statistics-or-please-tell-me-where-it-hurts/",
        "Tags":  "WaitStatistic",
        "Synopsis":  "Displays wait statistics",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaWaitStatistic",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaWaitStatistic",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWaitStatistic -SqlInstance sql2008, sqlserver2012\nCheck wait statistics for servers sql2008 and sqlserver2012\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaWaitStatistic -SqlInstance sql2008 -Threshold 98 -IncludeIgnorable\nCheck wait statistics on server sql2008 for thresholds above 98% and include wait stats that are most often, but not always, ignorable\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaWaitStatistic -SqlInstance sql2008 | Select *\nShows detailed notes, if available, from Paul\u0027s post\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$output = Get-DbaWaitStatistic -SqlInstance sql2008 -Threshold 100 -IncludeIgnorable | Select-Object * | ConvertTo-DbaDataTable\nCollects all Wait Statistics (including ignorable waits) on server sql2008 into a Data Table.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$output = Get-DbaWaitStatistic -SqlInstance sql2008\nPS C:\\\u003e foreach ($row in ($output | Sort-Object -Unique Url)) { Start-Process ($row).Url }\nDisplays the output then loads the associated sqlskills website for each result. Opens one tab per unique URL.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2005 or higher.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Threshold",
                           "Threshold, in percentage of all waits on the system. Default per Paul\u0027s post is 95%.",
                           "",
                           false,
                           "false",
                           "95"
                       ],
                       [
                           "IncludeIgnorable",
                           "Some waits are no big deal and can be safely ignored in most circumstances. If you\u0027ve got weird issues with mirroring or AGs.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaWaitStatistic [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Threshold] \u003cInt32\u003e] [-IncludeIgnorable] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaWindowsLog",
        "Description":  "Gets Windows Application events associated with an instance",
        "Tags":  "Logging",
        "Synopsis":  "Gets Windows Application events associated with an instance",
        "Alias":  "",
        "Author":  "Drew Furgiuele | Friedrich Weinmann (@FredWeinmann)",
        "CommandName":  "Get-DbaWindowsLog",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaWindowsLog",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$ErrorLogs = Get-DbaWindowsLog -SqlInstance sql01\\sharepoint\nPS C:\\\u003e $ErrorLogs | Where-Object ErrorNumber -eq 18456\nReturns all lines in the errorlogs that have event number 18456 in them\nThis exists to ignore the Script Analyzer rule for Start-Runspace",
        "Params":  [
                       [
                           "SqlInstance",
                           "The instance(s) to retrieve the event logs from",
                           "ServerInstance,SqlServer",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Start",
                           "Default: 1970\r\nRetrieve all events starting from this timestamp.",
                           "",
                           false,
                           "false",
                           "1/1/1970 00:00:00"
                       ],
                       [
                           "End",
                           "Default: Now\r\nRetrieve all events that happened before this timestamp",
                           "",
                           false,
                           "false",
                           "(Get-Date)"
                       ],
                       [
                           "Credential",
                           "Credential to be used to connect to the Server. Note this is a Windows credential, as this command requires we communicate with the computer and not with the SQL instance.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "MaxThreads",
                           "Default: Unlimited\r\nThe maximum number of parallel threads used on the local computer.\r\nGiven that those will mostly be waiting for the remote system, there is usually no need to limit this.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "MaxRemoteThreads",
                           "Default: 2\r\nThe maximum number of parallel threads that are executed on the target sql server.\r\nThese processes will cause considerable CPU load, so a low limit is advisable in most scenarios.\r\nAny value lower than 1 disables the limit",
                           "",
                           false,
                           "false",
                           "2"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaWindowsLog [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-Start] \u003cDateTime\u003e] [[-End] \u003cDateTime\u003e] [[-Credential] \u003cPSCredential\u003e] [[-MaxThreads] \u003cInt32\u003e] [[-MaxRemoteThreads] \u003cInt32\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaWsfcAvailableDisk",
        "Description":  "Gets information about the disks that can support Failover Clustering and are visible to all nodes, but are not yet part of the set of clustered disks.\n\nAll Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.",
        "Tags":  [
                     "Cluster",
                     "WSFC",
                     "FCI",
                     "HA"
                 ],
        "Synopsis":  "Gets information about the disks that can support Failover Clustering and are visible to all nodes, but are not yet part of the set of clustered disks.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaWsfcAvailableDisk",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaWsfcAvailableDisk",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWsfcAvailableDisk -ComputerName cluster01\nGets available disks from the failover cluster cluster01",
        "Params":  [
                       [
                           "ComputerName",
                           "The target cluster name. Can be a node or the cluster name itself.",
                           "",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to the cluster using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaWsfcAvailableDisk [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaWsfcCluster",
        "Description":  "Gets information about one or more failover clusters in a given domain.\n\nAll Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.",
        "Tags":  [
                     "Cluster",
                     "WSFC",
                     "FCI",
                     "HA"
                 ],
        "Synopsis":  "Gets information about one or more failover clusters in a given domain.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaWsfcCluster",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaWsfcCluster",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWsfcCluster -ComputerName cluster01\nGets failover cluster information about cluster01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaWsfcCluster -ComputerName cluster01 | Select *\nShows all cluster values, including the ones not shown in the default view",
        "Params":  [
                       [
                           "ComputerName",
                           "The target cluster name. Can be a node or the cluster name itself.",
                           "",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to the cluster using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaWsfcCluster [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaWsfcDisk",
        "Description":  "Gets information about the clustered disks on one or more failover clusters in a given domain.\n\nAll Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.",
        "Tags":  [
                     "Cluster",
                     "WSFC",
                     "FCI",
                     "HA"
                 ],
        "Synopsis":  "Gets information about the clustered disks on one or more failover clusters in a given domain.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaWsfcDisk",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaWsfcDisk",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWsfcDisk -ComputerName cluster01\nGets disk information from the failover cluster cluster01",
        "Params":  [
                       [
                           "ComputerName",
                           "The target cluster name. Can be a node or the cluster name itself.",
                           "",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to the cluster using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaWsfcDisk [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaWsfcNetwork",
        "Description":  "Gets information about one or more networks in a failover cluster.\n\nAll Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.",
        "Tags":  [
                     "Cluster",
                     "WSFC",
                     "FCI",
                     "HA"
                 ],
        "Synopsis":  "Gets information about one or more networks in a failover cluster.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaWsfcNetwork",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaWsfcNetwork",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWsfcNetwork -ComputerName cluster01\nGets network information from the failover cluster cluster01",
        "Params":  [
                       [
                           "ComputerName",
                           "The target cluster name. Can be a Network or the cluster name itself.",
                           "",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to the cluster using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaWsfcNetwork [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaWsfcNetworkInterface",
        "Description":  "Gets information about one or more network adapters in a failover cluster.\n\nAll Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.",
        "Tags":  [
                     "Cluster",
                     "WSFC",
                     "FCI",
                     "HA"
                 ],
        "Synopsis":  "Gets information about one or more network adapters in a failover cluster.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaWsfcNetworkInterface",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaWsfcNetworkInterface",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWsfcNetworkInterface -ComputerName cluster01\nGets network interface information from the failover cluster cluster01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaWsfcNetworkInterface -ComputerName cluster01 | Select *\nShows all network interface  values, including the ones not shown in the default view",
        "Params":  [
                       [
                           "ComputerName",
                           "The target cluster name. Can be a Network or the cluster name itself.",
                           "",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to the cluster using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaWsfcNetworkInterface [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaWsfcNode",
        "Description":  "Gets information about one or more nodes, or servers, in a failover cluster.\n\nAll Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.",
        "Tags":  [
                     "Cluster",
                     "WSFC",
                     "FCI",
                     "HA"
                 ],
        "Synopsis":  "Gets information about one or more nodes, or servers, in a failover cluster.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaWsfcNode",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaWsfcNode",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWsfcNode -ComputerName cluster01\nGets node information from the failover cluster cluster01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaWsfcNode -ComputerName cluster01 | Select-Object *\nShows all node values, including the ones not shown in the default view",
        "Params":  [
                       [
                           "ComputerName",
                           "The target cluster name. Can be a node or the cluster name itself.",
                           "",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to the cluster using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaWsfcNode [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaWsfcResource",
        "Description":  "Gets information about one or more resources in a failover cluster.\n\nAll Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.",
        "Tags":  [
                     "Cluster",
                     "WSFC",
                     "FCI",
                     "HA"
                 ],
        "Synopsis":  "Gets information about one or more resources in a failover cluster.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaWsfcResource",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaWsfcResource",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWsfcResource -ComputerName cluster01\nGets resource information from the failover cluster cluster01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaWsfcResource -ComputerName cluster01 | Select *\nShows all resource values, including the ones not shown in the default view",
        "Params":  [
                       [
                           "ComputerName",
                           "The target cluster name. Can be a node or the cluster name itself.",
                           "",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to the cluster using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaWsfcResource [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaWsfcResourceType",
        "Description":  "Gets information about one or more resource types in a failover cluster.\n\nAll Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.",
        "Tags":  [
                     "Cluster",
                     "WSFC",
                     "FCI",
                     "HA"
                 ],
        "Synopsis":  "Gets information about one or more resource types in a failover cluster.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaWsfcResourceType",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaWsfcResourceType",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWsfcResourceType -ComputerName cluster01\nGets resource type information from the failover cluster cluster01",
        "Params":  [
                       [
                           "ComputerName",
                           "The target cluster name. Can be a node or the cluster name itself.",
                           "",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to the cluster using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaWsfcResourceType [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaWsfcRole",
        "Description":  "Gets information about one or more clustered roles (resource groups) in a failover cluster.\n\nAll Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.",
        "Tags":  [
                     "Cluster",
                     "WSFC",
                     "FCI",
                     "HA"
                 ],
        "Synopsis":  "Gets information about one or more clustered roles (resource groups) in a failover cluster.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaWsfcRole",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaWsfcRole",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWsfcRole -ComputerName cluster01\nGets role information from the failover cluster cluster01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaWsfcRole -ComputerName cluster01 | Select *\nShows all role values, including the ones not shown in the default view",
        "Params":  [
                       [
                           "ComputerName",
                           "The target cluster name. Can be a Role or the cluster name itself.",
                           "",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to the cluster using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaWsfcRole [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaWsfcSharedVolume",
        "Description":  "Gets information about Cluster Shared Volumes in a failover cluster.\n\nAll Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.",
        "Tags":  [
                     "Cluster",
                     "WSFC",
                     "FCI",
                     "HA"
                 ],
        "Synopsis":  "Gets information about Cluster Shared Volumes in a failover cluster.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaWsfcSharedVolume",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Get-DbaWsfcSharedVolume",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWsfcSharedVolume -ComputerName cluster01\nGets shared volume (CSV) information from the failover cluster cluster01",
        "Params":  [
                       [
                           "ComputerName",
                           "The target cluster name. Can be a node or the cluster name itself.",
                           "",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to the cluster using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaWsfcSharedVolume [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaXEObject",
        "Description":  "This function returns a list of extended events objects exposed by event packages from specified SQL Server instance(s).",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "Gets a list of extended events objects exposed by event packages from specified SQL Server instance(s).",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaXEObject",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaXEObject -SqlInstance sql2016\nLists all the XE Objects on the sql2016 SQL Server.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaXEObject -SqlInstance sql2017 -Type Action, Event\nLists all the XE Objects of type Action and Event on the sql2017 SQL Server.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Type",
                           "Used to specify the type. Valid types include:\nAction\r\nEvent\r\nMap\r\nMessage\r\nPredicateComparator\r\nPredicateSource\r\nTarget\r\nType",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because \r\nit basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaXEObject [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Type \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaXESession",
        "Description":  "Retrieves a list of Extended Events Sessions present on the specified SQL Server instance(s).",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "Gets a list of Extended Events Sessions from the specified SQL Server instance(s).",
        "Alias":  "Get-DbaXEventSession",
        "Author":  "Klaas Vandenberghe (@PowerDBAKlaas)",
        "CommandName":  "Get-DbaXESession",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaXESession",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance ServerA\\sql987\nReturns a custom object with ComputerName, SQLInstance, Session, StartTime, Status and other properties.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance ServerA\\sql987 | Format-Table ComputerName, SqlInstance, Session, Status -AutoSize\nReturns a formatted table displaying ComputerName, SqlInstance, Session, and Status.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027ServerA\\sql987\u0027,\u0027ServerB\u0027 | Get-DbaXESession\nReturns a custom object with ComputerName, SqlInstance, Session, StartTime, Status and other properties, from multiple SQL instances.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Session",
                           "Only return specific sessions. Options for this parameter are auto-populated from the server.",
                           "Sessions",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaXESession [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Session] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaXESessionTarget",
        "Description":  "Retrieves a list of Extended Events Session Targets from the specified SQL Server instance(s).",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "Get a list of Extended Events Session Targets from the specified SQL Server instance(s).",
        "Alias":  "Get-DbaXEventSessionTarget",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaXESessionTarget",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaXESessionTarget",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaXESessionTarget -SqlInstance ServerA\\sql987 -Session system_health\nShows targets for the system_health session on ServerA\\sql987.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sql2016 -Session system_health | Get-DbaXESessionTarget\nReturns the targets for the system_health session on sql2016.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sql2016 -Session system_health | Get-DbaXESessionTarget -Target package0.event_file\nReturn only the package0.event_file target for the system_health session on sql2016.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Session",
                           "Only return a specific session. Options for this parameter are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Target",
                           "Only return a specific target.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Specifies an XE session returned by Get-DbaXESession to search.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaXESessionTarget [-SqlCredential \u003cPSCredential\u003e] [-Session \u003cString[]\u003e] [-Target \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]\nGet-DbaXESessionTarget -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Session \u003cString[]\u003e] [-Target \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]\nGet-DbaXESessionTarget [-SqlCredential \u003cPSCredential\u003e] [-Session \u003cString[]\u003e] [-Target \u003cString[]\u003e] -InputObject \u003cSession[]\u003e [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaXESessionTemplate",
        "Description":  "Parses Extended Event XML templates. Defaults to parsing templates in the dbatools template repository (\\bin\\xetemplates\\).\n\nThe default repository contains templates from:\nMicrosoft\u0027s Templates that come with SSMS\nJes Borland\u0027s \"Everyday Extended Events\" presentation and GitHub repository (https://github.com/grrlgeek/extended-events)\nChristian Grafe (@ChrGraefe) XE Repo: https://github.com/chrgraefe/sqlscripts/blob/master/XE-Events/\nErin Stellato\u0027s Blog: https://www.sqlskills.com/blogs/erin/\n\nSome profile templates converted using:\nsp_SQLskills_ConvertTraceToExtendedEvents.sql\nJonathan M. Kehayias, SQLskills.com\nhttp://sqlskills.com/blogs/jonathan",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "Parses Extended Event XML templates. Defaults to parsing templates in the dbatools template repository (\\bin\\xetemplates\\).",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaXESessionTemplate",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaXESessionTemplate",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaXESessionTemplate\nReturns information about all the templates in the local dbatools repository.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaXESessionTemplate | Out-GridView -PassThru | Import-DbaXESessionTemplate -SqlInstance sql2017 | Start-DbaXESession\nAllows you to select a Session template, then import it to the specified instance and start the session.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaXESessionTemplate -Path \"$home\\Documents\\SQL Server Management Studio\\Templates\\XEventTemplates\"\nReturns information about all the templates in your local XEventTemplates repository.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaXESessionTemplate -Pattern duration\nReturns information about all the templates that match the word \"duration\" in the title, category or body.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaXESessionTemplate | Select-Object *\nReturns more information about the template, including the full path/filename.",
        "Params":  [
                       [
                           "Path",
                           "The path to the template directory. Defaults to the dbatools template repository (\\bin\\xetemplates\\).",
                           "",
                           false,
                           "false",
                           "\"$script:PSModuleRoot\\bin\\xetemplates\""
                       ],
                       [
                           "Pattern",
                           "Specify a pattern for filtering. Alternatively, you can use Out-GridView -Passthru to select objects and pipe them to Import-DbaXESessionTemplate",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Template",
                           "Specifies one or more of the templates provided by dbatools. Press tab to cycle through the list of options.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaXESessionTemplate [[-Path] \u003cString[]\u003e] [[-Pattern] \u003cString\u003e] [[-Template] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaXESmartTarget",
        "Description":  "Gets an XESmartTarget PowerShell job created by Start-DbaXESmartTarget.",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "Gets an XESmartTarget PowerShell job created by Start-DbaXESmartTarget.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl) | SmartTarget by Gianluca Sartori (@spaghettidba)",
        "CommandName":  "Get-DbaXESmartTarget",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaXESmartTarget",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaXESmartTarget\nGets an XESmartTarget PowerShell Job created by Start-DbaXESmartTarget.",
        "Params":  [
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaXESmartTarget [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Get-DbaXEStore",
        "Description":  "Get a Extended Events store",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "Get a Extended Events store",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Get-DbaXEStore",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Get-DbaXEStore",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaXEStore -SqlInstance ServerA\\sql987\nReturns an XEvent Store.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Get-DbaXEStore [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Grant-DbaAgPermission",
        "Description":  "Grants endpoint and availability group permissions to a login. If the account is a Windows login and does not exist, it will be automatically added.",
        "Tags":  [
                     "AvailabilityGroup",
                     "HA",
                     "AG"
                 ],
        "Synopsis":  "Grants endpoint and availability group permissions to a login.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Grant-DbaAgPermission",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Grant-DbaAgPermission",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGrant-DbaAgPermission -SqlInstance sql2017a -Type AvailabilityGroup -AvailabilityGroup SharePoint -Login ad\\spservice -Permission CreateAnyDatabase\nAdds CreateAnyDatabase permissions to ad\\spservice on the SharePoint availability group on sql2017a. Does not prompt for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGrant-DbaAgPermission -SqlInstance sql2017a -Type AvailabilityGroup -AvailabilityGroup ag1, ag2 -Login ad\\spservice -Permission CreateAnyDatabase -Confirm\nAdds CreateAnyDatabase permissions to ad\\spservice on the ag1 and ag2 availability groups on sql2017a. Prompts for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2017a | Out-GridView -Passthru | Grant-DbaAgPermission -Type EndPoint\nGrants the selected logins Connect permissions on the DatabaseMirroring endpoint for sql2017a",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Login",
                           "The login or logins to modify.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityGroup",
                           "Only modify specific availability groups.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Type",
                           "Specify type: Endpoint or AvailabilityGroup. Endpoint will modify the DatabaseMirror endpoint type.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Permission",
                           "Grants one or more permissions:\r\n    Alter\r\n    Connect\r\n    Control\r\n    CreateSequence\r\n    CreateAnyDatabase\r\n    Delete\r\n    Execute\r\n    Impersonate\r\n    Insert\r\n    Receive\r\n    References\r\n    Select\r\n    Send\r\n    TakeOwnership\r\n    Update\r\n    ViewChangeTracking\r\n    ViewDefinition\n    CreateAnyDatabase\nConnect is default.",
                           "",
                           false,
                           "false",
                           "Connect"
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaLogin.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Grant-DbaAgPermission [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Login] \u003cString[]\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [-Type] \u003cString[]\u003e [[-Permission] \u003cString[]\u003e] [[-InputObject] \u003cLogin[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Import-DbaCmsRegServer",
        "Description":  "Imports registered servers and registered server groups to SQL Server Central Management Server (CMS)",
        "Tags":  [
                     "RegisteredServer",
                     "CMS"
                 ],
        "Synopsis":  "Imports registered servers and registered server groups to SQL Server Central Management Server (CMS)",
        "Alias":  "Import-DbaRegisteredServer",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Import-DbaCmsRegServer",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Import-DbaCmsRegServer",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eImport-DbaCmsRegServer -SqlInstance sql2012 -Path C:\\temp\\corp-regservers.xml\nImports C:\\temp\\corp-regservers.xml to the CMS on sql2012\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eImport-DbaCmsRegServer -SqlInstance sql2008 -Group hr\\Seattle -Path C:\\temp\\Seattle.xml\nImports C:\\temp\\Seattle.xml to Seattle subgroup within the hr group on sql2008\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sql2008, sql2012 | Import-DbaCmsRegServer -SqlInstance sql2017\nImports all registered servers from sql2008 and sql2012 to sql2017\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServerGroup -SqlInstance sql2008 -Group hr\\Seattle | Import-DbaCmsRegServer -SqlInstance sql2017 -Group Seattle\nImports all registered servers from the hr\\Seattle group on sql2008 to the Seattle group on sql2017",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "Optional path to exported reg server XML",
                           "FullName",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaCmsRegServer, Get-DbaCmsRegServerGroup, CSVs and other objects.\nIf importing from CSV or other object, a column named ServerName is required. Optional columns include Name, Description and Group.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Group",
                           "Imports to specific group",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Import-DbaCmsRegServer [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Path] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [[-Group] \u003cObject\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Import-DbaCsv",
        "Description":  "Import-DbaCsv takes advantage of .NET\u0027s super fast SqlBulkCopy class to import CSV files into SQL Server.\n\nThe entire import is performed within a transaction, so if a failure occurs or the script is aborted, no changes will persist.\n\nIf the table or view specified does not exist and -AutoCreateTable, it will be automatically created using slow and efficient but accomodating data types.\n\nThis importer supports fields spanning multiple lines. The only restriction is that they must be quoted, otherwise it would not be possible to distinguish between malformed data and multi-line values.",
        "Tags":  [
                     "Migration",
                     "Import"
                 ],
        "Synopsis":  "Efficiently imports very large (and small) CSV files into SQL Server.",
        "Alias":  "Import-DbaCsvToSql",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Import-DbaCsv",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Import-DbaCsv",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\housing.csv -SqlInstance sql001 -Database markets\nImports the entire comma-delimited housing.csv to the SQL \"markets\" database on a SQL Server named sql001, using the first row as column names.\nSince a table name was not specified, the table name is automatically determined from filename as \"housing\".\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path .\\housing.csv -SqlInstance sql001 -Database markets -Table housing -Delimiter \"`t\" -NoHeaderRow\nImports the entire comma-delimited housing.csv, including the first row which is not used for colum names, to the SQL markets database, into the housing table, on a SQL Server named sql001.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\huge.txt -SqlInstance sqlcluster -Database locations -Table latitudes -Delimiter \"|\"\nImports the entire pipe-delimited huge.txt to the locations database, into the latitudes table on a SQL Server named sqlcluster.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path c:\\temp\\SingleColumn.csv -SqlInstance sql001 -Database markets -Table TempTable -SingleColumn\nImports the single column CSV into TempTable\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-ChildItem -Path \\\\FileServer\\csvs | Import-DbaCsv -SqlInstance sql001, sql002 -Database tempdb -AutoCreateTable\nImports every CSV in the \\\\FileServer\\csvs path into both sql001 and sql002\u0027s tempdb database. Each CSV will be imported into an automatically determined table name.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-ChildItem -Path \\\\FileServer\\csvs | Import-DbaCsv -SqlInstance sql001, sql002 -Database tempdb -AutoCreateTable -WhatIf\nShows what would happen if the command were to be executed\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path c:\\temp\\dataset.csv -SqlInstance sql2016 -Database tempdb -Column Name, Address, Mobile\nImport only Name, Address and Mobile even if other columns exist. All other columns are ignored and therefore null or default values.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e$columns = @{\n\u003e\u003e Text = \u0027FirstName\u0027\r\n\u003e\u003e Number = \u0027PhoneNumber\u0027\r\n\u003e\u003e }\r\nPS C:\\\u003e Import-DbaCsv -Path c:\\temp\\supersmall.csv -SqlInstance sql2016 -Database tempdb -ColumnMap $columns\nThe CSV column \u0027Text\u0027 is inserted into SQL column \u0027FirstName\u0027 and CSV column Number is inserted into the SQL Column \u0027PhoneNumber\u0027. All other columns are ignored and therefore null or default values.",
        "Params":  [
                       [
                           "Path",
                           "Specifies path to the CSV file(s) to be imported. Multiple files may be imported at once.",
                           "Csv,FullPath",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlInstance",
                           "The SQL Server Instance to import data into.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies the name of the database the CSV will be imported into. Options for this this parameter are  auto-populated from the server.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Table",
                           "Specifies the SQL table or view where CSV will be imported into.\nIf a table name is not specified, the table name will be automatically determined from the filename.\nIf the table specified does not exist and -AutoCreateTable, it will be automatically created using slow and efficient but accomodating data types.\nIf the automatically generated table datatypes do not work for you, please create the table prior to import.\nIf you want to import specific columns from a CSV, create a view with corresponding columns.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Schema",
                           "Specifies the schema in which the SQL table or view where CSV will be imported into resides. Default is dbo\nIf a schema name is not specified, and a CSV name with multiple dots is specified (ie; something.data.csv) then this will be interpreted as a request to import into a table [data] in the schema \r\n[something].\nIf a schema does not currently exist, it will be created, after a prompt to confirm this. Authorization will be set to dbo by default",
                           "",
                           false,
                           "false",
                           "dbo"
                       ],
                       [
                           "Truncate",
                           "If this switch is enabled, the destination table will be truncated prior to import.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Delimiter",
                           "Specifies the delimiter used in the imported file(s). If no delimiter is specified, comma is assumed.\nValid delimiters are \u0027`t`, \u0027|\u0027, \u0027;\u0027,\u0027 \u0027 and \u0027,\u0027 (tab, pipe, semicolon, space, and comma).",
                           "",
                           false,
                           "false",
                           ","
                       ],
                       [
                           "SingleColumn",
                           "Specifies that the file contains a single column of data. Otherwise, the delimiter check bombs.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "BatchSize",
                           "Specifies the batch size for the import. Defaults to 50000.",
                           "",
                           false,
                           "false",
                           "50000"
                       ],
                       [
                           "NotifyAfter",
                           "Specifies the import row count interval for reporting progress. A notification will be shown after each group of this many rows has been imported.",
                           "",
                           false,
                           "false",
                           "50000"
                       ],
                       [
                           "TableLock",
                           "If this switch is enabled, the SqlBulkCopy option to acquire a table lock will be used. This is automatically used if -Turbo is enabled.\nPer Microsoft \"Obtain a bulk update lock for the duration of the bulk copy operation. When not\r\nspecified, row locks are used.\"",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "CheckConstraints",
                           "If this switch is enabled, the SqlBulkCopy option to check constraints will be used.\nPer Microsoft \"Check constraints while data is being inserted. By default, constraints are not checked.\"",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "FireTriggers",
                           "If this switch is enabled, the SqlBulkCopy option to allow insert triggers to be executed will be used.\nPer Microsoft \"When specified, cause the server to fire the insert triggers for the rows being inserted into the database.\"",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "KeepIdentity",
                           "If this switch is enabled, the SqlBulkCopy option to keep identity values from the source will be used.\nPer Microsoft \"Preserve source identity values. When not specified, identity values are assigned by the destination.\"",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "KeepNulls",
                           "If this switch is enabled, the SqlBulkCopy option to keep NULL values in the table will be used.\nPer Microsoft \"Preserve null values in the destination table regardless of the settings for default values. When not specified, null values are replaced by default values where applicable.\"",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Column",
                           "Import only specific columns. To remap column names, use the ColumnMap.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ColumnMap",
                           "By default, the bulk copy tries to automap columns. When it doesn\u0027t work as desired, this parameter will help. Check out the examples for more information.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AutoCreateTable",
                           "Creates a table if it does not already exist. The table will be created with sub-optimal data types such as nvarchar(max)",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NoProgress",
                           "The progress bar is pretty but can slow down imports. Use this parameter to quietly import.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NoHeaderRow",
                           "By default, the first row is used to determine column names for the data being imported.\nUse this switch if the first row contains data and not column names.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Quote",
                           "Defines the default quote character wrapping every field.",
                           "",
                           false,
                           "false",
                           "\""
                       ],
                       [
                           "Escape",
                           "Defines the default escape character letting insert quotation characters inside a quoted field.\nThe escape character can be the same as the quote character.",
                           "",
                           false,
                           "false",
                           "\""
                       ],
                       [
                           "Comment",
                           "Defines the default comment character indicating that a line is commented out. Default is #.",
                           "",
                           false,
                           "false",
                           "#"
                       ],
                       [
                           "TrimmingOption",
                           "Determines which values should be trimmed. Default is \"None\". Options are All, None, UnquotedOnly and QuotedOnly.",
                           "",
                           false,
                           "false",
                           "None"
                       ],
                       [
                           "BufferSize",
                           "Defines the default buffer size. The default BufferSize is 4096.",
                           "",
                           false,
                           "false",
                           "4096"
                       ],
                       [
                           "ParseErrorAction",
                           "By default, the parse error action throws an exception and ends the import.\nYou can also choose AdvanceToNextLine which basically ignores parse errors.",
                           "",
                           false,
                           "false",
                           "ThrowException"
                       ],
                       [
                           "Encoding",
                           "The encoding of the file.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NullValue",
                           "The value which denotes a DbNull-value.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Threshold",
                           "Defines the default value for Threshold indicating when the CsvReader should replace/remove consecutive null bytes.",
                           "",
                           false,
                           "false",
                           "60"
                       ],
                       [
                           "MaxQuotedFieldLength",
                           "The axmimum length (in bytes) for any quoted field.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "SkipEmptyLine",
                           "Skip empty lines.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "SupportsMultiline",
                           "Indicates if the importer should support multiline fields.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "UseColumnDefault",
                           "Use the column default values if the field is not in the record.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Import-DbaCsv [[-Path] \u003cObject[]\u003e] [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Database] \u003cString\u003e [[-Table] \u003cString\u003e] [[-Schema] \u003cString\u003e] [-Truncate] [[-Delimiter] \u003cChar\u003e] [-SingleColumn] [[-BatchSize] \u003cInt32\u003e] [[-NotifyAfter] \u003cInt32\u003e] [-TableLock] [-CheckConstraints] [-FireTriggers] [-KeepIdentity] [-KeepNulls] [[-Column] \u003cString[]\u003e] [[-ColumnMap] \u003cHashtable[]\u003e] [-AutoCreateTable] [-NoProgress] [-NoHeaderRow] [[-Quote] \u003cChar\u003e] [[-Escape] \u003cChar\u003e] [[-Comment] \u003cChar\u003e] [[-TrimmingOption] \u003cString\u003e] [[-BufferSize] \u003cInt32\u003e] [[-ParseErrorAction] \u003cString\u003e] \r\n[[-Encoding] \u003cEncoding\u003e] [[-NullValue] \u003cString\u003e] [[-Threshold] \u003cInt32\u003e] [[-MaxQuotedFieldLength] \u003cInt32\u003e] [-SkipEmptyLine] [-SupportsMultiline] [-UseColumnDefault] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Import-DbaPfDataCollectorSetTemplate",
        "Description":  "Imports a new Performance Monitor Data Collector Set Template either from the dbatools repository or a file you specify.\nWhen importing data collector sets from the local instance, Run As Admin is required.\n\nNote: The included counters will be added for all SQL instances on the machine by default.\nFor specific instances in addition to the default, use -Instance.\n\nSee https://msdn.microsoft.com/en-us/library/windows/desktop/aa371952 for more information",
        "Tags":  [
                     "Performance",
                     "DataCollector",
                     "PerfCounter"
                 ],
        "Synopsis":  "Imports a new Performance Monitor Data Collector Set Template either from the dbatools repository or a file you specify.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Import-DbaPfDataCollectorSetTemplate",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Import-DbaPfDataCollectorSetTemplate",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eImport-DbaPfDataCollectorSetTemplate -ComputerName sql2017 -Template \u0027Long Running Query\u0027\nCreates a new data collector set named \u0027Long Running Query\u0027 from the dbatools repository on the SQL Server sql2017.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eImport-DbaPfDataCollectorSetTemplate -ComputerName sql2017 -Template \u0027Long Running Query\u0027 -DisplayName \u0027New Long running query\u0027 -Confirm\nCreates a new data collector set named \"New Long Running Query\" using the \u0027Long Running Query\u0027 template. Forces a confirmation if the template exists.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet -ComputerName sql2017 -Session db_ola_health | Remove-DbaPfDataCollectorSet\nImport-DbaPfDataCollectorSetTemplate -ComputerName sql2017 -Template db_ola_health | Start-DbaPfDataCollectorSet\nImports a session if it exists, then recreates it using a template.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSetTemplate | Out-GridView -PassThru | Import-DbaPfDataCollectorSetTemplate -ComputerName sql2017\nAllows you to select a Session template then import to an instance named sql2017.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eImport-DbaPfDataCollectorSetTemplate -ComputerName sql2017 -Template \u0027Long Running Query\u0027 -Instance SHAREPOINT\nCreates a new data collector set named \u0027Long Running Query\u0027 from the dbatools repository on the SQL Server sql2017 for both the default and the SHAREPOINT instance.\nIf you\u0027d like to remove counters for the default instance, use Remove-DbaPfDataCollectorCounter.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer. Defaults to localhost.",
                           "",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to servers using alternative credentials. To use:\n$scred = Get-Credential, then pass $scred object to the -Credential parameter.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DisplayName",
                           "Sets the display name of the data collector set.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SchedulesEnabled",
                           "If this switch is enabled, sets a value that indicates whether the schedules are enabled.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "RootPath",
                           "Sets the base path where the subdirectories are created.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Segment",
                           "Sets a value that indicates whether PLA creates new logs if the maximum size or segment duration is reached before the data collector set is stopped.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "SegmentMaxDuration",
                           "Sets the duration that the data collector set can run before it begins writing to new log files.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "SegmentMaxSize",
                           "Sets the maximum size of any log file in the data collector set.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "Subdirectory",
                           "Sets a base subdirectory of the root path where the next instance of the data collector set will write its logs.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SubdirectoryFormat",
                           "Sets flags that describe how to decorate the subdirectory name. PLA appends the decoration to the folder name. For example, if you specify plaMonthDayHour, PLA appends the current month, day, and \r\nhour values to the folder name. If the folder name is MyFile, the result could be MyFile110816.",
                           "",
                           false,
                           "false",
                           "3"
                       ],
                       [
                           "SubdirectoryFormatPattern",
                           "Sets a format pattern to use when decorating the folder name. Default is \u0027yyyyMMdd\\-NNNNNN\u0027.",
                           "",
                           false,
                           "false",
                           "yyyyMMdd\\-NNNNNN"
                       ],
                       [
                           "Task",
                           "Sets the name of a Task Scheduler job to start each time the data collector set stops, including between segments.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "TaskRunAsSelf",
                           "If this switch is enabled, sets a value that determines whether the task runs as the data collector set user or as the user specified in the task.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "TaskArguments",
                           "Sets the command-line arguments to pass to the Task Scheduler job specified in the IDataCollectorSet::Task property.\r\nSee https://msdn.microsoft.com/en-us/library/windows/desktop/aa371992 for more information.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "TaskUserTextArguments",
                           "Sets the command-line arguments that are substituted for the {usertext} substitution variable in the IDataCollectorSet::TaskArguments property.\r\nSee https://msdn.microsoft.com/en-us/library/windows/desktop/aa371993 for more information.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "StopOnCompletion",
                           "If this switch is enabled, sets a value that determines whether the data collector set stops when all the data collectors in the set are in a completed state.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Path",
                           "The path to the xml file or files.",
                           "FullName",
                           false,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "Template",
                           "From one or more of the templates from the dbatools repository. Press Tab to cycle through the available options.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Instance",
                           "By default, the template will be applied to all instances. If you want to set specific ones in addition to the default, supply just the instance name.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Import-DbaPfDataCollectorSetTemplate [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-DisplayName] \u003cString\u003e] [-SchedulesEnabled] [[-RootPath] \u003cString\u003e] [-Segment] [[-SegmentMaxDuration] \u003cInt32\u003e] [[-SegmentMaxSize] \u003cInt32\u003e] [[-Subdirectory] \u003cString\u003e] [[-SubdirectoryFormat] \u003cInt32\u003e] [[-SubdirectoryFormatPattern] \u003cString\u003e] [[-Task] \u003cString\u003e] [-TaskRunAsSelf] [[-TaskArguments] \u003cString\u003e] [[-TaskUserTextArguments] \u003cString\u003e] [-StopOnCompletion] [[-Path] \u003cString[]\u003e] [[-Template] \u003cString[]\u003e] [[-Instance] \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] \r\n[\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Import-DbaSpConfigure",
        "Description":  "Updates sp_configure settings on destination server.",
        "Tags":  [
                     "SpConfig",
                     "Configure",
                     "Configuration"
                 ],
        "Synopsis":  "Updates sp_configure settings on destination server.",
        "Alias":  "Import-SqlSpConfigure",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Import-DbaSpConfigure",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Import-DbaSpConfigure",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eImport-DbaSpConfigure -Source sqlserver -Destination sqlcluster\nImports the sp_configure settings from the source server sqlserver and sets them on the sqlcluster server using Windows Authentication\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eImport-DbaSpConfigure -Source sqlserver -Destination sqlcluster -Force\nImports the sp_configure settings from the source server sqlserver and sets them on the sqlcluster server using Windows Authentication. Will not do a version check between Source and Destination\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eImport-DbaSpConfigure -Source sqlserver -Destination sqlcluster -SourceSqlCredential $SourceSqlCredential -DestinationSqlCredential $DestinationSqlCredential\nImports the sp_configure settings from the source server sqlserver and sets them on the sqlcluster server using the SQL credentials stored in the variables $SourceSqlCredential and \r\n$DestinationSqlCredential\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eImport-DbaSpConfigure -SqlInstance sqlserver -Path .\\spconfig.sql -SqlCredential $SqlCredential\nImports the sp_configure settings from the file .\\spconfig.sql and sets them on the sqlserver server using the SQL credential stored in the variable $SqlCredential",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlInstance",
                           "Specifies a SQL Server instance to set up sp_configure values on using a SQL file.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "Specifies the path to a SQL script file holding sp_configure queries for each of the settings to be changed. Export-DbaSPConfigure creates a suitable file as its output.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Use this SQL credential if you are setting up sp_configure values from a SQL file.\nLogin to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, no version check between Source and Destination is performed. By default, the major and minor versions of Source and Destination must match when copying sp_configure \r\nsettings.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Import-DbaSpConfigure [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nImport-DbaSpConfigure [-Source \u003cDbaInstanceParameter\u003e] [-Destination \u003cDbaInstanceParameter\u003e] [-SourceSqlCredential \u003cPSCredential\u003e] [-DestinationSqlCredential \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nImport-DbaSpConfigure [-SqlInstance \u003cDbaInstanceParameter\u003e] [-Path \u003cString\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Import-DbatoolsConfig",
        "Description":  "Imports a json configuration file into the configuration system.",
        "Synopsis":  "Imports a json configuration file into the configuration system.",
        "Alias":  "",
        "CommandName":  "Import-DbatoolsConfig",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eImport-DbatoolsConfig -Path \u0027.\\config.json\u0027\nImports the configuration stored in \u0027.\\config.json\u0027\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eImport-DbatoolsConfig -ModuleName message\nImports all the module specific settings that have been persisted in any of the default file system paths.",
        "Params":  [
                       [
                           "Path",
                           "The path to the json file to import.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "ModuleName",
                           "Import configuration items specific to a module from the default configuration paths.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "ModuleVersion",
                           "The configuration version of the module-settings to load.",
                           "",
                           false,
                           "false",
                           "1"
                       ],
                       [
                           "Scope",
                           "Where to import the module specific configuration items form.\r\nOnly file-based scopes are supported for this.\r\nBy default, all locations are queried, with user settings beating system settings.",
                           "",
                           false,
                           "false",
                           "FileUserLocal, FileUserShared, FileSystem"
                       ],
                       [
                           "IncludeFilter",
                           "If specified, only elements with names that are similar (-like) to names in this list will be imported.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeFilter",
                           "Elements that are similar (-like) to names in this list will not be imported.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Peek",
                           "Rather than applying the setting, return the configuration items that would have been applied.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "This parameters disables user-friendly warnings and enables the throwing of exceptions.\r\nThis is less user friendly, but allows catching exceptions in calling scripts.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Import-DbatoolsConfig -Path \u003cString[]\u003e [-IncludeFilter \u003cString[]\u003e] [-ExcludeFilter \u003cString[]\u003e] [-Peek] [-EnableException] [\u003cCommonParameters\u003e]\nImport-DbatoolsConfig -ModuleName \u003cString\u003e [-ModuleVersion \u003cInt32\u003e] [-Scope {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Import-DbaXESessionTemplate",
        "Description":  "Imports a new XESession XML Template either from the dbatools repository or a file you specify.",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "Imports a new XESession XML Template",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Import-DbaXESessionTemplate",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Import-DbaXESessionTemplate",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eImport-DbaXESessionTemplate -SqlInstance sql2017 -Template db_query_wait_stats\nCreates a new XESession named db_query_wait_stats from the dbatools repository to the SQL Server sql2017.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eImport-DbaXESessionTemplate -SqlInstance sql2017 -Template db_query_wait_stats -Name \"Query Wait Stats\"\nCreates a new XESession named \"Query Wait Stats\" using the db_query_wait_stats template.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sql2017 -Session \u0027Database Health 2014\u0027 | Remove-DbaXESession\nPS C:\\\u003e Import-DbaXESessionTemplate -SqlInstance sql2017 -Template \u0027Database Health 2014\u0027 | Start-DbaXESession\nRemoves a session if it exists, then recreates it using a template.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaXESessionTemplate | Out-GridView -PassThru | Import-DbaXESessionTemplate -SqlInstance sql2017\nAllows you to select a Session template then import to an instance named sql2017.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "The Name of the session to create.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "The path to the xml file or files for the session(s).",
                           "FullName",
                           false,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "Template",
                           "Specifies the name of one of the templates from the dbatools repository. Press tab to cycle through the provided templates.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "TargetFilePath",
                           "By default, files will be created in the default xel directory. Use TargetFilePath to change all instances of\r\nfilename = \"file.xel\" to filename = \"$TargetFilePath\\file.xel\". Only specify the directory, not the file itself.\nThis path is relative to the destination directory",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "TargetFileMetadataPath",
                           "By default, files will be created in the default xem directory. Use TargetFileMetadataPath to change all instances of\r\nfilename = \"file.xem\" to filename = \"$TargetFilePath\\file.xem\". Only specify the directory, not the file itself.\nThis path is relative to the destination directory",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Import-DbaXESessionTemplate [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString\u003e] [[-Path] \u003cString[]\u003e] [[-Template] \u003cString[]\u003e] [[-TargetFilePath] \u003cString\u003e] [[-TargetFileMetadataPath] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Install-DbaFirstResponderKit",
        "Description":  "Downloads, extracts and installs the First Responder Kit stored procedures:\nsp_Blitz, sp_BlitzWho, sp_BlitzFirst, sp_BlitzIndex, sp_BlitzCache and sp_BlitzTrace, etc.\n\nFirst Responder Kit links:\nhttp://FirstResponderKit.org\nhttps://github.com/BrentOzarULTD/SQL-Server-First-Responder-Kit",
        "Tags":  [
                     "BrentOzar",
                     "FRK",
                     "FirstResponderKit"
                 ],
        "Synopsis":  "Installs or updates the First Responder Kit stored procedures.",
        "Alias":  "",
        "Author":  "Tara Kizer, Brent Ozar Unlimited (https://www.brentozar.com/)",
        "CommandName":  "Install-DbaFirstResponderKit",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Install-DbaFirstResponderKit",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInstall-DbaFirstResponderKit -SqlInstance server1 -Database master\nLogs into server1 with Windows authentication and then installs the FRK in the master database.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInstall-DbaFirstResponderKit -SqlInstance server1\\instance1 -Database DBA\nLogs into server1\\instance1 with Windows authentication and then installs the FRK in the DBA database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInstall-DbaFirstResponderKit -SqlInstance server1\\instance1 -Database master -SqlCredential $cred\nLogs into server1\\instance1 with SQL authentication and then installs the FRK in the master database.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInstall-DbaFirstResponderKit -SqlInstance sql2016\\standardrtm, sql2016\\sqlexpress, sql2014\nLogs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs the FRK in the master database.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$servers = \"sql2016\\standardrtm\", \"sql2016\\sqlexpress\", \"sql2014\"\nPS C:\\\u003e $servers | Install-DbaFirstResponderKit\nLogs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs the FRK in the master database.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eInstall-DbaFirstResponderKit -SqlInstance sql2016 -Branch dev\nInstalls the dev branch version of the FRK in the master database on sql2016 instance.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Branch",
                           "Specifies an alternate branch of the First Responder Kit to install. (master or dev)",
                           "",
                           false,
                           "false",
                           "master"
                       ],
                       [
                           "Database",
                           "Specifies the database to instal the First Responder Kit stored procedures into",
                           "",
                           false,
                           "false",
                           "master"
                       ],
                       [
                           "LocalFile",
                           "Specifies the path to a local file to install FRK from. This *should* be the zipfile as distributed by the maintainers.\r\nIf this parameter is not specified, the latest version will be downloaded and installed from https://github.com/BrentOzarULTD/SQL-Server-First-Responder-Kit",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, the FRK will be downloaded from the internet even if previously cached.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts to confirm actions",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Install-DbaFirstResponderKit [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Branch] \u003cString\u003e] [[-Database] \u003cObject\u003e] [[-LocalFile] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Install-DbaMaintenanceSolution",
        "Description":  "This script will download and install the latest version of SQL Server Maintenance Solution created by Ola Hallengren",
        "Tags":  [
                     "Ola",
                     "Maintenance"
                 ],
        "Synopsis":  "Download and Install SQL Server Maintenance Solution created by Ola Hallengren (https://ola.hallengren.com)",
        "Alias":  "",
        "Author":  "Viorel Ciucu, cviorel.com",
        "CommandName":  "Install-DbaMaintenanceSolution",
        "Availability":  "Windows only",
        "Links":  "http://dbatools.io/Install-DbaMaintenanceSolution",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInstall-DbaMaintenanceSolution -SqlInstance RES14224 -Database DBA -CleanupTime 72\nInstalls Ola Hallengren\u0027s Solution objects on RES14224 in the DBA database.\r\nBackups will default to the default Backup Directory.\r\nIf the Maintenance Solution already exists, the script will be halted.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInstall-DbaMaintenanceSolution -SqlInstance RES14224 -Database DBA -BackupLocation \"Z:\\SQLBackup\" -CleanupTime 72\nThis will create the Ola Hallengren\u0027s Solution objects. Existing objects are not affected in any way.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInstall-DbaMaintenanceSolution -SqlInstance RES14224 -Database DBA -BackupLocation \"Z:\\SQLBackup\" -CleanupTime 72 -ReplaceExisting\nThis will drop and then recreate the Ola Hallengren\u0027s Solution objects\r\nThe cleanup script will drop and recreate:\r\n- TABLE [dbo].[CommandLog]\r\n- STORED PROCEDURE [dbo].[CommandExecute]\r\n- STORED PROCEDURE [dbo].[DatabaseBackup]\r\n- STORED PROCEDURE [dbo].[DatabaseIntegrityCheck]\r\n- STORED PROCEDURE [dbo].[IndexOptimize]\nThe following SQL Agent jobs will be deleted:\r\n- \u0027Output File Cleanup\u0027\r\n- \u0027IndexOptimize - USER_DATABASES\u0027\r\n- \u0027sp_delete_backuphistory\u0027\r\n- \u0027DatabaseBackup - USER_DATABASES - LOG\u0027\r\n- \u0027DatabaseBackup - SYSTEM_DATABASES - FULL\u0027\r\n- \u0027DatabaseBackup - USER_DATABASES - FULL\u0027\r\n- \u0027sp_purge_jobhistory\u0027\r\n- \u0027DatabaseIntegrityCheck - SYSTEM_DATABASES\u0027\r\n- \u0027CommandLog Cleanup\u0027\r\n- \u0027DatabaseIntegrityCheck - USER_DATABASES\u0027\r\n- \u0027DatabaseBackup - USER_DATABASES - DIFF\u0027",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance onto which the Maintenance Solution will be installed.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database where Ola Hallengren\u0027s solution will be installed. Defaults to master.",
                           "",
                           false,
                           "false",
                           "master"
                       ],
                       [
                           "BackupLocation",
                           "Location of the backup root directory. If this is not supplied, the default backup directory will be used.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CleanupTime",
                           "Time in hours, after which backup files are deleted.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "OutputFileDirectory",
                           "Specify the output file directory where the Maintenance Solution will write to.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ReplaceExisting",
                           "If this switch is enabled, objects already present in the target database will be dropped and recreated.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "LogToTable",
                           "If this switch is enabled, the Maintenance Solution will be configured to log commands to a table.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Solution",
                           "Specifies which portion of the Maintenance solution to install. Valid values are All (full solution), Backup, IntegrityCheck and IndexOptimize.",
                           "",
                           false,
                           "false",
                           "All"
                       ],
                       [
                           "InstallJobs",
                           "If this switch is enabled, the corresponding SQL Agent Jobs will be created.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "LocalFile",
                           "Specifies the path to a local file to install Ola\u0027s solution from. This *should* be the zipfile as distributed by the maintainers.\r\nIf this parameter is not specified, the latest version will be downloaded and installed from https://github.com/olahallengren/sql-server-maintenance-solution",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, the Ola\u0027s solution will be downloaded from the internet even if previously cached.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Install-DbaMaintenanceSolution [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject\u003e] [[-BackupLocation] \u003cString\u003e] [[-CleanupTime] \u003cInt32\u003e] [[-OutputFileDirectory] \u003cString\u003e] [-ReplaceExisting] [-LogToTable] [[-Solution] \u003cString\u003e] [-InstallJobs] [[-LocalFile] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Install-DbaSqlWatch",
        "Description":  "Downloads, extracts and installs or updates SqlWatch.\nhttps://sqlwatch.io/",
        "Tags":  "SqlWatch",
        "Synopsis":  "Installs or updates SqlWatch.",
        "Alias":  "",
        "Author":  "Ken K (github.com/koglerk)",
        "CommandName":  "Install-DbaSqlWatch",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Install-DbaSqlWatch",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInstall-DbaSqlWatch -SqlInstance server1\nLogs into server1 with Windows authentication and then installs SqlWatch in the SQLWATCH database.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInstall-DbaSqlWatch -SqlInstance server1\\instance1 -Database DBA\nLogs into server1\\instance1 with Windows authentication and then installs SqlWatch in the DBA database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInstall-DbaSqlWatch -SqlInstance server1\\instance1 -Database DBA -SqlCredential $cred\nLogs into server1\\instance1 with SQL authentication and then installs SqlWatch in the DBA database.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInstall-DbaSqlWatch -SqlInstance sql2016\\standardrtm, sql2016\\sqlexpress, sql2014\nLogs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs SqlWatch in the SQLWATCH database.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$servers = \"sql2016\\standardrtm\", \"sql2016\\sqlexpress\", \"sql2014\"\n$servers | Install-DbaSqlWatch\nLogs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs SqlWatch in the SQLWATCH database.",
        "Params":  [
                       [
                           "SqlInstance",
                           "SQL Server name or SMO object representing the SQL Server to connect to.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies the database to install SqlWatch into. Defaults to SQLWATCH.",
                           "",
                           false,
                           "false",
                           "SQLWATCH"
                       ],
                       [
                           "LocalFile",
                           "Specifies the path to a local file to install SqlWatch from. This *should* be the zipfile as distributed by the maintainers.\r\nIf this parameter is not specified, the latest version will be downloaded and installed from https://github.com/marcingminski/sqlwatch",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, SqlWatch will be downloaded from the internet even if previously cached.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts to confirm actions",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Install-DbaSqlWatch [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [[-LocalFile] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Install-DbaWatchUpdate",
        "Description":  "Adds the scheduled task to support Watch-DbaUpdate.",
        "Tags":  "Module",
        "Synopsis":  "Adds the scheduled task to support Watch-DbaUpdate.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Install-DbaWatchUpdate",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Install-DbaWatchUpdate",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInstall-DbaWatchUpdate\nAdds the scheduled task needed by Watch-DbaUpdate\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInstall-DbaWatchUpdate -TaskName MyScheduledTask\nWill create the scheduled task as the name MyScheduledTask",
        "Params":  [
                       [
                           "TaskName",
                           "Provide custom name for the Scheduled Task",
                           "",
                           false,
                           "false",
                           "dbatools version check"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Install-DbaWatchUpdate [[-TaskName] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Install-DbaWhoIsActive",
        "Description":  "This command downloads, extracts and installs sp_WhoisActive with Adam\u0027s permission. To read more about sp_WhoisActive, please visit http://whoisactive.com and http://sqlblog.com/blogs/adam_machanic/archive/tags/who+is+active/default.aspx\n\nPlease consider donating to Adam if you find this stored procedure helpful: http://tinyurl.com/WhoIsActiveDonate\n\nNote that you will be prompted a bunch of times to confirm an action.",
        "Tags":  [
                     "AdamMechanic",
                     "WhoIsActive",
                     "SpWhoIsActive"
                 ],
        "Synopsis":  "Automatically installs or updates sp_WhoisActive by Adam Machanic.",
        "Alias":  "Install-SqlWhoIsActive",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Install-DbaWhoIsActive",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Install-DbaWhoIsActive",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInstall-DbaWhoIsActive -SqlInstance sqlserver2014a -Database master\nDownloads sp_WhoisActive from the internet and installs to sqlserver2014a\u0027s master database. Connects to SQL Server using Windows Authentication.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInstall-DbaWhoIsActive -SqlInstance sqlserver2014a -SqlCredential $cred\nPops up a dialog box asking which database on sqlserver2014a you want to install the procedure into. Connects to SQL Server using SQL Authentication.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInstall-DbaWhoIsActive -SqlInstance sqlserver2014a -Database master -LocalFile c:\\SQLAdmin\\whoisactive_install.sql\nInstalls sp_WhoisActive to sqlserver2014a\u0027s master database from the local file whoisactive_install.sql\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$instances = Get-DbaCmsRegServer sqlserver\nPS C:\\\u003e Install-DbaWhoIsActive -SqlInstance $instances -Database master\nInstalls sp_WhoisActive to all servers within CMS",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2005 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "LocalFile",
                           "Specifies the path to a local file to install sp_WhoisActive from. This can be either the zipfile as distributed by the website or the expanded SQL script. If this parameter is not specified, the \r\nlatest version will be downloaded and installed from https://whoisactive.com/",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database to install sp_WhoisActive into. This parameter is mandatory when executing this command unattended.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "If this switch is enabled, the sp_WhoisActive will be downloaded from the internet even if previously cached.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Install-DbaWhoIsActive [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-LocalFile \u003cString\u003e] [-Database \u003cObject\u003e] [-EnableException] [-Force] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaAdvancedRestore",
        "Description":  "This is the final piece in the Restore-DbaDatabase Stack. Usually a BackupHistory object will arrive here from `Restore-Dbadatabase` via the following pipeline:\n`Get-DbaBackupInformation  | Select-DbaBackupInformation | Format-DbaBackupInformation | Test-DbaBackupInformation | Invoke-DbaAdvancedRestore`\n\nWe have exposed these functions publicly to allow advanced users to perform operations that we don\u0027t support, or won\u0027t add as they would make things too complex for the majority of our users\n\nFor example if you wanted to do some very complex redirection during a migration, then doing the rewrite of destinations may be better done with your own custom scripts rather than via `Format-DbaBackupInformation`\n\nWe would recommend ALWAYS pushing your input through `Test-DbaBackupInformation` just to make sure that it makes sense to us.",
        "Tags":  [
                     "Restore",
                     "Backup"
                 ],
        "Synopsis":  "Allows the restore of modified BackupHistory Objects\nFor 90% of users Restore-DbaDatabase should be your point of access to this function. The other 10% use it at their own risk",
        "Alias":  "",
        "Author":  "Stuart Moore (@napalmgram - http://stuart-moore.com)",
        "CommandName":  "Invoke-DbaAdvancedRestore",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbaAdvancedRestore",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$BackupHistory | Invoke-DbaAdvancedRestore -SqlInstance MyInstance\nWill restore all the backups in the BackupHistory object according to the transformations it contains\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$BackupHistory | Invoke-DbaAdvancedRestore -SqlInstance MyInstance -OutputScriptOnly\nPS C:\\\u003e $BackupHistory | Invoke-DbaAdvancedRestore -SqlInstance MyInstance\nFirst generates just the T-SQL restore scripts so they can be sanity checked, and then if they are good perform the full restore.\r\nBy reusing the BackupHistory object there is no need to rescan all the backup files again",
        "Params":  [
                       [
                           "BackupHistory",
                           "The BackupHistory object to be restored.\r\nCan be passed in on the pipeline",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlInstance",
                           "The SqlInstance to which the backups should be restored",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "SqlCredential to be used to connect to the target SqlInstance",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "OutputScriptOnly",
                           "If set, the restore will not be performed, but the T-SQL scripts to perform it will be returned",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "VerifyOnly",
                           "If set, performs a Verify of the backups rather than a full restore",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "RestoreTime",
                           "Point in Time to which the database should be restored.\nThis should be the same value or earlier, as used in the previous pipeline stages",
                           "",
                           false,
                           "false",
                           "(Get-Date).AddDays(2)"
                       ],
                       [
                           "StandbyDirectory",
                           "A folder path where a standby file should be created to put the recovered databases in a standby mode",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NoRecovery",
                           "Leave the database in a restoring state so that further restore may be made",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "MaxTransferSize",
                           "Parameter to set the unit of transfer. Values must be a multiple by 64kb",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "BlockSize",
                           "Specifies the block size to use. Must be one of 0.5kb,1kb,2kb,4kb,8kb,16kb,32kb or 64kb\r\nCan be specified in bytes\r\nRefer to https://msdn.microsoft.com/en-us/library/ms178615.aspx for more detail",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "BufferCount",
                           "Number of I/O buffers to use to perform the operation.\r\nRefer to https://msdn.microsoft.com/en-us/library/ms178615.aspx for more detail",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "Continue",
                           "Indicates that the restore is continuing a restore, so target database must be in Recovering or Standby states",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "AzureCredential",
                           "AzureCredential required to connect to blob storage holding the backups",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "WithReplace",
                           "Indicated that if the database already exists it should be replaced",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "KeepCDC",
                           "Indicates whether CDC information should be restored as part of the database",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "PageRestore",
                           "The output from Get-DbaSuspect page containing the suspect pages to be restored.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "Replaces user friendly yellow warnings with bloody red exceptions of doom!\r\nUse this if you want the function to throw terminating errors you want to catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the cmdlet runs. The cmdlet is not run.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before running the cmdlet.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Invoke-DbaAdvancedRestore [-BackupHistory] \u003cObject[]\u003e [[-SqlInstance] \u003cDbaInstanceParameter\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-OutputScriptOnly] [-VerifyOnly] [[-RestoreTime] \u003cDateTime\u003e] [[-StandbyDirectory] \u003cString\u003e] [-NoRecovery] [[-MaxTransferSize] \u003cInt32\u003e] [[-BlockSize] \u003cInt32\u003e] [[-BufferCount] \u003cInt32\u003e] [-Continue] [[-AzureCredential] \u003cString\u003e] [-WithReplace] [-KeepCDC] [[-PageRestore] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaAgFailover",
        "Description":  "Failover an availability group.",
        "Tags":  [
                     "AG",
                     "AvailabilityGroup",
                     "HA"
                 ],
        "Synopsis":  "Failover an availability group.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Invoke-DbaAgFailover",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbaAgFailover",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaAgFailover -SqlInstance sql2017 -AvailabilityGroup SharePoint\nSafely (no potential data loss) fails over the SharePoint AG to sql2017. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2017 | Out-GridView -Passthru | Invoke-DbaAgFailover -Confirm:$false\nSafely (no potential data loss) fails over the selected availability groups to sql2017. Does not prompt for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaAgFailover -SqlInstance sql2017 -AvailabilityGroup SharePoint -Force\nForcefully (with potential data loss) fails over the SharePoint AG to sql2017. Prompts for confirmation.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The SQL Server instance. Server version must be SQL Server version 2012 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityGroup",
                           "Only failover specific availability groups.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaAvailabilityGroup",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Force",
                           "Force Failover and allow data loss",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Invoke-DbaAgFailover [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-InputObject] \u003cAvailabilityGroup[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaBalanceDataFiles",
        "Description":  "When you have a large database with a single data file and add another file, SQL Server will only use the new file until it\u0027s about the same size.\nYou may want to balance the data between all the data files.\n\nThe function will check the server version and edition to see if the it allows for online index rebuilds.\nIf the server does support it, it will try to rebuild the index online.\nIf the server doesn\u0027t support it, it will rebuild the index offline. Be carefull though, this can cause downtime\n\nThe tables must have a clustered index to be able to balance out the data.\nThe function does NOT yet support heaps.\n\nThe function will also check if the file groups are subject to balance out.\nA file group whould have at least have 2 data files and should be writable.\nIf a table is within such a file group it will be subject for processing. If not the table will be skipped.",
        "Tags":  [
                     "Database",
                     "FileManagement",
                     "File",
                     "Space"
                 ],
        "Synopsis":  "Re-balance data between data files",
        "Alias":  "",
        "Author":  "Sander Stad (@sqlstad), sqlstad.nl",
        "CommandName":  "Invoke-DbaBalanceDataFiles",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaBalanceDataFiles -SqlInstance sql1 -Database db1\nThis command will distribute the data in database db1 on instance sql1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaBalanceDataFiles -SqlInstance sql1 -Database db1 | Select-Object -ExpandProperty DataFilesEnd\nThis command will distribute the data in database db1 on instance sql1\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaBalanceDataFiles -SqlInstance sql1 -Database db1 -Table table1,table2,table5\nThis command will distribute the data for only the tables table1,table2 and table5\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInvoke-DbaBalanceDataFiles -SqlInstance sql1 -Database db1 -RebuildOffline\nThis command will consider the fact that there might be a SQL Server edition that does not support online rebuilds of indexes.\r\nBy supplying this parameter you give permission to do the rebuilds offline if the edition does not support it.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Table",
                           "The tables(s) of the database to process. If unspecified, all tables will be processed.",
                           "Tables",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RebuildOffline",
                           "Will set all the indexes to rebuild offline.\r\nThis option is also needed when the server version is below 2005.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "This will disable the check for enough disk space for the action to be successful.\r\nUse this with caution!!",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts for confirmation of every step. For example:\nThe server does not support online rebuilds of indexes.\r\nDo you want to rebuild the indexes offline?\r\n[Y] Yes  [N] No   [?] Help (default is \"Y\"):",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Invoke-DbaBalanceDataFiles [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-Table \u003cObject[]\u003e] [-RebuildOffline] [-EnableException] [-Force] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nInvoke-DbaBalanceDataFiles -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-Table \u003cObject[]\u003e] [-RebuildOffline] [-EnableException] [-Force] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaCycleErrorLog",
        "Description":  "Cycles the current error log for the instance (SQL Server) and/or SQL Server Agent.",
        "Tags":  [
                     "Log",
                     "Cycle"
                 ],
        "Synopsis":  "Cycles the current instance or agent log.",
        "Alias":  "",
        "Author":  "Shawn Melton (@wsmelton), https://wsmelton.github.io",
        "CommandName":  "Invoke-DbaCycleErrorLog",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbaCycleLog",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaCycleLog -SqlInstance sql2016 -Type agent\nCycles the current error log for the SQL Server Agent on SQL Server instance sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaCycleLog -SqlInstance sql2016 -Type instance\nCycles the current error log for the SQL Server instance on SQL Server instance sql2016\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaCycleLog -SqlInstance sql2016\nCycles the current error log for both SQL Server instance and SQL Server Agent on SQL Server instance sql2016",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Type",
                           "The log to cycle.\r\nAccepts: instance or agent.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Invoke-DbaCycleErrorLog [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Type] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaDbccDropCleanBuffer",
        "Description":  "Allows execution of Database Console Command DBCC DROPCLEANBUFFERS\n\nRemoves all clean buffers from the buffer pool, and columnstore objects from the columnstore object pool.\n\nRead more:\n    - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-dropcleanbuffers-transact-sql",
        "Tags":  "DBCC",
        "Synopsis":  "Execution of Database Console Command DBCC DROPCLEANBUFFERS",
        "Alias":  "",
        "Author":  "Patrick Flynn (@sqllensman)",
        "CommandName":  "Invoke-DbaDbccDropCleanBuffer",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbaDbccDropCleanBuffer",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbccDropCleanBuffer -SqlInstance SqlServer2017\nRuns the command DBCC DROPCLEANBUFFERS against the instance SqlServer2017 using Windows Authentication\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDbccDropCleanBuffer -SqlInstance SqlServer2017 -NoInformationalMessages\nRuns the command DBCC DROPCLEANBUFFERS WITH NO_INFOMSGS against the instance SqlServer2017 using Windows Authentication\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Invoke-DbaDbccDropCleanBuffer -WhatIf\nDisplays what will happen if command DBCC DROPCLEANBUFFERS is called against Sql1 and Sql2/sqlexpress\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Invoke-DbaDbccDropCleanBuffer -SqlInstance Server1 -SqlCredential $cred\nConnects using sqladmin credential and executes command DBCC DROPCLEANBUFFERS for instance Server1",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NoInformationalMessages",
                           "Suppresses all informational messages.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the cmdlet runs. The cmdlet is not run.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before running the cmdlet.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Invoke-DbaDbccDropCleanBuffer [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-NoInformationalMessages] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaDbccFreeCache",
        "Description":  "Allows execution of Database Console Commands that act at Server Level to clear Memory caches\n\nAllows execution of the following commands\n    DBCC FREEPROCCACHE\n    DBCC FREESESSIONCACHE\n    DBCC FREESYSTEMCACHE\n\nRead more:\n    - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-freeproccache-transact-sql\n    - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-freesessioncache-transact-sql\n    - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-freesystemcache-transact-sql",
        "Tags":  "DBCC",
        "Synopsis":  "Execution of Database Console Commands that clear Server level Memory caches",
        "Alias":  "",
        "Author":  "Patrick Flynn (@sqllensman)",
        "CommandName":  "Invoke-DbaDbccFreeCache",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbaDbccFreeCache",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREEPROCCACHE\nRuns the command DBCC FREEPROCCACHE against the instance SqlServer2017 using Windows Authentication\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREESESSIONCACHE -NoInformationalMessages\nRuns the command DBCC FREESESSIONCACHE WITH NO_INFOMSGS against the instance SqlServer2017 using Windows Authentication\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREESYSTEMCACHE -NoInformationalMessages\nRuns the command DBCC FREESYSTEMCACHE WITH NO_INFOMSGS against the instance SqlServer2017 using Windows Authentication\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInvoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREEPROCCACHE -InputValue 0x060006001ECA270EC0215D05000000000000000000000000\nRemove a specific plan with plan_handle 0x060006001ECA270EC0215D05000000000000000000000000 from the cache via the command DBCC FREEPROCCACHE(0x060006001ECA270EC0215D05000000000000000000000000) \r\nagainst the instance SqlServer2017 using Windows Authentication\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eInvoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREEPROCCACHE -InputValue default\nRuns the command DBCC FREEPROCCACHE(\u0027default\u0027) against the instance SqlServer2017 using Windows Authentication. This clears all cache entries associated with a resource pool \u0027default\u0027.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eInvoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREESYSTEMCACHE -InputValue default\nRuns the command DBCC FREESYSTEMCACHE (\u0027ALL\u0027, default) against the instance SqlServer2017 using Windows Authentication. This will clean all the caches with entries specific to the resource pool named \r\n\"default\".\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eInvoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREESYSTEMCACHE -InputValue default -MarkInUseForRemoval\nRuns the command DBCC FREESYSTEMCACHE (\u0027ALL\u0027, default) WITH MARK_IN_USE_FOR_REMOVAL against the instance SqlServer2017 using Windows Authentication. This will to release entries once the entries \r\nbecome unused for all the caches with entries specific to the resource pool named \"default\".",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Operation",
                           "DBCC Operation to Perform - Supports specific set of operations",
                           "",
                           false,
                           "false",
                           "FreeProcCache"
                       ],
                       [
                           "InputValue",
                           "Value used for Operation - meaning depends on Operation\r\nDBCC FREEPROCCACHE accepts\r\n    a plan_handle of type varbinary(64)\r\n    a sql_handle of type varbinary(64)\r\n    or the name of a Resource Governor resource pool of type sysname\r\n    If blank then clears all elements from the plan cache\r\nDBCC FREESYSTEMCACHE accepts\r\n    \u0027ALL\u0027 for ALL specifies all supported caches\r\n    or name of a Resource Governor pool cache\r\nNot required for other values",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NoInformationalMessages",
                           "Suppresses all informational messages.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "MarkInUseForRemoval",
                           "Used when Operation = DBCC FREESYSTEMCACHE\r\nAsynchronously frees currently used entries from their respective caches after they become unused",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the cmdlet runs. The cmdlet is not run.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before running the cmdlet.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Invoke-DbaDbccFreeCache [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Operation] \u003cString\u003e] [[-InputValue] \u003cString\u003e] [-NoInformationalMessages] [-MarkInUseForRemoval] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaDbClone",
        "Description":  "Clones a database schema and statistics.\n\nThis can be useful for testing query performance without requiring all the space needed for the data in the database.\n\nRead more:\n    - https://sqlperformance.com/2016/08/sql-statistics/expanding-dbcc-clonedatabase\n    - https://support.microsoft.com/en-us/help/3177838/how-to-use-dbcc-clonedatabase-to-generate-a-schema-and-statistics-only\n\nThanks to Microsoft Tiger Team for the code and idea https://github.com/Microsoft/tigertoolbox/",
        "Tags":  [
                     "Statistics",
                     "Performance",
                     "Clone"
                 ],
        "Synopsis":  "Clones a database schema and statistics",
        "Alias":  "Invoke-DbaDatabaseClone",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Invoke-DbaDbClone",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbaDbClone",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbClone -SqlInstance sql2016 -Database mydb -CloneDatabase myclone\nClones mydb to myclone on sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016 -Database mydb | Invoke-DbaDbClone -CloneDatabase myclone, myclone2 -UpdateStatistics\nUpdates the statistics of mydb then clones to myclone and myclone2",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database to clone - this list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaDatabase",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "CloneDatabase",
                           "The name(s) to clone to.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeStatistics",
                           "Exclude the statistics in the cloned database",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ExcludeQueryStore",
                           "Exclude the QueryStore data in the cloned database",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "UpdateStatistics",
                           "Update the statistics prior to cloning (per Microsoft Tiger Team formula)",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Invoke-DbaDbClone [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [[-CloneDatabase] \u003cString[]\u003e] [-ExcludeStatistics] [-ExcludeQueryStore] [-UpdateStatistics] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaDbDataMasking",
        "Description":  "TMasks data by using randomized values determined by a configuration file and a randomizer framework\n\nIt will use a configuration file that can be made manually or generated using New-DbaDbMaskingConfig\n\nNote that the following column and data types are not currently supported:\nIdentity\nForeignKey\nComputed\nHierarchyid\nGeography\nGeometry\nXml",
        "Tags":  [
                     "DataMasking",
                     "Database"
                 ],
        "Synopsis":  "Masks data by using randomized values determined by a configuration file and a randomizer framework",
        "Alias":  "",
        "Author":  "Sander Stad (@sqlstad, sqlstad.nl) | Chrissy LeMaire (@cl, netnerds.net)",
        "CommandName":  "Invoke-DbaDbDataMasking",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbaDbDataMasking",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbDataMasking -SqlInstance SQLDB2 -Database DB1 -FilePath C:\\Temp\\sqldb1.db1.tables.json\nApply the data masking configuration from the file \"sqldb1.db1.tables.json\" to the db1 database on sqldb2. Prompt for confirmation for each table.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-ChildItem -Path C:\\Temp\\sqldb1.db1.tables.json | Invoke-DbaDbDataMasking -SqlInstance SQLDB2 -Database DB1 -Confirm:$false\nApply the data masking configuration from the file \"sqldb1.db1.tables.json\" to the db1 database on sqldb2. Do not prompt for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaDbMaskingConfig -SqlInstance SQLDB1 -Database DB1 -Path C:\\Temp\\clone -OutVariable file\n$file | Invoke-DbaDbDataMasking -SqlInstance SQLDB2 -Database DB1 -Confirm:$false\nCreate the data masking configuration file \"sqldb1.db1.tables.json\", then use it to mask the db1 database on sqldb2. Do not prompt for confirmation.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-ChildItem -Path C:\\Temp\\sqldb1.db1.tables.json | Invoke-DbaDbDataMasking -SqlInstance SQLDB2, sqldb3 -Database DB1 -Confirm:$false\nSee what would happen if you the data masking configuration from the file \"sqldb1.db1.tables.json\" to the db1 database on sqldb2 and sqldb3. Do not prompt for confirmation.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Databases to process through",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "FilePath",
                           "Configuration file that contains the which tables and columns need to be masked",
                           "Path,FullName",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Locale",
                           "Set the local to enable certain settings in the masking",
                           "",
                           false,
                           "false",
                           "en"
                       ],
                       [
                           "CharacterString",
                           "The characters to use in string data. \u0027abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\u0027 by default",
                           "",
                           false,
                           "false",
                           "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
                       ],
                       [
                           "Table",
                           "Tables to process. By default all the tables will be processed",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Column",
                           "Columns to process. By default all the columns will be processed",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeTable",
                           "Exclude specific tables even if it\u0027s listed in the config file.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeColumn",
                           "Exclude specific columns even if it\u0027s listed in the config file.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Query",
                           "If you would like to mask only a subset of a table, use the Query parameter, otherwise all data will be masked.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "MaxValue",
                           "Force a max length of strings instead of relying on datatype maxes. Note if a string datatype has a lower MaxValue, that will be used instead.\nUseful for adhoc updates and testing, otherwise, the config file should be used.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "ModulusFactor",
                           "Calculating the next nullable by using the remainder from the modulus. Default is every 10.",
                           "",
                           false,
                           "false",
                           "10"
                       ],
                       [
                           "ExactLength",
                           "Mask string values to the same length. So \u0027Tate\u0027 will be replaced with 4 random characters.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Invoke-DbaDbDataMasking [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [-FilePath] \u003cObject\u003e [[-Locale] \u003cString\u003e] [[-CharacterString] \u003cString\u003e] [[-Table] \u003cString[]\u003e] [[-Column] \u003cString[]\u003e] [[-ExcludeTable] \u003cString[]\u003e] [[-ExcludeColumn] \u003cString[]\u003e] [[-Query] \u003cString\u003e] [[-MaxValue] \u003cInt32\u003e] [[-ModulusFactor] \u003cInt32\u003e] [-ExactLength] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaDbDbccCheckConstraint",
        "Description":  "Executes the command DBCC CHECKCONSTRAINTS and returns results\n\nReports and corrects pages and row count inaccuracies in the catalog views.\nThese inaccuracies may cause incorrect space usage reports returned by the sp_spaceused system stored procedure.\n\nRead more:\n    - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkconstraints-transact-sql",
        "Tags":  "DBCC",
        "Synopsis":  "Execution of Database Console Command DBCC CHECKCONSTRAINTS",
        "Alias":  "",
        "Author":  "Patrick Flynn (@sqllensman)",
        "CommandName":  "Invoke-DbaDbDbccCheckConstraint",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbaDbDbccCheckConstraint",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbDbccCheckConstraint -SqlInstance SqlServer2017\nRuns the command DBCC CHECKCONSTRAINTS to check all enabled constraints on all tables for all databases for the instance SqlServer2017. Connect using Windows Authentication\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDbDbccCheckConstraint -SqlInstance SqlServer2017 -Database CurrentDB\nConnect to instance SqlServer2017 using Windows Authentication and run the command DBCC CHECKCONSTRAINTS to check all enabled constraints on all tables in the CurrentDB database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaDbDbccCheckConstraint -SqlInstance SqlServer2017 -Database CurrentDB -Object Sometable\nConnects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC CHECKCONSTRAINTS(SometableId) to check all enabled constraints in the table.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInvoke-DbaDbDbccCheckConstraint -SqlInstance SqlServer2017 -Database CurrentDB -Object ConstraintId\nConnects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC CHECKCONSTRAINTS(ConstraintId) to check the constraint with constraint_id = ConstraintId.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Invoke-DbaDbDbccCheckConstraint -SqlInstance SqlServer2017 -SqlCredential $cred -Database CurrentDB -Object TableId -AllConstraints -AllErrorMessages -NoInformationalMessages\nConnects to CurrentDB on instance SqlServer2017 using sqladmin credential and runs the command DBCC CHECKCONSTRAINTS(TableId) WITH ALL_CONSTRAINTS, ALL_ERRORMSGS, NO_INFOMSGS to check all enabled and \r\ndisabled constraints on the table with able_id = TableId. Returns all rows that violate constraints.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Invoke-DbaDbDbccCheckConstraint -WhatIf\nDisplays what will happen if command DBCC CHECKCONSTRAINTS is called against all databses on Sql1 and Sql2/sqlexpress",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Object",
                           "The table or constraint to be checked.\r\nWhen table_name or table_id is specified, all enabled constraints on that table are checked.\r\nWhen constraint_name or constraint_id is specified, only that constraint is checked.\r\nIf neither a table identifier nor a constraint identifier is specified, all enabled constraints on all tables in the current database are checked.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AllConstraints",
                           "Checks all enabled and disabled constraints on the table if the table name is specified or if all tables are checked;\r\nOtherwise, checks only the enabled constraint.\r\nHas no effect when a constraint is specified",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "AllErrorMessages",
                           "Returns all rows that violate constraints in the table that is checked.\r\nThe default is the first 200 rows.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NoInformationalMessages",
                           "Suppresses all informational messages.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the cmdlet runs. The cmdlet is not run.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before running the cmdlet.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Invoke-DbaDbDbccCheckConstraint [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Object] \u003cString\u003e] [-AllConstraints] [-AllErrorMessages] [-NoInformationalMessages] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaDbDbccCleanTable",
        "Description":  "Executes the command DBCC CLEANTABLE against defined objects and returns results\n\nReclaims space from dropped variable-length columns in tables or indexed views\n\nRead more:\n    - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-cleantable-transact-sql",
        "Tags":  "DBCC",
        "Synopsis":  "Execution of Database Console Command DBCC CLEANTABLE",
        "Alias":  "",
        "Author":  "Patrick Flynn (@sqllensman)",
        "CommandName":  "Invoke-DbaDbDbccCleanTable",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbaDbDbccCleanTable",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbDbccCleanTable -SqlInstance SqlServer2017 -Database CurrentDB -Object \u0027dbo.SomeTable\u0027\nConnects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC CLEANTABLE(\u0027CurrentDB\u0027, \u0027dbo.SomeTable\u0027) to reclaim space after variable-length columns have \r\nbeen dropped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDbDbccCleanTable -SqlInstance SqlServer2017 -Database CurrentDB -Object 34636372 -BatchSize 5000\nConnects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC CLEANTABLE(\u0027CurrentDB\u0027, 34636372, 5000) to reclaim space from table with Table_Id = 34636372 \r\nafter variable-length columns have been dropped.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Invoke-DbaDbDbccCleanTable -SqlInstance SqlServer2017 -SqlCredential $cred -Database CurrentDB -Object \u0027dbo.SomeTable\u0027  -NoInformationalMessages\nConnects to CurrentDB on instance SqlServer2017 using sqladmin credential and runs the command DBCC CLEANTABLE(\u0027CurrentDB\u0027, \u0027dbo.SomeTable\u0027) WITH NO_INFOMSGS to reclaim space after variable-length \r\ncolumns have been dropped.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Invoke-DbaDbDbccCleanTable -Object \u0027dbo.SomeTable\u0027 -BatchSize 5000\nRuns the command DBCC CLEANTABLE(\u0027DatabaseName\u0027, \u0027dbo.SomeTable\u0027, 5000) against all databses on Sql1 and Sql2/sqlexpress",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process. If unspecified, all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Object",
                           "The table(s) or indexed view(s) to be cleaned.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "BatchSize",
                           "Is the number of rows processed per transaction.\r\nIf not specified, or if 0 is specified, the statement processes the whole table in one transaction.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "NoInformationalMessages",
                           "Suppresses all informational messages.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the cmdlet runs. The cmdlet is not run.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before running the cmdlet.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Invoke-DbaDbDbccCleanTable [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Object] \u003cString[]\u003e] [[-BatchSize] \u003cInt32\u003e] [-NoInformationalMessages] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaDbDbccUpdateUsage",
        "Description":  "Executes the command DBCC UPDATEUSAGE and returns results\n\nReports and corrects pages and row count inaccuracies in the catalog views.\nThese inaccuracies may cause incorrect space usage reports returned by the sp_spaceused system stored procedure.\n\nRead more:\n    - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-updateusage-transact-sql",
        "Tags":  "DBCC",
        "Synopsis":  "Execution of Database Console Command DBCC UPDATEUSAGE",
        "Alias":  "",
        "Author":  "Patrick Flynn (@sqllensman)",
        "CommandName":  "Invoke-DbaDbDbccUpdateUsage",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbaDbDbccUpdateUsage",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbDbccUpdateUsage -SqlInstance SqlServer2017\nRuns the command DBCC UPDATEUSAGE to update the page or row counts or both for all objects in all databases for the instance SqlServer2017. Connect using Windows Authentication\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDbDbccUpdateUsage -SqlInstance SqlServer2017 -Database CurrentDB\nRuns the command DBCC UPDATEUSAGE to update the page or row counts or both for all objects in the CurrentDB database for the instance SqlServer2017. Connect using Windows Authentication\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaDbDbccUpdateUsage -SqlInstance SqlServer2017 -Database CurrentDB -Table Sometable\nConnects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC UPDATEUSAGE(SometableId) to update the page or row counts for all indexes in the table.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Invoke-DbaDbDbccUpdateUsage -SqlInstance SqlServer2017 -SqlCredential $cred -Database CurrentDB -Table \u0027SometableId -Index IndexName -NoInformationalMessages -CountRows\nConnects to CurrentDB on instance SqlServer2017 using sqladmin credential and runs the command DBCC UPDATEUSAGE(SometableId, IndexName) WITH NO_INFOMSGS, COUNT_ROWS to update the page or row counts.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Invoke-DbaDbDbccUpdateUsage -WhatIf\nDisplays what will happen if command DBCC UPDATEUSAGE is called against all databses on Sql1 and Sql2/sqlexpress",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process. If unspecified, all databases will be processed.\r\nThe Name or Id of a database can be specified\r\nDatabase names must comply with the rules for identifiers.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Table",
                           "The table or indexed view to process.\r\nTable and view names must comply with the rules for identifiers\r\nThe Id of Table or View can be specified\r\nIf not specified, all tables or indexed views will be processed",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Index",
                           "The Index to process.\r\nThe Id of Index can be specified\r\nIf not specified, all indexes for the specified table or view will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NoInformationalMessages",
                           "Suppresses all informational messages.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "CountRows",
                           "Specifies that the row count column is updated with the current count of the number of rows in the table or view.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the cmdlet runs. The cmdlet is not run.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before running the cmdlet.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Invoke-DbaDbDbccUpdateUsage [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Table] \u003cString\u003e] [[-Index] \u003cString\u003e] [-NoInformationalMessages] [-CountRows] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaDbDecryptObject",
        "Description":  "When a procedure or a function is created with encryption and you lost the code you\u0027re in trouble.\nYou cannot alter the object or view the definition.\nWith this command you can search for the object and decrypt the it.\n\nThe command will output the results to the console.\nThere is an option to export all the results to a folder creating .sql files.\n\nMake sure the instance allowed dedicated administrator connections (DAC).\nThe binary versions of the objects can only be retrieved using a DAC connection.\nYou can check the DAC connection with:\n\u0027Get-DbaSpConfigure -SqlInstance [yourinstance] -ConfigName RemoteDacConnectionsEnabled\u0027\nIt should say 1 in the ConfiguredValue.\n\nTo change the configurations you can use the Set-DbaSpConfigure command:\n\u0027Set-DbaSpConfigure -SqlInstance [yourinstance] -ConfigName RemoteDacConnectionsEnabled -Value 1\u0027\nIn some cases you may need to reboot the instance.",
        "Tags":  [
                     "Encryption",
                     "Decrypt",
                     "Database"
                 ],
        "Synopsis":  "Invoke-DbaDbDecryptObject returns the decrypted version of an object",
        "Alias":  "",
        "Author":  "Sander Stad (@sqlstad), sqlstad.nl",
        "CommandName":  "Invoke-DbaDbDecryptObject",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbaDbDecryptObject",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbDecryptObject -SqlInstance SQLDB1 -Database DB1 -ObjectName Function1\nDecrypt object \"Function1\" in DB1 of instance SQLDB1 and output the data to the user.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDbDecryptObject -SqlInstance SQLDB1 -Database DB1 -ObjectName Function1 -ExportDestination C:\\temp\\decrypt\nDecrypt object \"Function1\" in DB1 of instance SQLDB1 and output the data to the folder \"C:\\temp\\decrypt\".\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaDbDecryptObject -SqlInstance SQLDB1 -Database DB1 -ExportDestination C:\\temp\\decrypt\nDecrypt all objects in DB1 of instance SQLDB1 and output the data to the folder \"C:\\temp\\decrypt\"\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInvoke-DbaDbDecryptObject -SqlInstance SQLDB1 -Database DB1 -ObjectName Function1, Function2\nDecrypt objects \"Function1\" and \"Function2\" and output the data to the user.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\"SQLDB1\" | Invoke-DbaDbDecryptObject -Database DB1 -ObjectName Function1, Function2\nDecrypt objects \"Function1\" and \"Function2\" and output the data to the user using a pipeline for the instance.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Database to look through for the object.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "ObjectName",
                           "The name of the object to search for in the database.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EncodingType",
                           "The encoding that\u0027s used to decrypt and encrypt values.",
                           "",
                           false,
                           "false",
                           "ASCII"
                       ],
                       [
                           "ExportDestination",
                           "Used for exporting the results to.\r\nThe destiation will use the instance name, database name and object type i.e.: C:\\temp\\decrypt\\SQLDB1\\DB1\\StoredProcedure",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Invoke-DbaDbDecryptObject [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Database] \u003cObject[]\u003e [[-ObjectName] \u003cString[]\u003e] [[-EncodingType] \u003cString\u003e] [[-ExportDestination] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaDbLogShipping",
        "Description":  "Invoke-DbaDbLogShipping helps to easily set up log shipping for one or more databases.\n\nThis function will make a lot of decisions for you assuming you want default values like a daily interval for the schedules with a 15 minute interval on the day.\nThere are some settings that cannot be made by the function and they need to be prepared before the function is executed.\n\nThe following settings need to be made before log shipping can be initiated:\n- Backup destination (the folder and the privileges)\n- Copy destination (the folder and the privileges)\n\n* Privileges\nMake sure your agent service on both the primary and the secondary instance is an Active Directory account.\nAlso have the credentials ready to set the folder permissions\n\n** Network share\nThe backup destination needs to be shared and have the share privileges of FULL CONTROL to Everyone.\n\n** NTFS permissions\nThe backup destination must have at least read/write permissions for the primary instance agent account.\nThe backup destination must have at least read permissions for the secondary instance agent account.\nThe copy destination must have at least read/write permission for the secondary instance agent acount.",
        "Tags":  "LogShipping",
        "Synopsis":  "Invoke-DbaDbLogShipping sets up log shipping for one or more databases",
        "Alias":  "Invoke-DbaLogShipping",
        "Author":  "Sander Stad (@sqlstad), sqlstad.nl",
        "CommandName":  "Invoke-DbaDbLogShipping",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Invoke-DbaDbLogShipping",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e SourceSqlInstance = \u0027sql1\u0027\r\n\u003e\u003e DestinationSqlInstance = \u0027sql2\u0027\r\n\u003e\u003e Database = \u0027db1\u0027\r\n\u003e\u003e BackupNetworkPath= \u0027\\\\sql1\\logshipping\u0027\r\n\u003e\u003e BackupLocalPath= \u0027D:\\Data\\logshipping\u0027\r\n\u003e\u003e BackupScheduleFrequencyType = \u0027daily\u0027\r\n\u003e\u003e BackupScheduleFrequencyInterval = 1\r\n\u003e\u003e CompressBackup = $true\r\n\u003e\u003e CopyScheduleFrequencyType = \u0027daily\u0027\r\n\u003e\u003e CopyScheduleFrequencyInterval = 1\r\n\u003e\u003e GenerateFullBackup = $true\r\n\u003e\u003e RestoreScheduleFrequencyType = \u0027daily\u0027\r\n\u003e\u003e RestoreScheduleFrequencyInterval = 1\r\n\u003e\u003e SecondaryDatabaseSuffix = \u0027DR\u0027\r\n\u003e\u003e CopyDestinationFolder = \u0027\\\\sql2\\logshippingdest\u0027\r\n\u003e\u003e Force = $true\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Invoke-DbaDbLogShipping @params\nSets up log shipping for database \"db1\" with the backup path to a network share allowing local backups.\r\nIt creates daily schedules for the backup, copy and restore job with all the defaults to be executed every 15 minutes daily.\r\nThe secondary database will be called \"db1_LS\".\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e SourceSqlInstance = \u0027sql1\u0027\r\n\u003e\u003e DestinationSqlInstance = \u0027sql2\u0027\r\n\u003e\u003e Database = \u0027db1\u0027\r\n\u003e\u003e BackupNetworkPath= \u0027\\\\sql1\\logshipping\u0027\r\n\u003e\u003e GenerateFullBackup = $true\r\n\u003e\u003e Force = $true\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Invoke-DbaDbLogShipping @params\nSets up log shipping with all defaults except that a backup file is generated.\r\nThe script will show a message that the copy destination has not been supplied and asks if you want to use the default which would be the backup directory of the secondary server with the folder \r\n\"logshipping\" i.e. \"D:\\SQLBackup\\Logshiping\".",
        "Params":  [
                       [
                           "SourceSqlInstance",
                           "Source SQL Server instance which contains the databases to be log shipped.\r\nYou must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "SourceServerInstance,SourceSqlServerSqlServer,Source",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlInstance",
                           "Destination SQL Server instance which contains the databases to be log shipped.\r\nYou must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "DestinationServerInstance,DestinationSqlServer,Destination",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SourceCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DestinationCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Database to set up log shipping for.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "BackupNetworkPath",
                           "The backup unc path to place the backup files. This is the root directory.\r\nA directory with the name of the database will be created in this path.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "BackupLocalPath",
                           "If the backup path is locally for the source server you can also set this value.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "BackupJob",
                           "Name of the backup that will be created in the SQL Server agent.\r\nThe parameter works as a prefix where the name of the database will be added to the backup job name.\r\nThe default is \"LSBackup_[databasename]\"",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "BackupRetention",
                           "The backup retention period in minutes. Default is 4320 / 72 hours",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "BackupSchedule",
                           "Name of the backup schedule created for the backup job.\r\nThe parameter works as a prefix where the name of the database will be added to the backup job schedule name.\r\nDefault is \"LSBackupSchedule_[databasename]\"",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "BackupScheduleDisabled",
                           "Parameter to set the backup schedule to disabled upon creation.\r\nBy default the schedule is enabled.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "BackupScheduleFrequencyType",
                           "A value indicating when a job is to be executed.\r\nAllowed values are \"Daily\", \"AgentStart\", \"IdleComputer\"",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "BackupScheduleFrequencyInterval",
                           "The number of type periods to occur between each execution of the backup job.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "BackupScheduleFrequencySubdayType",
                           "Specifies the units for the sub-day FrequencyInterval.\r\nAllowed values are \"Time\", \"Seconds\", \"Minutes\", \"Hours\"",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "BackupScheduleFrequencySubdayInterval",
                           "The number of sub-day type periods to occur between each execution of the backup job.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "BackupScheduleFrequencyRelativeInterval",
                           "A job\u0027s occurrence of FrequencyInterval in each month, if FrequencyInterval is 32 (monthlyrelative).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "BackupScheduleFrequencyRecurrenceFactor",
                           "The number of weeks or months between the scheduled execution of a job. FrequencyRecurrenceFactor is used only if FrequencyType is 8, \"Weekly\", 16, \"Monthly\", 32 or \"MonthlyRelative\".",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "BackupScheduleStartDate",
                           "The date on which execution of a job can begin.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "BackupScheduleEndDate",
                           "The date on which execution of a job can stop.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "BackupScheduleStartTime",
                           "The time on any day to begin execution of a job. Format HHMMSS / 24 hour clock.\r\nExample: \u0027010000\u0027 for 01:00:00 AM.\r\nExample: \u0027140000\u0027 for 02:00:00 PM.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "BackupScheduleEndTime",
                           "The time on any day to end execution of a job. Format HHMMSS / 24 hour clock.\r\nExample: \u0027010000\u0027 for 01:00:00 AM.\r\nExample: \u0027140000\u0027 for 02:00:00 PM.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "BackupThreshold",
                           "Is the length of time, in minutes, after the last backup before a threshold alert error is raised.\r\nThe default is 60.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "CompressBackup",
                           "Do the backups need to be compressed. By default the backups are not compressed.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "CopyDestinationFolder",
                           "The path to copy the transaction log backup files to. This is the root directory.\r\nA directory with the name of the database will be created in this path.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CopyJob",
                           "Name of the copy job that will be created in the SQL Server agent.\r\nThe parameter works as a prefix where the name of the database will be added to the copy job name.\r\nThe default is \"LSBackup_[databasename]\"",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CopyRetention",
                           "The copy retention period in minutes. Default is 4320 / 72 hours",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "CopySchedule",
                           "Name of the backup schedule created for the copy job.\r\nThe parameter works as a prefix where the name of the database will be added to the copy job schedule name.\r\nDefault is \"LSCopy_[DestinationServerName]_[DatabaseName]\"",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CopyScheduleDisabled",
                           "Parameter to set the copy schedule to disabled upon creation.\r\nBy default the schedule is enabled.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "CopyScheduleFrequencyType",
                           "A value indicating when a job is to be executed.\r\nAllowed values are \"Daily\", \"AgentStart\", \"IdleComputer\"",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CopyScheduleFrequencyInterval",
                           "The number of type periods to occur between each execution of the copy job.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CopyScheduleFrequencySubdayType",
                           "Specifies the units for the subday FrequencyInterval.\r\nAllowed values are \"Time\", \"Seconds\", \"Minutes\", \"Hours\"",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CopyScheduleFrequencySubdayInterval",
                           "The number of subday type periods to occur between each execution of the copy job.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "CopyScheduleFrequencyRelativeInterval",
                           "A job\u0027s occurrence of FrequencyInterval in each month, if FrequencyInterval is 32 (monthlyrelative).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CopyScheduleFrequencyRecurrenceFactor",
                           "The number of weeks or months between the scheduled execution of a job. FrequencyRecurrenceFactor is used only if FrequencyType is 8, \"Weekly\", 16, \"Monthly\", 32 or \"MonthlyRelative\".",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "CopyScheduleStartDate",
                           "The date on which execution of a job can begin.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CopyScheduleEndDate",
                           "The date on which execution of a job can stop.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CopyScheduleStartTime",
                           "The time on any day to begin execution of a job. Format HHMMSS / 24 hour clock.\r\nExample: \u0027010000\u0027 for 01:00:00 AM.\r\nExample: \u0027140000\u0027 for 02:00:00 PM.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CopyScheduleEndTime",
                           "The time on any day to end execution of a job. Format HHMMSS / 24 hour clock.\r\nExample: \u0027010000\u0027 for 01:00:00 AM.\r\nExample: \u0027140000\u0027 for 02:00:00 PM.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DisconnectUsers",
                           "If this parameter is set in combinations of standby the users will be disconnected during restore.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "FullBackupPath",
                           "Path to an existing full backup. Use this when an existing backup needs to used to initialize the database on the secondary instance.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "GenerateFullBackup",
                           "If the database is not initialized on the secondary instance it can be done by creating a new full backup and\r\nrestore it for you.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "HistoryRetention",
                           "Is the length of time in minutes in which the history is retained.\r\nThe default value is 14420",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "NoRecovery",
                           "If this parameter is set the database will be in recovery mode. The database will not be readable.\r\nThis setting is default.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NoInitialization",
                           "If this parameter is set the secondary database will not be initialized.\r\nThe database needs to be on the secondary instance in recovery mode.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "PrimaryMonitorServer",
                           "Is the name of the monitor server for the primary server.\r\nThe default is the name of the primary sql server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "PrimaryMonitorCredential",
                           "Allows you to login to enter a secure credential. Only needs to be used when the PrimaryMonitorServerSecurityMode is 0 or \"sqlserver\"\r\nTo use: $scred = Get-Credential, then pass $scred object to the -PrimaryMonitorCredential parameter.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "PrimaryMonitorServerSecurityMode",
                           "The security mode used to connect to the monitor server for the primary server. Allowed values are 0, \"sqlserver\", 1, \"windows\"\r\nThe default is 1 or Windows.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "PrimaryThresholdAlertEnabled",
                           "Enables the Threshold alert for the primary database",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "RestoreDataFolder",
                           "Folder to be used to restore the database data files. Only used when parameter GenerateFullBackup or UseExistingFullBackup are set.\r\nIf the parameter is not set the default data folder of the secondary instance will be used including the name of the database.\r\nIf the folder is set but doesn\u0027t exist the default data folder of the secondary instance will be used including the name of the database.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RestoreLogFolder",
                           "Folder to be used to restore the database log files. Only used when parameter GenerateFullBackup or UseExistingFullBackup are set.\r\nIf the parameter is not set the default transaction log folder of the secondary instance will be used.\r\nIf the folder is set but doesn\u0027t exist the default transaction log folder of the secondary instance will be used.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RestoreDelay",
                           "In case a delay needs to be set for the restore.\r\nThe default is 0.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "RestoreAlertThreshold",
                           "The amount of minutes after which an alert will be raised is no restore has taken place.\r\nThe default is 45 minutes.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "RestoreJob",
                           "Name of the restore job that will be created in the SQL Server agent.\r\nThe parameter works as a prefix where the name of the database will be added to the restore job name.\r\nThe default is \"LSRestore_[databasename]\"",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RestoreRetention",
                           "The backup retention period in minutes. Default is 4320 / 72 hours",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "RestoreSchedule",
                           "Name of the backup schedule created for the restore job.\r\nThe parameter works as a prefix where the name of the database will be added to the restore job schedule name.\r\nDefault is \"LSRestore_[DestinationServerName]_[DatabaseName]\"",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RestoreScheduleDisabled",
                           "Parameter to set the restore schedule to disabled upon creation.\r\nBy default the schedule is enabled.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "RestoreScheduleFrequencyType",
                           "A value indicating when a job is to be executed.\r\nAllowed values are \"Daily\", \"AgentStart\", \"IdleComputer\"",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RestoreScheduleFrequencyInterval",
                           "The number of type periods to occur between each execution of the restore job.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RestoreScheduleFrequencySubdayType",
                           "Specifies the units for the subday FrequencyInterval.\r\nAllowed values are \"Time\", \"Seconds\", \"Minutes\", \"Hours\"",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RestoreScheduleFrequencySubdayInterval",
                           "The number of subday type periods to occur between each execution of the restore job.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "RestoreScheduleFrequencyRelativeInterval",
                           "A job\u0027s occurrence of FrequencyInterval in each month, if FrequencyInterval is 32 (monthlyrelative).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RestoreScheduleFrequencyRecurrenceFactor",
                           "The number of weeks or months between the scheduled execution of a job. FrequencyRecurrenceFactor is used only if FrequencyType is 8, \"Weekly\", 16, \"Monthly\", 32 or \"MonthlyRelative\".",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "RestoreScheduleStartDate",
                           "The date on which execution of a job can begin.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RestoreScheduleEndDate",
                           "The date on which execution of a job can stop.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RestoreScheduleStartTime",
                           "The time on any day to begin execution of a job. Format HHMMSS / 24 hour clock.\r\nExample: \u0027010000\u0027 for 01:00:00 AM.\r\nExample: \u0027140000\u0027 for 02:00:00 PM.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RestoreScheduleEndTime",
                           "The time on any day to end execution of a job. Format HHMMSS / 24 hour clock.\r\nExample: \u0027010000\u0027 for 01:00:00 AM.\r\nExample: \u0027140000\u0027 for 02:00:00 PM.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RestoreThreshold",
                           "The number of minutes allowed to elapse between restore operations before an alert is generated.\r\nThe default value = 0",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "SecondaryDatabasePrefix",
                           "The secondary database can be renamed to include a prefix.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SecondaryDatabaseSuffix",
                           "The secondary database can be renamed to include a suffix.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SecondaryMonitorServer",
                           "Is the name of the monitor server for the secondary server.\r\nThe default is the name of the secondary sql server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SecondaryMonitorCredential",
                           "Allows you to login to enter a secure credential. Only needs to be used when the SecondaryMonitorServerSecurityMode is 0 or \"sqlserver\"\r\nTo use: $scred = Get-Credential, then pass $scred object to the -SecondaryMonitorCredential parameter.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SecondaryMonitorServerSecurityMode",
                           "The security mode used to connect to the monitor server for the secondary server. Allowed values are 0, \"sqlserver\", 1, \"windows\"\r\nThe default is 1 or Windows.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SecondaryThresholdAlertEnabled",
                           "Enables the Threshold alert for the secondary database",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Standby",
                           "If this parameter is set the database will be set to standby mode making the database readable.\r\nIf not set the database will be in recovery mode.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "StandbyDirectory",
                           "Directory to place the standby file(s) in",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "UseExistingFullBackup",
                           "If the database is not initialized on the secondary instance it can be done by selecting an existing full backup\r\nand restore it for you.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "UseBackupFolder",
                           "This enables the user to specify a specific backup folder containing one or more backup files to initialize the database on the secondary instance.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "The force parameter will ignore some errors in the parameters and assume defaults.\r\nIt will also remove the any present schedules with the same name for the specific job.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "Use this switch to disable any kind of verbose messages",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Invoke-DbaDbLogShipping [-SourceSqlInstance] \u003cObject\u003e [-DestinationSqlInstance] \u003cObject[]\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [[-SourceCredential] \u003cPSCredential\u003e] [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-DestinationCredential] \u003cPSCredential\u003e] [-Database] \u003cObject[]\u003e [-BackupNetworkPath] \u003cString\u003e [[-BackupLocalPath] \u003cString\u003e] [[-BackupJob] \u003cString\u003e] [[-BackupRetention] \u003cInt32\u003e] [[-BackupSchedule] \u003cString\u003e] [-BackupScheduleDisabled] [[-BackupScheduleFrequencyType] \u003cObject\u003e] [[-BackupScheduleFrequencyInterval] \u003cObject[]\u003e] [[-BackupScheduleFrequencySubdayType] \u003cObject\u003e] \r\n[[-BackupScheduleFrequencySubdayInterval] \u003cInt32\u003e] [[-BackupScheduleFrequencyRelativeInterval] \u003cObject\u003e] [[-BackupScheduleFrequencyRecurrenceFactor] \u003cInt32\u003e] [[-BackupScheduleStartDate] \u003cString\u003e] [[-BackupScheduleEndDate] \u003cString\u003e] [[-BackupScheduleStartTime] \u003cString\u003e] [[-BackupScheduleEndTime] \u003cString\u003e] [[-BackupThreshold] \u003cInt32\u003e] [-CompressBackup] [[-CopyDestinationFolder] \u003cString\u003e] [[-CopyJob] \u003cString\u003e] [[-CopyRetention] \u003cInt32\u003e] [[-CopySchedule] \u003cString\u003e] [-CopyScheduleDisabled] [[-CopyScheduleFrequencyType] \u003cObject\u003e] [[-CopyScheduleFrequencyInterval] \u003cObject[]\u003e] \r\n[[-CopyScheduleFrequencySubdayType] \u003cObject\u003e] [[-CopyScheduleFrequencySubdayInterval] \u003cInt32\u003e] [[-CopyScheduleFrequencyRelativeInterval] \u003cObject\u003e] [[-CopyScheduleFrequencyRecurrenceFactor] \u003cInt32\u003e] [[-CopyScheduleStartDate] \u003cString\u003e] [[-CopyScheduleEndDate] \u003cString\u003e] [[-CopyScheduleStartTime] \u003cString\u003e] [[-CopyScheduleEndTime] \u003cString\u003e] [-DisconnectUsers] [[-FullBackupPath] \u003cString\u003e] [-GenerateFullBackup] [[-HistoryRetention] \u003cInt32\u003e] [-NoRecovery] [-NoInitialization] [[-PrimaryMonitorServer] \u003cString\u003e] [[-PrimaryMonitorCredential] \u003cPSCredential\u003e] [[-PrimaryMonitorServerSecurityMode] \u003cObject\u003e] \r\n[-PrimaryThresholdAlertEnabled] [[-RestoreDataFolder] \u003cString\u003e] [[-RestoreLogFolder] \u003cString\u003e] [[-RestoreDelay] \u003cInt32\u003e] [[-RestoreAlertThreshold] \u003cInt32\u003e] [[-RestoreJob] \u003cString\u003e] [[-RestoreRetention] \u003cInt32\u003e] [[-RestoreSchedule] \u003cString\u003e] [-RestoreScheduleDisabled] [[-RestoreScheduleFrequencyType] \u003cObject\u003e] [[-RestoreScheduleFrequencyInterval] \u003cObject[]\u003e] [[-RestoreScheduleFrequencySubdayType] \u003cObject\u003e] [[-RestoreScheduleFrequencySubdayInterval] \u003cInt32\u003e] [[-RestoreScheduleFrequencyRelativeInterval] \u003cObject\u003e] [[-RestoreScheduleFrequencyRecurrenceFactor] \u003cInt32\u003e] [[-RestoreScheduleStartDate] \r\n\u003cString\u003e] [[-RestoreScheduleEndDate] \u003cString\u003e] [[-RestoreScheduleStartTime] \u003cString\u003e] [[-RestoreScheduleEndTime] \u003cString\u003e] [[-RestoreThreshold] \u003cInt32\u003e] [[-SecondaryDatabasePrefix] \u003cString\u003e] [[-SecondaryDatabaseSuffix] \u003cString\u003e] [[-SecondaryMonitorServer] \u003cString\u003e] [[-SecondaryMonitorCredential] \u003cPSCredential\u003e] [[-SecondaryMonitorServerSecurityMode] \u003cObject\u003e] [-SecondaryThresholdAlertEnabled] [-Standby] [[-StandbyDirectory] \u003cString\u003e] [-UseExistingFullBackup] [[-UseBackupFolder] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaDbLogShipRecovery",
        "Description":  "By default all the databases for a particular instance are recovered.\nIf the database is in the right state, either standby or recovering, the process will try to recover the database.\n\nAt first the function will check if the backup source directory can still be reached.\nIf so it will look up the last transaction log backup for the database. If that backup file is not the last copied file the log shipping copy job will be started.\nIf the directory cannot be reached for the function will continue to the restoring process.\nAfter the copy job check is performed the job is disabled to prevent the job to run.\n\nFor the restore the log shipping status is checked in the msdb database.\nIf the last restored file is not the same as the last file name found, the log shipping restore job will be executed.\nAfter the restore job check is performed the job is disabled to prevent the job to run\n\nThe last part is to set the database online by restoring the databases with recovery",
        "Tags":  "LogShipping",
        "Synopsis":  "Invoke-DbaDbLogShipRecovery recovers log shipped databases to a normal state to act upon a migration or disaster.",
        "Alias":  "Invoke-DbaLogShippingRecovery",
        "Author":  "Sander Stad (@sqlstad), sqlstad.nl",
        "CommandName":  "Invoke-DbaDbLogShipRecovery",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbaDbLogShipRecovery",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbLogShipRecovery -SqlInstance server1\nRecovers all the databases on the instance that are enabled for log shipping\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDbLogShipRecovery -SqlInstance server1 -SqlCredential $cred -Verbose\nRecovers all the databases on the instance that are enabled for log shipping using a credential\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaDbLogShipRecovery -SqlInstance server1 -database db_logship -Verbose\nRecovers the database \"db_logship\" to a normal status\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003edb1, db2, db3, db4 | Invoke-DbaDbLogShipRecovery -SqlInstance server1 -Verbose\nRecovers the database db1, db2, db3, db4 to a normal status\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eInvoke-DbaDbLogShipRecovery -SqlInstance server1 -WhatIf\nShows what would happen if the command were executed.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Database to perform the restore for. This value can also be piped enabling multiple databases to be recovered.\r\nIf this value is not supplied all databases will be recovered.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NoRecovery",
                           "Allows you to choose to not restore the database to a functional state (Normal) in the final steps of the process.\r\nBy default the database is restored to a functional state (Normal).",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "Use this parameter to force the function to continue and perform any adjusting actions to successfully execute",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Allows piped input from Get-DbaDatabase",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Delay",
                           "Set the delay in seconds to wait for the copy and/or restore jobs.\r\nBy default the delay is 5 seconds",
                           "",
                           false,
                           "false",
                           "5"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Invoke-DbaDbLogShipRecovery [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-Database] \u003cString[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-NoRecovery] [-EnableException] [-Force] [[-InputObject] \u003cDatabase[]\u003e] [[-Delay] \u003cInt32\u003e] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaDbMirrorFailover",
        "Description":  "Failover a mirrored database",
        "Tags":  [
                     "Mirror",
                     "HA"
                 ],
        "Synopsis":  "Failover a mirrored database",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Invoke-DbaDbMirrorFailover",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbaDbMirrorFailover",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbMirrorFailover -SqlInstance sql2016 -Database pubs\nFails over the pubs database on sql2016. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016 -Database pubs | Invoke-DbaDbMirrorFailover -Force -Confirm:$false\nForces the failover of the pubs database on sql2016 and allows data loss.\r\nDoes not prompt for confirmation.",
        "Params":  [
                       [
                           "SqlInstance",
                           "SQL Server name or SMO object representing the primary SQL Server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the primary instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database or databases to mirror",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows piping from Get-DbaDatabase",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Force",
                           "Force Failover and allow data loss",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Invoke-DbaDbMirrorFailover [[-SqlInstance] \u003cDbaInstanceParameter\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaDbMirroring",
        "Description":  "Automates the creation of database mirrors.\n\n* Verifies that a mirror is possible\n* Sets the recovery model to Full if needed\n* If the database does not exist on mirror or witness, a backup/restore is performed\n* Sets up endpoints if necessary\n* Creates a login and grants permissions to service accounts if needed\n* Starts endpoints if needed\n* Sets up partner for mirror\n* Sets up partner for primary\n* Sets up witness if one is specified\n\nNOTE: If a backup / restore is performed, the backups will be left in tact on the network share.",
        "Tags":  [
                     "Mirror",
                     "HA"
                 ],
        "Synopsis":  "Automates the creation of database mirrors.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Invoke-DbaDbMirroring",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbaDbMirroring",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e Primary = \u0027sql2017a\u0027\r\n\u003e\u003e Mirror = \u0027sql2017b\u0027\r\n\u003e\u003e MirrorSqlCredential = \u0027sqladmin\u0027\r\n\u003e\u003e Witness = \u0027sql2019\u0027\r\n\u003e\u003e Database = \u0027pubs\u0027\r\n\u003e\u003e SharedPath = \u0027\\\\nas\\sql\\share\u0027\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Invoke-DbaDbMirroring @params\nPerforms a bunch of checks to ensure the pubs database on sql2017a\r\ncan be mirrored from sql2017a to sql2017b. Logs in to sql2019 and sql2017a\r\nusing Windows credentials and sql2017b using a SQL credential.\nPrompts for confirmation for most changes. To avoid confirmation, use -Confirm:$false or\r\nuse the syntax in the second example.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e Primary = \u0027sql2017a\u0027\r\n\u003e\u003e Mirror = \u0027sql2017b\u0027\r\n\u003e\u003e MirrorSqlCredential = \u0027sqladmin\u0027\r\n\u003e\u003e Witness = \u0027sql2019\u0027\r\n\u003e\u003e Database = \u0027pubs\u0027\r\n\u003e\u003e SharedPath = \u0027\\\\nas\\sql\\share\u0027\r\n\u003e\u003e Force = $true\r\n\u003e\u003e Confirm = $false\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Invoke-DbaDbMirroring @params\nPerforms a bunch of checks to ensure the pubs database on sql2017a\r\ncan be mirrored from sql2017a to sql2017b. Logs in to sql2019 and sql2017a\r\nusing Windows credentials and sql2017b using a SQL credential.\nDrops existing pubs database on Mirror and Witness and restores them with\r\na fresh backup.\nDoes all the things in the decription, does not prompt for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$map = @{ \u0027database_data\u0027 = \u0027M:\\Data\\database_data.mdf\u0027 \u0027database_log\u0027 = \u0027L:\\Log\\database_log.ldf\u0027 }\nPS C:\\\u003e Get-ChildItem \\\\nas\\seed | Restore-DbaDatabase -SqlInstance sql2017b -FileMapping $map -NoRecovery\r\nPS C:\\\u003e Get-DbaDatabase -SqlInstance sql2017a -Database pubs | Invoke-DbaDbMirroring -Mirror sql2017b -Confirm:$false\nRestores backups from sql2017a to a specific file struture on sql2017b then creates mirror with no prompts for confirmation.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2017a -Database pubs |\n\u003e\u003e Invoke-DbaDbMirroring -Mirror sql2017b -UseLastBackup -Confirm:$false\nMirrors pubs on sql2017a to sql2017b and uses the last full and logs from sql2017a to seed. Doesn\u0027t prompt for confirmation.",
        "Params":  [
                       [
                           "Primary",
                           "SQL Server name or SMO object representing the primary SQL Server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "PrimarySqlCredential",
                           "Login to the primary instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Mirror",
                           "SQL Server name or SMO object representing the mirror SQL Server.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "MirrorSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Witness",
                           "SQL Server name or SMO object representing the witness SQL Server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "WitnessSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database or databases to mirror.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SharedPath",
                           "The network share where the backups will be backed up and restored from.\nEach SQL Server service account must have access to this share.\nNOTE: If a backup / restore is performed, the backups will be left in tact on the network share.",
                           "NetworkShare",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaDatabase.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "UseLastBackup",
                           "Use the last full backup of database.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "Drop and recreate the database on remote servers using fresh backup.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Invoke-DbaDbMirroring [[-Primary] \u003cDbaInstanceParameter\u003e] [[-PrimarySqlCredential] \u003cPSCredential\u003e] [-Mirror] \u003cDbaInstanceParameter[]\u003e [[-MirrorSqlCredential] \u003cPSCredential\u003e] [[-Witness] \u003cDbaInstanceParameter\u003e] [[-WitnessSqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-SharedPath] \u003cString\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-UseLastBackup] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaDbShrink",
        "Description":  "Shrinks all files in a database. Databases should be shrunk only when completely necessary.\n\nMany awesome SQL people have written about why you should not shrink your data files. Paul Randal and Kalen Delaney wrote great posts about this topic:\n\nhttp://www.sqlskills.com/blogs/paul/why-you-should-not-shrink-your-data-files\nhttp://sqlmag.com/sql-server/shrinking-data-files\n\nHowever, there are some cases where a database will need to be shrunk. In the event that you must shrink your database:\n\n1. Ensure you have plenty of space for your T-Log to grow\n2. Understand that shrinks require a lot of CPU and disk resources\n3. Consider running DBCC INDEXDEFRAG or ALTER INDEX ... REORGANIZE after the shrink is complete.",
        "Tags":  [
                     "Shrink",
                     "Database"
                 ],
        "Synopsis":  "Shrinks all files in a database. This is a command that should rarely be used.\n\n- Shrinks can cause severe index fragmentation (to the tune of 99%)\n- Shrinks can cause massive growth in the database\u0027s transaction log\n- Shrinks can require a lot of time and system resources to perform data movement",
        "Alias":  "Invoke-DbaDatabaseShrink",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Invoke-DbaDbShrink",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbaDbShrink",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbShrink -SqlInstance sql2016 -Database Northwind,pubs,Adventureworks2014\nShrinks Northwind, pubs and Adventureworks2014 to have as little free space as possible.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDbShrink -SqlInstance sql2014 -Database AdventureWorks2014 -PercentFreeSpace 50\nShrinks AdventureWorks2014 to have 50% free space. So let\u0027s say AdventureWorks2014 was 1GB and it\u0027s using 100MB space. The database free space would be reduced to 50MB.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaDbShrink -SqlInstance sql2014 -Database AdventureWorks2014 -PercentFreeSpace 50 -FileType Data -StepSize 25MB\nShrinks AdventureWorks2014 to have 50% free space, runs shrinks in 25MB chunks for improved performance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInvoke-DbaDbShrink -SqlInstance sql2012 -AllUserDatabases\nShrinks all databases on SQL2012 (not ideal for production)",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Defaults to the default instance on localhost.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential).",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AllUserDatabases",
                           "Run command against all user databases.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "PercentFreeSpace",
                           "Specifies how much free space to leave, defaults to 0.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "ShrinkMethod",
                           "Specifies the method that is used to shrink the database\r\nDefault\r\nData in pages located at the end of a file is moved to pages earlier in the file. Files are truncated to reflect allocated space.\r\nEmptyFile\r\nMigrates all of the data from the referenced file to other files in the same filegroup. (DataFile and LogFile objects only).\r\nNoTruncate\r\nData in pages located at the end of a file is moved to pages earlier in the file.\r\nTruncateOnly\r\nData distribution is not affected. Files are truncated to reflect allocated space, recovering free space at the end of any file.",
                           "",
                           false,
                           "false",
                           "Default"
                       ],
                       [
                           "FileType",
                           "Specifies the files types that will be shrunk\r\nAll - All Data and Log files are shrunk, using database shrink (Default)\r\nData - Just the Data files are shrunk using file shrink\r\nLog - Just the Log files are shrunk using file shrink",
                           "",
                           false,
                           "false",
                           "All"
                       ],
                       [
                           "StepSize",
                           "Measured in bits - but no worries! PowerShell has a very cool way of formatting bits. Just specify something like: 1MB or 10GB. See the examples for more information.\nIf specified, this will chunk a larger shrink operation into multiple smaller shrinks.\r\nIf shrinking a file by a large amount there are benefits of doing multiple smaller chunks.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "StatementTimeout",
                           "Timeout in minutes. Defaults to infinity (shrinks can take a while).",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "LogsOnly",
                           "Deprecated. Use FileType instead.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ExcludeIndexStats",
                           "Exclude statistics about fragmentation.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ExcludeUpdateUsage",
                           "Exclude DBCC UPDATE USAGE for database.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts for confirmation of every step. For example:\nAre you sure you want to perform this action?\r\nPerforming the operation \"Shrink database\" on target \"pubs on SQL2016\\VNEXT\".\r\n[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is \"Y\"):",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Invoke-DbaDbShrink [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-AllUserDatabases] [[-PercentFreeSpace] \u003cInt32\u003e] [[-ShrinkMethod] \u003cString\u003e] [[-FileType] \u003cString\u003e] [[-StepSize] \u003cInt32\u003e] [[-StatementTimeout] \u003cInt32\u003e] [-LogsOnly] [-ExcludeIndexStats] [-ExcludeUpdateUsage] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaDbUpgrade",
        "Description":  "Updates compatibility level, then runs CHECKDB with data_purity, DBCC updateusage, sp_updatestats and finally sp_refreshview against all user views.",
        "Tags":  [
                     "Shrink",
                     "Database"
                 ],
        "Synopsis":  "Take a database and upgrades it to compatibility of the SQL Instance its hosted on. Based on https://thomaslarock.com/2014/06/upgrading-to-sql-server-2014-a-dozen-things-to-check/",
        "Alias":  "Invoke-DbaDatabaseUpgrade",
        "Author":  "Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/",
        "CommandName":  "Invoke-DbaDbUpgrade",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbaDbUpgrade",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbUpgrade -SqlInstance PRD-SQL-MSD01 -Database Test\nRuns the below processes against the databases\r\n-- Puts compatibility of database to level of SQL Instance\r\n-- Runs CHECKDB DATA_PURITY\r\n-- Runs DBCC UPDATESUSAGE\r\n-- Updates all users statistics\r\n-- Runs sp_refreshview against every view in the database\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDbUpgrade -SqlInstance PRD-SQL-INT01 -Database Test -NoRefreshView\nRuns the upgrade command skipping the sp_refreshview update on all views\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaDbUpgrade -SqlInstance PRD-SQL-INT01 -Database Test -Force\nIf database Test is already at the correct compatibility, runs every necessary step\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016 | Out-GridView -Passthru | Invoke-DbaDbUpgrade\nGet only specific databases using GridView and pass those to Invoke-DbaDbUpgrade",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "SqlCredential object used to connect to the SQL Server as a different user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is autopopulated from the server. If unspecified, all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is autopopulated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NoCheckDb",
                           "Skip checkdb",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NoUpdateUsage",
                           "Skip usage update",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NoUpdateStats",
                           "Skip stats update",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NoRefreshView",
                           "Skip view update",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "AllUserDatabases",
                           "Run command against all user databases",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "Don\u0027t skip over databases that are already at the same level the instance is",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "A collection of databases (such as returned by Get-DbaDatabase)",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts for confirmation of every step. For example:\nAre you sure you want to perform this action?\r\nPerforming the operation \"Update database\" on target \"pubs on SQL2016\\VNEXT\".\r\n[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is \"Y\"):",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Invoke-DbaDbUpgrade [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-NoCheckDb] [-NoUpdateUsage] [-NoUpdateStats] [-NoRefreshView] [-AllUserDatabases] [-Force] [-InputObject \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaDiagnosticQuery",
        "Description":  "This is the main function of the Sql Server Diagnostic Queries related functions in dbatools.\nThe diagnostic queries are developed and maintained by Glenn Berry and they can be found here along with a lot of documentation:\nhttp://www.sqlskills.com/blogs/glenn/category/dmv-queries/\n\nThe most recent version of the diagnostic queries are included in the dbatools module.\nBut it is possible to download a newer set or a specific version to an alternative location and parse and run those scripts.\nIt will run all or a selection of those scripts on one or multiple servers and return the result as a PowerShell Object",
        "Tags":  [
                     "Database",
                     "DMV"
                 ],
        "Synopsis":  "Invoke-DbaDiagnosticQuery runs the scripts provided by Glenn Berry\u0027s DMV scripts on specified servers",
        "Alias":  "",
        "Author":  "Andre Kamman (@AndreKamman), http://clouddba.io",
        "CommandName":  "Invoke-DbaDiagnosticQuery",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbaDiagnosticQuery",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDiagnosticQuery -SqlInstance sql2016\nRun the selection made by the user on the Sql Server instance specified.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDiagnosticQuery -SqlInstance sql2016 -UseSelectionHelper | Export-DbaDiagnosticQuery -Path C:\\temp\\gboutput\nProvides a gridview with all the queries to choose from and will run the selection made by the user on the SQL Server instance specified.\r\nThen it will export the results to Export-DbaDiagnosticQuery.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaDiagnosticQuery -sqlinstance localhost -ExportQueries -outputpath \"C:\\temp\\DiagnosticQueries\"\nExport All Queries to Disk\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInvoke-DbaDiagnosticQuery -sqlinstance localhost -DatabaseSpecific -DatabaseName \u0027tempdb\u0027 -ExportQueries -outputpath \"C:\\temp\\DiagnosticQueries\"\nExport Database Specific Queries for all User Dbs\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eInvoke-DbaDiagnosticQuery -sqlinstance localhost -DatabaseSpecific -DatabaseName \u0027tempdb\u0027 -ExportQueries -outputpath \"C:\\temp\\DiagnosticQueries\"\nExport Database Specific Queries For One Target Database\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eInvoke-DbaDiagnosticQuery -sqlinstance localhost -DatabaseSpecific -DatabaseName \u0027tempdb\u0027 -ExportQueries -outputpath \"C:\\temp\\DiagnosticQueries\" -queryname \u0027Database-scoped Configurations\u0027\nExport Database Specific Queries For One Target Database and One Specific Query\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eInvoke-DbaDiagnosticQuery -sqlinstance localhost -UseSelectionHelper\nChoose Queries To Export\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e[PSObject[]]$results = Invoke-DbaDiagnosticQuery -SqlInstance localhost -whatif\nParse the appropriate diagnostic queries by connecting to server, and instead of running them, return as [PSCustomObject[]] to work with further\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003e$results = Invoke-DbaDiagnosticQuery -SqlInstance Sql2017 -DatabaseSpecific -queryname \u0027Database-scoped Configurations\u0027 -databasename TestStuff\nRun diagnostic queries targeted at specific database, and only run database level queries against this database.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Can be either a string or SMO server",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process. If unspecified, all databases will be processed",
                           "DatabaseName",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeQuery",
                           "The Queries to exclude",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows alternative Windows or SQL login credentials to be used",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "Alternate path for the diagnostic scripts",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "QueryName",
                           "Only run specific query",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "UseSelectionHelper",
                           "Provides a gridview with all the queries to choose from and will run the selection made by the user on the Sql Server instance specified.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InstanceOnly",
                           "Run only instance level queries",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DatabaseSpecific",
                           "Run only database level queries",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ExcludeQueryTextColumn",
                           "Use this switch to exclude the [Complete Query Text] column from relevant queries",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ExcludePlanColumn",
                           "Use this switch to exclude the [Query Plan] column from relevant queries",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NoColumnParsing",
                           "Does not parse the [Complete Query Text] and [Query Plan] columns and disregards the ExcludeQueryTextColumn and NoColumnParsing switches",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "OutputPath",
                           "Directory to parsed diagnostict queries to. This will split them based on server, databasename, and query.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExportQueries",
                           "Use this switch to export the diagnostic queries to sql files. I\r\nnstead of running the queries, the server will be evaluated to find the appropriate queries to run based on SQL Version.\r\nThese sql files will then be created in the OutputDirectory",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command would execute, but does not actually perform the command",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts to confirm certain actions",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Invoke-DbaDiagnosticQuery [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-ExcludeQuery \u003cObject[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Path \u003cFileInfo\u003e] [-QueryName \u003cString[]\u003e] [-UseSelectionHelper] [-InstanceOnly] [-DatabaseSpecific] [-ExcludeQueryTextColumn] [-ExcludePlanColumn] [-NoColumnParsing] [-OutputPath \u003cString\u003e] [-ExportQueries] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaPfRelog",
        "Description":  "Pipeline-compatible wrapper for the relog command. Relog is useful for converting Windows Perfmon.\n\nExtracts performance counters from performance counter logs into other formats,\nsuch as text-TSV (for tab-delimited text), text-CSV (for comma-delimited text), binary-BIN, or SQL.\n\n`relog \"C:\\PerfLogs\\Admin\\System Correlation\\WORKSTATIONX_20180112-000001\\DataCollector01.blg\" -o C:\\temp\\foo.csv -f tsv`\n\nIf you find any input hangs, please send us the output so we can accommodate for it then use -Raw for an immediate solution.",
        "Tags":  [
                     "Performance",
                     "DataCollector",
                     "PerfCounter",
                     "Relog"
                 ],
        "Synopsis":  "Pipeline-compatible wrapper for the relog command which is available on modern Windows platforms.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Invoke-DbaPfRelog",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Invoke-DbaPfRelog",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaPfRelog -Path C:\\temp\\perfmon.blg\nCreates C:\\temp\\perfmon.tsv from C:\\temp\\perfmon.blg.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaPfRelog -Path C:\\temp\\perfmon.blg -Destination C:\\temp\\a\\b\\c\nCreates the temp, a, and b directories if needed, then generates c.tsv (tab separated) from C:\\temp\\perfmon.blg.\nReturns the newly created file as a file object.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet -ComputerName sql2016 | Get-DbaPfDataCollector | Invoke-DbaPfRelog -Destination C:\\temp\\perf\nCreates C:\\temp\\perf if needed, then generates computername-datacollectorname.tsv (tab separated) from the latest logs of all data collector sets on sql2016. This destination format was chosen to \r\navoid naming conflicts with piped input.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInvoke-DbaPfRelog -Path C:\\temp\\perfmon.blg -Destination C:\\temp\\a\\b\\c -Raw\n```\r\n[Invoke-DbaPfRelog][21:21:35] relog \"C:\\temp\\perfmon.blg\" -f csv -o C:\\temp\\a\\b\\c\nInput\r\n----------------\r\nFile(s):\r\nC:\\temp\\perfmon.blg (Binary)\nBegin:    1/13/2018 5:13:23\r\nEnd:      1/13/2018 14:29:55\r\nSamples:  2227\n100.00%\nOutput\r\n----------------\r\nFile:     C:\\temp\\a\\b\\c.csv\nBegin:    1/13/2018 5:13:23\r\nEnd:      1/13/2018 14:29:55\r\nSamples:  2227\nThe command completed successfully.\r\n```\nCreates the temp, a, and b directories if needed, then generates c.tsv (tab separated) from C:\\temp\\perfmon.blg then outputs the raw results of the relog command.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eInvoke-DbaPfRelog -Path \u0027C:\\temp\\perflog with spaces.blg\u0027 -Destination C:\\temp\\a\\b\\c -Type csv -BeginTime ((Get-Date).AddDays(-30)) -EndTime ((Get-Date).AddDays(-1))\nCreates the temp, a, and b directories if needed, then generates c.csv (comma separated) from C:\\temp\\perflog with spaces.blg\u0027, starts 30 days ago and ends one day ago.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$servers | Get-DbaPfDataCollectorSet | Get-DbaPfDataCollector | Invoke-DbaPfRelog -Multithread -AllowClobber\nRelogs latest data files from all collectors within the servers listed in $servers.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollector -Collector DataCollector01 | Invoke-DbaPfRelog -AllowClobber -AllTime\nRelogs all the log files from the DataCollector01 on the local computer and allows overwrite.",
        "Params":  [
                       [
                           "Path",
                           "Specifies the pathname of an existing performance counter log or performance counter path. You can specify multiple input files.",
                           "FullName",
                           false,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "Destination",
                           "Specifies the pathname of the output file or SQL database where the counters will be written. Defaults to the same directory as the source.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Type",
                           "The output format. Defaults to tsv. Options include tsv, csv, bin, and sql.\nFor a SQL database, the output file specifies the DSN!counter_log. You can specify the database location by using the ODBC manager to configure the DSN (Database System Name).\nFor more information, read here: https://technet.microsoft.com/en-us/library/bb490958.aspx",
                           "",
                           false,
                           "false",
                           "tsv"
                       ],
                       [
                           "Append",
                           "If this switch is enabled, output will be appended to the specified file instead of overwriting. This option does not apply to SQL format where the default is always to append.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "AllowClobber",
                           "If this switch is enabled, the destination file will be overwritten if it exists.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "PerformanceCounter",
                           "Specifies the performance counter path to log.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "PerformanceCounterPath",
                           "Specifies the pathname of the text file that lists the performance counters to be included in a relog file. Use this option to list counter paths in an input file, one per line. Default setting is \r\nall counters in the original log file are relogged.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Interval",
                           "Specifies sample intervals in \"n\" records. Includes every nth data point in the relog file. Default is every data point.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "BeginTime",
                           "This is is Get-Date object and we format it for you.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EndTime",
                           "Specifies end time for copying last record from the input file. This is is Get-Date object and we format it for you.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ConfigPath",
                           "Specifies the pathname of the settings file that contains command-line parameters.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Summary",
                           "If this switch is enabled, the performance counters and time ranges of log files specified in the input file will be displayed.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Accepts the output of Get-DbaPfDataCollector and Get-DbaPfDataCollectorSet as input via the pipeline.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Multithread",
                           "If this switch is enabled, processing will be done in parallel. This may speed up large batches or large files.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "AllTime",
                           "If this switch is enabled and a datacollector or datacollectorset is passed in via the pipeline, collects all logs, not just the latest.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Raw",
                           "If this switch is enabled, the results of the DOS command instead of Get-ChildItem will be displayed. This does not run in parallel.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Invoke-DbaPfRelog [[-Path] \u003cString[]\u003e] [[-Destination] \u003cString\u003e] [[-Type] \u003cString\u003e] [-Append] [-AllowClobber] [[-PerformanceCounter] \u003cString[]\u003e] [[-PerformanceCounterPath] \u003cString\u003e] [[-Interval] \u003cInt32\u003e] [[-BeginTime] \u003cDateTime\u003e] [[-EndTime] \u003cDateTime\u003e] [[-ConfigPath] \u003cString\u003e] [-Summary] [[-InputObject] \u003cObject[]\u003e] [-Multithread] [-AllTime] [-Raw] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaQuery",
        "Description":  "This function is a wrapper command around Invoke-DbaAsync, which in turn is based on Invoke-SqlCmd2.\nIt was designed to be more convenient to use in a pipeline and to behave in a way consistent with the rest of our functions.",
        "Tags":  [
                     "Database",
                     "Query"
                 ],
        "Synopsis":  "A command to run explicit T-SQL commands or files.",
        "Alias":  "Invoke-DbaCmd,Invoke-DbaSqlQuery",
        "Author":  "Friedrich Weinmann (@FredWeinmann)",
        "CommandName":  "Invoke-DbaQuery",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbaQuery",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaQuery -SqlInstance server\\instance -Query \u0027SELECT foo FROM bar\u0027\nRuns the sql query \u0027SELECT foo FROM bar\u0027 against the instance \u0027server\\instance\u0027\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance [SERVERNAME] -Group [GROUPNAME] | Invoke-DbaQuery -Query \u0027SELECT foo FROM bar\u0027\nRuns the sql query \u0027SELECT foo FROM bar\u0027 against all instances in the group [GROUPNAME] on the CMS [SERVERNAME]\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\"server1\", \"server1\\nordwind\", \"server2\" | Invoke-DbaQuery -File \"C:\\scripts\\sql\\rebuild.sql\"\nRuns the sql commands stored in rebuild.sql against the instances \"server1\", \"server1\\nordwind\" and \"server2\"\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance \"server1\", \"server1\\nordwind\", \"server2\" | Invoke-DbaQuery -File \"C:\\scripts\\sql\\rebuild.sql\"\nRuns the sql commands stored in rebuild.sql against all accessible databases of the instances \"server1\", \"server1\\nordwind\" and \"server2\"\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eInvoke-DbaQuery -SqlInstance . -Query \u0027SELECT * FROM users WHERE Givenname = @name\u0027 -SqlParameters @{ Name = \"Maria\" }\nExecutes a simple query against the users table using SQL Parameters.\r\nThis avoids accidental SQL Injection and is the safest way to execute queries with dynamic content.\r\nKeep in mind the limitations inherent in parameters - it is quite impossible to use them for content references.\r\nWhile it is possible to parameterize a where condition, it is impossible to use this to select which columns to select.\r\nThe inserted text will always be treated as string content, and not as a reference to any SQL entity (such as columns, tables or databases).\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eInvoke-DbaQuery -SqlInstance aglistener1 -ReadOnly -Query \"select something from readonlydb.dbo.atable\"\nExecutes a query with ReadOnly application intent on aglistener1.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Credential object used to connect to the SQL Server Instance as a different user. This can be a Windows or SQL Server account. Windows users are determined by the existence of a backslash, so if you \r\nare intending to use an alternative Windows connection instead of a SQL login, ensure it contains a backslash.",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database to select before running the query. This list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Query",
                           "Specifies one or more queries to be run. The queries can be Transact-SQL, XQuery statements, or sqlcmd commands. Multiple queries in a single batch may be separated by a semicolon or a GO\nEscape any double quotation marks included in the string.\nConsider using bracketed identifiers such as [MyTable] instead of quoted identifiers such as \"MyTable\".",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "QueryTimeout",
                           "Specifies the number of seconds before the queries time out.",
                           "",
                           false,
                           "false",
                           "600"
                       ],
                       [
                           "File",
                           "Specifies the path to one or several files to be used as the query input.",
                           "InputFile",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlObject",
                           "Specify on or multiple SQL objects. Those will be converted to script and their scripts run on the target system(s).",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "As",
                           "Specifies output type. Valid options for this parameter are \u0027DataSet\u0027, \u0027DataTable\u0027, \u0027DataRow\u0027, \u0027PSObject\u0027, and \u0027SingleValue\u0027\nPSObject output introduces overhead but adds flexibility for working with results: http://powershell.org/wp/forums/topic/dealing-with-dbnull/",
                           "",
                           false,
                           "false",
                           "DataRow"
                       ],
                       [
                           "SqlParameters",
                           "Specifies a hashtable of parameters for parameterized SQL queries.  http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AppendServerInstance",
                           "If this switch is enabled, the SQL Server instance will be appended to PSObject and DataRow output.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "MessagesToOutput",
                           "Use this switch to have on the output stream messages too (e.g. PRINT statements). Output will hold the resultset too. See examples for detail",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "A collection of databases (such as returned by Get-DbaDatabase)",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "ReadOnly",
                           "Execute the query with ReadOnly application intent.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Invoke-DbaQuery [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cString\u003e] [-Query] \u003cString\u003e [-QueryTimeout \u003cInt32\u003e] [-As \u003cString\u003e] [-SqlParameters \u003cIDictionary\u003e] [-AppendServerInstance] [-MessagesToOutput] [-InputObject \u003cDatabase[]\u003e] [-ReadOnly] [-EnableException] [\u003cCommonParameters\u003e]\nInvoke-DbaQuery [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cString\u003e] [-QueryTimeout \u003cInt32\u003e] -File \u003cObject[]\u003e [-As \u003cString\u003e] [-SqlParameters \u003cIDictionary\u003e] [-AppendServerInstance] [-MessagesToOutput] [-InputObject \u003cDatabase[]\u003e] [-ReadOnly] [-EnableException] [\u003cCommonParameters\u003e]\nInvoke-DbaQuery [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cString\u003e] [-QueryTimeout \u003cInt32\u003e] -SqlObject \u003cSqlSmoObject[]\u003e [-As \u003cString\u003e] [-SqlParameters \u003cIDictionary\u003e] [-AppendServerInstance] [-MessagesToOutput] [-InputObject \u003cDatabase[]\u003e] [-ReadOnly] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbatoolsFormatter",
        "Description":  "Uses PSSA\u0027s Invoke-Formatter to format the target files and saves it without the BOM.",
        "Tags":  "Formatting",
        "Synopsis":  "Helps formatting function files to dbatools\u0027 standards",
        "Alias":  "",
        "Author":  "Simone Bizzotto",
        "CommandName":  "Invoke-DbatoolsFormatter",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbatoolsFormatter",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbatoolsFormatter -Path C:\\dbatools\\functions\\Get-DbaDatabase.ps1\nReformats C:\\dbatools\\functions\\Get-DbaDatabase.ps1 to dbatools\u0027 standards",
        "Params":  [
                       [
                           "Path",
                           "The path to the ps1 file that needs to be formatted",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Invoke-DbatoolsFormatter [-Path] \u003cObject[]\u003e [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbatoolsRenameHelper",
        "Description":  "Older dbatools command names have been changed. This script helps keep up.",
        "Tags":  "Module",
        "Synopsis":  "Older dbatools command names have been changed. This script helps keep up.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Invoke-DbatoolsRenameHelper",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbatoolsRenameHelper",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-ChildItem C:\\temp\\ps\\*.ps1 -Recurse | Invoke-DbatoolsRenameHelper\nChecks to see if any ps1 file in C:\\temp\\ps matches an old command name.\r\nIf so, then the command name within the text is updated and the resulting changes are written to disk in UTF-8.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-ChildItem C:\\temp\\ps\\*.ps1 -Recurse | Invoke-DbatoolsRenameHelper -Encoding Ascii -WhatIf\nShows what would happen if the command would run. If the command would run and there were matches,\r\nthe resulting changes would be written to disk as Ascii encoded.",
        "Params":  [
                       [
                           "InputObject",
                           "A piped in object from Get-ChildItem",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Encoding",
                           "Specifies the file encoding. The default is UTF8.\nValid values are:\r\n-- ASCII: Uses the encoding for the ASCII (7-bit) character set.\r\n-- BigEndianUnicode: Encodes in UTF-16 format using the big-endian byte order.\r\n-- Byte: Encodes a set of characters into a sequence of bytes.\r\n-- String: Uses the encoding type for a string.\r\n-- Unicode: Encodes in UTF-16 format using the little-endian byte order.\r\n-- UTF7: Encodes in UTF-7 format.\r\n-- UTF8: Encodes in UTF-8 format.\r\n-- Unknown: The encoding type is unknown or invalid. The data can be treated as binary.",
                           "",
                           false,
                           "false",
                           "UTF8"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Invoke-DbatoolsRenameHelper [-InputObject] \u003cFileInfo[]\u003e [[-Encoding] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaWhoIsActive",
        "Description":  "Output results of Adam Machanic\u0027s sp_WhoIsActive\n\nThis command was built with Adam\u0027s permission. To read more about sp_WhoIsActive, please visit:\n\nUpdates: http://sqlblog.com/blogs/adam_machanic/archive/tags/who+is+active/default.aspx\n\nAlso, consider donating to Adam if you find this stored procedure helpful: http://tinyurl.com/WhoIsActiveDonate",
        "Tags":  [
                     "AdamMechanic",
                     "WhoIsActive",
                     "SpWhoIsActive"
                 ],
        "Synopsis":  "Outputs results of Adam Machanic\u0027s sp_WhoIsActive DataTable",
        "Alias":  "Show-SqlWhoIsActive",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Invoke-DbaWhoIsActive",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbaWhoIsActive",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaWhoIsActive -SqlInstance sqlserver2014a\nExecute sp_whoisactive on sqlserver2014a. This command expects sp_WhoIsActive to be in the master database. Logs into the SQL Server with Windows credentials.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaWhoIsActive -SqlInstance sqlserver2014a -SqlCredential $credential -Database dbatools\nExecute sp_whoisactive on sqlserver2014a. This command expects sp_WhoIsActive to be in the dbatools database. Logs into the SQL Server with SQL Authentication.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaWhoIsActive -SqlInstance sqlserver2014a -GetAverageTime\nSimilar to running sp_WhoIsActive @get_avg_time\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInvoke-DbaWhoIsActive -SqlInstance sqlserver2014a -GetOuterCommand -FindBlockLeaders\nSimilar to running sp_WhoIsActive @get_outer_command = 1, @find_block_leaders = 1",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database where sp_WhoIsActive is installed. Defaults to master. If the sp_WhoIsActive is not installed, the command will warn and exit.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Filter",
                           "FiltersBoth inclusive and exclusive\r\nSet either filter to \u0027\u0027 to disable\r\nSession is a session ID, and either 0 or \u0027\u0027 can be used to indicate \"all\" sessions\r\nAll other filter types support % or _ as wildcards",
                           "As",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "FilterType",
                           "Valid filter types are: session, program, database, login, and host",
                           "",
                           false,
                           "false",
                           "Session"
                       ],
                       [
                           "NotFilter",
                           "FiltersBoth inclusive and exclusive\r\nSet either filter to \u0027\u0027 to disable\r\nSession is a session ID, and either 0 or \u0027\u0027 can be used to indicate \"all\" sessions\r\nAll other filter types support % or _ as wildcards",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NotFilterType",
                           "Valid filter types are: session, program, database, login, and host",
                           "",
                           false,
                           "false",
                           "Session"
                       ],
                       [
                           "ShowOwnSpid",
                           "Retrieve data about the calling session?",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ShowSystemSpids",
                           "Retrieve data about system sessions?",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ShowSleepingSpids",
                           "Controls how sleeping SPIDs are handled, based on the idea of levels of interest\r\n0 does not pull any sleeping SPIDs\r\n1 pulls only those sleeping SPIDs that also have an open transaction\r\n2 pulls all sleeping SPIDs",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "GetFullInnerText",
                           "If 1, gets the full stored procedure or running batch, when available\r\nIf 0, gets only the actual statement that is currently running in the batch or procedure",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "GetPlans",
                           "Get associated query plans for running tasks, if available\r\nIf 1, gets the plan based on the request\u0027s statement offset\r\nIf 2, gets the entire plan based on the request\u0027s plan_handle",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "GetOuterCommand",
                           "Get the associated outer ad hoc query or stored procedure call, if available",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "GetTransactionInfo",
                           "Enables pulling transaction log write info and transaction duration",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "GetTaskInfo",
                           "Get information on active tasks, based on three interest levels\r\nLevel 0 does not pull any task-related information\r\nLevel 1 is a lightweight mode that pulls the top non-CXPACKET wait, giving preference to blockers\r\nLevel 2 pulls all available task-based metrics, including:\r\nnumber of active tasks, current wait stats, physical I/O, context switches, and blocker information",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "GetLocks",
                           "Gets associated locks for each request, aggregated in an XML format",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "GetAverageTime",
                           "Get average time for past runs of an active query\r\n(based on the combination of plan handle, sql handle, and offset)",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "GetAdditonalInfo",
                           "Get additional non-performance-related information about the session or request\r\ntext_size, language, date_format, date_first, quoted_identifier, arithabort, ansi_null_dflt_on,\r\nansi_defaults, ansi_warnings, ansi_padding, ansi_nulls, concat_null_yields_null,\r\ntransaction_isolation_level, lock_timeout, deadlock_priority, row_count, command_type\nIf a SQL Agent job is running, an subnode called agent_info will be populated with some or all of\r\nthe following: job_id, job_name, step_id, step_name, msdb_query_error (in the event of an error)\nIf @get_task_info is set to 2 and a lock wait is detected, a subnode called block_info will be\r\npopulated with some or all of the following: lock_type, database_name, object_id, file_id, hobt_id,\r\napplock_hash, metadata_resource, metadata_class_id, object_name, schema_name",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "FindBlockLeaders",
                           "Walk the blocking chain and count the number of\r\ntotal SPIDs blocked all the way down by a given session\r\nAlso enables task_info Level 1, if @get_task_info is set to 0",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DeltaInterval",
                           "Pull deltas on various metrics\r\nInterval in seconds to wait before doing the second data pull",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "OutputColumnList",
                           "List of desired output columns, in desired order\r\nNote that the final output will be the intersection of all enabled features and all\r\ncolumns in the list. Therefore, only columns associated with enabled features will\r\nactually appear in the output. Likewise, removing columns from this list may effectively\r\ndisable features, even if they are turned on\nEach element in this list must be one of the valid output column names. Names must be\r\ndelimited by square brackets. White space, formatting, and additional characters are\r\nallowed, as long as the list contains exact matches of delimited valid column names.",
                           "",
                           false,
                           "false",
                           "[dd%][session_id][sql_text][sql_command][login_name][wait_info][tasks][tran_log%][cpu%][temp%][block%][reads%][writes%][context%][physical%][query_plan][locks][%]"
                       ],
                       [
                           "SortOrder",
                           "Column(s) by which to sort output, optionally with sort directions.\r\nValid column choices:\r\nsession_id, physical_io, reads, physical_reads, writes, tempdb_allocations,\r\ntempdb_current, CPU, context_switches, used_memory, physical_io_delta,\r\nreads_delta, physical_reads_delta, writes_delta, tempdb_allocations_delta,\r\ntempdb_current_delta, CPU_delta, context_switches_delta, used_memory_delta,\r\ntasks, tran_start_time, open_tran_count, blocking_session_id, blocked_session_count,\r\npercent_complete, host_name, login_name, database_name, start_time, login_time\nNote that column names in the list must be bracket-delimited. Commas and/or white\r\nspace are not required.",
                           "",
                           false,
                           "false",
                           "[start_time] ASC"
                       ],
                       [
                           "FormatOutput",
                           "Formats some of the output columns in a more \"human readable\" form\r\n0 disables output format\r\n1 formats the output for variable-width fonts\r\n2 formats the output for fixed-width fonts",
                           "",
                           false,
                           "false",
                           "1"
                       ],
                       [
                           "DestinationTable",
                           "If set to a non-blank value, the script will attempt to insert into the specified destination table. Please note that the script will not verify that the table exists, or that it has the correct \r\nschema, before doing the insert. Table can be specified in one, two, or three-part format",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ReturnSchema",
                           "If set to 1, no data collection will happen and no result set will be returned; instead,\r\na CREATE TABLE statement will be returned via the @schema parameter, which will match\r\nthe schema of the result set that would be returned by using the same collection of the\r\nrest of the parameters. The CREATE TABLE statement will have a placeholder token of\r\n\u003ctable_name\u003e in place of an actual table name.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Schema",
                           "If set to 1, no data collection will happen and no result set will be returned; instead,\r\na CREATE TABLE statement will be returned via the @schema parameter, which will match\r\nthe schema of the result set that would be returned by using the same collection of the\r\nrest of the parameters. The CREATE TABLE statement will have a placeholder token of\r\n\u003ctable_name\u003e in place of an actual table name.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Help",
                           "Help! What do I do?",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Invoke-DbaWhoIsActive [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject\u003e] [[-Filter] \u003cString\u003e] [[-FilterType] \u003cString\u003e] [[-NotFilter] \u003cString\u003e] [[-NotFilterType] \u003cString\u003e] [-ShowOwnSpid] [-ShowSystemSpids] [[-ShowSleepingSpids] \u003cInt32\u003e] [-GetFullInnerText] [[-GetPlans] \u003cInt32\u003e] [-GetOuterCommand] [-GetTransactionInfo] [[-GetTaskInfo] \u003cInt32\u003e] [-GetLocks] [-GetAverageTime] [-GetAdditonalInfo] [-FindBlockLeaders] [[-DeltaInterval] \u003cInt32\u003e] [[-OutputColumnList] \u003cString\u003e] [[-SortOrder] \u003cString\u003e] [[-FormatOutput] \u003cInt32\u003e] [[-DestinationTable] \u003cString\u003e] \r\n[-ReturnSchema] [[-Schema] \u003cString\u003e] [-Help] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Invoke-DbaXeReplay",
        "Description":  "This command replays events from Read-DbaXEFile. It is simplistic in its approach.\n\n- Writes all queries to a temp sql file\n- Executes temp file using . $sqlcmd so that batches are executed properly\n- Deletes temp file",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "This command replays events from Read-DbaXEFile on one or more target servers",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Invoke-DbaXeReplay",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Invoke-DbaXEReplay",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRead-DbaXEFile -Path C:\\temp\\sample.xel | Invoke-DbaXeReplay -SqlInstance sql2017\nRuns all batch_text for sql_batch_completed against tempdb on sql2017.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRead-DbaXEFile -Path C:\\temp\\sample.xel | Invoke-DbaXeReplay -SqlInstance sql2017 -Database planning -Event sql_batch_completed\nSets the *initial* database to planning then runs only sql_batch_completed against sql2017.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRead-DbaXEFile -Path C:\\temp\\sample.xel | Invoke-DbaXeReplay -SqlInstance sql2017, sql2016\nRuns all batch_text for sql_batch_completed against tempdb on sql2017 and sql2016.",
        "Params":  [
                       [
                           "SqlInstance",
                           "Target SQL Server(s)",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Used to provide alternative credentials.",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The initial starting database.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Event",
                           "Each Response can be limited to processing specific events, while ignoring all the other ones. When this attribute is omitted, all events are processed.",
                           "",
                           false,
                           "false",
                           "@(\u0027sql_batch_completed\u0027, \u0027rcp_completed\u0027)"
                       ],
                       [
                           "InputObject",
                           "Accepts the object output of Read-DbaXESession.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Raw",
                           "By dafault, the results of . $sqlcmd are collected, cleaned up and displayed. If you\u0027d like to see all results immeidately, use Raw.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Invoke-DbaXeReplay [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Event] \u003cString[]\u003e] [-InputObject] \u003cObject\u003e [-Raw] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Join-DbaAvailabilityGroup",
        "Description":  "Joins a secondary replica to an availability group on a SQL Server instance.",
        "Tags":  [
                     "AvailabilityGroup",
                     "HA",
                     "AG"
                 ],
        "Synopsis":  "Joins a secondary replica to an availability group on a SQL Server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Join-DbaAvailabilityGroup",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Join-DbaAvailabilityGroup",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql01 -AvailabilityGroup SharePoint | Join-DbaAvailabilityGroup -SqlInstance sql02\nJoins sql02 to the SharePoint availability group on sql01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$ag = Get-DbaAvailabilityGroup -SqlInstance sql01 -AvailabilityGroup SharePoint\nPS C:\\\u003e Join-DbaAvailabilityGroup -SqlInstance sql02 -InputObject $ag\nJoins sql02 to the SharePoint availability group on sql01\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql01 -AvailabilityGroup SharePoint | Join-DbaAvailabilityGroup -SqlInstance sql02 -WhatIf\nShows what would happen if the command were to run. No actions are actually performed.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql01 -AvailabilityGroup SharePoint | Join-DbaAvailabilityGroup -SqlInstance sql02 -Confirm\nPrompts for confirmation then joins sql02 to the SharePoint availability group on sql01.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityGroup",
                           "The availability group to join.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ClusterType",
                           "Cluster type of the Availability Group. Only supported in SQL Server 2017 and above.\r\nOptions include: External, Wsfc or None.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piped input from Get-DbaAvailabilityGroup.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Join-DbaAvailabilityGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-ClusterType] \u003cString\u003e] [[-InputObject] \u003cAvailabilityGroup[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Join-DbaPath",
        "Description":  "Performs multisegment path joins.",
        "Synopsis":  "Performs multisegment path joins.",
        "Alias":  "",
        "CommandName":  "Join-DbaPath",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eJoin-DbaPath -Path \u0027C:\\temp\u0027 \u0027Foo\u0027 \u0027Bar\u0027\nReturns \u0027C:\\temp\\Foo\\Bar\u0027 on windows.\r\nReturns \u0027C:/temp/Foo/Bar\u0027 on non-windows.",
        "Params":  [
                       [
                           "Path",
                           "The basepath to join on.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Child",
                           "Any number of child paths to add.",
                           "",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Join-DbaPath [-Path] \u003cString\u003e [-Child \u003cString[]\u003e] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Measure-DbaBackupThroughput",
        "Description":  "Returns backup history details for one or more databases on a SQL Server.\n\nOutput looks like this:\nSqlInstance     : sql2016\nDatabase        : SharePoint_Config\nAvgThroughput   : 1.07 MB\nAvgSize         : 24.17\nAvgDuration     : 00:00:01.1000000\nMinThroughput   : 0.02 MB\nMaxThroughput   : 2.26 MB\nMinBackupDate   : 8/6/2015 10:22:01 PM\nMaxBackupDate   : 6/19/2016 12:57:45 PM\nBackupCount     : 10",
        "Tags":  [
                     "Backup",
                     "Database"
                 ],
        "Synopsis":  "Determines how quickly SQL Server is backing up databases to media.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Measure-DbaBackupThroughput",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Measure-DbaBackupThroughput",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eMeasure-DbaBackupThroughput -SqlInstance sql2016\nParses every backup in msdb\u0027s backuphistory for stats on all databases.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eMeasure-DbaBackupThroughput -SqlInstance sql2016 -Database AdventureWorks2014\nParses every backup in msdb\u0027s backuphistory for stats on AdventureWorks2014.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eMeasure-DbaBackupThroughput -SqlInstance sql2005 -Last\nProcesses the last full, diff and log backups every backup for all databases on sql2005.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eMeasure-DbaBackupThroughput -SqlInstance sql2005 -Last -Type Log\nProcesses the last log backups every backup for all databases on sql2005.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eMeasure-DbaBackupThroughput -SqlInstance sql2016 -Since (Get-Date).AddDays(-7) | Where-Object { $_.MinThroughput.Gigabyte -gt 1 }\nGets backup calculations for the last week and filters results that have a minimum of 1GB throughput\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eMeasure-DbaBackupThroughput -SqlInstance sql2016 -Since (Get-Date).AddDays(-365) -Database bigoldb\nGets backup calculations, limited to the last year and only the bigoldb database",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,Instance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Since",
                           "All backups taken on or after the point in time represented by this datetime object will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Last",
                           "If this switch is enabled, only the last backup will be measured.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Type",
                           "By default, this command measures the speed of Full backups. Valid options are \"Full\", \"Log\" and \"Differential\".",
                           "",
                           false,
                           "false",
                           "Full"
                       ],
                       [
                           "DeviceType",
                           "Specifies one or more DeviceTypes to use in filtering backup sets. Valid values are \"Disk\", \"Permanent Disk Device\", \"Tape\", \"Permanent Tape Device\", \"Pipe\", \"Permanent Pipe Device\" and \"Virtual \r\nDevice\", as well as custom integers for your own DeviceTypes.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Measure-DbaBackupThroughput [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-Since \u003cDateTime\u003e] [-Last] [-Type \u003cString\u003e] [-DeviceType \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Measure-DbaDiskSpaceRequirement",
        "Description":  "Returns a file list from source and destination where source file may overwrite destination. Complex scenarios where a new file may exist is taken into account.\nThis command will accept a hash object in pipeline with the following keys: Source, SourceDatabase, Destination. Using this command will provide a way to prepare before a complex migration with multiple databases from different sources and destinations.",
        "Tags":  [
                     "Database",
                     "DiskSpace",
                     "Migration"
                 ],
        "Synopsis":  "Calculate the space needed to copy and possibly replace a database from one SQL server to another.",
        "Alias":  "",
        "Author":  "Pollus Brodeur (@pollusb)",
        "CommandName":  "Measure-DbaDiskSpaceRequirement",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Measure-DbaDiskSpaceRequirement",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eMeasure-DbaDiskSpaceRequirement -Source INSTANCE1 -Database DB1 -Destination INSTANCE2\nCalculate space needed for a simple migration with one database with the same name at destination.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e@(\n\u003e\u003e [PSCustomObject]@{Source=\u0027SQL1\u0027;Destination=\u0027SQL2\u0027;Database=\u0027DB1\u0027},\r\n\u003e\u003e [PSCustomObject]@{Source=\u0027SQL1\u0027;Destination=\u0027SQL2\u0027;Database=\u0027DB2\u0027}\r\n\u003e\u003e ) | Measure-DbaDiskSpaceRequirement\nUsing a PSCustomObject with 2 databases to migrate on SQL2.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eImport-Csv -Path .\\migration.csv -Delimiter \"`t\" | Measure-DbaDiskSpaceRequirement | Format-Table -AutoSize\nUsing a CSV file. You will need to use this header line \"Source\u003ctab\u003eDestination\u003ctab\u003eDatabase\u003ctab\u003eDestinationDatabase\".\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$qry = \"SELECT Source, Destination, Database FROM dbo.Migrations\"\nPS C:\\\u003e Invoke-DbaCmd -SqlInstance DBA -Database Migrations -Query $qry | Measure-DbaDiskSpaceRequirement\nUsing a SQL table. We are DBA after all!",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server.",
                           "",
                           true,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "Database",
                           "The database to copy. It MUST exist.",
                           "",
                           true,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server instance.",
                           "",
                           true,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "DestinationDatabase",
                           "The database name at destination.\r\nMay or may not be present, if unspecified it will default to the database name provided in SourceDatabase.",
                           "",
                           false,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "Credential",
                           "The credentials to use to connect via CIM/WMI/PowerShell remoting.",
                           "",
                           false,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Measure-DbaDiskSpaceRequirement [-Source] \u003cDbaInstanceParameter\u003e [-Database] \u003cString\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter\u003e [[-DestinationDatabase] \u003cString\u003e] [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Measure-DbatoolsImport",
        "Description":  "Displays the import load times of the dbatools PowerShell module",
        "Tags":  "Debug",
        "Synopsis":  "Displays the import load times of the dbatools PowerShell module",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Measure-DbatoolsImport",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Measure-DbatoolsImport",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eMeasure-DbatoolsImport\nDisplays the import load times of the dbatools PowerShell module\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eImport-Module dbatools\nPS C:\\\u003e Measure-DbatoolsImport\nDisplays the import load times of the dbatools PowerShell module",
        "Params":  [

                   ],
        "Syntax":  "Measure-DbatoolsImport [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Mount-DbaDatabase",
        "Description":  "This command will attach a SQL Server database.",
        "Tags":  "Database",
        "Synopsis":  "Attach a SQL Server Database - aliased to Attach-DbaDatabase",
        "Alias":  "Attach-DbaDatabase",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Mount-DbaDatabase",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Mount-DbaDatabase",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$fileStructure = New-Object System.Collections.Specialized.StringCollection\nPS C:\\\u003e $fileStructure.Add(\"E:\\archive\\example.mdf\")\r\nPS C:\\\u003e $filestructure.Add(\"E:\\archive\\example.ldf\")\r\nPS C:\\\u003e $filestructure.Add(\"E:\\archive\\example.ndf\")\r\nPS C:\\\u003e Mount-DbaDatabase -SqlInstance sql2016 -Database example -FileStructure $fileStructure\nAttaches a database named \"example\" to sql2016 with the files \"E:\\archive\\example.mdf\", \"E:\\archive\\example.ldf\" and \"E:\\archive\\example.ndf\". The database owner will be set to sa and the attach \r\noption is None.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eMount-DbaDatabase -SqlInstance sql2016 -Database example\nSince the FileStructure was not provided, this command will attempt to determine it based on backup history. If found, a database named example will be attached to sql2016.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eMount-DbaDatabase -SqlInstance sql2016 -Database example -WhatIf\nShows what would happen if the command were executed (without actually performing the command)",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to attach.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "FileStructure",
                           "A StringCollection object value that contains a list database files. If FileStructure is not specified, BackupHistory will be used to guess the structure.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DatabaseOwner",
                           "Sets the database owner for the database. The sa account (or equivalent) will be used if DatabaseOwner is not specified.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AttachOption",
                           "An AttachOptions object value that contains the attachment options. Valid options are \"None\", \"RebuildLog\", \"EnableBroker\", \"NewBroker\" and \"ErrorBrokerConversations\".",
                           "",
                           false,
                           "false",
                           "None"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Mount-DbaDatabase [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Database] \u003cString[]\u003e [[-FileStructure] \u003cStringCollection\u003e] [[-DatabaseOwner] \u003cString\u003e] [[-AttachOption] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Move-DbaCmsRegServer",
        "Description":  "Moves registered servers around SQL Server Central Management Server (CMS)",
        "Tags":  [
                     "RegisteredServer",
                     "CMS"
                 ],
        "Synopsis":  "Moves registered servers around SQL Server Central Management Server (CMS)",
        "Alias":  "Move-DbaRegisteredServer",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Move-DbaCmsRegServer",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Move-DbaCmsRegServer",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eMove-DbaCmsRegServer -SqlInstance sql2012 -Name \u0027Web SQL Cluster\u0027 -NewGroup HR\\Prod\nMoves the registered server on sql2012 titled \u0027Web SQL Cluster\u0027 to the Prod group within the HR group\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sql2017 -Name \u0027Web SQL Cluster\u0027 | Move-DbaCmsRegServer -NewGroup Web\nMoves the registered server \u0027Web SQL Cluster\u0027 on sql2017 to the Web group, also on sql2017",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "Specifies one or more reg servers to move. Name is the visible name in SSMS CMS interface (labeled Registered Server Name)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ServerName",
                           "Specifies one or more reg servers to move. Server Name is the actual instance name (labeled Server Name)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NewGroup",
                           "The new group. If no new group is specified, the default root will used",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows results from Get-DbaCmsRegServer to be piped in",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Move-DbaCmsRegServer [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString[]\u003e] [[-ServerName] \u003cString[]\u003e] [[-NewGroup] \u003cString\u003e] [[-InputObject] \u003cRegisteredServer[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Move-DbaCmsRegServerGroup",
        "Description":  "Moves registered server groups around SQL Server Central Management Server (CMS).",
        "Tags":  [
                     "RegisteredServer",
                     "CMS"
                 ],
        "Synopsis":  "Moves registered server groups around SQL Server Central Management Server (CMS).",
        "Alias":  "Move-DbaRegisteredServerGroup",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Move-DbaCmsRegServerGroup",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Move-DbaCmsRegServerGroup",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eMove-DbaCmsRegServerGroup -SqlInstance sql2012 -Group HR\\Development -NewGroup AD\\Prod\nMoves the Development group within HR to the Prod group within AD\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServerGroup -SqlInstance sql2017 -Group HR\\Development| Move-DbaCmsRegServer -NewGroup Web\nMoves the Development group within HR to the Web group",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Group",
                           "Specifies one or more groups to include from SQL Server Central Management Server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NewGroup",
                           "The new location.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows results from Get-DbaCmsRegServerGroup to be piped in",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Move-DbaCmsRegServerGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Group] \u003cString[]\u003e] [-NewGroup] \u003cString\u003e [[-InputObject] \u003cServerGroup[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaAgentJob",
        "Description":  "New-DbaAgentJob makes is possible to create a job in the SQL Server Agent.\nIt returns an array of the job(s) created",
        "Tags":  [
                     "Agent",
                     "Job",
                     "JobStep"
                 ],
        "Synopsis":  "New-DbaAgentJob creates a new job",
        "Alias":  "",
        "Author":  "Sander Stad (@sqlstad), sqlstad.nl",
        "CommandName":  "New-DbaAgentJob",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaAgentJob",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaAgentJob -SqlInstance sql1 -Job \u0027Job One\u0027 -Description \u0027Just another job\u0027\nCreates a job with the name \"Job1\" and a small description\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaAgentJob -SqlInstance sql1 -Job \u0027Job One\u0027 -Disabled\nCreates the job but sets it to disabled\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaAgentJob -SqlInstance sql1 -Job \u0027Job One\u0027 -EventLogLevel OnSuccess\nCreates the job and sets the notification to write to the Windows Application event log on success\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eNew-DbaAgentJob -SqlInstance SSTAD-PC -Job \u0027Job One\u0027 -EmailLevel OnFailure -EmailOperator dba\nCreates the job and sets the notification to send an e-mail to the e-mail operator\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eNew-DbaAgentJob -SqlInstance sql1 -Job \u0027Job One\u0027 -Description \u0027Just another job\u0027 -Whatif\nDoesn\u0027t create the job but shows what would happen.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eNew-DbaAgentJob -SqlInstance sql1, sql2, sql3 -Job \u0027Job One\u0027\nCreates a job with the name \"Job One\" on multiple servers\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e\"sql1\", \"sql2\", \"sql3\" | New-DbaAgentJob -Job \u0027Job One\u0027\nCreates a job with the name \"Job One\" on multiple servers using the pipe line",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Job",
                           "The name of the job. The name must be unique and cannot contain the percent (%) character.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Schedule",
                           "Schedule to attach to job. This can be more than one schedule.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ScheduleId",
                           "Schedule ID to attach to job. This can be more than one schedule ID.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Disabled",
                           "Sets the status of the job to disabled. By default a job is enabled.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Description",
                           "The description of the job.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "StartStepId",
                           "The identification number of the first step to execute for the job.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "Category",
                           "The category of the job.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "OwnerLogin",
                           "The name of the login that owns the job.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EventLogLevel",
                           "Specifies when to place an entry in the Microsoft Windows application log for this job.\r\nAllowed values 0, \"Never\", 1, \"OnSuccess\", 2, \"OnFailure\", 3, \"Always\"\r\nThe text value can either be lowercase, uppercase or something in between as long as the text is correct.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EmailLevel",
                           "Specifies when to send an e-mail upon the completion of this job.\r\nAllowed values 0, \"Never\", 1, \"OnSuccess\", 2, \"OnFailure\", 3, \"Always\"\r\nThe text value can either be lowercase, uppercase or something in between as long as the text is correct.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "PageLevel",
                           "Specifies when to send a page upon the completion of this job.\r\nAllowed values 0, \"Never\", 1, \"OnSuccess\", 2, \"OnFailure\", 3, \"Always\"\r\nThe text value can either be lowercase, uppercase or something in between as long as the text is correct.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EmailOperator",
                           "The e-mail name of the operator to whom the e-mail is sent when EmailLevel is reached.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NetsendOperator",
                           "The name of the operator to whom the network message is sent.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "PageOperator",
                           "The name of the operator to whom a page is sent.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DeleteLevel",
                           "Specifies when to delete the job.\r\nAllowed values 0, \"Never\", 1, \"OnSuccess\", 2, \"OnFailure\", 3, \"Always\"\r\nThe text value can either be lowercase, uppercase or something in between as long as the text is correct.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "The force parameter will ignore some errors in the parameters and assume defaults.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaAgentJob [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Job] \u003cString\u003e [[-Schedule] \u003cObject[]\u003e] [[-ScheduleId] \u003cInt32[]\u003e] [-Disabled] [[-Description] \u003cString\u003e] [[-StartStepId] \u003cInt32\u003e] [[-Category] \u003cString\u003e] [[-OwnerLogin] \u003cString\u003e] [[-EventLogLevel] \u003cObject\u003e] [[-EmailLevel] \u003cObject\u003e] [[-PageLevel] \u003cObject\u003e] [[-EmailOperator] \u003cString\u003e] [[-NetsendOperator] \u003cString\u003e] [[-PageOperator] \u003cString\u003e] [[-DeleteLevel] \u003cObject\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaAgentJobCategory",
        "Description":  "New-DbaAgentJobCategory makes it possible to create a job category that can be used with jobs.\nIt returns an array of the job(s) created .",
        "Tags":  [
                     "Agent",
                     "Job",
                     "JobCategory"
                 ],
        "Synopsis":  "New-DbaAgentJobCategory creates a new job category.",
        "Alias":  "",
        "Author":  "Sander Stad (@sqlstad), sqlstad.nl",
        "CommandName":  "New-DbaAgentJobCategory",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaAgentJobCategory",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaAgentJobCategory -SqlInstance sql1 -Category \u0027Category 1\u0027\nCreates a new job category with the name \u0027Category 1\u0027.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaAgentJobCategory -SqlInstance sql1 -Category \u0027Category 2\u0027 -CategoryType MultiServerJob\nCreates a new job category with the name \u0027Category 2\u0027 and assign the category type for a multi server job.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Category",
                           "The name of the category",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "CategoryType",
                           "The type of category. This can be \"LocalJob\", \"MultiServerJob\" or \"None\".\r\nThe default is \"LocalJob\" and will automatically be set when no option is chosen.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "The force parameter will ignore some errors in the parameters and assume defaults.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaAgentJobCategory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Category] \u003cString[]\u003e [[-CategoryType] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaAgentJobStep",
        "Description":  "New-DbaAgentJobStep creates a new job in the SQL Server Agent for a specific job",
        "Tags":  [
                     "Agent",
                     "Job",
                     "JobStep"
                 ],
        "Synopsis":  "New-DbaAgentJobStep creates a new job step for a job",
        "Alias":  "",
        "Author":  "Sander Stad (@sqlstad), sqlstad.nl",
        "CommandName":  "New-DbaAgentJobStep",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaAgentJobStep",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaAgentJobStep -SqlInstance sql1 -Job Job1 -StepName Step1\nCreate a step in \"Job1\" with the name Step1 with the default subsystem TransactSql.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaAgentJobStep -SqlInstance sql1 -Job Job1 -StepName Step1 -Database msdb\nCreate a step in \"Job1\" with the name Step1 where the database will the msdb\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaAgentJobStep -SqlInstance sql1, sql2, sql3 -Job Job1 -StepName Step1 -Database msdb\nCreate a step in \"Job1\" with the name Step1 where the database will the \"msdb\" for multiple servers\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eNew-DbaAgentJobStep -SqlInstance sql1, sql2, sql3 -Job Job1, Job2, \u0027Job Three\u0027 -StepName Step1 -Database msdb\nCreate a step in \"Job1\" with the name Step1 where the database will the \"msdb\" for multiple servers for multiple jobs\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003esql1, sql2, sql3 | New-DbaAgentJobStep -Job Job1 -StepName Step1 -Database msdb\nCreate a step in \"Job1\" with the name Step1 where the database will the \"msdb\" for multiple servers using pipeline",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Job",
                           "The name of the job to which to add the step.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "StepId",
                           "The sequence identification number for the job step. Step identification numbers start at 1 and increment without gaps.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "StepName",
                           "The name of the step.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Subsystem",
                           "The subsystem used by the SQL Server Agent service to execute command.\r\nAllowed values \u0027ActiveScripting\u0027,\u0027AnalysisCommand\u0027,\u0027AnalysisQuery\u0027,\u0027CmdExec\u0027,\u0027Distribution\u0027,\u0027LogReader\u0027,\u0027Merge\u0027,\u0027PowerShell\u0027,\u0027QueueReader\u0027,\u0027Snapshot\u0027,\u0027Ssis\u0027,\u0027TransactSql\u0027\r\nThe default is \u0027TransactSql\u0027",
                           "",
                           false,
                           "false",
                           "TransactSql"
                       ],
                       [
                           "SubsystemServer",
                           "The subsystems AnalysisScripting, AnalysisCommand, AnalysisQuery ned the server property to be able to apply",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Command",
                           "The commands to be executed by SQLServerAgent service through subsystem.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CmdExecSuccessCode",
                           "The value returned by a CmdExec subsystem command to indicate that command executed successfully.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "OnSuccessAction",
                           "The action to perform if the step succeeds.\r\nAllowed values  \"QuitWithSuccess\" (default), \"QuitWithFailure\", \"GoToNextStep\", \"GoToStep\".\r\nThe text value van either be lowercase, uppercase or something in between as long as the text is correct.",
                           "",
                           false,
                           "false",
                           "QuitWithSuccess"
                       ],
                       [
                           "OnSuccessStepId",
                           "The ID of the step in this job to execute if the step succeeds and OnSuccessAction is \"GoToStep\".",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "OnFailAction",
                           "The action to perform if the step fails.\r\nAllowed values  \"QuitWithSuccess\" (default), \"QuitWithFailure\", \"GoToNextStep\", \"GoToStep\".\r\nThe text value van either be lowercase, uppercase or something in between as long as the text is correct.",
                           "",
                           false,
                           "false",
                           "QuitWithFailure"
                       ],
                       [
                           "OnFailStepId",
                           "The ID of the step in this job to execute if the step fails and OnFailAction is \"GoToStep\".",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "Database",
                           "The name of the database in which to execute a Transact-SQL step. The default is \u0027master\u0027.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DatabaseUser",
                           "The name of the user account to use when executing a Transact-SQL step.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RetryAttempts",
                           "The number of retry attempts to use if this step fails. The default is 0.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "RetryInterval",
                           "The amount of time in minutes between retry attempts. The default is 0.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "OutputFileName",
                           "The name of the file in which the output of this step is saved.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Flag",
                           "Sets the flag(s) for the job step.\nFlag                                    Description\r\n----------------------------------------------------------------------------\r\nAppendAllCmdExecOutputToJobHistory      Job history, including command output, is appended to the job history file.\r\nAppendToJobHistory                      Job history is appended to the job history file.\r\nAppendToLogFile                         Job history is appended to the SQL Server log file.\r\nAppendToTableLog                        Job history is appended to a log table.\r\nLogToTableWithOverwrite                 Job history is written to a log table, overwriting previous contents.\r\nNone                                    Job history is not appended to a file.\r\nProvideStopProcessEvent                 Job processing is stopped.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ProxyName",
                           "The name of the proxy that the job step runs as.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "The force parameter will ignore some errors in the parameters and assume defaults.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaAgentJobStep [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Job] \u003cObject[]\u003e [[-StepId] \u003cInt32\u003e] [-StepName] \u003cString\u003e [[-Subsystem] \u003cString\u003e] [[-SubsystemServer] \u003cString\u003e] [[-Command] \u003cString\u003e] [[-CmdExecSuccessCode] \u003cInt32\u003e] [[-OnSuccessAction] \u003cString\u003e] [[-OnSuccessStepId] \u003cInt32\u003e] [[-OnFailAction] \u003cString\u003e] [[-OnFailStepId] \u003cInt32\u003e] [[-Database] \u003cObject\u003e] [[-DatabaseUser] \u003cString\u003e] [[-RetryAttempts] \u003cInt32\u003e] [[-RetryInterval] \u003cInt32\u003e] [[-OutputFileName] \u003cString\u003e] [[-Flag] \u003cString[]\u003e] [[-ProxyName] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] \r\n[\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaAgentProxy",
        "Description":  "Adds one or more proxies to SQL Server Agent",
        "Tags":  [
                     "Agent",
                     "Proxy"
                 ],
        "Synopsis":  "Adds one or more proxies to SQL Server Agent",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "New-DbaAgentProxy",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaAgentProxy",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaAgentProxy -SqlInstance sql2016 -Name STIG -ProxyCredential \u0027PowerShell Proxy\u0027\nCreates an Agent Proxy on sql2016 with the name STIG with the \u0027PowerShell Proxy\u0027 credential.\r\nThe proxy is automatically added to the CmdExec subsystem.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaAgentProxy -SqlInstance localhost\\sql2016 -Name STIG -ProxyCredential \u0027PowerShell Proxy\u0027 -Description \"Used for auditing purposes\" -Login ad\\sqlstig -SubSystem CmdExec, PowerShell \r\n-ServerRole securtyadmin -MsdbRole ServerGroupAdministratorRole\nCreates an Agent Proxy on sql2016 with the name STIG with the \u0027PowerShell Proxy\u0027 credential and the following principals:\nLogin: ad\\sqlstig\r\nServerRole: securtyadmin\r\nMsdbRole: ServerGroupAdministratorRole\nBy default, only sysadmins have access to create job steps with proxies. This will allow 3 additional principals access:\r\nThe proxy is then added to the CmdExec and PowerShell subsystems",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "The name of the proxy or proxies you want to create",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "ProxyCredential",
                           "The associated SQL Server Credential. The credential must be created prior to creating the Proxy.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SubSystem",
                           "The associated subsystem or subsystems. Defaults to CmdExec.\nValid options include:\r\nActiveScripting\r\nAnalysisCommand\r\nAnalysisQuery\r\nCmdExec\r\nDistribution\r\nLogReader\r\nMerge\r\nPowerShell\r\nQueueReader\r\nSnapshot\r\nSsis\r\nTransactSql",
                           "",
                           false,
                           "false",
                           "CmdExec"
                       ],
                       [
                           "Description",
                           "A description of the proxy",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Login",
                           "The SQL Server login or logins (known as proxy principals) to assign to the proxy",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ServerRole",
                           "The SQL Server role or roles (known as proxy principals) to assign to the proxy",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "MsdbRole",
                           "The msdb role or roles (known as proxy principals) to assign to the proxy",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Disabled",
                           "Create the proxy as disabled",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "Drop and recreate the proxy if it already exists",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaAgentProxy [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Name] \u003cString[]\u003e [-ProxyCredential] \u003cString[]\u003e [[-SubSystem] \u003cString[]\u003e] [[-Description] \u003cString\u003e] [[-Login] \u003cString[]\u003e] [[-ServerRole] \u003cString[]\u003e] [[-MsdbRole] \u003cString[]\u003e] [-Disabled] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaAgentSchedule",
        "Description":  "New-DbaAgentSchedule will help create a new schedule for a job.\nIf the job parameter is not supplied the schedule will not be attached to a job.",
        "Tags":  [
                     "Agent",
                     "Job",
                     "JobStep"
                 ],
        "Synopsis":  "New-DbaAgentSchedule creates a new schedule in the msdb database.",
        "Alias":  "",
        "Author":  "Sander Stad (@sqlstad), sqlstad.nl",
        "CommandName":  "New-DbaAgentSchedule",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaAgentSchedule",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaAgentSchedule -SqlInstance localhost\\SQL2016 -Schedule daily -FrequencyType Daily -FrequencyInterval Everyday -Force\nCreates a schedule with a daily frequency every day. It assumes default values for the start date, start time, end date and end time due to -Force.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaAgentSchedule -SqlInstance sstad-pc -Schedule MonthlyTest -FrequencyType Monthly -FrequencyInterval 10 -FrequencyRecurrenceFactor 1 -Force\nCreate a schedule with a monhtly frequency occuring every 10th of the month. It assumes default values for the start date, start time, end date and end time due to -Force.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Job",
                           "The name of the job that has the schedule.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Schedule",
                           "The name of the schedule.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Disabled",
                           "Set the schedule to disabled. Default is enabled",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "FrequencyType",
                           "A value indicating when a job is to be executed.\nAllowed values: Once, Daily, Weekly, Monthly, MonthlyRelative, AgentStart or IdleComputer\nIf force is used the default will be \"Once\".",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "FrequencyInterval",
                           "The days that a job is executed\nAllowed values: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Weekdays, Weekend or EveryDay.\r\nThe other allowed values are the numbers 1 to 31 for each day of the month.\nIf \"Weekdays\", \"Weekend\" or \"EveryDay\" is used it over writes any other value that has been passed before.\nIf force is used the default will be 1.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "FrequencySubdayType",
                           "Specifies the units for the subday FrequencyInterval.\nAllowed values: Time, Seconds, Minutes, or Hours",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "FrequencySubdayInterval",
                           "The number of subday type periods to occur between each execution of a job.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "FrequencyRelativeInterval",
                           "A job\u0027s occurrence of FrequencyInterval in each month, if FrequencyInterval is 32 (monthlyrelative).\nAllowed values: First, Second, Third, Fourth or Last",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "FrequencyRecurrenceFactor",
                           "The number of weeks or months between the scheduled execution of a job.\nFrequencyRecurrenceFactor is used only if FrequencyType is \"Weekly\", \"Monthly\" or \"MonthlyRelative\".",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "StartDate",
                           "The date on which execution of a job can begin.\nIf force is used the start date will be the current day",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EndDate",
                           "The date on which execution of a job can stop.\nIf force is used the end date will be \u00279999-12-31\u0027",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "StartTime",
                           "The time on any day to begin execution of a job. Format HHMMSS / 24 hour clock.\r\nExample: \u0027010000\u0027 for 01:00:00 AM.\r\nExample: \u0027140000\u0027 for 02:00:00 PM.\nIf force is used the start time will be \u002700:00:00\u0027",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EndTime",
                           "The time on any day to end execution of a job. Format HHMMSS / 24 hour clock.\r\nExample: \u0027010000\u0027 for 01:00:00 AM.\r\nExample: \u0027140000\u0027 for 02:00:00 PM.\nIf force is used the start time will be \u002723:59:59\u0027",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "The force parameter will ignore some errors in the parameters and assume defaults.\r\nIt will also remove the any present schedules with the same name for the specific job.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaAgentSchedule [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Job] \u003cObject[]\u003e] [[-Schedule] \u003cObject\u003e] [-Disabled] [[-FrequencyType] \u003cObject\u003e] [[-FrequencyInterval] \u003cObject[]\u003e] [[-FrequencySubdayType] \u003cObject\u003e] [[-FrequencySubdayInterval] \u003cInt32\u003e] [[-FrequencyRelativeInterval] \u003cObject\u003e] [[-FrequencyRecurrenceFactor] \u003cInt32\u003e] [[-StartDate] \u003cString\u003e] [[-EndDate] \u003cString\u003e] [[-StartTime] \u003cString\u003e] [[-EndTime] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaAvailabilityGroup",
        "Description":  "Automates the creation of availability groups.\n\n* Checks prerequisites\n* Creates Availability Group and adds primary replica\n* Grants cluster permissions if necessary\n* Adds secondary replica if supplied\n* Adds databases if supplied\n* Performs backup/restore if seeding mode is manual\n* Performs backup to NUL if seeding mode is automatic\n* Adds listener to primary if supplied\n* Joins secondaries to availability group\n* Grants endpoint connect permissions to service accounts\n* Grants CreateAnyDatabase permissions if seeding mode is automatic\n* Returns Availability Group object from primary\n\nNOTE: If a backup / restore is performed, the backups will be left intact on the network share.\n\nThanks for this, Thomas Stringer! https://blogs.technet.microsoft.com/heyscriptingguy/2013/04/29/set-up-an-alwayson-availability-group-with-powershell/",
        "Tags":  "HA",
        "Synopsis":  "Automates the creation of availability groups.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "New-DbaAvailabilityGroup",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaAvailabilityGroup",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaAvailabilityGroup -Primary sql2016a -Name SharePoint\nCreates a new availability group on sql2016a named SharePoint\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaAvailabilityGroup -Primary sql2016a -Name SharePoint -Secondary sql2016b\nCreates a new availability group on sql2016a named SharePoint with a secondary replica, sql2016b\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaAvailabilityGroup -Primary sql2016std -Name BAG1 -Basic -Confirm:$false\nCreates a basic availability group named BAG1 on sql2016std and does not confirm when setting up\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eNew-DbaAvailabilityGroup -Primary sql2016b -Name AG1 -ClusterType Wsfc -Dhcp -Database db1 -UseLastBackup\nCreates an availability group on sql2016b with the name ag1. Uses the last backups available to add the database db1 to the AG.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eNew-DbaAvailabilityGroup -Primary sql2017 -Name SharePoint -ClusterType None -FailoverMode Manual\nCreates a new availability group on sql2017 named SharePoint with a cluster type of none and a failover mode of manual\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eNew-DbaAvailabilityGroup -Primary sql1 -Secondary sql2 -Name ag1 -Database pubs -ClusterType None -SeedingMode Automatic -FailoverMode Manual\nCreates a new availability group with a primary replica on sql1 and a secondary on sql2. Automatically adds the database pubs.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e $params = @{\r\n\u003e\u003e Primary = \"sql1\"\r\n\u003e\u003e PrimarySqlCredential = $cred\r\n\u003e\u003e Secondary = \"sql2\"\r\n\u003e\u003e SecondarySqlCredential = $cred\r\n\u003e\u003e Name = \"test-ag\"\r\n\u003e\u003e Database = \"pubs\"\r\n\u003e\u003e ClusterType = \"None\"\r\n\u003e\u003e SeedingMode = \"Automatic\"\r\n\u003e\u003e FailoverMode = \"Manual\"\r\n\u003e\u003e Confirm = $false\r\n\u003e\u003e }\r\nPS C:\\\u003e New-DbaAvailabilityGroup @params\nThis exact command was used to create an availability group on docker!",
        "Params":  [
                       [
                           "Primary",
                           "The primary SQL Server instance. Server version must be SQL Server version 2012 or higher.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "PrimarySqlCredential",
                           "Login to the primary instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Secondary",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SecondarySqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "The name of the Availability Group.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DtcSupport",
                           "Indicates whether the DtcSupport is enabled",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ClusterType",
                           "Cluster type of the Availability Group. Only supported in SQL Server 2017 and above.\r\nOptions include: External, Wsfc or None. None by default.",
                           "",
                           false,
                           "false",
                           "External"
                       ],
                       [
                           "AutomatedBackupPreference",
                           "Specifies how replicas in the primary role are treated in the evaluation to pick the desired replica to perform a backup.",
                           "",
                           false,
                           "false",
                           "Secondary"
                       ],
                       [
                           "FailureConditionLevel",
                           "Specifies the different conditions that can trigger an automatic failover in Availability Group.",
                           "",
                           false,
                           "false",
                           "OnServerDown"
                       ],
                       [
                           "HealthCheckTimeout",
                           "This setting used to specify the length of time, in milliseconds, that the SQL Server resource DLL should wait for information returned by the sp_server_diagnostics stored procedure before reporting \r\nthe Always On Failover Cluster Instance (FCI) as unresponsive.\nChanges that are made to the timeout settings are effective immediately and do not require a restart of the SQL Server resource.\nDefaults to 30000 (30 seconds).",
                           "",
                           false,
                           "false",
                           "30000"
                       ],
                       [
                           "Basic",
                           "Indicates whether the availability group is basic. Basic availability groups like pumpkin spice and uggs.\nhttps://docs.microsoft.com/en-us/sql/database-engine/availability-groups/windows/basic-availability-groups-always-on-availability-groups",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DatabaseHealthTrigger",
                           "Indicates whether the availability group triggers the database health.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Passthru",
                           "Don\u0027t create the availability group, just pass thru an object that can be further customized before creation.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Database",
                           "The database or databases to add.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SharedPath",
                           "The network share where the backups will be backed up and restored from.\nEach SQL Server service account must have access to this share.\nNOTE: If a backup / restore is performed, the backups will be left in tact on the network share.",
                           "NetworkShare",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "UseLastBackup",
                           "Use the last full backup of database.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "Drop and recreate the database on remote servers using fresh backup.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "AvailabilityMode",
                           "Sets the availability mode of the availability group replica. Options are: AsynchronousCommit and SynchronousCommit. SynchronousCommit is default.",
                           "",
                           false,
                           "false",
                           "SynchronousCommit"
                       ],
                       [
                           "FailoverMode",
                           "Sets the failover mode of the availability group replica. Options are Automatic, Manual and External. Automatic is default.",
                           "",
                           false,
                           "false",
                           "Automatic"
                       ],
                       [
                           "BackupPriority",
                           "Sets the backup priority availability group replica. Default is 50.",
                           "",
                           false,
                           "false",
                           "50"
                       ],
                       [
                           "ConnectionModeInPrimaryRole",
                           "Specifies the connection intent modes of an Availability Replica in primary role. AllowAllConnections by default.",
                           "",
                           false,
                           "false",
                           "AllowAllConnections"
                       ],
                       [
                           "ConnectionModeInSecondaryRole",
                           "Specifies the connection modes of an Availability Replica in secondary role. AllowAllConnections by default.",
                           "",
                           false,
                           "false",
                           "AllowAllConnections"
                       ],
                       [
                           "SeedingMode",
                           "Specifies how the secondary replica will be initially seeded.\nAutomatic enables direct seeding. This method will seed the secondary replica over the network. This method does not require you to backup and restore a copy of the primary database on the replica.\nManual requires you to create a backup of the database on the primary replica and manually restore that backup on the secondary replica.",
                           "",
                           false,
                           "false",
                           "Manual"
                       ],
                       [
                           "Endpoint",
                           "By default, this command will attempt to find a DatabaseMirror endpoint. If one does not exist, it will create it.\nIf an endpoint must be created, the name \"hadr_endpoint\" will be used. If an alternative is preferred, use Endpoint.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ReadonlyRoutingConnectionUrl",
                           "Sets the read only routing connection url for the availability replica.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Certificate",
                           "Specifies that the endpoint is to authenticate the connection using the certificate specified by certificate_name to establish identity for authorization.\nThe far endpoint must have a certificate with the public key matching the private key of the specified certificate.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IPAddress",
                           "Sets the IP address of the availability group listener.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SubnetMask",
                           "Sets the subnet IP mask of the availability group listener.",
                           "",
                           false,
                           "false",
                           "255.255.255.0"
                       ],
                       [
                           "Port",
                           "Sets the number of the port used to communicate with the availability group.",
                           "",
                           false,
                           "false",
                           "1433"
                       ],
                       [
                           "Dhcp",
                           "Indicates whether the object is DHCP.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaAvailabilityGroup [[-Primary] \u003cDbaInstanceParameter\u003e] [[-PrimarySqlCredential] \u003cPSCredential\u003e] [[-Secondary] \u003cDbaInstanceParameter[]\u003e] [[-SecondarySqlCredential] \u003cPSCredential\u003e] [-Name] \u003cString\u003e [-DtcSupport] [[-ClusterType] \u003cString\u003e] [[-AutomatedBackupPreference] \u003cString\u003e] [[-FailureConditionLevel] \u003cString\u003e] [[-HealthCheckTimeout] \u003cInt32\u003e] [-Basic] [-DatabaseHealthTrigger] [-Passthru] [[-Database] \u003cString[]\u003e] [[-SharedPath] \u003cString\u003e] [-UseLastBackup] [-Force] [[-AvailabilityMode] \u003cString\u003e] [[-FailoverMode] \u003cString\u003e] [[-BackupPriority] \u003cInt32\u003e] [[-ConnectionModeInPrimaryRole] \u003cString\u003e] \r\n[[-ConnectionModeInSecondaryRole] \u003cString\u003e] [[-SeedingMode] \u003cString\u003e] [[-Endpoint] \u003cString\u003e] [[-ReadonlyRoutingConnectionUrl] \u003cString\u003e] [[-Certificate] \u003cString\u003e] [[-IPAddress] \u003cIPAddress[]\u003e] [[-SubnetMask] \u003cIPAddress\u003e] [[-Port] \u003cInt32\u003e] [-Dhcp] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaClientAlias",
        "Description":  "Creates/updates a SQL Server alias by altering HKLM:\\SOFTWARE\\Microsoft\\MSSQLServer\\Client",
        "Tags":  "Alias",
        "Synopsis":  "Creates/updates a sql alias for the specified server - mimics cliconfg.exe",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "New-DbaClientAlias",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/New-DbaClientAlias",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaClientAlias -ServerName sqlcluster\\sharepoint -Alias sp\nCreates a new TCP alias on the local workstation called sp, which points sqlcluster\\sharepoint\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaClientAlias -ServerName \u0027sqlcluster,14443\u0027 -Alias spinstance\nCreates a new TCP alias on the local workstation called spinstance, which points to sqlcluster, port 14443.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaClientAlias -ServerName sqlcluster\\sharepoint -Alias sp -Protocol NamedPipes\nCreates a new NamedPipes alias on the local workstation called sp, which points sqlcluster\\sharepoint",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer where the alias will be created",
                           "",
                           false,
                           "false",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to remote computers using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ServerName",
                           "The target SQL Server",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Alias",
                           "The alias to be created",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Protocol",
                           "The protocol for the connection, either TCPIP or NetBIOS. Defaults to TCPIP.",
                           "",
                           false,
                           "false",
                           "TCPIP"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaClientAlias [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-ServerName] \u003cDbaInstanceParameter[]\u003e [-Alias] \u003cString\u003e [[-Protocol] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaCmConnection",
        "Description":  "Generates a connection object for use in remote computer management.\nThose objects are used for the purpose of cim/wmi queries, caching which protocol worked, optimizing performance and minimizing authentication errors.\n\nNew-DbaCmConnection will create a NEW object and overwrite any existing ones for the specified computer.\nFurthermore, information stored in the input beyond the computername will be discarded in favor of the new settings.\n\nUnless the connection cache has been disabled, all connections will automatically be registered in the cache, so no further action is necessary.\nThe output is primarily for information purposes, however it may be used to pass objects and circumvent the cache with those.\n\nNOTE: Generally, this function need not be used, as a first connection to a computer using any connecting function such as \"Get-DbaCmObject\" will automatically register a new default connection for it.\n\nThis function exists to be able to preconfigure connections.",
        "Tags":  [
                     "ComputerManagement",
                     "CIM"
                 ],
        "Synopsis":  "Generates a connection object for use in remote computer management.",
        "Alias":  "",
        "CommandName":  "New-DbaCmConnection",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/New-DbaCmConnection",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaCmConnection -ComputerName sql2014 -UseWindowsCredentials -OverrideExplicitCredential -DisabledConnectionTypes CimRM\nReturns a new configuration object for connecting to the computer sql2014.\r\n- The current user credentials are set as valid\r\n- The connection is configured to ignore explicit credentials (so all connections use the windows credentials)\r\n- The connections will not try using CIM over WinRM\nUnless caching is globally disabled, this is automatically stored in the connection cache and will be applied automatically.\r\nIn that (the default) case, the output is for information purposes only and need not be used.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-Content computers.txt | New-DbaCmConnection -Credential $cred -CimWinRMOptions $options -DisableBadCredentialCache -OverrideExplicitCredential\nGathers a list of computers from a text file, then creates and registers connections for each of them, setting them to ...\r\n- use the credentials stored in $cred\r\n- use the options stored in $options when connecting using CIM over WinRM\r\n- not store credentials that are known to not work\r\n- to ignore explicitly specified credentials\nEssentially, this configures all connections to those computers to prefer failure with the specified credentials over using alternative credentials.",
        "Params":  [
                       [
                           "ComputerName",
                           "The computer to build the connection object for.",
                           "",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "The credential to register.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "UseWindowsCredentials",
                           "Whether using the default windows credentials is legit.\r\nNot setting this will not exclude using windows credentials, but only not pre-confirm them as working.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "OverrideExplicitCredential",
                           "Setting this will enable the credential override.\r\nThe override will cause the system to ignore explicitly specified credentials, so long as known, good credentials are available.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DisabledConnectionTypes",
                           "Exlicitly disable connection types.\r\nThese types will then not be used for connecting to the computer.",
                           "",
                           false,
                           "false",
                           "None"
                       ],
                       [
                           "DisableBadCredentialCache",
                           "Will prevent the caching of credentials if set to true.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DisableCimPersistence",
                           "Will prevent Cim-Sessions to be reused.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DisableCredentialAutoRegister",
                           "Will prevent working credentials from being automatically cached",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableCredentialFailover",
                           "Will enable automatic failing over to known to work credentials, when using bad credentials.\r\nBy default, passing bad credentials will cause the Computer Management functions to interrupt with a warning (Or exception if in silent mode).",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WindowsCredentialsAreBad",
                           "Will prevent the windows credentials of the currently logged on user from being used for the remote connection.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "CimWinRMOptions",
                           "Specify a set of options to use when connecting to the target computer using CIM over WinRM.\r\nUse \u0027New-CimSessionOption\u0027 to create such an object.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CimDCOMOptions",
                           "Specify a set of options to use when connecting to the target computer using CIM over DCOM.\r\nUse \u0027New-CimSessionOption\u0027 to create such an object.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaCmConnection [-ComputerName \u003cDbaCmConnectionParameter[]\u003e] [-Credential \u003cPSCredential\u003e] [-OverrideExplicitCredential] [-DisabledConnectionTypes {None | CimRM | CimDCOM | Wmi | PowerShellRemoting}] [-DisableBadCredentialCache] [-DisableCimPersistence] [-DisableCredentialAutoRegister] [-EnableCredentialFailover] [-WindowsCredentialsAreBad] [-CimWinRMOptions \u003cWSManSessionOptions\u003e] [-CimDCOMOptions \u003cDComSessionOptions\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nNew-DbaCmConnection [-ComputerName \u003cDbaCmConnectionParameter[]\u003e] [-UseWindowsCredentials] [-OverrideExplicitCredential] [-DisabledConnectionTypes {None | CimRM | CimDCOM | Wmi | PowerShellRemoting}] [-DisableBadCredentialCache] [-DisableCimPersistence] [-DisableCredentialAutoRegister] [-EnableCredentialFailover] [-CimWinRMOptions \u003cWSManSessionOptions\u003e] [-CimDCOMOptions \u003cDComSessionOptions\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaComputerCertificate",
        "Description":  "Creates a new computer certificate - self-signed or signed by an Active Directory CA, using the Web Server certificate.\n\nBy default, a key with a length of 1024 and a friendly name of the machines FQDN is generated.\n\nThis command was originally intended to help automate the process so that SSL certificates can be available for enforcing encryption on connections.\n\nIt makes a lot of assumptions - namely, that your account is allowed to auto-enroll and that you have permission to do everything it needs to do ;)\n\nReferences:\nhttp://sqlmag.com/sql-server/7-steps-ssl-encryption\nhttps://azurebi.jppp.org/2016/01/23/using-lets-encrypt-certificates-for-secure-sql-server-connections/\nhttps://blogs.msdn.microsoft.com/sqlserverfaq/2016/09/26/creating-and-registering-ssl-certificates/\n\nThe certificate is generated using AD\u0027s webserver SSL template on the client machine and pushed to the remote machine.",
        "Tags":  "Certificate",
        "Synopsis":  "Creates a new computer certificate useful for Forcing Encryption",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "New-DbaComputerCertificate",
        "Availability":  "Windows only",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaComputerCertificate\nCreates a computer certificate signed by the local domain CA for the local machine with the keylength of 1024.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaComputerCertificate -ComputerName Server1\nCreates a computer certificate signed by the local domain CA _on the local machine_ for server1 with the keylength of 1024.\nThe certificate is then copied to the new machine over WinRM and imported.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaComputerCertificate -ComputerName sqla, sqlb -ClusterInstanceName sqlcluster -KeyLength 4096\nCreates a computer certificate for sqlcluster, signed by the local domain CA, with the keylength of 4096.\nThe certificate is then copied to sqla _and_ sqlb over WinRM and imported.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eNew-DbaComputerCertificate -ComputerName Server1 -WhatIf\nShows what would happen if the command were run\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eNew-DbaComputerCertificate -SelfSigned\nCreates a self-signed certificate",
        "Params":  [
                       [
                           "ComputerName",
                           "The target SQL Server instance or instances. Defaults to localhost. If target is a cluster, you must also specify ClusterInstanceName (see below)",
                           "ServerInstance,SqlServer,SqlInstance",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to $ComputerName using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CaServer",
                           "Optional - the CA Server where the request will be sent to",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CaName",
                           "The properly formatted CA name of the corresponding CaServer",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ClusterInstanceName",
                           "When creating certs for a cluster, use this parameter to create the certificate for the cluster node name. Use ComputerName for each of the nodes.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SecurePassword",
                           "Password to encrypt/decrypt private key for export to remote machine",
                           "Password",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "FriendlyName",
                           "The FriendlyName listed in the certificate. This defaults to the FQDN of the $ComputerName",
                           "",
                           false,
                           "false",
                           "SQL Server"
                       ],
                       [
                           "CertificateTemplate",
                           "The domain\u0027s Certificate Template - WebServer by default.",
                           "",
                           false,
                           "false",
                           "WebServer"
                       ],
                       [
                           "KeyLength",
                           "The length of the key - defaults to 1024",
                           "",
                           false,
                           "false",
                           "1024"
                       ],
                       [
                           "Store",
                           "Certificate store - defaults to LocalMachine",
                           "",
                           false,
                           "false",
                           "LocalMachine"
                       ],
                       [
                           "Folder",
                           "Certificate folder - defaults to My (Personal)",
                           "",
                           false,
                           "false",
                           "My"
                       ],
                       [
                           "Dns",
                           "Specify the Dns entries listed in SAN. By default, it will be ComputerName + FQDN, or in the case of clusters, clustername + cluster FQDN.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SelfSigned",
                           "Creates a self-signed certificate. All other parameters can still apply except CaServer and CaName because the command does not go and get the certificate signed.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaComputerCertificate [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CaServer] \u003cString\u003e] [[-CaName] \u003cString\u003e] [[-ClusterInstanceName] \u003cString\u003e] [[-SecurePassword] \u003cSecureString\u003e] [[-FriendlyName] \u003cString\u003e] [[-CertificateTemplate] \u003cString\u003e] [[-KeyLength] \u003cInt32\u003e] [[-Store] \u003cString\u003e] [[-Folder] \u003cString\u003e] [[-Dns] \u003cString[]\u003e] [-SelfSigned] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaConnectionString",
        "Description":  "Builds or extracts a SQL Server Connection String\n\nSee https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx\nand https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.aspx\nand https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx",
        "Tags":  [
                     "Connection",
                     "Connect",
                     "ConnectionString"
                 ],
        "Synopsis":  "Builds or extracts a SQL Server Connection String",
        "Alias":  "New-DbaSqlConnectionString",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "New-DbaConnectionString",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaConnectionString",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaConnectionString -SqlInstance sql2014\nCreates a connection string that connects using Windows Authentication\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eConnect-DbaInstance -SqlInstance sql2016 | New-DbaConnectionString\nBuilds a connected SMO object using Connect-DbaInstance then extracts and displays the connection string\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$wincred = Get-Credential ad\\sqladmin\nPS C:\\\u003e New-DbaConnectionString -SqlInstance sql2014 -Credential $wincred\nCreates a connection string that connects using alternative Windows credentials\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$sqlcred = Get-Credential sqladmin\nPS C:\\\u003e $server = New-DbaConnectionString -SqlInstance sql2014 -Credential $sqlcred\nLogin to sql2014 as SQL login sqladmin.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$server = New-DbaConnectionString -SqlInstance sql2014 -ClientName \"mah connection\"\nCreates a connection string that connects using Windows Authentication and uses the client name \"mah connection\". So when you open up profiler or use extended events, you can search for \"mah \r\nconnection\".\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$server = New-DbaConnectionString -SqlInstance sql2014 -AppendConnectionString \"Packet Size=4096;AttachDbFilename=C:\\MyFolder\\MyDataFile.mdf;User Instance=true;\"\nCreates a connection string that connects to sql2014 using Windows Authentication, then it sets the packet size (this can also be done via -PacketSize) and other connection attributes.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$server = New-DbaConnectionString -SqlInstance sql2014 -NetworkProtocol TcpIp -MultiSubnetFailover\nCreates a connection string with Windows Authentication that uses TCPIP and has MultiSubnetFailover enabled.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e$connstring = New-DbaConnectionString sql2016 -ApplicationIntent ReadOnly\nCreates a connection string with ReadOnly ApplicationIntent.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Credential",
                           "Credential object used to connect to the SQL Server as a different user be it Windows or SQL Server. Windows users are determined by the existence of a backslash, so if you are intending to use an \r\nalternative Windows connection instead of a SQL login, ensure it contains a backslash.",
                           "SqlCredential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AccessToken",
                           "Gets or sets the access token for the connection.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ApplicationIntent",
                           "Declares the application workload type when connecting to a server. Possible values are ReadOnly and ReadWrite.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "BatchSeparator",
                           "By default, this is \"GO\"",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ClientName",
                           "By default, this command sets the client to \"dbatools PowerShell module - dbatools.io - custom connection\" if you\u0027re doing anything that requires profiling, you can look for this client name. Using \r\n-ClientName allows you to set your own custom client.",
                           "",
                           false,
                           "false",
                           "custom connection"
                       ],
                       [
                           "ConnectTimeout",
                           "The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error.\nValid values are greater than or equal to 0 and less than or equal to 2147483647.\nWhen opening a connection to a Azure SQL Database, set the connection timeout to 30 seconds.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "EncryptConnection",
                           "When true, SQL Server uses SSL encryption for all data sent between the client and server if the server has a certificate installed. Recognized values are true, false, yes, and no. For more \r\ninformation, see Connection String Syntax.\nBeginning in .NET Framework 4.5, when TrustServerCertificate is false and Encrypt is true, the server name (or IP address) in a SQL Server SSL certificate must exactly match the server name (or IP \r\naddress) specified in the connection string. Otherwise, the connection attempt will fail. For information about support for certificates whose subject starts with a wildcard character (*), see \r\nAccepted wildcards used by server certificates for server authentication.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "FailoverPartner",
                           "The name of the failover partner server where database mirroring is configured.\nIf the value of this key is \"\", then Initial Catalog must be present, and its value must not be \"\".\nThe server name can be 128 characters or less.\nIf you specify a failover partner but the failover partner server is not configured for database mirroring and the primary server (specified with the Server keyword) is not available, then the \r\nconnection will fail.\nIf you specify a failover partner and the primary server is not configured for database mirroring, the connection to the primary server (specified with the Server keyword) will succeed if the primary \r\nserver is available.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IsActiveDirectoryUniversalAuth",
                           "Azure related",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "LockTimeout",
                           "Sets the time in seconds required for the connection to time out when the current transaction is locked.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "MaxPoolSize",
                           "Sets the maximum number of connections allowed in the connection pool for this specific connection string.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "MinPoolSize",
                           "Sets the minimum number of connections allowed in the connection pool for this specific connection string.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "MultipleActiveResultSets",
                           "When used, an application can maintain multiple active result sets (MARS). When false, an application must process or cancel all result sets from one batch before it can execute any other batch on \r\nthat connection.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "MultiSubnetFailover",
                           "If your application is connecting to an AlwaysOn availability group (AG) on different subnets, setting MultiSubnetFailover provides faster detection of and connection to the (currently) active \r\nserver. For more information about SqlClient support for Always On Availability Groups",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NetworkProtocol",
                           "Connect explicitly using \u0027TcpIp\u0027,\u0027NamedPipes\u0027,\u0027Multiprotocol\u0027,\u0027AppleTalk\u0027,\u0027BanyanVines\u0027,\u0027Via\u0027,\u0027SharedMemory\u0027 and \u0027NWLinkIpxSpx\u0027",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NonPooledConnection",
                           "Request a non-pooled connection",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "PacketSize",
                           "Sets the size in bytes of the network packets used to communicate with an instance of SQL Server. Must match at server.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "PooledConnectionLifetime",
                           "When a connection is returned to the pool, its creation time is compared with the current time, and the connection is destroyed if that time span (in seconds) exceeds the value specified by \r\nConnection Lifetime. This is useful in clustered configurations to force load balancing between a running server and a server just brought online.\nA value of zero (0) causes pooled connections to have the maximum connection timeout.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "SqlExecutionModes",
                           "The SqlExecutionModes enumeration contains values that are used to specify whether the commands sent to the referenced connection to the server are executed immediately or saved in a buffer.\nValid values include CaptureSql, ExecuteAndCaptureSql and ExecuteSql.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "StatementTimeout",
                           "Sets the number of seconds a statement is given to run before failing with a time-out error.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "TrustServerCertificate",
                           "Sets a value that indicates whether the channel will be encrypted while bypassing walking the certificate chain to validate trust.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WorkstationId",
                           "Sets the name of the workstation connecting to SQL Server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AppendConnectionString",
                           "Appends to the current connection string. Note that you cannot pass authentication information using this method. Use -SqlInstance and, optionally, -SqlCredential to set authentication information.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaConnectionString [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [[-AccessToken] \u003cString\u003e] [[-ApplicationIntent] \u003cString\u003e] [[-BatchSeparator] \u003cString\u003e] [[-ClientName] \u003cString\u003e] [[-ConnectTimeout] \u003cInt32\u003e] [-EncryptConnection] [[-FailoverPartner] \u003cString\u003e] [-IsActiveDirectoryUniversalAuth] [[-LockTimeout] \u003cInt32\u003e] [[-MaxPoolSize] \u003cInt32\u003e] [[-MinPoolSize] \u003cInt32\u003e] [-MultipleActiveResultSets] [-MultiSubnetFailover] [[-NetworkProtocol] \u003cString\u003e] [-NonPooledConnection] [[-PacketSize] \u003cInt32\u003e] [[-PooledConnectionLifetime] \u003cInt32\u003e] [[-SqlExecutionModes] \u003cString\u003e] \r\n[[-StatementTimeout] \u003cInt32\u003e] [-TrustServerCertificate] [[-WorkstationId] \u003cString\u003e] [[-AppendConnectionString] \u003cString\u003e] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaConnectionStringBuilder",
        "Description":  "Creates a System.Data.SqlClient.SqlConnectionStringBuilder from a connection string.",
        "Tags":  [
                     "SqlBuild",
                     "ConnectionString",
                     "Connection"
                 ],
        "Synopsis":  "Returns a System.Data.SqlClient.SqlConnectionStringBuilder with the string specified",
        "Alias":  "New-DbaSqlConnectionStringBuilder",
        "Author":  "zippy1981 | Chrissy LeMaire (@cl)",
        "CommandName":  "New-DbaConnectionStringBuilder",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaConnectionStringBuilder",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaConnectionStringBuilder\nReturns an empty ConnectionStringBuilder\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\"Data Source=localhost,1433;Initial Catalog=AlwaysEncryptedSample;UID=sa;PWD=alwaysB3Encrypt1ng;Application Name=Always Encrypted Sample MVC App;Column Encryption Setting=enabled\" | \r\nNew-DbaConnectionStringBuilder\nReturns a connection string builder that can be used to connect to the local sql server instance on the default port.",
        "Params":  [
                       [
                           "ConnectionString",
                           "A Connection String",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "ApplicationName",
                           "The application name to tell SQL Server the connection is associated with.",
                           "",
                           false,
                           "false",
                           "dbatools Powershell Module"
                       ],
                       [
                           "DataSource",
                           "The Sql Server to connect to.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InitialCatalog",
                           "The initial database on the server to connect to.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IntegratedSecurity",
                           "Set to true to use windows authentication.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "UserName",
                           "Sql User Name to connect with.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Password",
                           "Password to use to connect with.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "MultipleActiveResultSets",
                           "Enable Multiple Active Result Sets.",
                           "MARS",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ColumnEncryptionSetting",
                           "Enable Always Encrypted.",
                           "AlwaysEncrypted",
                           false,
                           "false",
                           "Enabled"
                       ],
                       [
                           "WorkstationId",
                           "Set the Workstation Id that is associated with the connection.",
                           "",
                           false,
                           "false",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaConnectionStringBuilder [[-ConnectionString] \u003cString[]\u003e] [[-ApplicationName] \u003cString\u003e] [[-DataSource] \u003cString\u003e] [[-InitialCatalog] \u003cString\u003e] [[-IntegratedSecurity] \u003cNullable`1\u003e] [[-UserName] \u003cString\u003e] [[-Password] \u003cString\u003e] [-MultipleActiveResultSets] [[-ColumnEncryptionSetting] {Disabled | Enabled}] [[-WorkstationId] \u003cString\u003e] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaCredential",
        "Description":  "Creates a new credential",
        "Tags":  "Certificate",
        "Synopsis":  "Creates a new SQL Server credential",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "New-DbaCredential",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaCredential -SqlInstance Server1\nYou will be prompted to securely enter your password, then a credential will be created in the master database on server1 if it does not exist.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaCredential -SqlInstance Server1 -Confirm:$false\nSuppresses all prompts to install but prompts to securely enter your password and creates a credential on Server1.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaCredential -SqlInstance Server1 -Name AzureBackupBlobStore -Identity \u0027\u003cAzure Storage Account Name\u003e\u0027 -SecurePassword (ConvertTo-SecureString \u0027\u003cAzure Storage Account Access Key\u003e\u0027 \r\n-AsPlainText -Force)\nCreate credential on SQL Server 2012 CU2, SQL Server 2014 for use with BACKUP TO URL.\r\nCredentialIdentity needs to be supplied with the Azure Storage Account Name.\r\nPassword needs to be one of the Access Keys for the account.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eNew-DbaCredential -SqlInstance Server1 -Name \u0027https://\u003cAzure Storage Account Name\u003e.blob.core.windows.net/\u003cBlob Store Container Name\u003e\u0027 -Identity \u0027SHARED ACCESS SIGNATURE\u0027 -SecurePassword \r\n(ConvertTo-SecureString \u0027\u003cShared Access Token\u003e\u0027 -AsPlainText -Force)\nCreate Credential on SQL Server 2016 or higher for use with BACKUP TO URL.\r\nName has to be the full URL for the blob store container that will be the backup target.\r\nPassword needs to be passed the Shared Access Token (SAS Key).",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server(s)",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to SQL Server using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "The Credential name",
                           "",
                           false,
                           "false",
                           "$Identity"
                       ],
                       [
                           "Identity",
                           "The Credential Identity",
                           "CredentialIdentity",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SecurePassword",
                           "Secure string used to authenticate the Credential Identity",
                           "Password",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "MappedClassType",
                           "Sets the class associated with the credential.",
                           "",
                           false,
                           "false",
                           "None"
                       ],
                       [
                           "ProviderName",
                           "Sets the name of the provider",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If credential exists, drop and recreate",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaCredential [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cObject[]\u003e] [-Identity] \u003cString[]\u003e [[-SecurePassword] \u003cSecureString\u003e] [[-MappedClassType] \u003cString\u003e] [[-ProviderName] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaDacOption",
        "Description":  "Creates a new Microsoft.SqlServer.Dac.DacExtractOptions/DacExportOptions object that can be used during DacPackage extract. Basically saves you the time from remembering the SMO assembly name ;)\n\nSee:\nhttps://msdn.microsoft.com/en-us/library/microsoft.sqlserver.dac.dacexportoptions.aspx\nhttps://msdn.microsoft.com/en-us/library/microsoft.sqlserver.dac.dacextractoptions.aspx\nfor more information",
        "Tags":  [
                     "Migration",
                     "Database",
                     "Dacpac"
                 ],
        "Synopsis":  "Creates a new Microsoft.SqlServer.Dac.DacExtractOptions/DacExportOptions object depending on the chosen Type",
        "Alias":  "",
        "Author":  "Kirill Kravtsov (@nvarscar), nvarscar.wordpress.com",
        "CommandName":  "New-DbaDacOption",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaDacOption",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$options = New-DbaDacOption -Type Dacpac -Action Export\nPS C:\\\u003e $options.ExtractAllTableData = $true\r\nPS C:\\\u003e $options.CommandTimeout = 0\r\nPS C:\\\u003e Export-DbaDacPackage -SqlInstance sql2016 -Database DB1 -Options $options\nUses DacOption object to set the CommandTimeout to 0 then extracts the dacpac for SharePoint_Config on sql2016 to C:\\temp\\SharePoint_Config.dacpac including all table data.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$options = New-DbaDacOption -Type Dacpac -Action Publish\nPS C:\\\u003e $options.DeployOptions.DropObjectsNotInSource = $true\r\nPS C:\\\u003e Publish-DbaDacPackage -SqlInstance sql2016 -Database DB1 -Options $options -Path c:\\temp\\db.dacpac\nUses DacOption object to set Deployment Options and publish the db.dacpac dacpac file as DB1 on sql2016",
        "Params":  [
                       [
                           "Type",
                           "Selecting the type of the export: Dacpac (default) or Bacpac.",
                           "",
                           false,
                           "false",
                           "Dacpac"
                       ],
                       [
                           "Action",
                           "Choosing an intended action: Publish or Export.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "PublishXml",
                           "Specifies the publish profile which will include options and sqlCmdVariables.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaDacOption [[-Type] \u003cString\u003e] [-Action] \u003cString\u003e [[-PublishXml] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaDacProfile",
        "Description":  "The New-DbaDacProfile command generates a standard publish profile xml file that can be used by the DacFx (this and everything else) to control the deployment of your dacpac\nThis generates a standard template XML which is enough to dpeloy a dacpac but it is highly recommended that you add additional options to the publish profile.\nIf you use Visual Studio you can open a publish.xml file and use the ui to edit the file -\nTo create a new file, right click on an SSDT project, choose \"Publish\" then \"Load Profile\" and load your profile or create a new one.\nOnce you have loaded it in Visual Studio, clicking advanced shows you the list of options available to you.\nFor a full list of options that you can add to the profile, google \"sqlpackage.exe command line switches\" or (https://msdn.microsoft.com/en-us/library/hh550080(v=vs.103).aspx)",
        "Tags":  "Dacpac",
        "Synopsis":  "Creates a new Publish Profile.",
        "Alias":  "New-DbaPublishProfile",
        "Author":  "Richie lee (@richiebzzzt)",
        "CommandName":  "New-DbaDacProfile",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/New-DbaDacProfile",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDacProfile -SqlInstance sql2017 -SqlCredential ad\\sqldba -Database WorldWideImporters -Path C:\\temp\nIn this example, a prompt will appear for alternative credentials, then a connection will be made to sql2017. Using that connection,\r\nthe ConnectionString will be extracted and used within the Publish Profile XML file which will be created at C:\\temp\\sql2017-WorldWideImporters-publish.xml\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDacProfile -Database WorldWideImporters -Path C:\\temp -ConnectionString \"SERVER=(localdb)\\MSSQLLocalDB;Integrated Security=True;Database=master\"\nIn this example, no connections are made, and a Publish Profile XML would be created at C:\\temp\\localdb-MSSQLLocalDB-WorldWideImporters-publish.xml",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Alternatively, you can provide a ConnectionString.",
                           "ServerInstance,SqlServer",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to servers using alternative logins instead Integrated, accepts Credential object created by Get-Credential",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database name you are targeting",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "The directory where you would like to save the profile xml file(s).",
                           "",
                           false,
                           "false",
                           "\"$home\\Documents\""
                       ],
                       [
                           "ConnectionString",
                           "The connection string to the database you are upgrading.\nAlternatively, you can provide a SqlInstance (and optionally SqlCredential) and the script will connect and generate the connectionstring.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "PublishOptions",
                           "Optional hashtable to set publish options. Key/value pairs in the hashtable get converted to strings of \"\u003ckey\u003evalue\u003c/key\u003e\".",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaDacProfile [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-Database] \u003cString[]\u003e [[-Path] \u003cString\u003e] [[-ConnectionString] \u003cString[]\u003e] [[-PublishOptions] \u003cHashtable\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaDatabase",
        "Description":  "This command creates a new database.\n\nIt allows creation with multiple files, and sets all growth settings to be fixed size rather than percentage growth.",
        "Tags":  "Database",
        "Synopsis":  "Creates a new database",
        "Alias":  "",
        "Author":  "Matthew Darwin (@evoDBA, naturalselectiondba.wordpress.com)  | Chrissy LeMaire (@cl)",
        "CommandName":  "New-DbaDatabase",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaDatabase",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDatabase -SqlInstance sql1\nCreates a randomly named database (random-N) on instance sql1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDatabase -SqlInstance sql1 -Name dbatools, dbachecks\nCreates a database named dbatools and a database named dbachecks on sql1\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaDatabase -SqlInstance sql1, sql2, sql3 -Name multidb, multidb2 -SecondaryFilesize 20 -SecondaryFileGrowth 20 -LogSize 20 -LogGrowth 20\nCreates two databases, multidb and multidb2, on 3 instances (sql1, sql2 and sql3) and sets the secondary data file size to 20MB, the file growth to 20MB and the log growth to 20MB for each\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eNew-DbaDatabase -SqlInstance sql1 -Name nondefault -DataFilePath M:\\Data -LogFilePath \u0027L:\\Logs with spaces\u0027 -SecondaryFileCount 2\nCreates a database named nondefault and places data files in in the M:\\data directory and log files in \"L:\\Logs with spaces\".\nCreates a secondary group with 2 files in the Secondary filegroup.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "The name of the new database or databases to be created.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Collation",
                           "The database collation, if not supplied the default server collation will be used.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Recoverymodel",
                           "The recovery model for the database, if not supplied the recovery model from the model database will be used.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Owner",
                           "The login that will be used as the database owner.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DataFilePath",
                           "The location that data files will be placed, otherwise the default SQL Server data path will be used.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "LogFilePath",
                           "The location the log file will be placed, otherwise the default SQL Server log path will be used.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "PrimaryFilesize",
                           "The size in MB for the Primary file. If this is less than the primary file size for the model database, then the model size will be used instead.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "PrimaryFileGrowth",
                           "The size in MB that the Primary file will autogrow by.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "PrimaryFileMaxSize",
                           "The maximum permitted size in MB for the Primary File. If this is less the primary file size for the model database, then the model size will be used instead.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "LogSize",
                           "The size in MB that the Transaction log will be created.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "LogGrowth",
                           "The amount in MB that the log file will be set to autogrow by.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "SecondaryFilesize",
                           "The size in MB of the files to be added to the Secondary filegroup. Each file added will be created with this size setting.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "SecondaryFileGrowth",
                           "The amount in MB that the Secondary files will be set to autogrow by. Use 0 for no growth allowed. Each file added will be created with this growth setting.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "SecondaryFileMaxSize",
                           "The maximum permitted size in MB for the Secondary data files to grow to. Each file added will be created with this max size setting.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "SecondaryFileCount",
                           "The number of files to create in the Secondary filegroup for the database.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "DefaultFileGroup",
                           "Sets the default file group. Either primary or secondary.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaDatabase [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString[]\u003e] [[-Collation] \u003cString\u003e] [[-Recoverymodel] \u003cString\u003e] [[-Owner] \u003cString\u003e] [[-DataFilePath] \u003cString\u003e] [[-LogFilePath] \u003cString\u003e] [[-PrimaryFilesize] \u003cInt32\u003e] [[-PrimaryFileGrowth] \u003cInt32\u003e] [[-PrimaryFileMaxSize] \u003cInt32\u003e] [[-LogSize] \u003cInt32\u003e] [[-LogGrowth] \u003cInt32\u003e] [[-SecondaryFilesize] \u003cInt32\u003e] [[-SecondaryFileGrowth] \u003cInt32\u003e] [[-SecondaryFileMaxSize] \u003cInt32\u003e] [[-SecondaryFileCount] \u003cInt32\u003e] [[-DefaultFileGroup] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaDbCertificate",
        "Description":  "Creates a new database certificate. If no database is specified, the certificate will be created in master.",
        "Tags":  "Certificate",
        "Synopsis":  "Creates a new database certificate",
        "Alias":  "New-DbaDatabaseCertificate",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "New-DbaDbCertificate",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDbCertificate -SqlInstance Server1\nYou will be prompted to securely enter your password, then a certificate will be created in the master database on server1 if it does not exist.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDbCertificate -SqlInstance Server1 -Database db1 -Confirm:$false\nSuppresses all prompts to install but prompts to securely enter your password and creates a certificate in the \u0027db1\u0027 database",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to SQL Server using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "Optional name to create the certificate. Defaults to database name.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database where the certificate will be created. Defaults to master.",
                           "",
                           false,
                           "false",
                           "master"
                       ],
                       [
                           "Subject",
                           "Optional subject to create the certificate.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "StartDate",
                           "Optional secure string used to create the certificate.",
                           "",
                           false,
                           "false",
                           "(Get-Date)"
                       ],
                       [
                           "ExpirationDate",
                           "Optional secure string used to create the certificate.",
                           "",
                           false,
                           "false",
                           "$StartDate.AddYears(5)"
                       ],
                       [
                           "ActiveForServiceBrokerDialog",
                           "Optional secure string used to create the certificate.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "SecurePassword",
                           "Optional password - if no password is supplied, the password will be protected by the master key",
                           "Password",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaDatabase",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaDbCertificate [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString[]\u003e] [[-Database] \u003cString[]\u003e] [[-Subject] \u003cString[]\u003e] [[-StartDate] \u003cDateTime\u003e] [[-ExpirationDate] \u003cDateTime\u003e] [-ActiveForServiceBrokerDialog] [[-SecurePassword] \u003cSecureString\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaDbMaskingConfig",
        "Description":  "Generates a new data masking configuration file. This file is important to apply any data masking to the data in a database.\n\nNote that the following column and data types are not currently supported:\nIdentity\nForeignKey\nComputed\nHierarchyid\nGeography\nGeometry\nXml\n\nRead more here:\nhttps://sachabarbs.wordpress.com/2018/06/11/bogus-simple-fake-data-tool/\nhttps://github.com/bchavez/Bogus",
        "Tags":  [
                     "DataMasking",
                     "Database"
                 ],
        "Synopsis":  "Generates a new data masking configuration file to be used with Invoke-DbaDbDataMasking",
        "Alias":  "",
        "Author":  "Sander Stad (@sqlstad, sqlstad.nl) | Chrissy LeMaire (@cl, netnerds.net)",
        "CommandName":  "New-DbaDbMaskingConfig",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaDbMaskingConfig",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDbMaskingConfig -SqlInstance SQLDB1 -Database DB1 -Path C:\\Temp\\clone\nProcess all tables and columns for database DB1 on instance SQLDB1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDbMaskingConfig -SqlInstance SQLDB1 -Database DB1 -Table Customer -Path C:\\Temp\\clone\nProcess only table Customer with all the columns\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaDbMaskingConfig -SqlInstance SQLDB1 -Database DB1 -Table Customer -Column City -Path C:\\Temp\\clone\nProcess only table Customer and only the column named \"City\"",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Databases to process through",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Table",
                           "Tables to process. By default all the tables will be processed",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Column",
                           "Columns to process. By default all the columns will be processed",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "Path where to save the generated JSON files.\r\nTh naming convention will be \"servername.databasename.tables.json\"",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Locale",
                           "Set the local to enable certain settings in the masking",
                           "",
                           false,
                           "false",
                           "en"
                       ],
                       [
                           "Force",
                           "Forcefully execute commands when needed",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "New-DbaDbMaskingConfig [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Table] \u003cString[]\u003e] [[-Column] \u003cString[]\u003e] [-Path] \u003cString\u003e [[-Locale] \u003cString\u003e] [-Force] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaDbMasterKey",
        "Description":  "Creates a new database master key. If no database is specified, the master key will be created in master.",
        "Tags":  "Certificate",
        "Synopsis":  "Creates a new database master key",
        "Alias":  "New-DbaDatabaseMasterKey",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "New-DbaDbMasterKey",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDbMasterKey -SqlInstance Server1\nYou will be prompted to securely enter your password, then a master key will be created in the master database on server1 if it does not exist.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDbMasterKey -SqlInstance Server1 -Credential usernamedoesntmatter\nYou will be prompted by a credential interface to securely enter your password, then a master key will be created in the master database on server1 if it does not exist.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaDbMasterKey -SqlInstance Server1 -Database db1 -Confirm:$false\nSuppresses all prompts to install but prompts in th console to securely enter your password and creates a master key in the \u0027db1\u0027 database",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to SQL Server using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Credential",
                           "Enables easy creation of a secure password.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database where the master key will be created. Defaults to master.",
                           "",
                           false,
                           "false",
                           "master"
                       ],
                       [
                           "SecurePassword",
                           "Secure string used to create the key.",
                           "Password",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Database object piped in from Get-DbaDatabase.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaDbMasterKey [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-SecurePassword] \u003cSecureString\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaDbSnapshot",
        "Description":  "Creates database snapshots without hassles",
        "Tags":  [
                     "Snapshot",
                     "Restore",
                     "Database"
                 ],
        "Synopsis":  "Creates database snapshots",
        "Alias":  "New-DbaDatabaseSnapshot",
        "Author":  "Simone Bizzotto (@niphold)",
        "CommandName":  "New-DbaDbSnapshot",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaDbSnapshot",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDbSnapshot -SqlInstance sqlserver2014a -Database HR, Accounting\nCreates snapshot for HR and Accounting, returning a custom object displaying Server, Database, DatabaseCreated, SnapshotOf, SizeMB, DatabaseCreated, PrimaryFilePath, Status, Notes\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDbSnapshot -SqlInstance sqlserver2014a -Database HR -Name HR_snap\nCreates snapshot named \"HR_snap\" for HR\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaDbSnapshot -SqlInstance sqlserver2014a -Database HR -NameSuffix \u0027fool_{0}_snap\u0027\nCreates snapshot named \"fool_HR_snap\" for HR\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eNew-DbaDbSnapshot -SqlInstance sqlserver2014a -Database HR, Accounting -Path F:\\snapshotpath\nCreates snapshots for HR and Accounting databases, storing files under the F:\\snapshotpath\\ dir\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016 -Database df | New-DbaDbSnapshot\nCreates a snapshot for the database df on sql2016",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Credential object used to connect to the SQL Server as a different user",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AllDatabases",
                           "Creates snapshot for all eligible databases",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Name",
                           "The specific snapshot name you want to create. Works only if you target a single database. If you need to create multiple snapshot,\r\nyou must use the NameSuffix parameter",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NameSuffix",
                           "When you pass a simple string, it\u0027ll be appended to use it to build the name of the snapshot. By default snapshots are created with yyyyMMdd_HHmmss suffix\r\nYou can also pass a standard placeholder, in which case it\u0027ll be interpolated (e.g. \u0027{0}\u0027 gets replaced with the database name)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "Snapshot files will be created here (by default the filestructure will be created in the same folder as the base db)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "Databases with Filestream FG can be snapshotted, but the Filestream FG is marked offline\r\nin the snapshot. To create a \"partial\" snapshot, you need to pass -Force explicitely\nNB: You can\u0027t then restore the Database from the newly-created snapshot.\r\nFor details, check https://msdn.microsoft.com/en-us/library/bb895334.aspx",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Allows Piping from Get-DbaDatabase",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts for confirmation of every step.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaDbSnapshot [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-AllDatabases] [[-Name] \u003cString\u003e] [[-NameSuffix] \u003cString\u003e] [[-Path] \u003cString\u003e] [-Force] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaDbUser",
        "Description":  "Creates a new user for a specified database with provided specifications.",
        "Tags":  [
                     "Database",
                     "User"
                 ],
        "Synopsis":  "Creates a new user for the specified database.",
        "Alias":  "",
        "Author":  "Frank Henninger (@osiris687)",
        "CommandName":  "New-DbaDbUser",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaDbUser",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -Login user1\nCreates a new sql user with login named user1 in the specified database.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -Username user1\nCreates a new sql user without login named user1 in the specified database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -Login Login1 -Username user1\nCreates a new sql user named user1 mapped to Login1 in the specified database.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbUser -SqlInstance sqlserver1 -Database DB1 | New-DbaDbUser -SqlInstance sqlserver2 -Database DB1\nCopies users from sqlserver1.DB1 to sqlserver2.DB1. Does not copy permissions!",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Defaults to the default instance on localhost.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to servers using SQL Logins instead of Windows Authentication (AKA Integrated or Trusted). To use:\n$scred = Get-Credential, then pass $scred object to the -SqlCredential parameter.\nWindows Authentication will be used if SqlCredential is not specified. SQL Server does not accept Windows credentials being passed as credentials.\nTo connect to SQL Server as a different Windows user, run PowerShell as that user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server. By default, system databases are excluded.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IncludeSystem",
                           "If this switch is enabled, the user will be added to system databases.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Login",
                           "When specified, the user will be associated to this SQL login and have the same name as the Login.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Username",
                           "When specified, the user will have this name.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If user exists, drop and recreate.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaDbUser [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-IncludeSystem] [-Username \u003cString[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nNew-DbaDbUser [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-IncludeSystem] [-Login \u003cString[]\u003e] [-Username \u003cString[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaDirectory",
        "Description":  "Uses master.dbo.xp_create_subdir to create the path\nReturns $true if the path can be created, $false otherwise",
        "Tags":  [
                     "Path",
                     "Directory",
                     "Folder"
                 ],
        "Synopsis":  "Creates new path as specified by the path variable",
        "Alias":  "New-DbaSqlDirectory",
        "Author":  "Stuart Moore",
        "CommandName":  "New-DbaDirectory",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaDirectory",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDirectory -SqlInstance sqlcluster -Path L:\\MSAS12.MSSQLSERVER\\OLAP\nIf the SQL Server instance sqlcluster can create the path L:\\MSAS12.MSSQLSERVER\\OLAP it will do and return $true, if not it will return $false.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$credential = Get-Credential\nPS C:\\\u003e New-DbaDirectory -SqlInstance sqlcluster -SqlCredential $credential -Path L:\\MSAS12.MSSQLSERVER\\OLAP\nIf the SQL Server instance sqlcluster can create the path L:\\MSAS12.MSSQLSERVER\\OLAP it will do and return $true, if not it will return $false. Uses a SqlCredential to connect",
        "Params":  [
                       [
                           "SqlInstance",
                           "The SQL Server you want to run the test on.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "The Path to tests. Can be a file or directory.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaDirectory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-Path] \u003cString\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaEndpoint",
        "Description":  "Creates endpoints on a SQL Server instance.",
        "Tags":  "Endpoint",
        "Synopsis":  "Creates endpoints on a SQL Server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "New-DbaEndpoint",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaEndpoint",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaEndpoint -SqlInstance localhost\nCreates all Endpoint(s) on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaEndpoint -SqlInstance localhost, sql2016\nReturns all Endpoint(s) for the local and sql2016 SQL Server instances",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "The name of the endpoint. If a name is not specified, one will be auto-generated.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Type",
                           "The type of endpoint. Defaults to DatabaseMirroring. Options: DatabaseMirroring, ServiceBroker, Soap, TSql",
                           "",
                           false,
                           "false",
                           "DatabaseMirroring"
                       ],
                       [
                           "Protocol",
                           "The type of protocol. Defaults to tcp. Options: Tcp, NamedPipes, Http, Via, SharedMemory",
                           "",
                           false,
                           "false",
                           "Tcp"
                       ],
                       [
                           "Role",
                           "The type of role. Defaults to All. Options: All, None, Partner, Witness",
                           "",
                           false,
                           "false",
                           "All"
                       ],
                       [
                           "EndpointEncryption",
                           "Used to specify the state of encryption on the endpoint. Defaults to required.\r\nDisabled\r\nRequired\r\nSupported",
                           "",
                           false,
                           "false",
                           "Required"
                       ],
                       [
                           "EncryptionAlgorithm",
                           "Specifies an encryption algorithm used on an endpoint. Defaults to Aes.\nOptions are:\r\nAesRC4\r\nAes\r\nNone\r\nRC4\r\nRC4Aes",
                           "",
                           false,
                           "false",
                           "Aes"
                       ],
                       [
                           "Certificate",
                           "Database certificate used for authentication.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Port",
                           "Port for TCP. If one is not provided, it will be autogenerated.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "SslPort",
                           "Port for SSL",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "Owner",
                           "Owner of the endpoint. Defaults to sa.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaEndpoint [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Name \u003cString\u003e] [-Type \u003cString\u003e] [-Protocol \u003cString\u003e] [-Role \u003cString\u003e] [-EndpointEncryption \u003cString\u003e] [-EncryptionAlgorithm \u003cString\u003e] [-Certificate \u003cString\u003e] [-Port \u003cInt32\u003e] [-SslPort \u003cInt32\u003e] [-Owner \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaLogin",
        "Description":  "Creates a new SQL Server login with provided specifications",
        "Tags":  [
                     "Login",
                     "Security"
                 ],
        "Synopsis":  "Creates a new SQL Server login",
        "Alias":  "",
        "Author":  "Kirill Kravtsov (@nvarscar)",
        "CommandName":  "New-DbaLogin",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaLogin",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaLogin -SqlInstance Server1,Server2 -Login Newlogin\nYou will be prompted to securely enter the password for a login [Newlogin]. The login would be created on servers Server1 and Server2 with default parameters.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$securePassword = Read-Host \"Input password\" -AsSecureString\nPS C:\\\u003e New-DbaLogin -SqlInstance Server1\\sql1 -Login Newlogin -Password $securePassword -PasswordPolicy -PasswordExpiration\nCreates a login on Server1\\sql1 with a predefined password. The login will have password and expiration policies enforced onto it.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql1 -Login Oldlogin | New-DbaLogin -SqlInstance sql1 -LoginRenameHashtable @{Oldlogin = \u0027Newlogin\u0027} -Force -NewSid -Disabled:$false\nCopies a login [Oldlogin] to the same instance sql1 with the same parameters (including password). New login will have a new sid, a new name [Newlogin] and will not be disabled. Existing login \r\n[Newlogin] will be removed prior to creation.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql1 -Login Login1,Login2 | New-DbaLogin -SqlInstance sql2 -PasswordPolicy -PasswordExpiration -DefaultDatabase tempdb -Disabled\nCopies logins [Login1] and [Login2] from instance sql1 to instance sql2, but enforces password and expiration policies for the new logins. New logins will also have a default database set to [tempdb] \r\nand will be created in a disabled state.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eNew-DbaLogin -SqlInstance sql1 -Login domain\\user\nCreates a new Windows Authentication backed login on sql1. The login will be part of the public server role.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server(s)",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to SQL Server using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Login",
                           "The Login name(s)",
                           "Name,LoginName",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Takes the parameters required from a Login object that has been piped into the command",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "LoginRenameHashtable",
                           "Pass a hash table into this parameter to change login names when piping objects into the procedure",
                           "Rename",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SecurePassword",
                           "Secure string used to authenticate the Login",
                           "Password",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "HashedPassword",
                           "Hashed password string used to authenticate the Login",
                           "Hash,PasswordHash",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "MapToCertificate",
                           "Map the login to a certificate",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "MapToAsymmetricKey",
                           "Map the login to an asymmetric key",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "MapToCredential",
                           "Map the login to a credential",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Sid",
                           "Provide an explicit Sid that should be used when creating the account. Can be [byte[]] or hex [string] (\u00270xFFFF...\u0027)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DefaultDatabase",
                           "Default database for the login",
                           "DefaulDB",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Language",
                           "Login\u0027s default language",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "PasswordExpiration",
                           "Enforces password expiration policy. Requires PasswordPolicy to be enabled. Can be $true or $false(default)",
                           "Expiration,CheckExpiration",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "PasswordPolicy",
                           "Enforces password complexity policy. Can be $true or $false(default)",
                           "Policy,CheckPolicy",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Disabled",
                           "Create the login in a disabled state",
                           "Disable",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NewSid",
                           "Ignore sids from the piped login object to generate new sids on the server. Useful when copying login onto the same server",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "If login exists, drop and recreate",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaLogin [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [[-Login] \u003cString[]\u003e] [-InputObject \u003cObject[]\u003e] [-LoginRenameHashtable \u003cHashtable\u003e] [[-SecurePassword] \u003cSecureString\u003e] [-MapToCredential \u003cString\u003e] [-Sid \u003cObject\u003e] [-DefaultDatabase \u003cString\u003e] [-Language \u003cString\u003e] [-PasswordExpiration] [-PasswordPolicy] [-Disabled] [-NewSid] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nNew-DbaLogin [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Login \u003cString[]\u003e] [-InputObject \u003cObject[]\u003e] [-LoginRenameHashtable \u003cHashtable\u003e] [-MapToAsymmetricKey \u003cString\u003e] [-MapToCredential \u003cString\u003e] [-Sid \u003cObject\u003e] [-Disabled] [-NewSid] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nNew-DbaLogin [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Login \u003cString[]\u003e] [-InputObject \u003cObject[]\u003e] [-LoginRenameHashtable \u003cHashtable\u003e] [-MapToCertificate \u003cString\u003e] [-MapToCredential \u003cString\u003e] [-Sid \u003cObject\u003e] [-Disabled] [-NewSid] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nNew-DbaLogin [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Login \u003cString[]\u003e] [-InputObject \u003cObject[]\u003e] [-LoginRenameHashtable \u003cHashtable\u003e] [-HashedPassword \u003cString\u003e] [-MapToCredential \u003cString\u003e] [-Sid \u003cObject\u003e] [-DefaultDatabase \u003cString\u003e] [-Language \u003cString\u003e] [-PasswordExpiration] [-PasswordPolicy] [-Disabled] [-NewSid] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaScriptingOption",
        "Description":  "Creates a new Microsoft.SqlServer.Management.Smo.ScriptingOptions object. Basically saves you the time from remembering the SMO assembly name ;)\n\nSee https://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.scriptingoptions.aspx for more information",
        "Tags":  [
                     "Migration",
                     "Backup",
                     "DR"
                 ],
        "Synopsis":  "Creates a new Microsoft.SqlServer.Management.Smo.ScriptingOptions object",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "New-DbaScriptingOption",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaScriptingOption",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$options = New-DbaScriptingOption\nPS C:\\\u003e $options.ScriptDrops = $false\r\nPS C:\\\u003e $options.WithDependencies = $true\r\nPS C:\\\u003e Get-DbaAgentJob -SqlInstance sql2016 | Export-DbaScript -ScriptingOptionObject $options\nExports Agent Jobs with the Scripting Options ScriptDrops set to $false and WithDependencies set to true",
        "Params":  [

                   ],
        "Syntax":  "New-DbaScriptingOption [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaServiceMasterKey",
        "Description":  "Creates a new service master key in the master database.",
        "Tags":  "Certificate",
        "Synopsis":  "Creates a new service master key.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "New-DbaServiceMasterKey",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaServiceMasterKey -SqlInstance Server1\nYou will be prompted to securely enter your Service Key password, then a master key will be created in the master database on server1 if it does not exist.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to SQL Server using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Credential",
                           "Enables easy creation of a secure password.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SecurePassword",
                           "Secure string used to create the key.",
                           "Password",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaServiceMasterKey [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-SecurePassword] \u003cSecureString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaSsisCatalog",
        "Description":  "After installing the SQL Server Engine and SSIS you still have to enable the SSIS Catalog. This function will enable the catalog and gives the option of supplying the password.",
        "Tags":  [
                     "SSIS",
                     "SSISDB",
                     "Catalog"
                 ],
        "Synopsis":  "Enables the SSIS Catalog on a SQL Server 2012+",
        "Alias":  "",
        "Author":  "Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/",
        "CommandName":  "New-DbaSsisCatalog",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/New-DbaSsisCatalog",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$SecurePassword = Read-Host -AsSecureString -Prompt \"Enter password\"\nPS C:\\\u003e New-DbaSsisCatalog -SqlInstance DEV01 -SecurePassword $SecurePassword\nCreates the SSIS Catalog on server DEV01 with the specified password.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaSsisCatalog -SqlInstance sql2016 -Credential usernamedoesntmatter\nCreates the SSIS Catalog on server DEV01 with the specified password in the credential prompt. As the example username suggets the username does not matter.\r\nThis is simply an easier way to get a secure password.",
        "Params":  [
                       [
                           "SqlInstance",
                           "SQL Server you wish to run the function on.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Credentials used to connect to the SQL Server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Credential",
                           "Use a credential object instead of a securepassword",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SecurePassword",
                           "Required password that will be used for the security key in SSISDB.",
                           "Password",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SsisCatalog",
                           "SSIS catalog name. By default, this is SSISDB.",
                           "",
                           false,
                           "false",
                           "SSISDB"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaSsisCatalog [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-SecurePassword] \u003cSecureString\u003e] [[-SsisCatalog] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbatoolsSupportPackage",
        "Description":  "This function creates an extensive debugging package that can help with reproducing and fixing issues.\n\nThe file will be created on the desktop by default and will contain quite a bit of information:\n- OS Information\n- Hardware Information (CPU, Ram, things like that)\n- .NET Information\n- PowerShell Information\n- Your input history\n- The In-Memory message log\n- The In-Memory error log\n- Screenshot of the console buffer (Basically, everything written in your current console, even if you have to scroll upwards to see it.",
        "Tags":  "Debug",
        "Synopsis":  "Creates a package of troubleshooting information that can be used by dbatools to help debug issues.",
        "Alias":  "",
        "Author":  "Friedrich Weinmann (@FredWeinmann)",
        "CommandName":  "New-DbatoolsSupportPackage",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/New-DbatoolsSupportPackage",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbatoolsSupportPackage\nCreates a large support pack in order to help us troubleshoot stuff.",
        "Params":  [
                       [
                           "Path",
                           "The folder where to place the output xml in.",
                           "",
                           false,
                           "false",
                           "\"$($env:USERPROFILE)\\Desktop\""
                       ],
                       [
                           "Variables",
                           "Name of additional variables to attach.\r\nThis allows you to add the content of variables to the support package, if you believe them to be relevant to the case.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "PassThru",
                           "Returns file object that was created during execution.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbatoolsSupportPackage [[-Path] \u003cString\u003e] [[-Variables] \u003cString[]\u003e] [-PassThru] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaXESession",
        "Description":  "Creates a new XESession object - for the dogged (very manual, Import-DbaXESessionTemplate is recommended). See the following for more info:\n\nhttps://docs.microsoft.com/en-us/sql/relational-databases/extended-events/use-the-powershell-provider-for-extended-events",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "Creates a new XESession object - for the dogged.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "New-DbaXESession",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaXESession",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$session = New-DbaXESession -SqlInstance sql2017 -Name XeSession_Test\nPS C:\\\u003e $event = $session.AddEvent(\"sqlserver.file_written\")\r\nPS C:\\\u003e $event.AddAction(\"package0.callstack\")\r\nPS C:\\\u003e $session.Create()\nReturns a new XE Session object from sql2017 then adds an event, an action then creates it.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "The Name of the session to be created.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaXESession [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Name] \u003cString\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaXESmartCsvWriter",
        "Description":  "This response type is used to write Extended Events to a CSV file.",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "This response type is used to write Extended Events to a CSV file.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl) | SmartTarget by Gianluca Sartori (@spaghettidba)",
        "CommandName":  "New-DbaXESmartCsvWriter",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaXESmartCsvWriter",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$columns = \"cpu_time\", \"duration\", \"physical_reads\", \"logical_reads\", \"writes\", \"row_count\"\nPS C:\\\u003e $response = New-DbaXESmartCsvWriter -OutputFile c:\\temp\\workload.csv -OutputColumn $columns -OverWrite -Event \"sql_batch_completed\"\r\nPS C:\\\u003e Start-DbaXESmartTarget -SqlInstance localhost\\sql2017 -Session \"Profiler Standard\" -Responder $response\nWrites Extended Events to the file \"C:\\temp\\workload.csv\".",
        "Params":  [
                       [
                           "OutputFile",
                           "Specifies the path to the output CSV file.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Overwrite",
                           "Specifies whether any existiting file should be overwritten or not.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Event",
                           "Specifies a list of events to be processed (with others being ignored. By default, all events are processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "OutputColumn",
                           "Specifies the list of columns to output from the events. XESmartTarget will capture in memory and write to the target table only the columns (fields or targets) that are present in this list.\nFields and actions are matched in a case-sensitive manner.\nExpression columns are supported. Specify a column with ColumnName AS Expression to add an expression column (Example: Total AS Reads + Writes)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Filter",
                           "Specifies a filter expression in the same form as you would use in the WHERE clause of a SQL query.\nExample: duration \u003e 10000 AND cpu_time \u003e 10000",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaXESmartCsvWriter [-OutputFile] \u003cString\u003e [-Overwrite] [[-Event] \u003cString[]\u003e] [[-OutputColumn] \u003cString[]\u003e] [[-Filter] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaXESmartEmail",
        "Description":  "This response type can be used to send an email each time an event is captured.",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "This response type can be used to send an email each time an event is captured.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl) | SmartTarget by Gianluca Sartori (@spaghettidba)",
        "CommandName":  "New-DbaXESmartEmail",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaXESmartEmail",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e SmtpServer = \"smtp.ad.local\"\r\n\u003e\u003e To = \"[email protected]\"\r\n\u003e\u003e Sender = \"[email protected]\"\r\n\u003e\u003e Subject = \"Query executed\"\r\n\u003e\u003e Body = \"Query executed at {collection_time}\"\r\n\u003e\u003e Attachment = \"batch_text\"\r\n\u003e\u003e AttachmentFileName = \"query.sql\"\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e $emailresponse = New-DbaXESmartEmail @params\r\nPS C:\\\u003e Start-DbaXESmartTarget -SqlInstance sql2017 -Session querytracker -Responder $emailresponse\nSends an email each time a querytracker event is captured.",
        "Params":  [
                       [
                           "SmtpServer",
                           "Address of the SMTP server for outgoing mail.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Sender",
                           "Sender\u0027s email address.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "To",
                           "Address of the To recipient(s).",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Cc",
                           "Address of the Cc recipient(s).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Bcc",
                           "Address of the Bcc recipient(s).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Credential",
                           "Credential object containing username and password used to authenticate on the SMTP server. When blank, no authentication is performed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Subject",
                           "Subject of the mail message. Accepts placeholders in the text.\nPlaceholders are in the form {PropertyName}, where PropertyName is one of the fields or actions available in the Event object.\nFor instance, a valid Subject in a configuration file looks like this: \"An event of name {Name} occurred at {collection_time}\"",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Body",
                           "Body of the mail message. The body can be static text or any property taken from the underlying event. See Subject for a description of how placeholders work.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Attachment",
                           "Data to attach to the email message. At this time, it can be any of the fields/actions of the underlying event. The data from the field/action is attached to the message as an ASCII stream. A single \r\nattachment is supported.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AttachmentFileName",
                           "File name to assign to the attachment.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "PlainText",
                           "If this switch is enabled, the email will be sent in plain text. By default, HTML formatting is used.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Event",
                           "Each Response can be limited to processing specific events, while ignoring all the other ones. When this attribute is omitted, all events are processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Filter",
                           "You can specify a filter expression by using this attribute. The filter expression is in the same form that you would use in a SQL query. For example, a valid example looks like this: duration \u003e \r\n10000 AND cpu_time \u003e 10000",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaXESmartEmail [-SmtpServer] \u003cString\u003e [-Sender] \u003cString\u003e [-To] \u003cString[]\u003e [[-Cc] \u003cString[]\u003e] [[-Bcc] \u003cString[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-Subject] \u003cString\u003e [-Body] \u003cString\u003e [[-Attachment] \u003cString\u003e] [[-AttachmentFileName] \u003cString\u003e] [[-PlainText] \u003cString\u003e] [[-Event] \u003cString[]\u003e] [[-Filter] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaXESmartQueryExec",
        "Description":  "This response type executes a T-SQL command against a target database whenever an event is recorded.",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "This response type executes a T-SQL command against a target database whenever an event is recorded.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl) | SmartTarget by Gianluca Sartori (@spaghettidba)",
        "CommandName":  "New-DbaXESmartQueryExec",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaXESmartQueryExec",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$response = New-DbaXESmartQueryExec -SqlInstance sql2017 -Database dbadb -Query \"update table set whatever = 1\"\nPS C:\\\u003e Start-DbaXESmartTarget -SqlInstance sql2017 -Session deadlock_tracker -Responder $response\nExecutes a T-SQL command against dbadb on sql2017 whenever a deadlock event is recorded.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies the name of the database that contains the target table.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Query",
                           "The T-SQL command to execute. This string can contain placeholders for properties taken from the events.\nPlaceholders are in the form {PropertyName}, where PropertyName is one of the fields or actions available in the Event object.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Event",
                           "Each Response can be limited to processing specific events, while ignoring all the other ones. When this attribute is omitted, all events are processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Filter",
                           "You can specify a filter expression by using this attribute. The filter expression is in the same form that you would use in a SQL query. For example, a valid example looks like this: duration \u003e \r\n10000 AND cpu_time \u003e 10000",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaXESmartQueryExec [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [[-Query] \u003cString\u003e] [-EnableException] [[-Event] \u003cString[]\u003e] [[-Filter] \u003cString\u003e] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaXESmartReplay",
        "Description":  "This response type can be used to replay execution related events to a target SQL Server instance. The events that you can replay are of the type sql_batch_completed and rpc_completed: all other events are ignored.",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "This response type can be used to replay execution related events to a target SQL Server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl) | SmartTarget by Gianluca Sartori (@spaghettidba)",
        "CommandName":  "New-DbaXESmartReplay",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaXESmartReplay",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$response = New-DbaXESmartReplay -SqlInstance sql2017 -Database planning\nPS C:\\\u003e Start-DbaXESmartTarget -SqlInstance sql2016 -Session loadrelay -Responder $response\nReplays events from sql2016 on sql2017 in the planning database. Returns a PowerShell job object.\nTo see a list of all SmartTarget job objects, use Get-DbaXESmartTarget.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$response = New-DbaXESmartReplay -SqlInstance sql2017 -Database planning\nPS C:\\\u003e Start-DbaXESmartTarget -SqlInstance sql2017 -Session \u0027Profiler Standard\u0027 -Responder $response -NotAsJob\nReplays events from the \u0027Profiler Standard\u0027 session on sql2016 to sql2017\u0027s planning database. Does not run as a job so you can see the raw output.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Name of the initial catalog to connect to. Statements will be replayed by changing database to the same database where the event was originally captured, so this property only controls the initial \r\ndatabase to connect to.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Event",
                           "Each Response can be limited to processing specific events, while ignoring all the other ones. When this attribute is omitted, all events are processed.",
                           "",
                           false,
                           "false",
                           "sql_batch_completed"
                       ],
                       [
                           "Filter",
                           "Specifies a filter expression in the same form as you would use in the WHERE clause of a SQL query.\nExample: duration \u003e 10000 AND cpu_time \u003e 10000",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DelaySeconds",
                           "Specifies the duration of the delay in seconds.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "StopOnError",
                           "If this switch is enabled, the replay will be stopped when the first error is encountered. By default, error messages are piped to the log and console output, and replay proceeds.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ReplayIntervalSeconds",
                           "Specifies the duration of the replay interval in seconds.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaXESmartReplay [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [[-Event] \u003cString[]\u003e] [[-Filter] \u003cString\u003e] [[-DelaySeconds] \u003cInt32\u003e] [-StopOnError] [[-ReplayIntervalSeconds] \u003cInt32\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "New-DbaXESmartTableWriter",
        "Description":  "This response type is used to write Extended Events to a database table. The events are temporarily stored in memory before being written to the database at regular intervals.\n\nThe target table can be created manually upfront or you can let the TableAppenderResponse create a target table based on the fields and actions available in the events captured.\n\nThe columns of the target table and the fields/actions of the events are mapped by name (case-sensitive).",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "This response type is used to write Extended Events to a database table.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl) | SmartTarget by Gianluca Sartori (@spaghettidba)",
        "CommandName":  "New-DbaXESmartTableWriter",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/New-DbaXESmartTableWriter",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$columns = \"cpu_time\", \"duration\", \"physical_reads\", \"logical_reads\", \"writes\", \"row_count\", \"batch_text\"\nPS C:\\\u003e $response = New-DbaXESmartTableWriter -SqlInstance sql2017 -Database dbadb -Table deadlocktracker -OutputColumn $columns -Filter \"duration \u003e 10000\"\r\nPS C:\\\u003e Start-DbaXESmartTarget -SqlInstance sql2017 -Session deadlock_tracker -Responder $response\nWrites Extended Events to the deadlocktracker table in dbadb on sql2017.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies the name of the database that contains the target table.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Table",
                           "Specifies the name of the target table.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "AutoCreateTargetTable",
                           "If this switch is enabled, XESmartTarget will infer the definition of the target table from the columns captured in the Extended Events session.\nIf the target table already exists, it will not be recreated.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "UploadIntervalSeconds",
                           "Specifies the number of seconds XESmartTarget will keep the events in memory before dumping them to the target table. The default is 10 seconds.",
                           "",
                           false,
                           "false",
                           "10"
                       ],
                       [
                           "Event",
                           "Specifies a list of events to be processed (with others being ignored. By default, all events are processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "OutputColumn",
                           "Specifies the list of columns to output from the events. XESmartTarget will capture in memory and write to the target table only the columns (fields or targets) that are present in this list.\nFields and actions are matched in a case-sensitive manner.\nExpression columns are supported. Specify a column with ColumnName AS Expression to add an expression column (Example: Total AS Reads + Writes)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Filter",
                           "Specifies a filter expression in the same form as you would use in the WHERE clause of a SQL query.\nExample: duration \u003e 10000 AND cpu_time \u003e 10000",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "New-DbaXESmartTableWriter [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Database] \u003cString\u003e [-Table] \u003cString\u003e [-AutoCreateTargetTable] [[-UploadIntervalSeconds] \u003cInt32\u003e] [[-Event] \u003cString[]\u003e] [[-OutputColumn] \u003cString[]\u003e] [[-Filter] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Publish-DbaDacPackage",
        "Description":  "Deploying a dacpac uses the DacFx which historically needed to be installed on a machine prior to use. In 2016 the DacFx was supplied by Microsoft as a nuget package (Microsoft.Data.Tools.MSBuild) and this uses that nuget package.",
        "Tags":  [
                     "Migration",
                     "Database",
                     "Dacpac"
                 ],
        "Synopsis":  "The Publish-DbaDacPackage command takes a dacpac which is the output from an SSDT project and publishes it to a database. Changing the schema to match the dacpac and also to run any scripts in the dacpac (pre/post deploy scripts).",
        "Alias":  "Publish-DbaDacpac",
        "Author":  "Richie lee (@richiebzzzt)",
        "CommandName":  "Publish-DbaDacPackage",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Publish-DbaDacPackage",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$options = New-DbaDacOption -Type Dacpac -Action Publish\nPS C:\\\u003e $options.DeployOptions.DropObjectsNotInSource = $true\r\nPS C:\\\u003e Publish-DbaDacPackage -SqlInstance sql2016 -Database DB1 -DacOption $options -Path c:\\temp\\db.dacpac\nUses DacOption object to set Deployment Options and updates DB1 database on sql2016 from the db.dacpac dacpac file, dropping objects that are missing from source.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003ePublish-DbaDacPackage -SqlInstance sql2017 -Database WideWorldImporters -Path C:\\temp\\sql2016-WideWorldImporters.dacpac -PublishXml C:\\temp\\sql2016-WideWorldImporters-publish.xml -Confirm\nUpdates WideWorldImporters on sql2017 from the sql2016-WideWorldImporters.dacpac using the sql2016-WideWorldImporters-publish.xml publish profile. Prompts for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaDacProfile -SqlInstance sql2016 -Database db2 -Path C:\\temp\nPS C:\\\u003e Export-DbaDacPackage -SqlInstance sql2016 -Database db2 | Publish-DbaDacPackage -PublishXml C:\\temp\\sql2016-db2-publish.xml -Database db1, db2 -SqlInstance sql2017\nCreates a publish profile at C:\\temp\\sql2016-db2-publish.xml, exports the .dacpac to $home\\Documents\\sql2016-db2.dacpac. Does not prompt for confirmation.\r\nthen publishes it to the sql2017 server database db2\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$loc = \"C:\\Users\\bob\\source\\repos\\Microsoft.Data.Tools.Msbuild\\lib\\net46\\Microsoft.SqlServer.Dac.dll\"\nPS C:\\\u003e Publish-DbaDacPackage -SqlInstance \"local\" -Database WideWorldImporters -Path C:\\temp\\WideWorldImporters.dacpac -PublishXml C:\\temp\\WideWorldImporters.publish.xml -DacFxPath $loc -Confirm\nPublishes the dacpac using a specific dacfx library. Prompts for confirmation.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003ePublish-DbaDacPackage -SqlInstance sql2017 -Database WideWorldImporters -Path C:\\temp\\sql2016-WideWorldImporters.dacpac -PublishXml C:\\temp\\sql2016-WideWorldImporters-publish.xml \r\n-GenerateDeploymentScript -ScriptOnly\nDoes not deploy the changes, but will generate the deployment script that would be executed against WideWorldImporters.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003ePublish-DbaDacPackage -SqlInstance sql2017 -Database WideWorldImporters -Path C:\\temp\\sql2016-WideWorldImporters.dacpac -PublishXml C:\\temp\\sql2016-WideWorldImporters-publish.xml \r\n-GenerateDeploymentReport -ScriptOnly\nDoes not deploy the changes, but will generate the deployment report that would be executed against WideWorldImporters.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "Specifies the filesystem path to the DACPAC",
                           "",
                           true,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "PublishXml",
                           "Specifies the publish profile which will include options and sqlCmdVariables.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies the name of the database being published.",
                           "",
                           true,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "ConnectionString",
                           "Specifies the connection string to the database you are upgrading. This is not required if SqlInstance is specified.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "GenerateDeploymentScript",
                           "If this switch is enabled, the publish script will be generated.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "GenerateDeploymentReport",
                           "If this switch is enabled, the publish XML report  will be generated.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ScriptOnly",
                           "If this switch is enabled, only the change scripts will be generated.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Type",
                           "Selecting the type of the export: Dacpac (default) or Bacpac.",
                           "",
                           false,
                           "false",
                           "Dacpac"
                       ],
                       [
                           "OutputPath",
                           "Specifies the filesystem path (directory) where output files will be generated.",
                           "",
                           false,
                           "false",
                           "\"$home\\Documents\""
                       ],
                       [
                           "IncludeSqlCmdVars",
                           "If this switch is enabled, SqlCmdVars in publish.xml will have their values overwritten.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DacOption",
                           "Export options for a corresponding export type. Can be created by New-DbaDacOption -Type Dacpac | Bacpac",
                           "Option",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DacFxPath",
                           "Path to the dac dll. If this is ommited, then the version of dac dll which is packaged with dbatools is used.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Publish-DbaDacPackage [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] -Path \u003cString\u003e -Database \u003cString[]\u003e [-ConnectionString \u003cString[]\u003e] [-ScriptOnly] [-Type \u003cString\u003e] [-OutputPath \u003cString\u003e] [-IncludeSqlCmdVars] [-DacOption \u003cObject\u003e] [-EnableException] [-DacFxPath \u003cString\u003e] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nPublish-DbaDacPackage [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] -Path \u003cString\u003e -PublishXml \u003cString\u003e -Database \u003cString[]\u003e [-ConnectionString \u003cString[]\u003e] [-GenerateDeploymentScript] [-GenerateDeploymentReport] [-ScriptOnly] [-Type \u003cString\u003e] [-OutputPath \u003cString\u003e] [-IncludeSqlCmdVars] [-EnableException] [-DacFxPath \u003cString\u003e] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Read-DbaAuditFile",
        "Description":  "Read Audit details from *.sqlaudit files.",
        "Tags":  [
                     "ExtendedEvent",
                     "Audit"
                 ],
        "Synopsis":  "Read Audit details from *.sqlaudit files.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Read-DbaAuditFile",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Read-DbaAuditFile",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRead-DbaAuditFile -Path C:\\temp\\logins.sqlaudit\nReturns events from C:\\temp\\logins.sqlaudit.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-ChildItem C:\\temp\\audit\\*.sqlaudit | Read-DbaAuditFile\nReturns events from all .sqlaudit files in C:\\temp\\audit.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaServerAudit -SqlInstance sql2014 -Audit LoginTracker | Read-DbaAuditFile\nReads remote Audit details by accessing the file over the admin UNC share.",
        "Params":  [
                       [
                           "Path",
                           "The path to the *.sqlaudit file. This is relative to the computer executing the command. UNC paths are supported.",
                           "FullName",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Exact",
                           "If this switch is enabled, only an exact search will be used for the Path. By default, this command will add a wildcard to the Path because Eventing uses the file name as a template and adds \r\ncharacters.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Raw",
                           "If this switch is enabled, the Microsoft.SqlServer.XEvent.Linq.PublishedEvent enumeration object will be returned.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Read-DbaAuditFile [-Path] \u003cObject[]\u003e [-Exact] [-Raw] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Read-DbaBackupHeader",
        "Description":  "Reads full, differential and transaction log backups. An online SQL Server is required to parse the backup files and the path specified must be relative to that SQL Server.",
        "Tags":  [
                     "DisasterRecovery",
                     "Backup",
                     "Restore"
                 ],
        "Synopsis":  "Reads and displays detailed information about a SQL Server backup.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Read-DbaBackupHeader",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Read-DbaBackupHeader",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRead-DbaBackupHeader -SqlInstance sql2016 -Path S:\\backups\\mydb\\mydb.bak\nLogs into sql2016 using Windows authentication and reads the local file on sql2016, S:\\backups\\mydb\\mydb.bak.\nIf you are running this command on a workstation and connecting remotely, remember that sql2016 cannot access files on your own workstation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRead-DbaBackupHeader -SqlInstance sql2016 -Path \\\\nas\\sql\\backups\\mydb\\mydb.bak, \\\\nas\\sql\\backups\\otherdb\\otherdb.bak\nLogs into sql2016 and reads two backup files - mydb.bak and otherdb.bak. The SQL Server service account must have rights to read this file.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRead-DbaBackupHeader -SqlInstance . -Path C:\\temp\\myfile.bak -Simple\nLogs into the local workstation (or computer) and shows simplified output about C:\\temp\\myfile.bak. The SQL Server service account must have rights to read this file.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$backupinfo = Read-DbaBackupHeader -SqlInstance . -Path C:\\temp\\myfile.bak\nPS C:\\\u003e $backupinfo.FileList\nDisplays detailed information about each of the datafiles contained in the backupset.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eRead-DbaBackupHeader -SqlInstance . -Path C:\\temp\\myfile.bak -FileList\nAlso returns detailed information about each of the datafiles contained in the backupset.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e\"C:\\temp\\myfile.bak\", \"\\backupserver\\backups\\myotherfile.bak\" | Read-DbaBackupHeader -SqlInstance sql2016  | Where-Object { $_.BackupSize.Megabyte -gt 100 }\nReads the two files and returns only backups larger than 100 MB\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-ChildItem \\\\nas\\sql\\*.bak | Read-DbaBackupHeader -SqlInstance sql2016\nGets a list of all .bak files on the \\\\nas\\sql share and reads the headers using the server named \"sql2016\". This means that the server, sql2016, must have read access to the \\\\nas\\sql share.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eRead-DbaBackupHeader -Path https://dbatoolsaz.blob.core.windows.net/azbackups/restoretime/restoretime_201705131850.bak -AzureCredential AzureBackupUser\nGets the backup header information from the SQL Server backup file stored at https://dbatoolsaz.blob.core.windows.net/azbackups/restoretime/restoretime_201705131850.bak on Azure",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "Path to SQL Server backup file. This can be a full, differential or log backup file. Accepts valid filesystem paths and URLs.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Simple",
                           "If this switch is enabled, fewer columns are returned, giving an easy overview.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "FileList",
                           "If this switch is enabled, detailed information about the files within the backup is returned.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "AzureCredential",
                           "Name of the SQL Server credential that should be used for Azure storage access.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because \r\nit basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Read-DbaBackupHeader [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Path] \u003cObject[]\u003e [-Simple] [-FileList] [[-AzureCredential] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Read-DbaTraceFile",
        "Description":  "Using the fn_trace_gettable function, a trace file is read and returned as a PowerShell object\n\nThis function returns the whole of the trace file. The information is presented in the format that the trace subsystem uses.",
        "Tags":  [
                     "Security",
                     "Trace"
                 ],
        "Synopsis":  "Reads SQL Server trace files",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Read-DbaTraceFile",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRead-DbaTraceFile -SqlInstance sql2016 -Database master, tempdb -Path C:\\traces\\big.trc\nReads the tracefile C:\\traces\\big.trc, stored on the sql2016 sql server. Filters only results that have master or tempdb as the DatabaseName.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRead-DbaTraceFile -SqlInstance sql2016 -Database master, tempdb -Path C:\\traces\\big.trc -TextData \u0027EXEC SP_PROCOPTION\u0027\nReads the tracefile C:\\traces\\big.trc, stored on the sql2016 sql server.\r\nFilters only results that have master or tempdb as the DatabaseName and that have \u0027EXEC SP_PROCOPTION\u0027 somewhere in the text.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRead-DbaTraceFile -SqlInstance sql2016 -Path C:\\traces\\big.trc -Where \"LinkedServerName = \u0027myls\u0027 and StartTime \u003e \u00275/30/2017 4:27:52 PM\u0027\"\nReads the tracefile C:\\traces\\big.trc, stored on the sql2016 sql server.\r\nFilters only results where LinkServerName = myls and StartTime is greater than \u00275/30/2017 4:27:52 PM\u0027.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaTrace -SqlInstance sql2014 | Read-DbaTraceFile\nReads every trace file on sql2014",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "Path",
                           "Path to the trace file. This path is relative to the SQL Server instance.",
                           "",
                           false,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "Database",
                           "Search for results only with specific DatabaseName. Uses IN for comparisons.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Login",
                           "Search for results only with specific Logins. Uses IN for comparisons.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Spid",
                           "Search for results only with specific Spids. Uses IN for comparisons.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EventClass",
                           "Search for results only with specific EventClasses. Uses IN for comparisons.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ObjectType",
                           "Search for results only with specific ObjectTypes. Uses IN for comparisons.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ErrorId",
                           "Search for results only with specific Errors. Filters \u0027Error in ($ErrorId)\u0027  Uses IN for comparisons.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EventSequence",
                           "Search for results only with specific EventSequences. Uses IN for comparisons.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "TextData",
                           "Search for results only with specific TextData. Uses LIKE for comparisons.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ApplicationName",
                           "Search for results only with specific ApplicationNames. Uses LIKE for comparisons.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ObjectName",
                           "Search for results only with specific ObjectNames. Uses LIKE for comparisons.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Where",
                           "Custom where clause - use without the word \"WHERE\". Here are the available columns:\nTextData\r\nBinaryData\r\nDatabaseID\r\nTransactionID\r\nLineNumber\r\nNTUserName\r\nNTDomainName\r\nHostName\r\nClientProcessID\r\nApplicationName\r\nLoginName\r\nSPID\r\nDuration\r\nStartTime\r\nEndTime\r\nReads\r\nWrites\r\nCPU\r\nPermissions\r\nSeverity\r\nEventSubClass\r\nObjectID\r\nSuccess\r\nIndexID\r\nIntegerData\r\nServerName\r\nEventClass\r\nObjectType\r\nNestLevel\r\nState\r\nError\r\nMode\r\nHandle\r\nObjectName\r\nDatabaseName\r\nFileName\r\nOwnerName\r\nRoleName\r\nTargetUserName\r\nDBUserName\r\nLoginSid\r\nTargetLoginName\r\nTargetLoginSid\r\nColumnPermissions\r\nLinkedServerName\r\nProviderName\r\nMethodName\r\nRowCounts\r\nRequestID\r\nXactSequence\r\nEventSequence\r\nBigintData1\r\nBigintData2\r\nGUID\r\nIntegerData2\r\nObjectID2\r\nType\r\nOwnerID\r\nParentName\r\nIsSystem\r\nOffset\r\nSourceDatabaseID\r\nSqlHandle\r\nSessionLoginName\r\nPlanHandle\r\nGroupID",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Read-DbaTraceFile [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Path \u003cString[]\u003e] [-Database \u003cString[]\u003e] [-Login \u003cString[]\u003e] [-Spid \u003cInt32[]\u003e] [-EventClass \u003cString[]\u003e] [-ObjectType \u003cString[]\u003e] [-ErrorId \u003cInt32[]\u003e] [-EventSequence \u003cInt32[]\u003e] [-TextData \u003cString[]\u003e] [-ApplicationName \u003cString[]\u003e] [-ObjectName \u003cString[]\u003e] [-Where \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Read-DbaTransactionLog",
        "Description":  "Using the fn_dblog function, the live transaction log is read and returned as a PowerShell object\n\nThis function returns the whole of the log. The information is presented in the format that the logging subsystem uses.\n\nA soft limit of 0.5GB of log as been implemented. This is based on testing. This limit can be overridden\nat the users request, but please be aware that this may have an impact on your target databases and on the\nsystem running this function",
        "Tags":  [
                     "Database",
                     "Log",
                     "LogFile"
                 ],
        "Synopsis":  "Reads the live Transaction log from specified SQL Server Database",
        "Alias":  "",
        "Author":  "Stuart Moore (@napalmgram), stuart-moore.com",
        "CommandName":  "Read-DbaTransactionLog",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$Log = Read-DbaTransactionLog -SqlInstance sql2016 -Database MyDatabase\nWill read the contents of the transaction log of MyDatabase on SQL Server Instance sql2016 into the local PowerShell object $Log\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$Log = Read-DbaTransactionLog -SqlInstance sql2016 -Database MyDatabase -IgnoreLimit\nWill read the contents of the transaction log of MyDatabase on SQL Server Instance sql2016 into the local PowerShell object $Log, ignoring the recommendation of not returning more that 0.5GB of log",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "A credential to use to connect to the SQL Instance rather than using Windows Authentication",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Database to read the transaction log of",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "IgnoreLimit",
                           "Switch to indicate that you wish to bypass the recommended limits of the function",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "RowLimit",
                           "Will limit the number of rows returned from the transaction log",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Read-DbaTransactionLog [-SqlInstance] \u003cDbaInstanceParameter\u003e [-SqlCredential \u003cPSCredential\u003e] -Database \u003cObject\u003e [-IgnoreLimit] [-RowLimit \u003cInt32\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Read-DbaXEFile",
        "Description":  "Read XEvents from a *.xel or *.xem file.",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "Read XEvents from a *.xel or *.xem file.",
        "Alias":  "Read-DbaXEventFile",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Read-DbaXEFile",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Read-DbaXEFile",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRead-DbaXEFile -Path C:\\temp\\deadocks.xel\nReturns events from C:\\temp\\deadocks.xel.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-ChildItem C:\\temp\\xe\\*.xel | Read-DbaXEFile\nReturns events from all .xel files in C:\\temp\\xe.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sql2014 -Session deadlocks | Read-DbaXEFile\nReads remote XEvents by accessing the file over the admin UNC share.",
        "Params":  [
                       [
                           "Path",
                           "The path to the *.xem or *.xem file. This is relative to the computer executing the command. UNC paths are supported.",
                           "FullName",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Exact",
                           "If this switch is enabled, only an exact search will be used for the Path. By default, this command will add a wildcard to the Path because Eventing uses the file name as a template and adds \r\ncharacters.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Raw",
                           "If this switch is enabled, the Microsoft.SqlServer.XEvent.Linq.PublishedEvent enumeration object will be returned.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Read-DbaXEFile [-Path] \u003cObject[]\u003e [-Exact] [-Raw] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Register-DbatoolsConfig",
        "Description":  "Registers an existing configuration object in registry.\nThis allows simple persisting of settings across powershell consoles.\nIt also can be used to generate a registry template, which can then be used to create policies.",
        "Synopsis":  "Registers an existing configuration object in registry.",
        "Alias":  "Register-DbaConfig",
        "CommandName":  "Register-DbatoolsConfig",
        "Availability":  "Windows only",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbatoolsConfig message.style.* | Register-DbatoolsConfig\nRetrieves all configuration items that that start with message.style. and registers them in registry for the current user.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRegister-DbatoolsConfig -FullName \"message.consoleoutput.disable\" -Scope SystemDefault\nRetrieves the configuration item \"message.consoleoutput.disable\" and registers it in registry as the default setting for all users on this machine.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRegister-DbatoolsConfig -Module Message -Scope SystemMandatory\nRetrieves all configuration items of the module Message, then registers them in registry to enforce them for all users on the current system.",
        "Params":  [
                       [
                           "Config",
                           "The configuration object to write to registry.\r\nCan be retrieved using Get-DbatoolsConfig.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "FullName",
                           "The full name of the setting to be written to registry.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Module",
                           "The name of the module, whose settings should be written to registry.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "Default: \"*\"\r\nUsed in conjunction with the -Module parameter to restrict the number of configuration items written to registry.",
                           "",
                           false,
                           "false",
                           "*"
                       ],
                       [
                           "Scope",
                           "Default: UserDefault\r\nWho will be affected by this export how? Current user or all? Default setting or enforced?\r\nLegal values: UserDefault, UserMandatory, SystemDefault, SystemMandatory",
                           "",
                           false,
                           "false",
                           "UserDefault"
                       ],
                       [
                           "EnableException",
                           "This parameters disables user-friendly warnings and enables the throwing of exceptions.\r\nThis is less user friendly, but allows catching exceptions in calling scripts.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Register-DbatoolsConfig [[-Config] \u003cConfig[]\u003e] [[-FullName] \u003cString[]\u003e] [-Scope {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [-EnableException] [\u003cCommonParameters\u003e]\nRegister-DbatoolsConfig [-Module] \u003cString\u003e [[-Name] \u003cString\u003e] [-Scope {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaAgDatabase",
        "Description":  "Removes a database from an availability group on a SQL Server instance.",
        "Tags":  [
                     "AvailabilityGroup",
                     "HA",
                     "AG"
                 ],
        "Synopsis":  "Removes a database from an availability group on a SQL Server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Remove-DbaAgDatabase",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Remove-DbaAgDatabase",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaAgDatabase -SqlInstance sqlserver2012 -AvailabilityGroup ag1, ag2 -Confirm:$false\nRemoves the ag1 and ag2 availability groups on sqlserver2012.  Does not prompt for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sqlserver2012 -AvailabilityGroup availabilitygroup1 | Remove-DbaAgDatabase\nRemoves the availability groups returned from the Get-DbaAvailabilityGroup function. Prompts for confirmation.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database or databases to remove.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityGroup",
                           "Only remove databases from specific availability groups.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaDatabase",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaAgDatabase [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaAgentJob",
        "Description":  "Remove-DbaAgentJob removes a job in the SQL Server Agent.",
        "Tags":  [
                     "Agent",
                     "Job"
                 ],
        "Synopsis":  "Remove-DbaAgentJob removes a job.",
        "Alias":  "",
        "Author":  "Sander Stad (@sqlstad, sqlstad.nl)",
        "CommandName":  "Remove-DbaAgentJob",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Remove-DbaAgentJob",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaAgentJob -SqlInstance sql1 -Job Job1\nRemoves the job from the instance with the name Job1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGetDbaAgentJob -SqlInstance sql1 -Job Job1 | Remove-DbaAgentJob -KeepHistory\nRemoves teh job but keeps the history\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaAgentJob -SqlInstance sql1 -Job Job1 -KeepUnusedSchedule\nRemoves the job but keeps the unused schedules\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eRemove-DbaAgentJob -SqlInstance sql1, sql2, sql3 -Job Job1\nRemoves the job from multiple servers",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Job",
                           "The name of the job. Can be null if the the job id is being used.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "KeepHistory",
                           "Specifies to keep the history for the job. By default history is deleted.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "KeepUnusedSchedule",
                           "Specifies to keep the schedules attached to this job if they are not attached to any other job.\r\nBy default the unused schedule is deleted.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Mode",
                           "Default: Strict\r\nHow strict does the command take lesser issues?\r\nStrict: Interrupt if the job specified doesn\u0027t exist.\r\nLazy:   Silently skip over jobs that don\u0027t exist.",
                           "",
                           false,
                           "false",
                           "(Get-DbatoolsConfigValue -FullName \u0027message.mode.default\u0027 -Fallback \"Strict\")"
                       ],
                       [
                           "InputObject",
                           "Accepts piped input from Get-DbaAgentJob",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaAgentJob [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Job] \u003cObject[]\u003e] [-KeepHistory] [-KeepUnusedSchedule] [[-Mode] {Strict | Lazy | Report}] [[-InputObject] \u003cJob[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaAgentJobCategory",
        "Description":  "Remove-DbaAgentJobCategory makes it possible to remove a job category.\nBe assured that the category you want to remove is not used with other jobs. If another job uses this category it will be get the category [Uncategorized (Local)].",
        "Tags":  [
                     "Agent",
                     "Job",
                     "JobCategory"
                 ],
        "Synopsis":  "Remove-DbaAgentJobCategory removes a job category.",
        "Alias":  "",
        "Author":  "Sander Stad (@sqlstad, sqlstad.nl)",
        "CommandName":  "Remove-DbaAgentJobCategory",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Remove-DbaAgentJobCategory",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaAgentJobCategory -SqlInstance sql1 -Category \u0027Category 1\u0027\nRemove the job category Category 1 from the instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaAgentJobCategory -SqlInstance sql1 -Category Category1, Category2, Category3\nRemove multiple job categories from the instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaAgentJobCategory -SqlInstance sql1, sql2, sql3 -Category Category1, Category2, Category3\nRemove multiple job categories from the multiple instances.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Category",
                           "The name of the category",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "The force parameter will ignore some errors in the parameters and assume defaults.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaAgentJobCategory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Category] \u003cString[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaAgentJobStep",
        "Description":  "Removes a job step from a SQL Server Agent job.",
        "Tags":  [
                     "Agent",
                     "Job",
                     "JobStep"
                 ],
        "Synopsis":  "Removes a step from the specified SQL Agent job.",
        "Alias":  "",
        "Author":  "Sander Stad (@sqlstad), sqlstad.nl",
        "CommandName":  "Remove-DbaAgentJobStep",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Remove-DbaAgentJobStep",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaAgentJobStep -SqlInstance sql1 -Job Job1 -StepName Step1\nRemove \u0027Step1\u0027 from job \u0027Job1\u0027 on sql1.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaAgentJobStep -SqlInstance sql1 -Job Job1, Job2, Job3 -StepName Step1\nRemove the job step from multiple jobs.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaAgentJobStep -SqlInstance sql1, sql2, sql3 -Job Job1 -StepName Step1\nRemove the job step from the job on multiple servers.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003esql1, sql2, sql3 | Remove-DbaAgentJobStep -Job Job1 -StepName Step1\nRemove the job step from the job on multiple servers using pipeline.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Job",
                           "The name of the job.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "StepName",
                           "The name of the job step.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Mode",
                           "Default: Strict\r\nHow strict does the command take lesser issues?\r\nStrict: Interrupt if the configuration already has the same value as the one specified.\r\nLazy:   Silently skip over instances that already have this configuration at the specified value.",
                           "",
                           false,
                           "false",
                           "(Get-DbatoolsConfigValue -Name \u0027message.mode.default\u0027 -Fallback \"Strict\")"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaAgentJobStep [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Job] \u003cObject[]\u003e [-StepName] \u003cString\u003e [[-Mode] {Strict | Lazy | Report}] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaAgentSchedule",
        "Description":  "Remove-DbaAgentJobSchedule removes a job in the SQL Server Agent.",
        "Tags":  [
                     "Agent",
                     "Job",
                     "Schedule"
                 ],
        "Synopsis":  "Remove-DbaAgentJobSchedule removes a job schedule.",
        "Alias":  "",
        "Author":  "Sander Stad (@sqlstad), sqlstad.nl",
        "CommandName":  "Remove-DbaAgentSchedule",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Remove-DbaAgentJobSchedule",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaAgentSchedule -SqlInstance sql1 -Schedule weekly\nRemove the schedule weekly\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaAgentSchedule -SqlInstance sql1 -Schedule weekly -Force\nRemove the schedule weekly from the job even if the schedule is being used by another job.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaAgentSchedule -SqlInstance sql1 -Schedule daily, weekly\nRemove multiple schedule\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eRemove-DbaAgentSchedule -SqlInstance sql1, sql2, sql3 -Schedule daily, weekly\nRemove the schedule on multiple servers for multiple schedules\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003esql1, sql2, sql3 | Remove-DbaAgentSchedule -Schedule daily, weekly\nRemove the schedule on multiple servers using pipe line\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaAgentSchedule -SqlInstance sql1 -Schedule sched1, sched2, sched3 | Remove-DbaAgentSchedule\nRemove the schedules using a pipeline",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Schedule",
                           "The name of the job schedule.",
                           "Schedules",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "A collection of schedule (such as returned by Get-DbaAgentSchedule), to be removed.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "The force parameter will ignore some errors in the parameters and assume defaults.\r\nIt will also remove the any present schedules with the same name for the specific job.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaAgentSchedule -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -Schedule \u003cObject[]\u003e [-EnableException] [-Force] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaAgentSchedule [-SqlCredential \u003cPSCredential\u003e] -InputObject \u003cScheduleBase[]\u003e [-EnableException] [-Force] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaAgListener",
        "Description":  "Removes a listener from an availability group on a SQL Server instance.",
        "Tags":  [
                     "AvailabilityGroup",
                     "HA",
                     "AG"
                 ],
        "Synopsis":  "Removes a listener from an availability group on a SQL Server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Remove-DbaAgListener",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Remove-DbaAgListener",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaAgListener -SqlInstance sqlserver2012 -AvailabilityGroup ag1, ag2 -Confirm:$false\nRemoves the ag1 and ag2 availability groups on sqlserver2012. Does not prompt for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sqlserver2012 -AvailabilityGroup availabilitygroup1 | Remove-DbaAgListener\nRemoves the listeners returned from the Get-DbaAvailabilityGroup function. Prompts for confirmation.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Listener",
                           "The listener or listeners to remove.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityGroup",
                           "Only remove listeners from specific availability groups.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaListener",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaAgListener [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Listener] \u003cString[]\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-InputObject] \u003cAvailabilityGroupListener[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaAgReplica",
        "Description":  "Removes availability group replicas from availability groups.",
        "Tags":  [
                     "AG",
                     "HA",
                     "AvailabilityGroup",
                     "Replica"
                 ],
        "Synopsis":  "Removes availability group replicas from availability groups.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Remove-DbaAgReplica",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Remove-DbaAgReplica",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaAgReplica -SqlInstance sql2017a -AvailabilityGroup SharePoint -Replica sp1\nRemoves the sp1 replica from the SharePoint ag on sql2017a. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaAgReplica -SqlInstance sql2017a | Select-Object *\nReturns full object properties on all availability group replicas found on sql2017a",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityGroup",
                           "The specific availability group to query.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Replica",
                           "The replica to remove.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piped input from Get-DbaAgReplica.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaAgReplica [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-Replica] \u003cString[]\u003e] [[-InputObject] \u003cAvailabilityReplica[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaAvailabilityGroup",
        "Description":  "Removes availability groups on a SQL Server instance.\n\nIf possible, remove the availability group only while connected to the server instance that hosts the primary replica.\nWhen the availability group is dropped from the primary replica, changes are allowed in the former primary databases (without high availability protection).\nDeleting an availability group from a secondary replica leaves the primary replica in the RESTORING state, and changes are not allowed on the databases.\n\nAvoid dropping an availability group when the Windows Server Failover Clustering (WSFC) cluster has no quorum.\nIf you must drop an availability group while the cluster lacks quorum, the metadata availability group that is stored in the cluster is not removed.\nAfter the cluster regains quorum, you will need to drop the availability group again to remove it from the WSFC cluster.\n\nFor more information: https://docs.microsoft.com/en-us/sql/t-sql/statements/drop-availability-group-transact-sql",
        "Tags":  [
                     "AvailabilityGroup",
                     "HA",
                     "AG"
                 ],
        "Synopsis":  "Removes availability groups on a SQL Server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Remove-DbaAvailabilityGroup",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Remove-DbaAvailabilityGroup",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaAvailabilityGroup -SqlInstance sqlserver2012 -AllAvailabilityGroups\nRemoves all availability groups on the sqlserver2014 instance. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaAvailabilityGroup -SqlInstance sqlserver2012 -AvailabilityGroup ag1, ag2 -Confirm:$false\nRemoves the ag1 and ag2 availability groups on sqlserver2012.  Does not prompt for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sqlserver2012 -AvailabilityGroup availabilitygroup1 | Remove-DbaAvailabilityGroup\nRemoves the availability groups returned from the Get-DbaAvailabilityGroup function. Prompts for confirmation.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityGroup",
                           "Only remove specific availability groups.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AllAvailabilityGroups",
                           "Remove all availability groups on an instance.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaAvailabilityGroup.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaAvailabilityGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [-AllAvailabilityGroups] [[-InputObject] \u003cAvailabilityGroup[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaBackup",
        "Description":  "Removes SQL Server backups from disk.\n\nProvides all of the same functionality for removing SQL backups from disk as a standard maintenance plan would.\n\nAs an addition you have the ability to check the Archive bit on files before deletion. This will allow you to ensure backups have been archived to your archive location before removal.\n\nAlso included is the ability to remove empty folders as part of this cleanup activity.",
        "Tags":  [
                     "Storage",
                     "DisasterRecovery",
                     "Backup"
                 ],
        "Synopsis":  "Removes SQL Server backups from disk.",
        "Alias":  "",
        "Author":  "Chris Sommer (@cjsommer), www.cjsommer.com",
        "CommandName":  "Remove-DbaBackup",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Remove-DbaBackup",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaBackup -Path \u0027C:\\MSSQL\\SQL Backup\\\u0027 -BackupFileExtension trn -RetentionPeriod 48h\n\u0027*.trn\u0027 files in \u0027C:\\MSSQL\\SQL Backup\\\u0027 and all subdirectories that are more than 48 hours old will be removed.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaBackup -Path \u0027C:\\MSSQL\\SQL Backup\\\u0027 -BackupFileExtension trn -RetentionPeriod 48h -WhatIf\nSame as example #1, but doesn\u0027t actually remove any files. The function will instead show you what would be done.\r\nThis is useful when first experimenting with using the function.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaBackup -Path \u0027C:\\MSSQL\\Backup\\\u0027 -BackupFileExtension bak -RetentionPeriod 7d -CheckArchiveBit\n\u0027*.bak\u0027 files in \u0027C:\\MSSQL\\Backup\\\u0027 and all subdirectories that are more than 7 days old will be removed, but only if the files have been backed up to another location as verified by checking the \r\nArchive bit.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eRemove-DbaBackup -Path \u0027C:\\MSSQL\\Backup\\\u0027 -BackupFileExtension bak -RetentionPeriod 1w -RemoveEmptyBackupFolder\n\u0027*.bak\u0027 files in \u0027C:\\MSSQL\\Backup\\\u0027 and all subdirectories that are more than 1 week old will be removed. Any folders left empty will be removed as well.",
        "Params":  [
                       [
                           "Path",
                           "Specifies the name of the base level folder to search for backup files. Deletion of backup files will be recursive from this location.",
                           "BackupFolder",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "BackupFileExtension",
                           "Specifies the filename extension of the backup files you wish to remove (typically \u0027bak\u0027, \u0027trn\u0027 or \u0027log\u0027). Do not include the period.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "RetentionPeriod",
                           "Specifies the retention period for backup files. Correct format is ##U.\n## is the retention value and must be an integer value\r\nU signifies the units where the valid units are:\r\nh = hours\r\nd = days\r\nw = weeks\r\nm = months\nFormatting Examples:\r\n\u002748h\u0027 = 48 hours\r\n\u00277d\u0027 = 7 days\r\n\u00274w\u0027 = 4 weeks\r\n\u00271m\u0027 = 1 month",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "CheckArchiveBit",
                           "If this switch is enabled, the filesystem Archive bit is checked before deletion. If this bit is set (which translates to \"it has not been backed up to another location yet\", the file won\u0027t be \r\ndeleted.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "RemoveEmptyBackupFolder",
                           "If this switch is enabled, empty folders will be removed after the cleanup process is complete.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.i",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaBackup [-Path] \u003cString\u003e [-BackupFileExtension] \u003cString\u003e [-RetentionPeriod] \u003cString\u003e [-CheckArchiveBit] [-RemoveEmptyBackupFolder] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaClientAlias",
        "Description":  "Removes a sql alias for the specified server by altering HKLM:\\SOFTWARE\\Microsoft\\MSSQLServer\\Client - mimics cliconfg.exe.",
        "Tags":  "Alias",
        "Synopsis":  "Removes a sql alias for the specified server - mimics cliconfg.exe",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Remove-DbaClientAlias",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Remove-DbaClientAlias",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaClientAlias -ComputerName workstationx -Alias sqlps\nRemoves the sqlps SQL client alias on workstationx\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaClientAlias | Remove-DbaClientAlias\nRemoves all SQL Server client aliases on the local computer",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer where the alias will be created.",
                           "",
                           false,
                           "true (ByPropertyName)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to remote computers using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Alias",
                           "The alias or array of aliases to be deleted",
                           "AliasName",
                           true,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaClientAlias [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-Alias] \u003cString[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaCmConnection",
        "Description":  "Removes connection objects from the connection cache used for remote computer management.",
        "Tags":  [
                     "ComputerManagement",
                     "CIM"
                 ],
        "Synopsis":  "Removes connection objects from the connection cache used for remote computer management.",
        "Alias":  "",
        "Author":  "Friedrich Weinmann (@FredWeinmann)",
        "CommandName":  "Remove-DbaCmConnection",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Remove-DbaCmConnection",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaCmConnection -ComputerName sql2014\nRemoves the cached connection to the server sql2014 from the cache.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCmConnection | Remove-DbaCmConnection\nClears the entire connection cache.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer. Accepts both text as well as the output of Get-DbaCmConnection.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaCmConnection [-ComputerName] \u003cDbaCmConnectionParameter[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaCmsRegServer",
        "Description":  "Removes registered servers found in SQL Server Central Management Server (CMS).",
        "Tags":  [
                     "RegisteredServer",
                     "CMS"
                 ],
        "Synopsis":  "Removes registered servers found in SQL Server Central Management Server (CMS).",
        "Alias":  "Remove-DbaRegisteredServer",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Remove-DbaCmsRegServer",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Remove-DbaCmsRegServer",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaCmsRegServer -SqlInstance sql2012 -Group HR, Accounting\nRemoves all servers from the HR and Accounting groups on sql2012\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaCmsRegServer -SqlInstance sql2012 -Group HR\\Development\nRemoves all servers from the HR and sub-group Development from the CMS on sql2012.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaCmsRegServer -SqlInstance sql2012 -Confirm:$false\nRemoves all registered servers on sql2012 and turns off all prompting",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "Specifies one or more names to include. Name is the visible name in SSMS CMS interface (labeled Registered Server Name)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ServerName",
                           "Specifies one or more server names to include. Server Name is the actual instance name (labeled Server Name)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Group",
                           "Specifies one or more groups to include from SQL Server Central Management Server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows results from Get-DbaCmsRegServer to be piped in",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaCmsRegServer [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString[]\u003e] [[-ServerName] \u003cString[]\u003e] [[-Group] \u003cString[]\u003e] [[-InputObject] \u003cRegisteredServer[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaCmsRegServerGroup",
        "Description":  "Returns an array of Server Groups found in the CMS.",
        "Tags":  [
                     "RegisteredServer",
                     "CMS"
                 ],
        "Synopsis":  "Gets list of Server Groups objects stored in SQL Server Central Management Server (CMS).",
        "Alias":  "Remove-DbaRegisteredServerGroup",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Remove-DbaCmsRegServerGroup",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Remove-DbaCmsRegServerGroup",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaCmsRegServerGroup -SqlInstance sql2012 -Group HR, Accounting\nRemoves the HR and Accounting groups on sql2012\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaCmsRegServerGroup -SqlInstance sql2012 -Group HR\\Development -Confirm:$false\nRemoves the Development subgroup within the HR group on sql2012 and turns off all prompting",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "Specifies one or more groups to include from SQL Server Central Management Server.",
                           "Group",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows results from Get-DbaCmsRegServerGroup to be piped in",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaCmsRegServerGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString[]\u003e] [[-InputObject] \u003cServerGroup[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaComputerCertificate",
        "Description":  "Removes a computer certificate from a local or remote compuer",
        "Tags":  "Certificate",
        "Synopsis":  "Removes a computer certificate - useful for removing easily certs from remote computers",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Remove-DbaComputerCertificate",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Remove-DbaComputerCertificate",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaComputerCertificate -ComputerName Server1 -Thumbprint C2BBE81A94FEE7A26FFF86C2DFDAF6BFD28C6C94\nRemoves certificate with thumbprint C2BBE81A94FEE7A26FFF86C2DFDAF6BFD28C6C94 in the LocalMachine store on Server1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaComputerCertificate | Where-Object Thumbprint -eq E0A071E387396723C45E92D42B2D497C6A182340 | Remove-DbaComputerCertificate\nRemoves certificate using the pipeline\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaComputerCertificate -ComputerName Server1 -Thumbprint C2BBE81A94FEE7A26FFF86C2DFDAF6BFD28C6C94 -Store User -Folder My\nRemoves certificate with thumbprint C2BBE81A94FEE7A26FFF86C2DFDAF6BFD28C6C94 in the User\\My (Personal) store on Server1",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer. Defaults to localhost.",
                           "ServerInstance,SqlServer,SqlInstance",
                           false,
                           "false",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to $ComputerName using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Thumbprint",
                           "The thumbprint of the certificate object",
                           "",
                           true,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "Store",
                           "Certificate store - defaults to LocalMachine (otherwise exceptions can be thrown on remote connections)",
                           "",
                           false,
                           "false",
                           "LocalMachine"
                       ],
                       [
                           "Folder",
                           "Certificate folder",
                           "",
                           false,
                           "false",
                           "My"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaComputerCertificate [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-Thumbprint] \u003cString[]\u003e [[-Store] \u003cString\u003e] [[-Folder] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaDatabase",
        "Description":  "Tries a bunch of different ways to remove a database or two or more.",
        "Tags":  [
                     "Delete",
                     "Databases"
                 ],
        "Synopsis":  "Drops a database, hopefully even the really stuck ones.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Remove-DbaDatabase",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Remove-DbaDatabase",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDatabase -SqlInstance sql2016 -Database containeddb\nPrompts then removes the database containeddb on SQL Server sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDatabase -SqlInstance sql2016 -Database containeddb, mydb\nPrompts then removes the databases containeddb and mydb on SQL Server sql2016\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaDatabase -SqlInstance sql2016 -Database containeddb -Confirm:$false\nDoes not prompt and swiftly removes containeddb on SQL Server sql2016\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance server\\instance -ExcludeSystem | Remove-DbaDatabase\nRemoves all the user databases from server\\instance\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance server\\instance -ExcludeSystem | Remove-DbaDatabase -Confirm:$false\nRemoves all the user databases from server\\instance without any confirmation",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "A collection of databases (such as returned by Get-DbaDatabase), to be removed.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "IncludeSystemDb",
                           "Use this switch to disable any kind of verbose messages",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaDatabase [-SqlCredential \u003cPSCredential\u003e] [-IncludeSystemDb] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaDatabase -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -Database \u003cObject[]\u003e [-IncludeSystemDb] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaDatabase [-SqlCredential \u003cPSCredential\u003e] -InputObject \u003cDatabase[]\u003e [-IncludeSystemDb] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaDatabaseSafely",
        "Description":  "Performs a DBCC CHECKDB on the database, backs up the database with Checksum and verify only to a final (golden) backup location, creates an Agent Job to restore from that backup, drops the database, runs the agent job to restore the database, performs a DBCC CHECKDB and drops the database.\n\nWith huge thanks to Grant Fritchey and his verify your backups video. Take a look, it\u0027s only 3 minutes long. http://sqlps.io/backuprant",
        "Tags":  [
                     "Database",
                     "Remove"
                 ],
        "Synopsis":  "Safely removes a SQL Database and creates an Agent Job to restore it.",
        "Alias":  "Remove-SqlDatabaseSafely",
        "Author":  "Rob Sewell (@SQLDBAWithBeard), sqldbawithabeard.com",
        "CommandName":  "Remove-DbaDatabaseSafely",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Remove-DbaDatabaseSafely",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDatabaseSafely -SqlInstance \u0027Fade2Black\u0027 -Database RideTheLightning -BackupFolder \u0027C:\\MSSQL\\Backup\\Rationalised - DO NOT DELETE\u0027\nPerforms a DBCC CHECKDB on database RideTheLightning on server Fade2Black. If there are no errors, the database is backup to the folder C:\\MSSQL\\Backup\\Rationalised - DO NOT DELETE. Then, an Agent \r\njob to restore the database from that backup is created. The database is then dropped, the Agent job to restore it run, a DBCC CHECKDB run against the restored database, and then it is dropped again.\nAny DBCC errors will be written to your documents folder\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$Database = \u0027DemoNCIndex\u0027,\u0027RemoveTestDatabase\u0027\nPS C:\\\u003e Remove-DbaDatabaseSafely -SqlInstance \u0027Fade2Black\u0027 -Database $Database -BackupFolder \u0027C:\\MSSQL\\Backup\\Rationalised - DO NOT DELETE\u0027\nPerforms a DBCC CHECKDB on two databases, \u0027DemoNCIndex\u0027 and \u0027RemoveTestDatabase\u0027 on server Fade2Black. Then, an Agent job to restore each database from those backups is created. The databases are \r\nthen dropped, the Agent jobs to restore them run, a DBCC CHECKDB run against the restored databases, and then they are dropped again.\nAny DBCC errors will be written to your documents folder\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaDatabaseSafely -SqlInstance \u0027Fade2Black\u0027 -Destination JusticeForAll -Database RideTheLightning -BackupFolder \u0027\\\\BACKUPSERVER\\BACKUPSHARE\\MSSQL\\Rationalised - DO NOT DELETE\u0027\nPerforms a DBCC CHECKDB on database RideTheLightning on server Fade2Black. If there are no errors, the database is backup to the folder \\\\BACKUPSERVER\\BACKUPSHARE\\MSSQL\\Rationalised - DO NOT DELETE . \r\nThen, an Agent job is created on server JusticeForAll to restore the database from that backup is created. The database is then dropped on Fade2Black, the Agent job to restore it on JusticeForAll is \r\nrun, a DBCC CHECKDB run against the restored database, and then it is dropped from JusticeForAll.\nAny DBCC errors will be written to your documents folder\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eRemove-DbaDatabaseSafely -SqlInstance IronMaiden -Database $Database -Destination TheWildHearts -BackupFolder Z:\\Backups -NoDbccCheckDb -JobOwner \u0027THEBEARD\\Rob\u0027\nFor the databases $Database on the server IronMaiden a DBCC CHECKDB will not be performed before backing up the databases to the folder Z:\\Backups. Then, an Agent job is created on server \r\nTheWildHearts with a Job Owner of THEBEARD\\Rob to restore each database from that backup using the instance\u0027s default file paths. The database(s) is(are) then dropped on IronMaiden, the Agent job(s) \r\nrun, a DBCC CHECKDB run on the restored database(s), and then the database(s) is(are) dropped.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eRemove-DbaDatabaseSafely -SqlInstance IronMaiden -Database $Database -Destination TheWildHearts -BackupFolder Z:\\Backups\nThe databases $Database on the server IronMaiden will be backed up the to the folder Z:\\Backups. Then, an Agent job is created on server TheWildHearts with a Job Owner of THEBEARD\\Rob to restore each \r\ndatabase from that backup using the instance\u0027s default file paths. The database(s) is(are) then dropped on IronMaiden, the Agent job(s) run, a DBCC CHECKDB run on the restored database(s), and then \r\nthe database(s) is(are) dropped.\nIf there is a DBCC Error, the function  will continue to perform rest of the actions and will create an Agent job with \u0027DBCCERROR\u0027 in the name and a Backup file with \u0027DBCCError\u0027 in the name.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies one or more databases to remove.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "If specified, Agent jobs will be created on this server. By default, the jobs will be created on the server specified by SqlInstance. You must have sysadmin access and the server must be SQL Server \r\n2000 or higher. The SQL Agent service will be started if it is not already running.",
                           "",
                           false,
                           "false",
                           "$sqlinstance"
                       ],
                       [
                           "DestinationCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NoDbccCheckDb",
                           "If this switch is enabled, the initial DBCC CHECK DB will be skipped. This will make the process quicker but will also allow you to create an Agent job that restores a database backup containing a \r\ncorrupt database.\nA second DBCC CHECKDB is performed on the restored database so you will still be notified BUT USE THIS WITH CARE.",
                           "NoCheck",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "BackupFolder",
                           "Specifies the path to a folder where the final backups of the removed databases will be stored. If you are using separate source and destination servers, you must specify a UNC path such as  \r\n\\\\SERVER1\\BACKUPSHARE\\",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "CategoryName",
                           "Specifies the Category Name for the Agent job that is created for restoring the database(s). By default, the name is \"Rationalisation\".",
                           "",
                           false,
                           "false",
                           "Rationalisation"
                       ],
                       [
                           "JobOwner",
                           "Specifies the name of the account which will own the Agent jobs. By default, sa is used.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AllDatabases",
                           "If this switch is enabled, all user databases on the server will be removed. This is useful when decommissioning a server. You should use a Destination with this switch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "BackupCompression",
                           "If this switch is enabled, compression will be used for the backup regardless of the SQL Server instance setting. By default, the SQL Server instance setting for backup compression is used.",
                           "",
                           false,
                           "false",
                           "Default"
                       ],
                       [
                           "ReuseSourceFolderStructure",
                           "If this switch is enabled, the source folder structure will be used when restoring instead of using the destination instance default folder structure.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "If this switch is enabled, all actions will be performed even if DBCC errors are detected. An Agent job will be created with \u0027DBCCERROR\u0027 in the name and the backup file will have \u0027DBCC\u0027 in its name.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaDatabaseSafely [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-Destination] \u003cDbaInstanceParameter\u003e] [[-DestinationCredential] \u003cPSCredential\u003e] [-NoDbccCheckDb] [-BackupFolder] \u003cString\u003e [[-CategoryName] \u003cString\u003e] [[-JobOwner] \u003cString\u003e] [-AllDatabases] [[-BackupCompression] \u003cString\u003e] [-ReuseSourceFolderStructure] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaDbBackupRestoreHistory",
        "Description":  "Reduces the size of the backup and restore history tables by deleting the entries for backup sets.\n\nCan be used at server level, in this case a retention period -KeepDays can be set (default is 30 days).\nCan also be used at database level, in this case the complete history for the database(s) is deleted.\n\nThe backup and restore history tables reside in the msdb database.\n\nTo periodically remove old data from backup and restore history tables it is recommended to schedule the agent job sp_delete_backuphistory from the\nSQL Server Maintenance Solution created by Ola Hallengren (https://ola.hallengren.com).",
        "Tags":  "Delete",
        "Synopsis":  "Reduces the size of the backup and restore history tables by deleting old entries for backup sets.",
        "Alias":  "",
        "Author":  "IJeb Reitsma",
        "CommandName":  "Remove-DbaDbBackupRestoreHistory",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Remove-DbaDbBackupRestoreHistory",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbBackupRestoreHistory -SqlInstance sql2016\nPrompts for confirmation then deletes backup and restore history on SQL Server sql2016 older than 30 days (default period)\nPS C:\\\u003e Remove-DbaDbBackupRestoreHistory -SqlInstance sql2016 -KeepDays 100 -Confirm:$false\nRemove backup and restore history on SQL Server sql2016 older than 100 days. Does not prompt for confirmation.\nPS C:\\\u003e Remove-DbaDbBackupRestoreHistory -SqlInstance sql2016 -Database db1\nPrompts for confirmation then deletes all backup and restore history for database db1 on SQL Server sql2016\nPS C:\\\u003e Get-DbaDatabase -SqlInstance sql2016 | Remove-DbaDbBackupRestoreHistory -WhatIf\nRemove complete backup and restore history for all databases on SQL Server sql2016",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "KeepDays",
                           "The number of days of history to keep. Defaults to 30 days.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "Database",
                           "The database(s) to process. If unspecified, all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piped input from Get-DbaDatabase",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaDbBackupRestoreHistory [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-KeepDays] \u003cInt32\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaDbCertificate",
        "Description":  "Deletes specified database certificate",
        "Tags":  "Certificate",
        "Synopsis":  "Deletes specified database certificate",
        "Alias":  "Remove-DbaDatabaseCertificate",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Remove-DbaDbCertificate",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbCertificate -SqlInstance Server1\nThe certificate in the master database on server1 will be removed if it exists.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDbCertificate -SqlInstance Server1 -Database db1 -Confirm:$false\nSuppresses all prompts to remove the certificate in the \u0027db1\u0027 database and drops the key.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The SQL Server to create the certificates on.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to SQL Server using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database where the certificate will be removed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Certificate",
                           "The certificate that will be removed",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Piped certificate objects",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaDbCertificate [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Certificate] \u003cString[]\u003e] [[-InputObject] \u003cCertificate[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaDbMasterKey",
        "Description":  "Deletes specified database master key",
        "Tags":  [
                     "Certificate",
                     "Masterkey"
                 ],
        "Synopsis":  "Deletes specified database master key",
        "Alias":  "Remove-DbaDatabaseMasterKey",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Remove-DbaDbMasterKey",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Remove-DbaMasterKey",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbMasterKey -SqlInstance sql2017, sql2016 -Database pubs\nThe master key in the pubs database on sql2017 and sql2016 will be removed if it exists.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDbMasterKey -SqlInstance sql2017 -Database db1 -Confirm:$false\nSuppresses all prompts to remove the master key in the \u0027db1\u0027 database and drops the key.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbMasterKey -SqlInstance sql2017 -Database db1 | Remove-DbaDbMasterKey -Confirm:$false\nSuppresses all prompts to remove the master key in the \u0027db1\u0027 database and drops the key.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to SQL Server using alternative credentials",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database where the master key will be removed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "List of databases to exclude from clearing all master keys",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "All",
                           "Purge the master keys from all databases on an instance",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Enables pipeline input from Get-DbaDatabase",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaDbMasterKey [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [-All] [[-InputObject] \u003cMasterKey[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaDbMirror",
        "Description":  "Removes database mirrors. Does not set databases in recovery to recovered.",
        "Tags":  [
                     "Mirror",
                     "HA"
                 ],
        "Synopsis":  "Removes database mirrors.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Remove-DbaDbMirror",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaDbMirror",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaDbMirror -SqlInstance localhost\nReturns all Endpoint(s) on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaDbMirror -SqlInstance localhost, sql2016\nReturns all Endpoint(s) for the local and sql2016 SQL Server instances",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The target database.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows piping from Get-DbaDatabase.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaDbMirror [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaDbMirrorMonitor",
        "Description":  "Stops and deletes the mirroring monitor job for all the databases on the server instance.\n\nBasically executes sp_dbmmonitordropmonitoring.",
        "Tags":  [
                     "Mirror",
                     "HA",
                     "Monitor"
                 ],
        "Synopsis":  "Stops and deletes the mirroring monitor job for all the databases on the server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Remove-DbaDbMirrorMonitor",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Remove-DbaDbMirrorMonitor",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbMirrorMonitor -SqlInstance sql2008, sql2012\nStops and deletes the mirroring monitor job for all the databases on sql2008 and sql2012.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternate Windows or SQL Login Authentication. Accepts credential objects (Get-Credential).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaDbMirrorMonitor [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaDbOrphanUser",
        "Description":  "An orphan user is defined by a user that does not have their matching login. (Login property = \"\").\n\nIf user is the owner of the schema with the same name and if if the schema does not have any underlying objects the schema will be dropped.\n\nIf user owns more than one schema, the owner of the schemas that does not have the same name as the user, will be changed to \u0027dbo\u0027. If schemas have underlying objects, you must specify the -Force parameter so the user can be dropped.\n\nIf exists a login to map the drop will not be performed unless you specify the -Force parameter (only when calling from Repair-DbaDbOrphanUser.",
        "Tags":  [
                     "Orphan",
                     "Database",
                     "Security",
                     "Login"
                 ],
        "Synopsis":  "Drop orphan users with no existing login to map",
        "Alias":  "Remove-DbaOrphanUser,Remove-SqlOrphanUser",
        "Author":  "Claudio Silva (@ClaudioESSilva) | Simone Bizzotto (@niphlod)",
        "CommandName":  "Remove-DbaDbOrphanUser",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Remove-DbaDbOrphanUser",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbOrphanUser -SqlInstance sql2005\nFinds and drops all orphan users without matching Logins in all databases present on server \u0027sql2005\u0027.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDbOrphanUser -SqlInstance sqlserver2014a -SqlCredential $cred\nFinds and drops all orphan users without matching Logins in all databases present on server \u0027sqlserver2014a\u0027. SQL Server authentication will be used in connecting to the server.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaDbOrphanUser -SqlInstance sqlserver2014a -Database db1, db2 -Force\nFinds and drops orphan users even if they have a matching Login on both db1 and db2 databases.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eRemove-DbaDbOrphanUser -SqlInstance sqlserver2014a -ExcludeDatabase db1, db2 -Force\nFinds and drops orphan users even if they have a matching Login from all databases except db1 and db2.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eRemove-DbaDbOrphanUser -SqlInstance sqlserver2014a -User OrphanUser\nRemoves user OrphanUser from all databases only if there is no matching login.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eRemove-DbaDbOrphanUser -SqlInstance sqlserver2014a -User OrphanUser -Force\nRemoves user OrphanUser from all databases even if they have a matching Login. Any schema that the user owns will change ownership to dbo.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "User",
                           "Specifies the list of users to remove.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled:\r\nIf exists any schema which owner is the User, this will force the change of the owner to \u0027dbo\u0027.\r\nIf exists a login to map the drop will not be performed unless you specify this parameter.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaDbOrphanUser [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-User] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaDbSnapshot",
        "Description":  "Removes (drops) database snapshots from the server",
        "Tags":  [
                     "Snapshot",
                     "Database"
                 ],
        "Synopsis":  "Removes database snapshots",
        "Alias":  "Remove-DbaDatabaseSnapshot",
        "Author":  "Simone Bizzotto (@niphold)",
        "CommandName":  "Remove-DbaDbSnapshot",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Remove-DbaDbSnapshot",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbSnapshot -SqlInstance sql2014 -Snapshot HR_snap_20161201, HR_snap_20161101\nRemoves database snapshots named HR_snap_20161201 and HR_snap_20161101\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDbSnapshot -SqlInstance sql2014 -Database HR, Accounting\nRemoves all database snapshots having HR and Accounting as base dbs\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbSnapshot -SqlInstance sql2014 -Database HR, Accounting | Remove-DbaDbSnapshot\nRemoves all database snapshots having HR and Accounting as base dbs\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eRemove-DbaDbSnapshot -SqlInstance sql2014 -Snapshot HR_snapshot, Accounting_snapshot\nRemoves HR_snapshot and Accounting_snapshot\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDbSnapshot -SqlInstance sql2016 | Where SnapshotOf -like \u0027*dumpsterfire*\u0027 | Remove-DbaDbSnapshot\nRemoves all snapshots associated with databases that have dumpsterfire in the name\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaDbSnapshot -SqlInstance sql2016 | Out-GridView -Passthru | Remove-DbaDbSnapshot\nAllows the selection of snapshots on sql2016 to remove\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eRemove-DbaDbSnapshot -SqlInstance sql2014 -AllSnapshots\nRemoves all database snapshots from sql2014\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eRemove-DbaDbSnapshot -SqlInstance sql2014 -AllSnapshots -Confirm\nRemoves all database snapshots from sql2014 and prompts for each database",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Credential object used to connect to the SQL Server as a different user",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Removes snapshots for only this specific base db",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Removes snapshots excluding this specific base dbs",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Snapshot",
                           "Restores databases from snapshot with this name only",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables input from Get-DbaDbSnapshot",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "AllSnapshots",
                           "Specifies that you want to remove all snapshots from the server",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "Will forcibly kill all running queries that prevent the drop process.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts for confirmation of every step.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaDbSnapshot [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-Snapshot] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-AllSnapshots] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaDbUser",
        "Description":  "If user is the owner of a schema with the same name and if if the schema does not have any underlying objects the schema will be\ndropped.  If user owns more than one schema, the owner of the schemas that does not have the same name as the user, will be\nchanged to \u0027dbo\u0027. If schemas have underlying objects, you must specify the -Force parameter so the user can be dropped.",
        "Tags":  [
                     "Database",
                     "User",
                     "Login",
                     "Security"
                 ],
        "Synopsis":  "Drop database user",
        "Alias":  "",
        "Author":  "Doug Meyers (@dgmyrs)",
        "CommandName":  "Remove-DbaDbUser",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Remove-DbaDbUser",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbUser -SqlInstance sqlserver2014 -User user1\nDrops user1 from all databases it exists in on server \u0027sqlserver2014\u0027.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDbUser -SqlInstance sqlserver2014 -Database database1 -User user1\nDrops user1 from the database1 database on server \u0027sqlserver2014\u0027.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaDbUser -SqlInstance sqlserver2014 -ExcludeDatabase model -User user1\nDrops user1 from all databases it exists in on server \u0027sqlserver2014\u0027 except for the model database.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbUser sqlserver2014 | Where-Object Name -In \"user1\" | Remove-DbaDbUser\nDrops user1 from all databases it exists in on server \u0027sqlserver2014\u0027.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Credential object used to connect to the SQL Server as a different user.",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "User",
                           "Specifies the list of users to remove.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Support piping from Get-DbaDbUser.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Force",
                           "If enabled this will force the change of the owner to \u0027dbo\u0027 for any schema which owner is the User.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaDbUser [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] -User \u003cObject[]\u003e [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaDbUser -InputObject \u003cUser[]\u003e [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaEndpoint",
        "Description":  "Removes endpoints from a SQL Server instance.",
        "Tags":  "Endpoint",
        "Synopsis":  "Removes endpoints from a SQL Server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Remove-DbaEndpoint",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Remove-DbaEndpoint",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaEndpoint -SqlInstance sqlserver2012 -AllEndpoints\nRemoves all endpoints on the sqlserver2014 instance. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaEndpoint -SqlInstance sqlserver2012 -Endpoint endpoint1,endpoint2 -Confirm:$false\nRemoves the endpoint1 and endpoint2 endpoints. Does not prompt for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaEndpoint -SqlInstance sqlserver2012 -Endpoint endpoint1 | Remove-DbaEndpoint\nRemoves the endpoints returned from the Get-DbaEndpoint function. Prompts for confirmation.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EndPoint",
                           "Only remove specific endpoints.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AllEndpoints",
                           "Remove all endpoints on an instance.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-Endpoint.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaEndpoint [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-EndPoint] \u003cString[]\u003e] [-AllEndpoints] [[-InputObject] \u003cEndpoint[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaLogin",
        "Description":  "Tries a bunch of different ways to remove a Login or two or more.",
        "Tags":  [
                     "Delete",
                     "Login"
                 ],
        "Synopsis":  "Drops a Login",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Remove-DbaLogin",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Remove-DbaLogin",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaLogin -SqlInstance sql2016 -Login mylogin\nPrompts then removes the Login mylogin on SQL Server sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaLogin -SqlInstance sql2016 -Login mylogin, yourlogin\nPrompts then removes the Logins mylogin and yourlogin on SQL Server sql2016\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaLogin -SqlInstance sql2016 -Login mylogin -Confirm:$false\nDoes not prompt and swiftly removes mylogin on SQL Server sql2016\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance server\\instance -Login yourlogin | Remove-DbaLogin\nRemoves mylogin on SQL Server server\\instance",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to servers using alternative credentials.",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Login",
                           "The Login(s) to process - this list is auto-populated from the server. If unspecified, all Logins will be processed.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "A collection of Logins (such as returned by Get-DbaLogin), to be removed.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Force",
                           "Kills any sessions associated with the login prior to drop",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaLogin [-SqlCredential \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaLogin -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -Login \u003cString[]\u003e [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaLogin [-SqlCredential \u003cPSCredential\u003e] -InputObject \u003cLogin[]\u003e [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaNetworkCertificate",
        "Description":  "Removes the network certificate for SQL Server instance. This setting is found in Configuration Manager.",
        "Tags":  "Certificate",
        "Synopsis":  "Removes the network certificate for SQL Server instance",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Remove-DbaNetworkCertificate",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Remove-DbaNetworkCertificate",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaNetworkCertificate\nRemoves the Network Certificate for the default instance (MSSQLSERVER) on localhost\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaNetworkCertificate -SqlInstance sql1\\SQL2008R2SP2\nRemoves the Network Certificate for the SQL2008R2SP2 instance on sql1\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaNetworkCertificate -SqlInstance localhost\\SQL2008R2SP2 -WhatIf\nShows what would happen if the command were run",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Defaults to localhost. If target is a cluster, you must also specify InstanceClusterName (see below)",
                           "ServerInstance,SqlServer,ComputerName",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to the computer (not sql instance) using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaNetworkCertificate [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaPfDataCollectorCounter",
        "Description":  "Removes a Performance Data Collector Counter.",
        "Tags":  "PerfMon",
        "Synopsis":  "Removes a Performance Data Collector Counter.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Remove-DbaPfDataCollectorCounter",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Remove-DbaPfDataCollectorCounter",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaPfDataCollectorCounter -ComputerName sql2017 -CollectorSet \u0027System Correlation\u0027 -Collector DataCollector01  -Counter \u0027\\LogicalDisk(*)\\Avg. Disk Queue Length\u0027\nPrompts for confirmation then removes the \u0027\\LogicalDisk(*)\\Avg. Disk Queue Length\u0027 counter within the DataCollector01 collector within the System Correlation collector set on sql2017.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorCounter | Out-GridView -PassThru | Remove-DbaPfDataCollectorCounter -Confirm:$false\nAllows you to select which counters you\u0027d like on localhost and does not prompt for confirmation.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer. Defaults to localhost.",
                           "",
                           false,
                           "false",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to the target computer using alternative credentials. To use:\n$cred = Get-Credential, then pass $cred object to the -Credential parameter.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CollectorSet",
                           "The name of the Collector Set to search.",
                           "DataCollectorSet",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Collector",
                           "The name of the Collector to remove.",
                           "DataCollector",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Counter",
                           "The name of the Counter - in the form of \u0027\\Processor(_Total)\\% Processor Time\u0027.",
                           "Name",
                           true,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "InputObject",
                           "Accepts the object output by Get-DbaPfDataCollectorSet via the pipeline.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaPfDataCollectorCounter [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CollectorSet] \u003cString[]\u003e] [[-Collector] \u003cString[]\u003e] [-Counter] \u003cObject[]\u003e [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaPfDataCollectorSet",
        "Description":  "Removes a Performance Monitor Data Collector Set. When removing data collector sets from the local instance, Run As Admin is required.",
        "Tags":  "PerfMon",
        "Synopsis":  "Removes a Performance Monitor Data Collector Set",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Remove-DbaPfDataCollectorSet",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Remove-DbaPfDataCollectorSet",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaPfDataCollectorSet\nPrompts for confirmation then removes all ready Collectors on localhost.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaPfDataCollectorSet -ComputerName sql2017 -Confirm:$false\nAttempts to remove all ready Collectors on localhost and does not prompt to confirm.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaPfDataCollectorSet -ComputerName sql2017, sql2016 -Credential ad\\sqldba -CollectorSet \u0027System Correlation\u0027\nPrompts for confirmation then removes the \u0027System Correlation\u0027 Collector on sql2017 and sql2016 using alternative credentials.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet -CollectorSet \u0027System Correlation\u0027 | Remove-DbaPfDataCollectorSet\nRemoves the \u0027System Correlation\u0027 Collector.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet -CollectorSet \u0027System Correlation\u0027 | Stop-DbaPfDataCollectorSet | Remove-DbaPfDataCollectorSet\nStops and removes the \u0027System Correlation\u0027 Collector.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer. Defaults to localhost.",
                           "",
                           false,
                           "false",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to the target computer using alternative credentials. To use:\n$cred = Get-Credential, then pass $cred object to the -Credential parameter.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CollectorSet",
                           "The name of the Collector Set to remove.",
                           "DataCollectorSet",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Accepts the object output by Get-DbaPfDataCollectorSet via the pipeline.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaPfDataCollectorSet [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CollectorSet] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaSpn",
        "Description":  "This function will connect to Active Directory and search for an account. If the account is found, it will attempt to remove the specified SPN. Once the SPN is removed, the function will also remove delegation to that service.\n\nIn order to run this function, the credential you provide must have write access to Active Directory.",
        "Tags":  "SPN",
        "Synopsis":  "Removes an SPN for a given service account in active directory and also removes delegation to the same SPN, if found",
        "Alias":  "",
        "Author":  "Drew Furgiuele (@pittfurg), http://www.port1433.com",
        "CommandName":  "Remove-DbaSpn",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Remove-DbaSpn",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaSpn -SPN MSSQLSvc\\SQLSERVERA.domain.something -ServiceAccount domain\\account\nConnects to Active Directory and removes a provided SPN from the given account (and also the relative delegation)\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaSpn -SPN MSSQLSvc\\SQLSERVERA.domain.something -ServiceAccount domain\\account -EnableException\nConnects to Active Directory and removes a provided SPN from the given account, suppressing all error messages and throw exceptions that can be caught instead\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaSpn -SPN MSSQLSvc\\SQLSERVERA.domain.something -ServiceAccount domain\\account -Credential ad\\sqldba\nConnects to Active Directory and removes a provided SPN to the given account. Uses alternative account to connect to AD.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eTest-DbaSpn -ComputerName sql2005 | Where { $_.isSet -eq $true } | Remove-DbaSpn -WhatIf\nShows what would happen trying to remove all set SPNs for sql2005 and the relative delegations\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eTest-DbaSpn -ComputerName sql2005 | Where { $_.isSet -eq $true } | Remove-DbaSpn\nRemoves all set SPNs for sql2005 and the relative delegations",
        "Params":  [
                       [
                           "SPN",
                           "The SPN you want to remove",
                           "RequiredSPN",
                           true,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "ServiceAccount",
                           "The account you want the SPN remove from",
                           "InstanceServiceAccount,AccountName",
                           true,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "Credential",
                           "The credential you want to use to connect to Active Directory to make the changes",
                           "",
                           false,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command was executed",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Turns confirmations before changes on or off",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaSpn [-SPN] \u003cString\u003e [-ServiceAccount] \u003cString\u003e [[-Credential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaTrace",
        "Description":  "Stops and closes the specified trace and deletes its definition from the server.",
        "Tags":  [
                     "Security",
                     "Trace"
                 ],
        "Synopsis":  "Stops and closes the specified trace and deletes its definition from the server.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Remove-DbaTrace",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaTrace -SqlInstance sql2008\nStops and removes all traces on sql2008\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaTrace -SqlInstance sql2008 -Id 1\nStops and removes all trace with ID 1 on sql2008\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaTrace -SqlInstance sql2008 | Out-GridView -PassThru | Remove-DbaTrace\nStops and removes selected traces on sql2008",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Id",
                           "A list of trace ids.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Internal parameter for piping.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaTrace [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Id] \u003cInt32[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaXESession",
        "Description":  "This script removes Extended Events sessions on a SQL Server instance.",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "Removes Extended Events sessions.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Remove-DbaXESession",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Remove-DbaXESession",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaXESession -SqlInstance sql2012 -AllSessions\nRemoves all Extended Event Session on the sqlserver2014 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaXESession -SqlInstance sql2012 -Session xesession1,xesession2\nRemoves the xesession1 and xesession2 Extended Event sessions.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sql2017 | Remove-DbaXESession -Confirm:$false\nRemoves all sessions from sql2017, bypassing prompts.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sql2012 -Session xesession1 | Remove-DbaXESession\nRemoves the sessions returned from the Get-DbaXESession function.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Session",
                           "Specifies a list of Extended Events sessions to remove.",
                           "Sessions",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "AllSessions",
                           "If this switch is enabled, all Extended Events sessions will be removed except the packaged sessions AlwaysOn_health, system_health, telemetry_xevents.",
                           "",
                           true,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Accepts a collection of XEsession objects as output by Get-DbaXESession.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaXESession [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -Session \u003cObject[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaXESession [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -AllSessions [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaXESession -InputObject \u003cSession[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Remove-DbaXESmartTarget",
        "Description":  "Removes XESmartTarget PowerShell jobs.",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "Removes XESmartTarget PowerShell jobs.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl) | SmartTarget by Gianluca Sartori (@spaghettidba)",
        "CommandName":  "Remove-DbaXESmartTarget",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Remove-DbaXESmartTarget",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaXESmartTarget | Remove-DbaXESmartTarget\nRemoves all XESmartTarget jobs.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaXESmartTarget | Where-Object Id -eq 2 | Remove-DbaXESmartTarget\nRemoves a specific XESmartTarget job.",
        "Params":  [
                       [
                           "InputObject",
                           "Specifies one or more XESmartTarget job objects as output by Get-DbaXESmartTarget.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Remove-DbaXESmartTarget [-InputObject] \u003cObject[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Rename-DbaDatabase",
        "Description":  "Can change every database metadata that can be renamed.\nThe ultimate goal is choosing to have a default template to enforce in your environment\nso your naming convention for every bit can be put in place in no time.\nThe process is as follows (it follows the hierarchy of the entities):\n- database name is changed (optionally, forcing users out)\n- filegroup name(s) are changed accordingly\n- logical name(s) are changed accordingly\n- physical file(s) are changed accordingly\n- if Move is specified, the database will be taken offline and the move will initiate, then it will be taken online\n- if Move is not specified, the database remains online (unless SetOffline), and you are in charge of moving files\nIf any of the above fails, the process stops.\nPlease take a backup of your databases BEFORE using this, and remember to backup AFTER (also a FULL backup of master)\n\nIt returns an object for each database with all the renames done, plus hidden properties showing a \"human\" representation of them.\n\nIt\u0027s better you store the resulting object in a variable so you can inspect it in case of issues, e.g. \"$result = Rename-DbaDatabase .....\"\n\nTo get a grasp without worrying of what would happen under the hood, use \"Rename-DbaDatabase .... -Preview | Select-Object *\"",
        "Tags":  [
                     "Database",
                     "Rename"
                 ],
        "Synopsis":  "Changes database name, logical file names, file group names and physical file names (optionally handling the move). BETA VERSION.",
        "Alias":  "",
        "Author":  "Simone Bizzotto (@niphold)",
        "CommandName":  "Rename-DbaDatabase",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Rename-DbaDatabase",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName HR2 -Preview | select *\nShows the detailed result set you\u0027ll get renaming the HR database to HR2 without doing anything\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName HR2\nRenames the HR database to HR2\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sqlserver2014a -Database HR | Rename-DbaDatabase -DatabaseName HR2\nSame as before, but with a piped database (renames the HR database to HR2)\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eRename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName \"dbatools_\u003cDBN\u003e\"\nRenames the HR database to dbatools_HR\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eRename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName \"dbatools_\u003cDBN\u003e_\u003cDATE\u003e\"\nRenames the HR database to dbatools_HR_20170807 (if today is 07th Aug 2017)\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eRename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -FileGroupName \"dbatools_\u003cFGN\u003e\"\nRenames every FileGroup within HR to \"dbatools_[the original FileGroup name]\"\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eRename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName \"dbatools_\u003cDBN\u003e\" -FileGroupName \"\u003cDBN\u003e_\u003cFGN\u003e\"\nRenames the HR database to \"dbatools_HR\", then renames every FileGroup within to \"dbatools_HR_[the original FileGroup name]\"\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eRename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -FileGroupName \"dbatools_\u003cDBN\u003e_\u003cFGN\u003e\"\nPS C:\\\u003e Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName \"dbatools_\u003cDBN\u003e\"\nRenames the HR database to \"dbatools_HR\", then renames every FileGroup within to \"dbatools_HR_[the original FileGroup name]\"\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eRename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName \"dbatools_\u003cDBN\u003e\" -FileName \"\u003cDBN\u003e_\u003cFGN\u003e_\u003cFNN\u003e\"\nRenames the HR database to \"dbatools_HR\" and then all filenames as \"dbatools_HR_[Name of the FileGroup]_[original_filename]\"\r\nThe db stays online (watch out!). You can then proceed manually to move/copy files by hand, set the db offline and then online again to finish the rename process\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003eRename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName \"dbatools_\u003cDBN\u003e\" -FileName \"\u003cDBN\u003e_\u003cFGN\u003e_\u003cFNN\u003e\" -SetOffline\nRenames the HR database to \"dbatools_HR\" and then all filenames as \"dbatools_HR_[Name of the FileGroup]_[original_filename]\"\r\nThe db is then set offline (watch out!). You can then proceed manually to move/copy files by hand and then set it online again to finish the rename process\n-------------------------- EXAMPLE 11 --------------------------\nPS C:\\\u003eRename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName \"dbatools_\u003cDBN\u003e\" -FileName \"\u003cDBN\u003e_\u003cFGN\u003e_\u003cFNN\u003e\" -Move\nRenames the HR database to \"dbatools_HR\" and then all filenames as \"dbatools_HR_[Name of the FileGroup]_[original_filename]\"\r\nThe db is then set offline (watch out!). The function tries to do a simple rename and then sets the db online again to finish the rename process",
        "Params":  [
                       [
                           "SqlInstance",
                           "Target any number of instances, in order to return their build state.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "When connecting to an instance, use the credentials specified.",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Targets only specified databases",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Excludes only specified databases",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AllDatabases",
                           "If you want to apply the naming convention system wide, you need to pass this parameter",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DatabaseName",
                           "Pass a template to rename the database name. Valid placeholders are:\r\n- \u003cDBN\u003e current database name\r\n- \u003cDATE\u003e date (yyyyMMdd)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "FileGroupName",
                           "Pass a template to rename file group name. Valid placeholders are:\r\n- \u003cFGN\u003e current filegroup name\r\n- \u003cDBN\u003e current database name\r\n- \u003cDATE\u003e date (yyyyMMdd)\r\nIf distinct names cannot be generated, a counter will be appended (0001, 0002, 0003, etc)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "LogicalName",
                           "Pass a template to rename logical name. Valid placeholders are:\r\n- \u003cFT\u003e file type (ROWS, LOG)\r\n- \u003cLGN\u003e current logical name\r\n- \u003cFGN\u003e current filegroup name\r\n- \u003cDBN\u003e current database name\r\n- \u003cDATE\u003e date (yyyyMMdd)\r\nIf distinct names cannot be generated, a counter will be appended (0001, 0002, 0003, etc)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "FileName",
                           "Pass a template to rename file name. Valid placeholders are:\r\n- \u003cFNN\u003e current file name (the basename, without directory nor extension)\r\n- \u003cFT\u003e file type (ROWS, LOG, MMO, FS)\r\n- \u003cLGN\u003e current logical name\r\n- \u003cFGN\u003e current filegroup name\r\n- \u003cDBN\u003e current database name\r\n- \u003cDATE\u003e date (yyyyMMdd)\r\nIf distinct names cannot be generated, a counter will be appended (0001, 0002, 0003, etc)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ReplaceBefore",
                           "If you pass this switch, all upper level \"current names\" will be inspected and replaced BEFORE doing the\r\nrename according to the template in the current level (remember the hierarchy):\r\nLet\u0027s say you have a database named \"dbatools_HR\", composed by 3 files\r\n- dbatools_HR_Data.mdf\r\n- dbatools_HR_Index.ndf\r\n- dbatools_HR_log.ldf\r\nRename-DbaDatabase .... -Database \"dbatools_HR\" -DatabaseName \"dbatools_HRARCHIVE\" -FileName \u0027\u003cDBN\u003e\u003cFNN\u003e\u0027\r\nwould end up with this logic:\r\n- database --\u003e no placeholders specified\r\n- dbatools_HR to dbatools_HRARCHIVE\r\n- filenames placeholders specified\r\n\u003cDBN\u003e\u003cFNN\u003e --\u003e current database name + current filename\"\r\n- dbatools_HR_Data.mdf to dbatools_HRARCHIVEdbatools_HR_Data.mdf\r\n- dbatools_HR_Index.mdf to dbatools_HRARCHIVEdbatools_HR_Data.mdf\r\n- dbatools_HR_log.ldf to dbatools_HRARCHIVEdbatools_HR_log.ldf\r\nPassing this switch, instead, e.g.\r\nRename-DbaDatabase .... -Database \"dbatools_HR\" -DatabaseName \"dbatools_HRARCHIVE\" -FileName \u0027\u003cDBN\u003e\u003cFNN\u003e\u0027 -ReplaceBefore\r\nend up with this logic instead:\r\n- database --\u003e no placeholders specified\r\n- dbatools_HR to dbatools_HRARCHIVE\r\n- filenames placeholders specified,\r\n\u003cDBN\u003e\u003cFNN\u003e, plus -ReplaceBefore --\u003e current database name + replace OLD \"upper level\" names inside the current filename\r\n- dbatools_HR_Data.mdf to dbatools_HRARCHIVE_Data.mdf\r\n- dbatools_HR_Index.mdf to dbatools_HRARCHIVE_Data.mdf\r\n- dbatools_HR_log.ldf to dbatools_HRARCHIVE_log.ldf",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "Kills any open session to be able to do renames.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Move",
                           "If you want this function to move files, else you\u0027re the one in charge of it.\r\nThis enables the same functionality as SetOffline, killing open transactions and putting the database\r\noffline, then do the actual rename and setting it online again afterwards",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "SetOffline",
                           "Kills any open session and sets the database offline to be able to move files",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Preview",
                           "Shows the renames without performing any operation (recommended to find your way around this function parameters ;-) )",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Accepts piped database objects",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Rename-DbaDatabase -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllDatabases] [-DatabaseName \u003cString\u003e] [-FileGroupName \u003cString\u003e] [-LogicalName \u003cString\u003e] [-FileName \u003cString\u003e] [-ReplaceBefore] [-Force] [-Move] [-SetOffline] [-Preview] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRename-DbaDatabase [-SqlCredential \u003cPSCredential\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllDatabases] [-DatabaseName \u003cString\u003e] [-FileGroupName \u003cString\u003e] [-LogicalName \u003cString\u003e] [-FileName \u003cString\u003e] [-ReplaceBefore] [-Force] [-Move] [-SetOffline] [-Preview] -InputObject \u003cDatabase[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Rename-DbaLogin",
        "Description":  "There are times where you might want to rename a login that was copied down, or if the name is not descriptive for what it does.\n\nIt can be a pain to update all of the mappings for a specific user, this does it for you.",
        "Tags":  "Login",
        "Synopsis":  "Rename-DbaLogin will rename login and database mapping for a specified login.",
        "Alias":  "",
        "Author":  "Mitchell Hamann (@SirCaptainMitch)",
        "CommandName":  "Rename-DbaLogin",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Rename-DbaLogin",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRename-DbaLogin -SqlInstance localhost -Login DbaToolsUser -NewLogin captain\nSQL Login Example\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRename-DbaLogin -SqlInstance localhost -Login domain\\oldname -NewLogin domain\\newname\nChange the windowsuser login name.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRename-DbaLogin -SqlInstance localhost -Login dbatoolsuser -NewLogin captain -WhatIf\nWhatIf Example",
        "Params":  [
                       [
                           "SqlInstance",
                           "Source SQL Server.You must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Login",
                           "The current Login on the server - this list is auto-populated from the server.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "NewLogin",
                           "The new Login that you wish to use. If it is a windows user login, then the SID must match.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts to confirm actions",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Rename-DbaLogin [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Login] \u003cString\u003e [-NewLogin] \u003cString\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Repair-DbaDbMirror",
        "Description":  "Attempts to repair a suspended mirroring database.\n\nRestarts the endpoints then sets the partner to resume. See this article for more info:\n\nhttp://www.sqlservercentral.com/blogs/vivekssqlnotes/2016/09/03/how-to-resume-suspended-database-mirroring-in-sql-server-/",
        "Tags":  [
                     "Mirror",
                     "HA"
                 ],
        "Synopsis":  "Attempts to repair a suspended or paused mirroring database.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Repair-DbaDbMirror",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Repair-DbaDbMirror",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRepair-DbaDbMirror -SqlInstance sql2017 -Database pubs\nAttempts to repair the mirrored but suspended pubs database on sql2017.\r\nRestarts the endpoints then sets the partner to resume. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2017 -Database pubs | Repair-DbaDbMirror -Confirm:$false\nAttempts to repair the mirrored but suspended pubs database on sql2017.\r\nRestarts the endpoints then sets the partner to resume. Does not prompt for confirmation.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The target database.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows piping from Get-DbaDatabase.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Repair-DbaDbMirror [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Repair-DbaDbOrphanUser",
        "Description":  "An orphan user is defined by a user that does not have a matching login (Login property = \"\").\n\nIf the matching login exists it must be:\nEnabled\nNot a system object\nNot locked\nHave the same name that user\n\nYou can drop users that does not have their matching login by specifying the parameter -RemoveNotExisting.",
        "Tags":  "Orphan",
        "Synopsis":  "Finds orphan users with existing login and remaps them.",
        "Alias":  "Repair-DbaOrphanUser,Repair-SqlOrphanUser",
        "Author":  "Claudio Silva (@ClaudioESSilva) | Simone Bizzotto (@niphlod)",
        "CommandName":  "Repair-DbaDbOrphanUser",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Repair-DbaDbOrphanUser",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRepair-DbaDbOrphanUser -SqlInstance sql2005\nFinds and repairs all orphan users of all databases present on server \u0027sql2005\u0027\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRepair-DbaDbOrphanUser -SqlInstance sqlserver2014a -SqlCredential $cred\nFinds and repair all orphan users in all databases present on server \u0027sqlserver2014a\u0027. SQL credentials are used to authenticate to the server.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRepair-DbaDbOrphanUser -SqlInstance sqlserver2014a -Database db1, db2\nFinds and repairs all orphan users in both db1 and db2 databases.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eRepair-DbaDbOrphanUser -SqlInstance sqlserver2014a -Database db1 -Users OrphanUser\nFinds and repairs user \u0027OrphanUser\u0027 in \u0027db1\u0027 database.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eRepair-DbaDbOrphanUser -SqlInstance sqlserver2014a -Users OrphanUser\nFinds and repairs user \u0027OrphanUser\u0027 on all databases\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eRepair-DbaDbOrphanUser -SqlInstance sqlserver2014a -RemoveNotExisting\nFinds all orphan users of all databases present on server \u0027sqlserver2014a\u0027. Removes all users that do not have  matching Logins.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Users",
                           "Specifies the list of usernames to repair.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "RemoveNotExisting",
                           "If this switch is enabled, all users that do not have a matching login will be dropped from the database.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "Forces alter schema to dbo owner so users can be dropped.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Repair-DbaDbOrphanUser [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-Users] \u003cObject[]\u003e] [-RemoveNotExisting] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Repair-DbaServerName",
        "Description":  "When a SQL Server\u0027s host OS is renamed, the SQL Server should be as well. This helps with Availability Groups and Kerberos.\n\nThis command renames @@SERVERNAME to match with the Windows name. The new name is automatically determined. It does not matter if you use an alias to connect to the SQL instance.\n\nIf the automatically determined new name matches the old name, the command will not run.\n\nhttps://www.mssqltips.com/sqlservertip/2525/steps-to-change-the-server-name-for-a-sql-server-machine/",
        "Tags":  "SPN",
        "Synopsis":  "Renames @@SERVERNAME to match with the Windows name.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Repair-DbaServerName",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Repair-DbaServerName",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRepair-DbaServerName -SqlInstance sql2014\nChecks to see if the server name is updatable and changes the name with a number of prompts.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRepair-DbaServerName -SqlInstance sql2014 -AutoFix\nChecks to see if the server name is updatable and automatically performs the change. Replication or mirroring will be broken if necessary.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRepair-DbaServerName -SqlInstance sql2014 -AutoFix -Force\nChecks to see if the server name is updatable and automatically performs the change, bypassing most prompts and confirmations. Replication or mirroring will be broken if necessary.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AutoFix",
                           "If this switch is enabled, the repair will be performed automatically.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "If this switch is enabled, most confirmation prompts will be skipped.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Repair-DbaServerName [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-AutoFix] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Reset-DbaAdmin",
        "Description":  "This function allows administrators to regain access to local or remote SQL Servers by either resetting the sa password, adding the sysadmin role to existing login, or adding a new login (SQL or Windows) and granting it sysadmin privileges.\n\nThis is accomplished by stopping the SQL services or SQL Clustered Resource Group, then restarting SQL via the command-line using the /mReset-DbaAdmin parameter which starts the server in Single-User mode and only allows this script to connect.\n\nOnce the service is restarted, the following tasks are performed:\n- Login is added if it doesn\u0027t exist\n- If login is a Windows User, an attempt is made to ensure it exists\n- If login is a SQL Login, password policy will be set to OFF when creating the login, and SQL Server authentication will be set to Mixed Mode.\n- Login will be enabled and unlocked\n- Login will be added to sysadmin role\n\nIf failures occur at any point, a best attempt is made to restart the SQL Server.\n\nIn order to make this script as portable as possible, System.Data.SqlClient and Get-WmiObject are used (as opposed to requiring the Failover Cluster Admin tools or SMO).\n\nIf using this function against a remote SQL Server, ensure WinRM is configured and accessible. If this is not possible, run the script locally.\n\nTested on Windows XP, 7, 8.1, Server 2012 and Windows Server Technical Preview 2.\nTested on SQL Server 2005 SP4 through 2016 CTP2.",
        "Tags":  "WSMan",
        "Synopsis":  "This function allows administrators to regain access to SQL Servers in the event that passwords or access was lost.\n\nSupports SQL Server 2005 and above. Windows administrator access is required.",
        "Alias":  "Reset-SqlAdmin",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Reset-DbaAdmin",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Reset-DbaAdmin",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eReset-DbaAdmin -SqlInstance sqlcluster -SqlCredential sqladmin\nPrompts for password, then resets the \"sqladmin\" account password on sqlcluster.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eReset-DbaAdmin -SqlInstance sqlserver\\sqlexpress -Login ad\\administrator -Confirm:$false\nAdds the domain account \"ad\\administrator\" as a sysadmin to the SQL instance.\nIf the account already exists, it will be added to the sysadmin role.\nDoes not prompt for a password since it is not a SQL login. Does not prompt for confirmation since -Confirm is set to $false.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eReset-DbaAdmin -SqlInstance sqlserver\\sqlexpress -Login sqladmin -Force\nSkips restart confirmation, prompts for password, then adds a SQL Login \"sqladmin\" with sysadmin privileges.\r\nIf the account already exists, it will be added to the sysadmin role and the password will be reset.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. SQL Server must be 2005 and above, and can be a clustered or stand-alone instance.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Instead of using Login and SecurePassword, you can just pass in a credential object.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Login",
                           "By default, the Login parameter is \"sa\" but any other SQL or Windows account can be specified. If a login does not currently exist, it will be added.\nWhen adding a Windows login to remote servers, ensure the SQL Server can add the login (ie, don\u0027t add WORKSTATION\\Admin to remoteserver\\instance. Domain users and Groups are valid input.",
                           "",
                           false,
                           "false",
                           "sa"
                       ],
                       [
                           "SecurePassword",
                           "By default, if a SQL Login is detected, you will be prompted for a password. Use this to securely bypass the prompt.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, the Login(s) will be dropped and recreated on Destination. Logins that own Agent jobs cannot be dropped at this time.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Reset-DbaAdmin [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Login] \u003cString\u003e] [[-SecurePassword] \u003cSecureString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Reset-DbatoolsConfig",
        "Description":  "This command can be used to revert a configuration item to the value it was initialized with.\nGenerally, this amounts to reverting it to its default value.\n\nIn order for a reset to be possible, two conditions must be met:\n- The setting must have been initialized.\n- The setting cannot have been enforced by policy.",
        "Synopsis":  "Reverts a configuration item to its default value.",
        "Alias":  "",
        "CommandName":  "Reset-DbatoolsConfig",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eReset-DbatoolsConfig -Module MyModule\nResets all configuration items of the MyModule to default.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbatoolsConfig | Reset-DbatoolsConfig\nResets ALL configuration items to default.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eReset-DbatoolsConfig -FullName MyModule.Group.Setting1\nResets the configuration item named \u0027MyModule.Group.Setting1\u0027.",
        "Params":  [
                       [
                           "ConfigurationItem",
                           "A configuration object as returned by Get-DbatoolsConfig.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "FullName",
                           "The full name of the setting to reset, offering the maximum of precision.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Module",
                           "The name of the module, from which configurations should be reset.\r\nUsed in conjunction with the -Name parameter to filter a specific set of items.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "Used in conjunction with the -Module parameter to select which settings to reset using wildcard comparison.",
                           "",
                           false,
                           "false",
                           "*"
                       ],
                       [
                           "EnableException",
                           "This parameters disables user-friendly warnings and enables the throwing of exceptions.\r\nThis is less user friendly, but allows catching exceptions in calling scripts.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Reset-DbatoolsConfig [-ConfigurationItem \u003cConfig[]\u003e] [-FullName \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]\nReset-DbatoolsConfig -Module \u003cString\u003e [-Name \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Resolve-DbaNetworkName",
        "Description":  "Retrieves the IPAddress, ComputerName from one computer.\nThe object can be used to take action against its name or IPAddress.\n\nFirst ICMP is used to test the connection, and get the connected IPAddress.\n\nMultiple protocols (e.g. WMI, CIM, etc) are attempted before giving up.\n\nImportant: Remember that FQDN doesn\u0027t always match \"ComputerName dot Domain\" as AD intends.\nThere are network setup (google \"disjoint domain\") where AD and DNS do not match.\n\"Full computer name\" (as reported by sysdm.cpl) is the only match between the two,\nand it matches the \"DNSHostName\"  property of the computer object stored in AD.\nThis means that the notation of FQDN that matches \"ComputerName dot Domain\" is incorrect\nin those scenarios.\nIn other words, the \"suffix\" of the FQDN CAN be different from the AD Domain.\n\nThis cmdlet has been providing good results since its inception but for lack of useful\nnames some doubts may arise.\nLet this clear the doubts:\n- InputName: whatever has been passed in\n- ComputerName: hostname only\n- IPAddress: IP Address\n- DNSHostName: hostname only, coming strictly from DNS (as reported from the calling computer)\n- DNSDomain: domain only, coming strictly from DNS (as reported from the calling computer)\n- Domain: domain only, coming strictly from AD (i.e. the domain the ComputerName is joined to)\n- DNSHostEntry: Fully name as returned by DNS [System.Net.Dns]::GetHostEntry\n- FQDN: \"legacy\" notation of ComputerName \"dot\" Domain (coming from AD)\n- FullComputerName: Full name as configured from within the Computer (i.e. the only secure match between AD and DNS)\n\nSo, if you need to use something, go with FullComputerName, always, as it is the most correct in every scenario.",
        "Tags":  [
                     "Network",
                     "Resolve"
                 ],
        "Synopsis":  "Returns information about the network connection of the target computer including NetBIOS name, IP Address, domain name and fully qualified domain name (FQDN).",
        "Alias":  "",
        "Author":  "Klaas Vandenberghe (@PowerDBAKlaas) | Simone Bizzotto (@niphold)",
        "CommandName":  "Resolve-DbaNetworkName",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Resolve-DbaNetworkName",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eResolve-DbaNetworkName -ComputerName ServerA\nReturns a custom object displaying InputName, ComputerName, IPAddress, DNSHostName, DNSDomain, Domain, DNSHostEntry, FQDN, DNSHostEntry for ServerA\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eResolve-DbaNetworkName -SqlInstance sql2016\\sqlexpress\nReturns a custom object displaying InputName, ComputerName, IPAddress, DNSHostName, DNSDomain, Domain, DNSHostEntry, FQDN, DNSHostEntry  for the SQL instance sql2016\\sqlexpress\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eResolve-DbaNetworkName -SqlInstance sql2016\\sqlexpress, sql2014\nReturns a custom object displaying InputName, ComputerName, IPAddress, DNSHostName, DNSDomain, Domain, DNSHostEntry, FQDN, DNSHostEntry  for the SQL instance sql2016\\sqlexpress and sql2014\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sql2014 | Resolve-DbaNetworkName\nReturns a custom object displaying InputName, ComputerName, IPAddress, DNSHostName, Domain, FQDN for all SQL Servers returned by Get-DbaCmsRegServer",
        "Params":  [
                       [
                           "ComputerName",
                           "The target SQL Server instance or instances.\r\nThis can be the name of a computer, a SMO object, an IP address or a SQL Instance.",
                           "cn,host,ServerInstance,Server,SqlInstance",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Credential object used to connect to the SQL Server as a different user",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Turbo",
                           "Resolves without accessing the server itself. Faster but may be less accurate because it relies on DNS only,\r\nso it may fail spectacularly for disjoin-domain setups. Also, everyone has its own DNS (i.e. results may vary\r\nchanging the computer where the function runs)",
                           "FastParrot",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Resolve-DbaNetworkName [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-Turbo] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Resolve-DbaPath",
        "Description":  "Resolves a path.\nWill try to resolve to paths including some basic path validation and resolution.\nWill fail if the path cannot be resolved (so an existing path must be reached at).",
        "Synopsis":  "Resolves a path.",
        "Alias":  "",
        "CommandName":  "Resolve-DbaPath",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eResolve-DbaPath -Path report.log -Provider FileSystem -NewChild -SingleItem\nEnsures the resolved path is a FileSystem path.\r\nThis will resolve to the current folder and the file report.log.\r\nWill not ensure the file exists or doesn\u0027t exist.\r\nIf the current path is in a different provider, it will throw an exception.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eResolve-DbaPath -Path ..\\*\nThis will resolve all items in the parent folder, whatever the current path or drive might be.",
        "Params":  [
                       [
                           "Path",
                           "The path to validate.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Provider",
                           "Ensure the path is of the expected provider.\r\nAllows ensuring one does not operate in the wrong provider.\r\nCommon providers include the filesystem, the registry or the active directory.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SingleItem",
                           "Ensure the path should resolve to a single path only.\r\nThis may - intentionally or not - trip up wildcard paths.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NewChild",
                           "Assumes one wishes to create a new child item.\r\nThe parent path will be resolved and must validate true.\r\nThe final leaf will be treated as a leaf item that does not exist yet.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Resolve-DbaPath [-Path] \u003cString[]\u003e [-Provider \u003cString\u003e] [-SingleItem] [-NewChild] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Restart-DbaService",
        "Description":  "Restarts the SQL Server related services on one or more computers. Will follow SQL Server service dependencies.\n\nRequires Local Admin rights on destination computer(s).",
        "Tags":  [
                     "Service",
                     "Instance",
                     "Restart"
                 ],
        "Synopsis":  "Restarts SQL Server services on a computer.",
        "Alias":  "Restart-DbaSqlService",
        "Author":  "Kirill Kravtsov (@nvarscar)",
        "CommandName":  "Restart-DbaService",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Restart-DbaService",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRestart-DbaService -ComputerName sqlserver2014a\nRestarts the SQL Server related services on computer sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\u0027,\u0027sql3\u0027| Get-DbaService | Restart-DbaService\nGets the SQL Server related services on computers sql1, sql2 and sql3 and restarts them.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRestart-DbaService -ComputerName sql1,sql2 -Instance MSSQLSERVER\nRestarts the SQL Server services related to the default instance MSSQLSERVER on computers sql1 and sql2.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eRestart-DbaService -ComputerName $MyServers -Type SSRS\nRestarts the SQL Server related services of type \"SSRS\" (Reporting Services) on computers in the variable MyServers.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eRestart-DbaService -ComputerName sql1 -Type Engine -Force\nRestarts SQL Server database engine services on sql1 forcing dependent SQL Server Agent services to restart as well.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target SQL Server instance or instances.",
                           "cn,host,Server",
                           false,
                           "false",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "InstanceName",
                           "Only affects services that belong to the specific instances.",
                           "Instance",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Type",
                           "Use -Type to collect only services of the desired SqlServiceType.\r\nCan be one of the following: \"Agent\",\"Browser\",\"Engine\",\"FullText\",\"SSAS\",\"SSIS\",\"SSRS\"",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "A collection of services from Get-DbaService",
                           "ServiceCollection",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Timeout",
                           "How long to wait for the start/stop request completion before moving on. Specify 0 to wait indefinitely.",
                           "",
                           false,
                           "false",
                           "60"
                       ],
                       [
                           "Credential",
                           "Credential object used to connect to the computer as a different user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "Will stop dependent SQL Server agents when stopping Engine services.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the cmdlet runs. The cmdlet is not run.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before running the cmdlet.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Restart-DbaService [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [-InstanceName \u003cString[]\u003e] [-Type \u003cString[]\u003e] [-Timeout \u003cInt32\u003e] [-Credential \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRestart-DbaService [-InstanceName \u003cString[]\u003e] [-Type \u003cString[]\u003e] -InputObject \u003cObject[]\u003e [-Timeout \u003cInt32\u003e] [-Credential \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Restore-DbaBackupFromDirectory",
        "Description":  "Please use `Get-ChildItem | Restore-DbaDatabase` instead. This command is no longer supported.",
        "Tags":  [
                     "DisasterRecovery",
                     "Backup",
                     "Restore"
                 ],
        "Synopsis":  "Please use `Get-ChildItem | Restore-DbaDatabase` instead. This command is no longer supported.",
        "Alias":  "Restore-SqlBackupFromDirectory",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Restore-DbaBackupFromDirectory",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Restore-SqlBackupFromDirectory",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRestore-SqlBackupFromDirectory -SqlInstance sqlcluster -Path \\\\fileserver\\share\\sqlbackups\\SQLSERVER2014A\nAll user databases contained within \\\\fileserver\\share\\sqlbackups\\SQLSERVERA will be restored to sqlcluster, down the most recent full/differential/logs.\nRequires -Version 3.0",
        "Params":  [
                       [
                           "SqlInstance",
                           "The SQL Server instance to which you will be restoring the database.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "Specifies the full path to the directory that contains the database backups. The SQL Server service must have read access to this path.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "NoRecovery",
                           "If this switch is enabled, the database is left in the No Recovery state to enable further backups to be added.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ReuseSourceFolderStructure",
                           "If this switch is enabled, the folder structure used on the instance where the backup was made will be recreated. By default, the database files will be restored to the default data and log \r\ndirectories for the instance you\u0027re restoring onto.",
                           "ReuseFolderStructure",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, any existing database matching the name of a database being restored will be overwritten.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Restore-DbaBackupFromDirectory [-SqlInstance] \u003cDbaInstanceParameter\u003e [-Path] \u003cString\u003e [-NoRecovery] [-ReuseSourceFolderStructure] [[-SqlCredential] \u003cPSCredential\u003e] [-Force] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Restore-DbaDatabase",
        "Description":  "Upon being passed a list of potential backups files this command will scan the files, select those that contain SQL Server\nbackup sets. It will then filter those files down to a set that can perform the requested restore, checking that we have a\nfull restore chain to the point in time requested by the caller.\n\nThe function defaults to working on a remote instance. This means that all paths passed in must be relative to the remote instance.\nXpDirTree will be used to perform the file scans\n\nVarious means can be used to pass in a list of files to be considered. The default is to non recursively scan the folder\npassed in.",
        "Tags":  [
                     "DisasterRecovery",
                     "Backup",
                     "Restore"
                 ],
        "Synopsis":  "Restores a SQL Server Database from a set of backup files",
        "Alias":  "",
        "Author":  "Stuart Moore (@napalmgram), stuart-moore.com",
        "CommandName":  "Restore-DbaDatabase",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Restore-DbaDatabase",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRestore-DbaDatabase -SqlInstance server1\\instance1 -Path \\\\server2\\backups\nScans all the backup files in \\\\server2\\backups, filters them and restores the database to server1\\instance1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRestore-DbaDatabase -SqlInstance server1\\instance1 -Path \\\\server2\\backups -MaintenanceSolutionBackup -DestinationDataDirectory c:\\restores\nScans all the backup files in \\\\server2\\backups$ stored in an Ola Hallengren style folder structure,\r\nfilters them and restores the database to the c:\\restores folder on server1\\instance1\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-ChildItem c:\\SQLbackups1\\, \\\\server\\sqlbackups2 | Restore-DbaDatabase -SqlInstance server1\\instance1\nTakes the provided files from multiple directories and restores them on  server1\\instance1\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$RestoreTime = Get-Date(\u002711:19 23/12/2016\u0027)\nPS C:\\\u003e Restore-DbaDatabase -SqlInstance server1\\instance1 -Path \\\\server2\\backups -MaintenanceSolutionBackup -DestinationDataDirectory c:\\restores -RestoreTime $RestoreTime\nScans all the backup files in \\\\server2\\backups stored in an Ola Hallengren style folder structure,\r\nfilters them and restores the database to the c:\\restores folder on server1\\instance1 up to 11:19 23/12/2016\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$result = Restore-DbaDatabase -SqlInstance server1\\instance1 -Path \\\\server2\\backups -DestinationDataDirectory c:\\restores -OutputScriptOnly\nPS C:\\\u003e $result | Select-Object -ExpandProperty Tsql | Out-File -Filepath c:\\scripts\\restore.sql\nScans all the backup files in \\\\server2\\backups stored in an Ola Hallengren style folder structure,\r\nfilters them and generate the T-SQL Scripts to restore the database to the latest point in time,\r\nand then stores the output in a file for later retrieval\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eRestore-DbaDatabase -SqlInstance server1\\instance1 -Path c:\\backups -DestinationDataDirectory c:\\DataFiles -DestinationLogDirectory c:\\LogFile\nScans all the files in c:\\backups and then restores them onto the SQL Server Instance server1\\instance1, placing data files\r\nc:\\DataFiles and all the log files into c:\\LogFiles\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eRestore-DbaDatabase -SqlInstance server1\\instance1 -Path http://demo.blob.core.windows.net/backups/dbbackup.bak -AzureCredential MyAzureCredential\nWill restore the backup held at  http://demo.blob.core.windows.net/backups/dbbackup.bak to server1\\instance1. The connection to Azure will be made using the\r\ncredential MyAzureCredential held on instance Server1\\instance1\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eRestore-DbaDatabase -SqlInstance server1\\instance1 -Path http://demo.blob.core.windows.net/backups/dbbackup.bak\nWill attempt to restore the backups from http://demo.blob.core.windows.net/backups/dbbackup.bak if a SAS credential with the name http://demo.blob.core.windows.net/backups exists on server1\\instance1\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003e$File = Get-ChildItem c:\\backups, \\\\server1\\backups -recurse\nPS C:\\\u003e $File | Restore-DbaDatabase -SqlInstance Server1\\Instance -UseDestinationDefaultDirectories\nThis will take all of the files found under the folders c:\\backups and \\\\server1\\backups, and pipeline them into\r\nRestore-DbaDatabase. Restore-DbaDatabase will then scan all of the files, and restore all of the databases included\r\nto the latest point in time covered by their backups. All data and log files will be moved to the default SQL Server\r\nfolder for those file types as defined on the target instance.\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003e$files = Get-ChildItem C:\\dbatools\\db1\nPS C:\\\u003e $files | Restore-DbaDatabase -SqlInstance server\\instance1 `\r\n\u003e\u003e -DestinationFilePrefix prefix -DatabaseName Restored  `\r\n\u003e\u003e -RestoreTime (get-date \"14:58:30 22/05/2017\") `\r\n\u003e\u003e -NoRecovery -WithReplace -StandbyDirectory C:\\dbatools\\standby\r\n\u003e\u003e\r\nPS C:\\\u003e #It\u0027s in standby so we can peek at it\r\nPS C:\\\u003e Invoke-DbaQuery -SQLInstance server\\instance1 -Query \"select top 1 * from Restored.dbo.steps order by dt desc\"\r\nPS C:\\\u003e #Not quite there so let\u0027s roll on a bit:\r\nPS C:\\\u003e $files | Restore-DbaDatabase -SqlInstance server\\instance1 `\r\n\u003e\u003e -DestinationFilePrefix prefix -DatabaseName Restored `\r\n\u003e\u003e -continue -WithReplace -RestoreTime (get-date \"15:09:30 22/05/2017\") `\r\n\u003e\u003e -StandbyDirectory C:\\dbatools\\standby\r\n\u003e\u003e\r\nPS C:\\\u003e Invoke-DbaQuery -SQLInstance server\\instance1 -Query \"select top 1 * from restored.dbo.steps order by dt desc\"\r\nPS C:\\\u003e Restore-DbaDatabase -SqlInstance server\\instance1 -DestinationFilePrefix prefix -DatabaseName Restored -Continue -WithReplace\nIn this example we step through the backup files held in c:\\dbatools\\db1 folder.\r\nFirst we restore the database to a point in time in standby mode. This means we can check some details in the databases\r\nWe then roll it on a further 9 minutes to perform some more checks\r\nAnd finally we continue by rolling it all the way forward to the latest point in the backup.\r\nAt each step, only the log files needed to roll the database forward are restored.\n-------------------------- EXAMPLE 11 --------------------------\nPS C:\\\u003eRestore-DbaDatabase -SqlInstance server\\instance1 -Path c:\\backups -DatabaseName example1 -NoRecovery\nPS C:\\\u003e Restore-DbaDatabase -SqlInstance server\\instance1 -Recover -DatabaseName example1\nIn this example we restore example1 database with no recovery, and then the second call is to set the database to recovery.\n-------------------------- EXAMPLE 12 --------------------------\nPS C:\\\u003eGet-DbaBackupHistory - SqlInstance server\\instance1 -Database ProdFinance -Last | Restore-DbaDatabase -PageRestore\nPS C:\\\u003e $SuspectPage -PageRestoreTailFolder c:\\temp -TrustDbBackupHistory -AllowContinues\nGets a list of Suspect Pages using Get-DbaSuspectPage. The uses Get-DbaBackupHistory and Restore-DbaDatabase to perform a restore of the suspect pages and bring them up to date\r\nIf server\\instance1 is Enterprise edition this will be done online, if not it will be performed offline\r\nAllowContinue is required to make sure we cope with existing files\n-------------------------- EXAMPLE 13 --------------------------\nPS C:\\\u003e$BackupHistory = Get-DbaBackupInformation -SqlInstance sql2005 -Path \\\\backups\\sql2000\\ProdDb\nPS C:\\\u003e $BackupHistory | Restore-DbaDatabase -SqlInstance sql2000 -TrustDbBackupHistory\nDue to SQL Server 2000 not returning all the backup headers we cannot restore directly. As this is an issues with the SQL engine all we can offer is the following workaround\r\nThis will use a SQL Server instance \u003e 2000 to read the headers, and then pass them in to Restore-DbaDatabase as a BackupHistory object.\n-------------------------- EXAMPLE 14 --------------------------\nPS C:\\\u003eRestore-DbaDatabase -SqlInstance server1\\instance1 -Path \"C:\\Temp\\devops_prod_full.bak\" -DatabaseName \"DevOps_DEV\" -ReplaceDbNameInFile\nPS C:\\\u003e Rename-DbaDatabase -SqlInstance server1\\instance1 -Database \"DevOps_DEV\" -LogicalName \"\u003cDBN\u003e_\u003cFT\u003e\"\nThis will restore the database from the \"C:\\Temp\\devops_prod_full.bak\" file, with the new name \"DevOps_DEV\" and store the different physical files with the new name. It will use the system default \r\nconfigured data and log locations.\r\nAfter the restore the logical names of the database files will be renamed with the \"DevOps_DEV_ROWS\" for MDF/NDF and \"DevOps_DEV_LOG\" for LDF\n-------------------------- EXAMPLE 15 --------------------------\nPS C:\\\u003e$FileStructure = @{\n\u003e\u003e \u0027database_data\u0027 = \u0027C:\\Data\\database_data.mdf\u0027\r\n\u003e\u003e \u0027database_log\u0027 = \u0027C:\\Log\\database_log.ldf\u0027\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Restore-DbaDatabase -SqlInstance server1 -Path \\\\ServerName\\ShareName\\File -DatabaseName database -FileMapping $FileStructure\nRestores \u0027database\u0027 to \u0027server1\u0027 and moves the files to new locations. The format for the $FileStructure HashTable is the file logical name as the Key, and the new location as the Value.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "Path to SQL Server backup files.\nPaths passed in as strings will be scanned using the desired method, default is a non recursive folder scan\r\nAccepts multiple paths separated by \u0027,\u0027\nOr it can consist of FileInfo objects, such as the output of Get-ChildItem or Get-Item. This allows you to work with\r\nyour own file structures as needed",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "DatabaseName",
                           "Name to restore the database under.\r\nOnly works with a single database restore. If multiple database are found in the provided paths then we will exit",
                           "Name",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "DestinationDataDirectory",
                           "Path to restore the SQL Server backups to on the target instance.\r\nIf only this parameter is specified, then all database files (data and log) will be restored to this location",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DestinationLogDirectory",
                           "Path to restore the database log files to.\r\nThis parameter can only be specified alongside DestinationDataDirectory.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DestinationFileStreamDirectory",
                           "Path to restore FileStream data to\r\nThis parameter can only be specified alongside DestinationDataDirectory",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RestoreTime",
                           "Specify a DateTime object to which you want the database restored to. Default is to the latest point  available in the specified backups",
                           "",
                           false,
                           "false",
                           "(Get-Date).AddYears(1)"
                       ],
                       [
                           "NoRecovery",
                           "Indicates if the databases should be recovered after last restore. Default is to recover",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WithReplace",
                           "Switch indicated is the restore is allowed to replace an existing database.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "XpDirTree",
                           "Switch that indicated file scanning should be performed by the SQL Server instance using xp_dirtree\r\nThis will scan recursively from the passed in path\r\nYou must have sysadmin role membership on the instance for this to work.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "OutputScriptOnly",
                           "Switch indicates that ONLY T-SQL scripts should be generated, no restore takes place",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "VerifyOnly",
                           "Switch indicate that restore should be verified",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "MaintenanceSolutionBackup",
                           "Switch to indicate the backup files are in a folder structure as created by Ola Hallengreen\u0027s maintenance scripts.\r\nThis switch enables a faster check for suitable backups. Other options require all files to be read first to ensure we have an anchoring full backup. Because we can rely on specific locations for \r\nbackups performed with OlaHallengren\u0027s backup solution, we can rely on file locations.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "FileMapping",
                           "A hashtable that can be used to move specific files to a location.\r\n`$FileMapping = @{\u0027DataFile1\u0027=\u0027c:\\restoredfiles\\Datafile1.mdf\u0027;\u0027DataFile3\u0027=\u0027d:\\DataFile3.mdf\u0027}`\r\nAnd files not specified in the mapping will be restored to their original location\r\nThis Parameter is exclusive with DestinationDataDirectory",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IgnoreLogBackup",
                           "This switch tells the function to ignore transaction log backups. The process will restore to the latest full or differential backup point only",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "UseDestinationDefaultDirectories",
                           "Switch that tells the restore to use the default Data and Log locations on the target server. If they don\u0027t exist, the function will try to create them",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ReuseSourceFolderStructure",
                           "By default, databases will be migrated to the destination Sql Server\u0027s default data and log directories. You can override this by specifying -ReuseSourceFolderStructure.\r\nThe same structure on the SOURCE will be kept exactly, so consider this if you\u0027re migrating between different versions and use part of Microsoft\u0027s default Sql structure (MSSql12.INSTANCE, etc)\n*Note, to reuse destination folder structure, specify -WithReplace",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DestinationFilePrefix",
                           "This value will be prefixed to ALL restored files (log and data). This is just a simple string prefix. If you want to perform more complex rename operations then please use the FileMapping parameter\nThis will apply to all file move options, except for FileMapping",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RestoredDatabaseNamePrefix",
                           "A string which will be prefixed to the start of the restore Database\u0027s Name\r\nUseful if restoring a copy to the same sql server for testing.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "TrustDbBackupHistory",
                           "This switch can be used when piping the output of Get-DbaBackupHistory or Backup-DbaDatabase into this command.\r\nIt allows the user to say that they trust that the output from those commands is correct, and skips the file header read portion of the process. This means a faster process, but at the risk of not \r\nknowing till halfway through the restore that something is wrong with a file.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "MaxTransferSize",
                           "Parameter to set the unit of transfer. Values must be a multiple by 64kb",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "BlockSize",
                           "Specifies the block size to use. Must be one of 0.5kb,1kb,2kb,4kb,8kb,16kb,32kb or 64kb\r\nCan be specified in bytes\r\nRefer to https://msdn.microsoft.com/en-us/library/ms178615.aspx for more detail",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "BufferCount",
                           "Number of I/O buffers to use to perform the operation.\r\nRefer to https://msdn.microsoft.com/en-us/library/ms178615.aspx for more detail",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "DirectoryRecurse",
                           "If specified the specified directory will be recursed into",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "StandbyDirectory",
                           "If a directory is specified the database(s) will be restored into a standby state, with the standby file placed into this directory (which must exist, and be writable by the target Sql Server \r\ninstance)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Continue",
                           "If specified we will to attempt to recover more transaction log backups onto  database(s) in Recovering or Standby states",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "AzureCredential",
                           "The name of the SQL Server credential to be used if restoring from an Azure hosted backup using Storage Access Keys\r\nIf a backup path beginning http is passed in and this parameter is not specified then if a credential with a name matching the URL",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ReplaceDbNameInFile",
                           "If switch set and occurrence of the original database\u0027s name in a data or log file will be replace with the name specified in the DatabaseName parameter",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DestinationFileSuffix",
                           "This value will be suffixed to ALL restored files (log and data). This is just a simple string suffix. If you want to perform more complex rename operations then please use the FileMapping parameter\nThis will apply to all file move options, except for FileMapping",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Recover",
                           "If set will perform recovery on the indicated database",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "KeepCDC",
                           "Indicates whether CDC information should be restored as part of the database",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "AllowContinue",
                           "By default, Restore-DbaDatabase will stop restoring any databases if it comes across an error.\r\nUse this switch to enable it to restore all databases without issues.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "GetBackupInformation",
                           "Passing a string value into this parameter will cause a global variable to be created holding the output of Get-DbaBackupInformation",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "StopAfterGetBackupInformation",
                           "Switch which will cause the function to exit after returning GetBackupInformation",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "SelectBackupInformation",
                           "Passing a string value into this parameter will cause a global variable to be created holding the output of Select-DbaBackupInformation",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "StopAfterSelectBackupInformation",
                           "Switch which will cause the function to exit after returning SelectBackupInformation",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "FormatBackupInformation",
                           "Passing a string value into this parameter will cause a global variable to be created holding the output of Format-DbaBackupInformation",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "StopAfterFormatBackupInformation",
                           "Switch which will cause the function to exit after returning FormatBackupInformation",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "TestBackupInformation",
                           "Passing a string value into this parameter will cause a global variable to be created holding the output of Test-DbaBackupInformation",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "StopAfterTestBackupInformation",
                           "Switch which will cause the function to exit after returning TestBackupInformation",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "PageRestore",
                           "Passes in an object from Get-DbaSuspectPages containing suspect pages from a single database.\r\nSetting this Parameter will cause an Online Page restore if the target Instance is Enterprise Edition, or offline if not.\r\nThis will involve taking a tail log backup, so you must check your restore chain once it has completed",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "PageRestoreTailFolder",
                           "This parameter passes in a location for the tail log backup required for page level restore",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "StatementTimeout",
                           "Timeout in minutes. Defaults to infinity (restores can take a while.)",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command would execute, but does not actually perform the command",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts to confirm certain actions",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Restore-DbaDatabase -SqlInstance \u003cDbaInstanceParameter\u003e [-SqlCredential \u003cPSCredential\u003e] -Path \u003cObject[]\u003e [-DatabaseName \u003cObject[]\u003e] [-DestinationDataDirectory \u003cString\u003e] [-DestinationLogDirectory \u003cString\u003e] [-DestinationFileStreamDirectory \u003cString\u003e] [-RestoreTime \u003cDateTime\u003e] [-NoRecovery] [-WithReplace] [-XpDirTree] [-OutputScriptOnly] [-VerifyOnly] [-MaintenanceSolutionBackup] [-FileMapping \u003cHashtable\u003e] [-IgnoreLogBackup] [-UseDestinationDefaultDirectories] [-ReuseSourceFolderStructure] [-DestinationFilePrefix \u003cString\u003e] [-RestoredDatabaseNamePrefix \u003cString\u003e] [-TrustDbBackupHistory] \r\n[-MaxTransferSize \u003cInt32\u003e] [-BlockSize \u003cInt32\u003e] [-BufferCount \u003cInt32\u003e] [-DirectoryRecurse] [-EnableException] [-StandbyDirectory \u003cString\u003e] [-Continue] [-AzureCredential \u003cString\u003e] [-ReplaceDbNameInFile] [-DestinationFileSuffix \u003cString\u003e] [-KeepCDC] [-AllowContinue] [-GetBackupInformation \u003cString\u003e] [-StopAfterGetBackupInformation] [-SelectBackupInformation \u003cString\u003e] [-StopAfterSelectBackupInformation] [-FormatBackupInformation \u003cString\u003e] [-StopAfterFormatBackupInformation] [-TestBackupInformation \u003cString\u003e] [-StopAfterTestBackupInformation] [-StatementTimeout \u003cInt32\u003e] [-WhatIf] [-Confirm] \r\n[\u003cCommonParameters\u003e]\nRestore-DbaDatabase -SqlInstance \u003cDbaInstanceParameter\u003e [-SqlCredential \u003cPSCredential\u003e] -Path \u003cObject[]\u003e [-DatabaseName \u003cObject[]\u003e] [-OutputScriptOnly] [-TrustDbBackupHistory] [-MaxTransferSize \u003cInt32\u003e] [-BlockSize \u003cInt32\u003e] [-BufferCount \u003cInt32\u003e] [-EnableException] [-AzureCredential \u003cString\u003e] [-AllowContinue] [-GetBackupInformation \u003cString\u003e] [-StopAfterGetBackupInformation] [-SelectBackupInformation \u003cString\u003e] [-StopAfterSelectBackupInformation] [-FormatBackupInformation \u003cString\u003e] [-StopAfterFormatBackupInformation] [-TestBackupInformation \u003cString\u003e] [-StopAfterTestBackupInformation] \r\n-PageRestore \u003cObject\u003e -PageRestoreTailFolder \u003cString\u003e [-StatementTimeout \u003cInt32\u003e] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRestore-DbaDatabase -SqlInstance \u003cDbaInstanceParameter\u003e [-SqlCredential \u003cPSCredential\u003e] [-DatabaseName \u003cObject[]\u003e] [-OutputScriptOnly] [-EnableException] [-AzureCredential \u003cString\u003e] [-Recover] [-AllowContinue] [-GetBackupInformation \u003cString\u003e] [-StopAfterGetBackupInformation] [-SelectBackupInformation \u003cString\u003e] [-StopAfterSelectBackupInformation] [-FormatBackupInformation \u003cString\u003e] [-StopAfterFormatBackupInformation] [-TestBackupInformation \u003cString\u003e] [-StopAfterTestBackupInformation] [-StatementTimeout \u003cInt32\u003e] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Restore-DbaDbCertificate",
        "Description":  "Imports certificates from.cer files using SMO.",
        "Tags":  [
                     "Migration",
                     "Certificate"
                 ],
        "Synopsis":  "Imports certificates from .cer files using SMO.",
        "Alias":  "Restore-DbaDatabaseCertificate",
        "Author":  "Jess Pomfret (@jpomfret), jesspomfret.com",
        "CommandName":  "Restore-DbaDbCertificate",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Restore-DbaDbCertificate",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRestore-DbaDbCertificate -SqlInstance Server1 -Path \\\\Server1\\Certificates -SecurePassword (ConvertTo-SecureString -Force -AsPlainText GoodPass1234!!)\nRestores all the certificates in the specified path, password is used to both decrypt and encrypt the private key.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRestore-DbaDbCertificate -SqlInstance Server1 -Path \\\\Server1\\Certificates\\DatabaseTDE.cer -SecurePassword (ConvertTo-SecureString -force -AsPlainText GoodPass1234!!)\nRestores the DatabaseTDE certificate to Server1 and uses the MasterKey to encrypt the private key.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "The Path the contains the certificate and private key files. The path can be a directory or a specific certificate.",
                           "FullName",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EncryptionPassword",
                           "If specified this will be used to encrypt the private key.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database where the certificate imports into. Defaults to master.",
                           "",
                           false,
                           "false",
                           "master"
                       ],
                       [
                           "SecurePassword",
                           "Secure string used to decrypt the private key.",
                           "Password",
                           false,
                           "false",
                           "(Read-Host \"Password\" -AsSecureString)"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Restore-DbaDbCertificate [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Path] \u003cObject[]\u003e [[-EncryptionPassword] \u003cSecureString\u003e] [[-Database] \u003cString\u003e] [[-SecurePassword] \u003cSecureString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Restore-DbaDbSnapshot",
        "Description":  "Restores the database from the snapshot, discarding every modification made to the database\nNB: Restoring to a snapshot will result in every other snapshot of the same database to be dropped\nIt also fixes some long-standing bugs in SQL Server when restoring from snapshots",
        "Tags":  [
                     "Snapshot",
                     "Backup",
                     "Restore",
                     "Database"
                 ],
        "Synopsis":  "Restores databases from snapshots",
        "Alias":  "Restore-DbaDatabaseSnapshot",
        "Author":  "Simone Bizzotto (@niphold)",
        "CommandName":  "Restore-DbaDbSnapshot",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Restore-DbaDbSnapshot",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRestore-DbaDbSnapshot -SqlInstance sql2014 -Database HR, Accounting\nRestores HR and Accounting databases using the latest snapshot available\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRestore-DbaDbSnapshot -SqlInstance sql2014 -Database HR -Force\nRestores HR database from latest snapshot and kills any active connections in the database on sql2014.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbSnapshot -SqlInstance sql2016 -Database HR | Restore-DbaDbSnapshot -Force\nRestores HR database from latest snapshot and kills any active connections in the database on sql2016.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbSnapshot -SqlInstance sql2016 | Out-GridView -PassThru | Restore-DbaDbSnapshot\nAllows the selection of snapshots on sql2016 to restore\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eRestore-DbaDbSnapshot -SqlInstance sql2014 -Snapshot HR_snap_20161201, Accounting_snap_20161101\nRestores databases from snapshots named HR_snap_20161201 and Accounting_snap_20161101",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Credential object used to connect to the SQL Server as a different user",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Restores from the last snapshot databases with this names only. You can pass either Databases or Snapshots",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Snapshot",
                           "Restores databases from snapshots with this names only. You can pass either Databases or Snapshots",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows piping from other Snapshot commands",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Force",
                           "If restoring from a snapshot involves dropping any other snapshot, you need to explicitly\r\nuse -Force to let this command delete the ones not involved in the restore process.\r\nAlso, -Force will forcibly kill all running queries that prevent the restore process.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts for confirmation of every step.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Restore-DbaDbSnapshot [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-Snapshot] \u003cObject[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Resume-DbaAgDbDataMovement",
        "Description":  "Resumes data movement for an availability group database on a SQL Server instance.",
        "Tags":  [
                     "AvailabilityGroup",
                     "HA",
                     "AG"
                 ],
        "Synopsis":  "Resumes data movement for an availability group database on a SQL Server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Resume-DbaAgDbDataMovement",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Resume-DbaAgDbDataMovement",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eResume-DbaAgDbDataMovement -SqlInstance sql2017a -AvailabilityGroup ag1 -Database db1, db2\nResumes data movement on db1 and db2 to ag1 on sql2017a. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgDatabase -SqlInstance sql2017a, sql2019 | Out-GridView -Passthru | Resume-DbaAgDbDataMovement -Confirm:$false\nResumes data movement on the selected availability group databases. Does not prompt for confirmation.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityGroup",
                           "The availability group where the database movement will be resumeed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database or databases to resume movement upon.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaAgDatabase",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Resume-DbaAgDbDataMovement [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cAvailabilityDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Revoke-DbaAgPermission",
        "Description":  "Revokes endpoint and availability group permissions to a login.",
        "Tags":  [
                     "AvailabilityGroup",
                     "HA",
                     "AG"
                 ],
        "Synopsis":  "Revokes endpoint and availability group permissions to a login.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Revoke-DbaAgPermission",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Revoke-DbaAgPermission",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRevoke-DbaAgPermission -SqlInstance sql2017a -Type AvailabilityGroup -AvailabilityGroup SharePoint -Login ad\\spservice -Permission CreateAnyDatabase\nRemoves CreateAnyDatabase permissions from ad\\spservice on the SharePoint availability group on sql2017a. Does not prompt for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRevoke-DbaAgPermission -SqlInstance sql2017a -Type AvailabilityGroup -AvailabilityGroup ag1, ag2 -Login ad\\spservice -Permission CreateAnyDatabase -Confirm\nRemoves CreateAnyDatabase permissions from ad\\spservice on the ag1 and ag2 availability groups on sql2017a. Prompts for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2017a | Out-GridView -Passthru | Revoke-DbaAgPermission -Type EndPoint\nRevokes the selected logins Connect permissions on the DatabaseMirroring endpoint for sql2017a.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Login",
                           "The login or logins to modify.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityGroup",
                           "Only modify specific availability groups.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Type",
                           "Specify type: Endpoint or AvailabilityGroup. Endpoint will modify the DatabaseMirror endpoint type.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Permission",
                           "Revokes one or more permissions:\r\n    Alter\r\n    Connect\r\n    Control\r\n    CreateAnyDatabase\r\n    CreateSequence\r\n    Delete\r\n    Execute\r\n    Impersonate\r\n    Insert\r\n    Receive\r\n    References\r\n    Select\r\n    Send\r\n    TakeOwnership\r\n    Update\r\n    ViewChangeTracking\r\n    ViewDefinition\nConnect is default.",
                           "",
                           false,
                           "false",
                           "Connect"
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaLogin.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Revoke-DbaAgPermission [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Login] \u003cString[]\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [-Type] \u003cString[]\u003e [[-Permission] \u003cString[]\u003e] [[-InputObject] \u003cLogin[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Save-DbaDiagnosticQueryScript",
        "Description":  "The dbatools module will have the diagnostic queries pre-installed. Use this only to update to a more recent version or specific versions.\n\nThis function is mainly used by Invoke-DbaDiagnosticQuery, but can also be used independently to download the Glenn Berry DMV scripts.\n\nUse this function to pre-download the scripts from a device with an Internet connection.\n\nThe function Invoke-DbaDiagnosticQuery will try to download these scripts automatically, but it obviously needs an internet connection to do that.",
        "Tags":  [
                     "Diagnostic",
                     "DMV",
                     "Troubleshooting"
                 ],
        "Synopsis":  "Save-DbaDiagnosticQueryScript downloads the most recent version of all Glenn Berry DMV scripts",
        "Alias":  "",
        "Author":  "Andre Kamman (@AndreKamman), http://clouddba.io",
        "CommandName":  "Save-DbaDiagnosticQueryScript",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSave-DbaDiagnosticQueryScript -Path c:\\temp\nDownloads the most recent version of all Glenn Berry DMV scripts to the specified location.\r\nIf Path is not specified, the \"My Documents\" location will be used.",
        "Params":  [
                       [
                           "Path",
                           "Specifies the path to the output",
                           "",
                           false,
                           "false",
                           "[Environment]::GetFolderPath(\"mydocuments\")"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Save-DbaDiagnosticQueryScript [[-Path] \u003cFileInfo\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Select-DbaBackupInformation",
        "Description":  "Select-DbaBackupInformation filters out a subset of backups from the dbatools backup history object with parameters supplied.",
        "Tags":  [
                     "Backup",
                     "Restore"
                 ],
        "Synopsis":  "Select a subset of backups from a dbatools backup history object",
        "Alias":  "",
        "Author":  "Stuart Moore (@napalmgram), stuart-moore.com",
        "CommandName":  "Select-DbaBackupInformation",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Select-DbaBackupInformation",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\\\server1\\backups$\nPS C:\\\u003e $FilteredBackups = $Backups | Select-DbaBackupInformation -RestoreTime (Get-Date).AddHours(-1)\nReturns all backups needed to restore all the backups in \\\\server1\\backups$ to 1 hour ago\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\\\server1\\backups$\nPS C:\\\u003e $FilteredBackups = $Backups | Select-DbaBackupInformation -RestoreTime (Get-Date).AddHours(-1) -DatabaseName ProdFinance\nReturns all the backups needed to restore Database ProdFinance to an hour ago\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\\\server1\\backups$\nPS C:\\\u003e $FilteredBackups = $Backups | Select-DbaBackupInformation -RestoreTime (Get-Date).AddHours(-1) -IgnoreLogs\nReturns all the backups in \\\\server1\\backups$ to restore to as close prior to 1 hour ago as can be managed with only full and differential backups\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\\\server1\\backups$\nPS C:\\\u003e $FilteredBackups = $Backups | Select-DbaBackupInformation -RestoreTime (Get-Date).AddHours(-1) -IgnoreDiffs\nReturns all the backups in \\\\server1\\backups$ to restore to 1 hour ago using only Full and Diff backups.",
        "Params":  [
                       [
                           "BackupHistory",
                           "A dbatools.BackupHistory object containing backup history records",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "RestoreTime",
                           "The point in time you want to restore to",
                           "",
                           false,
                           "false",
                           "(get-date).addmonths(1)"
                       ],
                       [
                           "IgnoreLogs",
                           "This switch will cause Log Backups to be ignored. So will restore to the last Full or Diff backup only",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IgnoreDiffs",
                           "This switch will cause Differential backups to be ignored. Unless IgnoreLogs is specified, restore to point in time will still occur, just using all available log backups",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DatabaseName",
                           "A string array of Database Names that you want to filter to",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ServerName",
                           "A string array of Server Names that you want to filter",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ContinuePoints",
                           "The Output of Get-RestoreContinuableDatabase while provides \u0027Database\u0027,redo_start_lsn,\u0027FirstRecoveryForkID\u0027 values. Used to filter backups to continue a restore on a database\r\nSets IgnoreDiffs, and also filters databases to only those within the ContinuePoints object, or the ContinuePoints object AND DatabaseName if both specified",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "LastRestoreType",
                           "The Output of Get-DbaDbRestoreHistory -last\r\nThis is used to check the last type of backup to a database to see if a differential backup can be restored",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Select-DbaBackupInformation [-BackupHistory] \u003cObject\u003e [[-RestoreTime] \u003cDateTime\u003e] [-IgnoreLogs] [-IgnoreDiffs] [[-DatabaseName] \u003cString[]\u003e] [[-ServerName] \u003cString[]\u003e] [[-ContinuePoints] \u003cObject\u003e] [[-LastRestoreType] \u003cObject\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaAgentAlert",
        "Description":  "Set-DbaAgentAlert updates an alert in the SQL Server Agent with parameters supplied.",
        "Tags":  [
                     "Agent",
                     "Alert"
                 ],
        "Synopsis":  "Set-DbaAgentAlert updates a the status of a SQL Agent Alert.",
        "Alias":  "",
        "Author":  "Garry Bargsley (@gbargsley), garrybargsley.com",
        "CommandName":  "Set-DbaAgentAlert",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaAgentAlert",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaAgentAlert -SqlInstance sql1 -Alert \u0027Severity 025: Fatal Error\u0027 -Disabled\nChanges the alert to disabled.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaAgentAlert -SqlInstance sql1 -Alert \u0027Severity 025: Fatal Error\u0027, \u0027Error Number 825\u0027, \u0027Error Number 824\u0027 -Enabled\nChanges multiple alerts to enabled.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaAgentAlert -SqlInstance sql1, sql2, sql3 -Alert \u0027Severity 025: Fatal Error\u0027, \u0027Error Number 825\u0027, \u0027Error Number 824\u0027 -Enabled\nChanges multiple alerts to enabled on multiple servers.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaAgentAlert -SqlInstance sql1 -Alert \u0027Severity 025: Fatal Error\u0027 -Disabled -WhatIf\nDoesn\u0027t Change the alert but shows what would happen.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Alert",
                           "The name of the alert.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NewName",
                           "The new name for the alert.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Enabled",
                           "Enabled the alert.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Disabled",
                           "Disabled the alert.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "The force parameter will ignore some errors in the parameters and assume defaults.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Enables piping alert objects",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaAgentAlert [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Alert] \u003cObject[]\u003e] [[-NewName] \u003cString\u003e] [-Enabled] [-Disabled] [-Force] [[-InputObject] \u003cAlert[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaAgentJob",
        "Description":  "Set-DbaAgentJob updates a job in the SQL Server Agent with parameters supplied.",
        "Tags":  [
                     "Agent",
                     "Job"
                 ],
        "Synopsis":  "Set-DbaAgentJob updates a job.",
        "Alias":  "",
        "Author":  "Sander Stad (@sqlstad), sqlstad.nl",
        "CommandName":  "Set-DbaAgentJob",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaAgentJob",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaAgentJob sql1 -Job Job1 -Disabled\nChanges the job to disabled\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaAgentJob sql1 -Job Job1 -OwnerLogin user1\nChanges the owner of the job\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaAgentJob -SqlInstance sql1 -Job Job1 -EventLogLevel OnSuccess\nChanges the job and sets the notification to write to the Windows Application event log on success\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaAgentJob -SqlInstance sql1 -Job Job1 -EmailLevel OnFailure -EmailOperator dba\nChanges the job and sets the notification to send an e-mail to the e-mail operator\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eSet-DbaAgentJob -SqlInstance sql1 -Job Job1, Job2, Job3 -Enabled\nChanges multiple jobs to enabled\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eSet-DbaAgentJob -SqlInstance sql1, sql2, sql3 -Job Job1, Job2, Job3 -Enabled\nChanges multiple jobs to enabled on multiple servers\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eSet-DbaAgentJob -SqlInstance sql1 -Job Job1 -Description \u0027Just another job\u0027 -Whatif\nDoesn\u0027t Change the job but shows what would happen.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eSet-DbaAgentJob -SqlInstance sql1, sql2, sql3 -Job \u0027Job One\u0027 -Description \u0027Job One\u0027\nChanges a job with the name \"Job1\" on multiple servers to have another description\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003esql1, sql2, sql3 | Set-DbaAgentJob -Job Job1 -Description \u0027Job One\u0027\nChanges a job with the name \"Job1\" on multiple servers to have another description using pipe line",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Job",
                           "The name of the job.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Schedule",
                           "Schedule to attach to job. This can be more than one schedule.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ScheduleId",
                           "Schedule ID to attach to job. This can be more than one schedule ID.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NewName",
                           "The new name for the job.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Enabled",
                           "Enabled the job.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Disabled",
                           "Disabled the job",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Description",
                           "The description of the job.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "StartStepId",
                           "The identification number of the first step to execute for the job.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "Category",
                           "The category of the job.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "OwnerLogin",
                           "The name of the login that owns the job.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EventLogLevel",
                           "Specifies when to place an entry in the Microsoft Windows application log for this job.\r\nAllowed values 0, \"Never\", 1, \"OnSuccess\", 2, \"OnFailure\", 3, \"Always\"\r\nThe text value van either be lowercase, uppercase or something in between as long as the text is correct.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EmailLevel",
                           "Specifies when to send an e-mail upon the completion of this job.\r\nAllowed values 0, \"Never\", 1, \"OnSuccess\", 2, \"OnFailure\", 3, \"Always\"\r\nThe text value van either be lowercase, uppercase or something in between as long as the text is correct.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NetsendLevel",
                           "Specifies when to send a network message upon the completion of this job.\r\nAllowed values 0, \"Never\", 1, \"OnSuccess\", 2, \"OnFailure\", 3, \"Always\"\r\nThe text value van either be lowercase, uppercase or something in between as long as the text is correct.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "PageLevel",
                           "Specifies when to send a page upon the completion of this job.\r\nAllowed values 0, \"Never\", 1, \"OnSuccess\", 2, \"OnFailure\", 3, \"Always\"\r\nThe text value van either be lowercase, uppercase or something in between as long as the text is correct.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EmailOperator",
                           "The e-mail name of the operator to whom the e-mail is sent when EmailLevel is reached.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NetsendOperator",
                           "The name of the operator to whom the network message is sent.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "PageOperator",
                           "The name of the operator to whom a page is sent.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DeleteLevel",
                           "Specifies when to delete the job.\r\nAllowed values 0, \"Never\", 1, \"OnSuccess\", 2, \"OnFailure\", 3, \"Always\"\r\nThe text value van either be lowercase, uppercase or something in between as long as the text is correct.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "The force parameter will ignore some errors in the parameters and assume defaults.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Enables piping job objects",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaAgentJob [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Job] \u003cObject[]\u003e] [[-Schedule] \u003cObject[]\u003e] [[-ScheduleId] \u003cInt32[]\u003e] [[-NewName] \u003cString\u003e] [-Enabled] [-Disabled] [[-Description] \u003cString\u003e] [[-StartStepId] \u003cInt32\u003e] [[-Category] \u003cString\u003e] [[-OwnerLogin] \u003cString\u003e] [[-EventLogLevel] \u003cObject\u003e] [[-EmailLevel] \u003cObject\u003e] [[-NetsendLevel] \u003cObject\u003e] [[-PageLevel] \u003cObject\u003e] [[-EmailOperator] \u003cString\u003e] [[-NetsendOperator] \u003cString\u003e] [[-PageOperator] \u003cString\u003e] [[-DeleteLevel] \u003cObject\u003e] [-Force] [[-InputObject] \u003cJob[]\u003e] [-EnableException] [-WhatIf] [-Confirm] \r\n[\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaAgentJobCategory",
        "Description":  "Set-DbaAgentJobCategory makes it possible to change a job category.",
        "Tags":  [
                     "Agent",
                     "Job",
                     "JobCategory"
                 ],
        "Synopsis":  "Set-DbaAgentJobCategory changes a job category.",
        "Alias":  "",
        "Author":  "Sander Stad (@sqlstad), sqlstad.nl",
        "CommandName":  "Set-DbaAgentJobCategory",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaAgentJobCategory",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaAgentJobCategory -SqlInstance sql1 -Category \u0027Category 1\u0027 -NewName \u0027Category 2\u0027\nChange the name of the category from \u0027Category 1\u0027 to \u0027Category 2\u0027.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaAgentJobCategory -SqlInstance sql1, sql2 -Category Category1, Category2 -NewName cat1, cat2\nRename multiple jobs in one go on multiple servers.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Category",
                           "The name of the category",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NewName",
                           "New name of the job category",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "The force parameter will ignore some errors in the parameters and assume defaults.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaAgentJobCategory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Category] \u003cString[]\u003e] [[-NewName] \u003cString[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaAgentJobOutputFile",
        "Description":  "Sets the Output File for a step of an agent job with the Job Names and steps provided dynamically if required",
        "Tags":  [
                     "Agent",
                     "Job",
                     "SqlAgent"
                 ],
        "Synopsis":  "Set the output file for a step within an Agent job.",
        "Alias":  "",
        "Author":  "Rob Sewell, https://sqldbawithabeard.com",
        "CommandName":  "Set-DbaAgentJobOutputFile",
        "Availability":  "Windows only",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaAgentJobOutputFile -SqlInstance SERVERNAME -Job \u0027The Agent Job\u0027 -OutPutFile E:\\Logs\\AgentJobStepOutput.txt\nSets the Job step for The Agent job on SERVERNAME to E:\\Logs\\AgentJobStepOutput.txt",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue, ByPropertyName)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Credential object used to connect to the SQL Server as a different user be it Windows or SQL Server. Windows users are determined by the existence of a backslash, so if you are intending to use an \r\nalternative Windows connection instead of a SQL login, ensure it contains a backslash.",
                           "",
                           false,
                           "true (ByValue, ByPropertyName)",
                           ""
                       ],
                       [
                           "Job",
                           "The job to process - this list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Step",
                           "The Agent Job Step to provide Output File Path for. Also available dynamically",
                           "",
                           false,
                           "true (ByValue, ByPropertyName)",
                           ""
                       ],
                       [
                           "OutputFile",
                           "The Full Path to the New Output file",
                           "",
                           true,
                           "true (ByValue, ByPropertyName)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaAgentJobOutputFile [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cObject[]\u003e] [-Step \u003cObject[]\u003e] -OutputFile \u003cString\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaAgentJobOwner",
        "Description":  "This function alters SQL Agent Job ownership to match a specified login if their current owner does not match the target login. By default, the target login will be \u0027sa\u0027,\nbut the the user may specify a different login for ownership. This be applied to all jobs or only to a select collection of jobs.\n\nBest practice reference: http://sqlmag.com/blog/sql-server-tip-assign-ownership-jobs-sysadmin-account\n\nIf the \u0027sa\u0027 account was renamed, the new name will be used.",
        "Tags":  [
                     "Agent",
                     "Job"
                 ],
        "Synopsis":  "Sets SQL Agent job owners with a desired login if jobs do not match that owner.",
        "Alias":  "Set-DbaJobOwner",
        "Author":  "Michael Fal (@Mike_Fal), http://mikefal.net",
        "CommandName":  "Set-DbaAgentJobOwner",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaAgentJobOwner",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaAgentJobOwner -SqlInstance localhost\nSets SQL Agent Job owner to sa on all jobs where the owner does not match sa.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaAgentJobOwner -SqlInstance localhost -Login DOMAIN\\account\nSets SQL Agent Job owner to \u0027DOMAIN\\account\u0027 on all jobs where the owner does not match \u0027DOMAIN\\account\u0027. Note\r\nthat Login must be a valid security principal that exists on the target server.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaAgentJobOwner -SqlInstance localhost -Job job1, job2\nSets SQL Agent Job owner to \u0027sa\u0027 on the job1 and job2 jobs if their current owner does not match \u0027sa\u0027.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027sqlserver\u0027,\u0027sql2016\u0027 | Set-DbaAgentJobOwner\nSets SQL Agent Job owner to sa on all jobs where the owner does not match sa on both sqlserver and sql2016.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance vmsql | Where-Object OwnerLoginName -eq login1 | Set-DbaAgentJobOwner -TargetLogin login2 | Out-Gridview\nSets SQL Agent Job owner to login2 where their current owner is login1 on instance vmsql. Send result to gridview.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Job",
                           "Specifies the job(s) to process. Options for this list are auto-populated from the server. If unspecified, all jobs will be processed.",
                           "Jobs",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeJob",
                           "Specifies the job(s) to exclude from processing. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piped input from Get-DbaAgentJob",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Login",
                           "Specifies the login that you wish check for ownership. This defaults to \u0027sa\u0027 or the sysadmin name if sa was renamed. This must be a valid security principal which exists on the target server.",
                           "TargetLogin",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaAgentJobOwner [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Job] \u003cObject[]\u003e] [[-ExcludeJob] \u003cObject[]\u003e] [[-InputObject] \u003cJob[]\u003e] [[-Login] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaAgentJobStep",
        "Description":  "Set-DbaAgentJobStep updates a job step in the SQL Server Agent with parameters supplied.",
        "Tags":  [
                     "Agent",
                     "Job",
                     "JobStep"
                 ],
        "Synopsis":  "Set-DbaAgentJobStep updates a job step.",
        "Alias":  "",
        "Author":  "Sander Stad (@sqlstad), sqlstad.nl",
        "CommandName":  "Set-DbaAgentJobStep",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaAgentJobStep",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaAgentJobStep -SqlInstance sql1 -Job Job1 -StepName Step1 -NewName Step2\nChanges the name of the step in \"Job1\" with the name Step1 to Step2\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaAgentJobStep -SqlInstance sql1 -Job Job1 -StepName Step1 -Database msdb\nChanges the database of the step in \"Job1\" with the name Step1 to msdb\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaAgentJobStep -SqlInstance sql1 -Job Job1, Job2 -StepName Step1 -Database msdb\nChanges job steps in multiple jobs with the name Step1 to msdb\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaAgentJobStep -SqlInstance sql1, sql2, sql3 -Job Job1, Job2 -StepName Step1 -Database msdb\nChanges job steps in multiple jobs on multiple servers with the name Step1 to msdb\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eSet-DbaAgentJobStep -SqlInstance sql1, sql2, sql3 -Job Job1 -StepName Step1 -Database msdb\nChanges the database of the step in \"Job1\" with the name Step1 to msdb for multiple servers\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003esql1, sql2, sql3 | Set-DbaAgentJobStep -Job Job1 -StepName Step1 -Database msdb\nChanges the database of the step in \"Job1\" with the name Step1 to msdb for multiple servers using pipeline",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Job",
                           "The name of the job. Can be null if the the job id is being used.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "StepName",
                           "The name of the step.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "NewName",
                           "The new name for the step in case it needs to be renamed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Subsystem",
                           "The subsystem used by the SQL Server Agent service to execute command.\r\nAllowed values \u0027ActiveScripting\u0027,\u0027AnalysisCommand\u0027,\u0027AnalysisQuery\u0027,\u0027CmdExec\u0027,\u0027Distribution\u0027,\u0027LogReader\u0027,\u0027Merge\u0027,\u0027PowerShell\u0027,\u0027QueueReader\u0027,\u0027Snapshot\u0027,\u0027Ssis\u0027,\u0027TransactSql\u0027",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Command",
                           "The commands to be executed by SQLServerAgent service through subsystem.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CmdExecSuccessCode",
                           "The value returned by a CmdExec subsystem command to indicate that command executed successfully.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "OnSuccessAction",
                           "The action to perform if the step succeeds.\r\nAllowed values  \"QuitWithSuccess\" (default), \"QuitWithFailure\", \"GoToNextStep\", \"GoToStep\".\r\nThe text value van either be lowercase, uppercase or something in between as long as the text is correct.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "OnSuccessStepId",
                           "The ID of the step in this job to execute if the step succeeds and OnSuccessAction is \"GoToNextStep\".",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "OnFailAction",
                           "The action to perform if the step fails.\r\nAllowed values  \"QuitWithSuccess\" (default), \"QuitWithFailure\", \"GoToNextStep\", \"GoToStep\".\r\nThe text value van either be lowercase, uppercase or something in between as long as the text is correct.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "OnFailStepId",
                           "The ID of the step in this job to execute if the step fails and OnFailAction is \"GoToNextStep\".",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "Database",
                           "The name of the database in which to execute a Transact-SQL step. The default is \u0027master\u0027.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DatabaseUser",
                           "The name of the user account to use when executing a Transact-SQL step. The default is \u0027sa\u0027.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RetryAttempts",
                           "The number of retry attempts to use if this step fails. The default is 0.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "RetryInterval",
                           "The amount of time in minutes between retry attempts. The default is 0.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "OutputFileName",
                           "The name of the file in which the output of this step is saved.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Flag",
                           "Sets the flag(s) for the job step.\nFlag                                    Description\r\n----------------------------------------------------------------------------\r\nAppendAllCmdExecOutputToJobHistory      Job history, including command output, is appended to the job history file.\r\nAppendToJobHistory                      Job history is appended to the job history file.\r\nAppendToLogFile                         Job history is appended to the SQL Server log file.\r\nAppendToTableLog                        Job history is appended to a log table.\r\nLogToTableWithOverwrite                 Job history is written to a log table, overwriting previous contents.\r\nNone                                    Job history is not appended to a file.\r\nProvideStopProcessEvent                 Job processing is stopped.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ProxyName",
                           "The name of the proxy that the job step runs as.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "The force parameter will ignore some errors in the parameters and assume defaults.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaAgentJobStep [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Job] \u003cObject[]\u003e [-StepName] \u003cString\u003e [[-NewName] \u003cString\u003e] [[-Subsystem] \u003cString\u003e] [[-Command] \u003cString\u003e] [[-CmdExecSuccessCode] \u003cInt32\u003e] [[-OnSuccessAction] \u003cString\u003e] [[-OnSuccessStepId] \u003cInt32\u003e] [[-OnFailAction] \u003cString\u003e] [[-OnFailStepId] \u003cInt32\u003e] [[-Database] \u003cString\u003e] [[-DatabaseUser] \u003cString\u003e] [[-RetryAttempts] \u003cInt32\u003e] [[-RetryInterval] \u003cInt32\u003e] [[-OutputFileName] \u003cString\u003e] [[-Flag] \u003cString[]\u003e] [[-ProxyName] \u003cString\u003e] [-EnableException] [-Force] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaAgentSchedule",
        "Description":  "Set-DbaAgentSchedule will help update a schedule for a job. It does not attach the schedule to a job.",
        "Tags":  [
                     "Agent",
                     "Job",
                     "JobStep"
                 ],
        "Synopsis":  "Set-DbaAgentSchedule updates a schedule in the msdb database.",
        "Alias":  "",
        "Author":  "Sander Stad (@sqlstad, sqlstad.nl)",
        "CommandName":  "Set-DbaAgentSchedule",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaAgentSchedule",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaAgentSchedule -SqlInstance sql1 -Job Job1 -ScheduleName daily -Enabled\nChanges the schedule for Job1 with the name \u0027daily\u0027 to enabled\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaAgentSchedule -SqlInstance sql1 -Job Job1 -ScheduleName daily -NewName weekly -FrequencyType Weekly -FrequencyInterval Monday, Wednesday, Friday\nChanges the schedule for Job1 with the name daily to have a new name weekly\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaAgentSchedule -SqlInstance sql1 -Job Job1, Job2, Job3 -ScheduleName daily -StartTime \u0027230000\u0027\nChanges the start time of the schedule for Job1 to 11 PM for multiple jobs\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaAgentSchedule -SqlInstance sql1, sql2, sql3 -Job Job1 -ScheduleName daily -Enabled\nChanges the schedule for Job1 with the name daily to enabled on multiple servers\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003esql1, sql2, sql3 | Set-DbaAgentSchedule -Job Job1 -ScheduleName \u0027daily\u0027 -Enabled\nChanges the schedule for Job1 with the name \u0027daily\u0027 to enabled on multiple servers using pipe line",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Job",
                           "The name of the job that has the schedule.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "ScheduleName",
                           "The name of the schedule.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "NewName",
                           "The new name for the schedule.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Enabled",
                           "Set the schedule to enabled.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Disabled",
                           "Set the schedule to disabled.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "FrequencyType",
                           "A value indicating when a job is to be executed.\r\nAllowed values are 1, \"Once\", 4, \"Daily\", 8, \"Weekly\", 16, \"Monthly\", 32, \"MonthlyRelative\", 64, \"AgentStart\", 128 or \"IdleComputer\"",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "FrequencyInterval",
                           "The days that a job is executed\r\nAllowed values are 1, \"Sunday\", 2, \"Monday\", 4, \"Tuesday\", 8, \"Wednesday\", 16, \"Thursday\", 32, \"Friday\", 64, \"Saturday\", 62, \"Weekdays\", 65, \"Weekend\", 127, \"EveryDay\".\r\nIf 62, \"Weekdays\", 65, \"Weekend\", 127, \"EveryDay\" is used it overwwrites any other value that has been passed before.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "FrequencySubdayType",
                           "Specifies the units for the subday FrequencyInterval.\r\nAllowed values are 1, \"Time\", 2, \"Seconds\", 4, \"Minutes\", 8 or \"Hours\"",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "FrequencySubdayInterval",
                           "The number of subday type periods to occur between each execution of a job.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "FrequencyRelativeInterval",
                           "A job\u0027s occurrence of FrequencyInterval in each month, if FrequencyInterval is 32 (monthlyrelative).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "FrequencyRecurrenceFactor",
                           "The number of weeks or months between the scheduled execution of a job. FrequencyRecurrenceFactor is used only if FrequencyType is 8, \"Weekly\", 16, \"Monthly\", 32 or \"MonthlyRelative\".",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "StartDate",
                           "The date on which execution of a job can begin.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EndDate",
                           "The date on which execution of a job can stop.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "StartTime",
                           "The time on any day to begin execution of a job. Format HHMMSS / 24 hour clock.\r\nExample: \u0027010000\u0027 for 01:00:00 AM.\r\nExample: \u0027140000\u0027 for 02:00:00 PM.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EndTime",
                           "The time on any day to end execution of a job. Format HHMMSS / 24 hour clock.\r\nExample: \u0027010000\u0027 for 01:00:00 AM.\r\nExample: \u0027140000\u0027 for 02:00:00 PM.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "The force parameter will ignore some errors in the parameters and assume defaults.\r\nIt will also remove the any present schedules with the same name for the specific job.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaAgentSchedule [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Job] \u003cObject[]\u003e [-ScheduleName] \u003cString\u003e [[-NewName] \u003cString\u003e] [-Enabled] [-Disabled] [[-FrequencyType] \u003cObject\u003e] [[-FrequencyInterval] \u003cObject[]\u003e] [[-FrequencySubdayType] \u003cObject\u003e] [[-FrequencySubdayInterval] \u003cInt32\u003e] [[-FrequencyRelativeInterval] \u003cObject\u003e] [[-FrequencyRecurrenceFactor] \u003cInt32\u003e] [[-StartDate] \u003cString\u003e] [[-EndDate] \u003cString\u003e] [[-StartTime] \u003cString\u003e] [[-EndTime] \u003cString\u003e] [-EnableException] [-Force] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaAgentServer",
        "Description":  "Set-DbaAgentServer updates properties in the SQL Server Server with parameters supplied.",
        "Tags":  [
                     "Agent",
                     "Server"
                 ],
        "Synopsis":  "Set-DbaAgentServer updates properties of a SQL Agent Server.",
        "Alias":  "",
        "Author":  "Cláudio Silva (@claudioessilva), https://claudioessilva.com",
        "CommandName":  "Set-DbaAgentServer",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaAgentServer",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaAgentServer -SqlInstance sql1 -MaximumHistoryRows 10000 -MaximumJobHistoryRows 100\nChanges the job history retention to 10000 rows with an maximum of 100 rows per job.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaAgentServer -SqlInstance sql1 -CpuPolling Enabled\nEnable the CPU Polling configurations.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaAgentServer -SqlInstance sql1, sql2, sql3 -AgentLogLevel \u0027Errors, Warnings\u0027\nSet the agent log level to Errors and Warnings on multiple servers.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaAgentServer -SqlInstance sql1 -CpuPolling Disabled\nDisable the CPU Polling configurations.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piping agent server objects",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "AgentLogLevel",
                           "Specifies the agent log level.\r\nAllowed values 1, \"Errors\", 2, \"Warnings\", 3, \"Errors, Warnings\", 4, \"Informational\", 5, \"Errors, Informational\", 6, \"Warnings, Informational\", 7, \"All\"\r\nThe text value can either be lowercase, uppercase or something in between as long as the text is correct.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AgentMailType",
                           "Specifies the agent mail type.\r\nAllowed values 0, \"SqlAgentMail\", 1, \"DatabaseMail\"\r\nThe text value can either be lowercase, uppercase or something in between as long as the text is correct.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AgentShutdownWaitTime",
                           "The Agent Shutdown Wait Time value of the server agent.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "DatabaseMailProfile",
                           "The Database Mail Profile to be used. Must exists on database mail profiles.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ErrorLogFile",
                           "Error log file location",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IdleCpuDuration",
                           "Idle CPU Duration value to be used",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "IdleCpuPercentage",
                           "Idle CPU Percentage value to be used",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "CpuPolling",
                           "Enable or Disable the Polling.\r\nAllowed values Enabled, Disabled",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "LocalHostAlias",
                           "The value for Local Host Alias configuration",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "LoginTimeout",
                           "The value for Login Timeout configuration",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "MaximumHistoryRows",
                           "Indicates the Maximum job history log size (in rows). If you want to turn it off use the value -1",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "MaximumJobHistoryRows",
                           "Indicates the Maximum job history rows per job. If you want to turn it off use the value 0",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "NetSendRecipient",
                           "The Net send recipient value",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ReplaceAlertTokens",
                           "Enable or Disable the Token replacement property.\r\nAllowed values Enabled, Disabled",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SaveInSentFolder",
                           "Enable or Disable the copy of the sent messages is save in the Sent Items folder.\r\nAllowed values Enabled, Disabled",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlAgentAutoStart",
                           "Enable or Disable the SQL Agent Auto Start.\r\nAllowed values Enabled, Disabled",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlAgentMailProfile",
                           "The SQL Server Agent Mail Profile to be used. Must exists on database mail profiles.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlAgentRestart",
                           "Enable or Disable the SQL Agent Restart.\r\nAllowed values Enabled, Disabled",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlServerRestart",
                           "Enable or Disable the SQL Server Restart.\r\nAllowed values Enabled, Disabled",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "WriteOemErrorLog",
                           "Enable or Disable the Write OEM Error Log.\r\nAllowed values Enabled, Disabled",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaAgentServer [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-InputObject] \u003cJobServer[]\u003e] [[-AgentLogLevel] \u003cObject\u003e] [[-AgentMailType] \u003cObject\u003e] [[-AgentShutdownWaitTime] \u003cInt32\u003e] [[-DatabaseMailProfile] \u003cString\u003e] [[-ErrorLogFile] \u003cString\u003e] [[-IdleCpuDuration] \u003cInt32\u003e] [[-IdleCpuPercentage] \u003cInt32\u003e] [[-CpuPolling] \u003cString\u003e] [[-LocalHostAlias] \u003cString\u003e] [[-LoginTimeout] \u003cInt32\u003e] [[-MaximumHistoryRows] \u003cInt32\u003e] [[-MaximumJobHistoryRows] \u003cInt32\u003e] [[-NetSendRecipient] \u003cString\u003e] [[-ReplaceAlertTokens] \u003cString\u003e] [[-SaveInSentFolder] \u003cString\u003e] \r\n[[-SqlAgentAutoStart] \u003cString\u003e] [[-SqlAgentMailProfile] \u003cString\u003e] [[-SqlAgentRestart] \u003cString\u003e] [[-SqlServerRestart] \u003cString\u003e] [[-WriteOemErrorLog] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaAgListener",
        "Description":  "Sets a listener property for an availability group on a SQL Server instance.\n\nBasically, only the port is settable at this time, so this command updates the listener port.",
        "Tags":  [
                     "AvailabilityGroup",
                     "HA",
                     "AG"
                 ],
        "Synopsis":  "Sets a listener property for an availability group on a SQL Server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Set-DbaAgListener",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaAgListener",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaAgListener -SqlInstance sql2017 -AvailabilityGroup SharePoint -Port 14333\nChanges the port for the SharePoint AG Listener on sql2017. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgListener -SqlInstance sql2017 | Out-GridView -Passthru | Set-DbaAgListener -Port 1433 -Confirm:$false\nChanges the port for selected AG listeners to 1433. Does not prompt for confirmation.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityGroup",
                           "The Availability Group to which a property will be changed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Listener",
                           "Modify only specific listeners.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Port",
                           "Sets the port number used to communicate with the availability group.",
                           "",
                           true,
                           "false",
                           "0"
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaAvailabilityGroup",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaAgListener [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-Listener] \u003cString[]\u003e] [-Port] \u003cInt32\u003e [[-InputObject] \u003cAvailabilityGroup[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaAgReplica",
        "Description":  "Sets the properties for a replica to an availability group on a SQL Server instance.\n\nAutomatically creates a database mirroring endpoint if required.",
        "Tags":  [
                     "AvailabilityGroup",
                     "HA",
                     "AG"
                 ],
        "Synopsis":  "Sets the properties for a replica to an availability group on a SQL Server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Set-DbaAgReplica",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaAgReplica",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaAgReplica -SqlInstance sql2016 -Replica sql2016 -AvailabilityGroup SharePoint -BackupPriority 5000\nSets the backup priority to 5000 for the sql2016 replica for the SharePoint availability group on sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgReplica -SqlInstance sql2016 | Out-GridView -Passthru | Set-DbaAgReplica -BackupPriority 5000\nSets the backup priority to 5000 for the selected availability groups.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityGroup",
                           "The availability group of the replica.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Replica",
                           "The replicas to modify.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityMode",
                           "Sets the availability mode of the availability group replica. Options are: AsynchronousCommit and SynchronousCommit. SynchronousCommit is default.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "FailoverMode",
                           "Sets the failover mode of the availability group replica. Options are Automatic and Manual.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "BackupPriority",
                           "Sets the backup priority availability group replica. Default is 50.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "ConnectionModeInPrimaryRole",
                           "Sets the connection intent modes of an Availability Replica in primary role.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ConnectionModeInSecondaryRole",
                           "Sets the connection modes of an Availability Replica in secondary role.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SeedingMode",
                           "Specifies how the secondary replica will be initially seeded.\nAutomatic enables direct seeding. This method will seed the secondary replica over the network. This method does not require you to backup and restore a copy of the primary database on the replica.\nManual requires you to create a backup of the database on the primary replica and manually restore that backup on the secondary replica.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EndpointUrl",
                           "The endpoint URL.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ReadonlyRoutingConnectionUrl",
                           "Sets the read only routing connection url for the availability replica.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaAgReplica.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaAgReplica [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString\u003e] [[-Replica] \u003cString\u003e] [[-AvailabilityMode] \u003cString\u003e] [[-FailoverMode] \u003cString\u003e] [[-BackupPriority] \u003cInt32\u003e] [[-ConnectionModeInPrimaryRole] \u003cString\u003e] [[-ConnectionModeInSecondaryRole] \u003cString\u003e] [[-SeedingMode] \u003cString\u003e] [[-EndpointUrl] \u003cString\u003e] [[-ReadonlyRoutingConnectionUrl] \u003cString\u003e] [[-InputObject] \u003cAvailabilityReplica\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaAvailabilityGroup",
        "Description":  "Sets availability group properties on a SQL Server instance.",
        "Tags":  [
                     "AvailabilityGroup",
                     "HA",
                     "AG"
                 ],
        "Synopsis":  "Sets availability group properties on a SQL Server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Set-DbaAvailabilityGroup",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaAvailabilityGroup",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2016 | Set-DbaAvailabilityGroup -DtcSupportEnabled\nEnables DTC for all availability groups on sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2016 -AvailabilityGroup AG1 | Set-DbaAvailabilityGroup -DtcSupportEnabled:$false\nDisables DTC support for the availability group AG1\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaAvailabilityGroup -SqlInstance sql2016 -AvailabilityGroup AG1 -DtcSupportEnabled:$false\nDisables DTC support for the availability group AG1",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityGroup",
                           "Only set specific availability group properties.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AllAvailabilityGroups",
                           "Set properties for all availability group on an instance.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DtcSupportEnabled",
                           "Enables DtcSupport.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ClusterType",
                           "Cluster type of the Availability Group. Only supported in SQL Server 2017 and above.\r\nOptions include: External, Wsfc or None.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AutomatedBackupPreference",
                           "Specifies how replicas in the primary role are treated in the evaluation to pick the desired replica to perform a backup.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "FailureConditionLevel",
                           "Specifies the different conditions that can trigger an automatic failover in Availability Group.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "HealthCheckTimeout",
                           "This setting used to specify the length of time, in milliseconds, that the SQL Server resource DLL should wait for information returned by the sp_server_diagnostics stored procedure before reporting \r\nthe Always On Failover Cluster Instance (FCI) as unresponsive.\nChanges that are made to the timeout settings are effective immediately and do not require a restart of the SQL Server resource.\nDefaults is 30000 (30 seconds).",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "BasicAvailabilityGroup",
                           "Indicates whether the availability group is basic. Basic availability groups like pumpkin spice and uggs.\nhttps://docs.microsoft.com/en-us/sql/database-engine/availability-groups/windows/basic-availability-groups-always-on-availability-groups",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DatabaseHealthTrigger",
                           "Indicates whether the availability group triggers the database health.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IsDistributedAvailabilityGroup",
                           "Indicates whether the availability group is distributed.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaAvailabilityGroup.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaAvailabilityGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [-AllAvailabilityGroups] [-DtcSupportEnabled] [[-ClusterType] \u003cString\u003e] [[-AutomatedBackupPreference] \u003cString\u003e] [[-FailureConditionLevel] \u003cString\u003e] [[-HealthCheckTimeout] \u003cInt32\u003e] [-BasicAvailabilityGroup] [-DatabaseHealthTrigger] [-IsDistributedAvailabilityGroup] [[-InputObject] \u003cAvailabilityGroup[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaCmConnection",
        "Description":  "Configures a connection object for use in remote computer management.\nThis function will either create new records for computers that have no connection registered so far, or it will configure existing connections if already present.\n\nAs such it can be handy in making bulk-edits on connections or manually adjusting some settings.",
        "Tags":  [
                     "ComputerManagement",
                     "CIM"
                 ],
        "Synopsis":  "Configures a connection object for use in remote computer management.",
        "Alias":  "",
        "Author":  "Friedrich Weinmann (@FredWeinmann)",
        "CommandName":  "Set-DbaCmConnection",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/set-DbaCmConnection",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaCmConnection sql2014 | Set-DbaCmConnection -ClearBadCredential -UseWindowsCredentials\nRetrieves the already existing connection to sql2014, removes the list of not working credentials and configures it to default to the credentials of the logged on user.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCmConnection | Set-DbaCmConnection -RemoveBadCredential $cred\nRemoves the credentials stored in $cred from all connections\u0027 list of \"known to not work\" credentials.\r\nHandy to update changes in privilege.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaCmConnection | Export-Clixml .\\connections.xml\nPS C:\\\u003e Import-Clixml .\\connections.xml | Set-DbaCmConnection -ResetConfiguration\nAt first, the current cached connections are stored in an xml file. At a later time - possibly in the profile when starting the console again - those connections are imported again and applied again \r\nto the connection cache.\nIn this example, the configuration settings will also be reset, since after re-import those will be set to explicit, rather than deriving them from the global settings.\r\nIn many cases, using the default settings is desirable. For specific settings, use New-DbaCmConnection as part of the profile in order to explicitly configure a connection.",
        "Params":  [
                       [
                           "ComputerName",
                           "The computer to build the connection object for.",
                           "",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "The credential to register.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "UseWindowsCredentials",
                           "Whether using the default windows credentials is legit.\r\nNot setting this will not exclude using windows credentials, but only not pre-confirm them as working.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "OverrideExplicitCredential",
                           "Setting this will enable the credential override.\r\nThe override will cause the system to ignore explicitly specified credentials, so long as known, good credentials are available.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "OverrideConnectionPolicy",
                           "Setting this will configure the connection policy override.\r\nBy default, global configurations enforce, which connection type is available at all and which is disabled.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DisabledConnectionTypes",
                           "Explicitly disable connection types.\r\nThese types will then not be used for connecting to the computer.",
                           "",
                           false,
                           "false",
                           "None"
                       ],
                       [
                           "DisableBadCredentialCache",
                           "Will prevent the caching of credentials if set to true.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DisableCimPersistence",
                           "Will prevent Cim-Sessions to be reused.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DisableCredentialAutoRegister",
                           "Will prevent working credentials from being automatically cached",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableCredentialFailover",
                           "Will enable automatic failing over to known to work credentials, when using bad credentials.\r\nBy default, passing bad credentials will cause the Computer Management functions to interrupt with a warning (Or exception if in silent mode).",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WindowsCredentialsAreBad",
                           "Will prevent the windows credentials of the currently logged on user from being used for the remote connection.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "CimWinRMOptions",
                           "Specify a set of options to use when connecting to the target computer using CIM over WinRM.\r\nUse \u0027New-CimSessionOption\u0027 to create such an object.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CimDCOMOptions",
                           "Specify a set of options to use when connecting to the target computer using CIM over DCOM.\r\nUse \u0027New-CimSessionOption\u0027 to create such an object.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AddBadCredential",
                           "Adds credentials to the bad credential cache.\r\nThese credentials will not be used when connecting to the target remote computer.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RemoveBadCredential",
                           "Removes credentials from the bad credential cache.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ClearBadCredential",
                           "Clears the cache of credentials that didn\u0027t worked.\r\nWill be applied before adding entries to the credential cache.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ClearCredential",
                           "Clears the cache of credentials that worked.\r\nWill be applied before adding entries to the credential cache.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ResetCredential",
                           "Resets all credential-related caches:\r\n- Clears bad credential cache\r\n- Removes last working credential\r\n- Un-Confirms the windows credentials as working\r\n- Un-Confirms the windows credentials as not working\nAutomatically implies the parameters -ClearCredential and -ClearBadCredential. Using them together is redundant.\r\nWill be applied before adding entries to the credential cache.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ResetConnectionStatus",
                           "Restores all connection status to default, as if no connection protocol had ever been tested.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ResetConfiguration",
                           "Restores the configuration back to system default.\r\nConfiguration elements are the basic behavior controlling settings, such as whether to cache bad credentials, etc.\r\nThese can be configured globally using the dbatools configuration system and overridden locally on a per-connection basis.\r\nFor a list of all available settings, use \"Get-DbatoolsConfig -Module ComputerManagement\".",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaCmConnection [-ComputerName \u003cDbaCmConnectionParameter[]\u003e] [-Credential \u003cPSCredential\u003e] [-OverrideExplicitCredential] [-OverrideConnectionPolicy] [-DisabledConnectionTypes {None | CimRM | CimDCOM | Wmi | PowerShellRemoting}] [-DisableBadCredentialCache] [-DisableCimPersistence] [-DisableCredentialAutoRegister] [-EnableCredentialFailover] [-WindowsCredentialsAreBad] [-CimWinRMOptions \u003cWSManSessionOptions\u003e] [-CimDCOMOptions \u003cDComSessionOptions\u003e] [-AddBadCredential \u003cPSCredential[]\u003e] [-RemoveBadCredential \u003cPSCredential[]\u003e] [-ClearBadCredential] [-ClearCredential] [-ResetCredential] \r\n[-ResetConnectionStatus] [-ResetConfiguration] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nSet-DbaCmConnection [-ComputerName \u003cDbaCmConnectionParameter[]\u003e] [-UseWindowsCredentials] [-OverrideExplicitCredential] [-OverrideConnectionPolicy] [-DisabledConnectionTypes {None | CimRM | CimDCOM | Wmi | PowerShellRemoting}] [-DisableBadCredentialCache] [-DisableCimPersistence] [-DisableCredentialAutoRegister] [-EnableCredentialFailover] [-CimWinRMOptions \u003cWSManSessionOptions\u003e] [-CimDCOMOptions \u003cDComSessionOptions\u003e] [-AddBadCredential \u003cPSCredential[]\u003e] [-RemoveBadCredential \u003cPSCredential[]\u003e] [-ClearBadCredential] [-ClearCredential] [-ResetCredential] [-ResetConnectionStatus] \r\n[-ResetConfiguration] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaDbCompatibility",
        "Description":  "Sets the current database compatibility level for all databases on a server or list of databases passed in to the function.",
        "Tags":  [
                     "Compatibility",
                     "Database"
                 ],
        "Synopsis":  "Sets the compatibility level for SQL Server databases.",
        "Alias":  "",
        "Author":  "Garry Bargsley, http://blog.garrybargsley.com/",
        "CommandName":  "Set-DbaDbCompatibility",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaDbCompatibility",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaDbCompatibility -SqlInstance localhost\\sql2017\nChanges database compatibility level for all user databases on server localhost\\sql2017 that have a Compatibility level that do not match\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaDbCompatibility -SqlInstance localhost\\sql2017 -TargetCompatibility 12\nChanges database compatibility level for all user databases on server localhost\\sql2017 to Version120\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaDbCompatibility -SqlInstance localhost\\sql2017 -Database Test -TargetCompatibility 12\nChanges database compatibility level for database Test on server localhost\\sql2017 to Version 120",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "SqlCredential object used to connect to the SQL Server as a different user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database or databases to process. If unspecified, all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "TargetCompatibility",
                           "The target compatibility level version. This is an int and follows Microsoft\u0027s versioning:\n9 = SQL Server 2005\r\n10 = SQL Server 2008\r\n11 = SQL Server 2012\r\n12 = SQL Server 2014\r\n13 = SQL Server 2016\r\n14 = SQL Server 2017\r\n15 = SQL Server 2019",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "InputObject",
                           "A collection of databases (such as returned by Get-DbaDatabase)",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts for confirmation of every step. For example:\nAre you sure you want to perform this action?\r\nPerforming the operation \"Update database\" on target \"pubs on SQL2016\\VNEXT\".\r\n[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is \"Y\"):",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaDbCompatibility [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-TargetCompatibility] \u003cInt32\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaDbCompression",
        "Description":  "This function sets the appropriate compression recommendation, determined either by using the Tiger Team\u0027s query or set to the CompressionType parameter.\n\nRemember Uptime is critical for the Tiger Team query, the longer uptime, the more accurate the analysis is.\nYou would probably be best if you utilized Get-DbaUptime first, before running this command.\n\nSet-DbaDbCompression script derived from GitHub and the tigertoolbox\n(https://github.com/Microsoft/tigertoolbox/tree/master/Evaluate-Compression-Gains)",
        "Tags":  [
                     "Compression",
                     "Table",
                     "Database"
                 ],
        "Synopsis":  "Sets tables and indexes with preferred compression setting.",
        "Alias":  "",
        "Author":  "Jason Squires (@js_0505), [email protected]",
        "CommandName":  "Set-DbaDbCompression",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaDbCompression",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaDbCompression -SqlInstance localhost -MaxRunTime 60 -PercentCompression 25\nSet the compression run time to 60 minutes and will start the compression of tables/indexes that have a difference of 25% or higher between current and recommended.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaDbCompression -SqlInstance ServerA -Database DBName -CompressionType Page\nUtilizes Page compression for all objects in DBName on ServerA with no time limit.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaDbCompression -SqlInstance ServerA -Database DBName -PercentCompression 25 | Out-GridView\nWill compress tables/indexes within the specified database that would show any % improvement with compression and with no time limit. The results will be piped into a nicely formatted GridView.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$testCompression = Test-DbaDbCompression -SqlInstance ServerA -Database DBName\nPS C:\\\u003e Set-DbaDbCompression -SqlInstance ServerA -Database DBName -InputObject $testCompression\nGets the compression suggestions from Test-DbaDbCompression into a variable, this can then be reviewed and passed into Set-DbaDbCompression.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Set-DbaDbCompression -SqlInstance ServerA -ExcludeDatabase Database -SqlCredential $cred -MaxRunTime 60 -PercentCompression 25\nSet the compression run time to 60 minutes and will start the compression of tables/indexes for all databases except the specified excluded database. Only objects that have a difference of 25% or \r\nhigher between current and recommended will be compressed.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$servers = \u0027Server1\u0027,\u0027Server2\u0027\nPS C:\\\u003e foreach ($svr in $servers) {\r\n\u003e\u003e Set-DbaDbCompression -SqlInstance $svr -MaxRunTime 60 -PercentCompression 25 | Export-Csv -Path C:\\temp\\CompressionAnalysisPAC.csv -Append\r\n\u003e\u003e }\nSet the compression run time to 60 minutes and will start the compression of tables/indexes across all listed servers that have a difference of 25% or higher between current and recommended. Output \r\nof command is exported to a csv.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto populated from the server. If unspecified, all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CompressionType",
                           "Control the compression type applied. Default is \u0027Recommended\u0027 which uses the Tiger Team query to use the most appropriate setting per object. Other option is to compress all objects to either Row or \r\nPage.",
                           "",
                           false,
                           "false",
                           "Recommended"
                       ],
                       [
                           "MaxRunTime",
                           "Will continue to alter tables and indexes for the given amount of minutes.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "PercentCompression",
                           "Will only work on the tables/indexes that have the calculated savings at and higher for the given number provided.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "InputObject",
                           "Takes the output of Test-DbaDbCompression as an object and applied compression based on those recommendations.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaDbCompression [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-CompressionType] \u003cObject\u003e] [[-MaxRunTime] \u003cInt32\u003e] [[-PercentCompression] \u003cInt32\u003e] [[-InputObject] \u003cObject\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaDbMirror",
        "Description":  "Sets properties of database mirrors.",
        "Tags":  [
                     "Mirror",
                     "HA"
                 ],
        "Synopsis":  "Sets properties of database mirrors.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Set-DbaDbMirror",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaDbMirror",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaDbMirror -SqlInstance sql2005 -Database dbatools -Partner TCP://SQL2008.ad.local:5374\nPrompts for confirmation then sets the partner to TCP://SQL2008.ad.local:5374 for the database \"dbtools\"\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaDbMirror -SqlInstance sql2005 -Database dbatools -Witness TCP://SQL2012.ad.local:5502 -Confirm:$false\nDoes not prompt for confirmation and sets the witness to TCP://SQL2012.ad.local:5502 for the database \"dbtools\"\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2005 | Out-GridView -PassThru | Set-DbaDbMirror -SafetyLevel Full -Confirm:$false\nSets the safety level to Full for databases selected from a grid view. Does not prompt for confirmation.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaDbMirror -SqlInstance sql2005 -Database dbatools -State Suspend -Confirm:$false\nDoes not prompt for confirmation and sets the state to suspend for the database \"dbtools\"",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The target database.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Partner",
                           "Sets the partner fqdn.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Witness",
                           "Sets the witness fqdn.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SafetyLevel",
                           "Sets the mirroring safety level.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "State",
                           "Sets the mirror state.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows piping from Get-DbaDatabase.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaDbMirror [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Partner] \u003cString\u003e] [[-Witness] \u003cString\u003e] [[-SafetyLevel] \u003cString\u003e] [[-State] \u003cString\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaDbOwner",
        "Description":  "This function will alter database ownership to match a specified login if their current owner does not match the target login. By default, the target login will be \u0027sa\u0027, but the function will allow the user to specify a different login for  ownership. The user can also apply this to all databases or only to a select list of databases (passed as either a comma separated list or a string array).\n\nBest Practice reference: http://weblogs.sqlteam.com/dang/archive/2008/01/13/Database-Owner-Troubles.aspx",
        "Tags":  [
                     "Database",
                     "Owner",
                     "DbOwner"
                 ],
        "Synopsis":  "Sets database owners with a desired login if databases do not match that owner.",
        "Alias":  "Set-DbaDatabaseOwner",
        "Author":  "Michael Fal (@Mike_Fal), http://mikefal.net",
        "CommandName":  "Set-DbaDbOwner",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaDbOwner",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaDbOwner -SqlInstance localhost\nSets database owner to \u0027sa\u0027 on all databases where the owner does not match \u0027sa\u0027.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaDbOwner -SqlInstance localhost -TargetLogin DOMAIN\\account\nSets the database owner to DOMAIN\\account on all databases where the owner does not match DOMAIN\\account.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaDbOwner -SqlInstance sqlserver -Database db1, db2\nSets database owner to \u0027sa\u0027 on the db1 and db2 databases if their current owner does not match \u0027sa\u0027.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "TargetLogin",
                           "Specifies the login that you wish check for ownership. This defaults to \u0027sa\u0027 or the sysadmin name if sa was renamed. This must be a valid security principal which exists on the target server.",
                           "Login",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaDbOwner [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-TargetLogin] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaDbQueryStoreOption",
        "Description":  "Configure Query Store settings for a specific or multiple databases.",
        "Tags":  "QueryStore",
        "Synopsis":  "Configure Query Store settings for a specific or multiple databases.",
        "Alias":  "Set-DbaDbQueryStoreOptions,Set-DbaQueryStoreConfig",
        "Author":  "Enrico van de Laar (@evdlaar)",
        "CommandName":  "Set-DbaDbQueryStoreOption",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaQueryStoreOptions",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaDbQueryStoreOption -SqlInstance ServerA\\SQL -State ReadWrite -FlushInterval 600 -CollectionInterval 10 -MaxSize 100 -CaptureMode All -CleanupMode Auto -StaleQueryThreshold 100 \r\n-AllDatabases\nConfigure the Query Store settings for all user databases in the ServerA\\SQL Instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaDbQueryStoreOption -SqlInstance ServerA\\SQL -FlushInterval 600\nOnly configure the FlushInterval setting for all Query Store databases in the ServerA\\SQL Instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaDbQueryStoreOption -SqlInstance ServerA\\SQL -Database AdventureWorks -State ReadWrite -FlushInterval 600 -CollectionInterval 10 -MaxSize 100 -CaptureMode all -CleanupMode Auto \r\n-StaleQueryThreshold 100\nConfigure the Query Store settings for the AdventureWorks database in the ServerA\\SQL Instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaDbQueryStoreOption -SqlInstance ServerA\\SQL -Exclude AdventureWorks -State ReadWrite -FlushInterval 600 -CollectionInterval 10 -MaxSize 100 -CaptureMode all -CleanupMode Auto \r\n-StaleQueryThreshold 100\nConfigure the Query Store settings for all user databases except the AdventureWorks database in the ServerA\\SQL Instance.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "SqlCredential object used to connect to the SQL Server as a different user.",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AllDatabases",
                           "Run command against all user databases",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "State",
                           "Set the state of the Query Store. Valid options are \"ReadWrite\", \"ReadOnly\" and \"Off\".",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "FlushInterval",
                           "Set the flush to disk interval of the Query Store in seconds.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "CollectionInterval",
                           "Set the runtime statistics collection interval of the Query Store in minutes.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "MaxSize",
                           "Set the maximum size of the Query Store in MB.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "CaptureMode",
                           "Set the query capture mode of the Query Store. Valid options are \"Auto\" and \"All\".",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CleanupMode",
                           "Set the query cleanup mode policy. Valid options are \"Auto\" and \"Off\".",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "StaleQueryThreshold",
                           "Set the stale query threshold in days.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts for confirmation of every step. For example:\nAre you sure you want to perform this action?\r\nPerforming the operation \"Changing Desired State\" on target \"pubs on SQL2016\\VNEXT\".\r\n[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is \"Y\"):",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaDbQueryStoreOption [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-AllDatabases] [[-State] \u003cString[]\u003e] [[-FlushInterval] \u003cInt64\u003e] [[-CollectionInterval] \u003cInt64\u003e] [[-MaxSize] \u003cInt64\u003e] [[-CaptureMode] \u003cString[]\u003e] [[-CleanupMode] \u003cString[]\u003e] [[-StaleQueryThreshold] \u003cInt64\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaDbRecoveryModel",
        "Description":  "Set-DbaDbRecoveryModel sets the Recovery Model for user databases.",
        "Tags":  [
                     "RecoveryModel",
                     "Database"
                 ],
        "Synopsis":  "Set-DbaDbRecoveryModel sets the Recovery Model.",
        "Alias":  "",
        "Author":  "Viorel Ciucu (@viorelciucu), https://www.cviorel.com",
        "CommandName":  "Set-DbaDbRecoveryModel",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaDbRecoveryModel",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaDbRecoveryModel -SqlInstance sql2014 -RecoveryModel BulkLogged -Database model -Confirm:$true -Verbose\nSets the Recovery Model to BulkLogged for database [model] on SQL Server instance sql2014. User is requested to confirm the action.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2014 -Database TestDB | Set-DbaDbRecoveryModel -RecoveryModel Simple  -Confirm:$false\nSets the Recovery Model to Simple for database [TestDB] on SQL Server instance sql2014. Confirmation is not required.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaDbRecoveryModel -SqlInstance sql2014 -RecoveryModel Simple -Database TestDB -Confirm:$false\nSets the Recovery Model to Simple for database [TestDB] on SQL Server instance sql2014. Confirmation is not required.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaDbRecoveryModel -SqlInstance sql2014 -RecoveryModel Simple -AllDatabases -Confirm:$false\nSets the Recovery Model to Simple for ALL uses databases MODEL database on SQL Server instance sql2014. Runs without asking for confirmation.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eSet-DbaDbRecoveryModel -SqlInstance sql2014 -RecoveryModel BulkLogged -Database TestDB1, TestDB2 -Confirm:$false -Verbose\nSets the Recovery Model to BulkLogged for [TestDB1] and [TestDB2] databases on SQL Server instance sql2014. Runs without asking for confirmation.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RecoveryModel",
                           "Recovery Model to be set. Valid options are \u0027Simple\u0027, \u0027Full\u0027, \u0027BulkLogged\u0027\nDetails about the recovery models can be found here:\r\nhttps://docs.microsoft.com/en-us/sql/relational-databases/backup-restore/recovery-models-sql-server",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. if unspecified, all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AllDatabases",
                           "This is a parameter that was included for safety, so you don\u0027t accidentally set options on all databases without specifying",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "A collection of databases (such as returned by Get-DbaDatabase)",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts for confirmation. For example:\nAre you sure you want to perform this action?\r\nPerforming the operation \"ALTER DATABASE [model] SET RECOVERY Full\" on target \"[model] on WERES14224\".\r\n[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is \"Y\"):",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaDbRecoveryModel [-SqlCredential \u003cPSCredential\u003e] -RecoveryModel \u003cString\u003e [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllDatabases] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nSet-DbaDbRecoveryModel -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -RecoveryModel \u003cString\u003e [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllDatabases] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nSet-DbaDbRecoveryModel [-SqlCredential \u003cPSCredential\u003e] -RecoveryModel \u003cString\u003e [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllDatabases] [-EnableException] -InputObject \u003cDatabase[]\u003e [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaDbState",
        "Description":  "Sets some common \"states\" on databases:\n- \"RW\" options (ReadOnly, ReadWrite)\n- \"Status\" options (Online, Offline, Emergency, plus a special \"Detached\")\n- \"Access\" options (SingleUser, RestrictedUser, MultiUser)\n\nReturns an object with SqlInstance, Database, RW, Status, Access, Notes\n\nNotes gets filled when something went wrong setting the state",
        "Tags":  [
                     "Database",
                     "State"
                 ],
        "Synopsis":  "Sets various options for databases, hereby called \"states\"",
        "Alias":  "Set-DbaDatabaseState",
        "Author":  "Simone Bizzotto (@niphold)",
        "CommandName":  "Set-DbaDbState",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaDbState",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaDbState -SqlInstance sqlserver2014a -Database HR -Offline\nSets the HR database as OFFLINE\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaDbState -SqlInstance sqlserver2014a -AllDatabases -Exclude HR -ReadOnly -Force\nSets all databases of the sqlserver2014a instance, except for HR, as READ_ONLY\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbState -SqlInstance sql2016 | Where-Object Status -eq \u0027Offline\u0027 | Set-DbaDbState -Online\nFinds all offline databases and sets them to online\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaDbState -SqlInstance sqlserver2014a -Database HR -SingleUser\nSets the HR database as SINGLE_USER\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eSet-DbaDbState -SqlInstance sqlserver2014a -Database HR -SingleUser -Force\nSets the HR database as SINGLE_USER, dropping all other connections (and rolling back open transactions)\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sqlserver2014a -Database HR | Set-DbaDbState -SingleUser -Force\nGets the databases from Get-DbaDatabase, and sets them as SINGLE_USER, dropping all other connections (and rolling back open transactions)",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Credential object used to connect to the SQL Server as a different user",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. if unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AllDatabases",
                           "This is a parameter that was included for safety, so you don\u0027t accidentally set options on all databases without specifying",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ReadOnly",
                           "RW Option : Sets the database as READ_ONLY",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ReadWrite",
                           "RW Option : Sets the database as READ_WRITE",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Online",
                           "Status Option : Sets the database as ONLINE",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Offline",
                           "Status Option : Sets the database as OFFLINE",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Emergency",
                           "Status Option : Sets the database as EMERGENCY",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Detached",
                           "Status Option : Detaches the database",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "SingleUser",
                           "Access Option : Sets the database as SINGLE_USER",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "RestrictedUser",
                           "Access Option : Sets the database as RESTRICTED_USER",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "MultiUser",
                           "Access Option : Sets the database as MULTI_USER",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "For most options, this translates to instantly rolling back any open transactions\r\nthat may be stopping the process.\r\nFor -Detached it is required to break mirroring and Availability Groups",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Accepts piped database objects",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaDbState [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllDatabases] [-ReadOnly] [-ReadWrite] [-Online] [-Offline] [-Emergency] [-Detached] [-SingleUser] [-RestrictedUser] [-MultiUser] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nSet-DbaDbState -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllDatabases] [-ReadOnly] [-ReadWrite] [-Online] [-Offline] [-Emergency] [-Detached] [-SingleUser] [-RestrictedUser] [-MultiUser] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nSet-DbaDbState [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllDatabases] [-ReadOnly] [-ReadWrite] [-Online] [-Offline] [-Emergency] [-Detached] [-SingleUser] [-RestrictedUser] [-MultiUser] [-Force] [-EnableException] -InputObject \u003cPSObject[]\u003e [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaEndpoint",
        "Description":  "Sets endpoint properties on a SQL Server instance.",
        "Tags":  "Endpoint",
        "Synopsis":  "Sets endpoint properties on a SQL Server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Set-DbaEndpoint",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaEndpoint",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaEndpoint -SqlInstance sql2016 -AllEndpoints -Owner sa\nSets all endpoint owners to sa on sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaEndpoint -SqlInstance sql2016 -Endpoint ep1 | Set-DbaEndpoint -Type TSql\nChanges the endpoint type to tsql on endpoint ep1",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EndPoint",
                           "Only set specific endpoint properties.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Owner",
                           "Change the endpoint owner.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Type",
                           "Change the endpoint type. Options: DatabaseMirroring, ServiceBroker, Soap, TSql",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AllEndpoints",
                           "Set all endpoint properties on an instance.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-Endpoint.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaEndpoint [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-EndPoint] \u003cString[]\u003e] [[-Owner] \u003cString\u003e] [[-Type] \u003cString\u003e] [-AllEndpoints] [[-InputObject] \u003cEndpoint[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaErrorLogConfig",
        "Description":  "Sets the number of log files configured on all versions, and size in KB in SQL Server 2012+ and above.\n\nTo set the Path to the ErrorLog, use Set-DbaStartupParameter -ErrorLog. Note that this command requires\nremote, administrative access to the Windows/WMI server, similar to SQL Configuration Manager.",
        "Tags":  [
                     "Instance",
                     "ErrorLog"
                 ],
        "Synopsis":  "Set the configuration for the ErrorLog on a given SQL Server instance",
        "Alias":  "",
        "Author":  "Shawn Melton (@wsmelton), https://wsmelton.github.com",
        "CommandName":  "Set-DbaErrorLogConfig",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaErrorLogConfig",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaErrorLogConfig -SqlInstance sql2017,sql2014 -LogCount 25\nSets the number of error log files to 25 on sql2017 and sql2014\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaErrorLogConfig -SqlInstance sql2014 -LogSize 102400\nSets the size of the error log file, before it rolls over, to 102400 KB (100 MB) on sql2014\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaErrorLogConfig -SqlInstance sql2012 -LogCount 25 -LogSize 500\nSets the number of error log files to 25 and size before it will roll over to 500 KB on sql2012",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances",
                           "",
                           true,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "LogCount",
                           "Integer value between 6 and 99 for setting the number of error log files to keep for SQL Server instance.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "LogSize",
                           "Integer value for the size in KB that you want the error log file to grow. This is feature only in SQL Server 2012 and higher. When the file reaches that limit SQL Server will roll the error log over.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaErrorLogConfig [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-LogCount] \u003cInt32\u003e] [[-LogSize] \u003cInt32\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaLogin",
        "Description":  "Set-DbaLogin will enable you to change the password, unlock, rename, disable or enable, deny or grant login privileges to the login. It\u0027s also possible to add or remove server roles from the login.",
        "Tags":  "Login",
        "Synopsis":  "Set-DbaLogin makes it possible to make changes to one or more logins.",
        "Alias":  "",
        "Author":  "Sander Stad (@sqlstad), sqlstad.nl",
        "CommandName":  "Set-DbaLogin",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaLogin",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$SecurePassword = ConvertTo-SecureString \"PlainTextPassword\" -AsPlainText -Force\nPS C:\\\u003e $cred = New-Object System.Management.Automation.PSCredential (\"username\", $SecurePassword)\r\nPS C:\\\u003e Set-DbaLogin -SqlInstance sql1 -Login login1 -SecurePassword $cred -Unlock -MustChange\nSet the new password for login1 using a credential, unlock the account and set the option\r\nthat the user must change password at next logon.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1 -Login login1 -Enable\nEnable the login\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1 -Login login1, login2, login3, login4 -Enable\nEnable multiple logins\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1, sql2, sql3 -Login login1, login2, login3, login4 -Enable\nEnable multiple logins on multiple instances\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1 -Login login1 -Disable\nDisable the login\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1 -Login login1 -DenyLogin\nDeny the login to connect to the instance\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1 -Login login1 -GrantLogin\nGrant the login to connect to the instance\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1 -Login login1 -PasswordPolicyEnforced\nEnforces the password policy on a login\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1 -Login login1 -PasswordPolicyEnforced:$false\nDisables enforcement of the password policy on a login\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1 -Login test -AddRole serveradmin\nAdd the server role \"serveradmin\" to the login\n-------------------------- EXAMPLE 11 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1 -Login test -RemoveRole bulkadmin\nRemove the server role \"bulkadmin\" to the login\n-------------------------- EXAMPLE 12 --------------------------\nPS C:\\\u003e$login = Get-DbaLogin -SqlInstance sql1 -Login test\nPS C:\\\u003e $login | Set-DbaLogin -Disable\nDisable the login from the pipeline",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Login",
                           "The login that needs to be changed",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SecurePassword",
                           "The new password for the login This can be either a credential or a secure string.",
                           "Password",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Unlock",
                           "Switch to unlock an account. This will only be used in conjunction with the -SecurePassword parameter.\r\nThe default is false.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "MustChange",
                           "Does the user need to change his/her password. This will only be used in conjunction with the -SecurePassword parameter.\r\nThe default is false.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NewName",
                           "The new name for the login.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Disable",
                           "Disable the login",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Enable",
                           "Enable the login",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DenyLogin",
                           "Deny access to SQL Server",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "GrantLogin",
                           "Grant access to SQL Server",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "PasswordPolicyEnforced",
                           "Should the password policy be enforced.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "AddRole",
                           "Add one or more server roles to the login\r\nThe following roles can be used \"bulkadmin\", \"dbcreator\", \"diskadmin\", \"processadmin\", \"public\", \"securityadmin\", \"serveradmin\", \"setupadmin\", \"sysadmin\".",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RemoveRole",
                           "Remove one or more server roles to the login\r\nThe following roles can be used \"bulkadmin\", \"dbcreator\", \"diskadmin\", \"processadmin\", \"public\", \"securityadmin\", \"serveradmin\", \"setupadmin\", \"sysadmin\".",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows logins to be piped in from Get-DbaLogin",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaLogin [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Login] \u003cString[]\u003e] [[-SecurePassword] \u003cObject\u003e] [-Unlock] [-MustChange] [[-NewName] \u003cString\u003e] [-Disable] [-Enable] [-DenyLogin] [-GrantLogin] [-PasswordPolicyEnforced] [[-AddRole] \u003cString[]\u003e] [[-RemoveRole] \u003cString[]\u003e] [[-InputObject] \u003cLogin[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaMaxDop",
        "Description":  "Uses the Test-DbaMaxDop command to get the recommended value if -MaxDop parameter is not specified.\n\nThese are just general recommendations for SQL Server and are a good starting point for setting the \"max degree of parallelism\" option.\n\nYou can set MaxDop database scoped configurations if the server is version 2016 or higher",
        "Tags":  [
                     "MaxDop",
                     "SpConfigure"
                 ],
        "Synopsis":  "Sets SQL Server maximum degree of parallelism (Max DOP), then displays information relating to SQL Server Max DOP configuration settings. Works on SQL Server 2005 and higher.",
        "Alias":  "",
        "Author":  "Claudio Silva (@claudioessilva)",
        "CommandName":  "Set-DbaMaxDop",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaMaxDop",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaMaxDop -SqlInstance sql2008, sql2012\nSets Max DOP to the recommended value for servers sql2008 and sql2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaMaxDop -SqlInstance sql2014 -MaxDop 4\nSets Max DOP to 4 for server sql2014.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaMaxDop -SqlInstance sql2008 | Set-DbaMaxDop\nGets the recommended Max DOP from Test-DbaMaxDop and applies it to to sql2008.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaMaxDop -SqlInstance sql2016 -Database db1\nSet recommended Max DOP for database db1 on server sql2016.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eSet-DbaMaxDop -SqlInstance sql2016 -AllDatabases\nSet recommended Max DOP for all databases on server sql2016.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Defaults to localhost.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies one or more databases to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies one or more databases to exclude from processing. Options for this list are auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "MaxDop",
                           "Specifies the Max DOP value to set.",
                           "",
                           false,
                           "false",
                           "-1"
                       ],
                       [
                           "InputObject",
                           "If Test-SqlMaxDop has been executed prior to this function, the results may be passed in via this parameter.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "AllDatabases",
                           "If this switch is enabled, Max DOP will be set on all databases. This switch is only useful on SQL Server 2016 and higher.",
                           "All",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the cmdlet runs. The cmdlet is not run.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before running the cmdlet.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaMaxDop [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-MaxDop \u003cInt32\u003e] [-InputObject \u003cPSObject\u003e] [-AllDatabases] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaMaxMemory",
        "Description":  "Sets SQL Server max memory then displays information relating to SQL Server Max Memory configuration settings.\n\nInspired by Jonathan Kehayias\u0027s post about SQL Server Max memory (http://bit.ly/sqlmemcalc), this uses a formula to\ndetermine the default optimum RAM to use, then sets the SQL max value to that number.\n\nJonathan notes that the formula used provides a *general recommendation* that doesn\u0027t account for everything that may\nbe going on in your specific environment.",
        "Tags":  [
                     "MaxMemory",
                     "Memory"
                 ],
        "Synopsis":  "Sets SQL Server \u0027Max Server Memory\u0027 configuration setting to a new value then displays information this setting.",
        "Alias":  "Set-SqlMaxMemory",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Set-DbaMaxMemory",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaMaxMemory",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaMaxMemory sqlserver1\nSet max memory to the recommended on just one server named \"sqlserver1\"\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaMaxMemory -SqlInstance sqlserver1 -Max 2048\nExplicitly set max memory to 2048 on just one server, \"sqlserver1\"\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sqlserver | Test-DbaMaxMemory | Where-Object { $_.MaxValue -gt $_.Total } | Set-DbaMaxMemory\nFind all servers in SQL Server Central Management Server that have Max SQL memory set to higher than the total memory\r\nof the server (think 2147483647), then pipe those to Set-DbaMaxMemory and use the default recommendation.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Max",
                           "Specifies the max megabytes (MB)",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "InputObject",
                           "A InputObject returned by Test-DbaMaxMemory",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the cmdlet runs. The cmdlet is not run.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before running the cmdlet.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaMaxMemory [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Max] \u003cInt32\u003e] [[-InputObject] \u003cPSObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaNetworkCertificate",
        "Description":  "Sets the network certificate for SQL Server instance. This setting is found in Configuration Manager.\n\nThis command also grants read permissions for the service account on the certificate\u0027s private key.\n\nReferences:\nhttp://sqlmag.com/sql-server/7-steps-ssl-encryption\nhttps://azurebi.jppp.org/2016/01/23/using-lets-encrypt-certificates-for-secure-sql-server-connections/\nhttps://blogs.msdn.microsoft.com/sqlserverfaq/2016/09/26/creating-and-registering-ssl-certificates/",
        "Tags":  "Certificate",
        "Synopsis":  "Sets the network certificate for SQL Server instance",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Set-DbaNetworkCertificate",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Set-DbaNetworkCertificate",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaComputerCertificate | Set-DbaNetworkCertificate -SqlInstance localhost\\SQL2008R2SP2\nCreates and imports a new certificate signed by an Active Directory CA on localhost then sets the network certificate for the SQL2008R2SP2 to that newly created certificate.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaNetworkCertificate -SqlInstance sql1\\SQL2008R2SP2 -Thumbprint 1223FB1ACBCA44D3EE9640F81B6BA14A92F3D6E2\nSets the network certificate for the SQL2008R2SP2 instance to the certificate with the thumbprint of 1223FB1ACBCA44D3EE9640F81B6BA14A92F3D6E2 in LocalMachine\\My on sql1",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Defaults to localhost.",
                           "ServerInstance,SqlServer,ComputerName",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to the computer (not sql instance) using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Certificate",
                           "The target certificate object",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Thumbprint",
                           "The thumbprint of the target certificate",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaNetworkCertificate [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-Credential \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nSet-DbaNetworkCertificate [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-Credential \u003cPSCredential\u003e] -Certificate \u003cX509Certificate2\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nSet-DbaNetworkCertificate [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-Credential \u003cPSCredential\u003e] -Thumbprint \u003cString\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaPowerPlan",
        "Description":  "Sets the SQL Server OS\u0027s Power Plan. Defaults to High Performance which is best practice.\n\nIf your organization uses a custom power plan that is considered best practice, specify -CustomPowerPlan.\n\nReferences:\nhttps://support.microsoft.com/en-us/kb/2207548\nhttp://www.sqlskills.com/blogs/glenn/windows-power-plan-effects-on-newer-intel-processors/",
        "Tags":  [
                     "PowerPlan",
                     "OS",
                     "Configure"
                 ],
        "Synopsis":  "Sets the SQL Server OS\u0027s Power Plan.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Set-DbaPowerPlan",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Set-DbaPowerPlan",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaPowerPlan -ComputerName sql2017\nSets the Power Plan to High Performance. Skips it if its already set.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027Server1\u0027, \u0027Server2\u0027 | Set-DbaPowerPlan -PowerPlan Balanced\nSets the Power Plan to Balanced for Server1 and Server2. Skips it if its already set.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$cred = Get-Credential \u0027Domain\\User\u0027\nPS C:\\\u003e Set-DbaPowerPlan -ComputerName sql2017 -Credential $cred\nConnects using alternative Windows credential and sets the Power Plan to High Performance. Skips it if its already set.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaPowerPlan -ComputerName sqlcluster -CustomPowerPlan \u0027Maximum Performance\u0027\nSets the Power Plan to the custom power plan called \"Maximum Performance\". Skips it if its already set.",
        "Params":  [
                       [
                           "ComputerName",
                           "The server(s) to set the Power Plan on.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Credential",
                           "Specifies a PSCredential object to use in authenticating to the server(s), instead of the current user account.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "PowerPlan",
                           "Specifies the Power Plan that you wish to use. Valid options for this match the Windows default Power Plans of \"Power Saver\", \"Balanced\", and \"High Performance\".",
                           "",
                           false,
                           "false",
                           "High Performance"
                       ],
                       [
                           "CustomPowerPlan",
                           "Specifies the name of a custom Power Plan to use.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaPowerPlan",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaPowerPlan [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-PowerPlan] \u003cString\u003e] [[-CustomPowerPlan] \u003cString\u003e] [[-InputObject] \u003cPSObject\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaPrivilege",
        "Description":  "Adds the SQL Service account to local privileges \u0027Lock Pages in Memory\u0027, \u0027Instant File Initialization\u0027, \u0027Logon as Batch\u0027 on one or more computers.\n\nRequires Local Admin rights on destination computer(s).",
        "Tags":  "Privilege",
        "Synopsis":  "Adds the SQL Service account to local privileges on one or more computers.",
        "Alias":  "",
        "Author":  "Klaas Vandenberghe ( @PowerDBAKlaas )",
        "CommandName":  "Set-DbaPrivilege",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Set-DbaPrivilege",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaPrivilege -ComputerName sqlserver2014a -Type LPIM,IFI\nAdds the SQL Service account(s) on computer sqlserver2014a to the local privileges \u0027SeManageVolumePrivilege\u0027 and \u0027SeLockMemoryPrivilege\u0027.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\u0027,\u0027sql3\u0027 | Set-DbaPrivilege -Type IFI\nAdds the SQL Service account(s) on computers sql1, sql2 and sql3 to the local privilege \u0027SeManageVolumePrivilege\u0027.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target SQL Server instance or instances.",
                           "cn,host,Server",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Credential object used to connect to the computer as a different user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Type",
                           "Use this to choose the privilege(s) to which you want to add the SQL Service account.\r\nAccepts \u0027IFI\u0027, \u0027LPIM\u0027 and/or \u0027BatchLogon\u0027 for local privileges \u0027Instant File Initialization\u0027, \u0027Lock Pages in Memory\u0027 and \u0027Logon as Batch\u0027.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaPrivilege [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-Type] \u003cString[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaSpConfigure",
        "Description":  "This function changes the configured value for sp_configure settings. If the setting is dynamic this setting will be used, otherwise the user will be warned that a restart of SQL is required.\nThis is designed to be safe and will not allow for configurations to be set outside of the defined configuration min and max values.\nWhile it is possible to set below the min, or above the max this can cause serious problems with SQL Server (including startup failures), and so is not permitted.",
        "Tags":  "SpConfigure",
        "Synopsis":  "Changes the server level system configuration (sys.configuration/sp_configure) value for a given configuration",
        "Alias":  "",
        "Author":  "Nic Cain, https://sirsql.net/",
        "CommandName":  "Set-DbaSpConfigure",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaSpConfigure",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaSpConfigure -SqlInstance localhost -Name ScanForStartupProcedures -Value 1\nAdjusts the Scan for startup stored procedures configuration value to 1 and notifies the user that this requires a SQL restart to take effect\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaSpConfigure -SqlInstance sql2017, sql2014 -Name XPCmdShellEnabled, IsSqlClrEnabled | Set-DbaSpConfigure -Value $false\nSets the values for XPCmdShellEnabled and IsSqlClrEnabled on sql2017 and sql2014 to False\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaSpConfigure -SqlInstance localhost -Name XPCmdShellEnabled -Value 1\nAdjusts the xp_cmdshell configuration value to 1.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaSpConfigure -SqlInstance localhost -Name XPCmdShellEnabled -Value 1 -WhatIf\nReturns information on the action that would be performed. No actual change will be made.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a\r\ncollection and receive pipeline input",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Value",
                           "The new value for the configuration",
                           "NewValue,NewConfig",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "Name",
                           "The name of the configuration to be set -- Configs is auto-populated for tabbing convenience.",
                           "Config,ConfigName",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Piped objects from Get-DbaSpConfigure",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaSpConfigure [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Value] \u003cInt32\u003e] [[-Name] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaSpn",
        "Description":  "This function will connect to Active Directory and search for an account. If the account is found, it will attempt to add an SPN. Once the SPN is added, the function will also set delegation to that service, unless -NoDelegation is specified. In order to run this function, the credential you provide must have write access to Active Directory.\n\nNote: This function supports -WhatIf",
        "Tags":  "SPN",
        "Synopsis":  "Sets an SPN for a given service account in active directory (and also enables delegation to the same SPN by default)",
        "Alias":  "",
        "Author":  "Drew Furgiuele (@pittfurg), http://www.port1433.com",
        "CommandName":  "Set-DbaSpn",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Set-DbaSpn",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaSpn -SPN MSSQLSvc/SQLSERVERA.domain.something -ServiceAccount domain\\account\nPS C:\\\u003e Set-DbaSpn -SPN MSSQLSvc/SQLSERVERA.domain.something -ServiceAccount domain\\account -EnableException\nConnects to Active Directory and adds a provided SPN to the given account.\r\nConnects to Active Directory and adds a provided SPN to the given account, suppressing all error messages and throw exceptions that can be caught instead\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaSpn -SPN MSSQLSvc/SQLSERVERA.domain.something -ServiceAccount domain\\account -Credential ad\\sqldba\nConnects to Active Directory and adds a provided SPN to the given account. Uses alternative account to connect to AD.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaSpn -SPN MSSQLSvc/SQLSERVERA.domain.something -ServiceAccount domain\\account -NoDelegation\nConnects to Active Directory and adds a provided SPN to the given account, without the delegation.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eTest-DbaSpn -ComputerName sql2016 | Where { $_.isSet -eq $false } | Set-DbaSpn\nSets all missing SPNs for sql2016\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eTest-DbaSpn -ComputerName sql2016 | Where { $_.isSet -eq $false } | Set-DbaSpn -WhatIf\nDisplays what would happen trying to set all missing SPNs for sql2016",
        "Params":  [
                       [
                           "SPN",
                           "The SPN you want to add",
                           "RequiredSPN",
                           true,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "ServiceAccount",
                           "The account you want the SPN added to",
                           "InstanceServiceAccount,AccountName",
                           true,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "Credential",
                           "The credential you want to use to connect to Active Directory to make the changes",
                           "",
                           false,
                           "true (ByPropertyName)",
                           ""
                       ],
                       [
                           "NoDelegation",
                           "Skips setting the delegation",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command was executed",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Turns confirmations before changes on or off",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaSpn [-SPN] \u003cString\u003e [-ServiceAccount] \u003cString\u003e [[-Credential] \u003cPSCredential\u003e] [-NoDelegation] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaStartupParameter",
        "Description":  "Modifies the startup parameters for a specified SQL Server Instance\n\nFor full details of what each parameter does, please refer to this MSDN article - https://msdn.microsoft.com/en-us/library/ms190737(v=sql.105).aspx",
        "Tags":  [
                     "Startup",
                     "Parameter",
                     "Configure"
                 ],
        "Synopsis":  "Sets the Startup Parameters for a SQL Server instance",
        "Alias":  "",
        "Author":  "Stuart Moore (@napalmgram), stuart-moore.com",
        "CommandName":  "Set-DbaStartupParameter",
        "Availability":  "Windows only",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaStartupParameter -SqlInstance server1\\instance1 -SingleUser\nWill configure the SQL Instance server1\\instance1 to startup up in Single User mode at next startup\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaStartupParameter -SqlInstance sql2016 -IncreasedExtents\nWill configure the SQL Instance sql2016 to IncreasedExtents = True (-E)\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaStartupParameter -SqlInstance sql2016  -IncreasedExtents:$false -WhatIf\nShows what would happen if you attempted to configure the SQL Instance sql2016 to IncreasedExtents = False (no -E)\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaStartupParameter -SqlInstance server1\\instance1 -SingleUser -TraceFlags 8032,8048\nThis will append Trace Flags 8032 and 8048 to the startup parameters\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eSet-DbaStartupParameter -SqlInstance sql2016 -SingleUser:$false -TraceFlagsOverride\nThis will remove all trace flags and set SingleUser to false\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eSet-DbaStartupParameter -SqlInstance server1\\instance1 -SingleUser -TraceFlags 8032,8048 -TraceFlagsOverride\nThis will set Trace Flags 8032 and 8048 to the startup parameters, removing any existing Trace Flags\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eSet-DbaStartupParameter -SqlInstance sql2016 -SingleUser:$false -TraceFlagsOverride -Offline\nThis will remove all trace flags and set SingleUser to false from an offline instance\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eSet-DbaStartupParameter -SqlInstance sql2016 -ErrorLog c:\\Sql\\ -Offline\nThis will attempt to change the ErrorLog path to c:\\sql\\. However, with the offline switch this will not happen. To force it, use the -Force switch like so:\nSet-DbaStartupParameter -SqlInstance sql2016 -ErrorLog c:\\Sql\\ -Offline -Force\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003e$StartupConfig = Get-DbaStartupParameter -SqlInstance server1\\instance1\nPS C:\\\u003e Set-DbaStartupParameter -SqlInstance server1\\instance1 -SingleUser -NoLoggingToWinEvents\r\nPS C:\\\u003e #Restart your SQL instance with the tool of choice\r\nPS C:\\\u003e #Do Some work\r\nPS C:\\\u003e Set-DbaStartupParameter -SqlInstance server1\\instance1 -StartUpConfig $StartUpConfig\r\nPS C:\\\u003e #Restart your SQL instance with the tool of choice and you\u0027re back to normal\nIn this example we take a copy of the existing startup configuration of server1\\instance1\nWe then change the startup parameters ahead of some work\nAfter the work has been completed, we can push the original startup parameters back to server1\\instance1 and resume normal operation",
        "Params":  [
                       [
                           "SqlInstance",
                           "The SQL Server instance to be modified\nIf the Sql Instance is offline path parameters will be ignored as we cannot test the instance\u0027s access to the path. If you want to force this to work then please use the Force switch",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Windows or Sql Login Credential with permission to log into the SQL instance",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Credential",
                           "Windows Credential with permission to log on to the server running the SQL instance",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "MasterData",
                           "Path to the data file for the Master database\nWill be ignored if SqlInstance is offline or the Offline switch is set. To override this behaviour use the Force switch. This is to ensure you understand the risk as we cannot validate the path if \r\nthe instance is offline",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "MasterLog",
                           "Path to the log file for the Master database\nWill be ignored if SqlInstance is offline or the Offline switch is set. To override this behaviour use the Force switch. This is to ensure you understand the risk as we cannot validate the path if \r\nthe instance is offline",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ErrorLog",
                           "Path to the SQL Server error log file\nWill be ignored if SqlInstance is offline or the Offline switch is set. To override this behaviour use the Force switch. This is to ensure you understand the risk as we cannot validate the path if \r\nthe instance is offline",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "TraceFlags",
                           "A comma separated list of TraceFlags to be applied at SQL Server startup\r\nBy default these will be appended to any existing trace flags set",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CommandPromptStart",
                           "Shortens startup time when starting SQL Server from the command prompt. Typically, the SQL Server Database Engine starts as a service by calling the Service Control Manager.\r\nBecause the SQL Server Database Engine does not start as a service when starting from the command prompt",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "MinimalStart",
                           "Starts an instance of SQL Server with minimal configuration. This is useful if the setting of a configuration value (for example, over-committing memory) has\r\nprevented the server from starting. Starting SQL Server in minimal configuration mode places SQL Server in single-user mode",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "MemoryToReserve",
                           "Specifies an integer number of megabytes (MB) of memory that SQL Server will leave available for memory allocations within the SQL Server process,\r\nbut outside the SQL Server memory pool. The memory outside of the memory pool is the area used by SQL Server for loading items such as extended procedure .dll files,\r\nthe OLE DB providers referenced by distributed queries, and automation objects referenced in Transact-SQL statements. The default is 256 MB.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "SingleUser",
                           "Start Sql Server in single user mode",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "SingleUserDetails",
                           "The username for single user",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NoLoggingToWinEvents",
                           "Don\u0027t use Windows Application events log",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "StartAsNamedInstance",
                           "Allows you to start a named instance of SQL Server",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DisableMonitoring",
                           "Disables the following monitoring features:\nSQL Server performance monitor counters\r\nKeeping CPU time and cache-hit ratio statistics\r\nCollecting information for the DBCC SQLPERF command\r\nCollecting information for some dynamic management views\r\nMany extended-events event points\n** Warning *\\* When you use the -x startup option, the information that is available for you to diagnose performance and functional problems with SQL Server is greatly reduced.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IncreasedExtents",
                           "Increases the number of extents that are allocated for each file in a filegroup.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "TraceFlagsOverride",
                           "Overrides the default behaviour and replaces any existing trace flags. If not trace flags specified will just remove existing ones",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "StartUpConfig",
                           "Pass in a previously saved SQL Instance startup config\r\nusing this parameter will set TraceFlagsOverride to true, so existing Trace Flags will be overridden",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Offline",
                           "Setting this switch will try perform the requested actions without connect to the SQL Server Instance, this will speed things up if you know the Instance is offline.\nWhen working offline, path inputs (MasterData, MasterLog and ErrorLog) will be ignored, unless Force is specified",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "By default we test the values passed in via MasterData, MasterLog, ErrorLog",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaStartupParameter [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-MasterData] \u003cString\u003e] [[-MasterLog] \u003cString\u003e] [[-ErrorLog] \u003cString\u003e] [[-TraceFlags] \u003cString[]\u003e] [-CommandPromptStart] [-MinimalStart] [[-MemoryToReserve] \u003cInt32\u003e] [-SingleUser] [[-SingleUserDetails] \u003cString\u003e] [-NoLoggingToWinEvents] [-StartAsNamedInstance] [-DisableMonitoring] [-IncreasedExtents] [-TraceFlagsOverride] [[-StartUpConfig] \u003cObject\u003e] [-Offline] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaTcpPort",
        "Description":  "This function changes the TCP port used by the specified SQL Server.",
        "Tags":  [
                     "Service",
                     "Port",
                     "TCP",
                     "Configure"
                 ],
        "Synopsis":  "Changes the TCP port used by the specified SQL Server.",
        "Alias":  "",
        "Author":  "@H0s0n77",
        "CommandName":  "Set-DbaTcpPort",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Set-DbaTcpPort",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaTcpPort -SqlInstance sql2017 -Port 1433\nSets the port number 1433 for all IP Addresses on the default instance on sql2017. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaTcpPort -SqlInstance winserver\\sqlexpress -IpAddress 192.168.1.22 -Port 1433 -Confirm:$false\nSets the port number 1433 for IP 192.168.1.22 on the sqlexpress instance on winserver. Does not prompt for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaTcpPort -SqlInstance sql2017, sql2019 -port 1337 -Credential ad\\dba\nSets the port number 1337 for all IP Addresses on SqlInstance sql2017 and sql2019 using the credentials for ad\\dba. Prompts for confirmation.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Credential",
                           "Credential object used to connect to the Windows server itself as a different user (like SQL Configuration Manager)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Port",
                           "TCPPort that SQLService should listen on.",
                           "",
                           true,
                           "false",
                           "0"
                       ],
                       [
                           "IpAddress",
                           "Which IpAddress should the portchange , if omitted allip (0.0.0.0) will be changed with the new port number.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaTcpPort [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [-Port] \u003cInt32\u003e [[-IpAddress] \u003cIPAddress[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Set-DbaTempdbConfig",
        "Description":  "Calculates tempdb size and file configurations based on passed parameters, calculated values, and Microsoft best practices. User must declare SQL Server to be configured and total data file size as mandatory values. Function then calculates the number of data files based on logical cores on the target host and create evenly sized data files based on the total data size declared by the user, with a log file 25% of the total data file size.\n\nOther parameters can adjust the settings as the user desires (such as different file paths, number of data files, and log file size). No functions that shrink or delete data files are performed. If you wish to do this, you will need to resize tempdb so that it is \"smaller\" than what the function will size it to before running the function.",
        "Tags":  [
                     "Tempdb",
                     "Space",
                     "Configure",
                     "Configuration"
                 ],
        "Synopsis":  "Sets tempdb data and log files according to best practices.",
        "Alias":  "Set-DbaTempDbConfiguration,Set-SqlTempDbConfiguration",
        "Author":  "Michael Fal (@Mike_Fal), http://mikefal.net",
        "CommandName":  "Set-DbaTempdbConfig",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Set-DbaTempdbConfig",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaTempdbConfig -SqlInstance localhost -DataFileSize 1000\nCreates tempdb with a number of data files equal to the logical cores where each file is equal to 1000MB divided by the number of logical cores, with a log file of 250MB.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaTempdbConfig -SqlInstance localhost -DataFileSize 1000 -DataFileCount 8\nCreates tempdb with 8 data files, each one sized at 125MB, with a log file of 250MB.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaTempdbConfig -SqlInstance localhost -DataFileSize 1000 -OutputScriptOnly\nProvides a SQL script output to configure tempdb according to the passed parameters.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaTempdbConfig -SqlInstance localhost -DataFileSize 1000 -DisableGrowth\nDisables the growth for the data and log files.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eSet-DbaTempdbConfig -SqlInstance localhost -DataFileSize 1000 -OutputScriptOnly\nReturns the T-SQL script representing tempdb configuration.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DataFileCount",
                           "Specifies the number of data files to create. If this number is not specified, the number of logical cores of the host will be used.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "DataFileSize",
                           "Specifies the total data file size in megabytes. This is distributed across the total number of data files.",
                           "",
                           true,
                           "false",
                           "0"
                       ],
                       [
                           "LogFileSize",
                           "Specifies the log file size in megabytes. If not specified, this will be set to 25% of total data file size.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "DataFileGrowth",
                           "Specifies the growth amount for the data file(s) in megabytes. The default is 512 MB.",
                           "",
                           false,
                           "false",
                           "512"
                       ],
                       [
                           "LogFileGrowth",
                           "Specifies the growth amount for the log file in megabytes. The default is 512 MB.",
                           "",
                           false,
                           "false",
                           "512"
                       ],
                       [
                           "DataPath",
                           "Specifies the filesystem path in which to create the tempdb data files. If not specified, current tempdb location will be used.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "LogPath",
                           "Specifies the filesystem path in which to create the tempdb log file. If not specified, current tempdb location will be used.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "OutFile",
                           "Specifies the filesystem path into which the generated T-SQL script will be saved.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "OutputScriptOnly",
                           "If this switch is enabled, only the T-SQL script to change the tempdb configuration is created and output.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DisableGrowth",
                           "If this switch is enabled, the tempdb files will be configured to not grow. This overrides -DataFileGrowth and -LogFileGrowth.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Set-DbaTempdbConfig [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-DataFileCount] \u003cInt32\u003e] [-DataFileSize] \u003cInt32\u003e [[-LogFileSize] \u003cInt32\u003e] [[-DataFileGrowth] \u003cInt32\u003e] [[-LogFileGrowth] \u003cInt32\u003e] [[-DataPath] \u003cString\u003e] [[-LogPath] \u003cString\u003e] [[-OutFile] \u003cString\u003e] [-OutputScriptOnly] [-DisableGrowth] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Show-DbaDbList",
        "Description":  "Shows a list of databases in a GUI. Returns a string holding the name of the selected database. Hitting cancel returns null.",
        "Tags":  [
                     "Database",
                     "FileSystem"
                 ],
        "Synopsis":  "Shows a list of databases in a GUI.",
        "Alias":  "Show-DbaDatabaseList,Show-SqlDatabaseList",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Show-DbaDbList",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Show-DbaDbList",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eShow-DbaDbList -SqlInstance sqlserver2014a\nShows a GUI list of databases using Windows Authentication to connect to the SQL Server. Returns a string of the selected database.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eShow-DbaDbList -SqlInstance sqlserver2014a -SqlCredential $cred\nShows a GUI list of databases using SQL credentials to connect to the SQL Server. Returns a string of the selected database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eShow-DbaDbList -SqlInstance sqlserver2014a -DefaultDb master\nShows a GUI list of databases using Windows Authentication to connect to the SQL Server. The \"master\" database will be selected when the lists shows. Returns a string of the selected database.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances..",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Title",
                           "Title of the window being displayed. Default is \"Select Database\".",
                           "",
                           false,
                           "false",
                           "Select Database"
                       ],
                       [
                           "Header",
                           "Header text displayed above the database listing. Default is \"Select the database:\".",
                           "",
                           false,
                           "false",
                           "Select the database:"
                       ],
                       [
                           "DefaultDb",
                           "Specify a database to have selected when the window appears.",
                           "",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Show-DbaDbList [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Title] \u003cString\u003e] [[-Header] \u003cString\u003e] [[-DefaultDb] \u003cString\u003e] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Show-DbaServerFileSystem",
        "Description":  "Similar to the remote file system popup you see when browsing a remote SQL Server in SQL Server Management Studio, this function allows you to traverse the remote SQL Server\u0027s file structure.\n\nShow-DbaServerFileSystem uses SQL Management Objects to browse the directories and what you see is limited to the permissions of the account running the command.",
        "Tags":  [
                     "Storage",
                     "FileSystem"
                 ],
        "Synopsis":  "Shows file system on remote SQL Server in a local GUI and returns the selected directory name",
        "Alias":  "Show-SqlServerFileSystem",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Show-DbaServerFileSystem",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Show-DbaServerFileSystem",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eShow-DbaServerFileSystem -SqlInstance sql2017\nShows a list of databases using Windows Authentication to connect to the SQL Server. Returns a string of the selected path.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eShow-DbaServerFileSystem -SqlInstance sql2017 -SqlCredential $cred\nShows a list of databases using SQL credentials to connect to the SQL Server. Returns a string of the selected path.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Defaults to localhost.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Show-DbaServerFileSystem [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Start-DbaAgentJob",
        "Description":  "This command starts a job then returns connected SMO object for SQL Agent Job information for each instance(s) of SQL Server.",
        "Tags":  [
                     "Job",
                     "Agent"
                 ],
        "Synopsis":  "Starts a running SQL Server Agent Job.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Start-DbaAgentJob",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Start-DbaAgentJob",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStart-DbaAgentJob -SqlInstance localhost\nStarts all running SQL Agent Jobs on the local SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance sql2016 -Job cdc.DBWithCDC_capture | Start-DbaAgentJob\nStarts the cdc.DBWithCDC_capture SQL Agent Job on sql2016\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eStart-DbaAgentJob -SqlInstance sql2016 -Job cdc.DBWithCDC_capture\nStarts the cdc.DBWithCDC_capture SQL Agent Job on sql2016\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$servers | Find-DbaAgentJob -IsFailed | Start-DbaAgentJob\nRestarts all failed jobs on all servers in the $servers collection\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eStart-DbaAgentJob -SqlInstance sql2016 -AllJobs\nStart all the jobs",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Job",
                           "The job(s) to process - this list is auto-populated from the server. If unspecified, all jobs will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeJob",
                           "The job(s) to exclude - this list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Internal parameter that enables piping",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "AllJobs",
                           "Retrieve all the jobs",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Wait",
                           "Wait for output until the job has started",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WaitPeriod",
                           "Wait period in seconds to use when -Wait is used",
                           "",
                           false,
                           "false",
                           "3"
                       ],
                       [
                           "SleepPeriod",
                           "Period in milliseconds to wait after a job has started",
                           "",
                           false,
                           "false",
                           "300"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Start-DbaAgentJob [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cString[]\u003e] [-ExcludeJob \u003cString[]\u003e] [-AllJobs] [-Wait] [-WaitPeriod \u003cInt32\u003e] [-SleepPeriod \u003cInt32\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStart-DbaAgentJob -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cString[]\u003e] [-ExcludeJob \u003cString[]\u003e] [-AllJobs] [-Wait] [-WaitPeriod \u003cInt32\u003e] [-SleepPeriod \u003cInt32\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStart-DbaAgentJob [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cString[]\u003e] [-ExcludeJob \u003cString[]\u003e] -InputObject \u003cJob[]\u003e [-AllJobs] [-Wait] [-WaitPeriod \u003cInt32\u003e] [-SleepPeriod \u003cInt32\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Start-DbaEndpoint",
        "Description":  "Starts endpoints on a SQL Server instance.",
        "Tags":  "Endpoint",
        "Synopsis":  "Starts endpoints on a SQL Server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Start-DbaEndpoint",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Start-DbaEndpoint",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStart-DbaEndpoint -SqlInstance sqlserver2012 -AllEndpoints\nStarts all endpoints on the sqlserver2014 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eStart-DbaEndpoint -SqlInstance sqlserver2012 -Endpoint endpoint1,endpoint2 -SqlCredential sqladmin\nLogs into sqlserver2012 using alternative credentials and starts the endpoint1 and endpoint2 endpoints.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-Endpoint -SqlInstance sqlserver2012 -Endpoint endpoint1 | Start-DbaEndpoint\nStarts the endpoints returned from the Get-Endpoint function.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EndPoint",
                           "Only start specific endpoints.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AllEndpoints",
                           "Start all endpoints on an instance.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-Endpoint.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Start-DbaEndpoint [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-EndPoint] \u003cString[]\u003e] [-AllEndpoints] [[-InputObject] \u003cEndpoint[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Start-DbaMigration",
        "Description":  "Start-DbaMigration consolidates most of the migration tools in dbatools into one command.  This is useful when you\u0027re looking to migrate entire instances. It less flexible than using the underlying functions. Think of it as an easy button. It migrates:\n\nAll user databases to exclude support databases such as ReportServerTempDB (Use -IncludeSupportDbs for this). Use -Exclude Databases to skip.\nAll logins. Use -Exclude Logins to skip.\nAll database mail objects. Use -Exclude DatabaseMail\nAll credentials. Use -Exclude Credentials to skip.\nAll objects within the Job Server (SQL Agent). Use -Exclude AgentServer to skip.\nAll linked servers. Use -Exclude LinkedServers to skip.\nAll groups and servers within Central Management Server. Use -Exclude CentralManagementServer to skip.\nAll SQL Server configuration objects (everything in sp_configure). Use -Exclude SpConfigure to skip.\nAll user objects in system databases. Use -Exclude SysDbUserObjects to skip.\nAll system triggers. Use -Exclude SystemTriggers to skip.\nAll system backup devices. Use -Exclude BackupDevices to skip.\nAll Audits. Use -Exclude Audits to skip.\nAll Endpoints. Use -Exclude Endpoints to skip.\nAll Extended Events. Use -Exclude ExtendedEvents to skip.\nAll Policy Management objects. Use -Exclude PolicyManagement to skip.\nAll Resource Governor objects. Use -Exclude ResourceGovernor to skip.\nAll Server Audit Specifications. Use -Exclude ServerAuditSpecifications to skip.\nAll Custom Errors (User Defined Messages). Use -Exclude CustomErrors to skip.\nCopies All Data Collector collection sets. Does not configure the server. Use -Exclude DataCollector to skip.\n\nThis script provides the ability to migrate databases using detach/copy/attach or backup/restore. SQL Server logins, including passwords, SID and database/server roles can also be migrated. In addition, job server objects can be migrated and server configuration settings can be exported or migrated. This script works with named instances, clusters and SQL Express.\n\nBy default, databases will be migrated to the destination SQL Server\u0027s default data and log directories. You can override this by specifying -ReuseSourceFolderStructure. Filestreams and filegroups are also migrated. Safety is emphasized.",
        "Tags":  "Migration",
        "Synopsis":  "Migrates SQL Server *ALL* databases, logins, database mail profiles/accounts, credentials, SQL Agent objects, linked servers,\nCentral Management Server objects, server configuration settings (sp_configure), user objects in systems databases,\nsystem triggers and backup devices from one SQL Server to another.\n\nFor more granular control, please use Exclude or use the other functions available within the dbatools module.",
        "Alias":  "Start-SqlMigration",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Start-DbaMigration",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Start-DbaMigration",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStart-DbaMigration -Source sqlserver\\instance -Destination sqlcluster -DetachAttach\nAll databases, logins, job objects and sp_configure options will be migrated from sqlserver\\instance to sqlcluster. Databases will be migrated using the detach/copy files/attach method. Dbowner will \r\nbe updated. User passwords, SIDs, database roles and server roles will be migrated along with the login.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e Source = \"sqlcluster\"\r\n\u003e\u003e Destination = \"sql2016\"\r\n\u003e\u003e SourceSqlCredential = $scred\r\n\u003e\u003e DestinationSqlCredential = $cred\r\n\u003e\u003e SharedPath = \"\\\\fileserver\\share\\sqlbackups\\Migration\"\r\n\u003e\u003e BackupRestore = $true\r\n\u003e\u003e ReuseSourceFolderStructure = $true\r\n\u003e\u003e Force = $true\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Start-DbaMigration @params -Verbose\nUtilizes splatting technique to set all the needed parameters. This will migrate databases using the backup/restore method. It will also include migration of the logins, database mail configuration, \r\ncredentials, SQL Agent, Central Management Server, and SQL Server global configuration.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eStart-DbaMigration -Verbose -Source sqlcluster -Destination sql2016 -DetachAttach -Reattach -SetSourceReadonly\nMigrates databases using detach/copy/attach. Reattach at source and set source databases read-only. Also migrates everything else.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$PSDefaultParameters = @{\n\u003e\u003e \"dbatools:Source\" = \"sqlcluster\"\r\n\u003e\u003e \"dbatools:Destination\" = \"sql2016\"\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Start-DbaMigration -Verbose -Exclude Databases, Logins\nUtilizes the PSDefaultParameterValues system variable, and sets the Source and Destination parameters for any function in the module that has those parameter names. This prevents the need from \r\npassing them in constantly.\r\nThe execution of the function will migrate everything but logins and databases.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You may specify multiple servers.\nNote that when using -BackupRestore with multiple servers, the backup will only be performed once and backups will be deleted at the end (if you didn\u0027t specify -ExcludeBackupCleanup).\nWhen using -DetachAttach with multiple servers, -Reattach must be specified.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DetachAttach",
                           "If this switch is enabled, the the detach/copy/attach method is used to perform database migrations. No files are deleted on Source. If the destination attachment fails, the source database will be \r\nreattached. File copies are performed over administrative shares (\\\\server\\x$\\mssql) using BITS. If a database is being mirrored, the mirror will be broken prior to migration.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Reattach",
                           "If this switch is enabled, all databases are reattached to Source after a DetachAttach migration is complete.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "BackupRestore",
                           "If this switch is enabled, the Copy-Only backup and restore method is used to perform database migrations. You must specify -SharedPath with a valid UNC format as well (\\\\server\\share).",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "SharedPath",
                           "Specifies the network location for the backup files. The SQL Server service accounts on both Source and Destination must have read/write permission to access this location.",
                           "NetworkShare",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "WithReplace",
                           "If this switch is enabled, databases are restored from backup using WITH REPLACE. This is useful if you want to stage some complex file paths.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NoRecovery",
                           "If this switch is enabled, databases will be left in the No Recovery state to enable further backups to be added.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "SetSourceReadOnly",
                           "If this switch is enabled, all migrated databases will be set to ReadOnly on the source instance prior to detach/attach \u0026 backup/restore. If -Reattach is specified, the database is set to read-only \r\nafter reattaching.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ReuseSourceFolderStructure",
                           "If this switch is enabled, the data and log directory structures on Source will be kept on Destination. Otherwise, databases will be migrated to Destination\u0027s default data and log directories.\nConsider this if you\u0027re migrating between different versions and use part of Microsoft\u0027s default SQL structure (MSSQL12.INSTANCE, etc.).",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IncludeSupportDbs",
                           "If this switch is enabled, the ReportServer, ReportServerTempDb, SSIDb, and distribution databases will be migrated if they exist. A logfile named $SOURCE-$DESTINATION-$date-Sqls.csv will be written \r\nto the current directory. Requires -BackupRestore or -DetachAttach.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Exclude",
                           "Exclude one or more objects to migrate\nDatabases\r\nLogins\r\nAgentServer\r\nCredentials\r\nLinkedServers\r\nSpConfigure\r\nCentralManagementServer\r\nDatabaseMail\r\nSysDbUserObjects\r\nSystemTriggers\r\nBackupDevices\r\nAudits\r\nEndpoints\r\nExtendedEvents\r\nPolicyManagement\r\nResourceGovernor\r\nServerAuditSpecifications\r\nCustomErrors\r\nDataCollector",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DisableJobsOnDestination",
                           "If this switch is enabled, migrated SQL Agent jobs will be disabled on the destination instance.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DisableJobsOnSource",
                           "If this switch is enabled, SQL Agent jobs will be disabled on the source instance.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ExcludeSaRename",
                           "If this switch is enabled, the sa account will not be renamed on the destination instance to match the source.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "UseLastBackup",
                           "Use the last full, diff and logs instead of performing backups. Note that the backups must exist in a location accessible by all destination servers, such a network share.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Continue",
                           "If specified, will to attempt to restore transaction log backups on top of existing database(s) in Recovering or Standby states. Only usable with -UseLastBackup",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Force",
                           "If migrating users, forces drop and recreate of SQL and Windows logins.\r\nIf migrating databases, deletes existing databases with matching names.\r\nIf using -DetachAttach, -Force will break mirrors and drop dbs from Availability Groups.\nFor other migration objects, it will just drop existing items and readd, if -force is supported within the underlying function.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Start-DbaMigration [[-Source] \u003cDbaInstanceParameter\u003e] [[-Destination] \u003cDbaInstanceParameter[]\u003e] [-DetachAttach] [-Reattach] [-BackupRestore] [[-SharedPath] \u003cString\u003e] [-WithReplace] [-NoRecovery] [-SetSourceReadOnly] [-ReuseSourceFolderStructure] [-IncludeSupportDbs] [[-SourceSqlCredential] \u003cPSCredential\u003e] [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Exclude] \u003cString[]\u003e] [-DisableJobsOnDestination] [-DisableJobsOnSource] [-ExcludeSaRename] [-UseLastBackup] [-Continue] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Start-DbaPfDataCollectorSet",
        "Description":  "Starts Performance Monitor Data Collector Set.",
        "Tags":  "PerfMon",
        "Synopsis":  "Starts Performance Monitor Data Collector Set.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Start-DbaPfDataCollectorSet",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Start-DbaPfDataCollectorSet",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStart-DbaPfDataCollectorSet\nAttempts to start all ready Collectors on localhost.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eStart-DbaPfDataCollectorSet -ComputerName sql2017\nAttempts to start all ready Collectors on localhost.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eStart-DbaPfDataCollectorSet -ComputerName sql2017, sql2016 -Credential ad\\sqldba -CollectorSet \u0027System Correlation\u0027\nStarts the \u0027System Correlation\u0027 Collector on sql2017 and sql2016 using alternative credentials.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet -CollectorSet \u0027System Correlation\u0027 | Start-DbaPfDataCollectorSet\nStarts the \u0027System Correlation\u0027 Collector.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer. Defaults to localhost.",
                           "",
                           false,
                           "false",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to $ComputerName using alternative credentials. To use:\n$cred = Get-Credential, then pass $cred object to the -Credential parameter.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CollectorSet",
                           "The name of the Collector Set to start.",
                           "DataCollectorSet",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Accepts the object output by Get-DbaPfDataCollectorSet via the pipeline.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "NoWait",
                           "If this switch is enabled, the collector is started and the results are returned immediately.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Start-DbaPfDataCollectorSet [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CollectorSet] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-NoWait] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Start-DbaService",
        "Description":  "Starts the SQL Server related services on one or more computers. Will follow SQL Server service dependencies.\n\nRequires Local Admin rights on destination computer(s).",
        "Tags":  [
                     "Service",
                     "SqlServer",
                     "Instance",
                     "Connect"
                 ],
        "Synopsis":  "Starts SQL Server services on a computer.",
        "Alias":  "Start-DbaSqlService",
        "Author":  "Kirill Kravtsov (@nvarscar)",
        "CommandName":  "Start-DbaService",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Start-DbaService",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStart-DbaService -ComputerName sqlserver2014a\nStarts the SQL Server related services on computer sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\u0027,\u0027sql3\u0027| Get-DbaService | Start-DbaService\nGets the SQL Server related services on computers sql1, sql2 and sql3 and starts them.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eStart-DbaService -ComputerName sql1,sql2 -Instance MSSQLSERVER\nStarts the SQL Server services related to the default instance MSSQLSERVER on computers sql1 and sql2.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eStart-DbaService -ComputerName $MyServers -Type SSRS\nStarts the SQL Server related services of type \"SSRS\" (Reporting Services) on computers in the variable MyServers.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target SQL Server instance or instances.",
                           "cn,host,Server",
                           false,
                           "false",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "InstanceName",
                           "Only affects services that belong to the specific instances.",
                           "Instance",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Type",
                           "Use -Type to collect only services of the desired SqlServiceType.\r\nCan be one of the following: \"Agent\",\"Browser\",\"Engine\",\"FullText\",\"SSAS\",\"SSIS\",\"SSRS\"",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "A collection of services from Get-DbaService",
                           "ServiceCollection",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Timeout",
                           "How long to wait for the start/stop request completion before moving on. Specify 0 to wait indefinitely.",
                           "",
                           false,
                           "false",
                           "60"
                       ],
                       [
                           "Credential",
                           "Credential object used to connect to the computer as a different user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the cmdlet runs. The cmdlet is not run.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before running the cmdlet.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Start-DbaService [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [-InstanceName \u003cString[]\u003e] [-Type \u003cString[]\u003e] [-Timeout \u003cInt32\u003e] [-Credential \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStart-DbaService [-InstanceName \u003cString[]\u003e] [-Type \u003cString[]\u003e] -InputObject \u003cObject[]\u003e [-Timeout \u003cInt32\u003e] [-Credential \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Start-DbaTrace",
        "Description":  "Starts SQL Server traces",
        "Tags":  [
                     "Security",
                     "Trace"
                 ],
        "Synopsis":  "Starts SQL Server traces",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Start-DbaTrace",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStart-DbaTrace -SqlInstance sql2008\nStarts all traces on sql2008\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eStart-DbaTrace -SqlInstance sql2008 -Id 1\nStarts all trace with ID 1 on sql2008\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaTrace -SqlInstance sql2008 | Out-GridView -PassThru | Start-DbaTrace\nStarts selected traces on sql2008",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Id",
                           "A list of trace ids",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Internal parameter for piping",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Start-DbaTrace [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Id] \u003cInt32[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Start-DbaXESession",
        "Description":  "This script starts Extended Events sessions on a SQL Server instance.",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "Starts Extended Events sessions.",
        "Alias":  "",
        "Author":  "Doug Meyers",
        "CommandName":  "Start-DbaXESession",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Start-DbaXESession",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStart-DbaXESession -SqlInstance sqlserver2012 -AllSessions\nStarts all Extended Event Session on the sqlserver2014 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eStart-DbaXESession -SqlInstance sqlserver2012 -Session xesession1,xesession2\nStarts the xesession1 and xesession2 Extended Event sessions.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eStart-DbaXESession -SqlInstance sqlserver2012 -Session xesession1,xesession2 -StopAt (Get-Date).AddMinutes(30)\nStarts the xesession1 and xesession2 Extended Event sessions and stops them in 30 minutes.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sqlserver2012 -Session xesession1 | Start-DbaXESession\nStarts the sessions returned from the Get-DbaXESession function.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Session",
                           "Only start specific Extended Events sessions.",
                           "Sessions",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "StopAt",
                           "Specifies a datetime at which the session will be stopped. This is done via a self-deleting schedule.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AllSessions",
                           "Start all Extended Events sessions on an instance, ignoring the packaged sessions: AlwaysOn_health, system_health, telemetry_xevents.",
                           "",
                           true,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Internal parameter to support piping from Get-DbaXESession",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Start-DbaXESession [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -Session \u003cObject[]\u003e [-StopAt \u003cDateTime\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStart-DbaXESession [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-StopAt \u003cDateTime\u003e] -AllSessions [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStart-DbaXESession [-StopAt \u003cDateTime\u003e] -InputObject \u003cSession[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Start-DbaXESmartTarget",
        "Description":  "XESmartTarget offers the ability to set up complex actions in response to Extended Events captured in sessions, without writing a single line of code.\n\nSee more at https://github.com/spaghettidba/XESmartTarget/wiki",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "XESmartTarget runs as a client application for an Extended Events session running on a SQL Server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl) | SmartTarget by Gianluca Sartori (@spaghettidba)",
        "CommandName":  "Start-DbaXESmartTarget",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Start-DbaXESmartTarget",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$response = New-DbaXESmartQueryExec -SqlInstance sql2017 -Database dbadb -Query \"update table set whatever = 1\"\nPS C:\\\u003eStart-DbaXESmartTarget -SqlInstance sql2017 -Session deadlock_tracker -Responder $response\nExecutes a T-SQL command against dbadb on sql2017 whenever a deadlock event is recorded.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$response = New-DbaXESmartQueryExec -SqlInstance sql2017 -Database dbadb -Query \"update table set whatever = 1\"\nPS C:\\\u003e$params = @{\r\n\u003e\u003e SmtpServer = \"smtp.ad.local\"\r\n\u003e\u003e To = \"[email protected]\"\r\n\u003e\u003e Sender = \"[email protected]\"\r\n\u003e\u003e Subject = \"Query executed\"\r\n\u003e\u003e Body = \"Query executed at {collection_time}\"\r\n\u003e\u003e Attachment = \"batch_text\"\r\n\u003e\u003e AttachmentFileName = \"query.sql\"\r\n\u003e\u003e }\r\nPS C:\\\u003e $emailresponse = New-DbaXESmartEmail @params\r\nPS C:\\\u003e Start-DbaXESmartTarget -SqlInstance sql2017 -Session querytracker -Responder $response, $emailresponse\nExecutes a T-SQL command against dbadb on sql2017 and sends an email whenever a querytracker event is recorded.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$columns = \"cpu_time\", \"duration\", \"physical_reads\", \"logical_reads\", \"writes\", \"row_count\", \"batch_text\"\nPS C:\\\u003e $response = New-DbaXESmartTableWriter -SqlInstance sql2017 -Database dbadb -Table deadlocktracker -OutputColumns $columns -Filter \"duration \u003e 10000\"\r\nPS C:\\\u003e Start-DbaXESmartTarget -SqlInstance sql2017 -Session deadlock_tracker -Responder $response\nWrites Extended Events to the deadlocktracker table in dbadb on sql2017.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies the name of the database that contains the target table.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Session",
                           "Name of the Extended Events session to attach to.\nYou can monitor a single session with an instance of XESmartTarget. In case you need to perform action on multiple sessions, run an additional instance of XESmartTarget, with its own configuration \r\nfile.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "FailOnProcessingError",
                           "If this switch is enabled, the a processing error will trigger a failure.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Responder",
                           "The list of responses can include zero or more Response objects, each to be configured by specifying values for their public members.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Template",
                           "Path to the dbatools built-in templates",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NotAsJob",
                           "If this switch is enabled, output will be sent to screen indefinitely. BY default, a job will be run in the background.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Start-DbaXESmartTarget [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [-Session] \u003cString\u003e [-FailOnProcessingError] [[-Responder] \u003cObject[]\u003e] [[-Template] \u003cString[]\u003e] [-NotAsJob] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Stop-DbaAgentJob",
        "Description":  "This command stops a job then returns connected SMO object for SQL Agent Job information for each instance(s) of SQL Server.",
        "Tags":  [
                     "Job",
                     "Agent"
                 ],
        "Synopsis":  "Stops a running SQL Server Agent Job.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Stop-DbaAgentJob",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Stop-DbaAgentJob",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStop-DbaAgentJob -SqlInstance localhost\nStops all running SQL Agent Jobs on the local SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance sql2016 -Job cdc.DBWithCDC_capture | Stop-DbaAgentJob\nStops the cdc.DBWithCDC_capture SQL Agent Job on sql2016\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eStop-DbaAgentJob -SqlInstance sql2016 -Job cdc.DBWithCDC_capture\nStops the cdc.DBWithCDC_capture SQL Agent Job on sql2016",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Job",
                           "The job(s) to process - this list is auto-populated from the server. If unspecified, all jobs will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeJob",
                           "The job(s) to exclude - this list is auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Internal parameter that enables piping",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Wait",
                           "Wait for output until the job has completely stopped",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Stop-DbaAgentJob [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cString[]\u003e] [-ExcludeJob \u003cString[]\u003e] [-Wait] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStop-DbaAgentJob -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cString[]\u003e] [-ExcludeJob \u003cString[]\u003e] [-Wait] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStop-DbaAgentJob [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cString[]\u003e] [-ExcludeJob \u003cString[]\u003e] -InputObject \u003cJob[]\u003e [-Wait] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Stop-DbaEndpoint",
        "Description":  "Stops endpoints on a SQL Server instance.",
        "Tags":  "Endpoint",
        "Synopsis":  "Stops endpoints on a SQL Server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Stop-DbaEndpoint",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Stop-DbaEndpoint",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStop-DbaEndpoint -SqlInstance sql2017a -AllEndpoints\nStops all endpoints on the sqlserver2014 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eStop-DbaEndpoint -SqlInstance sql2017a -Endpoint endpoint1,endpoint2\nStops the endpoint1 and endpoint2 endpoints.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-Endpoint -SqlInstance sql2017a -Endpoint endpoint1 | Stop-DbaEndpoint\nStops the endpoints returned from the Get-Endpoint command.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EndPoint",
                           "Only stop specific endpoints.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AllEndpoints",
                           "Stops all endpoints on an instance.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-Endpoint.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Stop-DbaEndpoint [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-EndPoint] \u003cString[]\u003e] [-AllEndpoints] [[-InputObject] \u003cEndpoint[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Stop-DbaPfDataCollectorSet",
        "Description":  "Stops Performance Monitor Data Collector Set.",
        "Tags":  "PerfMon",
        "Synopsis":  "Stops Performance Monitor Data Collector Set.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Stop-DbaPfDataCollectorSet",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Stop-DbaPfDataCollectorSet",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStop-DbaPfDataCollectorSet\nAttempts to stop all ready Collectors on localhost.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eStop-DbaPfDataCollectorSet -ComputerName sql2017\nAttempts to stop all ready Collectors on localhost.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eStop-DbaPfDataCollectorSet -ComputerName sql2017, sql2016 -Credential ad\\sqldba -CollectorSet \u0027System Correlation\u0027\nStops the \u0027System Correlation\u0027 Collector on sql2017 and sql2016 using alternative credentials.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet -CollectorSet \u0027System Correlation\u0027 | Stop-DbaPfDataCollectorSet\nStops the \u0027System Correlation\u0027 Collector.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer. Defaults to localhost.",
                           "",
                           false,
                           "false",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Allows you to login to $ComputerName using alternative credentials. To use:\n$cred = Get-Credential, then pass $cred object to the -Credential parameter.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CollectorSet",
                           "The name of the Collector Set to stop.",
                           "DataCollectorSet",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Accepts the object output by Get-DbaPfDataCollectorSet via the pipeline.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "NoWait",
                           "If this switch is enabled, the collector is stopped and the results are returned immediately.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Stop-DbaPfDataCollectorSet [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CollectorSet] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-NoWait] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Stop-DbaProcess",
        "Description":  "This command kills all spids associated with a spid, login, host, program or database.\n\nIf you are attempting to kill your own login sessions, the process performing the kills will be skipped.",
        "Tags":  "Processes",
        "Synopsis":  "This command finds and kills SQL Server processes.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Stop-DbaProcess",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Stop-DbaProcess",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStop-DbaProcess -SqlInstance sqlserver2014a -Login base\\ctrlb, sa\nFinds all processes for base\\ctrlb and sa on sqlserver2014a, then kills them. Uses Windows Authentication to login to sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eStop-DbaProcess -SqlInstance sqlserver2014a -SqlCredential $credential -Spid 56, 77\nFinds processes for spid 56 and 57, then kills them. Uses alternative (SQL or Windows) credentials to login to sqlserver2014a.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eStop-DbaProcess -SqlInstance sqlserver2014a -Program \u0027Microsoft SQL Server Management Studio\u0027\nFinds processes that were created in Microsoft SQL Server Management Studio, then kills them.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eStop-DbaProcess -SqlInstance sqlserver2014a -Hostname workstationx, server100\nFinds processes that were initiated (computers/clients) workstationx and server 1000, then kills them.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eStop-DbaProcess -SqlInstance sqlserver2014  -Database tempdb -WhatIf\nShows what would happen if the command were executed.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaProcess -SqlInstance sql2016 -Program \u0027dbatools PowerShell module - dbatools.io\u0027 | Stop-DbaProcess\nFinds processes that were created with dbatools, then kills them.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Spid",
                           "Specifies one or more spids to be killed. Options for this parameter are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeSpid",
                           "Specifies one or more spids which will not be killed. Options for this parameter are auto-populated from the server.\nExclude is the last filter to run, so even if a spid matches (for example) Hosts, if it\u0027s listed in Exclude it wil be excluded.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies one or more databases whose processes will be killed. Options for this parameter are auto-populated from the server and only databases that have active processes are offered.\nThis parameter is auto-populated from -SqlInstance and allows only database names that have active processes. You can specify one or more Databases whose processes will be killed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Login",
                           "Specifies one or more login names whose processes will be killed. Options for this parameter are auto-populated from the server and only login names that have active processes are offered.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Hostname",
                           "Specifies one or more client hostnames whose processes will be killed. Options for this parameter are auto-populated from the server and only hostnames that have active processes are offered.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Program",
                           "Specifies one or more client programs whose processes will be killed. Options for this parameter are auto-populated from the server and only programs that have active processes are offered.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "This is the process object passed by Get-DbaProcess if using a pipeline.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Stop-DbaProcess [-SqlCredential \u003cPSCredential\u003e] [-Spid \u003cInt32[]\u003e] [-ExcludeSpid \u003cInt32[]\u003e] [-Database \u003cString[]\u003e] [-Login \u003cString[]\u003e] [-Hostname \u003cString[]\u003e] [-Program \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStop-DbaProcess -SqlInstance \u003cDbaInstanceParameter\u003e [-SqlCredential \u003cPSCredential\u003e] [-Spid \u003cInt32[]\u003e] [-ExcludeSpid \u003cInt32[]\u003e] [-Database \u003cString[]\u003e] [-Login \u003cString[]\u003e] [-Hostname \u003cString[]\u003e] [-Program \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStop-DbaProcess [-SqlCredential \u003cPSCredential\u003e] [-Spid \u003cInt32[]\u003e] [-ExcludeSpid \u003cInt32[]\u003e] [-Database \u003cString[]\u003e] [-Login \u003cString[]\u003e] [-Hostname \u003cString[]\u003e] [-Program \u003cString[]\u003e] -InputObject \u003cObject[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Stop-DbaService",
        "Description":  "Stops the SQL Server related services on one or more computers. Will follow SQL Server service dependencies.\n\nRequires Local Admin rights on destination computer(s).",
        "Tags":  [
                     "Service",
                     "Stop"
                 ],
        "Synopsis":  "Stops SQL Server services on a computer.",
        "Alias":  "Stop-DbaSqlService",
        "Author":  "Kirill Kravtsov (@nvarscar)",
        "CommandName":  "Stop-DbaService",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Stop-DbaService",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStop-DbaService -ComputerName sqlserver2014a\nStops the SQL Server related services on computer sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\u0027,\u0027sql3\u0027| Get-DbaService | Stop-DbaService\nGets the SQL Server related services on computers sql1, sql2 and sql3 and stops them.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eStop-DbaService -ComputerName sql1,sql2 -Instance MSSQLSERVER\nStops the SQL Server services related to the default instance MSSQLSERVER on computers sql1 and sql2.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eStop-DbaService -ComputerName $MyServers -Type SSRS\nStops the SQL Server related services of type \"SSRS\" (Reporting Services) on computers in the variable MyServers.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eStop-DbaService -ComputerName sql1 -Type Engine -Force\nStops SQL Server database engine services on sql1 forcing dependent SQL Server Agent services to stop as well.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target SQL Server instance or instances.",
                           "cn,host,Server",
                           false,
                           "false",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "InstanceName",
                           "Only affects services that belong to the specific instances.",
                           "Instance",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Type",
                           "Use -Type to collect only services of the desired SqlServiceType.\r\nCan be one of the following: \"Agent\",\"Browser\",\"Engine\",\"FullText\",\"SSAS\",\"SSIS\",\"SSRS\"",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "A collection of services from Get-DbaService",
                           "ServiceCollection",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Timeout",
                           "How long to wait for the start/stop request completion before moving on. Specify 0 to wait indefinitely.",
                           "",
                           false,
                           "false",
                           "60"
                       ],
                       [
                           "Credential",
                           "Credential object used to connect to the computer as a different user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Force",
                           "Use this switch to stop dependent services before proceeding with the specified service",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the cmdlet runs. The cmdlet is not run.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before running the cmdlet.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Stop-DbaService [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [-InstanceName \u003cString[]\u003e] [-Type \u003cString[]\u003e] [-Timeout \u003cInt32\u003e] [-Credential \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStop-DbaService [-InstanceName \u003cString[]\u003e] [-Type \u003cString[]\u003e] -InputObject \u003cObject[]\u003e [-Timeout \u003cInt32\u003e] [-Credential \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Stop-DbaTrace",
        "Description":  "Stops SQL Server traces",
        "Tags":  [
                     "Security",
                     "Trace"
                 ],
        "Synopsis":  "Stops SQL Server traces",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Stop-DbaTrace",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStop-DbaTrace -SqlInstance sql2008\nStops all traces on sql2008\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eStop-DbaTrace -SqlInstance sql2008 -Id 1\nStops all trace with ID 1 on sql2008\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaTrace -SqlInstance sql2008 | Out-GridView -PassThru | Stop-DbaTrace\nStops selected traces on sql2008",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Id",
                           "A list of trace ids",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Internal parameter for piping",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Stop-DbaTrace [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Id] \u003cInt32[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Stop-DbaXESession",
        "Description":  "This script stops Extended Events sessions on a SQL Server instance.",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "Stops Extended Events sessions.",
        "Alias":  "",
        "Author":  "Doug Meyers",
        "CommandName":  "Stop-DbaXESession",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Stop-DbaXESession",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStop-DbaXESession -SqlInstance sqlserver2012 -AllSessions\nStops all Extended Event Session on the sqlserver2014 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eStop-DbaXESession -SqlInstance sqlserver2012 -Session xesession1,xesession2\nStops the xesession1 and xesession2 Extended Event sessions.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sqlserver2012 -Session xesession1 | Stop-DbaXESession\nStops the sessions returned from the Get-DbaXESession function.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Session",
                           "Specifies individual Extended Events sessions to stop.",
                           "Sessions",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "AllSessions",
                           "If this switch is enabled, all Extended Events sessions will be stopped except the packaged sessions AlwaysOn_health, system_health, telemetry_xevents.",
                           "",
                           true,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Accepts the object output by Get-DbaXESession as the list of sessions to be stopped.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Stop-DbaXESession [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -Session \u003cObject[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStop-DbaXESession [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -AllSessions [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStop-DbaXESession -InputObject \u003cSession[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Stop-DbaXESmartTarget",
        "Description":  "Stops an XESmartTarget PowerShell job. Useful if you want to run a target, but not right now.",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "Stops an XESmartTarget PowerShell job. Useful if you want to run a target, but not right now.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl) | SmartTarget by Gianluca Sartori (@spaghettidba)",
        "CommandName":  "Stop-DbaXESmartTarget",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Stop-DbaXESmartTarget\nhttps://github.com/spaghettidba/XESmartTarget/wiki",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaXESmartTarget | Stop-DbaXESmartTarget\nStops all XESmartTarget jobs.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaXESmartTarget | Where-Object Id -eq 2 | Stop-DbaXESmartTarget\nStops a specific XESmartTarget job.",
        "Params":  [
                       [
                           "InputObject",
                           "The XESmartTarget job object.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Stop-DbaXESmartTarget [-InputObject] \u003cObject[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Suspend-DbaAgDbDataMovement",
        "Description":  "Suspends data movement for an availability group database on a SQL Server instance.",
        "Tags":  [
                     "AvailabilityGroup",
                     "HA",
                     "AG"
                 ],
        "Synopsis":  "Suspends data movement for an availability group database on a SQL Server instance.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Suspend-DbaAgDbDataMovement",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Suspend-DbaAgDbDataMovement",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSuspend-DbaAgDbDataMovement -SqlInstance sql2017a -AvailabilityGroup ag1 -Database db1, db2\nSuspends data movement on db1 and db2 to ag1 on sql2017a. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgDatabase -SqlInstance sql2017a, sql2019 | Out-GridView -Passthru | Suspend-DbaAgDbDataMovement -Confirm:$false\nSuspends data movement on the selected availability group databases. Does not prompt for confirmation.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityGroup",
                           "The availability group where the database movement will be suspended.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database or databases to suspend movement upon.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaAgDatabase",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Suspend-DbaAgDbDataMovement [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cAvailabilityDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Sync-DbaAvailabilityGroup",
        "Description":  "Syncs depdendent objects for availability groups. Such objects include:\n\nSpConfigure\nCustomErrors\nCredentials\nDatabaseMail\nLinkedServers\nLogins\nLoginPermissions\nSystemTriggers\nDatabaseOwner\nAgentCategory\nAgentOperator\nAgentAlert\nAgentProxy\nAgentSchedule\nAgentJob\n\nNote that any of these can be excluded. For specific object exclusions (such as a single job), using the underlying Copy-Dba* command will be required.\n\nThis command does not filter by which logins are in use by the ag databases or which linked servers are used. All objects that are not excluded will be copied like hulk smash.",
        "Tags":  "HA",
        "Synopsis":  "Syncs depdendent objects such as jobs, logins and custom errors for availability groups",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Sync-DbaAvailabilityGroup",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Sync-DbaAvailabilityGroup",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSync-DbaAvailabilityGroup -Primary sql2016a -AvailabilityGroup db3\nSyncs the following on all replicas found in the db3 AG:\r\nSpConfigure, CustomErrors, Credentials, DatabaseMail, LinkedServers\r\nLogins, LoginPermissions, SystemTriggers, DatabaseOwner, AgentCategory,\r\nAgentOperator, AgentAlert, AgentProxy, AgentScheduleAgentJob\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2016a | Sync-DbaAvailabilityGroup -ExcludeType LoginPermissions, LinkedServers -ExcludeLogin login1, login2 -Job job1, job2\nSyncs the following on all replicas found in the db3 AG:\r\nSpConfigure, CustomErrors, Credentials, DatabaseMail, Logins,\r\nSystemTriggers, DatabaseOwner, AgentCategory, AgentOperator\r\nAgentAlert, AgentProxy, AgentScheduleAgentJob.\nCopies all logins except for login1 and login2 and only syncs job1 and job2\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2016a | Sync-DbaAvailabilityGroup -WhatIf\nShows what would happen if the command were to run but doesn\u0027t actually perform the action.",
        "Params":  [
                       [
                           "Primary",
                           "The primary SQL Server instance. Server version must be SQL Server version 2012 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "PrimarySqlCredential",
                           "Login to the primary instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Secondary",
                           "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SecondarySqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "AvailabilityGroup",
                           "The name of the Availability Group.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Exclude",
                           "Exclude one or more objects to export\nSpConfigure\r\nCustomErrors\r\nCredentials\r\nDatabaseMail\r\nLinkedServers\r\nLogins\r\nLoginPermissions\r\nSystemTriggers\r\nDatabaseOwner\r\nAgentCategory\r\nAgentOperator\r\nAgentAlert\r\nAgentProxy\r\nAgentSchedule\r\nAgentJob",
                           "ExcludeType",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Login",
                           "Specific logins to sync. If unspecified, all logins will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeLogin",
                           "Specific logins to exclude when performing the sync. If unspecified, all logins will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Job",
                           "Specific jobs to sync. If unspecified, all logins will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeJob",
                           "Specific jobs to exclude when performing the sync. If unspecified, all logins will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaAvailabilityGroup.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Force",
                           "If this switch is enabled, the objects will dropped and recreated on Destination.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Sync-DbaAvailabilityGroup [[-Primary] \u003cDbaInstanceParameter\u003e] [[-PrimarySqlCredential] \u003cPSCredential\u003e] [[-Secondary] \u003cDbaInstanceParameter[]\u003e] [[-SecondarySqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString\u003e] [[-Exclude] \u003cString[]\u003e] [[-Login] \u003cString[]\u003e] [[-ExcludeLogin] \u003cString[]\u003e] [[-Job] \u003cString[]\u003e] [[-ExcludeJob] \u003cString[]\u003e] [[-InputObject] \u003cAvailabilityGroup[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Sync-DbaLoginPermission",
        "Description":  "Syncs only SQL Server login permissions, roles, etc. Does not add or drop logins. If a matching login does not exist on the destination, the login will be skipped. Credential removal is not currently supported for this operation.",
        "Tags":  [
                     "Migration",
                     "Login"
                 ],
        "Synopsis":  "Copies SQL login permissions from one server to another.",
        "Alias":  "Sync-DbaSqlLoginPermission,Sync-SqlLoginPermissions",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Sync-DbaLoginPermission",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Sync-DbaLoginPermission",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSync-DbaLoginPermission -Source sqlserver2014a -Destination sqlcluster\nSyncs only SQL Server login permissions, roles, etc. Does not add or drop logins or users. To copy logins and their permissions, use Copy-SqlLogin.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSync-DbaLoginPermission -Source sqlserver2014a -Destination sqlcluster -Exclude realcajun -SourceSqlCredential $scred -DestinationSqlCredential $dcred\nCopies all login permissions except for realcajun using SQL Authentication to connect to each server. If a login already exists on the destination, the permissions will not be migrated.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSync-DbaLoginPermission -Source sqlserver2014a -Destination sqlcluster -Login realcajun, netnerds\nCopies permissions ONLY for logins netnerds and realcajun.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Login",
                           "The login(s) to process. Options for this list are auto-populated from the server. If unspecified, all logins will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeLogin",
                           "The login(s) to exclude. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Sync-DbaLoginPermission [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Login] \u003cString[]\u003e] [[-ExcludeLogin] \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaBackupInformation",
        "Description":  "Input is normally from a backup history object generated from `Format-DbaBackupInformation`. This is then parse to check that it\u0027s valid for restore. Tests performed include:\n  - Checking unbroken LSN chain\n  - If the target database exists and WithReplace has been provided\n  - If any files already exist, but owned by other databases\n  - Creates any new folders required\n  - That the backup files exists at the location specified, and can be seen by the Sql Instance\n  - If no errors are found then the objects for that database will me marked as Verified",
        "Tags":  [
                     "Backup",
                     "Restore",
                     "DisasterRecovery"
                 ],
        "Synopsis":  "Tests a dbatools backup history object is correct for restoring",
        "Alias":  "",
        "Author":  "Stuart Moore (@napalmgram), stuart-moore.com",
        "CommandName":  "Test-DbaBackupInformation",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaBackupInformation",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$BackupHistory | Test-DbaBackupInformation -SqlInstance MyInstance\nPS C:\\\u003e $PassedDbs = $BackupHistory | Where-Object {$_.IsVerified -eq $True}\r\nPS C:\\\u003e $FailedDbs = $BackupHistory | Where-Object {$_.IsVerified -ne $True}\nPass in a BackupHistory object to be tested against MyInstance.\r\nThose records that pass are marked as verified. We can then use the IsVerified property to divide the failures and successes",
        "Params":  [
                       [
                           "BackupHistory",
                           "dbatools BackupHistory object. Normally this will have been process with `Select-` and then `Format-DbaBackupInformation`",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlInstance",
                           "The Sql Server instance that wil be performing the restore",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "A Sql Credential to connect to $SqlInstance",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "WithReplace",
                           "By default we won\u0027t overwrite an existing database, this switch tells us you want to",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Continue",
                           "Switch to indicate a continuing restore",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "VerifyOnly",
                           "This switch indicates that you only wish to verify a restore, so runs a smaller number of tests as you won\u0027t be writing anything to the restore server",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "OutputScriptOnly",
                           "Switch to disable path creation. Will write a warning that a path does not exist",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the cmdlet runs. The cmdlet is not run.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before running the cmdlet.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Test-DbaBackupInformation [-BackupHistory] \u003cObject[]\u003e [[-SqlInstance] \u003cDbaInstanceParameter\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-WithReplace] [-Continue] [-VerifyOnly] [-OutputScriptOnly] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaBuild",
        "Description":  "Returns info about the specific build of a SQL instance, including the SP, the CU and the reference KB, End Of Support, wherever possible. It adds a Compliance property as true/false, and adds details about the \"targeted compliance\".",
        "Tags":  [
                     "SqlBuild",
                     "Version"
                 ],
        "Synopsis":  "Returns SQL Server Build \"compliance\" level on a build.",
        "Alias":  "Test-DbaSqlBuild",
        "Author":  "Simone Bizzotto (@niphold) | Friedrich Weinmann (@FredWeinmann)",
        "CommandName":  "Test-DbaBuild",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaBuild",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaBuild -Build \"12.0.5540\" -MinimumBuild \"12.0.5557\"\nReturns information about a build identified by \"12.0.5540\" (which is SQL 2014 with SP2 and CU4), which is not compliant as the minimum required\r\nbuild is \"12.0.5557\" (which is SQL 2014 with SP2 and CU8).\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaBuild -Build \"12.0.5540\" -MaxBehind \"1SP\"\nReturns information about a build identified by \"12.0.5540\", making sure it is AT MOST 1 Service Pack \"behind\". For that version,\r\nthat identifies an SP2, means accepting as the lowest compliance version as \"12.0.4110\", that identifies 2014 with SP1.\nOutput column CUTarget is not relevant (empty). SPTarget and BuildTarget are filled in the result.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaBuild -Build \"12.0.5540\" -MaxBehind \"1SP 1CU\"\nReturns information about a build identified by \"12.0.5540\", making sure it is AT MOST 1 Service Pack \"behind\", plus 1 CU \"behind\". For that version,\r\nthat identifies an SP2 and CU, rolling back 1 SP brings you to \"12.0.4110\", but given the latest CU for SP1 is CU13, the target \"compliant\" build\r\nwill be \"12.0.4511\", which is 2014 with SP1 and CU12.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eTest-DbaBuild -Build \"12.0.5540\" -MaxBehind \"0CU\"\nReturns information about a build identified by \"12.0.5540\", making sure it is the latest CU release.\nOutput columns CUTarget, SPTarget and BuildTarget are relevant. If the latest build is a service pack (not a CU), CUTarget will be empty.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eTest-DbaBuild -Build \"12.0.5540\" -Latest\nReturns information about a build identified by \"12.0.5540\", making sure it is the latest build available.\nOutput columns CUTarget and SPTarget are not relevant (empty), only the BuildTarget is.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eTest-DbaBuild -Build \"12.00.4502\" -MinimumBuild \"12.0.4511\" -Update\nSame as before, but tries to fetch the most up to date index online. When the online version is newer, the local one gets overwritten.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eTest-DbaBuild -Build \"12.0.4502\",\"10.50.4260\" -MinimumBuild \"12.0.4511\"\nReturns information builds identified by these versions strings.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sqlserver2014a | Test-DbaBuild -MinimumBuild \"12.0.4511\"\nIntegrate with other cmdlets to have builds checked for all your registered servers on sqlserver2014a.",
        "Params":  [
                       [
                           "Build",
                           "Instead of connecting to a real instance, pass a string identifying the build to get the info back.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "MinimumBuild",
                           "This is the build version to test \"compliance\" against. Anything below this is flagged as not compliant.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "MaxBehind",
                           "Instead of using a specific MinimumBuild here you can pass \"how many service packs and cu back\" is the targeted compliance level. You can use xxSP or xxCU or both, where xx is a number. See the \r\nExamples for more information.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Latest",
                           "Shortcut for specifying the very most up-to-date build available.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "SqlInstance",
                           "Target any number of instances, in order to return their compliance state.",
                           "ServerInstance,SqlServer",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "When connecting to an instance, use the credentials specified.",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Update",
                           "Looks online for the most up to date reference, replacing the local one.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Quiet",
                           "Makes the function just return $true/$false. It\u0027s useful if you use Test-DbaBuild in your own scripts.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaBuild [[-Build] \u003cVersion[]\u003e] [[-MinimumBuild] \u003cVersion\u003e] [[-MaxBehind] \u003cString\u003e] [-Latest] [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-Update] [-Quiet] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaCmConnection",
        "Description":  "Tests over which paths a computer can be managed.\n\nThis function tries out the connectivity for:\n- Cim over WinRM\n- Cim over DCOM\n- Wmi\n- PowerShellRemoting\nResults will be written to the connectivity cache and will cause Get-DbaCmObject and Invoke-DbaCmMethod to connect using the way most likely to succeed. This way, it is likely the other commands will take less time to execute. These others too cache their results, in order to dynamically update connection statistics.\n\nThis function ignores global configuration settings limiting which protocols may be used.",
        "Tags":  [
                     "ComputerManagement",
                     "CIM"
                 ],
        "Synopsis":  "Tests over which paths a computer can be managed.",
        "Alias":  "",
        "Author":  "Friedrich Weinmann (@FredWeinmann)",
        "CommandName":  "Test-DbaCmConnection",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Test-DbaCmConnection",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaCmConnection -ComputerName sql2014\nPerforms a full-spectrum connection test against the computer sql2014. The results will be reported and registered. Future calls from Get-DbaCmObject will recognize the results and optimize the query.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaCmConnection -ComputerName sql2014 -Credential $null -Type CimDCOM, CimRM\nThis test will run a connectivity test of CIM over DCOM and CIM over WinRM against the computer sql2014 using Windows Authentication.\nThe results will be reported and registered. Future calls from Get-DbaCmObject will recognize the results and optimize the query.",
        "Params":  [
                       [
                           "ComputerName",
                           "The computer to test against.",
                           "",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "The credentials to use when running the test. Bad credentials are automatically cached as non-working. This behavior can be disabled by the \u0027Cache.Management.Disable.BadCredentialList\u0027 configuration.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Type",
                           "The connection protocol types to test.\r\nBy default, all types are tested.\nNote that this function will ignore global configurations limiting the types of connections available and test all connections specified here instead.\nAvailable connection protocol types: \"CimRM\", \"CimDCOM\", \"Wmi\", \"PowerShellRemoting\"",
                           "",
                           false,
                           "false",
                           "@(\"CimRM\", \"CimDCOM\", \"Wmi\", \"PowerShellRemoting\")"
                       ],
                       [
                           "Force",
                           "If this switch is enabled, the Alert will be dropped and recreated on Destination.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaCmConnection [[-ComputerName] \u003cDbaCmConnectionParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Type] {None | CimRM | CimDCOM | Wmi | PowerShellRemoting}] [-Force] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaConnection",
        "Description":  "Tests the ability to connect to an SQL Server instance outputting information about the server and instance.",
        "Tags":  [
                     "CIM",
                     "Test",
                     "Connection"
                 ],
        "Synopsis":  "Tests the connection to a single instance.",
        "Alias":  "Test-SqlConnection",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Test-DbaConnection",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Test-DbaConnection",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaConnection SQL2016\n```\r\nComputerName         : SQL2016\r\nInstanceName         : MSSQLSERVER\r\nSqlInstance          : sql2016\r\nSqlVersion           : 13.0.4001\r\nConnectingAsUser     : BASE\\ctrlb\r\nConnectSuccess       : True\r\nAuthType             : Windows Authentication\r\nAuthScheme           : KERBEROS\r\nTcpPort              : 1433\r\nIPAddress            : 10.2.1.5\r\nNetBiosName          : sql2016.base.local\r\nIsPingable           : True\r\nPSRemotingAccessible : True\r\nDomainName           : base.local\r\nLocalWindows         : 10.0.15063.0\r\nLocalPowerShell      : 5.1.15063.502\r\nLocalCLR             : 4.0.30319.42000\r\nLocalSMOVersion      : 13.0.0.0\r\nLocalDomainUser      : True\r\nLocalRunAsAdmin      : False\r\n```\nTest connection to SQL2016 and outputs information collected",
        "Params":  [
                       [
                           "SqlInstance",
                           "The SQL Server Instance to test connection",
                           "ServerInstance,SqlServer",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Credential",
                           "Credential object used to connect to the Computer as a different user",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaConnection [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaConnectionAuthScheme",
        "Description":  "By default, this command will return the ConnectName, ServerName, Transport and AuthScheme of the current connection.\n\nConnectName is the name you used to connect. ServerName is the name that the SQL Server reports as its @@SERVERNAME which is used to register its SPN. If you were expecting a Kerberos connection and got NTLM instead, ensure ConnectName and ServerName match.\n\nIf -Kerberos or -Ntlm is specified, the $true/$false results of the test will be returned. Returns $true or $false by default for one server. Returns Server name and Results for more than one server.",
        "Tags":  [
                     "SPN",
                     "Kerberos"
                 ],
        "Synopsis":  "Returns the transport protocol and authentication scheme of the connection. This is useful to determine if your connection is using Kerberos.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Test-DbaConnectionAuthScheme",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaConnectionAuthScheme",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaConnectionAuthScheme -SqlInstance sqlserver2014a, sql2016\nReturns ConnectName, ServerName, Transport and AuthScheme for sqlserver2014a and sql2016.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaConnectionAuthScheme -SqlInstance sqlserver2014a -Kerberos\nReturns $true or $false depending on if the connection is Kerberos or not.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaConnectionAuthScheme -SqlInstance sqlserver2014a | Select-Object *\nReturns the results of \"SELECT * from sys.dm_exec_connections WHERE session_id = @@SPID\"",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Server(s) must be SQL Server 2005 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential,Cred",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Kerberos",
                           "If this switch is enabled, checks will be made for Kerberos authentication.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Ntlm",
                           "If this switch is enabled, checks will be made for NTLM authentication.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Detailed",
                           "Output all properties, will be deprecated in 1.0.0 release.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaConnectionAuthScheme [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Kerberos] [-Ntlm] [-Detailed] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaDbCollation",
        "Description":  "Compares Database Collations to Server Collation",
        "Tags":  [
                     "Database",
                     "Collation"
                 ],
        "Synopsis":  "Compares Database Collations to Server Collation",
        "Alias":  "Test-DbaDatabaseCollation",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Test-DbaDbCollation",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaDbCollation",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDbCollation -SqlInstance sqlserver2014a\nReturns server name, database name and true/false if the collations match for all databases on sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaDbCollation -SqlInstance sqlserver2014a -Database db1, db2\nReturns information for the db1 and db2 databases on sqlserver2014a.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaDbCollation -SqlInstance sqlserver2014a, sql2016 -Exclude db1\nReturns information for database and server collations for all databases except db1 on sqlserver2014a and sql2016.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sql2016 | Test-DbaDbCollation\nReturns db/server collation information for every database on every server listed in the Central Management Server on sql2016.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Detailed",
                           "Output all properties, will be deprecated in 1.0.0 release.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaDbCollation [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-Detailed] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaDbCompatibility",
        "Description":  "Compares Database Compatibility level to Server Compatibility",
        "Tags":  [
                     "Database",
                     "Compatibility"
                 ],
        "Synopsis":  "Compares Database Compatibility level to Server Compatibility",
        "Alias":  "Test-DbaDatabaseCompatibility",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Test-DbaDbCompatibility",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaDbCompatibility",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDbCompatibility -SqlInstance sqlserver2014a\nReturns server name, database name and true/false if the compatibility level match for all databases on sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaDbCompatibility -SqlInstance sqlserver2014a -Database db1, db2\nReturns detailed information for database and server compatibility level for the db1 and db2 databases on sqlserver2014a.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaDbCompatibility -SqlInstance sqlserver2014a, sql2016 -Exclude db1\nReturns detailed information for database and server compatibility level for all databases except db1 on sqlserver2014a and sql2016.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sql2014 | Test-DbaDbCompatibility\nReturns db/server compatibility information for every database on every server listed in the Central Management Server on sql2016.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Credential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Detailed",
                           "Will be deprecated in 1.0.0 release.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaDbCompatibility [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-Detailed] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaDbCompression",
        "Description":  "This function returns the results of a full table/index compression analysis and the estimated, best option to date for either NONE, Page, or Row Compression.\n\nRemember Uptime is critical, the longer uptime, the more accurate the analysis is, and it would be best if you utilized Get-DbaUptime first, before running this command.\n\nTest-DbaDbCompression script derived from GitHub and the tigertoolbox\n(https://github.com/Microsoft/tigertoolbox/tree/master/Evaluate-Compression-Gains)\nIn the output, you will find the following information:\n- Column Percent_Update shows the percentage of update operations on a specific table, index, or partition, relative to total operations on that object. The lower the percentage of Updates (that is, the table, index, or partition is infrequently updated), the better candidate it is for page compression.\n- Column Percent_Scan shows the percentage of scan operations on a table, index, or partition, relative to total operations on that object. The higher the value of Scan (that is, the table, index, or partition is mostly scanned), the better candidate it is for page compression.\n- Column Compression_Type_Recommendation can have four possible outputs indicating where there is most gain, if any: \u0027PAGE\u0027, \u0027ROW\u0027, \u0027NO_GAIN\u0027 or \u0027?\u0027. When the output is \u0027?\u0027 this approach could not give a recommendation, so as a rule of thumb I would lean to ROW if the object suffers mainly UPDATES, or PAGE if mainly INSERTS, but this is where knowing your workload is essential. When the output is \u0027NO_GAIN\u0027 well, that means that according to sp_estimate_data_compression_savings no space gains will be attained when compressing, as in the above output example, where compressing would grow the affected object.\n\nThis script will execute on the context of the current database.\nAlso be aware that this may take a while to execute on large objects, because if the IS locks taken by the\nsp_estimate_data_compression_savings cannot be honored, the SP will be blocked.\nIt only considers Row or Page Compression (not column compression)\nIt only evaluates User Tables",
        "Tags":  [
                     "Compression",
                     "Table",
                     "Database"
                 ],
        "Synopsis":  "Returns tables and indexes with preferred compression setting.",
        "Alias":  "",
        "Author":  "Jason Squires (@js_0505), [email protected]",
        "CommandName":  "Test-DbaDbCompression",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaDbCompression",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDbCompression -SqlInstance localhost\nReturns results of all potential compression options for all databases for the default instance on the local host. Returns a recommendation of either Page, Row or NO_GAIN\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaDbCompression -SqlInstance ServerA\nReturns results of all potential compression options for all databases on the instance ServerA\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaDbCompression -SqlInstance ServerA -Database DBName | Out-GridView\nReturns results of all potential compression options for a single database DBName with the recommendation of either Page or Row or NO_GAIN in a nicely formatted GridView\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Test-DbaDbCompression -SqlInstance ServerA -ExcludeDatabase MyDatabase -SqlCredential $cred\nReturns results of all potential compression options for all databases except MyDatabase on instance ServerA using SQL credentials to authentication to ServerA.\r\nReturns the recommendation of either Page, Row or NO_GAIN\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eTest-DbaDbCompression -SqlInstance ServerA -Schema Test -Table MyTable\nReturns results of all potential compression options for the Table Test.MyTable in instance ServerA on ServerA and ServerB.\r\nReturns the recommendation of either Page, Row or NO_GAIN.\r\nReturns a result for each partition of any Heap, Clustered or NonClustered index.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eTest-DbaDbCompression -SqlInstance ServerA, ServerB -ResultSize 10\nReturns results of all potential compression options for all databases on ServerA and ServerB.\r\nReturns the recommendation of either Page, Row or NO_GAIN.\r\nReturns results for the top 10 partitions by TotalPages used per database.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eServerA | Test-DbaDbCompression -Schema Test -ResultSize 10 -Rank UsedPages -FilterBy Table\nReturns results of all potential compression options for all databases on ServerA containing a schema Test\r\nReturns results for the top 10 Tables by Used Pages per database.\r\nResults are split by Table, Index and Partition so more than 10 results may be returned.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e$servers = \u0027Server1\u0027,\u0027Server2\u0027\nPS C:\\\u003e $servers | Test-DbaDbCompression -Database DBName | Out-GridView\nReturns results of all potential compression options for a single database DBName on Server1 or Server2\r\nReturns the recommendation of either Page, Row or NO_GAIN in a nicely formatted GridView\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Test-DbaDbCompression -SqlInstance ServerA -Database MyDB -SqlCredential $cred -Schema Test -Table Test1, Test2\nReturns results of all potential compression options for objects in Database MyDb on instance ServerA using SQL credentials to authentication to ServerA.\r\nReturns the recommendation of either Page, Row or NO_GAIN for tables with SchemA Test and name in Test1 or Test2\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003e$servers = \u0027Server1\u0027,\u0027Server2\u0027\nPS C:\\\u003e foreach ($svr in $servers) {\r\n\u003e\u003e Test-DbaDbCompression -SqlInstance $svr | Export-Csv -Path C:\\temp\\CompressionAnalysisPAC.csv -Append\r\n\u003e\u003e }\nThis produces a full analysis of all your servers listed and is pushed to a csv for you to analyze.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Schema",
                           "Filter to only get specific schemas If unspecified, all schemas will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Table",
                           "Filter to only get specific tables If unspecified, all User tables will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ResultSize",
                           "Allows you to limit the number of results returned, as some systems can have very large number of tables.  Default value is no restriction.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "Rank",
                           "Allows you to specify the field used for ranking when determining the ResultSize\r\nCan be either TotalPages, UsedPages or TotalRows with default of TotalPages. Only applies when ResultSize is used.",
                           "",
                           false,
                           "false",
                           "TotalPages"
                       ],
                       [
                           "FilterBy",
                           "Allows you to specify level of filtering when determining the ResultSize\r\nCan be at either Table, Index or Partition level with default of Partition. Only applies when ResultSize is used.",
                           "",
                           false,
                           "false",
                           "Partition"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaDbCompression [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-Schema] \u003cString[]\u003e] [[-Table] \u003cString[]\u003e] [[-ResultSize] \u003cInt32\u003e] [[-Rank] \u003cString\u003e] [[-FilterBy] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaDbLogShipStatus",
        "Description":  "Most of the time your log shipping \"just works\".\nChecking your log shipping status can be done really easy with this function.\n\nMake sure you\u0027re connecting to the monitoring instance of your log shipping infrastructure.\n\nThe function will return the status for a database. This can be one or more messages in a comma separated list.\nIf everything is OK with the database than you should only see the message \"All OK\".",
        "Tags":  "LogShipping",
        "Synopsis":  "Test-DbaDbLogShipStatus returns the status of your log shipping databases",
        "Alias":  "Test-DbaLogShippingStatus",
        "Author":  "Sander Stad (@sqlstad), sqlstad.nl",
        "CommandName":  "Test-DbaDbLogShipStatus",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaDbLogShipStatus",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDbLogShipStatus -SqlInstance sql1\nRetrieves the log ship information from sql1 and displays all the information present including the status.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaDbLogShipStatus -SqlInstance sql1 -Database AdventureWorks2014\nRetrieves the log ship information for just the database AdventureWorks.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaDbLogShipStatus -SqlInstance sql1 -Primary\nRetrieves the log ship information and only returns the information for the databases on the primary instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eTest-DbaDbLogShipStatus -SqlInstance sql1 -Secondary\nRetrieves the log ship information and only returns the information for the databases on the secondary instance.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eTest-DbaDbLogShipStatus -SqlInstance sql1 -Simple\nRetrieves the log ship information and only returns the columns SQL Instance, Database, Instance Type and Status",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Allows you to filter the results to only return the databases you\u0027re interested in. This can be one or more values separated by commas.\r\nThis is not a wildcard and should be the exact database name. See examples for more info.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Allows you to filter the results to only return the databases you\u0027re not interested in. This can be one or more values separated by commas.\r\nThis is not a wildcard and should be the exact database name.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Simple",
                           "By default all the information will be returned.\r\nIf this parameter is used you get an overview with the SQL Instance, Database, Instance Type and the status",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Primary",
                           "Allows to filter the results to only return values that apply to the primary instance.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Secondary",
                           "Allows to filter the results to only return values that apply to the secondary instance.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaDbLogShipStatus [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [-Simple] [-Primary] [-Secondary] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaDbOwner",
        "Description":  "This function will check all databases on an instance against a SQL login to validate if that\nlogin owns those databases or not. By default, the function will check against \u0027sa\u0027 for\nownership, but the user can pass a specific login if they use something else.\n\nBest Practice reference: http://weblogs.sqlteam.com/dang/archive/2008/01/13/Database-Owner-Troubles.aspx",
        "Tags":  [
                     "Database",
                     "Owner",
                     "DbOwner"
                 ],
        "Synopsis":  "Checks database owners against a login to validate which databases do not match that owner.",
        "Alias":  "Test-DbaDatabaseOwner",
        "Author":  "Michael Fal (@Mike_Fal), http://mikefal.net",
        "CommandName":  "Test-DbaDbOwner",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaDbOwner",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDbOwner -SqlInstance localhost\nReturns all databases where the owner does not match \u0027sa\u0027.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaDbOwner -SqlInstance localhost -TargetLogin \u0027DOMAIN\\account\u0027\nReturns all databases where the owner does not match \u0027DOMAIN\\account\u0027.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance localhost -OnlyAccessible | Test-DbaDbOwner\nGets only accessible databases and checks where the owner does not match \u0027sa\u0027.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "TargetLogin",
                           "Specifies the login that you wish check for ownership. This defaults to \u0027sa\u0027 or the sysadmin name if sa was renamed. This must be a valid security principal which exists on the target server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Detailed",
                           "Will be deprecated in 1.0.0 release.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "InputObject",
                           "Enables piped input from Get-DbaDatabase.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaDbOwner [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-TargetLogin \u003cString\u003e] [-Detailed] [-InputObject \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaDbRecoveryModel",
        "Description":  "When you switch a database into FULL recovery model, it will behave like a SIMPLE recovery model until a full backup is taken in order to begin a log backup chain.\n\nHowever, you may also desire to validate if a database is SIMPLE or BULK LOGGED on an instance.\n\nInspired by Paul Randal\u0027s post (http://www.sqlskills.com/blogs/paul/new-script-is-that-database-really-in-the-full-recovery-mode/)",
        "Tags":  [
                     "DisasterRecovery",
                     "Backup"
                 ],
        "Synopsis":  "Find if database is really a specific recovery model or not.",
        "Alias":  "Test-DbaFullRecoveryModel,Test-DbaRecoveryModel",
        "Author":  "Claudio Silva (@ClaudioESSilva)",
        "CommandName":  "Test-DbaDbRecoveryModel",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaDbRecoveryModel",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDbRecoveryModel -SqlInstance sql2005\nShows all databases where the configured recovery model is FULL and indicates whether or not they are really in FULL recovery model.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaDbRecoveryModel -SqlInstance . | Where-Object {$_.ActualRecoveryModel -ne \"FULL\"}\nOnly shows the databases that are functionally in \u0027simple\u0027 mode.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaDbRecoveryModel -SqlInstance sql2008 -RecoveryModel Bulk_Logged | Sort-Object Server  -Descending\nShows all databases where the configured recovery model is BULK_LOGGED and sort them by server name descending\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eTest-DbaDbRecoveryModel -SqlInstance localhost | Select-Object -Property *\nShows all of the properties for the databases that have Full Recovery Model",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "RecoveryModel",
                           "Specifies the type of recovery model you wish to test. By default it will test for FULL Recovery Model.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Detailed",
                           "Output all properties, will be deprecated in 1.0.0 release.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaDbRecoveryModel [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-RecoveryModel] \u003cObject\u003e] [-Detailed] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaDbVirtualLogFile",
        "Description":  "Having a transaction log file with too many virtual log files (VLFs) can hurt database performance.\n\nToo many VLFs can cause transaction log backups to slow down and can also slow down database recovery and, in extreme cases, even affect insert/update/delete performance.\n\nReferences:\nhttp://www.sqlskills.com/blogs/kimberly/transaction-log-vlfs-too-many-or-too-few/\nhttp://blogs.msdn.com/b/saponsqlserver/archive/2012/02/22/too-many-virtual-log-files-vlfs-can-cause-slow-database-recovery.aspx\n\nIf you\u0027ve got a high number of VLFs, you can use Expand-SqlTLogResponsibly to reduce the number.",
        "Tags":  [
                     "VLF",
                     "Database"
                 ],
        "Synopsis":  "Returns calculations on the database virtual log files for database on a SQL instance.",
        "Alias":  "Test-DbaVirtualLogFile",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Test-DbaDbVirtualLogFile",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaDbVirtualLogFile",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDbVirtualLogFile -SqlInstance sqlcluster\nReturns all user database virtual log file counts for the sqlcluster instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaDbVirtualLogFile -SqlInstance sqlserver | Where-Object {$_.Count -ge 50}\nReturns user databases that have 50 or more VLFs.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e@(\u0027sqlserver\u0027,\u0027sqlcluster\u0027) | Test-DbaDbVirtualLogFile\nReturns all VLF information for the sqlserver and sqlcluster SQL Server instances. Processes data via the pipeline.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eTest-DbaDbVirtualLogFile -SqlInstance sqlcluster -Database db1, db2\nReturns VLF counts for the db1 and db2 databases on sqlcluster.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "IncludeSystemDBs",
                           "If this switch is enabled, system database information will be displayed.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaDbVirtualLogFile [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-IncludeSystemDBs] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaDeprecatedFeature",
        "Description":  "Displays information relating to deprecated features for SQL Server 2005 and above.",
        "Tags":  "Deprecated",
        "Synopsis":  "Displays information relating to deprecated features for SQL Server 2005 and above.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Test-DbaDeprecatedFeature",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaDeprecatedFeature",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2008 -Database testdb, db2 | Test-DbaDeprecatedFeature\nCheck deprecated features on server sql2008 for only the testdb and db2 databases\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2008 -Database testdb, db2 | Test-DbaDeprecatedFeature | Select *\nSee the object definition in the output as well\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaDeprecatedFeature -SqlInstance sql2008, sqlserver2012\nCheck deprecated features for all databases on the servers sql2008 and sqlserver2012.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eTest-DbaDeprecatedFeature -SqlInstance sql2008 -Database TestDB\nCheck deprecated features on server sql2008 for only the TestDB database",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance",
                           "ServerInstance,SqlServer,SqlServers",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternate Windows or SQL Login Authentication. Accepts credential objects (Get-Credential).",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "A collection of databases (such as returned by Get-DbaDatabase), to be tested.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaDeprecatedFeature [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaDiskAlignment",
        "Description":  "Returns $true or $false by default for one server. Returns Server name and IsBestPractice for more than one server.\n\nPlease refer to your storage vendor best practices before following any advice below.\n\nBy default issues with disk alignment should be resolved by a new installation of Windows Server 2008, Windows Vista, or later operating systems, but verifying disk alignment continues to be recommended as a best practice.\nWhile some versions of Windows use different starting alignments, if you are starting anew 1MB is generally the best practice offset for current operating systems (because it ensures that the partition offset % common stripe unit sizes == 0 )\n\nCaveats:\n* Dynamic drives (or those provisioned via third party software) may or may not have accurate results when polled by any of the built in tools, see your vendor for details.\n* Windows does not have a reliable way to determine stripe unit Sizes. These values are obtained from vendor disk management software or from your SAN administrator.\n* System drives in versions previous to Windows Server 2008 cannot be aligned, but it is generally not recommended to place SQL Server databases on system drives.",
        "Tags":  "Storage",
        "Synopsis":  "Verifies that your non-dynamic disks are aligned according to physical constraints.",
        "Alias":  "",
        "Author":  "Constantine Kokkinos (@mobileck), https://constantinekokkinos.com",
        "CommandName":  "Test-DbaDiskAlignment",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Test-DbaDiskAlignment",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDiskAlignment -ComputerName sqlserver2014a\nTests the disk alignment of a single server named sqlserver2014a\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaDiskAlignment -ComputerName sqlserver2014a, sqlserver2014b, sqlserver2014c\nTests the disk alignment of multiple servers",
        "Params":  [
                       [
                           "ComputerName",
                           "The target computer or computers.",
                           "ServerInstance,SqlServer,SqlInstance",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Credential",
                           "Specifies an alternate Windows account to use when enumerating drives on the server. May require Administrator privileges. To use:\n$cred = Get-Credential, then pass $cred object to the -Credential parameter.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "NoSqlCheck",
                           "If this switch is enabled, the disk(s) will not be checked for SQL Server data or log files.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaDiskAlignment [-ComputerName] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-NoSqlCheck] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaDiskAllocation",
        "Description":  "Checks all disks on a computer for disk allocation units that match best practice recommendations. If one server is checked, only $true or $false is returned. If multiple servers are checked, each server\u0027s name and an IsBestPractice field are returned.\n\nReferences:\nhttps://technet.microsoft.com/en-us/library/dd758814(v=sql.100).aspx - \"The performance question here is usually not one of correlation per the formula, but whether the cluster size has been explicitly defined at 64 KB, which is a best practice for SQL Server.\"",
        "Tags":  [
                     "CIM",
                     "Storage"
                 ],
        "Synopsis":  "Checks all disks on a computer to see if they are formatted with allocation units of 64KB.",
        "Alias":  "Test-SqlDiskAllocation",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Test-DbaDiskAllocation",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Test-DbaDiskAllocation",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDiskAllocation -ComputerName sqlserver2014a\nScans all disks on server sqlserver2014a for best practice allocation unit size.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaDiskAllocation -ComputerName sqlserver2014 | Select-Output *\nScans all disks on server sqlserver2014a for allocation unit size and returns detailed results for each.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaDiskAllocation -ComputerName sqlserver2014a -NoSqlCheck\nScans all disks not hosting SQL Server data or log files on server sqlserver2014a for best practice allocation unit size.",
        "Params":  [
                       [
                           "ComputerName",
                           "The server(s) to check disk configuration on.",
                           "ServerInstance,SqlServer,SqlInstance",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "NoSqlCheck",
                           "If this switch is enabled, the disk(s) will not be checked for SQL Server data or log files.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Credential",
                           "Specifies an alternate Windows account to use when enumerating drives on the server. May require Administrator privileges. To use:\n$cred = Get-Credential, then pass $cred object to the -Credential parameter.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Detailed",
                           "Output all properties, will be deprecated in 1.0.0 release.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Test-DbaDiskAllocation [-ComputerName] \u003cObject[]\u003e [-NoSqlCheck] [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [-Detailed] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaDiskSpeed",
        "Description":  "Tests how disks are performing.\n\nThis command uses a query from Rich Benner which was adapted from David Pless\u0027s article:\nhttps://blogs.msdn.microsoft.com/dpless/2010/12/01/leveraging-sys-dm_io_virtual_file_stats/\nhttps://github.com/RichBenner/PersonalCode/blob/master/Disk_Speed_Check.sql",
        "Tags":  "Performance",
        "Synopsis":  "Tests how disks are performing.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Test-DbaDiskSpeed",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaDiskSpeed",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDiskSpeed -SqlInstance sql2008, sqlserver2012\nTests how disks are performing on sql2008 and sqlserver2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaDiskSpeed -SqlInstance sql2008 -Database tempdb\nTests how disks storing tempdb files on sql2008 are performing.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to the SQL Server using alternative credentials.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaDiskSpeed [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaEndpoint",
        "Description":  "Performs a simple connectivity test for TCP and SSL enabled endpoints. Tests if port is accessible, not if endpoint is working.\n\nNote that if an endpoint does not have a tcp listener port, it will be skipped.",
        "Tags":  "Endpoint",
        "Synopsis":  "Performs a simple connectivity test for TCP and SSL enabled endpoints.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Test-DbaEndpoint",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaEndpoint",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaEndpoint -SqlInstance localhost\nTests all endpoints on the local default SQL Server instance.\nNote that if an endpoint does not have a tcp listener port, it will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaEndpoint -SqlInstance localhost, sql2016 -Endpoint Mirror | Test-DbaEndpoint\nTests all endpoints named Mirroring on sql2016 and localhost.\nNote that if an endpoint does not have a tcp listener port, it will be skipped.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaEndpoint -SqlInstance localhost, sql2016 -Endpoint Mirror\nTests all endpoints named Mirroring on sql2016 and localhost.\nNote that if an endpoint does not have a tcp listener port, it will be skipped.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eTest-DbaEndpoint -SqlInstance localhost -Verbose\nTests all endpoints on the local default SQL Server instance.\nSee all endpoints that were skipped due to not having a tcp listener port.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Endpoint",
                           "Test only specific endpoint or endpoints.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaEndpoint.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaEndpoint [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Endpoint] \u003cString[]\u003e] [[-InputObject] \u003cEndpoint[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaIdentityUsage",
        "Description":  "IDENTITY seeds have max values based off of their data type.  This module will locate identity columns and report the seed usage.",
        "Tags":  [
                     "Identity",
                     "Table",
                     "Column"
                 ],
        "Synopsis":  "Displays information relating to IDENTITY seed usage.  Works on SQL Server 2008 and above.",
        "Alias":  "",
        "Author":  "Brandon Abshire, netnerds.net",
        "CommandName":  "Test-DbaIdentityUsage",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaIdentityUsage",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaIdentityUsage -SqlInstance sql2008, sqlserver2012\nCheck identity seeds for servers sql2008 and sqlserver2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaIdentityUsage -SqlInstance sql2008 -Database TestDB\nCheck identity seeds on server sql2008 for only the TestDB database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaIdentityUsage -SqlInstance sql2008 -Database TestDB -Threshold 20\nCheck identity seeds on server sql2008 for only the TestDB database, limiting results to 20% utilization of seed range or higher",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude - this list is auto-populated from the server",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Threshold",
                           "Allows you to specify a minimum % of the seed range being utilized.  This can be used to ignore seeds that have only utilized a small fraction of the range.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "ExcludeSystem",
                           "Allows you to suppress output on system databases",
                           "ExcludeSystemDb",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaIdentityUsage [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [[-Threshold] \u003cInt32\u003e] [[-ExcludeSystem]] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaLastBackup",
        "Description":  "Restores all or some of the latest backups and performs a DBCC CHECKDB.\n\n1. Gathers information about the last full backups\n2. Restores the backups to the Destination with a new name. If no Destination is specified, the originating SQL Server instance wil be used.\n3. The database is restored as \"dbatools-testrestore-$databaseName\" by default, but you can change dbatools-testrestore to whatever you would like using -Prefix\n4. The internal file names are also renamed to prevent conflicts with original database\n5. A DBCC CHECKDB is then performed\n6. And the test database is finally dropped",
        "Tags":  [
                     "DisasterRecovery",
                     "Backup",
                     "Restore"
                 ],
        "Synopsis":  "Quickly and easily tests the last set of full backups for a server.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Test-DbaLastBackup",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaLastBackup",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaLastBackup -SqlInstance sql2016\nDetermines the last full backup for ALL databases, attempts to restore all databases (with a different name and file structure), then performs a DBCC CHECKDB. Once the test is complete, the test \r\nrestore will be dropped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaLastBackup -SqlInstance sql2016 -Database SharePoint_Config\nDetermines the last full backup for SharePoint_Config, attempts to restore it, then performs a DBCC CHECKDB.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016, sql2017 | Test-DbaLastBackup\nTests every database backup on sql2016 and sql2017\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016, sql2017 -Database SharePoint_Config | Test-DbaLastBackup\nTests the database backup for the SharePoint_Config database on sql2016 and sql2017\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eTest-DbaLastBackup -SqlInstance sql2016 -Database model, master -VerifyOnly\nSkips performing an action restore of the database and simply verifies the backup using VERIFYONLY option of the restore.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eTest-DbaLastBackup -SqlInstance sql2016 -NoCheck -NoDrop\nSkips the DBCC CHECKDB check. This can help speed up the tests but makes it less tested. The test restores will remain on the server.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eTest-DbaLastBackup -SqlInstance sql2016 -DataDirectory E:\\bigdrive -LogDirectory L:\\bigdrive -MaxSize 10240\nRestores data and log files to alternative locations and only restores databases that are smaller than 10 GB.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eTest-DbaLastBackup -SqlInstance sql2014 -Destination sql2016 -CopyFile\nCopies the backup files for sql2014 databases to sql2016 default backup locations and then attempts restore from there.\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eTest-DbaLastBackup -SqlInstance sql2014 -Destination sql2016 -CopyFile -CopyPath \"\\\\BackupShare\\TestRestore\\\"\nCopies the backup files for sql2014 databases to sql2016 default backup locations and then attempts restore from there.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. Unlike many of the other commands, you cannot specify more than one server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database backups to test. If -Database is not provided, all database backups will be tested.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "Exclude specific Database backups to test.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "The destination server to use to test the restore. By default, the Destination will be set to the source server\nIf a different Destination server is specified, you must ensure that the database backups are on a shared location",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DestinationCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "DataDirectory",
                           "Specifies an alternative directory for mdfs, ndfs and so on. The command uses the SQL Server\u0027s default data directory for all restores.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "LogDirectory",
                           "Specifies an alternative directory for ldfs. The command uses the SQL Server\u0027s default log directory for all restores.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Prefix",
                           "The database is restored as \"dbatools-testrestore-$databaseName\" by default. You can change dbatools-testrestore to whatever you would like using this parameter.",
                           "",
                           false,
                           "false",
                           "dbatools-testrestore-"
                       ],
                       [
                           "VerifyOnly",
                           "If this switch is enabled, VERIFYONLY will be performed. An actual restore will not be executed.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NoCheck",
                           "If this switch is enabled, DBCC CHECKDB will be skipped",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NoDrop",
                           "If this switch is enabled, the newly-created test database will not be dropped.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "CopyFile",
                           "If this switch is enabled, the backup file will be copied to the destination default backup location unless CopyPath is specified.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "CopyPath",
                           "Specifies a path relative to the SQL Server to copy backups when CopyFile is specified. If not specified will use destination default backup location. If destination SQL Server is not local, admin \r\nUNC paths will be utilized for the copy.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "MaxSize",
                           "Max size in MB. Databases larger than this value will not be restored.",
                           "MaxMB",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "IncludeCopyOnly",
                           "If this switch is enabled, copy only backups will be counted as a last backup.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "IgnoreLogBackup",
                           "If this switch is enabled, transaction log backups will be ignored. The restore will stop at the latest full or differential backup point.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "AzureCredential",
                           "The name of the SQL Server credential on the destination instance that holds the key to the azure storage account.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaDatabase",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Test-DbaLastBackup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-Destination] \u003cDbaInstanceParameter\u003e] [[-DestinationCredential] \u003cObject\u003e] [[-DataDirectory] \u003cString\u003e] [[-LogDirectory] \u003cString\u003e] [[-Prefix] \u003cString\u003e] [-VerifyOnly] [-NoCheck] [-NoDrop] [-CopyFile] [[-CopyPath] \u003cString\u003e] [[-MaxSize] \u003cInt32\u003e] [-IncludeCopyOnly] [-IgnoreLogBackup] [[-AzureCredential] \u003cString\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaLinkedServerConnection",
        "Description":  "Test each linked server on the instance",
        "Tags":  "LinkedServer",
        "Synopsis":  "Test all linked servers from the sql servers passed",
        "Alias":  "",
        "Author":  "Thomas LaRock ( https://thomaslarock.com )",
        "CommandName":  "Test-DbaLinkedServerConnection",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaLinkedServerConnection",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaLinkedServerConnection -SqlInstance DEV01\nTest all Linked Servers for the SQL Server instance DEV01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaLinkedServerConnection -SqlInstance sql2016 | Out-File C:\\temp\\results.txt\nTest all Linked Servers for the SQL Server instance sql2016 and output results to file\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaLinkedServerConnection -SqlInstance sql2016, sql2014, sql2012\nTest all Linked Servers for the SQL Server instances sql2016, sql2014 and sql2012\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$servers = \"sql2016\",\"sql2014\",\"sql2012\"\nPS C:\\\u003e $servers | Test-DbaLinkedServerConnection -SqlCredential sqladmin\nTest all Linked Servers for the SQL Server instances sql2016, sql2014 and sql2012 using SQL login credentials\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$servers | Get-DbaLinkedServer | Test-DbaLinkedServerConnection\nTest all Linked Servers for the SQL Server instances sql2016, sql2014 and sql2012",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Credential object used to connect to the SQL Server as a different user",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaLinkedServerConnection [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaLoginPassword",
        "Description":  "The purpose of this function is to find SQL Server logins that have no password or the same password as login. You can add your own password to check for or add them to a csv file.\nBy default it will test for empty password and the same password as username.",
        "Tags":  [
                     "Login",
                     "Security"
                 ],
        "Synopsis":  "Test-DbaLoginPassword finds any logins on SQL instance that are SQL Logins and have a password that is either null or same as the login",
        "Alias":  "",
        "Author":  "Peter Samuelsson",
        "CommandName":  "Test-DbaLoginPassword",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaLoginPassword",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaLoginPassword -SqlInstance Dev01\nTest all SQL logins that the password is null or same as username on SQL server instance Dev01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaLoginPassword -SqlInstance Dev01 -Login sqladmin\nTest the \u0027sqladmin\u0027 SQL login that the password is null or same as username on SQL server instance Dev01\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaLoginPassword -SqlInstance Dev01 -Dictionary Test1,test2\nTest all SQL logins that the password is null, same as username or Test1,Test2 on SQL server instance Dev0\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance \"sql2017\",\"sql2016\" | Test-DbaLoginPassword\nTest all logins on sql2017 and sql2016\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$servers | Get-DbaLogin | Out-GridView -PassThru | Test-DbaLoginPassword\nTest selected logins on all servers in the $servers variable",
        "Params":  [
                       [
                           "SqlInstance",
                           "The SQL Server instance you\u0027re checking logins on. You must have sysadmin access and server version must be SQL Server version 2008 or higher.",
                           "ServerInstance,SqlServer,SqlServers",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Allows you to login to servers using SQL Logins instead of Windows Authentication (AKA Integrated or Trusted). To use:\n$scred = Get-Credential, then pass $scred object to the -SqlCredential parameter.\nWindows Authentication will be used if SqlCredential is not specified. SQL Server does not accept Windows credentials being passed as credentials.\nTo connect as a different Windows user, run PowerShell as that user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Login",
                           "The login(s) to process.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Dictionary",
                           "Specifies a list of passwords to include in the test for weak passwords.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Allows piping from Get-DbaLogin.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaLoginPassword [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Login] \u003cString[]\u003e] [[-Dictionary] \u003cString[]\u003e] [[-InputObject] \u003cLogin[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaManagementObject",
        "Description":  "The Test-DbaManagementObject returns True if the Version is on the computer, and False if it does not exist.",
        "Tags":  "SMO",
        "Synopsis":  "Tests to see if the SMO version specified exists on the computer.",
        "Alias":  "Test-DbaSqlManagementObject",
        "Author":  "Ben Miller (@DBAduck), http://dbaduck.com",
        "CommandName":  "Test-DbaManagementObject",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Test-DbaManagementObject",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaManagementObject -VersionNumber 13\nReturns True if the version exists, if it does not exist it will return False",
        "Params":  [
                       [
                           "ComputerName",
                           "The name of the target you would like to check",
                           "ServerInstance,SqlServer,SqlInstance",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "This command uses Windows credentials. This parameter allows you to connect remotely as a different user.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "VersionNumber",
                           "This is the specific version number you are looking for and the return will be True.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaManagementObject [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-VersionNumber] \u003cInt32[]\u003e [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaMaxDop",
        "Description":  "Inspired by Sakthivel Chidambaram\u0027s post about SQL Server MAXDOP Calculator (https://blogs.msdn.microsoft.com/sqlsakthi/p/maxdop-calculator-SqlInstance/),\nthis script displays a SQL Server\u0027s: max dop configured, and the calculated recommendation.\n\nFor SQL Server 2016 shows:\n- Instance max dop configured and the calculated recommendation\n- max dop configured per database (new feature)\n\nMore info:\nhttps://support.microsoft.com/en-us/kb/2806535\nhttps://blogs.msdn.microsoft.com/sqlsakthi/2012/05/23/wow-we-have-maxdop-calculator-for-sql-server-it-makes-my-job-easier/\n\nThese are just general recommendations for SQL Server and are a good starting point for setting the \"max degree of parallelism\" option.",
        "Tags":  [
                     "MaxDop",
                     "SpConfigure"
                 ],
        "Synopsis":  "Displays information relating to SQL Server Max Degree of Parallelism setting. Works on SQL Server 2005-2016.",
        "Alias":  "",
        "Author":  "Claudio Silva (@claudioessilva)",
        "CommandName":  "Test-DbaMaxDop",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaMaxDop",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaMaxDop -SqlInstance sql2008, sqlserver2012\nGet Max DOP setting for servers sql2008 and sqlserver2012 and also the recommended one.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaMaxDop -SqlInstance sql2014 | Select-Object *\nShows Max DOP setting for server sql2014 with the recommended value. Piping the output to Select-Object * will also show the \u0027NumaNodes\u0027 and \u0027NumberOfCores\u0027 of each instance\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaMaxDop -SqlInstance sqlserver2016 | Select-Object *\nGet Max DOP setting for servers sql2016 with the recommended value. Piping the output to Select-Object * will also show the \u0027NumaNodes\u0027 and \u0027NumberOfCores\u0027 of each instance. Because it is an 2016 \r\ninstance will be shown \u0027InstanceVersion\u0027, \u0027Database\u0027 and \u0027DatabaseMaxDop\u0027 columns.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Detailed",
                           "Output all properties, will be deprecated in 1.0.0 release.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaMaxDop [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Detailed] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaMaxMemory",
        "Description":  "Inspired by Jonathan Kehayias\u0027s post about SQL Server Max memory (http://bit.ly/sqlmemcalc), this script displays a SQL Server\u0027s: total memory, currently configured SQL max memory, and the calculated recommendation.\n\nJonathan notes that the formula used provides a *general recommendation* that doesn\u0027t account for everything that may be going on in your specific environment.",
        "Tags":  [
                     "MaxMemory",
                     "Memory"
                 ],
        "Synopsis":  "Calculates the recommended value for SQL Server \u0027Max Server Memory\u0027 configuration setting. Works on SQL Server 2000-2014.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Test-DbaMaxMemory",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Test-DbaMaxMemory",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaMaxMemory -SqlInstance sqlcluster,sqlserver2012\nCalculate the \u0027Max Server Memory\u0027 for SQL Server instances sqlcluster and sqlserver2012\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sqlcluster | Test-DbaMaxMemory\nCalculate the \u0027Max Server Memory\u0027 settings for all servers within the SQL Server Central Management Server \"sqlcluster\"\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sqlcluster | Test-DbaMaxMemory | Where-Object { $_.MaxValue -gt $_.Total } | Set-DbaMaxMemory\nFind all servers in CMS that have Max SQL memory set to higher than the total memory of the server (think 2147483647) and set it to recommended value.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Windows or Sql Login Credential with permission to log into the SQL instance",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Credential",
                           "Windows Credential with permission to log on to the server running the SQL instance",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaMaxMemory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaMigrationConstraint",
        "Description":  "When you want to migrate from a higher edition to a lower one there are some features that can\u0027t be used.\nThis function will validate if you have any of this features in use and will report to you.\nThe validation will be made ONLY on on SQL Server 2008 or higher using the \u0027sys.dm_db_persisted_sku_features\u0027 dmv.\n\nThis function only validate SQL Server 2008 versions or higher.\nThe editions supported by this function are:\n- Enterprise\n- Developer\n- Evaluation\n- Standard\n- Express\n\nTake into account the new features introduced on SQL Server 2016 SP1 for all versions. More information at https://blogs.msdn.microsoft.com/sqlreleaseservices/sql-server-2016-service-pack-1-sp1-released/\n\nThe -Database parameter is auto-populated for command-line completion.",
        "Tags":  "Migration",
        "Synopsis":  "Show if you can migrate the database(s) between the servers.",
        "Alias":  "Test-SqlMigrationConstraint",
        "Author":  "Claudio Silva (@ClaudioESSilva)",
        "CommandName":  "Test-DbaMigrationConstraint",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaMigrationConstraint",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaMigrationConstraint -Source sqlserver2014a -Destination sqlcluster\nAll databases on sqlserver2014a will be verified for features in use that can\u0027t be supported on sqlcluster.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaMigrationConstraint -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred\nAll databases will be verified for features in use that can\u0027t be supported on the destination server. SQL credentials are used to authenticate against sqlserver2014a and Windows Authentication is \r\nused for sqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaMigrationConstraint -Source sqlserver2014a -Destination sqlcluster -Database db1\nOnly db1 database will be verified for features in use that can\u0027t be supported on the destination server.",
        "Params":  [
                       [
                           "Source",
                           "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SourceSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Destination",
                           "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "DestinationSqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.",
                           "Databases",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeDatabase",
                           "The database(s) to exclude. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaMigrationConstraint [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaNetworkLatency",
        "Description":  "This function is intended to help measure SQL Server network latency by establishing a connection and executing a simple query. This is a better than a simple ping because it actually creates the connection to the SQL Server and measures the time required for only the entire routine, but the duration of the query as well how long it takes for the results to be returned.\n\nBy default, this command will execute \"SELECT TOP 100 * FROM INFORMATION_SCHEMA.TABLES\" three times. It will then output how long the entire connection and command took, as well as how long *only* the execution of the command took.\n\nThis allows you to see if the issue is with the connection or the SQL Server itself.",
        "Tags":  [
                     "Performance",
                     "Network"
                 ],
        "Synopsis":  "Tests how long a query takes to return from SQL Server",
        "Alias":  "Test-SqlNetworkLatency",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Test-DbaNetworkLatency",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaNetworkLatency",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaNetworkLatency -SqlInstance sqlserver2014a, sqlcluster\nTests the round trip return of \"SELECT TOP 100 * FROM INFORMATION_SCHEMA.TABLES\" on sqlserver2014a and sqlcluster using Windows credentials.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaNetworkLatency -SqlInstance sqlserver2014a -SqlCredential $cred\nTests the execution results return of \"SELECT TOP 100 * FROM INFORMATION_SCHEMA.TABLES\" on sqlserver2014a using SQL credentials.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaNetworkLatency -SqlInstance sqlserver2014a, sqlcluster, sqlserver -Query \"select top 10 * from otherdb.dbo.table\" -Count 10\nTests the execution results return of \"select top 10 * from otherdb.dbo.table\" 10 times on sqlserver2014a, sqlcluster, and sqlserver using Windows credentials.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The SQL Server you want to run the test on.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Query",
                           "Specifies the query to be executed. By default, \"SELECT TOP 100 * FROM INFORMATION_SCHEMA.TABLES\" will be executed on master. To execute in other databases, use fully qualified object names.",
                           "",
                           false,
                           "false",
                           "select top 100 * from INFORMATION_SCHEMA.TABLES"
                       ],
                       [
                           "Count",
                           "Specifies how many times the query should be executed. By default, the query is executed three times.",
                           "",
                           false,
                           "false",
                           "3"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaNetworkLatency [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Query] \u003cString\u003e] [[-Count] \u003cInt32\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaOptimizeForAdHoc",
        "Description":  "When this option is set, plan cache size is further reduced for single-use ad hoc OLTP workload.\n\nMore info: https://msdn.microsoft.com/en-us/library/cc645587.aspx\nhttp://www.sqlservercentral.com/blogs/glennberry/2011/02/25/some-suggested-sql-server-2008-r2-instance-configuration-settings/\n\nThese are just general recommendations for SQL Server and are a good starting point for setting the \"optimize for ad-hoc workloads\" option.",
        "Tags":  [
                     "Configure",
                     "SPConfigure"
                 ],
        "Synopsis":  "Displays information relating to SQL Server Optimize for AdHoc Workloads setting.  Works on SQL Server 2008-2016.",
        "Alias":  "",
        "Author":  "Brandon Abshire, netnerds.net",
        "CommandName":  "Test-DbaOptimizeForAdHoc",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaOptimizeForAdHoc",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaOptimizeForAdHoc -SqlInstance sql2008, sqlserver2012\nValidates whether Optimize for AdHoc Workloads setting is enabled for servers sql2008 and sqlserver2012.",
        "Params":  [
                       [
                           "SqlInstance",
                           "A collection of one or more SQL Server instance names to query.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because \r\nit basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaOptimizeForAdHoc [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaPath",
        "Description":  "Uses master.dbo.xp_fileexist to determine if a file or directory exists.",
        "Tags":  [
                     "Path",
                     "ServiceAccount"
                 ],
        "Synopsis":  "Tests if file or directory exists from the perspective of the SQL Server service account.",
        "Alias":  "Test-DbaSqlPath,Test-SqlPath",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Test-DbaPath",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaPath",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaPath -SqlInstance sqlcluster -Path L:\\MSAS12.MSSQLSERVER\\OLAP\nTests whether the service account running the \"sqlcluster\" SQL Server instance can access L:\\MSAS12.MSSQLSERVER\\OLAP. Logs into sqlcluster using Windows credentials.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$credential = Get-Credential\nPS C:\\\u003e Test-DbaPath -SqlInstance sqlcluster -SqlCredential $credential -Path L:\\MSAS12.MSSQLSERVER\\OLAP\nTests whether the service account running the \"sqlcluster\" SQL Server instance can access L:\\MSAS12.MSSQLSERVER\\OLAP. Logs into sqlcluster using SQL authentication.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The SQL Server you want to run the test on.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "The Path to test. This can be a file or directory",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaPath [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Path] \u003cObject\u003e [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaPowerPlan",
        "Description":  "Checks the Power Plan settings on a computer against best practices recommendations. If one server is checked, only $true or $false is returned. If multiple servers are checked, each server\u0027s name and an isBestPractice field are returned.\n\nReferences:\nhttps://support.microsoft.com/en-us/kb/2207548\nhttp://www.sqlskills.com/blogs/glenn/windows-power-plan-effects-on-newer-intel-processors/",
        "Tags":  "PowerPlan",
        "Synopsis":  "Checks the Power Plan settings for compliance with best practices, which recommend High Performance for SQL Server.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Test-DbaPowerPlan",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Test-DbaPowerPlan",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaPowerPlan -ComputerName sqlserver2014a\nChecks the Power Plan settings for sqlserver2014a and indicates whether or not it complies with best practices.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaPowerPlan -ComputerName sqlserver2014a -CustomPowerPlan \u0027Maximum Performance\u0027\nChecks the Power Plan settings for sqlserver2014a and indicates whether or not it is set to the custom plan \"Maximum Performance\".",
        "Params":  [
                       [
                           "ComputerName",
                           "The server(s) to check Power Plan settings on.",
                           "ServerInstance,SqlServer,SqlInstance",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Specifies a PSCredential object to use in authenticating to the server(s), instead of the current user account.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "CustomPowerPlan",
                           "If your organization uses a custom power plan that\u0027s considered best practice, specify it here.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Enables piping from Get-DbaPowerPlan",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Detailed",
                           "Output all properties, will be deprecated in 1.0.0 release.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaPowerPlan [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CustomPowerPlan] \u003cString\u003e] [[-InputObject] \u003cPSObject\u003e] [-Detailed] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaRepLatency",
        "Description":  "Creates tracer tokens to determine latency between the publisher/distributor and the distributor/subscriber\nfor all transactional publications for a server, database, or publication.",
        "Tags":  "Replication",
        "Synopsis":  "Displays replication latency for all transactional publications for a server or database.",
        "Alias":  "",
        "Author":  "Colin Douglas",
        "CommandName":  "Test-DbaRepLatency",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Test-DbaRepLatency",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaRepLatency -SqlInstance sql2008, sqlserver2012\nReturn replication latency for all transactional publications for servers sql2008 and sqlserver2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaRepLatency -SqlInstance sql2008 -Database TestDB\nReturn replication latency for all transactional publications on server sql2008 for only the TestDB database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaRepLatency -SqlInstance sql2008 -Database TestDB -PublicationName TestDB_Pub\nReturn replication latency for the TestDB_Pub publication for the TestDB database located on the server sql2008.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Database",
                           "The database(s) to process. If unspecified, all databases will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "PublicationName",
                           "The publication(s) to process. If unspecified, all publications will be processed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "TimeToLive",
                           "How long, in seconds, to wait for a tracer token to complete its journey from the publisher to the subscriber.\r\nIf unspecified, all tracer tokens will take as long as they need to process results.",
                           "",
                           false,
                           "false",
                           "0"
                       ],
                       [
                           "RetainToken",
                           "Retains the tracer tokens created for each publication. If unspecified, all tracer tokens created will be discarded.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "DisplayTokenHistory",
                           "Displays all tracer tokens in each publication. If unspecified, the current tracer token created will be only token displayed.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaRepLatency [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-Database] \u003cObject[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-PublicationName] \u003cObject[]\u003e] [[-TimeToLive] \u003cInt32\u003e] [-RetainToken] [-DisplayTokenHistory] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaServerName",
        "Description":  "When a SQL Server\u0027s host OS is renamed, the SQL Server should be as well. This helps with Availability Groups and Kerberos.\n\nThis command helps determine if your OS and SQL Server names match, and whether a rename is required.\n\nIt then checks conditions that would prevent a rename, such as database mirroring and replication.\n\nhttps://www.mssqltips.com/sqlservertip/2525/steps-to-change-the-server-name-for-a-sql-server-machine/",
        "Tags":  [
                     "SPN",
                     "ServerName"
                 ],
        "Synopsis":  "Tests to see if it\u0027s possible to easily rename the server at the SQL Server instance level, or if it even needs to be changed.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Test-DbaServerName",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaServerName",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaServerName -SqlInstance sqlserver2014a\nReturns ServerInstanceName, SqlServerName, IsEqual and RenameRequired for sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaServerName -SqlInstance sqlserver2014a, sql2016\nReturns ServerInstanceName, SqlServerName, IsEqual and RenameRequired for sqlserver2014a and sql2016.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaServerName -SqlInstance sqlserver2014a, sql2016 -ExcludeSsrs\nReturns ServerInstanceName, SqlServerName, IsEqual and RenameRequired for sqlserver2014a and sql2016, but skips validating if SSRS is installed on both instances.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eTest-DbaServerName -SqlInstance sqlserver2014a, sql2016 | Select-Object *\nReturns ServerInstanceName, SqlServerName, IsEqual and RenameRequired for sqlserver2014a and sql2016.\r\nIf a Rename is required, it will also show Updatable, and Reasons if the server name is not updatable.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Detailed",
                           "Output all properties, will be deprecated in 1.0.0 release.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "ExcludeSsrs",
                           "If this switch is enabled, checking for SQL Server Reporting Services will be skipped.",
                           "NoWarning",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaServerName [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Detailed] [-ExcludeSsrs] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaSpn",
        "Description":  "This function is designed to take in a server name(s) and attempt to determine required SPNs. It was initially written to mimic the (previously) broken functionality of the Microsoft Kerberos Configuration manager and SQL Server 2016.\n\n- For any instances with TCP/IP enabled, the script will determine which port(s) the instances are listening on and generate the required SPNs.\n- For named instances NOT using dynamic ports, the script will generate a port-based SPN for those instances as well.\n- At a minimum, the script will test a base, port-less SPN for each instance discovered.\n\nOnce the required SPNs are generated, the script will connect to Active Directory and search for any of the SPNs (if any) that are already set. The function will return a custom object(s) that contains the server name checked, the instance name discovered, the account the service is running under, and what the \"required\" SPN should be. It will also return a boolean property indicating if the SPN is set in Active Directory or not.",
        "Tags":  "SPN",
        "Synopsis":  "Test-DbaSpn will determine what SPNs *should* be set for a given server (and any instances of SQL running on it) and return\nwhether the SPNs are set or not.",
        "Alias":  "",
        "Author":  "Drew Furgiuele (@pittfurg), http://www.port1433.com | niphlod",
        "CommandName":  "Test-DbaSpn",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Test-DbaSpn",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaSpn -ComputerName SQLSERVERA -Credential ad\\sqldba\nConnects to a computer (SQLSERVERA) and queries WMI for all SQL instances and return \"required\" SPNs. It will then take each SPN it generates\r\nand query Active Directory to make sure the SPNs are set.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaSpn -ComputerName SQLSERVERA,SQLSERVERB -Credential ad\\sqldba\nConnects to multiple computers (SQLSERVERA, SQLSERVERB) and queries WMI for all SQL instances and return \"required\" SPNs.\r\nIt will then take each SPN it generates and query Active Directory to make sure the SPNs are set.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaSpn -ComputerName SQLSERVERC -Credential ad\\sqldba\nConnects to a computer (SQLSERVERC) on a specified and queries WMI for all SQL instances and return \"required\" SPNs.\r\nIt will then take each SPN it generates and query Active Directory to make sure the SPNs are set. Note that the credential you pass must have be a valid login with appropriate rights on the domain",
        "Params":  [
                       [
                           "ComputerName",
                           "The computer you want to discover any SQL Server instances on. This parameter is required.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Credential",
                           "The credential you want to use to connect to the remote server and active directory.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaSpn [-ComputerName] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaTempdbConfig",
        "Description":  "Evaluates tempdb against a set of rules to match best practices. The rules are:\n\n* TF 1118 enabled - Is Trace Flag 1118 enabled (See KB328551).\n* File Count - Does the count of data files in tempdb match the number of logical cores, up to 8?\n* File Growth - Are any files set to have percentage growth? Best practice is all files have an explicit growth value.\n* File Location - Is tempdb located on the C:\\? Best practice says to locate it elsewhere.\n* File MaxSize Set (optional) - Do any files have a max size value? Max size could cause tempdb problems if it isn\u0027t allowed to grow.\n* Data File Size Equal - Are the sizes of all the tempdb data files the same?\n\nOther rules can be added at a future date.",
        "Tags":  [
                     "tempdb",
                     "configuration"
                 ],
        "Synopsis":  "Evaluates tempdb against several rules to match best practices.",
        "Alias":  "Test-DbaTempDbConfiguration,Test-SqlTempDbConfiguration",
        "Author":  "Michael Fal (@Mike_Fal), http://mikefal.net",
        "CommandName":  "Test-DbaTempdbConfig",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Test-DbaTempdbConfig",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaTempdbConfig -SqlInstance localhost\nChecks tempdb on the localhost machine.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaTempdbConfig -SqlInstance localhost | Select-Object *\nChecks tempdb on the localhost machine. All rest results are shown.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaCmsRegServer -SqlInstance sqlserver2014a | Test-DbaTempdbConfig | Select-Object * | Out-GridView\nChecks tempdb configuration for a group of servers from SQL Server Central Management Server (CMS). Output includes all columns. Send output to GridView.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. SQL Server 2005 and higher are supported.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Detailed",
                           "Output all properties, will be depreciated in 1.0.0 release.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaTempdbConfig [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Detailed] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Test-DbaWindowsLogin",
        "Description":  "The purpose of this function is to find SQL Server logins that are used by active directory users that are either disabled or removed from the domain. It allows you to keep your logins accurate and up to date by removing accounts that are no longer needed.",
        "Tags":  [
                     "Login",
                     "Security"
                 ],
        "Synopsis":  "Test-DbaWindowsLogin finds any logins on SQL instance that are AD logins with either disabled AD user accounts or ones that no longer exist",
        "Alias":  "Test-DbaValidLogin",
        "Author":  "Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/ | Chrissy LeMaire (@cl)",
        "CommandName":  "Test-DbaWindowsLogin",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Test-DbaWindowsLogin",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaWindowsLogin -SqlInstance Dev01\nTests all logins in the current Active Directory domain that are either disabled or do not exist on the SQL Server instance Dev01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaWindowsLogin -SqlInstance Dev01 -FilterBy GroupsOnly | Select-Object -Property *\nTests all Active Directory groups that have logins on Dev01, and shows all information for those logins\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaWindowsLogin -SqlInstance Dev01 -IgnoreDomains testdomain\nTests all Domain logins excluding any that are from the testdomain",
        "Params":  [
                       [
                           "SqlInstance",
                           "The SQL Server instance you\u0027re checking logins on. You must have sysadmin access and server version must be SQL Server version 2000 or higher.",
                           "ServerInstance,SqlServer,SqlServers",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Login",
                           "Specifies a list of logins to include in the results. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ExcludeLogin",
                           "Specifies a list of logins to exclude from the results. Options for this list are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "FilterBy",
                           "Specifies the object types to return. By default, both Logins and Groups are returned. Valid options for this parameter are \u0027GroupsOnly\u0027 and \u0027LoginsOnly\u0027.",
                           "",
                           false,
                           "false",
                           "None"
                       ],
                       [
                           "IgnoreDomains",
                           "Specifies a list of Active Directory domains to ignore. By default, all domains in the forest as well as all trusted domains are traversed.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Detailed",
                           "Output all properties, will be depreciated in 1.0.0 release.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Test-DbaWindowsLogin [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Login \u003cObject[]\u003e] [-ExcludeLogin \u003cObject[]\u003e] [-FilterBy \u003cString\u003e] [-IgnoreDomains \u003cString[]\u003e] [-Detailed] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Uninstall-DbaSqlWatch",
        "Description":  "Deletes all user objects, agent jobs, and historical data associated with SqlWatch.",
        "Tags":  "SqlWatch",
        "Synopsis":  "Uninstalls SqlWatch.",
        "Alias":  "",
        "Author":  "Ken K (github.com/koglerk)",
        "CommandName":  "Uninstall-DbaSqlWatch",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Uninstall-DbaSqlWatch",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eUninstall-DbaSqlWatch -SqlInstance server1\nDeletes all user objects, agent jobs, and historical data associated with SqlWatch from the master database.",
        "Params":  [
                       [
                           "SqlInstance",
                           "SQL Server name or SMO object representing the SQL Server to connect to.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "Specifies the database to install SqlWatch into. Defaults to master.",
                           "",
                           false,
                           "false",
                           "master"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts to confirm actions",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Uninstall-DbaSqlWatch [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Uninstall-DbaWatchUpdate",
        "Description":  "Removes the scheduled task created for Watch-DbaUpdate by Install-DbaWatchUpdate so that notifications no longer pop up.",
        "Tags":  [
                     "JustForFun",
                     "Module"
                 ],
        "Synopsis":  "Removes the scheduled task created for Watch-DbaUpdate by Install-DbaWatchUpdate so that notifications no longer pop up.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Uninstall-DbaWatchUpdate",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Uninstall-DbaWatchUpdate",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eUninstall-DbaWatchUpdate\nRemoves the scheduled task created by Install-DbaWatchUpdate.",
        "Params":  [

                   ],
        "Syntax":  "Uninstall-DbaWatchUpdate [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Unregister-DbatoolsConfig",
        "Description":  "Removes registered configuration settings.\nThis function can be used to remove settings that have been persisted for either user or computer.\n\nNote: This command has no effect on configuration setings currently in memory.",
        "Synopsis":  "Removes registered configuration settings.",
        "Alias":  "",
        "CommandName":  "Unregister-DbatoolsConfig",
        "Availability":  "Windows, Linux, macOS",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbatoolsConfig | Unregister-DbatoolsConfig\nCompletely removes all registered configurations currently loaded in memory.\r\nIn most cases, this will mean removing all registered configurations.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eUnregister-DbatoolsConfig -Scope SystemDefault -FullName \u0027MyModule.Path.DefaultExport\u0027\nUnregisters the setting \u0027MyModule.Path.DefaultExport\u0027 from the list of computer-wide defaults.\r\nNote: Changing system wide settings requires running the console with elevation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eUnregister-DbatoolsConfig -Module MyModule\nUnregisters all configuration settings for the module MyModule.",
        "Params":  [
                       [
                           "ConfigurationItem",
                           "A configuration object as returned by Get-DbatoolsConfig.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "FullName",
                           "The full name of the configuration setting to purge.",
                           "",
                           false,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Module",
                           "The module, amongst which settings should be unregistered.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Name",
                           "The name of the setting to unregister.\r\nFor use together with the module parameter, to limit the amount of settings that are unregistered.",
                           "",
                           false,
                           "false",
                           "*"
                       ],
                       [
                           "Scope",
                           "Settings can be set to either default or enforced, for user or the entire computer.\r\nBy default, only DefaultSettings for the user are unregistered.\r\nUse this parameter to choose the actual scope for the command to process.",
                           "",
                           false,
                           "false",
                           "UserDefault"
                       ]
                   ],
        "Syntax":  "Unregister-DbatoolsConfig [-ConfigurationItem \u003cConfig[]\u003e] [-FullName \u003cString[]\u003e] [-Scope {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [\u003cCommonParameters\u003e]\nUnregister-DbatoolsConfig -Module \u003cString\u003e [-Name \u003cString\u003e] [-Scope {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Update-DbaInstance",
        "Description":  "Starts and automated process of updating SQL Server installation to a specific version defined in the parameters.\nThe command will:\n\n* Search for SQL Server installations in a remote registry\n* Check if current settings are applicable to the current SQL Server versions\n* Search for a KB executable in a folder specified in -Path\n* Establish a PSRemote connection to the target machine if necessary\n* Extract KB to a temporary folder in a current user\u0027s profile\n* Run the installation from the temporary folder updating all instances on the computer at once\n* Remove temporary files\n* Restart the computer (if -Restart is specified)\n* Repeat for each consequent KB and computer\n\nThe impact of this function is set to High, if you don\u0027t want to receive interactive prompts, set -Confirm to $false.\nCredentials are a required parameter for remote machines. Without specifying -Credential, the installation will fail due to lack of permissions.\n\nCredSSP is a recommended transport for running the updates remotely. Update-DbaInstance will attempt to reconfigure\nlocal and remote hosts to support CredSSP, which is why it is desirable to run this command in an elevated console at all times.\nCVE-2018-0886 security update is required for both local and remote hosts. If CredSSP connections are failing, make sure to\napply recent security updates prior to doing anything else.\n\nAlways backup databases and configurations prior to upgrade.",
        "Tags":  [
                     "Install",
                     "Patching",
                     "SP",
                     "CU",
                     "Instance"
                 ],
        "Synopsis":  "Invokes installation of SQL Server Service Packs and Cumulative Updates on local and remote servers.",
        "Alias":  "",
        "Author":  "Kirill Kravtsov (@nvarscar) https://nvarscar.wordpress.com/",
        "CommandName":  "Update-DbaInstance",
        "Availability":  "Windows only",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eUpdate-DbaInstance -ComputerName SQL1 -Version SP3 -Path \\\\network\\share\nUpdates all applicable SQL Server installations on SQL1 to SP3.\r\nBinary files for the update will be searched among all files and folders recursively in \\\\network\\share.\r\nPrompts for confirmation before the update.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eUpdate-DbaInstance -ComputerName SQL1, SQL2 -Restart -Path \\\\network\\share -Confirm:$false\nUpdates all applicable SQL Server installations on SQL1 and SQL2 with the most recent patch.\r\nIt will install latest ServicePack, restart the computers, install latest Cumulative Update, and finally restart the computer once again.\r\nBinary files for the update will be searched among all files and folders recursively in \\\\network\\share.\r\nDoes not prompt for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eUpdate-DbaInstance -ComputerName SQL1 -Version 2012 -Type ServicePack -Path \\\\network\\share\nUpdates SQL Server 2012 on SQL1 with the most recent ServicePack found in your patch repository.\r\nBinary files for the update will be searched among all files and folders recursively in \\\\network\\share.\r\nPrompts for confirmation before the update.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eUpdate-DbaInstance -ComputerName SQL1 -KB 123456 -Restart -Path \\\\network\\share -Confirm:$false\nInstalls KB 123456 on SQL1 and restarts the computer.\r\nBinary files for the update will be searched among all files and folders recursively in \\\\network\\share.\r\nDoes not prompt for confirmation.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eUpdate-DbaInstance -ComputerName Server1 -Version SQL2012SP3, SQL2016SP2CU3 -Path \\\\network\\share -Restart -Confirm:$false\nUpdates SQL 2012 to SP3 and SQL 2016 to SP2CU3 on Server1. Each update will be followed by a restart.\r\nBinary files for the update will be searched among all files and folders recursively in \\\\network\\share.\r\nDoes not prompt for confirmation.",
        "Params":  [
                       [
                           "ComputerName",
                           "Target computer with SQL instance or instances.",
                           "cn,host,Server",
                           false,
                           "true (ByValue)",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Windows Credential with permission to log on to the remote server.\r\nMust be specified for any remote connection if update Repository is located on a network folder.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Version",
                           "A target version of the installation you want to reach. If not specified, a latest available version would be used by default.\r\nCan be defined using the following general pattern: \u003cMajorVersion\u003e\u003cSPX\u003e\u003cCUX\u003e.\r\nAny part of the pattern can be omitted if needed:\r\n2008R2SP1 - will update SQL 2008R2 to SP1\r\n2016CU3 - will update SQL 2016 to CU3 of current Service Pack installed\r\nSP0CU3 - will update all existing SQL Server versions to RTM CU3 without installing any service packs\r\nSP1CU7 - will update all existing SQL Server versions to SP1 and then (after restart if -Restart is specified) to SP1CU7\r\nCU7 - will update all existing SQL Server versions to CU7 of current Service Pack installed",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Type",
                           "Type of the update: All | ServicePack | CumulativeUpdate.\r\nDefault: All\r\nUse -Version to limit upgrade to a certain Major version of SQL Server.",
                           "",
                           false,
                           "false",
                           "@(\u0027All\u0027)"
                       ],
                       [
                           "KB",
                           "Install a specific update or list of updates. Can be a number of a string KBXXXXXXX.",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "InstanceName",
                           "Only updates a specific instance(s).",
                           "Instance",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Path",
                           "Path to the folder(s) with SQL Server patches downloaded. It will be scanned recursively for available patches.\r\nPath should be available from both server with SQL Server installation and client that runs the command.\r\nAll file names should match the pattern used by Microsoft: SQLServer####*-KB###-*x##*.exe\r\nIf a file is missing in the repository, the installation will fail.\r\nConsider setting the following configuration if you want to omit this parameter: `Set-DbatoolsConfig -Name Path.SQLServerUpdates -Value \u0027\\\\path\\to\\updates\u0027`",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Restart",
                           "Restart computer automatically after a successful installation of a patch and wait until it comes back online.\r\nUsing this parameter is the only way to chain-install more than 1 patch on a computer, since every single patch will require a restart of said computer.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Continue",
                           "Continues a failed installation attempt when specified. Will abort a previously failed installation otherwise.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Throttle",
                           "Maximum number of computers updated in parallel. Once reached, the update operations will queue up.\r\nDefault: 50",
                           "",
                           false,
                           "false",
                           "50"
                       ],
                       [
                           "Authentication",
                           "Chooses an authentication protocol for remote connections.\r\nIf the protocol fails to establish a connection\nDefaults:\r\n* CredSSP when -Credential is specified - due to the fact that repository Path is usually a network share and credentials need to be passed to the remote host\r\n  to avoid the double-hop issue.\r\n* Default when -Credential is not specified. Will likely fail if a network path is specified.",
                           "",
                           false,
                           "false",
                           "Credssp"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Update-DbaInstance [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [-Credential \u003cPSCredential\u003e] [-Version \u003cString[]\u003e] [-Type \u003cString[]\u003e] [-InstanceName \u003cString\u003e] [-Path \u003cString[]\u003e] [-Restart] [-Continue] [-Throttle \u003cInt32\u003e] [-Authentication \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nUpdate-DbaInstance [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [-Credential \u003cPSCredential\u003e] -KB \u003cString[]\u003e [-InstanceName \u003cString\u003e] [-Path \u003cString[]\u003e] [-Restart] [-Continue] [-Throttle \u003cInt32\u003e] [-Authentication \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Update-DbaServiceAccount",
        "Description":  "Reconfigure the service account or update the password of the specified SQL Server service. The service will be restarted in the event of changing the account.",
        "Tags":  [
                     "Service",
                     "SqlServer",
                     "Instance",
                     "Connect"
                 ],
        "Synopsis":  "Changes service account (or just its password) of the SQL Server service.",
        "Alias":  "Update-DbaSqlServiceAccount",
        "Author":  "Kirill Kravtsov (@nvarscar)",
        "CommandName":  "Update-DbaServiceAccount",
        "Availability":  "Windows only",
        "Links":  null,
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$SecurePassword = ConvertTo-SecureString \u0027Qwerty1234\u0027 -AsPlainText -Force\nUpdate-DbaServiceAccount -ComputerName sql1 -ServiceName \u0027MSSQL$MYINSTANCE\u0027 -SecurePassword $SecurePassword\nChanges the current service account\u0027s password of the service MSSQL$MYINSTANCE to \u0027Qwerty1234\u0027\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$cred = Get-Credential\nPS C:\\\u003e Get-DbaService sql1 -Type Engine,Agent -Instance MYINSTANCE | Update-DbaServiceAccount -ServiceCredential $cred\nRequests credentials from the user and configures them as a service account for the SQL Server engine and agent services of the instance sql1\\MYINSTANCE\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eUpdate-DbaServiceAccount -ComputerName sql1,sql2 -ServiceName \u0027MSSQLSERVER\u0027,\u0027SQLSERVERAGENT\u0027 -Username NETWORKSERVICE\nConfigures SQL Server engine and agent services on the machines sql1 and sql2 to run under Network Service system user.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaService sql1 -Type Engine -Instance MSSQLSERVER | Update-DbaServiceAccount -Username \u0027MyDomain\\sqluser1\u0027\nConfigures SQL Server engine service on the machine sql1 to run under MyDomain\\sqluser1. Will request user to input the account password.",
        "Params":  [
                       [
                           "ComputerName",
                           "The target SQL Server instance or instances.",
                           "cn,host,Server",
                           false,
                           "false",
                           "$env:COMPUTERNAME"
                       ],
                       [
                           "Credential",
                           "Windows Credential with permission to log on to the server running the SQL instance",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "A collection of services. Basically, any object that has ComputerName and ServiceName properties. Can be piped from Get-DbaService.",
                           "ServiceCollection",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "ServiceName",
                           "A name of the service on which the action is performed. E.g. MSSQLSERVER or SqlAgent$INSTANCENAME",
                           "Name,Service",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Username",
                           "Username of the service account. Cannot be used with -ServiceCredential. For local service accounts use one of the following usernames omitting the -SecurePassword parameter:\r\nLOCALSERVICE\r\nNETWORKSERVICE\r\nLOCALSYSTEM",
                           "User",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ServiceCredential",
                           "Windows Credential object under which the service will be setup to run. Cannot be used with -Username. For local service accounts use one of the following usernames with empty password:\r\nLOCALSERVICE\r\nNETWORKSERVICE\r\nLOCALSYSTEM",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "PreviousPassword",
                           "An old password of the service account. Optional when run under local admin privileges.",
                           "",
                           false,
                           "false",
                           "(New-Object System.Security.SecureString)"
                       ],
                       [
                           "SecurePassword",
                           "New password of the service account. The function will ask for a password if not specified. MSAs and local system accounts will ignore the password.",
                           "Password,NewPassword",
                           false,
                           "false",
                           "(New-Object System.Security.SecureString)"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "WhatIf",
                           "Shows what would happen if the command were to run. No actions are actually performed.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "Prompts you for confirmation before executing any changing operations within the command.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Update-DbaServiceAccount [-ComputerName \u003cDbaInstanceParameter[]\u003e] [-Credential \u003cPSCredential\u003e] [-ServiceName] \u003cString[]\u003e [-Username \u003cString\u003e] [-ServiceCredential \u003cPSCredential\u003e] [-PreviousPassword \u003cSecureString\u003e] [-SecurePassword \u003cSecureString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nUpdate-DbaServiceAccount [-Credential \u003cPSCredential\u003e] -InputObject \u003cObject[]\u003e [-Username \u003cString\u003e] [-ServiceCredential \u003cPSCredential\u003e] [-PreviousPassword \u003cSecureString\u003e] [-SecurePassword \u003cSecureString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Update-Dbatools",
        "Description":  "Exported function. Updates dbatools. Deletes current copy and replaces it with freshest copy.",
        "Tags":  "Module",
        "Synopsis":  "Exported function. Updates dbatools. Deletes current copy and replaces it with freshest copy.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Update-Dbatools",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Update-DbaTools",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eUpdate-Dbatools\nUpdates dbatools. Deletes current copy and replaces it with freshest copy.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eUpdate-Dbatools -dev\nUpdates dbatools to the current development branch. Deletes current copy and replaces it with latest from github.",
        "Params":  [
                       [
                           "Development",
                           "If this switch is enabled, the current development branch will be installed. By default, the latest official release is installed.",
                           "dev,devbranch",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Update-Dbatools [-Development] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Watch-DbaDbLogin",
        "Description":  "Watch-DbaDbLogin uses SQL Server DMV\u0027s to track logins into a SQL Server table. This is helpful when you need to migrate a SQL Server and update connection strings, but have inadequate documentation on which servers/applications are logging into your SQL instance.\n\nRunning this script every 5 minutes for a week should give you a sufficient idea about database and login usage.",
        "Tags":  "Login",
        "Synopsis":  "Tracks SQL Server logins: which host they came from, what database they\u0027re using, and what program is being used to log in.",
        "Alias":  "Watch-SqlDbLogin",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Watch-DbaDbLogin",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Watch-DbaDbLogin",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eWatch-DbaDbLogin -SqlInstance sqlserver -SqlCms SqlCms1\nA list of all database instances within the Central Management Server SqlCms1 is generated. Using this list, the script enumerates all the processes and gathers login information and saves it to the \r\ntable Dblogins in the DatabaseLogins database on SQL Server sqlserver.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eWatch-DbaDbLogin -SqlInstance sqlcluster -Database CentralAudit -ServersFromFile .\\sqlservers.txt\nA list of servers is gathered from the file sqlservers.txt in the current directory. Using this list, the script enumerates all the processes and gathers login information and saves it to the table \r\nDblogins in the CentralAudit database on SQL Server sqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eWatch-DbaDbLogin -SqlInstance sqlserver -SqlCms SqlCms1 -SqlCredential $cred\nA list of servers is generated using database instance names within the SQL2014Clusters group on the Central Management Server SqlCms1. Using this list, the script enumerates all the processes and \r\ngathers login information and saves it to the table Dblogins in the DatabaseLogins database on sqlserver.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The SQL Server that stores the Watch database.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The name of the Watch database.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Table",
                           "The name of the Watch table. By default, this is DbaTools-WatchDbLogins.",
                           "",
                           false,
                           "false",
                           "DbaTools-WatchDbLogins"
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "SqlCms",
                           "Specifies a Central Management Server to query for a list of servers to watch.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "ServersFromFile",
                           "Specifies a file containing a list of servers to watch. This file must contain one server name per line.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Watch-DbaDbLogin [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-Database] \u003cObject\u003e] [[-Table] \u003cString\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-SqlCms] \u003cString\u003e] [[-ServersFromFile] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Watch-DbaUpdate",
        "Description":  "Just for fun - checks the PowerShell Gallery every 1 hour for updates to dbatools. Notifies once max per release.\n\nAnyone know how to make it clickable so that it opens an URL?",
        "Tags":  [
                     "JustForFun",
                     "Module"
                 ],
        "Synopsis":  "Just for fun - checks the PowerShell Gallery every 1 hour for updates to dbatools. Notifies once per release.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Watch-DbaUpdate",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Watch-DbaUpdate",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eWatch-DbaUpdate\nWatches the gallery for updates to dbatools.",
        "Params":  [

                   ],
        "Syntax":  "Watch-DbaUpdate [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Watch-DbaXESession",
        "Description":  "Watch live XEvent Data as it happens. This command runs until you stop the session, kill the PowerShell session, or Ctrl-C.\n\nThanks to Dave Mason (@BeginTry) for some straightforward code samples https://itsalljustelectrons.blogspot.be/2017/01/SQL-Server-Extended-Event-Handling-Via-Powershell.html",
        "Tags":  [
                     "ExtendedEvent",
                     "XE",
                     "XEvent"
                 ],
        "Synopsis":  "Watch live XEvent Data as it happens",
        "Alias":  "Watch-DbaXEventSession",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Watch-DbaXESession",
        "Availability":  "Windows only",
        "Links":  "https://dbatools.io/Watch-DbaXESession",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eWatch-DbaXESession -SqlInstance sql2017 -Session system_health\nShows events for the system_health session as it happens.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eWatch-DbaXESession -SqlInstance sql2017 -Session system_health | Export-Csv -NoTypeInformation -Path C:\\temp\\system_health.csv\nExports live events to CSV. Ctrl-C may not not cancel out of it - fastest way is to stop the session.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sql2017 -Session system_health | Start-DbaXESession | Watch-DbaXESession | Export-Csv -NoTypeInformation -Path C:\\temp\\system_health.csv\nExports live events to CSV. Ctrl-C may not not cancel out of this. The fastest way to do so is to stop the session.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.",
                           "ServerInstance,SqlServer",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Session",
                           "Only return a specific session. Options for this parameter are auto-populated from the server.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "Accepts an XESession object returned by Get-DbaXESession.",
                           "",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Raw",
                           "If this switch is enabled, the Microsoft.SqlServer.XEvent.Linq.QueryableXEventData enumeration object is returned.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ]
                   ],
        "Syntax":  "Watch-DbaXESession [-SqlCredential \u003cPSCredential\u003e] [-Session \u003cString\u003e] [-Raw] [-EnableException] [\u003cCommonParameters\u003e]\nWatch-DbaXESession -SqlInstance \u003cDbaInstanceParameter\u003e [-SqlCredential \u003cPSCredential\u003e] [-Session \u003cString\u003e] [-Raw] [-EnableException] [\u003cCommonParameters\u003e]\nWatch-DbaXESession [-SqlCredential \u003cPSCredential\u003e] [-Session \u003cString\u003e] -InputObject \u003cSession\u003e [-Raw] [-EnableException] [\u003cCommonParameters\u003e]"
    },
    {
        "Name":  "Write-DbaDataTable",
        "Description":  "Writes a .NET DataTable to a SQL Server table using SQL Bulk Copy.",
        "Tags":  [
                     "DataTable",
                     "Insert"
                 ],
        "Synopsis":  "Writes data to a SQL Server Table.",
        "Alias":  "",
        "Author":  "Chrissy LeMaire (@cl), netnerds.net",
        "CommandName":  "Write-DbaDataTable",
        "Availability":  "Windows, Linux, macOS",
        "Links":  "https://dbatools.io/Write-DbaDataTable",
        "Examples":  "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$DataTable = Import-Csv C:\\temp\\customers.csv\nPS C:\\\u003e Write-DbaDataTable -SqlInstance sql2014 -InputObject $DataTable -Table mydb.dbo.customers\nPerforms a bulk insert of all the data in customers.csv into database mydb, schema dbo, table customers. A progress bar will be shown as rows are inserted. If the destination table does not exist, \r\nthe import will be halted.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$tableName = \"MyTestData\"\nPS C:\\\u003e $query = \"SELECT name, create_date, owner_sid FROM sys.databases\"\r\nPS C:\\\u003e $dataset = Invoke-DbaQuery -SqlInstance \u0027localhost,1417\u0027 -SqlCredential $containerCred -Database master -Query $query\r\nPS C:\\\u003e $dataset | Select-Object name, create_date, @{L=\"owner_sid\";E={$_.\"owner_sid\"}} | Write-DbaDataTable -SqlInstance \u0027localhost,1417\u0027 -SqlCredential $containerCred -Database tempdb -Table \r\nmyTestData -Schema dbo -AutoCreateTable\nPulls data from a SQL Server instance and then performs a bulk insert of the dataset to a new, auto-generated table tempdb.dbo.MyTestData.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$DataTable = Import-Csv C:\\temp\\customers.csv\nPS C:\\\u003e Write-DbaDataTable -SqlInstance sql2014 -InputObject $DataTable -Table mydb.dbo.customers -AutoCreateTable -Confirm\nPerforms a bulk insert of all the data in customers.csv. If mydb.dbo.customers does not exist, it will be created with inefficient but forgiving DataTypes.\nPrompts for confirmation before a variety of steps.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$DataTable = Import-Csv C:\\temp\\customers.csv\nPS C:\\\u003e Write-DbaDataTable -SqlInstance sql2014 -InputObject $DataTable -Table mydb.dbo.customers -Truncate\nPerforms a bulk insert of all the data in customers.csv. Prior to importing into mydb.dbo.customers, the user is informed that the table will be truncated and asks for confirmation. The user is \r\nprompted again to perform the import.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$DataTable = Import-Csv C:\\temp\\customers.csv\nPS C:\\\u003e Write-DbaDataTable -SqlInstance sql2014 -InputObject $DataTable -Database mydb -Table customers -KeepNulls\nPerforms a bulk insert of all the data in customers.csv into mydb.dbo.customers. Because Schema was not specified, dbo was used. NULL values in the destination table will be preserved.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$passwd = ConvertTo-SecureString \"P@ssw0rd\" -AsPlainText -Force\nPS C:\\\u003e $AzureCredential = New-Object System.Management.Automation.PSCredential(\"AzureAccount\"),$passwd)\r\nPS C:\\\u003e $DataTable = Import-Csv C:\\temp\\customers.csv\r\nPS C:\\\u003e Write-DbaDataTable -SqlInstance AzureDB.database.windows.net -InputObject $DataTable -Database mydb -Table customers -KeepNulls -Credential $AzureCredential -BulkCopyTimeOut 300\nThis performs the same operation as the previous example, but against a SQL Azure Database instance using the required credentials.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$process = Get-Process\nPS C:\\\u003e Write-DbaDataTable -InputObject $process -SqlInstance sql2014 -Table \"[[DbName]]].[Schema.With.Dots].[`\"[Process]]`\"]\" -AutoCreateTable\nCreates a table based on the Process object with over 60 columns, converted from PowerShell data types to SQL Server data types. After the table is created a bulk insert is performed to add process \r\ninformation into the table\r\nWrites the results of Get-Process to a table named: \"[Process]\" in schema named: Schema.With.Dots in database named: [DbName]\r\nThe Table name, Schema name and Database name must be wrapped in square brackets [ ]\r\nSpecial charcters like \" must be escaped by a ` charcter.\r\nIn addition any actual instance of the ] character must be escaped by being duplicated.\nThis is an example of the type conversion in action. All process properties are converted, including special types like TimeSpan. Script properties are resolved before the type conversion starts \r\nthanks to ConvertTo-DbaDataTable.",
        "Params":  [
                       [
                           "SqlInstance",
                           "The target SQL Server instance or instances.",
                           "ServerInstance,SqlServer",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "SqlCredential",
                           "Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)",
                           "Credential",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Database",
                           "The database to import the table into.",
                           "",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "InputObject",
                           "This is the DataTable (or data row) to import to SQL Server.",
                           "DataTable",
                           true,
                           "true (ByValue)",
                           ""
                       ],
                       [
                           "Table",
                           "The table name to import data into. You can specify a one, two, or three part table name. If you specify a one or two part name, you must also use -Database.\nIf the table does not exist, you can use -AutoCreateTable to automatically create the table with inefficient data types.\nIf the object has special characters please wrap them in square brackets [ ].\r\nUsing dbo.First.Table will try to import to a table named \u0027Table\u0027 on schema \u0027First\u0027 and database \u0027dbo\u0027.\r\nThe correct way to import to a table named \u0027First.Table\u0027 on schema \u0027dbo\u0027 is by passing dbo.[First.Table]\r\nAny actual usage of the ] must be escaped by duplicating the ] character.\r\nThe correct way to import to a table Name] in schema Schema.Name is by passing [Schema.Name].[Name]]]",
                           "",
                           true,
                           "false",
                           ""
                       ],
                       [
                           "Schema",
                           "Defaults to dbo if no schema is specified.",
                           "",
                           false,
                           "false",
                           "dbo"
                       ],
                       [
                           "BatchSize",
                           "The BatchSize for the import defaults to 5000.",
                           "",
                           false,
                           "false",
                           "50000"
                       ],
                       [
                           "NotifyAfter",
                           "Sets the option to show the notification after so many rows of import",
                           "",
                           false,
                           "false",
                           "5000"
                       ],
                       [
                           "AutoCreateTable",
                           "If this switch is enabled, the table will be created if it does not already exist. The table will be created with sub-optimal data types such as nvarchar(max)",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "NoTableLock",
                           "If this switch is enabled, a table lock (TABLOCK) will not be placed on the destination table. By default, this operation will lock the destination table while running.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "CheckConstraints",
                           "If this switch is enabled, the SqlBulkCopy option to process check constraints will be enabled.\nPer Microsoft \"Check constraints while data is being inserted. By default, constraints are not checked.\"",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "FireTriggers",
                           "If this switch is enabled, the SqlBulkCopy option to fire insert triggers will be enabled.\nPer Microsoft \"When specified, cause the server to fire the insert triggers for the rows being inserted into the Database.\"",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "KeepIdentity",
                           "If this switch is enabled, the SqlBulkCopy option to preserve source identity values will be enabled.\nPer Microsoft \"Preserve source identity values. When not specified, identity values are assigned by the destination.\"",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "KeepNulls",
                           "If this switch is enabled, the SqlBulkCopy option to preserve NULL values will be enabled.\nPer Microsoft \"Preserve null values in the destination table regardless of the settings for default values. When not specified, null values are replaced by default values where applicable.\"",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "Truncate",
                           "If this switch is enabled, the destination table will be truncated after prompting for confirmation.",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "bulkCopyTimeOut",
                           "Value in seconds for the BulkCopy operations timeout. The default is 30 seconds.",
                           "",
                           false,
                           "false",
                           "5000"
                       ],
                       [
                           "RegularUser",
                           "Deprecated - now all connections are regular user (don\u0027t require admin)",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "EnableException",
                           "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.",
                           "Silent",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "UseDynamicStringLength",
                           "By default, all string columns will be NVARCHAR(MAX).\r\nIf this switch is enabled, all columns will get the length specified by the column\u0027s MaxLength property (if specified)",
                           "",
                           false,
                           "false",
                           "False"
                       ],
                       [
                           "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.",
                           "wi",
                           false,
                           "false",
                           ""
                       ],
                       [
                           "Confirm",
                           "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.",
                           "cf",
                           false,
                           "false",
                           ""
                       ]
                   ],
        "Syntax":  "Write-DbaDataTable [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject\u003e] -InputObject \u003cObject\u003e [-Table] \u003cString\u003e [[-Schema] \u003cString\u003e] [-BatchSize \u003cInt32\u003e] [-NotifyAfter \u003cInt32\u003e] [-AutoCreateTable] [-NoTableLock] [-CheckConstraints] [-FireTriggers] [-KeepIdentity] [-KeepNulls] [-Truncate] [-bulkCopyTimeOut \u003cInt32\u003e] [-RegularUser] [-EnableException] [-UseDynamicStringLength] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]"
    }
]
tools\dbatools\bin\dbatools.dll
md5: 06F6DB200D28C91D1E68F4C18C9102C9 | sha1: 3D72A105EFA68845B1CDBEEEEAD76DA7ACF160DB | sha256: C1A33D435B99AA2B9C8ADCA482CC7387DCC0A391819C4C6CA3359E1F349A1B25 | sha512: 8F7F17D4454EA33C31C0041B0006E8774A6E0C1A97F7218B72C1435CBA71E3BA9ADEB5917FEACC003B97A1C63DDB9ADC4EA0CA4D001C12650256EC5E3E3E598F
tools\dbatools\bin\dbatools.pdb
 
tools\dbatools\bin\dbatools.xml
<?xml version="1.0"?>
<doc>
    <assembly>
        <name>dbatools</name>
    </assembly>
    <members>
        <member name="T:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand">
            <summary>
            Implements the Select-DbaObject command
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.InputObject">
            <summary>
            The actual input object that is being processed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.Property">
            <summary>
            The properties to select. Supports fancy DSL
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.ExcludeProperty">
            <summary>
            Properties to skip
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.ExpandProperty">
            <summary>
            A property to expand.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.Unique">
            <summary>
            Whether to exclude duplicates
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.Last">
            <summary>
            The last number of items to pick
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.First">
            <summary>
            Pick the first n items.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.Skip">
            <summary>
            Skip n items before picking items
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.SkipLast">
            <summary>
            Skip the last n items
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.Wait">
            <summary>
            
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.Index">
            <summary>
            
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.ShowProperty">
            <summary>
            THe properties to display by default
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.ShowExcludeProperty">
            <summary>
            The properties to NOT display by default
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.TypeName">
            <summary>
            The typename to assign to the psobject
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.KeepInputObject">
            <summary>
            Keep the original input object, just add to it.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand._NonclonedProperties">
            <summary>
            List of properties to NOT clone into the hashtable used against Select-Object
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand._NoAdjustment">
            <summary>
            Whether some adjustments to the object need to be done or whether the Select-Object output can be simply passed through.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand._DisplayPropertySet">
            <summary>
            The set controlling what properties will be shown by default
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand._Pipeline">
            <summary>
            THe pipeline that is wrapped around Select-Object
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.BeginProcessing">
            <summary>
            Implements the begin action of the command
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.ProcessRecord">
            <summary>
            Implements the process action of the command
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.EndProcessing">
            <summary>
            Implements the end action of the command
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand">
            <summary>
            Implements the Set-PSFConfig command
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.FullName">
            <summary>
            The full name of the setting
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Module">
            <summary>
            The name of the module the setting belongs to.
            Is optional due to just specifying a name is legal, in which case the first name segment becomes the module name.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Name">
            <summary>
            The name of the setting within a module.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Value">
            <summary>
            The value to apply.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.PersistedValue">
            <summary>
            The persisted value to apply.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.PersistedType">
            <summary>
            The persisted type to apply.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Description">
            <summary>
            Add documentation to the setting.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Validation">
            <summary>
            The validation script to use.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Handler">
            <summary>
            The handling script to apply when changing the value.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Hidden">
            <summary>
            Whether the setting should be hidden from casual discovery.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Default">
            <summary>
            Whether the setting should be applied only when nothing exists yet.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Initialize">
            <summary>
            Whether this is the configuration initialization call.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.SimpleExport">
            <summary>
            Enabling this will cause the module to use friendly json notation on export to file.
            This may result in loss of data precision, but is more userfriendly.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.ModuleExport">
            <summary>
            Whether this setting applies to module scope file export.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.DisableValidation">
            <summary>
            Do not apply the validation script when changing values.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.DisableHandler">
            <summary>
            Do not run the handler script when changing values.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.PassThru">
            <summary>
            Return the changed configuration setting.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.EnableException">
            <summary>
            Enable throwing exceptions.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._Config">
            <summary>
            The configuration item changed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._KillIt">
            <summary>
            Whether execution should be terminated silently.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._Initialize">
            <summary>
            Whether this is an initialization execution.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._Persisted">
            <summary>
            Whether persisted values need to be restored.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._Exists">
            <summary>
            Whether the setting already exists.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._PolicyEnforced">
            <summary>
            The setting to be affected was enforced by policy and cannot be changed by the user.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._NameModule">
            <summary>
            Processed name of module.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._NameName">
            <summary>
            Processed name of setting within module.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._NameFull">
            <summary>
            Processed full name of setting.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._ValidationErrorMessage">
            <summary>
            The reason validation failed.
            Filled by ApplyValue.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.BeginProcessing">
            <summary>
            Implements the begin action of Set-PSFConfig
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.ProcessRecord">
            <summary>
            Implements the process action of Set-PSFConfig
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.ApplyValue(System.Object)">
            <summary>
            Applies a value to a configuration item, invoking validation and handler scriptblocks.
            </summary>
            <param name="Value">The value to apply</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.ApplyCommonSettings">
            <summary>
            Abstracts out 
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand">
            <summary>
            Implements the Write-Message command, performing message handling and loggin
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Level">
            <summary>
            This parameter represents the verbosity of the message. The lower the number, the more important it is for a human user to read the message.
            By default, the levels are distributed like this:
            - 1-3 Direct verbose output to the user (using Write-Host)
            - 4-6 Output only visible when requesting extra verbosity (using Write-Verbose)
            - 1-9 Debugging information, written using Write-Debug
            
            In addition, it is possible to select the level "Warning" which moves the message out of the configurable range:
            The user will always be shown this message, unless he silences the entire verbosity.
            
            Possible levels:
            Critical (1), Important / Output / Host (2), Significant (3), VeryVerbose (4), Verbose (5), SomewhatVerbose (6), System (7), Debug (8), InternalComment (9), Warning (666)
            Either one of the strings or its respective number will do as input.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Message">
            <summary>
            The message to write/log. The function name and timestamp will automatically be prepended.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Tag">
            <summary>
            Tags to add to the message written.
            This allows filtering and grouping by category of message, targeting specific messages.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.FunctionName">
            <summary>
            The name of the calling function.
            Will be automatically set, but can be overridden when necessary.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.ModuleName">
            <summary>
            The name of the module, the calling function is part of.
            Will be automatically set, but can be overridden when necessary.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.File">
            <summary>
            The file in which Write-Message was called.
            Will be automatically set, but can be overridden when necessary.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Line">
            <summary>
            The line on which Write-Message was called.
            Will be automatically set, but can be overridden when necessary.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.ErrorRecord">
            <summary>
            If an error record should be noted with the message, add the full record here.
            Especially designed for use with Warning-mode, it can legally be used in either mode.
            The error will be added to the $Error variable and enqued in the logging/debugging system.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Exception">
            <summary>
            Allows specifying an inner exception as input object. This will be passed on to the logging and used for messages.
            When specifying both ErrorRecord AND Exception, Exception wins, but ErrorRecord is still used for record metadata.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Once">
            <summary>
            Setting this parameter will cause this function to write the message only once per session.
            The string passed here and the calling function's name are used to create a unique ID, which is then used to register the action in the configuration system.
            Thus will the lockout only be written if called once and not burden the system unduly.
            This lockout will be written as a hidden value, to see it use Get-DbaConfig -Force.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.OverrideExceptionMessage">
            <summary>
            Disables automatic appending of exception messages.
            Use in cases where you already have a speaking message interpretation and do not need the original message.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Target">
            <summary>
            Add the object the message is all about, in order to simplify debugging / troubleshooting.
            For example, when calling this from a function targeting a remote computer, the computername could be specified here, allowing all messages to easily be correlated to the object processed.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.EnableException">
            <summary>
            This parameters disables user-friendly warnings and enables the throwing of exceptions.
            This is less user friendly, but allows catching exceptions in calling scripts.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Breakpoint">
            <summary>
            Enables breakpoints on the current message. By default, setting '-Debug' will NOT cause an interrupt on the current position.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._timestamp">
            <summary>
            The start time of the cmdlet
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._silent">
            <summary>
            Whether this cmdlet is run in silent mode
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._fromStopFunction">
            <summary>
            Whether this cmdlet was called by Stop-Function
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._callStack">
            <summary>
            The current callstack
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._stackDepth">
            <summary>
            How many items exist on the callstack
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._message">
            <summary>
            The message to write
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._messageSimple">
            <summary>
            The message simplified without timestamps. Used for logging.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._messageColor">
            <summary>
            The message to write in color
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._messageDeveloper">
            <summary>
            Non-colored version of developermode
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._messageDeveloperColor">
            <summary>
            Colored version of developermode
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._writeHostScript">
            <summary>
            Scriptblock that writes the host messages
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._Tags">
            <summary>
            List of tags to process
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._isDebug">
            <summary>
            Whether debug mode is enabled
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._errorQualifiedMessage">
            <summary>
            The input message with the error content included if desired
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._MessageSystem">
            <summary>
            The final message to use for internal logging
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._MessageStreams">
            <summary>
            The final message to use for writing to streams, such as verbose or warning
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._MessageHost">
            <summary>
            The final message to use for host messages (write using Write-HostColor)
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._BreadCrumbsString">
            <summary>
            Provide breadcrumb queue of the callstack
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._BreadCrumbsStringColored">
            <summary>
            Provide a breadcrumb queue of the callstack in color tags
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.BeginProcessing">
            <summary>
            Processes the begin phase of the cmdlet
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.ProcessRecord">
            <summary>
            Processes the process phase of the cmdlet
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.ResolveTarget(System.Object)">
            <summary>
            Processes the target transform rules on an input object
            </summary>
            <param name="Item">The item to transform</param>
            <returns>The transformed object</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.ResolveException(System.Exception)">
            <summary>
            Processes the specified exception specified
            </summary>
            <param name="Item">The exception to process</param>
            <returns>The transformed exception</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.ResolveLevel(Sqlcollaborative.Dbatools.Message.MessageLevel)">
            <summary>
            Processs the input level and apply policy and rules
            </summary>
            <param name="Level">The original level of the message</param>
            <returns>The processed level</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.GetMessage">
            <summary>
            Builds the message item for display of Verbose, Warning and Debug streams
            </summary>
            <returns>The message to return</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.GetMessageSimple">
            <summary>
            Builds the base message for internal system use.
            </summary>
            <returns>The message to return</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.GetMessageColor">
            <summary>
            Builds the message item if needed and returns it
            </summary>
            <returns>The message to return</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.GetMessageDeveloper">
            <summary>
            Non-host output in developermode
            </summary>
            <returns>The string to write on messages that don't go straight to Write-HostColor</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.GetMessageDeveloperColor">
            <summary>
            Host output in developermode
            </summary>
            <returns>The string to write on messages that go straight to Write-HostColor</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Computer.DiskSpace">
            <summary>
            Data Container for the output of Get-DbaDiskSpace
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.ComputerName">
            <summary>
            The computer that was scanned
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.Name">
            <summary>
            Name of the disk
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.Label">
            <summary>
            Label of the disk
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.Capacity">
            <summary>
            What's the total capacity of the disk?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.Free">
            <summary>
            How much is still free?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.PercentFree">
            <summary>
            How much is still free
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.BlockSize">
            <summary>
            What blocksize is the object set to
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.FileSystem">
            <summary>
            What filesystem is installed on the system
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.Type">
            <summary>
            What kind of drive is it?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.IsSqlDisk">
            <summary>
            Whether the drive is a sql disk. Nullable, because it is an optional property and may not always be included, thus a third state is necessary.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.Server">
            <summary>
            The computer that was scanned. Legacy-Name
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.DriveType">
            <summary>
            The type of drive this is in the legacy string notation
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.SizeInBytes">
            <summary>
            The total capacity in Bytes
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.FreeInBytes">
            <summary>
            The free space in Bytes
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.SizeInKB">
            <summary>
            The total capacity in KB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.FreeInKB">
            <summary>
            The free space in KB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.SizeInMB">
            <summary>
            The total capacity in MB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.FreeInMB">
            <summary>
            The free space in MB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.SizeInGB">
            <summary>
            The total capacity in GB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.FreeInGB">
            <summary>
            The free space in GB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.SizeInTB">
            <summary>
            The total capacity in TB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.FreeInTB">
            <summary>
            The free space in TB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.SizeInPB">
            <summary>
            The total capacity in PB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.FreeInPB">
            <summary>
            The free space in PB
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Computer.DriveType">
            <summary>
            What kind of drive are you?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.DriveType.Unknown">
            <summary>
            The drive type is not actually known
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.DriveType.NoRootDirectory">
            <summary>
            The drive has no root directory
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.DriveType.RemovableDisk">
            <summary>
            The drive is a removable disk
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.DriveType.LocalDisk">
            <summary>
            The drive is a local disk
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.DriveType.NetworkDrive">
            <summary>
            The drive is a network drive
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.DriveType.CompactDisk">
            <summary>
            The drive is a compact disk
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.DriveType.RAMDisk">
            <summary>
            The drive is a RAM disk
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Computer.PageFileSetting">
            <summary>
            Data container, listing pagefile settings.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.ComputerName">
            <summary>
            The name of the computer
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.AutoPageFile">
            <summary>
            Whether Automatic PageFile management is enabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.FileName">
            <summary>
            The pagefile name
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.Status">
            <summary>
            The pagefile status
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.SystemManaged">
            <summary>
            Whether the pagefile is system managed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.LastModified">
            <summary>
            When were the settings last changed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.LastAccessed">
            <summary>
            When were the settings last accessed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.AllocatedBaseSize">
            <summary>
            The base allocated pagefile size in MB
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.InitialSize">
            <summary>
            The initial pagefile size in MB
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.MaximumSize">
            <summary>
            The maximum pagefile size in MB
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.PeakUsage">
            <summary>
            The maximum percent of the pagefile limit that has been used
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.CurrentUsage">
            <summary>
            The currently used percentage of the pagefile limit that is in use.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Configuration.Config">
            <summary>
            Configuration Manager as well as individual configuration object.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.Name">
            <summary>
            The Name of the setting
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.FullName">
            <summary>
            The full name of the configuration entry, comprised of both Module and Name.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.Module">
            <summary>
            The module of the setting. Helps being able to group configurations.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.Description">
            <summary>
            A description of the specific setting
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.Type">
            <summary>
            The data type of the value stored in the configuration element.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.Value">
            <summary>
            The value stored in the configuration element
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.SafeValue">
            <summary>
            The value stored in the configuration element, but without deserializing objects.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.Unchanged">
            <summary>
            Whether the value of the configuration setting has been changed since its initialization.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.Handler">
            <summary>
            The handler script that is run whenever the configuration value is set.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.Validation">
            <summary>
            Validates the user input
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.Hidden">
            <summary>
            Setting this to true will cause the element to not be discovered unless using the '-Force' parameter on "Get-DbaConfig"
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.Initialized">
            <summary>
            Whether the setting has been initialized. This handles module imports and avoids modules overwriting settings when imported in multiple runspaces.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.PolicySet">
            <summary>
            Whether this setting was set by policy
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.PolicyEnforced">
            <summary>
            Whether this setting was set by policy and forbids changes to the configuration.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.SimpleExport">
            <summary>
            Enabling this causes export to json to use simple json serialization for data transmission.
            This is suitable for simple data that is not sensitive to conversion losses.
            Simple export leads to exports more easily readable to the human eye.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.ModuleExport">
            <summary>
            Whether this setting should be exported to a module specific file when exporting to json by modulename.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.RegistryData">
            <summary>
            The finalized value to put into the registry value when using policy to set this setting.
            Deprecated property.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.DefaultValue">
            <summary>
            The default value the configuration item was set to when initializing
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.Config.SetPersistedValue(Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType,System.String)">
            <summary>
            Applies the persisted value to the configuration item.
            This method should only be called by PSFramework internals
            </summary>
            <param name="Type">The type of data being specified</param>
            <param name="ValueString">The value string to register</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.Config.ResetValue">
            <summary>
            Resets the configuration value to its configured default value
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Configuration.ConfigScope">
            <summary>
            The location where a setting was applied
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigScope.UserDefault">
            <summary>
            The configuration is set as default value for the user
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigScope.UserMandatory">
            <summary>
            The configuration is enforced for the user
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigScope.SystemDefault">
            <summary>
            The configuration is set as default value for all users on the system
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigScope.SystemMandatory">
            <summary>
            The configuration is enforced for all users on the system.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigScope.FileUserLocal">
            <summary>
            The configuration is stored as Json in the per user local machine config directory.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigScope.FileUserShared">
            <summary>
            The configuration is stored as Json in the per user config directory shared across machines.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigScope.FileSystem">
            <summary>
            The configuration is stored as Json in the local computer config directory.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost">
            <summary>
            Host class providing static configuration settings that are constant across all runspaces within the process.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.Configurations">
            <summary>
            Hashtable containing all the configuration entries
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.Validation">
            <summary>
            Hashtable containing all the registered validations
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.ImportFromRegistryDone">
            <summary>
            Whether the import from registry has been completed. Prevents multiple imports and overwrites when importing the module multiple times.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.ConvertToPersistedValue(System.Object)">
            <summary>
            Converts any object into its persisted state.
            </summary>
            <param name="Item">The item to convert.</param>
            <returns>Its persisted state representation.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.ConvertFromPersistedValue(System.String,Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType)">
            <summary>
            Converts a persisted value back to its original data type
            </summary>
            <param name="PersistedValue">The value in its persisted state</param>
            <param name="Type">The type of the persisted value</param>
            <returns>The natural state of the value originally persisted</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.ConvertFromPersistedValue(System.String)">
            <summary>
            Converts a persisted value back to its original data type
            </summary>
            <param name="TypeQualifiedPersistedValue">The value in its persisted state, with a prefixed type identifier.</param>
            <returns>The natural state of the value originally persisted</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.Utf8ToBase64(System.String)">
            <summary>
            Converts a plain text into a base64 string
            </summary>
            <param name="Value">The string to convert</param>
            <returns>base64 encoded version of string.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.Base64ToUtf8(System.String)">
            <summary>
            Converts a base64 encoded string into plain text
            </summary>
            <param name="Value">The string to convert</param>
            <returns>Plain Text string</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue">
            <summary>
            Contains all information about a configuration item's value
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.Value">
            <summary>
            The runtime value of the setting.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.PersistedValue">
            <summary>
            The value in its persisted state
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.PersistedType">
            <summary>
            The kind of 
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.TypeQualifiedPersistedValue">
            <summary>
            The type qualified representation of the persisted value
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.SafeValue">
            <summary>
            Ensures wanton Get-PSFConfig will not deserialize persisted objects that might have registered deserialization in their module.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue._Value">
            <summary>
            Internal storage for the Value property
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue._PersistedValue">
            <summary>
            Internal storage for the PersistedValue property
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.ToString">
            <summary>
            The string representation of its actual value
            </summary>
            <returns>Returns the type-qualified string representation of its value</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.#ctor(System.String,Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType)">
            <summary>
            Creates a value object from persisted data
            </summary>
            <param name="PersistedValue">The value that will be persisted</param>
            <param name="PersistedType">The type of the value to be persisted</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.#ctor(System.Object)">
            <summary>
            Creates a value object from runtime data
            </summary>
            <param name="Value">The value that will be stored</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType">
            <summary>
            The data types supported by the configuration system.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Unknown">
            <summary>
            An unknown type, should be prevented
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Null">
            <summary>
            The value is as empty as the void.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Bool">
            <summary>
            The value is of a true/false kind
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Int">
            <summary>
            The value is a regular integer
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Double">
            <summary>
            The value is a double numeric value
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Long">
            <summary>
            The value is a long type
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.String">
            <summary>
            The value is a common string
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Timespan">
            <summary>
            The value is a regular timespan
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Datetime">
            <summary>
            The value is a plain datetime
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.ConsoleColor">
            <summary>
            The value is a fancy console color
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Array">
            <summary>
            The value is an array full of booty
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Hashtable">
            <summary>
            The value is a hashtable
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Object">
            <summary>
            The value is something indeterminate, but possibly complex
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Connection.ConnectionHost">
            <summary>
            Provides static tools for managing connections
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.Connections">
            <summary>
            List of all registered connections.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.BadConnectionTimeout">
            <summary>
            The time interval that must pass, before a connection using a known to not work connection protocol is reattempted
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableCache">
            <summary>
            Globally disables all caching done by the Computer Management functions.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableBadCredentialCache">
            <summary>
            Disables the caching of bad credentials. dbatools caches bad logon credentials for wmi/cim and will not reuse them.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableCredentialAutoRegister">
            <summary>
            Disables the automatic registration of working credentials. dbatools will caches the last working credential when connecting using wmi/cim and will use those rather than using known bad credentials
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.OverrideExplicitCredential">
            <summary>
            Enabling this will force the use of the last credentials known to work, rather than even trying explicit credentials.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.EnableCredentialFailover">
            <summary>
            Enables automatic failover to working credentials, when passed credentials either are known, or turn out to not work.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableCimPersistence">
            <summary>
            Globally disables the persistence of Cim sessions used to connect to a target system.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableConnectionCimRM">
            <summary>
            Whether the CM connection using Cim over WinRM is disabled globally
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableConnectionCimDCOM">
            <summary>
            Whether the CM connection using Cim over DCOM is disabled globally
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableConnectionWMI">
            <summary>
            Whether the CM connection using WMI is disabled globally
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableConnectionPowerShellRemoting">
            <summary>
            Whether the CM connection using PowerShell Remoting is disabled globally
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.SqlConnectionTimeout">
            <summary>
            The number of seconds before a sql connection attempt times out
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.PSSessions">
            <summary>
            List of all session containers used to maintain a cache
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ConnectionHost.PSSessionGet(System.Guid,System.String)">
            <summary>
            Returns a registered session for a given computer on a given runspace. Returns null if nothing is registered.
            </summary>
            <param name="Runspace">The host runspace that opened the session</param>
            <param name="ComputerName">The computer connected to</param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ConnectionHost.PSSessionSet(System.Guid,System.String,System.Management.Automation.Runspaces.PSSession)">
            <summary>
            Registeres a remote session under the owning runspace in its respective computer name
            </summary>
            <param name="Runspace">The runspace that owns the session</param>
            <param name="ComputerName">The computer the session connects to</param>
            <param name="Session">The session object</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ConnectionHost.PSSessionPurgeExpired">
            <summary>
            Searches the cache for an expired remoting session and purges it. After purging it from the list, it still needs to be closed!
            </summary>
            <returns>The session purged that then needs to be closed</returns>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ConnectionHost.PSSessionCountExpired">
            <summary>
            The number of expired sessions 
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.PSSessionTimeout">
            <summary>
            The time until established connections will be considered expired (if available)
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.PSSessionCacheEnabled">
            <summary>
            Whether sessions should be cached at all
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Connection.ManagementConnection">
            <summary>
            Contains management connection information for a windows server
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.ComputerName">
            <summary>
            The computer to connect to
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.DisableBadCredentialCache">
            <summary>
            Locally disables the caching of bad credentials
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.DisableCredentialAutoRegister">
            <summary>
            Locally disables the caching of working credentials
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.OverrideExplicitCredential">
            <summary>
            Locally overrides explicit credentials with working ones that were cached
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.EnableCredentialFailover">
            <summary>
            Locally enables automatic failover to working credentials, when passed credentials either are known, or turn out to not work.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.DisableCimPersistence">
            <summary>
            Locally disables the persistence of Cim sessions used to connect to a target system.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.DisabledConnectionTypes">
            <summary>
            Connectiontypes that will never be used
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.RestoreDefaultConfiguration">
            <summary>
            Restores all deviations from public policy back to default
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.OverrideConnectionPolicy">
            <summary>
            Whether this connection adhers to the global connection lockdowns or not
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.CimRM">
            <summary>
            Did the last connection attempt using CimRM work?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.LastCimRM">
            <summary>
            When was the last connection attempt using CimRM?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.CimDCOM">
            <summary>
            Did the last connection attempt using CimDCOM work?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.LastCimDCOM">
            <summary>
            When was the last connection attempt using CimRM?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.Wmi">
            <summary>
            Did the last connection attempt using Wmi work?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.LastWmi">
            <summary>
            When was the last connection attempt using CimRM?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.PowerShellRemoting">
            <summary>
            Did the last connection attempt using PowerShellRemoting work?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.LastPowerShellRemoting">
            <summary>
            When was the last connection attempt using CimRM?
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.ReportSuccess(Sqlcollaborative.Dbatools.Connection.ManagementConnectionType)">
            <summary>
            Report the successful connection against the computer of this connection
            </summary>
            <param name="Type">What connection type succeeded?</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.ReportFailure(Sqlcollaborative.Dbatools.Connection.ManagementConnectionType)">
            <summary>
            Report the failure of connecting to the target computer
            </summary>
            <param name="Type">What connection type failed?</param>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.Credentials">
            <summary>
            Any registered credentials to use on the connection.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.WindowsCredentialsAreBad">
            <summary>
            Whether the default windows credentials are known to not work against the target.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.UseWindowsCredentials">
            <summary>
            Whether windows credentials are known to be good. Do not build conditions on them being false, just on true.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.KnownBadCredentials">
            <summary>
            Credentials known to not work. They will not be used when specified.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.AddBadCredential(System.Management.Automation.PSCredential)">
            <summary>
            Adds a credentials object to the list of credentials known to not work.
            </summary>
            <param name="Credential">The bad credential that must be punished</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.AddGoodCredential(System.Management.Automation.PSCredential)">
            <summary>
            Reports a credentials object as being legit.
            </summary>
            <param name="Credential">The functioning credential that we may want to use again</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetCredential(System.Management.Automation.PSCredential)">
            <summary>
            Calculates, which credentials to use. Will consider input, compare it with know not-working credentials or use the configured working credentials for that.
            </summary>
            <param name="Credential">Any credential object a user may have explicitly specified.</param>
            <returns>The Credentials to use</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.IsBadCredential(System.Management.Automation.PSCredential)">
            <summary>
            Tests whether the input credential is on the list known, bad credentials
            </summary>
            <param name="Credential">The credential to test</param>
            <returns>True if the credential is known to not work, False if it is not yet known to not work</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.RemoveBadCredential(System.Management.Automation.PSCredential)">
            <summary>
            Removes an item from the list of known bad credentials
            </summary>
            <param name="Credential">The credential to remove</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetConnectionType(Sqlcollaborative.Dbatools.Connection.ManagementConnectionType,System.Boolean)">
            <summary>
            Returns the next connection type to try.
            </summary>
            <param name="ExcludedTypes">Exclude any type already tried and failed</param>
            <param name="Force">Overrides the timeout on bad connections</param>
            <returns>The next type to try.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetConnectionTypesTimed(System.DateTime)">
            <summary>
            Returns a list of all available connection types whose inherent timeout has expired.
            </summary>
            <param name="Timestamp">All last connection failures older than this point in time are considered to be expired</param>
            <returns>A list of all valid connection types</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetConnectionTypesTimed(System.TimeSpan)">
            <summary>
            Returns a list of all available connection types whose inherent timeout has expired.
            </summary>
            <param name="Timespan">All last connection failures older than this far back into the past are considered to be expired</param>
            <returns>A list of all valid connection types</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.#ctor">
            <summary>
            Creates a new, empty connection object. Necessary for serialization.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.#ctor(System.String)">
            <summary>
            Creates a new default connection object, containing only its computer's name and default results.
            </summary>
            <param name="ComputerName">The computer targeted. Will be forced to lowercase.</param>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.CimWinRMOptions">
            <summary>
            The options ot use when establishing a CIM Session
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetDefaultCimWsmanOptions">
            <summary>
            Returns the default wsman options object
            </summary>
            <returns>Something very default-y</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetCimRMInstance(System.Management.Automation.PSCredential,System.String,System.String)">
            <summary>
            Get all cim instances of the appropriate class using WinRM
            </summary>
            <param name="Credential">The credentiuls to use for the connection.</param>
            <param name="Class">The class to query.</param>
            <param name="Namespace">The namespace to look in (defaults to root\cimv2).</param>
            <returns>Hopefully a mountainload of CimInstances</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.QueryCimRMInstance(System.Management.Automation.PSCredential,System.String,System.String,System.String)">
            <summary>
            Get all cim instances matching the query using WinRM
            </summary>
            <param name="Credential">The credentiuls to use for the connection.</param>
            <param name="Query">The query to use requesting information.</param>
            <param name="Dialect">Defaults to WQL.</param>
            <param name="Namespace">The namespace to look in (defaults to root\cimv2).</param>
            <returns></returns>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.CimDComOptions">
            <summary>
            The options ot use when establishing a CIM Session
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetDefaultCimDcomOptions">
            <summary>
            Returns the default DCom options object
            </summary>
            <returns>Something very default-y</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetCimDComInstance(System.Management.Automation.PSCredential,System.String,System.String)">
            <summary>
            Get all cim instances of the appropriate class using DCOM
            </summary>
            <param name="Credential">The credentiuls to use for the connection.</param>
            <param name="Class">The class to query</param>
            <param name="Namespace">The namespace to look in (defaults to root\cimv2)</param>
            <returns>Hopefully a mountainload of CimInstances</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.QueryCimDCOMInstance(System.Management.Automation.PSCredential,System.String,System.String,System.String)">
            <summary>
            Get all cim instances matching the query using DCOM
            </summary>
            <param name="Credential">The credentiuls to use for the connection.</param>
            <param name="Query">The query to use requesting information.</param>
            <param name="Dialect">Defaults to WQL.</param>
            <param name="Namespace">The namespace to look in (defaults to root\cimv2).</param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.ToString">
            <summary>
            Simple string representation
            </summary>
            <returns>Returns the computerName it is connection for</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Connection.ManagementConnectionProtocolState">
            <summary>
            The various types of state a connection-protocol may have
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionProtocolState.Unknown">
            <summary>
            The default initial state, before any tests are performed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionProtocolState.Success">
            <summary>
            A successful connection was last established
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionProtocolState.Error">
            <summary>
            Connecting using the relevant protocol failed last it was tried
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionProtocolState.Disabled">
            <summary>
            The relevant protocol has been disabled and should not be used
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Connection.ManagementConnectionType">
            <summary>
            The various ways to connect to a windows server fopr management purposes.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionType.None">
            <summary>
            No Connection-Type
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionType.CimRM">
            <summary>
            Cim over a WinRM connection
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionType.CimDCOM">
            <summary>
            Cim over a DCOM connection
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionType.Wmi">
            <summary>
            WMI Connection
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionType.PowerShellRemoting">
            <summary>
            Connecting with PowerShell remoting and performing WMI queries locally
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Connection.PSSessionContainer">
            <summary>
            The container that lists all sessions for a given runspace
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.Runspace">
            <summary>
            The runspace that owns the sessions
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.CountExpired">
            <summary>
            The count of expired sessions registered
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.Sessions">
            <summary>
            List of sessions and their associated computer names
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.ConnectionTimestamps">
            <summary>
            List of timestamps, when the last command was run against them
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.#ctor(System.Guid)">
            <summary>
            Creates a list of sessions the current runspace is connected to.
            </summary>
            <param name="Runspace">The Guid of the runspace that is the owner of the registered sessions</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.Get(System.String)">
            <summary>
            Returns the requested session.
            </summary>
            <param name="ComputerName">The name of the host whose connection to retrieve</param>
            <returns>The established connection to the host, null if none exists.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.Set(System.String,System.Management.Automation.Runspaces.PSSession)">
            <summary>
            Sets a session and writes its timestamp to the cache
            </summary>
            <param name="ComputerName">The hostname it connects to.</param>
            <param name="Session">The session that is being registered.</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.GetExpiredNames">
            <summary>
            Returns the name of hostnames with expired sessions
            </summary>
            <returns>THe hostnames whose session has expired</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.PurgeExpiredSession">
            <summary>
            Removes an expired session from the cache, an returns it, so it can be properly closed.
            </summary>
            <returns>Returns a session to disconnect</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Connection.SqlConnectionProtocol">
            <summary>
            The protocol to connect over via SMO
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.SqlConnectionProtocol.Any">
            <summary>
            Connect using any protocol available
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.SqlConnectionProtocol.TCP">
            <summary>
            Connect using TCP/IP
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.SqlConnectionProtocol.NP">
            <summary>
            Connect using named pipes or shared memory
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Database.BackupHistory">
            <summary>
            Object containing the information about the history of mankind ... or a database backup. WHo knows.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.ComputerName">
            <summary>
            The name of the computer running MSSQL Server
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.InstanceName">
            <summary>
            The Instance that was queried
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.SqlInstance">
            <summary>
            The full Instance name as seen from outside
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.Database">
            <summary>
            The Database that was backed up
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.UserName">
            <summary>
            The user that is running the backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.Start">
            <summary>
            When was the backup started
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.End">
            <summary>
            When did the backup end
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.Duration">
            <summary>
            What was the longest duration among the backups
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.Path">
            <summary>
            Where is the backup stored
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.TotalSize">
            <summary>
            What is the total size of the backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.CompressedBackupSize">
            <summary>
            What is the total compressesed size of the backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.CompressionRatio">
            <summary>
            What is the ratio of total size to compressed size of the backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.Type">
            <summary>
            The kind of backup this was
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.BackupSetId">
            <summary>
            The ID for the Backup job
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.DeviceType">
            <summary>
            What kind of backup-device was the backup stored to
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.Software">
            <summary>
            What is the name of the backup software?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.FullName">
            <summary>
            The full name of the backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.FileList">
            <summary>
            The files that are part of this backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.Position">
            <summary>
            The position of the backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.FirstLsn">
            <summary>
            The first Log Sequence Number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.DatabaseBackupLsn">
            <summary>
            The Log Squence Number that marks the beginning of the backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.CheckpointLsn">
            <summary>
            The checkpoint's Log Sequence Number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.LastLsn">
            <summary>
            The last Log Sequence Number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.SoftwareVersionMajor">
            <summary>
            The primary version number of the Sql Server
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.IsCopyOnly">
            <summary>
            Was the backup performed with the CopyOnlyOption
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.LastRecoveryForkGUID">
            <summary>
            Recovery Fork backup was takeon
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.RecoveryModel">
            <summary>
            Recovery Model of the database when backup was taken
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Database.Dependency">
            <summary>
            Class containing all dependency information over a database object
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.ComputerName">
            <summary>
            The name of the SQL server from whence the query came
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.ServiceName">
            <summary>
            Name of the service running the database containing the dependency
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.SqlInstance">
            <summary>
            The Instance the database containing the dependency is running in.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Dependent">
            <summary>
            The name of the dependent
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Type">
            <summary>
            The kind of object the dependent is
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Owner">
            <summary>
            The owner of the dependent (usually the Database)
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.IsSchemaBound">
            <summary>
            Whether the dependency is Schemabound. If it is, then the creation statement order is of utmost importance.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Parent">
            <summary>
            The immediate parent of the dependent. Useful in multi-tier dependencies.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.ParentType">
            <summary>
            The type of object the immediate parent is.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Script">
            <summary>
            The script used to create the object.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Tier">
            <summary>
            The tier in the dependency hierarchy tree. Used to determine, which dependency must be applied in which order.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Object">
            <summary>
            The smo object of the dependent.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Urn">
            <summary>
            The Uniform Resource Name of the dependent.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.OriginalResource">
            <summary>
            The object of the original resource, from which the dependency hierachy has been calculated.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord">
            <summary>
            An error record written by dbatools
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.CategoryInfo">
            <summary>
            The category of the error
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.ErrorDetails">
            <summary>
            The details on the error
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.Exception">
            <summary>
            The actual exception thrown
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.FullyQualifiedErrorId">
            <summary>
            The specific error identity, used to identify the target
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.InvocationInfo">
            <summary>
            The details of how this was called.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.ScriptStackTrace">
            <summary>
            The script's stacktrace
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.TargetObject">
            <summary>
            The object being processed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.FunctionName">
            <summary>
            The name of the function throwing the error
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.Timestamp">
            <summary>
            When was the error thrown
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.Message">
            <summary>
            The message that was written in a userfriendly manner
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.Runspace">
            <summary>
            The runspace the error occured on.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.#ctor">
            <summary>
            Create an empty record
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.#ctor(System.Management.Automation.ErrorRecord,System.String,System.DateTime,System.String)">
            <summary>
            Create a filled out error record
            </summary>
            <param name="Record">The original error record</param>
            <param name="FunctionName">The function that wrote the error</param>
            <param name="Timestamp">When was the error generated</param>
            <param name="Message">What message was passed when writing the error</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.#ctor(System.Management.Automation.ErrorRecord,System.String,System.DateTime,System.String,System.Guid)">
            <summary>
            Create a filled out error record
            </summary>
            <param name="Record">The original error record</param>
            <param name="FunctionName">The function that wrote the error</param>
            <param name="Timestamp">When was the error generated</param>
            <param name="Message">What message was passed when writing the error</param>
            <param name="Runspace">The ID of the runspace writing the error. Used to separate output between different runspaces in the same process.</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.dbaSystem.DebugHost">
            <summary>
            Hosts static debugging values and methods
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DebugHost.ImportTimeEntries">
            <summary>
            Lists the duration for the last import of dbatools.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.DebugHost.ImportTime">
            <summary>
            Returns the calculated time each phase took during the last import of dbatool.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.dbaSystem.StartTimeEntry">
            <summary>
            Entry containing the information of a step during the import sequence
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.StartTimeEntry.Action">
            <summary>
            The action that has been taken
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.StartTimeEntry.Timestamp">
            <summary>
            When was the action taken?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.StartTimeEntry.Runspace">
            <summary>
            The runspace the entry was written on
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.dbaSystem.StartTimeEntry.#ctor(System.String,System.DateTime,System.Guid)">
            <summary>
            Creates a new StartTimeEntry
            </summary>
            <param name="Action">The action that has been taken</param>
            <param name="Timestamp">When was the action taken?</param>
            <param name="Runspace">The runspace the entry was written on</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.dbaSystem.StartTimeResult">
            <summary>
            The processed result how long a given step took
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.StartTimeResult.Action">
            <summary>
            What action was taken?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.StartTimeResult.Duration">
            <summary>
            How long did things take?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.StartTimeResult.Start">
            <summary>
            When did this action start?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.StartTimeResult.End">
            <summary>
            When did this action end?
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.dbaSystem.StartTimeResult.#ctor(System.String,System.DateTime,System.DateTime)">
            <summary>
            Creates a new StartTimeResult with all values preconfigured
            </summary>
            <param name="Action">The action that was taken</param>
            <param name="Start">When did the action start?</param>
            <param name="End">When did the action end?</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.dbaSystem.SystemHost">
            <summary>
            Provides system-wide static resources regarding the dbatools system runtime in general
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.SystemHost.UnattendedMode">
            <summary>
            When this is set to true, functions must assume dbatools is in unattended mode. May not ask for user input of any kind.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.SystemHost.ModuleBase">
            <summary>
            Path where the module was located when imported
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.SystemHost.ModuleImported">
            <summary>
            Flag whether the module has ever been imported in the current process. If that is true, several things (such as importing libraries) is no longer necessary and will be skipped on import.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply">
            <summary>
            The reply the browser service gave
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.MachineName">
            <summary>
            The machine name of the computer
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.ComputerName">
            <summary>
            the computername of the computer
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.SqlInstance">
            <summary>
            The instance running on the computer
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.InstanceName">
            <summary>
            The name of the instance, running on the computer
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.TCPPort">
            <summary>
            The port number the instance is running under
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.Version">
            <summary>
            The version of the SQL Server
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.IsClustered">
            <summary>
            Whether the instance is part of a cluster or no.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.ToString">
            <summary>
            Override in order to make it look neater in PowerShell
            </summary>
            <returns></returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Discovery.DbaInstanceAvailability">
            <summary>
            Indiciator for whether an instance is known to be available or not
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceAvailability.Unknown">
            <summary>
            It is not known, whether the instance is available or not
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceAvailability.Available">
            <summary>
            The instance is known to be available
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceAvailability.Unavailable">
            <summary>
            The instance is known to be not available
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Discovery.DbaInstanceConfidenceLevel">
            <summary>
            How high is our confidence that this is a valid instance?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceConfidenceLevel.None">
            <summary>
            No confidence at all. There is virtually no way for this to be an instance
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceConfidenceLevel.Low">
            <summary>
            We have a few indications, but couldn't follow them up
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceConfidenceLevel.Medium">
            <summary>
            We're fairly sure this is legit, but can't guarantee it
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceConfidenceLevel.High">
            <summary>
            This absolutely is an instance
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Discovery.DbaInstanceDiscoveryType">
            <summary>
            What discovery mechanisms to use
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceDiscoveryType.IPRange">
            <summary>
            We shall sweep the network for instances, by targeting every IP within a range.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceDiscoveryType.Domain">
            <summary>
            We shall search for SQL SPNs in active directory
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceDiscoveryType.DataSourceEnumeration">
            <summary>
            We shall use the SSMS Data Sizrce Enumeration mechanism and hope for the best
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceDiscoveryType.All">
            <summary>
            We shall use all tools in our control to find stuff
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport">
            <summary>
            The report on a discovered instance
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.MachineName">
            <summary>
            The computername of the underlying machine. Usually equal to the computername, but may differ in case of clusters
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.ComputerName">
            <summary>
            The computername of the target
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.InstanceName">
            <summary>
            The name of the instance
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.FullName">
            <summary>
            The full server instance name
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.SqlInstance">
            <summary>
            The full name usable to connect via SMO
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.Port">
            <summary>
            The port number the server listens on
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.Timestamp">
            <summary>
            When the scan was concluded
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.TcpConnected">
            <summary>
            Was a TCP connect successful?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.SqlConnected">
            <summary>
            Was a connection via SQL successful (even if we got access denied)
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.DnsResolution">
            <summary>
            The DNS Resolution object
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.Ping">
            <summary>
            The ping resolution object
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.BrowseReply">
            <summary>
            The reply received from the browse request
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.Services">
            <summary>
            The windows services for the instance
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.SystemServices">
            <summary>
            The SQL Server services that do not belong to that instance alone
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.SPNs">
            <summary>
            Service Principal Names found
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.PortsScanned">
            <summary>
            The ports that have been scanned
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.Availability">
            <summary>
            What we know about its availability
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.Confidence">
            <summary>
            How confident we are, that this is a real instance
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.ScanTypes">
            <summary>
            What we used to scan the instance
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType">
            <summary>
            The mechanisms we use to determine, whether a given host contains a legit instance
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.TCPPort">
            <summary>
            Try connecting to specific ports
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.SqlConnect">
            <summary>
            Try to connect to discovered instances (improves confidence)
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.SqlService">
            <summary>
            Check the windows services on the target
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.DNSResolve">
            <summary>
            Try resolving a computername in DNS
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.SPN">
            <summary>
            Scan the SPNs for the targeted computer
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.Browser">
            <summary>
            Try contacting the local browser service and demand answers
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.Ping">
            <summary>
            See whether you can ping the host
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.All">
            <summary>
            Do EVERYTHING
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.Default">
            <summary>
            Do all the things we consider sane defaults
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Discovery.DbaPortReport">
            <summary>
            We tried to connect to a port, how did it go?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaPortReport.ComputerName">
            <summary>
            The name of the computer connected to
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaPortReport.Port">
            <summary>
            The number of the port we tried to connect to.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaPortReport.IsOpen">
            <summary>
            Whether the port was open
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Discovery.DbaPortReport.#ctor">
            <summary>
            Creates an empty report (serialization uses this)
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Discovery.DbaPortReport.#ctor(System.String,System.Int32,System.Boolean)">
            <summary>
            Creates a filled in report
            </summary>
            <param name="ComputerName">The name of the computer connected to</param>
            <param name="Port">The port we tried to connect to</param>
            <param name="IsOpen">Whether things worked out</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Discovery.DbaPortReport.ToString">
            <summary>
            Displays port connection reports in a user friendly manner
            </summary>
            <returns></returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Exceptions.BloodyHellGiveMeSomethingToWorkWithException">
            <summary>
            An exception that is thrown by parameter classes when given empty input
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Exceptions.BloodyHellGiveMeSomethingToWorkWithException.ParameterClass">
            <summary>
            The parameter class that did the throwing
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Exceptions.BloodyHellGiveMeSomethingToWorkWithException.#ctor(System.String,System.Exception)">
            <summary>
            Creates an exception with a message and a nested exception
            </summary>
            <param name="Message">The message to tell</param>
            <param name="Inner">The inner exception to nest</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Exceptions.BloodyHellGiveMeSomethingToWorkWithException.#ctor(System.String,System.String)">
            <summary>
            Creates an exception with a message and a ParameterClass
            </summary>
            <param name="Message">The message to tell</param>
            <param name="ParameterClass">The Parameter Class that threw the exception</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Exceptions.BloodyHellGiveMeSomethingToWorkWithException.#ctor(System.String,System.Exception,System.String)">
            <summary>
            Creates an exception with a message, a nested exception and a ParameterClass
            </summary>
            <param name="Message">The message to tell</param>
            <param name="Inner">The inner exception to nest</param>
            <param name="ParameterClass">The Parameter Class that threw the exception</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.General.ExecutionMode">
            <summary>
            What kind of mode do you want to run a command in?
            This allows the user to choose how a dbatools function handles a bump in the execution where terminating directly may not be actually mandated.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.General.ExecutionMode.Strict">
            <summary>
            When encountering issues, terminate, or skip the currently processed input, rather than continue.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.General.ExecutionMode.Lazy">
            <summary>
            Continue as able with a best-effort attempt. Simple verbose output should do the rest.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.General.ExecutionMode.Report">
            <summary>
            Continue, but provide output that can be used to identify the operations that had issues.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Maintenance.MaintenanceHost">
            <summary>
            Host class providing access to resources need to perform dbatools maintenance
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceHost.Tasks">
            <summary>
            The register of available tasks.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Maintenance.MaintenanceHost.HasDueTasks">
            <summary>
            Whether there are any due tasks
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Maintenance.MaintenanceHost.GetNextTask(System.String[])">
            <summary>
            Returns the next task to perform. Returns null when there are no more tasks to perform
            </summary>
            <param name="Exclusions">List of tasks not to return, even if they are ready to execute again. This avoids one misconfigured task starving all lower priority tasks</param>
            <returns>The next task to perform.</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Maintenance.MaintenancePriority">
            <summary>
            How high the priority of the task. Higher priority tasks take precedence over low priority tasks.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenancePriority.Trivial">
            <summary>
            This task is completely trivial and can be done whenever there is some spare time for it
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenancePriority.Low">
            <summary>
            The task is not very significant, but should be dealt with at some point
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenancePriority.Medium">
            <summary>
            Average priority task
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenancePriority.High">
            <summary>
            An important task that will take precedence over most other tasks
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenancePriority.Critical">
            <summary>
            A task so critical, that it should be considered to move it to synchronous execution instead.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask">
            <summary>
            An individual task assigned to the maintenance engine
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.Name">
            <summary>
            The name of the task to execute. No duplciates are possible.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.Once">
            <summary>
            Whether the task should be done once only
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.Interval">
            <summary>
            The interval at which the task should be performed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.Delay">
            <summary>
            If the task need not be performed right away, it can be delayed, in order to prioritize more important initialization tasks
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.Registered">
            <summary>
            When was the task first registered. Duplicate registration calls will not increment this value.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.LastExecution">
            <summary>
            When was the task last executed.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.Priority">
            <summary>
            How important is this task?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.ScriptBlock">
            <summary>
            The task code to execute
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.IsDue">
            <summary>
            Whether the task is due and should be executed
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.DbatoolsException">
            <summary>
            Wrapper class that can emulate any exception for purpose of serialization without blowing up the storage space consumed
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsException.GetException">
            <summary>
            Returns the original exception object that we interpreted. This is on purpose not a property, as we want to avoid messing with serialization size.
            </summary>
            <returns>The original exception that got thrown</returns>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.Message">
            <summary>
            The actual Exception Message
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.Source">
            <summary>
            The original source of the Exception
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.StackTrace">
            <summary>
            Where on the callstack did the exception occur?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.TargetSite">
            <summary>
            What was the target site on the code that caused it. This property has been altered to avoid export issues, if a string representation is not sufficient, access the original exception using GetException()
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.HResult">
            <summary>
            The HResult of the exception. Useful in debugging native code errors.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.HelpLink">
            <summary>
            Link to a proper help article.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.Data">
            <summary>
            Additional data that has been appended
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.InnerException">
            <summary>
            The inner exception in a chain of exceptions.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.ExceptionTypeName">
            <summary>
            The full namespace name of the exception that has been wrapped.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.ExceptionData">
            <summary>
            Contains additional properties other exceptions might contain.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.CategoryInfo">
            <summary>
            The category of the error
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.ErrorDetails">
            <summary>
            The details on the error
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.FullyQualifiedErrorId">
            <summary>
            The specific error identity, used to identify the target
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.InvocationInfo">
            <summary>
            The details of how this was called.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.ScriptStackTrace">
            <summary>
            The script's stacktrace
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.TargetObject">
            <summary>
            The object being processed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.FunctionName">
            <summary>
            The name of the function throwing the error
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.Timestamp">
            <summary>
            When was the error thrown
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.Runspace">
            <summary>
            The runspace the error occured on.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.ComputerName">
            <summary>
            The computer the error occured on.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsException.#ctor">
            <summary>
            Creates an empty exception object. Mostly for serialization support
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsException.#ctor(System.Exception)">
            <summary>
            Creates an exception based on an original exception object
            </summary>
            <param name="Except">The exception to wrap around</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsException.#ctor(System.Management.Automation.ErrorRecord)">
            <summary>
            Creates a rich information exception object based on a full error record as recorded by PowerShell
            </summary>
            <param name="Record">The error record to copy from</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsException.#ctor(System.Exception,System.String,System.DateTime,System.String,System.Guid,System.String)">
            <summary>
            Creates a new exception object with rich meta information from the PowerShell runtime.
            </summary>
            <param name="Except">The exception thrown</param>
            <param name="FunctionName">The name of the function in which the error occured</param>
            <param name="Timestamp">When did the error occur</param>
            <param name="Message">The message to add to the exception</param>
            <param name="Runspace">The ID of the runspace from which the exception was thrown. Useful in multi-runspace scenarios.</param>
            <param name="ComputerName">The computer the error occured on.</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsException.#ctor(System.Management.Automation.ErrorRecord,System.String,System.DateTime,System.String,System.Guid,System.String)">
            <summary>
            Creates a new exception object with rich meta information from the PowerShell runtime.
            </summary>
            <param name="Record">The error record written</param>
            <param name="FunctionName">The name of the function in which the error occured</param>
            <param name="Timestamp">When did the error occur</param>
            <param name="Message">The message to add to the exception</param>
            <param name="Runspace">The ID of the runspace from which the exception was thrown. Useful in multi-runspace scenarios.</param>
            <param name="ComputerName">The computer the error occured on.</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsException.ToString">
            <summary>
            Returns a string representation of the exception.
            </summary>
            <returns></returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord">
            <summary>
            Carrier class, designed to hold an arbitrary number of exceptions. Used for exporting to XML in nice per-incident packages.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.Runspace">
            <summary>
            Runspace where shit happened.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.ComputerName">
            <summary>
            The computer name the exception was written on
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.Timestamp">
            <summary>
            When did things go bad?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.FunctionName">
            <summary>
            Name of the function, where fail happened.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.ModuleName">
            <summary>
            The module of the function where fail happened
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.Tags">
            <summary>
            The tags that were applied to the failure
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.Message">
            <summary>
            The message the poor user was shown.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.ExceptionType">
            <summary>
            Displays the name of the exception, the make scanning exceptions easier.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.TargetObject">
            <summary>
            The target object of the first exception in the list, if any
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.Exceptions">
            <summary>
            List of Exceptions that are part of the incident (usually - but not always - only one).
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.#ctor">
            <summary>
            Creates an empty container. Ideal for the homeworker who loves doing it all himself.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.#ctor(Sqlcollaborative.Dbatools.Message.DbatoolsException)">
            <summary>
            Creates a container filled with the first exception.
            </summary>
            <param name="Exception"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.#ctor(System.Guid,System.String,System.DateTime,System.String,System.String,System.Collections.Generic.List{System.String},System.String)">
            <summary>
            Creates a container filled with the meta information but untouched by exceptions
            </summary>
            <param name="Runspace">The runspace where it all happened</param>
            <param name="ComputerName">The computer the error was recorded</param>
            <param name="Timestamp">When did it happen?</param>
            <param name="FunctionName">Where did it happen?</param>
            <param name="ModuleName">The name of the module where fail happened</param>
            <param name="Tags">The tags that were assigned to the failure</param>
            <param name="Message">What did the witness have to say?</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.LogEntry">
            <summary>
            An individual entry for the message log
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Message">
            <summary>
            The message logged
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Type">
            <summary>
            What kind of entry was this?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Timestamp">
            <summary>
            When was the message logged?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.FunctionName">
            <summary>
            What function wrote the message
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.ModuleName">
            <summary>
            The name of the module of the function that wrote the message
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Tags">
            <summary>
            The tags applied to the message
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Level">
            <summary>
            What level was the message?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Runspace">
            <summary>
            What runspace was the message written from?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.ComputerName">
            <summary>
            The computer the message was generated on
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.TargetObject">
            <summary>
            The object that was the focus of this message.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.File">
            <summary>
            The file from which the message was written.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Line">
            <summary>
            The line on which the message was written.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.CallStack">
            <summary>
            The callstack when the message was written.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Username">
            <summary>
            The user that did the writing.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.LogEntry.#ctor">
            <summary>
            Creates an empty log entry
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.LogEntry.#ctor(System.String,Sqlcollaborative.Dbatools.Message.LogEntryType,System.DateTime,System.String,System.String,System.Collections.Generic.List{System.String},Sqlcollaborative.Dbatools.Message.MessageLevel,System.Guid,System.String,System.Object,System.String,System.Int32,System.Collections.Generic.IEnumerable{System.Management.Automation.CallStackFrame},System.String)">
            <summary>
            Creates a filled out log entry
            </summary>
            <param name="Message">The message that was logged</param>
            <param name="Type">The type(s) of message written</param>
            <param name="Timestamp">When was the message logged</param>
            <param name="FunctionName">What function wrote the message</param>
            <param name="ModuleName">Name of the module the function writing this message came from</param>
            <param name="Tags">Tags that were applied to the message</param>
            <param name="Level">What level was the message written at.</param>
            <param name="Runspace">The ID of the runspace that wrote the message.</param>
            <param name="ComputerName">The computer the message was generated on.</param>
            <param name="TargetObject">The object this message was all about.</param>
            <param name="File">The file of the code that wrote the message.</param>
            <param name="Line">The line on which the message was written.</param>
            <param name="CallStack">The callstack that triggered the write.</param>
            <param name="Username">The user responsible for running the code that is writing the message.</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.LogEntryType">
            <summary>
            The kind of information the logged entry was.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntryType.None">
            <summary>
            This entry wasn't written to any stream
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntryType.Information">
            <summary>
            A message that was written to the current host equivalent, if available also to the information stream
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntryType.Verbose">
            <summary>
            A message that was written to the verbose stream
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntryType.Debug">
            <summary>
            A message that was written to the Debug stream
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntryType.Warning">
            <summary>
            A message written to the warning stream
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.LogHost">
            <summary>
            Provides static information storage for logging related settings, as well as housing the logging queues.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MaxErrorCount">
            <summary>
            The maximum numbers of error records maintained in-memory.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MaxMessageCount">
            <summary>
            The maximum number of messages that can be maintained in the in-memory message queue
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MaxMessagefileBytes">
            <summary>
            The maximum size of a given logfile. When reaching this limit, the file will be abandoned and a new log created. Set to 0 to not limit the size.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MaxMessagefileCount">
            <summary>
            The maximum number of logfiles maintained at a time. Exceeding this number will cause the oldest to be culled. Set to 0 to disable the limit.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MaxErrorFileBytes">
            <summary>
            The maximum size all error files combined may have. When this number is exceeded, the oldest entry is culled.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MaxTotalFolderSize">
            <summary>
            This is the upper limit of length all items in the log folder may have combined across all processes.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.LoggingPath">
            <summary>
            Path to where the logfiles live.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MaxLogFileAge">
            <summary>
            Any logfile older than this will automatically be cleansed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MessageLogFileEnabled">
            <summary>
            Governs, whether a log file for the system messages is written
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MessageLogEnabled">
            <summary>
            Governs, whether a log of recent messages is kept in memory
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.ErrorLogFileEnabled">
            <summary>
            Governs, whether log files for errors are written
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.ErrorLogEnabled">
            <summary>
            Governs, whether a log of recent errors is kept in memory
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.OutQueueError">
            <summary>
            The outbound queue for errors. These will be processed and written to xml
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.OutQueueLog">
            <summary>
            The outbound queue for logs. These will be processed and written to logfile
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.LogHost.GetErrors">
            <summary>
            Retrieves a copy of the Error stack
            </summary>
            <returns>All errors thrown by functions using the message or flowcontrol system</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.LogHost.GetLog">
            <summary>
            Retrieves a copy of the message log
            </summary>
            <returns>All messages logged this session.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.LogHost.WriteErrorEntry(System.Management.Automation.ErrorRecord[],System.String,System.String,System.Collections.Generic.List{System.String},System.DateTime,System.String,System.Guid,System.String)">
            <summary>
            Write an error record to the log
            </summary>
            <param name="Record">The actual error record as powershell wrote it</param>
            <param name="FunctionName">The name of the function writing the error</param>
            <param name="ModuleName">The name of the module the function writing the error came from</param>
            <param name="Tags">The tags that were assigned to the error event</param>
            <param name="Timestamp">When was the error written</param>
            <param name="Message">What message was passed to the user</param>
            <param name="Runspace">The runspace the message was written from</param>
            <param name="ComputerName">The computer the error was written on</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.LogHost.WriteLogEntry(System.String,Sqlcollaborative.Dbatools.Message.LogEntryType,System.DateTime,System.String,System.String,System.Collections.Generic.List{System.String},Sqlcollaborative.Dbatools.Message.MessageLevel,System.Guid,System.String,System.String,System.Int32,System.Collections.Generic.IEnumerable{System.Management.Automation.CallStackFrame},System.String,System.Object)">
            <summary>
            Write a new entry to the log
            </summary>
            <param name="Message">The message to log</param>
            <param name="Type">The type of the message logged</param>
            <param name="Timestamp">When was the message generated</param>
            <param name="FunctionName">What function wrote the message</param>
            <param name="ModuleName">What module did the function writing this message come from?</param>
            <param name="Tags">The tags that were applied to the message</param>
            <param name="Level">At what level was the function written</param>
            <param name="Runspace">The runspace the message is coming from</param>
            <param name="ComputerName">The computer the message was generated on</param>
            <param name="File">The file from which the message was written</param>
            <param name="Line">The line on which the message was written</param>
            <param name="TargetObject">The object associated with a given message.</param>
            <param name="CallStack">The callstack at the moment the message was written.</param>
            <param name="Username">The name of the user under which the code being executed</param>
            <returns>The entry that is being written</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.MessageEventSubscription">
            <summary>
            Condition and logic to be executed on message events
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.Name">
            <summary>
            Name of the event subscription, must be unique.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.ScriptBlock">
            <summary>
            Scriptblock to execute if the condition is met
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription._MessageFilter">
            <summary>
            The internally stored filter value for Message
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.MessageFilter">
            <summary>
            The value the Message is filtered by
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.MessageFilterSet">
            <summary>
            Whether filtering by Message was enabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription._ModuleNameFilter">
            <summary>
            The internally stored filter value for ModuleName
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.ModuleNameFilter">
            <summary>
            The value the ModuleName is filtered by
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.ModuleNameFilterSet">
            <summary>
            Whether filtering by ModuleName was enabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription._FunctionNameFilter">
            <summary>
            The internally stored filter value for FunctionName
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.FunctionNameFilter">
            <summary>
            The value the FunctionName is filtered by
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.FunctionNameFilterSet">
            <summary>
            Whether filtering by FunctionName was enabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription._TargetFilter">
            <summary>
            The internally stored filter value for Target
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.TargetFilter">
            <summary>
            The value the Target is filtered by
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.TargetFilterSet">
            <summary>
            Whether filtering by Target was enabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription._LevelFilter">
            <summary>
            The internally stored filter value for Level
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.LevelFilter">
            <summary>
            The value the Level is filtered by
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.LevelFilterSet">
            <summary>
            Whether filtering by Level was enabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription._TagFilter">
            <summary>
            The internally stored filter value for Tag
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.TagFilter">
            <summary>
            The value the Tag is filtered by
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.TagFilterSet">
            <summary>
            Whether filtering by Tag was enabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription._RunspaceFilter">
            <summary>
            The internally stored filter value for Runspace
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.RunspaceFilter">
            <summary>
            The value the Runspace is filtered by
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.RunspaceFilterSet">
            <summary>
            Whether filtering by Runspace was enabled
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.Applies(Sqlcollaborative.Dbatools.Message.LogEntry)">
            <summary>
            Checks, whether a given entry matches the filter defined in this subscription
            </summary>
            <param name="Entry">The entry to validate</param>
            <returns>Whether the subscription should react to this entry</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.MessageHost">
            <summary>
            Provides static resources to the messaging subsystem
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.MaximumInformation">
            <summary>
            The maximum message level to still display to the user directly.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.MaximumVerbose">
            <summary>
            The maxium message level where verbose information is still written.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.MaximumDebug">
            <summary>
            The maximum message level where debug information is still written.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.MinimumInformation">
            <summary>
            The minimum required message level for messages that will be shown to the user.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.MinimumVerbose">
            <summary>
            The minimum required message level where verbose information is written.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.MinimumDebug">
            <summary>
            The minimum required message level where debug information is written.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.InfoColor">
            <summary>
            The color stuff gets written to the console in
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.InfoColorEmphasis">
            <summary>
            The color important stuff gets written to the console in
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.InfoColorSubtle">
            <summary>
            The color background stuff gets written to the console in
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.DeveloperColor">
            <summary>
            The color stuff gets written to the console in, when developer mode is enabled and the message would not have been written after all
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.DeveloperMode">
            <summary>
            Enables the developer mode. In this all messages are written to the console, in order to make it easier to troubleshoot issues.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.NestedLevelDecrement">
            <summary>
            Message levels can decrease by nested level. This causes messages to have an increasingly reduced level as the size of the callstack increases. 
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.DisableVerbosity">
            <summary>
            Globally override all verbosity
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.EnableMessageTimestamp">
            <summary>
            Include message timestamps in verbose message output
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.EnableMessageDisplayCommand">
            <summary>
            Include the message display command in the verbose message output
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.EnableMessageBreadcrumbs">
            <summary>
            Include the entire callstack in the verbose message output
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.TransformErrorQueueSize">
            <summary>
            The size of the transform error queue. When adding more than this, the oldest entry will be discarded
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.ExceptionTransforms">
            <summary>
            Provides the option to transform exceptions based on the original exception type
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.TargetTransforms">
            <summary>
            Provides the option to transform target objects based on type. This is sometimes important when working with live state objects that should not be serialized.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.TransformErrors">
            <summary>
            The list of transformation errors that occured.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.MessageHost.GetTransformErrors">
            <summary>
            Returns the current queue of failed transformations
            </summary>
            <returns>The list of transformations that failed</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.MessageHost.WriteTransformError(System.Management.Automation.ErrorRecord,System.String,System.String,System.Object,Sqlcollaborative.Dbatools.Message.TransformType,System.Guid)">
            <summary>
            Writes a new transform error
            </summary>
            <param name="Record">The record of what went wrong</param>
            <param name="FunctionName">The name of the function writing the transformed message</param>
            <param name="ModuleName">The module the function writing the transformed message is part of</param>
            <param name="Object">The object that should have been transformed</param>
            <param name="Type">The type of transform that was attempted</param>
            <param name="Runspace">The runspace it all happened on</param>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.ExceptionTransformList">
            <summary>
            List of custom transforms for exceptions
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.TargetTransformlist">
            <summary>
            List of custom transforms for targets
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.MessageLevelModifiers">
            <summary>
            List of all modifiers that apply to message levels
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.Events">
            <summary>
            List of events that subscribe to messages being written
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.MessageLevel">
            <summary>
            The various levels of verbosity available.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.Critical">
            <summary>
            Very important message, should be shown to the user as a high priority
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.Important">
            <summary>
            Important message, the user should read this
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.Output">
            <summary>
            Important message, the user should read this
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.Significant">
            <summary>
            Message relevant to the user.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.VeryVerbose">
            <summary>
            Not important to the regular user, still of some interest to the curious
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.Verbose">
            <summary>
            Background process information, in case the user wants some detailed information on what is currently happening.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.SomewhatVerbose">
            <summary>
            A footnote in current processing, rarely of interest to the user
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.System">
            <summary>
            A message of some interest from an internal system persepctive, but largely irrelevant to the user.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.Debug">
            <summary>
            Something only of interest to a debugger
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.InternalComment">
            <summary>
            This message barely made the cut from being culled. Of purely development internal interest, and even there is 'interest' a strong word for it.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.Warning">
            <summary>
            This message is a warning, sure sign something went badly wrong
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.MessageLevelModifier">
            <summary>
            A modification to a given message's level
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.Name">
            <summary>
            Name of the modifier. Prevents duplication in a multi-runspace scenario.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.Modifier">
            <summary>
            The amount to modify the level by
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.IncludeFunctionName">
            <summary>
            Apply modifier only to messages from this function.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.ExcludeFunctionName">
            <summary>
            Apply modifier not when the message is written by this function.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.IncludeModuleName">
            <summary>
            Apply modifier only to messages from this module
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.ExcludeModuleName">
            <summary>
            Do not apply modifier to messages from this module
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.IncludeTags">
            <summary>
            Only apply this modifier to a message that includes at least one of these tags
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.ExcludeTags">
            <summary>
            Do not apply this modifier to a message that includes any of the following tags
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.AppliesTo(System.String,System.String,System.Collections.Generic.List{System.String})">
            <summary>
            Tests, whether a message a message should be modified by this modiier
            </summary>
            <param name="FunctionName">The name of the function writing the message</param>
            <param name="ModuleName">The name of the module, the function writing this message comes from</param>
            <param name="Tags">The tags of the message written</param>
            <returns>Whether the message applies</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.TransformCondition">
            <summary>
            A condition, under which the object shall be transaformed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformCondition.TypeName">
            <summary>
            Name of the type. All similar types (as determined by the '-like' operator) will be transformed.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformCondition.ModuleName">
            <summary>
            The name of the module to consider, using the -Like operator
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformCondition.FunctionName">
            <summary>
            The name of the function name to consider, using the -Like operator
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformCondition.ScriptBlock">
            <summary>
            The scriptblock that performs the transformation
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformCondition.Type">
            <summary>
            What kind of transformation is being performed?
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformCondition.#ctor(System.String,System.String,System.String,System.Management.Automation.ScriptBlock,Sqlcollaborative.Dbatools.Message.TransformType)">
            <summary>
            Initializes a transform condition
            </summary>
            <param name="TypeName">Only objects of similar name will be transformed</param>
            <param name="ModuleName">Only objects coming from similar modules will be considered</param>
            <param name="FunctionName">Only objects coming from similar functions will be considered</param>
            <param name="ScriptBlock">The scriptblock used for the transformation</param>
            <param name="Type">What kind of transformation this is</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.TransformError">
            <summary>
            An error occured during a message transformation
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformError.Record">
            <summary>
            The error record of what went wrong
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformError.FunctionName">
            <summary>
            The name of the function writing the message that failed to transform
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformError.ModuleName">
            <summary>
            The name of the module the command writing the message came from
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformError.Timestamp">
            <summary>
            When did it all happen?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformError.Object">
            <summary>
            The object that was supposed to be transformed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformError.Type">
            <summary>
            The kind of transform that failed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformError.Runspace">
            <summary>
            The runspace it all happened on
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformError.#ctor(System.Management.Automation.ErrorRecord,System.String,System.String,System.Object,Sqlcollaborative.Dbatools.Message.TransformType,System.Guid)">
            <summary>
            Creates a new transform error
            </summary>
            <param name="Record">The record of what went wrong</param>
            <param name="FunctionName">The name of the function writing the transformed message</param>
            <param name="ModuleName">The module the function writing the transformed message is part of</param>
            <param name="Object">The object that should have been transformed</param>
            <param name="Type">The type of transform that was attempted</param>
            <param name="Runspace">The runspace it all happened on</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.TransformList">
            <summary>
            List engine, managing the lists for a message transformation type
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformList.GetAll">
            <summary>
            Returns all entries in the list.
            </summary>
            <returns>The list of transforms contained within</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformList.IsListed(Sqlcollaborative.Dbatools.Message.TransformCondition)">
            <summary>
            Returns whether the actual object is part of the list
            </summary>
            <param name="Condition">The object to test for list membership</param>
            <returns>Whether the object is listed</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformList.IsContained(Sqlcollaborative.Dbatools.Message.TransformCondition)">
            <summary>
            Returns whether a condition with equal conditions already exists
            </summary>
            <param name="Condition">The condition to test</param>
            <returns>Whether the referenced condition is already listed</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformList.Add(Sqlcollaborative.Dbatools.Message.TransformCondition)">
            <summary>
            Adds a condition to the list, if there is no equivalent condition present.
            </summary>
            <param name="Condition">The condition to add</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformList.Remove(Sqlcollaborative.Dbatools.Message.TransformCondition)">
            <summary>
            Removes a condition from the lsit of conditional transforms
            </summary>
            <param name="Condition">The condition to remove</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformList.Get(System.String,System.String,System.String)">
            <summary>
            Returns the first transform whose filter is similar enough to work out.
            </summary>
            <param name="TypeName">The name of the type to check for a transform</param>
            <param name="ModuleName">The module of the command that wrote the message with the transformable object</param>
            <param name="Functionname">The command that wrote the message with the transformable object</param>
            <returns>Either a transform or null, if no fitting transform was found</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.TransformType">
            <summary>
            The messaging system provides these kinds of transformations for input.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformType.Target">
            <summary>
            A target transform can transform the target object specified. Used for live-state objects that should not be serialized on a second thread.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformType.Exception">
            <summary>
            An exception transform allows automatic transformation of exceptions. Primarily used to unwrap exceptions from an API that wraps all exceptions.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter">
            <summary>
            Input converter for Computer Management Information
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.Connection">
            <summary>
            The resolved connection object
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.Success">
            <summary>
            Whether input processing was successful
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.InputObject">
            <summary>
            The object actually passed to the class
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.op_Implicit(Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter)~Sqlcollaborative.Dbatools.Connection.ManagementConnection">
            <summary>
            Implicitly convert all connection parameter objects to the connection-type
            </summary>
            <param name="Input">The parameter object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.#ctor(System.String)">
            <summary>
            Creates a new DbaWmConnectionParameter based on an input-name
            </summary>
            <param name="ComputerName">The name of the computer the connection is stored for.</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.#ctor(Sqlcollaborative.Dbatools.Connection.ManagementConnection)">
            <summary>
            Creates a new DbaWmConnectionParameter based on an already existing connection object.
            </summary>
            <param name="Connection">The connection to accept</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.#ctor(System.Object)">
            <summary>
            Tries to convert a generic input object into a true input.
            </summary>
            <param name="Input">Any damn object in the world</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.#ctor(Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter)">
            <summary>
            Creates a new DbaCmConnectionParameter based on an instance parameter
            </summary>
            <param name="Instance">The instance to interpret</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter">
            <summary>
            Parameter class that handles the various kinds of credential input
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.Credential">
            <summary>
            The credential object received
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.UserName">
            <summary>
            The name of the credential object
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.Password">
            <summary>
            The password of the credential object
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.#ctor(System.Management.Automation.PSCredential)">
            <summary>
            Creates a credential parameter from a PSCredential object
            </summary>
            <param name="Credential">A PSCredential object</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.#ctor(System.Net.NetworkCredential)">
            <summary>
            Creates a credential parameter from a NetworkCredential object
            </summary>
            <param name="Credential">The credentials to use</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.#ctor(System.Object)">
            <summary>
            Creates a credential parameter from anything it nows how to handle
            </summary>
            <param name="Credential">The object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.op_Implicit(Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter)~System.Management.Automation.PSCredential">
            <summary>
            Implicitly converts from DbaCredentialParameter to PSCredential
            </summary>
            <param name="Input">The DbaCredentialParameter to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.op_Implicit(System.Management.Automation.PSCredential)~Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter">
            <summary>
            Implicitly converts a PSCredential object to DbaCredenitalParameter
            </summary>
            <param name="Input">The PSCredential to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.op_Implicit(Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter)~System.Net.NetworkCredential">
            <summary>
            Implicitly converts from DbaCredentialParameter to NetworkCredential
            </summary>
            <param name="Input">The DbaCredentialParameter to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.op_Implicit(System.Net.NetworkCredential)~Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter">
            <summary>
            Implicitly converts a NetworkCredential object to DbaCredenitalParameter
            </summary>
            <param name="Input">The NetworkCredential to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.GetNetworkCredential">
            <summary>
            Legacy wrapper. While there exists implicit conversion, this allows using the object as before, avoiding errors for unknown method.
            </summary>
            <returns>A network credential object with the same credentials as the original object</returns>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.CredentialStore">
            <summary>
            Cached credentials, if the user stors them under a name.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.GetTypeCode">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToBoolean(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToChar(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToSByte(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToByte(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToInt16(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToUInt16(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToInt32(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToUInt32(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToInt64(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToUInt64(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToSingle(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToDouble(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToDecimal(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToDateTime(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToString(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToType(System.Type,System.IFormatProvider)">
            <summary>
            Tries to convert the credential parameter to one of its supported types
            </summary>
            <param name="TargetType">The type to convert to</param>
            <param name="Format">Irrelevant</param>
            <returns></returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseParameter">
            <summary>
            Parameter class that accepts anything pointing at a database
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseParameter.InputObject">
            <summary>
            The original object passed to the parameter
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseParameter.Database">
            <summary>
            The SMO Database Object
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseParameter.Name">
            <summary>
            The name of the database
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseParameter.#ctor(System.String)">
            <summary>
            Accepts the name of a database and converts it to a DbaDatabaseParameter
            </summary>
            <param name="Name"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseParameter.#ctor(System.Object)">
            <summary>
            Accepts anything and tries to convert it to a live SMO Database object
            </summary>
            <param name="Item">The item to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseParameter.ToString">
            <summary>
            Overrides the regular tostring to show something pleasant and useful
            </summary>
            <returns>The name of the database</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseSmoParameter">
            <summary>
            Parameter class that only accepts live SMO Databases
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseSmoParameter.InputObject">
            <summary>
            The original object passed to the parameter
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseSmoParameter.Database">
            <summary>
            The SMO Database Object
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseSmoParameter.Name">
            <summary>
            The name of the database
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseSmoParameter.#ctor(System.Object)">
            <summary>
            Accepts anything and tries to convert it to a live SMO Database object
            </summary>
            <param name="Item">The item to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseSmoParameter.ToString">
            <summary>
            Overrides the regular tostring to show something pleasant and useful
            </summary>
            <returns>The name of the database</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType">
            <summary>
            What kind of object was bound to the parameter class?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType.Default">
            <summary>
            Anything, really. An unspecific not reusable type was bound
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType.Linked">
            <summary>
            A live smo linked server object was bound
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType.Server">
            <summary>
            A live smo server object was bound
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType.RegisteredServer">
            <summary>
            A Central Management Server RegisteredServer SMO object was bound
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType.ConnectionString">
            <summary>
            An actual connection string was specified. Connection strings are directly reused for SMO connections
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType.ConnectionStringLocalDB">
            <summary>
            A connection string pointing at a local, file-based DB
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType.SqlConnection">
            <summary>
            An already established sql connection to was created outside of SMO
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter">
            <summary>
            Input converter for instance information
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.ComputerName">
            <summary>
            Name of the computer as resolvable by DNS
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.InstanceName">
            <summary>
            Name of the instance on the target server
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.Port">
            <summary>
            The port over which to connect to the server. Only present if non-default
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.NetworkProtocol">
            <summary>
            The network protocol to connect over
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.IsLocalHost">
            <summary>
            Verifies, whether the specified computer is localhost or not.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.FullName">
            <summary>
            Full name of the instance, including the server-name
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.FullSmoName">
            <summary>
            Full name of the instance, including the server-name, used when connecting via SMO
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.SqlComputerName">
            <summary>
            Name of the computer as used in an SQL Statement
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.SqlInstanceName">
            <summary>
            Name of the instance as used in an SQL Statement
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.SqlFullName">
            <summary>
            Full name of the instance, including the server-name as used in an SQL statement
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.IsConnectionString">
            <summary>
            Whether the input is a connection string
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.InputObject">
            <summary>
            The original object passed to the parameter class.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.Type">
            <summary>
            What kind of object was bound to the parameter class? For efficiency's purposes.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.LinkedLive">
            <summary>
            Returns, whether a live SMO object was bound for the purpose of accessing LinkedServer functionality
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.LinkedServer">
            <summary>
            Returns the available Linked Server objects from live objects only
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.op_Implicit(Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter)~System.String">
            <summary>
            Converts the parameter class to its full name
            </summary>
            <param name="Input">The parameter class object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.#ctor(System.String)">
            <summary>
            Creates a DBA Instance Parameter from string
            </summary>
            <param name="Name">The name of the instance</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.#ctor(System.Net.IPAddress)">
            <summary>
            Creates a DBA Instance Parameter from an IPAddress
            </summary>
            <param name="Address"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.#ctor(System.Net.NetworkInformation.PingReply)">
            <summary>
            Creates a DBA Instance Parameter from the reply to a ping
            </summary>
            <param name="Ping">The result of a ping</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.#ctor(System.Net.IPHostEntry)">
            <summary>
            Creates a DBA Instance Parameter from the result of a dns resolution
            </summary>
            <param name="Entry">The result of a dns resolution, to be used for targetting the default instance</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.#ctor(System.Data.SqlClient.SqlConnection)">
            <summary>
            Creates a DBA Instance Parameter from an established SQL Connection
            </summary>
            <param name="Connection">The connection to reuse</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.#ctor(Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport)">
            <summary>
            Accept and understand discovery reports.
            </summary>
            <param name="Report">The report to interpret</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.#ctor(System.Object)">
            <summary>
            Creates a DBA Instance parameter from any object
            </summary>
            <param name="Input">Object to parse</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.ToString">
            <summary>
            Overrides the regular <c>ToString()</c> to show something pleasant and useful
            </summary>
            <returns>The <see cref="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.FullSmoName"/></returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.DbaSelectParameter">
            <summary>
            Class that automatically parses input chosen for the -Property parameter of Select-PSUObject
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaSelectParameter.InputObject">
            <summary>
            The original input object
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaSelectParameter.Value">
            <summary>
            The value as Select-Object wants it
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaSelectParameter.#ctor(System.String)">
            <summary>
            Builds a property parameter from string
            </summary>
            <param name="Value">The string to interpret</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaSelectParameter.#ctor(System.Collections.Hashtable)">
            <summary>
            Builds a select parameter from a hashtable (pretty straightforward)
            </summary>
            <param name="Hash">The hashtable to accept</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.ParameterContractAttribute">
            <summary>
            The attribute used to define the elements of a ParameterClass contract
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.ParameterContractAttribute.Type">
            <summary>
            Returns the type of the element this attribute is supposed to be attached to.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.ParameterContractAttribute.Behavior">
            <summary>
            Returns the behavior to expect from the contracted element. This sets the expectations on how this element is likely to act.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.ParameterContractAttribute.#ctor(Sqlcollaborative.Dbatools.Parameter.ParameterContractType,Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior)">
            <summary>
            Ceates a perfectly common parameter contract attribute. For use with all parameter classes' public elements.
            </summary>
            <param name="Type"></param>
            <param name="Behavior"></param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior">
            <summary>
            Defines how this element will behave
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior.NotContracted">
            <summary>
            This elements is not actually part of the contract. Generally you wouldn't want to add the attribute at all in that case. However, in some places it helps avoiding confusion.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior.Mandatory">
            <summary>
            This element may never be null and must be considered in all assignments. Even if the element is de facto not nullable, all constructors must assign it.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior.Optional">
            <summary>
            This element may contain data, but is not required to. In case of a method, it may simply do nothing
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior.Failable">
            <summary>
            This method may throw an error when executing and should always be handled with try/catch. Use this on methods that use external calls.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior.Arbiter">
            <summary>
            The content of the thus marked field determines the dependent's state. Generally, only if the arbiter is true, will the dependent elements be mandatory. This behavior may only be assigned to boolean fields.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior.Conditional">
            <summary>
            This behavior can be assigned together with the 'Mandatory' behavior. It means the field is only mandatory if an arbiter field is present and set to true.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior.Conversion">
            <summary>
            Converts content. Generally applied only to operators, but some methods may also convert information.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.ParameterContractType">
            <summary>
            Defines what kind of element is granted the contract
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractType.Field">
            <summary>
            The contracted element is a field containing a value
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractType.Method">
            <summary>
            The contracted element is a method, performing an action
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractType.Operator">
            <summary>
            The contracted element is an operator, facilitating type conversion. Generally into a dedicated object type this parameterclass abstracts.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Runspace.DbaRunspaceState">
            <summary>
            Contains the state a managed, unique runspace can be in.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Runspace.DbaRunspaceState.Running">
            <summary>
            The runspace is up and running
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Runspace.DbaRunspaceState.Stopping">
            <summary>
            The runspace has received the stop order, but has not yet obeyed it
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Runspace.DbaRunspaceState.Stopped">
            <summary>
            The runspace has followed its order to stop and is currently disabled
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer">
            <summary>
            Class that contains the logic necessary to manage a unique runspace
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.Name">
            <summary>
            The name of the runspace.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.RunspaceGuid">
            <summary>
            The Guid of the running Runspace
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.SetScript(System.Management.Automation.ScriptBlock)">
            <summary>
            Sets the script to execute in the runspace. Will NOT take immediate effect. Only after restarting the runspace will it be used.
            </summary>
            <param name="Script">The scriptblock to execute</param>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.State">
            <summary>
            The state the runspace currently is in.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.Start">
            <summary>
            Starts the Runspace.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.SetName(System.Management.Automation.Runspaces.Runspace)">
            <summary>
            Sets the name on a runspace. This WILL FAIL for PowerShell v3!
            </summary>
            <param name="Runspace">The runspace to be named</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.Stop">
            <summary>
            Gracefully stops the Runspace
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.Kill">
            <summary>
            Very ungracefully kills the runspace. Use only in the most dire emergency.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.SignalStopped">
            <summary>
            Signals the registered runspace has stopped execution
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.#ctor(System.String,System.Management.Automation.ScriptBlock)">
            <summary>
            Creates a new runspace container with the basic information needed
            </summary>
            <param name="Name">The name of the Runspace</param>
            <param name="Script">The code using the runspace logic</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Runspace.RunspaceHost">
            <summary>
            Provides hosting for all registered runspaces
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Runspace.RunspaceHost.StopTimeoutSeconds">
            <summary>
            The number of seconds before a Stop command is interrupted and instead the runspace is gracelessly shut down.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Runspace.RunspaceHost.Runspaces">
            <summary>
            The dictionary containing the definitive list of unique Runspace
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.TabExpansion.InstanceAccess">
            <summary>
            Contains information on access to an instance
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.InstanceAccess.InstanceName">
            <summary>
            The name of the instance to access
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.InstanceAccess.IsSysAdmin">
            <summary>
            Whether the account had sysadmin privileges. On multiple user usage, the cache will prefer sysadmin accounts.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.InstanceAccess.ConnectionObject">
            <summary>
            The actual connection object to connect with to the server
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.InstanceAccess.LastAccess">
            <summary>
            When was the instance last accessed using dbatools
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.InstanceAccess.LastUpdate">
            <summary>
            When was the instance's TEPP cache last updated
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.TabExpansion.ScriptContainer">
            <summary>
            Regular container to store scripts in, that are used in TEPP
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.ScriptContainer.Name">
            <summary>
            The name of the scriptblock
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.ScriptContainer.ScriptBlock">
            <summary>
            The scriptblock doing the logic
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.ScriptContainer.LastExecution">
            <summary>
            The last time the scriptblock was called. Must be updated by the scriptblock itself
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.ScriptContainer.LastDuration">
            <summary>
            The time it took to run the last time
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.TabExpansion.TabCompletionSet">
            <summary>
            Contains information used to transmit Tepp Assignment
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabCompletionSet.Command">
            <summary>
            The name of the command to complete. "*" if all commands that have the parameter should be selected instead
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabCompletionSet.Parameter">
            <summary>
            The parameter to complete
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabCompletionSet.Script">
            <summary>
            The name of the script to complete with
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TabExpansion.TabCompletionSet.#ctor(System.String,System.String,System.String)">
            <summary>
            Creates a new tab completion set object with all information prefilled
            </summary>
            <param name="Command">The name of the command to complete. "*" if all commands that have the parameter should be selected instead</param>
            <param name="Parameter">The parameter to complete</param>
            <param name="Script">The name of the script to complete with</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TabExpansion.TabCompletionSet.Applies(System.String,System.String)">
            <summary>
            Tests, whether the completion set applies to the specified parameter / command combination
            </summary>
            <param name="Command">The command to test</param>
            <param name="Parameter">The parameter of the command to test</param>
            <returns>Whether this completion set applies to the specified combination of parameter / command</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost">
            <summary>
            Class that handles the static fields supporting the dbatools TabExpansion implementation
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.Scripts">
            <summary>
            Field containing the scripts that were registered.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.Cache">
            <summary>
            The cache used by scripts utilizing TabExpansionPlusPlus in dbatools
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.InstanceAccess">
            <summary>
            List of instances and when they were last accessed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppGatherScriptsFast">
            <summary>
            Scripts that build the cache and are suitable for synchronous execution
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppGatherScriptsSlow">
            <summary>
            Scripts that build the cache and are not suitable for synchronous execution
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.DbatoolsCommands">
            <summary>
            A list of all commands imported into dbatools
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TabCompletionSets">
            <summary>
            List of completion sets that should be processed into Tepp Assignments. Only populate this list on first import.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppAssignment">
            <summary>
            Maps a TEPP scriptblock to a command and parameter
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.SetInstance(System.String,System.Object,System.Boolean)">
            <summary>
            Registers a new instance or updates an already existing one. Should only be called from Connect-SqlInstance and Connect-DbaSqlServer
            </summary>
            <param name="InstanceName">Name of the instance connected to</param>
            <param name="Connection">To connection object containing the relevant information for accessing the instance</param>
            <param name="IsSysAdmin">Whether the account connecting to the instnace has SA privileges</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.GetTeppScript(System.String,System.String)">
            <summary>
            Returns the assigned scriptblock for a given parameter
            </summary>
            <param name="Command">The command that should be completed</param>
            <param name="Parameter">The parameter completion is provided for</param>
            <returns>Either the relevant script container or null</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.SetTeppScript(System.String,System.String,System.String)">
            <summary>
            Assigns a registered script to the parameter of a command
            </summary>
            <param name="Command">The command for which to complete</param>
            <param name="Parameter">The parameter for which to complete</param>
            <param name="Script">To name of the script with which to complete</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.AddTabCompletionSet(System.String,System.String,System.String)">
            <summary>
            Adds a completion set to the list of items to process
            </summary>
            <param name="Command">The command to complete for (accepts wildcard matching)</param>
            <param name="Parameter">The parameter to complete for (accepts wildcard matching)</param>
            <param name="Script">The script to register</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.CalculateTabExpansion">
            <summary>
            Processes the content of TabCompletionSets and Scripts into TappAssignments based on the DbatoolsCommands list.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppDisabled">
            <summary>
            Whether TEPP in its entirety is disabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppAsyncDisabled">
            <summary>
            Whether asynchronous TEPP updating should be disabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppSyncDisabled">
            <summary>
            Whether synchronous TEPP updating should be disabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppUpdateInterval">
            <summary>
            The interval in which asynchronous TEPP cache updates are performed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppUpdateTimeout">
            <summary>
            After this timespan of no requests to a server, the updates to its cache are disabled.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.TypeConversion.DbaCredentialParameterConverter">
            <summary>
            Converts to and from DbaCredentialparameter
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TypeConversion.DbaCredentialParameterConverter.CanConvertTo(System.Object,System.Type)">
            <summary>
            Verifies, whether a conversion for the object to the target type is possible
            </summary>
            <param name="SourceValue">The object to convert</param>
            <param name="DestinationType">The type to convert to</param>
            <returns>Whether it's possible, duh!</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TypeConversion.DbaCredentialParameterConverter.ConvertTo(System.Object,System.Type,System.IFormatProvider,System.Boolean)">
            <summary>
            Converts from DbaCredentialparameter to whatever destination type is attempted
            </summary>
            <param name="sourceValue">The source object. Better be a DbaCredentialparameter!</param>
            <param name="destinationType">Should be a supported destination type</param>
            <param name="formatProvider">Irrelevant</param>
            <param name="ignoreCase">Irrelevant</param>
            <returns>The target content type</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TypeConversion.DbaCredentialParameterConverter.CanConvertFrom(System.Object,System.Type)">
            <summary>
            Verifies, whether a conversion for the object from the source type to DbaCredentialParameter is possible
            </summary>
            <param name="SourceValue">The object to convert</param>
            <param name="DestinationType">The source type to convert to</param>
            <returns>Whether it's possible, duh!</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TypeConversion.DbaCredentialParameterConverter.ConvertFrom(System.Object,System.Type,System.IFormatProvider,System.Boolean)">
            <summary>
            Converts a source object to DbaCredentialparameter
            </summary>
            <param name="sourceValue">The source object</param>
            <param name="destinationType">The destination type. Must be DbaCredentialParameter, or red stuff happens</param>
            <param name="formatProvider">Irrelevant</param>
            <param name="ignoreCase">Irrelevant</param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TypeConversion.DbaCredentialParameterConverter.IsSupportedType(System.Type)">
            <summary>
            Returns, whether a given type is supported for conversion
            </summary>
            <param name="type">The type to validate</param>
            <returns>Whether it's a supported conversion</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DateTimeExtension">
            <summary>
            Extends DateTime
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DateTimeExtension.CompareTo(System.DateTime,Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)">
            <summary>
            Adds a compareTo method to DateTime to compare with DbaDateTimeBase
            </summary>
            <param name="Base">The extended DateTime object</param>
            <param name="comparedTo">The DbaDateTimeBase to compare with</param>
            <returns></returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaDate">
            <summary>
            A dbatools-internal datetime wrapper for neater display
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.DateTime)">
            <summary>
            Constructs a generic timestamp object wrapper from an input timestamp object.
            </summary>
            <param name="Timestamp">The timestamp to wrap</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.String)">
            <summary>
            Parses a string into a datetime object.
            </summary>
            <param name="Time">The time-string to parse</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int64)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int64,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.ToString">
            <summary>
            Provids the default-formated string, using the defined default formatting.
            </summary>
            <returns>Formatted datetime-string</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaDate)~System.DateTime">
            <summary>
            Implicitly convert to DateTime
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.op_Implicit(System.DateTime)~Sqlcollaborative.Dbatools.Utility.DbaDate">
            <summary>
            Implicitly convert from DateTime
            </summary>
            <param name="Base">The object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaDate)~Sqlcollaborative.Dbatools.Utility.DbaDateTime">
            <summary>
            Implicitly convert to DbaDate
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaDate)~Sqlcollaborative.Dbatools.Utility.DbaTime">
            <summary>
            Implicitly convert to DbaTime
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.Generate(System.DateTime)">
            <summary>
            Generates a DbaDate object based off DateTime object. Will be null if Base is the start value (Tickes == 0).
            </summary>
            <param name="Base">The Datetime to base it off</param>
            <returns>The object to generate (or null)</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaDateTime">
            <summary>
            A dbatools-internal datetime wrapper for neater display
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.DateTime)">
            <summary>
            Constructs a generic timestamp object wrapper from an input timestamp object.
            </summary>
            <param name="Timestamp">The timestamp to wrap</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.String)">
            <summary>
            Parses a string into a datetime object.
            </summary>
            <param name="Time">The time-string to parse</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int64)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int64,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.ToString">
            <summary>
            Provids the default-formated string, using the defined default formatting.
            </summary>
            <returns>Formatted datetime-string</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaDateTime)~System.DateTime">
            <summary>
            Implicitly convert to DateTime
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.op_Implicit(System.DateTime)~Sqlcollaborative.Dbatools.Utility.DbaDateTime">
            <summary>
            Implicitly convert from DateTime
            </summary>
            <param name="Base">The object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaDateTime)~Sqlcollaborative.Dbatools.Utility.DbaDate">
            <summary>
            Implicitly convert to DbaDate
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaDateTime)~Sqlcollaborative.Dbatools.Utility.DbaTime">
            <summary>
            Implicitly convert to DbaTime
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.Generate(System.DateTime)">
            <summary>
            Generates a DbaDateTime object based off DateTime object. Will be null if Base is the start value (Tickes == 0).
            </summary>
            <param name="Base">The Datetime to base it off</param>
            <returns>The object to generate (or null)</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase">
            <summary>
            Base class for wrapping around a DateTime object
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase._timestamp">
            <summary>
            The core resource, containing the actual timestamp
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Date">
            <summary>
            Gets the date component of this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Day">
            <summary>
            Gets the day of the month represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.DayOfWeek">
            <summary>
            Gets the day of the week represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.DayOfYear">
            <summary>
            Gets the day of the year represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Hour">
            <summary>
            Gets the hour component of the date represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Kind">
            <summary>
            Gets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Millisecond">
            <summary>
            Gets the milliseconds component of the date represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Minute">
            <summary>
            Gets the minute component of the date represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Month">
            <summary>
            Gets the month component of the date represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Second">
            <summary>
            Gets the seconds component of the date represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Ticks">
            <summary>
            Gets the number of ticks that represent the date and time of this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.TimeOfDay">
            <summary>
            Gets the time of day for this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Year">
            <summary>
            Gets the year component of the date represented by this instance.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor">
            <summary>
            Constructor that should never be called, since this class should never be instantiated. It's there for implicit calls on child classes.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.DateTime)">
            <summary>
            Constructs a generic timestamp object wrapper from an input timestamp object.
            </summary>
            <param name="Timestamp">The timestamp to wrap</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.String)">
            <summary>
            Parses a string into a datetime object.
            </summary>
            <param name="Time">The time-string to parse</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int64)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int64,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Add(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddDays(System.Double)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddHours(System.Double)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddMilliseconds(System.Double)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddMinutes(System.Double)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddMonths(System.Int32)">
            <summary>
            
            </summary>
            <param name="months"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddSeconds(System.Double)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddTicks(System.Int64)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddYears(System.Int32)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.CompareTo(System.Object)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.CompareTo(System.DateTime)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Equals(System.Object)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Equals(System.DateTime)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.GetDateTimeFormats">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.GetDateTimeFormats(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="provider"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.GetDateTimeFormats(System.Char)">
            <summary>
            
            </summary>
            <param name="format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.GetDateTimeFormats(System.Char,System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="format"></param>
            <param name="provider"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.GetBaseObject">
            <summary>
            Retrieve base DateTime object, this is a wrapper for
            </summary>
            <returns>Base DateTime object</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.GetHashCode">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.GetTypeCode">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.IsDaylightSavingTime">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Subtract(System.DateTime)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Subtract(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToBinary">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToFileTime">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToFileTimeUtc">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToLocalTime">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToLongDateString">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToLongTimeString">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToOADate">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToShortDateString">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToShortTimeString">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToString(System.String)">
            <summary>
            
            </summary>
            <param name="format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToString(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="provider"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToString(System.String,System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="format"></param>
            <param name="provider"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToUniversalTime">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ParseDateTime(System.String)">
            <summary>
            Parses input string into datetime
            </summary>
            <param name="Value">The string to parse</param>
            <returns>The resultant datetime.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_Addition(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="Timestamp"></param>
            <param name="Duration"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_Subtraction(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="Timestamp"></param>
            <param name="Duration"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_Equality(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)">
            <summary>
            
            </summary>
            <param name="Timestamp1"></param>
            <param name="Timestamp2"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_Inequality(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)">
            <summary>
            
            </summary>
            <param name="Timestamp1"></param>
            <param name="Timestamp2"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_GreaterThan(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)">
            <summary>
            
            </summary>
            <param name="Timestamp1"></param>
            <param name="Timestamp2"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_LessThan(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)">
            <summary>
            
            </summary>
            <param name="Timestamp1"></param>
            <param name="Timestamp2"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_GreaterThanOrEqual(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)">
            <summary>
            
            </summary>
            <param name="Timestamp1"></param>
            <param name="Timestamp2"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_LessThanOrEqual(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)">
            <summary>
            
            </summary>
            <param name="Timestamp1"></param>
            <param name="Timestamp2"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)~System.DateTime">
            <summary>
            Implicitly convert DbaDateTimeBase to DateTime
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_Implicit(System.DateTime)~Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase">
            <summary>
            Implicitly convert DateTime to DbaDateTimeBase
            </summary>
            <param name="Base">The object to convert</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaTime">
            <summary>
            A dbatools-internal datetime wrapper for neater display
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.DateTime)">
            <summary>
            Constructs a generic timestamp object wrapper from an input timestamp object.
            </summary>
            <param name="Timestamp">The timestamp to wrap</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.String)">
            <summary>
            Parses a string into a datetime object.
            </summary>
            <param name="Time">The time-string to parse</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int64)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int64,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.ToString">
            <summary>
            Provids the default-formated string, using the defined default formatting.
            </summary>
            <returns>Formatted datetime-string</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaTime)~System.DateTime">
            <summary>
            Implicitly convert to DateTime
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.op_Implicit(System.DateTime)~Sqlcollaborative.Dbatools.Utility.DbaTime">
            <summary>
            Implicitly convert from DateTime
            </summary>
            <param name="Base">The object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaTime)~Sqlcollaborative.Dbatools.Utility.DbaDate">
            <summary>
            Implicitly convert to DbaDate
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaTime)~Sqlcollaborative.Dbatools.Utility.DbaDateTime">
            <summary>
            Implicitly convert to DbaTime
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaTime)~System.String">
            <summary>
            Implicitly convert to string
            </summary>
            <param name="Base">Object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.Generate(System.DateTime)">
            <summary>
            Generates a DbaDateTime object based off DateTime object. Will be null if Base is the start value (Tickes == 0).
            </summary>
            <param name="Base">The Datetime to base it off</param>
            <returns>The object to generate (or null)</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan">
            <summary>
            A wrapper class, encapsuling a regular TimeSpan object. Used to provide custom timespan display.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Days">
            <summary>
            Gets the days component of the time interval represented by the current TimeSpan structure.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Hours">
            <summary>
            Gets the hours component of the time interval represented by the current TimeSpan structure.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Milliseconds">
            <summary>
            Gets the milliseconds component of the time interval represented by the current TimeSpan structure.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Minutes">
            <summary>
            Gets the minutes component of the time interval represented by the current TimeSpan structure.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Seconds">
            <summary>
            Gets the seconds component of the time interval represented by the current TimeSpan structure.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Ticks">
            <summary>
            Gets the number of ticks that represent the value of the current TimeSpan structure.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.TotalDays">
            <summary>
            Gets the value of the current TimeSpan structure expressed in whole and fractional days.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.TotalHours">
            <summary>
            Gets the value of the current TimeSpan structure expressed in whole and fractional hours.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.TotalMilliseconds">
            <summary>
            Gets the value of the current TimeSpan structure expressed in whole and fractional milliseconds.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.TotalMinutes">
            <summary>
            Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.TotalSeconds">
            <summary>
            Gets the value of the current TimeSpan structure expressed in whole and fractional seconds.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.#ctor(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="Timespan"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.#ctor(System.String)">
            <summary>
            Converts a string into a timespan
            </summary>
            <param name="Timespan">The string to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.#ctor(System.Int64)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.#ctor(System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="hours"></param>
            <param name="minutes"></param>
            <param name="seconds"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.#ctor(System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="days"></param>
            <param name="hours"></param>
            <param name="minutes"></param>
            <param name="seconds"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="days"></param>
            <param name="hours"></param>
            <param name="minutes"></param>
            <param name="seconds"></param>
            <param name="milliseconds"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.ParseTimeSpan(System.String)">
            <summary>
            Parses an input string as timespan
            </summary>
            <param name="Value">The string to interpret</param>
            <returns>The interpreted timespan value</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Add(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="ts"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.CompareTo(System.Object)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.CompareTo(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.CompareTo(Sqlcollaborative.Dbatools.Utility.DbaTimeSpan)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Duration">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Equals(System.Object)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Equals(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="obj"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.GetBaseObject">
            <summary>
            Returns the wrapped base object
            </summary>
            <returns>The base object</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.GetHashCode">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Negate">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Subtract(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="ts"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.ToString">
            <summary>
            Returns the default string representation of the TimeSpan object
            </summary>
            <returns>The string representation of the DbaTimeSpan object</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.ToString(System.String)">
            <summary>
            
            </summary>
            <param name="format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.ToString(System.String,System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="format"></param>
            <param name="formatProvider"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaTimeSpan)~System.TimeSpan">
            <summary>
            Implicitly converts a DbaTimeSpan object into a TimeSpan object
            </summary>
            <param name="Base">The original object to revert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.op_Implicit(System.TimeSpan)~Sqlcollaborative.Dbatools.Utility.DbaTimeSpan">
            <summary>
            Implicitly converts a TimeSpan object into a DbaTimeSpan object
            </summary>
            <param name="Base">The original object to wrap</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty">
            <summary>
            Makes timespan great again
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.FromMilliseconds(System.Double)">
            <summary>
            Creates a new, pretty timespan object from milliseconds
            </summary>
            <param name="Milliseconds">The milliseconds to convert from.</param>
            <returns>A pretty timespan object</returns>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.Digits">
            <summary>
            The number of digits a pretty timespan should round to.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.#ctor(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="Timespan"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.#ctor(System.String)">
            <summary>
            Converts a string into a timespan
            </summary>
            <param name="Timespan">The string to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.#ctor(System.Int64)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.#ctor(System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="hours"></param>
            <param name="minutes"></param>
            <param name="seconds"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.#ctor(System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="days"></param>
            <param name="hours"></param>
            <param name="minutes"></param>
            <param name="seconds"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="days"></param>
            <param name="hours"></param>
            <param name="minutes"></param>
            <param name="seconds"></param>
            <param name="milliseconds"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.ToString">
            <summary>
            Creates extra-nice timespan formats
            </summary>
            <returns>Humanly readable timespans</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaValidatePatternAttribute">
            <summary>
            Validates that each parameter argument matches the RegexPattern
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaValidatePatternAttribute.RegexPattern">
            <summary>
            Gets the Regex pattern to be used in the validation
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaValidatePatternAttribute.Options">
            <summary>
            Gets or sets the Regex options to be used in the validation
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaValidatePatternAttribute.ErrorMessage">
             <summary>
             Gets or sets the custom error message pattern that is displayed to the user.
            
             The text representation of the object being validated and the validating regex is passed as
             the first and second formatting parameters to the ErrorMessage formatting pattern.
             <example>
             [ValidatePattern("\s+", ErrorMessage="The text '{0}' did not pass validation of regex '{1}'")]
             </example>
             </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaValidatePatternAttribute.ValidateElement(System.Object)">
            <summary>
            Validates that each parameter argument matches the RegexPattern
            </summary>
            <param name="element">object to validate</param>
            <exception cref="T:System.Management.Automation.ValidationMetadataException">if <paramref name="element"/> is not a string
             that matches the pattern
             and for invalid arguments</exception>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaValidatePatternAttribute.#ctor(System.String)">
            <summary>
            Initializes a new instance of the PsfValidatePatternAttribute class
            </summary>
            <param name="regexPattern">Pattern string to match</param>
            <exception cref="T:System.ArgumentException">for invalid arguments</exception>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaValidateScriptAttribute">
            <summary>
            Class for validating against a script block.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaValidateScriptAttribute.ErrorMessage">
             <summary>
             Gets or sets the custom error message that is displayed to the user.
            
             The item being validated and the validating scriptblock is passed as the first and second
             formatting argument.
            
             <example>
             [ValidateScript("$_ % 2", ErrorMessage = "The item '{0}' did not pass validation of script '{1}'")]
             </example>
             </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaValidateScriptAttribute.ScriptBlock">
            <summary>
            Gets the scriptblock to be used in the validation
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaValidateScriptAttribute.ValidateElement(System.Object)">
            <summary>
            Validates that each parameter argument matches the scriptblock
            </summary>
            <param name="element">object to validate</param>
            <exception cref="T:System.Management.Automation.ValidationMetadataException">if <paramref name="element"/> is invalid</exception>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaValidateScriptAttribute.#ctor(System.Management.Automation.ScriptBlock)">
            <summary>
            Initializes a new instance of the ValidateScriptBlockAttribute class
            </summary>
            <param name="scriptBlock">Scriptblock to match</param>
            <exception cref="T:System.ArgumentException">for invalid arguments</exception>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.RegexHelper">
            <summary>
            Static class that holds useful regex patterns, ready for use
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.HostName">
            <summary>
            Pattern that checks for a valid hostname
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.HostNameEx">
            <summary>
            Pattern that checks for valid hostnames within a larger text
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.IPv4">
            <summary>
            Pattern that checks for a valid IPv4 address
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.IPv4Ex">
            <summary>
            Pattern that checks for valid IPv4 addresses within a larger text
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.IPv6">
            <summary>
            Will match a valid IPv6 address
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.IPv6Ex">
            <summary>
            Will match any IPv6 address within a larger text
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.ComputerTarget">
            <summary>
            Will match any string that in its entirety represents a valid target for dns- or ip-based targeting. Combination of HostName, IPv4 and IPv6
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.Guid">
            <summary>
            Will match a valid Guid
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.GuidEx">
            <summary>
            Will match any number of valid Guids in a larger text
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.InstanceName">
            <summary>
            Will match a mostly valid instance name.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.InstanceNameEx">
            <summary>
            Will match any instance of a mostly valid instance name.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.SqlReservedKeyword">
            <summary>
            Matches a word against the list of officially reserved keywords
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.SqlReservedKeywordEx">
            <summary>
            Will match any reserved keyword in a larger text
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.SqlReservedKeywordOdbc">
            <summary>
            Matches a word against the list of officially reserved keywords for odbc
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.SqlReservedKeywordOdbcEx">
            <summary>
            Will match any reserved odbc-keyword in a larger text
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.SqlReservedKeywordFuture">
            <summary>
            Matches a word against the list of keywords that are likely to become reserved in the future
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.SqlReservedKeywordFutureEx">
            <summary>
            Will match against the list of keywords that are likely to become reserved in the future and are used in a larger text
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.Size">
            <summary>
            Class that reports File size.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.Size.Byte">
            <summary>
            Number of bytes contained in whatever object uses this object as a property
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.Size.Kilobyte">
            <summary>
            Kilobyte representation of the bytes
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.Size.Megabyte">
            <summary>
            Megabyte representation of the bytes
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.Size.Gigabyte">
            <summary>
            Gigabyte representation of the bytes
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.Size.Terabyte">
            <summary>
            Terabyte representation of the bytes
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.Size.Digits">
            <summary>
            Number if digits behind the dot.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.Size.Style">
            <summary>
            How the size object should be displayed.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.ToString">
            <summary>
            Shows the default string representation of size
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.Equals(System.Object)">
            <summary>
            Simple equality test
            </summary>
            <param name="obj">The object to test it against</param>
            <returns>True if equal, false elsewise</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.GetHashCode">
            <inheritdoc cref="M:System.Int64.GetHashCode"/>
            <remarks>The hashcode of the underlying size</remarks>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.#ctor">
            <summary>
            Creates an empty size.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.#ctor(System.Int64)">
            <summary>
            Creates a size with some content
            </summary>
            <param name="Byte">The length in bytes to set the size to</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.CompareTo(Sqlcollaborative.Dbatools.Utility.Size)">
            <inheritdoc cref="M:System.IComparable`1.CompareTo(`0)"/>
            <remarks>For sorting</remarks>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.CompareTo(System.Object)">
            <inheritdoc cref="M:System.IComparable.CompareTo(System.Object)"/>
            <remarks>For sorting</remarks>
            <exception cref="T:System.ArgumentException">If you compare with something invalid.</exception>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Addition(Sqlcollaborative.Dbatools.Utility.Size,Sqlcollaborative.Dbatools.Utility.Size)">
            <summary>
            Adds two sizes
            </summary>
            <param name="a">The first size to add</param>
            <param name="b">The second size to add</param>
            <returns>The sum of both sizes</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Subtraction(Sqlcollaborative.Dbatools.Utility.Size,Sqlcollaborative.Dbatools.Utility.Size)">
            <summary>
            Substracts two sizes
            </summary>
            <param name="a">The first size to substract</param>
            <param name="b">The second size to substract</param>
            <returns>The difference between both sizes</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Multiply(Sqlcollaborative.Dbatools.Utility.Size,System.Double)">
            <summary>
            Multiplies two sizes with each other
            </summary>
            <param name="a">The size to multiply</param>
            <param name="b">The size to multiply with</param>
            <returns>A multiplied size.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Division(Sqlcollaborative.Dbatools.Utility.Size,System.Double)">
            <summary>
            Divides one size by another. 
            </summary>
            <param name="a">The size to divide</param>
            <param name="b">The size to divide with</param>
            <returns>Divided size (note: Cut off)</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Multiply(Sqlcollaborative.Dbatools.Utility.Size,Sqlcollaborative.Dbatools.Utility.Size)">
            <summary>
            Multiplies two sizes with each other
            </summary>
            <param name="a">The size to multiply</param>
            <param name="b">The size to multiply with</param>
            <returns>A multiplied size.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Division(Sqlcollaborative.Dbatools.Utility.Size,Sqlcollaborative.Dbatools.Utility.Size)">
            <summary>
            Divides one size by another.
            </summary>
            <param name="a">The size to divide</param>
            <param name="b">The size to divide with</param>
            <returns>Divided size (note: Cut off)</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(System.Int32)~Sqlcollaborative.Dbatools.Utility.Size">
            <summary>
            Implicitly converts int to size
            </summary>
            <param name="a">The number to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(System.Decimal)~Sqlcollaborative.Dbatools.Utility.Size">
            <summary>
            Implicitly converts int to size
            </summary>
            <param name="a">The number to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(Sqlcollaborative.Dbatools.Utility.Size)~System.Int32">
            <summary>
            Implicitly converts size to int
            </summary>
            <param name="a">The size to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(System.Int64)~Sqlcollaborative.Dbatools.Utility.Size">
            <summary>
            Implicitly converts long to size
            </summary>
            <param name="a">The number to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(Sqlcollaborative.Dbatools.Utility.Size)~System.Int64">
            <summary>
            Implicitly converts size to long
            </summary>
            <param name="a">The size to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(System.String)~Sqlcollaborative.Dbatools.Utility.Size">
            <summary>
            Implicitly converts string to size
            </summary>
            <param name="a">The string to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(System.Double)~Sqlcollaborative.Dbatools.Utility.Size">
            <summary>
            Implicitly converts double to size
            </summary>
            <param name="a">The number to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(Sqlcollaborative.Dbatools.Utility.Size)~System.Double">
            <summary>
            Implicitly converts size to double
            </summary>
            <param name="a">The size to convert</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.SizeStyle">
            <summary>
            How size objects should be displayed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.SizeStyle.Dynamic">
            <summary>
            The size object is styled dependend on the number stored within.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.SizeStyle.Plain">
            <summary>
            The size object is shown as a plain number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.SizeStyle.Byte">
            <summary>
            The size object is styled as a byte number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.SizeStyle.Kilobyte">
            <summary>
            The size object is styled as a kilobyte number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.SizeStyle.Megabyte">
            <summary>
            The size object is styled as a megabyte number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.SizeStyle.Gigabyte">
            <summary>
            The size object is styled as a Gigabyte number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.SizeStyle.Terabyte">
            <summary>
            The size object is styled as a Terabyte number
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.UtilityHost">
            <summary>
            Provides static resources to utility-namespaced stuff
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.UtilityHost.DisableCustomDateTime">
            <summary>
            Restores all DateTime objects to their default display behavior
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.UtilityHost.DisableCustomTimeSpan">
            <summary>
            Restores all timespan objects to their default display behavior.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.UtilityHost.FormatDate">
            <summary>
            Formating string for date-style datetime objects.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.UtilityHost.FormatDateTime">
            <summary>
            Formating string for datetime-style datetime objects
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.UtilityHost.FormatTime">
            <summary>
            Formating string for time-style datetime objects
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.UtilityHost.SizeDigits">
            <summary>
            The number of digits a size object shows by default
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.UtilityHost.SizeStyle">
            <summary>
            The way size objects are usually displayed
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.UtilityHost.IsLike(System.String,System.String,System.Boolean)">
            <summary>
            Implement's VB's Like operator logic.
            </summary>
            <param name="CaseSensitive">Whether the comparison is case sensitive</param>
            <param name="Pattern">The pattern the string is compared with</param>
            <param name="String">The string that is being compared with a pattern</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.UtilityHost.CompressString(System.String)">
            <summary>
            Compress string using default zip algorithms
            </summary>
            <param name="String">The string to compress</param>
            <returns>Returns a compressed string.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.UtilityHost.ExpandString(System.String)">
            <summary>
            Expand a string using default zig algorithms
            </summary>
            <param name="CompressedString">The compressed string to expand</param>
            <returns>Returns an expanded string.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.UtilityHost.CharListToSet(System.String)">
            <summary>
            Converts a string of characters to a HashSet of characters. If the string
            contains character ranges, such as A-Z, all characters in the range are
            also added to the returned set of characters.
            </summary>
            <param name="charList">Character list string</param>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.UtilityHost.Callstack">
            <summary>
            Returns the current callstack
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.UtilityHost._CallstackNew">
            <summary>
            Returns the current callstack on PS4+
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.UtilityHost._CallstackOld">
            <summary>
            Returns the current callstack on PS3
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.Validation">
            <summary>
            Provides helper methods that aid in validating stuff.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Validation.IsLocalhost(System.String)">
            <summary>
            Tests whether a given string is the local host.
            Does NOT use DNS resolution, DNS aliases will NOT be recognized!
            </summary>
            <param name="Name">The name to test for being local host</param>
            <returns>Whether the name is localhost</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Validation.IsRecommendedInstanceName(System.String)">
            <summary>
            Tests whether a given string is a recommended instance name. Recommended names musst be legal, nbot on the ODBC list and not on the list of words likely to become reserved keywords in the future.
            </summary>
            <param name="InstanceName">The name to test. MAY contain server name, but will NOT test the server.</param>
            <returns>Whether the name is recommended</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Validation.IsValidComputerTarget(System.String)">
            <summary>
            Tests whether a given string is a valid target for targeting as a computer. Will first convert from idn name.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Validation.IsValidInstanceName(System.String,System.Boolean)">
            <summary>
            Tests whether a given string is a valid instance name.
            </summary>
            <param name="InstanceName">The name to test. MAY contain server name, but will NOT test the server.</param>
            <param name="Lenient">Setting this to true will make the validation ignore default and mssqlserver as illegal names (as they are illegal names for named instances, but legal for targeting)</param>
            <returns>Whether the name is legal</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Validation.LinkedServerResult">
            <summary>
            The results of testing linked server connectivity as seen from the server that was linked to.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.ComputerName">
            <summary>
            The name of the server running the tests
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.InstanceName">
            <summary>
            The name of the instance running the tests
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.SqlInstance">
            <summary>
            The full name of the instance running the tests
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.LinkedServerName">
            <summary>
            The name of the linked server, the connectivity with whom was tested
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.RemoteServer">
            <summary>
            The name of the remote computer running the linked server.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.Connectivity">
            <summary>
            The test result
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.Result">
            <summary>
            Text interpretation of the result. Contains error messages if the test failed.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.#ctor">
            <summary>
            Creates an empty object
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.#ctor(System.String,System.String,System.String,System.String,System.String,System.Boolean,System.String)">
            <summary>
            Creates a test result with prefilled values
            </summary>
            <param name="ComputerName">The name of the server running the tests</param>
            <param name="InstanceName">The name of the instance running the tests</param>
            <param name="SqlInstance">The full name of the instance running the tests</param>
            <param name="LinkedServerName">The name of the linked server, the connectivity with whom was tested</param>
            <param name="RemoteServer">The name of the remote computer running the linked server.</param>
            <param name="Connectivity">The test result</param>
            <param name="Result">Text interpretation of the result. Contains error messages if the test failed.</param>
        </member>
    </members>
</doc>
tools\dbatools\bin\diagnosticquery\SQLServerDiagnosticQueries_2005_201811.sql

-- SQL Server 2005 Diagnostic Information Queries
-- Glenn Berry 
-- Last Modified: January 7, 2019
-- https://www.sqlserverperformance.wordpress.com/
-- https://www.sqlskills.com/blogs/glenn/
-- Twitter: GlennAlanBerry

-- Please listen to my Pluralsight courses
-- https://www.pluralsight.com/author/glenn-berry

-- If you want to find all of our SQLskills SQL101 blog posts, check out https://www.sqlskills.com/help/sql101/

-- Many of these queries will not work if you have databases in 80 compatibility mode
-- Please make sure you are using the correct version of these diagnostic queries for your version of SQL Server

--******************************************************************************
--*   Copyright (C) 2019 Glenn Berry, SQLskills.com
--*   All rights reserved. 
--*
--*   For more scripts and sample code, check out 
--*      https://www.sqlskills.com/blogs/glenn
--*
--*   You may alter this code for your own *non-commercial* purposes. You may
--*   republish altered code as long as you include this copyright and give due credit. 
--*
--*
--*   THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF 
--*   ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED 
--*   TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
--*   PARTICULAR PURPOSE. 
--*
--******************************************************************************

-- Check the major product version to see if it is SQL Server 2005
IF NOT EXISTS (SELECT * WHERE CONVERT(varchar(128), SERVERPROPERTY('ProductVersion')) LIKE '9%')
	BEGIN
		DECLARE @ProductVersion varchar(128); 
		SET @ProductVersion = CONVERT(varchar(128), SERVERPROPERTY('ProductVersion'));
		RAISERROR ('Script does not match the ProductVersion [%s] of this instance. Many of these queries may not work on this version.' , 18 , 16 , @ProductVersion);
	END
	ELSE
		PRINT N'You have the correct major version of SQL Server for this diagnostic information script';


-- SQL Version information for current instance  (Query 1) (Version Info)
SELECT @@SERVERNAME AS [Server Name], @@VERSION AS [SQL Server and OS Version Info];
------

-- SQL Server 2005 is out of both mainstream and extended support from Microsoft
-- Build 9.0.5266 was the last cumulative update


--   SQL 2005 SP2 Builds             SQL 2005 SP3 Builds            SQL 2005 SP4 Builds
-- Build          Description         Build         Description     Build		   Description
-- 9.0.3042        SP2 RTM			  9.0.4035        SP3 RTM
-- 9.0.3161        SP2 CU1			  9.0.4207        SP3 CU1
-- 9.0.3175        SP2 CU2			  9.0.4211        SP3 CU2 
-- 9.0.3186        SP2 CU3			  9.0.4220       SP3 CU3         
-- 9.0.3200        SP2 CU4			  9.0.4226        SP3 CU4         
-- 9.0.3215        SP2 CU5			  9.0.4230		  SP3 CU5          
-- 9.0.3228		   SP2 CU6			  9.0.4266        SP3 CU6        
-- 9.0.3239        SP2 CU7			  9.0.4273		  SP3 CU7        
-- 9.0.3257        SP2 CU8			  9.0.4285        SP3 CU8
-- 9.0.3282        SP2 CU9			  9.0.4294		  SP3 CU9
-- 9.0.3294		   SP2 CU10			  9.0.4305        SP3 CU10
-- 9.0.3301		   SP2 CU11			  9.0.4309		  SP3 CU11  ---> 9.0.5000		SP4 RTM
-- 9.0.3315        SP2 CU12           9.0.4311        SP3 CU12  ---> 9.0.5254       SP4 CU1		12/22/2010
-- 9.0.3325		   SP2 CU13			  9.0.4315		  SP3 CU13
-- 9.0.3328        SP2 CU14			  9.0.4317		  SP3 CU14	---> 9.0.5259		SP4 CU2		 2/21/2011
-- 9.0.3330        SP2 CU15			  9.0.4325		  SP3 CU15	---> 9.0.5266		SP4 CU3      3/21/2011
-- 9.0.3355        SP2 CU16
-- 9.0.3356		   SP2 CU17



-- The SQL Server 2005 builds that were released after SQL Server 2005 Service Pack 2 was released
-- http://support.microsoft.com/kb/937137

-- The SQL Server 2005 builds that were released after SQL Server 2005 Service Pack 3 was released
-- http://support.microsoft.com/kb/960598

-- The SQL Server 2005 builds that were released after SQL Server 2005 Service Pack 4 was released 
-- http://support.microsoft.com/kb/2485757

-- SQL Server 2005 fell out of Mainsteam Support on April 12, 2011
-- This means no more Service Packs or Cumulative Updates
-- SQL Server 2005 ended Extended Support on April 12, 2016 

-- SQL Server 2005 Service Pack 4
-- http://www.microsoft.com/en-us/download/details.aspx?id=7218



-- When was SQL Server installed  (Query 2) (SQL Server Install Date)  
SELECT @@SERVERNAME AS [Server Name], create_date AS [SQL Server Install Date] 
FROM sys.server_principals WITH (NOLOCK)
WHERE name = N'NT AUTHORITY\SYSTEM'
OR name = N'NT AUTHORITY\NETWORK SERVICE' OPTION (RECOMPILE);
------

-- Tells you the date and time that SQL Server was installed
-- It is a good idea to know how old your instance is



-- Get selected server properties (Query 3) (Server Properties)
SELECT SERVERPROPERTY('MachineName') AS [MachineName], SERVERPROPERTY('ServerName') AS [ServerName],  
SERVERPROPERTY('InstanceName') AS [Instance], SERVERPROPERTY('IsClustered') AS [IsClustered], 
SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS [ComputerNamePhysicalNetBIOS], 
SERVERPROPERTY('Edition') AS [Edition], SERVERPROPERTY('ProductLevel') AS [ProductLevel], 
SERVERPROPERTY('ProductVersion') AS [ProductVersion], SERVERPROPERTY('ProcessID') AS [ProcessID],
SERVERPROPERTY('Collation') AS [Collation], SERVERPROPERTY('IsFullTextInstalled') AS [IsFullTextInstalled], 
SERVERPROPERTY('IsIntegratedSecurityOnly') AS [IsIntegratedSecurityOnly];
------

-- This gives you a lot of useful information about your instance of SQL Server,
-- such as the ProcessID for SQL Server and your collation


-- Get SQL Server Agent jobs and Category information (Query 4) (SQL Server Agent Jobs)
SELECT sj.name AS [Job Name], sj.[description] AS [Job Description], SUSER_SNAME(sj.owner_sid) AS [Job Owner],
sj.date_created AS [Date Created], sj.[enabled] AS [Job Enabled], 
sj.notify_email_operator_id, sj.notify_level_email, sc.name AS [CategoryName],
s.[enabled] AS [Sched Enabled], js.next_run_date, js.next_run_time
FROM msdb.dbo.sysjobs AS sj WITH (NOLOCK)
INNER JOIN msdb.dbo.syscategories AS sc WITH (NOLOCK)
ON sj.category_id = sc.category_id
LEFT OUTER JOIN msdb.dbo.sysjobschedules AS js WITH (NOLOCK)
ON sj.job_id = js.job_id
LEFT OUTER JOIN msdb.dbo.sysschedules AS s WITH (NOLOCK)
ON js.schedule_id = s.schedule_id
ORDER BY sj.name OPTION (RECOMPILE);
------

-- Gives you some basic information about your SQL Server Agent jobs, who owns them and how they are configured
-- Look for Agent jobs that are not owned by sa
-- Look for jobs that have a notify_email_operator_id set to 0 (meaning no operator)
-- Look for jobs that have a notify_level_email set to 0 (meaning no e-mail is ever sent)
--
-- MSDN sysjobs documentation
-- http://msdn.microsoft.com/en-us/library/ms189817.aspx


-- Get SQL Server Agent Alert Information (Query 5) (SQL Server Agent Alerts)
SELECT name, event_source, message_id, severity, [enabled], has_notification, 
       delay_between_responses, occurrence_count, last_occurrence_date, last_occurrence_time
FROM msdb.dbo.sysalerts WITH (NOLOCK)
ORDER BY name OPTION (RECOMPILE);
------

-- Gives you some basic information about your SQL Server Agent Alerts (which are different from SQL Server Agent jobs)
-- Read more about Agent Alerts here: https://www.sqlskills.com/blogs/glenn/creating-sql-server-agent-alerts-for-critical-errors/


-- Returns a list of all global trace flags that are enabled (Query 6) (Global Trace Flags)
DBCC TRACESTATUS (-1);
------
 
-- If no global trace flags are enabled, no results will be returned.
-- It is very useful to know what global trace flags are currently enabled as part of the diagnostic process.

-- Common trace flags that should be enabled in most cases
-- TF 1117 - When growing a data file, grow all files at the same time so they remain the same size, reducing allocation contention points
--           http://support2.microsoft.com/kb/2154845
-- 
-- TF 1118 - Helps alleviate allocation contention in tempdb, SQL Server allocates full extents to each database object, 
--           thereby eliminating the contention on SGAM pages (more important with older versions of SQL Server)
--           Recommendations to reduce allocation contention in SQL Server tempdb database
--           http://support2.microsoft.com/kb/2154845

-- TF 3226 - Supresses logging of successful database backup messages to the SQL Server Error Log
--           https://www.sqlskills.com/blogs/paul/fed-up-with-backup-success-messages-bloating-your-error-logs/


-- Hardware Information from SQL Server 2005  (Query 7) (Hardware Info)
-- (Cannot distinguish between HT and multi-core)
SELECT cpu_count AS [Logical CPU Count], hyperthread_ratio AS [Hyperthread Ratio],
cpu_count/hyperthread_ratio AS [Physical CPU Count], 
physical_memory_in_bytes/1048576 AS [Physical Memory (MB)]
FROM sys.dm_os_sys_info WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Gives you some good basic hardware information about your database server


-- Get System Manufacturer and model number from (Query 8) (System Manufacturer)
-- SQL Server Error log. This query might take a few seconds 
-- if you have not recycled your error log recently  
EXEC sys.xp_readerrorlog 0, 1, N'Manufacturer';
------  

-- This can help you determine the capabilities
-- and capacities of your database server
-- This often comes back with no results on SQL Server 2005


-- Get processor description from Windows Registry  (Query 9) (Processor Description)
EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'HARDWARE\DESCRIPTION\System\CentralProcessor\0', N'ProcessorNameString';
------

-- Gives you the model number and rated clock speed of your processor(s)
-- Your processors may be running at less that the rated clock speed due
-- to the Windows Power Plan or hardware power management

-- You can use CPU-Z to get your actual CPU core speed and a lot of other useful information
-- http://www.cpuid.com/softwares/cpu-z.html

-- You can learn more about processor selection for SQL Server by following this link
-- https://www.sqlskills.com/blogs/glenn/processor-selection-for-sql-server/



-- Get configuration values for instance  (Query 10) (Configuration Values)
SELECT name, value, value_in_use, minimum, maximum, [description], is_dynamic, is_advanced
FROM sys.configurations WITH (NOLOCK)
ORDER BY name OPTION (RECOMPILE);
------

-- Focus on these settings:)
-- backup compression default (should be 1 in most cases)
-- clr enabled (only enable if it is needed)
-- cost threshold for parallelism (depends on your workload)
-- lightweight pooling (should be zero)
-- max degree of parallelism (depends on your workload)
-- max server memory (MB) (set to an appropriate value, not the default)
-- priority boost (should be zero)
-- remote admin connections (should be 1)


-- File names and paths for all user and system databases on instance  (Query 11) (Database Filenames and Paths)
SELECT DB_NAME([database_id]) AS [Database Name], 
       [file_id], [name], physical_name, [type_desc], state_desc,
	   is_percent_growth, growth,
	   CONVERT(bigint, growth/128.0) AS [Growth in MB], 
       CONVERT(bigint, size/128.0) AS [Total Size in MB]
FROM sys.master_files WITH (NOLOCK)
ORDER BY DB_NAME([database_id]), [file_id] OPTION (RECOMPILE);
------

-- Things to look at:
-- Are data files and log files on different drives?
-- Is everything on the C: drive?
-- Is TempDB on dedicated drives?
-- Is there only one TempDB data file?
-- Are all of the TempDB data files the same size?
-- Are there multiple data files for user databases?
-- Is percent growth enabled for any files (which is bad)?


-- Look for I/O requests taking longer than 15 seconds in the five most recent SQL Server Error Logs (Query 12) (IO Warnings)
CREATE TABLE #IOWarningResults(LogDate datetime, ProcessInfo sysname, LogText nvarchar(1000));

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 0, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 1, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 2, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 3, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 4, 1, N'taking longer than 15 seconds';

SELECT LogDate, ProcessInfo, LogText
FROM #IOWarningResults
ORDER BY LogDate DESC;

DROP TABLE #IOWarningResults; 
------ 

-- Finding 15 second I/O warnings in the SQL Server Error Log is useful evidence of
-- poor I/O performance (which might have many different causes)
-- Look to see if you see any patterns in the results (same files, same drives, same time of day, etc.)

-- Diagnostics in SQL Server help detect stalled and stuck I/O operations
-- https://support.microsoft.com/en-us/kb/897284


-- Drive level latency information (Query 13) (Drive Level Latency)
-- Based on code from Jimmy May
SELECT tab.[Drive],  
	CASE 
		WHEN num_of_reads = 0 THEN 0 
		ELSE (io_stall_read_ms/num_of_reads) 
	END AS [Read Latency],
	CASE 
		WHEN num_of_writes = 0 THEN 0 
		ELSE (io_stall_write_ms/num_of_writes) 
	END AS [Write Latency],
	CASE 
		WHEN (num_of_reads = 0 AND num_of_writes = 0) THEN 0 
		ELSE (io_stall/(num_of_reads + num_of_writes)) 
	END AS [Overall Latency],
	CASE 
		WHEN num_of_reads = 0 THEN 0 
		ELSE (num_of_bytes_read/num_of_reads) 
	END AS [Avg Bytes/Read],
	CASE 
		WHEN num_of_writes = 0 THEN 0 
		ELSE (num_of_bytes_written/num_of_writes) 
	END AS [Avg Bytes/Write],
	CASE 
		WHEN (num_of_reads = 0 AND num_of_writes = 0) THEN 0 
		ELSE ((num_of_bytes_read + num_of_bytes_written)/(num_of_reads + num_of_writes)) 
	END AS [Avg Bytes/Transfer]
FROM (SELECT LEFT(UPPER(mf.physical_name), 2) AS Drive, SUM(num_of_reads) AS num_of_reads,
	         SUM(io_stall_read_ms) AS io_stall_read_ms, SUM(num_of_writes) AS num_of_writes,
	         SUM(io_stall_write_ms) AS io_stall_write_ms, SUM(num_of_bytes_read) AS num_of_bytes_read,
	         SUM(num_of_bytes_written) AS num_of_bytes_written, SUM(io_stall) AS io_stall
      FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS vfs
      INNER JOIN sys.master_files AS mf WITH (NOLOCK)
      ON vfs.database_id = mf.database_id AND vfs.file_id = mf.file_id
      GROUP BY LEFT(UPPER(mf.physical_name), 2)) AS tab
ORDER BY [Overall Latency] OPTION (RECOMPILE);
------

-- Shows you the drive-level latency for reads and writes, in milliseconds
-- Latency above 20-25ms is usually a problem


-- Calculates average stalls per read, per write, and per total input/output for each database file  (Query 14) (IO Stalls by File)
SELECT DB_NAME(fs.database_id) AS [Database Name], CAST(fs.io_stall_read_ms/(1.0 + fs.num_of_reads) AS NUMERIC(16,1)) AS [avg_read_stall_ms],
CAST(fs.io_stall_write_ms/(1.0 + fs.num_of_writes) AS NUMERIC(16,1)) AS [avg_write_stall_ms],
CAST((fs.io_stall_read_ms + fs.io_stall_write_ms)/(1.0 + fs.num_of_reads + fs.num_of_writes) AS NUMERIC(16,1)) AS [avg_io_stall_ms],
CONVERT(DECIMAL(18,2), mf.size/128.0) AS [File Size (MB)], mf.physical_name, mf.type_desc, fs.io_stall_read_ms, fs.num_of_reads, 
fs.io_stall_write_ms, fs.num_of_writes, fs.io_stall_read_ms + fs.io_stall_write_ms AS [io_stalls], fs.num_of_reads + fs.num_of_writes AS [total_io]
FROM sys.dm_io_virtual_file_stats(null,null) AS fs
INNER JOIN sys.master_files AS mf WITH (NOLOCK)
ON fs.database_id = mf.database_id
AND fs.[file_id] = mf.[file_id]
ORDER BY avg_io_stall_ms DESC OPTION (RECOMPILE);
------

-- Helps determine which database files on the entire instance have the most I/O bottlenecks
-- This can help you decide whether certain LUNs are overloaded and whether you might
-- want to move some files to a different location or perhaps improve your I/O performance


-- Recovery model, log reuse wait description, log file size, log usage size (Query 15) (Database Properties)
-- and compatibility level for all databases on instance
SELECT db.[name] AS [Database Name], SUSER_SNAME(db.owner_sid) AS [Database Owner], db.recovery_model_desc AS [Recovery Model], 
db.log_reuse_wait_desc AS [Log Reuse Wait Description], 
ls.cntr_value AS [Log Size (KB)], lu.cntr_value AS [Log Used (KB)],
CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log Used %], 
db.[compatibility_level] AS [DB Compatibility Level], 
db.page_verify_option_desc AS [Page Verify Option], db.is_auto_create_stats_on, db.is_auto_update_stats_on,
db.is_auto_update_stats_async_on, db.is_parameterization_forced, 
db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on,
db.is_auto_close_on, db.is_auto_shrink_on, db.is_published
FROM sys.databases AS db WITH (NOLOCK)
INNER JOIN sys.dm_os_performance_counters AS lu WITH (NOLOCK)
ON db.name = lu.instance_name
INNER JOIN sys.dm_os_performance_counters AS ls WITH (NOLOCK)
ON db.name = ls.instance_name
WHERE lu.counter_name LIKE N'Log File(s) Used Size (KB)%' 
AND ls.counter_name LIKE N'Log File(s) Size (KB)%'
AND ls.cntr_value > 0 OPTION (RECOMPILE);
------

-- Things to look at:
-- How many databases are on the instance?
-- What recovery models are they using?
-- What is the log reuse wait description?
-- How full are the transaction logs ?
-- What compatibility level are the databases on? 
-- What is the Page Verify Option? (should be CHECKSUM)
-- Is Auto Update Statistics Asynchronously enabled?
-- Make sure auto_shrink and auto_close are not enabled!



-- Missing Indexes for all databases by Index Advantage  (Query 16) (Missing Indexes All Databases)
SELECT CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage], 
migs.last_user_seek, mid.[statement] AS [Database.Schema.Table],
mid.equality_columns, mid.inequality_columns, mid.included_columns,
migs.unique_compiles, migs.user_seeks, migs.avg_total_user_cost, migs.avg_user_impact
FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)
INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)
ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)
ON mig.index_handle = mid.index_handle
ORDER BY index_advantage DESC OPTION (RECOMPILE);
------

-- Getting missing index information for all of the databases on the instance is very useful
-- Look at last user seek time, number of user seeks to help determine source and importance
-- Also look at avg_user_impact and avg_total_user_cost to help determine importance
-- SQL Server is overly eager to add included columns, so beware
-- Do not just blindly add indexes that show up from this query!!!



-- Get VLF Counts for all databases on the instance (Query 17) (VLF Counts)
-- (adapted from Michelle Ufford) 
CREATE TABLE #VLFInfo (FileID  int,
					   FileSize bigint, StartOffset bigint,
					   FSeqNo      bigint, [Status]    bigint,
					   Parity      bigint, CreateLSN   numeric(38));
	 
CREATE TABLE #VLFCountResults(DatabaseName sysname, VLFCount int);
	 
EXEC sp_MSforeachdb N'Use [?]; 

				INSERT INTO #VLFInfo 
				EXEC sp_executesql N''DBCC LOGINFO([?])''; 
	 
				INSERT INTO #VLFCountResults 
				SELECT DB_NAME(), COUNT(*) 
				FROM #VLFInfo; 

				TRUNCATE TABLE #VLFInfo;'
	 
SELECT DatabaseName, VLFCount  
FROM #VLFCountResults
ORDER BY VLFCount DESC;
	 
DROP TABLE #VLFInfo;
DROP TABLE #VLFCountResults;
------

-- High VLF counts can affect write performance 
-- and they can make full database restores and crash recovery take much longer
-- Try to keep your VLF counts under 200 in most cases



-- Get CPU utilization by database (Query 18) (CPU Usage by Database)
WITH DB_CPU_Stats
AS
(SELECT pa.DatabaseID, DB_Name(pa.DatabaseID) AS [Database Name], SUM(qs.total_worker_time/1000) AS [CPU_Time_Ms]
 FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
 CROSS APPLY (SELECT CONVERT(int, value) AS [DatabaseID] 
              FROM sys.dm_exec_plan_attributes(qs.plan_handle)
              WHERE attribute = N'dbid') AS pa
 GROUP BY DatabaseID)
SELECT ROW_NUMBER() OVER(ORDER BY [CPU_Time_Ms] DESC) AS [CPU Rank],
       [Database Name], [CPU_Time_Ms] AS [CPU Time (ms)], 
       CAST([CPU_Time_Ms] * 1.0 / SUM([CPU_Time_Ms]) OVER() * 100.0 AS DECIMAL(5, 2)) AS [CPU Percent]
FROM DB_CPU_Stats
WHERE DatabaseID <> 32767 -- ResourceDB
ORDER BY [CPU Rank] OPTION (RECOMPILE);
------

-- Helps determine which database is using the most CPU resources on the instance
-- Note: This only reflects CPU usage from the currently cached query plans


-- Get I/O utilization by database (Query 19) (IO Usage By Database)
WITH Aggregate_IO_Statistics
AS
(SELECT DB_NAME(database_id) AS [Database Name],
CAST(SUM(num_of_bytes_read + num_of_bytes_written)/1048576 AS DECIMAL(12, 2)) AS io_in_mb
FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS [DM_IO_STATS]
GROUP BY database_id)
SELECT ROW_NUMBER() OVER(ORDER BY io_in_mb DESC) AS [I/O Rank], [Database Name], io_in_mb AS [Total I/O (MB)],
       CAST(io_in_mb/ SUM(io_in_mb) OVER() * 100.0 AS DECIMAL(5,2)) AS [I/O Percent]
FROM Aggregate_IO_Statistics
ORDER BY [I/O Rank] OPTION (RECOMPILE);
------

-- Helps determine which database is using the most I/O resources on the instance


-- Get total buffer usage by database for current instance (Query 20) (Total Buffer Usage by Database)
-- This make take some time to run on a busy instance
WITH AggregateBufferPoolUsage
AS
(SELECT DB_NAME(database_id) AS [Database Name],
CAST(COUNT(*) * 8/1024.0 AS DECIMAL (10,2))  AS [CachedSize]
FROM sys.dm_os_buffer_descriptors WITH (NOLOCK)
WHERE database_id <> 32767 -- ResourceDB
GROUP BY DB_NAME(database_id))
SELECT ROW_NUMBER() OVER(ORDER BY CachedSize DESC) AS [Buffer Pool Rank], [Database Name], CachedSize AS [Cached Size (MB)],
       CAST(CachedSize / SUM(CachedSize) OVER() * 100.0 AS DECIMAL(5,2)) AS [Buffer Pool Percent]
FROM AggregateBufferPoolUsage
ORDER BY [Buffer Pool Rank] OPTION (RECOMPILE);
------

-- Tells you how much memory (in the buffer pool) 
-- is being used by each database on the instance


-- Clear Wait Stats with this command
-- DBCC SQLPERF('sys.dm_os_wait_stats', CLEAR);

-- Isolate top waits for server instance since last restart or wait statistics clear (Query 21) (Top Waits)
WITH [Waits] 
AS (SELECT wait_type, wait_time_ms/ 1000.0 AS [WaitS],
          (wait_time_ms - signal_wait_time_ms) / 1000.0 AS [ResourceS],
           signal_wait_time_ms / 1000.0 AS [SignalS],
           waiting_tasks_count AS [WaitCount],
           100.0 *  wait_time_ms / SUM (wait_time_ms) OVER() AS [Percentage],
           ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS [RowNum]
    FROM sys.dm_os_wait_stats WITH (NOLOCK)
    WHERE [wait_type] NOT IN (
        N'BROKER_EVENTHANDLER', N'BROKER_RECEIVE_WAITFOR', N'BROKER_TASK_STOP',
		N'BROKER_TO_FLUSH', N'BROKER_TRANSMITTER', N'CHECKPOINT_QUEUE',
        N'CHKPT', N'CLR_AUTO_EVENT', N'CLR_MANUAL_EVENT', N'CLR_SEMAPHORE',
        N'DBMIRROR_DBM_EVENT', N'DBMIRROR_EVENTS_QUEUE', N'DBMIRROR_WORKER_QUEUE',
		N'DBMIRRORING_CMD', N'DIRTY_PAGE_POLL', N'DISPATCHER_QUEUE_SEMAPHORE',
        N'EXECSYNC', N'FSAGENT', N'FT_IFTS_SCHEDULER_IDLE_WAIT', N'FT_IFTSHC_MUTEX',
        N'HADR_CLUSAPI_CALL', N'HADR_FILESTREAM_IOMGR_IOCOMPLETION', N'HADR_LOGCAPTURE_WAIT', 
		N'HADR_NOTIFICATION_DEQUEUE', N'HADR_TIMER_TASK', N'HADR_WORK_QUEUE',
        N'KSOURCE_WAKEUP', N'LAZYWRITER_SLEEP', N'LOGMGR_QUEUE', N'ONDEMAND_TASK_QUEUE',
        N'PWAIT_ALL_COMPONENTS_INITIALIZED', N'QDS_PERSIST_TASK_MAIN_LOOP_SLEEP',
        N'QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP', N'REQUEST_FOR_DEADLOCK_SEARCH',
		N'RESOURCE_QUEUE', N'SERVER_IDLE_CHECK', N'SLEEP_BPOOL_FLUSH', N'SLEEP_DBSTARTUP',
		N'SLEEP_DCOMSTARTUP', N'SLEEP_MASTERDBREADY', N'SLEEP_MASTERMDREADY',
        N'SLEEP_MASTERUPGRADED', N'SLEEP_MSDBSTARTUP', N'SLEEP_SYSTEMTASK', N'SLEEP_TASK',
        N'SLEEP_TEMPDBSTARTUP', N'SNI_HTTP_ACCEPT', N'SP_SERVER_DIAGNOSTICS_SLEEP',
		N'SQLTRACE_BUFFER_FLUSH', N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', N'SQLTRACE_WAIT_ENTRIES',
		N'WAIT_FOR_RESULTS', N'WAITFOR', N'WAITFOR_TASKSHUTDOWN', N'WAIT_XTP_HOST_WAIT',
		N'WAIT_XTP_OFFLINE_CKPT_NEW_LOG', N'WAIT_XTP_CKPT_CLOSE', N'XE_DISPATCHER_JOIN',
        N'XE_DISPATCHER_WAIT', N'XE_TIMER_EVENT')
    AND waiting_tasks_count > 0)
SELECT
    MAX (W1.wait_type) AS [WaitType],
	CAST (MAX (W1.Percentage) AS DECIMAL (5,2)) AS [Wait Percentage],
	CAST ((MAX (W1.WaitS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgWait_Sec],
    CAST ((MAX (W1.ResourceS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgRes_Sec],
    CAST ((MAX (W1.SignalS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgSig_Sec], 
    CAST (MAX (W1.WaitS) AS DECIMAL (16,2)) AS [Wait_Sec],
    CAST (MAX (W1.ResourceS) AS DECIMAL (16,2)) AS [Resource_Sec],
    CAST (MAX (W1.SignalS) AS DECIMAL (16,2)) AS [Signal_Sec],
    MAX (W1.WaitCount) AS [Wait Count],
	CAST (N'https://www.sqlskills.com/help/waits/' + W1.wait_type AS XML) AS [Help/Info URL]
FROM Waits AS W1
INNER JOIN Waits AS W2
ON W2.RowNum <= W1.RowNum
GROUP BY W1.RowNum, W1.wait_type
HAVING SUM (W2.Percentage) - MAX (W1.Percentage) < 99 -- percentage threshold
OPTION (RECOMPILE);
------

-- Cumulative wait stats are not as useful on an idle instance that is not under load or performance pressure

-- SQL Server Wait Types Library (Paul Randal)
-- https://www.sqlskills.com/help/waits/

-- The SQL Server Wait Type Repository
-- http://blogs.msdn.com/b/psssql/archive/2009/11/03/the-sql-server-wait-type-repository.aspx

-- Wait statistics, or please tell me where it hurts
-- https://www.sqlskills.com/blogs/paul/wait-statistics-or-please-tell-me-where-it-hurts/

-- SQL Server 2005 Performance Tuning using the Waits and Queues
-- http://technet.microsoft.com/en-us/library/cc966413.aspx

-- sys.dm_os_wait_stats (Transact-SQL)
-- http://msdn.microsoft.com/en-us/library/ms179984(v=sql.105).aspx



-- Signal Waits for instance  (Query 22) (Signal Waits)
SELECT CAST(100.0 * SUM(signal_wait_time_ms) / SUM (wait_time_ms) AS NUMERIC(20,2)) AS [% Signal (CPU) Waits],
CAST(100.0 * SUM(wait_time_ms - signal_wait_time_ms) / SUM (wait_time_ms) AS NUMERIC(20,2)) AS [% Resource Waits]
FROM sys.dm_os_wait_stats WITH (NOLOCK)
WHERE wait_type NOT IN (
        N'BROKER_EVENTHANDLER', N'BROKER_RECEIVE_WAITFOR', N'BROKER_TASK_STOP',
		N'BROKER_TO_FLUSH', N'BROKER_TRANSMITTER', N'CHECKPOINT_QUEUE',
        N'CHKPT', N'CLR_AUTO_EVENT', N'CLR_MANUAL_EVENT', N'CLR_SEMAPHORE',
        N'DBMIRROR_DBM_EVENT', N'DBMIRROR_EVENTS_QUEUE', N'DBMIRROR_WORKER_QUEUE',
		N'DBMIRRORING_CMD', N'DIRTY_PAGE_POLL', N'DISPATCHER_QUEUE_SEMAPHORE',
        N'EXECSYNC', N'FSAGENT', N'FT_IFTS_SCHEDULER_IDLE_WAIT', N'FT_IFTSHC_MUTEX',
        N'HADR_CLUSAPI_CALL', N'HADR_FILESTREAM_IOMGR_IOCOMPLETION', N'HADR_LOGCAPTURE_WAIT', 
		N'HADR_NOTIFICATION_DEQUEUE', N'HADR_TIMER_TASK', N'HADR_WORK_QUEUE',
        N'KSOURCE_WAKEUP', N'LAZYWRITER_SLEEP', N'LOGMGR_QUEUE', N'ONDEMAND_TASK_QUEUE',
        N'PWAIT_ALL_COMPONENTS_INITIALIZED', N'QDS_PERSIST_TASK_MAIN_LOOP_SLEEP',
        N'QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP', N'REQUEST_FOR_DEADLOCK_SEARCH',
		N'RESOURCE_QUEUE', N'SERVER_IDLE_CHECK', N'SLEEP_BPOOL_FLUSH', N'SLEEP_DBSTARTUP',
		N'SLEEP_DCOMSTARTUP', N'SLEEP_MASTERDBREADY', N'SLEEP_MASTERMDREADY',
        N'SLEEP_MASTERUPGRADED', N'SLEEP_MSDBSTARTUP', N'SLEEP_SYSTEMTASK', N'SLEEP_TASK',
        N'SLEEP_TEMPDBSTARTUP', N'SNI_HTTP_ACCEPT', N'SP_SERVER_DIAGNOSTICS_SLEEP',
		N'SQLTRACE_BUFFER_FLUSH', N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', N'SQLTRACE_WAIT_ENTRIES',
		N'WAIT_FOR_RESULTS', N'WAITFOR', N'WAITFOR_TASKSHUTDOWN', N'WAIT_XTP_HOST_WAIT',
		N'WAIT_XTP_OFFLINE_CKPT_NEW_LOG', N'WAIT_XTP_CKPT_CLOSE', N'XE_DISPATCHER_JOIN',
        N'XE_DISPATCHER_WAIT', N'XE_TIMER_EVENT') OPTION (RECOMPILE);
------

-- Signal Waits above 10-15% is usually a confirming sign of CPU pressure
-- Cumulative wait stats are not as useful on an idle instance that is not under load or performance pressure
-- Resource waits are non-CPU related waits


--  Get logins that are connected and how many sessions they have (Query 23) (Connection Counts)
SELECT login_name, [program_name], COUNT(session_id) AS [session_count] 
FROM sys.dm_exec_sessions WITH (NOLOCK)
GROUP BY login_name, [program_name]
ORDER BY COUNT(session_id) DESC OPTION (RECOMPILE);
------

-- This can help characterize your workload and
-- determine whether you are seeing a normal level of activity


-- Get a count of SQL connections by IP address (Query 24) (Connection Counts by IP Address)
SELECT ec.client_net_address, es.[program_name], es.[host_name], es.login_name, 
COUNT(ec.session_id) AS [connection count] 
FROM sys.dm_exec_sessions AS es WITH (NOLOCK) 
INNER JOIN sys.dm_exec_connections AS ec WITH (NOLOCK) 
ON es.session_id = ec.session_id 
GROUP BY ec.client_net_address, es.[program_name], es.[host_name], es.login_name  
ORDER BY ec.client_net_address, es.[program_name] OPTION (RECOMPILE);
------

-- This helps you figure where your database load is coming from
-- and verifies connectivity from other machines


-- Get Average Task Counts (run multiple times) (Query 25) (Avg Task Counts)
SELECT AVG(current_tasks_count) AS [Avg Task Count], 
AVG(runnable_tasks_count) AS [Avg Runnable Task Count],
AVG(pending_disk_io_count) AS [Avg Pending DiskIO Count]
FROM sys.dm_os_schedulers WITH (NOLOCK)
WHERE scheduler_id < 255 OPTION (RECOMPILE);
------

-- Sustained values above 10 suggest further investigation in that area
-- High Avg Task Counts are often caused by blocking/deadlocking or other resource contention

-- Sustained values above 1 suggest further investigation in that area
-- High Avg Runnable Task Counts are a good sign of CPU pressure
-- High Avg Pending DiskIO Counts are a sign of disk pressure

-- How to Do Some Very Basic SQL Server Monitoring
-- https://www.sqlskills.com/blogs/glenn/how-to-do-some-very-basic-sql-server-monitoring/



-- Get CPU Utilization History for last 256 minutes (in one minute intervals) (Query 26) (CPU Utilization History)
-- This version works with SQL Server 2005
DECLARE @ts_now bigint; 
SET @ts_now = (SELECT cpu_ticks / CONVERT(float, cpu_ticks_in_ms) FROM sys.dm_os_sys_info WITH (NOLOCK)); 

SELECT TOP(256) SQLProcessUtilization AS [SQL Server Process CPU Utilization], 
               SystemIdle AS [System Idle Process], 
               100 - SystemIdle - SQLProcessUtilization AS [Other Process CPU Utilization], 
               DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) AS [Event Time] 
FROM ( 
	  SELECT record.value('(./Record/@id)[1]', 'int') AS record_id, 
			record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') 
			AS [SystemIdle], 
			record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 
			'int') 
			AS [SQLProcessUtilization], [timestamp] 
	  FROM ( 
			SELECT [timestamp], CONVERT(xml, record) AS [record] 
			FROM sys.dm_os_ring_buffers WITH (NOLOCK)
			WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR' 
			AND record LIKE '%<SystemHealth>%') AS x 
	  ) AS y 
ORDER BY record_id DESC OPTION (RECOMPILE);
------

-- Look at the trend over the entire period. 
-- Also look at high sustained Other Process CPU Utilization values


-- Page Life Expectancy (PLE) value for each NUMA node in current instance  (Query 27) (PLE by NUMA Node)
SELECT @@SERVERNAME AS [Server Name], RTRIM([object_name]) AS [Object Name], instance_name, cntr_value AS [Page Life Expectancy]
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Buffer Node%' -- Handles named instances
AND counter_name = N'Page life expectancy' OPTION (RECOMPILE);
------

-- PLE is a good measurement of memory pressure.
-- Higher PLE is better. Watch the trend over time, not the absolute value.
-- This will only return one row for non-NUMA systems.

-- Page Life Expectancy isn�t what you think�
-- https://www.sqlskills.com/blogs/paul/page-life-expectancy-isnt-what-you-think/



-- Memory Grants Pending value for current instance (Query 28) (Memory Grants Pending)
SELECT @@SERVERNAME AS [Server Name], RTRIM([object_name]) AS [Object Name], cntr_value AS [Memory Grants Pending]                                                                                                       
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Memory Manager%' -- Handles named instances
AND counter_name = N'Memory Grants Pending' OPTION (RECOMPILE);
------

-- Memory Grants Pending above zero for a sustained period is a very strong indicator of memory pressure


-- Memory Clerk Usage for instance  (Query 29) (Memory Clerk Usage)
-- Look for high value for CACHESTORE_SQLCP (Ad-hoc query plans)
SELECT TOP(10) [type] AS [Memory Clerk Type], SUM(single_pages_kb)/1024 AS [SPA Memory Usage (MB)] 
FROM sys.dm_os_memory_clerks WITH (NOLOCK)
GROUP BY [type]  
ORDER BY SUM(single_pages_kb) DESC OPTION (RECOMPILE);
------

-- CACHESTORE_SQLCP  SQL Plans         
-- These are cached SQL statements or batches that aren't in stored procedures, functions and triggers
-- Watch out for high values for CACHESTORE_SQLCP

-- CACHESTORE_OBJCP  Object Plans      
-- These are compiled plans for stored procedures, functions and triggers



-- Find single-use, ad-hoc queries that are bloating the plan cache (Query 30) (Ad hoc Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], t.[text] AS [Query Text], 
cp.objtype AS [Object Type], cp.cacheobjtype AS [Cache Object Type],  
cp.size_in_bytes/1024 AS [Plan Size in KB]
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t
WHERE cp.cacheobjtype = N'Compiled Plan' 
AND cp.objtype IN (N'Adhoc', N'Prepared') 
AND cp.usecounts = 1
ORDER BY cp.size_in_bytes DESC, DB_NAME(t.[dbid]) OPTION (RECOMPILE);
------

-- Gives you the text and size of single-use ad-hoc queries that waste space in plan cache
-- SQL Server Agent creates lots of ad-hoc, single use query plans in SQL Server 2005
-- Running DBCC FREESYSTEMCACHE ('SQL Plans') periodically may be required to better control this.
-- Enabling forced parameterization for the database can help, but test first!

-- Plan cache, adhoc workloads and clearing the single-use plan cache bloat
-- https://www.sqlskills.com/blogs/kimberly/plan-cache-adhoc-workloads-and-clearing-the-single-use-plan-cache-bloat/



-- Database specific queries *****************************************************************

-- **** Please switch to a user database that you are interested in! *****
USE YourDatabaseName; -- make sure to change to an actual database on your instance, not the master system database
GO

-- Individual File Sizes and space available for current database  (Query 31) (File Sizes and Space)
SELECT f.name AS [File Name] , f.physical_name AS [Physical Name], 
CAST((f.size/128.0) AS DECIMAL(15,2)) AS [Total Size in MB],
CAST(f.size/128.0 - CAST(FILEPROPERTY(f.name, 'SpaceUsed') AS int)/128.0 AS DECIMAL(15,2)) 
AS [Available Space In MB], [file_id], fg.name AS [Filegroup Name]
FROM sys.database_files AS f WITH (NOLOCK) 
LEFT OUTER JOIN sys.data_spaces AS fg WITH (NOLOCK) 
ON f.data_space_id = fg.data_space_id OPTION (RECOMPILE);
------

-- Look at how large and how full the files are and where they are located
-- Make sure the transaction log is not full!!



-- I/O Statistics by file for the current database  (Query 32) (IO Stats By File)
SELECT DB_NAME(DB_ID()) AS [Database Name], df.name AS [Logical Name], vfs.[file_id], 
df.physical_name AS [Physical Name], vfs.num_of_reads, vfs.num_of_writes, vfs.io_stall_read_ms, vfs.io_stall_write_ms,
CAST(100. * vfs.io_stall_read_ms/(vfs.io_stall_read_ms + vfs.io_stall_write_ms) AS DECIMAL(10,1)) AS [IO Stall Reads Pct],
CAST(100. * vfs.io_stall_write_ms/(vfs.io_stall_write_ms + vfs.io_stall_read_ms) AS DECIMAL(10,1)) AS [IO Stall Writes Pct],
(vfs.num_of_reads + vfs.num_of_writes) AS [Writes + Reads], 
CAST(vfs.num_of_bytes_read/1048576.0 AS DECIMAL(10, 2)) AS [MB Read], 
CAST(vfs.num_of_bytes_written/1048576.0 AS DECIMAL(10, 2)) AS [MB Written],
CAST(100. * vfs.num_of_reads/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(10,1)) AS [# Reads Pct],
CAST(100. * vfs.num_of_writes/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(10,1)) AS [# Write Pct],
CAST(100. * vfs.num_of_bytes_read/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(10,1)) AS [Read Bytes Pct],
CAST(100. * vfs.num_of_bytes_written/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(10,1)) AS [Written Bytes Pct]
FROM sys.dm_io_virtual_file_stats(DB_ID(), NULL) AS vfs
INNER JOIN sys.database_files AS df WITH (NOLOCK)
ON vfs.[file_id]= df.[file_id] OPTION (RECOMPILE);
------

-- This helps you characterize your workload better from an I/O perspective
-- It helps you determine whether you has an OLTP or DW/DSS type of workload



-- Cached SP's By Execution Count (SQL 2005)  (Query 33) (SP Execution Counts)
SELECT TOP(25) OBJECT_NAME(objectid, dbid) AS [SP Name], qt.[text] AS [SP Text], 
qs.execution_count AS [Execution Count],  
qs.execution_count/DATEDIFF(Minute, qs.creation_time, GETDATE()) AS [Calls/Minute],
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime],
qs.total_worker_time AS [TotalWorkerTime],
qs.total_elapsed_time/qs.execution_count AS [AvgElapsedTime],
qs.max_logical_reads, qs.max_logical_writes, qs.total_physical_reads, 
DATEDIFF(Minute, qs.creation_time, GetDate()) AS [Age in Cache]
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(qs.[sql_handle]) AS qt
WHERE qt.[dbid] = DB_ID() 
ORDER BY qs.execution_count DESC OPTION (RECOMPILE);
------

-- Tells you which cached stored procedures are called the most often
-- This helps you characterize and baseline your workload


-- Top Cached SPs By Avg Elapsed Time (SQL 2005)  (Query 34) (SP Avg Elapsed Time)
SELECT TOP(25) OBJECT_NAME(objectid, dbid) AS [SP Name], qt.[text] AS [SP Text],  
ISNULL(qs.total_elapsed_time/qs.execution_count, 0) AS [AvgElapsedTime], 
qs.execution_count AS [Execution Count], qs.total_worker_time AS [TotalWorkerTime], 
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime],
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.creation_time, GETDATE()), 0) AS [Calls/Minute],
qs.max_logical_reads, qs.max_logical_writes, 
DATEDIFF(Minute, qs.creation_time, GETDATE()) AS [Age in Cache]
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(qs.[sql_handle]) AS qt
WHERE qt.[dbid] = DB_ID() 
ORDER BY qs.total_elapsed_time/qs.execution_count DESC OPTION (RECOMPILE);
------

-- This helps you find long-running cached stored procedures that
-- may be easy to optimize with standard query tuning techniques

-- Cached SP's By Worker Time (SQL 2005) Worker time relates to CPU cost  (Query 35) (SP Worker Time)
SELECT TOP(25) OBJECT_NAME(objectid, dbid) AS [SP Name], qt.[text] AS [SP Text], 
qs.total_worker_time AS [TotalWorkerTime], qs.total_worker_time/qs.execution_count AS [AvgWorkerTime],
qs.execution_count AS [Execution Count], 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.creation_time, GETDATE()), 0) AS [Calls/Minute],
ISNULL(qs.total_elapsed_time/qs.execution_count, 0) AS [AvgElapsedTime], 
qs.max_logical_reads, qs.max_logical_writes, 
DATEDIFF(Minute, qs.creation_time, GETDATE()) AS [Age in Cache]
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(qs.[sql_handle]) AS qt
WHERE qt.[dbid] = DB_ID() 
ORDER BY qs.total_worker_time DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a CPU perspective
-- You should look at this if you see signs of CPU pressure

-- Cached SP's By Logical Reads (SQL 2005) Logical reads relate to memory pressure  (Query 36) (SP Logical Reads)
SELECT TOP(25) OBJECT_NAME(objectid, dbid) AS [SP Name], qt.[text] AS [SP Text],  
total_logical_reads, qs.max_logical_reads,
total_logical_reads/qs.execution_count AS [AvgLogicalReads], qs.execution_count AS [Execution Count], 
qs.execution_count/DATEDIFF(Minute, qs.creation_time, GETDATE()) AS [Calls/Minute], 
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime],
qs.total_worker_time AS [TotalWorkerTime],
qs.total_elapsed_time/qs.execution_count AS [AvgElapsedTime],
qs.total_logical_writes,
 qs.max_logical_writes, qs.total_physical_reads, 
DATEDIFF(Minute, qs.creation_time, GETDATE()) AS [Age in Cache]
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(qs.[sql_handle]) AS qt
WHERE qt.[dbid] = DB_ID() 
ORDER BY total_logical_reads DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a memory perspective
-- You should look at this if you see signs of memory pressure


-- Cached SP's By Physical Reads (SQL 2005) Physical reads relate to read I/O pressure  (Query 37) (SP Physical Reads)
SELECT TOP(25) OBJECT_NAME(objectid, dbid) AS [SP Name], qt.[text] AS [SP Text],  
qs.total_physical_reads, total_logical_reads, qs.max_logical_reads,
total_logical_reads/qs.execution_count AS [AvgLogicalReads], qs.execution_count AS [Execution Count], 
qs.execution_count/DATEDIFF(Minute, qs.creation_time, GETDATE()) AS [Calls/Minute], 
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime],
qs.total_worker_time AS [TotalWorkerTime],
qs.total_elapsed_time/qs.execution_count AS [AvgElapsedTime],
DATEDIFF(Minute, qs.creation_time, GETDATE()) AS [Age in Cache]
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(qs.[sql_handle]) AS qt
WHERE qt.[dbid] = DB_ID() -- Filter by current database
AND qs.total_physical_reads > 0
ORDER BY qs.total_physical_reads DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a read I/O perspective
-- You should look at this if you see signs of I/O pressure or of memory pressure


-- Top Cached SPs By Total Logical Writes (SQL 2005)  (Query 38) (SP Logical Writes)
-- Logical writes relate to both memory and disk I/O pressure 
SELECT TOP(25) OBJECT_NAME(objectid, dbid) AS [SP Name], qt.[text] AS [SP Text],  
qs.total_logical_writes, qs.max_logical_writes,
qs.total_logical_writes/qs.execution_count AS [AvgLogicalWrites], qs.execution_count AS [Execution Count], 
qs.execution_count/DATEDIFF(Minute, qs.creation_time, GETDATE()) AS [Calls/Minute], 
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime],
qs.total_worker_time AS [TotalWorkerTime],
qs.total_elapsed_time/qs.execution_count AS [AvgElapsedTime],
qs.total_physical_reads, 
DATEDIFF(Minute, qs.creation_time, GETDATE()) AS [Age in Cache]
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(qs.[sql_handle]) AS qt
WHERE qt.[dbid] = DB_ID()
AND qs.total_logical_writes > 0 
ORDER BY total_logical_writes DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a write I/O perspective
-- You should look at this if you see signs of I/O pressure or of memory pressure


-- Lists the top statements by average input/output usage for the current database  (Query 39) (Top IO Statements)
SELECT TOP(50) OBJECT_NAME(qt.objectid, dbid) AS [SP Name],
(qs.total_logical_reads + qs.total_logical_writes) /qs.execution_count AS [Avg IO], qs.execution_count AS [Execution Count],
SUBSTRING(qt.[text],qs.statement_start_offset/2, 
	(CASE 
		WHEN qs.statement_end_offset = -1 
	 THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2 
		ELSE qs.statement_end_offset 
	 END - qs.statement_start_offset)/2) AS [Query Text]	
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
WHERE qt.[dbid] = DB_ID()
ORDER BY [Avg IO] DESC OPTION (RECOMPILE);
------

-- Helps you find the most expensive statements for I/O by SP



-- Possible Bad NC Indexes (writes > reads)  (Query 40) (Bad NC Indexes)
SELECT OBJECT_NAME(s.[object_id]) AS [Table Name], i.name AS [Index Name], i.index_id, 
i.is_disabled, i.is_hypothetical, i.has_filter, i.fill_factor,
user_updates AS [Total Writes], user_seeks + user_scans + user_lookups AS [Total Reads],
user_updates - (user_seeks + user_scans + user_lookups) AS [Difference]
FROM sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON s.[object_id] = i.[object_id]
AND i.index_id = s.index_id
WHERE OBJECTPROPERTY(s.[object_id],'IsUserTable') = 1
AND s.database_id = DB_ID()
AND s.user_updates > (s.user_seeks + s.user_scans + s.user_lookups)
AND i.index_id > 1 AND i.[type_desc] = N'NONCLUSTERED'
AND i.is_primary_key = 0 AND i.is_unique_constraint = 0
ORDER BY [Difference] DESC, [Total Writes] DESC, [Total Reads] ASC OPTION (RECOMPILE);
------

-- Look for indexes with high numbers of writes and zero or very low numbers of reads
-- Consider your complete workload, and how long your instance has been running
-- Investigate further before dropping an index!


-- Missing Indexes for current database by Index Advantage  (Query 41) (Missing Indexes)
SELECT DISTINCT CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage], 
migs.last_user_seek, mid.[statement] AS [Database.Schema.Table],
mid.equality_columns, mid.inequality_columns, mid.included_columns,
migs.unique_compiles, migs.user_seeks, migs.avg_total_user_cost, migs.avg_user_impact,
OBJECT_NAME(mid.[object_id]) AS [Table Name], p.rows AS [Table Rows]
FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)
INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)
ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)
ON mig.index_handle = mid.index_handle
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON p.[object_id] = mid.[object_id]
WHERE mid.database_id = DB_ID()
AND p.index_id < 2 
ORDER BY index_advantage DESC OPTION (RECOMPILE);
------

-- Look at index advantage, last user seek time, number of user seeks to help determine source and importance
-- SQL Server is overly eager to add included columns, so beware
-- Do not just blindly add indexes that show up from this query!!!


-- Find missing index warnings for cached plans in the current database  (Query 42) (Missing Index Warnings)
-- Note: This query could take some time on a busy instance
SELECT TOP(25) OBJECT_NAME(objectid) AS [ObjectName], 
               query_plan, cp.objtype, cp.usecounts
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) AS qp
WHERE CAST(query_plan AS NVARCHAR(MAX)) LIKE N'%MissingIndex%'
AND dbid = DB_ID()
ORDER BY cp.usecounts DESC OPTION (RECOMPILE);
------

-- Helps you connect missing indexes to specific stored procedures
-- This can help you decide whether to add them or not


-- Breaks down buffers used by current database by object (table, index) in the buffer cache  (Query 43) (Buffer Usage)
-- Note: This query could take some time on a busy instance
SELECT OBJECT_NAME(p.[object_id]) AS [ObjectName], 
p.index_id, COUNT(*)/128 AS [buffer size(MB)],  COUNT(*) AS [buffer_count] 
FROM sys.allocation_units AS a
INNER JOIN sys.dm_os_buffer_descriptors AS b WITH (NOLOCK)
ON a.allocation_unit_id = b.allocation_unit_id
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON a.container_id = p.hobt_id
WHERE b.database_id = DB_ID()
AND p.[object_id] > 100
GROUP BY p.[object_id], p.index_id
ORDER BY buffer_count DESC OPTION (RECOMPILE);
------

-- Tells you what tables and indexes are using the most memory in the buffer cache


-- Get Table names, row counts  (Query 44) (Table Sizes)
SELECT SCHEMA_NAME(o.Schema_ID) AS [Schema Name], OBJECT_NAME(p.object_id) AS [ObjectName], 
SUM(p.Rows) AS [RowCount]
FROM sys.partitions AS p WITH (NOLOCK)
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON p.object_id = o.object_id
WHERE index_id < 2 --ignore the partitions from the non-clustered index if any
AND OBJECT_NAME(p.object_id) NOT LIKE N'sys%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'spt_%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'queue_%' 
AND OBJECT_NAME(p.object_id) NOT LIKE N'filestream_tombstone%' 
AND OBJECT_NAME(p.object_id) NOT LIKE N'fulltext%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'ifts_comp_fragment%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'filetable_updates%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'xml_index_nodes%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'sqlagent_job%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'plan_persist%'
GROUP BY  SCHEMA_NAME(o.Schema_ID), p.object_id
ORDER BY SUM(p.Rows) DESC OPTION (RECOMPILE);
------

-- Gives you an idea of table sizes


-- Detect blocking (run multiple times)  (Query 45) (Detect Blocking)
SELECT t1.resource_type AS [lock type], DB_NAME(resource_database_id) AS [database],
t1.resource_associated_entity_id AS [blk object],t1.request_mode AS [lock req],  --- lock requested
t1.request_session_id AS [waiter sid], t2.wait_duration_ms AS [wait time],       -- spid of waiter  
(SELECT [text] FROM sys.dm_exec_requests AS r WITH (NOLOCK)                      -- get sql for waiter
CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) 
WHERE r.session_id = t1.request_session_id) AS [waiter_batch],
(SELECT SUBSTRING(qt.[text],r.statement_start_offset/2, 
    (CASE WHEN r.statement_end_offset = -1 
    THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2 
    ELSE r.statement_end_offset END - r.statement_start_offset)/2) 
FROM sys.dm_exec_requests AS r WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) AS qt
WHERE r.session_id = t1.request_session_id) AS [waiter_stmt],					-- statement blocked
t2.blocking_session_id AS [blocker sid],										-- spid of blocker
(SELECT [text] FROM sys.sysprocesses AS p										-- get sql for blocker
CROSS APPLY sys.dm_exec_sql_text(p.[sql_handle]) 
WHERE p.spid = t2.blocking_session_id) AS [blocker_stmt]
FROM sys.dm_tran_locks AS t1 WITH (NOLOCK)
INNER JOIN sys.dm_os_waiting_tasks AS t2 WITH (NOLOCK)
ON t1.lock_owner_address = t2.resource_address OPTION (RECOMPILE);
------

-- Helps troubleshoot blocking and deadlocking issues
-- The results will change from second to second on a busy system
-- You should run this query multiple times when you see signs of blocking


-- When were Statistics last updated on all indexes?  (Query 46) (Statistics Update)
SELECT SCHEMA_NAME(o.Schema_ID) + N'.' + o.NAME AS [Object Name], o.type_desc AS [Object Type],
      i.name AS [Index Name], STATS_DATE(i.[object_id], i.index_id) AS [Statistics Date], 
      s.auto_created, s.no_recompute, s.user_created, st.row_count, st.used_page_count
FROM sys.objects AS o WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON o.[object_id] = i.[object_id]
INNER JOIN sys.stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id] 
AND i.index_id = s.stats_id
INNER JOIN sys.dm_db_partition_stats AS st WITH (NOLOCK)
ON o.[object_id] = st.[object_id]
AND i.[index_id] = st.[index_id]
WHERE o.[type] IN ('U', 'V')
AND st.row_count > 0
ORDER BY STATS_DATE(i.[object_id], i.index_id) DESC OPTION (RECOMPILE);
------  

-- Helps discover possible problems with out-of-date statistics
-- Also gives you an idea which indexes are the most active



-- Get fragmentation info for all indexes above a certain size in the current database  (Query 47) (Index Fragmentation)
-- Note: This query could take some time on a very large database
SELECT DB_NAME(ps.database_id) AS [Database Name], OBJECT_NAME(ps.OBJECT_ID) AS [Object Name], 
i.name AS [Index Name], ps.index_id, ps.index_type_desc, ps.avg_fragmentation_in_percent, 
ps.fragment_count, ps.page_count, i.fill_factor
FROM sys.dm_db_index_physical_stats(DB_ID(),NULL, NULL, NULL , N'LIMITED') AS ps
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ps.[object_id] = i.[object_id] 
AND ps.index_id = i.index_id
WHERE ps.database_id = DB_ID()
AND ps.page_count > 2500
ORDER BY ps.avg_fragmentation_in_percent DESC OPTION (RECOMPILE);
------

-- Helps determine whether you have framentation in your relational indexes
-- and how effective your index maintenance strategy is


--- Index Read/Write stats (all tables in current DB) ordered by Reads  (Query 48) (Overall Index Usage - Reads)
SELECT OBJECT_NAME(s.[object_id]) AS [ObjectName], i.name AS [IndexName], i.index_id,
	   user_seeks + user_scans + user_lookups AS [Reads], s.user_updates AS [Writes],  
	   i.type_desc AS [IndexType], i.fill_factor AS [FillFactor]
FROM sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON s.[object_id] = i.[object_id]
WHERE OBJECTPROPERTY(s.[object_id],'IsUserTable') = 1
AND i.index_id = s.index_id
AND s.database_id = DB_ID()
ORDER BY user_seeks + user_scans + user_lookups DESC OPTION (RECOMPILE); -- Order by reads
------

-- Show which indexes in the current database are most active for Reads


--- Index Read/Write stats (all tables in current DB) ordered by Writes  (Query 49) (Overall Index Usage - Writes)
SELECT OBJECT_NAME(s.[object_id]) AS [ObjectName], i.name AS [IndexName], i.index_id,
	   s.user_updates AS [Writes], user_seeks + user_scans + user_lookups AS [Reads], 
	   i.type_desc AS [IndexType], i.fill_factor AS [FillFactor],
	   s.last_system_update, s.last_user_update
FROM sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON s.[object_id] = i.[object_id]
WHERE OBJECTPROPERTY(s.[object_id],'IsUserTable') = 1
AND i.index_id = s.index_id
AND s.database_id = DB_ID()
ORDER BY s.user_updates DESC OPTION (RECOMPILE);						 -- Order by writes
------

-- Show which indexes in the current database are most active for Writes


-- Get lock waits for current database (Query 50) (Lock Waits)
SELECT o.name AS [table_name], i.name AS [index_name], ios.index_id, ios.partition_number,
		SUM(ios.row_lock_wait_count) AS [total_row_lock_waits], 
		SUM(ios.row_lock_wait_in_ms) AS [total_row_lock_wait_in_ms],
		SUM(ios.page_lock_wait_count) AS [total_page_lock_waits],
		SUM(ios.page_lock_wait_in_ms) AS [total_page_lock_wait_in_ms],
		SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) AS [total_lock_wait_in_ms]
FROM sys.dm_db_index_operational_stats(DB_ID(), NULL, NULL, NULL) AS ios
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON ios.[object_id] = o.[object_id]
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ios.[object_id] = i.[object_id] 
AND ios.index_id = i.index_id
WHERE o.[object_id] > 100
GROUP BY o.name, i.name, ios.index_id, ios.partition_number
HAVING SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) > 0
ORDER BY total_lock_wait_in_ms DESC OPTION (RECOMPILE);
------

-- This query is helpful for troubleshooting blocking and deadlocking issues


-- Look at recent Full backups for the current database (Query 51) (Recent Full Backups)
SELECT TOP (30) bs.server_name, bs.database_name AS [Database Name], 
CONVERT (BIGINT, bs.backup_size / 1048576 ) AS [Backup Size (MB)],
DATEDIFF (SECOND, bs.backup_start_date, bs.backup_finish_date) AS [Backup Elapsed Time (sec)],
bs.backup_finish_date AS [Backup Finish Date], bmf.physical_device_name AS [Backup Location], bmf.physical_block_size
FROM msdb.dbo.backupset AS bs WITH (NOLOCK)
INNER JOIN msdb.dbo.backupmediafamily AS bmf WITH (NOLOCK)
ON bs.media_set_id = bmf.media_set_id  
WHERE DATEDIFF (SECOND, bs.backup_start_date, bs.backup_finish_date) > 0 
AND bs.backup_size > 0
AND bs.type = 'D' -- Change to L if you want Log backups
AND database_name = DB_NAME(DB_ID())
ORDER BY bs.backup_finish_date DESC OPTION (RECOMPILE);
------

-- Are your backup sizes and times changing over time?
-- Are you using backup compression?
-- Are you using backup checksums?
-- Are you doing copy_only backups?
-- Have you done any backup tuning with striped backups, or changing the parameters of the backup command?



-- These three Pluralsight Courses go into more detail about how to run these queries and interpret the results

-- SQL Server 2014 DMV Diagnostic Queries � Part 1 
-- https://bit.ly/2plxCer

-- SQL Server 2014 DMV Diagnostic Queries � Part 2
-- https://bit.ly/2IuJpzI

-- SQL Server 2014 DMV Diagnostic Queries � Part 3
-- https://bit.ly/2FIlCPb



-- Sign up for Microsoft Visual Studio Dev Essentials and get a free three month pass to Pluralsight

-- Microsoft Visual Studio Dev Essentials
-- http://bit.ly/1q6xbDL


-- Sign up for Microsoft Azure Essentials and get lots of free Azure usage credits, MCP exam voucher, three month Pluralsight subscription

-- Microsoft Azure Essentials
-- https://bit.ly/2JMWe8x


-- August 2017 blog series about upgrading and migrating SQL Server
-- https://bit.ly/2ftKVrX


tools\dbatools\bin\diagnosticquery\SQLServerDiagnosticQueries_2008R2_201811.sql

-- SQL Server 2008 R2 Diagnostic Information Queries
-- Glenn Berry 
-- Last Modified: January 7, 2019
-- https://www.sqlserverperformance.wordpress.com/
-- https://www.sqlskills.com/blogs/glenn/
-- Twitter: GlennAlanBerry

-- Please listen to my Pluralsight courses
-- https://www.pluralsight.com/author/glenn-berry

-- If you want to find all of our SQLskills SQL101 blog posts, check out https://www.sqlskills.com/help/sql101/

-- Many of these queries will not work if you have databases in 80 compatibility mode
-- Please make sure you are using the correct version of these diagnostic queries for your version of SQL Server

--******************************************************************************
--*   Copyright (C) 2019 Glenn Berry, SQLskills.com
--*   All rights reserved. 
--*
--*   For more scripts and sample code, check out 
--*      https://www.sqlskills.com/blogs/glenn
--*
--*   You may alter this code for your own *non-commercial* purposes. You may
--*   republish altered code as long as you include this copyright and give due credit. 
--*
--*
--*   THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF 
--*   ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED 
--*   TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
--*   PARTICULAR PURPOSE. 
--*
--******************************************************************************

-- Note: A number of these queries will only work on SQL Server 2008 R2 SP1 or later
-- They are all noted in the instructions

-- Check the major product version to see if it is SQL Server 2008 R2
IF NOT EXISTS (SELECT * WHERE CONVERT(varchar(128), SERVERPROPERTY('ProductVersion')) LIKE '10.5%')
	BEGIN
		DECLARE @ProductVersion varchar(128) = CONVERT(varchar(128), SERVERPROPERTY('ProductVersion'));
		RAISERROR ('Script does not match the ProductVersion [%s] of this instance. Many of these queries may not work on this version.' , 18 , 16 , @ProductVersion);
	END
	ELSE
		PRINT N'You have the correct major version of SQL Server for this diagnostic information script';


-- Instance level queries *******************************

-- SQL and OS Version information for current instance  (Query 1) (Version Info)
SELECT SERVERPROPERTY ('MachineName') AS [Server Name], @@VERSION AS [SQL Server and OS Version Info];
------


-- SQL Server 2008 R2 Builds				SQL Server 2008 R2 SP1 Builds			SQL Server 2008 R2 SP2 Builds							SQL Server 2008 R2 SP3 Builds
-- Build			Description				Build		Description					Build		Description									Build		Description
-- 10.50.1092		August 2009 CTP2		
-- 10.50.1352		November 2009 CTP3
-- 10.50.1450		Release Candidate
-- 10.50.1600		RTM
-- 10.50.1702		RTM CU1
-- 10.50.1720		RTM CU2
-- 10.50.1734		RTM CU3
-- 10.50.1746		RTM CU4
-- 10.50.1753		RTM CU5
-- 10.50.1765		RTM CU6	 --->			10.50.2500	SP1 RTM
-- 10.50.1777		RTM CU7
-- 10.50.1797		RTM CU8	 --->			10.50.2769  SP1 CU1
-- 10.50.1804       RTM CU9  --->			10.50.2772  SP1 CU2
-- 10.50.1807		RTM CU10 --->           10.50.2789  SP1 CU3
-- 10.50.1809       RTM CU11 --->			10.50.2796  SP1 CU4 
-- 10.50.1810		RTM CU12 --->			10.50.2806	SP1 CU5		--->			10.50.4000	SP2 RTM
-- 10.50.1815		RTM CU13 --->           10.50.2811  SP1 CU6
-- 10.50.1817		RTM CU14 --->			10.50.2817  SP1 CU7		--->			10.50.4260	SP2 CU1			         7/24/2012
-- RTM Branch Retired        --->			10.50.2822  SP1 CU8     --->			10.50.4263  SP2 CU2                  8/31/2012   
--											10.50.2866  SP1 CU9     --->			10.50.4266  SP2 CU3					10/15/2012
--                                          10.50.2868  SP1 CU10    --->			10.50.4270  SP2 CU4					12/17/2012
--                                          10.50.2869  SP1 CU11    --->            10.50.4276  SP2 CU5				     2/18/2013
--                                          10.50.2874  SP1 CU12    --->            10.50.4279  SP2 CU6                  4/15/2013
--                                          10.50.2876  SP1 CU13    --->            10.50.4286  SP2 CU7					 6/17/2013
--                                          10.50.2881  SP1 CU14    --->            10.50.4290  SP2 CU8                  8/22/2013
--                                                                                  10.50.4295  SP2 CU9                 10/28/2013  
--                                                                                  10.50.4297  SP2 CU10                12/16/2013 
--                                                                                  10.50.4302  SP2 CU11                 2/17/2014
--                                                                                  10.50.4305	SP2 CU12                 4/21/2014
--                                                                                  10.50.4319  SP2 CU13                 6/30/2014   
--																																			10.50.6000	SP3 RTM		9/26/2014
--                                                                                                                                          10.50.6525  SP3 + HF     2/9/2015      http://support.microsoft.com/kb/3033860
-- Security Update for SQL Server 2008 R2 SP3 (KB4057113) https://www.microsoft.com/en-us/download/details.aspx?id=56415					10.50.6560	SP3 + HF	 1/5/2018	   Hot fix for Spectre/Meltdown


-- SQL Server 2008 R2 SP3 RTM plus an on-demand hotfix (Build 10.50.6525) is the final public build of SQL Server 2008 R2, barring any later security fixes.          

-- SQL Server 2008 R2 RTM was considered an "unsupported service pack" as of July 12, 2012
-- SQL Server 2008 R2 SP1 was considered an "unsupported service pack" as of August 8, 2013										

-- The SQL Server 2008 R2 builds that were released after SQL Server 2008 R2 was released
-- http://support.microsoft.com/kb/981356

-- The SQL Server 2008 R2 builds that were released after SQL Server 2008 R2 Service Pack 1 was released 
-- http://support.microsoft.com/kb/2567616

-- The SQL Server 2008 R2 builds that were released after SQL Server 2008 R2 Service Pack 2 was released
-- http://support.microsoft.com/kb/2730301 

-- SQL Server 2008 R2 SP2 CU13 is the final cumulative update for SQL Server 2008 R2 SP2

-- SQL Server 2008 R2 SP3 Release information
-- http://support2.microsoft.com/kb/2979597

-- Download SQL Server Management Studio (SSMS)
-- https://msdn.microsoft.com/en-us/library/mt238290.aspx



-- When was SQL Server installed  (Query 2) (SQL Server Install Date) 
SELECT @@SERVERNAME AS [Server Name], create_date AS [SQL Server Install Date] 
FROM sys.server_principals WITH (NOLOCK)
WHERE name = N'NT AUTHORITY\SYSTEM'
OR name = N'NT AUTHORITY\NETWORK SERVICE' OPTION (RECOMPILE);
------

-- Tells you the date and time that SQL Server was installed
-- It is a good idea to know how old your instance is


-- Get selected server properties (Query 3) (Server Properties)
SELECT SERVERPROPERTY('MachineName') AS [MachineName], SERVERPROPERTY('ServerName') AS [ServerName],  
SERVERPROPERTY('InstanceName') AS [Instance], SERVERPROPERTY('IsClustered') AS [IsClustered], 
SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS [ComputerNamePhysicalNetBIOS], 
SERVERPROPERTY('Edition') AS [Edition], SERVERPROPERTY('ProductLevel') AS [ProductLevel], 
SERVERPROPERTY('ProductVersion') AS [ProductVersion], SERVERPROPERTY('ProcessID') AS [ProcessID],
SERVERPROPERTY('Collation') AS [Collation], SERVERPROPERTY('IsFullTextInstalled') AS [IsFullTextInstalled], 
SERVERPROPERTY('IsIntegratedSecurityOnly') AS [IsIntegratedSecurityOnly];
------

-- This gives you a lot of useful information about your instance of SQL Server,
-- such as the ProcessID for SQL Server and your collation


-- Get SQL Server Agent jobs and Category information (Query 4) (SQL Server Agent Jobs)
SELECT sj.name AS [Job Name], sj.[description] AS [Job Description], SUSER_SNAME(sj.owner_sid) AS [Job Owner],
sj.date_created AS [Date Created], sj.[enabled] AS [Job Enabled], 
sj.notify_email_operator_id, sj.notify_level_email, sc.name AS [CategoryName],
s.[enabled] AS [Sched Enabled], js.next_run_date, js.next_run_time
FROM msdb.dbo.sysjobs AS sj WITH (NOLOCK)
INNER JOIN msdb.dbo.syscategories AS sc WITH (NOLOCK)
ON sj.category_id = sc.category_id
LEFT OUTER JOIN msdb.dbo.sysjobschedules AS js WITH (NOLOCK)
ON sj.job_id = js.job_id
LEFT OUTER JOIN msdb.dbo.sysschedules AS s WITH (NOLOCK)
ON js.schedule_id = s.schedule_id
ORDER BY sj.name OPTION (RECOMPILE);
------

-- Gives you some basic information about your SQL Server Agent jobs, who owns them and how they are configured
-- Look for Agent jobs that are not owned by sa
-- Look for jobs that have a notify_email_operator_id set to 0 (meaning no operator)
-- Look for jobs that have a notify_level_email set to 0 (meaning no e-mail is ever sent)
--
-- MSDN sysjobs documentation
-- http://msdn.microsoft.com/en-us/library/ms189817.aspx


-- Get SQL Server Agent Alert Information (Query 5) (SQL Server Agent Alerts)
SELECT name, event_source, message_id, severity, [enabled], has_notification, 
       delay_between_responses, occurrence_count, last_occurrence_date, last_occurrence_time
FROM msdb.dbo.sysalerts WITH (NOLOCK)
ORDER BY name OPTION (RECOMPILE);
------

-- Gives you some basic information about your SQL Server Agent Alerts (which are different from SQL Server Agent jobs)
-- Read more about Agent Alerts here: https://www.sqlskills.com/blogs/glenn/creating-sql-server-agent-alerts-for-critical-errors/


-- Returns a list of all global trace flags that are enabled (Query 6) (Global Trace Flags)
DBCC TRACESTATUS (-1);
------

-- If no global trace flags are enabled, no results will be returned.
-- It is very useful to know what global trace flags are currently enabled as part of the diagnostic process.

-- Common trace flags that should be enabled in most cases
-- TF 1117 - When growing a data file, grow all files at the same time so they remain the same size, reducing allocation contention points
--           http://support2.microsoft.com/kb/2154845
-- 
-- TF 1118 - Helps alleviate allocation contention in tempdb, SQL Server allocates full extents to each database object, 
--           thereby eliminating the contention on SGAM pages (more important with older versions of SQL Server)
--           Recommendations to reduce allocation contention in SQL Server tempdb database
--           http://support2.microsoft.com/kb/2154845

-- TF 2371 - Lowers auto update statistics threshold for large tables
--           http://blogs.msdn.com/b/saponsqlserver/archive/2011/09/07/changes-to-automatic-update-statistics-in-sql-server-traceflag-2371.aspx

-- TF 3226 - Supresses logging of successful database backup messages to the SQL Server Error Log
--           https://www.sqlskills.com/blogs/paul/fed-up-with-backup-success-messages-bloating-your-error-logs/


-- Windows information (SQL Server 2008 R2 SP1 or greater)  (Query 7) (Windows Info)
SELECT windows_release, windows_service_pack_level, 
       windows_sku, os_language_version
FROM sys.dm_os_windows_info WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Gives you major OS version, Service Pack, Edition, and language info for the operating system 
-- 6.3 is either Windows 8.1 or Windows Server 2012 R2
-- 6.2 is either Windows 8 or Windows Server 2012
-- 6.1 is either Windows 7 or Windows Server 2008 R2
-- 6.0 is either Windows Vista or Windows Server 2008
-- 5.2 is either Windows XP or Windows Server 2003

-- Windows SKU codes
-- 4 is Enterprise Edition
-- 7 is Standard Server Edition
-- 8 is Datacenter Server Edition
-- 10 is Enterprise Server Edition
-- 48 is Professional Edition

-- 1033 for os_language_version is US-English

-- Hardware and Software Requirements for Installing SQL Server 2008 R2
-- http://msdn.microsoft.com/en-us/library/ms143506(v=sql.105).aspx

-- Using SQL Server in Windows 8, Windows 8.1, Windows Server 2012 and Windows Server 2012 R2 environments
-- http://support.microsoft.com/kb/2681562


-- SQL Server Services information (SQL Server 2008 R2 SP1 or greater)  (Query 8) (SQL Server Services Info)
SELECT servicename, process_id, startup_type_desc, status_desc, 
last_startup_time, service_account, is_clustered, cluster_nodename, [filename]
FROM sys.dm_server_services WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Tells you the account being used for the SQL Server Service and the SQL Agent Service
-- Shows the processid, when they were last started, and their current status
-- Shows whether you are running on a failover cluster instance


-- SQL Server NUMA Node information  (Query 9) (SQL Server NUMA Info)
SELECT node_id, node_state_desc, memory_node_id, processor_group, online_scheduler_count, 
       active_worker_count, avg_load_balance, resource_monitor_state
FROM sys.dm_os_nodes WITH (NOLOCK) 
WHERE node_state_desc <> N'ONLINE DAC' OPTION (RECOMPILE);
------

-- Gives you some useful information about the composition 
-- and relative load on your NUMA nodes


-- Hardware information from SQL Server 2008 R2  (Query 10) (Hardware Info)
-- (Cannot distinguish between HT and multi-core)
SELECT cpu_count AS [Logical CPU Count], hyperthread_ratio AS [Hyperthread Ratio],
cpu_count/hyperthread_ratio AS [Physical CPU Count], 
physical_memory_in_bytes/1048576 AS [Physical Memory (MB)], 
sqlserver_start_time,
DATEDIFF(hour, sqlserver_start_time, GETDATE()) AS [SQL Server Up Time (hrs)],
affinity_type_desc 
FROM sys.dm_os_sys_info WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Gives you some good basic hardware information about your database server


-- Get System Manufacturer and model number from  (Query 11) (System Manufacturer)
-- SQL Server Error log. This query might take a few seconds 
-- if you have not recycled your error log recently
EXEC sys.xp_readerrorlog 0, 1, N'Manufacturer';
------ 

-- This can help you determine the capabilities
-- and capacities of your database server


-- Get processor description from Windows Registry  (Query 12) (Processor Description)
EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'HARDWARE\DESCRIPTION\System\CentralProcessor\0', N'ProcessorNameString';
------

-- Gives you the model number and rated clock speed of your processor(s)
-- Your processors may be running at less than the rated clock speed due
-- to the Windows Power Plan or hardware power management

-- You can use CPU-Z to get your actual CPU core speed and a lot of other useful information
-- http://www.cpuid.com/softwares/cpu-z.html

-- You can learn more about processor selection for SQL Server by following this link
-- https://www.sqlskills.com/blogs/glenn/processor-selection-for-sql-server/



-- Get the current node name from your cluster nodes  (Query 13) (Cluster Node Properties)
-- (if your database server is in a failover cluster)
SELECT NodeName
FROM sys.dm_os_cluster_nodes WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Knowing which node owns the cluster resources is critical
-- Especially when you are installing Windows or SQL Server updates
-- You will see no results if your instance is not clustered


-- Get configuration values for instance  (Query 14) (Configuration Values)
SELECT name, value, value_in_use, minimum, maximum, [description], is_dynamic, is_advanced
FROM sys.configurations WITH (NOLOCK)
ORDER BY name OPTION (RECOMPILE);
------

-- Focus on these settings:
-- backup compression default (should be 1 in most cases)
-- clr enabled (only enable if it is needed)
-- cost threshold for parallelism (depends on your workload)
-- lightweight pooling (should be zero)
-- max degree of parallelism (depends on your workload)
-- max server memory (MB) (set to an appropriate value, not the default)
-- optimize for ad hoc workloads (should be 1)
-- priority boost (should be zero)
-- remote admin connections (should be 1)




-- Get information on location, time and size of any memory dumps from SQL Server (SQL Server 2008 R2 SP1 or greater)  (Query 15) (Memory Dump Info)
SELECT [filename], creation_time, size_in_bytes/1048576.0 AS [Size (MB)]
FROM sys.dm_server_memory_dumps WITH (NOLOCK) 
ORDER BY creation_time DESC OPTION (RECOMPILE);
------

-- This will not return any rows if you have 
-- not had any memory dumps (which is a good thing)


-- File names and paths for all user and system databases on instance   (Query 16) (Database Filenames and Paths)
SELECT DB_NAME([database_id]) AS [Database Name], 
       [file_id], [name], physical_name, [type_desc], state_desc,
	   is_percent_growth, growth,
	   CONVERT(bigint, growth/128.0) AS [Growth in MB], 
       CONVERT(bigint, size/128.0) AS [Total Size in MB]
FROM sys.master_files WITH (NOLOCK)
ORDER BY DB_NAME([database_id]), [file_id] OPTION (RECOMPILE);
------

-- Things to look at:
-- Are data files and log files on different drives?
-- Is everything on the C: drive?
-- Is TempDB on dedicated drives?
-- Is there only one TempDB data file?
-- Are all of the TempDB data files the same size?
-- Are there multiple data files for user databases?
-- Is percent growth enabled for any files (which is bad)?


-- Volume info for all LUNS that have database files on the current instance (SQL Server 2008 R2 SP1 or greater)  (Query 17) (Volume Info)
SELECT DISTINCT vs.volume_mount_point, vs.file_system_type, 
vs.logical_volume_name, CONVERT(DECIMAL(18,2),vs.total_bytes/1073741824.0) AS [Total Size (GB)],
CONVERT(DECIMAL(18,2),vs.available_bytes/1073741824.0) AS [Available Size (GB)],  
CAST(CAST(vs.available_bytes AS FLOAT)/ CAST(vs.total_bytes AS FLOAT) AS DECIMAL(18,2)) * 100 AS [Space Free %] 
FROM sys.master_files AS f WITH (NOLOCK)
CROSS APPLY sys.dm_os_volume_stats(f.database_id, f.[file_id]) AS vs OPTION (RECOMPILE);
------

--Shows you the total and free space on the LUNs where you have database files


-- Look for I/O requests taking longer than 15 seconds in the five most recent SQL Server Error Logs (Query 18) (IO Warnings)
CREATE TABLE #IOWarningResults(LogDate datetime, ProcessInfo sysname, LogText nvarchar(1000));

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 0, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 1, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 2, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 3, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 4, 1, N'taking longer than 15 seconds';

SELECT LogDate, ProcessInfo, LogText
FROM #IOWarningResults
ORDER BY LogDate DESC;

DROP TABLE #IOWarningResults;
------  

-- Finding 15 second I/O warnings in the SQL Server Error Log is useful evidence of
-- poor I/O performance (which might have many different causes)
-- Look to see if you see any patterns in the results (same files, same drives, same time of day, etc.)

-- Diagnostics in SQL Server help detect stalled and stuck I/O operations
-- https://support.microsoft.com/en-us/kb/897284



-- Drive level latency information (Query 19) (Drive Level Latency)
-- Based on code from Jimmy May
SELECT tab.[Drive], tab.volume_mount_point AS [Volume Mount Point], 
	CASE 
		WHEN num_of_reads = 0 THEN 0 
		ELSE (io_stall_read_ms/num_of_reads) 
	END AS [Read Latency],
	CASE 
		WHEN num_of_writes = 0 THEN 0 
		ELSE (io_stall_write_ms/num_of_writes) 
	END AS [Write Latency],
	CASE 
		WHEN (num_of_reads = 0 AND num_of_writes = 0) THEN 0 
		ELSE (io_stall/(num_of_reads + num_of_writes)) 
	END AS [Overall Latency],
	CASE 
		WHEN num_of_reads = 0 THEN 0 
		ELSE (num_of_bytes_read/num_of_reads) 
	END AS [Avg Bytes/Read],
	CASE 
		WHEN num_of_writes = 0 THEN 0 
		ELSE (num_of_bytes_written/num_of_writes) 
	END AS [Avg Bytes/Write],
	CASE 
		WHEN (num_of_reads = 0 AND num_of_writes = 0) THEN 0 
		ELSE ((num_of_bytes_read + num_of_bytes_written)/(num_of_reads + num_of_writes)) 
	END AS [Avg Bytes/Transfer]
FROM (SELECT LEFT(UPPER(mf.physical_name), 2) AS Drive, SUM(num_of_reads) AS num_of_reads,
	         SUM(io_stall_read_ms) AS io_stall_read_ms, SUM(num_of_writes) AS num_of_writes,
	         SUM(io_stall_write_ms) AS io_stall_write_ms, SUM(num_of_bytes_read) AS num_of_bytes_read,
	         SUM(num_of_bytes_written) AS num_of_bytes_written, SUM(io_stall) AS io_stall, vs.volume_mount_point 
      FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS vfs
      INNER JOIN sys.master_files AS mf WITH (NOLOCK)
      ON vfs.database_id = mf.database_id AND vfs.file_id = mf.file_id
	  CROSS APPLY sys.dm_os_volume_stats(mf.database_id, mf.[file_id]) AS vs 
      GROUP BY LEFT(UPPER(mf.physical_name), 2), vs.volume_mount_point) AS tab
ORDER BY [Overall Latency] OPTION (RECOMPILE);
------

-- Shows you the drive-level latency for reads and writes, in milliseconds
-- Latency above 20-25ms is usually a problem


-- Calculates average stalls per read, per write, and per total input/output for each database file  (Query 20) (IO Stalls by File)
SELECT DB_NAME(fs.database_id) AS [Database Name], CAST(fs.io_stall_read_ms/(1.0 + fs.num_of_reads) AS NUMERIC(16,1)) AS [avg_read_stall_ms],
CAST(fs.io_stall_write_ms/(1.0 + fs.num_of_writes) AS NUMERIC(16,1)) AS [avg_write_stall_ms],
CAST((fs.io_stall_read_ms + fs.io_stall_write_ms)/(1.0 + fs.num_of_reads + fs.num_of_writes) AS NUMERIC(16,1)) AS [avg_io_stall_ms],
CONVERT(DECIMAL(18,2), mf.size/128.0) AS [File Size (MB)], mf.physical_name, mf.type_desc, fs.io_stall_read_ms, fs.num_of_reads, 
fs.io_stall_write_ms, fs.num_of_writes, fs.io_stall_read_ms + fs.io_stall_write_ms AS [io_stalls], fs.num_of_reads + fs.num_of_writes AS [total_io]
FROM sys.dm_io_virtual_file_stats(null,null) AS fs
INNER JOIN sys.master_files AS mf WITH (NOLOCK)
ON fs.database_id = mf.database_id
AND fs.[file_id] = mf.[file_id]
ORDER BY avg_io_stall_ms DESC OPTION (RECOMPILE);
------

-- Helps determine which database files on the entire instance have the most I/O bottlenecks
-- This can help you decide whether certain LUNs are overloaded and whether you might
-- want to move some files to a different location or perhaps improve your I/O performance


-- Recovery model, log reuse wait description, log file size, log usage size  (Query 21) (Database Properties)
-- and compatibility level for all databases on instance
SELECT db.[name] AS [Database Name], db.recovery_model_desc AS [Recovery Model], 
db.log_reuse_wait_desc AS [Log Reuse Wait Description], 
ls.cntr_value AS [Log Size (KB)], lu.cntr_value AS [Log Used (KB)],
CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log Used %], 
db.[compatibility_level] AS [DB Compatibility Level], 
db.page_verify_option_desc AS [Page Verify Option], db.is_auto_create_stats_on, db.is_auto_update_stats_on,
db.is_auto_update_stats_async_on, db.is_parameterization_forced, 
db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on,
db.is_auto_close_on, db.is_auto_shrink_on, db.is_cdc_enabled, db.is_published
FROM sys.databases AS db WITH (NOLOCK)
INNER JOIN sys.dm_os_performance_counters AS lu WITH (NOLOCK)
ON db.name = lu.instance_name
INNER JOIN sys.dm_os_performance_counters AS ls WITH (NOLOCK) 
ON db.name = ls.instance_name
WHERE lu.counter_name LIKE N'Log File(s) Used Size (KB)%' 
AND ls.counter_name LIKE N'Log File(s) Size (KB)%'
AND ls.cntr_value > 0
ORDER BY db.[name] OPTION (RECOMPILE);
------

-- Things to look at:
-- How many databases are on the instance?
-- What recovery models are they using?
-- What is the log reuse wait description?
-- How full are the transaction logs ?
-- What compatibility level are the databases on? 
-- What is the Page Verify Option? (should be CHECKSUM)
-- Is Auto Update Statistics Asynchronously enabled?
-- Make sure auto_shrink and auto_close are not enabled!



-- Missing Indexes for all databases by Index Advantage  (Query 22) (Missing Indexes All Databases)
SELECT CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage],  
migs.last_user_seek, mid.[statement] AS [Database.Schema.Table],
mid.equality_columns, mid.inequality_columns, mid.included_columns,
migs.unique_compiles, migs.user_seeks, migs.avg_total_user_cost, migs.avg_user_impact
FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)
INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)
ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)
ON mig.index_handle = mid.index_handle
ORDER BY index_advantage DESC OPTION (RECOMPILE);
------

-- Getting missing index information for all of the databases on the instance is very useful
-- Look at last user seek time, number of user seeks to help determine source and importance
-- Also look at avg_user_impact and avg_total_user_cost to help determine importance
-- SQL Server is overly eager to add included columns, so beware
-- Do not just blindly add indexes that show up from this query!!!



-- Get VLF Counts for all databases on the instance (Query 23) (VLF Counts)
-- (adapted from Michelle Ufford) 
CREATE TABLE #VLFInfo (FileID  int,
					   FileSize bigint, StartOffset bigint,
					   FSeqNo      bigint, [Status]    bigint,
					   Parity      bigint, CreateLSN   numeric(38));
	 
CREATE TABLE #VLFCountResults(DatabaseName sysname, VLFCount int);
	 
EXEC sp_MSforeachdb N'Use [?]; 

				INSERT INTO #VLFInfo 
				EXEC sp_executesql N''DBCC LOGINFO([?])''; 
	 
				INSERT INTO #VLFCountResults 
				SELECT DB_NAME(), COUNT(*) 
				FROM #VLFInfo; 

				TRUNCATE TABLE #VLFInfo;'
	 
SELECT DatabaseName, VLFCount  
FROM #VLFCountResults
ORDER BY VLFCount DESC;
	 
DROP TABLE #VLFInfo;
DROP TABLE #VLFCountResults;
------

-- High VLF counts can affect write performance 
-- and they can make full database restores and crash recovery take much longer
-- Try to keep your VLF counts under 200 in most cases (depending on log file size)



-- Get CPU utilization by database (Query 24) (CPU Usage by Database)
WITH DB_CPU_Stats
AS
(SELECT pa.DatabaseID, DB_Name(pa.DatabaseID) AS [Database Name], SUM(qs.total_worker_time/1000) AS [CPU_Time_Ms]
 FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
 CROSS APPLY (SELECT CONVERT(int, value) AS [DatabaseID] 
              FROM sys.dm_exec_plan_attributes(qs.plan_handle)
              WHERE attribute = N'dbid') AS pa
 GROUP BY DatabaseID)
SELECT ROW_NUMBER() OVER(ORDER BY [CPU_Time_Ms] DESC) AS [CPU Rank],
       [Database Name], [CPU_Time_Ms] AS [CPU Time (ms)], 
       CAST([CPU_Time_Ms] * 1.0 / SUM([CPU_Time_Ms]) OVER() * 100.0 AS DECIMAL(5, 2)) AS [CPU Percent]
FROM DB_CPU_Stats
WHERE DatabaseID <> 32767 -- ResourceDB
ORDER BY [CPU Rank] OPTION (RECOMPILE);
------

-- Helps determine which database is using the most CPU resources on the instance
-- Note: This only reflects CPU usage from the currently cached query plans


-- Get I/O utilization by database (Query 25) (IO Usage By Database)
WITH Aggregate_IO_Statistics
AS
(SELECT DB_NAME(database_id) AS [Database Name],
CAST(SUM(num_of_bytes_read + num_of_bytes_written)/1048576 AS DECIMAL(12, 2)) AS io_in_mb
FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS [DM_IO_STATS]
GROUP BY database_id)
SELECT ROW_NUMBER() OVER(ORDER BY io_in_mb DESC) AS [I/O Rank], [Database Name], io_in_mb AS [Total I/O (MB)],
       CAST(io_in_mb/ SUM(io_in_mb) OVER() * 100.0 AS DECIMAL(5,2)) AS [I/O Percent]
FROM Aggregate_IO_Statistics
ORDER BY [I/O Rank] OPTION (RECOMPILE);
------

-- Helps determine which database is using the most I/O resources on the instance


-- Get total buffer usage by database for current instance  (Query 26) (Total Buffer Usage by Database)
-- This make take some time to run on a busy instance
WITH AggregateBufferPoolUsage
AS
(SELECT DB_NAME(database_id) AS [Database Name],
CAST(COUNT(*) * 8/1024.0 AS DECIMAL (10,2))  AS [CachedSize]
FROM sys.dm_os_buffer_descriptors WITH (NOLOCK)
WHERE database_id <> 32767 -- ResourceDB
GROUP BY DB_NAME(database_id))
SELECT ROW_NUMBER() OVER(ORDER BY CachedSize DESC) AS [Buffer Pool Rank], [Database Name], CachedSize AS [Cached Size (MB)],
       CAST(CachedSize / SUM(CachedSize) OVER() * 100.0 AS DECIMAL(5,2)) AS [Buffer Pool Percent]
FROM AggregateBufferPoolUsage
ORDER BY [Buffer Pool Rank] OPTION (RECOMPILE);
------

-- Tells you how much memory (in the buffer pool) 
-- is being used by each database on the instance


-- Clear Wait Stats with this command
-- DBCC SQLPERF('sys.dm_os_wait_stats', CLEAR);

-- Isolate top waits for server instance since last restart or wait statistics clear (Query 27) (Top Waits)
WITH [Waits] 
AS (SELECT wait_type, wait_time_ms/ 1000.0 AS [WaitS],
          (wait_time_ms - signal_wait_time_ms) / 1000.0 AS [ResourceS],
           signal_wait_time_ms / 1000.0 AS [SignalS],
           waiting_tasks_count AS [WaitCount],
           100.0 *  wait_time_ms / SUM (wait_time_ms) OVER() AS [Percentage],
           ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS [RowNum]
    FROM sys.dm_os_wait_stats WITH (NOLOCK)
    WHERE [wait_type] NOT IN (
        N'BROKER_EVENTHANDLER', N'BROKER_RECEIVE_WAITFOR', N'BROKER_TASK_STOP',
		N'BROKER_TO_FLUSH', N'BROKER_TRANSMITTER', N'CHECKPOINT_QUEUE',
        N'CHKPT', N'CLR_AUTO_EVENT', N'CLR_MANUAL_EVENT', N'CLR_SEMAPHORE',
        N'DBMIRROR_DBM_EVENT', N'DBMIRROR_EVENTS_QUEUE', N'DBMIRROR_WORKER_QUEUE',
		N'DBMIRRORING_CMD', N'DIRTY_PAGE_POLL', N'DISPATCHER_QUEUE_SEMAPHORE',
        N'EXECSYNC', N'FSAGENT', N'FT_IFTS_SCHEDULER_IDLE_WAIT', N'FT_IFTSHC_MUTEX',
        N'HADR_CLUSAPI_CALL', N'HADR_FILESTREAM_IOMGR_IOCOMPLETION', N'HADR_LOGCAPTURE_WAIT', 
		N'HADR_NOTIFICATION_DEQUEUE', N'HADR_TIMER_TASK', N'HADR_WORK_QUEUE',
        N'KSOURCE_WAKEUP', N'LAZYWRITER_SLEEP', N'LOGMGR_QUEUE', N'ONDEMAND_TASK_QUEUE',
        N'PWAIT_ALL_COMPONENTS_INITIALIZED', N'QDS_PERSIST_TASK_MAIN_LOOP_SLEEP',
        N'QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP', N'REQUEST_FOR_DEADLOCK_SEARCH',
		N'RESOURCE_QUEUE', N'SERVER_IDLE_CHECK', N'SLEEP_BPOOL_FLUSH', N'SLEEP_DBSTARTUP',
		N'SLEEP_DCOMSTARTUP', N'SLEEP_MASTERDBREADY', N'SLEEP_MASTERMDREADY',
        N'SLEEP_MASTERUPGRADED', N'SLEEP_MSDBSTARTUP', N'SLEEP_SYSTEMTASK', N'SLEEP_TASK',
        N'SLEEP_TEMPDBSTARTUP', N'SNI_HTTP_ACCEPT', N'SP_SERVER_DIAGNOSTICS_SLEEP',
		N'SQLTRACE_BUFFER_FLUSH', N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', N'SQLTRACE_WAIT_ENTRIES',
		N'WAIT_FOR_RESULTS', N'WAITFOR', N'WAITFOR_TASKSHUTDOWN', N'WAIT_XTP_HOST_WAIT',
		N'WAIT_XTP_OFFLINE_CKPT_NEW_LOG', N'WAIT_XTP_CKPT_CLOSE', N'XE_DISPATCHER_JOIN',
        N'XE_DISPATCHER_WAIT', N'XE_TIMER_EVENT')
    AND waiting_tasks_count > 0)
SELECT
    MAX (W1.wait_type) AS [WaitType],
	CAST (MAX (W1.Percentage) AS DECIMAL (5,2)) AS [Wait Percentage],
	CAST ((MAX (W1.WaitS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgWait_Sec],
    CAST ((MAX (W1.ResourceS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgRes_Sec],
    CAST ((MAX (W1.SignalS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgSig_Sec], 
    CAST (MAX (W1.WaitS) AS DECIMAL (16,2)) AS [Wait_Sec],
    CAST (MAX (W1.ResourceS) AS DECIMAL (16,2)) AS [Resource_Sec],
    CAST (MAX (W1.SignalS) AS DECIMAL (16,2)) AS [Signal_Sec],
    MAX (W1.WaitCount) AS [Wait Count],
	CAST (N'https://www.sqlskills.com/help/waits/' + W1.wait_type AS XML) AS [Help/Info URL]
FROM Waits AS W1
INNER JOIN Waits AS W2
ON W2.RowNum <= W1.RowNum
GROUP BY W1.RowNum, W1.wait_type
HAVING SUM (W2.Percentage) - MAX (W1.Percentage) < 99 -- percentage threshold
OPTION (RECOMPILE);
------

-- Cumulative wait stats are not as useful on an idle instance that is not under load or performance pressure

-- SQL Server Wait Types Library (Paul Randal)
-- https://www.sqlskills.com/help/waits/

-- The SQL Server Wait Type Repository
-- http://blogs.msdn.com/b/psssql/archive/2009/11/03/the-sql-server-wait-type-repository.aspx

-- Wait statistics, or please tell me where it hurts
-- https://www.sqlskills.com/blogs/paul/wait-statistics-or-please-tell-me-where-it-hurts/

-- SQL Server 2005 Performance Tuning using the Waits and Queues
-- http://technet.microsoft.com/en-us/library/cc966413.aspx

-- sys.dm_os_wait_stats (Transact-SQL)
-- http://msdn.microsoft.com/en-us/library/ms179984(v=sql.105).aspx




-- Signal Waits for instance  (Query 28) (Signal Waits)
SELECT CAST(100.0 * SUM(signal_wait_time_ms) / SUM (wait_time_ms) AS NUMERIC(20,2)) AS [% Signal (CPU) Waits],
CAST(100.0 * SUM(wait_time_ms - signal_wait_time_ms) / SUM (wait_time_ms) AS NUMERIC(20,2)) AS [% Resource Waits]
FROM sys.dm_os_wait_stats WITH (NOLOCK)
WHERE wait_type NOT IN (
        N'BROKER_EVENTHANDLER', N'BROKER_RECEIVE_WAITFOR', N'BROKER_TASK_STOP',
		N'BROKER_TO_FLUSH', N'BROKER_TRANSMITTER', N'CHECKPOINT_QUEUE',
        N'CHKPT', N'CLR_AUTO_EVENT', N'CLR_MANUAL_EVENT', N'CLR_SEMAPHORE',
        N'DBMIRROR_DBM_EVENT', N'DBMIRROR_EVENTS_QUEUE', N'DBMIRROR_WORKER_QUEUE',
		N'DBMIRRORING_CMD', N'DIRTY_PAGE_POLL', N'DISPATCHER_QUEUE_SEMAPHORE',
        N'EXECSYNC', N'FSAGENT', N'FT_IFTS_SCHEDULER_IDLE_WAIT', N'FT_IFTSHC_MUTEX',
        N'HADR_CLUSAPI_CALL', N'HADR_FILESTREAM_IOMGR_IOCOMPLETION', N'HADR_LOGCAPTURE_WAIT', 
		N'HADR_NOTIFICATION_DEQUEUE', N'HADR_TIMER_TASK', N'HADR_WORK_QUEUE',
        N'KSOURCE_WAKEUP', N'LAZYWRITER_SLEEP', N'LOGMGR_QUEUE', N'ONDEMAND_TASK_QUEUE',
        N'PWAIT_ALL_COMPONENTS_INITIALIZED', N'QDS_PERSIST_TASK_MAIN_LOOP_SLEEP',
        N'QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP', N'REQUEST_FOR_DEADLOCK_SEARCH',
		N'RESOURCE_QUEUE', N'SERVER_IDLE_CHECK', N'SLEEP_BPOOL_FLUSH', N'SLEEP_DBSTARTUP',
		N'SLEEP_DCOMSTARTUP', N'SLEEP_MASTERDBREADY', N'SLEEP_MASTERMDREADY',
        N'SLEEP_MASTERUPGRADED', N'SLEEP_MSDBSTARTUP', N'SLEEP_SYSTEMTASK', N'SLEEP_TASK',
        N'SLEEP_TEMPDBSTARTUP', N'SNI_HTTP_ACCEPT', N'SP_SERVER_DIAGNOSTICS_SLEEP',
		N'SQLTRACE_BUFFER_FLUSH', N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', N'SQLTRACE_WAIT_ENTRIES',
		N'WAIT_FOR_RESULTS', N'WAITFOR', N'WAITFOR_TASKSHUTDOWN', N'WAIT_XTP_HOST_WAIT',
		N'WAIT_XTP_OFFLINE_CKPT_NEW_LOG', N'WAIT_XTP_CKPT_CLOSE', N'XE_DISPATCHER_JOIN',
        N'XE_DISPATCHER_WAIT', N'XE_TIMER_EVENT') OPTION (RECOMPILE);
------

-- Signal Waits above 10-15% is usually a confirming sign of CPU pressure
-- Cumulative wait stats are not as useful on an idle instance that is not under load or performance pressure
-- Resource waits are non-CPU related waits


--  Get logins that are connected and how many sessions they have (Query 29) (Connection Counts)
SELECT login_name, [program_name], COUNT(session_id) AS [session_count] 
FROM sys.dm_exec_sessions WITH (NOLOCK)
GROUP BY login_name, [program_name]
ORDER BY COUNT(session_id) DESC OPTION (RECOMPILE);
------

-- This can help characterize your workload and
-- determine whether you are seeing a normal level of activity


-- Get a count of SQL connections by IP address (Query 30) (Connection Counts by IP Address)
SELECT ec.client_net_address, es.[program_name], es.[host_name], es.login_name, 
COUNT(ec.session_id) AS [connection count] 
FROM sys.dm_exec_sessions AS es WITH (NOLOCK) 
INNER JOIN sys.dm_exec_connections AS ec WITH (NOLOCK) 
ON es.session_id = ec.session_id 
GROUP BY ec.client_net_address, es.[program_name], es.[host_name], es.login_name  
ORDER BY ec.client_net_address, es.[program_name] OPTION (RECOMPILE);
------

-- This helps you figure where your database load is coming from
-- and verifies connectivity from other machines


-- Get Average Task Counts (run multiple times) (Query 31) (Avg Task Counts)
SELECT AVG(current_tasks_count) AS [Avg Task Count], 
AVG(runnable_tasks_count) AS [Avg Runnable Task Count],
AVG(pending_disk_io_count) AS [Avg Pending DiskIO Count]
FROM sys.dm_os_schedulers WITH (NOLOCK)
WHERE scheduler_id < 255 OPTION (RECOMPILE);
------

-- Sustained values above 10 suggest further investigation in that area
-- High Avg Task Counts are often caused by blocking/deadlocking or other resource contention

-- Sustained values above 1 suggest further investigation in that area
-- High Avg Runnable Task Counts are a good sign of CPU pressure
-- High Avg Pending DiskIO Counts are a sign of disk pressure

-- How to Do Some Very Basic SQL Server Monitoring
-- https://www.sqlskills.com/blogs/glenn/how-to-do-some-very-basic-sql-server-monitoring/



-- Get CPU Utilization History for last 256 minutes (in one minute intervals)  (Query 32) (CPU Utilization History)
-- This version works with SQL Server 2008 R2
DECLARE @ts_now bigint = (SELECT cpu_ticks/(cpu_ticks/ms_ticks) FROM sys.dm_os_sys_info WITH (NOLOCK)); 

SELECT TOP(256) SQLProcessUtilization AS [SQL Server Process CPU Utilization], 
               SystemIdle AS [System Idle Process], 
               100 - SystemIdle - SQLProcessUtilization AS [Other Process CPU Utilization], 
               DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) AS [Event Time] 
FROM ( 
	  SELECT record.value('(./Record/@id)[1]', 'int') AS record_id, 
			record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') 
			AS [SystemIdle], 
			record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 
			'int') 
			AS [SQLProcessUtilization], [timestamp] 
	  FROM ( 
			SELECT [timestamp], CONVERT(xml, record) AS [record] 
			FROM sys.dm_os_ring_buffers WITH (NOLOCK)
			WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR' 
			AND record LIKE N'%<SystemHealth>%') AS x 
	  ) AS y 
ORDER BY record_id DESC OPTION (RECOMPILE);
------

-- Look at the trend over the entire period. 
-- Also look at high sustained Other Process CPU Utilization values


-- Get top total worker time queries for entire instance (Query 33) (Top Worker Time Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], t.[text] AS [Query Text],  
qs.total_worker_time AS [Total Worker Time], qs.min_worker_time AS [Min Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.max_worker_time AS [Max Worker Time], qs.execution_count AS [Execution Count], 
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time], 
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads], 
qs.total_physical_reads/qs.execution_count AS [Avg Physical Reads], qs.creation_time AS [Creation Time]
, qp.query_plan AS [Query Plan] -- comment out this column if copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
ORDER BY qs.total_worker_time DESC OPTION (RECOMPILE);
------


-- Helps you find the most expensive queries from a CPU perspective across the entire instance



-- Good basic information about OS memory amounts and state  (Query 34) (System Memory)
SELECT total_physical_memory_kb/1024 AS [Physical Memory (MB)], 
       available_physical_memory_kb/1024 AS [Available Memory (MB)], 
       total_page_file_kb/1024 AS [Total Page File (MB)], 
	   available_page_file_kb/1024 AS [Available Page File (MB)], 
	   system_cache_kb/1024 AS [System Cache (MB)],
       system_memory_state_desc AS [System Memory State]
FROM sys.dm_os_sys_memory WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You want to see "Available physical memory is high"
-- This indicates that you are not under external memory pressure


-- SQL Server Process Address space info  (Query 35) (Process Memory) 
-- (shows whether locked pages is enabled, among other things)
SELECT physical_memory_in_use_kb/1024 AS [SQL Server Memory Usage (MB)],
       large_page_allocations_kb, locked_page_allocations_kb, page_fault_count, 
	   memory_utilization_percentage, available_commit_limit_kb, 
	   process_physical_memory_low, process_virtual_memory_low
FROM sys.dm_os_process_memory WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You want to see 0 for process_physical_memory_low
-- You want to see 0 for process_virtual_memory_low
-- This indicates that you are not under internal memory pressure


-- Page Life Expectancy (PLE) value for each NUMA node in current instance  (Query 36) (PLE by NUMA Node)
SELECT @@SERVERNAME AS [Server Name], RTRIM([object_name]) AS [Object Name], instance_name, cntr_value AS [Page Life Expectancy]
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Buffer Node%' -- Handles named instances
AND counter_name = N'Page life expectancy' OPTION (RECOMPILE);
------

-- PLE is a good measurement of memory pressure.
-- Higher PLE is better. Watch the trend over time, not the absolute value.
-- This will only return one row for non-NUMA systems.

-- Page Life Expectancy isn�t what you think�
-- https://www.sqlskills.com/blogs/paul/page-life-expectancy-isnt-what-you-think/



-- Memory Grants Pending value for current instance  (Query 37) (Memory Grants Pending)
SELECT @@SERVERNAME AS [Server Name], RTRIM([object_name]) AS [Object Name], cntr_value AS [Memory Grants Pending]                                                                                                       
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Memory Manager%' -- Handles named instances
AND counter_name = N'Memory Grants Pending' OPTION (RECOMPILE);
------

-- Memory Grants Pending above zero for a sustained period is a very strong indicator of memory pressure


-- Memory Clerk Usage for instance  (Query 38) (Memory Clerk Usage)
-- Look for high value for CACHESTORE_SQLCP (Ad-hoc query plans)
SELECT TOP(10) [type] AS [Memory Clerk Type], SUM(single_pages_kb)/1024 AS [SPA Memory Usage (MB)] 
FROM sys.dm_os_memory_clerks WITH (NOLOCK)
GROUP BY [type]  
ORDER BY SUM(single_pages_kb) DESC OPTION (RECOMPILE);
------

-- CACHESTORE_SQLCP  SQL Plans         
-- These are cached SQL statements or batches that aren't in stored procedures, functions and triggers
-- Watch out for high values for CACHESTORE_SQLCP

-- CACHESTORE_OBJCP  Object Plans      
-- These are compiled plans for stored procedures, functions and triggers



-- Find single-use, ad-hoc and prepared queries that are bloating the plan cache  (Query 39) (Ad hoc Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], t.[text] AS [Query Text], 
cp.objtype AS [Object Type], cp.cacheobjtype AS [Cache Object Type],  
cp.size_in_bytes/1024 AS [Plan Size in KB]
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t
WHERE cp.cacheobjtype = N'Compiled Plan' 
AND cp.objtype IN (N'Adhoc', N'Prepared') 
AND cp.usecounts = 1
ORDER BY cp.size_in_bytes DESC, DB_NAME(t.[dbid]) OPTION (RECOMPILE);
------

-- Gives you the text, type and size of single-use ad-hoc and prepared queries that waste space in the plan cache
-- Enabling 'optimize for ad hoc workloads' for the instance can help (SQL Server 2008 and above only)
-- Running DBCC FREESYSTEMCACHE ('SQL Plans') periodically may be required to better control this.
-- Enabling forced parameterization for the database can help, but test first!

-- Plan cache, adhoc workloads and clearing the single-use plan cache bloat
-- https://www.sqlskills.com/blogs/kimberly/plan-cache-adhoc-workloads-and-clearing-the-single-use-plan-cache-bloat/



-- Database specific queries *****************************************************************

-- **** Please switch to a user database that you are interested in! *****
USE YourDatabaseName; -- make sure to change to an actual database on your instance, not the master system database
GO

-- Individual File Sizes and space available for current database  (Query 40) (File Sizes and Space)
SELECT f.name AS [File Name] , f.physical_name AS [Physical Name], 
CAST((f.size/128.0) AS DECIMAL(15,2)) AS [Total Size in MB],
CAST(f.size/128.0 - CAST(FILEPROPERTY(f.name, 'SpaceUsed') AS int)/128.0 AS DECIMAL(15,2)) 
AS [Available Space In MB], [file_id], fg.name AS [Filegroup Name]
FROM sys.database_files AS f WITH (NOLOCK) 
LEFT OUTER JOIN sys.data_spaces AS fg WITH (NOLOCK) 
ON f.data_space_id = fg.data_space_id OPTION (RECOMPILE);
------

-- Look at how large and how full the files are and where they are located
-- Make sure the transaction log is not full!!



-- I/O Statistics by file for the current database  (Query 41) (IO Stats By File)
SELECT DB_NAME(DB_ID()) AS [Database Name], df.name AS [Logical Name], vfs.[file_id], 
df.physical_name AS [Physical Name], vfs.num_of_reads, vfs.num_of_writes, vfs.io_stall_read_ms, vfs.io_stall_write_ms,
CAST(100. * vfs.io_stall_read_ms/(vfs.io_stall_read_ms + vfs.io_stall_write_ms) AS DECIMAL(10,1)) AS [IO Stall Reads Pct],
CAST(100. * vfs.io_stall_write_ms/(vfs.io_stall_write_ms + vfs.io_stall_read_ms) AS DECIMAL(10,1)) AS [IO Stall Writes Pct],
(vfs.num_of_reads + vfs.num_of_writes) AS [Writes + Reads], 
CAST(vfs.num_of_bytes_read/1048576.0 AS DECIMAL(10, 2)) AS [MB Read], 
CAST(vfs.num_of_bytes_written/1048576.0 AS DECIMAL(10, 2)) AS [MB Written],
CAST(100. * vfs.num_of_reads/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(10,1)) AS [# Reads Pct],
CAST(100. * vfs.num_of_writes/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(10,1)) AS [# Write Pct],
CAST(100. * vfs.num_of_bytes_read/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(10,1)) AS [Read Bytes Pct],
CAST(100. * vfs.num_of_bytes_written/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(10,1)) AS [Written Bytes Pct]
FROM sys.dm_io_virtual_file_stats(DB_ID(), NULL) AS vfs
INNER JOIN sys.database_files AS df WITH (NOLOCK)
ON vfs.[file_id]= df.[file_id] OPTION (RECOMPILE);
------

-- This helps you characterize your workload better from an I/O perspective for this database
-- It helps you determine whether you has an OLTP or DW/DSS type of workload



-- Top cached queries by Execution Count (SQL Server 2008 R2)  (Query 42) (Query Execution Counts)
-- SQL Server 2008 R2 SP1 and greater only
SELECT TOP (100) qs.execution_count, qs.total_rows, qs.last_rows, qs.min_rows, qs.max_rows,
qs.last_elapsed_time, qs.min_elapsed_time, qs.max_elapsed_time,
total_worker_time, total_logical_reads, 
SUBSTRING(qt.TEXT,qs.statement_start_offset/2 +1,
(CASE WHEN qs.statement_end_offset = -1
			THEN LEN(CONVERT(NVARCHAR(MAX), qt.TEXT)) * 2
	  ELSE qs.statement_end_offset END - qs.statement_start_offset)/2) AS query_text 
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
ORDER BY qs.execution_count DESC OPTION (RECOMPILE);
------

-- Uses several new rows returned columns to help troubleshoot performance problems


-- Top Cached SPs By Execution Count (SQL 2008 R2) (Query 43) (SP Execution Counts)
SELECT TOP(100) p.name AS [SP Name], qs.execution_count,
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], qs.total_worker_time AS [TotalWorkerTime],  
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
qs.cached_time
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
WHERE qs.database_id = DB_ID()
ORDER BY qs.execution_count DESC OPTION (RECOMPILE);
------

-- Tells you which cached stored procedures are called the most often
-- This helps you characterize and baseline your workload


-- Top Cached SPs By Avg Elapsed Time (SQL 2008 R2)  (Query 44) (SP Avg Elapsed Time) 
SELECT TOP(25) p.name AS [SP Name], qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time], 
qs.total_elapsed_time, qs.execution_count, ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, 
GETDATE()), 0) AS [Calls/Minute], qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], 
qs.total_worker_time AS [TotalWorkerTime], qs.cached_time
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
WHERE qs.database_id = DB_ID()
ORDER BY avg_elapsed_time DESC OPTION (RECOMPILE);
------

-- This helps you find long-running cached stored procedures that
-- may be easy to optimize with standard query tuning techniques


-- Top Cached SPs By Avg Elapsed Time with execution time variability   (Query 45) (SP Avg Elapsed Variable Time)
SELECT TOP(25) p.name AS [SP Name], qs.execution_count, qs.min_elapsed_time,
qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
qs.max_elapsed_time, qs.last_elapsed_time,  qs.cached_time
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
WHERE qs.database_id = DB_ID()
ORDER BY avg_elapsed_time DESC OPTION (RECOMPILE);
------

-- This gives you some interesting information about the variability in the
-- execution time of your cached stored procedures, which is useful for tuning


-- Top Cached SPs By Total Worker time (SQL 2008 R2). Worker time relates to CPU cost  (Query 46) (SP Worker Time)
SELECT TOP(25) p.name AS [SP Name], qs.total_worker_time AS [TotalWorkerTime], 
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count 
AS [avg_elapsed_time], qs.cached_time
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
WHERE qs.database_id = DB_ID()
ORDER BY qs.total_worker_time DESC OPTION (RECOMPILE);

-- This helps you find the most expensive cached stored procedures from a CPU perspective
-- You should look at this if you see signs of CPU pressure


-- Top Cached SPs By Total Logical Reads (SQL 2008 R2). Logical reads relate to memory pressure  (Query 47) (SP Logical Reads)
SELECT TOP(25) p.name AS [SP Name], qs.total_logical_reads AS [TotalLogicalReads], 
qs.total_logical_reads/qs.execution_count AS [AvgLogicalReads],qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute], 
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count 
AS [avg_elapsed_time], qs.cached_time
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
WHERE qs.database_id = DB_ID()
ORDER BY qs.total_logical_reads DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a memory perspective
-- You should look at this if you see signs of memory pressure


-- Top Cached SPs By Total Physical Reads (SQL 2008 R2). Physical reads relate to disk I/O pressure  (Query 48) (SP Physical Reads)
SELECT TOP(25) p.name AS [SP Name],qs.total_physical_reads AS [TotalPhysicalReads], 
qs.total_physical_reads/qs.execution_count AS [AvgPhysicalReads], qs.execution_count, 
qs.total_logical_reads,qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count 
AS [avg_elapsed_time], qs.cached_time 
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
WHERE qs.database_id = DB_ID()
AND qs.total_physical_reads > 0
ORDER BY qs.total_physical_reads DESC, qs.total_logical_reads DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a read I/O perspective
-- You should look at this if you see signs of I/O pressure or of memory pressure
       
-- Top Cached SPs By Total Logical Writes (SQL 2008 R2)  (Query 49) (SP Logical Writes)
-- Logical writes relate to both memory and disk I/O pressure 
SELECT TOP(25) p.name AS [SP Name], qs.total_logical_writes AS [TotalLogicalWrites], 
qs.total_logical_writes/qs.execution_count AS [AvgLogicalWrites], qs.execution_count,
ISNULL(qs.execution_count/DATEDIFF(Second, qs.cached_time, GETDATE()), 0) AS [Calls/Second],
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time], 
qs.cached_time
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
WHERE qs.database_id = DB_ID()
AND qs.total_logical_writes > 0
ORDER BY qs.total_logical_writes DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a write I/O perspective
-- You should look at this if you see signs of I/O pressure or of memory pressure


-- Lists the top statements by average input/output usage for the current database  (Query 50) (Top IO Statements)
SELECT TOP(50) OBJECT_NAME(qt.objectid, dbid) AS [SP Name],
(qs.total_logical_reads + qs.total_logical_writes) /qs.execution_count AS [Avg IO], qs.execution_count AS [Execution Count],
SUBSTRING(qt.[text],qs.statement_start_offset/2, 
	(CASE 
		WHEN qs.statement_end_offset = -1 
	 THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2 
		ELSE qs.statement_end_offset 
	 END - qs.statement_start_offset)/2) AS [Query Text]	
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
WHERE qt.[dbid] = DB_ID()
ORDER BY [Avg IO] DESC OPTION (RECOMPILE);
------

-- Helps you find the most expensive statements for I/O by SP



-- Possible Bad NC Indexes (writes > reads)  (Query 51) (Bad NC Indexes)
SELECT OBJECT_NAME(s.[object_id]) AS [Table Name], i.name AS [Index Name], i.index_id, 
i.is_disabled, i.is_hypothetical, i.has_filter, i.fill_factor,
user_updates AS [Total Writes], user_seeks + user_scans + user_lookups AS [Total Reads],
user_updates - (user_seeks + user_scans + user_lookups) AS [Difference]
FROM sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON s.[object_id] = i.[object_id]
AND i.index_id = s.index_id
WHERE OBJECTPROPERTY(s.[object_id],'IsUserTable') = 1
AND s.database_id = DB_ID()
AND s.user_updates > (s.user_seeks + s.user_scans + s.user_lookups)
AND i.index_id > 1 AND i.[type_desc] = N'NONCLUSTERED'
AND i.is_primary_key = 0 AND i.is_unique_constraint = 0
ORDER BY [Difference] DESC, [Total Writes] DESC, [Total Reads] ASC OPTION (RECOMPILE);
------

-- Look for indexes with high numbers of writes and zero or very low numbers of reads
-- Consider your complete workload, and how long your instance has been running
-- Investigate further before dropping an index!


-- Missing Indexes for current database by Index Advantage  (Query 52) (Missing Indexes)
SELECT DISTINCT CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage], 
migs.last_user_seek, mid.[statement] AS [Database.Schema.Table],
mid.equality_columns, mid.inequality_columns, mid.included_columns,
migs.unique_compiles, migs.user_seeks, migs.avg_total_user_cost, migs.avg_user_impact,
OBJECT_NAME(mid.[object_id]) AS [Table Name], p.rows AS [Table Rows]
FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)
INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)
ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)
ON mig.index_handle = mid.index_handle
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON p.[object_id] = mid.[object_id]
WHERE mid.database_id = DB_ID()
AND p.index_id < 2 
ORDER BY index_advantage DESC OPTION (RECOMPILE);
------

-- Look at index advantage, last user seek time, number of user seeks to help determine source and importance
-- SQL Server is overly eager to add included columns, so beware
-- Do not just blindly add indexes that show up from this query!!!


-- Find missing index warnings for cached plans in the current database  (Query 53) (Missing Index Warnings)
-- Note: This query could take some time on a busy instance
SELECT TOP(25) OBJECT_NAME(objectid) AS [ObjectName], 
               query_plan, cp.objtype, cp.usecounts
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) AS qp
WHERE CAST(query_plan AS NVARCHAR(MAX)) LIKE N'%MissingIndex%'
AND dbid = DB_ID()
ORDER BY cp.usecounts DESC OPTION (RECOMPILE);
------

-- Helps you connect missing indexes to specific stored procedures
-- This can help you decide whether to add them or not


-- Breaks down buffers used by current database by object (table, index) in the buffer cache  (Query 54) (Buffer Usage)
-- Note: This query could take some time on a busy instance
SELECT OBJECT_NAME(p.[object_id]) AS [Object Name], p.index_id, 
CAST(COUNT(*)/128.0 AS DECIMAL(10, 2)) AS [Buffer size(MB)],  
COUNT(*) AS [BufferCount], p.Rows AS [Row Count],
p.data_compression_desc AS [Compression Type]
FROM sys.allocation_units AS a WITH (NOLOCK)
INNER JOIN sys.dm_os_buffer_descriptors AS b WITH (NOLOCK)
ON a.allocation_unit_id = b.allocation_unit_id
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON a.container_id = p.hobt_id
WHERE b.database_id = CONVERT(int,DB_ID())
AND p.[object_id] > 100
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'plan_%'
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'sys%'
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'xml_index_nodes%'
GROUP BY p.[object_id], p.index_id, p.data_compression_desc, p.[Rows]
ORDER BY [BufferCount] DESC OPTION (RECOMPILE);
------

-- Tells you what tables and indexes are using the most memory in the buffer cache
-- It can help identify possible candidates for data compression


-- Get Table names, row counts, and compression status for clustered index or heap  (Query 55) (Table Sizes)
SELECT SCHEMA_NAME(o.Schema_ID) AS [Schema Name], OBJECT_NAME(p.object_id) AS [ObjectName], 
SUM(p.Rows) AS [RowCount], data_compression_desc AS [CompressionType]
FROM sys.partitions AS p WITH (NOLOCK)
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON p.object_id = o.object_id
WHERE index_id < 2 --ignore the partitions from the non-clustered index if any
AND OBJECT_NAME(p.object_id) NOT LIKE N'sys%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'spt_%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'queue_%' 
AND OBJECT_NAME(p.object_id) NOT LIKE N'filestream_tombstone%' 
AND OBJECT_NAME(p.object_id) NOT LIKE N'fulltext%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'ifts_comp_fragment%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'filetable_updates%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'xml_index_nodes%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'sqlagent_job%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'plan_persist%'
GROUP BY  SCHEMA_NAME(o.Schema_ID), p.object_id, data_compression_desc
ORDER BY SUM(p.Rows) DESC OPTION (RECOMPILE);
------

-- Gives you an idea of table sizes, and possible data compression opportunities



-- Get some key table properties (Query 56) (Table Properties)
SELECT [name], create_date, lock_on_bulk_load, is_replicated, has_replication_filter, 
       is_tracked_by_cdc, lock_escalation_desc
FROM sys.tables WITH (NOLOCK) 
ORDER BY [name] OPTION (RECOMPILE);
------

-- Gives you some good information about your tables


-- Detect blocking (run multiple times)  (Query 57) (Detect Blocking)
SELECT t1.resource_type AS [lock type], DB_NAME(resource_database_id) AS [database],
t1.resource_associated_entity_id AS [blk object],t1.request_mode AS [lock req],  --- lock requested
t1.request_session_id AS [waiter sid], t2.wait_duration_ms AS [wait time],       -- spid of waiter  
(SELECT [text] FROM sys.dm_exec_requests AS r WITH (NOLOCK)                      -- get sql for waiter
CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) 
WHERE r.session_id = t1.request_session_id) AS [waiter_batch],
(SELECT SUBSTRING(qt.[text],r.statement_start_offset/2, 
    (CASE WHEN r.statement_end_offset = -1 
    THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2 
    ELSE r.statement_end_offset END - r.statement_start_offset)/2) 
FROM sys.dm_exec_requests AS r WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) AS qt
WHERE r.session_id = t1.request_session_id) AS [waiter_stmt],					-- statement blocked
t2.blocking_session_id AS [blocker sid],										-- spid of blocker
(SELECT [text] FROM sys.sysprocesses AS p										-- get sql for blocker
CROSS APPLY sys.dm_exec_sql_text(p.[sql_handle]) 
WHERE p.spid = t2.blocking_session_id) AS [blocker_stmt]
FROM sys.dm_tran_locks AS t1 WITH (NOLOCK)
INNER JOIN sys.dm_os_waiting_tasks AS t2 WITH (NOLOCK)
ON t1.lock_owner_address = t2.resource_address OPTION (RECOMPILE);
------

-- Helps troubleshoot blocking and deadlocking issues
-- The results will change from second to second on a busy system
-- You should run this query multiple times when you see signs of blocking



-- When were Statistics last updated on all indexes?  (Query 58) (Statistics Update)
SELECT SCHEMA_NAME(o.Schema_ID) + N'.' + o.NAME AS [Object Name], o.type_desc AS [Object Type],
      i.name AS [Index Name], STATS_DATE(i.[object_id], i.index_id) AS [Statistics Date], 
      s.auto_created, s.no_recompute, s.user_created, st.row_count, st.used_page_count
FROM sys.objects AS o WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON o.[object_id] = i.[object_id]
INNER JOIN sys.stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id] 
AND i.index_id = s.stats_id
INNER JOIN sys.dm_db_partition_stats AS st WITH (NOLOCK)
ON o.[object_id] = st.[object_id]
AND i.[index_id] = st.[index_id]
WHERE o.[type] IN ('U', 'V')
AND st.row_count > 0
ORDER BY STATS_DATE(i.[object_id], i.index_id) DESC OPTION (RECOMPILE);
------  

-- Helps discover possible problems with out-of-date statistics
-- Also gives you an idea which indexes are the most active


-- Look at most frequently modified indexes and statistics (Query 59) (Volatile Indexes)
-- Requires SQL Server 2008 R2 SP2 or newer
SELECT o.name AS [Object Name], o.[object_id], o.type_desc, s.name AS [Statistics Name], 
       s.stats_id, s.no_recompute, s.auto_created, 
	   sp.modification_counter, sp.rows, sp.rows_sampled, sp.last_updated
FROM sys.objects AS o WITH (NOLOCK)
INNER JOIN sys.stats AS s WITH (NOLOCK)
ON s.object_id = o.object_id
CROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) AS sp
WHERE o.type_desc NOT IN (N'SYSTEM_TABLE', N'INTERNAL_TABLE')
AND sp.modification_counter > 0
ORDER BY sp.modification_counter DESC, o.name OPTION (RECOMPILE);
------


-- Get fragmentation info for all indexes above a certain size in the current database  (Query 60) (Index Fragmentation)
-- Note: This query could take some time on a very large database
SELECT DB_NAME(ps.database_id) AS [Database Name], SCHEMA_NAME(o.[schema_id]) AS [Schema Name],
OBJECT_NAME(ps.OBJECT_ID) AS [Object Name], 
i.name AS [Index Name], ps.index_id, ps.index_type_desc, ps.avg_fragmentation_in_percent, 
ps.fragment_count, ps.page_count, i.fill_factor, i.has_filter, i.filter_definition, i.allow_page_locks
FROM sys.dm_db_index_physical_stats(DB_ID(),NULL, NULL, NULL , N'LIMITED') AS ps
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ps.[object_id] = i.[object_id] 
AND ps.index_id = i.index_id
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON i.[object_id] = o.[object_id]
WHERE ps.database_id = DB_ID()
AND ps.page_count > 2500
ORDER BY ps.avg_fragmentation_in_percent DESC OPTION (RECOMPILE);
------

-- Helps determine whether you have framentation in your relational indexes
-- and how effective your index maintenance strategy is


--- Index Read/Write stats (all tables in current DB) ordered by Reads  (Query 61) (Overall Index Usage - Reads)
SELECT OBJECT_NAME(s.[object_id]) AS [ObjectName], i.name AS [IndexName], i.index_id,
	   user_seeks + user_scans + user_lookups AS [Reads], s.user_updates AS [Writes],  
	   i.type_desc AS [IndexType], i.fill_factor AS [FillFactor], i.has_filter, i.filter_definition, 
	   s.last_user_scan, s.last_user_lookup, s.last_user_seek
FROM sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON s.[object_id] = i.[object_id]
WHERE OBJECTPROPERTY(s.[object_id],'IsUserTable') = 1
AND i.index_id = s.index_id
AND s.database_id = DB_ID()
ORDER BY user_seeks + user_scans + user_lookups DESC OPTION (RECOMPILE); -- Order by reads
------


-- Show which indexes in the current database are most active for Reads


--- Index Read/Write stats (all tables in current DB) ordered by Writes  (Query 62) (Overall Index Usage - Writes)
SELECT OBJECT_NAME(s.[object_id]) AS [ObjectName], i.name AS [IndexName], i.index_id,
	   s.user_updates AS [Writes], user_seeks + user_scans + user_lookups AS [Reads], 
	   i.type_desc AS [IndexType], i.fill_factor AS [FillFactor], i.has_filter, i.filter_definition,
	   s.last_system_update, s.last_user_update
FROM sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON s.[object_id] = i.[object_id]
WHERE OBJECTPROPERTY(s.[object_id],'IsUserTable') = 1
AND i.index_id = s.index_id
AND s.database_id = DB_ID()
ORDER BY s.user_updates DESC OPTION (RECOMPILE);						 -- Order by writes
------

-- Show which indexes in the current database are most active for Writes


-- Get lock waits for current database (Query 63) (Lock Waits)
SELECT o.name AS [table_name], i.name AS [index_name], ios.index_id, ios.partition_number,
		SUM(ios.row_lock_wait_count) AS [total_row_lock_waits], 
		SUM(ios.row_lock_wait_in_ms) AS [total_row_lock_wait_in_ms],
		SUM(ios.page_lock_wait_count) AS [total_page_lock_waits],
		SUM(ios.page_lock_wait_in_ms) AS [total_page_lock_wait_in_ms],
		SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) AS [total_lock_wait_in_ms]
FROM sys.dm_db_index_operational_stats(DB_ID(), NULL, NULL, NULL) AS ios
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON ios.[object_id] = o.[object_id]
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ios.[object_id] = i.[object_id] 
AND ios.index_id = i.index_id
WHERE o.[object_id] > 100
GROUP BY o.name, i.name, ios.index_id, ios.partition_number
HAVING SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) > 0
ORDER BY total_lock_wait_in_ms DESC OPTION (RECOMPILE);
------

-- This query is helpful for troubleshooting blocking and deadlocking issues


-- Look at recent Full backups for the current database (Query 64) (Recent Full Backups)
SELECT TOP (30) bs.machine_name, bs.server_name, bs.database_name AS [Database Name], bs.recovery_model,
CONVERT (BIGINT, bs.backup_size / 1048576 ) AS [Uncompressed Backup Size (MB)],
CONVERT (BIGINT, bs.compressed_backup_size / 1048576 ) AS [Compressed Backup Size (MB)],
CONVERT (NUMERIC (20,2), (CONVERT (FLOAT, bs.backup_size) /
CONVERT (FLOAT, bs.compressed_backup_size))) AS [Compression Ratio], bs.has_backup_checksums, bs.is_copy_only,
DATEDIFF (SECOND, bs.backup_start_date, bs.backup_finish_date) AS [Backup Elapsed Time (sec)],
bs.backup_finish_date AS [Backup Finish Date], bmf.physical_device_name AS [Backup Location], bmf.physical_block_size
FROM msdb.dbo.backupset AS bs WITH (NOLOCK)
INNER JOIN msdb.dbo.backupmediafamily AS bmf WITH (NOLOCK)
ON bs.media_set_id = bmf.media_set_id  
WHERE DATEDIFF (SECOND, bs.backup_start_date, bs.backup_finish_date) > 0 
AND bs.backup_size > 0
AND bs.type = 'D' -- Change to L if you want Log backups
AND database_name = DB_NAME(DB_ID())
ORDER BY bs.backup_finish_date DESC OPTION (RECOMPILE);
------

-- Are your backup sizes and times changing over time?
-- Are you using backup checksums?
-- Are you doing copy_only backups?
-- Have you done any backup tuning with striped backups, or changing the parameters of the backup command?


-- These three Pluralsight Courses go into more detail about how to run these queries and interpret the results

-- SQL Server 2014 DMV Diagnostic Queries � Part 1 
-- https://bit.ly/2plxCer

-- SQL Server 2014 DMV Diagnostic Queries � Part 2
-- https://bit.ly/2IuJpzI

-- SQL Server 2014 DMV Diagnostic Queries � Part 3
-- https://bit.ly/2FIlCPb



-- Sign up for Microsoft Visual Studio Dev Essentials and get a free three month pass to Pluralsight

-- Microsoft Visual Studio Dev Essentials
-- http://bit.ly/1q6xbDL


-- Sign up for Microsoft Azure Essentials and get lots of free Azure usage credits, MCP exam voucher, three month Pluralsight subscription

-- Microsoft Azure Essentials
-- https://bit.ly/2JMWe8x


-- August 2017 blog series about upgrading and migrating SQL Server
-- https://bit.ly/2ftKVrX
tools\dbatools\bin\diagnosticquery\SQLServerDiagnosticQueries_2008_201811.sql

-- SQL Server 2008 Diagnostic Information Queries
-- Glenn Berry 
-- Last Modified: January 7, 2019
-- https://sqlserverperformance.wordpress.com/
-- https://www.sqlskills.com/blogs/glenn/
-- Twitter: GlennAlanBerry

-- Please listen to my Pluralsight courses
-- https://www.pluralsight.com/author/glenn-berry

-- If you want to find all of our SQLskills SQL101 blog posts, check out https://www.sqlskills.com/help/sql101/

-- Many of these queries will not work if you have databases in 80 compatibility mode
-- Please make sure you are using the correct version of these diagnostic queries for your version of SQL Server

--******************************************************************************
--*   Copyright (C) 2019 Glenn Berry, SQLskills.com
--*   All rights reserved. 
--*
--*   For more scripts and sample code, check out 
--*      https://www.sqlskills.com/blogs/glenn
--*
--*   You may alter this code for your own *non-commercial* purposes. You may
--*   republish altered code as long as you include this copyright and give due credit. 
--*
--*
--*   THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF 
--*   ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED 
--*   TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
--*   PARTICULAR PURPOSE. 
--*
--******************************************************************************

-- Check the major product version to see if it is SQL Server 2008
IF NOT EXISTS (SELECT * WHERE CONVERT(varchar(128), SERVERPROPERTY('ProductVersion')) LIKE '10%')
	BEGIN
		DECLARE @ProductVersion varchar(128) = CONVERT(varchar(128), SERVERPROPERTY('ProductVersion'));
		RAISERROR ('Script does not match the ProductVersion [%s] of this instance. Many of these queries may not work on this version.' , 18 , 16 , @ProductVersion);
	END
	ELSE
		PRINT N'You have the correct major version of SQL Server for this diagnostic information script';


-- Instance level queries *******************************

-- SQL and OS Version information for current instance  (Query 1) (Version Info)
SELECT @@SERVERNAME AS [Server Name], @@VERSION AS [SQL Server and OS Version Info];
------


-- SQL Server 2008 RTM Builds       SQL Server 2008 SP1 Builds       SQL Server 2008 SP2 Builds		      SQL Server 2008 SP3 Builds						SQL Server 2008 SP4 Builds
-- Build           Description      Build          Description		 Build     Description			      Build		    Description							Build		Description
-- 10.0.1600        Gold RTM
-- 10.0.1763        RTM CU1
-- 10.0.1779        RTM CU2
-- 10.0.1787        RTM CU3    -->	10.0.2531		SP1 RTM
-- 10.0.1798        RTM CU4    -->	10.0.2710       SP1 CU1
-- 10.0.1806        RTM CU5    -->	10.0.2714       SP1 CU2 
-- 10.0.1812		RTM CU6    -->	10.0.2723       SP1 CU3
-- 10.0.1818        RTM CU7    -->	10.0.2734       SP1 CU4
-- 10.0.1823        RTM CU8    -->	10.0.2746		SP1 CU5
-- 10.0.1828		RTM CU9    -->	10.0.2757		SP1 CU6
-- 10.0.1835	    RTM CU10   -->	10.0.2766		SP1 CU7
-- RTM Branch Retired          -->	10.0.2775		SP1 CU8		-->  10.0.4000	   SP2 RTM
--								    10.0.2789		SP1 CU9
--								    10.0.2799		SP1 CU10	
--								    10.0.2804		SP1 CU11	-->  10.0.4266     SP2 CU1		
--								    10.0.2808		SP1 CU12	-->  10.0.4272	   SP2 CU2	
--								    10.0.2816	    SP1 CU13    -->  10.0.4279     SP2 CU3	
--								    10.0.2821		SP1 CU14	-->  10.0.4285	   SP2 CU4	-->				10.0.5500		SP3 RTM
--								    10.0.2847		SP1 CU15	-->  10.0.4316	   SP2 CU5  
--								    10.0.2850		SP1 CU16	-->  10.0.4321	   SP2 CU6	-->				10.0.5766		SP3 CU1	      10/17/2011
--                                  SP1 Branch Retired          -->  10.0.4323     SP2 CU7  -->             10.0.5768       SP3 CU2       11/21/2011
--                                                                   10.0.4326	   SP2 CU8  -->             10.0.5770		SP3 CU3       1/16/2012
--														             10.0.4330	   SP2 CU9  -->				10.0.5775		SP3 CU4       3/19/2012
--															         10.0.4332	   SP2 CU10 -->             10.0.5785       SP3 CU5		  5/21/2012
--															         10.0.4333     SP2 CU11 -->			    10.0.5788       SP3 CU6		  7/16/2012
--															         SP2 Branch Retired					    10.0.5794       SP3 CU7		  9/17/2012
--																								            10.0.5828       SP3 CU8		  11/19/2012
--																								            10.0.5829       SP3 CU9       1/21/2013
--																								            10.0.5835       SP3 CU10      3/19/2013
--                                                                                                          10.0.5841       SP3 CU11      5/20/2013
--                                                                                                          10.0.5844       SP3 CU12      7/15/2013
--                                                                                                          10.0.5846       SP3 CU13      9/16/2013
--                                                                                                          10.0.5848       SP3 CU14      11/18/2013
--                                                                                                          10.0.5850		SP3 CU15      1/20/2014
--                                                                                                          10.0.5852       SP3 CU16      3/17/2014
--                                                                                                          10.0.5861       SP3 CU17      5/19/2014			
--                                                                                                          10.0.5867       SP3 CU17+					  10.0.6000		SP4 RTM		9/30/2014
--                                                                                                                                                        10.0.6526     SP4 + HF    2/9/2015 
-- Security Update for SQL Server 2008 SP4 (KB4057114)  https://www.microsoft.com/en-us/download/details.aspx?id=56418                                    10.0.6556		SP4 + HF	1/5/2018
--
-- SQL Server 2008 RTM is considered an "unsupported service pack" as of April 13, 2010
-- SQL Server 2008 SP1 is considered an "unsupported service pack" as of September 19, 2011
-- SQL Server 2008 SP2 is considered an "unsupported service pack" as of September 17, 2012
-- Any build older than 10.0.5500 is on an "unsupported service pack"

-- SQL Server 2008 fell out of Mainstream Support on July 8, 2014

-- The SQL Server 2008 builds that were released after SQL Server 2008 was released
-- http://support.microsoft.com/kb/956909
--
-- The SQL Server 2008 builds that were released after SQL Server 2008 Service Pack 1 was released
-- http://support.microsoft.com/kb/970365
--
-- The SQL Server 2008 builds that were released after SQL Server 2008 Service Pack 2 was released 
-- http://support.microsoft.com/kb/2402659	
--
-- The SQL Server 2008 builds that were released after SQL Server 2008 Service Pack 3 was released
-- http://support.microsoft.com/kb/2629969					   

-- Download SQL Server Management Studio (SSMS)
-- https://msdn.microsoft.com/en-us/library/mt238290.aspx



-- When was SQL Server installed  (Query 2) (SQL Server Install Date)   
SELECT @@SERVERNAME AS [Server Name], create_date AS [SQL Server Install Date] 
FROM sys.server_principals WITH (NOLOCK)
WHERE name = N'NT AUTHORITY\SYSTEM'
OR name = N'NT AUTHORITY\NETWORK SERVICE' OPTION (RECOMPILE);
------

-- Tells you the date and time that SQL Server was installed
-- It is a good idea to know how old your instance is


-- Get selected server properties (Query 3) (Server Properties)
SELECT SERVERPROPERTY('MachineName') AS [MachineName], SERVERPROPERTY('ServerName') AS [ServerName],  
SERVERPROPERTY('InstanceName') AS [Instance], SERVERPROPERTY('IsClustered') AS [IsClustered], 
SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS [ComputerNamePhysicalNetBIOS], 
SERVERPROPERTY('Edition') AS [Edition], SERVERPROPERTY('ProductLevel') AS [ProductLevel], 
SERVERPROPERTY('ProductVersion') AS [ProductVersion], SERVERPROPERTY('ProcessID') AS [ProcessID],
SERVERPROPERTY('Collation') AS [Collation], SERVERPROPERTY('IsFullTextInstalled') AS [IsFullTextInstalled], 
SERVERPROPERTY('IsIntegratedSecurityOnly') AS [IsIntegratedSecurityOnly];
------

-- This gives you a lot of useful information about your instance of SQL Server,
-- such as the ProcessID for SQL Server and your collation


-- Get SQL Server Agent jobs and Category information (Query 4) (SQL Server Agent Jobs)
SELECT sj.name AS [Job Name], sj.[description] AS [Job Description], SUSER_SNAME(sj.owner_sid) AS [Job Owner],
sj.date_created AS [Date Created], sj.[enabled] AS [Job Enabled], 
sj.notify_email_operator_id, sj.notify_level_email, sc.name AS [CategoryName],
s.[enabled] AS [Sched Enabled], js.next_run_date, js.next_run_time
FROM msdb.dbo.sysjobs AS sj WITH (NOLOCK)
INNER JOIN msdb.dbo.syscategories AS sc WITH (NOLOCK)
ON sj.category_id = sc.category_id
LEFT OUTER JOIN msdb.dbo.sysjobschedules AS js WITH (NOLOCK)
ON sj.job_id = js.job_id
LEFT OUTER JOIN msdb.dbo.sysschedules AS s WITH (NOLOCK)
ON js.schedule_id = s.schedule_id
ORDER BY sj.name OPTION (RECOMPILE);
------

-- Gives you some basic information about your SQL Server Agent jobs, who owns them and how they are configured
-- Look for Agent jobs that are not owned by sa
-- Look for jobs that have a notify_email_operator_id set to 0 (meaning no operator)
-- Look for jobs that have a notify_level_email set to 0 (meaning no e-mail is ever sent)
--
-- MSDN sysjobs documentation
-- http://msdn.microsoft.com/en-us/library/ms189817.aspx


-- Get SQL Server Agent Alert Information (Query 5) (SQL Server Agent Alerts)
SELECT name, event_source, message_id, severity, [enabled], has_notification, 
       delay_between_responses, occurrence_count, last_occurrence_date, last_occurrence_time
FROM msdb.dbo.sysalerts WITH (NOLOCK)
ORDER BY name OPTION (RECOMPILE);
------

-- Gives you some basic information about your SQL Server Agent Alerts (which are different from SQL Server Agent jobs)
-- Read more about Agent Alerts here: https://www.sqlskills.com/blogs/glenn/creating-sql-server-agent-alerts-for-critical-errors/


-- Returns a list of all global trace flags that are enabled (Query 6) (Global Trace Flags)
DBCC TRACESTATUS (-1);
------

-- If no global trace flags are enabled, no results will be returned.
-- It is very useful to know what global trace flags are currently enabled as part of the diagnostic process.

-- Common trace flags that should be enabled in most cases
-- TF 1117 - When growing a data file, grow all files at the same time so they remain the same size, reducing allocation contention points
--           http://support2.microsoft.com/kb/2154845
-- 
-- TF 1118 - Helps alleviate allocation contention in tempdb, SQL Server allocates full extents to each database object, 
--           thereby eliminating the contention on SGAM pages (more important with older versions of SQL Server)
--           Recommendations to reduce allocation contention in SQL Server tempdb database
--           http://support2.microsoft.com/kb/2154845

-- TF 2371 - Lowers auto update statistics threshold for large tables
--           http://blogs.msdn.com/b/saponsqlserver/archive/2011/09/07/changes-to-automatic-update-statistics-in-sql-server-traceflag-2371.aspx

-- TF 3226 - Supresses logging of successful database backup messages to the SQL Server Error Log
--           https://www.sqlskills.com/blogs/paul/fed-up-with-backup-success-messages-bloating-your-error-logs/


-- SQL Server NUMA Node information  (Query 7) (SQL Server NUMA Info)
SELECT node_id, node_state_desc, memory_node_id, online_scheduler_count, 
       active_worker_count, avg_load_balance, resource_monitor_state
FROM sys.dm_os_nodes WITH (NOLOCK) 
WHERE node_state_desc <> N'ONLINE DAC' OPTION (RECOMPILE);
------

-- Gives you some useful information about the composition 
-- and relative load on your NUMA nodes


-- Hardware information from SQL Server 2008  (Query 8) (Hardware Info)
-- (Cannot distinguish between HT and multi-core)
SELECT cpu_count AS [Logical CPU Count], hyperthread_ratio AS [Hyperthread Ratio],
cpu_count/hyperthread_ratio AS [Physical CPU Count], 
physical_memory_in_bytes/1048576 AS [Physical Memory (MB)], 
sqlserver_start_time,
DATEDIFF(hour, sqlserver_start_time, GETDATE()) AS [SQL Server Up Time (hrs)]
FROM sys.dm_os_sys_info WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Gives you some good basic hardware information about your database server


-- Get System Manufacturer and model number from  (Query 9) (System Manufacturer)
-- SQL Server Error log. This query might take a few seconds 
-- if you have not recycled your error log recently
EXEC sys.xp_readerrorlog 0, 1, N'Manufacturer';
------ 

-- This can help you determine the capabilities
-- and capacities of your database server


-- Get processor description from Windows Registry  (Query 10) (Processor Description)
EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'HARDWARE\DESCRIPTION\System\CentralProcessor\0', N'ProcessorNameString';
------

-- Gives you the model number and rated clock speed of your processor(s)
-- Your processors may be running at less that the rated clock speed due
-- to the Windows Power Plan or hardware power management

-- You can use CPU-Z to get your actual CPU core speed and a lot of other useful information
-- http://www.cpuid.com/softwares/cpu-z.html

-- You can learn more about processor selection for SQL Server by following this link
-- https://www.sqlskills.com/blogs/glenn/processor-selection-for-sql-server/



-- Get the current node name from your cluster nodes  (Query 11) (Cluster Node Properties)
-- (if your database server is in a failover cluster)
SELECT NodeName
FROM sys.dm_os_cluster_nodes WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Knowing which node owns the cluster resources is critical
-- Especially when you are installing Windows or SQL Server updates
-- You will see no results if your instance is not clustered


-- Get configuration values for instance  (Query 12) (Configuration Values)
SELECT name, value, value_in_use, minimum, maximum, [description], is_dynamic, is_advanced
FROM sys.configurations WITH (NOLOCK)
ORDER BY name OPTION (RECOMPILE);
------

-- Focus on these settings:
-- backup compression default (should be 1 in most cases)
-- clr enabled (only enable if it is needed)
-- cost threshold for parallelism (depends on your workload)
-- lightweight pooling (should be zero)
-- max degree of parallelism (depends on your workload)
-- max server memory (MB) (set to an appropriate value, not the default)
-- optimize for ad hoc workloads (should be 1)
-- priority boost (should be zero)
-- remote admin connections (should be 1)





-- File names and paths for all user and system databases on instance   (Query 13) (Database Filenames and Paths)
SELECT DB_NAME([database_id]) AS [Database Name], 
       [file_id], [name], physical_name, [type_desc], state_desc,
	   is_percent_growth, growth,
	   CONVERT(bigint, growth/128.0) AS [Growth in MB], 
       CONVERT(bigint, size/128.0) AS [Total Size in MB]
FROM sys.master_files WITH (NOLOCK)
ORDER BY DB_NAME([database_id]), [file_id] OPTION (RECOMPILE);
------

-- Things to look at:
-- Are data files and log files on different drives?
-- Is everything on the C: drive?
-- Is TempDB on dedicated drives?
-- Is there only one TempDB data file?
-- Are all of the TempDB data files the same size?
-- Are there multiple data files for user databases?
-- Is percent growth enabled for any files (which is bad)?


-- Look for I/O requests taking longer than 15 seconds in the five most recent SQL Server Error Logs (Query 14) (IO Warnings)
CREATE TABLE #IOWarningResults(LogDate datetime, ProcessInfo sysname, LogText nvarchar(1000));

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 0, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 1, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 2, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 3, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 4, 1, N'taking longer than 15 seconds';

SELECT LogDate, ProcessInfo, LogText
FROM #IOWarningResults
ORDER BY LogDate DESC;

DROP TABLE #IOWarningResults;
------  

-- Finding 15 second I/O warnings in the SQL Server Error Log is useful evidence of
-- poor I/O performance (which might have many different causes)
-- Look to see if you see any patterns in the results (same files, same drives, same time of day, etc.)

-- Diagnostics in SQL Server help detect stalled and stuck I/O operations
-- https://support.microsoft.com/en-us/kb/897284


-- Drive level latency information (Query 15) (Drive Level Latency)
-- Based on code from Jimmy May
SELECT tab.[Drive],  
	CASE 
		WHEN num_of_reads = 0 THEN 0 
		ELSE (io_stall_read_ms/num_of_reads) 
	END AS [Read Latency],
	CASE 
		WHEN num_of_writes = 0 THEN 0 
		ELSE (io_stall_write_ms/num_of_writes) 
	END AS [Write Latency],
	CASE 
		WHEN (num_of_reads = 0 AND num_of_writes = 0) THEN 0 
		ELSE (io_stall/(num_of_reads + num_of_writes)) 
	END AS [Overall Latency],
	CASE 
		WHEN num_of_reads = 0 THEN 0 
		ELSE (num_of_bytes_read/num_of_reads) 
	END AS [Avg Bytes/Read],
	CASE 
		WHEN num_of_writes = 0 THEN 0 
		ELSE (num_of_bytes_written/num_of_writes) 
	END AS [Avg Bytes/Write],
	CASE 
		WHEN (num_of_reads = 0 AND num_of_writes = 0) THEN 0 
		ELSE ((num_of_bytes_read + num_of_bytes_written)/(num_of_reads + num_of_writes)) 
	END AS [Avg Bytes/Transfer]
FROM (SELECT LEFT(UPPER(mf.physical_name), 2) AS Drive, SUM(num_of_reads) AS num_of_reads,
	         SUM(io_stall_read_ms) AS io_stall_read_ms, SUM(num_of_writes) AS num_of_writes,
	         SUM(io_stall_write_ms) AS io_stall_write_ms, SUM(num_of_bytes_read) AS num_of_bytes_read,
	         SUM(num_of_bytes_written) AS num_of_bytes_written, SUM(io_stall) AS io_stall
      FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS vfs
      INNER JOIN sys.master_files AS mf WITH (NOLOCK)
      ON vfs.database_id = mf.database_id AND vfs.file_id = mf.file_id
      GROUP BY LEFT(UPPER(mf.physical_name), 2)) AS tab
ORDER BY [Overall Latency] OPTION (RECOMPILE);
------

-- Shows you the drive-level latency for reads and writes, in milliseconds
-- Latency above 20-25ms is usually a problem


-- Calculates average stalls per read, per write, and per total input/output for each database file  (Query 16) (IO Stalls by File)
SELECT DB_NAME(fs.database_id) AS [Database Name], CAST(fs.io_stall_read_ms/(1.0 + fs.num_of_reads) AS NUMERIC(16,1)) AS [avg_read_stall_ms],
CAST(fs.io_stall_write_ms/(1.0 + fs.num_of_writes) AS NUMERIC(16,1)) AS [avg_write_stall_ms],
CAST((fs.io_stall_read_ms + fs.io_stall_write_ms)/(1.0 + fs.num_of_reads + fs.num_of_writes) AS NUMERIC(16,1)) AS [avg_io_stall_ms],
CONVERT(DECIMAL(18,2), mf.size/128.0) AS [File Size (MB)], mf.physical_name, mf.type_desc, fs.io_stall_read_ms, fs.num_of_reads, 
fs.io_stall_write_ms, fs.num_of_writes, fs.io_stall_read_ms + fs.io_stall_write_ms AS [io_stalls], fs.num_of_reads + fs.num_of_writes AS [total_io]
FROM sys.dm_io_virtual_file_stats(null,null) AS fs
INNER JOIN sys.master_files AS mf WITH (NOLOCK)
ON fs.database_id = mf.database_id
AND fs.[file_id] = mf.[file_id]
ORDER BY avg_io_stall_ms DESC OPTION (RECOMPILE);
------

-- Helps determine which database files on the entire instance have the most I/O bottlenecks
-- This can help you decide whether certain LUNs are overloaded and whether you might
-- want to move some files to a different location or perhaps improve your I/O performance


-- Recovery model, log reuse wait description, log file size, log usage size  (Query 17) (Database Properties)
-- and compatibility level for all databases on instance
SELECT db.[name] AS [Database Name], SUSER_SNAME(db.owner_sid) AS [Database Owner], db.recovery_model_desc AS [Recovery Model], 
db.log_reuse_wait_desc AS [Log Reuse Wait Description], 
ls.cntr_value AS [Log Size (KB)], lu.cntr_value AS [Log Used (KB)],
CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log Used %], 
db.[compatibility_level] AS [DB Compatibility Level], 
db.page_verify_option_desc AS [Page Verify Option], db.is_auto_create_stats_on, db.is_auto_update_stats_on,
db.is_auto_update_stats_async_on, db.is_parameterization_forced, 
db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on,
db.is_auto_close_on, db.is_auto_shrink_on, db.is_cdc_enabled, db.is_published
FROM sys.databases AS db WITH (NOLOCK)
INNER JOIN sys.dm_os_performance_counters AS lu WITH (NOLOCK)
ON db.name = lu.instance_name
INNER JOIN sys.dm_os_performance_counters AS ls WITH (NOLOCK) 
ON db.name = ls.instance_name
WHERE lu.counter_name LIKE N'Log File(s) Used Size (KB)%' 
AND ls.counter_name LIKE N'Log File(s) Size (KB)%'
AND ls.cntr_value > 0 OPTION (RECOMPILE);
------

-- Things to look at:
-- How many databases are on the instance?
-- What recovery models are they using?
-- What is the log reuse wait description?
-- How full are the transaction logs ?
-- What compatibility level are the databases on? 
-- What is the Page Verify Option? (should be CHECKSUM)
-- Is Auto Update Statistics Asynchronously enabled?
-- Make sure auto_shrink and auto_close are not enabled!



-- Missing Indexes for all databases by Index Advantage  (Query 18) (Missing Indexes All Databases)
SELECT CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage], 
migs.last_user_seek, mid.[statement] AS [Database.Schema.Table],
mid.equality_columns, mid.inequality_columns, mid.included_columns,
migs.unique_compiles, migs.user_seeks, migs.avg_total_user_cost, migs.avg_user_impact
FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)
INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)
ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)
ON mig.index_handle = mid.index_handle
ORDER BY index_advantage DESC OPTION (RECOMPILE);
------

-- Getting missing index information for all of the databases on the instance is very useful
-- Look at last user seek time, number of user seeks to help determine source and importance
-- Also look at avg_user_impact and avg_total_user_cost to help determine importance
-- SQL Server is overly eager to add included columns, so beware
-- Do not just blindly add indexes that show up from this query!!!



-- Get VLF Counts for all databases on the instance (Query 19) (VLF Counts)
-- (adapted from Michelle Ufford) 
CREATE TABLE #VLFInfo (FileID  int,
					   FileSize bigint, StartOffset bigint,
					   FSeqNo      bigint, [Status]    bigint,
					   Parity      bigint, CreateLSN   numeric(38));
	 
CREATE TABLE #VLFCountResults(DatabaseName sysname, VLFCount int);
	 
EXEC sp_MSforeachdb N'Use [?]; 

				INSERT INTO #VLFInfo 
				EXEC sp_executesql N''DBCC LOGINFO([?])''; 
	 
				INSERT INTO #VLFCountResults 
				SELECT DB_NAME(), COUNT(*) 
				FROM #VLFInfo; 

				TRUNCATE TABLE #VLFInfo;'
	 
SELECT DatabaseName, VLFCount  
FROM #VLFCountResults
ORDER BY VLFCount DESC;
	 
DROP TABLE #VLFInfo;
DROP TABLE #VLFCountResults;
------

-- High VLF counts can affect write performance 
-- and they can make full database restores and crash recovery take much longer
-- Try to keep your VLF counts under 200 in most cases



-- Get CPU utilization by database (Query 20) (CPU Usage by Database)
WITH DB_CPU_Stats
AS
(SELECT pa.DatabaseID, DB_Name(pa.DatabaseID) AS [Database Name], SUM(qs.total_worker_time/1000) AS [CPU_Time_Ms]
 FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
 CROSS APPLY (SELECT CONVERT(int, value) AS [DatabaseID] 
              FROM sys.dm_exec_plan_attributes(qs.plan_handle)
              WHERE attribute = N'dbid') AS pa
 GROUP BY DatabaseID)
SELECT ROW_NUMBER() OVER(ORDER BY [CPU_Time_Ms] DESC) AS [CPU Rank],
       [Database Name], [CPU_Time_Ms] AS [CPU Time (ms)], 
       CAST([CPU_Time_Ms] * 1.0 / SUM([CPU_Time_Ms]) OVER() * 100.0 AS DECIMAL(5, 2)) AS [CPU Percent]
FROM DB_CPU_Stats
WHERE DatabaseID <> 32767 -- ResourceDB
ORDER BY [CPU Rank] OPTION (RECOMPILE);
------

-- Helps determine which database is using the most CPU resources on the instance
-- Note: This only reflects CPU usage from the currently cached query plans


-- Get I/O utilization by database (Query 21) (IO Usage By Database)
WITH Aggregate_IO_Statistics
AS
(SELECT DB_NAME(database_id) AS [Database Name],
CAST(SUM(num_of_bytes_read + num_of_bytes_written)/1048576 AS DECIMAL(12, 2)) AS io_in_mb
FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS [DM_IO_STATS]
GROUP BY database_id)
SELECT ROW_NUMBER() OVER(ORDER BY io_in_mb DESC) AS [I/O Rank], [Database Name], io_in_mb AS [Total I/O (MB)],
       CAST(io_in_mb/ SUM(io_in_mb) OVER() * 100.0 AS DECIMAL(5,2)) AS [I/O Percent]
FROM Aggregate_IO_Statistics
ORDER BY [I/O Rank] OPTION (RECOMPILE);
------

-- Helps determine which database is using the most I/O resources on the instance


-- Get total buffer usage by database for current instance  (Query 22) (Total Buffer Usage by Database)
-- This make take some time to run on a busy instance
WITH AggregateBufferPoolUsage
AS
(SELECT DB_NAME(database_id) AS [Database Name],
CAST(COUNT(*) * 8/1024.0 AS DECIMAL (10,2))  AS [CachedSize]
FROM sys.dm_os_buffer_descriptors WITH (NOLOCK)
WHERE database_id <> 32767 -- ResourceDB
GROUP BY DB_NAME(database_id))
SELECT ROW_NUMBER() OVER(ORDER BY CachedSize DESC) AS [Buffer Pool Rank], [Database Name], CachedSize AS [Cached Size (MB)],
       CAST(CachedSize / SUM(CachedSize) OVER() * 100.0 AS DECIMAL(5,2)) AS [Buffer Pool Percent]
FROM AggregateBufferPoolUsage
ORDER BY [Buffer Pool Rank] OPTION (RECOMPILE);
------

-- Tells you how much memory (in the buffer pool) 
-- is being used by each database on the instance


-- Clear Wait Stats with this command
-- DBCC SQLPERF('sys.dm_os_wait_stats', CLEAR);

-- Isolate top waits for server instance since last restart or wait statistics clear (Query 23) (Top Waits)
WITH [Waits] 
AS (SELECT wait_type, wait_time_ms/ 1000.0 AS [WaitS],
          (wait_time_ms - signal_wait_time_ms) / 1000.0 AS [ResourceS],
           signal_wait_time_ms / 1000.0 AS [SignalS],
           waiting_tasks_count AS [WaitCount],
           100.0 *  wait_time_ms / SUM (wait_time_ms) OVER() AS [Percentage],
           ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS [RowNum]
    FROM sys.dm_os_wait_stats WITH (NOLOCK)
    WHERE [wait_type] NOT IN (
        N'BROKER_EVENTHANDLER', N'BROKER_RECEIVE_WAITFOR', N'BROKER_TASK_STOP',
		N'BROKER_TO_FLUSH', N'BROKER_TRANSMITTER', N'CHECKPOINT_QUEUE',
        N'CHKPT', N'CLR_AUTO_EVENT', N'CLR_MANUAL_EVENT', N'CLR_SEMAPHORE',
        N'DBMIRROR_DBM_EVENT', N'DBMIRROR_EVENTS_QUEUE', N'DBMIRROR_WORKER_QUEUE',
		N'DBMIRRORING_CMD', N'DIRTY_PAGE_POLL', N'DISPATCHER_QUEUE_SEMAPHORE',
        N'EXECSYNC', N'FSAGENT', N'FT_IFTS_SCHEDULER_IDLE_WAIT', N'FT_IFTSHC_MUTEX',
        N'HADR_CLUSAPI_CALL', N'HADR_FILESTREAM_IOMGR_IOCOMPLETION', N'HADR_LOGCAPTURE_WAIT', 
		N'HADR_NOTIFICATION_DEQUEUE', N'HADR_TIMER_TASK', N'HADR_WORK_QUEUE',
        N'KSOURCE_WAKEUP', N'LAZYWRITER_SLEEP', N'LOGMGR_QUEUE', N'ONDEMAND_TASK_QUEUE',
        N'PWAIT_ALL_COMPONENTS_INITIALIZED', N'QDS_PERSIST_TASK_MAIN_LOOP_SLEEP',
        N'QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP', N'REQUEST_FOR_DEADLOCK_SEARCH',
		N'RESOURCE_QUEUE', N'SERVER_IDLE_CHECK', N'SLEEP_BPOOL_FLUSH', N'SLEEP_DBSTARTUP',
		N'SLEEP_DCOMSTARTUP', N'SLEEP_MASTERDBREADY', N'SLEEP_MASTERMDREADY',
        N'SLEEP_MASTERUPGRADED', N'SLEEP_MSDBSTARTUP', N'SLEEP_SYSTEMTASK', N'SLEEP_TASK',
        N'SLEEP_TEMPDBSTARTUP', N'SNI_HTTP_ACCEPT', N'SP_SERVER_DIAGNOSTICS_SLEEP',
		N'SQLTRACE_BUFFER_FLUSH', N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', N'SQLTRACE_WAIT_ENTRIES',
		N'WAIT_FOR_RESULTS', N'WAITFOR', N'WAITFOR_TASKSHUTDOWN', N'WAIT_XTP_HOST_WAIT',
		N'WAIT_XTP_OFFLINE_CKPT_NEW_LOG', N'WAIT_XTP_CKPT_CLOSE', N'XE_DISPATCHER_JOIN',
        N'XE_DISPATCHER_WAIT', N'XE_TIMER_EVENT')
    AND waiting_tasks_count > 0)
SELECT
    MAX (W1.wait_type) AS [WaitType],
	CAST (MAX (W1.Percentage) AS DECIMAL (5,2)) AS [Wait Percentage],
	CAST ((MAX (W1.WaitS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgWait_Sec],
    CAST ((MAX (W1.ResourceS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgRes_Sec],
    CAST ((MAX (W1.SignalS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgSig_Sec], 
    CAST (MAX (W1.WaitS) AS DECIMAL (16,2)) AS [Wait_Sec],
    CAST (MAX (W1.ResourceS) AS DECIMAL (16,2)) AS [Resource_Sec],
    CAST (MAX (W1.SignalS) AS DECIMAL (16,2)) AS [Signal_Sec],
    MAX (W1.WaitCount) AS [Wait Count],
	CAST (N'https://www.sqlskills.com/help/waits/' + W1.wait_type AS XML) AS [Help/Info URL]
FROM Waits AS W1
INNER JOIN Waits AS W2
ON W2.RowNum <= W1.RowNum
GROUP BY W1.RowNum, W1.wait_type
HAVING SUM (W2.Percentage) - MAX (W1.Percentage) < 99 -- percentage threshold
OPTION (RECOMPILE);
------

-- Cumulative wait stats are not as useful on an idle instance that is not under load or performance pressure

-- SQL Server Wait Types Library (Paul Randal)
-- https://www.sqlskills.com/help/waits/

-- The SQL Server Wait Type Repository
-- http://blogs.msdn.com/b/psssql/archive/2009/11/03/the-sql-server-wait-type-repository.aspx

-- Wait statistics, or please tell me where it hurts
-- https://www.sqlskills.com/blogs/paul/wait-statistics-or-please-tell-me-where-it-hurts/

-- SQL Server 2005 Performance Tuning using the Waits and Queues
-- http://technet.microsoft.com/en-us/library/cc966413.aspx

-- sys.dm_os_wait_stats (Transact-SQL)
-- http://msdn.microsoft.com/en-us/library/ms179984(v=sql.105).aspx




-- Signal Waits for instance  (Query 24) (Signal Waits)
SELECT CAST(100.0 * SUM(signal_wait_time_ms) / SUM (wait_time_ms) AS NUMERIC(20,2)) AS [% Signal (CPU) Waits],
CAST(100.0 * SUM(wait_time_ms - signal_wait_time_ms) / SUM (wait_time_ms) AS NUMERIC(20,2)) AS [% Resource Waits]
FROM sys.dm_os_wait_stats WITH (NOLOCK)
WHERE wait_type NOT IN (
        N'BROKER_EVENTHANDLER', N'BROKER_RECEIVE_WAITFOR', N'BROKER_TASK_STOP',
		N'BROKER_TO_FLUSH', N'BROKER_TRANSMITTER', N'CHECKPOINT_QUEUE',
        N'CHKPT', N'CLR_AUTO_EVENT', N'CLR_MANUAL_EVENT', N'CLR_SEMAPHORE',
        N'DBMIRROR_DBM_EVENT', N'DBMIRROR_EVENTS_QUEUE', N'DBMIRROR_WORKER_QUEUE',
		N'DBMIRRORING_CMD', N'DIRTY_PAGE_POLL', N'DISPATCHER_QUEUE_SEMAPHORE',
        N'EXECSYNC', N'FSAGENT', N'FT_IFTS_SCHEDULER_IDLE_WAIT', N'FT_IFTSHC_MUTEX',
        N'HADR_CLUSAPI_CALL', N'HADR_FILESTREAM_IOMGR_IOCOMPLETION', N'HADR_LOGCAPTURE_WAIT', 
		N'HADR_NOTIFICATION_DEQUEUE', N'HADR_TIMER_TASK', N'HADR_WORK_QUEUE',
        N'KSOURCE_WAKEUP', N'LAZYWRITER_SLEEP', N'LOGMGR_QUEUE', N'ONDEMAND_TASK_QUEUE',
        N'PWAIT_ALL_COMPONENTS_INITIALIZED', N'QDS_PERSIST_TASK_MAIN_LOOP_SLEEP',
        N'QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP', N'REQUEST_FOR_DEADLOCK_SEARCH',
		N'RESOURCE_QUEUE', N'SERVER_IDLE_CHECK', N'SLEEP_BPOOL_FLUSH', N'SLEEP_DBSTARTUP',
		N'SLEEP_DCOMSTARTUP', N'SLEEP_MASTERDBREADY', N'SLEEP_MASTERMDREADY',
        N'SLEEP_MASTERUPGRADED', N'SLEEP_MSDBSTARTUP', N'SLEEP_SYSTEMTASK', N'SLEEP_TASK',
        N'SLEEP_TEMPDBSTARTUP', N'SNI_HTTP_ACCEPT', N'SP_SERVER_DIAGNOSTICS_SLEEP',
		N'SQLTRACE_BUFFER_FLUSH', N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', N'SQLTRACE_WAIT_ENTRIES',
		N'WAIT_FOR_RESULTS', N'WAITFOR', N'WAITFOR_TASKSHUTDOWN', N'WAIT_XTP_HOST_WAIT',
		N'WAIT_XTP_OFFLINE_CKPT_NEW_LOG', N'WAIT_XTP_CKPT_CLOSE', N'XE_DISPATCHER_JOIN',
        N'XE_DISPATCHER_WAIT', N'XE_TIMER_EVENT') OPTION (RECOMPILE);
------

-- Signal Waits above 10-15% is usually a confirming sign of CPU pressure
-- Cumulative wait stats are not as useful on an idle instance that is not under load or performance pressure
-- Resource waits are non-CPU related waits


--  Get logins that are connected and how many sessions they have (Query 25) (Connection Counts)
SELECT login_name, [program_name], COUNT(session_id) AS [session_count] 
FROM sys.dm_exec_sessions WITH (NOLOCK)
GROUP BY login_name, [program_name]
ORDER BY COUNT(session_id) DESC OPTION (RECOMPILE);
------

-- This can help characterize your workload and
-- determine whether you are seeing a normal level of activity


-- Get a count of SQL connections by IP address (Query 26) (Connection Counts by IP Address)
SELECT ec.client_net_address, es.[program_name], es.[host_name], es.login_name, 
COUNT(ec.session_id) AS [connection count] 
FROM sys.dm_exec_sessions AS es WITH (NOLOCK) 
INNER JOIN sys.dm_exec_connections AS ec WITH (NOLOCK) 
ON es.session_id = ec.session_id 
GROUP BY ec.client_net_address, es.[program_name], es.[host_name], es.login_name  
ORDER BY ec.client_net_address, es.[program_name] OPTION (RECOMPILE);
------

-- This helps you figure where your database load is coming from
-- and verifies connectivity from other machines


-- Get Average Task Counts (run multiple times) (Query 27) (Avg Task Counts)
SELECT AVG(current_tasks_count) AS [Avg Task Count], 
AVG(runnable_tasks_count) AS [Avg Runnable Task Count],
AVG(pending_disk_io_count) AS [Avg Pending DiskIO Count]
FROM sys.dm_os_schedulers WITH (NOLOCK)
WHERE scheduler_id < 255 OPTION (RECOMPILE);
------

-- Sustained values above 10 suggest further investigation in that area
-- High Avg Task Counts are often caused by blocking/deadlocking or other resource contention

-- Sustained values above 1 suggest further investigation in that area
-- High Avg Runnable Task Counts are a good sign of CPU pressure
-- High Avg Pending DiskIO Counts are a sign of disk pressure

-- How to Do Some Very Basic SQL Server Monitoring
-- https://www.sqlskills.com/blogs/glenn/how-to-do-some-very-basic-sql-server-monitoring/



-- Get CPU Utilization History for last 256 minutes (in one minute intervals)  (Query 28) (CPU Utilization History)
-- This version works with SQL Server 2008
DECLARE @ts_now bigint = (SELECT cpu_ticks/(cpu_ticks/ms_ticks) FROM sys.dm_os_sys_info WITH (NOLOCK)); 

SELECT TOP(256) SQLProcessUtilization AS [SQL Server Process CPU Utilization], 
               SystemIdle AS [System Idle Process], 
               100 - SystemIdle - SQLProcessUtilization AS [Other Process CPU Utilization], 
               DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) AS [Event Time] 
FROM ( 
	  SELECT record.value('(./Record/@id)[1]', 'int') AS record_id, 
			record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') 
			AS [SystemIdle], 
			record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 
			'int') 
			AS [SQLProcessUtilization], [timestamp] 
	  FROM ( 
			SELECT [timestamp], CONVERT(xml, record) AS [record] 
			FROM sys.dm_os_ring_buffers WITH (NOLOCK)
			WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR' 
			AND record LIKE N'%<SystemHealth>%') AS x 
	  ) AS y 
ORDER BY record_id DESC OPTION (RECOMPILE);
------

-- Look at the trend over the entire period. 
-- Also look at high sustained Other Process CPU Utilization values


-- Get top total worker time queries for entire instance (Query 29) (Top Worker Time Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], t.[text] AS [Query Text],  
qs.total_worker_time AS [Total Worker Time], qs.min_worker_time AS [Min Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.max_worker_time AS [Max Worker Time], qs.execution_count AS [Execution Count], 
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time], 
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads], 
qs.total_physical_reads/qs.execution_count AS [Avg Physical Reads], qs.creation_time AS [Creation Time]
, qp.query_plan AS [Query Plan] -- comment out this column if copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
ORDER BY qs.total_worker_time DESC OPTION (RECOMPILE);
------


-- Helps you find the most expensive queries from a CPU perspective across the entire instance



-- Good basic information about OS memory amounts and state  (Query 30) (System Memory)
SELECT total_physical_memory_kb/1024 AS [Physical Memory (MB)], 
       available_physical_memory_kb/1024 AS [Available Memory (MB)], 
       total_page_file_kb/1024 AS [Total Page File (MB)], 
	   available_page_file_kb/1024 AS [Available Page File (MB)], 
	   system_cache_kb/1024 AS [System Cache (MB)],
       system_memory_state_desc AS [System Memory State]
FROM sys.dm_os_sys_memory WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You want to see "Available physical memory is high"
-- This indicates that you are not under external memory pressure


-- SQL Server Process Address space info  (Query 31) (Process Memory) 
-- (shows whether locked pages is enabled, among other things)
SELECT physical_memory_in_use_kb/1024 AS [SQL Server Memory Usage (MB)],
       large_page_allocations_kb, locked_page_allocations_kb, page_fault_count, 
	   memory_utilization_percentage, available_commit_limit_kb, 
	   process_physical_memory_low, process_virtual_memory_low
FROM sys.dm_os_process_memory WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You want to see 0 for process_physical_memory_low
-- You want to see 0 for process_virtual_memory_low
-- This indicates that you are not under internal memory pressure


-- Page Life Expectancy (PLE) value for each NUMA node in current instance  (Query 32) (PLE by NUMA Node)
SELECT @@SERVERNAME AS [Server Name], RTRIM([object_name]) AS [Object Name], instance_name, cntr_value AS [Page Life Expectancy]
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Buffer Node%' -- Handles named instances
AND counter_name = N'Page life expectancy' OPTION (RECOMPILE);
------

-- PLE is a good measurement of memory pressure.
-- Higher PLE is better. Watch the trend over time, not the absolute value.
-- This will only return one row for non-NUMA systems.

-- Page Life Expectancy isn�t what you think�
-- http://www.sqlskills.com/blogs/paul/page-life-expectancy-isnt-what-you-think/



-- Memory Grants Pending value for current instance  (Query 33) (Memory Grants Pending)
SELECT @@SERVERNAME AS [Server Name], RTRIM([object_name]) AS [Object Name], cntr_value AS [Memory Grants Pending]                                                                                                       
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Memory Manager%' -- Handles named instances
AND counter_name = N'Memory Grants Pending' OPTION (RECOMPILE);
------

-- Memory Grants Pending above zero for a sustained period is a very strong indicator of memory pressure


-- Memory Clerk Usage for instance  (Query 34) (Memory Clerk Usage)
-- Look for high value for CACHESTORE_SQLCP (Ad-hoc query plans)
SELECT TOP(10) [type] AS [Memory Clerk Type], SUM(single_pages_kb)/1024 AS [SPA Memory Usage (MB)] 
FROM sys.dm_os_memory_clerks WITH (NOLOCK)
GROUP BY [type]  
ORDER BY SUM(single_pages_kb) DESC OPTION (RECOMPILE);
------

-- CACHESTORE_SQLCP  SQL Plans         
-- These are cached SQL statements or batches that aren't in stored procedures, functions and triggers
-- Watch out for high values for CACHESTORE_SQLCP

-- CACHESTORE_OBJCP  Object Plans      
-- These are compiled plans for stored procedures, functions and triggers



-- Find single-use, ad-hoc and prepared queries that are bloating the plan cache  (Query 35) (Ad hoc Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], t.[text] AS [Query Text], 
cp.objtype AS [Object Type], cp.cacheobjtype AS [Cache Object Type],  
cp.size_in_bytes/1024 AS [Plan Size in KB]
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t
WHERE cp.cacheobjtype = N'Compiled Plan' 
AND cp.objtype IN (N'Adhoc', N'Prepared') 
AND cp.usecounts = 1
ORDER BY cp.size_in_bytes DESC, DB_NAME(t.[dbid]) OPTION (RECOMPILE);
------

-- Gives you the text, type and size of single-use ad-hoc and prepared queries that waste space in the plan cache
-- Enabling 'optimize for ad hoc workloads' for the instance can help (SQL Server 2008 and above only)
-- Running DBCC FREESYSTEMCACHE ('SQL Plans') periodically may be required to better control this.
-- Enabling forced parameterization for the database can help, but test first!

-- Plan cache, adhoc workloads and clearing the single-use plan cache bloat
-- https://www.sqlskills.com/blogs/kimberly/plan-cache-adhoc-workloads-and-clearing-the-single-use-plan-cache-bloat/



-- Database specific queries *****************************************************************

-- **** Please switch to a user database that you are interested in! *****
USE YourDatabaseName; -- make sure to change to an actual database on your instance, not the master system database
GO

-- Individual File Sizes and space available for current database  (Query 36) (File Sizes and Space)
SELECT f.name AS [File Name] , f.physical_name AS [Physical Name], 
CAST((f.size/128.0) AS DECIMAL(15,2)) AS [Total Size in MB],
CAST(f.size/128.0 - CAST(FILEPROPERTY(f.name, 'SpaceUsed') AS int)/128.0 AS DECIMAL(15,2)) 
AS [Available Space In MB], [file_id], fg.name AS [Filegroup Name]
FROM sys.database_files AS f WITH (NOLOCK) 
LEFT OUTER JOIN sys.data_spaces AS fg WITH (NOLOCK) 
ON f.data_space_id = fg.data_space_id OPTION (RECOMPILE);
------

-- Look at how large and how full the files are and where they are located
-- Make sure the transaction log is not full!!



-- I/O Statistics by file for the current database  (Query 37) (IO Stats By File)
SELECT DB_NAME(DB_ID()) AS [Database Name], df.name AS [Logical Name], vfs.[file_id], 
df.physical_name AS [Physical Name], vfs.num_of_reads, vfs.num_of_writes, vfs.io_stall_read_ms, vfs.io_stall_write_ms,
CAST(100. * vfs.io_stall_read_ms/(vfs.io_stall_read_ms + vfs.io_stall_write_ms) AS DECIMAL(10,1)) AS [IO Stall Reads Pct],
CAST(100. * vfs.io_stall_write_ms/(vfs.io_stall_write_ms + vfs.io_stall_read_ms) AS DECIMAL(10,1)) AS [IO Stall Writes Pct],
(vfs.num_of_reads + vfs.num_of_writes) AS [Writes + Reads], 
CAST(vfs.num_of_bytes_read/1048576.0 AS DECIMAL(10, 2)) AS [MB Read], 
CAST(vfs.num_of_bytes_written/1048576.0 AS DECIMAL(10, 2)) AS [MB Written],
CAST(100. * vfs.num_of_reads/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(10,1)) AS [# Reads Pct],
CAST(100. * vfs.num_of_writes/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(10,1)) AS [# Write Pct],
CAST(100. * vfs.num_of_bytes_read/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(10,1)) AS [Read Bytes Pct],
CAST(100. * vfs.num_of_bytes_written/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(10,1)) AS [Written Bytes Pct]
FROM sys.dm_io_virtual_file_stats(DB_ID(), NULL) AS vfs
INNER JOIN sys.database_files AS df WITH (NOLOCK)
ON vfs.[file_id]= df.[file_id] OPTION (RECOMPILE);
------

-- This helps you characterize your workload better from an I/O perspective for this database
-- It helps you determine whether you has an OLTP or DW/DSS type of workload



-- Top cached queries by Execution Count (SQL Server 2008)  (Query 38) (Query Execution Counts)
SELECT TOP (100) qs.execution_count, qs.total_worker_time, qs.total_logical_reads, qs.total_elapsed_time,
SUBSTRING(qt.TEXT,qs.statement_start_offset/2 +1,
(CASE WHEN qs.statement_end_offset = -1
			THEN LEN(CONVERT(NVARCHAR(MAX), qt.TEXT)) * 2
	  ELSE qs.statement_end_offset END - qs.statement_start_offset)/2) AS query_text 
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
ORDER BY qs.execution_count DESC OPTION (RECOMPILE);
------


-- Look at non-stored procedure queries


-- Top Cached SPs By Execution Count (SQL 2008) (Query 39) (SP Execution Counts)
SELECT TOP(100) p.name AS [SP Name], qs.execution_count,
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], qs.total_worker_time AS [TotalWorkerTime],  
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
qs.cached_time
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
WHERE qs.database_id = DB_ID()
ORDER BY qs.execution_count DESC OPTION (RECOMPILE);
------

-- Tells you which cached stored procedures are called the most often
-- This helps you characterize and baseline your workload


-- Top Cached SPs By Avg Elapsed Time (SQL 2008)  (Query 40) (SP Avg Elapsed Time)
SELECT TOP(25) p.name AS [SP Name], qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time], 
qs.total_elapsed_time, qs.execution_count, ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, 
GETDATE()), 0) AS [Calls/Minute], qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], 
qs.total_worker_time AS [TotalWorkerTime], qs.cached_time
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
WHERE qs.database_id = DB_ID()
ORDER BY avg_elapsed_time DESC OPTION (RECOMPILE);
------

-- This helps you find long-running cached stored procedures that
-- may be easy to optimize with standard query tuning techniques


-- Top Cached SPs By Avg Elapsed Time with execution time variability   (Query 41) (SP Avg Elapsed Variable Time)
SELECT TOP(25) p.name AS [SP Name], qs.execution_count, qs.min_elapsed_time,
qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
qs.max_elapsed_time, qs.last_elapsed_time,  qs.cached_time
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
WHERE qs.database_id = DB_ID()
ORDER BY avg_elapsed_time DESC OPTION (RECOMPILE);
------

-- This gives you some interesting information about the variability in the
-- execution time of your cached stored procedures, which is useful for tuning


-- Top Cached SPs By Total Worker time (SQL 2008). Worker time relates to CPU cost  (Query 42) (SP Worker Time)
SELECT TOP(25) p.name AS [SP Name], qs.total_worker_time AS [TotalWorkerTime], 
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count 
AS [avg_elapsed_time], qs.cached_time
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
WHERE qs.database_id = DB_ID()
ORDER BY qs.total_worker_time DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a CPU perspective
-- You should look at this if you see signs of CPU pressure


-- Top Cached SPs By Total Logical Reads (SQL 2008). Logical reads relate to memory pressure  (Query 43) (SP Logical Reads)
SELECT TOP(25) p.name AS [SP Name], qs.total_logical_reads AS [TotalLogicalReads], 
qs.total_logical_reads/qs.execution_count AS [AvgLogicalReads],qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute], 
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count 
AS [avg_elapsed_time], qs.cached_time
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
WHERE qs.database_id = DB_ID()
ORDER BY qs.total_logical_reads DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a memory perspective
-- You should look at this if you see signs of memory pressure


-- Top Cached SPs By Total Physical Reads (SQL 2008). Physical reads relate to disk I/O pressure  (Query 44) (SP Physical Reads)
SELECT TOP(25) p.name AS [SP Name],qs.total_physical_reads AS [TotalPhysicalReads], 
qs.total_physical_reads/qs.execution_count AS [AvgPhysicalReads], qs.execution_count, 
qs.total_logical_reads,qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count 
AS [avg_elapsed_time], qs.cached_time 
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
WHERE qs.database_id = DB_ID()
AND qs.total_physical_reads > 0
ORDER BY qs.total_physical_reads DESC, qs.total_logical_reads DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a read I/O perspective
-- You should look at this if you see signs of I/O pressure or of memory pressure
       
-- Top Cached SPs By Total Logical Writes (SQL 2008)  (Query 45) (SP Logical Writes) 
-- Logical writes relate to both memory and disk I/O pressure 
SELECT TOP(25) p.name AS [SP Name], qs.total_logical_writes AS [TotalLogicalWrites], 
qs.total_logical_writes/qs.execution_count AS [AvgLogicalWrites], qs.execution_count,
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time], 
qs.cached_time
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
WHERE qs.database_id = DB_ID()
AND qs.total_logical_writes > 0
ORDER BY qs.total_logical_writes DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a write I/O perspective
-- You should look at this if you see signs of I/O pressure or of memory pressure


-- Lists the top statements by average input/output usage for the current database  (Query 46) (Top IO Statements)
SELECT TOP(50) OBJECT_NAME(qt.objectid, dbid) AS [SP Name],
(qs.total_logical_reads + qs.total_logical_writes) /qs.execution_count AS [Avg IO], qs.execution_count AS [Execution Count],
SUBSTRING(qt.[text],qs.statement_start_offset/2, 
	(CASE 
		WHEN qs.statement_end_offset = -1 
	 THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2 
		ELSE qs.statement_end_offset 
	 END - qs.statement_start_offset)/2) AS [Query Text]	
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
WHERE qt.[dbid] = DB_ID()
ORDER BY [Avg IO] DESC OPTION (RECOMPILE);
------

-- Helps you find the most expensive statements for I/O by SP



-- Possible Bad NC Indexes (writes > reads)  (Query 47) (Bad NC Indexes)
SELECT OBJECT_NAME(s.[object_id]) AS [Table Name], i.name AS [Index Name], i.index_id, 
i.is_disabled, i.is_hypothetical, i.has_filter, i.fill_factor,
user_updates AS [Total Writes], user_seeks + user_scans + user_lookups AS [Total Reads],
user_updates - (user_seeks + user_scans + user_lookups) AS [Difference]
FROM sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON s.[object_id] = i.[object_id]
AND i.index_id = s.index_id
WHERE OBJECTPROPERTY(s.[object_id],'IsUserTable') = 1
AND s.database_id = DB_ID()
AND s.user_updates > (s.user_seeks + s.user_scans + s.user_lookups)
AND i.index_id > 1 AND i.[type_desc] = N'NONCLUSTERED'
AND i.is_primary_key = 0 AND i.is_unique_constraint = 0
ORDER BY [Difference] DESC, [Total Writes] DESC, [Total Reads] ASC OPTION (RECOMPILE);
------

-- Look for indexes with high numbers of writes and zero or very low numbers of reads
-- Consider your complete workload, and how long your instance has been running
-- Investigate further before dropping an index!


-- Missing Indexes for current database by Index Advantage  (Query 48) (Missing Indexes)
SELECT DISTINCT CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage], 
migs.last_user_seek, mid.[statement] AS [Database.Schema.Table],
mid.equality_columns, mid.inequality_columns, mid.included_columns,
migs.unique_compiles, migs.user_seeks, migs.avg_total_user_cost, migs.avg_user_impact,
OBJECT_NAME(mid.[object_id]) AS [Table Name], p.rows AS [Table Rows]
FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)
INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)
ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)
ON mig.index_handle = mid.index_handle
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON p.[object_id] = mid.[object_id]
WHERE mid.database_id = DB_ID()
AND p.index_id < 2 
ORDER BY index_advantage DESC OPTION (RECOMPILE);
------

-- Look at index advantage, last user seek time, number of user seeks to help determine source and importance
-- SQL Server is overly eager to add included columns, so beware
-- Do not just blindly add indexes that show up from this query!!!


-- Find missing index warnings for cached plans in the current database  (Query 49) (Missing Index Warnings)
-- Note: This query could take some time on a busy instance
SELECT TOP(25) OBJECT_NAME(objectid) AS [ObjectName], 
               query_plan, cp.objtype, cp.usecounts
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) AS qp
WHERE CAST(query_plan AS NVARCHAR(MAX)) LIKE N'%MissingIndex%'
AND dbid = DB_ID()
ORDER BY cp.usecounts DESC OPTION (RECOMPILE);
------

-- Helps you connect missing indexes to specific stored procedures
-- This can help you decide whether to add them or not


-- Breaks down buffers used by current database by object (table, index) in the buffer cache  (Query 50) (Buffer Usage)
-- Note: This query could take some time on a busy instance
SELECT OBJECT_NAME(p.[object_id]) AS [Object Name], p.index_id, 
CAST(COUNT(*)/128.0 AS DECIMAL(10, 2)) AS [Buffer size(MB)],  
COUNT(*) AS [BufferCount], p.Rows AS [Row Count],
p.data_compression_desc AS [Compression Type]
FROM sys.allocation_units AS a WITH (NOLOCK)
INNER JOIN sys.dm_os_buffer_descriptors AS b WITH (NOLOCK)
ON a.allocation_unit_id = b.allocation_unit_id
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON a.container_id = p.hobt_id
WHERE b.database_id = CONVERT(int,DB_ID())
AND p.[object_id] > 100
GROUP BY p.[object_id], p.index_id, p.data_compression_desc, p.[Rows]
ORDER BY [BufferCount] DESC OPTION (RECOMPILE);
------

-- Tells you what tables and indexes are using the most memory in the buffer cache
-- It can help identify possible candidates for data compression


-- Get Table names, row counts, and compression status for clustered index or heap  (Query 51) (Table Sizes)
SELECT SCHEMA_NAME(o.Schema_ID) AS [Schema Name], OBJECT_NAME(p.object_id) AS [ObjectName], 
SUM(p.Rows) AS [RowCount], data_compression_desc AS [CompressionType]
FROM sys.partitions AS p WITH (NOLOCK)
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON p.object_id = o.object_id
WHERE index_id < 2 --ignore the partitions from the non-clustered index if any
AND OBJECT_NAME(p.object_id) NOT LIKE N'sys%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'spt_%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'queue_%' 
AND OBJECT_NAME(p.object_id) NOT LIKE N'filestream_tombstone%' 
AND OBJECT_NAME(p.object_id) NOT LIKE N'fulltext%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'ifts_comp_fragment%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'filetable_updates%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'xml_index_nodes%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'sqlagent_job%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'plan_persist%'
GROUP BY  SCHEMA_NAME(o.Schema_ID), p.object_id, data_compression_desc
ORDER BY SUM(p.Rows) DESC OPTION (RECOMPILE);
------

-- Gives you an idea of table sizes, and possible data compression opportunities


-- Get some key table properties (Query 52) (Table Properties)
SELECT [name], create_date, lock_on_bulk_load, is_replicated, has_replication_filter, 
       is_tracked_by_cdc, lock_escalation_desc
FROM sys.tables WITH (NOLOCK) 
ORDER BY [name] OPTION (RECOMPILE);
------

-- Gives you some good information about your tables


-- Detect blocking (run multiple times)  (Query 53) (Detect Blocking)
SELECT t1.resource_type AS [lock type], DB_NAME(resource_database_id) AS [database],
t1.resource_associated_entity_id AS [blk object],t1.request_mode AS [lock req],  --- lock requested
t1.request_session_id AS [waiter sid], t2.wait_duration_ms AS [wait time],       -- spid of waiter  
(SELECT [text] FROM sys.dm_exec_requests AS r WITH (NOLOCK)                      -- get sql for waiter
CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) 
WHERE r.session_id = t1.request_session_id) AS [waiter_batch],
(SELECT SUBSTRING(qt.[text],r.statement_start_offset/2, 
    (CASE WHEN r.statement_end_offset = -1 
    THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2 
    ELSE r.statement_end_offset END - r.statement_start_offset)/2) 
FROM sys.dm_exec_requests AS r WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) AS qt
WHERE r.session_id = t1.request_session_id) AS [waiter_stmt],					-- statement blocked
t2.blocking_session_id AS [blocker sid],										-- spid of blocker
(SELECT [text] FROM sys.sysprocesses AS p										-- get sql for blocker
CROSS APPLY sys.dm_exec_sql_text(p.[sql_handle]) 
WHERE p.spid = t2.blocking_session_id) AS [blocker_stmt]
FROM sys.dm_tran_locks AS t1 WITH (NOLOCK)
INNER JOIN sys.dm_os_waiting_tasks AS t2 WITH (NOLOCK)
ON t1.lock_owner_address = t2.resource_address OPTION (RECOMPILE);
------

-- Helps troubleshoot blocking and deadlocking issues
-- The results will change from second to second on a busy system
-- You should run this query multiple times when you see signs of blocking



-- When were Statistics last updated on all indexes?  (Query 54) (Statistics Update)
SELECT SCHEMA_NAME(o.Schema_ID) + N'.' + o.NAME AS [Object Name], o.type_desc AS [Object Type],
      i.name AS [Index Name], STATS_DATE(i.[object_id], i.index_id) AS [Statistics Date], 
      s.auto_created, s.no_recompute, s.user_created, st.row_count, st.used_page_count
FROM sys.objects AS o WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON o.[object_id] = i.[object_id]
INNER JOIN sys.stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id] 
AND i.index_id = s.stats_id
INNER JOIN sys.dm_db_partition_stats AS st WITH (NOLOCK)
ON o.[object_id] = st.[object_id]
AND i.[index_id] = st.[index_id]
WHERE o.[type] IN ('U', 'V')
AND st.row_count > 0
ORDER BY STATS_DATE(i.[object_id], i.index_id) DESC OPTION (RECOMPILE); 
------ 

-- Helps discover possible problems with out-of-date statistics
-- Also gives you an idea which indexes are the most active


-- Get fragmentation info for all indexes above a certain size in the current database  (Query 55) (Index Fragmentation)
-- Note: This query could take some time on a very large database
SELECT DB_NAME(ps.database_id) AS [Database Name], OBJECT_NAME(ps.OBJECT_ID) AS [Object Name], 
i.name AS [Index Name], ps.index_id, ps.index_type_desc, ps.avg_fragmentation_in_percent, 
ps.fragment_count, ps.page_count, i.fill_factor, i.has_filter, i.filter_definition
FROM sys.dm_db_index_physical_stats(DB_ID(),NULL, NULL, NULL , N'LIMITED') AS ps
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ps.[object_id] = i.[object_id] 
AND ps.index_id = i.index_id
WHERE ps.database_id = DB_ID()
AND ps.page_count > 2500
ORDER BY ps.avg_fragmentation_in_percent DESC OPTION (RECOMPILE);
------

-- Helps determine whether you have framentation in your relational indexes
-- and how effective your index maintenance strategy is


--- Index Read/Write stats (all tables in current DB) ordered by Reads  (Query 56) (Overall Index Usage - Reads)
SELECT OBJECT_NAME(s.[object_id]) AS [ObjectName], i.name AS [IndexName], i.index_id,
	   user_seeks + user_scans + user_lookups AS [Reads], s.user_updates AS [Writes],  
	   i.type_desc AS [IndexType], i.fill_factor AS [FillFactor], i.has_filter, i.filter_definition, 
	   s.last_user_scan, s.last_user_lookup, s.last_user_seek
FROM sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON s.[object_id] = i.[object_id]
WHERE OBJECTPROPERTY(s.[object_id],'IsUserTable') = 1
AND i.index_id = s.index_id
AND s.database_id = DB_ID()
ORDER BY user_seeks + user_scans + user_lookups DESC OPTION (RECOMPILE); -- Order by reads
------


-- Show which indexes in the current database are most active for Reads


--- Index Read/Write stats (all tables in current DB) ordered by Writes  (Query 57) (Overall Index Usage - Writes)
SELECT OBJECT_NAME(s.[object_id]) AS [ObjectName], i.name AS [IndexName], i.index_id,
	   s.user_updates AS [Writes], user_seeks + user_scans + user_lookups AS [Reads], 
	   i.type_desc AS [IndexType], i.fill_factor AS [FillFactor], i.has_filter, i.filter_definition,
	   s.last_system_update, s.last_user_update
FROM sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON s.[object_id] = i.[object_id]
WHERE OBJECTPROPERTY(s.[object_id],'IsUserTable') = 1
AND i.index_id = s.index_id
AND s.database_id = DB_ID()
ORDER BY s.user_updates DESC OPTION (RECOMPILE);						 -- Order by writes
------

-- Show which indexes in the current database are most active for Writes


-- Get lock waits for current database (Query 58) (Lock Waits)
SELECT o.name AS [table_name], i.name AS [index_name], ios.index_id, ios.partition_number,
		SUM(ios.row_lock_wait_count) AS [total_row_lock_waits], 
		SUM(ios.row_lock_wait_in_ms) AS [total_row_lock_wait_in_ms],
		SUM(ios.page_lock_wait_count) AS [total_page_lock_waits],
		SUM(ios.page_lock_wait_in_ms) AS [total_page_lock_wait_in_ms],
		SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) AS [total_lock_wait_in_ms]
FROM sys.dm_db_index_operational_stats(DB_ID(), NULL, NULL, NULL) AS ios
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON ios.[object_id] = o.[object_id]
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ios.[object_id] = i.[object_id] 
AND ios.index_id = i.index_id
WHERE o.[object_id] > 100
GROUP BY o.name, i.name, ios.index_id, ios.partition_number
HAVING SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) > 0
ORDER BY total_lock_wait_in_ms DESC OPTION (RECOMPILE);
------

-- This query is helpful for troubleshooting blocking and deadlocking issues


-- Look at recent Full backups for the current database (Query 59) (Recent Full Backups)
SELECT TOP (30) bs.machine_name, bs.server_name, bs.database_name AS [Database Name], bs.recovery_model,
CONVERT (BIGINT, bs.backup_size / 1048576 ) AS [Uncompressed Backup Size (MB)],
CONVERT (BIGINT, bs.compressed_backup_size / 1048576 ) AS [Compressed Backup Size (MB)],
CONVERT (NUMERIC (20,2), (CONVERT (FLOAT, bs.backup_size) /
CONVERT (FLOAT, bs.compressed_backup_size))) AS [Compression Ratio], bs.has_backup_checksums, bs.is_copy_only,
DATEDIFF (SECOND, bs.backup_start_date, bs.backup_finish_date) AS [Backup Elapsed Time (sec)],
bs.backup_finish_date AS [Backup Finish Date], bmf.physical_device_name AS [Backup Location], bmf.physical_block_size
FROM msdb.dbo.backupset AS bs WITH (NOLOCK)
INNER JOIN msdb.dbo.backupmediafamily AS bmf WITH (NOLOCK)
ON bs.media_set_id = bmf.media_set_id  
WHERE DATEDIFF (SECOND, bs.backup_start_date, bs.backup_finish_date) > 0 
AND bs.backup_size > 0
AND bs.type = 'D' -- Change to L if you want Log backups
AND database_name = DB_NAME(DB_ID())
ORDER BY bs.backup_finish_date DESC OPTION (RECOMPILE);
------

-- Are your backup sizes and times changing over time?
-- Are you using backup compression?
-- Are you using backup checksums?
-- Are you doing copy_only backups?
-- Have you done any backup tuning with striped backups, or changing the parameters of the backup command?


-- These three Pluralsight Courses go into more detail about how to run these queries and interpret the results

-- SQL Server 2014 DMV Diagnostic Queries � Part 1 
-- https://bit.ly/2plxCer

-- SQL Server 2014 DMV Diagnostic Queries � Part 2
-- https://bit.ly/2IuJpzI

-- SQL Server 2014 DMV Diagnostic Queries � Part 3
-- https://bit.ly/2FIlCPb



-- Sign up for Microsoft Visual Studio Dev Essentials and get a free three month pass to Pluralsight

-- Microsoft Visual Studio Dev Essentials
-- http://bit.ly/1q6xbDL


-- Sign up for Microsoft Azure Essentials and get lots of free Azure usage credits, MCP exam voucher, three month Pluralsight subscription

-- Microsoft Azure Essentials
-- https://bit.ly/2JMWe8x


-- August 2017 blog series about upgrading and migrating SQL Server
-- https://bit.ly/2ftKVrX
tools\dbatools\bin\diagnosticquery\SQLServerDiagnosticQueries_2012_201811.sql

-- SQL Server 2012 Diagnostic Information Queries
-- Glenn Berry 
-- Last Modified: January 7, 2019
-- https://www.sqlskills.com/blogs/glenn/
-- http://sqlserverperformance.wordpress.com/
-- Twitter: GlennAlanBerry

-- Please listen to my Pluralsight courses
-- https://www.pluralsight.com/author/glenn-berry

-- If you want to find all of our SQLskills SQL101 blog posts, check out https://www.sqlskills.com/help/sql101/


-- Please make sure you are using the correct version of these diagnostic queries for your version of SQL Server


-- If you like PowerShell, there is a very useful community solution for running these queries in an automated fashion
-- https://dbatools.io/

-- Invoke-DbaDiagnosticQuery
-- https://dbatools.io/functions/invoke-dbadiagnosticquery/


--******************************************************************************
--*   Copyright (C) 2019 Glenn Berry, SQLskills.com
--*   All rights reserved. 
--*
--*   For more scripts and sample code, check out 
--*      https://www.sqlskills.com/blogs/glenn
--*
--*   You may alter this code for your own *non-commercial* purposes. You may
--*   republish altered code as long as you include this copyright and give due credit. 
--*
--*
--*   THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF 
--*   ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED 
--*   TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
--*   PARTICULAR PURPOSE. 
--*
--******************************************************************************

-- Check the major product version to see if it is SQL Server 2012
IF NOT EXISTS (SELECT * WHERE CONVERT(varchar(128), SERVERPROPERTY('ProductVersion')) LIKE '11%')
	BEGIN
		DECLARE @ProductVersion varchar(128) = CONVERT(varchar(128), SERVERPROPERTY('ProductVersion'));
		RAISERROR ('Script does not match the ProductVersion [%s] of this instance. Many of these queries may not work on this version.' , 18 , 16 , @ProductVersion);
	END
	ELSE
		PRINT N'You have the correct major version of SQL Server for this diagnostic information script';


-- Instance level queries *******************************

-- SQL and OS Version information for current instance  (Query 1) (Version Info)
SELECT @@SERVERNAME AS [Server Name], @@VERSION AS [SQL Server and OS Version Info];
------

-- SQL Server 2012 RTM Branch Builds						SQL Server 2012 SP1 Branch Builds					SQL Server 2012 SP2 Branch Builds						SQL Server 2012 SP3 Branch Builds					SQL Server 2012 SP4 Branch Builds
-- Build			Description			Release Date		Build			Description		Release Date		Build			Description		    Release Date        Build			Description		    Release Date	Build			Description		    Release Date
-- 11.0.2100		RTM					  3/6/2012  
-- 11.0.2316		RTM CU1				 4/12/2012
-- 11.0.2325        RTM CU2				 6/18/2012 -->		11.0.3000		SP1 RTM			11/7/2012
-- 11.0.2332		RTM CU3				 8/31/2012
-- 11.0.2376	    RTM CU3 + QFE	     10/9/2012
-- 11.0.2383	    RTM CU4			    10/15/2012 -->		11.0.3321		SP1 CU1			11/20/2012
-- 11.0.2395		RTM CU5				12/17/2012 -->      11.0.3339		SP1 CU2			1/21/2013
-- 11.0.2401        RTM CU6              2/18/2013 -->      11.0.3349       SP1 CU3			3/18/2013
-- 11.0.2405        RTM CU7              4/15/2013 -->      11.0 3368       SP1 CU4         5/30/2013
-- 11.0.2410        RTM CU8              6/17/2013 -->      11.0.3373       SP1 CU5         7/15/2013
-- 11.0.2419        RTM CU9              8/20/2013 -->      11.0.3381		SP1 CU6			9/16/2013
-- 11.0.2420        RTM CU10            10/21/2013 -->		11.0.3393       SP1 CU7         11/18/2013
-- 11.0.2424        RTM CU11            12/16/2003 -->      11.0.3401       SP1 CU8         1/20/2014
--                                                          11.0.3412       SP1 CU9         3/17/2014 -->		11.0.5058		SP2 RTM			    6/10/2014
--                                                          11.0.3431       SP1 CU10        5/19/2014
--                                                          11.0.3449       SP1 CU11        7/21/2014 -->		11.0.5532		SP2 CU1			    7/23/2014
--                                                          11.0.3470       SP1 CU12        9/15/2014 -->       11.0.5548       SP2 CU2             9/15/2014
--                                                          11.0.3482		SP1 CU13        11/17/2014-->       11.0.5556		SP2 CU3            11/17/2014
--                                                          11.0.3486       SP1 CU14        1/19/2015 -->       11.0.5569       SP2 CU4             1/19/2015
--                                                                                                              11.0.5571       SP2 CU4 + COD HF     2/4/2015  
--                                                          11.0.3487		SP1 CU15		3/16/2015 -->       11.0.5582       SP2 CU5             3/16/2015
--															11.0.3492       SP1 CU16        5/18/2015 -->       11.0.5592		SP2 CU6				5/18/2015
--                                                                                                              11.0.5623       SP2 CU7				7/20/2015
--                                                                                                              11.0.5634		SP2 CU8				9/21/2015
--																												11.0.5641		SP2 CU9			   11/16/2015   ---->  11.0.6020		SP3 RTM			11/21/2015
--																												11.0.5644		SP2 CU10			1/18/2016   ---->  11.0.6518		SP3 CU1			 1/18/2016
--																												11.0.5646		SP2 CU11			3/21/2016	---->  11.0.6523		SP3 CU2			 3/21/2016
--																												11.0.5649		SP2 CU12			5/16/2016	---->  11.0.6537		SP3 CU3			 5/16/2016
--																												11.0.5655		SP2 CU13			7/18/2016	---->  11.0.6540		SP3 CU4			 7/18/2016	
--																												11.0.5657		SP2 CU14		    9/19/2016   ---->  11.0.6544		SP3 CU5			 9/20/2016
--																												11.0.5676		SP2 CU15 		   11/16/2016   ---->  11.0.6567		SP3 CU6 		11/16/2016
--																												11.0.5678		SP2 CU16			1/17/2017   ---->  11.0.6579		SP3 CU7			 1/17/2017
--																																									   11.0.6594		SP3 CU8			 3/20/2017
--																																									   11.0.6598		SP3 CU9			 5/15/2017																											                                                            				
--																																									   11.0.6607		SP3 CU10		  8/8/2017																											
--																																																							11.0.7001		SP4 RTM				10/3/2017	
-- 
-- Security Update for SQL Server 2012 SP4 (KB4057116) 
-- https://bit.ly/2F33Sc4
--                                                                                                                                                                                                                          11.0.7462	    Security Update		1/12/2018  (Security Update for SQL Server 2012 SP4 (KB4057116))
-- SQL Server 2012 Service Pack 4 (SP4) Released!
-- https://bit.ly/2qN8kr3

-- How to determine the version, edition and update level of SQL Server and its components 
-- https://bit.ly/2oAjKgW	

-- SQL Server 2012 SP3 build versions
-- https://bit.ly/2HFjAzA 

-- SQL Server 2012 SP2 build versions 
-- https://bit.ly/2qLqqcS

-- The SQL Server 2012 builds that were released after SQL Server 2012 Service Pack 1 was released
-- https://bit.ly/2HG21za

-- The SQL Server 2012 builds that were released after SQL Server 2012 was released
-- https://bit.ly/2K1xZnX

-- Where to find information about the latest SQL Server builds
-- https://bit.ly/2IGHbfY

-- Recommended updates and configuration options for SQL Server 2012 and SQL Server 2014 used with high-performance workloads
-- https://bit.ly/2Hy3zIZ

-- Performance and Stability Related Fixes in Post-SQL Server 2012 SP3 Builds
-- https://bit.ly/2woDJ4Z

-- Performance and Stability Related Fixes in Post-SQL Server 2012 SP2 Builds
-- https://bit.ly/2vuKZzp

-- Performance and Stability Related Fixes in Post-SQL Server 2012 SP1 Builds
-- https://bit.ly/2vBt1LC

-- Performance Related Fixes in Post-SQL Server 2012 RTM Builds
-- https://bit.ly/2vuIQn4

-- Announcing updates to the SQL Server Incremental Servicing Model (ISM)
-- https://bit.ly/1RzYITz

-- Update Center for Microsoft SQL Server
-- https://bit.ly/2pZptuQ

-- Download SQL Server Management Studio (SSMS)
-- https://bit.ly/1OcupT9

-- Download and install Azure Data Studio 
-- https://bit.ly/2vgke1A


-- Get socket, physical core and logical core count from the SQL Server Error log. (Query 2) (Core Counts)
-- This query might take a few seconds depending on the size of your error log 
EXEC sys.xp_readerrorlog 0, 1, N'detected', N'socket';
------

-- This can help you determine the exact core counts used by SQL Server and whether HT is enabled or not
-- It can also help you confirm your SQL Server licensing model
-- Be on the lookout for this message "using 40 logical processors based on SQL Server licensing" 
-- (when you have more than 40 logical cores) which means grandfathered Server/CAL licensing
-- This query will return no results if your error log has been recycled since the instance was last started
-- New in SQL Server 2012 SP4



-- Get selected server properties (Query 3) (Server Properties)
SELECT SERVERPROPERTY('MachineName') AS [MachineName], 
SERVERPROPERTY('ServerName') AS [ServerName],  
SERVERPROPERTY('InstanceName') AS [Instance], 
SERVERPROPERTY('IsClustered') AS [IsClustered], 
SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS [ComputerNamePhysicalNetBIOS], 
SERVERPROPERTY('Edition') AS [Edition], 
SERVERPROPERTY('ProductLevel') AS [ProductLevel],				-- What servicing branch (RTM/SP/CU)
SERVERPROPERTY('ProductUpdateLevel') AS [ProductUpdateLevel],	-- Within a servicing branch, what CU# is applied
SERVERPROPERTY('ProductVersion') AS [ProductVersion],
SERVERPROPERTY('ProductMajorVersion') AS [ProductMajorVersion], 
SERVERPROPERTY('ProductMinorVersion') AS [ProductMinorVersion], 
SERVERPROPERTY('ProductBuild') AS [ProductBuild], 
SERVERPROPERTY('ProductBuildType') AS [ProductBuildType],		      -- Is this a GDR or OD hotfix (NULL if on a CU build)
SERVERPROPERTY('ProductUpdateReference') AS [ProductUpdateReference], -- KB article number that is applicable for this build
SERVERPROPERTY('ProcessID') AS [ProcessID],
SERVERPROPERTY('Collation') AS [Collation], 
SERVERPROPERTY('IsFullTextInstalled') AS [IsFullTextInstalled], 
SERVERPROPERTY('IsIntegratedSecurityOnly') AS [IsIntegratedSecurityOnly],
SERVERPROPERTY('FilestreamConfiguredLevel') AS [FilestreamConfiguredLevel],
SERVERPROPERTY('IsHadrEnabled') AS [IsHadrEnabled], 
SERVERPROPERTY('HadrManagerStatus') AS [HadrManagerStatus],
SERVERPROPERTY('InstanceDefaultDataPath') AS [InstanceDefaultDataPath],
SERVERPROPERTY('InstanceDefaultLogPath') AS [InstanceDefaultLogPath],
SERVERPROPERTY('BuildClrVersion') AS [Build CLR Version];
------

-- This gives you a lot of useful information about your instance of SQL Server,
-- such as the ProcessID for SQL Server and your collation
-- Note: Some columns will be NULL on older SQL Server builds

-- SERVERPROPERTY (Transact-SQL)
-- https://bit.ly/2eeaXeI


-- Get instance-level configuration values for instance  (Query 4) (Configuration Values)
SELECT name, value, value_in_use, minimum, maximum, [description], is_dynamic, is_advanced
FROM sys.configurations WITH (NOLOCK)
ORDER BY name OPTION (RECOMPILE);
------

-- Focus on these settings:
-- backup compression default (should be 1 in most cases)
-- clr enabled (only enable if it is needed)
-- cost threshold for parallelism (depends on your workload)
-- lightweight pooling (should be zero)
-- max degree of parallelism (depends on your workload and hardware)
-- max server memory (MB) (set to an appropriate value, not the default)
-- optimize for ad hoc workloads (should be 1)
-- priority boost (should be zero)
-- remote admin connections (should be 1)


-- Returns a list of all global trace flags that are enabled (Query 5) (Global Trace Flags)
DBCC TRACESTATUS (-1);
------

-- If no global trace flags are enabled, no results will be returned.
-- It is very useful to know what global trace flags are currently enabled as part of the diagnostic process.

-- Common trace flags that should be enabled in most cases
-- TF 1117 - When growing a data file, grow all files at the same time so they remain the same size, reducing allocation contention points
--           https://bit.ly/2GY1kOl
-- 
-- TF 1118 - Helps alleviate allocation contention in tempdb, SQL Server allocates full extents to each database object, 
--           thereby eliminating the contention on SGAM pages (more important with older versions of SQL Server)
--           Recommendations to reduce allocation contention in SQL Server tempdb database
--           https://bit.ly/2GY1kOl

-- TF 2371 - Lowers auto update statistics threshold for large tables (on tables with more than 25,000 rows)
--           https://bit.ly/2HySkAg

-- TF 3023 - Enables backup checksum default
--           https://bit.ly/2vtjqqc

-- TF 3226 - Supresses logging of successful database backup messages to the SQL Server Error Log
--           https://bit.ly/2p6MTjS

-- TF 3449 - Enables use of dirty page manager (SQL Server 2012 SP3 CU3 and later)
--			 https://bit.ly/2uj0h5M

-- TF 6533 - Spatial performance improvements in SQL Server 2012 and 2014
--           https://bit.ly/2v7C7ze

-- TF 6534 - Enables use of native code to improve performance with spatial data
--           https://bit.ly/2HrQUpU

-- TF 8079 - Enables automatic soft-NUMA on systems with eight or more physical cores per NUMA node (with SQL Server 2012 SP4)
--           https://bit.ly/2qN8kr3

-- DBCC TRACEON - Trace Flags (Transact-SQL)
-- https://bit.ly/2FuSvPg


-- Returns status of instant file initialization (Query 6) (IFI Status)
EXEC sys.xp_readerrorlog 0, 1, N'Database Instant File Initialization';
------

-- Lets you determine whether Instant File Initialization (IFI) is enabled for the instance
-- This should be enabled in the vast majority of cases
-- (Added in SQL Server 2012 SP4)

-- Database Instant File Initialization
-- https://bit.ly/2nTX74y

-- Misconceptions around instant file initialization
-- https://bit.ly/2oBSKgZ



-- SQL Server Process Address space info  (Query 7) (Process Memory)
-- (shows whether locked pages is enabled, among other things)
SELECT physical_memory_in_use_kb/1024 AS [SQL Server Memory Usage (MB)],
	   locked_page_allocations_kb/1024 AS [SQL Server Locked Pages Allocation (MB)],
       large_page_allocations_kb/1024 AS [SQL Server Large Pages Allocation (MB)], 
	   page_fault_count, memory_utilization_percentage, available_commit_limit_kb, 
	   process_physical_memory_low, process_virtual_memory_low
FROM sys.dm_os_process_memory WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You want to see 0 for process_physical_memory_low
-- You want to see 0 for process_virtual_memory_low
-- This indicates that you are not under internal memory pressure
-- If locked_page_allocations_kb > 0, then LPIM is enabled

-- How to enable the "locked pages" feature in SQL Server 2012
-- https://bit.ly/2F5UjOA

-- Memory Management Architecture Guide
-- https://bit.ly/2JKkadC 



-- SQL Server Services information (Query 8) (SQL Server Services Info)
SELECT servicename, process_id, startup_type_desc, status_desc, 
last_startup_time, service_account, is_clustered, cluster_nodename, [filename]
FROM sys.dm_server_services WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Tells you the account being used for the SQL Server Service and the SQL Agent Service
-- Shows the process_id, when they were last started, and their current status
-- Also shows whether you are running on a failover cluster instance, and what node you are running on

-- sys.dm_server_services (Transact-SQL)
-- https://bit.ly/2oKa1Un


-- Last backup information by database  (Query 9) (Last Backup By Database)
SELECT ISNULL(d.[name], bs.[database_name]) AS [Database], d.recovery_model_desc AS [Recovery Model], 
       d.log_reuse_wait_desc AS [Log Reuse Wait Desc],
    MAX(CASE WHEN [type] = 'D' THEN bs.backup_finish_date ELSE NULL END) AS [Last Full Backup],
    MAX(CASE WHEN [type] = 'I' THEN bs.backup_finish_date ELSE NULL END) AS [Last Differential Backup],
    MAX(CASE WHEN [type] = 'L' THEN bs.backup_finish_date ELSE NULL END) AS [Last Log Backup]
FROM sys.databases AS d WITH (NOLOCK)
LEFT OUTER JOIN msdb.dbo.backupset AS bs WITH (NOLOCK)
ON bs.[database_name] = d.[name] 
AND bs.backup_finish_date > GETDATE()- 30
WHERE d.name <> N'tempdb'
GROUP BY ISNULL(d.[name], bs.[database_name]), d.recovery_model_desc, d.log_reuse_wait_desc, d.[name] 
ORDER BY d.recovery_model_desc, d.[name] OPTION (RECOMPILE);
------

-- This helps you spot runaway transaction logs and other issues with your backup schedule


-- Get SQL Server Agent jobs and Category information (Query 10) (SQL Server Agent Jobs)
SELECT sj.name AS [Job Name], sj.[description] AS [Job Description], SUSER_SNAME(sj.owner_sid) AS [Job Owner],
sj.date_created AS [Date Created], sj.[enabled] AS [Job Enabled], 
sj.notify_email_operator_id, sj.notify_level_email, sc.name AS [CategoryName],
s.[enabled] AS [Sched Enabled], js.next_run_date, js.next_run_time
FROM msdb.dbo.sysjobs AS sj WITH (NOLOCK)
INNER JOIN msdb.dbo.syscategories AS sc WITH (NOLOCK)
ON sj.category_id = sc.category_id
LEFT OUTER JOIN msdb.dbo.sysjobschedules AS js WITH (NOLOCK)
ON sj.job_id = js.job_id
LEFT OUTER JOIN msdb.dbo.sysschedules AS s WITH (NOLOCK)
ON js.schedule_id = s.schedule_id
ORDER BY sj.name OPTION (RECOMPILE);
------

-- Gives you some basic information about your SQL Server Agent jobs, who owns them and how they are configured
-- Look for Agent jobs that are not owned by sa
-- Look for jobs that have a notify_email_operator_id set to 0 (meaning no operator)
-- Look for jobs that have a notify_level_email set to 0 (meaning no e-mail is ever sent)
--
-- MSDN sysjobs documentation
-- https://bit.ly/2paDEOP

-- SQL Server Maintenance Solution
-- https://bit.ly/1pgchQu


-- Get SQL Server Agent Alert Information (Query 11) (SQL Server Agent Alerts)
SELECT name, event_source, message_id, severity, [enabled], has_notification, 
       delay_between_responses, occurrence_count, last_occurrence_date, last_occurrence_time
FROM msdb.dbo.sysalerts WITH (NOLOCK)
ORDER BY name OPTION (RECOMPILE);
------

-- Gives you some basic information about your SQL Server Agent Alerts (which are different from SQL Server Agent jobs)
-- Read more about Agent Alerts here: https://bit.ly/2Giz0Xf



-- Windows information (Query 12) (Windows Info)
SELECT windows_release, windows_service_pack_level, 
       windows_sku, os_language_version
FROM sys.dm_os_windows_info WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Gives you major OS version, Service Pack, Edition, and language info for the operating system
-- 10.0 is either Windows 10 or Windows Server 2016
-- 6.3 is either Windows 8.1, or Windows Server 2012 R2  
-- 6.2 is either Windows 8 or Windows Server 2012
-- 6.1 is either Windows 7 or Windows Server 2008 R2
-- 6.0 is either Windows Vista or Windows Server 2008

-- Windows SKU codes
-- 4 is Enterprise Edition
-- 7 is Standard Server Edition
-- 8 is Datacenter Server Edition
-- 10 is Enterprise Server Edition
-- 48 is Professional Edition
-- 161 is Pro for Workstations

-- 1033 for os_language_version is US-English

-- SQL Server 2012 requires Windows Server 2008 SP2 or newer

-- Hardware and Software Requirements for Installing SQL Server 2012
-- https://bit.ly/1yRYXkQ

-- Using SQL Server in Windows 8 and later versions of Windows operating system 
-- https://bit.ly/2F7Ax0P



-- SQL Server NUMA Node information  (Query 13) (SQL Server NUMA Info)
SELECT node_id, node_state_desc, memory_node_id, processor_group, online_scheduler_count, 
       idle_scheduler_count, active_worker_count, avg_load_balance, resource_monitor_state
FROM sys.dm_os_nodes WITH (NOLOCK) 
WHERE node_state_desc <> N'ONLINE DAC' OPTION (RECOMPILE);
------

-- Gives you some useful information about the composition and relative load on your NUMA nodes
-- You want to see an equal number of schedulers on each NUMA node
-- Watch out if SQL Server 2012 Standard Edition has been installed 
-- on a physical or virtual machine with more than four sockets or more than 16 physical cores

-- sys.dm_os_nodes (Transact-SQL)
-- https://bit.ly/2pn5Mw8

-- Balancing Your Available SQL Server Core Licenses Evenly Across NUMA Nodes
-- https://bit.ly/2vfC4Rq



-- Good basic information about OS memory amounts and state  (Query 14) (System Memory)
SELECT total_physical_memory_kb/1024 AS [Physical Memory (MB)], 
       available_physical_memory_kb/1024 AS [Available Memory (MB)], 
       total_page_file_kb/1024 AS [Total Page File (MB)], 
	   available_page_file_kb/1024 AS [Available Page File (MB)], 
	   system_cache_kb/1024 AS [System Cache (MB)],
       system_memory_state_desc AS [System Memory State]
FROM sys.dm_os_sys_memory WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You want to see "Available physical memory is high" for System Memory State
-- This indicates that you are not under external memory pressure

-- Possible System Memory State values:
-- Available physical memory is high
-- Physical memory usage is steady
-- Available physical memory is low
-- Available physical memory is running low
-- Physical memory state is transitioning

-- sys.dm_os_sys_memory (Transact-SQL)
-- https://bit.ly/2pcV0xq



-- You can skip the next two queries if you know you don't have a clustered instance


-- Get information about your cluster nodes and their status  (Query 15) (Cluster Node Properties)
-- (if your database server is in a failover cluster)
SELECT NodeName, status_description, is_current_owner
FROM sys.dm_os_cluster_nodes WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Knowing which node owns the cluster resources is critical
-- Especially when you are installing Windows or SQL Server updates
-- You will see no results if your instance is not clustered

-- Recommended hotfixes and updates for Windows Server 2012 R2-based failover clusters
-- https://bit.ly/1z5BfCw


-- Get information about any AlwaysOn AG cluster this instance is a part of (Query 16) (AlwaysOn AG Cluster)
SELECT cluster_name, quorum_type_desc, quorum_state_desc
FROM sys.dm_hadr_cluster WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You will see no results if your instance is not using AlwaysOn AGs



-- Hardware information from SQL Server 2012  (Query 17) (Hardware Info)
SELECT cpu_count AS [Logical CPU Count], scheduler_count, 
       hyperthread_ratio AS [Hyperthread Ratio],
       cpu_count/hyperthread_ratio AS [Physical CPU Count], 
       physical_memory_kb/1024 AS [Physical Memory (MB)], 
	   committed_kb/1024 AS [Committed Memory (MB)],
       committed_target_kb/1024 AS [Committed Target Memory (MB)],
       max_workers_count AS [Max Workers Count], 
	   affinity_type_desc AS [Affinity Type], 
       sqlserver_start_time AS [SQL Server Start Time],
	   DATEDIFF(hour, sqlserver_start_time, GETDATE()) AS [SQL Server Up Time (hrs)],
	   virtual_machine_type_desc AS [Virtual Machine Type]
FROM sys.dm_os_sys_info WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Gives you some good basic hardware information about your database server
-- Cannot distinguish between HT and multi-core
-- Note: virtual_machine_type_desc of HYPERVISOR does not automatically mean you are running SQL Server inside of a VM
-- It merely indicates that you have a hypervisor running on your host

-- sys.dm_os_sys_info (Transact-SQL)
-- https://bit.ly/2pczOYs


-- Get System Manufacturer and model number from SQL Server Error log (Query 18) (System Manufacturer)
EXEC sys.xp_readerrorlog 0, 1, N'Manufacturer';
------ 

-- This can help you determine the capabilities and capacities of your database server
-- Can also be used to confirm if you are running in a VM
-- This query might take a few seconds if you have not recycled your error log recently
-- This query will return no results if your error log has been recycled since the instance was started


-- Get pvscsi info from Windows Registry  (Query 19) (PVSCSI Driver Parameters)
EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SYSTEM\CurrentControlSet\services\pvscsi\Parameters\Device', N'DriverParameter';
------

-- This is valid for VMware VMs
-- Recommended value for intensive I/O patterns from VMware is: RequestRingPages=32,MaxQueueDepth=254
-- https://kb.vmware.com/s/article/2053145



-- Get BIOS date from Windows Registry (Query 20) (BIOS Date)
EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'HARDWARE\DESCRIPTION\System\BIOS', N'BiosReleaseDate';
------

-- Helps you understand whether the main system BIOS is up to date, and the possible age of the hardware
-- Not as useful for virtualization


-- Get processor description from Windows Registry  (Query 21) (Processor Description)
EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'HARDWARE\DESCRIPTION\System\CentralProcessor\0', N'ProcessorNameString';
------

-- Gives you the model number and rated clock speed of your processor(s)
-- Your processors may be running at less than the rated clock speed due
-- to the Windows Power Plan or hardware power management

-- You can use CPU-Z to get your actual CPU core speed and a lot of other useful information
-- https://bit.ly/QhR6xF

-- You can learn more about processor selection for SQL Server by following this link
-- https://bit.ly/2F3aVlP



-- Get information on location, time and size of any memory dumps from SQL Server  (Query 22) (Memory Dump Info)
SELECT [filename], creation_time, size_in_bytes/1048576.0 AS [Size (MB)]
FROM sys.dm_server_memory_dumps WITH (NOLOCK) 
ORDER BY creation_time DESC OPTION (RECOMPILE);
------

-- This will not return any rows if you have 
-- not had any memory dumps (which is a good thing)

-- sys.dm_server_memory_dumps (Transact-SQL)
-- https://bit.ly/2elwWll



-- Look at Suspect Pages table (Query 23) (Suspect Pages)
SELECT DB_NAME(database_id) AS [Database Name], [file_id], page_id, 
       event_type, error_count, last_update_date 
FROM msdb.dbo.suspect_pages WITH (NOLOCK)
ORDER BY database_id OPTION (RECOMPILE);
------

-- event_type value descriptions
-- 1 = 823 error caused by an operating system CRC error
--     or 824 error other than a bad checksum or a torn page (for example, a bad page ID)
-- 2 = Bad checksum
-- 3 = Torn page
-- 4 = Restored (The page was restored after it was marked bad)
-- 5 = Repaired (DBCC repaired the page)
-- 7 = Deallocated by DBCC

-- Ideally, this query returns no results. The table is limited to 1000 rows.
-- If you do get results here, you should do further investigation to determine the root cause

-- Manage the suspect_pages Table
-- https://bit.ly/2Fvr1c9


-- Get number of data files in tempdb database (Query 24) (Tempdb Data Files)
EXEC sys.xp_readerrorlog 0, 1, N'The tempdb database has';
------

-- Get the number of data files in the tempdb database
-- 4-8 data files that are all the same size is a good starting point
-- This query will return no results if your error log has been recycled since the instance was last started
-- This will be blank unless you have Service Pack 4 or later


-- File names and paths for all user and system databases on instance  (Query 25) (Database Filenames and Paths)
SELECT DB_NAME([database_id]) AS [Database Name], 
       [file_id], [name], physical_name, [type_desc], state_desc,
	   is_percent_growth, growth,
	   CONVERT(bigint, growth/128.0) AS [Growth in MB], 
       CONVERT(bigint, size/128.0) AS [Total Size in MB]
FROM sys.master_files WITH (NOLOCK)
ORDER BY DB_NAME([database_id]), [file_id] OPTION (RECOMPILE);
------

-- Things to look at:
-- Are data files and log files on different drives?
-- Is everything on the C: drive?
-- Is tempdb on dedicated drives?
-- Is there only one tempdb data file?
-- Are all of the tempdb data files the same size?
-- Are there multiple data files for user databases?
-- Is percent growth enabled for any files (which is bad)?


-- Volume info for all LUNS that have database files on the current instance (Query 26) (Volume Info)
SELECT DISTINCT vs.volume_mount_point, vs.file_system_type, vs.logical_volume_name, 
CONVERT(DECIMAL(18,2), vs.total_bytes/1073741824.0) AS [Total Size (GB)],
CONVERT(DECIMAL(18,2), vs.available_bytes/1073741824.0) AS [Available Size (GB)],  
CONVERT(DECIMAL(18,2), vs.available_bytes * 1. / vs.total_bytes * 100.) AS [Space Free %],
vs.supports_compression, vs.is_compressed, 
vs.supports_sparse_files, vs.supports_alternate_streams
FROM sys.master_files AS f WITH (NOLOCK)
CROSS APPLY sys.dm_os_volume_stats(f.database_id, f.[file_id]) AS vs 
ORDER BY vs.volume_mount_point OPTION (RECOMPILE);
------

-- Shows you the total and free space on the LUNs where you have database files
-- Being low on free space can negatively affect performance

-- sys.dm_os_volume_stats (Transact-SQL)
-- https://bit.ly/2oBPNNr



-- Drive level latency information (Query 27) (Drive Level Latency)
-- Based on code from Jimmy May
SELECT tab.[Drive], tab.volume_mount_point AS [Volume Mount Point], 
	CASE 
		WHEN num_of_reads = 0 THEN 0 
		ELSE (io_stall_read_ms/num_of_reads) 
	END AS [Read Latency],
	CASE 
		WHEN num_of_writes = 0 THEN 0 
		ELSE (io_stall_write_ms/num_of_writes) 
	END AS [Write Latency],
	CASE 
		WHEN (num_of_reads = 0 AND num_of_writes = 0) THEN 0 
		ELSE (io_stall/(num_of_reads + num_of_writes)) 
	END AS [Overall Latency],
	CASE 
		WHEN num_of_reads = 0 THEN 0 
		ELSE (num_of_bytes_read/num_of_reads) 
	END AS [Avg Bytes/Read],
	CASE 
		WHEN num_of_writes = 0 THEN 0 
		ELSE (num_of_bytes_written/num_of_writes) 
	END AS [Avg Bytes/Write],
	CASE 
		WHEN (num_of_reads = 0 AND num_of_writes = 0) THEN 0 
		ELSE ((num_of_bytes_read + num_of_bytes_written)/(num_of_reads + num_of_writes)) 
	END AS [Avg Bytes/Transfer]
FROM (SELECT LEFT(UPPER(mf.physical_name), 2) AS Drive, SUM(num_of_reads) AS num_of_reads,
	         SUM(io_stall_read_ms) AS io_stall_read_ms, SUM(num_of_writes) AS num_of_writes,
	         SUM(io_stall_write_ms) AS io_stall_write_ms, SUM(num_of_bytes_read) AS num_of_bytes_read,
	         SUM(num_of_bytes_written) AS num_of_bytes_written, SUM(io_stall) AS io_stall, vs.volume_mount_point 
      FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS vfs
      INNER JOIN sys.master_files AS mf WITH (NOLOCK)
      ON vfs.database_id = mf.database_id AND vfs.file_id = mf.file_id
	  CROSS APPLY sys.dm_os_volume_stats(mf.database_id, mf.[file_id]) AS vs 
      GROUP BY LEFT(UPPER(mf.physical_name), 2), vs.volume_mount_point) AS tab
ORDER BY [Overall Latency] OPTION (RECOMPILE);
------

-- Shows you the drive-level latency for reads and writes, in milliseconds
-- Latency above 30-40ms is usually a problem
-- These latency numbers include all file activity against all SQL Server 
-- database files on each drive since SQL Server was last started


-- Calculates average stalls per read, per write, and per total input/output for each database file  (Query 28) (IO Latency by File)
SELECT DB_NAME(fs.database_id) AS [Database Name], CAST(fs.io_stall_read_ms/(1.0 + fs.num_of_reads) AS NUMERIC(10,1)) AS [avg_read_latency_ms],
CAST(fs.io_stall_write_ms/(1.0 + fs.num_of_writes) AS NUMERIC(10,1)) AS [avg_write_latency_ms],
CAST((fs.io_stall_read_ms + fs.io_stall_write_ms)/(1.0 + fs.num_of_reads + fs.num_of_writes) AS NUMERIC(10,1)) AS [avg_io_latency_ms],
CONVERT(DECIMAL(18,2), mf.size/128.0) AS [File Size (MB)], mf.physical_name, mf.type_desc, fs.io_stall_read_ms, fs.num_of_reads, 
fs.io_stall_write_ms, fs.num_of_writes, fs.io_stall_read_ms + fs.io_stall_write_ms AS [io_stalls], fs.num_of_reads + fs.num_of_writes AS [total_io]
FROM sys.dm_io_virtual_file_stats(null,null) AS fs
INNER JOIN sys.master_files AS mf WITH (NOLOCK)
ON fs.database_id = mf.database_id
AND fs.[file_id] = mf.[file_id]
ORDER BY avg_io_latency_ms DESC OPTION (RECOMPILE);
------

-- Helps determine which database files on the entire instance have the most I/O bottlenecks
-- This can help you decide whether certain LUNs are overloaded and whether you might
-- want to move some files to a different location or perhaps improve your I/O performance
-- These latency numbers include all file activity against each SQL Server 
-- database file since SQL Server was last started


-- Look for I/O requests taking longer than 15 seconds in the six most recent SQL Server Error Logs (Query 29) (IO Warnings)
CREATE TABLE #IOWarningResults(LogDate datetime, ProcessInfo sysname, LogText nvarchar(1000));

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 0, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 1, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 2, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 3, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 4, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 5, 1, N'taking longer than 15 seconds';

SELECT LogDate, ProcessInfo, LogText
FROM #IOWarningResults
ORDER BY LogDate DESC;

DROP TABLE #IOWarningResults;
------  

-- Finding 15 second I/O warnings in the SQL Server Error Log is useful evidence of
-- poor I/O performance (which might have many different causes)
-- Look to see if you see any patterns in the results (same files, same drives, same time of day, etc.)

-- Diagnostics in SQL Server help detect stalled and stuck I/O operations
-- https://bit.ly/2qtaw73


-- Resource Governor Resource Pool information (Query 30) (RG Resource Pools)
SELECT pool_id, [Name], statistics_start_time,
       min_memory_percent, max_memory_percent,  
       max_memory_kb/1024 AS [max_memory_mb],  
       used_memory_kb/1024 AS [used_memory_mb],   
       target_memory_kb/1024 AS [target_memory_mb]
FROM sys.dm_resource_governor_resource_pools WITH (NOLOCK)
OPTION (RECOMPILE);
------

-- sys.dm_resource_governor_resource_pools (Transact-SQL)
-- https://bit.ly/2MVU0Vy



-- Recovery model, log reuse wait description, log file size, log usage size  (Query 31) (Database Properties)
-- and compatibility level for all databases on instance
SELECT db.[name] AS [Database Name], SUSER_SNAME(db.owner_sid) AS [Database Owner], db.recovery_model_desc AS [Recovery Model], 
db.state_desc, db.containment_desc, db.log_reuse_wait_desc AS [Log Reuse Wait Description], 
CONVERT(DECIMAL(18,2), ls.cntr_value/1024.0) AS [Log Size (MB)], CONVERT(DECIMAL(18,2), lu.cntr_value/1024.0) AS [Log Used (MB)],
CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log Used %], 
db.[compatibility_level] AS [DB Compatibility Level], db.page_verify_option_desc AS [Page Verify Option], 
db.is_auto_create_stats_on, db.is_auto_update_stats_on, db.is_auto_update_stats_async_on, db.is_parameterization_forced, 
db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on, db.is_auto_close_on, db.is_auto_shrink_on, 
db.target_recovery_time_in_seconds, db.is_cdc_enabled, db.is_published, db.group_database_id, db.replica_id,
db.is_encrypted, de.encryption_state, de.percent_complete, de.key_algorithm, de.key_length
FROM sys.databases AS db WITH (NOLOCK)
INNER JOIN sys.dm_os_performance_counters AS lu WITH (NOLOCK)
ON db.name = lu.instance_name
INNER JOIN sys.dm_os_performance_counters AS ls WITH (NOLOCK)
ON db.name = ls.instance_name
LEFT OUTER JOIN sys.dm_database_encryption_keys AS de WITH (NOLOCK)
ON db.database_id = de.database_id
WHERE lu.counter_name LIKE N'Log File(s) Used Size (KB)%' 
AND ls.counter_name LIKE N'Log File(s) Size (KB)%'
AND ls.cntr_value > 0 
ORDER BY db.[name] OPTION (RECOMPILE);
------

-- Things to look at:
-- How many databases are on the instance?
-- What recovery models are they using?
-- What is the log reuse wait description?
-- How full are the transaction logs?
-- What compatibility level are the databases on? 
-- What is the Page Verify Option? (should be CHECKSUM)
-- Is Auto Update Statistics Asynchronously enabled?
-- Make sure auto_shrink and auto_close are not enabled!



-- Missing Indexes for all databases by Index Advantage  (Query 32) (Missing Indexes All Databases)
SELECT CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage],
FORMAT(migs.last_user_seek, 'yyyy-MM-dd HH:mm:ss') AS [last_user_seek], 
mid.[statement] AS [Database.Schema.Table],
COUNT(1) OVER(PARTITION BY mid.[statement]) AS [missing_indexes_for_table],
COUNT(1) OVER(PARTITION BY mid.[statement], equality_columns) AS [similar_missing_indexes_for_table],
mid.equality_columns, mid.inequality_columns, mid.included_columns,
migs.unique_compiles, migs.user_seeks, 
CONVERT(decimal(18,2), migs.avg_total_user_cost) AS [avg_total_user_cost], migs.avg_user_impact 
FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)
INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)
ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)
ON mig.index_handle = mid.index_handle
ORDER BY index_advantage DESC OPTION (RECOMPILE);
------

-- Getting missing index information for all of the databases on the instance is very useful
-- Look at last user seek time, number of user seeks to help determine source and importance
-- Also look at avg_user_impact and avg_total_user_cost to help determine importance
-- SQL Server is overly eager to add included columns, so beware
-- Do not just blindly add indexes that show up from this query!!!

-- SQL Server Index Design Guide
-- https://bit.ly/2qtZr4N



-- Get VLF Counts for all databases on the instance (Query 33) (VLF Counts)
-- (adapted from Michelle Ufford) 
CREATE TABLE #VLFInfo (RecoveryUnitID int, FileID  int,
					   FileSize bigint, StartOffset bigint,
					   FSeqNo      bigint, [Status]    bigint,
					   Parity      bigint, CreateLSN   numeric(38));
	 
CREATE TABLE #VLFCountResults(DatabaseName sysname, VLFCount int);
	 
EXEC sp_MSforeachdb N'Use [?]; 

				INSERT INTO #VLFInfo 
				EXEC sp_executesql N''DBCC LOGINFO([?])''; 
	 
				INSERT INTO #VLFCountResults 
				SELECT DB_NAME(), COUNT(*) 
				FROM #VLFInfo; 

				TRUNCATE TABLE #VLFInfo;'
	 
SELECT DatabaseName, VLFCount  
FROM #VLFCountResults
ORDER BY VLFCount DESC;
	 
DROP TABLE #VLFInfo;
DROP TABLE #VLFCountResults;
------

-- High VLF counts can affect write performance to the log file 
-- and they can make full database restores and crash recovery take much longer
-- Try to keep your VLF counts under 200 in most cases (depending on log file size)



-- Get CPU utilization by database (Query 34) (CPU Usage by Database)
WITH DB_CPU_Stats
AS
(SELECT pa.DatabaseID, DB_Name(pa.DatabaseID) AS [Database Name], SUM(qs.total_worker_time/1000) AS [CPU_Time_Ms]
 FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
 CROSS APPLY (SELECT CONVERT(int, value) AS [DatabaseID] 
              FROM sys.dm_exec_plan_attributes(qs.plan_handle)
              WHERE attribute = N'dbid') AS pa
 GROUP BY DatabaseID)
SELECT ROW_NUMBER() OVER(ORDER BY [CPU_Time_Ms] DESC) AS [CPU Rank],
       [Database Name], [CPU_Time_Ms] AS [CPU Time (ms)], 
       CAST([CPU_Time_Ms] * 1.0 / SUM([CPU_Time_Ms]) OVER() * 100.0 AS DECIMAL(5, 2)) AS [CPU Percent]
FROM DB_CPU_Stats
WHERE DatabaseID <> 32767 -- ResourceDB
ORDER BY [CPU Rank] OPTION (RECOMPILE);
------

-- Helps determine which database is using the most CPU resources on the instance
-- Note: This only reflects CPU usage from the currently cached query plans


-- Get I/O utilization by database (Query 35) (IO Usage By Database)
WITH Aggregate_IO_Statistics
AS (SELECT DB_NAME(database_id) AS [Database Name],
    CAST(SUM(num_of_bytes_read + num_of_bytes_written) / 1048576 AS DECIMAL(12, 2)) AS [ioTotalMB],
    CAST(SUM(num_of_bytes_read ) / 1048576 AS DECIMAL(12, 2)) AS [ioReadMB],
    CAST(SUM(num_of_bytes_written) / 1048576 AS DECIMAL(12, 2)) AS [ioWriteMB]
    FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS [DM_IO_STATS]
    GROUP BY database_id)
SELECT ROW_NUMBER() OVER (ORDER BY ioTotalMB DESC) AS [I/O Rank],
        [Database Name], ioTotalMB AS [Total I/O (MB)],
        CAST(ioTotalMB / SUM(ioTotalMB) OVER () * 100.0 AS DECIMAL(5, 2)) AS [Total I/O %],
        ioReadMB AS [Read I/O (MB)], 
		CAST(ioReadMB / SUM(ioReadMB) OVER () * 100.0 AS DECIMAL(5, 2)) AS [Read I/O %],
        ioWriteMB AS [Write I/O (MB)], 
		CAST(ioWriteMB / SUM(ioWriteMB) OVER () * 100.0 AS DECIMAL(5, 2)) AS [Write I/O %]
FROM Aggregate_IO_Statistics
ORDER BY [I/O Rank] OPTION (RECOMPILE);
------

-- Helps determine which database is using the most I/O resources on the instance
-- These numbers are cumulative since the last service restart
-- They include all I/O activity, not just the nominal I/O workload


-- Get total buffer usage by database for current instance  (Query 36) (Total Buffer Usage by Database)
-- This make take some time to run on a busy instance
WITH AggregateBufferPoolUsage
AS
(SELECT DB_NAME(database_id) AS [Database Name],
CAST(COUNT(*) * 8/1024.0 AS DECIMAL (10,2))  AS [CachedSize]
FROM sys.dm_os_buffer_descriptors WITH (NOLOCK)
WHERE database_id <> 32767 -- ResourceDB
GROUP BY DB_NAME(database_id))
SELECT ROW_NUMBER() OVER(ORDER BY CachedSize DESC) AS [Buffer Pool Rank], [Database Name], CachedSize AS [Cached Size (MB)],
       CAST(CachedSize / SUM(CachedSize) OVER() * 100.0 AS DECIMAL(5,2)) AS [Buffer Pool Percent]
FROM AggregateBufferPoolUsage
ORDER BY [Buffer Pool Rank] OPTION (RECOMPILE);
------

-- Tells you how much memory (in the buffer pool) 
-- is being used by each database on the instance


-- Clear Wait Stats with this command
-- DBCC SQLPERF('sys.dm_os_wait_stats', CLEAR);

-- Isolate top waits for server instance since last restart or wait statistics clear  (Query 37) (Top Waits)
WITH [Waits] 
AS (SELECT wait_type, wait_time_ms/ 1000.0 AS [WaitS],
          (wait_time_ms - signal_wait_time_ms) / 1000.0 AS [ResourceS],
           signal_wait_time_ms / 1000.0 AS [SignalS],
           waiting_tasks_count AS [WaitCount],
           100.0 *  wait_time_ms / SUM (wait_time_ms) OVER() AS [Percentage],
           ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS [RowNum]
    FROM sys.dm_os_wait_stats WITH (NOLOCK)
    WHERE [wait_type] NOT IN (
        N'BROKER_EVENTHANDLER', N'BROKER_RECEIVE_WAITFOR', N'BROKER_TASK_STOP',
		N'BROKER_TO_FLUSH', N'BROKER_TRANSMITTER', N'CHECKPOINT_QUEUE',
        N'CHKPT', N'CLR_AUTO_EVENT', N'CLR_MANUAL_EVENT', N'CLR_SEMAPHORE',
        N'DBMIRROR_DBM_EVENT', N'DBMIRROR_EVENTS_QUEUE', N'DBMIRROR_WORKER_QUEUE',
		N'DBMIRRORING_CMD', N'DIRTY_PAGE_POLL', N'DISPATCHER_QUEUE_SEMAPHORE',
        N'EXECSYNC', N'FSAGENT', N'FT_IFTS_SCHEDULER_IDLE_WAIT', N'FT_IFTSHC_MUTEX',
        N'HADR_CLUSAPI_CALL', N'HADR_FILESTREAM_IOMGR_IOCOMPLETION', N'HADR_LOGCAPTURE_WAIT', 
		N'HADR_NOTIFICATION_DEQUEUE', N'HADR_TIMER_TASK', N'HADR_WORK_QUEUE',
        N'KSOURCE_WAKEUP', N'LAZYWRITER_SLEEP', N'LOGMGR_QUEUE', N'ONDEMAND_TASK_QUEUE',
        N'PREEMPTIVE_OS_QUERYREGISTRY', 
		N'PREEMPTIVE_HADR_LEASE_MECHANISM', N'PREEMPTIVE_SP_SERVER_DIAGNOSTICS',
		N'PWAIT_ALL_COMPONENTS_INITIALIZED', 
		N'QDS_PERSIST_TASK_MAIN_LOOP_SLEEP',
        N'QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP', N'REQUEST_FOR_DEADLOCK_SEARCH',
		N'RESOURCE_QUEUE', N'SERVER_IDLE_CHECK', N'SLEEP_BPOOL_FLUSH', N'SLEEP_DBSTARTUP',
		N'SLEEP_DCOMSTARTUP', N'SLEEP_MASTERDBREADY', N'SLEEP_MASTERMDREADY',
        N'SLEEP_MASTERUPGRADED', N'SLEEP_MSDBSTARTUP', N'SLEEP_SYSTEMTASK', N'SLEEP_TASK',
        N'SLEEP_TEMPDBSTARTUP', N'SNI_HTTP_ACCEPT', N'SP_SERVER_DIAGNOSTICS_SLEEP',
		N'SQLTRACE_BUFFER_FLUSH', N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', N'SQLTRACE_WAIT_ENTRIES',
		N'WAIT_FOR_RESULTS', N'WAITFOR', N'WAITFOR_TASKSHUTDOWN', N'WAIT_XTP_HOST_WAIT',
		N'WAIT_XTP_OFFLINE_CKPT_NEW_LOG', N'WAIT_XTP_CKPT_CLOSE', N'XE_DISPATCHER_JOIN',
        N'XE_DISPATCHER_WAIT', N'XE_TIMER_EVENT')
    AND waiting_tasks_count > 0)
SELECT
    MAX (W1.wait_type) AS [WaitType],
	CAST (MAX (W1.Percentage) AS DECIMAL (5,2)) AS [Wait Percentage],
	CAST ((MAX (W1.WaitS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgWait_Sec],
    CAST ((MAX (W1.ResourceS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgRes_Sec],
    CAST ((MAX (W1.SignalS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgSig_Sec], 
    CAST (MAX (W1.WaitS) AS DECIMAL (16,2)) AS [Wait_Sec],
    CAST (MAX (W1.ResourceS) AS DECIMAL (16,2)) AS [Resource_Sec],
    CAST (MAX (W1.SignalS) AS DECIMAL (16,2)) AS [Signal_Sec],
    MAX (W1.WaitCount) AS [Wait Count],
	CAST (N'https://www.sqlskills.com/help/waits/' + W1.wait_type AS XML) AS [Help/Info URL]
FROM Waits AS W1
INNER JOIN Waits AS W2
ON W2.RowNum <= W1.RowNum
GROUP BY W1.RowNum, W1.wait_type
HAVING SUM (W2.Percentage) - MAX (W1.Percentage) < 99 -- percentage threshold
OPTION (RECOMPILE);
------

-- Cumulative wait stats are not as useful on an idle instance that is not under load or performance pressure

-- SQL Server Wait Types Library (Paul Randal)
-- https://www.sqlskills.com/help/waits/

-- The SQL Server Wait Type Repository
-- http://blogs.msdn.com/b/psssql/archive/2009/11/03/the-sql-server-wait-type-repository.aspx

-- Wait statistics, or please tell me where it hurts
-- http://www.sqlskills.com/blogs/paul/wait-statistics-or-please-tell-me-where-it-hurts/

-- SQL Server 2005 Performance Tuning using the Waits and Queues
-- http://technet.microsoft.com/en-us/library/cc966413.aspx

-- sys.dm_os_wait_stats (Transact-SQL)
-- http://msdn.microsoft.com/en-us/library/ms179984(v=sql.120).aspx



-- Get a count of SQL connections by IP address (Query 38) (Connection Counts by IP Address)
SELECT ec.client_net_address, es.[program_name], es.[host_name], es.login_name, 
COUNT(ec.session_id) AS [connection count] 
FROM sys.dm_exec_sessions AS es WITH (NOLOCK) 
INNER JOIN sys.dm_exec_connections AS ec WITH (NOLOCK) 
ON es.session_id = ec.session_id 
GROUP BY ec.client_net_address, es.[program_name], es.[host_name], es.login_name  
ORDER BY ec.client_net_address, es.[program_name] OPTION (RECOMPILE);
------

-- This helps you figure where your database load is coming from
-- and verifies connectivity from other machines

-- Solving Connectivity errors to SQL Server
-- https://bit.ly/2EgzoD0



-- Get Average Task Counts (run multiple times)  (Query 39) (Avg Task Counts)
SELECT AVG(current_tasks_count) AS [Avg Task Count], 
AVG(work_queue_count) AS [Avg Work Queue Count],
AVG(runnable_tasks_count) AS [Avg Runnable Task Count],
AVG(pending_disk_io_count) AS [Avg Pending DiskIO Count]
FROM sys.dm_os_schedulers WITH (NOLOCK)
WHERE scheduler_id < 255 OPTION (RECOMPILE);
------

-- Sustained values above 10 suggest further investigation in that area
-- High Avg Task Counts are often caused by blocking/deadlocking or other resource contention

-- Sustained values above 1 suggest further investigation in that area
-- High Avg Runnable Task Counts are a good sign of CPU pressure
-- High Avg Pending DiskIO Counts are a sign of disk pressure

-- How to Do Some Very Basic SQL Server Monitoring
-- https://bit.ly/2q3Btgt



-- Detect blocking (run multiple times)  (Query 40) (Detect Blocking)
SELECT t1.resource_type AS [lock type], DB_NAME(resource_database_id) AS [database],
t1.resource_associated_entity_id AS [blk object],t1.request_mode AS [lock req],  -- lock requested
t1.request_session_id AS [waiter sid], t2.wait_duration_ms AS [wait time],       -- spid of waiter  
(SELECT [text] FROM sys.dm_exec_requests AS r WITH (NOLOCK)                      -- get sql for waiter
CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) 
WHERE r.session_id = t1.request_session_id) AS [waiter_batch],
(SELECT SUBSTRING(qt.[text],r.statement_start_offset/2, 
    (CASE WHEN r.statement_end_offset = -1 
    THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2 
    ELSE r.statement_end_offset END - r.statement_start_offset)/2) 
FROM sys.dm_exec_requests AS r WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) AS qt
WHERE r.session_id = t1.request_session_id) AS [waiter_stmt],					-- statement blocked
t2.blocking_session_id AS [blocker sid],										-- spid of blocker
(SELECT [text] FROM sys.sysprocesses AS p										-- get sql for blocker
CROSS APPLY sys.dm_exec_sql_text(p.[sql_handle]) 
WHERE p.spid = t2.blocking_session_id) AS [blocker_batch]
FROM sys.dm_tran_locks AS t1 WITH (NOLOCK)
INNER JOIN sys.dm_os_waiting_tasks AS t2 WITH (NOLOCK)
ON t1.lock_owner_address = t2.resource_address OPTION (RECOMPILE);
------

-- Helps troubleshoot blocking and deadlocking issues
-- The results will change from second to second on a busy system
-- You should run this query multiple times when you see signs of blocking



-- Get CPU Utilization History for last 256 minutes (in one minute intervals)  (Query 41) (CPU Utilization History)
DECLARE @ts_now bigint = (SELECT cpu_ticks/(cpu_ticks/ms_ticks) FROM sys.dm_os_sys_info WITH (NOLOCK)); 

SELECT TOP(256) SQLProcessUtilization AS [SQL Server Process CPU Utilization], 
               SystemIdle AS [System Idle Process], 
               100 - SystemIdle - SQLProcessUtilization AS [Other Process CPU Utilization], 
               DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) AS [Event Time] 
FROM (SELECT record.value('(./Record/@id)[1]', 'int') AS record_id, 
			record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') 
			AS [SystemIdle], 
			record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int') 
			AS [SQLProcessUtilization], [timestamp] 
	  FROM (SELECT [timestamp], CONVERT(xml, record) AS [record] 
			FROM sys.dm_os_ring_buffers WITH (NOLOCK)
			WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR' 
			AND record LIKE N'%<SystemHealth>%') AS x) AS y 
ORDER BY record_id DESC OPTION (RECOMPILE);
------

-- Look at the trend over the entire period 
-- Also look at high sustained 'Other Process' CPU Utilization values
-- Note: This query sometimes gives inaccurate results (negative values)
-- on high core count (> 64 cores) systems


-- Get top total worker time queries for entire instance (Query 42) (Top Worker Time Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], 
REPLACE(REPLACE(LEFT(t.[text], 255), CHAR(10),''), CHAR(13),'') AS [Short Query Text],  
qs.total_worker_time AS [Total Worker Time], qs.min_worker_time AS [Min Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.max_worker_time AS [Max Worker Time], 
qs.min_elapsed_time AS [Min Elapsed Time], 
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time], 
qs.max_elapsed_time AS [Max Elapsed Time],
qs.min_logical_reads AS [Min Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.max_logical_reads AS [Max Logical Reads], 
qs.execution_count AS [Execution Count],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
qs.creation_time AS [Creation Time]
--,t.[text] AS [Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
ORDER BY qs.total_worker_time DESC OPTION (RECOMPILE);
------


-- Helps you find the most expensive queries from a CPU perspective across the entire instance
-- Can also help track down parameter sniffing issues



-- Page Life Expectancy (PLE) value for each NUMA node in current instance  (Query 43) (PLE by NUMA Node)
SELECT @@SERVERNAME AS [Server Name], RTRIM([object_name]) AS [Object Name], instance_name, cntr_value AS [Page Life Expectancy]
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Buffer Node%' -- Handles named instances
AND counter_name = N'Page life expectancy' OPTION (RECOMPILE);
------

-- PLE is a good measurement of internal memory pressure
-- Higher PLE is better. Watch the trend over time, not the absolute value
-- This will only return one row for non-NUMA systems

-- Page Life Expectancy isn�t what you think�
-- https://bit.ly/2EgynLa


-- Memory Grants Pending value for current instance  (Query 44) (Memory Grants Pending)
SELECT @@SERVERNAME AS [Server Name], RTRIM([object_name]) AS [Object Name], cntr_value AS [Memory Grants Pending]                                                                                                       
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Memory Manager%' -- Handles named instances
AND counter_name = N'Memory Grants Pending' OPTION (RECOMPILE);
------

-- Run multiple times, and run periodically if you suspect you are under memory pressure
-- Memory Grants Pending above zero for a sustained period is a very strong indicator of internal memory pressure


-- Memory Clerk Usage for instance  (Query 45) (Memory Clerk Usage)
-- Look for high value for CACHESTORE_SQLCP (Ad-hoc query plans)
SELECT TOP(10) mc.[type] AS [Memory Clerk Type], 
       CAST((SUM(mc.pages_kb)/1024.0) AS DECIMAL (15,2)) AS [Memory Usage (MB)] 
FROM sys.dm_os_memory_clerks AS mc WITH (NOLOCK)
GROUP BY mc.[type]  
ORDER BY SUM(mc.pages_kb) DESC OPTION (RECOMPILE);
------

-- MEMORYCLERK_SQLBUFFERPOOL was new for SQL Server 2012. It should be your highest consumer of memory

-- CACHESTORE_SQLCP  SQL Plans         
-- These are cached SQL statements or batches that aren't in stored procedures, functions and triggers
-- Watch out for high values for CACHESTORE_SQLCP
-- Enabling 'optimize for ad hoc workloads' at the instance level can help reduce this
-- Running DBCC FREESYSTEMCACHE ('SQL Plans') periodically may be required to better control this

-- CACHESTORE_OBJCP  Object Plans      
-- These are compiled plans for stored procedures, functions and triggers



-- Find single-use, ad-hoc and prepared queries that are bloating the plan cache  (Query 46) (Ad hoc Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], t.[text] AS [Query Text], 
cp.objtype AS [Object Type], cp.cacheobjtype AS [Cache Object Type],  
cp.size_in_bytes/1024 AS [Plan Size in KB]
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t
WHERE cp.cacheobjtype = N'Compiled Plan' 
AND cp.objtype IN (N'Adhoc', N'Prepared') 
AND cp.usecounts = 1
ORDER BY cp.size_in_bytes DESC, DB_NAME(t.[dbid]) OPTION (RECOMPILE);
------

-- Gives you the text, type and size of single-use ad-hoc and prepared queries that waste space in the plan cache
-- Enabling 'optimize for ad hoc workloads' for the instance can help (SQL Server 2008 and above only)
-- Running DBCC FREESYSTEMCACHE ('SQL Plans') periodically may be required to better control this
-- Enabling forced parameterization for the database can help, but test first!

-- Plan cache, adhoc workloads and clearing the single-use plan cache bloat
-- https://www.sqlskills.com/blogs/kimberly/plan-cache-adhoc-workloads-and-clearing-the-single-use-plan-cache-bloat/


-- Get top total logical reads queries for entire instance (Query 47) (Top Logical Reads Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name],
REPLACE(REPLACE(LEFT(t.[text], 255), CHAR(10),''), CHAR(13),'') AS [Short Query Text], 
qs.total_logical_reads AS [Total Logical Reads],
qs.min_logical_reads AS [Min Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.max_logical_reads AS [Max Logical Reads],   
qs.min_worker_time AS [Min Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.max_worker_time AS [Max Worker Time], 
qs.min_elapsed_time AS [Min Elapsed Time], 
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time], 
qs.max_elapsed_time AS [Max Elapsed Time],
qs.execution_count AS [Execution Count], 
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
qs.creation_time AS [Creation Time]
--,t.[text] AS [Complete Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
ORDER BY qs.total_logical_reads DESC OPTION (RECOMPILE);
------


-- Helps you find the most expensive queries from a memory perspective across the entire instance
-- Can also help track down parameter sniffing issues


-- Get top average elapsed time queries for entire instance (Query 48) (Top Avg Elapsed Time Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], 
REPLACE(REPLACE(LEFT(t.[text], 255), CHAR(10),''), CHAR(13),'') AS [Short Query Text],  
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
qs.min_elapsed_time, qs.max_elapsed_time, qs.last_elapsed_time,
qs.execution_count AS [Execution Count],  
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads], 
qs.total_physical_reads/qs.execution_count AS [Avg Physical Reads], 
qs.total_worker_time/qs.execution_count AS [Avg Worker Time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
qs.creation_time AS [Creation Time]
--,t.[text] AS [Complete Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
ORDER BY qs.total_elapsed_time/qs.execution_count DESC OPTION (RECOMPILE);
------

-- Helps you find the highest average elapsed time queries across the entire instance
-- Can also help track down parameter sniffing issues




-- Database specific queries *****************************************************************

-- **** Please switch to a user database that you are interested in! *****
--USE YourDatabaseName; -- make sure to change to an actual database on your instance, not the master system database
--GO

-- Individual File Sizes and space available for current database  (Query 49) (File Sizes and Space)
SELECT f.name AS [File Name] , f.physical_name AS [Physical Name], 
CAST((f.size/128.0) AS DECIMAL(15,2)) AS [Total Size in MB],
CAST(f.size/128.0 - CAST(FILEPROPERTY(f.name, 'SpaceUsed') AS int)/128.0 AS DECIMAL(15,2)) 
AS [Available Space In MB], f.[file_id], fg.name AS [Filegroup Name],
f.is_percent_growth, f.growth, fg.is_default, fg.is_read_only
FROM sys.database_files AS f WITH (NOLOCK) 
LEFT OUTER JOIN sys.filegroups AS fg WITH (NOLOCK)
ON f.data_space_id = fg.data_space_id
ORDER BY f.[file_id] OPTION (RECOMPILE);
------

-- Look at how large and how full the files are and where they are located
-- Make sure the transaction log is not full!!


-- I/O Statistics by file for the current database  (Query 50) (IO Stats By File)
SELECT DB_NAME(DB_ID()) AS [Database Name], df.name AS [Logical Name], vfs.[file_id], df.type_desc,
df.physical_name AS [Physical Name], CAST(vfs.size_on_disk_bytes/1048576.0 AS DECIMAL(16, 2)) AS [Size on Disk (MB)],
vfs.num_of_reads, vfs.num_of_writes, vfs.io_stall_read_ms, vfs.io_stall_write_ms,
CAST(100. * vfs.io_stall_read_ms/(vfs.io_stall_read_ms + vfs.io_stall_write_ms) AS DECIMAL(16,1)) AS [IO Stall Reads Pct],
CAST(100. * vfs.io_stall_write_ms/(vfs.io_stall_write_ms + vfs.io_stall_read_ms) AS DECIMAL(16,1)) AS [IO Stall Writes Pct],
(vfs.num_of_reads + vfs.num_of_writes) AS [Writes + Reads], 
CAST(vfs.num_of_bytes_read/1048576.0 AS DECIMAL(16, 2)) AS [MB Read], 
CAST(vfs.num_of_bytes_written/1048576.0 AS DECIMAL(16, 2)) AS [MB Written],
CAST(100. * vfs.num_of_reads/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(16,1)) AS [# Reads Pct],
CAST(100. * vfs.num_of_writes/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(16,1)) AS [# Write Pct],
CAST(100. * vfs.num_of_bytes_read/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(16,1)) AS [Read Bytes Pct],
CAST(100. * vfs.num_of_bytes_written/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(16,1)) AS [Written Bytes Pct]
FROM sys.dm_io_virtual_file_stats(DB_ID(), NULL) AS vfs
INNER JOIN sys.database_files AS df WITH (NOLOCK)
ON vfs.[file_id]= df.[file_id] OPTION (RECOMPILE);
------

-- This helps you characterize your workload better from an I/O perspective for this database
-- It helps you determine whether you has an OLTP or DW/DSS type of workload



-- Get most frequently executed queries for this database (Query 51) (Query Execution Counts)
SELECT TOP(50) LEFT(t.[text], 50) AS [Short Query Text], qs.execution_count AS [Execution Count],
qs.total_logical_reads AS [Total Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.total_worker_time AS [Total Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.total_elapsed_time AS [Total Elapsed Time],
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
qs.creation_time AS [Creation Time]
--,t.[text] AS [Complete Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
WHERE t.dbid = DB_ID()
ORDER BY qs.execution_count DESC OPTION (RECOMPILE);
------


-- Queries 50 through 55 are the "Bad Man List" for stored procedures
-- Top Cached SPs By Execution Count (Query 52) (SP Execution Counts)
SELECT TOP(100) p.name AS [SP Name], qs.execution_count AS [Execution Count],
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time],    
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.execution_count DESC OPTION (RECOMPILE);
------

-- Tells you which cached stored procedures are called the most often
-- This helps you characterize and baseline your workload


-- Top Cached SPs By Avg Elapsed Time (Query 53) (SP Avg Elapsed Time)
SELECT TOP(25) p.name AS [SP Name], qs.min_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time], 
qs.max_elapsed_time, qs.last_elapsed_time, qs.total_elapsed_time, qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute], 
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], 
qs.total_worker_time AS [TotalWorkerTime],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY avg_elapsed_time DESC OPTION (RECOMPILE);
------

-- This helps you find high average elapsed time cached stored procedures that
-- may be easy to optimize with standard query tuning techniques



-- Top Cached SPs By Total Worker time. Worker time relates to CPU cost  (Query 54) (SP Worker Time)
SELECT TOP(25) p.name AS [SP Name], qs.total_worker_time AS [TotalWorkerTime], 
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.total_worker_time DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a CPU perspective
-- You should look at this if you see signs of CPU pressure


-- Top Cached SPs By Total Logical Reads. Logical reads relate to memory pressure  (Query 55) (SP Logical Reads)
SELECT TOP(25) p.name AS [SP Name], qs.total_logical_reads AS [TotalLogicalReads], 
qs.total_logical_reads/qs.execution_count AS [AvgLogicalReads],qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute], 
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.total_logical_reads DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a memory perspective
-- You should look at this if you see signs of memory pressure


-- Top Cached SPs By Total Physical Reads. Physical reads relate to disk read I/O pressure  (Query 56) (SP Physical Reads)
SELECT TOP(25) p.name AS [SP Name],qs.total_physical_reads AS [TotalPhysicalReads], 
qs.total_physical_reads/qs.execution_count AS [AvgPhysicalReads], qs.execution_count, 
qs.total_logical_reads,qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan 
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND qs.total_physical_reads > 0
ORDER BY qs.total_physical_reads DESC, qs.total_logical_reads DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a read I/O perspective
-- You should look at this if you see signs of I/O pressure or of memory pressure


       
-- Top Cached SPs By Total Logical Writes (Query 57) (SP Logical Writes)
-- Logical writes relate to both memory and disk I/O pressure 
SELECT TOP(25) p.name AS [SP Name], qs.total_logical_writes AS [TotalLogicalWrites], 
qs.total_logical_writes/qs.execution_count AS [AvgLogicalWrites], qs.execution_count,
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan 
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND qs.total_logical_writes > 0
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.total_logical_writes DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a write I/O perspective
-- You should look at this if you see signs of I/O pressure or of memory pressure


-- Lists the top statements by average input/output usage for the current database  (Query 58) (Top IO Statements)
SELECT TOP(50) OBJECT_NAME(qt.objectid, dbid) AS [SP Name],
(qs.total_logical_reads + qs.total_logical_writes) /qs.execution_count AS [Avg IO], qs.execution_count AS [Execution Count],
SUBSTRING(qt.[text],qs.statement_start_offset/2, 
	(CASE 
		WHEN qs.statement_end_offset = -1 
	 THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2 
		ELSE qs.statement_end_offset 
	 END - qs.statement_start_offset)/2) AS [Query Text]	
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
WHERE qt.[dbid] = DB_ID()
ORDER BY [Avg IO] DESC OPTION (RECOMPILE);
------

-- Helps you find the most expensive statements for I/O by SP



-- Possible Bad NC Indexes (writes > reads)  (Query 59) (Bad NC Indexes)
SELECT OBJECT_NAME(s.[object_id]) AS [Table Name], i.name AS [Index Name], i.index_id, 
i.is_disabled, i.is_hypothetical, i.has_filter, i.fill_factor,
s.user_updates AS [Total Writes], s.user_seeks + s.user_scans + s.user_lookups AS [Total Reads],
s.user_updates - (s.user_seeks + s.user_scans + s.user_lookups) AS [Difference]
FROM sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON s.[object_id] = i.[object_id]
AND i.index_id = s.index_id
WHERE OBJECTPROPERTY(s.[object_id],'IsUserTable') = 1
AND s.database_id = DB_ID()
AND s.user_updates > (s.user_seeks + s.user_scans + s.user_lookups)
AND i.index_id > 1 AND i.[type_desc] = N'NONCLUSTERED'
AND i.is_primary_key = 0 AND i.is_unique_constraint = 0 AND i.is_unique = 0
ORDER BY [Difference] DESC, [Total Writes] DESC, [Total Reads] ASC OPTION (RECOMPILE);
------

-- Look for indexes with high numbers of writes and zero or very low numbers of reads
-- Consider your complete workload, and how long your instance has been running
-- Investigate further before dropping an index!


-- Missing Indexes for current database by Index Advantage  (Query 60) (Missing Indexes)
SELECT CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage], 
migs.last_user_seek, mid.[statement] AS [Database.Schema.Table],
COUNT(1) OVER(PARTITION BY mid.[statement]) AS [missing_indexes_for_table],
COUNT(1) OVER(PARTITION BY mid.[statement], equality_columns) AS [similar_missing_indexes_for_table],
mid.equality_columns, mid.inequality_columns, mid.included_columns,
migs.unique_compiles, migs.user_seeks, 
CONVERT(decimal(18,2), migs.avg_total_user_cost) AS [avg_total_user_cost], migs.avg_user_impact,
OBJECT_NAME(mid.[object_id]) AS [Table Name], p.rows AS [Table Rows]
FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)
INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)
ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)
ON mig.index_handle = mid.index_handle
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON p.[object_id] = mid.[object_id]
WHERE mid.database_id = DB_ID()
AND p.index_id < 2 
ORDER BY index_advantage DESC OPTION (RECOMPILE);
------

-- Look at index advantage, last user seek time, number of user seeks to help determine source and importance
-- SQL Server is overly eager to add included columns, so beware
-- Do not just blindly add indexes that show up from this query!!!


-- Find missing index warnings for cached plans in the current database  (Query 61) (Missing Index Warnings)
-- Note: This query could take some time on a busy instance
SELECT TOP(25) OBJECT_NAME(objectid) AS [ObjectName], 
               cp.objtype, cp.usecounts, cp.size_in_bytes, query_plan
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) AS qp
WHERE CAST(query_plan AS NVARCHAR(MAX)) LIKE N'%MissingIndex%'
AND dbid = DB_ID()
ORDER BY cp.usecounts DESC OPTION (RECOMPILE);
------

-- Helps you connect missing indexes to specific stored procedures or queries
-- This can help you decide whether to add them or not


-- Breaks down buffers used by current database by object (table, index) in the buffer cache  (Query 62) (Buffer Usage)
-- Note: This query could take some time on a busy instance
SELECT OBJECT_NAME(p.[object_id]) AS [Object Name], p.index_id, 
CAST(COUNT(*)/128.0 AS DECIMAL(10, 2)) AS [Buffer size(MB)],  
COUNT(*) AS [BufferCount], p.[Rows] AS [Row Count],
p.data_compression_desc AS [Compression Type]
FROM sys.allocation_units AS a WITH (NOLOCK)
INNER JOIN sys.dm_os_buffer_descriptors AS b WITH (NOLOCK)
ON a.allocation_unit_id = b.allocation_unit_id
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON a.container_id = p.hobt_id
WHERE b.database_id = CONVERT(int, DB_ID())
AND p.[object_id] > 100
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'plan_%'
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'sys%'
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'xml_index_nodes%'
GROUP BY p.[object_id], p.index_id, p.data_compression_desc, p.[Rows]
ORDER BY [BufferCount] DESC OPTION (RECOMPILE);
------

-- Tells you what tables and indexes are using the most memory in the buffer cache
-- It can help identify possible candidates for data compression


-- Get Table names, row counts, and compression status for clustered index or heap  (Query 63) (Table Sizes)
SELECT SCHEMA_NAME(o.Schema_ID) AS [Schema Name], OBJECT_NAME(p.object_id) AS [ObjectName], 
SUM(p.Rows) AS [RowCount], data_compression_desc AS [CompressionType]
FROM sys.partitions AS p WITH (NOLOCK)
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON p.object_id = o.object_id
WHERE index_id < 2 --ignore the partitions from the non-clustered index if any
AND OBJECT_NAME(p.object_id) NOT LIKE N'sys%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'spt_%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'queue_%' 
AND OBJECT_NAME(p.object_id) NOT LIKE N'filestream_tombstone%' 
AND OBJECT_NAME(p.object_id) NOT LIKE N'fulltext%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'ifts_comp_fragment%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'filetable_updates%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'xml_index_nodes%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'sqlagent_job%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'plan_persist%'
GROUP BY  SCHEMA_NAME(o.Schema_ID), p.object_id, data_compression_desc
ORDER BY SUM(p.Rows) DESC OPTION (RECOMPILE);
------

-- Gives you an idea of table sizes, and possible data compression opportunities



-- Get some key table properties (Query 64) (Table Properties)
SELECT OBJECT_NAME(t.[object_id]) AS [ObjectName], p.[rows] AS [Table Rows], p.index_id, 
       p.data_compression_desc AS [Index Data Compression],
       t.create_date, t.lock_on_bulk_load, t.is_replicated, t.has_replication_filter, 
       t.is_tracked_by_cdc, t.lock_escalation_desc, t.is_filetable
FROM sys.tables AS t WITH (NOLOCK)
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON t.[object_id] = p.[object_id]
WHERE OBJECT_NAME(t.[object_id]) NOT LIKE N'sys%'
ORDER BY OBJECT_NAME(t.[object_id]), p.index_id OPTION (RECOMPILE);
------

-- Gives you some good information about your tables



-- When were Statistics last updated on all indexes?  (Query 65) (Statistics Update)
SELECT SCHEMA_NAME(o.Schema_ID) + N'.' + o.NAME AS [Object Name], o.type_desc AS [Object Type],
      i.name AS [Index Name], STATS_DATE(i.[object_id], i.index_id) AS [Statistics Date], 
      s.auto_created, s.no_recompute, s.user_created, s.is_temporary,
	  st.row_count, st.used_page_count
FROM sys.objects AS o WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON o.[object_id] = i.[object_id]
INNER JOIN sys.stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id] 
AND i.index_id = s.stats_id
INNER JOIN sys.dm_db_partition_stats AS st WITH (NOLOCK)
ON o.[object_id] = st.[object_id]
AND i.[index_id] = st.[index_id]
WHERE o.[type] IN ('U', 'V')
AND st.row_count > 0
ORDER BY STATS_DATE(i.[object_id], i.index_id) DESC OPTION (RECOMPILE);
------  

-- Helps discover possible problems with out-of-date statistics
-- Also gives you an idea which indexes are the most active

-- sys.stats (Transact-SQL)
-- https://msdn.microsoft.com/en-us/library/ms177623.aspx



-- Look at most frequently modified indexes and statistics (Query 66) (Volatile Indexes)
SELECT o.[name] AS [Object Name], o.[object_id], o.[type_desc], s.[name] AS [Statistics Name], 
       s.stats_id, s.no_recompute, s.auto_created, s.is_temporary,
	   sp.modification_counter, sp.[rows], sp.rows_sampled, sp.last_updated
FROM sys.objects AS o WITH (NOLOCK)
INNER JOIN sys.stats AS s WITH (NOLOCK)
ON s.object_id = o.object_id
CROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) AS sp
WHERE o.[type_desc] NOT IN (N'SYSTEM_TABLE', N'INTERNAL_TABLE')
AND sp.modification_counter > 0
ORDER BY sp.modification_counter DESC, o.name OPTION (RECOMPILE);
------

-- This helps you understand your workload and make better decisions about 
-- things like data compression and adding new indexes to a table



-- Get fragmentation info for all indexes above a certain size in the current database  (Query 67) (Index Fragmentation)
-- Note: This query could take some time on a very large database
SELECT DB_NAME(ps.database_id) AS [Database Name], SCHEMA_NAME(o.[schema_id]) AS [Schema Name],
OBJECT_NAME(ps.OBJECT_ID) AS [Object Name], i.[name] AS [Index Name], ps.index_id, 
ps.index_type_desc, ps.avg_fragmentation_in_percent, 
ps.fragment_count, ps.page_count, i.fill_factor, i.has_filter, 
i.filter_definition, i.[allow_page_locks]
FROM sys.dm_db_index_physical_stats(DB_ID(),NULL, NULL, NULL , N'LIMITED') AS ps
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ps.[object_id] = i.[object_id] 
AND ps.index_id = i.index_id
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON i.[object_id] = o.[object_id]
WHERE ps.database_id = DB_ID()
AND ps.page_count > 2500
ORDER BY ps.avg_fragmentation_in_percent DESC OPTION (RECOMPILE);
------

-- Helps determine whether you have framentation in your relational indexes
-- and how effective your index maintenance strategy is


--- Index Read/Write stats (all tables in current DB) ordered by Reads  (Query 68) (Overall Index Usage - Reads)
SELECT OBJECT_NAME(i.[object_id]) AS [ObjectName], i.[name] AS [IndexName], i.index_id, 
       s.user_seeks, s.user_scans, s.user_lookups,
	   s.user_seeks + s.user_scans + s.user_lookups AS [Total Reads], 
	   s.user_updates AS [Writes],  
	   i.[type_desc] AS [Index Type], i.fill_factor AS [Fill Factor], i.has_filter, i.filter_definition, 
	   s.last_user_scan, s.last_user_lookup, s.last_user_seek
FROM sys.indexes AS i WITH (NOLOCK)
LEFT OUTER JOIN sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id]
AND i.index_id = s.index_id
AND s.database_id = DB_ID()
WHERE OBJECTPROPERTY(i.[object_id],'IsUserTable') = 1
ORDER BY s.user_seeks + s.user_scans + s.user_lookups DESC OPTION (RECOMPILE); -- Order by reads
------

-- Show which indexes in the current database are most active for Reads


--- Index Read/Write stats (all tables in current DB) ordered by Writes  (Query 69) (Overall Index Usage - Writes)
SELECT OBJECT_NAME(i.[object_id]) AS [ObjectName], i.[name] AS [IndexName], i.index_id,
	   s.user_updates AS [Writes], s.user_seeks + s.user_scans + s.user_lookups AS [Total Reads], 
	   i.[type_desc] AS [Index Type], i.fill_factor AS [Fill Factor], i.has_filter, i.filter_definition,
	   s.last_system_update, s.last_user_update
FROM sys.indexes AS i WITH (NOLOCK)
LEFT OUTER JOIN sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id]
AND i.index_id = s.index_id
AND s.database_id = DB_ID()
WHERE OBJECTPROPERTY(i.[object_id],'IsUserTable') = 1
ORDER BY s.user_updates DESC OPTION (RECOMPILE);						 -- Order by writes
------

-- Show which indexes in the current database are most active for Writes


-- Get lock waits for current database (Query 70) (Lock Waits)
SELECT o.name AS [table_name], i.name AS [index_name], ios.index_id, ios.partition_number,
		SUM(ios.row_lock_wait_count) AS [total_row_lock_waits], 
		SUM(ios.row_lock_wait_in_ms) AS [total_row_lock_wait_in_ms],
		SUM(ios.page_lock_wait_count) AS [total_page_lock_waits],
		SUM(ios.page_lock_wait_in_ms) AS [total_page_lock_wait_in_ms],
		SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) AS [total_lock_wait_in_ms]
FROM sys.dm_db_index_operational_stats(DB_ID(), NULL, NULL, NULL) AS ios
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON ios.[object_id] = o.[object_id]
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ios.[object_id] = i.[object_id] 
AND ios.index_id = i.index_id
WHERE o.[object_id] > 100
GROUP BY o.name, i.name, ios.index_id, ios.partition_number
HAVING SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) > 0
ORDER BY total_lock_wait_in_ms DESC OPTION (RECOMPILE);
------

-- This query is helpful for troubleshooting blocking and deadlocking issues


-- Look at recent Full backups for the current database (Query 71) (Recent Full Backups)
SELECT TOP (30) bs.machine_name, bs.server_name, bs.database_name AS [Database Name], bs.recovery_model,
CONVERT (BIGINT, bs.backup_size / 1048576 ) AS [Uncompressed Backup Size (MB)],
CONVERT (BIGINT, bs.compressed_backup_size / 1048576 ) AS [Compressed Backup Size (MB)],
CONVERT (NUMERIC (20,2), (CONVERT (FLOAT, bs.backup_size) /
CONVERT (FLOAT, bs.compressed_backup_size))) AS [Compression Ratio], bs.has_backup_checksums, bs.is_copy_only,
DATEDIFF (SECOND, bs.backup_start_date, bs.backup_finish_date) AS [Backup Elapsed Time (sec)],
bs.backup_finish_date AS [Backup Finish Date], bmf.physical_device_name AS [Backup Location], bmf.physical_block_size
FROM msdb.dbo.backupset AS bs WITH (NOLOCK)
INNER JOIN msdb.dbo.backupmediafamily AS bmf WITH (NOLOCK)
ON bs.media_set_id = bmf.media_set_id  
WHERE bs.database_name = DB_NAME(DB_ID())
AND bs.[type] = 'D' -- Change to L if you want Log backups
ORDER BY bs.backup_finish_date DESC OPTION (RECOMPILE);
------

-- Are your backup sizes and times changing over time?
-- Are you using backup compression?
-- Are you using backup checksums?
-- Are you doing copy_only backups?
-- Have you done any backup tuning with striped backups, or changing the parameters of the backup command?


-- These four Pluralsight Courses go into more detail about how to run these queries and interpret the results

-- SQL Server 2017: Diagnosing Configuration Issues with DMVs
-- https://bit.ly/2MSUDUL

-- SQL Server 2014 DMV Diagnostic Queries � Part 1 
-- https://bit.ly/2plxCer

-- SQL Server 2014 DMV Diagnostic Queries � Part 2
-- https://bit.ly/2IuJpzI

-- SQL Server 2014 DMV Diagnostic Queries � Part 3
-- https://bit.ly/2FIlCPb



-- Sign up for Microsoft Visual Studio Dev Essentials and get a free three month pass to Pluralsight

-- Microsoft Visual Studio Dev Essentials
-- http://bit.ly/1q6xbDL


-- Sign up for Microsoft Azure Essentials and get lots of free Azure usage credits, MCP exam voucher, three month Pluralsight subscription

-- Microsoft Azure Essentials
-- https://bit.ly/2JMWe8x


-- August 2017 blog series about upgrading and migrating to SQL Server 2016/2017
-- https://bit.ly/2ftKVrX
tools\dbatools\bin\diagnosticquery\SQLServerDiagnosticQueries_2014_201811.sql

-- SQL Server 2014 Diagnostic Information Queries
-- Glenn Berry 
-- Last Modified: January 7, 2019
-- https://www.sqlskills.com/blogs/glenn/
-- http://sqlserverperformance.wordpress.com/
-- Twitter: GlennAlanBerry

-- Please listen to my Pluralsight courses
-- https://www.pluralsight.com/author/glenn-berry

-- If you want to find all of our SQLskills SQL101 blog posts, check out https://www.sqlskills.com/help/sql101/


-- Please make sure you are using the correct version of these diagnostic queries for your version of SQL Server!


-- If you like PowerShell, there is a very useful community solution for running these queries in an automated fashion
-- https://dbatools.io/

-- Invoke-DbaDiagnosticQuery
-- https://dbatools.io/functions/invoke-dbadiagnosticquery/


--******************************************************************************
--*   Copyright (C) 2019 Glenn Berry, SQLskills.com
--*   All rights reserved. 
--*
--*   For more scripts and sample code, check out 
--*      https://www.sqlskills.com/blogs/glenn
--*
--*   You may alter this code for your own *non-commercial* purposes. You may
--*   republish altered code as long as you include this copyright and give due credit. 
--*
--*
--*   THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF 
--*   ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED 
--*   TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
--*   PARTICULAR PURPOSE. 
--*
--******************************************************************************

-- Check the major product version to see if it is SQL Server 2014 CTP2 or greater
IF NOT EXISTS (SELECT * WHERE CONVERT(varchar(128), SERVERPROPERTY('ProductVersion')) LIKE '12%')
	BEGIN
		DECLARE @ProductVersion varchar(128) = CONVERT(varchar(128), SERVERPROPERTY('ProductVersion'));
		RAISERROR ('Script does not match the ProductVersion [%s] of this instance. Many of these queries may not work on this version.' , 18 , 16 , @ProductVersion);
	END
	ELSE
		PRINT N'You have the correct major version of SQL Server for this diagnostic information script';
	

-- Instance level queries *******************************

-- SQL and OS Version information for current instance  (Query 1) (Version Info)
SELECT @@SERVERNAME AS [Server Name], @@VERSION AS [SQL Server and OS Version Info];
------

-- SQL Server 2014 RTM Branch Builds						SQL Server 2014 SP1 Branch Builds						SQL Server 2014 SP2 Branch Builds					SQL Server 2014 SP23 Branch Builds				
-- Build			Description			Release Date		Build			Description		Release Date			Build			Description		Release Date		Build			Description		Release Date
-- 11.0.9120        CTP1				6/2/2013
-- 12.0.1524		CTP2				10/15/2013
-- 12.0.2000        RTM					4/1/2014
-- 12.0.2342        CU1                 4/21/2014
-- 12.0.2370        CU2                 6/27/2014
-- 12.0.2402		CU3					8/18/2014
-- 12.0.2430        CU4					10/21/2014
-- 12.0.2456		CU5					12/17/2014	---->	12.0.4100		SP1 RTM			5/4/2015
-- 12.0.2474		CU5 + COD HF		2/3/2015   
-- 12.0.2480		CU6					2/16/2015
-- 12.0.2495        CU7                 4/20/2015
-- 12.0.2546		CU8					6/19/2015			12.0.4416		SP1 CU1			6/19/2015
-- 12.0.2553		CU9					8/17/2015			12.0.4422		SP1 CU2			8/17/2015
-- 12.0.2556		CU10				10/19/2015          12.0.4427		SP1 CU3			10/19/2015
-- 12.0.2560		CU11				12/21/2015			12.0.4436		SP1 CU4			12/21/2015
-- 12.0.2564		CU12				2/22/2016			12.0.4439		SP1 CU5			2/22/2016
-- 12.0.2568		CU13				4/18/2016			12.0.4449		SP1 CU6			4/18/2016 (Deprecated)
--															12.0.4457		SP1 CU6 		5/30/2016 (Re-release)
-- 12.0.2569		CU14				6/20/2016			12.0.4459		SP1 CU7			6/20/2016 ----------->	12.0.5000		SP2 RTM			 7/11/2016
--															12.0.4468		SP1 CU8			8/15/2016				12.0.5511		SP2 CU1			 8/25/2016
--                                                          12.0.4474		SP1 CU9		    10/17/2016				12.0.5522		SP2 CU2			10/17/2016
--															12.0.4487		SP1 CU9 + HF	11/8/2016				12.0.5532		SP2 CU2 + HF     11/8/2016  
--                                                          12.0.4491       SP1 CU10		12/28/2016				12.0.5537		SP2 CU3			12/28/2016
--															12.0.4502		SP1 CU11		2/21/2017				12.0.5540		SP2 CU4			 2/21/2017
--															12.0.4511		SP1 CU12        4/17/2017				12.0.5546		SP2 CU5			 4/17/2017
--															12.0.4522		SP1	CU13		7/17/2017				12.0.5552		SP2 CU6			 7/17/2017
--																													12.0.5556		SP2 CU7			 8/28/2017
--																													12.0.5557		SP2 CU8			10/16/2017
--																													12.0.5563		SP2 CU9			12/18/2017
--																													12.0.5571		SP2 CU10		 1/16/2018
--                                                                                                                  12.0.5579		SP2 CU11		 3/19/2018
--																													12.0.5589		SP2 CU12		 6/18/2018
--																													12.0.5590		SP2 CU13		 8/27/2018
--																													12.0.5600		SP2 CU14	    10/15/2018
--																																										12.0.6024	SP3 RTM		10/30/2018
--																													12.0.5605		SP2 CU15		12/12/2018 ---->	12.0.6205	SP3 CU1	    12/12/2018	    	



-- How to determine the version, edition and update level of SQL Server and its components 
-- https://bit.ly/2oAjKgW	

-- SQL Server 2014 build versions
-- https://bit.ly/2HpmYOG

-- Where to find information about the latest SQL Server builds
-- https://bit.ly/2IGHbfY

-- Recommended updates and configuration options for SQL Server 2012 and SQL Server 2014 used with high-performance workloads
-- https://bit.ly/2Hy3zIZ

-- Performance and Stability Related Fixes in Post-SQL Server 2014 RTM Builds
-- https://bit.ly/2Hx50HU

-- Performance and Stability Related Fixes in Post-SQL Server 2014 SP1 Builds
-- https://bit.ly/2GWLx6a

-- Performance and Stability Related Fixes in Post-SQL Server 2014 SP2 Builds
-- https://bit.ly/2iJ9G4N

-- Performance and Stability Related Fixes in Post-SQL Server 2014 SP3 Builds
-- https://bit.ly/2PRGTWS

-- Announcing updates to the SQL Server Incremental Servicing Model (ISM)
-- https://bit.ly/1RzYITz

-- Update Center for Microsoft SQL Server
-- https://bit.ly/2pZptuQ

-- Download SQL Server Management Studio (SSMS)
-- https://bit.ly/1OcupT9

-- Download and install Azure Data Studio 
-- https://bit.ly/2vgke1A


-- Get socket, physical core and logical core count from the SQL Server Error log. (Query 2) (Core Counts)
-- This query might take a few seconds depending on the size of your error log
EXEC sys.xp_readerrorlog 0, 1, N'detected', N'socket';
------

-- This can help you determine the exact core counts used by SQL Server and whether HT is enabled or not
-- It can also help you confirm your SQL Server licensing model
-- Be on the lookout for this message "using 40 logical processors based on SQL Server licensing" 
-- (when you have more than 40 logical cores) which means grandfathered Server/CAL licensing
-- This query will return no results if your error log has been recycled since the instance was last started



-- Get selected server properties (Query 3) (Server Properties)
SELECT SERVERPROPERTY('MachineName') AS [MachineName], 
SERVERPROPERTY('ServerName') AS [ServerName],  
SERVERPROPERTY('InstanceName') AS [Instance], 
SERVERPROPERTY('IsClustered') AS [IsClustered], 
SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS [ComputerNamePhysicalNetBIOS], 
SERVERPROPERTY('Edition') AS [Edition], 
SERVERPROPERTY('ProductLevel') AS [ProductLevel],				-- What servicing branch (RTM/SP/CU)
SERVERPROPERTY('ProductUpdateLevel') AS [ProductUpdateLevel],	-- Within a servicing branch, what CU# is applied
SERVERPROPERTY('ProductVersion') AS [ProductVersion],
SERVERPROPERTY('ProductMajorVersion') AS [ProductMajorVersion], 
SERVERPROPERTY('ProductMinorVersion') AS [ProductMinorVersion], 
SERVERPROPERTY('ProductBuild') AS [ProductBuild], 
SERVERPROPERTY('ProductBuildType') AS [ProductBuildType],		      -- Is this a GDR or OD hotfix (NULL if on a CU build)
SERVERPROPERTY('ProductUpdateReference') AS [ProductUpdateReference], -- KB article number that is applicable for this build
SERVERPROPERTY('ProcessID') AS [ProcessID],
SERVERPROPERTY('Collation') AS [Collation], 
SERVERPROPERTY('IsFullTextInstalled') AS [IsFullTextInstalled], 
SERVERPROPERTY('IsIntegratedSecurityOnly') AS [IsIntegratedSecurityOnly],
SERVERPROPERTY('FilestreamConfiguredLevel') AS [FilestreamConfiguredLevel],
SERVERPROPERTY('IsHadrEnabled') AS [IsHadrEnabled], 
SERVERPROPERTY('HadrManagerStatus') AS [HadrManagerStatus],
SERVERPROPERTY('InstanceDefaultDataPath') AS [InstanceDefaultDataPath],
SERVERPROPERTY('InstanceDefaultLogPath') AS [InstanceDefaultLogPath],
SERVERPROPERTY('BuildClrVersion') AS [Build CLR Version],
SERVERPROPERTY('IsXTPSupported') AS [IsXTPSupported];
------

-- This gives you a lot of useful information about your instance of SQL Server,
-- such as the ProcessID for SQL Server and your collation
-- Note: Some columns will be NULL on older SQL Server builds

-- SERVERPROPERTY (Transact-SQL)
-- https://bit.ly/2eeaXeI


-- Get instance-level configuration values for instance  (Query 4) (Configuration Values)
SELECT name, value, value_in_use, minimum, maximum, [description], is_dynamic, is_advanced
FROM sys.configurations WITH (NOLOCK)
ORDER BY name OPTION (RECOMPILE);
------

-- Focus on these settings:
-- backup checksum default (should be 1)
-- backup compression default (should be 1 in most cases)
-- clr enabled (only enable if it is needed)
-- cost threshold for parallelism (depends on your workload)
-- lightweight pooling (should be zero)
-- max degree of parallelism (depends on your workload and hardware)
-- max server memory (MB) (set to an appropriate value, not the default)
-- optimize for ad hoc workloads (should be 1)
-- priority boost (should be zero)
-- remote admin connections (should be 1)


-- Returns a list of all global trace flags that are enabled (Query 5) (Global Trace Flags)
DBCC TRACESTATUS (-1);
------

-- If no global trace flags are enabled, no results will be returned.
-- It is very useful to know what global trace flags are currently enabled as part of the diagnostic process.

-- Common trace flags that should be enabled in most cases
-- TF 1117 - When growing a data file, grow all files at the same time so they remain the same size, reducing allocation contention points
--           https://bit.ly/2GY1kOl
-- 
-- TF 1118 - Helps alleviate allocation contention in tempdb, SQL Server allocates full extents to each database object, 
--           thereby eliminating the contention on SGAM pages (more important with older versions of SQL Server)
--           Recommendations to reduce allocation contention in SQL Server tempdb database
--           https://bit.ly/2GY1kOl

-- TF 2371 - Lowers auto update statistics threshold for large tables (on tables with more than 25,000 rows)
--           https://bit.ly/2HySkAg

-- TF 3226 - Supresses logging of successful database backup messages to the SQL Server Error Log
--           https://bit.ly/2p6MTjS

-- TF 3449 - Enables use of dirty page manager (SQL Server 2014 SP1 CU7 and later)
--			 https://bit.ly/2uj0h5M

-- TF 6533 - Spatial performance improvements in SQL Server 2012 and 2014
--           https://bit.ly/2v7C7ze

-- TF 6534 - Enables use of native code to improve performance with spatial data
--           https://bit.ly/2HrQUpU

-- TF 8079 - Enables automatic soft-NUMA on systems with eight or more physical cores per NUMA node (with SQL Server 2014 SP2)
--           https://bit.ly/29B7oR8

-- DBCC TRACEON - Trace Flags (Transact-SQL)
-- https://bit.ly/2FuSvPg



-- Returns status of instant file initialization (Query 6) (IFI Status)
EXEC sys.xp_readerrorlog 0, 1, N'Database Instant File Initialization';
------

-- Lets you determine whether Instant File Initialization (IFI) is enabled for the instance
-- This should be enabled in the vast majority of cases


-- Database Instant File Initialization
-- https://bit.ly/2nTX74y

-- Misconceptions around instant file initialization
-- https://bit.ly/2oBSKgZ



-- SQL Server Process Address space info  (Query 7) (Process Memory)
-- (shows whether locked pages is enabled, among other things)
SELECT physical_memory_in_use_kb/1024 AS [SQL Server Memory Usage (MB)],
	   locked_page_allocations_kb/1024 AS [SQL Server Locked Pages Allocation (MB)],
       large_page_allocations_kb/1024 AS [SQL Server Large Pages Allocation (MB)], 
	   page_fault_count, memory_utilization_percentage, available_commit_limit_kb, 
	   process_physical_memory_low, process_virtual_memory_low
FROM sys.dm_os_process_memory WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You want to see 0 for process_physical_memory_low
-- You want to see 0 for process_virtual_memory_low
-- This indicates that you are not under internal memory pressure
-- If locked_page_allocations_kb > 0, then LPIM is enabled

-- How to enable the "locked pages" feature in SQL Server 2012
-- https://bit.ly/2F5UjOA

-- Memory Management Architecture Guide
-- https://bit.ly/2JKkadC 



-- SQL Server Services information (Query 8) (SQL Server Services Info)
SELECT servicename, process_id, startup_type_desc, status_desc, 
last_startup_time, service_account, is_clustered, cluster_nodename, [filename]
FROM sys.dm_server_services WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Tells you the account being used for the SQL Server Service and the SQL Agent Service
-- Shows the process_id, when they were last started, and their current status
-- Also shows whether you are running on a failover cluster instance, and what node you are running on

-- sys.dm_server_services (Transact-SQL)
-- https://bit.ly/2oKa1Un


-- Last backup information by database  (Query 9) (Last Backup By Database)
SELECT ISNULL(d.[name], bs.[database_name]) AS [Database], d.recovery_model_desc AS [Recovery Model], 
       d.log_reuse_wait_desc AS [Log Reuse Wait Desc],
    MAX(CASE WHEN [type] = 'D' THEN bs.backup_finish_date ELSE NULL END) AS [Last Full Backup],
    MAX(CASE WHEN [type] = 'I' THEN bs.backup_finish_date ELSE NULL END) AS [Last Differential Backup],
    MAX(CASE WHEN [type] = 'L' THEN bs.backup_finish_date ELSE NULL END) AS [Last Log Backup]
FROM sys.databases AS d WITH (NOLOCK)
LEFT OUTER JOIN msdb.dbo.backupset AS bs WITH (NOLOCK)
ON bs.[database_name] = d.[name] 
AND bs.backup_finish_date > GETDATE()- 30
WHERE d.name <> N'tempdb'
GROUP BY ISNULL(d.[name], bs.[database_name]), d.recovery_model_desc, d.log_reuse_wait_desc, d.[name] 
ORDER BY d.recovery_model_desc, d.[name] OPTION (RECOMPILE);
------

-- This helps you spot runaway transaction logs and other issues with your backup schedule


-- Get SQL Server Agent jobs and Category information (Query 10) (SQL Server Agent Jobs)
SELECT sj.name AS [Job Name], sj.[description] AS [Job Description], SUSER_SNAME(sj.owner_sid) AS [Job Owner],
sj.date_created AS [Date Created], sj.[enabled] AS [Job Enabled], 
sj.notify_email_operator_id, sj.notify_level_email, sc.name AS [CategoryName],
s.[enabled] AS [Sched Enabled], js.next_run_date, js.next_run_time
FROM msdb.dbo.sysjobs AS sj WITH (NOLOCK)
INNER JOIN msdb.dbo.syscategories AS sc WITH (NOLOCK)
ON sj.category_id = sc.category_id
LEFT OUTER JOIN msdb.dbo.sysjobschedules AS js WITH (NOLOCK)
ON sj.job_id = js.job_id
LEFT OUTER JOIN msdb.dbo.sysschedules AS s WITH (NOLOCK)
ON js.schedule_id = s.schedule_id
ORDER BY sj.name OPTION (RECOMPILE);
------

-- Gives you some basic information about your SQL Server Agent jobs, who owns them and how they are configured
-- Look for Agent jobs that are not owned by sa
-- Look for jobs that have a notify_email_operator_id set to 0 (meaning no operator)
-- Look for jobs that have a notify_level_email set to 0 (meaning no e-mail is ever sent)
--
-- MSDN sysjobs documentation
-- https://bit.ly/2paDEOP 

-- SQL Server Maintenance Solution
-- https://bit.ly/1pgchQu  


-- Get SQL Server Agent Alert Information (Query 11) (SQL Server Agent Alerts)
SELECT name, event_source, message_id, severity, [enabled], has_notification, 
       delay_between_responses, occurrence_count, last_occurrence_date, last_occurrence_time
FROM msdb.dbo.sysalerts WITH (NOLOCK)
ORDER BY name OPTION (RECOMPILE);
------

-- Gives you some basic information about your SQL Server Agent Alerts 
-- (which are different from SQL Server Agent jobs)
-- Read more about Agent Alerts here: https://bit.ly/2Giz0Xf 



-- Windows information (Query 12) (Windows Info)
SELECT windows_release, windows_service_pack_level, 
       windows_sku, os_language_version
FROM sys.dm_os_windows_info WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Gives you major OS version, Service Pack, Edition, and language info for the operating system
-- 10.0 is either Windows 10 or Windows Server 2016
-- 6.3 is either Windows 8.1, or Windows Server 2012 R2  
-- 6.2 is either Windows 8 or Windows Server 2012
-- 6.1 is either Windows 7 or Windows Server 2008 R2
-- 6.0 is either Windows Vista or Windows Server 2008

-- Windows SKU codes
-- 4 is Enterprise Edition
-- 7 is Standard Server Edition
-- 8 is Datacenter Server Edition
-- 10 is Enterprise Server Edition
-- 48 is Professional Edition
-- 161 is Pro for Workstations

-- 1033 for os_language_version is US-English

-- SQL Server 2014 requires Windows Server 2008 SP2 or newer

-- Hardware and Software Requirements for Installing SQL Server 2014
-- https://bit.ly/1yRYXkQ

-- Using SQL Server in Windows 8 and later versions of Windows operating system 
-- https://bit.ly/2F7Ax0P



-- SQL Server NUMA Node information  (Query 13) (SQL Server NUMA Info)
SELECT node_id, node_state_desc, memory_node_id, processor_group, online_scheduler_count, 
       idle_scheduler_count, active_worker_count, avg_load_balance, resource_monitor_state
FROM sys.dm_os_nodes WITH (NOLOCK) 
WHERE node_state_desc <> N'ONLINE DAC' OPTION (RECOMPILE);
------

-- Gives you some useful information about the composition and relative load on your NUMA nodes
-- You want to see an equal number of schedulers on each NUMA node
-- Watch out if SQL Server 2014 Standard Edition has been installed 
-- on a physical or virtual machine with more than four sockets or more than 16 physical cores

-- sys.dm_os_nodes (Transact-SQL)
-- https://bit.ly/2pn5Mw8

-- Balancing Your Available SQL Server Core Licenses Evenly Across NUMA Nodes
-- https://bit.ly/2vfC4Rq



-- Good basic information about OS memory amounts and state  (Query 14) (System Memory)
SELECT total_physical_memory_kb/1024 AS [Physical Memory (MB)], 
       available_physical_memory_kb/1024 AS [Available Memory (MB)], 
       total_page_file_kb/1024 AS [Total Page File (MB)], 
	   available_page_file_kb/1024 AS [Available Page File (MB)], 
	   system_cache_kb/1024 AS [System Cache (MB)],
       system_memory_state_desc AS [System Memory State]
FROM sys.dm_os_sys_memory WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You want to see "Available physical memory is high" for System Memory State
-- This indicates that you are not under external memory pressure

-- Possible System Memory State values:
-- Available physical memory is high
-- Physical memory usage is steady
-- Available physical memory is low
-- Available physical memory is running low
-- Physical memory state is transitioning

-- sys.dm_os_sys_memory (Transact-SQL)
-- https://bit.ly/2pcV0xq



-- You can skip the next two queries if you know you don't have a clustered instance


-- Get information about your cluster nodes and their status  (Query 15) (Cluster Node Properties)
-- (if your database server is in a failover cluster)
SELECT NodeName, status_description, is_current_owner
FROM sys.dm_os_cluster_nodes WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Knowing which node owns the cluster resources is critical
-- Especially when you are installing Windows or SQL Server updates
-- You will see no results if your instance is not clustered

-- Recommended hotfixes and updates for Windows Server 2012 R2-based failover clusters
-- https://bit.ly/1z5BfCw


-- Get information about any AlwaysOn AG cluster this instance is a part of (Query 16) (AlwaysOn AG Cluster)
SELECT cluster_name, quorum_type_desc, quorum_state_desc
FROM sys.dm_hadr_cluster WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You will see no results if your instance is not using AlwaysOn AGs


-- Good overview of AG health and status (Query 17) (AlwaysOn AG Status)
SELECT ag.name AS [AG Name], ar.replica_server_name, ar.availability_mode_desc, adc.[database_name], 
       drs.is_local, drs.is_primary_replica, drs.synchronization_state_desc, drs.is_commit_participant, 
	   drs.synchronization_health_desc, drs.recovery_lsn, drs.truncation_lsn, drs.last_sent_lsn, 
	   drs.last_sent_time, drs.last_received_lsn, drs.last_received_time, drs.last_hardened_lsn, 
	   drs.last_hardened_time, drs.last_redone_lsn, drs.last_redone_time, drs.log_send_queue_size, 
	   drs.log_send_rate, drs.redo_queue_size, drs.redo_rate, drs.filestream_send_rate, 
	   drs.end_of_log_lsn, drs.last_commit_lsn, drs.last_commit_time, drs.database_state_desc 
FROM sys.dm_hadr_database_replica_states AS drs WITH (NOLOCK)
INNER JOIN sys.availability_databases_cluster AS adc WITH (NOLOCK)
ON drs.group_id = adc.group_id 
AND drs.group_database_id = adc.group_database_id
INNER JOIN sys.availability_groups AS ag WITH (NOLOCK)
ON ag.group_id = drs.group_id
INNER JOIN sys.availability_replicas AS ar WITH (NOLOCK)
ON drs.group_id = ar.group_id 
AND drs.replica_id = ar.replica_id
ORDER BY ag.name, ar.replica_server_name, adc.[database_name] OPTION (RECOMPILE);

-- You will see no results if your instance is not using AlwaysOn AGs


-- Hardware information from SQL Server 2014  (Query 18) (Hardware Info)
SELECT cpu_count AS [Logical CPU Count], scheduler_count, 
       hyperthread_ratio AS [Hyperthread Ratio],
       cpu_count/hyperthread_ratio AS [Physical CPU Count], 
       physical_memory_kb/1024 AS [Physical Memory (MB)], 
	   committed_kb/1024 AS [Committed Memory (MB)],
       committed_target_kb/1024 AS [Committed Target Memory (MB)],
       max_workers_count AS [Max Workers Count], 
	   affinity_type_desc AS [Affinity Type], 
       sqlserver_start_time AS [SQL Server Start Time],
	   DATEDIFF(hour, sqlserver_start_time, GETDATE()) AS [SQL Server Up Time (hrs)],
	   virtual_machine_type_desc AS [Virtual Machine Type]
FROM sys.dm_os_sys_info WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Gives you some good basic hardware information about your database server
-- Cannot distinguish between HT and multi-core
-- Note: virtual_machine_type_desc of HYPERVISOR does not automatically mean you are running SQL Server inside of a VM
-- It merely indicates that you have a hypervisor running on your host

-- sys.dm_os_sys_info (Transact-SQL)
-- https://bit.ly/2pczOYs

-- Soft NUMA configuration was a new column for SQL Server 2016
-- OFF = Soft-NUMA feature is OFF
-- ON = SQL Server automatically determines the NUMA node sizes for Soft-NUMA
-- MANUAL = Manually configured soft-NUMA

-- Configure SQL Server to Use Soft-NUMA (SQL Server)
-- https://bit.ly/2HTpKJt



-- Get System Manufacturer and model number from SQL Server Error log (Query 19) (System Manufacturer)
EXEC sys.xp_readerrorlog 0, 1, N'Manufacturer';
------ 

-- This can help you determine the capabilities and capacities of your database server
-- Can also be used to confirm if you are running in a VM
-- This query might take a few seconds if you have not recycled your error log recently
-- This query will return no results if your error log has been recycled since the instance was started


-- Get pvscsi info from Windows Registry  (Query 20) (PVSCSI Driver Parameters)
EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SYSTEM\CurrentControlSet\services\pvscsi\Parameters\Device', N'DriverParameter';
------

-- This is valid for VMware VMs
-- Recommended value for intensive I/O patterns from VMware is: RequestRingPages=32,MaxQueueDepth=254
-- https://kb.vmware.com/s/article/2053145


-- Get BIOS date from Windows Registry (Query 21) (BIOS Date)
EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'HARDWARE\DESCRIPTION\System\BIOS', N'BiosReleaseDate';
------

-- Helps you understand whether the main system BIOS is up to date, and the possible age of the hardware
-- Not as useful for virtualization


-- Get processor description from Windows Registry  (Query 22) (Processor Description)
EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'HARDWARE\DESCRIPTION\System\CentralProcessor\0', N'ProcessorNameString';
------

-- Gives you the model number and rated clock speed of your processor(s)
-- Your processors may be running at less than the rated clock speed due
-- to the Windows Power Plan or hardware power management

-- You can use CPU-Z to get your actual CPU core speed and a lot of other useful information
-- https://bit.ly/QhR6xF

-- You can learn more about processor selection for SQL Server by following this link
-- https://bit.ly/2F3aVlP



-- See if buffer pool extension (BPE) is enabled (Query 23) (BPE Configuration)
SELECT [path], state_description, current_size_in_kb, 
CAST(current_size_in_kb/1048576.0 AS DECIMAL(10,2)) AS [Size (GB)]
FROM sys.dm_os_buffer_pool_extension_configuration WITH (NOLOCK) OPTION (RECOMPILE);
------

-- BPE is available in both Standard Edition and Enterprise Edition
-- It is a more interesting feature for Standard Edition

-- Buffer Pool Extension to SSDs in SQL Server 2014
-- https://bit.ly/1bm08m8

-- Buffer Pool Extension
-- https://bit.ly/2oBuieO



-- Look at buffer descriptors to see BPE usage by database (Query 24) (BPE Usage) 
SELECT DB_NAME(database_id) AS [Database Name], COUNT(page_id) AS [Page Count],
CAST(COUNT(*)/128.0 AS DECIMAL(10, 2)) AS [Buffer size(MB)], 
AVG(read_microsec) AS [Avg Read Time (microseconds)]
FROM sys.dm_os_buffer_descriptors WITH (NOLOCK)
WHERE database_id <> 32767
AND is_in_bpool_extension = 1
GROUP BY DB_NAME(database_id) 
ORDER BY [Buffer size(MB)] DESC OPTION (RECOMPILE);
------

-- You will see no results if BPE is not enabled or if there is no BPE usage


-- Get information on location, time and size of any memory dumps from SQL Server  (Query 25) (Memory Dump Info)
SELECT [filename], creation_time, size_in_bytes/1048576.0 AS [Size (MB)]
FROM sys.dm_server_memory_dumps WITH (NOLOCK) 
ORDER BY creation_time DESC OPTION (RECOMPILE);
------

-- This will not return any rows if you have 
-- not had any memory dumps (which is a good thing)

-- sys.dm_server_memory_dumps (Transact-SQL)
-- https://bit.ly/2elwWll



-- Look at Suspect Pages table (Query 26) (Suspect Pages)
SELECT DB_NAME(database_id) AS [Database Name], [file_id], page_id, 
       event_type, error_count, last_update_date 
FROM msdb.dbo.suspect_pages WITH (NOLOCK)
ORDER BY database_id OPTION (RECOMPILE);
------

-- event_type value descriptions
-- 1 = 823 error caused by an operating system CRC error
--     or 824 error other than a bad checksum or a torn page (for example, a bad page ID)
-- 2 = Bad checksum
-- 3 = Torn page
-- 4 = Restored (The page was restored after it was marked bad)
-- 5 = Repaired (DBCC repaired the page)
-- 7 = Deallocated by DBCC

-- Ideally, this query returns no results. The table is limited to 1000 rows.
-- If you do get results here, you should do further investigation to determine the root cause

-- Manage the suspect_pages Table
-- https://bit.ly/2Fvr1c9


-- Get number of data files in tempdb database (Query 27) (Tempdb Data Files)
EXEC sys.xp_readerrorlog 0, 1, N'The tempdb database has';
------

-- Get the number of data files in the tempdb database
-- 4-8 data files that are all the same size is a good starting point
-- This query will return no results if your error log has been recycled since the instance was last started
-- This will be blank unless you have Service Pack 2 or later


-- File names and paths for all user and system databases on instance  (Query 28) (Database Filenames and Paths)
SELECT DB_NAME([database_id]) AS [Database Name], 
       [file_id], [name], physical_name, [type_desc], state_desc,
	   is_percent_growth, growth,
	   CONVERT(bigint, growth/128.0) AS [Growth in MB], 
       CONVERT(bigint, size/128.0) AS [Total Size in MB]
FROM sys.master_files WITH (NOLOCK)
ORDER BY DB_NAME([database_id]), [file_id] OPTION (RECOMPILE);
------

-- Things to look at:
-- Are data files and log files on different drives?
-- Is everything on the C: drive?
-- Is tempdb on dedicated drives?
-- Is there only one tempdb data file?
-- Are all of the tempdb data files the same size?
-- Are there multiple data files for user databases?
-- Is percent growth enabled for any files (which is bad)?


-- Volume info for all LUNS that have database files on the current instance (Query 29) (Volume Info)
SELECT DISTINCT vs.volume_mount_point, vs.file_system_type, vs.logical_volume_name, 
CONVERT(DECIMAL(18,2), vs.total_bytes/1073741824.0) AS [Total Size (GB)],
CONVERT(DECIMAL(18,2), vs.available_bytes/1073741824.0) AS [Available Size (GB)],  
CONVERT(DECIMAL(18,2), vs.available_bytes * 1. / vs.total_bytes * 100.) AS [Space Free %],
vs.supports_compression, vs.is_compressed, 
vs.supports_sparse_files, vs.supports_alternate_streams
FROM sys.master_files AS f WITH (NOLOCK)
CROSS APPLY sys.dm_os_volume_stats(f.database_id, f.[file_id]) AS vs 
ORDER BY vs.volume_mount_point OPTION (RECOMPILE);
------

-- Shows you the total and free space on the LUNs where you have database files
-- Being low on free space can negatively affect performance

-- sys.dm_os_volume_stats (Transact-SQL)
-- https://bit.ly/2oBPNNr



-- Drive level latency information (Query 30) (Drive Level Latency)
-- Based on code from Jimmy May
SELECT tab.[Drive], tab.volume_mount_point AS [Volume Mount Point], 
	CASE 
		WHEN num_of_reads = 0 THEN 0 
		ELSE (io_stall_read_ms/num_of_reads) 
	END AS [Read Latency],
	CASE 
		WHEN num_of_writes = 0 THEN 0 
		ELSE (io_stall_write_ms/num_of_writes) 
	END AS [Write Latency],
	CASE 
		WHEN (num_of_reads = 0 AND num_of_writes = 0) THEN 0 
		ELSE (io_stall/(num_of_reads + num_of_writes)) 
	END AS [Overall Latency],
	CASE 
		WHEN num_of_reads = 0 THEN 0 
		ELSE (num_of_bytes_read/num_of_reads) 
	END AS [Avg Bytes/Read],
	CASE 
		WHEN num_of_writes = 0 THEN 0 
		ELSE (num_of_bytes_written/num_of_writes) 
	END AS [Avg Bytes/Write],
	CASE 
		WHEN (num_of_reads = 0 AND num_of_writes = 0) THEN 0 
		ELSE ((num_of_bytes_read + num_of_bytes_written)/(num_of_reads + num_of_writes)) 
	END AS [Avg Bytes/Transfer]
FROM (SELECT LEFT(UPPER(mf.physical_name), 2) AS Drive, SUM(num_of_reads) AS num_of_reads,
	         SUM(io_stall_read_ms) AS io_stall_read_ms, SUM(num_of_writes) AS num_of_writes,
	         SUM(io_stall_write_ms) AS io_stall_write_ms, SUM(num_of_bytes_read) AS num_of_bytes_read,
	         SUM(num_of_bytes_written) AS num_of_bytes_written, SUM(io_stall) AS io_stall, vs.volume_mount_point 
      FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS vfs
      INNER JOIN sys.master_files AS mf WITH (NOLOCK)
      ON vfs.database_id = mf.database_id AND vfs.file_id = mf.file_id
	  CROSS APPLY sys.dm_os_volume_stats(mf.database_id, mf.[file_id]) AS vs 
      GROUP BY LEFT(UPPER(mf.physical_name), 2), vs.volume_mount_point) AS tab
ORDER BY [Overall Latency] OPTION (RECOMPILE);
------

-- Shows you the drive-level latency for reads and writes, in milliseconds
-- Latency above 30-40ms is usually a problem
-- These latency numbers include all file activity against all SQL Server 
-- database files on each drive since SQL Server was last started


-- Calculates average stalls per read, per write, and per total input/output for each database file  (Query 31) (IO Latency by File)
SELECT DB_NAME(fs.database_id) AS [Database Name], CAST(fs.io_stall_read_ms/(1.0 + fs.num_of_reads) AS NUMERIC(10,1)) AS [avg_read_latency_ms],
CAST(fs.io_stall_write_ms/(1.0 + fs.num_of_writes) AS NUMERIC(10,1)) AS [avg_write_latency_ms],
CAST((fs.io_stall_read_ms + fs.io_stall_write_ms)/(1.0 + fs.num_of_reads + fs.num_of_writes) AS NUMERIC(10,1)) AS [avg_io_latency_ms],
CONVERT(DECIMAL(18,2), mf.size/128.0) AS [File Size (MB)], mf.physical_name, mf.type_desc, fs.io_stall_read_ms, fs.num_of_reads, 
fs.io_stall_write_ms, fs.num_of_writes, fs.io_stall_read_ms + fs.io_stall_write_ms AS [io_stalls], fs.num_of_reads + fs.num_of_writes AS [total_io],
io_stall_queued_read_ms AS [Resource Governor Total Read IO Latency (ms)], io_stall_queued_write_ms AS [Resource Governor Total Write IO Latency (ms)] 
FROM sys.dm_io_virtual_file_stats(null,null) AS fs
INNER JOIN sys.master_files AS mf WITH (NOLOCK)
ON fs.database_id = mf.database_id
AND fs.[file_id] = mf.[file_id]
ORDER BY avg_io_latency_ms DESC OPTION (RECOMPILE);
------

-- Helps determine which database files on the entire instance have the most I/O bottlenecks
-- This can help you decide whether certain LUNs are overloaded and whether you might
-- want to move some files to a different location or perhaps improve your I/O performance
-- These latency numbers include all file activity against each SQL Server 
-- database file since SQL Server was last started


-- Look for I/O requests taking longer than 15 seconds in the six most recent SQL Server Error Logs (Query 32) (IO Warnings)
CREATE TABLE #IOWarningResults(LogDate datetime, ProcessInfo sysname, LogText nvarchar(1000));

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 0, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 1, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 2, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 3, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 4, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 5, 1, N'taking longer than 15 seconds';

SELECT LogDate, ProcessInfo, LogText
FROM #IOWarningResults
ORDER BY LogDate DESC;

DROP TABLE #IOWarningResults;
------  

-- Finding 15 second I/O warnings in the SQL Server Error Log is useful evidence of
-- poor I/O performance (which might have many different causes)
-- Look to see if you see any patterns in the results (same files, same drives, same time of day, etc.)

-- Diagnostics in SQL Server help detect stalled and stuck I/O operations
-- https://bit.ly/2qtaw73


-- Resource Governor Resource Pool information (Query 33) (RG Resource Pools)
SELECT pool_id, [Name], statistics_start_time,
       min_memory_percent, max_memory_percent,  
       max_memory_kb/1024 AS [max_memory_mb],  
       used_memory_kb/1024 AS [used_memory_mb],   
       target_memory_kb/1024 AS [target_memory_mb],
	   min_iops_per_volume, max_iops_per_volume
FROM sys.dm_resource_governor_resource_pools WITH (NOLOCK)
OPTION (RECOMPILE);
------

-- sys.dm_resource_governor_resource_pools (Transact-SQL)
-- https://bit.ly/2MVU0Vy



-- Recovery model, log reuse wait description, log file size, log usage size  (Query 34) (Database Properties)
-- and compatibility level for all databases on instance
SELECT db.[name] AS [Database Name], SUSER_SNAME(db.owner_sid) AS [Database Owner], db.recovery_model_desc AS [Recovery Model], 
db.state_desc, db.containment_desc, db.log_reuse_wait_desc AS [Log Reuse Wait Description], 
CONVERT(DECIMAL(18,2), ls.cntr_value/1024.0) AS [Log Size (MB)], CONVERT(DECIMAL(18,2), lu.cntr_value/1024.0) AS [Log Used (MB)],
CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log Used %], 
db.[compatibility_level] AS [DB Compatibility Level], db.page_verify_option_desc AS [Page Verify Option], 
db.is_auto_create_stats_on, db.is_auto_update_stats_on, db.is_auto_update_stats_async_on, db.is_parameterization_forced, 
db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on, db.is_auto_close_on, db.is_auto_shrink_on, 
db.target_recovery_time_in_seconds, db.is_cdc_enabled, db.is_published, db.is_distributor, db.is_encrypted,
db.group_database_id, db.replica_id,db.is_memory_optimized_elevate_to_snapshot_on, 
db.delayed_durability_desc, db.is_auto_create_stats_incremental_on,
db.is_encrypted, de.encryption_state, de.percent_complete, de.key_algorithm, de.key_length      
FROM sys.databases AS db WITH (NOLOCK)
INNER JOIN sys.dm_os_performance_counters AS lu WITH (NOLOCK)
ON db.name = lu.instance_name
INNER JOIN sys.dm_os_performance_counters AS ls WITH (NOLOCK)
ON db.name = ls.instance_name
LEFT OUTER JOIN sys.dm_database_encryption_keys AS de WITH (NOLOCK)
ON db.database_id = de.database_id
WHERE lu.counter_name LIKE N'Log File(s) Used Size (KB)%' 
AND ls.counter_name LIKE N'Log File(s) Size (KB)%'
AND ls.cntr_value > 0 
ORDER BY db.[name] OPTION (RECOMPILE);
------

-- Things to look at:
-- How many databases are on the instance?
-- What recovery models are they using?
-- What is the log reuse wait description?
-- How full are the transaction logs?
-- What compatibility level are the databases on? 
-- What is the Page Verify Option? (should be CHECKSUM)
-- Is Auto Update Statistics Asynchronously enabled?
-- Make sure auto_shrink and auto_close are not enabled!

 

-- Missing Indexes for all databases by Index Advantage  (Query 35) (Missing Indexes All Databases)
SELECT CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage],
FORMAT(migs.last_user_seek, 'yyyy-MM-dd HH:mm:ss') AS [last_user_seek], 
mid.[statement] AS [Database.Schema.Table],
COUNT(1) OVER(PARTITION BY mid.[statement]) AS [missing_indexes_for_table],
COUNT(1) OVER(PARTITION BY mid.[statement], equality_columns) AS [similar_missing_indexes_for_table],
mid.equality_columns, mid.inequality_columns, mid.included_columns,
migs.unique_compiles, migs.user_seeks, 
CONVERT(decimal(18,2), migs.avg_total_user_cost) AS [avg_total_user_cost], migs.avg_user_impact 
FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)
INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)
ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)
ON mig.index_handle = mid.index_handle
ORDER BY index_advantage DESC OPTION (RECOMPILE);
------

-- Getting missing index information for all of the databases on the instance is very useful
-- Look at last user seek time, number of user seeks to help determine source and importance
-- Also look at avg_user_impact and avg_total_user_cost to help determine importance
-- SQL Server is overly eager to add included columns, so beware
-- Do not just blindly add indexes that show up from this query!!!

-- SQL Server Index Design Guide
-- https://bit.ly/2qtZr4N



-- Get VLF Counts for all databases on the instance (Query 36) (VLF Counts)
-- (adapted from Michelle Ufford) 
CREATE TABLE #VLFInfo (RecoveryUnitID int, FileID  int,
					   FileSize bigint, StartOffset bigint,
					   FSeqNo      bigint, [Status]    bigint,
					   Parity      bigint, CreateLSN   numeric(38));
	 
CREATE TABLE #VLFCountResults(DatabaseName sysname, VLFCount int);
	 
EXEC sp_MSforeachdb N'Use [?]; 

				INSERT INTO #VLFInfo 
				EXEC sp_executesql N''DBCC LOGINFO([?])''; 
	 
				INSERT INTO #VLFCountResults 
				SELECT DB_NAME(), COUNT(*) 
				FROM #VLFInfo; 

				TRUNCATE TABLE #VLFInfo;'
	 
SELECT DatabaseName, VLFCount  
FROM #VLFCountResults
ORDER BY VLFCount DESC;
	 
DROP TABLE #VLFInfo;
DROP TABLE #VLFCountResults;
------

-- High VLF counts can affect write performance to the log file 
-- and they can make full database restores and crash recovery take much longer
-- Try to keep your VLF counts under 200 in most cases (depending on log file size)

-- Important change to VLF creation algorithm in SQL Server 2014
-- https://bit.ly/2Hsjbg4

-- SQL Server Transaction Log Architecture and Management Guide
-- https://bit.ly/2JjmQRZ



-- Get CPU utilization by database (Query 37) (CPU Usage by Database)
WITH DB_CPU_Stats
AS
(SELECT pa.DatabaseID, DB_Name(pa.DatabaseID) AS [Database Name], SUM(qs.total_worker_time/1000) AS [CPU_Time_Ms]
 FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
 CROSS APPLY (SELECT CONVERT(int, value) AS [DatabaseID] 
              FROM sys.dm_exec_plan_attributes(qs.plan_handle)
              WHERE attribute = N'dbid') AS pa
 GROUP BY DatabaseID)
SELECT ROW_NUMBER() OVER(ORDER BY [CPU_Time_Ms] DESC) AS [CPU Rank],
       [Database Name], [CPU_Time_Ms] AS [CPU Time (ms)], 
       CAST([CPU_Time_Ms] * 1.0 / SUM([CPU_Time_Ms]) OVER() * 100.0 AS DECIMAL(5, 2)) AS [CPU Percent]
FROM DB_CPU_Stats
WHERE DatabaseID <> 32767 -- ResourceDB
ORDER BY [CPU Rank] OPTION (RECOMPILE);
------

-- Helps determine which database is using the most CPU resources on the instance
-- Note: This only reflects CPU usage from the currently cached query plans


-- Get I/O utilization by database (Query 38) (IO Usage By Database)
WITH Aggregate_IO_Statistics
AS (SELECT DB_NAME(database_id) AS [Database Name],
    CAST(SUM(num_of_bytes_read + num_of_bytes_written) / 1048576 AS DECIMAL(12, 2)) AS [ioTotalMB],
    CAST(SUM(num_of_bytes_read ) / 1048576 AS DECIMAL(12, 2)) AS [ioReadMB],
    CAST(SUM(num_of_bytes_written) / 1048576 AS DECIMAL(12, 2)) AS [ioWriteMB]
    FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS [DM_IO_STATS]
    GROUP BY database_id)
SELECT ROW_NUMBER() OVER (ORDER BY ioTotalMB DESC) AS [I/O Rank],
        [Database Name], ioTotalMB AS [Total I/O (MB)],
        CAST(ioTotalMB / SUM(ioTotalMB) OVER () * 100.0 AS DECIMAL(5, 2)) AS [Total I/O %],
        ioReadMB AS [Read I/O (MB)], 
		CAST(ioReadMB / SUM(ioReadMB) OVER () * 100.0 AS DECIMAL(5, 2)) AS [Read I/O %],
        ioWriteMB AS [Write I/O (MB)], 
		CAST(ioWriteMB / SUM(ioWriteMB) OVER () * 100.0 AS DECIMAL(5, 2)) AS [Write I/O %]
FROM Aggregate_IO_Statistics
ORDER BY [I/O Rank] OPTION (RECOMPILE);
------

-- Helps determine which database is using the most I/O resources on the instance
-- These numbers are cumulative since the last service restart
-- They include all I/O activity, not just the nominal I/O workload


-- Get total buffer usage by database for current instance  (Query 39) (Total Buffer Usage by Database)
-- This make take some time to run on a busy instance
WITH AggregateBufferPoolUsage
AS
(SELECT DB_NAME(database_id) AS [Database Name],
CAST(COUNT(*) * 8/1024.0 AS DECIMAL (10,2))  AS [CachedSize]
FROM sys.dm_os_buffer_descriptors WITH (NOLOCK)
WHERE database_id <> 32767 -- ResourceDB
GROUP BY DB_NAME(database_id))
SELECT ROW_NUMBER() OVER(ORDER BY CachedSize DESC) AS [Buffer Pool Rank], [Database Name], CachedSize AS [Cached Size (MB)],
       CAST(CachedSize / SUM(CachedSize) OVER() * 100.0 AS DECIMAL(5,2)) AS [Buffer Pool Percent]
FROM AggregateBufferPoolUsage
ORDER BY [Buffer Pool Rank] OPTION (RECOMPILE);
------

-- Tells you how much memory (in the buffer pool) 
-- is being used by each database on the instance


-- Clear Wait Stats with this command
-- DBCC SQLPERF('sys.dm_os_wait_stats', CLEAR);

-- Isolate top waits for server instance since last restart or wait statistics clear  (Query 40) (Top Waits)
WITH [Waits] 
AS (SELECT wait_type, wait_time_ms/ 1000.0 AS [WaitS],
          (wait_time_ms - signal_wait_time_ms) / 1000.0 AS [ResourceS],
           signal_wait_time_ms / 1000.0 AS [SignalS],
           waiting_tasks_count AS [WaitCount],
           100.0 *  wait_time_ms / SUM (wait_time_ms) OVER() AS [Percentage],
           ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS [RowNum]
    FROM sys.dm_os_wait_stats WITH (NOLOCK)
    WHERE [wait_type] NOT IN (
        N'BROKER_EVENTHANDLER', N'BROKER_RECEIVE_WAITFOR', N'BROKER_TASK_STOP',
		N'BROKER_TO_FLUSH', N'BROKER_TRANSMITTER', N'CHECKPOINT_QUEUE',
        N'CHKPT', N'CLR_AUTO_EVENT', N'CLR_MANUAL_EVENT', N'CLR_SEMAPHORE',
        N'DBMIRROR_DBM_EVENT', N'DBMIRROR_EVENTS_QUEUE', N'DBMIRROR_WORKER_QUEUE',
		N'DBMIRRORING_CMD', N'DIRTY_PAGE_POLL', N'DISPATCHER_QUEUE_SEMAPHORE',
        N'EXECSYNC', N'FSAGENT', N'FT_IFTS_SCHEDULER_IDLE_WAIT', N'FT_IFTSHC_MUTEX',
        N'HADR_CLUSAPI_CALL', N'HADR_FILESTREAM_IOMGR_IOCOMPLETION', N'HADR_LOGCAPTURE_WAIT', 
		N'HADR_NOTIFICATION_DEQUEUE', N'HADR_TIMER_TASK', N'HADR_WORK_QUEUE',
        N'KSOURCE_WAKEUP', N'LAZYWRITER_SLEEP', N'LOGMGR_QUEUE', N'ONDEMAND_TASK_QUEUE',
        N'PWAIT_ALL_COMPONENTS_INITIALIZED', 
		N'PREEMPTIVE_OS_AUTHENTICATIONOPS', N'PREEMPTIVE_OS_CREATEFILE', N'PREEMPTIVE_OS_GENERICOPS',
		N'PREEMPTIVE_OS_LIBRARYOPS', N'PREEMPTIVE_OS_QUERYREGISTRY',
		N'PREEMPTIVE_HADR_LEASE_MECHANISM', N'PREEMPTIVE_SP_SERVER_DIAGNOSTICS',
		N'QDS_PERSIST_TASK_MAIN_LOOP_SLEEP',
        N'QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP', N'QDS_SHUTDOWN_QUEUE', N'REQUEST_FOR_DEADLOCK_SEARCH',
		N'RESOURCE_QUEUE', N'SERVER_IDLE_CHECK', N'SLEEP_BPOOL_FLUSH', N'SLEEP_DBSTARTUP',
		N'SLEEP_DCOMSTARTUP', N'SLEEP_MASTERDBREADY', N'SLEEP_MASTERMDREADY',
        N'SLEEP_MASTERUPGRADED', N'SLEEP_MSDBSTARTUP', N'SLEEP_SYSTEMTASK', N'SLEEP_TASK',
        N'SLEEP_TEMPDBSTARTUP', N'SNI_HTTP_ACCEPT', N'SP_SERVER_DIAGNOSTICS_SLEEP',
		N'SQLTRACE_BUFFER_FLUSH', N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', N'SQLTRACE_WAIT_ENTRIES',
		N'WAIT_FOR_RESULTS', N'WAITFOR', N'WAITFOR_TASKSHUTDOWN', N'WAIT_XTP_HOST_WAIT',
		N'WAIT_XTP_OFFLINE_CKPT_NEW_LOG', N'WAIT_XTP_CKPT_CLOSE', N'XE_DISPATCHER_JOIN',
        N'XE_DISPATCHER_WAIT', N'XE_TIMER_EVENT')
    AND waiting_tasks_count > 0)
SELECT
    MAX (W1.wait_type) AS [WaitType],
	CAST (MAX (W1.Percentage) AS DECIMAL (5,2)) AS [Wait Percentage],
	CAST ((MAX (W1.WaitS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgWait_Sec],
    CAST ((MAX (W1.ResourceS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgRes_Sec],
    CAST ((MAX (W1.SignalS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgSig_Sec], 
    CAST (MAX (W1.WaitS) AS DECIMAL (16,2)) AS [Wait_Sec],
    CAST (MAX (W1.ResourceS) AS DECIMAL (16,2)) AS [Resource_Sec],
    CAST (MAX (W1.SignalS) AS DECIMAL (16,2)) AS [Signal_Sec],
    MAX (W1.WaitCount) AS [Wait Count],
	CAST (N'https://www.sqlskills.com/help/waits/' + W1.wait_type AS XML) AS [Help/Info URL]
FROM Waits AS W1
INNER JOIN Waits AS W2
ON W2.RowNum <= W1.RowNum
GROUP BY W1.RowNum, W1.wait_type
HAVING SUM (W2.Percentage) - MAX (W1.Percentage) < 99 -- percentage threshold
OPTION (RECOMPILE);
------

-- Cumulative wait stats are not as useful on an idle instance that is not under load or performance pressure

-- SQL Server Wait Types Library (Paul Randal)
-- https://bit.ly/2ePzYO2

-- The SQL Server Wait Type Repository
-- https://bit.ly/1afzfjC

-- Wait statistics, or please tell me where it hurts
-- https://bit.ly/2wsQHQE

-- SQL Server 2005 Performance Tuning using the Waits and Queues
-- https://bit.ly/1o2NFoF

-- sys.dm_os_wait_stats (Transact-SQL)
-- https://bit.ly/2Hjq9Yl



-- Get a count of SQL connections by IP address (Query 41) (Connection Counts by IP Address)
SELECT ec.client_net_address, es.[program_name], es.[host_name], es.login_name, 
COUNT(ec.session_id) AS [connection count] 
FROM sys.dm_exec_sessions AS es WITH (NOLOCK) 
INNER JOIN sys.dm_exec_connections AS ec WITH (NOLOCK) 
ON es.session_id = ec.session_id 
GROUP BY ec.client_net_address, es.[program_name], es.[host_name], es.login_name  
ORDER BY ec.client_net_address, es.[program_name] OPTION (RECOMPILE);
------

-- This helps you figure where your database load is coming from
-- and verifies connectivity from other machines

-- Solving Connectivity errors to SQL Server
-- https://bit.ly/2EgzoD0



-- Get Average Task Counts (run multiple times)  (Query 42) (Avg Task Counts)
SELECT AVG(current_tasks_count) AS [Avg Task Count], 
AVG(work_queue_count) AS [Avg Work Queue Count],
AVG(runnable_tasks_count) AS [Avg Runnable Task Count],
AVG(pending_disk_io_count) AS [Avg Pending DiskIO Count]
FROM sys.dm_os_schedulers WITH (NOLOCK)
WHERE scheduler_id < 255 OPTION (RECOMPILE);
------

-- Sustained values above 10 suggest further investigation in that area
-- High Avg Task Counts are often caused by blocking/deadlocking or other resource contention

-- Sustained values above 1 suggest further investigation in that area
-- High Avg Runnable Task Counts are a good sign of CPU pressure
-- High Avg Pending DiskIO Counts are a sign of disk pressure

-- How to Do Some Very Basic SQL Server Monitoring
-- https://bit.ly/2q3Btgt



-- Detect blocking (run multiple times)  (Query 42) (Detect Blocking)
SELECT t1.resource_type AS [lock type], DB_NAME(resource_database_id) AS [database],
t1.resource_associated_entity_id AS [blk object],t1.request_mode AS [lock req],  -- lock requested
t1.request_session_id AS [waiter sid], t2.wait_duration_ms AS [wait time],       -- spid of waiter  
(SELECT [text] FROM sys.dm_exec_requests AS r WITH (NOLOCK)                      -- get sql for waiter
CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) 
WHERE r.session_id = t1.request_session_id) AS [waiter_batch],
(SELECT SUBSTRING(qt.[text],r.statement_start_offset/2, 
    (CASE WHEN r.statement_end_offset = -1 
    THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2 
    ELSE r.statement_end_offset END - r.statement_start_offset)/2) 
FROM sys.dm_exec_requests AS r WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) AS qt
WHERE r.session_id = t1.request_session_id) AS [waiter_stmt],					-- statement blocked
t2.blocking_session_id AS [blocker sid],										-- spid of blocker
(SELECT [text] FROM sys.sysprocesses AS p										-- get sql for blocker
CROSS APPLY sys.dm_exec_sql_text(p.[sql_handle]) 
WHERE p.spid = t2.blocking_session_id) AS [blocker_batch]
FROM sys.dm_tran_locks AS t1 WITH (NOLOCK)
INNER JOIN sys.dm_os_waiting_tasks AS t2 WITH (NOLOCK)
ON t1.lock_owner_address = t2.resource_address OPTION (RECOMPILE);
------

-- Helps troubleshoot blocking and deadlocking issues
-- The results will change from second to second on a busy system
-- You should run this query multiple times when you see signs of blocking



-- Get CPU Utilization History for last 256 minutes (in one minute intervals)  (Query 44) (CPU Utilization History)
DECLARE @ts_now bigint = (SELECT cpu_ticks/(cpu_ticks/ms_ticks) FROM sys.dm_os_sys_info WITH (NOLOCK)); 

SELECT TOP(256) SQLProcessUtilization AS [SQL Server Process CPU Utilization], 
               SystemIdle AS [System Idle Process], 
               100 - SystemIdle - SQLProcessUtilization AS [Other Process CPU Utilization], 
               DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) AS [Event Time] 
FROM (SELECT record.value('(./Record/@id)[1]', 'int') AS record_id, 
			record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') 
			AS [SystemIdle], 
			record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int') 
			AS [SQLProcessUtilization], [timestamp] 
	  FROM (SELECT [timestamp], CONVERT(xml, record) AS [record] 
			FROM sys.dm_os_ring_buffers WITH (NOLOCK)
			WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR' 
			AND record LIKE N'%<SystemHealth>%') AS x) AS y 
ORDER BY record_id DESC OPTION (RECOMPILE);
------

-- Look at the trend over the entire period 
-- Also look at high sustained 'Other Process' CPU Utilization values
-- Note: This query sometimes gives inaccurate results (negative values)
-- on high core count (> 64 cores) systems


-- Get top total worker time queries for entire instance (Query 45) (Top Worker Time Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], 
REPLACE(REPLACE(LEFT(t.[text], 255), CHAR(10),''), CHAR(13),'') AS [Short Query Text],  
qs.total_worker_time AS [Total Worker Time], qs.min_worker_time AS [Min Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.max_worker_time AS [Max Worker Time], 
qs.min_elapsed_time AS [Min Elapsed Time], 
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time], 
qs.max_elapsed_time AS [Max Elapsed Time],
qs.min_logical_reads AS [Min Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.max_logical_reads AS [Max Logical Reads], 
qs.execution_count AS [Execution Count],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
qs.creation_time AS [Creation Time]
--,t.[text] AS [Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
ORDER BY qs.total_worker_time DESC OPTION (RECOMPILE);
------


-- Helps you find the most expensive queries from a CPU perspective across the entire instance
-- Can also help track down parameter sniffing issues



-- Page Life Expectancy (PLE) value for each NUMA node in current instance  (Query 46) (PLE by NUMA Node)
SELECT @@SERVERNAME AS [Server Name], RTRIM([object_name]) AS [Object Name], instance_name, cntr_value AS [Page Life Expectancy]
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Buffer Node%' -- Handles named instances
AND counter_name = N'Page life expectancy' OPTION (RECOMPILE);
------

-- PLE is a good measurement of internal memory pressure
-- Higher PLE is better. Watch the trend over time, not the absolute value
-- This will only return one row for non-NUMA systems

-- Page Life Expectancy isn�t what you think�
-- https://bit.ly/2EgynLa


-- Memory Grants Pending value for current instance  (Query 47) (Memory Grants Pending)
SELECT @@SERVERNAME AS [Server Name], RTRIM([object_name]) AS [Object Name], cntr_value AS [Memory Grants Pending]                                                                                                       
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Memory Manager%' -- Handles named instances
AND counter_name = N'Memory Grants Pending' OPTION (RECOMPILE);
------

-- Run multiple times, and run periodically if you suspect you are under memory pressure
-- Memory Grants Pending above zero for a sustained period is a very strong indicator of internal memory pressure


-- Memory Clerk Usage for instance  (Query 48) (Memory Clerk Usage)
-- Look for high value for CACHESTORE_SQLCP (Ad-hoc query plans)
SELECT TOP(10) mc.[type] AS [Memory Clerk Type], 
       CAST((SUM(mc.pages_kb)/1024.0) AS DECIMAL (15,2)) AS [Memory Usage (MB)] 
FROM sys.dm_os_memory_clerks AS mc WITH (NOLOCK)
GROUP BY mc.[type]  
ORDER BY SUM(mc.pages_kb) DESC OPTION (RECOMPILE);
------

-- MEMORYCLERK_SQLBUFFERPOOL was new for SQL Server 2012. It should be your highest consumer of memory

-- CACHESTORE_SQLCP  SQL Plans         
-- These are cached SQL statements or batches that aren't in stored procedures, functions and triggers
-- Watch out for high values for CACHESTORE_SQLCP
-- Enabling 'optimize for ad hoc workloads' at the instance level can help reduce this
-- Running DBCC FREESYSTEMCACHE ('SQL Plans') periodically may be required to better control this

-- CACHESTORE_OBJCP  Object Plans      
-- These are compiled plans for stored procedures, functions and triggers



-- Find single-use, ad-hoc and prepared queries that are bloating the plan cache  (Query 49) (Ad hoc Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], t.[text] AS [Query Text], 
cp.objtype AS [Object Type], cp.cacheobjtype AS [Cache Object Type],  
cp.size_in_bytes/1024 AS [Plan Size in KB]
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t
WHERE cp.cacheobjtype = N'Compiled Plan' 
AND cp.objtype IN (N'Adhoc', N'Prepared') 
AND cp.usecounts = 1
ORDER BY cp.size_in_bytes DESC, DB_NAME(t.[dbid]) OPTION (RECOMPILE);
------

-- Gives you the text, type and size of single-use ad-hoc and prepared queries that waste space in the plan cache
-- Enabling 'optimize for ad hoc workloads' for the instance can help (SQL Server 2008 and above only)
-- Running DBCC FREESYSTEMCACHE ('SQL Plans') periodically may be required to better control this
-- Enabling forced parameterization for the database can help, but test first!

-- Plan cache, adhoc workloads and clearing the single-use plan cache bloat
-- https://bit.ly/2EfYOkl


-- Get top total logical reads queries for entire instance (Query 50) (Top Logical Reads Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name],
REPLACE(REPLACE(LEFT(t.[text], 255), CHAR(10),''), CHAR(13),'') AS [Short Query Text], 
qs.total_logical_reads AS [Total Logical Reads],
qs.min_logical_reads AS [Min Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.max_logical_reads AS [Max Logical Reads],   
qs.min_worker_time AS [Min Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.max_worker_time AS [Max Worker Time], 
qs.min_elapsed_time AS [Min Elapsed Time], 
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time], 
qs.max_elapsed_time AS [Max Elapsed Time],
qs.execution_count AS [Execution Count], 
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
qs.creation_time AS [Creation Time]
--,t.[text] AS [Complete Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
ORDER BY qs.total_logical_reads DESC OPTION (RECOMPILE);
------


-- Helps you find the most expensive queries from a memory perspective across the entire instance
-- Can also help track down parameter sniffing issues


-- Get top average elapsed time queries for entire instance (Query 51) (Top Avg Elapsed Time Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], 
REPLACE(REPLACE(LEFT(t.[text], 255), CHAR(10),''), CHAR(13),'') AS [Short Query Text],  
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
qs.min_elapsed_time, qs.max_elapsed_time, qs.last_elapsed_time,
qs.execution_count AS [Execution Count],  
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads], 
qs.total_physical_reads/qs.execution_count AS [Avg Physical Reads], 
qs.total_worker_time/qs.execution_count AS [Avg Worker Time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
qs.creation_time AS [Creation Time]
--,t.[text] AS [Complete Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
ORDER BY qs.total_elapsed_time/qs.execution_count DESC OPTION (RECOMPILE);
------

-- Helps you find the highest average elapsed time queries across the entire instance
-- Can also help track down parameter sniffing issues




-- Database specific queries *****************************************************************

-- **** Please switch to a user database that you are interested in! *****
--USE YourDatabaseName; -- make sure to change to an actual database on your instance, not the master system database
--GO

-- Individual File Sizes and space available for current database  (Query 52) (File Sizes and Space)
SELECT f.name AS [File Name] , f.physical_name AS [Physical Name], 
CAST((f.size/128.0) AS DECIMAL(15,2)) AS [Total Size in MB],
CAST(f.size/128.0 - CAST(FILEPROPERTY(f.name, 'SpaceUsed') AS int)/128.0 AS DECIMAL(15,2)) 
AS [Available Space In MB], f.[file_id], fg.name AS [Filegroup Name],
f.is_percent_growth, f.growth, fg.is_default, fg.is_read_only
FROM sys.database_files AS f WITH (NOLOCK) 
LEFT OUTER JOIN sys.filegroups AS fg WITH (NOLOCK)
ON f.data_space_id = fg.data_space_id
ORDER BY f.[file_id] OPTION (RECOMPILE);
------

-- Look at how large and how full the files are and where they are located
-- Make sure the transaction log is not full!!


-- Log space usage for current database  (Query 53) (Log Space Usage)
SELECT DB_NAME(lsu.database_id) AS [Database Name], db.recovery_model_desc AS [Recovery Model],
		CAST(lsu.total_log_size_in_bytes/1048576.0 AS DECIMAL(10, 2)) AS [Total Log Space (MB)],
		CAST(lsu.used_log_space_in_bytes/1048576.0 AS DECIMAL(10, 2)) AS [Used Log Space (MB)], 
		CAST(lsu.used_log_space_in_percent AS DECIMAL(10, 2)) AS [Used Log Space %],
		CAST(lsu.log_space_in_bytes_since_last_backup/1048576.0 AS DECIMAL(10, 2)) AS [Used Log Space Since Last Backup (MB)],
		db.log_reuse_wait_desc		 
FROM sys.dm_db_log_space_usage AS lsu WITH (NOLOCK)
INNER JOIN sys.databases AS db WITH (NOLOCK)
ON lsu.database_id = db.database_id
OPTION (RECOMPILE);
------

-- Look at log file size and usage, along with the log reuse wait description for the current database


-- I/O Statistics by file for the current database  (Query 54) (IO Stats By File)
SELECT DB_NAME(DB_ID()) AS [Database Name], df.name AS [Logical Name], vfs.[file_id], df.type_desc,
df.physical_name AS [Physical Name], CAST(vfs.size_on_disk_bytes/1048576.0 AS DECIMAL(16, 2)) AS [Size on Disk (MB)],
vfs.num_of_reads, vfs.num_of_writes, vfs.io_stall_read_ms, vfs.io_stall_write_ms,
CAST(100. * vfs.io_stall_read_ms/(vfs.io_stall_read_ms + vfs.io_stall_write_ms) AS DECIMAL(16,1)) AS [IO Stall Reads Pct],
CAST(100. * vfs.io_stall_write_ms/(vfs.io_stall_write_ms + vfs.io_stall_read_ms) AS DECIMAL(16,1)) AS [IO Stall Writes Pct],
(vfs.num_of_reads + vfs.num_of_writes) AS [Writes + Reads], 
CAST(vfs.num_of_bytes_read/1048576.0 AS DECIMAL(16, 2)) AS [MB Read], 
CAST(vfs.num_of_bytes_written/1048576.0 AS DECIMAL(16, 2)) AS [MB Written],
CAST(100. * vfs.num_of_reads/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(16,1)) AS [# Reads Pct],
CAST(100. * vfs.num_of_writes/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(16,1)) AS [# Write Pct],
CAST(100. * vfs.num_of_bytes_read/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(16,1)) AS [Read Bytes Pct],
CAST(100. * vfs.num_of_bytes_written/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(16,1)) AS [Written Bytes Pct]
FROM sys.dm_io_virtual_file_stats(DB_ID(), NULL) AS vfs
INNER JOIN sys.database_files AS df WITH (NOLOCK)
ON vfs.[file_id]= df.[file_id] OPTION (RECOMPILE);
------

-- This helps you characterize your workload better from an I/O perspective for this database
-- It helps you determine whether you has an OLTP or DW/DSS type of workload



-- Get most frequently executed queries for this database (Query 55) (Query Execution Counts)
SELECT TOP(50) LEFT(t.[text], 50) AS [Short Query Text], qs.execution_count AS [Execution Count],
qs.total_logical_reads AS [Total Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.total_worker_time AS [Total Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.total_elapsed_time AS [Total Elapsed Time],
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
qs.creation_time AS [Creation Time]
--,t.[text] AS [Complete Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
WHERE t.dbid = DB_ID()
ORDER BY qs.execution_count DESC OPTION (RECOMPILE);
------


-- Queries 54 through 59 are the "Bad Man List" for stored procedures

-- Top Cached SPs By Execution Count (Query 56) (SP Execution Counts)
SELECT TOP(100) p.name AS [SP Name], qs.execution_count AS [Execution Count],
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time],    
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.execution_count DESC OPTION (RECOMPILE);
------

-- Tells you which cached stored procedures are called the most often
-- This helps you characterize and baseline your workload


-- Top Cached SPs By Avg Elapsed Time (Query 57) (SP Avg Elapsed Time)
SELECT TOP(25) p.name AS [SP Name], qs.min_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time], 
qs.max_elapsed_time, qs.last_elapsed_time, qs.total_elapsed_time, qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute], 
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], 
qs.total_worker_time AS [TotalWorkerTime],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY avg_elapsed_time DESC OPTION (RECOMPILE);
------

-- This helps you find high average elapsed time cached stored procedures that
-- may be easy to optimize with standard query tuning techniques



-- Top Cached SPs By Total Worker time. Worker time relates to CPU cost  (Query 58) (SP Worker Time)
SELECT TOP(25) p.name AS [SP Name], qs.total_worker_time AS [TotalWorkerTime], 
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.total_worker_time DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a CPU perspective
-- You should look at this if you see signs of CPU pressure


-- Top Cached SPs By Total Logical Reads. Logical reads relate to memory pressure  (Query 59) (SP Logical Reads)
SELECT TOP(25) p.name AS [SP Name], qs.total_logical_reads AS [TotalLogicalReads], 
qs.total_logical_reads/qs.execution_count AS [AvgLogicalReads],qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute], 
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.total_logical_reads DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a memory perspective
-- You should look at this if you see signs of memory pressure


-- Top Cached SPs By Total Physical Reads. Physical reads relate to disk read I/O pressure  (Query 60) (SP Physical Reads)
SELECT TOP(25) p.name AS [SP Name],qs.total_physical_reads AS [TotalPhysicalReads], 
qs.total_physical_reads/qs.execution_count AS [AvgPhysicalReads], qs.execution_count, 
qs.total_logical_reads,qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan 
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND qs.total_physical_reads > 0
ORDER BY qs.total_physical_reads DESC, qs.total_logical_reads DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a read I/O perspective
-- You should look at this if you see signs of I/O pressure or of memory pressure


       
-- Top Cached SPs By Total Logical Writes (Query 61) (SP Logical Writes)
-- Logical writes relate to both memory and disk I/O pressure 
SELECT TOP(25) p.name AS [SP Name], qs.total_logical_writes AS [TotalLogicalWrites], 
qs.total_logical_writes/qs.execution_count AS [AvgLogicalWrites], qs.execution_count,
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan 
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND qs.total_logical_writes > 0
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.total_logical_writes DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a write I/O perspective
-- You should look at this if you see signs of I/O pressure or of memory pressure


-- Lists the top statements by average input/output usage for the current database  (Query 62) (Top IO Statements)
SELECT TOP(50) OBJECT_NAME(qt.objectid, dbid) AS [SP Name],
(qs.total_logical_reads + qs.total_logical_writes) /qs.execution_count AS [Avg IO], qs.execution_count AS [Execution Count],
SUBSTRING(qt.[text],qs.statement_start_offset/2, 
	(CASE 
		WHEN qs.statement_end_offset = -1 
	 THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2 
		ELSE qs.statement_end_offset 
	 END - qs.statement_start_offset)/2) AS [Query Text]	
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
WHERE qt.[dbid] = DB_ID()
ORDER BY [Avg IO] DESC OPTION (RECOMPILE);
------

-- Helps you find the most expensive statements for I/O by SP



-- Possible Bad NC Indexes (writes > reads)  (Query 63) (Bad NC Indexes)
SELECT OBJECT_NAME(s.[object_id]) AS [Table Name], i.name AS [Index Name], i.index_id, 
i.is_disabled, i.is_hypothetical, i.has_filter, i.fill_factor,
s.user_updates AS [Total Writes], s.user_seeks + s.user_scans + s.user_lookups AS [Total Reads],
s.user_updates - (s.user_seeks + s.user_scans + s.user_lookups) AS [Difference]
FROM sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON s.[object_id] = i.[object_id]
AND i.index_id = s.index_id
WHERE OBJECTPROPERTY(s.[object_id],'IsUserTable') = 1
AND s.database_id = DB_ID()
AND s.user_updates > (s.user_seeks + s.user_scans + s.user_lookups)
AND i.index_id > 1 AND i.[type_desc] = N'NONCLUSTERED'
AND i.is_primary_key = 0 AND i.is_unique_constraint = 0 AND i.is_unique = 0
ORDER BY [Difference] DESC, [Total Writes] DESC, [Total Reads] ASC OPTION (RECOMPILE);
------

-- Look for indexes with high numbers of writes and zero or very low numbers of reads
-- Consider your complete workload, and how long your instance has been running
-- Investigate further before dropping an index!


-- Missing Indexes for current database by Index Advantage  (Query 64) (Missing Indexes)
SELECT CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage], 
migs.last_user_seek, mid.[statement] AS [Database.Schema.Table],
COUNT(1) OVER(PARTITION BY mid.[statement]) AS [missing_indexes_for_table],
COUNT(1) OVER(PARTITION BY mid.[statement], equality_columns) AS [similar_missing_indexes_for_table],
mid.equality_columns, mid.inequality_columns, mid.included_columns,
migs.unique_compiles, migs.user_seeks, 
CONVERT(decimal(18,2), migs.avg_total_user_cost) AS [avg_total_user_cost], migs.avg_user_impact,
OBJECT_NAME(mid.[object_id]) AS [Table Name], p.rows AS [Table Rows]
FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)
INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)
ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)
ON mig.index_handle = mid.index_handle
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON p.[object_id] = mid.[object_id]
WHERE mid.database_id = DB_ID()
AND p.index_id < 2 
ORDER BY index_advantage DESC OPTION (RECOMPILE);
------

-- Look at index advantage, last user seek time, number of user seeks to help determine source and importance
-- SQL Server is overly eager to add included columns, so beware
-- Do not just blindly add indexes that show up from this query!!!


-- Find missing index warnings for cached plans in the current database  (Query 65) (Missing Index Warnings)
-- Note: This query could take some time on a busy instance
SELECT TOP(25) OBJECT_NAME(objectid) AS [ObjectName], 
               cp.objtype, cp.usecounts, cp.size_in_bytes, query_plan
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) AS qp
WHERE CAST(query_plan AS NVARCHAR(MAX)) LIKE N'%MissingIndex%'
AND dbid = DB_ID()
ORDER BY cp.usecounts DESC OPTION (RECOMPILE);
------

-- Helps you connect missing indexes to specific stored procedures or queries
-- This can help you decide whether to add them or not


-- Breaks down buffers used by current database by object (table, index) in the buffer cache  (Query 66) (Buffer Usage)
-- Note: This query could take some time on a busy instance
SELECT OBJECT_NAME(p.[object_id]) AS [Object Name], p.index_id, 
CAST(COUNT(*)/128.0 AS DECIMAL(10, 2)) AS [Buffer size(MB)],  
COUNT(*) AS [BufferCount], p.[Rows] AS [Row Count],
p.data_compression_desc AS [Compression Type]
FROM sys.allocation_units AS a WITH (NOLOCK)
INNER JOIN sys.dm_os_buffer_descriptors AS b WITH (NOLOCK)
ON a.allocation_unit_id = b.allocation_unit_id
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON a.container_id = p.hobt_id
WHERE b.database_id = CONVERT(int, DB_ID())
AND p.[object_id] > 100
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'plan_%'
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'sys%'
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'xml_index_nodes%'
GROUP BY p.[object_id], p.index_id, p.data_compression_desc, p.[Rows]
ORDER BY [BufferCount] DESC OPTION (RECOMPILE);
------

-- Tells you what tables and indexes are using the most memory in the buffer cache
-- It can help identify possible candidates for data compression


-- Get Table names, row counts, and compression status for clustered index or heap  (Query 67) (Table Sizes)
SELECT SCHEMA_NAME(o.Schema_ID) AS [Schema Name], OBJECT_NAME(p.object_id) AS [ObjectName], 
SUM(p.Rows) AS [RowCount], data_compression_desc AS [CompressionType]
FROM sys.partitions AS p WITH (NOLOCK)
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON p.object_id = o.object_id
WHERE index_id < 2 --ignore the partitions from the non-clustered index if any
AND OBJECT_NAME(p.object_id) NOT LIKE N'sys%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'spt_%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'queue_%' 
AND OBJECT_NAME(p.object_id) NOT LIKE N'filestream_tombstone%' 
AND OBJECT_NAME(p.object_id) NOT LIKE N'fulltext%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'ifts_comp_fragment%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'filetable_updates%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'xml_index_nodes%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'sqlagent_job%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'plan_persist%'
GROUP BY  SCHEMA_NAME(o.Schema_ID), p.object_id, data_compression_desc
ORDER BY SUM(p.Rows) DESC OPTION (RECOMPILE);
------

-- Gives you an idea of table sizes, and possible data compression opportunities



-- Get some key table properties (Query 68) (Table Properties)
SELECT OBJECT_NAME(t.[object_id]) AS [ObjectName], p.[rows] AS [Table Rows], p.index_id, 
       p.data_compression_desc AS [Index Data Compression],
       t.create_date, t.lock_on_bulk_load, t.is_replicated, t.has_replication_filter, 
       t.is_tracked_by_cdc, t.lock_escalation_desc, t.is_filetable, 
	   t.is_memory_optimized, t.durability_desc  -- new for SQL Server 2014
FROM sys.tables AS t WITH (NOLOCK)
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON t.[object_id] = p.[object_id]
WHERE OBJECT_NAME(t.[object_id]) NOT LIKE N'sys%'
ORDER BY OBJECT_NAME(t.[object_id]), p.index_id OPTION (RECOMPILE);
------

-- Gives you some good information about your tables
-- Is Memory optimized and durability description are Hekaton-related properties that were new in SQL Server 2014



-- When were Statistics last updated on all indexes?  (Query 69) (Statistics Update)
SELECT SCHEMA_NAME(o.Schema_ID) + N'.' + o.[NAME] AS [Object Name], o.[type_desc] AS [Object Type],
      i.[name] AS [Index Name], STATS_DATE(i.[object_id], i.index_id) AS [Statistics Date], 
      s.auto_created, s.no_recompute, s.user_created, s.is_incremental, s.is_temporary,
	  st.row_count, st.used_page_count
FROM sys.objects AS o WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON o.[object_id] = i.[object_id]
INNER JOIN sys.stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id] 
AND i.index_id = s.stats_id
INNER JOIN sys.dm_db_partition_stats AS st WITH (NOLOCK)
ON o.[object_id] = st.[object_id]
AND i.[index_id] = st.[index_id]
WHERE o.[type] IN ('U', 'V')
AND st.row_count > 0
ORDER BY STATS_DATE(i.[object_id], i.index_id) DESC OPTION (RECOMPILE);
------  

-- Helps discover possible problems with out-of-date statistics
-- Also gives you an idea which indexes are the most active

-- sys.stats (Transact-SQL)
-- https://bit.ly/2GyAxrn

-- UPDATEs to Statistics (Erin Stellato)
-- https://bit.ly/2vhrYQy



-- Look at most frequently modified indexes and statistics (Query 70) (Volatile Indexes)
SELECT o.[name] AS [Object Name], o.[object_id], o.[type_desc], s.[name] AS [Statistics Name], 
       s.stats_id, s.no_recompute, s.auto_created, s.is_incremental, s.is_temporary,
	   sp.modification_counter, sp.[rows], sp.rows_sampled, sp.last_updated
FROM sys.objects AS o WITH (NOLOCK)
INNER JOIN sys.stats AS s WITH (NOLOCK)
ON s.object_id = o.object_id
CROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) AS sp
WHERE o.[type_desc] NOT IN (N'SYSTEM_TABLE', N'INTERNAL_TABLE')
AND sp.modification_counter > 0
ORDER BY sp.modification_counter DESC, o.name OPTION (RECOMPILE);
------

-- This helps you understand your workload and make better decisions about 
-- things like data compression and adding new indexes to a table



-- Get fragmentation info for all indexes above a certain size in the current database  (Query 71) (Index Fragmentation)
-- Note: This query could take some time on a very large database
SELECT DB_NAME(ps.database_id) AS [Database Name], SCHEMA_NAME(o.[schema_id]) AS [Schema Name],
OBJECT_NAME(ps.OBJECT_ID) AS [Object Name], i.[name] AS [Index Name], ps.index_id, 
ps.index_type_desc, ps.avg_fragmentation_in_percent, 
ps.fragment_count, ps.page_count, i.fill_factor, i.has_filter, 
i.filter_definition, i.[allow_page_locks]
FROM sys.dm_db_index_physical_stats(DB_ID(),NULL, NULL, NULL , N'LIMITED') AS ps
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ps.[object_id] = i.[object_id] 
AND ps.index_id = i.index_id
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON i.[object_id] = o.[object_id]
WHERE ps.database_id = DB_ID()
AND ps.page_count > 2500
ORDER BY ps.avg_fragmentation_in_percent DESC OPTION (RECOMPILE);
------

-- Helps determine whether you have framentation in your relational indexes
-- and how effective your index maintenance strategy is


--- Index Read/Write stats (all tables in current DB) ordered by Reads  (Query 72) (Overall Index Usage - Reads)
SELECT OBJECT_NAME(i.[object_id]) AS [ObjectName], i.[name] AS [IndexName], i.index_id, 
       s.user_seeks, s.user_scans, s.user_lookups,
	   s.user_seeks + s.user_scans + s.user_lookups AS [Total Reads], 
	   s.user_updates AS [Writes],  
	   i.[type_desc] AS [Index Type], i.fill_factor AS [Fill Factor], i.has_filter, i.filter_definition, 
	   s.last_user_scan, s.last_user_lookup, s.last_user_seek
FROM sys.indexes AS i WITH (NOLOCK)
LEFT OUTER JOIN sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id]
AND i.index_id = s.index_id
AND s.database_id = DB_ID()
WHERE OBJECTPROPERTY(i.[object_id],'IsUserTable') = 1
ORDER BY s.user_seeks + s.user_scans + s.user_lookups DESC OPTION (RECOMPILE); -- Order by reads
------

-- Show which indexes in the current database are most active for Reads


--- Index Read/Write stats (all tables in current DB) ordered by Writes  (Query 73) (Overall Index Usage - Writes)
SELECT OBJECT_NAME(i.[object_id]) AS [ObjectName], i.[name] AS [IndexName], i.index_id,
	   s.user_updates AS [Writes], s.user_seeks + s.user_scans + s.user_lookups AS [Total Reads], 
	   i.[type_desc] AS [Index Type], i.fill_factor AS [Fill Factor], i.has_filter, i.filter_definition,
	   s.last_system_update, s.last_user_update
FROM sys.indexes AS i WITH (NOLOCK)
LEFT OUTER JOIN sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id]
AND i.index_id = s.index_id
AND s.database_id = DB_ID()
WHERE OBJECTPROPERTY(i.[object_id],'IsUserTable') = 1
ORDER BY s.user_updates DESC OPTION (RECOMPILE);						 -- Order by writes
------

-- Show which indexes in the current database are most active for Writes


-- Get in-memory OLTP index usage (Query 74) (XTP Index Usage)
SELECT OBJECT_NAME(i.[object_id]) AS [Object Name], i.index_id, i.[name] AS [Index Name],
       i.[type_desc], xis.scans_started, xis.scans_retries, 
	   xis.rows_touched, xis.rows_returned
FROM sys.dm_db_xtp_index_stats AS xis WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON i.[object_id] = xis.[object_id] 
AND i.index_id = xis.index_id 
ORDER BY OBJECT_NAME(i.[object_id]) OPTION (RECOMPILE);
------

-- This gives you some index usage statistics for in-memory OLTP
-- Returns no data if you are not using in-memory OLTP

-- Guidelines for Using Indexes on Memory-Optimized Tables
-- https://bit.ly/2GCP8lF


-- Get lock waits for current database (Query 75) (Lock Waits)
SELECT o.name AS [table_name], i.name AS [index_name], ios.index_id, ios.partition_number,
		SUM(ios.row_lock_wait_count) AS [total_row_lock_waits], 
		SUM(ios.row_lock_wait_in_ms) AS [total_row_lock_wait_in_ms],
		SUM(ios.page_lock_wait_count) AS [total_page_lock_waits],
		SUM(ios.page_lock_wait_in_ms) AS [total_page_lock_wait_in_ms],
		SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) AS [total_lock_wait_in_ms]
FROM sys.dm_db_index_operational_stats(DB_ID(), NULL, NULL, NULL) AS ios
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON ios.[object_id] = o.[object_id]
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ios.[object_id] = i.[object_id] 
AND ios.index_id = i.index_id
WHERE o.[object_id] > 100
GROUP BY o.name, i.name, ios.index_id, ios.partition_number
HAVING SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) > 0
ORDER BY total_lock_wait_in_ms DESC OPTION (RECOMPILE);
------

-- This query is helpful for troubleshooting blocking and deadlocking issues


-- Get input buffer information for the current database (Query 76) (Input Buffer)
SELECT es.session_id, DB_NAME(es.database_id) AS [Database Name],
es.login_time, es.cpu_time, es.logical_reads,
es.[status], ib.event_info AS [Input Buffer]
FROM sys.dm_exec_sessions AS es WITH (NOLOCK)
CROSS APPLY sys.dm_exec_input_buffer(es.session_id, NULL) AS ib
WHERE es.database_id = DB_ID()
AND es.session_id > 50
AND es.session_id <> @@SPID OPTION (RECOMPILE);

-- Gives you input buffer information from all non-system sessions for the current database
-- Replaces DBCC INPUTBUFFER
-- Requires SQL Server 2014 SP2 or later

-- New DMF for retrieving input buffer in SQL Server
-- https://bit.ly/2uHKMbz


-- Look at recent Full backups for the current database (Query 77) (Recent Full Backups)
SELECT TOP (30) bs.machine_name, bs.server_name, bs.database_name AS [Database Name], bs.recovery_model,
CONVERT (BIGINT, bs.backup_size / 1048576 ) AS [Uncompressed Backup Size (MB)],
CONVERT (BIGINT, bs.compressed_backup_size / 1048576 ) AS [Compressed Backup Size (MB)],
CONVERT (NUMERIC (20,2), (CONVERT (FLOAT, bs.backup_size) /
CONVERT (FLOAT, bs.compressed_backup_size))) AS [Compression Ratio], bs.has_backup_checksums, bs.is_copy_only, bs.encryptor_type,
DATEDIFF (SECOND, bs.backup_start_date, bs.backup_finish_date) AS [Backup Elapsed Time (sec)],
bs.backup_finish_date AS [Backup Finish Date], bmf.physical_device_name AS [Backup Location], bmf.physical_block_size
FROM msdb.dbo.backupset AS bs WITH (NOLOCK)
INNER JOIN msdb.dbo.backupmediafamily AS bmf WITH (NOLOCK)
ON bs.media_set_id = bmf.media_set_id  
WHERE bs.database_name = DB_NAME(DB_ID())
AND bs.[type] = 'D' -- Change to L if you want Log backups
ORDER BY bs.backup_finish_date DESC OPTION (RECOMPILE);
------

-- Are your backup sizes and times changing over time?
-- Are you using backup compression?
-- Are you using backup checksums?
-- Are you doing copy_only backups?
-- Are you doing encrypted backups?
-- Have you done any backup tuning with striped backups, or changing the parameters of the backup command?


-- These four Pluralsight Courses go into more detail about how to run these queries and interpret the results

-- SQL Server 2017: Diagnosing Configuration Issues with DMVs
-- https://bit.ly/2MSUDUL

-- SQL Server 2014 DMV Diagnostic Queries � Part 1 
-- https://bit.ly/2plxCer

-- SQL Server 2014 DMV Diagnostic Queries � Part 2
-- https://bit.ly/2IuJpzI

-- SQL Server 2014 DMV Diagnostic Queries � Part 3
-- https://bit.ly/2FIlCPb



-- Sign up for Microsoft Visual Studio Dev Essentials and get a free three month pass to Pluralsight

-- Microsoft Visual Studio Dev Essentials
-- http://bit.ly/1q6xbDL


-- Sign up for Microsoft Azure Essentials and get lots of free Azure usage credits, MCP exam voucher, three month Pluralsight subscription

-- Microsoft Azure Essentials
-- https://bit.ly/2JMWe8x


-- August 2017 blog series about upgrading and migrating to SQL Server 2016/2017
-- https://bit.ly/2ftKVrX
tools\dbatools\bin\diagnosticquery\SQLServerDiagnosticQueries_2016SP2_201811.sql

-- SQL Server 2016 SP2 Diagnostic Information Queries
-- Glenn Berry 
-- Last Modified: January 7, 2019
-- https://www.sqlskills.com/blogs/glenn/
-- http://sqlserverperformance.wordpress.com/
-- Twitter: GlennAlanBerry

-- Please listen to my Pluralsight courses
-- https://www.pluralsight.com/author/glenn-berry

-- If you want to find all of our SQLskills SQL101 blog posts, check out https://bit.ly/2qLwfXW


-- Please make sure you are using the correct version of these diagnostic queries for your version of SQL Server


-- If you like PowerShell, there is a very useful community solution for running these queries in an automated fashion
-- https://dbatools.io/

-- Invoke-DbaDiagnosticQuery
-- https://dbatools.io/functions/invoke-dbadiagnosticquery/


--******************************************************************************
--*   Copyright (C) 2019 Glenn Berry, SQLskills.com
--*   All rights reserved. 
--*
--*   For more scripts and sample code, check out 
--*      https://www.sqlskills.com/blogs/glenn
--*
--*   You may alter this code for your own *non-commercial* purposes. You may
--*   republish altered code as long as you include this copyright and give due credit. 
--*
--*
--*   THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF 
--*   ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED 
--*   TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
--*   PARTICULAR PURPOSE. 
--*
--******************************************************************************

-- Check the major product version to see if it is SQL Server 2016 SP2 or greater
IF EXISTS (SELECT * WHERE CONVERT(varchar(128), SERVERPROPERTY('ProductVersion')) LIKE '13%')
	BEGIN
		IF CONVERT(int, SERVERPROPERTY('ProductBuild')) >= 5026
			PRINT N'You have the correct Service Pack of SQL Server 2016 for this diagnostic information script';
		IF CONVERT(int, SERVERPROPERTY('ProductBuild')) < 5026
			PRINT N'You do NOT have the correct Service Pack of SQL Server 2016 for this diagnostic information script';		
	END
ELSE
	BEGIN
		DECLARE @ProductVersion varchar(128) = CONVERT(varchar(128), SERVERPROPERTY('ProductVersion'));
		RAISERROR ('Script does not match the ProductVersion [%s] of this instance. Many of these queries may not work on this version.' , 18 , 16 , @ProductVersion);
	END
	
	

-- Instance level queries *******************************

-- SQL and OS Version information for current instance  (Query 1) (Version Info)
SELECT @@SERVERNAME AS [Server Name], @@VERSION AS [SQL Server and OS Version Info];
------

-- SQL Server 2016 Builds																		
-- Build			Description			Release Date	URL to KB Article								
-- 13.0.5026.0		SP2 RTM				4/24/2018		https://bit.ly/2FEvN2q 
-- 13.0.5149.0		SP2 CU1				5/30/2018		https://support.microsoft.com/en-us/help/4135048/cumulative-update-1-for-sql-server-2016-sp2
-- 13.0.5153.0		SP2 CU2				7/16/2018		https://support.microsoft.com/en-us/help/4340355
-- 13.0.5216.0		SP2 CU3				9/20/2018		https://support.microsoft.com/en-us/help/4458871
-- 13.0.5233.0		SP2 CU4			   11/13/2018		https://support.microsoft.com/en-us/help/4464106/cumulative-update-4-for-sql-server-2016-sp2	

		
															

-- How to determine the version, edition and update level of SQL Server and its components 
-- https://bit.ly/2oAjKgW														

-- How to obtain the latest Service Pack for SQL Server 2016
-- https://bit.ly/2egtfzK

-- SQL Server 2016 build versions 
-- https://bit.ly/2epkTDT

-- Where to find information about the latest SQL Server builds
-- https://bit.ly/2IGHbfY

-- Performance and Stability Related Fixes in Post-SQL Server 2016 SP2 Builds
-- https://bit.ly/2K3LoPf		

-- Announcing updates to the SQL Server Incremental Servicing Model (ISM)
-- https://bit.ly/1RzYITz

-- Update Center for Microsoft SQL Server
-- https://bit.ly/2pZptuQ

-- Download SQL Server Management Studio (SSMS)
-- https://bit.ly/1OcupT9

-- Download and install Azure Data Studio
-- https://bit.ly/2vgke1A



-- Get socket, physical core and logical core count from the SQL Server Error log. (Query 2) (Core Counts)
-- This query might take a few seconds depending on the size of your error log
EXEC sys.xp_readerrorlog 0, 1, N'detected', N'socket';
------

-- This can help you determine the exact core counts used by SQL Server and whether HT is enabled or not
-- It can also help you confirm your SQL Server licensing model
-- Be on the lookout for this message "using 40 logical processors based on SQL Server licensing" 
-- (when you have more than 40 logical cores) which means grandfathered Server/CAL licensing
-- This query will return no results if your error log has been recycled since the instance was last started



-- Get selected server properties (Query 3) (Server Properties)
SELECT SERVERPROPERTY('MachineName') AS [MachineName], 
SERVERPROPERTY('ServerName') AS [ServerName],  
SERVERPROPERTY('InstanceName') AS [Instance], 
SERVERPROPERTY('IsClustered') AS [IsClustered], 
SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS [ComputerNamePhysicalNetBIOS], 
SERVERPROPERTY('Edition') AS [Edition], 
SERVERPROPERTY('ProductLevel') AS [ProductLevel],				-- What servicing branch (RTM/SP/CU)
SERVERPROPERTY('ProductUpdateLevel') AS [ProductUpdateLevel],	-- Within a servicing branch, what CU# is applied
SERVERPROPERTY('ProductVersion') AS [ProductVersion],
SERVERPROPERTY('ProductMajorVersion') AS [ProductMajorVersion], 
SERVERPROPERTY('ProductMinorVersion') AS [ProductMinorVersion], 
SERVERPROPERTY('ProductBuild') AS [ProductBuild], 
SERVERPROPERTY('ProductBuildType') AS [ProductBuildType],			  -- Is this a GDR or OD hotfix (NULL if on a CU build)
SERVERPROPERTY('ProductUpdateReference') AS [ProductUpdateReference], -- KB article number that is applicable for this build
SERVERPROPERTY('ProcessID') AS [ProcessID],
SERVERPROPERTY('Collation') AS [Collation], 
SERVERPROPERTY('IsFullTextInstalled') AS [IsFullTextInstalled], 
SERVERPROPERTY('IsIntegratedSecurityOnly') AS [IsIntegratedSecurityOnly],
SERVERPROPERTY('FilestreamConfiguredLevel') AS [FilestreamConfiguredLevel],
SERVERPROPERTY('IsHadrEnabled') AS [IsHadrEnabled], 
SERVERPROPERTY('HadrManagerStatus') AS [HadrManagerStatus],
SERVERPROPERTY('InstanceDefaultDataPath') AS [InstanceDefaultDataPath],
SERVERPROPERTY('InstanceDefaultLogPath') AS [InstanceDefaultLogPath],
SERVERPROPERTY('BuildClrVersion') AS [Build CLR Version],
SERVERPROPERTY('IsXTPSupported') AS [IsXTPSupported],
SERVERPROPERTY('IsPolybaseInstalled') AS [IsPolybaseInstalled],				-- New for SQL Server 2016
SERVERPROPERTY('IsAdvancedAnalyticsInstalled') AS [IsRServicesInstalled];	-- New for SQL Server 2016
------

-- This gives you a lot of useful information about your instance of SQL Server,
-- such as the ProcessID for SQL Server and your collation
-- Note: Some columns will be NULL on older SQL Server builds

-- SERVERPROPERTY (Transact-SQL)
-- https://bit.ly/2eeaXeI



-- Get instance-level configuration values for instance  (Query 4) (Configuration Values)
SELECT name, value, value_in_use, minimum, maximum, [description], is_dynamic, is_advanced
FROM sys.configurations WITH (NOLOCK)
ORDER BY name OPTION (RECOMPILE);
------

-- Focus on these settings:
-- automatic soft-NUMA disabled (should be 0 in most cases)
-- backup checksum default (should be 1)
-- backup compression default (should be 1 in most cases)
-- clr enabled (only enable if it is needed)
-- cost threshold for parallelism (depends on your workload)
-- lightweight pooling (should be zero)
-- max degree of parallelism (depends on your workload and hardware)
-- max server memory (MB) (set to an appropriate value, not the default)
-- optimize for ad hoc workloads (should be 1)
-- priority boost (should be zero)
-- remote admin connections (should be 1)


-- sys.configurations (Transact-SQL)
-- https://bit.ly/2HsyDZI


-- Returns a list of all global trace flags that are enabled (Query 5) (Global Trace Flags)
DBCC TRACESTATUS (-1);
------

-- If no global trace flags are enabled, no results will be returned.
-- It is very useful to know what global trace flags are currently enabled as part of the diagnostic process.

-- Common trace flags that should be enabled in most cases
-- TF 3226 - Supresses logging of successful database backup messages to the SQL Server Error Log
--           https://bit.ly/2p6MTjS  

-- TF 6534 - Enables use of native code to improve performance with spatial data
--           https://bit.ly/2HrQUpU         

-- The behavior of TF 1117, 1118 are enabled for tempdb in SQL Server 2016 by default
-- SQL 2016 � It Just Runs Faster: -T1117 and -T1118 changes for TEMPDB and user databases
-- https://bit.ly/2lbNWxK           

-- The behavior of TF 2371 is enabled by default in SQL Server 2016 and newer (in compat level 130 and higher)

-- DBCC TRACEON - Trace Flags (Transact-SQL)
-- https://bit.ly/2FuSvPg





-- Returns status of instant file initialization (Query 6) (IFI Status)
EXEC sys.xp_readerrorlog 0, 1, N'Database Instant File Initialization';
------

-- Lets you determine whether Instant File Initialization (IFI) is enabled for the instance
-- This should be enabled in the vast majority of cases
-- SQL Server 2016 and newer lets you enable this during the SQL server installation process

-- Database Instant File Initialization
-- https://bit.ly/2nTX74y

-- Misconceptions around instant file initialization
-- https://bit.ly/2oBSKgZ



-- SQL Server Process Address space info  (Query 7) (Process Memory)
-- (shows whether locked pages is enabled, among other things)
SELECT physical_memory_in_use_kb/1024 AS [SQL Server Memory Usage (MB)],
	   locked_page_allocations_kb/1024 AS [SQL Server Locked Pages Allocation (MB)],
       large_page_allocations_kb/1024 AS [SQL Server Large Pages Allocation (MB)], 
	   page_fault_count, memory_utilization_percentage, available_commit_limit_kb, 
	   process_physical_memory_low, process_virtual_memory_low
FROM sys.dm_os_process_memory WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You want to see 0 for process_physical_memory_low
-- You want to see 0 for process_virtual_memory_low
-- This indicates that you are not under internal memory pressure
-- If locked_page_allocations_kb > 0, then LPIM is enabled

-- How to enable the "locked pages" feature in SQL Server 2012
-- https://bit.ly/2F5UjOA

-- Memory Management Architecture Guide
-- https://bit.ly/2JKkadC 



-- SQL Server Services information (Query 8) (SQL Server Services Info)
SELECT servicename, process_id, startup_type_desc, status_desc, 
last_startup_time, service_account, is_clustered, cluster_nodename, [filename], 
instant_file_initialization_enabled 
FROM sys.dm_server_services WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Tells you the account being used for the SQL Server Service and the SQL Agent Service
-- Shows the process_id, when they were last started, and their current status
-- Also shows whether you are running on a failover cluster instance, and what node you are running on
-- Also shows whether IFI is enabled

-- sys.dm_server_services (Transact-SQL)
-- https://bit.ly/2oKa1Un


-- Last backup information by database  (Query 9) (Last Backup By Database)
SELECT ISNULL(d.[name], bs.[database_name]) AS [Database], d.recovery_model_desc AS [Recovery Model], 
       d.log_reuse_wait_desc AS [Log Reuse Wait Desc],
    MAX(CASE WHEN [type] = 'D' THEN bs.backup_finish_date ELSE NULL END) AS [Last Full Backup],
    MAX(CASE WHEN [type] = 'I' THEN bs.backup_finish_date ELSE NULL END) AS [Last Differential Backup],
    MAX(CASE WHEN [type] = 'L' THEN bs.backup_finish_date ELSE NULL END) AS [Last Log Backup]
FROM sys.databases AS d WITH (NOLOCK)
LEFT OUTER JOIN msdb.dbo.backupset AS bs WITH (NOLOCK)
ON bs.[database_name] = d.[name] 
AND bs.backup_finish_date > GETDATE()- 30
WHERE d.name <> N'tempdb'
GROUP BY ISNULL(d.[name], bs.[database_name]), d.recovery_model_desc, d.log_reuse_wait_desc, d.[name] 
ORDER BY d.recovery_model_desc, d.[name] OPTION (RECOMPILE);
------

-- This helps you spot runaway transaction logs and other issues with your backup schedule


-- Get SQL Server Agent jobs and Category information (Query 10) (SQL Server Agent Jobs)
SELECT sj.name AS [Job Name], sj.[description] AS [Job Description], SUSER_SNAME(sj.owner_sid) AS [Job Owner],
sj.date_created AS [Date Created], sj.[enabled] AS [Job Enabled], 
sj.notify_email_operator_id, sj.notify_level_email, sc.name AS [CategoryName],
s.[enabled] AS [Sched Enabled], js.next_run_date, js.next_run_time
FROM msdb.dbo.sysjobs AS sj WITH (NOLOCK)
INNER JOIN msdb.dbo.syscategories AS sc WITH (NOLOCK)
ON sj.category_id = sc.category_id
LEFT OUTER JOIN msdb.dbo.sysjobschedules AS js WITH (NOLOCK)
ON sj.job_id = js.job_id
LEFT OUTER JOIN msdb.dbo.sysschedules AS s WITH (NOLOCK)
ON js.schedule_id = s.schedule_id
ORDER BY sj.name OPTION (RECOMPILE);
------

-- Gives you some basic information about your SQL Server Agent jobs, who owns them and how they are configured
-- Look for Agent jobs that are not owned by sa
-- Look for jobs that have a notify_email_operator_id set to 0 (meaning no operator)
-- Look for jobs that have a notify_level_email set to 0 (meaning no e-mail is ever sent)
--
-- MSDN sysjobs documentation
-- https://bit.ly/2paDEOP 

-- SQL Server Maintenance Solution
-- https://bit.ly/1pgchQu  


-- Get SQL Server Agent Alert Information (Query 11) (SQL Server Agent Alerts)
SELECT name, event_source, message_id, severity, [enabled], has_notification, 
       delay_between_responses, occurrence_count, last_occurrence_date, last_occurrence_time
FROM msdb.dbo.sysalerts WITH (NOLOCK)
ORDER BY name OPTION (RECOMPILE);
------

-- Gives you some basic information about your SQL Server Agent Alerts 
-- (which are different from SQL Server Agent jobs)
-- Read more about Agent Alerts here: https://bit.ly/2Giz0Xf 



-- Windows information (Query 12) (Windows Info)
SELECT windows_release, windows_service_pack_level, 
       windows_sku, os_language_version
FROM sys.dm_os_windows_info WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Gives you major OS version, Service Pack, Edition, and language info for the operating system
-- 10.0 is either Windows 10 or Windows Server 2016
-- 6.3 is either Windows 8.1 or Windows Server 2012 R2 
-- 6.2 is either Windows 8 or Windows Server 2012


-- Windows SKU codes
-- 4 is Enterprise Edition
-- 7 is Standard Server Edition
-- 8 is Datacenter Server Edition
-- 10 is Enterprise Server Edition
-- 48 is Professional Edition
-- 161 is Pro for Workstations

-- 1033 for os_language_version is US-English

-- SQL Server 2016 requires Windows Server 2012 or newer

-- Quick-Start Installation of SQL Server 2016
-- https://bit.ly/2qtxQ3G

-- Hardware and Software Requirements for Installing SQL Server 2016
-- https://bit.ly/2JJIUTl

-- Using SQL Server in Windows 8 and later versions of Windows operating system 
-- https://bit.ly/2F7Ax0P


-- SQL Server NUMA Node information  (Query 13) (SQL Server NUMA Info)
SELECT node_id, node_state_desc, memory_node_id, processor_group, cpu_count, online_scheduler_count, 
       idle_scheduler_count, active_worker_count, avg_load_balance, resource_monitor_state
FROM sys.dm_os_nodes WITH (NOLOCK) 
WHERE node_state_desc <> N'ONLINE DAC' OPTION (RECOMPILE);
------

-- Gives you some useful information about the composition and relative load on your NUMA nodes
-- You want to see an equal number of schedulers on each NUMA node
-- Watch out if SQL Server 2017 Standard Edition has been installed 
-- on a physical or virtual machine with more than four sockets or more than 24 physical cores

-- sys.dm_os_nodes (Transact-SQL)
-- https://bit.ly/2pn5Mw8

-- Balancing Your Available SQL Server Core Licenses Evenly Across NUMA Nodes
-- https://bit.ly/2vfC4Rq



-- Good basic information about OS memory amounts and state  (Query 14) (System Memory)
SELECT total_physical_memory_kb/1024 AS [Physical Memory (MB)], 
       available_physical_memory_kb/1024 AS [Available Memory (MB)], 
       total_page_file_kb/1024 AS [Total Page File (MB)], 
	   available_page_file_kb/1024 AS [Available Page File (MB)], 
	   system_cache_kb/1024 AS [System Cache (MB)],
       system_memory_state_desc AS [System Memory State]
FROM sys.dm_os_sys_memory WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You want to see "Available physical memory is high" for System Memory State
-- This indicates that you are not under external memory pressure

-- Possible System Memory State values:
-- Available physical memory is high
-- Physical memory usage is steady
-- Available physical memory is low
-- Available physical memory is running low
-- Physical memory state is transitioning

-- sys.dm_os_sys_memory (Transact-SQL)
-- https://bit.ly/2pcV0xq



-- You can skip the next two queries if you know you don't have a clustered instance


-- Get information about your cluster nodes and their status  (Query 15) (Cluster Node Properties)
-- (if your database server is in a failover cluster)
SELECT NodeName, status_description, is_current_owner
FROM sys.dm_os_cluster_nodes WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Knowing which node owns the cluster resources is critical
-- Especially when you are installing Windows or SQL Server updates
-- You will see no results if your instance is not clustered

-- Recommended hotfixes and updates for Windows Server 2012 R2-based failover clusters
-- https://bit.ly/1z5BfCw


-- Get information about any AlwaysOn AG cluster this instance is a part of (Query 16) (AlwaysOn AG Cluster)
SELECT cluster_name, quorum_type_desc, quorum_state_desc
FROM sys.dm_hadr_cluster WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You will see no results if your instance is not using AlwaysOn AGs


-- Good overview of AG health and status (Query 17) (AlwaysOn AG Status)
SELECT ag.name AS [AG Name], ar.replica_server_name, ar.availability_mode_desc, adc.[database_name], 
       drs.is_local, drs.is_primary_replica, drs.synchronization_state_desc, drs.is_commit_participant, 
	   drs.synchronization_health_desc, drs.recovery_lsn, drs.truncation_lsn, drs.last_sent_lsn, 
	   drs.last_sent_time, drs.last_received_lsn, drs.last_received_time, drs.last_hardened_lsn, 
	   drs.last_hardened_time, drs.last_redone_lsn, drs.last_redone_time, drs.log_send_queue_size, 
	   drs.log_send_rate, drs.redo_queue_size, drs.redo_rate, drs.filestream_send_rate, 
	   drs.end_of_log_lsn, drs.last_commit_lsn, drs.last_commit_time, drs.database_state_desc 
FROM sys.dm_hadr_database_replica_states AS drs WITH (NOLOCK)
INNER JOIN sys.availability_databases_cluster AS adc WITH (NOLOCK)
ON drs.group_id = adc.group_id 
AND drs.group_database_id = adc.group_database_id
INNER JOIN sys.availability_groups AS ag WITH (NOLOCK)
ON ag.group_id = drs.group_id
INNER JOIN sys.availability_replicas AS ar WITH (NOLOCK)
ON drs.group_id = ar.group_id 
AND drs.replica_id = ar.replica_id
ORDER BY ag.name, ar.replica_server_name, adc.[database_name] OPTION (RECOMPILE);

-- You will see no results if your instance is not using AlwaysOn AGs

-- SQL Server 2016 � It Just Runs Faster: Always On Availability Groups Turbocharged
-- https://bit.ly/2dn1H6r


-- Hardware information from SQL Server 2016 SP2  (Query 18) (Hardware Info)
SELECT cpu_count AS [Logical CPU Count], scheduler_count, 
       (socket_count * cores_per_socket) AS [Physical Core Count], 
       socket_count AS [Socket Count], cores_per_socket, numa_node_count,
       physical_memory_kb/1024 AS [Physical Memory (MB)], 
       max_workers_count AS [Max Workers Count], 
	   affinity_type_desc AS [Affinity Type], 
       sqlserver_start_time AS [SQL Server Start Time],
	   DATEDIFF(hour, sqlserver_start_time, GETDATE()) AS [SQL Server Up Time (hrs)],
	   virtual_machine_type_desc AS [Virtual Machine Type], 
       softnuma_configuration_desc AS [Soft NUMA Configuration], 
	   sql_memory_model_desc
FROM sys.dm_os_sys_info WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Gives you some good basic hardware information about your database server
-- Note: virtual_machine_type_desc of HYPERVISOR does not automatically mean you are running SQL Server inside of a VM
-- It merely indicates that you have a hypervisor running on your host

-- sys.dm_os_sys_info (Transact-SQL)
-- https://bit.ly/2pczOYs

-- Soft NUMA configuration was a new column for SQL Server 2016
-- OFF = Soft-NUMA feature is OFF
-- ON = SQL Server automatically determines the NUMA node sizes for Soft-NUMA
-- MANUAL = Manually configured soft-NUMA

-- Configure SQL Server to Use Soft-NUMA (SQL Server)
-- https://bit.ly/2HTpKJt

-- sql_memory_model_desc values (Added in SQL Server 2016 SP1)
-- CONVENTIONAL
-- LOCK_PAGES
-- LARGE_PAGES
   

-- Get System Manufacturer and model number from SQL Server Error log (Query 19) (System Manufacturer)
EXEC sys.xp_readerrorlog 0, 1, N'Manufacturer';
------ 

-- This can help you determine the capabilities and capacities of your database server
-- Can also be used to confirm if you are running in a VM
-- This query might take a few seconds if you have not recycled your error log recently
-- This query will return no results if your error log has been recycled since the instance was started


-- Get pvscsi info from Windows Registry  (Query 20) (PVSCSI Driver Parameters)
EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SYSTEM\CurrentControlSet\services\pvscsi\Parameters\Device', N'DriverParameter';
------

-- This is valid for VMware VMs
-- Recommended value for intensive I/O patterns from VMware is: RequestRingPages=32,MaxQueueDepth=254
-- https://kb.vmware.com/s/article/2053145



-- Get BIOS date from Windows Registry (Query 21) (BIOS Date)
EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'HARDWARE\DESCRIPTION\System\BIOS', N'BiosReleaseDate';
------

-- Helps you understand whether the main system BIOS is up to date, and the possible age of the hardware
-- Not as useful for virtualization


-- Get processor description from Windows Registry  (Query 22) (Processor Description)
EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'HARDWARE\DESCRIPTION\System\CentralProcessor\0', N'ProcessorNameString';
------

-- Gives you the model number and rated clock speed of your processor(s)
-- Your processors may be running at less than the rated clock speed due
-- to the Windows Power Plan or hardware power management

-- You can use CPU-Z to get your actual CPU core speed and a lot of other useful information
-- https://bit.ly/QhR6xF

-- You can learn more about processor selection for SQL Server by following this link
-- https://bit.ly/2F3aVlP



-- See if buffer pool extension (BPE) is enabled (Query 23) (BPE Configuration)
SELECT [path], state_description, current_size_in_kb, 
CAST(current_size_in_kb/1048576.0 AS DECIMAL(10,2)) AS [Size (GB)]
FROM sys.dm_os_buffer_pool_extension_configuration WITH (NOLOCK) OPTION (RECOMPILE);
------

-- BPE is available in both Standard Edition and Enterprise Edition
-- It is a more interesting feature for Standard Edition

-- Buffer Pool Extension to SSDs in SQL Server 2014
-- https://bit.ly/1bm08m8

-- Buffer Pool Extension
-- https://bit.ly/2oBuieO



-- Look at buffer descriptors to see BPE usage by database (Query 24) (BPE Usage) 
SELECT DB_NAME(database_id) AS [Database Name], COUNT(page_id) AS [Page Count],
CAST(COUNT(*)/128.0 AS DECIMAL(10, 2)) AS [Buffer size(MB)], 
AVG(read_microsec) AS [Avg Read Time (microseconds)]
FROM sys.dm_os_buffer_descriptors WITH (NOLOCK)
WHERE database_id <> 32767
AND is_in_bpool_extension = 1
GROUP BY DB_NAME(database_id) 
ORDER BY [Buffer size(MB)] DESC OPTION (RECOMPILE);
------

-- You will see no results if BPE is not enabled or if there is no BPE usage


-- Get information on location, time and size of any memory dumps from SQL Server  (Query 25) (Memory Dump Info)
SELECT [filename], creation_time, size_in_bytes/1048576.0 AS [Size (MB)]
FROM sys.dm_server_memory_dumps WITH (NOLOCK) 
ORDER BY creation_time DESC OPTION (RECOMPILE);
------

-- This will not return any rows if you have 
-- not had any memory dumps (which is a good thing)

-- sys.dm_server_memory_dumps (Transact-SQL)
-- https://bit.ly/2elwWll



-- Look at Suspect Pages table (Query 26) (Suspect Pages)
SELECT DB_NAME(database_id) AS [Database Name], [file_id], page_id, 
       event_type, error_count, last_update_date 
FROM msdb.dbo.suspect_pages WITH (NOLOCK)
ORDER BY database_id OPTION (RECOMPILE);
------

-- event_type value descriptions
-- 1 = 823 error caused by an operating system CRC error
--     or 824 error other than a bad checksum or a torn page (for example, a bad page ID)
-- 2 = Bad checksum
-- 3 = Torn page
-- 4 = Restored (The page was restored after it was marked bad)
-- 5 = Repaired (DBCC repaired the page)
-- 7 = Deallocated by DBCC

-- Ideally, this query returns no results. The table is limited to 1000 rows.
-- If you do get results here, you should do further investigation to determine the root cause

-- Manage the suspect_pages Table
-- https://bit.ly/2Fvr1c9


-- Get number of data files in tempdb database (Query 27) (TempDB Data Files)
EXEC sys.xp_readerrorlog 0, 1, N'The tempdb database has';
------

-- Get the number of data files in the tempdb database
-- 4-8 data files that are all the same size is a good starting point
-- This query will return no results if your error log has been recycled since the instance was last started


-- File names and paths for all user and system databases on instance  (Query 28) (Database Filenames and Paths)
SELECT DB_NAME([database_id]) AS [Database Name], 
       [file_id], [name], physical_name, [type_desc], state_desc,
	   is_percent_growth, growth,
	   CONVERT(bigint, growth/128.0) AS [Growth in MB], 
       CONVERT(bigint, size/128.0) AS [Total Size in MB]
FROM sys.master_files WITH (NOLOCK)
ORDER BY DB_NAME([database_id]), [file_id] OPTION (RECOMPILE);
------

-- Things to look at:
-- Are data files and log files on different drives?
-- Is everything on the C: drive?
-- Is tempdb on dedicated drives?
-- Is there only one tempdb data file?
-- Are all of the tempdb data files the same size?
-- Are there multiple data files for user databases?
-- Is percent growth enabled for any files (which is bad)?



-- Volume info for all LUNS that have database files on the current instance (Query 29) (Volume Info)
SELECT DISTINCT vs.volume_mount_point, vs.file_system_type, vs.logical_volume_name, 
CONVERT(DECIMAL(18,2), vs.total_bytes/1073741824.0) AS [Total Size (GB)],
CONVERT(DECIMAL(18,2), vs.available_bytes/1073741824.0) AS [Available Size (GB)],  
CONVERT(DECIMAL(18,2), vs.available_bytes * 1. / vs.total_bytes * 100.) AS [Space Free %],
vs.supports_compression, vs.is_compressed, 
vs.supports_sparse_files, vs.supports_alternate_streams
FROM sys.master_files AS f WITH (NOLOCK)
CROSS APPLY sys.dm_os_volume_stats(f.database_id, f.[file_id]) AS vs 
ORDER BY vs.volume_mount_point OPTION (RECOMPILE);
------

-- Shows you the total and free space on the LUNs where you have database files
-- Being low on free space can negatively affect performance

-- sys.dm_os_volume_stats (Transact-SQL)
-- https://bit.ly/2oBPNNr



-- Drive level latency information (Query 30) (Drive Level Latency)
-- Based on code from Jimmy May
SELECT tab.[Drive], tab.volume_mount_point AS [Volume Mount Point], 
	CASE 
		WHEN num_of_reads = 0 THEN 0 
		ELSE (io_stall_read_ms/num_of_reads) 
	END AS [Read Latency],
	CASE 
		WHEN num_of_writes = 0 THEN 0 
		ELSE (io_stall_write_ms/num_of_writes) 
	END AS [Write Latency],
	CASE 
		WHEN (num_of_reads = 0 AND num_of_writes = 0) THEN 0 
		ELSE (io_stall/(num_of_reads + num_of_writes)) 
	END AS [Overall Latency],
	CASE 
		WHEN num_of_reads = 0 THEN 0 
		ELSE (num_of_bytes_read/num_of_reads) 
	END AS [Avg Bytes/Read],
	CASE 
		WHEN num_of_writes = 0 THEN 0 
		ELSE (num_of_bytes_written/num_of_writes) 
	END AS [Avg Bytes/Write],
	CASE 
		WHEN (num_of_reads = 0 AND num_of_writes = 0) THEN 0 
		ELSE ((num_of_bytes_read + num_of_bytes_written)/(num_of_reads + num_of_writes)) 
	END AS [Avg Bytes/Transfer]
FROM (SELECT LEFT(UPPER(mf.physical_name), 2) AS Drive, SUM(num_of_reads) AS num_of_reads,
	         SUM(io_stall_read_ms) AS io_stall_read_ms, SUM(num_of_writes) AS num_of_writes,
	         SUM(io_stall_write_ms) AS io_stall_write_ms, SUM(num_of_bytes_read) AS num_of_bytes_read,
	         SUM(num_of_bytes_written) AS num_of_bytes_written, SUM(io_stall) AS io_stall, vs.volume_mount_point 
      FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS vfs
      INNER JOIN sys.master_files AS mf WITH (NOLOCK)
      ON vfs.database_id = mf.database_id AND vfs.file_id = mf.file_id
	  CROSS APPLY sys.dm_os_volume_stats(mf.database_id, mf.[file_id]) AS vs 
      GROUP BY LEFT(UPPER(mf.physical_name), 2), vs.volume_mount_point) AS tab
ORDER BY [Overall Latency] OPTION (RECOMPILE);
------

-- Shows you the drive-level latency for reads and writes, in milliseconds
-- Latency above 30-40ms is usually a problem
-- These latency numbers include all file activity against all SQL Server 
-- database files on each drive since SQL Server was last started


-- Calculates average stalls per read, per write, and per total input/output for each database file  (Query 31) (IO Latency by File)
SELECT DB_NAME(fs.database_id) AS [Database Name], CAST(fs.io_stall_read_ms/(1.0 + fs.num_of_reads) AS NUMERIC(10,1)) AS [avg_read_latency_ms],
CAST(fs.io_stall_write_ms/(1.0 + fs.num_of_writes) AS NUMERIC(10,1)) AS [avg_write_latency_ms],
CAST((fs.io_stall_read_ms + fs.io_stall_write_ms)/(1.0 + fs.num_of_reads + fs.num_of_writes) AS NUMERIC(10,1)) AS [avg_io_latency_ms],
CONVERT(DECIMAL(18,2), mf.size/128.0) AS [File Size (MB)], mf.physical_name, mf.type_desc, fs.io_stall_read_ms, fs.num_of_reads, 
fs.io_stall_write_ms, fs.num_of_writes, fs.io_stall_read_ms + fs.io_stall_write_ms AS [io_stalls], fs.num_of_reads + fs.num_of_writes AS [total_io],
io_stall_queued_read_ms AS [Resource Governor Total Read IO Latency (ms)], io_stall_queued_write_ms AS [Resource Governor Total Write IO Latency (ms)] 
FROM sys.dm_io_virtual_file_stats(null,null) AS fs
INNER JOIN sys.master_files AS mf WITH (NOLOCK)
ON fs.database_id = mf.database_id
AND fs.[file_id] = mf.[file_id]
ORDER BY avg_io_latency_ms DESC OPTION (RECOMPILE);
------

-- Helps determine which database files on the entire instance have the most I/O bottlenecks
-- This can help you decide whether certain LUNs are overloaded and whether you might
-- want to move some files to a different location or perhaps improve your I/O performance
-- These latency numbers include all file activity against each SQL Server 
-- database file since SQL Server was last started


-- Look for I/O requests taking longer than 15 seconds in the six most recent SQL Server Error Logs (Query 32) (IO Warnings)
CREATE TABLE #IOWarningResults(LogDate datetime, ProcessInfo sysname, LogText nvarchar(1000));

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 0, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 1, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 2, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 3, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 4, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 5, 1, N'taking longer than 15 seconds';

SELECT LogDate, ProcessInfo, LogText
FROM #IOWarningResults
ORDER BY LogDate DESC;

DROP TABLE #IOWarningResults;
------  

-- Finding 15 second I/O warnings in the SQL Server Error Log is useful evidence of
-- poor I/O performance (which might have many different causes)
-- Look to see if you see any patterns in the results (same files, same drives, same time of day, etc.)

-- Diagnostics in SQL Server help detect stalled and stuck I/O operations
-- https://bit.ly/2qtaw73



-- Resource Governor Resource Pool information (Query 33) (RG Resource Pools)
SELECT pool_id, [Name], statistics_start_time,
       min_memory_percent, max_memory_percent,  
       max_memory_kb/1024 AS [max_memory_mb],  
       used_memory_kb/1024 AS [used_memory_mb],   
       target_memory_kb/1024 AS [target_memory_mb],
	   min_iops_per_volume, max_iops_per_volume
FROM sys.dm_resource_governor_resource_pools WITH (NOLOCK)
OPTION (RECOMPILE);
------

-- sys.dm_resource_governor_resource_pools (Transact-SQL)
-- https://bit.ly/2MVU0Vy
   


-- Recovery model, log reuse wait description, log file size, log usage size  (Query 34) (Database Properties)
-- and compatibility level for all databases on instance
SELECT db.[name] AS [Database Name], SUSER_SNAME(db.owner_sid) AS [Database Owner], db.recovery_model_desc AS [Recovery Model], 
db.state_desc, db.containment_desc, db.log_reuse_wait_desc AS [Log Reuse Wait Description], 
CONVERT(DECIMAL(18,2), ls.cntr_value/1024.0) AS [Log Size (MB)], CONVERT(DECIMAL(18,2), lu.cntr_value/1024.0) AS [Log Used (MB)],
CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log Used %], 
db.[compatibility_level] AS [DB Compatibility Level], 
db.is_mixed_page_allocation_on, db.page_verify_option_desc AS [Page Verify Option], 
db.is_auto_create_stats_on, db.is_auto_update_stats_on, db.is_auto_update_stats_async_on, db.is_parameterization_forced, 
db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on, db.is_auto_close_on, db.is_auto_shrink_on, 
db.target_recovery_time_in_seconds, db.is_cdc_enabled, db.is_published, db.is_distributor,
db.group_database_id, db.replica_id,db.is_memory_optimized_elevate_to_snapshot_on, 
db.delayed_durability_desc, db.is_auto_create_stats_incremental_on,
db.is_query_store_on, db.is_sync_with_backup, 
db.is_supplemental_logging_enabled, db.is_remote_data_archive_enabled,
db.is_encrypted, de.encryption_state, de.percent_complete, de.key_algorithm, de.key_length      
FROM sys.databases AS db WITH (NOLOCK)
INNER JOIN sys.dm_os_performance_counters AS lu WITH (NOLOCK)
ON db.name = lu.instance_name
INNER JOIN sys.dm_os_performance_counters AS ls WITH (NOLOCK)
ON db.name = ls.instance_name
LEFT OUTER JOIN sys.dm_database_encryption_keys AS de WITH (NOLOCK)
ON db.database_id = de.database_id
WHERE lu.counter_name LIKE N'Log File(s) Used Size (KB)%' 
AND ls.counter_name LIKE N'Log File(s) Size (KB)%'
AND ls.cntr_value > 0 
ORDER BY db.[name] OPTION (RECOMPILE);
------

-- Things to look at:
-- How many databases are on the instance?
-- What recovery models are they using?
-- What is the log reuse wait description?
-- How full are the transaction logs?
-- What compatibility level are the databases on? 
-- What is the Page Verify Option? (should be CHECKSUM)
-- Is Auto Update Statistics Asynchronously enabled?
-- Is Delayed Durability enabled
-- Make sure auto_shrink and auto_close are not enabled!

-- is_mixed_page_allocation_on is a new property for SQL Server 2016. Equivalent to TF 1118 for a user database
-- SQL Server 2016: Changes in default behavior for autogrow and allocations for tempdb and user databases
-- https://bit.ly/2evRZSR

-- A non-zero value for target_recovery_time_in_seconds means that indirect checkpoint is enabled 
-- If the setting has a zero value it indicates that automatic checkpoint is enabled

-- Changes in SQL Server 2016 Checkpoint Behavior
-- https://bit.ly/2pdggk3


-- Missing Indexes for all databases by Index Advantage  (Query 35) (Missing Indexes All Databases)
SELECT CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage],
FORMAT(migs.last_user_seek, 'yyyy-MM-dd HH:mm:ss') AS [last_user_seek], 
mid.[statement] AS [Database.Schema.Table],
COUNT(1) OVER(PARTITION BY mid.[statement]) AS [missing_indexes_for_table],
COUNT(1) OVER(PARTITION BY mid.[statement], equality_columns) AS [similar_missing_indexes_for_table],
mid.equality_columns, mid.inequality_columns, mid.included_columns,
migs.unique_compiles, migs.user_seeks, 
CONVERT(decimal(18,2), migs.avg_total_user_cost) AS [avg_total_user_cost], migs.avg_user_impact 
FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)
INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)
ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)
ON mig.index_handle = mid.index_handle
ORDER BY index_advantage DESC OPTION (RECOMPILE);
------

-- Getting missing index information for all of the databases on the instance is very useful
-- Look at last user seek time, number of user seeks to help determine source and importance
-- Also look at avg_user_impact and avg_total_user_cost to help determine importance
-- SQL Server is overly eager to add included columns, so beware
-- Do not just blindly add indexes that show up from this query!!!

-- SQL Server Index Design Guide
-- https://bit.ly/2qtZr4N



-- Get VLF Counts for all databases on the instance (Query 36) (VLF Counts)
SELECT [name] AS [Database Name], [VLF Count]
FROM sys.databases AS db WITH (NOLOCK)
CROSS APPLY (SELECT file_id, COUNT(*) AS [VLF Count]
		     FROM sys.dm_db_log_info(db.database_id)
			 GROUP BY file_id) AS li
ORDER BY [VLF Count] DESC OPTION (RECOMPILE);
------

-- High VLF counts can affect write performance to the log file
-- and they can make full database restores and crash recovery take much longer
-- Try to keep your VLF counts under 200 in most cases (depending on log file size)

-- Important change to VLF creation algorithm in SQL Server 2014
-- https://bit.ly/2Hsjbg4

-- SQL Server Transaction Log Architecture and Management Guide
-- https://bit.ly/2JjmQRZ



-- Get CPU utilization by database (Query 37) (CPU Usage by Database)
WITH DB_CPU_Stats
AS
(SELECT pa.DatabaseID, DB_Name(pa.DatabaseID) AS [Database Name], SUM(qs.total_worker_time/1000) AS [CPU_Time_Ms]
 FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
 CROSS APPLY (SELECT CONVERT(int, value) AS [DatabaseID] 
              FROM sys.dm_exec_plan_attributes(qs.plan_handle)
              WHERE attribute = N'dbid') AS pa
 GROUP BY DatabaseID)
SELECT ROW_NUMBER() OVER(ORDER BY [CPU_Time_Ms] DESC) AS [CPU Rank],
       [Database Name], [CPU_Time_Ms] AS [CPU Time (ms)], 
       CAST([CPU_Time_Ms] * 1.0 / SUM([CPU_Time_Ms]) OVER() * 100.0 AS DECIMAL(5, 2)) AS [CPU Percent]
FROM DB_CPU_Stats
WHERE DatabaseID <> 32767 -- ResourceDB
ORDER BY [CPU Rank] OPTION (RECOMPILE);
------

-- Helps determine which database is using the most CPU resources on the instance
-- Note: This only reflects CPU usage from the currently cached query plans


-- Get I/O utilization by database (Query 38) (IO Usage By Database)
WITH Aggregate_IO_Statistics
AS (SELECT DB_NAME(database_id) AS [Database Name],
    CAST(SUM(num_of_bytes_read + num_of_bytes_written) / 1048576 AS DECIMAL(12, 2)) AS [ioTotalMB],
    CAST(SUM(num_of_bytes_read ) / 1048576 AS DECIMAL(12, 2)) AS [ioReadMB],
    CAST(SUM(num_of_bytes_written) / 1048576 AS DECIMAL(12, 2)) AS [ioWriteMB]
    FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS [DM_IO_STATS]
    GROUP BY database_id)
SELECT ROW_NUMBER() OVER (ORDER BY ioTotalMB DESC) AS [I/O Rank],
        [Database Name], ioTotalMB AS [Total I/O (MB)],
        CAST(ioTotalMB / SUM(ioTotalMB) OVER () * 100.0 AS DECIMAL(5, 2)) AS [Total I/O %],
        ioReadMB AS [Read I/O (MB)], 
		CAST(ioReadMB / SUM(ioReadMB) OVER () * 100.0 AS DECIMAL(5, 2)) AS [Read I/O %],
        ioWriteMB AS [Write I/O (MB)], 
		CAST(ioWriteMB / SUM(ioWriteMB) OVER () * 100.0 AS DECIMAL(5, 2)) AS [Write I/O %]
FROM Aggregate_IO_Statistics
ORDER BY [I/O Rank] OPTION (RECOMPILE);
------

-- Helps determine which database is using the most I/O resources on the instance
-- These numbers are cumulative since the last service restart
-- They include all I/O activity, not just the nominal I/O workload


-- Get total buffer usage by database for current instance  (Query 39) (Total Buffer Usage by Database)
-- This make take some time to run on a busy instance
WITH AggregateBufferPoolUsage
AS
(SELECT DB_NAME(database_id) AS [Database Name],
CAST(COUNT(*) * 8/1024.0 AS DECIMAL (10,2))  AS [CachedSize]
FROM sys.dm_os_buffer_descriptors WITH (NOLOCK)
WHERE database_id <> 32767 -- ResourceDB
GROUP BY DB_NAME(database_id))
SELECT ROW_NUMBER() OVER(ORDER BY CachedSize DESC) AS [Buffer Pool Rank], [Database Name], CachedSize AS [Cached Size (MB)],
       CAST(CachedSize / SUM(CachedSize) OVER() * 100.0 AS DECIMAL(5,2)) AS [Buffer Pool Percent]
FROM AggregateBufferPoolUsage
ORDER BY [Buffer Pool Rank] OPTION (RECOMPILE);
------

-- Tells you how much memory (in the buffer pool) 
-- is being used by each database on the instance


-- Get tempdb version store space usage by database (Query 40) (Version Store Space Usage)
SELECT DB_NAME(database_id) AS [Database Name],
       reserved_page_count AS [Version Store Reserved Page Count], 
	   reserved_space_kb/1024 AS [Version Store Reserved Space (MB)] 
FROM sys.dm_tran_version_store_space_usage WITH (NOLOCK) 
ORDER BY reserved_space_kb/1024 DESC OPTION (RECOMPILE);
------  

-- sys.dm_tran_version_store_space_usage (Transact-SQL)
-- https://bit.ly/2vh3Bmk




-- Clear Wait Stats with this command
-- DBCC SQLPERF('sys.dm_os_wait_stats', CLEAR);

-- Isolate top waits for server instance since last restart or wait statistics clear  (Query 41) (Top Waits)
WITH [Waits] 
AS (SELECT wait_type, wait_time_ms/ 1000.0 AS [WaitS],
          (wait_time_ms - signal_wait_time_ms) / 1000.0 AS [ResourceS],
           signal_wait_time_ms / 1000.0 AS [SignalS],
           waiting_tasks_count AS [WaitCount],
           100.0 *  wait_time_ms / SUM (wait_time_ms) OVER() AS [Percentage],
           ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS [RowNum]
    FROM sys.dm_os_wait_stats WITH (NOLOCK)
    WHERE [wait_type] NOT IN (
        N'BROKER_EVENTHANDLER', N'BROKER_RECEIVE_WAITFOR', N'BROKER_TASK_STOP',
		N'BROKER_TO_FLUSH', N'BROKER_TRANSMITTER', N'CHECKPOINT_QUEUE',
        N'CHKPT', N'CLR_AUTO_EVENT', N'CLR_MANUAL_EVENT', N'CLR_SEMAPHORE', N'CXCONSUMER',
        N'DBMIRROR_DBM_EVENT', N'DBMIRROR_EVENTS_QUEUE', N'DBMIRROR_WORKER_QUEUE',
		N'DBMIRRORING_CMD', N'DIRTY_PAGE_POLL', N'DISPATCHER_QUEUE_SEMAPHORE',
        N'EXECSYNC', N'FSAGENT', N'FT_IFTS_SCHEDULER_IDLE_WAIT', N'FT_IFTSHC_MUTEX',
        N'HADR_CLUSAPI_CALL', N'HADR_FILESTREAM_IOMGR_IOCOMPLETION', N'HADR_LOGCAPTURE_WAIT', 
		N'HADR_NOTIFICATION_DEQUEUE', N'HADR_TIMER_TASK', N'HADR_WORK_QUEUE',
        N'KSOURCE_WAKEUP', N'LAZYWRITER_SLEEP', N'LOGMGR_QUEUE', 
		N'MEMORY_ALLOCATION_EXT', N'ONDEMAND_TASK_QUEUE',
		N'PARALLEL_REDO_DRAIN_WORKER', N'PARALLEL_REDO_LOG_CACHE', N'PARALLEL_REDO_TRAN_LIST',
		N'PARALLEL_REDO_WORKER_SYNC', N'PARALLEL_REDO_WORKER_WAIT_WORK',
		N'PREEMPTIVE_HADR_LEASE_MECHANISM', N'PREEMPTIVE_SP_SERVER_DIAGNOSTICS',
		N'PREEMPTIVE_OS_LIBRARYOPS', N'PREEMPTIVE_OS_COMOPS', N'PREEMPTIVE_OS_CRYPTOPS',
		N'PREEMPTIVE_OS_PIPEOPS', N'PREEMPTIVE_OS_AUTHENTICATIONOPS',
		N'PREEMPTIVE_OS_GENERICOPS', N'PREEMPTIVE_OS_VERIFYTRUST',
		N'PREEMPTIVE_OS_FILEOPS', N'PREEMPTIVE_OS_DEVICEOPS', N'PREEMPTIVE_OS_QUERYREGISTRY',
		N'PREEMPTIVE_OS_WRITEFILE',
		N'PREEMPTIVE_XE_CALLBACKEXECUTE', N'PREEMPTIVE_XE_DISPATCHER',
		N'PREEMPTIVE_XE_GETTARGETSTATE', N'PREEMPTIVE_XE_SESSIONCOMMIT',
		N'PREEMPTIVE_XE_TARGETINIT', N'PREEMPTIVE_XE_TARGETFINALIZE',
        N'PWAIT_ALL_COMPONENTS_INITIALIZED', N'PWAIT_DIRECTLOGCONSUMER_GETNEXT',
		N'QDS_PERSIST_TASK_MAIN_LOOP_SLEEP',
		N'QDS_ASYNC_QUEUE',
        N'QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP', N'REQUEST_FOR_DEADLOCK_SEARCH',
		N'RESOURCE_QUEUE', N'SERVER_IDLE_CHECK', N'SLEEP_BPOOL_FLUSH', N'SLEEP_DBSTARTUP',
		N'SLEEP_DCOMSTARTUP', N'SLEEP_MASTERDBREADY', N'SLEEP_MASTERMDREADY',
        N'SLEEP_MASTERUPGRADED', N'SLEEP_MSDBSTARTUP', N'SLEEP_SYSTEMTASK', N'SLEEP_TASK',
        N'SLEEP_TEMPDBSTARTUP', N'SNI_HTTP_ACCEPT', N'SP_SERVER_DIAGNOSTICS_SLEEP',
		N'SQLTRACE_BUFFER_FLUSH', N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', N'SQLTRACE_WAIT_ENTRIES',
		N'WAIT_FOR_RESULTS', N'WAITFOR', N'WAITFOR_TASKSHUTDOWN', N'WAIT_XTP_HOST_WAIT',
		N'WAIT_XTP_OFFLINE_CKPT_NEW_LOG', N'WAIT_XTP_CKPT_CLOSE', N'WAIT_XTP_RECOVERY',
		N'XE_BUFFERMGR_ALLPROCESSED_EVENT', N'XE_DISPATCHER_JOIN',
        N'XE_DISPATCHER_WAIT', N'XE_LIVE_TARGET_TVF', N'XE_TIMER_EVENT')
    AND waiting_tasks_count > 0)
SELECT
    MAX (W1.wait_type) AS [WaitType],
	CAST (MAX (W1.Percentage) AS DECIMAL (5,2)) AS [Wait Percentage],
	CAST ((MAX (W1.WaitS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgWait_Sec],
    CAST ((MAX (W1.ResourceS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgRes_Sec],
    CAST ((MAX (W1.SignalS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgSig_Sec], 
    CAST (MAX (W1.WaitS) AS DECIMAL (16,2)) AS [Wait_Sec],
    CAST (MAX (W1.ResourceS) AS DECIMAL (16,2)) AS [Resource_Sec],
    CAST (MAX (W1.SignalS) AS DECIMAL (16,2)) AS [Signal_Sec],
    MAX (W1.WaitCount) AS [Wait Count],
	CAST (N'https://www.sqlskills.com/help/waits/' + W1.wait_type AS XML) AS [Help/Info URL]
FROM Waits AS W1
INNER JOIN Waits AS W2
ON W2.RowNum <= W1.RowNum
GROUP BY W1.RowNum, W1.wait_type
HAVING SUM (W2.Percentage) - MAX (W1.Percentage) < 99 -- percentage threshold
OPTION (RECOMPILE);
------

-- Cumulative wait stats are not as useful on an idle instance that is not under load or performance pressure

-- SQL Server Wait Types Library (Paul Randal)
-- https://bit.ly/2ePzYO2

-- The SQL Server Wait Type Repository
-- https://bit.ly/1afzfjC

-- Wait statistics, or please tell me where it hurts
-- https://bit.ly/2wsQHQE

-- SQL Server 2005 Performance Tuning using the Waits and Queues
-- https://bit.ly/1o2NFoF

-- sys.dm_os_wait_stats (Transact-SQL)
-- https://bit.ly/2Hjq9Yl



-- Get a count of SQL connections by IP address (Query 42) (Connection Counts by IP Address)
SELECT ec.client_net_address, es.[program_name], es.[host_name], es.login_name, 
COUNT(ec.session_id) AS [connection count] 
FROM sys.dm_exec_sessions AS es WITH (NOLOCK) 
INNER JOIN sys.dm_exec_connections AS ec WITH (NOLOCK) 
ON es.session_id = ec.session_id 
GROUP BY ec.client_net_address, es.[program_name], es.[host_name], es.login_name  
ORDER BY ec.client_net_address, es.[program_name] OPTION (RECOMPILE);
------

-- This helps you figure where your database load is coming from
-- and verifies connectivity from other machines

-- Solving Connectivity errors to SQL Server
-- https://bit.ly/2EgzoD0



-- Get Average Task Counts (run multiple times)  (Query 43) (Avg Task Counts)
SELECT AVG(current_tasks_count) AS [Avg Task Count], 
AVG(work_queue_count) AS [Avg Work Queue Count],
AVG(runnable_tasks_count) AS [Avg Runnable Task Count],
AVG(pending_disk_io_count) AS [Avg Pending DiskIO Count]
FROM sys.dm_os_schedulers WITH (NOLOCK)
WHERE scheduler_id < 255 OPTION (RECOMPILE);
------

-- Sustained values above 10 suggest further investigation in that area
-- High Avg Task Counts are often caused by blocking/deadlocking or other resource contention

-- Sustained values above 1 suggest further investigation in that area
-- High Avg Runnable Task Counts are a good sign of CPU pressure
-- High Avg Pending DiskIO Counts are a sign of disk pressure

-- How to Do Some Very Basic SQL Server Monitoring
-- https://bit.ly/2q3Btgt



-- Detect blocking (run multiple times)  (Query 44) (Detect Blocking)
SELECT t1.resource_type AS [lock type], DB_NAME(resource_database_id) AS [database],
t1.resource_associated_entity_id AS [blk object],t1.request_mode AS [lock req],  -- lock requested
t1.request_session_id AS [waiter sid], t2.wait_duration_ms AS [wait time],       -- spid of waiter  
(SELECT [text] FROM sys.dm_exec_requests AS r WITH (NOLOCK)                      -- get sql for waiter
CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) 
WHERE r.session_id = t1.request_session_id) AS [waiter_batch],
(SELECT SUBSTRING(qt.[text],r.statement_start_offset/2, 
    (CASE WHEN r.statement_end_offset = -1 
    THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2 
    ELSE r.statement_end_offset END - r.statement_start_offset)/2) 
FROM sys.dm_exec_requests AS r WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) AS qt
WHERE r.session_id = t1.request_session_id) AS [waiter_stmt],					-- statement blocked
t2.blocking_session_id AS [blocker sid],										-- spid of blocker
(SELECT [text] FROM sys.sysprocesses AS p										-- get sql for blocker
CROSS APPLY sys.dm_exec_sql_text(p.[sql_handle]) 
WHERE p.spid = t2.blocking_session_id) AS [blocker_batch]
FROM sys.dm_tran_locks AS t1 WITH (NOLOCK)
INNER JOIN sys.dm_os_waiting_tasks AS t2 WITH (NOLOCK)
ON t1.lock_owner_address = t2.resource_address OPTION (RECOMPILE);
------

-- Helps troubleshoot blocking and deadlocking issues
-- The results will change from second to second on a busy system
-- You should run this query multiple times when you see signs of blocking



-- Get CPU Utilization History for last 256 minutes (in one minute intervals)  (Query 45) (CPU Utilization History)
DECLARE @ts_now bigint = (SELECT cpu_ticks/(cpu_ticks/ms_ticks) FROM sys.dm_os_sys_info WITH (NOLOCK)); 

SELECT TOP(256) SQLProcessUtilization AS [SQL Server Process CPU Utilization], 
               SystemIdle AS [System Idle Process], 
               100 - SystemIdle - SQLProcessUtilization AS [Other Process CPU Utilization], 
               DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) AS [Event Time] 
FROM (SELECT record.value('(./Record/@id)[1]', 'int') AS record_id, 
			record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') 
			AS [SystemIdle], 
			record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int') 
			AS [SQLProcessUtilization], [timestamp] 
	  FROM (SELECT [timestamp], CONVERT(xml, record) AS [record] 
			FROM sys.dm_os_ring_buffers WITH (NOLOCK)
			WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR' 
			AND record LIKE N'%<SystemHealth>%') AS x) AS y 
ORDER BY record_id DESC OPTION (RECOMPILE);
------

-- Look at the trend over the entire period 
-- Also look at high sustained 'Other Process' CPU Utilization values
-- Note: This query sometimes gives inaccurate results (negative values)
-- on high core count (> 64 cores) systems


-- Get top total worker time queries for entire instance (Query 46) (Top Worker Time Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], 
REPLACE(REPLACE(LEFT(t.[text], 255), CHAR(10),''), CHAR(13),'') AS [Short Query Text],  
qs.total_worker_time AS [Total Worker Time], qs.min_worker_time AS [Min Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.max_worker_time AS [Max Worker Time], 
qs.min_elapsed_time AS [Min Elapsed Time], 
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time], 
qs.max_elapsed_time AS [Max Elapsed Time],
qs.min_logical_reads AS [Min Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.max_logical_reads AS [Max Logical Reads], 
qs.execution_count AS [Execution Count],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
qs.creation_time AS [Creation Time]
--,t.[text] AS [Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
ORDER BY qs.total_worker_time DESC OPTION (RECOMPILE);
------


-- Helps you find the most expensive queries from a CPU perspective across the entire instance
-- Can also help track down parameter sniffing issues



-- Page Life Expectancy (PLE) value for each NUMA node in current instance  (Query 47) (PLE by NUMA Node)
SELECT @@SERVERNAME AS [Server Name], RTRIM([object_name]) AS [Object Name], instance_name, cntr_value AS [Page Life Expectancy]
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Buffer Node%' -- Handles named instances
AND counter_name = N'Page life expectancy' OPTION (RECOMPILE);
------

-- PLE is a good measurement of internal memory pressure
-- Higher PLE is better. Watch the trend over time, not the absolute value
-- This will only return one row for non-NUMA systems

-- Page Life Expectancy isn�t what you think�
-- https://bit.ly/2EgynLa


-- Memory Grants Pending value for current instance  (Query 48) (Memory Grants Pending)
SELECT @@SERVERNAME AS [Server Name], RTRIM([object_name]) AS [Object Name], cntr_value AS [Memory Grants Pending]                                                                                                       
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Memory Manager%' -- Handles named instances
AND counter_name = N'Memory Grants Pending' OPTION (RECOMPILE);
------

-- Run multiple times, and run periodically if you suspect you are under memory pressure
-- Memory Grants Pending above zero for a sustained period is a very strong indicator of internal memory pressure


-- Memory Clerk Usage for instance  (Query 49) (Memory Clerk Usage)
-- Look for high value for CACHESTORE_SQLCP (Ad-hoc query plans)
SELECT TOP(10) mc.[type] AS [Memory Clerk Type], 
       CAST((SUM(mc.pages_kb)/1024.0) AS DECIMAL (15,2)) AS [Memory Usage (MB)] 
FROM sys.dm_os_memory_clerks AS mc WITH (NOLOCK)
GROUP BY mc.[type]  
ORDER BY SUM(mc.pages_kb) DESC OPTION (RECOMPILE);
------

-- MEMORYCLERK_SQLBUFFERPOOL was new for SQL Server 2012. It should be your highest consumer of memory

-- CACHESTORE_SQLCP  SQL Plans         
-- These are cached SQL statements or batches that aren't in stored procedures, functions and triggers
-- Watch out for high values for CACHESTORE_SQLCP
-- Enabling 'optimize for ad hoc workloads' at the instance level can help reduce this
-- Running DBCC FREESYSTEMCACHE ('SQL Plans') periodically may be required to better control this

-- CACHESTORE_OBJCP  Object Plans      
-- These are compiled plans for stored procedures, functions and triggers

-- sys.dm_os_memory_clerks (Transact-SQL)
-- https://bit.ly/2H31xDR



-- Find single-use, ad-hoc and prepared queries that are bloating the plan cache  (Query 50) (Ad hoc Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], t.[text] AS [Query Text], 
cp.objtype AS [Object Type], cp.cacheobjtype AS [Cache Object Type],  
cp.size_in_bytes/1024 AS [Plan Size in KB]
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t
WHERE cp.cacheobjtype = N'Compiled Plan' 
AND cp.objtype IN (N'Adhoc', N'Prepared') 
AND cp.usecounts = 1
ORDER BY cp.size_in_bytes DESC, DB_NAME(t.[dbid]) OPTION (RECOMPILE);
------

-- Gives you the text, type and size of single-use ad-hoc and prepared queries that waste space in the plan cache
-- Enabling 'optimize for ad hoc workloads' for the instance can help (SQL Server 2008 and above only)
-- Running DBCC FREESYSTEMCACHE ('SQL Plans') periodically may be required to better control this
-- Enabling forced parameterization for the database can help, but test first!

-- Plan cache, adhoc workloads and clearing the single-use plan cache bloat
-- https://bit.ly/2EfYOkl


-- Get top total logical reads queries for entire instance (Query 51) (Top Logical Reads Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name],
REPLACE(REPLACE(LEFT(t.[text], 255), CHAR(10),''), CHAR(13),'') AS [Short Query Text], 
qs.total_logical_reads AS [Total Logical Reads],
qs.min_logical_reads AS [Min Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.max_logical_reads AS [Max Logical Reads],   
qs.min_worker_time AS [Min Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.max_worker_time AS [Max Worker Time], 
qs.min_elapsed_time AS [Min Elapsed Time], 
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time], 
qs.max_elapsed_time AS [Max Elapsed Time],
qs.execution_count AS [Execution Count], 
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
qs.creation_time AS [Creation Time]
--,t.[text] AS [Complete Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
ORDER BY qs.total_logical_reads DESC OPTION (RECOMPILE);
------


-- Helps you find the most expensive queries from a memory perspective across the entire instance
-- Can also help track down parameter sniffing issues


-- Get top average elapsed time queries for entire instance (Query 52) (Top Avg Elapsed Time Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], 
REPLACE(REPLACE(LEFT(t.[text], 255), CHAR(10),''), CHAR(13),'') AS [Short Query Text],  
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
qs.min_elapsed_time, qs.max_elapsed_time, qs.last_elapsed_time,
qs.execution_count AS [Execution Count],  
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads], 
qs.total_physical_reads/qs.execution_count AS [Avg Physical Reads], 
qs.total_worker_time/qs.execution_count AS [Avg Worker Time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
qs.creation_time AS [Creation Time]
--,t.[text] AS [Complete Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
ORDER BY qs.total_elapsed_time/qs.execution_count DESC OPTION (RECOMPILE);
------

-- Helps you find the highest average elapsed time queries across the entire instance
-- Can also help track down parameter sniffing issues


-- Look at UDF execution statistics (Query 53) (UDF Stats by DB)
SELECT TOP (25) DB_NAME(database_id) AS [Database Name], 
		   OBJECT_NAME(object_id, database_id) AS [Function Name],
		   total_worker_time, execution_count, total_elapsed_time,  
           total_elapsed_time/execution_count AS [avg_elapsed_time],  
           last_elapsed_time, last_execution_time, cached_time, [type_desc] 
FROM sys.dm_exec_function_stats WITH (NOLOCK) 
ORDER BY total_worker_time DESC OPTION (RECOMPILE);
------

-- sys.dm_exec_function_stats (Transact-SQL)
-- https://bit.ly/2q1Q6BM



-- Database specific queries *****************************************************************

-- **** Please switch to a user database that you are interested in! *****
--USE YourDatabaseName; -- make sure to change to an actual database on your instance, not the master system database
--GO

-- Individual File Sizes and space available for current database  (Query 54) (File Sizes and Space)
SELECT f.name AS [File Name] , f.physical_name AS [Physical Name], 
CAST((f.size/128.0) AS DECIMAL(15,2)) AS [Total Size in MB],
CAST(f.size/128.0 - CAST(FILEPROPERTY(f.name, 'SpaceUsed') AS int)/128.0 AS DECIMAL(15,2)) 
AS [Available Space In MB], f.[file_id], fg.name AS [Filegroup Name],
f.is_percent_growth, f.growth, fg.is_default, fg.is_read_only, 
fg.is_autogrow_all_files
FROM sys.database_files AS f WITH (NOLOCK) 
LEFT OUTER JOIN sys.filegroups AS fg WITH (NOLOCK)
ON f.data_space_id = fg.data_space_id
ORDER BY f.[file_id] OPTION (RECOMPILE);
------

-- Look at how large and how full the files are and where they are located
-- Make sure the transaction log is not full!!

-- is_autogrow_all_files was new for SQL Server 2016. Equivalent to TF 1117 for user databases

-- SQL Server 2016: Changes in default behavior for autogrow and allocations for tempdb and user databases
-- https://bit.ly/2evRZSR


-- Log space usage for current database  (Query 55) (Log Space Usage)
SELECT DB_NAME(lsu.database_id) AS [Database Name], db.recovery_model_desc AS [Recovery Model],
		CAST(lsu.total_log_size_in_bytes/1048576.0 AS DECIMAL(10, 2)) AS [Total Log Space (MB)],
		CAST(lsu.used_log_space_in_bytes/1048576.0 AS DECIMAL(10, 2)) AS [Used Log Space (MB)], 
		CAST(lsu.used_log_space_in_percent AS DECIMAL(10, 2)) AS [Used Log Space %],
		CAST(lsu.log_space_in_bytes_since_last_backup/1048576.0 AS DECIMAL(10, 2)) AS [Used Log Space Since Last Backup (MB)],
		db.log_reuse_wait_desc		 
FROM sys.dm_db_log_space_usage AS lsu WITH (NOLOCK)
INNER JOIN sys.databases AS db WITH (NOLOCK)
ON lsu.database_id = db.database_id
OPTION (RECOMPILE);
------

-- Look at log file size and usage, along with the log reuse wait description for the current database

-- sys.dm_db_log_space_usage (Transact-SQL)
-- https://bit.ly/2H4MQw9


-- Status of last VLF for current database  (Query 56) (Last VLF Status)
SELECT TOP(1) DB_NAME(li.database_id) AS [Database Name], li.[file_id],
              li.vlf_size_mb, li.vlf_sequence_number, li.vlf_active, li.vlf_status
FROM sys.dm_db_log_info(DB_ID()) AS li 
ORDER BY vlf_sequence_number DESC OPTION (RECOMPILE);
------

-- Determine whether you will be able to shrink the transaction log file

-- vlf_status Values
-- 0 is inactive 
-- 1 is initialized but unused 
-- 2 is active

-- sys.dm_db_log_info (Transact-SQL)
-- https://bit.ly/2EQUU1v



-- Get database scoped configuration values for current database (Query 57) (Database-scoped Configurations)
SELECT configuration_id, name, [value] AS [value_for_primary], value_for_secondary
FROM sys.database_scoped_configurations WITH (NOLOCK) OPTION (RECOMPILE);
------

-- This lets you see the value of these new properties for the current database

-- Clear plan cache for current database
-- ALTER DATABASE SCOPED CONFIGURATION CLEAR PROCEDURE_CACHE;

-- ALTER DATABASE SCOPED CONFIGURATION (Transact-SQL)
-- https://bit.ly/2sOH7nb


-- I/O Statistics by file for the current database  (Query 58) (IO Stats By File)
SELECT DB_NAME(DB_ID()) AS [Database Name], df.name AS [Logical Name], vfs.[file_id], df.type_desc,
df.physical_name AS [Physical Name], CAST(vfs.size_on_disk_bytes/1048576.0 AS DECIMAL(16, 2)) AS [Size on Disk (MB)],
vfs.num_of_reads, vfs.num_of_writes, vfs.io_stall_read_ms, vfs.io_stall_write_ms,
CAST(100. * vfs.io_stall_read_ms/(vfs.io_stall_read_ms + vfs.io_stall_write_ms) AS DECIMAL(16,1)) AS [IO Stall Reads Pct],
CAST(100. * vfs.io_stall_write_ms/(vfs.io_stall_write_ms + vfs.io_stall_read_ms) AS DECIMAL(16,1)) AS [IO Stall Writes Pct],
(vfs.num_of_reads + vfs.num_of_writes) AS [Writes + Reads], 
CAST(vfs.num_of_bytes_read/1048576.0 AS DECIMAL(16, 2)) AS [MB Read], 
CAST(vfs.num_of_bytes_written/1048576.0 AS DECIMAL(16, 2)) AS [MB Written],
CAST(100. * vfs.num_of_reads/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(16,1)) AS [# Reads Pct],
CAST(100. * vfs.num_of_writes/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(16,1)) AS [# Write Pct],
CAST(100. * vfs.num_of_bytes_read/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(16,1)) AS [Read Bytes Pct],
CAST(100. * vfs.num_of_bytes_written/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(16,1)) AS [Written Bytes Pct]
FROM sys.dm_io_virtual_file_stats(DB_ID(), NULL) AS vfs
INNER JOIN sys.database_files AS df WITH (NOLOCK)
ON vfs.[file_id]= df.[file_id] OPTION (RECOMPILE);
------

-- This helps you characterize your workload better from an I/O perspective for this database
-- It helps you determine whether you has an OLTP or DW/DSS type of workload



-- Get most frequently executed queries for this database (Query 59) (Query Execution Counts)
SELECT TOP(50) LEFT(t.[text], 50) AS [Short Query Text], qs.execution_count AS [Execution Count],
qs.total_logical_reads AS [Total Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.total_worker_time AS [Total Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.total_elapsed_time AS [Total Elapsed Time],
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
qs.creation_time AS [Creation Time]
--,t.[text] AS [Complete Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
WHERE t.dbid = DB_ID()
ORDER BY qs.execution_count DESC OPTION (RECOMPILE);
------


-- Queries 60 through 65 are the "Bad Man List" for stored procedures

-- Top Cached SPs By Execution Count (Query 60) (SP Execution Counts)
SELECT TOP(100) p.name AS [SP Name], qs.execution_count AS [Execution Count],
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time],    
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.execution_count DESC OPTION (RECOMPILE);
------

-- Tells you which cached stored procedures are called the most often
-- This helps you characterize and baseline your workload


-- Top Cached SPs By Avg Elapsed Time (Query 61) (SP Avg Elapsed Time)
SELECT TOP(25) p.name AS [SP Name], qs.min_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time], 
qs.max_elapsed_time, qs.last_elapsed_time, qs.total_elapsed_time, qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute], 
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], 
qs.total_worker_time AS [TotalWorkerTime],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY avg_elapsed_time DESC OPTION (RECOMPILE);
------

-- This helps you find high average elapsed time cached stored procedures that
-- may be easy to optimize with standard query tuning techniques



-- Top Cached SPs By Total Worker time. Worker time relates to CPU cost  (Query 62) (SP Worker Time)
SELECT TOP(25) p.name AS [SP Name], qs.total_worker_time AS [TotalWorkerTime], 
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.total_worker_time DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a CPU perspective
-- You should look at this if you see signs of CPU pressure


-- Top Cached SPs By Total Logical Reads. Logical reads relate to memory pressure  (Query 63) (SP Logical Reads)
SELECT TOP(25) p.name AS [SP Name], qs.total_logical_reads AS [TotalLogicalReads], 
qs.total_logical_reads/qs.execution_count AS [AvgLogicalReads],qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute], 
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.total_logical_reads DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a memory perspective
-- You should look at this if you see signs of memory pressure


-- Top Cached SPs By Total Physical Reads. Physical reads relate to disk read I/O pressure  (Query 64) (SP Physical Reads)
SELECT TOP(25) p.name AS [SP Name],qs.total_physical_reads AS [TotalPhysicalReads], 
qs.total_physical_reads/qs.execution_count AS [AvgPhysicalReads], qs.execution_count, 
qs.total_logical_reads,qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan 
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND qs.total_physical_reads > 0
ORDER BY qs.total_physical_reads DESC, qs.total_logical_reads DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a read I/O perspective
-- You should look at this if you see signs of I/O pressure or of memory pressure
       


-- Top Cached SPs By Total Logical Writes (Query 65) (SP Logical Writes)
-- Logical writes relate to both memory and disk I/O pressure 
SELECT TOP(25) p.name AS [SP Name], qs.total_logical_writes AS [TotalLogicalWrites], 
qs.total_logical_writes/qs.execution_count AS [AvgLogicalWrites], qs.execution_count,
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan 
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND qs.total_logical_writes > 0
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.total_logical_writes DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a write I/O perspective
-- You should look at this if you see signs of I/O pressure or of memory pressure


-- Lists the top statements by average input/output usage for the current database  (Query 66) (Top IO Statements)
SELECT TOP(50) OBJECT_NAME(qt.objectid, dbid) AS [SP Name],
(qs.total_logical_reads + qs.total_logical_writes) /qs.execution_count AS [Avg IO], qs.execution_count AS [Execution Count],
SUBSTRING(qt.[text],qs.statement_start_offset/2, 
	(CASE 
		WHEN qs.statement_end_offset = -1 
	 THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2 
		ELSE qs.statement_end_offset 
	 END - qs.statement_start_offset)/2) AS [Query Text]	
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
WHERE qt.[dbid] = DB_ID()
ORDER BY [Avg IO] DESC OPTION (RECOMPILE);
------

-- Helps you find the most expensive statements for I/O by SP



-- Possible Bad NC Indexes (writes > reads)  (Query 67) (Bad NC Indexes)
SELECT OBJECT_NAME(s.[object_id]) AS [Table Name], i.name AS [Index Name], i.index_id, 
i.is_disabled, i.is_hypothetical, i.has_filter, i.fill_factor,
s.user_updates AS [Total Writes], s.user_seeks + s.user_scans + s.user_lookups AS [Total Reads],
s.user_updates - (s.user_seeks + s.user_scans + s.user_lookups) AS [Difference]
FROM sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON s.[object_id] = i.[object_id]
AND i.index_id = s.index_id
WHERE OBJECTPROPERTY(s.[object_id],'IsUserTable') = 1
AND s.database_id = DB_ID()
AND s.user_updates > (s.user_seeks + s.user_scans + s.user_lookups)
AND i.index_id > 1 AND i.[type_desc] = N'NONCLUSTERED'
AND i.is_primary_key = 0 AND i.is_unique_constraint = 0 AND i.is_unique = 0
ORDER BY [Difference] DESC, [Total Writes] DESC, [Total Reads] ASC OPTION (RECOMPILE);
------

-- Look for indexes with high numbers of writes and zero or very low numbers of reads
-- Consider your complete workload, and how long your instance has been running
-- Investigate further before dropping an index!


-- Missing Indexes for current database by Index Advantage  (Query 68) (Missing Indexes)
SELECT CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage], 
migs.last_user_seek, mid.[statement] AS [Database.Schema.Table],
COUNT(1) OVER(PARTITION BY mid.[statement]) AS [missing_indexes_for_table],
COUNT(1) OVER(PARTITION BY mid.[statement], equality_columns) AS [similar_missing_indexes_for_table],
mid.equality_columns, mid.inequality_columns, mid.included_columns,
migs.unique_compiles, migs.user_seeks, 
CONVERT(decimal(18,2), migs.avg_total_user_cost) AS [avg_total_user_cost], migs.avg_user_impact,
OBJECT_NAME(mid.[object_id]) AS [Table Name], p.rows AS [Table Rows]
FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)
INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)
ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)
ON mig.index_handle = mid.index_handle
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON p.[object_id] = mid.[object_id]
WHERE mid.database_id = DB_ID()
AND p.index_id < 2 
ORDER BY index_advantage DESC OPTION (RECOMPILE);
------

-- Look at index advantage, last user seek time, number of user seeks to help determine source and importance
-- SQL Server is overly eager to add included columns, so beware
-- Do not just blindly add indexes that show up from this query!!!


-- Find missing index warnings for cached plans in the current database  (Query 69) (Missing Index Warnings)
-- Note: This query could take some time on a busy instance
SELECT TOP(25) OBJECT_NAME(objectid) AS [ObjectName], 
               cp.objtype, cp.usecounts, cp.size_in_bytes, query_plan
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) AS qp
WHERE CAST(query_plan AS NVARCHAR(MAX)) LIKE N'%MissingIndex%'
AND dbid = DB_ID()
ORDER BY cp.usecounts DESC OPTION (RECOMPILE);
------

-- Helps you connect missing indexes to specific stored procedures or queries
-- This can help you decide whether to add them or not


-- Breaks down buffers used by current database by object (table, index) in the buffer cache  (Query 70) (Buffer Usage)
-- Note: This query could take some time on a busy instance
SELECT OBJECT_NAME(p.[object_id]) AS [Object Name], p.index_id, 
CAST(COUNT(*)/128.0 AS DECIMAL(10, 2)) AS [Buffer size(MB)],  
COUNT(*) AS [BufferCount], p.[Rows] AS [Row Count],
p.data_compression_desc AS [Compression Type]
FROM sys.allocation_units AS a WITH (NOLOCK)
INNER JOIN sys.dm_os_buffer_descriptors AS b WITH (NOLOCK)
ON a.allocation_unit_id = b.allocation_unit_id
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON a.container_id = p.hobt_id
WHERE b.database_id = CONVERT(int, DB_ID())
AND p.[object_id] > 100
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'plan_%'
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'sys%'
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'xml_index_nodes%'
GROUP BY p.[object_id], p.index_id, p.data_compression_desc, p.[Rows]
ORDER BY [BufferCount] DESC OPTION (RECOMPILE);
------

-- Tells you what tables and indexes are using the most memory in the buffer cache
-- It can help identify possible candidates for data compression


-- Get Table names, row counts, and compression status for clustered index or heap  (Query 71) (Table Sizes)
SELECT SCHEMA_NAME(o.Schema_ID) AS [Schema Name], OBJECT_NAME(p.object_id) AS [ObjectName], 
SUM(p.Rows) AS [RowCount], data_compression_desc AS [CompressionType]
FROM sys.partitions AS p WITH (NOLOCK)
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON p.object_id = o.object_id
WHERE index_id < 2 --ignore the partitions from the non-clustered index if any
AND OBJECT_NAME(p.object_id) NOT LIKE N'sys%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'spt_%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'queue_%' 
AND OBJECT_NAME(p.object_id) NOT LIKE N'filestream_tombstone%' 
AND OBJECT_NAME(p.object_id) NOT LIKE N'fulltext%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'ifts_comp_fragment%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'filetable_updates%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'xml_index_nodes%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'sqlagent_job%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'plan_persist%'
GROUP BY  SCHEMA_NAME(o.Schema_ID), p.object_id, data_compression_desc
ORDER BY SUM(p.Rows) DESC OPTION (RECOMPILE);
------

-- Gives you an idea of table sizes, and possible data compression opportunities



-- Get some key table properties (Query 72) (Table Properties)
SELECT OBJECT_NAME(t.[object_id]) AS [ObjectName], p.[rows] AS [Table Rows], p.index_id, 
       p.data_compression_desc AS [Index Data Compression],
       t.create_date, t.lock_on_bulk_load, t.is_replicated, t.has_replication_filter, 
       t.is_tracked_by_cdc, t.lock_escalation_desc, t.is_filetable, 
	   t.is_memory_optimized, t.durability_desc, 
	   t.temporal_type_desc, t.is_remote_data_archive_enabled, t.is_external -- new for SQL Server 2016
FROM sys.tables AS t WITH (NOLOCK)
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON t.[object_id] = p.[object_id]
WHERE OBJECT_NAME(t.[object_id]) NOT LIKE N'sys%'
ORDER BY OBJECT_NAME(t.[object_id]), p.index_id OPTION (RECOMPILE);
------

-- Gives you some good information about your tables
-- is_memory_optimized and durability_desc were new in SQL Server 2014
-- temporal_type_desc, is_remote_data_archive_enabled, is_external were new in SQL Server 2016

-- sys.tables (Transact-SQL)
-- https://bit.ly/2Gk7998



-- When were Statistics last updated on all indexes?  (Query 73) (Statistics Update)
SELECT SCHEMA_NAME(o.Schema_ID) + N'.' + o.[NAME] AS [Object Name], o.[type_desc] AS [Object Type],
      i.[name] AS [Index Name], STATS_DATE(i.[object_id], i.index_id) AS [Statistics Date], 
      s.auto_created, s.no_recompute, s.user_created, s.is_incremental, s.is_temporary,
	  st.row_count, st.used_page_count
FROM sys.objects AS o WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON o.[object_id] = i.[object_id]
INNER JOIN sys.stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id] 
AND i.index_id = s.stats_id
INNER JOIN sys.dm_db_partition_stats AS st WITH (NOLOCK)
ON o.[object_id] = st.[object_id]
AND i.[index_id] = st.[index_id]
WHERE o.[type] IN ('U', 'V')
AND st.row_count > 0
ORDER BY STATS_DATE(i.[object_id], i.index_id) DESC OPTION (RECOMPILE);
------  

-- Helps discover possible problems with out-of-date statistics
-- Also gives you an idea which indexes are the most active

-- sys.stats (Transact-SQL)
-- https://bit.ly/2GyAxrn

-- UPDATEs to Statistics (Erin Stellato)
-- https://bit.ly/2vhrYQy




-- Look at most frequently modified indexes and statistics (Query 74) (Volatile Indexes)
SELECT o.[name] AS [Object Name], o.[object_id], o.[type_desc], s.[name] AS [Statistics Name], 
       s.stats_id, s.no_recompute, s.auto_created, s.is_incremental, s.is_temporary,
	   sp.modification_counter, sp.[rows], sp.rows_sampled, sp.last_updated
FROM sys.objects AS o WITH (NOLOCK)
INNER JOIN sys.stats AS s WITH (NOLOCK)
ON s.object_id = o.object_id
CROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) AS sp
WHERE o.[type_desc] NOT IN (N'SYSTEM_TABLE', N'INTERNAL_TABLE')
AND sp.modification_counter > 0
ORDER BY sp.modification_counter DESC, o.name OPTION (RECOMPILE);
------

-- This helps you understand your workload and make better decisions about 
-- things like data compression and adding new indexes to a table



-- Get fragmentation info for all indexes above a certain size in the current database  (Query 75) (Index Fragmentation)
-- Note: This query could take some time on a very large database
SELECT DB_NAME(ps.database_id) AS [Database Name], SCHEMA_NAME(o.[schema_id]) AS [Schema Name],
OBJECT_NAME(ps.OBJECT_ID) AS [Object Name], i.[name] AS [Index Name], ps.index_id, 
ps.index_type_desc, ps.avg_fragmentation_in_percent, 
ps.fragment_count, ps.page_count, i.fill_factor, i.has_filter, 
i.filter_definition, i.[allow_page_locks]
FROM sys.dm_db_index_physical_stats(DB_ID(),NULL, NULL, NULL , N'LIMITED') AS ps
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ps.[object_id] = i.[object_id] 
AND ps.index_id = i.index_id
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON i.[object_id] = o.[object_id]
WHERE ps.database_id = DB_ID()
AND ps.page_count > 2500
ORDER BY ps.avg_fragmentation_in_percent DESC OPTION (RECOMPILE);
------

-- Helps determine whether you have framentation in your relational indexes
-- and how effective your index maintenance strategy is


--- Index Read/Write stats (all tables in current DB) ordered by Reads  (Query 76) (Overall Index Usage - Reads)
SELECT OBJECT_NAME(i.[object_id]) AS [ObjectName], i.[name] AS [IndexName], i.index_id, 
       s.user_seeks, s.user_scans, s.user_lookups,
	   s.user_seeks + s.user_scans + s.user_lookups AS [Total Reads], 
	   s.user_updates AS [Writes],  
	   i.[type_desc] AS [Index Type], i.fill_factor AS [Fill Factor], i.has_filter, i.filter_definition, 
	   s.last_user_scan, s.last_user_lookup, s.last_user_seek
FROM sys.indexes AS i WITH (NOLOCK)
LEFT OUTER JOIN sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id]
AND i.index_id = s.index_id
AND s.database_id = DB_ID()
WHERE OBJECTPROPERTY(i.[object_id],'IsUserTable') = 1
ORDER BY s.user_seeks + s.user_scans + s.user_lookups DESC OPTION (RECOMPILE); -- Order by reads
------

-- Show which indexes in the current database are most active for Reads


--- Index Read/Write stats (all tables in current DB) ordered by Writes  (Query 77) (Overall Index Usage - Writes)
SELECT OBJECT_NAME(i.[object_id]) AS [ObjectName], i.[name] AS [IndexName], i.index_id,
	   s.user_updates AS [Writes], s.user_seeks + s.user_scans + s.user_lookups AS [Total Reads], 
	   i.[type_desc] AS [Index Type], i.fill_factor AS [Fill Factor], i.has_filter, i.filter_definition,
	   s.last_system_update, s.last_user_update
FROM sys.indexes AS i WITH (NOLOCK)
LEFT OUTER JOIN sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id]
AND i.index_id = s.index_id
AND s.database_id = DB_ID()
WHERE OBJECTPROPERTY(i.[object_id],'IsUserTable') = 1
ORDER BY s.user_updates DESC OPTION (RECOMPILE);						 -- Order by writes
------

-- Show which indexes in the current database are most active for Writes


-- Get in-memory OLTP index usage (Query 78) (XTP Index Usage)
SELECT OBJECT_NAME(i.[object_id]) AS [Object Name], i.index_id, i.[name] AS [Index Name],
       i.[type_desc], xis.scans_started, xis.scans_retries, 
	   xis.rows_touched, xis.rows_returned
FROM sys.dm_db_xtp_index_stats AS xis WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON i.[object_id] = xis.[object_id] 
AND i.index_id = xis.index_id 
ORDER BY OBJECT_NAME(i.[object_id]) OPTION (RECOMPILE);
------

-- This gives you some index usage statistics for in-memory OLTP
-- Returns no data if you are not using in-memory OLTP

-- Guidelines for Using Indexes on Memory-Optimized Tables
-- https://bit.ly/2GCP8lF



-- Look at Columnstore index physical statistics (Query 79) (Columnstore Index Physical Stat)
SELECT OBJECT_NAME(ps.object_id) AS [TableName],  
	i.[name] AS [IndexName], ps.index_id, ps.partition_number,
	ps.delta_store_hobt_id, ps.state_desc, ps.total_rows, ps.size_in_bytes,
	ps.trim_reason_desc, ps.generation, ps.transition_to_compressed_state_desc,
	ps.has_vertipaq_optimization, ps.deleted_rows,
	100 * (ISNULL(ps.deleted_rows, 0))/ps.total_rows AS [Fragmentation]
FROM sys.dm_db_column_store_row_group_physical_stats AS ps WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ps.object_id = i.object_id 
AND ps.index_id = i.index_id
ORDER BY ps.object_id, ps.partition_number, ps.row_group_id OPTION (RECOMPILE);
------

-- sys.dm_db_column_store_row_group_physical_stats (Transact-SQL)
-- https://bit.ly/2q276XQ



-- Get lock waits for current database (Query 80) (Lock Waits)
SELECT o.name AS [table_name], i.name AS [index_name], ios.index_id, ios.partition_number,
		SUM(ios.row_lock_wait_count) AS [total_row_lock_waits], 
		SUM(ios.row_lock_wait_in_ms) AS [total_row_lock_wait_in_ms],
		SUM(ios.page_lock_wait_count) AS [total_page_lock_waits],
		SUM(ios.page_lock_wait_in_ms) AS [total_page_lock_wait_in_ms],
		SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) AS [total_lock_wait_in_ms]
FROM sys.dm_db_index_operational_stats(DB_ID(), NULL, NULL, NULL) AS ios
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON ios.[object_id] = o.[object_id]
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ios.[object_id] = i.[object_id] 
AND ios.index_id = i.index_id
WHERE o.[object_id] > 100
GROUP BY o.name, i.name, ios.index_id, ios.partition_number
HAVING SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) > 0
ORDER BY total_lock_wait_in_ms DESC OPTION (RECOMPILE);
------

-- This query is helpful for troubleshooting blocking and deadlocking issues



-- Look at UDF execution statistics (Query 81) (UDF Statistics)
SELECT OBJECT_NAME(object_id) AS [Function Name], execution_count,
	   total_worker_time, total_logical_reads, total_physical_reads, total_elapsed_time, 
	   total_elapsed_time/execution_count AS [avg_elapsed_time],
	   FORMAT(cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
FROM sys.dm_exec_function_stats WITH (NOLOCK) 
WHERE database_id = DB_ID()
ORDER BY total_worker_time DESC OPTION (RECOMPILE); 
------

-- New for SQL Server 2016
-- Helps you investigate scalar UDF performance issues
-- Does not return information for table valued functions

-- sys.dm_exec_function_stats (Transact-SQL)
-- https://bit.ly/2q1Q6BM


-- Get QueryStore Options for this database (Query 82) (QueryStore Options)
SELECT actual_state_desc, desired_state_desc, [interval_length_minutes],
       current_storage_size_mb, [max_storage_size_mb], 
	   query_capture_mode_desc, size_based_cleanup_mode_desc
FROM sys.database_query_store_options WITH (NOLOCK) OPTION (RECOMPILE);
------

-- New for SQL Server 2016
-- Requires that Query Store is enabled for this database

-- Tuning Workload Performance with Query Store
-- https://bit.ly/1kHSl7w


-- Get highest aggregate duration queries over last hour (Query 83) (High Aggregate Duration Queries)
WITH AggregatedDurationLastHour
AS
(SELECT q.query_id, SUM(count_executions * avg_duration) AS total_duration,
   COUNT (distinct p.plan_id) AS number_of_plans
   FROM sys.query_store_query_text AS qt WITH (NOLOCK)
   INNER JOIN sys.query_store_query AS q WITH (NOLOCK)
   ON qt.query_text_id = q.query_text_id
   INNER JOIN sys.query_store_plan AS p WITH (NOLOCK)
   ON q.query_id = p.query_id
   INNER JOIN sys.query_store_runtime_stats AS rs WITH (NOLOCK)
   ON rs.plan_id = p.plan_id
   INNER JOIN sys.query_store_runtime_stats_interval AS rsi WITH (NOLOCK)
   ON rsi.runtime_stats_interval_id = rs.runtime_stats_interval_id
   WHERE rsi.start_time >= DATEADD(hour, -1, GETUTCDATE()) 
   AND rs.execution_type_desc = N'Regular'
   GROUP BY q.query_id),
OrderedDuration AS
(SELECT query_id, total_duration, number_of_plans, 
 ROW_NUMBER () OVER (ORDER BY total_duration DESC, query_id) AS RN
 FROM AggregatedDurationLastHour)
SELECT OBJECT_NAME(q.object_id) AS [Containing Object], qt.query_sql_text, 
od.total_duration AS [Total Duration (microsecs)], 
od.number_of_plans AS [Plan Count],
p.is_forced_plan, p.is_parallel_plan, p.is_trivial_plan,
q.query_parameterization_type_desc, p.[compatibility_level],
p.last_compile_start_time, q.last_execution_time,
CONVERT(xml, p.query_plan) AS query_plan_xml 
FROM OrderedDuration AS od 
INNER JOIN sys.query_store_query AS q WITH (NOLOCK)
ON q.query_id  = od.query_id
INNER JOIN sys.query_store_query_text AS qt WITH (NOLOCK)
ON q.query_text_id = qt.query_text_id
INNER JOIN sys.query_store_plan AS p WITH (NOLOCK)
ON q.query_id = p.query_id
WHERE od.RN <= 50 
ORDER BY total_duration DESC OPTION (RECOMPILE);
------

-- New for SQL Server 2016
-- Requires that QueryStore is enabled for this database



-- Get highest aggregate CPU time queries over last hour (Query 84) (High Aggregate CPU Queries)
WITH AggregatedCPULastHour
AS
(SELECT q.query_id, SUM(rs.count_executions * rs.avg_cpu_time) AS total_cpu_time,
   COUNT (DISTINCT p.plan_id) AS number_of_plans
   FROM sys.query_store_query_text AS qt WITH (NOLOCK)
   INNER JOIN sys.query_store_query AS q WITH (NOLOCK)
   ON qt.query_text_id = q.query_text_id
   INNER JOIN sys.query_store_plan AS p WITH (NOLOCK)
   ON q.query_id = p.query_id
   INNER JOIN sys.query_store_runtime_stats AS rs WITH (NOLOCK)
   ON rs.plan_id = p.plan_id
   INNER JOIN sys.query_store_runtime_stats_interval AS rsi WITH (NOLOCK)
   ON rsi.runtime_stats_interval_id = rs.runtime_stats_interval_id
   WHERE rsi.start_time >= DATEADD(hour, -1, GETUTCDATE()) 
   AND rs.execution_type_desc = N'Regular'
   GROUP BY q.query_id), OrderedDuration 
AS
(SELECT query_id, total_cpu_time, number_of_plans, 
 ROW_NUMBER () OVER (ORDER BY total_cpu_time DESC, query_id) AS RN
 FROM AggregatedCPULastHour)
SELECT OBJECT_NAME(q.object_id) AS [Containing Object], qt.query_sql_text, 
od.total_cpu_time AS [Total CPU Time (microsecs)], 
od.number_of_plans AS [Plan Count],
p.is_forced_plan, p.is_parallel_plan, p.is_trivial_plan,
q.query_parameterization_type_desc, p.[compatibility_level],
p.last_compile_start_time, 
q.last_execution_time,
CONVERT(xml, p.query_plan) AS query_plan_xml 
FROM OrderedDuration AS od 
INNER JOIN sys.query_store_query AS q WITH (NOLOCK)
ON q.query_id  = od.query_id
INNER JOIN sys.query_store_query_text AS qt WITH (NOLOCK)
ON q.query_text_id = qt.query_text_id
INNER JOIN sys.query_store_plan AS p WITH (NOLOCK)
ON q.query_id = p.query_id
WHERE od.RN <= 50 
ORDER BY od.total_cpu_time DESC OPTION (RECOMPILE);
------

-- New for SQL Server 2016
-- Requires that QueryStore is enabled for this database




-- Get input buffer information for the current database (Query 85) (Input Buffer)
SELECT es.session_id, DB_NAME(es.database_id) AS [Database Name],
       es.login_time, es.cpu_time, es.logical_reads, es.memory_usage,
       es.[status], ib.event_info AS [Input Buffer]
FROM sys.dm_exec_sessions AS es WITH (NOLOCK)
CROSS APPLY sys.dm_exec_input_buffer(es.session_id, NULL) AS ib
WHERE es.database_id = DB_ID()
AND es.session_id > 50
AND es.session_id <> @@SPID OPTION (RECOMPILE);
------

-- Gives you input buffer information from all non-system sessions for the current database
-- Replaces DBCC INPUTBUFFER

-- New DMF for retrieving input buffer in SQL Server
-- https://bit.ly/2uHKMbz

-- sys.dm_exec_input_buffer (Transact-SQL)
-- https://bit.ly/2J5Hf9q



-- Look at recent Full backups for the current database (Query 86) (Recent Full Backups)
SELECT TOP (30) bs.machine_name, bs.server_name, bs.database_name AS [Database Name], bs.recovery_model,
CONVERT (BIGINT, bs.backup_size / 1048576 ) AS [Uncompressed Backup Size (MB)],
CONVERT (BIGINT, bs.compressed_backup_size / 1048576 ) AS [Compressed Backup Size (MB)],
CONVERT (NUMERIC (20,2), (CONVERT (FLOAT, bs.backup_size) /
CONVERT (FLOAT, bs.compressed_backup_size))) AS [Compression Ratio], bs.has_backup_checksums, bs.is_copy_only, bs.encryptor_type,
DATEDIFF (SECOND, bs.backup_start_date, bs.backup_finish_date) AS [Backup Elapsed Time (sec)],
bs.backup_finish_date AS [Backup Finish Date], bmf.physical_device_name AS [Backup Location], bmf.physical_block_size
FROM msdb.dbo.backupset AS bs WITH (NOLOCK)
INNER JOIN msdb.dbo.backupmediafamily AS bmf WITH (NOLOCK)
ON bs.media_set_id = bmf.media_set_id  
WHERE bs.database_name = DB_NAME(DB_ID())
AND bs.[type] = 'D' -- Change to L if you want Log backups
ORDER BY bs.backup_finish_date DESC OPTION (RECOMPILE);
------

-- Are your backup sizes and times changing over time?
-- Are you using backup compression?
-- Are you using backup checksums?
-- Are you doing copy_only backups?
-- Are you doing encrypted backups?
-- Have you done any backup tuning with striped backups, or changing the parameters of the backup command?

-- In SQL Server 2016, native SQL Server backup compression actually works 
-- much better with databases that are using TDE than in previous versions
-- https://bit.ly/28Rpb2x


-- These four Pluralsight Courses go into more detail about how to run these queries and interpret the results

-- SQL Server 2017: Diagnosing Configuration Issues with DMVs
-- https://bit.ly/2MSUDUL

-- SQL Server 2014 DMV Diagnostic Queries � Part 1 
-- https://bit.ly/2plxCer

-- SQL Server 2014 DMV Diagnostic Queries � Part 2
-- https://bit.ly/2IuJpzI

-- SQL Server 2014 DMV Diagnostic Queries � Part 3
-- https://bit.ly/2FIlCPb



-- Sign up for Microsoft Visual Studio Dev Essentials and get a free three month pass to Pluralsight

-- Microsoft Visual Studio Dev Essentials
-- http://bit.ly/1q6xbDL


-- Sign up for Microsoft Azure Essentials and get lots of free Azure usage credits, MCP exam voucher, three month Pluralsight subscription

-- Microsoft Azure Essentials
-- https://bit.ly/2JMWe8x


-- August 2017 blog series about upgrading and migrating to SQL Server 2016/2017
-- https://bit.ly/2ftKVrX
tools\dbatools\bin\diagnosticquery\SQLServerDiagnosticQueries_2016_201811.sql

-- SQL Server 2016 Diagnostic Information Queries
-- Glenn Berry 
-- Last Modified: January 7, 2019
-- https://www.sqlskills.com/blogs/glenn/
-- http://sqlserverperformance.wordpress.com/
-- Twitter: GlennAlanBerry

-- Please listen to my Pluralsight courses
-- https://www.pluralsight.com/author/glenn-berry

-- If you want to find all of our SQLskills SQL101 blog posts, check out https://www.sqlskills.com/help/sql101/


-- Please make sure you are using the correct version of these diagnostic queries for your version of SQL Server


-- If you like PowerShell, there is a very useful community solution for running these queries in an automated fashion
-- https://dbatools.io/

-- Invoke-DbaDiagnosticQuery
-- https://dbatools.io/functions/invoke-dbadiagnosticquery/


--******************************************************************************
--*   Copyright (C) 2019 Glenn Berry, SQLskills.com
--*   All rights reserved. 
--*
--*   For more scripts and sample code, check out 
--*      https://www.sqlskills.com/blogs/glenn
--*
--*   You may alter this code for your own *non-commercial* purposes. You may
--*   republish altered code as long as you include this copyright and give due credit. 
--*
--*
--*   THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF 
--*   ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED 
--*   TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
--*   PARTICULAR PURPOSE. 
--*
--******************************************************************************

-- Check the major product version to see if it is SQL Server 2016 CTP 2 or greater
IF NOT EXISTS (SELECT * WHERE CONVERT(varchar(128), SERVERPROPERTY('ProductVersion')) LIKE '13%')
	BEGIN
		DECLARE @ProductVersion varchar(128) = CONVERT(varchar(128), SERVERPROPERTY('ProductVersion'));
		RAISERROR ('Script does not match the ProductVersion [%s] of this instance. Many of these queries may not work on this version.' , 18 , 16 , @ProductVersion);
	END
	ELSE
		PRINT N'You have the correct major version of SQL Server for this diagnostic information script';
	

-- Instance level queries *******************************

-- SQL and OS Version information for current instance  (Query 1) (Version Info)
SELECT @@SERVERNAME AS [Server Name], @@VERSION AS [SQL Server and OS Version Info];
------

-- SQL Server 2016 RTM Branch Builds								-- SQL Server 2016 SP1 Branch Builds                     -- SQL Server 2016 SP2 Branch Builds										
-- Build			Description			Release Date				Build			Description			Release Date	     Build			Description			Release Date			
-- 13.0.200.172		CTP 2.0				5/26/2015
-- 13.0.300.44		CTP 2.1				6/14/2015
-- 13.0.407.1		CTP 2.2				7/28/2015
-- 13.0.500.53		CTP 2.3				9/4/2015
-- 13.0.600.65		CTP 2.4				9/30/2015
-- 13.0.700.242		CTP 3.0				10/29/2015
-- 13.0.900.73		CTP 3.2				12/12/2015
-- 13.0.1000.276	CTP 3.3				1/27/2016
-- 13.0.1100.288	RC0					3/2/2016
-- 13.0.1200.242	RC1					3/18/2016 
-- 13.0.1300.275	RC2					3/28/2016
-- 13.0.1400.361	RC3					4/11/2016
-- 13.0.1601.5		RTM					6/1/2016
-- 13.0.1708.0		RTM-GDR				6/12/2016
-- 13.0.2149.0		RTM CU1				7/25/2016
-- 13.0.2164.0		RTM CU2				9/22/2016
-- 13.0.2186.0		RTM CU3				11/16/2016	---->			13.0.4001.0		SP1 RTM				 11/16/2016
-- 13.0.2193.0		RTM CU4				1/18/2017   ---->			13.0.4411.0		SP1 CU1				 1/18/2017
-- 13.0.2197.0		RTM CU5				3/20/2017   ---->			13.0.4422.0		SP1 CU2				 3/20/2017
-- 13.0.2204.0		RTM CU6				5/15/2017   ---->			13.0.4435.0		SP1 CU3				 5/15/2017
-- 13.0.2210.0		RTM CU7				8/8/2017    ---->			13.0.4446.0		SP1 CU4				  8/8/2017
-- 13.0.2213.0		RTM CU8				9/18/2017   ---->           13.0.4451.0		SP1 CU5				 9/18/2017
-- 13.0.2216.0		RTM CU9				11/21/2017  ---->			13.0.4457.0		SP1 CU6				 11/21/2017
--																	13.0.4466.4		SP1 CU7				  1/4/2018
--																	13.0.4474.0		SP1 CU8				  3/20/2018	---->	13.0.5026.0		SP2 RTM				4/24/2018
--                                                                  13.0.4502.0		SP1 CU9				  5/30/2018 ---->   13.0.5149.0		SP2 CU1				5/30/2018
--                                                                  13.0.4514.0     SP1 CU10			  7/16/2018 ---->   13.0.5153.0     SP2 CU2				7/16/2018
--																	13.0.4528.0		SP1 CU11			  9/17/2018	---->	13.0.5216.0		SP2 CU3				9/20/2018
--																	13.0.4541.0		SP1 CU12			 11/13/2018	---_>	13.0.5233.0		SP2 CU4			   11/13/2018			


-- How to determine the version, edition and update level of SQL Server and its components 
-- https://bit.ly/2oAjKgW														

-- How to obtain the latest Service Pack for SQL Server 2016
-- https://bit.ly/2egtfzK

-- Microsoft SQL Server 2016 SP1 Latest Cumulative Update
-- https://bit.ly/2jTwxWC

-- SQL Server 2016 build versions 
-- https://bit.ly/2epkTDT

-- Where to find information about the latest SQL Server builds
-- https://bit.ly/2IGHbfY

-- Performance and Stability Related Fixes in Post-SQL Server 2016 SP1 Builds
-- https://bit.ly/2gr7k9L

-- Performance and Stability Related Fixes in Post-SQL Server 2016 SP2 Builds
-- https://bit.ly/2K3LoPf			

-- Announcing updates to the SQL Server Incremental Servicing Model (ISM)
-- https://bit.ly/1RzYITz

-- Update Center for Microsoft SQL Server
-- https://bit.ly/2pZptuQ

-- Download SQL Server Management Studio (SSMS)
-- https://bit.ly/1OcupT9

-- Download and install Azure Data Studio 
-- https://bit.ly/2vgke1A
	


-- Get socket, physical core and logical core count from the SQL Server Error log. (Query 2) (Core Counts)
-- This query might take a few seconds depending on the size of your error log
EXEC sys.xp_readerrorlog 0, 1, N'detected', N'socket';
------

-- This can help you determine the exact core counts used by SQL Server and whether HT is enabled or not
-- It can also help you confirm your SQL Server licensing model
-- Be on the lookout for this message "using 40 logical processors based on SQL Server licensing" 
-- (when you have more than 40 logical cores) which means grandfathered Server/CAL licensing
-- This query will return no results if your error log has been recycled since the instance was last started



-- Get selected server properties (Query 3) (Server Properties)
SELECT SERVERPROPERTY('MachineName') AS [MachineName], 
SERVERPROPERTY('ServerName') AS [ServerName],  
SERVERPROPERTY('InstanceName') AS [Instance], 
SERVERPROPERTY('IsClustered') AS [IsClustered], 
SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS [ComputerNamePhysicalNetBIOS], 
SERVERPROPERTY('Edition') AS [Edition], 
SERVERPROPERTY('ProductLevel') AS [ProductLevel],				-- What servicing branch (RTM/SP/CU)
SERVERPROPERTY('ProductUpdateLevel') AS [ProductUpdateLevel],	-- Within a servicing branch, what CU# is applied
SERVERPROPERTY('ProductVersion') AS [ProductVersion],
SERVERPROPERTY('ProductMajorVersion') AS [ProductMajorVersion], 
SERVERPROPERTY('ProductMinorVersion') AS [ProductMinorVersion], 
SERVERPROPERTY('ProductBuild') AS [ProductBuild], 
SERVERPROPERTY('ProductBuildType') AS [ProductBuildType],			  -- Is this a GDR or OD hotfix (NULL if on a CU build)
SERVERPROPERTY('ProductUpdateReference') AS [ProductUpdateReference], -- KB article number that is applicable for this build
SERVERPROPERTY('ProcessID') AS [ProcessID],
SERVERPROPERTY('Collation') AS [Collation], 
SERVERPROPERTY('IsFullTextInstalled') AS [IsFullTextInstalled], 
SERVERPROPERTY('IsIntegratedSecurityOnly') AS [IsIntegratedSecurityOnly],
SERVERPROPERTY('FilestreamConfiguredLevel') AS [FilestreamConfiguredLevel],
SERVERPROPERTY('IsHadrEnabled') AS [IsHadrEnabled], 
SERVERPROPERTY('HadrManagerStatus') AS [HadrManagerStatus],
SERVERPROPERTY('InstanceDefaultDataPath') AS [InstanceDefaultDataPath],
SERVERPROPERTY('InstanceDefaultLogPath') AS [InstanceDefaultLogPath],
SERVERPROPERTY('BuildClrVersion') AS [Build CLR Version],
SERVERPROPERTY('IsXTPSupported') AS [IsXTPSupported],
SERVERPROPERTY('IsPolybaseInstalled') AS [IsPolybaseInstalled],				-- New for SQL Server 2016
SERVERPROPERTY('IsAdvancedAnalyticsInstalled') AS [IsRServicesInstalled];	-- New for SQL Server 2016
------

-- This gives you a lot of useful information about your instance of SQL Server,
-- such as the ProcessID for SQL Server and your collation
-- Note: Some columns will be NULL on older SQL Server builds

-- SERVERPROPERTY (Transact-SQL)
-- https://bit.ly/2eeaXeI



-- Get instance-level configuration values for instance  (Query 4) (Configuration Values)
SELECT name, value, value_in_use, minimum, maximum, [description], is_dynamic, is_advanced
FROM sys.configurations WITH (NOLOCK)
ORDER BY name OPTION (RECOMPILE);
------

-- Focus on these settings:
-- automatic soft-NUMA disabled (should be 0 in most cases)
-- backup checksum default (should be 1)
-- backup compression default (should be 1 in most cases)
-- clr enabled (only enable if it is needed)
-- cost threshold for parallelism (depends on your workload)
-- lightweight pooling (should be zero)
-- max degree of parallelism (depends on your workload and hardware)
-- max server memory (MB) (set to an appropriate value, not the default)
-- optimize for ad hoc workloads (should be 1)
-- priority boost (should be zero)
-- remote admin connections (should be 1)

-- New configuration options for SQL Server 2016
-- allow polybase export (Allow INSERT into a Hadoop external table)
-- automatic soft-NUMA disabled (Automatic soft-NUMA is enabled by default)
-- external scripts enabled (Allows execution of external scripts, for R Services)
-- hadoop connectivity (Configure SQL Server to connect to external Hadoop or Microsoft Azure storage blob data sources through PolyBase)
-- polybase network encryption (Configure SQL Server to encrypt control and data channels when using PolyBase)
-- remote data archive (Allow the use of the REMOTE_DATA_ARCHIVE data access for Stretch databases)

-- SQLSweet16!, Episode 1: Backup Compression for TDE-enabled Databases
-- https://bit.ly/28Rpb2x



-- Returns a list of all global trace flags that are enabled (Query 5) (Global Trace Flags)
DBCC TRACESTATUS (-1);
------

-- If no global trace flags are enabled, no results will be returned.
-- It is very useful to know what global trace flags are currently enabled as part of the diagnostic process.

-- Common trace flags that should be enabled in most cases
-- TF 3226 - Supresses logging of successful database backup messages to the SQL Server Error Log
--           https://bit.ly/2p6MTjS

-- TF 6534 - Enables use of native code to improve performance with spatial data
--           https://bit.ly/2HrQUpU

-- The behavior of TF 1117, 1118 are enabled for tempdb in SQL Server 2016 by default
-- SQL 2016 � It Just Runs Faster: -T1117 and -T1118 changes for TEMPDB and user databases
-- https://bit.ly/2lbNWxK           

-- The behavior of TF 2371 is enabled by default in SQL Server 2016 and newer (in compat level 130 and higher)

-- DBCC TRACEON - Trace Flags (Transact-SQL)
-- https://bit.ly/2FuSvPg



-- Returns status of instant file initialization (Query 6) (IFI Status)
EXEC sys.xp_readerrorlog 0, 1, N'Database Instant File Initialization';
------

-- Lets you determine whether Instant File Initialization (IFI) is enabled for the instance
-- This should be enabled in the vast majority of cases
-- SQL Server 2016 lets you enable this during the SQL server installation process

-- Database Instant File Initialization
-- https://bit.ly/2nTX74y

-- Misconceptions around instant file initialization
-- https://bit.ly/2oBSKgZ



-- SQL Server Process Address space info  (Query 7) (Process Memory)
-- (shows whether locked pages is enabled, among other things)
SELECT physical_memory_in_use_kb/1024 AS [SQL Server Memory Usage (MB)],
	   locked_page_allocations_kb/1024 AS [SQL Server Locked Pages Allocation (MB)],
       large_page_allocations_kb/1024 AS [SQL Server Large Pages Allocation (MB)], 
	   page_fault_count, memory_utilization_percentage, available_commit_limit_kb, 
	   process_physical_memory_low, process_virtual_memory_low
FROM sys.dm_os_process_memory WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You want to see 0 for process_physical_memory_low
-- You want to see 0 for process_virtual_memory_low
-- This indicates that you are not under internal memory pressure
-- If locked_page_allocations_kb > 0, then LPIM is enabled

-- How to enable the "locked pages" feature in SQL Server 2012
-- https://bit.ly/2F5UjOA

-- Memory Management Architecture Guide
-- https://bit.ly/2JKkadC 



-- SQL Server Services information (Query 8) (SQL Server Services Info)
SELECT servicename, process_id, startup_type_desc, status_desc, 
last_startup_time, service_account, is_clustered, cluster_nodename, [filename], 
instant_file_initialization_enabled -- New in SQL Server 2016 SP1
FROM sys.dm_server_services WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Tells you the account being used for the SQL Server Service and the SQL Agent Service
-- Shows the process_id, when they were last started, and their current status
-- Also shows whether you are running on a failover cluster instance, and what node you are running on
-- Also shows whether IFI is enabled

-- sys.dm_server_services (Transact-SQL)
-- https://bit.ly/2oKa1Un


-- Last backup information by database  (Query 9) (Last Backup By Database)
SELECT ISNULL(d.[name], bs.[database_name]) AS [Database], d.recovery_model_desc AS [Recovery Model], 
       d.log_reuse_wait_desc AS [Log Reuse Wait Desc],
    MAX(CASE WHEN [type] = 'D' THEN bs.backup_finish_date ELSE NULL END) AS [Last Full Backup],
    MAX(CASE WHEN [type] = 'I' THEN bs.backup_finish_date ELSE NULL END) AS [Last Differential Backup],
    MAX(CASE WHEN [type] = 'L' THEN bs.backup_finish_date ELSE NULL END) AS [Last Log Backup]
FROM sys.databases AS d WITH (NOLOCK)
LEFT OUTER JOIN msdb.dbo.backupset AS bs WITH (NOLOCK)
ON bs.[database_name] = d.[name] 
AND bs.backup_finish_date > GETDATE()- 30
WHERE d.name <> N'tempdb'
GROUP BY ISNULL(d.[name], bs.[database_name]), d.recovery_model_desc, d.log_reuse_wait_desc, d.[name] 
ORDER BY d.recovery_model_desc, d.[name] OPTION (RECOMPILE);
------

-- This helps you spot runaway transaction logs and other issues with your backup schedule


-- Get SQL Server Agent jobs and Category information (Query 10) (SQL Server Agent Jobs)
SELECT sj.name AS [Job Name], sj.[description] AS [Job Description], SUSER_SNAME(sj.owner_sid) AS [Job Owner],
sj.date_created AS [Date Created], sj.[enabled] AS [Job Enabled], 
sj.notify_email_operator_id, sj.notify_level_email, sc.name AS [CategoryName],
s.[enabled] AS [Sched Enabled], js.next_run_date, js.next_run_time
FROM msdb.dbo.sysjobs AS sj WITH (NOLOCK)
INNER JOIN msdb.dbo.syscategories AS sc WITH (NOLOCK)
ON sj.category_id = sc.category_id
LEFT OUTER JOIN msdb.dbo.sysjobschedules AS js WITH (NOLOCK)
ON sj.job_id = js.job_id
LEFT OUTER JOIN msdb.dbo.sysschedules AS s WITH (NOLOCK)
ON js.schedule_id = s.schedule_id
ORDER BY sj.name OPTION (RECOMPILE);
------

-- Gives you some basic information about your SQL Server Agent jobs, who owns them and how they are configured
-- Look for Agent jobs that are not owned by sa
-- Look for jobs that have a notify_email_operator_id set to 0 (meaning no operator)
-- Look for jobs that have a notify_level_email set to 0 (meaning no e-mail is ever sent)
--
-- MSDN sysjobs documentation
-- https://bit.ly/2paDEOP 

-- SQL Server Maintenance Solution
-- https://bit.ly/1pgchQu  


-- Get SQL Server Agent Alert Information (Query 11) (SQL Server Agent Alerts)
SELECT name, event_source, message_id, severity, [enabled], has_notification, 
       delay_between_responses, occurrence_count, last_occurrence_date, last_occurrence_time
FROM msdb.dbo.sysalerts WITH (NOLOCK)
ORDER BY name OPTION (RECOMPILE);
------

-- Gives you some basic information about your SQL Server Agent Alerts 
-- (which are different from SQL Server Agent jobs)
-- Read more about Agent Alerts here: https://bit.ly/2Giz0Xf 



-- Windows information (Query 12) (Windows Info)
SELECT windows_release, windows_service_pack_level, 
       windows_sku, os_language_version
FROM sys.dm_os_windows_info WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Gives you major OS version, Service Pack, Edition, and language info for the operating system
-- 10.0 is either Windows 10 or Windows Server 2016
-- 6.3 is either Windows 8.1 or Windows Server 2012 R2 
-- 6.2 is either Windows 8 or Windows Server 2012


-- Windows SKU codes
-- 4 is Enterprise Edition
-- 7 is Standard Server Edition
-- 8 is Datacenter Server Edition
-- 10 is Enterprise Server Edition
-- 48 is Professional Edition
-- 161 is Pro for Workstations

-- 1033 for os_language_version is US-English

-- SQL Server 2016 requires Windows Server 2012 or newer

-- Quick-Start Installation of SQL Server 2016
-- https://bit.ly/2qtxQ3G

-- Hardware and Software Requirements for Installing SQL Server 2016
-- https://bit.ly/2JJIUTl

-- Using SQL Server in Windows 8 and later versions of Windows operating system 
-- https://bit.ly/2F7Ax0P


-- SQL Server NUMA Node information  (Query 13) (SQL Server NUMA Info)
SELECT node_id, node_state_desc, memory_node_id, processor_group, online_scheduler_count, 
       idle_scheduler_count, active_worker_count, avg_load_balance, resource_monitor_state
FROM sys.dm_os_nodes WITH (NOLOCK) 
WHERE node_state_desc <> N'ONLINE DAC' OPTION (RECOMPILE);
------

-- Gives you some useful information about the composition and relative load on your NUMA nodes
-- You want to see an equal number of schedulers on each NUMA node
-- Watch out if SQL Server 2016 Standard Edition has been installed 
-- on a physical or virtual machine with more than four sockets or more than 24 physical cores

-- sys.dm_os_nodes (Transact-SQL)
-- https://bit.ly/2pn5Mw8

-- Balancing Your Available SQL Server Core Licenses Evenly Across NUMA Nodes
-- https://bit.ly/2vfC4Rq



-- Good basic information about OS memory amounts and state  (Query 14) (System Memory)
SELECT total_physical_memory_kb/1024 AS [Physical Memory (MB)], 
       available_physical_memory_kb/1024 AS [Available Memory (MB)], 
       total_page_file_kb/1024 AS [Total Page File (MB)], 
	   available_page_file_kb/1024 AS [Available Page File (MB)], 
	   system_cache_kb/1024 AS [System Cache (MB)],
       system_memory_state_desc AS [System Memory State]
FROM sys.dm_os_sys_memory WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You want to see "Available physical memory is high" for System Memory State
-- This indicates that you are not under external memory pressure

-- Possible System Memory State values:
-- Available physical memory is high
-- Physical memory usage is steady
-- Available physical memory is low
-- Available physical memory is running low
-- Physical memory state is transitioning

-- sys.dm_os_sys_memory (Transact-SQL)
-- https://bit.ly/2pcV0xq



-- You can skip the next two queries if you know you don't have a clustered instance


-- Get information about your cluster nodes and their status  (Query 15) (Cluster Node Properties)
-- (if your database server is in a failover cluster)
SELECT NodeName, status_description, is_current_owner
FROM sys.dm_os_cluster_nodes WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Knowing which node owns the cluster resources is critical
-- Especially when you are installing Windows or SQL Server updates
-- You will see no results if your instance is not clustered

-- Recommended hotfixes and updates for Windows Server 2012 R2-based failover clusters
-- https://bit.ly/1z5BfCw


-- Get information about any AlwaysOn AG cluster this instance is a part of (Query 16) (AlwaysOn AG Cluster)
SELECT cluster_name, quorum_type_desc, quorum_state_desc
FROM sys.dm_hadr_cluster WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You will see no results if your instance is not using AlwaysOn AGs


-- Good overview of AG health and status (Query 17) (AlwaysOn AG Status)
SELECT ag.name AS [AG Name], ar.replica_server_name, ar.availability_mode_desc, adc.[database_name], 
       drs.is_local, drs.is_primary_replica, drs.synchronization_state_desc, drs.is_commit_participant, 
	   drs.synchronization_health_desc, drs.recovery_lsn, drs.truncation_lsn, drs.last_sent_lsn, 
	   drs.last_sent_time, drs.last_received_lsn, drs.last_received_time, drs.last_hardened_lsn, 
	   drs.last_hardened_time, drs.last_redone_lsn, drs.last_redone_time, drs.log_send_queue_size, 
	   drs.log_send_rate, drs.redo_queue_size, drs.redo_rate, drs.filestream_send_rate, 
	   drs.end_of_log_lsn, drs.last_commit_lsn, drs.last_commit_time, drs.database_state_desc 
FROM sys.dm_hadr_database_replica_states AS drs WITH (NOLOCK)
INNER JOIN sys.availability_databases_cluster AS adc WITH (NOLOCK)
ON drs.group_id = adc.group_id 
AND drs.group_database_id = adc.group_database_id
INNER JOIN sys.availability_groups AS ag WITH (NOLOCK)
ON ag.group_id = drs.group_id
INNER JOIN sys.availability_replicas AS ar WITH (NOLOCK)
ON drs.group_id = ar.group_id 
AND drs.replica_id = ar.replica_id
ORDER BY ag.name, ar.replica_server_name, adc.[database_name] OPTION (RECOMPILE);

-- You will see no results if your instance is not using AlwaysOn AGs

-- SQL Server 2016 � It Just Runs Faster: Always On Availability Groups Turbocharged
-- https://bit.ly/2dn1H6r


-- Hardware information from SQL Server 2016  (Query 18) (Hardware Info)
SELECT cpu_count AS [Logical CPU Count], scheduler_count, 
       hyperthread_ratio AS [Hyperthread Ratio],
       cpu_count/hyperthread_ratio AS [Physical CPU Count], 
       physical_memory_kb/1024 AS [Physical Memory (MB)], 
	   committed_kb/1024 AS [Committed Memory (MB)],
       committed_target_kb/1024 AS [Committed Target Memory (MB)],
       max_workers_count AS [Max Workers Count], 
	   affinity_type_desc AS [Affinity Type], 
       sqlserver_start_time AS [SQL Server Start Time],
	   DATEDIFF(hour, sqlserver_start_time, GETDATE()) AS [SQL Server Up Time (hrs)],
	   virtual_machine_type_desc AS [Virtual Machine Type],
	   softnuma_configuration_desc AS [Soft NUMA Configuration], 
	   sql_memory_model_desc -- New in SQL Server 2016
FROM sys.dm_os_sys_info WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Gives you some good basic hardware information about your database server
-- Note: virtual_machine_type_desc of HYPERVISOR does not automatically mean you are running SQL Server inside of a VM
-- It merely indicates that you have a hypervisor running on your host

-- sys.dm_os_sys_info (Transact-SQL)
-- https://bit.ly/2pczOYs

-- Soft NUMA configuration was a new column for SQL Server 2016
-- OFF = Soft-NUMA feature is OFF
-- ON = SQL Server automatically determines the NUMA node sizes for Soft-NUMA
-- MANUAL = Manually configured soft-NUMA

-- Configure SQL Server to Use Soft-NUMA (SQL Server)
-- https://bit.ly/2HTpKJt

-- sql_memory_model_desc values (Added in SQL Server 2016 SP1)
-- CONVENTIONAL
-- LOCK_PAGES
-- LARGE_PAGES
   

-- Get System Manufacturer and model number from SQL Server Error log (Query 19) (System Manufacturer)
EXEC sys.xp_readerrorlog 0, 1, N'Manufacturer';
------ 

-- This can help you determine the capabilities and capacities of your database server
-- Can also be used to confirm if you are running in a VM
-- This query might take a few seconds if you have not recycled your error log recently
-- This query will return no results if your error log has been recycled since the instance was started


-- Get pvscsi info from Windows Registry  (Query 20) (PVSCSI Driver Parameters)
EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SYSTEM\CurrentControlSet\services\pvscsi\Parameters\Device', N'DriverParameter';
------

-- This is valid for VMware VMs
-- Recommended value for intensive I/O patterns from VMware is: RequestRingPages=32,MaxQueueDepth=254
-- https://kb.vmware.com/s/article/2053145



-- Get BIOS date from Windows Registry (Query 21) (BIOS Date)
EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'HARDWARE\DESCRIPTION\System\BIOS', N'BiosReleaseDate';
------

-- Helps you understand whether the main system BIOS is up to date, and the possible age of the hardware
-- Not as useful for virtualization


-- Get processor description from Windows Registry  (Query 22) (Processor Description)
EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'HARDWARE\DESCRIPTION\System\CentralProcessor\0', N'ProcessorNameString';
------

-- Gives you the model number and rated clock speed of your processor(s)
-- Your processors may be running at less than the rated clock speed due
-- to the Windows Power Plan or hardware power management

-- You can use CPU-Z to get your actual CPU core speed and a lot of other useful information
-- https://bit.ly/QhR6xF

-- You can learn more about processor selection for SQL Server by following this link
-- https://bit.ly/2F3aVlP



-- See if buffer pool extension (BPE) is enabled (Query 23) (BPE Configuration)
SELECT [path], state_description, current_size_in_kb, 
CAST(current_size_in_kb/1048576.0 AS DECIMAL(10,2)) AS [Size (GB)]
FROM sys.dm_os_buffer_pool_extension_configuration WITH (NOLOCK) OPTION (RECOMPILE);
------

-- BPE is available in both Standard Edition and Enterprise Edition
-- It is a more interesting feature for Standard Edition

-- Buffer Pool Extension to SSDs in SQL Server 2014
-- https://bit.ly/1bm08m8

-- Buffer Pool Extension
-- https://bit.ly/2oBuieO



-- Look at buffer descriptors to see BPE usage by database (Query 24) (BPE Usage) 
SELECT DB_NAME(database_id) AS [Database Name], COUNT(page_id) AS [Page Count],
CAST(COUNT(*)/128.0 AS DECIMAL(10, 2)) AS [Buffer size(MB)], 
AVG(read_microsec) AS [Avg Read Time (microseconds)]
FROM sys.dm_os_buffer_descriptors WITH (NOLOCK)
WHERE database_id <> 32767
AND is_in_bpool_extension = 1
GROUP BY DB_NAME(database_id) 
ORDER BY [Buffer size(MB)] DESC OPTION (RECOMPILE);
------

-- You will see no results if BPE is not enabled or if there is no BPE usage


-- Get information on location, time and size of any memory dumps from SQL Server  (Query 25) (Memory Dump Info)
SELECT [filename], creation_time, size_in_bytes/1048576.0 AS [Size (MB)]
FROM sys.dm_server_memory_dumps WITH (NOLOCK) 
ORDER BY creation_time DESC OPTION (RECOMPILE);
------

-- This will not return any rows if you have 
-- not had any memory dumps (which is a good thing)

-- sys.dm_server_memory_dumps (Transact-SQL)
-- https://bit.ly/2elwWll



-- Look at Suspect Pages table (Query 26) (Suspect Pages)
SELECT DB_NAME(database_id) AS [Database Name], [file_id], page_id, 
       event_type, error_count, last_update_date 
FROM msdb.dbo.suspect_pages WITH (NOLOCK)
ORDER BY database_id OPTION (RECOMPILE);
------

-- event_type value descriptions
-- 1 = 823 error caused by an operating system CRC error
--     or 824 error other than a bad checksum or a torn page (for example, a bad page ID)
-- 2 = Bad checksum
-- 3 = Torn page
-- 4 = Restored (The page was restored after it was marked bad)
-- 5 = Repaired (DBCC repaired the page)
-- 7 = Deallocated by DBCC

-- Ideally, this query returns no results. The table is limited to 1000 rows.
-- If you do get results here, you should do further investigation to determine the root cause

-- Manage the suspect_pages Table
-- https://bit.ly/2Fvr1c9


-- Get number of data files in tempdb database (Query 27) (TempDB Data Files)
EXEC sys.xp_readerrorlog 0, 1, N'The tempdb database has';
------

-- Get the number of data files in the tempdb database
-- 4-8 data files that are all the same size is a good starting point
-- This query will return no results if your error log has been recycled since the instance was last started


-- File names and paths for all user and system databases on instance  (Query 28) (Database Filenames and Paths)
SELECT DB_NAME([database_id]) AS [Database Name], 
       [file_id], [name], physical_name, [type_desc], state_desc,
	   is_percent_growth, growth,
	   CONVERT(bigint, growth/128.0) AS [Growth in MB], 
       CONVERT(bigint, size/128.0) AS [Total Size in MB]
FROM sys.master_files WITH (NOLOCK)
ORDER BY DB_NAME([database_id]), [file_id] OPTION (RECOMPILE);
------

-- Things to look at:
-- Are data files and log files on different drives?
-- Is everything on the C: drive?
-- Is tempdb on dedicated drives?
-- Is there only one tempdb data file?
-- Are all of the tempdb data files the same size?
-- Are there multiple data files for user databases?
-- Is percent growth enabled for any files (which is bad)?


-- Volume info for all LUNS that have database files on the current instance (Query 29) (Volume Info)
SELECT DISTINCT vs.volume_mount_point, vs.file_system_type, vs.logical_volume_name, 
CONVERT(DECIMAL(18,2), vs.total_bytes/1073741824.0) AS [Total Size (GB)],
CONVERT(DECIMAL(18,2), vs.available_bytes/1073741824.0) AS [Available Size (GB)],  
CONVERT(DECIMAL(18,2), vs.available_bytes * 1. / vs.total_bytes * 100.) AS [Space Free %],
vs.supports_compression, vs.is_compressed, 
vs.supports_sparse_files, vs.supports_alternate_streams
FROM sys.master_files AS f WITH (NOLOCK)
CROSS APPLY sys.dm_os_volume_stats(f.database_id, f.[file_id]) AS vs 
ORDER BY vs.volume_mount_point OPTION (RECOMPILE);
------

-- Shows you the total and free space on the LUNs where you have database files
-- Being low on free space can negatively affect performance

-- sys.dm_os_volume_stats (Transact-SQL)
-- https://bit.ly/2oBPNNr



-- Drive level latency information (Query 30) (Drive Level Latency)
-- Based on code from Jimmy May
SELECT tab.[Drive], tab.volume_mount_point AS [Volume Mount Point], 
	CASE 
		WHEN num_of_reads = 0 THEN 0 
		ELSE (io_stall_read_ms/num_of_reads) 
	END AS [Read Latency],
	CASE 
		WHEN num_of_writes = 0 THEN 0 
		ELSE (io_stall_write_ms/num_of_writes) 
	END AS [Write Latency],
	CASE 
		WHEN (num_of_reads = 0 AND num_of_writes = 0) THEN 0 
		ELSE (io_stall/(num_of_reads + num_of_writes)) 
	END AS [Overall Latency],
	CASE 
		WHEN num_of_reads = 0 THEN 0 
		ELSE (num_of_bytes_read/num_of_reads) 
	END AS [Avg Bytes/Read],
	CASE 
		WHEN num_of_writes = 0 THEN 0 
		ELSE (num_of_bytes_written/num_of_writes) 
	END AS [Avg Bytes/Write],
	CASE 
		WHEN (num_of_reads = 0 AND num_of_writes = 0) THEN 0 
		ELSE ((num_of_bytes_read + num_of_bytes_written)/(num_of_reads + num_of_writes)) 
	END AS [Avg Bytes/Transfer]
FROM (SELECT LEFT(UPPER(mf.physical_name), 2) AS Drive, SUM(num_of_reads) AS num_of_reads,
	         SUM(io_stall_read_ms) AS io_stall_read_ms, SUM(num_of_writes) AS num_of_writes,
	         SUM(io_stall_write_ms) AS io_stall_write_ms, SUM(num_of_bytes_read) AS num_of_bytes_read,
	         SUM(num_of_bytes_written) AS num_of_bytes_written, SUM(io_stall) AS io_stall, vs.volume_mount_point 
      FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS vfs
      INNER JOIN sys.master_files AS mf WITH (NOLOCK)
      ON vfs.database_id = mf.database_id AND vfs.file_id = mf.file_id
	  CROSS APPLY sys.dm_os_volume_stats(mf.database_id, mf.[file_id]) AS vs 
      GROUP BY LEFT(UPPER(mf.physical_name), 2), vs.volume_mount_point) AS tab
ORDER BY [Overall Latency] OPTION (RECOMPILE);
------

-- Shows you the drive-level latency for reads and writes, in milliseconds
-- Latency above 30-40ms is usually a problem
-- These latency numbers include all file activity against all SQL Server 
-- database files on each drive since SQL Server was last started


-- Calculates average stalls per read, per write, and per total input/output for each database file  (Query 31) (IO Latency by File)
SELECT DB_NAME(fs.database_id) AS [Database Name], CAST(fs.io_stall_read_ms/(1.0 + fs.num_of_reads) AS NUMERIC(10,1)) AS [avg_read_latency_ms],
CAST(fs.io_stall_write_ms/(1.0 + fs.num_of_writes) AS NUMERIC(10,1)) AS [avg_write_latency_ms],
CAST((fs.io_stall_read_ms + fs.io_stall_write_ms)/(1.0 + fs.num_of_reads + fs.num_of_writes) AS NUMERIC(10,1)) AS [avg_io_latency_ms],
CONVERT(DECIMAL(18,2), mf.size/128.0) AS [File Size (MB)], mf.physical_name, mf.type_desc, fs.io_stall_read_ms, fs.num_of_reads, 
fs.io_stall_write_ms, fs.num_of_writes, fs.io_stall_read_ms + fs.io_stall_write_ms AS [io_stalls], fs.num_of_reads + fs.num_of_writes AS [total_io],
io_stall_queued_read_ms AS [Resource Governor Total Read IO Latency (ms)], io_stall_queued_write_ms AS [Resource Governor Total Write IO Latency (ms)] 
FROM sys.dm_io_virtual_file_stats(null,null) AS fs
INNER JOIN sys.master_files AS mf WITH (NOLOCK)
ON fs.database_id = mf.database_id
AND fs.[file_id] = mf.[file_id]
ORDER BY avg_io_latency_ms DESC OPTION (RECOMPILE);
------

-- Helps determine which database files on the entire instance have the most I/O bottlenecks
-- This can help you decide whether certain LUNs are overloaded and whether you might
-- want to move some files to a different location or perhaps improve your I/O performance
-- These latency numbers include all file activity against each SQL Server 
-- database file since SQL Server was last started


-- Look for I/O requests taking longer than 15 seconds in the six most recent SQL Server Error Logs (Query 32) (IO Warnings)
CREATE TABLE #IOWarningResults(LogDate datetime, ProcessInfo sysname, LogText nvarchar(1000));

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 0, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 1, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 2, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 3, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 4, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 5, 1, N'taking longer than 15 seconds';

SELECT LogDate, ProcessInfo, LogText
FROM #IOWarningResults
ORDER BY LogDate DESC;

DROP TABLE #IOWarningResults;
------  

-- Finding 15 second I/O warnings in the SQL Server Error Log is useful evidence of
-- poor I/O performance (which might have many different causes)
-- Look to see if you see any patterns in the results (same files, same drives, same time of day, etc.)

-- Diagnostics in SQL Server help detect stalled and stuck I/O operations
-- https://bit.ly/2qtaw73


-- Resource Governor Resource Pool information (Query 33) (RG Resource Pools)
SELECT pool_id, [Name], statistics_start_time,
       min_memory_percent, max_memory_percent,  
       max_memory_kb/1024 AS [max_memory_mb],  
       used_memory_kb/1024 AS [used_memory_mb],   
       target_memory_kb/1024 AS [target_memory_mb],
	   min_iops_per_volume, max_iops_per_volume
FROM sys.dm_resource_governor_resource_pools WITH (NOLOCK)
OPTION (RECOMPILE);
------

-- sys.dm_resource_governor_resource_pools (Transact-SQL)
-- https://bit.ly/2MVU0Vy



-- Recovery model, log reuse wait description, log file size, log usage size  (Query 34) (Database Properties)
-- and compatibility level for all databases on instance
SELECT db.[name] AS [Database Name], SUSER_SNAME(db.owner_sid) AS [Database Owner], db.recovery_model_desc AS [Recovery Model], 
db.state_desc, db.containment_desc, db.log_reuse_wait_desc AS [Log Reuse Wait Description], 
CONVERT(DECIMAL(18,2), ls.cntr_value/1024.0) AS [Log Size (MB)], CONVERT(DECIMAL(18,2), lu.cntr_value/1024.0) AS [Log Used (MB)],
CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log Used %], 
db.[compatibility_level] AS [DB Compatibility Level], 
db.is_mixed_page_allocation_on, db.page_verify_option_desc AS [Page Verify Option], 
db.is_auto_create_stats_on, db.is_auto_update_stats_on, db.is_auto_update_stats_async_on, db.is_parameterization_forced, 
db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on, db.is_auto_close_on, db.is_auto_shrink_on, 
db.target_recovery_time_in_seconds, db.is_cdc_enabled, db.is_published, db.is_distributor, db.is_encrypted,
db.group_database_id, db.replica_id,db.is_memory_optimized_elevate_to_snapshot_on, 
db.delayed_durability_desc, db.is_auto_create_stats_incremental_on,
db.is_query_store_on, db.is_sync_with_backup, 
db.is_supplemental_logging_enabled, db.is_remote_data_archive_enabled,
db.is_encrypted, de.encryption_state, de.percent_complete, de.key_algorithm, de.key_length      
FROM sys.databases AS db WITH (NOLOCK)
INNER JOIN sys.dm_os_performance_counters AS lu WITH (NOLOCK)
ON db.name = lu.instance_name
INNER JOIN sys.dm_os_performance_counters AS ls WITH (NOLOCK)
ON db.name = ls.instance_name
LEFT OUTER JOIN sys.dm_database_encryption_keys AS de WITH (NOLOCK)
ON db.database_id = de.database_id
WHERE lu.counter_name LIKE N'Log File(s) Used Size (KB)%' 
AND ls.counter_name LIKE N'Log File(s) Size (KB)%'
AND ls.cntr_value > 0 
ORDER BY db.[name] OPTION (RECOMPILE);
------

-- Things to look at:
-- How many databases are on the instance?
-- What recovery models are they using?
-- What is the log reuse wait description?
-- How full are the transaction logs?
-- What compatibility level are the databases on? 
-- What is the Page Verify Option? (should be CHECKSUM)
-- Is Auto Update Statistics Asynchronously enabled?
-- Is Delayed Durability enabled
-- Make sure auto_shrink and auto_close are not enabled!

-- is_mixed_page_allocation_on is a new property for SQL Server 2016. Equivalent to TF 1118 for a user database
-- SQL Server 2016: Changes in default behavior for autogrow and allocations for tempdb and user databases
-- https://bit.ly/2evRZSR

-- A non-zero value for target_recovery_time_in_seconds means that indirect checkpoint is enabled 
-- If the setting has a zero value it indicates that automatic checkpoint is enabled

-- Changes in SQL Server 2016 Checkpoint Behavior
-- https://bit.ly/2pdggk3


-- Missing Indexes for all databases by Index Advantage  (Query 35) (Missing Indexes All Databases)
SELECT CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage],
FORMAT(migs.last_user_seek, 'yyyy-MM-dd HH:mm:ss') AS [last_user_seek], 
mid.[statement] AS [Database.Schema.Table],
COUNT(1) OVER(PARTITION BY mid.[statement]) AS [missing_indexes_for_table],
COUNT(1) OVER(PARTITION BY mid.[statement], equality_columns) AS [similar_missing_indexes_for_table],
mid.equality_columns, mid.inequality_columns, mid.included_columns,
migs.unique_compiles, migs.user_seeks, 
CONVERT(decimal(18,2), migs.avg_total_user_cost) AS [avg_total_user_cost], migs.avg_user_impact 
FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)
INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)
ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)
ON mig.index_handle = mid.index_handle
ORDER BY index_advantage DESC OPTION (RECOMPILE);
------

-- Getting missing index information for all of the databases on the instance is very useful
-- Look at last user seek time, number of user seeks to help determine source and importance
-- Also look at avg_user_impact and avg_total_user_cost to help determine importance
-- SQL Server is overly eager to add included columns, so beware
-- Do not just blindly add indexes that show up from this query!!!

-- SQL Server Index Design Guide
-- https://bit.ly/2qtZr4N



-- Get VLF Counts for all databases on the instance (Query 36) (VLF Counts)
-- (adapted from Michelle Ufford) 
CREATE TABLE #VLFInfo (RecoveryUnitID int, FileID  int,
					   FileSize bigint, StartOffset bigint,
					   FSeqNo      bigint, [Status]    bigint,
					   Parity      bigint, CreateLSN   numeric(38));
	 
CREATE TABLE #VLFCountResults(DatabaseName sysname, VLFCount int);
	 
EXEC sp_MSforeachdb N'Use [?]; 

				INSERT INTO #VLFInfo 
				EXEC sp_executesql N''DBCC LOGINFO([?])''; 
	 
				INSERT INTO #VLFCountResults 
				SELECT DB_NAME(), COUNT(*) 
				FROM #VLFInfo; 

				TRUNCATE TABLE #VLFInfo;'
	 
SELECT DatabaseName, VLFCount  
FROM #VLFCountResults
ORDER BY VLFCount DESC;
	 
DROP TABLE #VLFInfo;
DROP TABLE #VLFCountResults;
------

-- High VLF counts can affect write performance to the log file
-- and they can make full database restores and crash recovery take much longer
-- Try to keep your VLF counts under 200 in most cases (depending on log file size)

-- Important change to VLF creation algorithm in SQL Server 2014
-- https://bit.ly/2Hsjbg4

-- SQL Server Transaction Log Architecture and Management Guide
-- https://bit.ly/2JjmQRZ




-- Get CPU utilization by database (Query 37) (CPU Usage by Database)
WITH DB_CPU_Stats
AS
(SELECT pa.DatabaseID, DB_Name(pa.DatabaseID) AS [Database Name], SUM(qs.total_worker_time/1000) AS [CPU_Time_Ms]
 FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
 CROSS APPLY (SELECT CONVERT(int, value) AS [DatabaseID] 
              FROM sys.dm_exec_plan_attributes(qs.plan_handle)
              WHERE attribute = N'dbid') AS pa
 GROUP BY DatabaseID)
SELECT ROW_NUMBER() OVER(ORDER BY [CPU_Time_Ms] DESC) AS [CPU Rank],
       [Database Name], [CPU_Time_Ms] AS [CPU Time (ms)], 
       CAST([CPU_Time_Ms] * 1.0 / SUM([CPU_Time_Ms]) OVER() * 100.0 AS DECIMAL(5, 2)) AS [CPU Percent]
FROM DB_CPU_Stats
WHERE DatabaseID <> 32767 -- ResourceDB
ORDER BY [CPU Rank] OPTION (RECOMPILE);
------

-- Helps determine which database is using the most CPU resources on the instance
-- Note: This only reflects CPU usage from the currently cached query plans


-- Get I/O utilization by database (Query 38) (IO Usage By Database)
WITH Aggregate_IO_Statistics
AS (SELECT DB_NAME(database_id) AS [Database Name],
    CAST(SUM(num_of_bytes_read + num_of_bytes_written) / 1048576 AS DECIMAL(12, 2)) AS [ioTotalMB],
    CAST(SUM(num_of_bytes_read ) / 1048576 AS DECIMAL(12, 2)) AS [ioReadMB],
    CAST(SUM(num_of_bytes_written) / 1048576 AS DECIMAL(12, 2)) AS [ioWriteMB]
    FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS [DM_IO_STATS]
    GROUP BY database_id)
SELECT ROW_NUMBER() OVER (ORDER BY ioTotalMB DESC) AS [I/O Rank],
        [Database Name], ioTotalMB AS [Total I/O (MB)],
        CAST(ioTotalMB / SUM(ioTotalMB) OVER () * 100.0 AS DECIMAL(5, 2)) AS [Total I/O %],
        ioReadMB AS [Read I/O (MB)], 
		CAST(ioReadMB / SUM(ioReadMB) OVER () * 100.0 AS DECIMAL(5, 2)) AS [Read I/O %],
        ioWriteMB AS [Write I/O (MB)], 
		CAST(ioWriteMB / SUM(ioWriteMB) OVER () * 100.0 AS DECIMAL(5, 2)) AS [Write I/O %]
FROM Aggregate_IO_Statistics
ORDER BY [I/O Rank] OPTION (RECOMPILE);
------

-- Helps determine which database is using the most I/O resources on the instance
-- These numbers are cumulative since the last service restart
-- They include all I/O activity, not just the nominal I/O workload


-- Get total buffer usage by database for current instance  (Query 39) (Total Buffer Usage by Database)
-- This make take some time to run on a busy instance
WITH AggregateBufferPoolUsage
AS
(SELECT DB_NAME(database_id) AS [Database Name],
CAST(COUNT(*) * 8/1024.0 AS DECIMAL (10,2))  AS [CachedSize]
FROM sys.dm_os_buffer_descriptors WITH (NOLOCK)
WHERE database_id <> 32767 -- ResourceDB
GROUP BY DB_NAME(database_id))
SELECT ROW_NUMBER() OVER(ORDER BY CachedSize DESC) AS [Buffer Pool Rank], [Database Name], CachedSize AS [Cached Size (MB)],
       CAST(CachedSize / SUM(CachedSize) OVER() * 100.0 AS DECIMAL(5,2)) AS [Buffer Pool Percent]
FROM AggregateBufferPoolUsage
ORDER BY [Buffer Pool Rank] OPTION (RECOMPILE);
------

-- Tells you how much memory (in the buffer pool) 
-- is being used by each database on the instance


-- Clear Wait Stats with this command
-- DBCC SQLPERF('sys.dm_os_wait_stats', CLEAR);

-- Isolate top waits for server instance since last restart or wait statistics clear  (Query 40) (Top Waits)
WITH [Waits] 
AS (SELECT wait_type, wait_time_ms/ 1000.0 AS [WaitS],
          (wait_time_ms - signal_wait_time_ms) / 1000.0 AS [ResourceS],
           signal_wait_time_ms / 1000.0 AS [SignalS],
           waiting_tasks_count AS [WaitCount],
           100.0 *  wait_time_ms / SUM (wait_time_ms) OVER() AS [Percentage],
           ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS [RowNum]
    FROM sys.dm_os_wait_stats WITH (NOLOCK)
    WHERE [wait_type] NOT IN (
        N'BROKER_EVENTHANDLER', N'BROKER_RECEIVE_WAITFOR', N'BROKER_TASK_STOP',
		N'BROKER_TO_FLUSH', N'BROKER_TRANSMITTER', N'CHECKPOINT_QUEUE',
        N'CHKPT', N'CLR_AUTO_EVENT', N'CLR_MANUAL_EVENT', N'CLR_SEMAPHORE',
        N'DBMIRROR_DBM_EVENT', N'DBMIRROR_EVENTS_QUEUE', N'DBMIRROR_WORKER_QUEUE',
		N'DBMIRRORING_CMD', N'DIRTY_PAGE_POLL', N'DISPATCHER_QUEUE_SEMAPHORE',
        N'EXECSYNC', N'FSAGENT', N'FT_IFTS_SCHEDULER_IDLE_WAIT', N'FT_IFTSHC_MUTEX',
        N'HADR_CLUSAPI_CALL', N'HADR_FILESTREAM_IOMGR_IOCOMPLETION', N'HADR_LOGCAPTURE_WAIT', 
		N'HADR_NOTIFICATION_DEQUEUE', N'HADR_TIMER_TASK', N'HADR_WORK_QUEUE',
        N'KSOURCE_WAKEUP', N'LAZYWRITER_SLEEP', N'LOGMGR_QUEUE', 
		N'MEMORY_ALLOCATION_EXT', N'ONDEMAND_TASK_QUEUE',
		N'PARALLEL_REDO_DRAIN_WORKER', N'PARALLEL_REDO_LOG_CACHE', N'PARALLEL_REDO_TRAN_LIST',
		N'PARALLEL_REDO_WORKER_SYNC', N'PARALLEL_REDO_WORKER_WAIT_WORK',
		N'PREEMPTIVE_HADR_LEASE_MECHANISM', N'PREEMPTIVE_SP_SERVER_DIAGNOSTICS',
		N'PREEMPTIVE_OS_LIBRARYOPS', N'PREEMPTIVE_OS_COMOPS', N'PREEMPTIVE_OS_CRYPTOPS',
		N'PREEMPTIVE_OS_PIPEOPS', N'PREEMPTIVE_OS_AUTHENTICATIONOPS',
		N'PREEMPTIVE_OS_GENERICOPS', N'PREEMPTIVE_OS_VERIFYTRUST',
		N'PREEMPTIVE_OS_FILEOPS', N'PREEMPTIVE_OS_DEVICEOPS', N'PREEMPTIVE_OS_QUERYREGISTRY',
		N'PREEMPTIVE_OS_WRITEFILE',
		N'PREEMPTIVE_XE_CALLBACKEXECUTE', N'PREEMPTIVE_XE_DISPATCHER',
		N'PREEMPTIVE_XE_GETTARGETSTATE', N'PREEMPTIVE_XE_SESSIONCOMMIT',
		N'PREEMPTIVE_XE_TARGETINIT', N'PREEMPTIVE_XE_TARGETFINALIZE',
        N'PWAIT_ALL_COMPONENTS_INITIALIZED', N'PWAIT_DIRECTLOGCONSUMER_GETNEXT',
		N'QDS_PERSIST_TASK_MAIN_LOOP_SLEEP',
		N'QDS_ASYNC_QUEUE',
        N'QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP', N'REQUEST_FOR_DEADLOCK_SEARCH',
		N'RESOURCE_QUEUE', N'SERVER_IDLE_CHECK', N'SLEEP_BPOOL_FLUSH', N'SLEEP_DBSTARTUP',
		N'SLEEP_DCOMSTARTUP', N'SLEEP_MASTERDBREADY', N'SLEEP_MASTERMDREADY',
        N'SLEEP_MASTERUPGRADED', N'SLEEP_MSDBSTARTUP', N'SLEEP_SYSTEMTASK', N'SLEEP_TASK',
        N'SLEEP_TEMPDBSTARTUP', N'SNI_HTTP_ACCEPT', N'SP_SERVER_DIAGNOSTICS_SLEEP',
		N'SQLTRACE_BUFFER_FLUSH', N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', N'SQLTRACE_WAIT_ENTRIES',
		N'WAIT_FOR_RESULTS', N'WAITFOR', N'WAITFOR_TASKSHUTDOWN', N'WAIT_XTP_HOST_WAIT',
		N'WAIT_XTP_OFFLINE_CKPT_NEW_LOG', N'WAIT_XTP_CKPT_CLOSE', N'WAIT_XTP_RECOVERY',
		N'XE_BUFFERMGR_ALLPROCESSED_EVENT', N'XE_DISPATCHER_JOIN',
        N'XE_DISPATCHER_WAIT', N'XE_LIVE_TARGET_TVF', N'XE_TIMER_EVENT')
    AND waiting_tasks_count > 0)
SELECT
    MAX (W1.wait_type) AS [WaitType],
	CAST (MAX (W1.Percentage) AS DECIMAL (5,2)) AS [Wait Percentage],
	CAST ((MAX (W1.WaitS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgWait_Sec],
    CAST ((MAX (W1.ResourceS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgRes_Sec],
    CAST ((MAX (W1.SignalS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgSig_Sec], 
    CAST (MAX (W1.WaitS) AS DECIMAL (16,2)) AS [Wait_Sec],
    CAST (MAX (W1.ResourceS) AS DECIMAL (16,2)) AS [Resource_Sec],
    CAST (MAX (W1.SignalS) AS DECIMAL (16,2)) AS [Signal_Sec],
    MAX (W1.WaitCount) AS [Wait Count],
	CAST (N'https://www.sqlskills.com/help/waits/' + W1.wait_type AS XML) AS [Help/Info URL]
FROM Waits AS W1
INNER JOIN Waits AS W2
ON W2.RowNum <= W1.RowNum
GROUP BY W1.RowNum, W1.wait_type
HAVING SUM (W2.Percentage) - MAX (W1.Percentage) < 99 -- percentage threshold
OPTION (RECOMPILE);
------

-- Cumulative wait stats are not as useful on an idle instance that is not under load or performance pressure

-- SQL Server Wait Types Library (Paul Randal)
-- https://bit.ly/2ePzYO2

-- The SQL Server Wait Type Repository
-- https://bit.ly/1afzfjC

-- Wait statistics, or please tell me where it hurts
-- https://bit.ly/2wsQHQE

-- SQL Server 2005 Performance Tuning using the Waits and Queues
-- https://bit.ly/1o2NFoF

-- sys.dm_os_wait_stats (Transact-SQL)
-- https://bit.ly/2Hjq9Yl



-- Get a count of SQL connections by IP address (Query 41) (Connection Counts by IP Address)
SELECT ec.client_net_address, es.[program_name], es.[host_name], es.login_name, 
COUNT(ec.session_id) AS [connection count] 
FROM sys.dm_exec_sessions AS es WITH (NOLOCK) 
INNER JOIN sys.dm_exec_connections AS ec WITH (NOLOCK) 
ON es.session_id = ec.session_id 
GROUP BY ec.client_net_address, es.[program_name], es.[host_name], es.login_name  
ORDER BY ec.client_net_address, es.[program_name] OPTION (RECOMPILE);
------

-- This helps you figure where your database load is coming from
-- and verifies connectivity from other machines

-- Solving Connectivity errors to SQL Server
-- https://bit.ly/2EgzoD0



-- Get Average Task Counts (run multiple times)  (Query 42) (Avg Task Counts)
SELECT AVG(current_tasks_count) AS [Avg Task Count], 
AVG(work_queue_count) AS [Avg Work Queue Count],
AVG(runnable_tasks_count) AS [Avg Runnable Task Count],
AVG(pending_disk_io_count) AS [Avg Pending DiskIO Count]
FROM sys.dm_os_schedulers WITH (NOLOCK)
WHERE scheduler_id < 255 OPTION (RECOMPILE);
------

-- Sustained values above 10 suggest further investigation in that area
-- High Avg Task Counts are often caused by blocking/deadlocking or other resource contention

-- Sustained values above 1 suggest further investigation in that area
-- High Avg Runnable Task Counts are a good sign of CPU pressure
-- High Avg Pending DiskIO Counts are a sign of disk pressure

-- How to Do Some Very Basic SQL Server Monitoring
-- https://bit.ly/2q3Btgt



-- Detect blocking (run multiple times)  (Query 43) (Detect Blocking)
SELECT t1.resource_type AS [lock type], DB_NAME(resource_database_id) AS [database],
t1.resource_associated_entity_id AS [blk object],t1.request_mode AS [lock req],  -- lock requested
t1.request_session_id AS [waiter sid], t2.wait_duration_ms AS [wait time],       -- spid of waiter  
(SELECT [text] FROM sys.dm_exec_requests AS r WITH (NOLOCK)                      -- get sql for waiter
CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) 
WHERE r.session_id = t1.request_session_id) AS [waiter_batch],
(SELECT SUBSTRING(qt.[text],r.statement_start_offset/2, 
    (CASE WHEN r.statement_end_offset = -1 
    THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2 
    ELSE r.statement_end_offset END - r.statement_start_offset)/2) 
FROM sys.dm_exec_requests AS r WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) AS qt
WHERE r.session_id = t1.request_session_id) AS [waiter_stmt],					-- statement blocked
t2.blocking_session_id AS [blocker sid],										-- spid of blocker
(SELECT [text] FROM sys.sysprocesses AS p										-- get sql for blocker
CROSS APPLY sys.dm_exec_sql_text(p.[sql_handle]) 
WHERE p.spid = t2.blocking_session_id) AS [blocker_batch]
FROM sys.dm_tran_locks AS t1 WITH (NOLOCK)
INNER JOIN sys.dm_os_waiting_tasks AS t2 WITH (NOLOCK)
ON t1.lock_owner_address = t2.resource_address OPTION (RECOMPILE);
------

-- Helps troubleshoot blocking and deadlocking issues
-- The results will change from second to second on a busy system
-- You should run this query multiple times when you see signs of blocking



-- Get CPU Utilization History for last 256 minutes (in one minute intervals)  (Query 44) (CPU Utilization History)
DECLARE @ts_now bigint = (SELECT cpu_ticks/(cpu_ticks/ms_ticks) FROM sys.dm_os_sys_info WITH (NOLOCK)); 

SELECT TOP(256) SQLProcessUtilization AS [SQL Server Process CPU Utilization], 
               SystemIdle AS [System Idle Process], 
               100 - SystemIdle - SQLProcessUtilization AS [Other Process CPU Utilization], 
               DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) AS [Event Time] 
FROM (SELECT record.value('(./Record/@id)[1]', 'int') AS record_id, 
			record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') 
			AS [SystemIdle], 
			record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int') 
			AS [SQLProcessUtilization], [timestamp] 
	  FROM (SELECT [timestamp], CONVERT(xml, record) AS [record] 
			FROM sys.dm_os_ring_buffers WITH (NOLOCK)
			WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR' 
			AND record LIKE N'%<SystemHealth>%') AS x) AS y 
ORDER BY record_id DESC OPTION (RECOMPILE);
------

-- Look at the trend over the entire period 
-- Also look at high sustained 'Other Process' CPU Utilization values
-- Note: This query sometimes gives inaccurate results (negative values)
-- on high core count (> 64 cores) systems


-- Get top total worker time queries for entire instance (Query 45) (Top Worker Time Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], 
REPLACE(REPLACE(LEFT(t.[text], 255), CHAR(10),''), CHAR(13),'') AS [Short Query Text],  
qs.total_worker_time AS [Total Worker Time], qs.min_worker_time AS [Min Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.max_worker_time AS [Max Worker Time], 
qs.min_elapsed_time AS [Min Elapsed Time], 
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time], 
qs.max_elapsed_time AS [Max Elapsed Time],
qs.min_logical_reads AS [Min Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.max_logical_reads AS [Max Logical Reads], 
qs.execution_count AS [Execution Count],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
qs.creation_time AS [Creation Time]
--,t.[text] AS [Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
ORDER BY qs.total_worker_time DESC OPTION (RECOMPILE);
------


-- Helps you find the most expensive queries from a CPU perspective across the entire instance
-- Can also help track down parameter sniffing issues



-- Page Life Expectancy (PLE) value for each NUMA node in current instance  (Query 46) (PLE by NUMA Node)
SELECT @@SERVERNAME AS [Server Name], RTRIM([object_name]) AS [Object Name], instance_name, cntr_value AS [Page Life Expectancy]
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Buffer Node%' -- Handles named instances
AND counter_name = N'Page life expectancy' OPTION (RECOMPILE);
------

-- PLE is a good measurement of internal memory pressure
-- Higher PLE is better. Watch the trend over time, not the absolute value
-- This will only return one row for non-NUMA systems

-- Page Life Expectancy isn�t what you think�
-- https://bit.ly/2EgynLa


-- Memory Grants Pending value for current instance  (Query 47) (Memory Grants Pending)
SELECT @@SERVERNAME AS [Server Name], RTRIM([object_name]) AS [Object Name], cntr_value AS [Memory Grants Pending]                                                                                                       
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Memory Manager%' -- Handles named instances
AND counter_name = N'Memory Grants Pending' OPTION (RECOMPILE);
------

-- Run multiple times, and run periodically if you suspect you are under memory pressure
-- Memory Grants Pending above zero for a sustained period is a very strong indicator of internal memory pressure


-- Memory Clerk Usage for instance  (Query 48) (Memory Clerk Usage)
-- Look for high value for CACHESTORE_SQLCP (Ad-hoc query plans)
SELECT TOP(10) mc.[type] AS [Memory Clerk Type], 
       CAST((SUM(mc.pages_kb)/1024.0) AS DECIMAL (15,2)) AS [Memory Usage (MB)] 
FROM sys.dm_os_memory_clerks AS mc WITH (NOLOCK)
GROUP BY mc.[type]  
ORDER BY SUM(mc.pages_kb) DESC OPTION (RECOMPILE);
------

-- MEMORYCLERK_SQLBUFFERPOOL was new for SQL Server 2012. It should be your highest consumer of memory

-- CACHESTORE_SQLCP  SQL Plans         
-- These are cached SQL statements or batches that aren't in stored procedures, functions and triggers
-- Watch out for high values for CACHESTORE_SQLCP
-- Enabling 'optimize for ad hoc workloads' at the instance level can help reduce this
-- Running DBCC FREESYSTEMCACHE ('SQL Plans') periodically may be required to better control this

-- CACHESTORE_OBJCP  Object Plans      
-- These are compiled plans for stored procedures, functions and triggers



-- Find single-use, ad-hoc and prepared queries that are bloating the plan cache  (Query 49) (Ad hoc Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], t.[text] AS [Query Text], 
cp.objtype AS [Object Type], cp.cacheobjtype AS [Cache Object Type],  
cp.size_in_bytes/1024 AS [Plan Size in KB]
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t
WHERE cp.cacheobjtype = N'Compiled Plan' 
AND cp.objtype IN (N'Adhoc', N'Prepared') 
AND cp.usecounts = 1
ORDER BY cp.size_in_bytes DESC, DB_NAME(t.[dbid]) OPTION (RECOMPILE);
------

-- Gives you the text, type and size of single-use ad-hoc and prepared queries that waste space in the plan cache
-- Enabling 'optimize for ad hoc workloads' for the instance can help (SQL Server 2008 and above only)
-- Running DBCC FREESYSTEMCACHE ('SQL Plans') periodically may be required to better control this
-- Enabling forced parameterization for the database can help, but test first!

-- Plan cache, adhoc workloads and clearing the single-use plan cache bloat
-- https://bit.ly/2EfYOkl


-- Get top total logical reads queries for entire instance (Query 50) (Top Logical Reads Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name],
REPLACE(REPLACE(LEFT(t.[text], 255), CHAR(10),''), CHAR(13),'') AS [Short Query Text], 
qs.total_logical_reads AS [Total Logical Reads],
qs.min_logical_reads AS [Min Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.max_logical_reads AS [Max Logical Reads],   
qs.min_worker_time AS [Min Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.max_worker_time AS [Max Worker Time], 
qs.min_elapsed_time AS [Min Elapsed Time], 
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time], 
qs.max_elapsed_time AS [Max Elapsed Time],
qs.execution_count AS [Execution Count], 
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
qs.creation_time AS [Creation Time]
--,t.[text] AS [Complete Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
ORDER BY qs.total_logical_reads DESC OPTION (RECOMPILE);
------


-- Helps you find the most expensive queries from a memory perspective across the entire instance
-- Can also help track down parameter sniffing issues


-- Get top average elapsed time queries for entire instance (Query 51) (Top Avg Elapsed Time Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], 
REPLACE(REPLACE(LEFT(t.[text], 255), CHAR(10),''), CHAR(13),'') AS [Short Query Text],  
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
qs.min_elapsed_time, qs.max_elapsed_time, qs.last_elapsed_time,
qs.execution_count AS [Execution Count],  
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads], 
qs.total_physical_reads/qs.execution_count AS [Avg Physical Reads], 
qs.total_worker_time/qs.execution_count AS [Avg Worker Time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
qs.creation_time AS [Creation Time]
--,t.[text] AS [Complete Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
ORDER BY qs.total_elapsed_time/qs.execution_count DESC OPTION (RECOMPILE);
------

-- Helps you find the highest average elapsed time queries across the entire instance
-- Can also help track down parameter sniffing issues


-- Look at UDF execution statistics (Query 52) (UDF Stats by DB)
SELECT TOP (25) DB_NAME(database_id) AS [Database Name], 
		   OBJECT_NAME(object_id, database_id) AS [Function Name],
		   total_worker_time, execution_count, total_elapsed_time,  
           total_elapsed_time/execution_count AS [avg_elapsed_time],  
           last_elapsed_time, last_execution_time, cached_time 
FROM sys.dm_exec_function_stats WITH (NOLOCK) 
ORDER BY total_worker_time DESC OPTION (RECOMPILE);
------

-- sys.dm_exec_function_stats (Transact-SQL)
-- https://bit.ly/2q1Q6BM

-- Showplan Enhancements for UDFs
-- https://bit.ly/2LVqiQ1


-- Database specific queries *****************************************************************

-- **** Please switch to a user database that you are interested in! *****
--USE YourDatabaseName; -- make sure to change to an actual database on your instance, not the master system database
--GO

-- Individual File Sizes and space available for current database  (Query 53) (File Sizes and Space)
SELECT f.name AS [File Name] , f.physical_name AS [Physical Name], 
CAST((f.size/128.0) AS DECIMAL(15,2)) AS [Total Size in MB],
CAST(f.size/128.0 - CAST(FILEPROPERTY(f.name, 'SpaceUsed') AS int)/128.0 AS DECIMAL(15,2)) 
AS [Available Space In MB], f.[file_id], fg.name AS [Filegroup Name],
f.is_percent_growth, f.growth, fg.is_default, fg.is_read_only, 
fg.is_autogrow_all_files -- New in SQL Server 2016
FROM sys.database_files AS f WITH (NOLOCK) 
LEFT OUTER JOIN sys.filegroups AS fg WITH (NOLOCK)
ON f.data_space_id = fg.data_space_id
ORDER BY f.[file_id] OPTION (RECOMPILE);
------

-- Look at how large and how full the files are and where they are located
-- Make sure the transaction log is not full!!

-- is_autogrow_all_files is new for SQL Server 2016. Equivalent to TF 1117 for user databases

-- SQL Server 2016: Changes in default behavior for autogrow and allocations for tempdb and user databases
-- https://bit.ly/2evRZSR


-- Log space usage for current database  (Query 54) (Log Space Usage)
SELECT DB_NAME(lsu.database_id) AS [Database Name], db.recovery_model_desc AS [Recovery Model],
		CAST(lsu.total_log_size_in_bytes/1048576.0 AS DECIMAL(10, 2)) AS [Total Log Space (MB)],
		CAST(lsu.used_log_space_in_bytes/1048576.0 AS DECIMAL(10, 2)) AS [Used Log Space (MB)], 
		CAST(lsu.used_log_space_in_percent AS DECIMAL(10, 2)) AS [Used Log Space %],
		CAST(lsu.log_space_in_bytes_since_last_backup/1048576.0 AS DECIMAL(10, 2)) AS [Used Log Space Since Last Backup (MB)],
		db.log_reuse_wait_desc		 
FROM sys.dm_db_log_space_usage AS lsu WITH (NOLOCK)
INNER JOIN sys.databases AS db WITH (NOLOCK)
ON lsu.database_id = db.database_id
OPTION (RECOMPILE);
------

-- Look at log file size and usage, along with the log reuse wait description for the current database



-- Get database scoped configuration values for current database (Query 55) (Database-scoped Configurations)
SELECT configuration_id, name, [value] AS [value_for_primary], value_for_secondary
FROM sys.database_scoped_configurations WITH (NOLOCK) OPTION (RECOMPILE);
------

-- This lets you see the value of these new properties for the current database

-- Clear plan cache for current database
-- ALTER DATABASE SCOPED CONFIGURATION CLEAR PROCEDURE_CACHE;

-- ALTER DATABASE SCOPED CONFIGURATION (Transact-SQL)
-- https://bit.ly/2sOH7nb


-- I/O Statistics by file for the current database  (Query 56) (IO Stats By File)
SELECT DB_NAME(DB_ID()) AS [Database Name], df.name AS [Logical Name], vfs.[file_id], df.type_desc,
df.physical_name AS [Physical Name], CAST(vfs.size_on_disk_bytes/1048576.0 AS DECIMAL(16, 2)) AS [Size on Disk (MB)],
vfs.num_of_reads, vfs.num_of_writes, vfs.io_stall_read_ms, vfs.io_stall_write_ms,
CAST(100. * vfs.io_stall_read_ms/(vfs.io_stall_read_ms + vfs.io_stall_write_ms) AS DECIMAL(16,1)) AS [IO Stall Reads Pct],
CAST(100. * vfs.io_stall_write_ms/(vfs.io_stall_write_ms + vfs.io_stall_read_ms) AS DECIMAL(16,1)) AS [IO Stall Writes Pct],
(vfs.num_of_reads + vfs.num_of_writes) AS [Writes + Reads], 
CAST(vfs.num_of_bytes_read/1048576.0 AS DECIMAL(16, 2)) AS [MB Read], 
CAST(vfs.num_of_bytes_written/1048576.0 AS DECIMAL(16, 2)) AS [MB Written],
CAST(100. * vfs.num_of_reads/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(16,1)) AS [# Reads Pct],
CAST(100. * vfs.num_of_writes/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(16,1)) AS [# Write Pct],
CAST(100. * vfs.num_of_bytes_read/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(16,1)) AS [Read Bytes Pct],
CAST(100. * vfs.num_of_bytes_written/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(16,1)) AS [Written Bytes Pct]
FROM sys.dm_io_virtual_file_stats(DB_ID(), NULL) AS vfs
INNER JOIN sys.database_files AS df WITH (NOLOCK)
ON vfs.[file_id]= df.[file_id] OPTION (RECOMPILE);
------

-- This helps you characterize your workload better from an I/O perspective for this database
-- It helps you determine whether you has an OLTP or DW/DSS type of workload



-- Get most frequently executed queries for this database (Query 57) (Query Execution Counts)
SELECT TOP(50) LEFT(t.[text], 50) AS [Short Query Text], qs.execution_count AS [Execution Count],
qs.total_logical_reads AS [Total Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.total_worker_time AS [Total Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.total_elapsed_time AS [Total Elapsed Time],
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
qs.creation_time AS [Creation Time]
--,t.[text] AS [Complete Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
WHERE t.dbid = DB_ID()
ORDER BY qs.execution_count DESC OPTION (RECOMPILE);
------


-- Queries 56 through 61 are the "Bad Man List" for stored procedures

-- Top Cached SPs By Execution Count (Query 58) (SP Execution Counts)
SELECT TOP(100) p.name AS [SP Name], qs.execution_count AS [Execution Count],
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time],    
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.execution_count DESC OPTION (RECOMPILE);
------

-- Tells you which cached stored procedures are called the most often
-- This helps you characterize and baseline your workload


-- Top Cached SPs By Avg Elapsed Time (Query 59) (SP Avg Elapsed Time)
SELECT TOP(25) p.name AS [SP Name], qs.min_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time], 
qs.max_elapsed_time, qs.last_elapsed_time, qs.total_elapsed_time, qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute], 
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], 
qs.total_worker_time AS [TotalWorkerTime],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY avg_elapsed_time DESC OPTION (RECOMPILE);
------

-- This helps you find high average elapsed time cached stored procedures that
-- may be easy to optimize with standard query tuning techniques



-- Top Cached SPs By Total Worker time. Worker time relates to CPU cost  (Query 60) (SP Worker Time)
SELECT TOP(25) p.name AS [SP Name], qs.total_worker_time AS [TotalWorkerTime], 
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.total_worker_time DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a CPU perspective
-- You should look at this if you see signs of CPU pressure


-- Top Cached SPs By Total Logical Reads. Logical reads relate to memory pressure  (Query 61) (SP Logical Reads)
SELECT TOP(25) p.name AS [SP Name], qs.total_logical_reads AS [TotalLogicalReads], 
qs.total_logical_reads/qs.execution_count AS [AvgLogicalReads],qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute], 
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.total_logical_reads DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a memory perspective
-- You should look at this if you see signs of memory pressure


-- Top Cached SPs By Total Physical Reads. Physical reads relate to disk read I/O pressure  (Query 62) (SP Physical Reads)
SELECT TOP(25) p.name AS [SP Name],qs.total_physical_reads AS [TotalPhysicalReads], 
qs.total_physical_reads/qs.execution_count AS [AvgPhysicalReads], qs.execution_count, 
qs.total_logical_reads,qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan 
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND qs.total_physical_reads > 0
ORDER BY qs.total_physical_reads DESC, qs.total_logical_reads DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a read I/O perspective
-- You should look at this if you see signs of I/O pressure or of memory pressure
       


-- Top Cached SPs By Total Logical Writes (Query 63) (SP Logical Writes)
-- Logical writes relate to both memory and disk I/O pressure 
SELECT TOP(25) p.name AS [SP Name], qs.total_logical_writes AS [TotalLogicalWrites], 
qs.total_logical_writes/qs.execution_count AS [AvgLogicalWrites], qs.execution_count,
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan 
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND qs.total_logical_writes > 0
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.total_logical_writes DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a write I/O perspective
-- You should look at this if you see signs of I/O pressure or of memory pressure


-- Lists the top statements by average input/output usage for the current database  (Query 64) (Top IO Statements)
SELECT TOP(50) OBJECT_NAME(qt.objectid, dbid) AS [SP Name],
(qs.total_logical_reads + qs.total_logical_writes) /qs.execution_count AS [Avg IO], qs.execution_count AS [Execution Count],
SUBSTRING(qt.[text],qs.statement_start_offset/2, 
	(CASE 
		WHEN qs.statement_end_offset = -1 
	 THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2 
		ELSE qs.statement_end_offset 
	 END - qs.statement_start_offset)/2) AS [Query Text]	
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
WHERE qt.[dbid] = DB_ID()
ORDER BY [Avg IO] DESC OPTION (RECOMPILE);
------

-- Helps you find the most expensive statements for I/O by SP



-- Possible Bad NC Indexes (writes > reads)  (Query 65) (Bad NC Indexes)
SELECT OBJECT_NAME(s.[object_id]) AS [Table Name], i.name AS [Index Name], i.index_id, 
i.is_disabled, i.is_hypothetical, i.has_filter, i.fill_factor,
s.user_updates AS [Total Writes], s.user_seeks + s.user_scans + s.user_lookups AS [Total Reads],
s.user_updates - (s.user_seeks + s.user_scans + s.user_lookups) AS [Difference]
FROM sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON s.[object_id] = i.[object_id]
AND i.index_id = s.index_id
WHERE OBJECTPROPERTY(s.[object_id],'IsUserTable') = 1
AND s.database_id = DB_ID()
AND s.user_updates > (s.user_seeks + s.user_scans + s.user_lookups)
AND i.index_id > 1 AND i.[type_desc] = N'NONCLUSTERED'
AND i.is_primary_key = 0 AND i.is_unique_constraint = 0 AND i.is_unique = 0
ORDER BY [Difference] DESC, [Total Writes] DESC, [Total Reads] ASC OPTION (RECOMPILE);
------

-- Look for indexes with high numbers of writes and zero or very low numbers of reads
-- Consider your complete workload, and how long your instance has been running
-- Investigate further before dropping an index!


-- Missing Indexes for current database by Index Advantage  (Query 66) (Missing Indexes)
SELECT CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage], 
migs.last_user_seek, mid.[statement] AS [Database.Schema.Table],
COUNT(1) OVER(PARTITION BY mid.[statement]) AS [missing_indexes_for_table],
COUNT(1) OVER(PARTITION BY mid.[statement], equality_columns) AS [similar_missing_indexes_for_table],
mid.equality_columns, mid.inequality_columns, mid.included_columns,
migs.unique_compiles, migs.user_seeks, 
CONVERT(decimal(18,2), migs.avg_total_user_cost) AS [avg_total_user_cost], migs.avg_user_impact,
OBJECT_NAME(mid.[object_id]) AS [Table Name], p.rows AS [Table Rows]
FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)
INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)
ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)
ON mig.index_handle = mid.index_handle
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON p.[object_id] = mid.[object_id]
WHERE mid.database_id = DB_ID()
AND p.index_id < 2 
ORDER BY index_advantage DESC OPTION (RECOMPILE);
------

-- Look at index advantage, last user seek time, number of user seeks to help determine source and importance
-- SQL Server is overly eager to add included columns, so beware
-- Do not just blindly add indexes that show up from this query!!!


-- Find missing index warnings for cached plans in the current database  (Query 67) (Missing Index Warnings)
-- Note: This query could take some time on a busy instance
SELECT TOP(25) OBJECT_NAME(objectid) AS [ObjectName], 
               cp.objtype, cp.usecounts, cp.size_in_bytes, query_plan
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) AS qp
WHERE CAST(query_plan AS NVARCHAR(MAX)) LIKE N'%MissingIndex%'
AND dbid = DB_ID()
ORDER BY cp.usecounts DESC OPTION (RECOMPILE);
------

-- Helps you connect missing indexes to specific stored procedures or queries
-- This can help you decide whether to add them or not


-- Breaks down buffers used by current database by object (table, index) in the buffer cache  (Query 68) (Buffer Usage)
-- Note: This query could take some time on a busy instance
SELECT OBJECT_NAME(p.[object_id]) AS [Object Name], p.index_id, 
CAST(COUNT(*)/128.0 AS DECIMAL(10, 2)) AS [Buffer size(MB)],  
COUNT(*) AS [BufferCount], p.[Rows] AS [Row Count],
p.data_compression_desc AS [Compression Type]
FROM sys.allocation_units AS a WITH (NOLOCK)
INNER JOIN sys.dm_os_buffer_descriptors AS b WITH (NOLOCK)
ON a.allocation_unit_id = b.allocation_unit_id
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON a.container_id = p.hobt_id
WHERE b.database_id = CONVERT(int, DB_ID())
AND p.[object_id] > 100
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'plan_%'
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'sys%'
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'xml_index_nodes%'
GROUP BY p.[object_id], p.index_id, p.data_compression_desc, p.[Rows]
ORDER BY [BufferCount] DESC OPTION (RECOMPILE);
------

-- Tells you what tables and indexes are using the most memory in the buffer cache
-- It can help identify possible candidates for data compression


-- Get Table names, row counts, and compression status for clustered index or heap  (Query 69) (Table Sizes)
SELECT SCHEMA_NAME(o.Schema_ID) AS [Schema Name], OBJECT_NAME(p.object_id) AS [ObjectName], 
SUM(p.Rows) AS [RowCount], data_compression_desc AS [CompressionType]
FROM sys.partitions AS p WITH (NOLOCK)
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON p.object_id = o.object_id
WHERE index_id < 2 --ignore the partitions from the non-clustered index if any
AND OBJECT_NAME(p.object_id) NOT LIKE N'sys%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'spt_%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'queue_%' 
AND OBJECT_NAME(p.object_id) NOT LIKE N'filestream_tombstone%' 
AND OBJECT_NAME(p.object_id) NOT LIKE N'fulltext%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'ifts_comp_fragment%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'filetable_updates%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'xml_index_nodes%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'sqlagent_job%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'plan_persist%'
GROUP BY  SCHEMA_NAME(o.Schema_ID), p.object_id, data_compression_desc
ORDER BY SUM(p.Rows) DESC OPTION (RECOMPILE);
------

-- Gives you an idea of table sizes, and possible data compression opportunities



-- Get some key table properties (Query 70) (Table Properties)
SELECT OBJECT_NAME(t.[object_id]) AS [ObjectName], p.[rows] AS [Table Rows], p.index_id, 
       p.data_compression_desc AS [Index Data Compression],
       t.create_date, t.lock_on_bulk_load, t.is_replicated, t.has_replication_filter, 
       t.is_tracked_by_cdc, t.lock_escalation_desc, t.is_filetable, 
	   t.is_memory_optimized, t.durability_desc, 
	   t.temporal_type_desc, t.is_remote_data_archive_enabled, t.is_external -- new for SQL Server 2016
FROM sys.tables AS t WITH (NOLOCK)
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON t.[object_id] = p.[object_id]
WHERE OBJECT_NAME(t.[object_id]) NOT LIKE N'sys%'
ORDER BY OBJECT_NAME(t.[object_id]), p.index_id OPTION (RECOMPILE);
------

-- Gives you some good information about your tables
-- is_memory_optimized and durability_desc were new in SQL Server 2014
-- temporal_type_desc, is_remote_data_archive_enabled, is_external are new in SQL Server 2016

-- sys.tables (Transact-SQL)
-- https://bit.ly/2Gk7998



-- When were Statistics last updated on all indexes?  (Query 71) (Statistics Update)
SELECT SCHEMA_NAME(o.Schema_ID) + N'.' + o.[NAME] AS [Object Name], o.[type_desc] AS [Object Type],
      i.[name] AS [Index Name], STATS_DATE(i.[object_id], i.index_id) AS [Statistics Date], 
      s.auto_created, s.no_recompute, s.user_created, s.is_incremental, s.is_temporary,
	  st.row_count, st.used_page_count
FROM sys.objects AS o WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON o.[object_id] = i.[object_id]
INNER JOIN sys.stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id] 
AND i.index_id = s.stats_id
INNER JOIN sys.dm_db_partition_stats AS st WITH (NOLOCK)
ON o.[object_id] = st.[object_id]
AND i.[index_id] = st.[index_id]
WHERE o.[type] IN ('U', 'V')
AND st.row_count > 0
ORDER BY STATS_DATE(i.[object_id], i.index_id) DESC OPTION (RECOMPILE);
------  

-- Helps discover possible problems with out-of-date statistics
-- Also gives you an idea which indexes are the most active

-- sys.stats (Transact-SQL)
-- https://bit.ly/2GyAxrn

-- UPDATEs to Statistics (Erin Stellato)
-- https://bit.ly/2vhrYQy



-- Look at most frequently modified indexes and statistics (Query 72) (Volatile Indexes)
SELECT o.[name] AS [Object Name], o.[object_id], o.[type_desc], s.[name] AS [Statistics Name], 
       s.stats_id, s.no_recompute, s.auto_created, s.is_incremental, s.is_temporary,
	   sp.modification_counter, sp.[rows], sp.rows_sampled, sp.last_updated
FROM sys.objects AS o WITH (NOLOCK)
INNER JOIN sys.stats AS s WITH (NOLOCK)
ON s.object_id = o.object_id
CROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) AS sp
WHERE o.[type_desc] NOT IN (N'SYSTEM_TABLE', N'INTERNAL_TABLE')
AND sp.modification_counter > 0
ORDER BY sp.modification_counter DESC, o.name OPTION (RECOMPILE);
------

-- This helps you understand your workload and make better decisions about 
-- things like data compression and adding new indexes to a table



-- Get fragmentation info for all indexes above a certain size in the current database  (Query 73) (Index Fragmentation)
-- Note: This query could take some time on a very large database
SELECT DB_NAME(ps.database_id) AS [Database Name], SCHEMA_NAME(o.[schema_id]) AS [Schema Name],
OBJECT_NAME(ps.OBJECT_ID) AS [Object Name], i.[name] AS [Index Name], ps.index_id, 
ps.index_type_desc, ps.avg_fragmentation_in_percent, 
ps.fragment_count, ps.page_count, i.fill_factor, i.has_filter, 
i.filter_definition, i.[allow_page_locks]
FROM sys.dm_db_index_physical_stats(DB_ID(),NULL, NULL, NULL , N'LIMITED') AS ps
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ps.[object_id] = i.[object_id] 
AND ps.index_id = i.index_id
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON i.[object_id] = o.[object_id]
WHERE ps.database_id = DB_ID()
AND ps.page_count > 2500
ORDER BY ps.avg_fragmentation_in_percent DESC OPTION (RECOMPILE);
------

-- Helps determine whether you have framentation in your relational indexes
-- and how effective your index maintenance strategy is


--- Index Read/Write stats (all tables in current DB) ordered by Reads  (Query 74) (Overall Index Usage - Reads)
SELECT OBJECT_NAME(i.[object_id]) AS [ObjectName], i.[name] AS [IndexName], i.index_id, 
       s.user_seeks, s.user_scans, s.user_lookups,
	   s.user_seeks + s.user_scans + s.user_lookups AS [Total Reads], 
	   s.user_updates AS [Writes],  
	   i.[type_desc] AS [Index Type], i.fill_factor AS [Fill Factor], i.has_filter, i.filter_definition, 
	   s.last_user_scan, s.last_user_lookup, s.last_user_seek
FROM sys.indexes AS i WITH (NOLOCK)
LEFT OUTER JOIN sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id]
AND i.index_id = s.index_id
AND s.database_id = DB_ID()
WHERE OBJECTPROPERTY(i.[object_id],'IsUserTable') = 1
ORDER BY s.user_seeks + s.user_scans + s.user_lookups DESC OPTION (RECOMPILE); -- Order by reads
------

-- Show which indexes in the current database are most active for Reads


--- Index Read/Write stats (all tables in current DB) ordered by Writes  (Query 75) (Overall Index Usage - Writes)
SELECT OBJECT_NAME(i.[object_id]) AS [ObjectName], i.[name] AS [IndexName], i.index_id,
	   s.user_updates AS [Writes], s.user_seeks + s.user_scans + s.user_lookups AS [Total Reads], 
	   i.[type_desc] AS [Index Type], i.fill_factor AS [Fill Factor], i.has_filter, i.filter_definition,
	   s.last_system_update, s.last_user_update
FROM sys.indexes AS i WITH (NOLOCK)
LEFT OUTER JOIN sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id]
AND i.index_id = s.index_id
AND s.database_id = DB_ID()
WHERE OBJECTPROPERTY(i.[object_id],'IsUserTable') = 1
ORDER BY s.user_updates DESC OPTION (RECOMPILE);						 -- Order by writes
------

-- Show which indexes in the current database are most active for Writes


-- Get in-memory OLTP index usage (Query 76) (XTP Index Usage)
SELECT OBJECT_NAME(i.[object_id]) AS [Object Name], i.index_id, i.[name] AS [Index Name],
       i.[type_desc], xis.scans_started, xis.scans_retries, 
	   xis.rows_touched, xis.rows_returned
FROM sys.dm_db_xtp_index_stats AS xis WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON i.[object_id] = xis.[object_id] 
AND i.index_id = xis.index_id 
ORDER BY OBJECT_NAME(i.[object_id]) OPTION (RECOMPILE);
------

-- This gives you some index usage statistics for in-memory OLTP
-- Returns no data if you are not using in-memory OLTP

-- Guidelines for Using Indexes on Memory-Optimized Tables
-- https://bit.ly/2GCP8lF


-- Look at Columnstore index physical statistics (Query 77) (Columnstore Index Physical Stat)
SELECT OBJECT_NAME(ps.object_id) AS [TableName],  
	i.[name] AS [IndexName], ps.index_id, ps.partition_number,
	ps.delta_store_hobt_id, ps.state_desc, ps.total_rows, ps.size_in_bytes,
	ps.trim_reason_desc, ps.generation, ps.transition_to_compressed_state_desc,
	ps.has_vertipaq_optimization, ps.deleted_rows,
	100 * (ISNULL(ps.deleted_rows, 0))/ps.total_rows AS [Fragmentation]
FROM sys.dm_db_column_store_row_group_physical_stats AS ps WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ps.object_id = i.object_id 
AND ps.index_id = i.index_id
ORDER BY ps.object_id, ps.partition_number, ps.row_group_id OPTION (RECOMPILE);
------

-- sys.dm_db_column_store_row_group_physical_stats (Transact-SQL)
-- https://bit.ly/2q276XQ


-- Get lock waits for current database (Query 78) (Lock Waits)
SELECT o.name AS [table_name], i.name AS [index_name], ios.index_id, ios.partition_number,
		SUM(ios.row_lock_wait_count) AS [total_row_lock_waits], 
		SUM(ios.row_lock_wait_in_ms) AS [total_row_lock_wait_in_ms],
		SUM(ios.page_lock_wait_count) AS [total_page_lock_waits],
		SUM(ios.page_lock_wait_in_ms) AS [total_page_lock_wait_in_ms],
		SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) AS [total_lock_wait_in_ms]
FROM sys.dm_db_index_operational_stats(DB_ID(), NULL, NULL, NULL) AS ios
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON ios.[object_id] = o.[object_id]
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ios.[object_id] = i.[object_id] 
AND ios.index_id = i.index_id
WHERE o.[object_id] > 100
GROUP BY o.name, i.name, ios.index_id, ios.partition_number
HAVING SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) > 0
ORDER BY total_lock_wait_in_ms DESC OPTION (RECOMPILE);
------

-- This query is helpful for troubleshooting blocking and deadlocking issues



-- Look at UDF execution statistics (Query 79) (UDF Statistics)
SELECT OBJECT_NAME(object_id) AS [Function Name], execution_count,
	   total_worker_time, total_logical_reads, total_physical_reads, total_elapsed_time, 
	   total_elapsed_time/execution_count AS [avg_elapsed_time],
	   FORMAT(cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
FROM sys.dm_exec_function_stats WITH (NOLOCK) 
WHERE database_id = DB_ID()
ORDER BY total_worker_time DESC OPTION (RECOMPILE); 
------

-- New for SQL Server 2016
-- Helps you investigate scalar UDF performance issues
-- Does not return information for table valued functions

-- sys.dm_exec_function_stats (Transact-SQL)
-- https://bit.ly/2q1Q6BM


-- Get Query Store Options for this database (Query 80) (QueryStore Options)
SELECT actual_state_desc, desired_state_desc, [interval_length_minutes],
       current_storage_size_mb, [max_storage_size_mb], 
	   query_capture_mode_desc, size_based_cleanup_mode_desc
FROM sys.database_query_store_options WITH (NOLOCK) OPTION (RECOMPILE);
------

-- New for SQL Server 2016
-- Requires that Query Store is enabled for this database

-- Tuning Workload Performance with Query Store
-- https://bit.ly/1kHSl7w


-- Get highest aggregate duration queries over last hour (Query 81) (High Aggregate Duration Queries)
WITH AggregatedDurationLastHour
AS
(SELECT q.query_id, SUM(count_executions * avg_duration) AS total_duration,
   COUNT (distinct p.plan_id) AS number_of_plans
   FROM sys.query_store_query_text AS qt WITH (NOLOCK)
   INNER JOIN sys.query_store_query AS q WITH (NOLOCK)
   ON qt.query_text_id = q.query_text_id
   INNER JOIN sys.query_store_plan AS p WITH (NOLOCK)
   ON q.query_id = p.query_id
   INNER JOIN sys.query_store_runtime_stats AS rs WITH (NOLOCK)
   ON rs.plan_id = p.plan_id
   INNER JOIN sys.query_store_runtime_stats_interval AS rsi WITH (NOLOCK)
   ON rsi.runtime_stats_interval_id = rs.runtime_stats_interval_id
   WHERE rsi.start_time >= DATEADD(hour, -1, GETUTCDATE()) 
   AND rs.execution_type_desc = N'Regular'
   GROUP BY q.query_id),
OrderedDuration AS
(SELECT query_id, total_duration, number_of_plans, 
 ROW_NUMBER () OVER (ORDER BY total_duration DESC, query_id) AS RN
 FROM AggregatedDurationLastHour)
SELECT OBJECT_NAME(q.object_id) AS [Containing Object], qt.query_sql_text, 
od.total_duration AS [Total Duration (microsecs)], 
od.number_of_plans AS [Plan Count],
p.is_forced_plan, p.is_parallel_plan, p.is_trivial_plan,
q.query_parameterization_type_desc, p.[compatibility_level],
p.last_compile_start_time, q.last_execution_time,
CONVERT(xml, p.query_plan) AS query_plan_xml 
FROM OrderedDuration AS od 
INNER JOIN sys.query_store_query AS q WITH (NOLOCK)
ON q.query_id  = od.query_id
INNER JOIN sys.query_store_query_text AS qt WITH (NOLOCK)
ON q.query_text_id = qt.query_text_id
INNER JOIN sys.query_store_plan AS p WITH (NOLOCK)
ON q.query_id = p.query_id
WHERE od.RN <= 50 
ORDER BY total_duration DESC OPTION (RECOMPILE);
------

-- New for SQL Server 2016
-- Requires that QueryStore is enabled for this database


-- Get input buffer information for the current database (Query 82) (Input Buffer)
SELECT es.session_id, DB_NAME(es.database_id) AS [Database Name],
es.login_time, es.cpu_time, es.logical_reads,
es.[status], ib.event_info AS [Input Buffer]
FROM sys.dm_exec_sessions AS es WITH (NOLOCK)
CROSS APPLY sys.dm_exec_input_buffer(es.session_id, NULL) AS ib
WHERE es.database_id = DB_ID()
AND es.session_id > 50
AND es.session_id <> @@SPID OPTION (RECOMPILE);

-- Gives you input buffer information from all non-system sessions for the current database
-- Replaces DBCC INPUTBUFFER

-- New DMF for retrieving input buffer in SQL Server
-- https://bit.ly/2uHKMbz



-- Look at recent Full backups for the current database (Query 83) (Recent Full Backups)
SELECT TOP (30) bs.machine_name, bs.server_name, bs.database_name AS [Database Name], bs.recovery_model,
CONVERT (BIGINT, bs.backup_size / 1048576 ) AS [Uncompressed Backup Size (MB)],
CONVERT (BIGINT, bs.compressed_backup_size / 1048576 ) AS [Compressed Backup Size (MB)],
CONVERT (NUMERIC (20,2), (CONVERT (FLOAT, bs.backup_size) /
CONVERT (FLOAT, bs.compressed_backup_size))) AS [Compression Ratio], bs.has_backup_checksums, bs.is_copy_only, bs.encryptor_type,
DATEDIFF (SECOND, bs.backup_start_date, bs.backup_finish_date) AS [Backup Elapsed Time (sec)],
bs.backup_finish_date AS [Backup Finish Date], bmf.physical_device_name AS [Backup Location], bmf.physical_block_size
FROM msdb.dbo.backupset AS bs WITH (NOLOCK)
INNER JOIN msdb.dbo.backupmediafamily AS bmf WITH (NOLOCK)
ON bs.media_set_id = bmf.media_set_id  
WHERE bs.database_name = DB_NAME(DB_ID())
AND bs.[type] = 'D' -- Change to L if you want Log backups
ORDER BY bs.backup_finish_date DESC OPTION (RECOMPILE);
------

-- Are your backup sizes and times changing over time?
-- Are you using backup compression?
-- Are you using backup checksums?
-- Are you doing copy_only backups?
-- Are you doing encrypted backups?
-- Have you done any backup tuning with striped backups, or changing the parameters of the backup command?

-- In SQL Server 2016, native SQL Server backup compression actually works much better with databases that are using TDE than in previous versions
-- https://bit.ly/28Rpb2x


-- These four Pluralsight Courses go into more detail about how to run these queries and interpret the results

-- SQL Server 2017: Diagnosing Configuration Issues with DMVs
-- https://bit.ly/2MSUDUL

-- SQL Server 2014 DMV Diagnostic Queries � Part 1 
-- https://bit.ly/2plxCer

-- SQL Server 2014 DMV Diagnostic Queries � Part 2
-- https://bit.ly/2IuJpzI

-- SQL Server 2014 DMV Diagnostic Queries � Part 3
-- https://bit.ly/2FIlCPb



-- Sign up for Microsoft Visual Studio Dev Essentials and get a free three month pass to Pluralsight

-- Microsoft Visual Studio Dev Essentials
-- http://bit.ly/1q6xbDL


-- Sign up for Microsoft Azure Essentials and get lots of free Azure usage credits, MCP exam voucher, three month Pluralsight subscription

-- Microsoft Azure Essentials
-- https://bit.ly/2JMWe8x


-- August 2017 blog series about upgrading and migrating to SQL Server 2016/2017
-- https://bit.ly/2ftKVrX



tools\dbatools\bin\diagnosticquery\SQLServerDiagnosticQueries_2017_201811.sql

-- SQL Server 2017 Diagnostic Information Queries
-- Glenn Berry 
-- Last Modified: January 7, 2019
-- https://www.sqlskills.com/blogs/glenn/
-- http://sqlserverperformance.wordpress.com/
-- Twitter: GlennAlanBerry

-- Please listen to my Pluralsight courses
-- https://www.pluralsight.com/author/glenn-berry

-- If you want to find all of our SQLskills SQL101 blog posts, check out https://bit.ly/2qLwfXW


-- Please make sure you are using the correct version of these diagnostic queries for your version of SQL Server


-- If you like PowerShell, there is a very useful community solution for running these queries in an automated fashion
-- https://dbatools.io/

-- Invoke-DbaDiagnosticQuery
-- https://dbatools.io/functions/invoke-dbadiagnosticquery/


--******************************************************************************
--*   Copyright (C) 2019 Glenn Berry, SQLskills.com
--*   All rights reserved. 
--*
--*   For more scripts and sample code, check out 
--*      https://www.sqlskills.com/blogs/glenn
--*
--*   You may alter this code for your own *non-commercial* purposes. You may
--*   republish altered code as long as you include this copyright and give due credit. 
--*
--*
--*   THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF 
--*   ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED 
--*   TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
--*   PARTICULAR PURPOSE. 
--*
--******************************************************************************

-- Check the major product version to see if it is SQL Server 2017 CTP 1 or greater
IF NOT EXISTS (SELECT * WHERE CONVERT(varchar(128), SERVERPROPERTY('ProductVersion')) LIKE '14%')
	BEGIN
		DECLARE @ProductVersion varchar(128) = CONVERT(varchar(128), SERVERPROPERTY('ProductVersion'));
		RAISERROR ('Script does not match the ProductVersion [%s] of this instance. Many of these queries may not work on this version.' , 18 , 16 , @ProductVersion);
	END
	ELSE
		PRINT N'You have the correct major version of SQL Server for this diagnostic information script';
	

-- Instance level queries *******************************

-- SQL and OS Version information for current instance  (Query 1) (Version Info)
SELECT @@SERVERNAME AS [Server Name], @@VERSION AS [SQL Server and OS Version Info];
------

-- SQL Server 2017 Builds																		
-- Build			Description							Release Date	URL to KB Article								
-- 14.0.1.246		CTP 1.0								11/30/2016
-- 14.0.100.187		CTP 1.1								12/16/2016
-- 14.0.200.24		CTP 1.2								1/19/2017
-- 14.0.304.138		CTP 1.3								2/17/2017
-- 14.0.405.198		CTP 1.4								3/20/2017
-- 14.0.500.272		CTP 2.0								4/19/2017
-- 14.0.600.250		CTP 2.1								5/17/2017
-- 14.0.800.90		RC1									7/17/2017
-- 14.0.900.75		RC2									8/2/2017
-- 14.0.1000.169	RTM									10/2/2017
-- 14.0.3006.16		CU1									10/24/2017		https://support.microsoft.com/en-us/help/4038634
-- 14.0.3008.27		CU2									11/28/2017		https://support.microsoft.com/en-us/help/4052574
-- 14.0.3015.40		CU3									1/4/2018		https://support.microsoft.com/en-us/help/4052987
-- 14.0.3022.28		CU4									2/20/2018	    https://support.microsoft.com/en-us/help/4056498
-- 14.0.3023.8		CU5									3/20/2018		https://support.microsoft.com/en-us/help/4092643
-- 14.0.3025.34		CU6									4/17/2018	    https://support.microsoft.com/en-us/help/4101464
-- 14.0.3026.27		CU7									5/23/2018		https://support.microsoft.com/en-us/help/4229789
-- 14.0.3029.16		CU8									6/19/2018		https://support.microsoft.com/en-us/help/4338363
-- 14.0.3030.27		CU9									7/19/2018		https://support.microsoft.com/en-us/help/4341265
-- 14.0.3035.2		CU9 + Security Update				8/13/2018		https://www.microsoft.com/en-us/download/details.aspx?id=57263
-- 14.0.3037.1		CU10								8/27/2018		https://support.microsoft.com/en-us/help/4342123/cumulative-update-10-for-sql-server-2017
-- 14.0.3038.14		CU11								9/20/2018		https://support.microsoft.com/en-us/help/4462262	
-- 14.0.3045.24		CU12								10/23/2018		https://support.microsoft.com/en-us/help/4464082/cumulative-update-12-for-sql-server-2017
-- 14.0.3048.4		CU13								12/18/2018		https://support.microsoft.com/en-us/help/4466404/cumulative-update-13-for-sql-server-2017		
		
															

-- How to determine the version, edition and update level of SQL Server and its components 
-- https://bit.ly/2oAjKgW	

-- SQL Server 2017 build versions
-- https://bit.ly/2FLY88I

-- Performance and Stability Fixes in SQL Server 2017 CU Builds
-- https://bit.ly/2GV3CNM

-- What's New in SQL Server 2017 (Database Engine)
-- https://bit.ly/2HjSeyQ

-- What's New in SQL Server 2017
-- https://bit.ly/2saQ4Yh

-- Announcing the Modern Servicing Model for SQL Server
-- https://bit.ly/2xHnh0l

-- SQL Server Service Packs are discontinued starting from SQL Server 2017 
-- https://bit.ly/2GTkbgt 

-- Update Center for Microsoft SQL Server
-- https://bit.ly/2pZptuQ

-- Download SQL Server Management Studio (SSMS)
-- https://bit.ly/1OcupT9

-- Download and install Azure Data Studio  
-- https://bit.ly/2vgke1A



-- Get socket, physical core and logical core count from the SQL Server Error log. (Query 2) (Core Counts)
-- This query might take a few seconds depending on the size of your error log
EXEC sys.xp_readerrorlog 0, 1, N'detected', N'socket';
------

-- This can help you determine the exact core counts used by SQL Server and whether HT is enabled or not
-- It can also help you confirm your SQL Server licensing model
-- Be on the lookout for this message "using 40 logical processors based on SQL Server licensing" 
-- (when you have more than 40 logical cores) which means grandfathered Server/CAL licensing
-- This query will return no results if your error log has been recycled since the instance was last started



-- Get selected server properties (Query 3) (Server Properties)
SELECT SERVERPROPERTY('MachineName') AS [MachineName], 
SERVERPROPERTY('ServerName') AS [ServerName],  
SERVERPROPERTY('InstanceName') AS [Instance], 
SERVERPROPERTY('IsClustered') AS [IsClustered], 
SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS [ComputerNamePhysicalNetBIOS], 
SERVERPROPERTY('Edition') AS [Edition], 
SERVERPROPERTY('ProductLevel') AS [ProductLevel],				-- What servicing branch (RTM/SP/CU)
SERVERPROPERTY('ProductUpdateLevel') AS [ProductUpdateLevel],	-- Within a servicing branch, what CU# is applied
SERVERPROPERTY('ProductVersion') AS [ProductVersion],
SERVERPROPERTY('ProductMajorVersion') AS [ProductMajorVersion], 
SERVERPROPERTY('ProductMinorVersion') AS [ProductMinorVersion], 
SERVERPROPERTY('ProductBuild') AS [ProductBuild], 
SERVERPROPERTY('ProductBuildType') AS [ProductBuildType],			  -- Is this a GDR or OD hotfix (NULL if on a CU build)
SERVERPROPERTY('ProductUpdateReference') AS [ProductUpdateReference], -- KB article number that is applicable for this build
SERVERPROPERTY('ProcessID') AS [ProcessID],
SERVERPROPERTY('Collation') AS [Collation], 
SERVERPROPERTY('IsFullTextInstalled') AS [IsFullTextInstalled], 
SERVERPROPERTY('IsIntegratedSecurityOnly') AS [IsIntegratedSecurityOnly],
SERVERPROPERTY('FilestreamConfiguredLevel') AS [FilestreamConfiguredLevel],
SERVERPROPERTY('IsHadrEnabled') AS [IsHadrEnabled], 
SERVERPROPERTY('HadrManagerStatus') AS [HadrManagerStatus],
SERVERPROPERTY('InstanceDefaultDataPath') AS [InstanceDefaultDataPath],
SERVERPROPERTY('InstanceDefaultLogPath') AS [InstanceDefaultLogPath],
SERVERPROPERTY('BuildClrVersion') AS [Build CLR Version],
SERVERPROPERTY('IsXTPSupported') AS [IsXTPSupported],
SERVERPROPERTY('IsPolybaseInstalled') AS [IsPolybaseInstalled],				-- New for SQL Server 2016
SERVERPROPERTY('IsAdvancedAnalyticsInstalled') AS [IsRServicesInstalled];	-- New for SQL Server 2016
------

-- This gives you a lot of useful information about your instance of SQL Server,
-- such as the ProcessID for SQL Server and your collation
-- Note: Some columns will be NULL on older SQL Server builds

-- SERVERPROPERTY (Transact-SQL)
-- https://bit.ly/2eeaXeI



-- Get instance-level configuration values for instance  (Query 4) (Configuration Values)
SELECT name, value, value_in_use, minimum, maximum, [description], is_dynamic, is_advanced
FROM sys.configurations WITH (NOLOCK)
ORDER BY name OPTION (RECOMPILE);
------

-- Focus on these settings:
-- automatic soft-NUMA disabled (should be 0 in most cases)
-- backup checksum default (should be 1)
-- backup compression default (should be 1 in most cases)
-- clr enabled (only enable if it is needed)
-- cost threshold for parallelism (depends on your workload)
-- lightweight pooling (should be zero)
-- max degree of parallelism (depends on your workload and hardware)
-- max server memory (MB) (set to an appropriate value, not the default)
-- optimize for ad hoc workloads (should be 1)
-- priority boost (should be zero)
-- remote admin connections (should be 1)

-- New configuration options for SQL Server 2017
-- clr strict security is new in SQL Server 2017, and is enabled by default

-- sys.configurations (Transact-SQL)
-- https://bit.ly/2HsyDZI


-- Returns a list of all global trace flags that are enabled (Query 5) (Global Trace Flags)
DBCC TRACESTATUS (-1);
------

-- If no global trace flags are enabled, no results will be returned.
-- It is very useful to know what global trace flags are currently enabled as part of the diagnostic process.

-- Common trace flags that should be enabled in most cases
-- TF 3226 - Supresses logging of successful database backup messages to the SQL Server Error Log
--           https://bit.ly/2p6MTjS  

-- TF 6534 - Enables use of native code to improve performance with spatial data
--           https://bit.ly/2HrQUpU         

-- The behavior of TF 1117, 1118 are enabled for tempdb in SQL Server 2016 by default
-- SQL 2016 � It Just Runs Faster: -T1117 and -T1118 changes for TEMPDB and user databases
-- https://bit.ly/2lbNWxK           

-- The behavior of TF 2371 is enabled by default in SQL Server 2016 and newer (in compat level 130 and higher)

-- DBCC TRACEON - Trace Flags (Transact-SQL)
-- https://bit.ly/2FuSvPg





-- Returns status of instant file initialization (Query 6) (IFI Status)
EXEC sys.xp_readerrorlog 0, 1, N'Database Instant File Initialization';
------

-- Lets you determine whether Instant File Initialization (IFI) is enabled for the instance
-- This should be enabled in the vast majority of cases
-- SQL Server 2016 and newer lets you enable this during the SQL server installation process

-- Database Instant File Initialization
-- https://bit.ly/2nTX74y

-- Misconceptions around instant file initialization
-- https://bit.ly/2oBSKgZ



-- SQL Server Process Address space info  (Query 7) (Process Memory)
-- (shows whether locked pages is enabled, among other things)
SELECT physical_memory_in_use_kb/1024 AS [SQL Server Memory Usage (MB)],
	   locked_page_allocations_kb/1024 AS [SQL Server Locked Pages Allocation (MB)],
       large_page_allocations_kb/1024 AS [SQL Server Large Pages Allocation (MB)], 
	   page_fault_count, memory_utilization_percentage, available_commit_limit_kb, 
	   process_physical_memory_low, process_virtual_memory_low
FROM sys.dm_os_process_memory WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You want to see 0 for process_physical_memory_low
-- You want to see 0 for process_virtual_memory_low
-- This indicates that you are not under internal memory pressure
-- If locked_page_allocations_kb > 0, then LPIM is enabled

-- How to enable the "locked pages" feature in SQL Server 2012
-- https://bit.ly/2F5UjOA

-- Memory Management Architecture Guide
-- https://bit.ly/2JKkadC 



-- SQL Server Services information (Query 8) (SQL Server Services Info)
SELECT servicename, process_id, startup_type_desc, status_desc, 
last_startup_time, service_account, is_clustered, cluster_nodename, [filename], 
instant_file_initialization_enabled
FROM sys.dm_server_services WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Tells you the account being used for the SQL Server Service and the SQL Agent Service
-- Shows the process_id, when they were last started, and their current status
-- Also shows whether you are running on a failover cluster instance, and what node you are running on
-- Also shows whether IFI is enabled

-- sys.dm_server_services (Transact-SQL)
-- https://bit.ly/2oKa1Un


-- Last backup information by database  (Query 9) (Last Backup By Database)
SELECT ISNULL(d.[name], bs.[database_name]) AS [Database], d.recovery_model_desc AS [Recovery Model], 
       d.log_reuse_wait_desc AS [Log Reuse Wait Desc],
    MAX(CASE WHEN [type] = 'D' THEN bs.backup_finish_date ELSE NULL END) AS [Last Full Backup],
    MAX(CASE WHEN [type] = 'I' THEN bs.backup_finish_date ELSE NULL END) AS [Last Differential Backup],
    MAX(CASE WHEN [type] = 'L' THEN bs.backup_finish_date ELSE NULL END) AS [Last Log Backup]
FROM sys.databases AS d WITH (NOLOCK)
LEFT OUTER JOIN msdb.dbo.backupset AS bs WITH (NOLOCK)
ON bs.[database_name] = d.[name] 
AND bs.backup_finish_date > GETDATE()- 30
WHERE d.name <> N'tempdb'
GROUP BY ISNULL(d.[name], bs.[database_name]), d.recovery_model_desc, d.log_reuse_wait_desc, d.[name] 
ORDER BY d.recovery_model_desc, d.[name] OPTION (RECOMPILE);
------

-- This helps you spot runaway transaction logs and other issues with your backup schedule


-- Get SQL Server Agent jobs and Category information (Query 10) (SQL Server Agent Jobs)
SELECT sj.name AS [Job Name], sj.[description] AS [Job Description], SUSER_SNAME(sj.owner_sid) AS [Job Owner],
sj.date_created AS [Date Created], sj.[enabled] AS [Job Enabled], 
sj.notify_email_operator_id, sj.notify_level_email, sc.name AS [CategoryName],
s.[enabled] AS [Sched Enabled], js.next_run_date, js.next_run_time
FROM msdb.dbo.sysjobs AS sj WITH (NOLOCK)
INNER JOIN msdb.dbo.syscategories AS sc WITH (NOLOCK)
ON sj.category_id = sc.category_id
LEFT OUTER JOIN msdb.dbo.sysjobschedules AS js WITH (NOLOCK)
ON sj.job_id = js.job_id
LEFT OUTER JOIN msdb.dbo.sysschedules AS s WITH (NOLOCK)
ON js.schedule_id = s.schedule_id
ORDER BY sj.name OPTION (RECOMPILE);
------

-- Gives you some basic information about your SQL Server Agent jobs, who owns them and how they are configured
-- Look for Agent jobs that are not owned by sa
-- Look for jobs that have a notify_email_operator_id set to 0 (meaning no operator)
-- Look for jobs that have a notify_level_email set to 0 (meaning no e-mail is ever sent)
--
-- MSDN sysjobs documentation
-- https://bit.ly/2paDEOP 

-- SQL Server Maintenance Solution
-- https://bit.ly/1pgchQu  


-- Get SQL Server Agent Alert Information (Query 11) (SQL Server Agent Alerts)
SELECT name, event_source, message_id, severity, [enabled], has_notification, 
       delay_between_responses, occurrence_count, last_occurrence_date, last_occurrence_time
FROM msdb.dbo.sysalerts WITH (NOLOCK)
ORDER BY name OPTION (RECOMPILE);
------

-- Gives you some basic information about your SQL Server Agent Alerts 
-- (which are different from SQL Server Agent jobs)
-- Read more about Agent Alerts here: https://bit.ly/2Giz0Xf 



-- Host information (Query 12) (Host Info)
SELECT host_platform, host_distribution, host_release, 
       host_service_pack_level, host_sku, os_language_version 
FROM sys.dm_os_host_info WITH (NOLOCK) OPTION (RECOMPILE); 
------

-- host_release codes (only valid for Windows)
-- 10.0 is either Windows 10 or Windows Server 2016
-- 6.3 is either Windows 8.1 or Windows Server 2012 R2 
-- 6.2 is either Windows 8 or Windows Server 2012


-- host_sku codes (only valid for Windows)
-- 4 is Enterprise Edition
-- 7 is Standard Server Edition
-- 8 is Datacenter Server Edition
-- 10 is Enterprise Server Edition
-- 48 is Professional Edition
-- 161 is Pro for Workstations

-- 1033 for os_language_version is US-English

-- SQL Server 2017 requires Windows Server 2012 or newer

-- Hardware and Software Requirements for Installing SQL Server
-- https://bit.ly/2y3ka5L

-- Using SQL Server in Windows 8 and later versions of Windows operating system
-- https://bit.ly/2F7Ax0P 


-- SQL Server NUMA Node information  (Query 13) (SQL Server NUMA Info)
SELECT node_id, node_state_desc, memory_node_id, processor_group, cpu_count, online_scheduler_count, 
       idle_scheduler_count, active_worker_count, avg_load_balance, resource_monitor_state
FROM sys.dm_os_nodes WITH (NOLOCK) 
WHERE node_state_desc <> N'ONLINE DAC' OPTION (RECOMPILE);
------

-- Gives you some useful information about the composition and relative load on your NUMA nodes
-- You want to see an equal number of schedulers on each NUMA node
-- Watch out if SQL Server 2017 Standard Edition has been installed 
-- on a physical or virtual machine with more than four sockets or more than 24 physical cores

-- sys.dm_os_nodes (Transact-SQL)
-- https://bit.ly/2pn5Mw8

-- Balancing Your Available SQL Server Core Licenses Evenly Across NUMA Nodes
-- https://bit.ly/2vfC4Rq



-- Good basic information about OS memory amounts and state  (Query 14) (System Memory)
SELECT total_physical_memory_kb/1024 AS [Physical Memory (MB)], 
       available_physical_memory_kb/1024 AS [Available Memory (MB)], 
       total_page_file_kb/1024 AS [Total Page File (MB)], 
	   available_page_file_kb/1024 AS [Available Page File (MB)], 
	   system_cache_kb/1024 AS [System Cache (MB)],
       system_memory_state_desc AS [System Memory State]
FROM sys.dm_os_sys_memory WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You want to see "Available physical memory is high" for System Memory State
-- This indicates that you are not under external memory pressure

-- Possible System Memory State values:
-- Available physical memory is high
-- Physical memory usage is steady
-- Available physical memory is low
-- Available physical memory is running low
-- Physical memory state is transitioning

-- sys.dm_os_sys_memory (Transact-SQL)
-- https://bit.ly/2pcV0xq



-- You can skip the next two queries if you know you don't have a clustered instance


-- Get information about your cluster nodes and their status  (Query 15) (Cluster Node Properties)
-- (if your database server is in a failover cluster)
SELECT NodeName, status_description, is_current_owner
FROM sys.dm_os_cluster_nodes WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Knowing which node owns the cluster resources is critical
-- Especially when you are installing Windows or SQL Server updates
-- You will see no results if your instance is not clustered

-- Recommended hotfixes and updates for Windows Server 2012 R2-based failover clusters
-- https://bit.ly/1z5BfCw


-- Get information about any AlwaysOn AG cluster this instance is a part of (Query 16) (AlwaysOn AG Cluster)
SELECT cluster_name, quorum_type_desc, quorum_state_desc
FROM sys.dm_hadr_cluster WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You will see no results if your instance is not using AlwaysOn AGs


-- Good overview of AG health and status (Query 17) (AlwaysOn AG Status)
SELECT ag.name AS [AG Name], ar.replica_server_name, ar.availability_mode_desc, adc.[database_name], 
       drs.is_local, drs.is_primary_replica, drs.synchronization_state_desc, drs.is_commit_participant, 
	   drs.synchronization_health_desc, drs.recovery_lsn, drs.truncation_lsn, drs.last_sent_lsn, 
	   drs.last_sent_time, drs.last_received_lsn, drs.last_received_time, drs.last_hardened_lsn, 
	   drs.last_hardened_time, drs.last_redone_lsn, drs.last_redone_time, drs.log_send_queue_size, 
	   drs.log_send_rate, drs.redo_queue_size, drs.redo_rate, drs.filestream_send_rate, 
	   drs.end_of_log_lsn, drs.last_commit_lsn, drs.last_commit_time, drs.database_state_desc 
FROM sys.dm_hadr_database_replica_states AS drs WITH (NOLOCK)
INNER JOIN sys.availability_databases_cluster AS adc WITH (NOLOCK)
ON drs.group_id = adc.group_id 
AND drs.group_database_id = adc.group_database_id
INNER JOIN sys.availability_groups AS ag WITH (NOLOCK)
ON ag.group_id = drs.group_id
INNER JOIN sys.availability_replicas AS ar WITH (NOLOCK)
ON drs.group_id = ar.group_id 
AND drs.replica_id = ar.replica_id
ORDER BY ag.name, ar.replica_server_name, adc.[database_name] OPTION (RECOMPILE);

-- You will see no results if your instance is not using AlwaysOn AGs

-- SQL Server 2016 � It Just Runs Faster: Always On Availability Groups Turbocharged
-- https://bit.ly/2dn1H6r


-- Hardware information from SQL Server 2017  (Query 18) (Hardware Info)
SELECT cpu_count AS [Logical CPU Count], scheduler_count, 
       (socket_count * cores_per_socket) AS [Physical Core Count], 
       socket_count AS [Socket Count], cores_per_socket, numa_node_count,
       physical_memory_kb/1024 AS [Physical Memory (MB)], 
       max_workers_count AS [Max Workers Count], 
	   affinity_type_desc AS [Affinity Type], 
       sqlserver_start_time AS [SQL Server Start Time],
	   DATEDIFF(hour, sqlserver_start_time, GETDATE()) AS [SQL Server Up Time (hrs)],
	   virtual_machine_type_desc AS [Virtual Machine Type], 
       softnuma_configuration_desc AS [Soft NUMA Configuration], 
	   sql_memory_model_desc, process_physical_affinity -- New in SQL Server 2017
FROM sys.dm_os_sys_info WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Gives you some good basic hardware information about your database server
-- Note: virtual_machine_type_desc of HYPERVISOR does not automatically mean you are running SQL Server inside of a VM
-- It merely indicates that you have a hypervisor running on your host

-- sys.dm_os_sys_info (Transact-SQL)
-- https://bit.ly/2pczOYs

-- Soft NUMA configuration was a new column for SQL Server 2016
-- OFF = Soft-NUMA feature is OFF
-- ON = SQL Server automatically determines the NUMA node sizes for Soft-NUMA
-- MANUAL = Manually configured soft-NUMA

-- Configure SQL Server to Use Soft-NUMA (SQL Server)
-- https://bit.ly/2HTpKJt

-- sql_memory_model_desc values (Added in SQL Server 2016 SP1)
-- CONVENTIONAL
-- LOCK_PAGES
-- LARGE_PAGES
   

-- Get System Manufacturer and model number from SQL Server Error log (Query 19) (System Manufacturer)
EXEC sys.xp_readerrorlog 0, 1, N'Manufacturer';
------ 

-- This can help you determine the capabilities and capacities of your database server
-- Can also be used to confirm if you are running in a VM
-- This query might take a few seconds if you have not recycled your error log recently
-- This query will return no results if your error log has been recycled since the instance was started


-- Get pvscsi info from Windows Registry  (Query 20) (PVSCSI Driver Parameters)
EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SYSTEM\CurrentControlSet\services\pvscsi\Parameters\Device', N'DriverParameter';
------

-- This is valid for VMware VMs
-- Recommended value for intensive I/O patterns from VMware is: RequestRingPages=32,MaxQueueDepth=254
-- https://kb.vmware.com/s/article/2053145
-- Does not work on Linux



-- Get BIOS date from Windows Registry (Query 21) (BIOS Date)
EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'HARDWARE\DESCRIPTION\System\BIOS', N'BiosReleaseDate';
------

-- Helps you understand whether the main system BIOS is up to date, and the possible age of the hardware
-- Not as useful for virtualization
-- Does not work on Linux


-- Get processor description from Windows Registry  (Query 22) (Processor Description)
EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'HARDWARE\DESCRIPTION\System\CentralProcessor\0', N'ProcessorNameString';
------

-- Gives you the model number and rated clock speed of your processor(s)
-- Your processors may be running at less than the rated clock speed due
-- to the Windows Power Plan or hardware power management
-- Does not work on Linux

-- You can use CPU-Z to get your actual CPU core speed and a lot of other useful information
-- https://bit.ly/QhR6xF

-- You can learn more about processor selection for SQL Server by following this link
-- https://bit.ly/2F3aVlP



-- See if buffer pool extension (BPE) is enabled (Query 23) (BPE Configuration)
SELECT [path], state_description, current_size_in_kb, 
CAST(current_size_in_kb/1048576.0 AS DECIMAL(10,2)) AS [Size (GB)]
FROM sys.dm_os_buffer_pool_extension_configuration WITH (NOLOCK) OPTION (RECOMPILE);
------

-- BPE is available in both Standard Edition and Enterprise Edition
-- It is a more interesting feature for Standard Edition

-- Buffer Pool Extension to SSDs in SQL Server 2014
-- https://bit.ly/1bm08m8

-- Buffer Pool Extension
-- https://bit.ly/2oBuieO



-- Look at buffer descriptors to see BPE usage by database (Query 24) (BPE Usage) 
SELECT DB_NAME(database_id) AS [Database Name], COUNT(page_id) AS [Page Count],
CAST(COUNT(*)/128.0 AS DECIMAL(10, 2)) AS [Buffer size(MB)], 
AVG(read_microsec) AS [Avg Read Time (microseconds)]
FROM sys.dm_os_buffer_descriptors WITH (NOLOCK)
WHERE database_id <> 32767
AND is_in_bpool_extension = 1
GROUP BY DB_NAME(database_id) 
ORDER BY [Buffer size(MB)] DESC OPTION (RECOMPILE);
------

-- You will see no results if BPE is not enabled or if there is no BPE usage


-- Get information on location, time and size of any memory dumps from SQL Server  (Query 25) (Memory Dump Info)
SELECT [filename], creation_time, size_in_bytes/1048576.0 AS [Size (MB)]
FROM sys.dm_server_memory_dumps WITH (NOLOCK) 
ORDER BY creation_time DESC OPTION (RECOMPILE);
------

-- This will not return any rows if you have 
-- not had any memory dumps (which is a good thing)

-- sys.dm_server_memory_dumps (Transact-SQL)
-- https://bit.ly/2elwWll



-- Look at Suspect Pages table (Query 26) (Suspect Pages)
SELECT DB_NAME(database_id) AS [Database Name], [file_id], page_id, 
       event_type, error_count, last_update_date 
FROM msdb.dbo.suspect_pages WITH (NOLOCK)
ORDER BY database_id OPTION (RECOMPILE);
------

-- event_type value descriptions
-- 1 = 823 error caused by an operating system CRC error
--     or 824 error other than a bad checksum or a torn page (for example, a bad page ID)
-- 2 = Bad checksum
-- 3 = Torn page
-- 4 = Restored (The page was restored after it was marked bad)
-- 5 = Repaired (DBCC repaired the page)
-- 7 = Deallocated by DBCC

-- Ideally, this query returns no results. The table is limited to 1000 rows.
-- If you do get results here, you should do further investigation to determine the root cause

-- Manage the suspect_pages Table
-- https://bit.ly/2Fvr1c9


-- Get number of data files in tempdb database (Query 27) (TempDB Data Files)
EXEC sys.xp_readerrorlog 0, 1, N'The tempdb database has';
------

-- Get the number of data files in the tempdb database
-- 4-8 data files that are all the same size is a good starting point
-- This query will return no results if your error log has been recycled since the instance was last started


-- File names and paths for all user and system databases on instance  (Query 28) (Database Filenames and Paths)
SELECT DB_NAME([database_id]) AS [Database Name], 
       [file_id], [name], physical_name, [type_desc], state_desc,
	   is_percent_growth, growth,
	   CONVERT(bigint, growth/128.0) AS [Growth in MB], 
       CONVERT(bigint, size/128.0) AS [Total Size in MB]
FROM sys.master_files WITH (NOLOCK)
ORDER BY DB_NAME([database_id]), [file_id] OPTION (RECOMPILE);
------

-- Things to look at:
-- Are data files and log files on different drives?
-- Is everything on the C: drive?
-- Is tempdb on dedicated drives?
-- Is there only one tempdb data file?
-- Are all of the tempdb data files the same size?
-- Are there multiple data files for user databases?
-- Is percent growth enabled for any files (which is bad)?


-- Drive information for all fixed drives visible to the operating system (Query 29) (Fixed Drives)
SELECT fixed_drive_path, drive_type_desc, 
CONVERT(DECIMAL(18,2), free_space_in_bytes/1073741824.0) AS [Available Space (GB)]
FROM sys.dm_os_enumerate_fixed_drives WITH (NOLOCK) OPTION (RECOMPILE);
------

-- This shows all of your fixed drives, not just LUNs with SQL Server database files



-- Volume info for all LUNS that have database files on the current instance (Query 30) (Volume Info)
SELECT DISTINCT vs.volume_mount_point, vs.file_system_type, vs.logical_volume_name, 
CONVERT(DECIMAL(18,2), vs.total_bytes/1073741824.0) AS [Total Size (GB)],
CONVERT(DECIMAL(18,2), vs.available_bytes/1073741824.0) AS [Available Size (GB)],  
CONVERT(DECIMAL(18,2), vs.available_bytes * 1. / vs.total_bytes * 100.) AS [Space Free %],
vs.supports_compression, vs.is_compressed, 
vs.supports_sparse_files, vs.supports_alternate_streams
FROM sys.master_files AS f WITH (NOLOCK)
CROSS APPLY sys.dm_os_volume_stats(f.database_id, f.[file_id]) AS vs 
ORDER BY vs.volume_mount_point OPTION (RECOMPILE);
------

-- Shows you the total and free space on the LUNs where you have database files
-- Being low on free space can negatively affect performance

-- sys.dm_os_volume_stats (Transact-SQL)
-- https://bit.ly/2oBPNNr



-- Drive level latency information (Query 31) (Drive Level Latency)
-- Based on code from Jimmy May
SELECT tab.[Drive], tab.volume_mount_point AS [Volume Mount Point], 
	CASE 
		WHEN num_of_reads = 0 THEN 0 
		ELSE (io_stall_read_ms/num_of_reads) 
	END AS [Read Latency],
	CASE 
		WHEN num_of_writes = 0 THEN 0 
		ELSE (io_stall_write_ms/num_of_writes) 
	END AS [Write Latency],
	CASE 
		WHEN (num_of_reads = 0 AND num_of_writes = 0) THEN 0 
		ELSE (io_stall/(num_of_reads + num_of_writes)) 
	END AS [Overall Latency],
	CASE 
		WHEN num_of_reads = 0 THEN 0 
		ELSE (num_of_bytes_read/num_of_reads) 
	END AS [Avg Bytes/Read],
	CASE 
		WHEN num_of_writes = 0 THEN 0 
		ELSE (num_of_bytes_written/num_of_writes) 
	END AS [Avg Bytes/Write],
	CASE 
		WHEN (num_of_reads = 0 AND num_of_writes = 0) THEN 0 
		ELSE ((num_of_bytes_read + num_of_bytes_written)/(num_of_reads + num_of_writes)) 
	END AS [Avg Bytes/Transfer]
FROM (SELECT LEFT(UPPER(mf.physical_name), 2) AS Drive, SUM(num_of_reads) AS num_of_reads,
	         SUM(io_stall_read_ms) AS io_stall_read_ms, SUM(num_of_writes) AS num_of_writes,
	         SUM(io_stall_write_ms) AS io_stall_write_ms, SUM(num_of_bytes_read) AS num_of_bytes_read,
	         SUM(num_of_bytes_written) AS num_of_bytes_written, SUM(io_stall) AS io_stall, vs.volume_mount_point 
      FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS vfs
      INNER JOIN sys.master_files AS mf WITH (NOLOCK)
      ON vfs.database_id = mf.database_id AND vfs.file_id = mf.file_id
	  CROSS APPLY sys.dm_os_volume_stats(mf.database_id, mf.[file_id]) AS vs 
      GROUP BY LEFT(UPPER(mf.physical_name), 2), vs.volume_mount_point) AS tab
ORDER BY [Overall Latency] OPTION (RECOMPILE);
------

-- Shows you the drive-level latency for reads and writes, in milliseconds
-- Latency above 30-40ms is usually a problem
-- These latency numbers include all file activity against all SQL Server 
-- database files on each drive since SQL Server was last started


-- Calculates average stalls per read, per write, and per total input/output for each database file  (Query 32) (IO Latency by File)
SELECT DB_NAME(fs.database_id) AS [Database Name], CAST(fs.io_stall_read_ms/(1.0 + fs.num_of_reads) AS NUMERIC(10,1)) AS [avg_read_latency_ms],
CAST(fs.io_stall_write_ms/(1.0 + fs.num_of_writes) AS NUMERIC(10,1)) AS [avg_write_latency_ms],
CAST((fs.io_stall_read_ms + fs.io_stall_write_ms)/(1.0 + fs.num_of_reads + fs.num_of_writes) AS NUMERIC(10,1)) AS [avg_io_latency_ms],
CONVERT(DECIMAL(18,2), mf.size/128.0) AS [File Size (MB)], mf.physical_name, mf.type_desc, fs.io_stall_read_ms, fs.num_of_reads, 
fs.io_stall_write_ms, fs.num_of_writes, fs.io_stall_read_ms + fs.io_stall_write_ms AS [io_stalls], fs.num_of_reads + fs.num_of_writes AS [total_io],
io_stall_queued_read_ms AS [Resource Governor Total Read IO Latency (ms)], io_stall_queued_write_ms AS [Resource Governor Total Write IO Latency (ms)] 
FROM sys.dm_io_virtual_file_stats(null,null) AS fs
INNER JOIN sys.master_files AS mf WITH (NOLOCK)
ON fs.database_id = mf.database_id
AND fs.[file_id] = mf.[file_id]
ORDER BY avg_io_latency_ms DESC OPTION (RECOMPILE);
------

-- Helps determine which database files on the entire instance have the most I/O bottlenecks
-- This can help you decide whether certain LUNs are overloaded and whether you might
-- want to move some files to a different location or perhaps improve your I/O performance
-- These latency numbers include all file activity against each SQL Server 
-- database file since SQL Server was last started


-- Look for I/O requests taking longer than 15 seconds in the six most recent SQL Server Error Logs (Query 33) (IO Warnings)
CREATE TABLE #IOWarningResults(LogDate datetime, ProcessInfo sysname, LogText nvarchar(1000));

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 0, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 1, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 2, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 3, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 4, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 5, 1, N'taking longer than 15 seconds';

SELECT LogDate, ProcessInfo, LogText
FROM #IOWarningResults
ORDER BY LogDate DESC;

DROP TABLE #IOWarningResults;
------  

-- Finding 15 second I/O warnings in the SQL Server Error Log is useful evidence of
-- poor I/O performance (which might have many different causes)
-- Look to see if you see any patterns in the results (same files, same drives, same time of day, etc.)

-- Diagnostics in SQL Server help detect stalled and stuck I/O operations
-- https://bit.ly/2qtaw73


-- Resource Governor Resource Pool information (Query 34) (RG Resource Pools)
SELECT pool_id, [Name], statistics_start_time,
       min_memory_percent, max_memory_percent,  
       max_memory_kb/1024 AS [max_memory_mb],  
       used_memory_kb/1024 AS [used_memory_mb],   
       target_memory_kb/1024 AS [target_memory_mb],
	   min_iops_per_volume, max_iops_per_volume
FROM sys.dm_resource_governor_resource_pools WITH (NOLOCK)
OPTION (RECOMPILE);
------

-- sys.dm_resource_governor_resource_pools (Transact-SQL)
-- https://bit.ly/2MVU0Vy



-- Recovery model, log reuse wait description, log file size, log usage size  (Query 35) (Database Properties)
-- and compatibility level for all databases on instance
SELECT db.[name] AS [Database Name], SUSER_SNAME(db.owner_sid) AS [Database Owner], db.recovery_model_desc AS [Recovery Model], 
db.state_desc, db.containment_desc, db.log_reuse_wait_desc AS [Log Reuse Wait Description], 
CONVERT(DECIMAL(18,2), ls.cntr_value/1024.0) AS [Log Size (MB)], CONVERT(DECIMAL(18,2), lu.cntr_value/1024.0) AS [Log Used (MB)],
CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log Used %], 
db.[compatibility_level] AS [DB Compatibility Level], 
db.is_mixed_page_allocation_on, db.page_verify_option_desc AS [Page Verify Option], 
db.is_auto_create_stats_on, db.is_auto_update_stats_on, db.is_auto_update_stats_async_on, db.is_parameterization_forced, 
db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on, db.is_auto_close_on, db.is_auto_shrink_on, 
db.target_recovery_time_in_seconds, db.is_cdc_enabled, db.is_published, db.is_distributor,
db.group_database_id, db.replica_id,db.is_memory_optimized_elevate_to_snapshot_on, 
db.delayed_durability_desc, db.is_auto_create_stats_incremental_on,
db.is_query_store_on, db.is_sync_with_backup, db.is_temporal_history_retention_enabled,
db.is_supplemental_logging_enabled, db.is_remote_data_archive_enabled,
db.is_encrypted, de.encryption_state, de.percent_complete, de.key_algorithm, de.key_length, db.resource_pool_id      
FROM sys.databases AS db WITH (NOLOCK)
INNER JOIN sys.dm_os_performance_counters AS lu WITH (NOLOCK)
ON db.name = lu.instance_name
INNER JOIN sys.dm_os_performance_counters AS ls WITH (NOLOCK)
ON db.name = ls.instance_name
LEFT OUTER JOIN sys.dm_database_encryption_keys AS de WITH (NOLOCK)
ON db.database_id = de.database_id
WHERE lu.counter_name LIKE N'Log File(s) Used Size (KB)%' 
AND ls.counter_name LIKE N'Log File(s) Size (KB)%'
AND ls.cntr_value > 0 
ORDER BY db.[name] OPTION (RECOMPILE);
------

-- Things to look at:
-- How many databases are on the instance?
-- What recovery models are they using?
-- What is the log reuse wait description?
-- How full are the transaction logs?
-- What compatibility level are the databases on? 
-- What is the Page Verify Option? (should be CHECKSUM)
-- Is Auto Update Statistics Asynchronously enabled?
-- Is Delayed Durability enabled
-- Make sure auto_shrink and auto_close are not enabled!

-- is_mixed_page_allocation_on is a new property for SQL Server 2016. Equivalent to TF 1118 for a user database
-- SQL Server 2016: Changes in default behavior for autogrow and allocations for tempdb and user databases
-- https://bit.ly/2evRZSR

-- A non-zero value for target_recovery_time_in_seconds means that indirect checkpoint is enabled 
-- If the setting has a zero value it indicates that automatic checkpoint is enabled

-- Changes in SQL Server 2016 Checkpoint Behavior
-- https://bit.ly/2pdggk3


-- Missing Indexes for all databases by Index Advantage  (Query 36) (Missing Indexes All Databases)
SELECT CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage],
FORMAT(migs.last_user_seek, 'yyyy-MM-dd HH:mm:ss') AS [last_user_seek], 
mid.[statement] AS [Database.Schema.Table],
COUNT(1) OVER(PARTITION BY mid.[statement]) AS [missing_indexes_for_table],
COUNT(1) OVER(PARTITION BY mid.[statement], equality_columns) AS [similar_missing_indexes_for_table],
mid.equality_columns, mid.inequality_columns, mid.included_columns,
migs.unique_compiles, migs.user_seeks, 
CONVERT(decimal(18,2), migs.avg_total_user_cost) AS [avg_total_user_cost], migs.avg_user_impact 
FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)
INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)
ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)
ON mig.index_handle = mid.index_handle
ORDER BY index_advantage DESC OPTION (RECOMPILE);
------

-- Getting missing index information for all of the databases on the instance is very useful
-- Look at last user seek time, number of user seeks to help determine source and importance
-- Also look at avg_user_impact and avg_total_user_cost to help determine importance
-- SQL Server is overly eager to add included columns, so beware
-- Do not just blindly add indexes that show up from this query!!!

-- SQL Server Index Design Guide
-- https://bit.ly/2qtZr4N



-- Get VLF Counts for all databases on the instance (Query 37) (VLF Counts)
SELECT [name] AS [Database Name], [VLF Count]
FROM sys.databases AS db WITH (NOLOCK)
CROSS APPLY (SELECT file_id, COUNT(*) AS [VLF Count]
		     FROM sys.dm_db_log_info(db.database_id)
			 GROUP BY file_id) AS li
ORDER BY [VLF Count] DESC OPTION (RECOMPILE);
------

-- High VLF counts can affect write performance to the log file
-- and they can make full database restores and crash recovery take much longer
-- Try to keep your VLF counts under 200 in most cases (depending on log file size)

-- Important change to VLF creation algorithm in SQL Server 2014
-- https://bit.ly/2Hsjbg4

-- SQL Server Transaction Log Architecture and Management Guide
-- https://bit.ly/2JjmQRZ



-- Get CPU utilization by database (Query 38) (CPU Usage by Database)
WITH DB_CPU_Stats
AS
(SELECT pa.DatabaseID, DB_Name(pa.DatabaseID) AS [Database Name], SUM(qs.total_worker_time/1000) AS [CPU_Time_Ms]
 FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
 CROSS APPLY (SELECT CONVERT(int, value) AS [DatabaseID] 
              FROM sys.dm_exec_plan_attributes(qs.plan_handle)
              WHERE attribute = N'dbid') AS pa
 GROUP BY DatabaseID)
SELECT ROW_NUMBER() OVER(ORDER BY [CPU_Time_Ms] DESC) AS [CPU Rank],
       [Database Name], [CPU_Time_Ms] AS [CPU Time (ms)], 
       CAST([CPU_Time_Ms] * 1.0 / SUM([CPU_Time_Ms]) OVER() * 100.0 AS DECIMAL(5, 2)) AS [CPU Percent]
FROM DB_CPU_Stats
WHERE DatabaseID <> 32767 -- ResourceDB
ORDER BY [CPU Rank] OPTION (RECOMPILE);
------

-- Helps determine which database is using the most CPU resources on the instance
-- Note: This only reflects CPU usage from the currently cached query plans


-- Get I/O utilization by database (Query 39) (IO Usage By Database)
WITH Aggregate_IO_Statistics
AS (SELECT DB_NAME(database_id) AS [Database Name],
    CAST(SUM(num_of_bytes_read + num_of_bytes_written) / 1048576 AS DECIMAL(12, 2)) AS [ioTotalMB],
    CAST(SUM(num_of_bytes_read ) / 1048576 AS DECIMAL(12, 2)) AS [ioReadMB],
    CAST(SUM(num_of_bytes_written) / 1048576 AS DECIMAL(12, 2)) AS [ioWriteMB]
    FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS [DM_IO_STATS]
    GROUP BY database_id)
SELECT ROW_NUMBER() OVER (ORDER BY ioTotalMB DESC) AS [I/O Rank],
        [Database Name], ioTotalMB AS [Total I/O (MB)],
        CAST(ioTotalMB / SUM(ioTotalMB) OVER () * 100.0 AS DECIMAL(5, 2)) AS [Total I/O %],
        ioReadMB AS [Read I/O (MB)], 
		CAST(ioReadMB / SUM(ioReadMB) OVER () * 100.0 AS DECIMAL(5, 2)) AS [Read I/O %],
        ioWriteMB AS [Write I/O (MB)], 
		CAST(ioWriteMB / SUM(ioWriteMB) OVER () * 100.0 AS DECIMAL(5, 2)) AS [Write I/O %]
FROM Aggregate_IO_Statistics
ORDER BY [I/O Rank] OPTION (RECOMPILE);
------

-- Helps determine which database is using the most I/O resources on the instance
-- These numbers are cumulative since the last service restart
-- They include all I/O activity, not just the nominal I/O workload


-- Get total buffer usage by database for current instance  (Query 40) (Total Buffer Usage by Database)
-- This make take some time to run on a busy instance
WITH AggregateBufferPoolUsage
AS
(SELECT DB_NAME(database_id) AS [Database Name],
CAST(COUNT(*) * 8/1024.0 AS DECIMAL (10,2))  AS [CachedSize]
FROM sys.dm_os_buffer_descriptors WITH (NOLOCK)
WHERE database_id <> 32767 -- ResourceDB
GROUP BY DB_NAME(database_id))
SELECT ROW_NUMBER() OVER(ORDER BY CachedSize DESC) AS [Buffer Pool Rank], [Database Name], CachedSize AS [Cached Size (MB)],
       CAST(CachedSize / SUM(CachedSize) OVER() * 100.0 AS DECIMAL(5,2)) AS [Buffer Pool Percent]
FROM AggregateBufferPoolUsage
ORDER BY [Buffer Pool Rank] OPTION (RECOMPILE);
------

-- Tells you how much memory (in the buffer pool) 
-- is being used by each database on the instance


-- Get tempdb version store space usage by database (Query 41) (Version Store Space Usage)
SELECT DB_NAME(database_id) AS [Database Name],
       reserved_page_count AS [Version Store Reserved Page Count], 
	   reserved_space_kb/1024 AS [Version Store Reserved Space (MB)] 
FROM sys.dm_tran_version_store_space_usage WITH (NOLOCK) 
ORDER BY reserved_space_kb/1024 DESC OPTION (RECOMPILE);
------  

-- sys.dm_tran_version_store_space_usage (Transact-SQL)
-- https://bit.ly/2vh3Bmk




-- Clear Wait Stats with this command
-- DBCC SQLPERF('sys.dm_os_wait_stats', CLEAR);

-- Isolate top waits for server instance since last restart or wait statistics clear  (Query 42) (Top Waits)
WITH [Waits] 
AS (SELECT wait_type, wait_time_ms/ 1000.0 AS [WaitS],
          (wait_time_ms - signal_wait_time_ms) / 1000.0 AS [ResourceS],
           signal_wait_time_ms / 1000.0 AS [SignalS],
           waiting_tasks_count AS [WaitCount],
           100.0 *  wait_time_ms / SUM (wait_time_ms) OVER() AS [Percentage],
           ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS [RowNum]
    FROM sys.dm_os_wait_stats WITH (NOLOCK)
    WHERE [wait_type] NOT IN (
        N'BROKER_EVENTHANDLER', N'BROKER_RECEIVE_WAITFOR', N'BROKER_TASK_STOP',
		N'BROKER_TO_FLUSH', N'BROKER_TRANSMITTER', N'CHECKPOINT_QUEUE',
        N'CHKPT', N'CLR_AUTO_EVENT', N'CLR_MANUAL_EVENT', N'CLR_SEMAPHORE', N'CXCONSUMER',
        N'DBMIRROR_DBM_EVENT', N'DBMIRROR_EVENTS_QUEUE', N'DBMIRROR_WORKER_QUEUE',
		N'DBMIRRORING_CMD', N'DIRTY_PAGE_POLL', N'DISPATCHER_QUEUE_SEMAPHORE',
        N'EXECSYNC', N'FSAGENT', N'FT_IFTS_SCHEDULER_IDLE_WAIT', N'FT_IFTSHC_MUTEX',
        N'HADR_CLUSAPI_CALL', N'HADR_FILESTREAM_IOMGR_IOCOMPLETION', N'HADR_LOGCAPTURE_WAIT', 
		N'HADR_NOTIFICATION_DEQUEUE', N'HADR_TIMER_TASK', N'HADR_WORK_QUEUE',
        N'KSOURCE_WAKEUP', N'LAZYWRITER_SLEEP', N'LOGMGR_QUEUE', 
		N'MEMORY_ALLOCATION_EXT', N'ONDEMAND_TASK_QUEUE',
		N'PARALLEL_REDO_DRAIN_WORKER', N'PARALLEL_REDO_LOG_CACHE', N'PARALLEL_REDO_TRAN_LIST',
		N'PARALLEL_REDO_WORKER_SYNC', N'PARALLEL_REDO_WORKER_WAIT_WORK',
		N'PREEMPTIVE_HADR_LEASE_MECHANISM', N'PREEMPTIVE_SP_SERVER_DIAGNOSTICS',
		N'PREEMPTIVE_OS_LIBRARYOPS', N'PREEMPTIVE_OS_COMOPS', N'PREEMPTIVE_OS_CRYPTOPS',
		N'PREEMPTIVE_OS_PIPEOPS', N'PREEMPTIVE_OS_AUTHENTICATIONOPS',
		N'PREEMPTIVE_OS_GENERICOPS', N'PREEMPTIVE_OS_VERIFYTRUST',
		N'PREEMPTIVE_OS_FILEOPS', N'PREEMPTIVE_OS_DEVICEOPS', N'PREEMPTIVE_OS_QUERYREGISTRY',
		N'PREEMPTIVE_OS_WRITEFILE',
		N'PREEMPTIVE_XE_CALLBACKEXECUTE', N'PREEMPTIVE_XE_DISPATCHER',
		N'PREEMPTIVE_XE_GETTARGETSTATE', N'PREEMPTIVE_XE_SESSIONCOMMIT',
		N'PREEMPTIVE_XE_TARGETINIT', N'PREEMPTIVE_XE_TARGETFINALIZE',
        N'PWAIT_ALL_COMPONENTS_INITIALIZED', N'PWAIT_DIRECTLOGCONSUMER_GETNEXT',
		N'QDS_PERSIST_TASK_MAIN_LOOP_SLEEP',
		N'QDS_ASYNC_QUEUE',
        N'QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP', N'REQUEST_FOR_DEADLOCK_SEARCH',
		N'RESOURCE_QUEUE', N'SERVER_IDLE_CHECK', N'SLEEP_BPOOL_FLUSH', N'SLEEP_DBSTARTUP',
		N'SLEEP_DCOMSTARTUP', N'SLEEP_MASTERDBREADY', N'SLEEP_MASTERMDREADY',
        N'SLEEP_MASTERUPGRADED', N'SLEEP_MSDBSTARTUP', N'SLEEP_SYSTEMTASK', N'SLEEP_TASK',
        N'SLEEP_TEMPDBSTARTUP', N'SNI_HTTP_ACCEPT', N'SP_SERVER_DIAGNOSTICS_SLEEP',
		N'SQLTRACE_BUFFER_FLUSH', N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', N'SQLTRACE_WAIT_ENTRIES',
		N'WAIT_FOR_RESULTS', N'WAITFOR', N'WAITFOR_TASKSHUTDOWN', N'WAIT_XTP_HOST_WAIT',
		N'WAIT_XTP_OFFLINE_CKPT_NEW_LOG', N'WAIT_XTP_CKPT_CLOSE', N'WAIT_XTP_RECOVERY',
		N'XE_BUFFERMGR_ALLPROCESSED_EVENT', N'XE_DISPATCHER_JOIN',
        N'XE_DISPATCHER_WAIT', N'XE_LIVE_TARGET_TVF', N'XE_TIMER_EVENT')
    AND waiting_tasks_count > 0)
SELECT
    MAX (W1.wait_type) AS [WaitType],
	CAST (MAX (W1.Percentage) AS DECIMAL (5,2)) AS [Wait Percentage],
	CAST ((MAX (W1.WaitS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgWait_Sec],
    CAST ((MAX (W1.ResourceS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgRes_Sec],
    CAST ((MAX (W1.SignalS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgSig_Sec], 
    CAST (MAX (W1.WaitS) AS DECIMAL (16,2)) AS [Wait_Sec],
    CAST (MAX (W1.ResourceS) AS DECIMAL (16,2)) AS [Resource_Sec],
    CAST (MAX (W1.SignalS) AS DECIMAL (16,2)) AS [Signal_Sec],
    MAX (W1.WaitCount) AS [Wait Count],
	CAST (N'https://www.sqlskills.com/help/waits/' + W1.wait_type AS XML) AS [Help/Info URL]
FROM Waits AS W1
INNER JOIN Waits AS W2
ON W2.RowNum <= W1.RowNum
GROUP BY W1.RowNum, W1.wait_type
HAVING SUM (W2.Percentage) - MAX (W1.Percentage) < 99 -- percentage threshold
OPTION (RECOMPILE);
------

-- Cumulative wait stats are not as useful on an idle instance that is not under load or performance pressure

-- SQL Server Wait Types Library (Paul Randal)
-- https://bit.ly/2ePzYO2

-- The SQL Server Wait Type Repository
-- https://bit.ly/1afzfjC

-- Wait statistics, or please tell me where it hurts
-- https://bit.ly/2wsQHQE

-- SQL Server 2005 Performance Tuning using the Waits and Queues
-- https://bit.ly/1o2NFoF

-- sys.dm_os_wait_stats (Transact-SQL)
-- https://bit.ly/2Hjq9Yl



-- Get a count of SQL connections by IP address (Query 43) (Connection Counts by IP Address)
SELECT ec.client_net_address, es.[program_name], es.[host_name], es.login_name, 
COUNT(ec.session_id) AS [connection count] 
FROM sys.dm_exec_sessions AS es WITH (NOLOCK) 
INNER JOIN sys.dm_exec_connections AS ec WITH (NOLOCK) 
ON es.session_id = ec.session_id 
GROUP BY ec.client_net_address, es.[program_name], es.[host_name], es.login_name  
ORDER BY ec.client_net_address, es.[program_name] OPTION (RECOMPILE);
------

-- This helps you figure where your database load is coming from
-- and verifies connectivity from other machines

-- Solving Connectivity errors to SQL Server
-- https://bit.ly/2EgzoD0



-- Get Average Task Counts (run multiple times)  (Query 44) (Avg Task Counts)
SELECT AVG(current_tasks_count) AS [Avg Task Count], 
AVG(work_queue_count) AS [Avg Work Queue Count],
AVG(runnable_tasks_count) AS [Avg Runnable Task Count],
AVG(pending_disk_io_count) AS [Avg Pending DiskIO Count]
FROM sys.dm_os_schedulers WITH (NOLOCK)
WHERE scheduler_id < 255 OPTION (RECOMPILE);
------

-- Sustained values above 10 suggest further investigation in that area
-- High Avg Task Counts are often caused by blocking/deadlocking or other resource contention

-- Sustained values above 1 suggest further investigation in that area
-- High Avg Runnable Task Counts are a good sign of CPU pressure
-- High Avg Pending DiskIO Counts are a sign of disk pressure

-- How to Do Some Very Basic SQL Server Monitoring
-- https://bit.ly/2q3Btgt



-- Detect blocking (run multiple times)  (Query 45) (Detect Blocking)
SELECT t1.resource_type AS [lock type], DB_NAME(resource_database_id) AS [database],
t1.resource_associated_entity_id AS [blk object],t1.request_mode AS [lock req],  -- lock requested
t1.request_session_id AS [waiter sid], t2.wait_duration_ms AS [wait time],       -- spid of waiter  
(SELECT [text] FROM sys.dm_exec_requests AS r WITH (NOLOCK)                      -- get sql for waiter
CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) 
WHERE r.session_id = t1.request_session_id) AS [waiter_batch],
(SELECT SUBSTRING(qt.[text],r.statement_start_offset/2, 
    (CASE WHEN r.statement_end_offset = -1 
    THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2 
    ELSE r.statement_end_offset END - r.statement_start_offset)/2) 
FROM sys.dm_exec_requests AS r WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) AS qt
WHERE r.session_id = t1.request_session_id) AS [waiter_stmt],					-- statement blocked
t2.blocking_session_id AS [blocker sid],										-- spid of blocker
(SELECT [text] FROM sys.sysprocesses AS p										-- get sql for blocker
CROSS APPLY sys.dm_exec_sql_text(p.[sql_handle]) 
WHERE p.spid = t2.blocking_session_id) AS [blocker_batch]
FROM sys.dm_tran_locks AS t1 WITH (NOLOCK)
INNER JOIN sys.dm_os_waiting_tasks AS t2 WITH (NOLOCK)
ON t1.lock_owner_address = t2.resource_address OPTION (RECOMPILE);
------

-- Helps troubleshoot blocking and deadlocking issues
-- The results will change from second to second on a busy system
-- You should run this query multiple times when you see signs of blocking



-- Get CPU Utilization History for last 256 minutes (in one minute intervals)  (Query 46) (CPU Utilization History)
DECLARE @ts_now bigint = (SELECT cpu_ticks/(cpu_ticks/ms_ticks) FROM sys.dm_os_sys_info WITH (NOLOCK)); 

SELECT TOP(256) SQLProcessUtilization AS [SQL Server Process CPU Utilization], 
               SystemIdle AS [System Idle Process], 
               100 - SystemIdle - SQLProcessUtilization AS [Other Process CPU Utilization], 
               DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) AS [Event Time] 
FROM (SELECT record.value('(./Record/@id)[1]', 'int') AS record_id, 
			record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') 
			AS [SystemIdle], 
			record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int') 
			AS [SQLProcessUtilization], [timestamp] 
	  FROM (SELECT [timestamp], CONVERT(xml, record) AS [record] 
			FROM sys.dm_os_ring_buffers WITH (NOLOCK)
			WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR' 
			AND record LIKE N'%<SystemHealth>%') AS x) AS y 
ORDER BY record_id DESC OPTION (RECOMPILE);
------

-- Look at the trend over the entire period 
-- Also look at high sustained 'Other Process' CPU Utilization values
-- Note: This query sometimes gives inaccurate results (negative values)
-- on high core count (> 64 cores) systems


-- Get top total worker time queries for entire instance (Query 47) (Top Worker Time Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], 
REPLACE(REPLACE(LEFT(t.[text], 255), CHAR(10),''), CHAR(13),'') AS [Short Query Text],  
qs.total_worker_time AS [Total Worker Time], qs.min_worker_time AS [Min Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.max_worker_time AS [Max Worker Time], 
qs.min_elapsed_time AS [Min Elapsed Time], 
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time], 
qs.max_elapsed_time AS [Max Elapsed Time],
qs.min_logical_reads AS [Min Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.max_logical_reads AS [Max Logical Reads], 
qs.execution_count AS [Execution Count],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
qs.creation_time AS [Creation Time]
--,t.[text] AS [Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
ORDER BY qs.total_worker_time DESC OPTION (RECOMPILE);
------


-- Helps you find the most expensive queries from a CPU perspective across the entire instance
-- Can also help track down parameter sniffing issues



-- Page Life Expectancy (PLE) value for each NUMA node in current instance  (Query 48) (PLE by NUMA Node)
SELECT @@SERVERNAME AS [Server Name], RTRIM([object_name]) AS [Object Name], instance_name, cntr_value AS [Page Life Expectancy]
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Buffer Node%' -- Handles named instances
AND counter_name = N'Page life expectancy' OPTION (RECOMPILE);
------

-- PLE is a good measurement of internal memory pressure
-- Higher PLE is better. Watch the trend over time, not the absolute value
-- This will only return one row for non-NUMA systems

-- Page Life Expectancy isn�t what you think�
-- https://bit.ly/2EgynLa


-- Memory Grants Pending value for current instance  (Query 49) (Memory Grants Pending)
SELECT @@SERVERNAME AS [Server Name], RTRIM([object_name]) AS [Object Name], cntr_value AS [Memory Grants Pending]                                                                                                       
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Memory Manager%' -- Handles named instances
AND counter_name = N'Memory Grants Pending' OPTION (RECOMPILE);
------

-- Run multiple times, and run periodically if you suspect you are under memory pressure
-- Memory Grants Pending above zero for a sustained period is a very strong indicator of internal memory pressure


-- Memory Clerk Usage for instance  (Query 50) (Memory Clerk Usage)
-- Look for high value for CACHESTORE_SQLCP (Ad-hoc query plans)
SELECT TOP(10) mc.[type] AS [Memory Clerk Type], 
       CAST((SUM(mc.pages_kb)/1024.0) AS DECIMAL (15,2)) AS [Memory Usage (MB)] 
FROM sys.dm_os_memory_clerks AS mc WITH (NOLOCK)
GROUP BY mc.[type]  
ORDER BY SUM(mc.pages_kb) DESC OPTION (RECOMPILE);
------

-- MEMORYCLERK_SQLBUFFERPOOL was new for SQL Server 2012. It should be your highest consumer of memory

-- CACHESTORE_SQLCP  SQL Plans         
-- These are cached SQL statements or batches that aren't in stored procedures, functions and triggers
-- Watch out for high values for CACHESTORE_SQLCP
-- Enabling 'optimize for ad hoc workloads' at the instance level can help reduce this
-- Running DBCC FREESYSTEMCACHE ('SQL Plans') periodically may be required to better control this

-- CACHESTORE_OBJCP  Object Plans      
-- These are compiled plans for stored procedures, functions and triggers

-- sys.dm_os_memory_clerks (Transact-SQL)
-- https://bit.ly/2H31xDR



-- Find single-use, ad-hoc and prepared queries that are bloating the plan cache  (Query 51) (Ad hoc Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], t.[text] AS [Query Text], 
cp.objtype AS [Object Type], cp.cacheobjtype AS [Cache Object Type],  
cp.size_in_bytes/1024 AS [Plan Size in KB]
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t
WHERE cp.cacheobjtype = N'Compiled Plan' 
AND cp.objtype IN (N'Adhoc', N'Prepared') 
AND cp.usecounts = 1
ORDER BY cp.size_in_bytes DESC, DB_NAME(t.[dbid]) OPTION (RECOMPILE);
------

-- Gives you the text, type and size of single-use ad-hoc and prepared queries that waste space in the plan cache
-- Enabling 'optimize for ad hoc workloads' for the instance can help (SQL Server 2008 and above only)
-- Running DBCC FREESYSTEMCACHE ('SQL Plans') periodically may be required to better control this
-- Enabling forced parameterization for the database can help, but test first!

-- Plan cache, adhoc workloads and clearing the single-use plan cache bloat
-- https://bit.ly/2EfYOkl


-- Get top total logical reads queries for entire instance (Query 52) (Top Logical Reads Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name],
REPLACE(REPLACE(LEFT(t.[text], 255), CHAR(10),''), CHAR(13),'') AS [Short Query Text], 
qs.total_logical_reads AS [Total Logical Reads],
qs.min_logical_reads AS [Min Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.max_logical_reads AS [Max Logical Reads],   
qs.min_worker_time AS [Min Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.max_worker_time AS [Max Worker Time], 
qs.min_elapsed_time AS [Min Elapsed Time], 
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time], 
qs.max_elapsed_time AS [Max Elapsed Time],
qs.execution_count AS [Execution Count], 
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
qs.creation_time AS [Creation Time]
--,t.[text] AS [Complete Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
ORDER BY qs.total_logical_reads DESC OPTION (RECOMPILE);
------


-- Helps you find the most expensive queries from a memory perspective across the entire instance
-- Can also help track down parameter sniffing issues


-- Get top average elapsed time queries for entire instance (Query 53) (Top Avg Elapsed Time Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], 
REPLACE(REPLACE(LEFT(t.[text], 255), CHAR(10),''), CHAR(13),'') AS [Short Query Text],  
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
qs.min_elapsed_time, qs.max_elapsed_time, qs.last_elapsed_time,
qs.execution_count AS [Execution Count],  
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads], 
qs.total_physical_reads/qs.execution_count AS [Avg Physical Reads], 
qs.total_worker_time/qs.execution_count AS [Avg Worker Time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
qs.creation_time AS [Creation Time]
--,t.[text] AS [Complete Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
ORDER BY qs.total_elapsed_time/qs.execution_count DESC OPTION (RECOMPILE);
------

-- Helps you find the highest average elapsed time queries across the entire instance
-- Can also help track down parameter sniffing issues


-- Look at UDF execution statistics (Query 54) (UDF Stats by DB)
SELECT TOP (25) DB_NAME(database_id) AS [Database Name], 
		   OBJECT_NAME(object_id, database_id) AS [Function Name],
		   total_worker_time, execution_count, total_elapsed_time,  
           total_elapsed_time/execution_count AS [avg_elapsed_time],  
           last_elapsed_time, last_execution_time, cached_time, [type_desc] 
FROM sys.dm_exec_function_stats WITH (NOLOCK) 
ORDER BY total_worker_time DESC OPTION (RECOMPILE);
------

-- sys.dm_exec_function_stats (Transact-SQL)
-- https://bit.ly/2q1Q6BM

-- Showplan Enhancements for UDFs
-- https://bit.ly/2LVqiQ1


-- Database specific queries *****************************************************************

-- **** Please switch to a user database that you are interested in! *****
--USE YourDatabaseName; -- make sure to change to an actual database on your instance, not the master system database
--GO

-- Individual File Sizes and space available for current database  (Query 55) (File Sizes and Space)
SELECT f.name AS [File Name] , f.physical_name AS [Physical Name], 
CAST((f.size/128.0) AS DECIMAL(15,2)) AS [Total Size in MB],
CAST(f.size/128.0 - CAST(FILEPROPERTY(f.name, 'SpaceUsed') AS int)/128.0 AS DECIMAL(15,2)) 
AS [Available Space In MB], f.[file_id], fg.name AS [Filegroup Name],
f.is_percent_growth, f.growth, fg.is_default, fg.is_read_only, 
fg.is_autogrow_all_files
FROM sys.database_files AS f WITH (NOLOCK) 
LEFT OUTER JOIN sys.filegroups AS fg WITH (NOLOCK)
ON f.data_space_id = fg.data_space_id
ORDER BY f.[file_id] OPTION (RECOMPILE);
------

-- Look at how large and how full the files are and where they are located
-- Make sure the transaction log is not full!!

-- is_autogrow_all_files was new for SQL Server 2016. Equivalent to TF 1117 for user databases

-- SQL Server 2016: Changes in default behavior for autogrow and allocations for tempdb and user databases
-- https://bit.ly/2evRZSR


-- Log space usage for current database  (Query 56) (Log Space Usage)
SELECT DB_NAME(lsu.database_id) AS [Database Name], db.recovery_model_desc AS [Recovery Model],
		CAST(lsu.total_log_size_in_bytes/1048576.0 AS DECIMAL(10, 2)) AS [Total Log Space (MB)],
		CAST(lsu.used_log_space_in_bytes/1048576.0 AS DECIMAL(10, 2)) AS [Used Log Space (MB)], 
		CAST(lsu.used_log_space_in_percent AS DECIMAL(10, 2)) AS [Used Log Space %],
		CAST(lsu.log_space_in_bytes_since_last_backup/1048576.0 AS DECIMAL(10, 2)) AS [Used Log Space Since Last Backup (MB)],
		db.log_reuse_wait_desc		 
FROM sys.dm_db_log_space_usage AS lsu WITH (NOLOCK)
INNER JOIN sys.databases AS db WITH (NOLOCK)
ON lsu.database_id = db.database_id
OPTION (RECOMPILE);
------

-- Look at log file size and usage, along with the log reuse wait description for the current database

-- sys.dm_db_log_space_usage (Transact-SQL)
-- https://bit.ly/2H4MQw9


-- Status of last VLF for current database  (Query 57) (Last VLF Status)
SELECT TOP(1) DB_NAME(li.database_id) AS [Database Name], li.[file_id],
              li.vlf_size_mb, li.vlf_sequence_number, li.vlf_active, li.vlf_status
FROM sys.dm_db_log_info(DB_ID()) AS li 
ORDER BY vlf_sequence_number DESC OPTION (RECOMPILE);
------

-- Determine whether you will be able to shrink the transaction log file

-- vlf_status Values
-- 0 is inactive 
-- 1 is initialized but unused 
-- 2 is active

-- sys.dm_db_log_info (Transact-SQL)
-- https://bit.ly/2EQUU1v



-- Get database scoped configuration values for current database (Query 58) (Database-scoped Configurations)
SELECT configuration_id, name, [value] AS [value_for_primary], value_for_secondary
FROM sys.database_scoped_configurations WITH (NOLOCK) OPTION (RECOMPILE);
------

-- This lets you see the value of these new properties for the current database

-- Clear plan cache for current database
-- ALTER DATABASE SCOPED CONFIGURATION CLEAR PROCEDURE_CACHE;

-- ALTER DATABASE SCOPED CONFIGURATION (Transact-SQL)
-- https://bit.ly/2sOH7nb


-- I/O Statistics by file for the current database  (Query 59) (IO Stats By File)
SELECT DB_NAME(DB_ID()) AS [Database Name], df.name AS [Logical Name], vfs.[file_id], df.type_desc,
df.physical_name AS [Physical Name], CAST(vfs.size_on_disk_bytes/1048576.0 AS DECIMAL(16, 2)) AS [Size on Disk (MB)],
vfs.num_of_reads, vfs.num_of_writes, vfs.io_stall_read_ms, vfs.io_stall_write_ms,
CAST(100. * vfs.io_stall_read_ms/(vfs.io_stall_read_ms + vfs.io_stall_write_ms) AS DECIMAL(16,1)) AS [IO Stall Reads Pct],
CAST(100. * vfs.io_stall_write_ms/(vfs.io_stall_write_ms + vfs.io_stall_read_ms) AS DECIMAL(16,1)) AS [IO Stall Writes Pct],
(vfs.num_of_reads + vfs.num_of_writes) AS [Writes + Reads], 
CAST(vfs.num_of_bytes_read/1048576.0 AS DECIMAL(16, 2)) AS [MB Read], 
CAST(vfs.num_of_bytes_written/1048576.0 AS DECIMAL(16, 2)) AS [MB Written],
CAST(100. * vfs.num_of_reads/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(16,1)) AS [# Reads Pct],
CAST(100. * vfs.num_of_writes/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(16,1)) AS [# Write Pct],
CAST(100. * vfs.num_of_bytes_read/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(16,1)) AS [Read Bytes Pct],
CAST(100. * vfs.num_of_bytes_written/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(16,1)) AS [Written Bytes Pct]
FROM sys.dm_io_virtual_file_stats(DB_ID(), NULL) AS vfs
INNER JOIN sys.database_files AS df WITH (NOLOCK)
ON vfs.[file_id]= df.[file_id] OPTION (RECOMPILE);
------

-- This helps you characterize your workload better from an I/O perspective for this database
-- It helps you determine whether you has an OLTP or DW/DSS type of workload



-- Get most frequently executed queries for this database (Query 60) (Query Execution Counts)
SELECT TOP(50) LEFT(t.[text], 50) AS [Short Query Text], qs.execution_count AS [Execution Count],
qs.total_logical_reads AS [Total Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.total_worker_time AS [Total Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.total_elapsed_time AS [Total Elapsed Time],
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
qs.creation_time AS [Creation Time]
--,t.[text] AS [Complete Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
WHERE t.dbid = DB_ID()
ORDER BY qs.execution_count DESC OPTION (RECOMPILE);
------


-- Queries 61 through 66 are the "Bad Man List" for stored procedures

-- Top Cached SPs By Execution Count (Query 61) (SP Execution Counts)
SELECT TOP(100) p.name AS [SP Name], qs.execution_count AS [Execution Count],
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time],    
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.execution_count DESC OPTION (RECOMPILE);
------

-- Tells you which cached stored procedures are called the most often
-- This helps you characterize and baseline your workload


-- Top Cached SPs By Avg Elapsed Time (Query 62) (SP Avg Elapsed Time)
SELECT TOP(25) p.name AS [SP Name], qs.min_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time], 
qs.max_elapsed_time, qs.last_elapsed_time, qs.total_elapsed_time, qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute], 
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], 
qs.total_worker_time AS [TotalWorkerTime],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY avg_elapsed_time DESC OPTION (RECOMPILE);
------

-- This helps you find high average elapsed time cached stored procedures that
-- may be easy to optimize with standard query tuning techniques



-- Top Cached SPs By Total Worker time. Worker time relates to CPU cost  (Query 63) (SP Worker Time)
SELECT TOP(25) p.name AS [SP Name], qs.total_worker_time AS [TotalWorkerTime], 
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.total_worker_time DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a CPU perspective
-- You should look at this if you see signs of CPU pressure


-- Top Cached SPs By Total Logical Reads. Logical reads relate to memory pressure  (Query 64) (SP Logical Reads)
SELECT TOP(25) p.name AS [SP Name], qs.total_logical_reads AS [TotalLogicalReads], 
qs.total_logical_reads/qs.execution_count AS [AvgLogicalReads],qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute], 
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.total_logical_reads DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a memory perspective
-- You should look at this if you see signs of memory pressure


-- Top Cached SPs By Total Physical Reads. Physical reads relate to disk read I/O pressure  (Query 65) (SP Physical Reads)
SELECT TOP(25) p.name AS [SP Name],qs.total_physical_reads AS [TotalPhysicalReads], 
qs.total_physical_reads/qs.execution_count AS [AvgPhysicalReads], qs.execution_count, 
qs.total_logical_reads,qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan 
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND qs.total_physical_reads > 0
ORDER BY qs.total_physical_reads DESC, qs.total_logical_reads DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a read I/O perspective
-- You should look at this if you see signs of I/O pressure or of memory pressure
       


-- Top Cached SPs By Total Logical Writes (Query 66) (SP Logical Writes)
-- Logical writes relate to both memory and disk I/O pressure 
SELECT TOP(25) p.name AS [SP Name], qs.total_logical_writes AS [TotalLogicalWrites], 
qs.total_logical_writes/qs.execution_count AS [AvgLogicalWrites], qs.execution_count,
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan 
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND qs.total_logical_writes > 0
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.total_logical_writes DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a write I/O perspective
-- You should look at this if you see signs of I/O pressure or of memory pressure


-- Lists the top statements by average input/output usage for the current database  (Query 67) (Top IO Statements)
SELECT TOP(50) OBJECT_NAME(qt.objectid, dbid) AS [SP Name],
(qs.total_logical_reads + qs.total_logical_writes) /qs.execution_count AS [Avg IO], qs.execution_count AS [Execution Count],
SUBSTRING(qt.[text],qs.statement_start_offset/2, 
	(CASE 
		WHEN qs.statement_end_offset = -1 
	 THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2 
		ELSE qs.statement_end_offset 
	 END - qs.statement_start_offset)/2) AS [Query Text]	
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
WHERE qt.[dbid] = DB_ID()
ORDER BY [Avg IO] DESC OPTION (RECOMPILE);
------

-- Helps you find the most expensive statements for I/O by SP



-- Possible Bad NC Indexes (writes > reads)  (Query 68) (Bad NC Indexes)
SELECT OBJECT_NAME(s.[object_id]) AS [Table Name], i.name AS [Index Name], i.index_id, 
i.is_disabled, i.is_hypothetical, i.has_filter, i.fill_factor,
s.user_updates AS [Total Writes], s.user_seeks + s.user_scans + s.user_lookups AS [Total Reads],
s.user_updates - (s.user_seeks + s.user_scans + s.user_lookups) AS [Difference]
FROM sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON s.[object_id] = i.[object_id]
AND i.index_id = s.index_id
WHERE OBJECTPROPERTY(s.[object_id],'IsUserTable') = 1
AND s.database_id = DB_ID()
AND s.user_updates > (s.user_seeks + s.user_scans + s.user_lookups)
AND i.index_id > 1 AND i.[type_desc] = N'NONCLUSTERED'
AND i.is_primary_key = 0 AND i.is_unique_constraint = 0 AND i.is_unique = 0
ORDER BY [Difference] DESC, [Total Writes] DESC, [Total Reads] ASC OPTION (RECOMPILE);
------

-- Look for indexes with high numbers of writes and zero or very low numbers of reads
-- Consider your complete workload, and how long your instance has been running
-- Investigate further before dropping an index!


-- Missing Indexes for current database by Index Advantage  (Query 69) (Missing Indexes)
SELECT DISTINCT CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage], 
migs.last_user_seek, mid.[statement] AS [Database.Schema.Table],
mid.equality_columns, mid.inequality_columns, mid.included_columns,
migs.unique_compiles, migs.user_seeks, migs.avg_total_user_cost, migs.avg_user_impact,
OBJECT_NAME(mid.[object_id]) AS [Table Name], p.rows AS [Table Rows]
FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)
INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)
ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)
ON mig.index_handle = mid.index_handle
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON p.[object_id] = mid.[object_id]
WHERE mid.database_id = DB_ID()
AND p.index_id < 2 
ORDER BY index_advantage DESC OPTION (RECOMPILE);
------

-- Look at index advantage, last user seek time, number of user seeks to help determine source and importance
-- SQL Server is overly eager to add included columns, so beware
-- Do not just blindly add indexes that show up from this query!!!


-- Find missing index warnings for cached plans in the current database  (Query 70) (Missing Index Warnings)
-- Note: This query could take some time on a busy instance
SELECT TOP(25) OBJECT_NAME(objectid) AS [ObjectName], 
               cp.objtype, cp.usecounts, cp.size_in_bytes, query_plan
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) AS qp
WHERE CAST(query_plan AS NVARCHAR(MAX)) LIKE N'%MissingIndex%'
AND dbid = DB_ID()
ORDER BY cp.usecounts DESC OPTION (RECOMPILE);
------

-- Helps you connect missing indexes to specific stored procedures or queries
-- This can help you decide whether to add them or not


-- Breaks down buffers used by current database by object (table, index) in the buffer cache  (Query 71) (Buffer Usage)
-- Note: This query could take some time on a busy instance
SELECT OBJECT_NAME(p.[object_id]) AS [Object Name], p.index_id, 
CAST(COUNT(*)/128.0 AS DECIMAL(10, 2)) AS [Buffer size(MB)],  
COUNT(*) AS [BufferCount], p.[Rows] AS [Row Count],
p.data_compression_desc AS [Compression Type]
FROM sys.allocation_units AS a WITH (NOLOCK)
INNER JOIN sys.dm_os_buffer_descriptors AS b WITH (NOLOCK)
ON a.allocation_unit_id = b.allocation_unit_id
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON a.container_id = p.hobt_id
WHERE b.database_id = CONVERT(int, DB_ID())
AND p.[object_id] > 100
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'plan_%'
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'sys%'
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'xml_index_nodes%'
GROUP BY p.[object_id], p.index_id, p.data_compression_desc, p.[Rows]
ORDER BY [BufferCount] DESC OPTION (RECOMPILE);
------

-- Tells you what tables and indexes are using the most memory in the buffer cache
-- It can help identify possible candidates for data compression


-- Get Table names, row counts, and compression status for clustered index or heap  (Query 72) (Table Sizes)
SELECT SCHEMA_NAME(o.Schema_ID) AS [Schema Name], OBJECT_NAME(p.object_id) AS [ObjectName], 
SUM(p.Rows) AS [RowCount], data_compression_desc AS [CompressionType]
FROM sys.partitions AS p WITH (NOLOCK)
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON p.object_id = o.object_id
WHERE index_id < 2 --ignore the partitions from the non-clustered index if any
AND OBJECT_NAME(p.object_id) NOT LIKE N'sys%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'spt_%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'queue_%' 
AND OBJECT_NAME(p.object_id) NOT LIKE N'filestream_tombstone%' 
AND OBJECT_NAME(p.object_id) NOT LIKE N'fulltext%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'ifts_comp_fragment%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'filetable_updates%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'xml_index_nodes%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'sqlagent_job%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'plan_persist%'
GROUP BY  SCHEMA_NAME(o.Schema_ID), p.object_id, data_compression_desc
ORDER BY SUM(p.Rows) DESC OPTION (RECOMPILE);
------

-- Gives you an idea of table sizes, and possible data compression opportunities



-- Get some key table properties (Query 73) (Table Properties)
SELECT OBJECT_NAME(t.[object_id]) AS [ObjectName], p.[rows] AS [Table Rows], p.index_id, 
       p.data_compression_desc AS [Index Data Compression],
       t.create_date, t.lock_on_bulk_load, t.is_replicated, t.has_replication_filter, 
       t.is_tracked_by_cdc, t.lock_escalation_desc, t.is_filetable, 
	   t.is_memory_optimized, t.durability_desc, 
	   t.temporal_type_desc, t.is_remote_data_archive_enabled, t.is_external -- new for SQL Server 2016
FROM sys.tables AS t WITH (NOLOCK)
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON t.[object_id] = p.[object_id]
WHERE OBJECT_NAME(t.[object_id]) NOT LIKE N'sys%'
ORDER BY OBJECT_NAME(t.[object_id]), p.index_id OPTION (RECOMPILE);
------

-- Gives you some good information about your tables
-- is_memory_optimized and durability_desc were new in SQL Server 2014
-- temporal_type_desc, is_remote_data_archive_enabled, is_external were new in SQL Server 2016

-- sys.tables (Transact-SQL)
-- https://bit.ly/2Gk7998



-- When were Statistics last updated on all indexes?  (Query 74) (Statistics Update)
SELECT SCHEMA_NAME(o.Schema_ID) + N'.' + o.[NAME] AS [Object Name], o.[type_desc] AS [Object Type],
      i.[name] AS [Index Name], STATS_DATE(i.[object_id], i.index_id) AS [Statistics Date], 
      s.auto_created, s.no_recompute, s.user_created, s.is_incremental, s.is_temporary,
	  st.row_count, st.used_page_count
FROM sys.objects AS o WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON o.[object_id] = i.[object_id]
INNER JOIN sys.stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id] 
AND i.index_id = s.stats_id
INNER JOIN sys.dm_db_partition_stats AS st WITH (NOLOCK)
ON o.[object_id] = st.[object_id]
AND i.[index_id] = st.[index_id]
WHERE o.[type] IN ('U', 'V')
AND st.row_count > 0
ORDER BY STATS_DATE(i.[object_id], i.index_id) DESC OPTION (RECOMPILE);
------  

-- Helps discover possible problems with out-of-date statistics
-- Also gives you an idea which indexes are the most active

-- sys.stats (Transact-SQL)
-- https://bit.ly/2GyAxrn

-- UPDATEs to Statistics (Erin Stellato)
-- https://bit.ly/2vhrYQy




-- Look at most frequently modified indexes and statistics (Query 75) (Volatile Indexes)
SELECT o.[name] AS [Object Name], o.[object_id], o.[type_desc], s.[name] AS [Statistics Name], 
       s.stats_id, s.no_recompute, s.auto_created, s.is_incremental, s.is_temporary,
	   sp.modification_counter, sp.[rows], sp.rows_sampled, sp.last_updated
FROM sys.objects AS o WITH (NOLOCK)
INNER JOIN sys.stats AS s WITH (NOLOCK)
ON s.object_id = o.object_id
CROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) AS sp
WHERE o.[type_desc] NOT IN (N'SYSTEM_TABLE', N'INTERNAL_TABLE')
AND sp.modification_counter > 0
ORDER BY sp.modification_counter DESC, o.name OPTION (RECOMPILE);
------

-- This helps you understand your workload and make better decisions about 
-- things like data compression and adding new indexes to a table



-- Get fragmentation info for all indexes above a certain size in the current database  (Query 76) (Index Fragmentation)
-- Note: This query could take some time on a very large database
SELECT DB_NAME(ps.database_id) AS [Database Name], SCHEMA_NAME(o.[schema_id]) AS [Schema Name],
OBJECT_NAME(ps.OBJECT_ID) AS [Object Name], i.[name] AS [Index Name], ps.index_id, 
ps.index_type_desc, ps.avg_fragmentation_in_percent, 
ps.fragment_count, ps.page_count, i.fill_factor, i.has_filter, 
i.filter_definition, i.[allow_page_locks]
FROM sys.dm_db_index_physical_stats(DB_ID(),NULL, NULL, NULL , N'LIMITED') AS ps
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ps.[object_id] = i.[object_id] 
AND ps.index_id = i.index_id
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON i.[object_id] = o.[object_id]
WHERE ps.database_id = DB_ID()
AND ps.page_count > 2500
ORDER BY ps.avg_fragmentation_in_percent DESC OPTION (RECOMPILE);
------

-- Helps determine whether you have framentation in your relational indexes
-- and how effective your index maintenance strategy is


--- Index Read/Write stats (all tables in current DB) ordered by Reads  (Query 77) (Overall Index Usage - Reads)
SELECT OBJECT_NAME(i.[object_id]) AS [ObjectName], i.[name] AS [IndexName], i.index_id, 
       s.user_seeks, s.user_scans, s.user_lookups,
	   s.user_seeks + s.user_scans + s.user_lookups AS [Total Reads], 
	   s.user_updates AS [Writes],  
	   i.[type_desc] AS [Index Type], i.fill_factor AS [Fill Factor], i.has_filter, i.filter_definition, 
	   s.last_user_scan, s.last_user_lookup, s.last_user_seek
FROM sys.indexes AS i WITH (NOLOCK)
LEFT OUTER JOIN sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id]
AND i.index_id = s.index_id
AND s.database_id = DB_ID()
WHERE OBJECTPROPERTY(i.[object_id],'IsUserTable') = 1
ORDER BY s.user_seeks + s.user_scans + s.user_lookups DESC OPTION (RECOMPILE); -- Order by reads
------

-- Show which indexes in the current database are most active for Reads


--- Index Read/Write stats (all tables in current DB) ordered by Writes  (Query 78) (Overall Index Usage - Writes)
SELECT OBJECT_NAME(i.[object_id]) AS [ObjectName], i.[name] AS [IndexName], i.index_id,
	   s.user_updates AS [Writes], s.user_seeks + s.user_scans + s.user_lookups AS [Total Reads], 
	   i.[type_desc] AS [Index Type], i.fill_factor AS [Fill Factor], i.has_filter, i.filter_definition,
	   s.last_system_update, s.last_user_update
FROM sys.indexes AS i WITH (NOLOCK)
LEFT OUTER JOIN sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id]
AND i.index_id = s.index_id
AND s.database_id = DB_ID()
WHERE OBJECTPROPERTY(i.[object_id],'IsUserTable') = 1
ORDER BY s.user_updates DESC OPTION (RECOMPILE);						 -- Order by writes
------

-- Show which indexes in the current database are most active for Writes


-- Get in-memory OLTP index usage (Query 79) (XTP Index Usage)
SELECT OBJECT_NAME(i.[object_id]) AS [Object Name], i.index_id, i.[name] AS [Index Name],
       i.[type_desc], xis.scans_started, xis.scans_retries, 
	   xis.rows_touched, xis.rows_returned
FROM sys.dm_db_xtp_index_stats AS xis WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON i.[object_id] = xis.[object_id] 
AND i.index_id = xis.index_id 
ORDER BY OBJECT_NAME(i.[object_id]) OPTION (RECOMPILE);
------

-- This gives you some index usage statistics for in-memory OLTP
-- Returns no data if you are not using in-memory OLTP

-- Guidelines for Using Indexes on Memory-Optimized Tables
-- https://bit.ly/2GCP8lF



-- Look at Columnstore index physical statistics (Query 80) (Columnstore Index Physical Stat)
SELECT OBJECT_NAME(ps.object_id) AS [TableName],  
	i.[name] AS [IndexName], ps.index_id, ps.partition_number,
	ps.delta_store_hobt_id, ps.state_desc, ps.total_rows, ps.size_in_bytes,
	ps.trim_reason_desc, ps.generation, ps.transition_to_compressed_state_desc,
	ps.has_vertipaq_optimization, ps.deleted_rows,
	100 * (ISNULL(ps.deleted_rows, 0))/ps.total_rows AS [Fragmentation]
FROM sys.dm_db_column_store_row_group_physical_stats AS ps WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ps.object_id = i.object_id 
AND ps.index_id = i.index_id
ORDER BY ps.object_id, ps.partition_number, ps.row_group_id OPTION (RECOMPILE);
------

-- sys.dm_db_column_store_row_group_physical_stats (Transact-SQL)
-- https://bit.ly/2q276XQ



-- Get lock waits for current database (Query 81) (Lock Waits)
SELECT o.name AS [table_name], i.name AS [index_name], ios.index_id, ios.partition_number,
		SUM(ios.row_lock_wait_count) AS [total_row_lock_waits], 
		SUM(ios.row_lock_wait_in_ms) AS [total_row_lock_wait_in_ms],
		SUM(ios.page_lock_wait_count) AS [total_page_lock_waits],
		SUM(ios.page_lock_wait_in_ms) AS [total_page_lock_wait_in_ms],
		SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) AS [total_lock_wait_in_ms]
FROM sys.dm_db_index_operational_stats(DB_ID(), NULL, NULL, NULL) AS ios
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON ios.[object_id] = o.[object_id]
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ios.[object_id] = i.[object_id] 
AND ios.index_id = i.index_id
WHERE o.[object_id] > 100
GROUP BY o.name, i.name, ios.index_id, ios.partition_number
HAVING SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) > 0
ORDER BY total_lock_wait_in_ms DESC OPTION (RECOMPILE);
------

-- This query is helpful for troubleshooting blocking and deadlocking issues



-- Look at UDF execution statistics (Query 82) (UDF Statistics)
SELECT OBJECT_NAME(object_id) AS [Function Name], execution_count,
	   total_worker_time, total_logical_reads, total_physical_reads, total_elapsed_time, 
	   total_elapsed_time/execution_count AS [avg_elapsed_time],
	   FORMAT(cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
FROM sys.dm_exec_function_stats WITH (NOLOCK) 
WHERE database_id = DB_ID()
ORDER BY total_worker_time DESC OPTION (RECOMPILE); 
------

-- New for SQL Server 2016
-- Helps you investigate scalar UDF performance issues
-- Does not return information for table valued functions

-- sys.dm_exec_function_stats (Transact-SQL)
-- https://bit.ly/2q1Q6BM


-- Get QueryStore Options for this database (Query 83) (QueryStore Options)
SELECT actual_state_desc, desired_state_desc, [interval_length_minutes],
       current_storage_size_mb, [max_storage_size_mb], 
	   query_capture_mode_desc, size_based_cleanup_mode_desc
FROM sys.database_query_store_options WITH (NOLOCK) OPTION (RECOMPILE);
------

-- New for SQL Server 2016
-- Requires that Query Store is enabled for this database

-- Make sure that the actual_state_desc is the same as desired_state_desc
-- Make sure that the current_storage_size_mb is less than the max_storage_size_mb

-- Tuning Workload Performance with Query Store
-- https://bit.ly/1kHSl7w


-- Get highest aggregate duration queries over last hour (Query 84) (High Aggregate Duration Queries)
WITH AggregatedDurationLastHour
AS
(SELECT q.query_id, SUM(rs.count_executions * rs.avg_duration) AS total_duration,
   COUNT (DISTINCT p.plan_id) AS number_of_plans
   FROM sys.query_store_query_text AS qt WITH (NOLOCK)
   INNER JOIN sys.query_store_query AS q WITH (NOLOCK)
   ON qt.query_text_id = q.query_text_id
   INNER JOIN sys.query_store_plan AS p WITH (NOLOCK)
   ON q.query_id = p.query_id
   INNER JOIN sys.query_store_runtime_stats AS rs WITH (NOLOCK)
   ON rs.plan_id = p.plan_id
   INNER JOIN sys.query_store_runtime_stats_interval AS rsi WITH (NOLOCK)
   ON rsi.runtime_stats_interval_id = rs.runtime_stats_interval_id
   WHERE rsi.start_time >= DATEADD(hour, -1, GETUTCDATE()) 
   AND rs.execution_type_desc = N'Regular'
   GROUP BY q.query_id), OrderedDuration 
AS
(SELECT query_id, total_duration, number_of_plans, 
 ROW_NUMBER () OVER (ORDER BY total_duration DESC, query_id) AS RN
 FROM AggregatedDurationLastHour)
SELECT OBJECT_NAME(q.object_id) AS [Containing Object], qt.query_sql_text, 
od.total_duration AS [Total Duration (microsecs)], 
od.number_of_plans AS [Plan Count],
p.is_forced_plan, p.is_parallel_plan, p.is_trivial_plan,
q.query_parameterization_type_desc, p.[compatibility_level],
p.last_compile_start_time, 
q.last_execution_time,
CONVERT(xml, p.query_plan) AS query_plan_xml 
FROM OrderedDuration AS od 
INNER JOIN sys.query_store_query AS q WITH (NOLOCK)
ON q.query_id  = od.query_id
INNER JOIN sys.query_store_query_text AS qt WITH (NOLOCK)
ON q.query_text_id = qt.query_text_id
INNER JOIN sys.query_store_plan AS p WITH (NOLOCK)
ON q.query_id = p.query_id
WHERE od.RN <= 50 
ORDER BY od.total_duration DESC OPTION (RECOMPILE);
------

-- New for SQL Server 2016
-- Requires that QueryStore is enabled for this database



-- Get highest aggregate CPU time queries over last hour (Query 85) (High Aggregate CPU Queries)
WITH AggregatedCPULastHour
AS
(SELECT q.query_id, SUM(rs.count_executions * rs.avg_cpu_time) AS total_cpu_time,
   COUNT (DISTINCT p.plan_id) AS number_of_plans
   FROM sys.query_store_query_text AS qt WITH (NOLOCK)
   INNER JOIN sys.query_store_query AS q WITH (NOLOCK)
   ON qt.query_text_id = q.query_text_id
   INNER JOIN sys.query_store_plan AS p WITH (NOLOCK)
   ON q.query_id = p.query_id
   INNER JOIN sys.query_store_runtime_stats AS rs WITH (NOLOCK)
   ON rs.plan_id = p.plan_id
   INNER JOIN sys.query_store_runtime_stats_interval AS rsi WITH (NOLOCK)
   ON rsi.runtime_stats_interval_id = rs.runtime_stats_interval_id
   WHERE rsi.start_time >= DATEADD(hour, -1, GETUTCDATE()) 
   AND rs.execution_type_desc = N'Regular'
   GROUP BY q.query_id), OrderedDuration 
AS
(SELECT query_id, total_cpu_time, number_of_plans, 
 ROW_NUMBER () OVER (ORDER BY total_cpu_time DESC, query_id) AS RN
 FROM AggregatedCPULastHour)
SELECT OBJECT_NAME(q.object_id) AS [Containing Object], qt.query_sql_text, 
od.total_cpu_time AS [Total CPU Time (microsecs)], 
od.number_of_plans AS [Plan Count],
p.is_forced_plan, p.is_parallel_plan, p.is_trivial_plan,
q.query_parameterization_type_desc, p.[compatibility_level],
p.last_compile_start_time, 
q.last_execution_time,
CONVERT(xml, p.query_plan) AS query_plan_xml 
FROM OrderedDuration AS od 
INNER JOIN sys.query_store_query AS q WITH (NOLOCK)
ON q.query_id  = od.query_id
INNER JOIN sys.query_store_query_text AS qt WITH (NOLOCK)
ON q.query_text_id = qt.query_text_id
INNER JOIN sys.query_store_plan AS p WITH (NOLOCK)
ON q.query_id = p.query_id
WHERE od.RN <= 50 
ORDER BY od.total_cpu_time DESC OPTION (RECOMPILE);
------

-- New for SQL Server 2016
-- Requires that QueryStore is enabled for this database


-- Get input buffer information for the current database (Query 86) (Input Buffer)
SELECT es.session_id, DB_NAME(es.database_id) AS [Database Name],
       es.login_time, es.cpu_time, es.logical_reads, es.memory_usage,
       es.[status], ib.event_info AS [Input Buffer]
FROM sys.dm_exec_sessions AS es WITH (NOLOCK)
CROSS APPLY sys.dm_exec_input_buffer(es.session_id, NULL) AS ib
WHERE es.database_id = DB_ID()
AND es.session_id > 50
AND es.session_id <> @@SPID OPTION (RECOMPILE);
------

-- Gives you input buffer information from all non-system sessions for the current database
-- Replaces DBCC INPUTBUFFER

-- New DMF for retrieving input buffer in SQL Server
-- https://bit.ly/2uHKMbz

-- sys.dm_exec_input_buffer (Transact-SQL)
-- https://bit.ly/2J5Hf9q



-- Get any resumable index rebuild operation information (Query 87) (Resumable Index Rebuild)
SELECT OBJECT_NAME(iro.object_id) AS [Object Name], iro.index_id, iro.name AS [Index Name],
       iro.sql_text, iro.last_max_dop_used, iro.partition_number, iro.state_desc, 
	   iro.start_time, iro.percent_complete
FROM  sys.index_resumable_operations AS iro WITH (NOLOCK)
OPTION (RECOMPILE);
------ 

-- index_resumable_operations (Transact-SQL)
-- https://bit.ly/2pYSWqq


-- Get database automatic tuning options (Query 88) (Automatic Tuning Options)
SELECT [name], desired_state_desc, actual_state_desc, reason_desc
FROM sys.database_automatic_tuning_options WITH (NOLOCK)
OPTION (RECOMPILE);
------ 

-- sys.database_automatic_tuning_options (Transact-SQL)
-- https://bit.ly/2FHhLkL



-- Look at recent Full backups for the current database (Query 89) (Recent Full Backups)
SELECT TOP (30) bs.machine_name, bs.server_name, bs.database_name AS [Database Name], bs.recovery_model,
CONVERT (BIGINT, bs.backup_size / 1048576 ) AS [Uncompressed Backup Size (MB)],
CONVERT (BIGINT, bs.compressed_backup_size / 1048576 ) AS [Compressed Backup Size (MB)],
CONVERT (NUMERIC (20,2), (CONVERT (FLOAT, bs.backup_size) /
CONVERT (FLOAT, bs.compressed_backup_size))) AS [Compression Ratio], bs.has_backup_checksums, bs.is_copy_only, bs.encryptor_type,
DATEDIFF (SECOND, bs.backup_start_date, bs.backup_finish_date) AS [Backup Elapsed Time (sec)],
bs.backup_finish_date AS [Backup Finish Date], bmf.physical_device_name AS [Backup Location], bmf.physical_block_size
FROM msdb.dbo.backupset AS bs WITH (NOLOCK)
INNER JOIN msdb.dbo.backupmediafamily AS bmf WITH (NOLOCK)
ON bs.media_set_id = bmf.media_set_id  
WHERE bs.database_name = DB_NAME(DB_ID())
AND bs.[type] = 'D' -- Change to L if you want Log backups
ORDER BY bs.backup_finish_date DESC OPTION (RECOMPILE);
------

-- Are your backup sizes and times changing over time?
-- Are you using backup compression?
-- Are you using backup checksums?
-- Are you doing copy_only backups?
-- Are you doing encrypted backups?
-- Have you done any backup tuning with striped backups, or changing the parameters of the backup command?

-- In SQL Server 2016, native SQL Server backup compression actually works 
-- much better with databases that are using TDE than in previous versions
-- https://bit.ly/28Rpb2x


-- These four Pluralsight Courses go into more detail about how to run these queries and interpret the results

-- SQL Server 2017: Diagnosing Configuration Issues with DMVs
-- https://bit.ly/2MSUDUL


-- SQL Server 2014 DMV Diagnostic Queries � Part 1 
-- https://bit.ly/2plxCer

-- SQL Server 2014 DMV Diagnostic Queries � Part 2
-- https://bit.ly/2IuJpzI

-- SQL Server 2014 DMV Diagnostic Queries � Part 3
-- https://bit.ly/2FIlCPb



-- Sign up for Microsoft Visual Studio Dev Essentials and get a free three month pass to Pluralsight

-- Microsoft Visual Studio Dev Essentials
-- http://bit.ly/1q6xbDL


-- Sign up for Microsoft Azure Essentials and get lots of free Azure usage credits, MCP exam voucher, three month Pluralsight subscription

-- Microsoft Azure Essentials
-- https://bit.ly/2JMWe8x


-- August 2017 blog series about upgrading and migrating to SQL Server 2016/2017
-- https://bit.ly/2ftKVrX
tools\dbatools\bin\diagnosticquery\SQLServerDiagnosticQueries_2019_201811.sql

-- SQL Server 2019 Diagnostic Information Queries
-- Glenn Berry 
-- Last Modified: January 7, 2019
-- https://www.sqlskills.com/blogs/glenn/
-- http://sqlserverperformance.wordpress.com/
-- Twitter: GlennAlanBerry

-- Please listen to my Pluralsight courses
-- https://www.pluralsight.com/author/glenn-berry

-- If you want to find all of our SQLskills SQL101 blog posts, check out https://bit.ly/2qLwfXW


-- Please make sure you are using the correct version of these diagnostic queries for your version of SQL Server


-- If you like PowerShell, there is a very useful community solution for running these queries in an automated fashion
-- https://dbatools.io/

-- Invoke-DbaDiagnosticQuery
-- https://dbatools.io/functions/invoke-dbadiagnosticquery/


--******************************************************************************
--*   Copyright (C) 2019 Glenn Berry, SQLskills.com
--*   All rights reserved. 
--*
--*   For more scripts and sample code, check out 
--*      https://www.sqlskills.com/blogs/glenn
--*
--*   You may alter this code for your own *non-commercial* purposes. You may
--*   republish altered code as long as you include this copyright and give due credit. 
--*
--*
--*   THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF 
--*   ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED 
--*   TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
--*   PARTICULAR PURPOSE. 
--*
--******************************************************************************

-- Check the major product version to see if it is SQL Server 2019 CTP 2 or greater
IF NOT EXISTS (SELECT * WHERE CONVERT(varchar(128), SERVERPROPERTY('ProductVersion')) LIKE '15%')
	BEGIN
		DECLARE @ProductVersion varchar(128) = CONVERT(varchar(128), SERVERPROPERTY('ProductVersion'));
		RAISERROR ('Script does not match the ProductVersion [%s] of this instance. Many of these queries may not work on this version.' , 18 , 16 , @ProductVersion);
	END
	ELSE
		PRINT N'You have the correct major version of SQL Server for this diagnostic information script';
	

-- Instance level queries *******************************

-- SQL and OS Version information for current instance  (Query 1) (Version Info)
SELECT @@SERVERNAME AS [Server Name], @@VERSION AS [SQL Server and OS Version Info];
------

-- SQL Server 2019 Builds																		
-- Build			Description							Release Date	URL to KB Article								
-- 15.0.1000.34		CTP 2.0								9/24/2018
-- 15.0.1100.94		CTP 2.1								11/7/2018
-- 15.0.1200.24		CTP 2.2								12/6/2018

		
															

-- How to determine the version, edition and update level of SQL Server and its components 
-- https://bit.ly/2oAjKgW	

-- What's New in SQL Server 2019 (Database Engine)
-- https://bit.ly/2Q29fhz

-- What's New in SQL Server 2019
-- https://bit.ly/2PY442b

-- Announcing the Modern Servicing Model for SQL Server
-- https://bit.ly/2xHnh0l

-- SQL Server Service Packs are discontinued starting from SQL Server 2017 
-- https://bit.ly/2GTkbgt 

-- Update Center for Microsoft SQL Server
-- https://bit.ly/2pZptuQ

-- Download SQL Server Management Studio (SSMS)
-- https://bit.ly/1OcupT9

-- Download and install Azure Data Studio 
-- https://bit.ly/2vgke1A



-- Get socket, physical core and logical core count from the SQL Server Error log. (Query 2) (Core Counts)
-- This query might take a few seconds depending on the size of your error log
EXEC sys.xp_readerrorlog 0, 1, N'detected', N'socket';
------

-- This can help you determine the exact core counts used by SQL Server and whether HT is enabled or not
-- It can also help you confirm your SQL Server licensing model
-- Be on the lookout for this message "using 40 logical processors based on SQL Server licensing" 
-- (when you have more than 40 logical cores) which means grandfathered Server/CAL licensing
-- This query will return no results if your error log has been recycled since the instance was last started



-- Get selected server properties (Query 3) (Server Properties)
SELECT SERVERPROPERTY('MachineName') AS [MachineName], 
SERVERPROPERTY('ServerName') AS [ServerName],  
SERVERPROPERTY('InstanceName') AS [Instance], 
SERVERPROPERTY('IsClustered') AS [IsClustered], 
SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS [ComputerNamePhysicalNetBIOS], 
SERVERPROPERTY('Edition') AS [Edition], 
SERVERPROPERTY('ProductLevel') AS [ProductLevel],				-- What servicing branch (RTM/SP/CU)
SERVERPROPERTY('ProductUpdateLevel') AS [ProductUpdateLevel],	-- Within a servicing branch, what CU# is applied
SERVERPROPERTY('ProductVersion') AS [ProductVersion],
SERVERPROPERTY('ProductMajorVersion') AS [ProductMajorVersion], 
SERVERPROPERTY('ProductMinorVersion') AS [ProductMinorVersion], 
SERVERPROPERTY('ProductBuild') AS [ProductBuild], 
SERVERPROPERTY('ProductBuildType') AS [ProductBuildType],			  -- Is this a GDR or OD hotfix (NULL if on a CU build)
SERVERPROPERTY('ProductUpdateReference') AS [ProductUpdateReference], -- KB article number that is applicable for this build
SERVERPROPERTY('ProcessID') AS [ProcessID],
SERVERPROPERTY('Collation') AS [Collation], 
SERVERPROPERTY('IsFullTextInstalled') AS [IsFullTextInstalled], 
SERVERPROPERTY('IsIntegratedSecurityOnly') AS [IsIntegratedSecurityOnly],
SERVERPROPERTY('FilestreamConfiguredLevel') AS [FilestreamConfiguredLevel],
SERVERPROPERTY('IsHadrEnabled') AS [IsHadrEnabled], 
SERVERPROPERTY('HadrManagerStatus') AS [HadrManagerStatus],
SERVERPROPERTY('InstanceDefaultDataPath') AS [InstanceDefaultDataPath],
SERVERPROPERTY('InstanceDefaultLogPath') AS [InstanceDefaultLogPath],
SERVERPROPERTY('BuildClrVersion') AS [Build CLR Version],
SERVERPROPERTY('IsXTPSupported') AS [IsXTPSupported],
SERVERPROPERTY('IsPolybaseInstalled') AS [IsPolybaseInstalled],				-- New for SQL Server 2016
SERVERPROPERTY('IsAdvancedAnalyticsInstalled') AS [IsRServicesInstalled];	-- New for SQL Server 2016
------

-- This gives you a lot of useful information about your instance of SQL Server,
-- such as the ProcessID for SQL Server and your collation
-- Note: Some columns will be NULL on older SQL Server builds

-- SERVERPROPERTY (Transact-SQL)
-- https://bit.ly/2eeaXeI



-- Get instance-level configuration values for instance  (Query 4) (Configuration Values)
SELECT name, value, value_in_use, minimum, maximum, [description], is_dynamic, is_advanced
FROM sys.configurations WITH (NOLOCK)
ORDER BY name OPTION (RECOMPILE);
------

-- Focus on these settings:
-- automatic soft-NUMA disabled (should be 0 in most cases)
-- backup checksum default (should be 1)
-- backup compression default (should be 1 in most cases)
-- clr enabled (only enable if it is needed)
-- cost threshold for parallelism (depends on your workload)
-- lightweight pooling (should be zero)
-- max degree of parallelism (depends on your workload and hardware)
-- max server memory (MB) (set to an appropriate value, not the default)
-- optimize for ad hoc workloads (should be 1)
-- priority boost (should be zero)
-- remote admin connections (should be 1)

-- sys.configurations (Transact-SQL)
-- https://bit.ly/2HsyDZI


-- Returns a list of all global trace flags that are enabled (Query 5) (Global Trace Flags)
DBCC TRACESTATUS (-1);
------

-- If no global trace flags are enabled, no results will be returned.
-- It is very useful to know what global trace flags are currently enabled as part of the diagnostic process.

-- Common trace flags that should be enabled in most cases
-- TF 3226 - Supresses logging of successful database backup messages to the SQL Server Error Log
--           https://bit.ly/2p6MTjS  

-- TF 6534 - Enables use of native code to improve performance with spatial data
--           https://bit.ly/2HrQUpU         

-- The behavior of TF 1117, 1118 are enabled for tempdb in SQL Server 2016 by default
-- SQL 2016 � It Just Runs Faster: -T1117 and -T1118 changes for TEMPDB and user databases
-- https://bit.ly/2lbNWxK           

-- The behavior of TF 2371 is enabled by default in SQL Server 2016 and newer (in compat level 130 and higher)

-- DBCC TRACEON - Trace Flags (Transact-SQL)
-- https://bit.ly/2FuSvPg





-- Returns status of instant file initialization (Query 6) (IFI Status)
EXEC sys.xp_readerrorlog 0, 1, N'Database Instant File Initialization';
------

-- Lets you determine whether Instant File Initialization (IFI) is enabled for the instance
-- This should be enabled in the vast majority of cases
-- SQL Server 2016 and newer lets you enable this during the SQL server installation process

-- Database Instant File Initialization
-- https://bit.ly/2nTX74y

-- Misconceptions around instant file initialization
-- https://bit.ly/2oBSKgZ



-- SQL Server Process Address space info  (Query 7) (Process Memory)
-- (shows whether locked pages is enabled, among other things)
SELECT physical_memory_in_use_kb/1024 AS [SQL Server Memory Usage (MB)],
	   locked_page_allocations_kb/1024 AS [SQL Server Locked Pages Allocation (MB)],
       large_page_allocations_kb/1024 AS [SQL Server Large Pages Allocation (MB)], 
	   page_fault_count, memory_utilization_percentage, available_commit_limit_kb, 
	   process_physical_memory_low, process_virtual_memory_low
FROM sys.dm_os_process_memory WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You want to see 0 for process_physical_memory_low
-- You want to see 0 for process_virtual_memory_low
-- This indicates that you are not under internal memory pressure
-- If locked_page_allocations_kb > 0, then LPIM is enabled

-- How to enable the "locked pages" feature in SQL Server 2012
-- https://bit.ly/2F5UjOA

-- Memory Management Architecture Guide
-- https://bit.ly/2JKkadC 



-- SQL Server Services information (Query 8) (SQL Server Services Info)
SELECT servicename, process_id, startup_type_desc, status_desc, 
last_startup_time, service_account, is_clustered, cluster_nodename, [filename], 
instant_file_initialization_enabled
FROM sys.dm_server_services WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Tells you the account being used for the SQL Server Service and the SQL Agent Service
-- Shows the process_id, when they were last started, and their current status
-- Also shows whether you are running on a failover cluster instance, and what node you are running on
-- Also shows whether IFI is enabled

-- sys.dm_server_services (Transact-SQL)
-- https://bit.ly/2oKa1Un


-- Last backup information by database  (Query 9) (Last Backup By Database)
SELECT ISNULL(d.[name], bs.[database_name]) AS [Database], d.recovery_model_desc AS [Recovery Model], 
       d.log_reuse_wait_desc AS [Log Reuse Wait Desc],
    MAX(CASE WHEN [type] = 'D' THEN bs.backup_finish_date ELSE NULL END) AS [Last Full Backup],
    MAX(CASE WHEN [type] = 'I' THEN bs.backup_finish_date ELSE NULL END) AS [Last Differential Backup],
    MAX(CASE WHEN [type] = 'L' THEN bs.backup_finish_date ELSE NULL END) AS [Last Log Backup]
FROM sys.databases AS d WITH (NOLOCK)
LEFT OUTER JOIN msdb.dbo.backupset AS bs WITH (NOLOCK)
ON bs.[database_name] = d.[name] 
AND bs.backup_finish_date > GETDATE()- 30
WHERE d.name <> N'tempdb'
GROUP BY ISNULL(d.[name], bs.[database_name]), d.recovery_model_desc, d.log_reuse_wait_desc, d.[name] 
ORDER BY d.recovery_model_desc, d.[name] OPTION (RECOMPILE);
------

-- This helps you spot runaway transaction logs and other issues with your backup schedule


-- Get SQL Server Agent jobs and Category information (Query 10) (SQL Server Agent Jobs)
SELECT sj.name AS [Job Name], sj.[description] AS [Job Description], SUSER_SNAME(sj.owner_sid) AS [Job Owner],
sj.date_created AS [Date Created], sj.[enabled] AS [Job Enabled], 
sj.notify_email_operator_id, sj.notify_level_email, sc.name AS [CategoryName],
s.[enabled] AS [Sched Enabled], js.next_run_date, js.next_run_time
FROM msdb.dbo.sysjobs AS sj WITH (NOLOCK)
INNER JOIN msdb.dbo.syscategories AS sc WITH (NOLOCK)
ON sj.category_id = sc.category_id
LEFT OUTER JOIN msdb.dbo.sysjobschedules AS js WITH (NOLOCK)
ON sj.job_id = js.job_id
LEFT OUTER JOIN msdb.dbo.sysschedules AS s WITH (NOLOCK)
ON js.schedule_id = s.schedule_id
ORDER BY sj.name OPTION (RECOMPILE);
------

-- Gives you some basic information about your SQL Server Agent jobs, who owns them and how they are configured
-- Look for Agent jobs that are not owned by sa
-- Look for jobs that have a notify_email_operator_id set to 0 (meaning no operator)
-- Look for jobs that have a notify_level_email set to 0 (meaning no e-mail is ever sent)
--
-- MSDN sysjobs documentation
-- https://bit.ly/2paDEOP 

-- SQL Server Maintenance Solution
-- https://bit.ly/1pgchQu  


-- Get SQL Server Agent Alert Information (Query 11) (SQL Server Agent Alerts)
SELECT name, event_source, message_id, severity, [enabled], has_notification, 
       delay_between_responses, occurrence_count, last_occurrence_date, last_occurrence_time
FROM msdb.dbo.sysalerts WITH (NOLOCK)
ORDER BY name OPTION (RECOMPILE);
------

-- Gives you some basic information about your SQL Server Agent Alerts 
-- (which are different from SQL Server Agent jobs)
-- Read more about Agent Alerts here: https://bit.ly/2Giz0Xf 



-- Host information (Query 12) (Host Info)
SELECT host_platform, host_distribution, host_release, 
       host_service_pack_level, host_sku, os_language_version 
FROM sys.dm_os_host_info WITH (NOLOCK) OPTION (RECOMPILE); 
------

-- host_release codes (only valid for Windows)
-- 10.0 is either Windows 10 or Windows Server 2016
-- 6.3 is either Windows 8.1 or Windows Server 2012 R2 
-- 6.2 is either Windows 8 or Windows Server 2012


-- host_sku codes (only valid for Windows)
-- 4 is Enterprise Edition
-- 7 is Standard Server Edition
-- 8 is Datacenter Server Edition
-- 10 is Enterprise Server Edition
-- 48 is Professional Edition
-- 161 is Pro for Workstations

-- 1033 for os_language_version is US-English

-- SQL Server 2019 requires Windows Server 2012 or newer (may change by RTM)

-- Hardware and Software Requirements for Installing SQL Server
-- https://bit.ly/2y3ka5L

-- Using SQL Server in Windows 8 and later versions of Windows operating system
-- https://bit.ly/2F7Ax0P 


-- SQL Server NUMA Node information  (Query 13) (SQL Server NUMA Info)
SELECT node_id, node_state_desc, memory_node_id, processor_group, cpu_count, online_scheduler_count, 
       idle_scheduler_count, active_worker_count, avg_load_balance, resource_monitor_state
FROM sys.dm_os_nodes WITH (NOLOCK) 
WHERE node_state_desc <> N'ONLINE DAC' OPTION (RECOMPILE);
------

-- Gives you some useful information about the composition and relative load on your NUMA nodes
-- You want to see an equal number of schedulers on each NUMA node
-- Watch out if SQL Server 2019 Standard Edition has been installed 
-- on a physical or virtual machine with more than four sockets or more than 24 physical cores

-- sys.dm_os_nodes (Transact-SQL)
-- https://bit.ly/2pn5Mw8

-- Balancing Your Available SQL Server Core Licenses Evenly Across NUMA Nodes
-- https://bit.ly/2vfC4Rq



-- Good basic information about OS memory amounts and state  (Query 14) (System Memory)
SELECT total_physical_memory_kb/1024 AS [Physical Memory (MB)], 
       available_physical_memory_kb/1024 AS [Available Memory (MB)], 
       total_page_file_kb/1024 AS [Total Page File (MB)], 
	   available_page_file_kb/1024 AS [Available Page File (MB)], 
	   system_cache_kb/1024 AS [System Cache (MB)],
       system_memory_state_desc AS [System Memory State]
FROM sys.dm_os_sys_memory WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You want to see "Available physical memory is high" for System Memory State
-- This indicates that you are not under external memory pressure

-- Possible System Memory State values:
-- Available physical memory is high
-- Physical memory usage is steady
-- Available physical memory is low
-- Available physical memory is running low
-- Physical memory state is transitioning

-- sys.dm_os_sys_memory (Transact-SQL)
-- https://bit.ly/2pcV0xq



-- You can skip the next two queries if you know you don't have a clustered instance


-- Get information about your cluster nodes and their status  (Query 15) (Cluster Node Properties)
-- (if your database server is in a failover cluster)
SELECT NodeName, status_description, is_current_owner
FROM sys.dm_os_cluster_nodes WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Knowing which node owns the cluster resources is critical
-- Especially when you are installing Windows or SQL Server updates
-- You will see no results if your instance is not clustered

-- Recommended hotfixes and updates for Windows Server 2012 R2-based failover clusters
-- https://bit.ly/1z5BfCw


-- Get information about any AlwaysOn AG cluster this instance is a part of (Query 16) (AlwaysOn AG Cluster)
SELECT cluster_name, quorum_type_desc, quorum_state_desc
FROM sys.dm_hadr_cluster WITH (NOLOCK) OPTION (RECOMPILE);
------

-- You will see no results if your instance is not using AlwaysOn AGs


-- Good overview of AG health and status (Query 17) (AlwaysOn AG Status)
SELECT ag.name AS [AG Name], ar.replica_server_name, ar.availability_mode_desc, adc.[database_name], 
       drs.is_local, drs.is_primary_replica, drs.synchronization_state_desc, drs.is_commit_participant, 
	   drs.synchronization_health_desc, drs.recovery_lsn, drs.truncation_lsn, drs.last_sent_lsn, 
	   drs.last_sent_time, drs.last_received_lsn, drs.last_received_time, drs.last_hardened_lsn, 
	   drs.last_hardened_time, drs.last_redone_lsn, drs.last_redone_time, drs.log_send_queue_size, 
	   drs.log_send_rate, drs.redo_queue_size, drs.redo_rate, drs.filestream_send_rate, 
	   drs.end_of_log_lsn, drs.last_commit_lsn, drs.last_commit_time, drs.database_state_desc 
FROM sys.dm_hadr_database_replica_states AS drs WITH (NOLOCK)
INNER JOIN sys.availability_databases_cluster AS adc WITH (NOLOCK)
ON drs.group_id = adc.group_id 
AND drs.group_database_id = adc.group_database_id
INNER JOIN sys.availability_groups AS ag WITH (NOLOCK)
ON ag.group_id = drs.group_id
INNER JOIN sys.availability_replicas AS ar WITH (NOLOCK)
ON drs.group_id = ar.group_id 
AND drs.replica_id = ar.replica_id
ORDER BY ag.name, ar.replica_server_name, adc.[database_name] OPTION (RECOMPILE);

-- You will see no results if your instance is not using AlwaysOn AGs

-- SQL Server 2016 � It Just Runs Faster: Always On Availability Groups Turbocharged
-- https://bit.ly/2dn1H6r


-- Hardware information from SQL Server 2019  (Query 18) (Hardware Info)
SELECT cpu_count AS [Logical CPU Count], scheduler_count, 
       (socket_count * cores_per_socket) AS [Physical Core Count], 
       socket_count AS [Socket Count], cores_per_socket, numa_node_count,
       physical_memory_kb/1024 AS [Physical Memory (MB)], 
       max_workers_count AS [Max Workers Count], 
	   affinity_type_desc AS [Affinity Type], 
       sqlserver_start_time AS [SQL Server Start Time],
	   DATEDIFF(hour, sqlserver_start_time, GETDATE()) AS [SQL Server Up Time (hrs)],
	   virtual_machine_type_desc AS [Virtual Machine Type], 
       softnuma_configuration_desc AS [Soft NUMA Configuration], 
	   sql_memory_model_desc, container_type_desc -- New in SQL Server 2019
FROM sys.dm_os_sys_info WITH (NOLOCK) OPTION (RECOMPILE);
------

-- Gives you some good basic hardware information about your database server
-- Note: virtual_machine_type_desc of HYPERVISOR does not automatically mean you are running SQL Server inside of a VM
-- It merely indicates that you have a hypervisor running on your host

-- sys.dm_os_sys_info (Transact-SQL)
-- https://bit.ly/2pczOYs

-- Soft NUMA configuration was a new column for SQL Server 2016
-- OFF = Soft-NUMA feature is OFF
-- ON = SQL Server automatically determines the NUMA node sizes for Soft-NUMA
-- MANUAL = Manually configured soft-NUMA

-- Configure SQL Server to Use Soft-NUMA (SQL Server)
-- https://bit.ly/2HTpKJt

-- sql_memory_model_desc values (Added in SQL Server 2016 SP1)
-- CONVENTIONAL
-- LOCK_PAGES
-- LARGE_PAGES
   

-- Get System Manufacturer and model number from SQL Server Error log (Query 19) (System Manufacturer)
EXEC sys.xp_readerrorlog 0, 1, N'Manufacturer';
------ 

-- This can help you determine the capabilities and capacities of your database server
-- Can also be used to confirm if you are running in a VM
-- This query might take a few seconds if you have not recycled your error log recently
-- This query will return no results if your error log has been recycled since the instance was started


-- Get pvscsi info from Windows Registry  (Query 20) (PVSCSI Driver Parameters)
EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SYSTEM\CurrentControlSet\services\pvscsi\Parameters\Device', N'DriverParameter';
------

-- This is valid for VMware VMs
-- Recommended value for intensive I/O patterns from VMware is: RequestRingPages=32,MaxQueueDepth=254
-- https://kb.vmware.com/s/article/2053145
-- Does not work on Linux


-- Get BIOS date from Windows Registry (Query 21) (BIOS Date)
EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'HARDWARE\DESCRIPTION\System\BIOS', N'BiosReleaseDate';
------

-- Helps you understand whether the main system BIOS is up to date, and the possible age of the hardware
-- Not as useful for virtualization
-- Does not work on Linux


-- Get processor description from Windows Registry  (Query 22) (Processor Description)
EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'HARDWARE\DESCRIPTION\System\CentralProcessor\0', N'ProcessorNameString';
------

-- Gives you the model number and rated clock speed of your processor(s)
-- Your processors may be running at less than the rated clock speed due
-- to the Windows Power Plan or hardware power management
-- Does not work on Linux

-- You can use CPU-Z to get your actual CPU core speed and a lot of other useful information
-- https://bit.ly/QhR6xF

-- You can learn more about processor selection for SQL Server by following this link
-- https://bit.ly/2F3aVlP



-- See if buffer pool extension (BPE) is enabled (Query 23) (BPE Configuration)
SELECT [path], state_description, current_size_in_kb, 
CAST(current_size_in_kb/1048576.0 AS DECIMAL(10,2)) AS [Size (GB)]
FROM sys.dm_os_buffer_pool_extension_configuration WITH (NOLOCK) OPTION (RECOMPILE);
------

-- BPE is available in both Standard Edition and Enterprise Edition
-- It is a more interesting feature for Standard Edition

-- Buffer Pool Extension to SSDs in SQL Server 2014
-- https://bit.ly/1bm08m8

-- Buffer Pool Extension
-- https://bit.ly/2oBuieO



-- Look at buffer descriptors to see BPE usage by database (Query 24) (BPE Usage) 
SELECT DB_NAME(database_id) AS [Database Name], COUNT(page_id) AS [Page Count],
CAST(COUNT(*)/128.0 AS DECIMAL(10, 2)) AS [Buffer size(MB)], 
AVG(read_microsec) AS [Avg Read Time (microseconds)]
FROM sys.dm_os_buffer_descriptors WITH (NOLOCK)
WHERE database_id <> 32767
AND is_in_bpool_extension = 1
GROUP BY DB_NAME(database_id) 
ORDER BY [Buffer size(MB)] DESC OPTION (RECOMPILE);
------

-- You will see no results if BPE is not enabled or if there is no BPE usage


-- Get information on location, time and size of any memory dumps from SQL Server  (Query 25) (Memory Dump Info)
SELECT [filename], creation_time, size_in_bytes/1048576.0 AS [Size (MB)]
FROM sys.dm_server_memory_dumps WITH (NOLOCK) 
ORDER BY creation_time DESC OPTION (RECOMPILE);
------

-- This will not return any rows if you have 
-- not had any memory dumps (which is a good thing)

-- sys.dm_server_memory_dumps (Transact-SQL)
-- https://bit.ly/2elwWll



-- Look at Suspect Pages table (Query 26) (Suspect Pages)
SELECT DB_NAME(database_id) AS [Database Name], [file_id], page_id, 
       event_type, error_count, last_update_date 
FROM msdb.dbo.suspect_pages WITH (NOLOCK)
ORDER BY database_id OPTION (RECOMPILE);
------

-- event_type value descriptions
-- 1 = 823 error caused by an operating system CRC error
--     or 824 error other than a bad checksum or a torn page (for example, a bad page ID)
-- 2 = Bad checksum
-- 3 = Torn page
-- 4 = Restored (The page was restored after it was marked bad)
-- 5 = Repaired (DBCC repaired the page)
-- 7 = Deallocated by DBCC

-- Ideally, this query returns no results. The table is limited to 1000 rows.
-- If you do get results here, you should do further investigation to determine the root cause

-- Manage the suspect_pages Table
-- https://bit.ly/2Fvr1c9


-- Get number of data files in tempdb database (Query 27) (TempDB Data Files)
EXEC sys.xp_readerrorlog 0, 1, N'The tempdb database has';
------

-- Get the number of data files in the tempdb database
-- 4-8 data files that are all the same size is a good starting point
-- This query will return no results if your error log has been recycled since the instance was last started


-- File names and paths for all user and system databases on instance  (Query 28) (Database Filenames and Paths)
SELECT DB_NAME([database_id]) AS [Database Name], 
       [file_id], [name], physical_name, [type_desc], state_desc,
	   is_percent_growth, growth,
	   CONVERT(bigint, growth/128.0) AS [Growth in MB], 
       CONVERT(bigint, size/128.0) AS [Total Size in MB]
FROM sys.master_files WITH (NOLOCK)
ORDER BY DB_NAME([database_id]), [file_id] OPTION (RECOMPILE);
------

-- Things to look at:
-- Are data files and log files on different drives?
-- Is everything on the C: drive?
-- Is tempdb on dedicated drives?
-- Is there only one tempdb data file?
-- Are all of the tempdb data files the same size?
-- Are there multiple data files for user databases?
-- Is percent growth enabled for any files (which is bad)?


-- Drive information for all fixed drives visible to the operating system (Query 29) (Fixed Drives)
SELECT fixed_drive_path, drive_type_desc, 
CONVERT(DECIMAL(18,2), free_space_in_bytes/1073741824.0) AS [Available Space (GB)]
FROM sys.dm_os_enumerate_fixed_drives WITH (NOLOCK) OPTION (RECOMPILE);
------

-- This shows all of your fixed drives, not just LUNs with SQL Server database files



-- Volume info for all LUNS that have database files on the current instance (Query 30) (Volume Info)
SELECT DISTINCT vs.volume_mount_point, vs.file_system_type, vs.logical_volume_name, 
CONVERT(DECIMAL(18,2), vs.total_bytes/1073741824.0) AS [Total Size (GB)],
CONVERT(DECIMAL(18,2), vs.available_bytes/1073741824.0) AS [Available Size (GB)],  
CONVERT(DECIMAL(18,2), vs.available_bytes * 1. / vs.total_bytes * 100.) AS [Space Free %],
vs.supports_compression, vs.is_compressed, 
vs.supports_sparse_files, vs.supports_alternate_streams
FROM sys.master_files AS f WITH (NOLOCK)
CROSS APPLY sys.dm_os_volume_stats(f.database_id, f.[file_id]) AS vs 
ORDER BY vs.volume_mount_point OPTION (RECOMPILE);
------

-- Shows you the total and free space on the LUNs where you have database files
-- Being low on free space can negatively affect performance

-- sys.dm_os_volume_stats (Transact-SQL)
-- https://bit.ly/2oBPNNr



-- Drive level latency information (Query 31) (Drive Level Latency)
-- Based on code from Jimmy May
SELECT tab.[Drive], tab.volume_mount_point AS [Volume Mount Point], 
	CASE 
		WHEN num_of_reads = 0 THEN 0 
		ELSE (io_stall_read_ms/num_of_reads) 
	END AS [Read Latency],
	CASE 
		WHEN num_of_writes = 0 THEN 0 
		ELSE (io_stall_write_ms/num_of_writes) 
	END AS [Write Latency],
	CASE 
		WHEN (num_of_reads = 0 AND num_of_writes = 0) THEN 0 
		ELSE (io_stall/(num_of_reads + num_of_writes)) 
	END AS [Overall Latency],
	CASE 
		WHEN num_of_reads = 0 THEN 0 
		ELSE (num_of_bytes_read/num_of_reads) 
	END AS [Avg Bytes/Read],
	CASE 
		WHEN num_of_writes = 0 THEN 0 
		ELSE (num_of_bytes_written/num_of_writes) 
	END AS [Avg Bytes/Write],
	CASE 
		WHEN (num_of_reads = 0 AND num_of_writes = 0) THEN 0 
		ELSE ((num_of_bytes_read + num_of_bytes_written)/(num_of_reads + num_of_writes)) 
	END AS [Avg Bytes/Transfer]
FROM (SELECT LEFT(UPPER(mf.physical_name), 2) AS Drive, SUM(num_of_reads) AS num_of_reads,
	         SUM(io_stall_read_ms) AS io_stall_read_ms, SUM(num_of_writes) AS num_of_writes,
	         SUM(io_stall_write_ms) AS io_stall_write_ms, SUM(num_of_bytes_read) AS num_of_bytes_read,
	         SUM(num_of_bytes_written) AS num_of_bytes_written, SUM(io_stall) AS io_stall, vs.volume_mount_point 
      FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS vfs
      INNER JOIN sys.master_files AS mf WITH (NOLOCK)
      ON vfs.database_id = mf.database_id AND vfs.file_id = mf.file_id
	  CROSS APPLY sys.dm_os_volume_stats(mf.database_id, mf.[file_id]) AS vs 
      GROUP BY LEFT(UPPER(mf.physical_name), 2), vs.volume_mount_point) AS tab
ORDER BY [Overall Latency] OPTION (RECOMPILE);
------

-- Shows you the drive-level latency for reads and writes, in milliseconds
-- Latency above 30-40ms is usually a problem
-- These latency numbers include all file activity against all SQL Server 
-- database files on each drive since SQL Server was last started


-- Calculates average latency per read, per write, and per total input/output for each database file  (Query 32) (IO Latency by File)
SELECT DB_NAME(fs.database_id) AS [Database Name], CAST(fs.io_stall_read_ms/(1.0 + fs.num_of_reads) AS NUMERIC(10,1)) AS [avg_read_latency_ms],
CAST(fs.io_stall_write_ms/(1.0 + fs.num_of_writes) AS NUMERIC(10,1)) AS [avg_write_latency_ms],
CAST((fs.io_stall_read_ms + fs.io_stall_write_ms)/(1.0 + fs.num_of_reads + fs.num_of_writes) AS NUMERIC(10,1)) AS [avg_io_latency_ms],
CONVERT(DECIMAL(18,2), mf.size/128.0) AS [File Size (MB)], mf.physical_name, mf.type_desc, fs.io_stall_read_ms, fs.num_of_reads, 
fs.io_stall_write_ms, fs.num_of_writes, fs.io_stall_read_ms + fs.io_stall_write_ms AS [io_stalls], fs.num_of_reads + fs.num_of_writes AS [total_io],
io_stall_queued_read_ms AS [Resource Governor Total Read IO Latency (ms)], io_stall_queued_write_ms AS [Resource Governor Total Write IO Latency (ms)] 
FROM sys.dm_io_virtual_file_stats(null,null) AS fs
INNER JOIN sys.master_files AS mf WITH (NOLOCK)
ON fs.database_id = mf.database_id
AND fs.[file_id] = mf.[file_id]
ORDER BY avg_io_latency_ms DESC OPTION (RECOMPILE);
------

-- Helps determine which database files on the entire instance have the most I/O bottlenecks
-- This can help you decide whether certain LUNs are overloaded and whether you might
-- want to move some files to a different location or perhaps improve your I/O performance
-- These latency numbers include all file activity against each SQL Server 
-- database file since SQL Server was last started


-- Look for I/O requests taking longer than 15 seconds in the six most recent SQL Server Error Logs (Query 33) (IO Warnings)
CREATE TABLE #IOWarningResults(LogDate datetime, ProcessInfo sysname, LogText nvarchar(1000));

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 0, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 1, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 2, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 3, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 4, 1, N'taking longer than 15 seconds';

	INSERT INTO #IOWarningResults 
	EXEC xp_readerrorlog 5, 1, N'taking longer than 15 seconds';

SELECT LogDate, ProcessInfo, LogText
FROM #IOWarningResults
ORDER BY LogDate DESC;

DROP TABLE #IOWarningResults;
------  

-- Finding 15 second I/O warnings in the SQL Server Error Log is useful evidence of
-- poor I/O performance (which might have many different causes)
-- Look to see if you see any patterns in the results (same files, same drives, same time of day, etc.)

-- Diagnostics in SQL Server help detect stalled and stuck I/O operations
-- https://bit.ly/2qtaw73



-- Resource Governor Resource Pool information (Query 34) (RG Resource Pools)
SELECT pool_id, [Name], statistics_start_time,
       min_memory_percent, max_memory_percent,  
       max_memory_kb/1024 AS [max_memory_mb],  
       used_memory_kb/1024 AS [used_memory_mb],   
       target_memory_kb/1024 AS [target_memory_mb],
	   min_iops_per_volume, max_iops_per_volume
FROM sys.dm_resource_governor_resource_pools WITH (NOLOCK)
OPTION (RECOMPILE);
------

-- sys.dm_resource_governor_resource_pools (Transact-SQL)
-- https://bit.ly/2MVU0Vy



-- Recovery model, log reuse wait description, log file size, log usage size  (Query 35) (Database Properties)
-- and compatibility level for all databases on instance
SELECT db.[name] AS [Database Name], SUSER_SNAME(db.owner_sid) AS [Database Owner], db.recovery_model_desc AS [Recovery Model], 
db.state_desc, db.containment_desc, db.log_reuse_wait_desc AS [Log Reuse Wait Description], 
CONVERT(DECIMAL(18,2), ls.cntr_value/1024.0) AS [Log Size (MB)], CONVERT(DECIMAL(18,2), lu.cntr_value/1024.0) AS [Log Used (MB)],
CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log Used %], 
db.[compatibility_level] AS [DB Compatibility Level], 
db.is_mixed_page_allocation_on, db.page_verify_option_desc AS [Page Verify Option], 
db.is_auto_create_stats_on, db.is_auto_update_stats_on, db.is_auto_update_stats_async_on, db.is_parameterization_forced, 
db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on, db.is_auto_close_on, db.is_auto_shrink_on, 
db.target_recovery_time_in_seconds, db.is_cdc_enabled, db.is_published, db.is_distributor,
db.group_database_id, db.replica_id,db.is_memory_optimized_elevate_to_snapshot_on, 
db.delayed_durability_desc, db.is_auto_create_stats_incremental_on,
db.is_query_store_on, db.is_sync_with_backup, db.is_temporal_history_retention_enabled,
db.is_supplemental_logging_enabled, db.is_remote_data_archive_enabled,
db.is_encrypted, de.encryption_state, de.percent_complete, de.key_algorithm, de.key_length, db.resource_pool_id      
FROM sys.databases AS db WITH (NOLOCK)
INNER JOIN sys.dm_os_performance_counters AS lu WITH (NOLOCK)
ON db.name = lu.instance_name
INNER JOIN sys.dm_os_performance_counters AS ls WITH (NOLOCK)
ON db.name = ls.instance_name
LEFT OUTER JOIN sys.dm_database_encryption_keys AS de WITH (NOLOCK)
ON db.database_id = de.database_id
WHERE lu.counter_name LIKE N'Log File(s) Used Size (KB)%' 
AND ls.counter_name LIKE N'Log File(s) Size (KB)%'
AND ls.cntr_value > 0 
ORDER BY db.[name] OPTION (RECOMPILE);
------

-- Things to look at:
-- How many databases are on the instance?
-- What recovery models are they using?
-- What is the log reuse wait description?
-- How full are the transaction logs?
-- What compatibility level are the databases on? 
-- What is the Page Verify Option? (should be CHECKSUM)
-- Is Auto Update Statistics Asynchronously enabled?
-- Is Delayed Durability enabled
-- Make sure auto_shrink and auto_close are not enabled!

-- is_mixed_page_allocation_on is a new property for SQL Server 2016. Equivalent to TF 1118 for a user database
-- SQL Server 2016: Changes in default behavior for autogrow and allocations for tempdb and user databases
-- https://bit.ly/2evRZSR

-- A non-zero value for target_recovery_time_in_seconds means that indirect checkpoint is enabled 
-- If the setting has a zero value it indicates that automatic checkpoint is enabled

-- Changes in SQL Server 2016 Checkpoint Behavior
-- https://bit.ly/2pdggk3


-- Missing Indexes for all databases by Index Advantage  (Query 36) (Missing Indexes All Databases)
SELECT CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage],
FORMAT(migs.last_user_seek, 'yyyy-MM-dd HH:mm:ss') AS [last_user_seek], 
mid.[statement] AS [Database.Schema.Table],
COUNT(1) OVER(PARTITION BY mid.[statement]) AS [missing_indexes_for_table],
COUNT(1) OVER(PARTITION BY mid.[statement], equality_columns) AS [similar_missing_indexes_for_table],
mid.equality_columns, mid.inequality_columns, mid.included_columns,
migs.unique_compiles, migs.user_seeks, 
CONVERT(decimal(18,2), migs.avg_total_user_cost) AS [avg_total_user_cost], migs.avg_user_impact 
FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)
INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)
ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)
ON mig.index_handle = mid.index_handle
ORDER BY index_advantage DESC OPTION (RECOMPILE);
------

-- Getting missing index information for all of the databases on the instance is very useful
-- Look at last user seek time, number of user seeks to help determine source and importance
-- Also look at avg_user_impact and avg_total_user_cost to help determine importance
-- SQL Server is overly eager to add included columns, so beware
-- Do not just blindly add indexes that show up from this query!!!

-- SQL Server Index Design Guide
-- https://bit.ly/2qtZr4N



-- Get VLF Counts for all databases on the instance (Query 37) (VLF Counts)
SELECT [name] AS [Database Name], [VLF Count]
FROM sys.databases AS db WITH (NOLOCK)
CROSS APPLY (SELECT file_id, COUNT(*) AS [VLF Count]
		     FROM sys.dm_db_log_info(db.database_id)
			 GROUP BY file_id) AS li
ORDER BY [VLF Count] DESC OPTION (RECOMPILE);
------

-- High VLF counts can affect write performance to the log file
-- and they can make full database restores and crash recovery take much longer
-- Try to keep your VLF counts under 200 in most cases (depending on log file size)

-- Important change to VLF creation algorithm in SQL Server 2014
-- https://bit.ly/2Hsjbg4

-- SQL Server Transaction Log Architecture and Management Guide
-- https://bit.ly/2JjmQRZ



-- Get CPU utilization by database (Query 38) (CPU Usage by Database)
WITH DB_CPU_Stats
AS
(SELECT pa.DatabaseID, DB_Name(pa.DatabaseID) AS [Database Name], SUM(qs.total_worker_time/1000) AS [CPU_Time_Ms]
 FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
 CROSS APPLY (SELECT CONVERT(int, value) AS [DatabaseID] 
              FROM sys.dm_exec_plan_attributes(qs.plan_handle)
              WHERE attribute = N'dbid') AS pa
 GROUP BY DatabaseID)
SELECT ROW_NUMBER() OVER(ORDER BY [CPU_Time_Ms] DESC) AS [CPU Rank],
       [Database Name], [CPU_Time_Ms] AS [CPU Time (ms)], 
       CAST([CPU_Time_Ms] * 1.0 / SUM([CPU_Time_Ms]) OVER() * 100.0 AS DECIMAL(5, 2)) AS [CPU Percent]
FROM DB_CPU_Stats
WHERE DatabaseID <> 32767 -- ResourceDB
ORDER BY [CPU Rank] OPTION (RECOMPILE);
------

-- Helps determine which database is using the most CPU resources on the instance
-- Note: This only reflects CPU usage from the currently cached query plans


-- Get I/O utilization by database (Query 39) (IO Usage By Database)
WITH Aggregate_IO_Statistics
AS (SELECT DB_NAME(database_id) AS [Database Name],
    CAST(SUM(num_of_bytes_read + num_of_bytes_written) / 1048576 AS DECIMAL(12, 2)) AS [ioTotalMB],
    CAST(SUM(num_of_bytes_read ) / 1048576 AS DECIMAL(12, 2)) AS [ioReadMB],
    CAST(SUM(num_of_bytes_written) / 1048576 AS DECIMAL(12, 2)) AS [ioWriteMB]
    FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS [DM_IO_STATS]
    GROUP BY database_id)
SELECT ROW_NUMBER() OVER (ORDER BY ioTotalMB DESC) AS [I/O Rank],
        [Database Name], ioTotalMB AS [Total I/O (MB)],
        CAST(ioTotalMB / SUM(ioTotalMB) OVER () * 100.0 AS DECIMAL(5, 2)) AS [Total I/O %],
        ioReadMB AS [Read I/O (MB)], 
		CAST(ioReadMB / SUM(ioReadMB) OVER () * 100.0 AS DECIMAL(5, 2)) AS [Read I/O %],
        ioWriteMB AS [Write I/O (MB)], 
		CAST(ioWriteMB / SUM(ioWriteMB) OVER () * 100.0 AS DECIMAL(5, 2)) AS [Write I/O %]
FROM Aggregate_IO_Statistics
ORDER BY [I/O Rank] OPTION (RECOMPILE);
------

-- Helps determine which database is using the most I/O resources on the instance
-- These numbers are cumulative since the last service restart
-- They include all I/O activity, not just the nominal I/O workload


-- Get total buffer usage by database for current instance  (Query 40) (Total Buffer Usage by Database)
-- This make take some time to run on a busy instance
WITH AggregateBufferPoolUsage
AS
(SELECT DB_NAME(database_id) AS [Database Name],
CAST(COUNT(*) * 8/1024.0 AS DECIMAL (10,2))  AS [CachedSize]
FROM sys.dm_os_buffer_descriptors WITH (NOLOCK)
WHERE database_id <> 32767 -- ResourceDB
GROUP BY DB_NAME(database_id))
SELECT ROW_NUMBER() OVER(ORDER BY CachedSize DESC) AS [Buffer Pool Rank], [Database Name], CachedSize AS [Cached Size (MB)],
       CAST(CachedSize / SUM(CachedSize) OVER() * 100.0 AS DECIMAL(5,2)) AS [Buffer Pool Percent]
FROM AggregateBufferPoolUsage
ORDER BY [Buffer Pool Rank] OPTION (RECOMPILE);
------

-- Tells you how much memory (in the buffer pool) 
-- is being used by each database on the instance


-- Get tempdb version store space usage by database (Query 41) (Version Store Space Usage)
SELECT DB_NAME(database_id) AS [Database Name],
       reserved_page_count AS [Version Store Reserved Page Count], 
	   reserved_space_kb/1024 AS [Version Store Reserved Space (MB)] 
FROM sys.dm_tran_version_store_space_usage WITH (NOLOCK) 
ORDER BY reserved_space_kb/1024 DESC OPTION (RECOMPILE);
------  

-- sys.dm_tran_version_store_space_usage (Transact-SQL)
-- https://bit.ly/2vh3Bmk




-- Clear Wait Stats with this command
-- DBCC SQLPERF('sys.dm_os_wait_stats', CLEAR);

-- Isolate top waits for server instance since last restart or wait statistics clear  (Query 42) (Top Waits)
WITH [Waits] 
AS (SELECT wait_type, wait_time_ms/ 1000.0 AS [WaitS],
          (wait_time_ms - signal_wait_time_ms) / 1000.0 AS [ResourceS],
           signal_wait_time_ms / 1000.0 AS [SignalS],
           waiting_tasks_count AS [WaitCount],
           100.0 *  wait_time_ms / SUM (wait_time_ms) OVER() AS [Percentage],
           ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS [RowNum]
    FROM sys.dm_os_wait_stats WITH (NOLOCK)
    WHERE [wait_type] NOT IN (
        N'BROKER_EVENTHANDLER', N'BROKER_RECEIVE_WAITFOR', N'BROKER_TASK_STOP',
		N'BROKER_TO_FLUSH', N'BROKER_TRANSMITTER', N'CHECKPOINT_QUEUE',
        N'CHKPT', N'CLR_AUTO_EVENT', N'CLR_MANUAL_EVENT', N'CLR_SEMAPHORE', N'CXCONSUMER',
        N'DBMIRROR_DBM_EVENT', N'DBMIRROR_EVENTS_QUEUE', N'DBMIRROR_WORKER_QUEUE',
		N'DBMIRRORING_CMD', N'DIRTY_PAGE_POLL', N'DISPATCHER_QUEUE_SEMAPHORE',
        N'EXECSYNC', N'FSAGENT', N'FT_IFTS_SCHEDULER_IDLE_WAIT', N'FT_IFTSHC_MUTEX',
        N'HADR_CLUSAPI_CALL', N'HADR_FILESTREAM_IOMGR_IOCOMPLETION', N'HADR_LOGCAPTURE_WAIT', 
		N'HADR_NOTIFICATION_DEQUEUE', N'HADR_TIMER_TASK', N'HADR_WORK_QUEUE',
        N'KSOURCE_WAKEUP', N'LAZYWRITER_SLEEP', N'LOGMGR_QUEUE', 
		N'MEMORY_ALLOCATION_EXT', N'ONDEMAND_TASK_QUEUE',
		N'PARALLEL_REDO_DRAIN_WORKER', N'PARALLEL_REDO_LOG_CACHE', N'PARALLEL_REDO_TRAN_LIST',
		N'PARALLEL_REDO_WORKER_SYNC', N'PARALLEL_REDO_WORKER_WAIT_WORK',
		N'PREEMPTIVE_HADR_LEASE_MECHANISM', N'PREEMPTIVE_SP_SERVER_DIAGNOSTICS',
		N'PREEMPTIVE_OS_LIBRARYOPS', N'PREEMPTIVE_OS_COMOPS', N'PREEMPTIVE_OS_CRYPTOPS',
		N'PREEMPTIVE_OS_PIPEOPS', N'PREEMPTIVE_OS_AUTHENTICATIONOPS',
		N'PREEMPTIVE_OS_GENERICOPS', N'PREEMPTIVE_OS_VERIFYTRUST',
		N'PREEMPTIVE_OS_FILEOPS', N'PREEMPTIVE_OS_DEVICEOPS', N'PREEMPTIVE_OS_QUERYREGISTRY',
		N'PREEMPTIVE_OS_WRITEFILE',
		N'PREEMPTIVE_XE_CALLBACKEXECUTE', N'PREEMPTIVE_XE_DISPATCHER',
		N'PREEMPTIVE_XE_GETTARGETSTATE', N'PREEMPTIVE_XE_SESSIONCOMMIT',
		N'PREEMPTIVE_XE_TARGETINIT', N'PREEMPTIVE_XE_TARGETFINALIZE',
        N'PWAIT_ALL_COMPONENTS_INITIALIZED', N'PWAIT_DIRECTLOGCONSUMER_GETNEXT',
		N'PWAIT_EXTENSIBILITY_CLEANUP_TASK',
		N'QDS_PERSIST_TASK_MAIN_LOOP_SLEEP', N'QDS_ASYNC_QUEUE',
        N'QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP', N'REQUEST_FOR_DEADLOCK_SEARCH',
		N'RESOURCE_QUEUE', N'SERVER_IDLE_CHECK', N'SLEEP_BPOOL_FLUSH', N'SLEEP_DBSTARTUP',
		N'SLEEP_DCOMSTARTUP', N'SLEEP_MASTERDBREADY', N'SLEEP_MASTERMDREADY',
        N'SLEEP_MASTERUPGRADED', N'SLEEP_MSDBSTARTUP', N'SLEEP_SYSTEMTASK', N'SLEEP_TASK',
        N'SLEEP_TEMPDBSTARTUP', N'SNI_HTTP_ACCEPT', N'SOS_WORK_DISPATCHER',
		N'SP_SERVER_DIAGNOSTICS_SLEEP',
		N'SQLTRACE_BUFFER_FLUSH', N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', N'SQLTRACE_WAIT_ENTRIES',
		N'STARTUP_DEPENDENCY_MANAGER',
		N'WAIT_FOR_RESULTS', N'WAITFOR', N'WAITFOR_TASKSHUTDOWN', N'WAIT_XTP_HOST_WAIT',
		N'WAIT_XTP_OFFLINE_CKPT_NEW_LOG', N'WAIT_XTP_CKPT_CLOSE', N'WAIT_XTP_RECOVERY',
		N'XE_BUFFERMGR_ALLPROCESSED_EVENT', N'XE_DISPATCHER_JOIN',
        N'XE_DISPATCHER_WAIT', N'XE_LIVE_TARGET_TVF', N'XE_TIMER_EVENT')
    AND waiting_tasks_count > 0)
SELECT
    MAX (W1.wait_type) AS [WaitType],
	CAST (MAX (W1.Percentage) AS DECIMAL (5,2)) AS [Wait Percentage],
	CAST ((MAX (W1.WaitS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgWait_Sec],
    CAST ((MAX (W1.ResourceS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgRes_Sec],
    CAST ((MAX (W1.SignalS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgSig_Sec], 
    CAST (MAX (W1.WaitS) AS DECIMAL (16,2)) AS [Wait_Sec],
    CAST (MAX (W1.ResourceS) AS DECIMAL (16,2)) AS [Resource_Sec],
    CAST (MAX (W1.SignalS) AS DECIMAL (16,2)) AS [Signal_Sec],
    MAX (W1.WaitCount) AS [Wait Count],
	CAST (N'https://www.sqlskills.com/help/waits/' + W1.wait_type AS XML) AS [Help/Info URL]
FROM Waits AS W1
INNER JOIN Waits AS W2
ON W2.RowNum <= W1.RowNum
GROUP BY W1.RowNum, W1.wait_type
HAVING SUM (W2.Percentage) - MAX (W1.Percentage) < 99 -- percentage threshold
OPTION (RECOMPILE);
------

-- Cumulative wait stats are not as useful on an idle instance that is not under load or performance pressure

-- SQL Server Wait Types Library (Paul Randal)
-- https://bit.ly/2ePzYO2

-- The SQL Server Wait Type Repository
-- https://bit.ly/1afzfjC

-- Wait statistics, or please tell me where it hurts
-- https://bit.ly/2wsQHQE

-- SQL Server 2005 Performance Tuning using the Waits and Queues
-- https://bit.ly/1o2NFoF

-- sys.dm_os_wait_stats (Transact-SQL)
-- https://bit.ly/2Hjq9Yl



-- Get a count of SQL connections by IP address (Query 43) (Connection Counts by IP Address)
SELECT ec.client_net_address, es.[program_name], es.[host_name], es.login_name, 
COUNT(ec.session_id) AS [connection count] 
FROM sys.dm_exec_sessions AS es WITH (NOLOCK) 
INNER JOIN sys.dm_exec_connections AS ec WITH (NOLOCK) 
ON es.session_id = ec.session_id 
GROUP BY ec.client_net_address, es.[program_name], es.[host_name], es.login_name  
ORDER BY ec.client_net_address, es.[program_name] OPTION (RECOMPILE);
------

-- This helps you figure where your database load is coming from
-- and verifies connectivity from other machines

-- Solving Connectivity errors to SQL Server
-- https://bit.ly/2EgzoD0



-- Get Average Task Counts (run multiple times)  (Query 44) (Avg Task Counts)
SELECT AVG(current_tasks_count) AS [Avg Task Count], 
AVG(work_queue_count) AS [Avg Work Queue Count],
AVG(runnable_tasks_count) AS [Avg Runnable Task Count],
AVG(pending_disk_io_count) AS [Avg Pending DiskIO Count]
FROM sys.dm_os_schedulers WITH (NOLOCK)
WHERE scheduler_id < 255 OPTION (RECOMPILE);
------

-- Sustained values above 10 suggest further investigation in that area
-- High Avg Task Counts are often caused by blocking/deadlocking or other resource contention

-- Sustained values above 1 suggest further investigation in that area
-- High Avg Runnable Task Counts are a good sign of CPU pressure
-- High Avg Pending DiskIO Counts are a sign of disk pressure

-- How to Do Some Very Basic SQL Server Monitoring
-- https://bit.ly/2q3Btgt



-- Detect blocking (run multiple times)  (Query 45) (Detect Blocking)
SELECT t1.resource_type AS [lock type], DB_NAME(resource_database_id) AS [database],
t1.resource_associated_entity_id AS [blk object],t1.request_mode AS [lock req],  -- lock requested
t1.request_session_id AS [waiter sid], t2.wait_duration_ms AS [wait time],       -- spid of waiter  
(SELECT [text] FROM sys.dm_exec_requests AS r WITH (NOLOCK)                      -- get sql for waiter
CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) 
WHERE r.session_id = t1.request_session_id) AS [waiter_batch],
(SELECT SUBSTRING(qt.[text],r.statement_start_offset/2, 
    (CASE WHEN r.statement_end_offset = -1 
    THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2 
    ELSE r.statement_end_offset END - r.statement_start_offset)/2) 
FROM sys.dm_exec_requests AS r WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) AS qt
WHERE r.session_id = t1.request_session_id) AS [waiter_stmt],					-- statement blocked
t2.blocking_session_id AS [blocker sid],										-- spid of blocker
(SELECT [text] FROM sys.sysprocesses AS p										-- get sql for blocker
CROSS APPLY sys.dm_exec_sql_text(p.[sql_handle]) 
WHERE p.spid = t2.blocking_session_id) AS [blocker_batch]
FROM sys.dm_tran_locks AS t1 WITH (NOLOCK)
INNER JOIN sys.dm_os_waiting_tasks AS t2 WITH (NOLOCK)
ON t1.lock_owner_address = t2.resource_address OPTION (RECOMPILE);
------

-- Helps troubleshoot blocking and deadlocking issues
-- The results will change from second to second on a busy system
-- You should run this query multiple times when you see signs of blocking



-- Get CPU Utilization History for last 256 minutes (in one minute intervals)  (Query 46) (CPU Utilization History)
DECLARE @ts_now bigint = (SELECT cpu_ticks/(cpu_ticks/ms_ticks) FROM sys.dm_os_sys_info WITH (NOLOCK)); 

SELECT TOP(256) SQLProcessUtilization AS [SQL Server Process CPU Utilization], 
               SystemIdle AS [System Idle Process], 
               100 - SystemIdle - SQLProcessUtilization AS [Other Process CPU Utilization], 
               DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) AS [Event Time] 
FROM (SELECT record.value('(./Record/@id)[1]', 'int') AS record_id, 
			record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') 
			AS [SystemIdle], 
			record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int') 
			AS [SQLProcessUtilization], [timestamp] 
	  FROM (SELECT [timestamp], CONVERT(xml, record) AS [record] 
			FROM sys.dm_os_ring_buffers WITH (NOLOCK)
			WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR' 
			AND record LIKE N'%<SystemHealth>%') AS x) AS y 
ORDER BY record_id DESC OPTION (RECOMPILE);
------

-- Look at the trend over the entire period 
-- Also look at high sustained 'Other Process' CPU Utilization values
-- Note: This query sometimes gives inaccurate results (negative values)
-- on high core count (> 64 cores) systems


-- Get top total worker time queries for entire instance (Query 47) (Top Worker Time Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], 
REPLACE(REPLACE(LEFT(t.[text], 255), CHAR(10),''), CHAR(13),'') AS [Short Query Text],  
qs.total_worker_time AS [Total Worker Time], qs.min_worker_time AS [Min Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.max_worker_time AS [Max Worker Time], 
qs.min_elapsed_time AS [Min Elapsed Time], 
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time], 
qs.max_elapsed_time AS [Max Elapsed Time],
qs.min_logical_reads AS [Min Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.max_logical_reads AS [Max Logical Reads], 
qs.execution_count AS [Execution Count],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
qs.creation_time AS [Creation Time]
--,t.[text] AS [Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
ORDER BY qs.total_worker_time DESC OPTION (RECOMPILE);
------


-- Helps you find the most expensive queries from a CPU perspective across the entire instance
-- Can also help track down parameter sniffing issues



-- Page Life Expectancy (PLE) value for each NUMA node in current instance  (Query 48) (PLE by NUMA Node)
SELECT @@SERVERNAME AS [Server Name], RTRIM([object_name]) AS [Object Name], instance_name, cntr_value AS [Page Life Expectancy]
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Buffer Node%' -- Handles named instances
AND counter_name = N'Page life expectancy' OPTION (RECOMPILE);
------

-- PLE is a good measurement of internal memory pressure
-- Higher PLE is better. Watch the trend over time, not the absolute value
-- This will only return one row for non-NUMA systems

-- Page Life Expectancy isn�t what you think�
-- https://bit.ly/2EgynLa


-- Memory Grants Pending value for current instance  (Query 49) (Memory Grants Pending)
SELECT @@SERVERNAME AS [Server Name], RTRIM([object_name]) AS [Object Name], cntr_value AS [Memory Grants Pending]                                                                                                       
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Memory Manager%' -- Handles named instances
AND counter_name = N'Memory Grants Pending' OPTION (RECOMPILE);
------

-- Run multiple times, and run periodically if you suspect you are under memory pressure
-- Memory Grants Pending above zero for a sustained period is a very strong indicator of internal memory pressure


-- Memory Clerk Usage for instance  (Query 50) (Memory Clerk Usage)
-- Look for high value for CACHESTORE_SQLCP (Ad-hoc query plans)
SELECT TOP(10) mc.[type] AS [Memory Clerk Type], 
       CAST((SUM(mc.pages_kb)/1024.0) AS DECIMAL (15,2)) AS [Memory Usage (MB)] 
FROM sys.dm_os_memory_clerks AS mc WITH (NOLOCK)
GROUP BY mc.[type]  
ORDER BY SUM(mc.pages_kb) DESC OPTION (RECOMPILE);
------

-- MEMORYCLERK_SQLBUFFERPOOL was new for SQL Server 2012. It should be your highest consumer of memory

-- CACHESTORE_SQLCP  SQL Plans         
-- These are cached SQL statements or batches that aren't in stored procedures, functions and triggers
-- Watch out for high values for CACHESTORE_SQLCP
-- Enabling 'optimize for ad hoc workloads' at the instance level can help reduce this
-- Running DBCC FREESYSTEMCACHE ('SQL Plans') periodically may be required to better control this

-- CACHESTORE_OBJCP  Object Plans      
-- These are compiled plans for stored procedures, functions and triggers

-- sys.dm_os_memory_clerks (Transact-SQL)
-- https://bit.ly/2H31xDR



-- Find single-use, ad-hoc and prepared queries that are bloating the plan cache  (Query 51) (Ad hoc Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], t.[text] AS [Query Text], 
cp.objtype AS [Object Type], cp.cacheobjtype AS [Cache Object Type],  
cp.size_in_bytes/1024 AS [Plan Size in KB]
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t
WHERE cp.cacheobjtype = N'Compiled Plan' 
AND cp.objtype IN (N'Adhoc', N'Prepared') 
AND cp.usecounts = 1
ORDER BY cp.size_in_bytes DESC, DB_NAME(t.[dbid]) OPTION (RECOMPILE);
------

-- Gives you the text, type and size of single-use ad-hoc and prepared queries that waste space in the plan cache
-- Enabling 'optimize for ad hoc workloads' for the instance can help (SQL Server 2008 and above only)
-- Running DBCC FREESYSTEMCACHE ('SQL Plans') periodically may be required to better control this
-- Enabling forced parameterization for the database can help, but test first!

-- Plan cache, adhoc workloads and clearing the single-use plan cache bloat
-- https://bit.ly/2EfYOkl


-- Get top total logical reads queries for entire instance (Query 52) (Top Logical Reads Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name],
REPLACE(REPLACE(LEFT(t.[text], 255), CHAR(10),''), CHAR(13),'') AS [Short Query Text], 
qs.total_logical_reads AS [Total Logical Reads],
qs.min_logical_reads AS [Min Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.max_logical_reads AS [Max Logical Reads],   
qs.min_worker_time AS [Min Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.max_worker_time AS [Max Worker Time], 
qs.min_elapsed_time AS [Min Elapsed Time], 
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time], 
qs.max_elapsed_time AS [Max Elapsed Time],
qs.execution_count AS [Execution Count], 
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
qs.creation_time AS [Creation Time]
--,t.[text] AS [Complete Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
ORDER BY qs.total_logical_reads DESC OPTION (RECOMPILE);
------


-- Helps you find the most expensive queries from a memory perspective across the entire instance
-- Can also help track down parameter sniffing issues


-- Get top average elapsed time queries for entire instance (Query 53) (Top Avg Elapsed Time Queries)
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], 
REPLACE(REPLACE(LEFT(t.[text], 255), CHAR(10),''), CHAR(13),'') AS [Short Query Text],  
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
qs.min_elapsed_time, qs.max_elapsed_time, qs.last_elapsed_time,
qs.execution_count AS [Execution Count],  
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads], 
qs.total_physical_reads/qs.execution_count AS [Avg Physical Reads], 
qs.total_worker_time/qs.execution_count AS [Avg Worker Time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
qs.creation_time AS [Creation Time]
--,t.[text] AS [Complete Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
ORDER BY qs.total_elapsed_time/qs.execution_count DESC OPTION (RECOMPILE);
------

-- Helps you find the highest average elapsed time queries across the entire instance
-- Can also help track down parameter sniffing issues


-- Look at UDF execution statistics (Query 54) (UDF Stats by DB)
SELECT TOP (25) DB_NAME(database_id) AS [Database Name], 
		   OBJECT_NAME(object_id, database_id) AS [Function Name],
		   total_worker_time, execution_count, total_elapsed_time,  
           total_elapsed_time/execution_count AS [avg_elapsed_time],  
           last_elapsed_time, last_execution_time, cached_time, [type_desc] 
FROM sys.dm_exec_function_stats WITH (NOLOCK) 
ORDER BY total_worker_time DESC OPTION (RECOMPILE);
------

-- sys.dm_exec_function_stats (Transact-SQL)
-- https://bit.ly/2q1Q6BM

-- Showplan Enhancements for UDFs
-- https://bit.ly/2LVqiQ1


-- Database specific queries *****************************************************************

-- **** Please switch to a user database that you are interested in! *****
--USE YourDatabaseName; -- make sure to change to an actual database on your instance, not the master system database
--GO

-- Individual File Sizes and space available for current database  (Query 55) (File Sizes and Space)
SELECT f.name AS [File Name] , f.physical_name AS [Physical Name], 
CAST((f.size/128.0) AS DECIMAL(15,2)) AS [Total Size in MB],
CAST(f.size/128.0 - CAST(FILEPROPERTY(f.name, 'SpaceUsed') AS int)/128.0 AS DECIMAL(15,2)) 
AS [Available Space In MB], f.[file_id], fg.name AS [Filegroup Name],
f.is_percent_growth, f.growth, fg.is_default, fg.is_read_only, 
fg.is_autogrow_all_files
FROM sys.database_files AS f WITH (NOLOCK) 
LEFT OUTER JOIN sys.filegroups AS fg WITH (NOLOCK)
ON f.data_space_id = fg.data_space_id
ORDER BY f.[file_id] OPTION (RECOMPILE);
------

-- Look at how large and how full the files are and where they are located
-- Make sure the transaction log is not full!!

-- is_autogrow_all_files was new for SQL Server 2016. Equivalent to TF 1117 for user databases

-- SQL Server 2016: Changes in default behavior for autogrow and allocations for tempdb and user databases
-- https://bit.ly/2evRZSR


-- Log space usage for current database  (Query 56) (Log Space Usage)
SELECT DB_NAME(lsu.database_id) AS [Database Name], db.recovery_model_desc AS [Recovery Model],
		CAST(lsu.total_log_size_in_bytes/1048576.0 AS DECIMAL(10, 2)) AS [Total Log Space (MB)],
		CAST(lsu.used_log_space_in_bytes/1048576.0 AS DECIMAL(10, 2)) AS [Used Log Space (MB)], 
		CAST(lsu.used_log_space_in_percent AS DECIMAL(10, 2)) AS [Used Log Space %],
		CAST(lsu.log_space_in_bytes_since_last_backup/1048576.0 AS DECIMAL(10, 2)) AS [Used Log Space Since Last Backup (MB)],
		db.log_reuse_wait_desc		 
FROM sys.dm_db_log_space_usage AS lsu WITH (NOLOCK)
INNER JOIN sys.databases AS db WITH (NOLOCK)
ON lsu.database_id = db.database_id
OPTION (RECOMPILE);
------

-- Look at log file size and usage, along with the log reuse wait description for the current database

-- sys.dm_db_log_space_usage (Transact-SQL)
-- https://bit.ly/2H4MQw9


-- Status of last VLF for current database  (Query 57) (Last VLF Status)
SELECT TOP(1) DB_NAME(li.database_id) AS [Database Name], li.[file_id],
              li.vlf_size_mb, li.vlf_sequence_number, li.vlf_active, li.vlf_status
FROM sys.dm_db_log_info(DB_ID()) AS li 
ORDER BY vlf_sequence_number DESC OPTION (RECOMPILE);
------

-- Determine whether you will be able to shrink the transaction log file

-- vlf_status Values
-- 0 is inactive 
-- 1 is initialized but unused 
-- 2 is active

-- sys.dm_db_log_info (Transact-SQL)
-- https://bit.ly/2EQUU1v



-- Get database scoped configuration values for current database (Query 58) (Database-scoped Configurations)
SELECT configuration_id, name, [value] AS [value_for_primary], value_for_secondary
FROM sys.database_scoped_configurations WITH (NOLOCK) OPTION (RECOMPILE);
------

-- This lets you see the value of these new properties for the current database

-- Clear plan cache for current database
-- ALTER DATABASE SCOPED CONFIGURATION CLEAR PROCEDURE_CACHE;

-- ALTER DATABASE SCOPED CONFIGURATION (Transact-SQL)
-- https://bit.ly/2sOH7nb


-- I/O Statistics by file for the current database  (Query 59) (IO Stats By File)
SELECT DB_NAME(DB_ID()) AS [Database Name], df.name AS [Logical Name], vfs.[file_id], df.type_desc,
df.physical_name AS [Physical Name], CAST(vfs.size_on_disk_bytes/1048576.0 AS DECIMAL(10, 2)) AS [Size on Disk (MB)],
vfs.num_of_reads, vfs.num_of_writes, vfs.io_stall_read_ms, vfs.io_stall_write_ms,
CAST(100. * vfs.io_stall_read_ms/(vfs.io_stall_read_ms + vfs.io_stall_write_ms) AS DECIMAL(10,1)) AS [IO Stall Reads Pct],
CAST(100. * vfs.io_stall_write_ms/(vfs.io_stall_write_ms + vfs.io_stall_read_ms) AS DECIMAL(10,1)) AS [IO Stall Writes Pct],
(vfs.num_of_reads + vfs.num_of_writes) AS [Writes + Reads], 
CAST(vfs.num_of_bytes_read/1048576.0 AS DECIMAL(10, 2)) AS [MB Read], 
CAST(vfs.num_of_bytes_written/1048576.0 AS DECIMAL(10, 2)) AS [MB Written],
CAST(100. * vfs.num_of_reads/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(10,1)) AS [# Reads Pct],
CAST(100. * vfs.num_of_writes/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(10,1)) AS [# Write Pct],
CAST(100. * vfs.num_of_bytes_read/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(10,1)) AS [Read Bytes Pct],
CAST(100. * vfs.num_of_bytes_written/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(10,1)) AS [Written Bytes Pct]
FROM sys.dm_io_virtual_file_stats(DB_ID(), NULL) AS vfs
INNER JOIN sys.database_files AS df WITH (NOLOCK)
ON vfs.[file_id]= df.[file_id] OPTION (RECOMPILE);
------

-- This helps you characterize your workload better from an I/O perspective for this database
-- It helps you determine whether you has an OLTP or DW/DSS type of workload



-- Get most frequently executed queries for this database (Query 60) (Query Execution Counts)
SELECT TOP(50) LEFT(t.[text], 50) AS [Short Query Text], qs.execution_count AS [Execution Count],
qs.total_logical_reads AS [Total Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.total_worker_time AS [Total Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.total_elapsed_time AS [Total Elapsed Time],
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
qs.creation_time AS [Creation Time]
--,t.[text] AS [Complete Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
WHERE t.dbid = DB_ID()
ORDER BY qs.execution_count DESC OPTION (RECOMPILE);
------


-- Queries 61 through 66 are the "Bad Man List" for stored procedures

-- Top Cached SPs By Execution Count (Query 61) (SP Execution Counts)
SELECT TOP(100) p.name AS [SP Name], qs.execution_count AS [Execution Count],
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time],    
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.execution_count DESC OPTION (RECOMPILE);
------

-- Tells you which cached stored procedures are called the most often
-- This helps you characterize and baseline your workload


-- Top Cached SPs By Avg Elapsed Time (Query 62) (SP Avg Elapsed Time)
SELECT TOP(25) p.name AS [SP Name], qs.min_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time], 
qs.max_elapsed_time, qs.last_elapsed_time, qs.total_elapsed_time, qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute], 
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], 
qs.total_worker_time AS [TotalWorkerTime],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY avg_elapsed_time DESC OPTION (RECOMPILE);
------

-- This helps you find high average elapsed time cached stored procedures that
-- may be easy to optimize with standard query tuning techniques



-- Top Cached SPs By Total Worker time. Worker time relates to CPU cost  (Query 63) (SP Worker Time)
SELECT TOP(25) p.name AS [SP Name], qs.total_worker_time AS [TotalWorkerTime], 
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.total_worker_time DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a CPU perspective
-- You should look at this if you see signs of CPU pressure


-- Top Cached SPs By Total Logical Reads. Logical reads relate to memory pressure  (Query 64) (SP Logical Reads)
SELECT TOP(25) p.name AS [SP Name], qs.total_logical_reads AS [TotalLogicalReads], 
qs.total_logical_reads/qs.execution_count AS [AvgLogicalReads],qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute], 
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.total_logical_reads DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a memory perspective
-- You should look at this if you see signs of memory pressure


-- Top Cached SPs By Total Physical Reads. Physical reads relate to disk read I/O pressure  (Query 65) (SP Physical Reads)
SELECT TOP(25) p.name AS [SP Name],qs.total_physical_reads AS [TotalPhysicalReads], 
qs.total_physical_reads/qs.execution_count AS [AvgPhysicalReads], qs.execution_count, 
qs.total_logical_reads,qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan 
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND qs.total_physical_reads > 0
ORDER BY qs.total_physical_reads DESC, qs.total_logical_reads DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a read I/O perspective
-- You should look at this if you see signs of I/O pressure or of memory pressure
       


-- Top Cached SPs By Total Logical Writes (Query 66) (SP Logical Writes)
-- Logical writes relate to both memory and disk I/O pressure 
SELECT TOP(25) p.name AS [SP Name], qs.total_logical_writes AS [TotalLogicalWrites], 
qs.total_logical_writes/qs.execution_count AS [AvgLogicalWrites], qs.execution_count,
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan 
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND qs.total_logical_writes > 0
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.total_logical_writes DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a write I/O perspective
-- You should look at this if you see signs of I/O pressure or of memory pressure


-- Lists the top statements by average input/output usage for the current database  (Query 67) (Top IO Statements)
SELECT TOP(50) OBJECT_NAME(qt.objectid, dbid) AS [SP Name],
(qs.total_logical_reads + qs.total_logical_writes) /qs.execution_count AS [Avg IO], qs.execution_count AS [Execution Count],
SUBSTRING(qt.[text],qs.statement_start_offset/2, 
	(CASE 
		WHEN qs.statement_end_offset = -1 
	 THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2 
		ELSE qs.statement_end_offset 
	 END - qs.statement_start_offset)/2) AS [Query Text]	
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
WHERE qt.[dbid] = DB_ID()
ORDER BY [Avg IO] DESC OPTION (RECOMPILE);
------

-- Helps you find the most expensive statements for I/O by SP



-- Possible Bad NC Indexes (writes > reads)  (Query 68) (Bad NC Indexes)
SELECT OBJECT_NAME(s.[object_id]) AS [Table Name], i.name AS [Index Name], i.index_id, 
i.is_disabled, i.is_hypothetical, i.has_filter, i.fill_factor,
s.user_updates AS [Total Writes], s.user_seeks + s.user_scans + s.user_lookups AS [Total Reads],
s.user_updates - (s.user_seeks + s.user_scans + s.user_lookups) AS [Difference]
FROM sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON s.[object_id] = i.[object_id]
AND i.index_id = s.index_id
WHERE OBJECTPROPERTY(s.[object_id],'IsUserTable') = 1
AND s.database_id = DB_ID()
AND s.user_updates > (s.user_seeks + s.user_scans + s.user_lookups)
AND i.index_id > 1 AND i.[type_desc] = N'NONCLUSTERED'
AND i.is_primary_key = 0 AND i.is_unique_constraint = 0 AND i.is_unique = 0
ORDER BY [Difference] DESC, [Total Writes] DESC, [Total Reads] ASC OPTION (RECOMPILE);
------

-- Look for indexes with high numbers of writes and zero or very low numbers of reads
-- Consider your complete workload, and how long your instance has been running
-- Investigate further before dropping an index!


-- Missing Indexes for current database by Index Advantage  (Query 69) (Missing Indexes)
SELECT DISTINCT CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage], 
migs.last_user_seek, mid.[statement] AS [Database.Schema.Table],
mid.equality_columns, mid.inequality_columns, mid.included_columns,
migs.unique_compiles, migs.user_seeks, migs.avg_total_user_cost, migs.avg_user_impact,
OBJECT_NAME(mid.[object_id]) AS [Table Name], p.rows AS [Table Rows]
FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)
INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)
ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)
ON mig.index_handle = mid.index_handle
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON p.[object_id] = mid.[object_id]
WHERE mid.database_id = DB_ID()
AND p.index_id < 2 
ORDER BY index_advantage DESC OPTION (RECOMPILE);
------

-- Look at index advantage, last user seek time, number of user seeks to help determine source and importance
-- SQL Server is overly eager to add included columns, so beware
-- Do not just blindly add indexes that show up from this query!!!


-- Find missing index warnings for cached plans in the current database  (Query 70) (Missing Index Warnings)
-- Note: This query could take some time on a busy instance
SELECT TOP(25) OBJECT_NAME(objectid) AS [ObjectName], 
               cp.objtype, cp.usecounts, cp.size_in_bytes, query_plan
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) AS qp
WHERE CAST(query_plan AS NVARCHAR(MAX)) LIKE N'%MissingIndex%'
AND dbid = DB_ID()
ORDER BY cp.usecounts DESC OPTION (RECOMPILE);
------

-- Helps you connect missing indexes to specific stored procedures or queries
-- This can help you decide whether to add them or not


-- Breaks down buffers used by current database by object (table, index) in the buffer cache  (Query 71) (Buffer Usage)
-- Note: This query could take some time on a busy instance
SELECT OBJECT_NAME(p.[object_id]) AS [Object Name], p.index_id, 
CAST(COUNT(*)/128.0 AS DECIMAL(10, 2)) AS [Buffer size(MB)],  
COUNT(*) AS [BufferCount], p.[Rows] AS [Row Count],
p.data_compression_desc AS [Compression Type]
FROM sys.allocation_units AS a WITH (NOLOCK)
INNER JOIN sys.dm_os_buffer_descriptors AS b WITH (NOLOCK)
ON a.allocation_unit_id = b.allocation_unit_id
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON a.container_id = p.hobt_id
WHERE b.database_id = CONVERT(int, DB_ID())
AND p.[object_id] > 100
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'plan_%'
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'sys%'
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'xml_index_nodes%'
GROUP BY p.[object_id], p.index_id, p.data_compression_desc, p.[Rows]
ORDER BY [BufferCount] DESC OPTION (RECOMPILE);
------

-- Tells you what tables and indexes are using the most memory in the buffer cache
-- It can help identify possible candidates for data compression


-- Get Table names, row counts, and compression status for clustered index or heap  (Query 72) (Table Sizes)
SELECT SCHEMA_NAME(o.Schema_ID) AS [Schema Name], OBJECT_NAME(p.object_id) AS [ObjectName], 
SUM(p.Rows) AS [RowCount], data_compression_desc AS [CompressionType]
FROM sys.partitions AS p WITH (NOLOCK)
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON p.object_id = o.object_id
WHERE index_id < 2 --ignore the partitions from the non-clustered index if any
AND OBJECT_NAME(p.object_id) NOT LIKE N'sys%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'spt_%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'queue_%' 
AND OBJECT_NAME(p.object_id) NOT LIKE N'filestream_tombstone%' 
AND OBJECT_NAME(p.object_id) NOT LIKE N'fulltext%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'ifts_comp_fragment%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'filetable_updates%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'xml_index_nodes%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'sqlagent_job%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'plan_persist%'
GROUP BY  SCHEMA_NAME(o.Schema_ID), p.object_id, data_compression_desc
ORDER BY SUM(p.Rows) DESC OPTION (RECOMPILE);
------

-- Gives you an idea of table sizes, and possible data compression opportunities



-- Get some key table properties (Query 73) (Table Properties)
SELECT OBJECT_NAME(t.[object_id]) AS [ObjectName], p.[rows] AS [Table Rows], p.index_id, 
       p.data_compression_desc AS [Index Data Compression],
       t.create_date, t.lock_on_bulk_load, t.is_replicated, t.has_replication_filter, 
       t.is_tracked_by_cdc, t.lock_escalation_desc, t.is_filetable, 
	   t.is_memory_optimized, t.durability_desc, 
	   t.temporal_type_desc, t.is_remote_data_archive_enabled, t.is_external -- new for SQL Server 2016
FROM sys.tables AS t WITH (NOLOCK)
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON t.[object_id] = p.[object_id]
WHERE OBJECT_NAME(t.[object_id]) NOT LIKE N'sys%'
ORDER BY OBJECT_NAME(t.[object_id]), p.index_id OPTION (RECOMPILE);
------

-- Gives you some good information about your tables
-- is_memory_optimized and durability_desc were new in SQL Server 2014
-- temporal_type_desc, is_remote_data_archive_enabled, is_external were new in SQL Server 2016

-- sys.tables (Transact-SQL)
-- https://bit.ly/2Gk7998



-- When were Statistics last updated on all indexes?  (Query 74) (Statistics Update)
SELECT SCHEMA_NAME(o.Schema_ID) + N'.' + o.[NAME] AS [Object Name], o.[type_desc] AS [Object Type],
      i.[name] AS [Index Name], STATS_DATE(i.[object_id], i.index_id) AS [Statistics Date], 
      s.auto_created, s.no_recompute, s.user_created, s.is_incremental, s.is_temporary,
	  st.row_count, st.used_page_count
FROM sys.objects AS o WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON o.[object_id] = i.[object_id]
INNER JOIN sys.stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id] 
AND i.index_id = s.stats_id
INNER JOIN sys.dm_db_partition_stats AS st WITH (NOLOCK)
ON o.[object_id] = st.[object_id]
AND i.[index_id] = st.[index_id]
WHERE o.[type] IN ('U', 'V')
AND st.row_count > 0
ORDER BY STATS_DATE(i.[object_id], i.index_id) DESC OPTION (RECOMPILE);
------  

-- Helps discover possible problems with out-of-date statistics
-- Also gives you an idea which indexes are the most active

-- sys.stats (Transact-SQL)
-- https://bit.ly/2GyAxrn

-- UPDATEs to Statistics (Erin Stellato)
-- https://bit.ly/2vhrYQy




-- Look at most frequently modified indexes and statistics (Query 75) (Volatile Indexes)
SELECT o.[name] AS [Object Name], o.[object_id], o.[type_desc], s.[name] AS [Statistics Name], 
       s.stats_id, s.no_recompute, s.auto_created, s.is_incremental, s.is_temporary,
	   sp.modification_counter, sp.[rows], sp.rows_sampled, sp.last_updated
FROM sys.objects AS o WITH (NOLOCK)
INNER JOIN sys.stats AS s WITH (NOLOCK)
ON s.object_id = o.object_id
CROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) AS sp
WHERE o.[type_desc] NOT IN (N'SYSTEM_TABLE', N'INTERNAL_TABLE')
AND sp.modification_counter > 0
ORDER BY sp.modification_counter DESC, o.name OPTION (RECOMPILE);
------

-- This helps you understand your workload and make better decisions about 
-- things like data compression and adding new indexes to a table



-- Get fragmentation info for all indexes above a certain size in the current database  (Query 76) (Index Fragmentation)
-- Note: This query could take some time on a very large database
SELECT DB_NAME(ps.database_id) AS [Database Name], SCHEMA_NAME(o.[schema_id]) AS [Schema Name],
OBJECT_NAME(ps.OBJECT_ID) AS [Object Name], i.[name] AS [Index Name], ps.index_id, 
ps.index_type_desc, ps.avg_fragmentation_in_percent, 
ps.fragment_count, ps.page_count, i.fill_factor, i.has_filter, 
i.filter_definition, i.[allow_page_locks]
FROM sys.dm_db_index_physical_stats(DB_ID(),NULL, NULL, NULL , N'LIMITED') AS ps
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ps.[object_id] = i.[object_id] 
AND ps.index_id = i.index_id
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON i.[object_id] = o.[object_id]
WHERE ps.database_id = DB_ID()
AND ps.page_count > 2500
ORDER BY ps.avg_fragmentation_in_percent DESC OPTION (RECOMPILE);
------

-- Helps determine whether you have framentation in your relational indexes
-- and how effective your index maintenance strategy is


--- Index Read/Write stats (all tables in current DB) ordered by Reads  (Query 77) (Overall Index Usage - Reads)
SELECT OBJECT_NAME(i.[object_id]) AS [ObjectName], i.[name] AS [IndexName], i.index_id, 
       s.user_seeks, s.user_scans, s.user_lookups,
	   s.user_seeks + s.user_scans + s.user_lookups AS [Total Reads], 
	   s.user_updates AS [Writes],  
	   i.[type_desc] AS [Index Type], i.fill_factor AS [Fill Factor], i.has_filter, i.filter_definition, 
	   s.last_user_scan, s.last_user_lookup, s.last_user_seek
FROM sys.indexes AS i WITH (NOLOCK)
LEFT OUTER JOIN sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id]
AND i.index_id = s.index_id
AND s.database_id = DB_ID()
WHERE OBJECTPROPERTY(i.[object_id],'IsUserTable') = 1
ORDER BY s.user_seeks + s.user_scans + s.user_lookups DESC OPTION (RECOMPILE); -- Order by reads
------

-- Show which indexes in the current database are most active for Reads


--- Index Read/Write stats (all tables in current DB) ordered by Writes  (Query 78) (Overall Index Usage - Writes)
SELECT OBJECT_NAME(i.[object_id]) AS [ObjectName], i.[name] AS [IndexName], i.index_id,
	   s.user_updates AS [Writes], s.user_seeks + s.user_scans + s.user_lookups AS [Total Reads], 
	   i.[type_desc] AS [Index Type], i.fill_factor AS [Fill Factor], i.has_filter, i.filter_definition,
	   s.last_system_update, s.last_user_update
FROM sys.indexes AS i WITH (NOLOCK)
LEFT OUTER JOIN sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id]
AND i.index_id = s.index_id
AND s.database_id = DB_ID()
WHERE OBJECTPROPERTY(i.[object_id],'IsUserTable') = 1
ORDER BY s.user_updates DESC OPTION (RECOMPILE);						 -- Order by writes
------

-- Show which indexes in the current database are most active for Writes


-- Get in-memory OLTP index usage (Query 79) (XTP Index Usage)
SELECT OBJECT_NAME(i.[object_id]) AS [Object Name], i.index_id, i.[name] AS [Index Name],
       i.[type_desc], xis.scans_started, xis.scans_retries, 
	   xis.rows_touched, xis.rows_returned
FROM sys.dm_db_xtp_index_stats AS xis WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON i.[object_id] = xis.[object_id] 
AND i.index_id = xis.index_id 
ORDER BY OBJECT_NAME(i.[object_id]) OPTION (RECOMPILE);
------

-- This gives you some index usage statistics for in-memory OLTP
-- Returns no data if you are not using in-memory OLTP

-- Guidelines for Using Indexes on Memory-Optimized Tables
-- https://bit.ly/2GCP8lF



-- Look at Columnstore index physical statistics (Query 80) (Columnstore Index Physical Stat)
SELECT OBJECT_NAME(ps.object_id) AS [TableName],  
	i.[name] AS [IndexName], ps.index_id, ps.partition_number,
	ps.delta_store_hobt_id, ps.state_desc, ps.total_rows, ps.size_in_bytes,
	ps.trim_reason_desc, ps.generation, ps.transition_to_compressed_state_desc,
	ps.has_vertipaq_optimization, ps.deleted_rows,
	100 * (ISNULL(ps.deleted_rows, 0))/ps.total_rows AS [Fragmentation]
FROM sys.dm_db_column_store_row_group_physical_stats AS ps WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ps.object_id = i.object_id 
AND ps.index_id = i.index_id
ORDER BY ps.object_id, ps.partition_number, ps.row_group_id OPTION (RECOMPILE);
------

-- sys.dm_db_column_store_row_group_physical_stats (Transact-SQL)
-- https://bit.ly/2q276XQ



-- Get lock waits for current database (Query 81) (Lock Waits)
SELECT o.name AS [table_name], i.name AS [index_name], ios.index_id, ios.partition_number,
		SUM(ios.row_lock_wait_count) AS [total_row_lock_waits], 
		SUM(ios.row_lock_wait_in_ms) AS [total_row_lock_wait_in_ms],
		SUM(ios.page_lock_wait_count) AS [total_page_lock_waits],
		SUM(ios.page_lock_wait_in_ms) AS [total_page_lock_wait_in_ms],
		SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) AS [total_lock_wait_in_ms]
FROM sys.dm_db_index_operational_stats(DB_ID(), NULL, NULL, NULL) AS ios
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON ios.[object_id] = o.[object_id]
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ios.[object_id] = i.[object_id] 
AND ios.index_id = i.index_id
WHERE o.[object_id] > 100
GROUP BY o.name, i.name, ios.index_id, ios.partition_number
HAVING SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) > 0
ORDER BY total_lock_wait_in_ms DESC OPTION (RECOMPILE);
------

-- This query is helpful for troubleshooting blocking and deadlocking issues



-- Look at UDF execution statistics (Query 82) (UDF Statistics)
SELECT OBJECT_NAME(object_id) AS [Function Name], execution_count,
	   total_worker_time, total_logical_reads, total_physical_reads, total_elapsed_time, 
	   total_elapsed_time/execution_count AS [avg_elapsed_time],
	   FORMAT(cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
FROM sys.dm_exec_function_stats WITH (NOLOCK) 
WHERE database_id = DB_ID()
ORDER BY total_worker_time DESC OPTION (RECOMPILE); 
------

-- New for SQL Server 2016
-- Helps you investigate scalar UDF performance issues
-- Does not return information for table valued functions

-- sys.dm_exec_function_stats (Transact-SQL)
-- https://bit.ly/2q1Q6BM


-- Determine which scalar UDFs are in-lineable (Query 83) (Inlineable UDFs)
SELECT OBJECT_NAME(m.object_id) AS [Function Name], is_inlineable, inline_type
FROM sys.sql_modules AS m WITH (NOLOCK) 
LEFT OUTER JOIN sys.dm_exec_function_stats AS efs WITH (NOLOCK)
ON  m.object_id = efs.object_id
WHERE efs.type_desc = N'SQL_SCALAR_FUNCTION'
OPTION (RECOMPILE);
------

-- Scalar UDF Inlining
-- https://bit.ly/2JU971M

-- sys.sql_modules (Transact-SQL)
-- https://bit.ly/2Qt216S


-- Get QueryStore Options for this database (Query 84) (QueryStore Options)
SELECT actual_state_desc, desired_state_desc, [interval_length_minutes],
       current_storage_size_mb, [max_storage_size_mb], 
	   query_capture_mode_desc, size_based_cleanup_mode_desc
FROM sys.database_query_store_options WITH (NOLOCK) OPTION (RECOMPILE);
------

-- New for SQL Server 2016
-- Requires that Query Store is enabled for this database

-- Make sure that the actual_state_desc is the same as desired_state_desc
-- Make sure that the current_storage_size_mb is less than the max_storage_size_mb

-- Tuning Workload Performance with Query Store
-- https://bit.ly/1kHSl7w


-- Get highest aggregate duration queries over last hour (Query 85) (High Aggregate Duration Queries)
WITH AggregatedDurationLastHour
AS
(SELECT q.query_id, SUM(rs.count_executions * rs.avg_duration) AS total_duration,
   COUNT (DISTINCT p.plan_id) AS number_of_plans
   FROM sys.query_store_query_text AS qt WITH (NOLOCK)
   INNER JOIN sys.query_store_query AS q WITH (NOLOCK)
   ON qt.query_text_id = q.query_text_id
   INNER JOIN sys.query_store_plan AS p WITH (NOLOCK)
   ON q.query_id = p.query_id
   INNER JOIN sys.query_store_runtime_stats AS rs WITH (NOLOCK)
   ON rs.plan_id = p.plan_id
   INNER JOIN sys.query_store_runtime_stats_interval AS rsi WITH (NOLOCK)
   ON rsi.runtime_stats_interval_id = rs.runtime_stats_interval_id
   WHERE rsi.start_time >= DATEADD(hour, -1, GETUTCDATE()) 
   AND rs.execution_type_desc = N'Regular'
   GROUP BY q.query_id), OrderedDuration 
AS
(SELECT query_id, total_duration, number_of_plans, 
 ROW_NUMBER () OVER (ORDER BY total_duration DESC, query_id) AS RN
 FROM AggregatedDurationLastHour)
SELECT OBJECT_NAME(q.object_id) AS [Containing Object], qt.query_sql_text, 
od.total_duration AS [Total Duration (microsecs)], 
od.number_of_plans AS [Plan Count],
p.is_forced_plan, p.is_parallel_plan, p.is_trivial_plan,
q.query_parameterization_type_desc, p.[compatibility_level],
p.last_compile_start_time, 
q.last_execution_time,
CONVERT(xml, p.query_plan) AS query_plan_xml 
FROM OrderedDuration AS od 
INNER JOIN sys.query_store_query AS q WITH (NOLOCK)
ON q.query_id  = od.query_id
INNER JOIN sys.query_store_query_text AS qt WITH (NOLOCK)
ON q.query_text_id = qt.query_text_id
INNER JOIN sys.query_store_plan AS p WITH (NOLOCK)
ON q.query_id = p.query_id
WHERE od.RN <= 50 
ORDER BY od.total_duration DESC OPTION (RECOMPILE);
------

-- New for SQL Server 2016
-- Requires that QueryStore is enabled for this database



-- Get highest aggregate CPU time queries over last hour (Query 86) (High Aggregate CPU Queries)
WITH AggregatedCPULastHour
AS
(SELECT q.query_id, SUM(rs.count_executions * rs.avg_cpu_time) AS total_cpu_time,
   COUNT (DISTINCT p.plan_id) AS number_of_plans
   FROM sys.query_store_query_text AS qt WITH (NOLOCK)
   INNER JOIN sys.query_store_query AS q WITH (NOLOCK)
   ON qt.query_text_id = q.query_text_id
   INNER JOIN sys.query_store_plan AS p WITH (NOLOCK)
   ON q.query_id = p.query_id
   INNER JOIN sys.query_store_runtime_stats AS rs WITH (NOLOCK)
   ON rs.plan_id = p.plan_id
   INNER JOIN sys.query_store_runtime_stats_interval AS rsi WITH (NOLOCK)
   ON rsi.runtime_stats_interval_id = rs.runtime_stats_interval_id
   WHERE rsi.start_time >= DATEADD(hour, -1, GETUTCDATE()) 
   AND rs.execution_type_desc = N'Regular'
   GROUP BY q.query_id), OrderedDuration 
AS
(SELECT query_id, total_cpu_time, number_of_plans, 
 ROW_NUMBER () OVER (ORDER BY total_cpu_time DESC, query_id) AS RN
 FROM AggregatedCPULastHour)
SELECT OBJECT_NAME(q.object_id) AS [Containing Object], qt.query_sql_text, 
od.total_cpu_time AS [Total CPU Time (microsecs)], 
od.number_of_plans AS [Plan Count],
p.is_forced_plan, p.is_parallel_plan, p.is_trivial_plan,
q.query_parameterization_type_desc, p.[compatibility_level],
p.last_compile_start_time, 
q.last_execution_time,
CONVERT(xml, p.query_plan) AS query_plan_xml 
FROM OrderedDuration AS od 
INNER JOIN sys.query_store_query AS q WITH (NOLOCK)
ON q.query_id  = od.query_id
INNER JOIN sys.query_store_query_text AS qt WITH (NOLOCK)
ON q.query_text_id = qt.query_text_id
INNER JOIN sys.query_store_plan AS p WITH (NOLOCK)
ON q.query_id = p.query_id
WHERE od.RN <= 50 
ORDER BY od.total_cpu_time DESC OPTION (RECOMPILE);
------

-- New for SQL Server 2016
-- Requires that QueryStore is enabled for this database


-- Get input buffer information for the current database (Query 87) (Input Buffer)
SELECT es.session_id, DB_NAME(es.database_id) AS [Database Name],
       es.login_time, es.cpu_time, es.logical_reads, es.memory_usage,
       es.[status], ib.event_info AS [Input Buffer]
FROM sys.dm_exec_sessions AS es WITH (NOLOCK)
CROSS APPLY sys.dm_exec_input_buffer(es.session_id, NULL) AS ib
WHERE es.database_id = DB_ID()
AND es.session_id > 50
AND es.session_id <> @@SPID OPTION (RECOMPILE);
------

-- Gives you input buffer information from all non-system sessions for the current database
-- Replaces DBCC INPUTBUFFER

-- New DMF for retrieving input buffer in SQL Server
-- https://bit.ly/2uHKMbz

-- sys.dm_exec_input_buffer (Transact-SQL)
-- https://bit.ly/2J5Hf9q



-- Get any resumable index rebuild operation information (Query 88) (Resumable Index Rebuild)
SELECT OBJECT_NAME(iro.object_id) AS [Object Name], iro.index_id, iro.name AS [Index Name],
       iro.sql_text, iro.last_max_dop_used, iro.partition_number, iro.state_desc, iro.start_time, iro.percent_complete
FROM  sys.index_resumable_operations AS iro WITH (NOLOCK)
OPTION (RECOMPILE);
------ 

-- index_resumable_operations (Transact-SQL)
-- https://bit.ly/2pYSWqq


-- Get database automatic tuning options (Query 89) (Automatic Tuning Options)
SELECT [name], desired_state_desc, actual_state_desc, reason_desc
FROM sys.database_automatic_tuning_options WITH (NOLOCK)
OPTION (RECOMPILE);
------ 

-- sys.database_automatic_tuning_options (Transact-SQL)
-- https://bit.ly/2FHhLkL



-- Look at recent Full backups for the current database (Query 90) (Recent Full Backups)
SELECT TOP (30) bs.machine_name, bs.server_name, bs.database_name AS [Database Name], bs.recovery_model,
CONVERT (BIGINT, bs.backup_size / 1048576 ) AS [Uncompressed Backup Size (MB)],
CONVERT (BIGINT, bs.compressed_backup_size / 1048576 ) AS [Compressed Backup Size (MB)],
CONVERT (NUMERIC (20,2), (CONVERT (FLOAT, bs.backup_size) /
CONVERT (FLOAT, bs.compressed_backup_size))) AS [Compression Ratio], bs.has_backup_checksums, bs.is_copy_only, bs.encryptor_type,
DATEDIFF (SECOND, bs.backup_start_date, bs.backup_finish_date) AS [Backup Elapsed Time (sec)],
bs.backup_finish_date AS [Backup Finish Date], bmf.physical_device_name AS [Backup Location], bmf.physical_block_size
FROM msdb.dbo.backupset AS bs WITH (NOLOCK)
INNER JOIN msdb.dbo.backupmediafamily AS bmf WITH (NOLOCK)
ON bs.media_set_id = bmf.media_set_id  
WHERE bs.database_name = DB_NAME(DB_ID())
AND bs.[type] = 'D' -- Change to L if you want Log backups
ORDER BY bs.backup_finish_date DESC OPTION (RECOMPILE);
------

-- Are your backup sizes and times changing over time?
-- Are you using backup compression?
-- Are you using backup checksums?
-- Are you doing copy_only backups?
-- Are you doing encrypted backups?
-- Have you done any backup tuning with striped backups, or changing the parameters of the backup command?

-- In SQL Server 2016, native SQL Server backup compression actually works 
-- much better with databases that are using TDE than in previous versions
-- https://bit.ly/28Rpb2x


-- These four Pluralsight Courses go into more detail about how to run these queries and interpret the results

-- SQL Server 2017: Diagnosing Configuration Issues with DMVs
-- https://bit.ly/2MSUDUL

-- SQL Server 2014 DMV Diagnostic Queries � Part 1 
-- https://bit.ly/2plxCer

-- SQL Server 2014 DMV Diagnostic Queries � Part 2
-- https://bit.ly/2IuJpzI

-- SQL Server 2014 DMV Diagnostic Queries � Part 3
-- https://bit.ly/2FIlCPb



-- Sign up for Microsoft Visual Studio Dev Essentials and get a free three month pass to Pluralsight

-- Microsoft Visual Studio Dev Essentials
-- http://bit.ly/1q6xbDL


-- Sign up for Microsoft Azure Essentials and get lots of free Azure usage credits, MCP exam voucher, three month Pluralsight subscription

-- Microsoft Azure Essentials
-- https://bit.ly/2JMWe8x


-- August 2017 blog series about upgrading and migrating to SQL Server 2016/2017
-- https://bit.ly/2ftKVrX
tools\dbatools\bin\diagnosticquery\SQLServerDiagnosticQueries_AzureSQLDatabase_201811.sql

-- Azure SQL Database Diagnostic Information Queries
-- Glenn Berry 
-- Last Modified: January 7, 2019
-- https://www.sqlskills.com/blogs/glenn/
-- http://sqlserverperformance.wordpress.com/
-- Twitter: GlennAlanBerry

-- Please listen to my Pluralsight courses
-- https://www.pluralsight.com/author/glenn-berry

-- If you want to find all of our SQLskills SQL101 blog posts, check out https://www.sqlskills.com/help/sql101/



--******************************************************************************
--*   Copyright (C) 2019 Glenn Berry, SQLskills.com
--*   All rights reserved. 
--*
--*   For more scripts and sample code, check out 
--*      https://www.sqlskills.com/blogs/glenn
--*
--*   You may alter this code for your own *non-commercial* purposes. You may
--*   republish altered code as long as you include this copyright and give due credit. 
--*
--*
--*   THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF 
--*   ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED 
--*   TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
--*   PARTICULAR PURPOSE. 
--*
--******************************************************************************

-- Make sure you are connected a user database, rather than the master system database


-- Server level queries *******************************

-- SQL and OS Version information for current instance  (Query 1) (Version Info)
SELECT @@SERVERNAME AS [Server Name], @@VERSION AS [SQL Server and OS Version Info];
------

-- Azure SQL Database does not expose as much information as on-premises SQL Server does
													


-- Get logical instance-level configuration values for instance  (Query 2) (Configuration Values)
SELECT name, value, value_in_use, minimum, maximum, [description], is_dynamic, is_advanced
FROM sys.configurations WITH (NOLOCK)
ORDER BY name OPTION (RECOMPILE);
------

-- All of these settings are read-only in Azure SQL Database, so they are informational only



-- SQL Server NUMA Node information  (Query 3) (SQL Server NUMA Info)
SELECT node_id, node_state_desc, memory_node_id, processor_group, cpu_count, online_scheduler_count, 
       idle_scheduler_count, active_worker_count, avg_load_balance, resource_monitor_state
FROM sys.dm_os_nodes WITH (NOLOCK) 
WHERE node_state_desc <> N'ONLINE DAC' OPTION (RECOMPILE);
------

-- Gives you some useful information about the composition and relative load on your NUMA nodes
-- You want to see an equal number of schedulers on each NUMA node



-- Calculates average stalls per read, per write, and per total input/output for each database file  (Query 4) (IO Stalls by File)
SELECT DB_NAME(fs.database_id) AS [Database Name], CAST(fs.io_stall_read_ms/(1.0 + fs.num_of_reads) AS NUMERIC(16,1)) AS [avg_read_stall_ms],
CAST(fs.io_stall_write_ms/(1.0 + fs.num_of_writes) AS NUMERIC(16,1)) AS [avg_write_stall_ms],
CAST((fs.io_stall_read_ms + fs.io_stall_write_ms)/(1.0 + fs.num_of_reads + fs.num_of_writes) AS NUMERIC(16,1)) AS [avg_io_stall_ms],
fs.io_stall_read_ms, fs.num_of_reads, 
fs.io_stall_write_ms, fs.num_of_writes, fs.io_stall_read_ms + fs.io_stall_write_ms AS [io_stalls], fs.num_of_reads + fs.num_of_writes AS [total_io],
io_stall_queued_read_ms AS [Resource Governor Total Read IO Latency (ms)], io_stall_queued_write_ms AS [Resource Governor Total Write IO Latency (ms)]
FROM sys.dm_io_virtual_file_stats(null,null) AS fs
ORDER BY avg_io_stall_ms DESC OPTION (RECOMPILE);
------

-- Helps determine which database files on the entire instance have the most I/O bottlenecks
-- This can help you decide whether certain LUNs are overloaded and whether you might
-- want to move some files to a different location or perhaps improve your I/O performance
-- These latency numbers include all file activity against each SQL Server 
-- database file since SQL Server was last started



-- Get I/O utilization by database (Query 5) (IO Usage By Database)
WITH Aggregate_IO_Statistics
AS
(SELECT DB_NAME(database_id) AS [Database Name],
CAST(SUM(num_of_bytes_read + num_of_bytes_written)/1048576 AS DECIMAL(12, 2)) AS io_in_mb
FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS [DM_IO_STATS]
WHERE database_id NOT IN (4, 5, 32767)
GROUP BY database_id)
SELECT ROW_NUMBER() OVER(ORDER BY io_in_mb DESC) AS [I/O Rank], [Database Name], 
      CAST(io_in_mb/ SUM(io_in_mb) OVER() * 100.0 AS DECIMAL(5,2)) AS [I/O Percent],
      io_in_mb AS [Total I/O (MB)]     
FROM Aggregate_IO_Statistics
ORDER BY [I/O Rank] OPTION (RECOMPILE);
------

-- Helps determine which database is using the most I/O resources on the instance


-- Get total buffer usage by database for current instance  (Query 6) (Total Buffer Usage by Database)
-- This make take some time to run on a busy instance
WITH AggregateBufferPoolUsage
AS
(SELECT DB_NAME(database_id) AS [Database Name], COUNT(page_id) AS [Page Count],
CAST(COUNT(*) * 8/1024.0 AS DECIMAL (10,2))  AS [CachedSize],
AVG(read_microsec) AS [Avg Read Time (microseconds)]
FROM sys.dm_os_buffer_descriptors WITH (NOLOCK)
WHERE database_id NOT IN (4, 5, 32767)
GROUP BY DB_NAME(database_id))
SELECT ROW_NUMBER() OVER(ORDER BY CachedSize DESC) AS [Buffer Pool Rank], [Database Name], 
       CAST(CachedSize / SUM(CachedSize) OVER() * 100.0 AS DECIMAL(5,2)) AS [Buffer Pool Percent],
       [Page Count], CachedSize AS [Cached Size (MB)], [Avg Read Time (microseconds)]
FROM AggregateBufferPoolUsage
ORDER BY [Buffer Pool Rank] OPTION (RECOMPILE);
------

-- Tells you how much memory (in the buffer pool) 
-- is being used by each database on the instance



-- Get a count of SQL connections by IP address (Query 7) (Connection Counts by IP Address)    
SELECT ec.client_net_address, es.[program_name], es.[host_name], es.login_name, 
COUNT(ec.session_id) AS [connection count] 
FROM sys.dm_exec_sessions AS es WITH (NOLOCK) 
INNER JOIN sys.dm_exec_connections AS ec WITH (NOLOCK) 
ON es.session_id = ec.session_id 
GROUP BY ec.client_net_address, es.[program_name], es.[host_name], es.login_name  
ORDER BY ec.client_net_address, es.[program_name] OPTION (RECOMPILE);
------

-- This helps you figure where your database load is coming from
-- and verifies connectivity from other machines

-- Solving Connectivity errors to SQL Server
-- https://bit.ly/2EgzoD0



-- Get Average Task Counts (run multiple times)  (Query 8) (Avg Task Counts)
SELECT AVG(current_tasks_count) AS [Avg Task Count], 
AVG(work_queue_count) AS [Avg Work Queue Count],
AVG(runnable_tasks_count) AS [Avg Runnable Task Count],
AVG(pending_disk_io_count) AS [Avg Pending DiskIO Count]
FROM sys.dm_os_schedulers WITH (NOLOCK)
WHERE scheduler_id < 255 OPTION (RECOMPILE);
------

-- Sustained values above 10 suggest further investigation in that area (depending on your Service Tier)
-- Avg Task Counts will be higher with lower service tiers
-- High Avg Task Counts are often caused by blocking/deadlocking or other resource contention

-- Sustained values above 1 suggest further investigation in that area
-- High Avg Runnable Task Counts are a good sign of CPU pressure
-- High Avg Pending DiskIO Counts are a sign of disk pressure



-- Detect blocking (run multiple times)  (Query 9) (Detect Blocking)						
SELECT t1.resource_type AS [lock type], DB_NAME(resource_database_id) AS [database],
t1.resource_associated_entity_id AS [blk object],t1.request_mode AS [lock req],  -- lock requested
t1.request_session_id AS [waiter sid], t2.wait_duration_ms AS [wait time],       -- spid of waiter  
(SELECT [text] FROM sys.dm_exec_requests AS r WITH (NOLOCK)                      -- get sql for waiter
CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) 
WHERE r.session_id = t1.request_session_id) AS [waiter_batch],
(SELECT SUBSTRING(qt.[text],r.statement_start_offset/2, 
    (CASE WHEN r.statement_end_offset = -1 
    THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2 
    ELSE r.statement_end_offset END - r.statement_start_offset)/2) 
FROM sys.dm_exec_requests AS r WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) AS qt
WHERE r.session_id = t1.request_session_id) AS [waiter_stmt],					-- statement blocked
t2.blocking_session_id AS [blocker sid],										-- spid of blocker
(SELECT [text] FROM sys.sysprocesses AS p										-- get sql for blocker
CROSS APPLY sys.dm_exec_sql_text(p.[sql_handle]) 
WHERE p.spid = t2.blocking_session_id) AS [blocker_batch]
FROM sys.dm_tran_locks AS t1 WITH (NOLOCK)
INNER JOIN sys.dm_os_waiting_tasks AS t2 WITH (NOLOCK)
ON t1.lock_owner_address = t2.resource_address OPTION (RECOMPILE);
------

-- Helps troubleshoot blocking and deadlocking issues
-- The results will change from second to second on a busy system
-- You should run this query multiple times when you see signs of blocking



-- Page Life Expectancy (PLE) value for each NUMA node in current instance  (Query 10) (PLE by NUMA Node)
SELECT @@SERVERNAME AS [Server Name], RTRIM([object_name]) AS [Object Name], instance_name, cntr_value AS [Page Life Expectancy]
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Buffer Node%' -- Handles named instances
AND counter_name = N'Page life expectancy' OPTION (RECOMPILE);
------

-- PLE is a good measurement of internal memory pressure
-- Higher PLE is better. Watch the trend over time, not the absolute value
-- This will only return one row for non-NUMA systems

-- Page Life Expectancy isn�t what you think�
-- https://bit.ly/2EgynLa


-- Memory Grants Pending value for current instance  (Query 11) (Memory Grants Pending)
SELECT @@SERVERNAME AS [Server Name], RTRIM([object_name]) AS [Object Name], cntr_value AS [Memory Grants Pending]                                                                                                       
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Memory Manager%' -- Handles named instances
AND counter_name = N'Memory Grants Pending' OPTION (RECOMPILE);
------

-- Run multiple times, and run periodically if you suspect you are under memory pressure
-- Memory Grants Pending above zero for a sustained period is a very strong indicator of internal memory pressure


-- Memory Clerk Usage for instance  (Query 12) (Memory Clerk Usage)
-- Look for high value for CACHESTORE_SQLCP (Ad-hoc query plans)
SELECT TOP(10) mc.[type] AS [Memory Clerk Type], 
       CAST((SUM(mc.pages_kb)/1024.0) AS DECIMAL (15,2)) AS [Memory Usage (MB)] 
FROM sys.dm_os_memory_clerks AS mc WITH (NOLOCK)
GROUP BY mc.[type]  
ORDER BY SUM(mc.pages_kb) DESC OPTION (RECOMPILE);
------

-- MEMORYCLERK_SQLBUFFERPOOL was new for SQL Server 2012. It should be your highest consumer of memory

-- CACHESTORE_SQLCP  SQL Plans         
-- These are cached SQL statements or batches that aren't in stored procedures, functions and triggers
-- Watch out for high values for CACHESTORE_SQLCP
-- Enabling 'optimize for ad hoc workloads' at the instance level can help reduce this


-- CACHESTORE_OBJCP  Object Plans      
-- These are compiled plans for stored procedures, functions and triggers



-- Find single-use, ad-hoc and prepared queries that are bloating the plan cache  (Query 13) (Ad hoc Queries)   
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], t.[text] AS [Query Text], 
cp.objtype AS [Object Type], cp.cacheobjtype AS [Cache Object Type],  
cp.size_in_bytes/1024 AS [Plan Size in KB]
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t
WHERE cp.cacheobjtype = N'Compiled Plan' 
AND cp.objtype IN (N'Adhoc', N'Prepared') 
AND cp.usecounts = 1
ORDER BY cp.size_in_bytes DESC, DB_NAME(t.[dbid]) OPTION (RECOMPILE);
------

-- Gives you the text, type and size of single-use ad-hoc and prepared queries that waste space in the plan cache
-- Enabling forced parameterization for the database can help, but test first!

-- Plan cache, adhoc workloads and clearing the single-use plan cache bloat
-- https://bit.ly/2EfYOkl






-- Database specific queries *****************************************************************


-- Azure SQL Database size  (Query 14) (Azure SQL DB Size)
SELECT CAST(SUM(CAST(FILEPROPERTY(name, 'SpaceUsed') AS bigint) * 8192.) / 1024 / 1024 AS DECIMAL(15,2)) AS [Database Size In MB],
       CAST(SUM(CAST(FILEPROPERTY(name, 'SpaceUsed') AS bigint) * 8192.) / 1024 / 1024 / 1024 AS DECIMAL(15,2)) AS [Database Size In GB]
FROM sys.database_files WITH (NOLOCK)
WHERE [type_desc] = N'ROWS' OPTION (RECOMPILE);
------

-- This gives you the actual space usage within the data file only, to match what the Azure portal shows for the database size

-- Determining Database Size in Azure SQL Database V12
-- https://bit.ly/2JjrqNh



-- Individual File Sizes and space available for current database  (Query 15) (File Sizes and Space)
SELECT f.name AS [File Name] , f.physical_name AS [Physical Name], 
CAST((f.size/128.0) AS DECIMAL(15,2)) AS [Total Size in MB],
CAST(f.size/128.0 - CAST(FILEPROPERTY(f.name, 'SpaceUsed') AS int)/128.0 AS DECIMAL(15,2)) 
AS [Available Space In MB], f.[file_id], fg.name AS [Filegroup Name],
f.is_percent_growth, f.growth, fg.is_default, fg.is_read_only, 
fg.is_autogrow_all_files
FROM sys.database_files AS f WITH (NOLOCK) 
LEFT OUTER JOIN sys.filegroups AS fg WITH (NOLOCK)
ON f.data_space_id = fg.data_space_id
ORDER BY f.[file_id] OPTION (RECOMPILE);
------

-- Look at how large and how full the files are and where they are located

-- is_autogrow_all_files was new for SQL Server 2016. Equivalent to TF 1117 for user databases

-- SQL Server 2016: Changes in default behavior for autogrow and allocations for tempdb and user databases
-- http://bit.ly/2evRZSR



-- Log space usage for current database  (Query 16) (Log Space Usage)
SELECT DB_NAME(lsu.database_id) AS [Database Name], db.recovery_model_desc AS [Recovery Model],
		CAST(lsu.total_log_size_in_bytes/1048576.0 AS DECIMAL(10, 2)) AS [Total Log Space (MB)],
		CAST(lsu.used_log_space_in_bytes/1048576.0 AS DECIMAL(10, 2)) AS [Used Log Space (MB)], 
		CAST(lsu.used_log_space_in_percent AS DECIMAL(10, 2)) AS [Used Log Space %],
		CAST(lsu.log_space_in_bytes_since_last_backup/1048576.0 AS DECIMAL(10, 2)) AS [Used Log Space Since Last Backup (MB)],
		db.log_reuse_wait_desc		 
FROM sys.dm_db_log_space_usage AS lsu WITH (NOLOCK)
INNER JOIN sys.databases AS db WITH (NOLOCK)
ON lsu.database_id = db.database_id
OPTION (RECOMPILE);
------

-- Look at log file size and usage, along with the log reuse wait description for the current database


-- Get VLF Counts for current database (Query 17) (VLF Counts)
SELECT [name] AS [Database Name], [VLF Count]
FROM sys.databases AS db WITH (NOLOCK)
CROSS APPLY (SELECT file_id, COUNT(*) AS [VLF Count]
		     FROM sys.dm_db_log_info(db.database_id)
			 GROUP BY file_id) AS li
WHERE [name] <> N'master'
ORDER BY [VLF Count] DESC OPTION (RECOMPILE);
------

-- High VLF counts can affect write performance to the log file
-- and they can make full database restores and crash recovery take much longer
-- Try to keep your VLF counts under 200 in most cases (depending on log file size)

-- Important change to VLF creation algorithm in SQL Server 2014
-- https://bit.ly/2Hsjbg4



-- Status of last VLF for current database  (Query 18) (Last VLF Status)
SELECT TOP(1) DB_NAME(li.database_id) AS [Database Name], li.[file_id],
               li.vlf_size_mb, li.vlf_sequence_number, li.vlf_active, li.vlf_status
FROM sys.dm_db_log_info(DB_ID()) AS li 
ORDER BY vlf_sequence_number DESC OPTION (RECOMPILE);
------

-- Determine whether you will be able to shrink the transaction log file

-- vlf_status Values
-- 0 is inactive 
-- 1 is initialized but unused 
-- 2 is active


-- Important database properties for current database   (Query 19) (Database Properties)
SELECT db.[name] AS [Database Name], db.recovery_model_desc AS [Recovery Model], 
db.state_desc, db.containment_desc, db.log_reuse_wait_desc AS [Log Reuse Wait Description], 
db.[compatibility_level] AS [DB Compatibility Level], 
db.is_mixed_page_allocation_on, db.page_verify_option_desc AS [Page Verify Option], 
db.is_auto_create_stats_on, db.is_auto_update_stats_on, db.is_auto_update_stats_async_on, db.is_parameterization_forced, 
db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on, db.is_auto_close_on, db.is_auto_shrink_on, 
db.target_recovery_time_in_seconds, db.is_cdc_enabled, db.is_memory_optimized_elevate_to_snapshot_on, 
db.delayed_durability_desc, db.is_auto_create_stats_incremental_on,
db.is_query_store_on, db.is_sync_with_backup, db.is_temporal_history_retention_enabled,
db.is_encrypted  
FROM sys.databases AS db WITH (NOLOCK)
WHERE db.[name] <> N'master'
ORDER BY db.[name] OPTION (RECOMPILE);
------

-- Things to look at:
-- What recovery models are you using?
-- What is the log reuse wait description?
-- What compatibility level are the databases on? 
-- What is the Page Verify Option? (should be CHECKSUM)
-- Is Auto Update Statistics Asynchronously enabled?
-- Is Delayed Durability enabled?
-- Make sure auto_shrink and auto_close are not enabled!



-- Get database scoped configuration values for current database (Query 20) (Database-scoped Configurations)
SELECT configuration_id, [name], [value] AS [value_for_primary]
FROM sys.database_scoped_configurations WITH (NOLOCK) OPTION (RECOMPILE);
------

-- This lets you see the value of these new properties for the current database

-- Clear plan cache for current database
-- ALTER DATABASE SCOPED CONFIGURATION CLEAR PROCEDURE_CACHE;

-- ALTER DATABASE SCOPED CONFIGURATION (Transact-SQL)
-- https://bit.ly/2sOH7nb


-- I/O Statistics by file for the current database  (Query 21) (IO Stats By File)
SELECT DB_NAME(DB_ID()) AS [Database Name], df.name AS [Logical Name], vfs.[file_id], df.type_desc,
df.physical_name AS [Physical Name], CAST(vfs.size_on_disk_bytes/1048576.0 AS DECIMAL(10, 2)) AS [Size on Disk (MB)],
vfs.num_of_reads, vfs.num_of_writes, vfs.io_stall_read_ms, vfs.io_stall_write_ms,
CAST(100. * vfs.io_stall_read_ms/(vfs.io_stall_read_ms + vfs.io_stall_write_ms) AS DECIMAL(10,1)) AS [IO Stall Reads Pct],
CAST(100. * vfs.io_stall_write_ms/(vfs.io_stall_write_ms + vfs.io_stall_read_ms) AS DECIMAL(10,1)) AS [IO Stall Writes Pct],
(vfs.num_of_reads + vfs.num_of_writes) AS [Writes + Reads], 
CAST(vfs.num_of_bytes_read/1048576.0 AS DECIMAL(10, 2)) AS [MB Read], 
CAST(vfs.num_of_bytes_written/1048576.0 AS DECIMAL(10, 2)) AS [MB Written],
CAST(100. * vfs.num_of_reads/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(10,1)) AS [# Reads Pct],
CAST(100. * vfs.num_of_writes/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(10,1)) AS [# Write Pct],
CAST(100. * vfs.num_of_bytes_read/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(10,1)) AS [Read Bytes Pct],
CAST(100. * vfs.num_of_bytes_written/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(10,1)) AS [Written Bytes Pct]
FROM sys.dm_io_virtual_file_stats(DB_ID(), NULL) AS vfs
INNER JOIN sys.database_files AS df WITH (NOLOCK)
ON vfs.[file_id]= df.[file_id] OPTION (RECOMPILE);
------

-- This helps you characterize your workload better from an I/O perspective for this database
-- It helps you determine whether you has an OLTP or DW/DSS type of workload


-- Get recent resource usage (Query 22) (Recent Resource Usage)
SELECT dtu_limit, cpu_limit, avg_cpu_percent, avg_data_io_percent, avg_log_write_percent, avg_memory_usage_percent, xtp_storage_percent,
       max_worker_percent, max_session_percent,  avg_login_rate_percent, end_time 
FROM sys.dm_db_resource_stats WITH (NOLOCK) 
ORDER BY end_time DESC OPTION (RECOMPILE);
------

-- Returns a row of usage metrics every 15 seconds, going back 64 minutes
-- The end_time column is UTC time

-- sys.dm_db_resource_stats (Azure SQL Database)
-- https://bit.ly/2HaSpKn



-- Get recent resource usage (Query 23) (Avg/Max Resource Usage)
SELECT AVG(avg_cpu_percent) AS [Average CPU Utilization In Percent],   
       MAX(avg_cpu_percent) AS [Maximum CPU Utilization In Percent],   
       AVG(avg_data_io_percent) AS [Average Data IO In Percent],   
       MAX(avg_data_io_percent) AS [Maximum Data IO In Percent],   
       AVG(avg_log_write_percent) AS [Average Log Write Utilization In Percent],   
       MAX(avg_log_write_percent) AS [Maximum Log Write Utilization In Percent],   
       AVG(avg_memory_usage_percent) AS [Average Memory Usage In Percent],   
       MAX(avg_memory_usage_percent) AS [Maximum Memory Usage In Percent]   
FROM sys.dm_db_resource_stats WITH (NOLOCK) OPTION (RECOMPILE); 
------


-- Isolate top waits for this database since last restart or failover (Query 24) (Top DB Waits)
WITH [Waits] 
AS (SELECT wait_type, wait_time_ms/ 1000.0 AS [WaitS],
          (wait_time_ms - signal_wait_time_ms) / 1000.0 AS [ResourceS],
           signal_wait_time_ms / 1000.0 AS [SignalS],
           waiting_tasks_count AS [WaitCount],
           100.0 *  wait_time_ms / SUM (wait_time_ms) OVER() AS [Percentage],
           ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS [RowNum]
    FROM sys.dm_db_wait_stats WITH (NOLOCK)
    WHERE [wait_type] NOT IN (
        N'BROKER_EVENTHANDLER', N'BROKER_RECEIVE_WAITFOR', N'BROKER_TASK_STOP',
		N'BROKER_TO_FLUSH', N'BROKER_TRANSMITTER', N'CHECKPOINT_QUEUE',
        N'CHKPT', N'CLR_AUTO_EVENT', N'CLR_MANUAL_EVENT', N'CLR_SEMAPHORE',
        N'DBMIRROR_DBM_EVENT', N'DBMIRROR_EVENTS_QUEUE', N'DBMIRROR_WORKER_QUEUE',
		N'DBMIRRORING_CMD', N'DIRTY_PAGE_POLL', N'DISPATCHER_QUEUE_SEMAPHORE',
        N'EXECSYNC', N'FSAGENT', N'FT_IFTS_SCHEDULER_IDLE_WAIT', N'FT_IFTSHC_MUTEX',
        N'HADR_CLUSAPI_CALL', N'HADR_FILESTREAM_IOMGR_IOCOMPLETION', N'HADR_LOGCAPTURE_WAIT', 
		N'HADR_NOTIFICATION_DEQUEUE', N'HADR_TIMER_TASK', N'HADR_WORK_QUEUE',
        N'KSOURCE_WAKEUP', N'LAZYWRITER_SLEEP', N'LOGMGR_QUEUE', 
		N'MEMORY_ALLOCATION_EXT', N'ONDEMAND_TASK_QUEUE',
		N'PREEMPTIVE_HADR_LEASE_MECHANISM', N'PREEMPTIVE_SP_SERVER_DIAGNOSTICS',
		N'PREEMPTIVE_ODBCOPS',
		N'PREEMPTIVE_OS_LIBRARYOPS', N'PREEMPTIVE_OS_COMOPS', N'PREEMPTIVE_OS_CRYPTOPS',
		N'PREEMPTIVE_OS_PIPEOPS', N'PREEMPTIVE_OS_AUTHENTICATIONOPS',
		N'PREEMPTIVE_OS_GENERICOPS', N'PREEMPTIVE_OS_VERIFYTRUST',
		N'PREEMPTIVE_OS_FILEOPS', N'PREEMPTIVE_OS_DEVICEOPS', N'PREEMPTIVE_OS_QUERYREGISTRY',
		N'PREEMPTIVE_OS_WRITEFILE',
		N'PREEMPTIVE_XE_CALLBACKEXECUTE', N'PREEMPTIVE_XE_DISPATCHER',
		N'PREEMPTIVE_XE_GETTARGETSTATE', N'PREEMPTIVE_XE_SESSIONCOMMIT',
		N'PREEMPTIVE_XE_TARGETINIT', N'PREEMPTIVE_XE_TARGETFINALIZE',
		N'PREEMPTIVE_XHTTP',
        N'PWAIT_ALL_COMPONENTS_INITIALIZED', N'PWAIT_DIRECTLOGCONSUMER_GETNEXT',
		N'QDS_PERSIST_TASK_MAIN_LOOP_SLEEP',
		N'QDS_ASYNC_QUEUE',
        N'QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP', N'REQUEST_FOR_DEADLOCK_SEARCH',
		N'RESOURCE_GOVERNOR_IDLE',
		N'RESOURCE_QUEUE', N'SERVER_IDLE_CHECK', N'SLEEP_BPOOL_FLUSH', N'SLEEP_DBSTARTUP',
		N'SLEEP_DCOMSTARTUP', N'SLEEP_MASTERDBREADY', N'SLEEP_MASTERMDREADY',
        N'SLEEP_MASTERUPGRADED', N'SLEEP_MSDBSTARTUP', N'SLEEP_SYSTEMTASK', N'SLEEP_TASK',
        N'SLEEP_TEMPDBSTARTUP', N'SNI_HTTP_ACCEPT', N'SP_SERVER_DIAGNOSTICS_SLEEP',
		N'SQLTRACE_BUFFER_FLUSH', N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', N'SQLTRACE_WAIT_ENTRIES',
		N'WAIT_FOR_RESULTS', N'WAITFOR', N'WAITFOR_TASKSHUTDOWN', N'WAIT_XTP_HOST_WAIT',
		N'WAIT_XTP_OFFLINE_CKPT_NEW_LOG', N'WAIT_XTP_CKPT_CLOSE', N'WAIT_XTP_RECOVERY',
		N'XE_BUFFERMGR_ALLPROCESSED_EVENT', N'XE_DISPATCHER_JOIN',
        N'XE_DISPATCHER_WAIT', N'XE_LIVE_TARGET_TVF', N'XE_TIMER_EVENT')
    AND waiting_tasks_count > 0)
SELECT
    MAX (W1.wait_type) AS [WaitType],
	CAST (MAX (W1.Percentage) AS DECIMAL (5,2)) AS [Wait Percentage],
	CAST ((MAX (W1.WaitS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgWait_Sec],
    CAST ((MAX (W1.ResourceS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgRes_Sec],
    CAST ((MAX (W1.SignalS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgSig_Sec],
    CAST (MAX (W1.WaitS) AS DECIMAL (16,2)) AS [Total_Wait_Sec],
    CAST (MAX (W1.ResourceS) AS DECIMAL (16,2)) AS [Resource_Sec],
    CAST (MAX (W1.SignalS) AS DECIMAL (16,2)) AS [Signal_Sec],
    MAX (W1.WaitCount) AS [Wait Count]   
FROM Waits AS W1
INNER JOIN Waits AS W2
ON W2.RowNum <= W1.RowNum
GROUP BY W1.RowNum
HAVING SUM (W2.Percentage) - MAX (W1.Percentage) < 99 -- percentage threshold
OPTION (RECOMPILE);
------

-- Cumulative wait stats are not as useful on an idle instance that is not under load or performance pressure

-- SQL Server Wait Types Library (Paul Randal)
-- https://www.sqlskills.com/help/waits/

-- The SQL Server Wait Type Repository
-- http://blogs.msdn.com/b/psssql/archive/2009/11/03/the-sql-server-wait-type-repository.aspx

-- Wait statistics, or please tell me where it hurts
-- https://www.sqlskills.com/blogs/paul/wait-statistics-or-please-tell-me-where-it-hurts/

-- SQL Server 2005 Performance Tuning using the Waits and Queues
-- http://technet.microsoft.com/en-us/library/cc966413.aspx

-- sys.dm_os_wait_stats (Transact-SQL)
-- http://msdn.microsoft.com/en-us/library/ms179984(v=sql.120).aspx



-- Get most frequently executed queries for this database (Query 25) (Query Execution Counts)
SELECT TOP(50) LEFT(t.[text], 50) AS [Short Query Text], qs.execution_count AS [Execution Count],
qs.total_logical_reads AS [Total Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.total_worker_time AS [Total Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.total_elapsed_time AS [Total Elapsed Time],
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
qs.creation_time AS [Creation Time]
--,t.[text] AS [Complete Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
WHERE t.dbid = DB_ID()
ORDER BY qs.execution_count DESC OPTION (RECOMPILE);
------


-- Get top total worker time queries for this database (Query 26) (Top Worker Time Queries)		
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], 
REPLACE(REPLACE(LEFT(t.[text], 50), CHAR(10),''), CHAR(13),'') AS [Short Query Text],  
qs.total_worker_time AS [Total Worker Time], qs.min_worker_time AS [Min Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.max_worker_time AS [Max Worker Time], 
qs.min_elapsed_time AS [Min Elapsed Time], 
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time], 
qs.max_elapsed_time AS [Max Elapsed Time],
qs.min_logical_reads AS [Min Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.max_logical_reads AS [Max Logical Reads], 
qs.execution_count AS [Execution Count],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],  
qs.creation_time AS [Creation Time]
--,t.[text] AS [Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp
WHERE t.dbid = DB_ID() 
ORDER BY qs.total_worker_time DESC OPTION (RECOMPILE);
------

-- Helps you find the most expensive queries from a CPU perspective for this database
-- Can also help track down parameter sniffing issues


-- Get top total logical reads queries for this database (Query 27) (Top Logical Reads Queries)    
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name],
REPLACE(REPLACE(LEFT(t.[text], 50), CHAR(10),''), CHAR(13),'') AS [Short Query Text], 
qs.total_logical_reads AS [Total Logical Reads],
qs.min_logical_reads AS [Min Logical Reads],
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
qs.max_logical_reads AS [Max Logical Reads],   
qs.min_worker_time AS [Min Worker Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time], 
qs.max_worker_time AS [Max Worker Time], 
qs.min_elapsed_time AS [Min Elapsed Time], 
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time], 
qs.max_elapsed_time AS [Max Elapsed Time],
qs.execution_count AS [Execution Count],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],   
qs.creation_time AS [Creation Time]
--,t.[text] AS [Complete Query Text], qp.query_plan AS [Query Plan] -- uncomment out these columns if not copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp
WHERE t.dbid = DB_ID()  
ORDER BY qs.total_logical_reads DESC OPTION (RECOMPILE);
------


-- Helps you find the most expensive queries from a memory perspective for this database
-- Can also help track down parameter sniffing issues



-- Get top average elapsed time queries for this database (Query 28) (Top Avg Elapsed Time Queries)   
SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], 
REPLACE(REPLACE(LEFT(t.[text], 255), CHAR(10),''), CHAR(13),'') AS [Short Query Text],  
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
qs.min_elapsed_time, qs.max_elapsed_time, qs.last_elapsed_time,
qs.execution_count AS [Execution Count],  
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads], 
qs.total_physical_reads/qs.execution_count AS [Avg Physical Reads], 
qs.total_worker_time/qs.execution_count AS [Avg Worker Time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],  
qs.creation_time AS [Creation Time]
, qp.query_plan AS [Query Plan] -- comment out this column if copying results to Excel
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp
WHERE t.dbid = DB_ID()  
ORDER BY qs.total_elapsed_time/qs.execution_count DESC OPTION (RECOMPILE);
------

-- Helps you find the highest average elapsed time queries for this database
-- Can also help track down parameter sniffing issues



-- Top Cached SPs By Execution Count (Query 29) (SP Execution Counts)
SELECT TOP(100) p.name AS [SP Name], qs.execution_count AS [Execution Count],
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
qs.total_worker_time/qs.execution_count AS [Avg Worker Time],    
qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.execution_count DESC OPTION (RECOMPILE);
------

-- Tells you which cached stored procedures are called the most often
-- This helps you characterize and baseline your workload


-- Top Cached SPs By Avg Elapsed Time (Query 30) (SP Avg Elapsed Time)
SELECT TOP(25) p.name AS [SP Name], qs.min_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time], 
qs.max_elapsed_time, qs.last_elapsed_time, qs.total_elapsed_time, qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute], 
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], 
qs.total_worker_time AS [TotalWorkerTime],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY avg_elapsed_time DESC OPTION (RECOMPILE);
------

-- This helps you find high average elapsed time cached stored procedures that
-- may be easy to optimize with standard query tuning techniques



-- Top Cached SPs By Total Worker time. Worker time relates to CPU cost  (Query 31) (SP Worker Time)
SELECT TOP(25) p.name AS [SP Name], qs.total_worker_time AS [TotalWorkerTime], 
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.total_worker_time DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a CPU perspective
-- You should look at this if you see signs of CPU pressure


-- Top Cached SPs By Total Logical Reads. Logical reads relate to memory pressure  (Query 32) (SP Logical Reads)
SELECT TOP(25) p.name AS [SP Name], qs.total_logical_reads AS [TotalLogicalReads], 
qs.total_logical_reads/qs.execution_count AS [AvgLogicalReads],qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute], 
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.total_logical_reads DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a memory perspective
-- You should look at this if you see signs of memory pressure


-- Top Cached SPs By Total Physical Reads. Physical reads relate to disk read I/O pressure  (Query 33) (SP Physical Reads)
SELECT TOP(25) p.name AS [SP Name],qs.total_physical_reads AS [TotalPhysicalReads], 
qs.total_physical_reads/qs.execution_count AS [AvgPhysicalReads], qs.execution_count, 
qs.total_logical_reads,qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index],
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan 
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND qs.total_physical_reads > 0
ORDER BY qs.total_physical_reads DESC, qs.total_logical_reads DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a read I/O perspective
-- You should look at this if you see signs of I/O pressure or of memory pressure
       


-- Top Cached SPs By Total Logical Writes (Query 34) (SP Logical Writes)
-- Logical writes relate to both memory and disk I/O pressure 
SELECT TOP(25) p.name AS [SP Name], qs.total_logical_writes AS [TotalLogicalWrites], 
qs.total_logical_writes/qs.execution_count AS [AvgLogicalWrites], qs.execution_count,
ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
CASE WHEN CONVERT(nvarchar(max), qp.query_plan) LIKE N'%<MissingIndexes>%' THEN 1 ELSE 0 END AS [Has Missing Index], 
FORMAT(qs.last_execution_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Last Execution Time], 
FORMAT(qs.cached_time, 'yyyy-MM-dd HH:mm:ss', 'en-US') AS [Plan Cached Time]
-- ,qp.query_plan AS [Query Plan] -- Uncomment if you want the Query Plan 
FROM sys.procedures AS p WITH (NOLOCK)
INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
ON p.[object_id] = qs.[object_id]
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.database_id = DB_ID()
AND qs.total_logical_writes > 0
AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0
ORDER BY qs.total_logical_writes DESC OPTION (RECOMPILE);
------

-- This helps you find the most expensive cached stored procedures from a write I/O perspective
-- You should look at this if you see signs of I/O pressure or of memory pressure



-- Lists the top statements by average input/output usage for the current database  (Query 35) (Top IO Statements)
SELECT TOP(50) OBJECT_NAME(qt.objectid, dbid) AS [SP Name],
(qs.total_logical_reads + qs.total_logical_writes) /qs.execution_count AS [Avg IO], qs.execution_count AS [Execution Count],
SUBSTRING(qt.[text],qs.statement_start_offset/2, 
	(CASE 
		WHEN qs.statement_end_offset = -1 
	 THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2 
		ELSE qs.statement_end_offset 
	 END - qs.statement_start_offset)/2) AS [Query Text]	
FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
WHERE qt.[dbid] = DB_ID()
ORDER BY [Avg IO] DESC OPTION (RECOMPILE);
------

-- Helps you find the most expensive statements for I/O by SP



-- Possible Bad NC Indexes (writes > reads)  (Query 36) (Bad NC Indexes)
SELECT OBJECT_NAME(s.[object_id]) AS [Table Name], i.name AS [Index Name], i.index_id, 
i.is_disabled, i.is_hypothetical, i.has_filter, i.fill_factor,
user_updates AS [Total Writes], user_seeks + user_scans + user_lookups AS [Total Reads],
user_updates - (user_seeks + user_scans + user_lookups) AS [Difference]
FROM sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON s.[object_id] = i.[object_id]
AND i.index_id = s.index_id
WHERE OBJECTPROPERTY(s.[object_id],'IsUserTable') = 1
AND s.database_id = DB_ID()
AND user_updates > (user_seeks + user_scans + user_lookups)
AND i.index_id > 1
ORDER BY [Difference] DESC, [Total Writes] DESC, [Total Reads] ASC OPTION (RECOMPILE);
------

-- Look for indexes with high numbers of writes and zero or very low numbers of reads
-- Consider your complete workload, and how long your instance has been running
-- Investigate further before dropping an index!


-- Missing Indexes for current database by Index Advantage  (Query 37) (Missing Indexes)
SELECT DISTINCT CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage], 
migs.last_user_seek, mid.[statement] AS [Database.Schema.Table],
mid.equality_columns, mid.inequality_columns, mid.included_columns,
migs.unique_compiles, migs.user_seeks, migs.avg_total_user_cost, migs.avg_user_impact,
OBJECT_NAME(mid.[object_id]) AS [Table Name], p.rows AS [Table Rows]
FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)
INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)
ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)
ON mig.index_handle = mid.index_handle
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON p.[object_id] = mid.[object_id]
WHERE mid.database_id = DB_ID() 
ORDER BY index_advantage DESC OPTION (RECOMPILE);
------

-- Look at index advantage, last user seek time, number of user seeks to help determine source and importance
-- SQL Server is overly eager to add included columns, so beware
-- Do not just blindly add indexes that show up from this query!!!


-- Find missing index warnings for cached plans in the current database  (Query 38) (Missing Index Warnings)
-- Note: This query could take some time on a busy instance
SELECT TOP(25) OBJECT_NAME(objectid) AS [ObjectName], 
               cp.objtype, cp.usecounts, cp.size_in_bytes, query_plan
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) AS qp
WHERE CAST(query_plan AS NVARCHAR(MAX)) LIKE N'%MissingIndex%'
AND dbid = DB_ID()
ORDER BY cp.usecounts DESC OPTION (RECOMPILE);
------

-- Helps you connect missing indexes to specific stored procedures or queries
-- This can help you decide whether to add them or not


-- Breaks down buffers used by current database by object (table, index) in the buffer cache  (Query 39) (Buffer Usage)
-- Note: This query could take some time on a busy instance
SELECT OBJECT_NAME(p.[object_id]) AS [Object Name], p.index_id, 
CAST(COUNT(*)/128.0 AS DECIMAL(10, 2)) AS [Buffer size(MB)],  
COUNT(*) AS [BufferCount], p.[Rows] AS [Row Count],
p.data_compression_desc AS [Compression Type]
FROM sys.allocation_units AS a WITH (NOLOCK)
INNER JOIN sys.dm_os_buffer_descriptors AS b WITH (NOLOCK)
ON a.allocation_unit_id = b.allocation_unit_id
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON a.container_id = p.hobt_id
WHERE b.database_id = CONVERT(int, DB_ID())
AND p.[object_id] > 100
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'plan_%'
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'sys%'
AND OBJECT_NAME(p.[object_id]) NOT LIKE N'xml_index_nodes%'
GROUP BY p.[object_id], p.index_id, p.data_compression_desc, p.[Rows]
ORDER BY [BufferCount] DESC OPTION (RECOMPILE);
------

-- Tells you what tables and indexes are using the most memory in the buffer cache
-- It can help identify possible candidates for data compression


-- Get Table names, row counts, and compression status for clustered index or heap  (Query 40) (Table Sizes)
SELECT SCHEMA_NAME(o.Schema_ID) AS [Schema Name], OBJECT_NAME(p.object_id) AS [ObjectName], 
SUM(p.Rows) AS [RowCount], data_compression_desc AS [CompressionType]
FROM sys.partitions AS p WITH (NOLOCK)
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON p.object_id = o.object_id
WHERE index_id < 2 --ignore the partitions from the non-clustered index if any
AND OBJECT_NAME(p.object_id) NOT LIKE N'sys%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'spt_%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'queue_%' 
AND OBJECT_NAME(p.object_id) NOT LIKE N'filestream_tombstone%' 
AND OBJECT_NAME(p.object_id) NOT LIKE N'fulltext%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'ifts_comp_fragment%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'filetable_updates%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'xml_index_nodes%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'sqlagent_job%'
AND OBJECT_NAME(p.object_id) NOT LIKE N'plan_persist%'
GROUP BY  SCHEMA_NAME(o.Schema_ID), p.object_id, data_compression_desc
ORDER BY SUM(p.Rows) DESC OPTION (RECOMPILE);
------

-- Gives you an idea of table sizes, and possible data compression opportunities



-- Get some key table properties (Query 41) (Table Properties)
SELECT OBJECT_NAME(t.[object_id]) AS [ObjectName], p.[rows] AS [Table Rows], p.index_id, 
       p.data_compression_desc AS [Index Data Compression],
       t.create_date, t.lock_on_bulk_load,  
       t.is_tracked_by_cdc, t.lock_escalation_desc, t.is_filetable, 
	   t.is_memory_optimized, t.durability_desc, 
	   t.temporal_type_desc
FROM sys.tables AS t WITH (NOLOCK)
INNER JOIN sys.partitions AS p WITH (NOLOCK)
ON t.[object_id] = p.[object_id]
WHERE OBJECT_NAME(t.[object_id]) NOT LIKE N'sys%'
ORDER BY OBJECT_NAME(t.[object_id]), p.index_id OPTION (RECOMPILE);
------

-- Gives you some good information about your tables
-- is_memory_optimized and durability_desc were new in SQL Server 2014
-- temporal_type_desc, is_remote_data_archive_enabled, is_external are new in SQL Server 2016

-- sys.tables (Transact-SQL)
-- https://bit.ly/2Gk7998



-- When were Statistics last updated on all indexes?  (Query 42) (Statistics Update)
SELECT SCHEMA_NAME(o.Schema_ID) + N'.' + o.[NAME] AS [Object Name], o.[type_desc] AS [Object Type],
      i.[name] AS [Index Name], STATS_DATE(i.[object_id], i.index_id) AS [Statistics Date], 
      s.auto_created, s.no_recompute, s.user_created, s.is_incremental, s.is_temporary,
	  st.row_count, st.used_page_count
FROM sys.objects AS o WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON o.[object_id] = i.[object_id]
INNER JOIN sys.stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id] 
AND i.index_id = s.stats_id
INNER JOIN sys.dm_db_partition_stats AS st WITH (NOLOCK)
ON o.[object_id] = st.[object_id]
AND i.[index_id] = st.[index_id]
WHERE o.[type] IN ('U', 'V')
AND st.row_count > 0
ORDER BY STATS_DATE(i.[object_id], i.index_id) DESC OPTION (RECOMPILE);
------  

-- Helps discover possible problems with out-of-date statistics
-- Also gives you an idea which indexes are the most active

-- sys.stats (Transact-SQL)
-- https://bit.ly/2GyAxrn



-- Look at most frequently modified indexes and statistics (Query 43) (Volatile Indexes)
SELECT o.[name] AS [Object Name], o.[object_id], o.[type_desc], s.[name] AS [Statistics Name], 
       s.stats_id, s.no_recompute, s.auto_created, s.is_incremental, s.is_temporary,
	   sp.modification_counter, sp.[rows], sp.rows_sampled, sp.last_updated
FROM sys.objects AS o WITH (NOLOCK)
INNER JOIN sys.stats AS s WITH (NOLOCK)
ON s.object_id = o.object_id
CROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) AS sp
WHERE o.[type_desc] NOT IN (N'SYSTEM_TABLE', N'INTERNAL_TABLE')
AND sp.modification_counter > 0
ORDER BY sp.modification_counter DESC, o.name OPTION (RECOMPILE);
------

-- This helps you understand your workload and make better decisions about 
-- things like data compression and adding new indexes to a table



-- Get fragmentation info for all indexes above a certain size in the current database  (Query 44) (Index Fragmentation)
-- Note: This query could take some time on a very large database
SELECT DB_NAME(ps.database_id) AS [Database Name], SCHEMA_NAME(o.[schema_id]) AS [Schema Name],
OBJECT_NAME(ps.OBJECT_ID) AS [Object Name], i.[name] AS [Index Name], ps.index_id, 
ps.index_type_desc, ps.avg_fragmentation_in_percent, 
ps.fragment_count, ps.page_count, i.fill_factor, i.has_filter, 
i.filter_definition, i.[allow_page_locks]
FROM sys.dm_db_index_physical_stats(DB_ID(),NULL, NULL, NULL , N'LIMITED') AS ps
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ps.[object_id] = i.[object_id] 
AND ps.index_id = i.index_id
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON i.[object_id] = o.[object_id]
WHERE ps.database_id = DB_ID()
AND ps.page_count > 2500
ORDER BY ps.avg_fragmentation_in_percent DESC OPTION (RECOMPILE);
------

-- Helps determine whether you have framentation in your relational indexes
-- and how effective your index maintenance strategy is


--- Index Read/Write stats (all tables in current DB) ordered by Reads  (Query 45) (Overall Index Usage - Reads)
SELECT OBJECT_NAME(i.[object_id]) AS [ObjectName], i.[name] AS [IndexName], i.index_id, 
       s.user_seeks, s.user_scans, s.user_lookups,
	   s.user_seeks + s.user_scans + s.user_lookups AS [Total Reads], 
	   s.user_updates AS [Writes],  
	   i.[type_desc] AS [Index Type], i.fill_factor AS [Fill Factor], i.has_filter, i.filter_definition, 
	   s.last_user_scan, s.last_user_lookup, s.last_user_seek
FROM sys.indexes AS i WITH (NOLOCK)
LEFT OUTER JOIN sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id]
AND i.index_id = s.index_id
AND s.database_id = DB_ID()
WHERE OBJECTPROPERTY(i.[object_id],'IsUserTable') = 1
ORDER BY s.user_seeks + s.user_scans + s.user_lookups DESC OPTION (RECOMPILE); -- Order by reads
------

-- Show which indexes in the current database are most active for Reads


--- Index Read/Write stats (all tables in current DB) ordered by Writes  (Query 46) (Overall Index Usage - Writes)
SELECT OBJECT_NAME(i.[object_id]) AS [ObjectName], i.[name] AS [IndexName], i.index_id,
	   s.user_updates AS [Writes], s.user_seeks + s.user_scans + s.user_lookups AS [Total Reads], 
	   i.[type_desc] AS [Index Type], i.fill_factor AS [Fill Factor], i.has_filter, i.filter_definition,
	   s.last_system_update, s.last_user_update
FROM sys.indexes AS i WITH (NOLOCK)
LEFT OUTER JOIN sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
ON i.[object_id] = s.[object_id]
AND i.index_id = s.index_id
AND s.database_id = DB_ID()
WHERE OBJECTPROPERTY(i.[object_id],'IsUserTable') = 1
ORDER BY s.user_updates DESC OPTION (RECOMPILE);						 -- Order by writes
------

-- Show which indexes in the current database are most active for Writes


-- Get in-memory OLTP index usage (Query 47) (XTP Index Usage)
SELECT OBJECT_NAME(i.[object_id]) AS [Object Name], i.index_id, i.[name] AS [Index Name],
       i.[type_desc], xis.scans_started, xis.scans_retries, 
	   xis.rows_touched, xis.rows_returned
FROM sys.dm_db_xtp_index_stats AS xis WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON i.[object_id] = xis.[object_id] 
AND i.index_id = xis.index_id 
ORDER BY OBJECT_NAME(i.[object_id]) OPTION (RECOMPILE);
------

-- This gives you some index usage statistics for in-memory OLTP
-- Returns no data if you are not using in-memory OLTP

-- Guidelines for Using Indexes on Memory-Optimized Tables
-- https://bit.ly/2GCP8lF



-- Look at Columnstore index physical statistics (Query 48) (Columnstore Index Physical Stat)
SELECT OBJECT_NAME(ps.object_id) AS [TableName],  
	i.[name] AS [IndexName], ps.index_id, ps.partition_number,
	ps.delta_store_hobt_id, ps.state_desc, ps.total_rows, ps.size_in_bytes,
	ps.trim_reason_desc, ps.generation, ps.transition_to_compressed_state_desc,
	ps.has_vertipaq_optimization, ps.deleted_rows,
	100 * (ISNULL(ps.deleted_rows, 0))/ps.total_rows AS [Fragmentation]
FROM sys.dm_db_column_store_row_group_physical_stats AS ps WITH (NOLOCK)
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ps.object_id = i.object_id 
AND ps.index_id = i.index_id
ORDER BY ps.object_id, ps.partition_number, ps.row_group_id OPTION (RECOMPILE);
------

-- sys.dm_db_column_store_row_group_physical_stats (Transact-SQL)
-- https://bit.ly/2q276XQ



-- Get lock waits for current database (Query 49) (Lock Waits)
SELECT o.name AS [table_name], i.name AS [index_name], ios.index_id, ios.partition_number,
		SUM(ios.row_lock_wait_count) AS [total_row_lock_waits], 
		SUM(ios.row_lock_wait_in_ms) AS [total_row_lock_wait_in_ms],
		SUM(ios.page_lock_wait_count) AS [total_page_lock_waits],
		SUM(ios.page_lock_wait_in_ms) AS [total_page_lock_wait_in_ms],
		SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) AS [total_lock_wait_in_ms]
FROM sys.dm_db_index_operational_stats(DB_ID(), NULL, NULL, NULL) AS ios
INNER JOIN sys.objects AS o WITH (NOLOCK)
ON ios.[object_id] = o.[object_id]
INNER JOIN sys.indexes AS i WITH (NOLOCK)
ON ios.[object_id] = i.[object_id] 
AND ios.index_id = i.index_id
WHERE o.[object_id] > 100
GROUP BY o.name, i.name, ios.index_id, ios.partition_number
HAVING SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) > 0
ORDER BY total_lock_wait_in_ms DESC OPTION (RECOMPILE);
------

-- This query is helpful for troubleshooting blocking and deadlocking issues



-- Look at UDF execution statistics (Query 50) (UDF Statistics)
SELECT OBJECT_NAME(object_id) AS [Function Name], total_worker_time,
       execution_count, total_elapsed_time,  
       total_elapsed_time/execution_count AS [avg_elapsed_time],  
       last_elapsed_time, last_execution_time, cached_time 
FROM sys.dm_exec_function_stats WITH (NOLOCK) 
WHERE database_id = DB_ID()
ORDER BY total_worker_time DESC OPTION (RECOMPILE); 
------


-- Helps you investigate scalar UDF performance issues

-- sys.dm_exec_function_stats (Transact-SQL)
-- https://bit.ly/2q1Q6BM




-- Get QueryStore Options for this database (Query 51) (QueryStore Options)
SELECT actual_state_desc, desired_state_desc,
       current_storage_size_mb, [max_storage_size_mb], 
	   query_capture_mode_desc, size_based_cleanup_mode_desc
FROM sys.database_query_store_options WITH (NOLOCK) OPTION (RECOMPILE);
------

-- New for SQL Server 2016
-- Requires that QueryStore is enabled for this database

-- Tuning Workload Performance with Query Store
-- https://bit.ly/1kHSl7w


-- Get highest aggregate duration queries over last hour (Query 52) (High Aggregate Duration Queries)
WITH AggregatedDurationLastHour
AS
(SELECT q.query_id, SUM(count_executions * avg_duration) AS total_duration,
   COUNT (distinct p.plan_id) AS number_of_plans
   FROM sys.query_store_query_text AS qt WITH (NOLOCK)
   INNER JOIN sys.query_store_query AS q WITH (NOLOCK)
   ON qt.query_text_id = q.query_text_id
   INNER JOIN sys.query_store_plan AS p WITH (NOLOCK)
   ON q.query_id = p.query_id
   INNER JOIN sys.query_store_runtime_stats AS rs WITH (NOLOCK)
   ON rs.plan_id = p.plan_id
   INNER JOIN sys.query_store_runtime_stats_interval AS rsi WITH (NOLOCK)
   ON rsi.runtime_stats_interval_id = rs.runtime_stats_interval_id
   WHERE rsi.start_time >= DATEADD(hour, -1, GETUTCDATE()) 
   AND rs.execution_type_desc = N'Regular'
   GROUP BY q.query_id),
OrderedDuration AS
(SELECT query_id, total_duration, number_of_plans, 
 ROW_NUMBER () OVER (ORDER BY total_duration DESC, query_id) AS RN
 FROM AggregatedDurationLastHour)
SELECT OBJECT_NAME(q.object_id) AS [Containing Object], qt.query_sql_text, 
od.total_duration AS [Total Duration (microsecs)], 
od.number_of_plans AS [Plan Count],
p.is_forced_plan, p.is_parallel_plan, p.is_trivial_plan,
q.query_parameterization_type_desc, p.[compatibility_level],
p.last_compile_start_time, q.last_execution_time,
CONVERT(xml, p.query_plan) AS query_plan_xml 
FROM OrderedDuration AS od 
INNER JOIN sys.query_store_query AS q WITH (NOLOCK)
ON q.query_id  = od.query_id
INNER JOIN sys.query_store_query_text AS qt WITH (NOLOCK)
ON q.query_text_id = qt.query_text_id
INNER JOIN sys.query_store_plan AS p WITH (NOLOCK)
ON q.query_id = p.query_id
WHERE od.RN <= 50 
ORDER BY total_duration DESC OPTION (RECOMPILE);
------

-- New for SQL Server 2016
-- Requires that QueryStore is enabled for this database


-- Get input buffer information for the current database (Query 53) (Input Buffer)
SELECT es.session_id, DB_NAME(es.database_id) AS [Database Name],
       es.login_time, es.cpu_time, es.logical_reads,
       es.[status], ib.event_info AS [Input Buffer]
FROM sys.dm_exec_sessions AS es WITH (NOLOCK)
CROSS APPLY sys.dm_exec_input_buffer(es.session_id, NULL) AS ib
WHERE es.database_id = DB_ID()
AND es.session_id > 50
AND es.session_id <> @@SPID OPTION (RECOMPILE);
------

-- Gives you input buffer information from all non-system sessions for the current database
-- Replaces DBCC INPUTBUFFER

-- New DMF for retrieving input buffer in SQL Server
-- https://bit.ly/2uHKMbz



-- Get any resumable index rebuild operation information (Query 54) (Resumable Index Rebuild)
SELECT OBJECT_NAME(iro.object_id) AS [Object Name], iro.index_id, iro.name AS [Index Name],
       iro.sql_text, iro.last_max_dop_used, iro.partition_number, iro.state_desc, iro.start_time, iro.percent_complete
FROM  sys.index_resumable_operations AS iro WITH (NOLOCK)
OPTION (RECOMPILE);
------ 

-- index_resumable_operations (Transact-SQL)
-- https://bit.ly/2pYSWqq


-- Get database automatic tuning options (Query 55) (Automatic Tuning Options)
SELECT [name], desired_state_desc, actual_state_desc, reason_desc
FROM sys.database_automatic_tuning_options WITH (NOLOCK)
OPTION (RECOMPILE);
------ 

-- sys.database_automatic_tuning_options (Transact-SQL)
-- https://bit.ly/2FHhLkL



-- Get geo-replication link status for all secondary databases (Query 56) (Geo-Replication Link Status)
SELECT link_guid, partner_server, partner_database, last_replication, 
       replication_lag_sec, replication_state_desc, role_desc, secondary_allow_connections_desc 
FROM sys.dm_geo_replication_link_status WITH (NOLOCK) OPTION (RECOMPILE);
------  

-- sys.dm_geo_replication_link_status (Azure SQL Database)
-- https://bit.ly/2GwIqC2



-- Retrieve some Azure SQL Database properties (Query 57) (Azure SQL DB Properties)
SELECT DATABASEPROPERTYEX (DB_NAME(DB_ID()), 'Edition') AS [Database Edition],
	   DATABASEPROPERTYEX (DB_NAME(DB_ID()), 'ServiceObjective') AS [Service Objective],
	   DATABASEPROPERTYEX (DB_NAME(DB_ID()), 'MaxSizeInBytes') AS [Max Size In Bytes],
	   DATABASEPROPERTYEX (DB_NAME(DB_ID()), 'IsXTPSupported') AS [Is XTP Supported]
	   OPTION (RECOMPILE);   
------  

-- DATABASEPROPERTYEX (Transact-SQL)
-- https://bit.ly/2ItexPg





-- Sign up for Microsoft Visual Studio Dev Essentials and get a free three month pass to Pluralsight

-- Microsoft Visual Studio Dev Essentials
-- https://bit.ly/1q6xbDL


-- Sign up for Microsoft Azure Essentials and get lots of free Azure usage credits, MCP exam voucher, three month Pluralsight subscription

-- Microsoft Azure Essentials
-- https://bit.ly/2KH91dQ


tools\dbatools\bin\library.ps1
# Current library Version the module expects
$currentLibraryVersion = New-Object System.Version(0, 10, 0, 70)

<#
Library Versioning 101:
The version consists of 4 segments: Major, Minor, Build, Revision

Major: Should always be equal to the main version number of the dbatools PowerShell project.
Minor: Tracks major features within a major release. Increment on new features or significant structural changes. Reset to 0 when incrementing the major version.
Build: Tracks lesser functionality upgrades. Increment on all minor upgrades, reset to 0 when introducing a new major feature or major version.
Revision: Tracks all changes. Every single update to the library - bugfix, feature or redesign - increments the revision counter. It is never reset to 0.

Updating the library version number:
When changing the library version number, it is necessary to do so in TWO places:
- At the top of this very library.ps1
- Within AssemblyInfo.cs
These two locations MUST have matching version numbers, otherwise it will keep building the library and complaining about version mismatch!
#>

<#
#---------------------------------#
# Runtime configuration variables #
#---------------------------------#

The library recognizes a few external variables in order to customize its behavior on import.

$dbatools_strictsecuritymode
Setting this to $true will cause dbatools to always load the library directly from the module directory.
This is more secure, but less convenient when it comes to updating the module, as all consoles using it must be closed.

$dbatools_alwaysbuildlibrary
Setting this to $true will cause the module to always build the library from source, rather than reuse the binaries.
Mostly for developers working on the library.

#>

#region Test whether the module had already been imported
if (([System.Management.Automation.PSTypeName]'Sqlcollaborative.Dbatools.Configuration.Config').Type) {
    # No need to load the library again, if the module was once already imported.
    Write-Verbose -Message "Library already loaded, will not load again"
    $ImportLibrary = $false
} else {
    Write-Verbose -Message "Library not present already, will import"
    $ImportLibrary = $true
}
#endregion Test whether the module had already been imported

$libraryBase = (Resolve-Path -Path ($ExecutionContext.SessionState.Module.ModuleBase + "\bin"))

if ($PSVersionTable.PSVersion.Major -ge 6) {
    $dll = (Resolve-Path -Path "$libraryBase\netcoreapp2.1\dbatools.dll" -ErrorAction Ignore)
} else {
    $dll = (Resolve-Path -Path "$libraryBase\net452\dbatools.dll" -ErrorAction Ignore)
}

if ($ImportLibrary) {
    #region Add Code
    try {
        # In strict security mode, only load from the already pre-compiled binary within the module
        if ($script:strictSecurityMode) {
            if (Test-Path -Path $dll) {
                Add-Type -Path $dll -ErrorAction Stop
            } else {
                throw "Library not found, terminating!"
            }
        }
        # Else we prioritize user convenience
else {
            try {
                $sln = (Resolve-Path -Path "$libraryBase\projects\dbatools\dbatools.sln" -ErrorAction Stop)
                $hasProject = Test-Path -Path $sln -ErrorAction Stop
            } catch {
                $null = 1
            }
            
            if (-not $dll) {
                $hasCompiledDll = $false
            } else {
                $hasCompiledDll = Test-Path -Path $dll -ErrorAction Stop
            }
            
            $reslibdll = Resolve-Path -Path "$libraryBase\dbatools.dll"
            
            if ((-not $script:alwaysBuildLibrary) -and $hasCompiledDll -and ([System.Diagnostics.FileVersionInfo]::GetVersionInfo($reslibdll).FileVersion -eq $currentLibraryVersion)) {
                $start = Get-Date
                
                try {
                    $libraryBase = Resolve-Path -Path "$libraryBase\"
                    $script:DllRoot = Resolve-Path -Path $script:DllRoot
                    Write-Verbose -Message "Found library, trying to copy & import"
                    # this looks excessive but for some reason the explicit string to string is required
                    if (("$($dll)" -ne "$(Join-Path -Path $script:DllRoot -ChildPath dbatools.dll)") -and $script:isWindows) {
                        Copy-Item -Path $dll -Destination $script:DllRoot -Force -ErrorAction Stop
                    }
                    Add-Type -Path (Resolve-Path -Path "$script:DllRoot\dbatools.dll") -ErrorAction Stop
                } catch {
                    Write-Verbose -Message "Failed to copy and import, attempting to import straight from the module directory"
                    Add-Type -Path $dll -ErrorAction Stop
                }
                Write-Verbose -Message "Total duration: $((Get-Date) - $start)"
            } elseif ($hasProject) {
                . Import-ModuleFile (Resolve-Path -Path "$($script:PSModuleRoot)\bin\build-project.ps1")
            } else {
                throw "No valid dbatools library found! Check your module integrity"
            }
        }
        
        #region PowerShell TypeData
        Update-TypeData -TypeName "Sqlcollaborative.Dbatools.dbaSystem.DbatoolsException" -SerializationDepth 2 -ErrorAction Ignore
        Update-TypeData -TypeName "Sqlcollaborative.Dbatools.dbaSystem.DbatoolsExceptionRecord" -SerializationDepth 2 -ErrorAction Ignore
        #endregion PowerShell TypeData
    } catch {
        #region Warning
        Write-Verbose @'
Dear User,

in the name of the dbatools team I apologize for the inconvenience.
Generally, when something goes wrong we try to handle and interpret in an
understandable manner. Unfortunately, something went awry with importing
our main library, so all the systems making this possible would not be initialized
yet. We have taken great pains to avoid this issue but this notification indicates
we have failed.

Please, in order to help us prevent this from happening again, visit us at:
https://github.com/sqlcollaborative/dbatools/issues
and tell us about this failure. All information will be appreciated, but
especially valuable are:
- Exports of the exception: $Error | Export-Clixml error.xml -Depth 4
- Screenshots
- Environment information (Operating System, Hardware Stats, .NET Version,
  PowerShell Version and whatever else you may consider of potential impact.)

Again, I apologize for the inconvenience and hope we will be able to speedily
resolve the issue.

Best Regards,
Friedrich Weinmann
aka "The guy who made most of The Library that Failed to import"

'@
        throw
        #endregion Warning
    }
    #endregion Add Code
}

#region Version Warning
if ($currentLibraryVersion -ne ([version](([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object ManifestModule -like "dbatools.dll").CustomAttributes | Where-Object AttributeType -like "System.Reflection.AssemblyFileVersionAttribute").ConstructorArguments.Value)) {
    Write-Verbose @"
A version missmatch between the dbatools library loaded and the one expected by
this module. This usually happens when you update the dbatools module and use
Remove-Module / Import-Module in order to load the latest version without
starting a new PowerShell instance.

Please restart the console to apply the library update, or unexpected behavior will likely occur.

If the issues continue to persist, please Remove-Item '$script:PSModuleRoot\bin\dbatools.dll'
"@
}
#endregion Version Warning
tools\dbatools\bin\net452\dbatools.dll
md5: 06F6DB200D28C91D1E68F4C18C9102C9 | sha1: 3D72A105EFA68845B1CDBEEEEAD76DA7ACF160DB | sha256: C1A33D435B99AA2B9C8ADCA482CC7387DCC0A391819C4C6CA3359E1F349A1B25 | sha512: 8F7F17D4454EA33C31C0041B0006E8774A6E0C1A97F7218B72C1435CBA71E3BA9ADEB5917FEACC003B97A1C63DDB9ADC4EA0CA4D001C12650256EC5E3E3E598F
tools\dbatools\bin\net452\dbatools.pdb
 
tools\dbatools\bin\net452\dbatools.xml
<?xml version="1.0"?>
<doc>
    <assembly>
        <name>dbatools</name>
    </assembly>
    <members>
        <member name="T:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand">
            <summary>
            Implements the Select-DbaObject command
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.InputObject">
            <summary>
            The actual input object that is being processed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.Property">
            <summary>
            The properties to select. Supports fancy DSL
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.ExcludeProperty">
            <summary>
            Properties to skip
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.ExpandProperty">
            <summary>
            A property to expand.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.Unique">
            <summary>
            Whether to exclude duplicates
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.Last">
            <summary>
            The last number of items to pick
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.First">
            <summary>
            Pick the first n items.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.Skip">
            <summary>
            Skip n items before picking items
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.SkipLast">
            <summary>
            Skip the last n items
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.Wait">
            <summary>
            
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.Index">
            <summary>
            
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.ShowProperty">
            <summary>
            THe properties to display by default
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.ShowExcludeProperty">
            <summary>
            The properties to NOT display by default
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.TypeName">
            <summary>
            The typename to assign to the psobject
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.KeepInputObject">
            <summary>
            Keep the original input object, just add to it.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand._NonclonedProperties">
            <summary>
            List of properties to NOT clone into the hashtable used against Select-Object
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand._NoAdjustment">
            <summary>
            Whether some adjustments to the object need to be done or whether the Select-Object output can be simply passed through.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand._DisplayPropertySet">
            <summary>
            The set controlling what properties will be shown by default
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand._Pipeline">
            <summary>
            THe pipeline that is wrapped around Select-Object
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.BeginProcessing">
            <summary>
            Implements the begin action of the command
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.ProcessRecord">
            <summary>
            Implements the process action of the command
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.EndProcessing">
            <summary>
            Implements the end action of the command
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand">
            <summary>
            Implements the Set-PSFConfig command
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.FullName">
            <summary>
            The full name of the setting
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Module">
            <summary>
            The name of the module the setting belongs to.
            Is optional due to just specifying a name is legal, in which case the first name segment becomes the module name.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Name">
            <summary>
            The name of the setting within a module.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Value">
            <summary>
            The value to apply.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.PersistedValue">
            <summary>
            The persisted value to apply.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.PersistedType">
            <summary>
            The persisted type to apply.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Description">
            <summary>
            Add documentation to the setting.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Validation">
            <summary>
            The validation script to use.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Handler">
            <summary>
            The handling script to apply when changing the value.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Hidden">
            <summary>
            Whether the setting should be hidden from casual discovery.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Default">
            <summary>
            Whether the setting should be applied only when nothing exists yet.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Initialize">
            <summary>
            Whether this is the configuration initialization call.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.SimpleExport">
            <summary>
            Enabling this will cause the module to use friendly json notation on export to file.
            This may result in loss of data precision, but is more userfriendly.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.ModuleExport">
            <summary>
            Whether this setting applies to module scope file export.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.DisableValidation">
            <summary>
            Do not apply the validation script when changing values.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.DisableHandler">
            <summary>
            Do not run the handler script when changing values.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.PassThru">
            <summary>
            Return the changed configuration setting.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.EnableException">
            <summary>
            Enable throwing exceptions.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._Config">
            <summary>
            The configuration item changed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._KillIt">
            <summary>
            Whether execution should be terminated silently.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._Initialize">
            <summary>
            Whether this is an initialization execution.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._Persisted">
            <summary>
            Whether persisted values need to be restored.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._Exists">
            <summary>
            Whether the setting already exists.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._PolicyEnforced">
            <summary>
            The setting to be affected was enforced by policy and cannot be changed by the user.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._NameModule">
            <summary>
            Processed name of module.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._NameName">
            <summary>
            Processed name of setting within module.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._NameFull">
            <summary>
            Processed full name of setting.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._ValidationErrorMessage">
            <summary>
            The reason validation failed.
            Filled by ApplyValue.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.BeginProcessing">
            <summary>
            Implements the begin action of Set-PSFConfig
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.ProcessRecord">
            <summary>
            Implements the process action of Set-PSFConfig
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.ApplyValue(System.Object)">
            <summary>
            Applies a value to a configuration item, invoking validation and handler scriptblocks.
            </summary>
            <param name="Value">The value to apply</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.ApplyCommonSettings">
            <summary>
            Abstracts out 
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand">
            <summary>
            Implements the Write-Message command, performing message handling and loggin
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Level">
            <summary>
            This parameter represents the verbosity of the message. The lower the number, the more important it is for a human user to read the message.
            By default, the levels are distributed like this:
            - 1-3 Direct verbose output to the user (using Write-Host)
            - 4-6 Output only visible when requesting extra verbosity (using Write-Verbose)
            - 1-9 Debugging information, written using Write-Debug
            
            In addition, it is possible to select the level "Warning" which moves the message out of the configurable range:
            The user will always be shown this message, unless he silences the entire verbosity.
            
            Possible levels:
            Critical (1), Important / Output / Host (2), Significant (3), VeryVerbose (4), Verbose (5), SomewhatVerbose (6), System (7), Debug (8), InternalComment (9), Warning (666)
            Either one of the strings or its respective number will do as input.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Message">
            <summary>
            The message to write/log. The function name and timestamp will automatically be prepended.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Tag">
            <summary>
            Tags to add to the message written.
            This allows filtering and grouping by category of message, targeting specific messages.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.FunctionName">
            <summary>
            The name of the calling function.
            Will be automatically set, but can be overridden when necessary.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.ModuleName">
            <summary>
            The name of the module, the calling function is part of.
            Will be automatically set, but can be overridden when necessary.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.File">
            <summary>
            The file in which Write-Message was called.
            Will be automatically set, but can be overridden when necessary.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Line">
            <summary>
            The line on which Write-Message was called.
            Will be automatically set, but can be overridden when necessary.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.ErrorRecord">
            <summary>
            If an error record should be noted with the message, add the full record here.
            Especially designed for use with Warning-mode, it can legally be used in either mode.
            The error will be added to the $Error variable and enqued in the logging/debugging system.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Exception">
            <summary>
            Allows specifying an inner exception as input object. This will be passed on to the logging and used for messages.
            When specifying both ErrorRecord AND Exception, Exception wins, but ErrorRecord is still used for record metadata.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Once">
            <summary>
            Setting this parameter will cause this function to write the message only once per session.
            The string passed here and the calling function's name are used to create a unique ID, which is then used to register the action in the configuration system.
            Thus will the lockout only be written if called once and not burden the system unduly.
            This lockout will be written as a hidden value, to see it use Get-DbaConfig -Force.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.OverrideExceptionMessage">
            <summary>
            Disables automatic appending of exception messages.
            Use in cases where you already have a speaking message interpretation and do not need the original message.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Target">
            <summary>
            Add the object the message is all about, in order to simplify debugging / troubleshooting.
            For example, when calling this from a function targeting a remote computer, the computername could be specified here, allowing all messages to easily be correlated to the object processed.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.EnableException">
            <summary>
            This parameters disables user-friendly warnings and enables the throwing of exceptions.
            This is less user friendly, but allows catching exceptions in calling scripts.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Breakpoint">
            <summary>
            Enables breakpoints on the current message. By default, setting '-Debug' will NOT cause an interrupt on the current position.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._timestamp">
            <summary>
            The start time of the cmdlet
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._silent">
            <summary>
            Whether this cmdlet is run in silent mode
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._fromStopFunction">
            <summary>
            Whether this cmdlet was called by Stop-Function
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._callStack">
            <summary>
            The current callstack
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._stackDepth">
            <summary>
            How many items exist on the callstack
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._message">
            <summary>
            The message to write
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._messageSimple">
            <summary>
            The message simplified without timestamps. Used for logging.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._messageColor">
            <summary>
            The message to write in color
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._messageDeveloper">
            <summary>
            Non-colored version of developermode
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._messageDeveloperColor">
            <summary>
            Colored version of developermode
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._writeHostScript">
            <summary>
            Scriptblock that writes the host messages
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._Tags">
            <summary>
            List of tags to process
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._isDebug">
            <summary>
            Whether debug mode is enabled
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._errorQualifiedMessage">
            <summary>
            The input message with the error content included if desired
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._MessageSystem">
            <summary>
            The final message to use for internal logging
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._MessageStreams">
            <summary>
            The final message to use for writing to streams, such as verbose or warning
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._MessageHost">
            <summary>
            The final message to use for host messages (write using Write-HostColor)
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._BreadCrumbsString">
            <summary>
            Provide breadcrumb queue of the callstack
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._BreadCrumbsStringColored">
            <summary>
            Provide a breadcrumb queue of the callstack in color tags
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.BeginProcessing">
            <summary>
            Processes the begin phase of the cmdlet
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.ProcessRecord">
            <summary>
            Processes the process phase of the cmdlet
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.ResolveTarget(System.Object)">
            <summary>
            Processes the target transform rules on an input object
            </summary>
            <param name="Item">The item to transform</param>
            <returns>The transformed object</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.ResolveException(System.Exception)">
            <summary>
            Processes the specified exception specified
            </summary>
            <param name="Item">The exception to process</param>
            <returns>The transformed exception</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.ResolveLevel(Sqlcollaborative.Dbatools.Message.MessageLevel)">
            <summary>
            Processs the input level and apply policy and rules
            </summary>
            <param name="Level">The original level of the message</param>
            <returns>The processed level</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.GetMessage">
            <summary>
            Builds the message item for display of Verbose, Warning and Debug streams
            </summary>
            <returns>The message to return</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.GetMessageSimple">
            <summary>
            Builds the base message for internal system use.
            </summary>
            <returns>The message to return</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.GetMessageColor">
            <summary>
            Builds the message item if needed and returns it
            </summary>
            <returns>The message to return</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.GetMessageDeveloper">
            <summary>
            Non-host output in developermode
            </summary>
            <returns>The string to write on messages that don't go straight to Write-HostColor</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.GetMessageDeveloperColor">
            <summary>
            Host output in developermode
            </summary>
            <returns>The string to write on messages that go straight to Write-HostColor</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Computer.DiskSpace">
            <summary>
            Data Container for the output of Get-DbaDiskSpace
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.ComputerName">
            <summary>
            The computer that was scanned
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.Name">
            <summary>
            Name of the disk
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.Label">
            <summary>
            Label of the disk
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.Capacity">
            <summary>
            What's the total capacity of the disk?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.Free">
            <summary>
            How much is still free?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.PercentFree">
            <summary>
            How much is still free
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.BlockSize">
            <summary>
            What blocksize is the object set to
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.FileSystem">
            <summary>
            What filesystem is installed on the system
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.Type">
            <summary>
            What kind of drive is it?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.IsSqlDisk">
            <summary>
            Whether the drive is a sql disk. Nullable, because it is an optional property and may not always be included, thus a third state is necessary.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.Server">
            <summary>
            The computer that was scanned. Legacy-Name
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.DriveType">
            <summary>
            The type of drive this is in the legacy string notation
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.SizeInBytes">
            <summary>
            The total capacity in Bytes
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.FreeInBytes">
            <summary>
            The free space in Bytes
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.SizeInKB">
            <summary>
            The total capacity in KB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.FreeInKB">
            <summary>
            The free space in KB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.SizeInMB">
            <summary>
            The total capacity in MB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.FreeInMB">
            <summary>
            The free space in MB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.SizeInGB">
            <summary>
            The total capacity in GB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.FreeInGB">
            <summary>
            The free space in GB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.SizeInTB">
            <summary>
            The total capacity in TB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.FreeInTB">
            <summary>
            The free space in TB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.SizeInPB">
            <summary>
            The total capacity in PB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.FreeInPB">
            <summary>
            The free space in PB
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Computer.DriveType">
            <summary>
            What kind of drive are you?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.DriveType.Unknown">
            <summary>
            The drive type is not actually known
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.DriveType.NoRootDirectory">
            <summary>
            The drive has no root directory
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.DriveType.RemovableDisk">
            <summary>
            The drive is a removable disk
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.DriveType.LocalDisk">
            <summary>
            The drive is a local disk
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.DriveType.NetworkDrive">
            <summary>
            The drive is a network drive
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.DriveType.CompactDisk">
            <summary>
            The drive is a compact disk
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.DriveType.RAMDisk">
            <summary>
            The drive is a RAM disk
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Computer.PageFileSetting">
            <summary>
            Data container, listing pagefile settings.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.ComputerName">
            <summary>
            The name of the computer
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.AutoPageFile">
            <summary>
            Whether Automatic PageFile management is enabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.FileName">
            <summary>
            The pagefile name
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.Status">
            <summary>
            The pagefile status
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.SystemManaged">
            <summary>
            Whether the pagefile is system managed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.LastModified">
            <summary>
            When were the settings last changed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.LastAccessed">
            <summary>
            When were the settings last accessed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.AllocatedBaseSize">
            <summary>
            The base allocated pagefile size in MB
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.InitialSize">
            <summary>
            The initial pagefile size in MB
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.MaximumSize">
            <summary>
            The maximum pagefile size in MB
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.PeakUsage">
            <summary>
            The maximum percent of the pagefile limit that has been used
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.CurrentUsage">
            <summary>
            The currently used percentage of the pagefile limit that is in use.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Configuration.Config">
            <summary>
            Configuration Manager as well as individual configuration object.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.Name">
            <summary>
            The Name of the setting
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.FullName">
            <summary>
            The full name of the configuration entry, comprised of both Module and Name.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.Module">
            <summary>
            The module of the setting. Helps being able to group configurations.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.Description">
            <summary>
            A description of the specific setting
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.Type">
            <summary>
            The data type of the value stored in the configuration element.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.Value">
            <summary>
            The value stored in the configuration element
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.SafeValue">
            <summary>
            The value stored in the configuration element, but without deserializing objects.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.Unchanged">
            <summary>
            Whether the value of the configuration setting has been changed since its initialization.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.Handler">
            <summary>
            The handler script that is run whenever the configuration value is set.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.Validation">
            <summary>
            Validates the user input
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.Hidden">
            <summary>
            Setting this to true will cause the element to not be discovered unless using the '-Force' parameter on "Get-DbaConfig"
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.Initialized">
            <summary>
            Whether the setting has been initialized. This handles module imports and avoids modules overwriting settings when imported in multiple runspaces.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.PolicySet">
            <summary>
            Whether this setting was set by policy
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.PolicyEnforced">
            <summary>
            Whether this setting was set by policy and forbids changes to the configuration.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.SimpleExport">
            <summary>
            Enabling this causes export to json to use simple json serialization for data transmission.
            This is suitable for simple data that is not sensitive to conversion losses.
            Simple export leads to exports more easily readable to the human eye.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.ModuleExport">
            <summary>
            Whether this setting should be exported to a module specific file when exporting to json by modulename.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.RegistryData">
            <summary>
            The finalized value to put into the registry value when using policy to set this setting.
            Deprecated property.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.DefaultValue">
            <summary>
            The default value the configuration item was set to when initializing
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.Config.SetPersistedValue(Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType,System.String)">
            <summary>
            Applies the persisted value to the configuration item.
            This method should only be called by PSFramework internals
            </summary>
            <param name="Type">The type of data being specified</param>
            <param name="ValueString">The value string to register</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.Config.ResetValue">
            <summary>
            Resets the configuration value to its configured default value
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Configuration.ConfigScope">
            <summary>
            The location where a setting was applied
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigScope.UserDefault">
            <summary>
            The configuration is set as default value for the user
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigScope.UserMandatory">
            <summary>
            The configuration is enforced for the user
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigScope.SystemDefault">
            <summary>
            The configuration is set as default value for all users on the system
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigScope.SystemMandatory">
            <summary>
            The configuration is enforced for all users on the system.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigScope.FileUserLocal">
            <summary>
            The configuration is stored as Json in the per user local machine config directory.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigScope.FileUserShared">
            <summary>
            The configuration is stored as Json in the per user config directory shared across machines.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigScope.FileSystem">
            <summary>
            The configuration is stored as Json in the local computer config directory.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost">
            <summary>
            Host class providing static configuration settings that are constant across all runspaces within the process.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.Configurations">
            <summary>
            Hashtable containing all the configuration entries
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.Validation">
            <summary>
            Hashtable containing all the registered validations
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.ImportFromRegistryDone">
            <summary>
            Whether the import from registry has been completed. Prevents multiple imports and overwrites when importing the module multiple times.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.ConvertToPersistedValue(System.Object)">
            <summary>
            Converts any object into its persisted state.
            </summary>
            <param name="Item">The item to convert.</param>
            <returns>Its persisted state representation.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.ConvertFromPersistedValue(System.String,Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType)">
            <summary>
            Converts a persisted value back to its original data type
            </summary>
            <param name="PersistedValue">The value in its persisted state</param>
            <param name="Type">The type of the persisted value</param>
            <returns>The natural state of the value originally persisted</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.ConvertFromPersistedValue(System.String)">
            <summary>
            Converts a persisted value back to its original data type
            </summary>
            <param name="TypeQualifiedPersistedValue">The value in its persisted state, with a prefixed type identifier.</param>
            <returns>The natural state of the value originally persisted</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.Utf8ToBase64(System.String)">
            <summary>
            Converts a plain text into a base64 string
            </summary>
            <param name="Value">The string to convert</param>
            <returns>base64 encoded version of string.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.Base64ToUtf8(System.String)">
            <summary>
            Converts a base64 encoded string into plain text
            </summary>
            <param name="Value">The string to convert</param>
            <returns>Plain Text string</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue">
            <summary>
            Contains all information about a configuration item's value
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.Value">
            <summary>
            The runtime value of the setting.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.PersistedValue">
            <summary>
            The value in its persisted state
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.PersistedType">
            <summary>
            The kind of 
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.TypeQualifiedPersistedValue">
            <summary>
            The type qualified representation of the persisted value
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.SafeValue">
            <summary>
            Ensures wanton Get-PSFConfig will not deserialize persisted objects that might have registered deserialization in their module.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue._Value">
            <summary>
            Internal storage for the Value property
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue._PersistedValue">
            <summary>
            Internal storage for the PersistedValue property
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.ToString">
            <summary>
            The string representation of its actual value
            </summary>
            <returns>Returns the type-qualified string representation of its value</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.#ctor(System.String,Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType)">
            <summary>
            Creates a value object from persisted data
            </summary>
            <param name="PersistedValue">The value that will be persisted</param>
            <param name="PersistedType">The type of the value to be persisted</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.#ctor(System.Object)">
            <summary>
            Creates a value object from runtime data
            </summary>
            <param name="Value">The value that will be stored</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType">
            <summary>
            The data types supported by the configuration system.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Unknown">
            <summary>
            An unknown type, should be prevented
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Null">
            <summary>
            The value is as empty as the void.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Bool">
            <summary>
            The value is of a true/false kind
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Int">
            <summary>
            The value is a regular integer
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Double">
            <summary>
            The value is a double numeric value
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Long">
            <summary>
            The value is a long type
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.String">
            <summary>
            The value is a common string
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Timespan">
            <summary>
            The value is a regular timespan
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Datetime">
            <summary>
            The value is a plain datetime
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.ConsoleColor">
            <summary>
            The value is a fancy console color
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Array">
            <summary>
            The value is an array full of booty
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Hashtable">
            <summary>
            The value is a hashtable
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Object">
            <summary>
            The value is something indeterminate, but possibly complex
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Connection.ConnectionHost">
            <summary>
            Provides static tools for managing connections
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.Connections">
            <summary>
            List of all registered connections.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.BadConnectionTimeout">
            <summary>
            The time interval that must pass, before a connection using a known to not work connection protocol is reattempted
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableCache">
            <summary>
            Globally disables all caching done by the Computer Management functions.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableBadCredentialCache">
            <summary>
            Disables the caching of bad credentials. dbatools caches bad logon credentials for wmi/cim and will not reuse them.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableCredentialAutoRegister">
            <summary>
            Disables the automatic registration of working credentials. dbatools will caches the last working credential when connecting using wmi/cim and will use those rather than using known bad credentials
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.OverrideExplicitCredential">
            <summary>
            Enabling this will force the use of the last credentials known to work, rather than even trying explicit credentials.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.EnableCredentialFailover">
            <summary>
            Enables automatic failover to working credentials, when passed credentials either are known, or turn out to not work.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableCimPersistence">
            <summary>
            Globally disables the persistence of Cim sessions used to connect to a target system.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableConnectionCimRM">
            <summary>
            Whether the CM connection using Cim over WinRM is disabled globally
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableConnectionCimDCOM">
            <summary>
            Whether the CM connection using Cim over DCOM is disabled globally
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableConnectionWMI">
            <summary>
            Whether the CM connection using WMI is disabled globally
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableConnectionPowerShellRemoting">
            <summary>
            Whether the CM connection using PowerShell Remoting is disabled globally
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.SqlConnectionTimeout">
            <summary>
            The number of seconds before a sql connection attempt times out
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.PSSessions">
            <summary>
            List of all session containers used to maintain a cache
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ConnectionHost.PSSessionGet(System.Guid,System.String)">
            <summary>
            Returns a registered session for a given computer on a given runspace. Returns null if nothing is registered.
            </summary>
            <param name="Runspace">The host runspace that opened the session</param>
            <param name="ComputerName">The computer connected to</param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ConnectionHost.PSSessionSet(System.Guid,System.String,System.Management.Automation.Runspaces.PSSession)">
            <summary>
            Registeres a remote session under the owning runspace in its respective computer name
            </summary>
            <param name="Runspace">The runspace that owns the session</param>
            <param name="ComputerName">The computer the session connects to</param>
            <param name="Session">The session object</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ConnectionHost.PSSessionPurgeExpired">
            <summary>
            Searches the cache for an expired remoting session and purges it. After purging it from the list, it still needs to be closed!
            </summary>
            <returns>The session purged that then needs to be closed</returns>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ConnectionHost.PSSessionCountExpired">
            <summary>
            The number of expired sessions 
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.PSSessionTimeout">
            <summary>
            The time until established connections will be considered expired (if available)
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.PSSessionCacheEnabled">
            <summary>
            Whether sessions should be cached at all
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Connection.ManagementConnection">
            <summary>
            Contains management connection information for a windows server
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.ComputerName">
            <summary>
            The computer to connect to
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.DisableBadCredentialCache">
            <summary>
            Locally disables the caching of bad credentials
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.DisableCredentialAutoRegister">
            <summary>
            Locally disables the caching of working credentials
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.OverrideExplicitCredential">
            <summary>
            Locally overrides explicit credentials with working ones that were cached
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.EnableCredentialFailover">
            <summary>
            Locally enables automatic failover to working credentials, when passed credentials either are known, or turn out to not work.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.DisableCimPersistence">
            <summary>
            Locally disables the persistence of Cim sessions used to connect to a target system.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.DisabledConnectionTypes">
            <summary>
            Connectiontypes that will never be used
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.RestoreDefaultConfiguration">
            <summary>
            Restores all deviations from public policy back to default
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.OverrideConnectionPolicy">
            <summary>
            Whether this connection adhers to the global connection lockdowns or not
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.CimRM">
            <summary>
            Did the last connection attempt using CimRM work?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.LastCimRM">
            <summary>
            When was the last connection attempt using CimRM?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.CimDCOM">
            <summary>
            Did the last connection attempt using CimDCOM work?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.LastCimDCOM">
            <summary>
            When was the last connection attempt using CimRM?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.Wmi">
            <summary>
            Did the last connection attempt using Wmi work?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.LastWmi">
            <summary>
            When was the last connection attempt using CimRM?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.PowerShellRemoting">
            <summary>
            Did the last connection attempt using PowerShellRemoting work?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.LastPowerShellRemoting">
            <summary>
            When was the last connection attempt using CimRM?
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.ReportSuccess(Sqlcollaborative.Dbatools.Connection.ManagementConnectionType)">
            <summary>
            Report the successful connection against the computer of this connection
            </summary>
            <param name="Type">What connection type succeeded?</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.ReportFailure(Sqlcollaborative.Dbatools.Connection.ManagementConnectionType)">
            <summary>
            Report the failure of connecting to the target computer
            </summary>
            <param name="Type">What connection type failed?</param>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.Credentials">
            <summary>
            Any registered credentials to use on the connection.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.WindowsCredentialsAreBad">
            <summary>
            Whether the default windows credentials are known to not work against the target.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.UseWindowsCredentials">
            <summary>
            Whether windows credentials are known to be good. Do not build conditions on them being false, just on true.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.KnownBadCredentials">
            <summary>
            Credentials known to not work. They will not be used when specified.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.AddBadCredential(System.Management.Automation.PSCredential)">
            <summary>
            Adds a credentials object to the list of credentials known to not work.
            </summary>
            <param name="Credential">The bad credential that must be punished</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.AddGoodCredential(System.Management.Automation.PSCredential)">
            <summary>
            Reports a credentials object as being legit.
            </summary>
            <param name="Credential">The functioning credential that we may want to use again</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetCredential(System.Management.Automation.PSCredential)">
            <summary>
            Calculates, which credentials to use. Will consider input, compare it with know not-working credentials or use the configured working credentials for that.
            </summary>
            <param name="Credential">Any credential object a user may have explicitly specified.</param>
            <returns>The Credentials to use</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.IsBadCredential(System.Management.Automation.PSCredential)">
            <summary>
            Tests whether the input credential is on the list known, bad credentials
            </summary>
            <param name="Credential">The credential to test</param>
            <returns>True if the credential is known to not work, False if it is not yet known to not work</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.RemoveBadCredential(System.Management.Automation.PSCredential)">
            <summary>
            Removes an item from the list of known bad credentials
            </summary>
            <param name="Credential">The credential to remove</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetConnectionType(Sqlcollaborative.Dbatools.Connection.ManagementConnectionType,System.Boolean)">
            <summary>
            Returns the next connection type to try.
            </summary>
            <param name="ExcludedTypes">Exclude any type already tried and failed</param>
            <param name="Force">Overrides the timeout on bad connections</param>
            <returns>The next type to try.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetConnectionTypesTimed(System.DateTime)">
            <summary>
            Returns a list of all available connection types whose inherent timeout has expired.
            </summary>
            <param name="Timestamp">All last connection failures older than this point in time are considered to be expired</param>
            <returns>A list of all valid connection types</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetConnectionTypesTimed(System.TimeSpan)">
            <summary>
            Returns a list of all available connection types whose inherent timeout has expired.
            </summary>
            <param name="Timespan">All last connection failures older than this far back into the past are considered to be expired</param>
            <returns>A list of all valid connection types</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.#ctor">
            <summary>
            Creates a new, empty connection object. Necessary for serialization.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.#ctor(System.String)">
            <summary>
            Creates a new default connection object, containing only its computer's name and default results.
            </summary>
            <param name="ComputerName">The computer targeted. Will be forced to lowercase.</param>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.CimWinRMOptions">
            <summary>
            The options ot use when establishing a CIM Session
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetDefaultCimWsmanOptions">
            <summary>
            Returns the default wsman options object
            </summary>
            <returns>Something very default-y</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetCimRMInstance(System.Management.Automation.PSCredential,System.String,System.String)">
            <summary>
            Get all cim instances of the appropriate class using WinRM
            </summary>
            <param name="Credential">The credentiuls to use for the connection.</param>
            <param name="Class">The class to query.</param>
            <param name="Namespace">The namespace to look in (defaults to root\cimv2).</param>
            <returns>Hopefully a mountainload of CimInstances</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.QueryCimRMInstance(System.Management.Automation.PSCredential,System.String,System.String,System.String)">
            <summary>
            Get all cim instances matching the query using WinRM
            </summary>
            <param name="Credential">The credentiuls to use for the connection.</param>
            <param name="Query">The query to use requesting information.</param>
            <param name="Dialect">Defaults to WQL.</param>
            <param name="Namespace">The namespace to look in (defaults to root\cimv2).</param>
            <returns></returns>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.CimDComOptions">
            <summary>
            The options ot use when establishing a CIM Session
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetDefaultCimDcomOptions">
            <summary>
            Returns the default DCom options object
            </summary>
            <returns>Something very default-y</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetCimDComInstance(System.Management.Automation.PSCredential,System.String,System.String)">
            <summary>
            Get all cim instances of the appropriate class using DCOM
            </summary>
            <param name="Credential">The credentiuls to use for the connection.</param>
            <param name="Class">The class to query</param>
            <param name="Namespace">The namespace to look in (defaults to root\cimv2)</param>
            <returns>Hopefully a mountainload of CimInstances</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.QueryCimDCOMInstance(System.Management.Automation.PSCredential,System.String,System.String,System.String)">
            <summary>
            Get all cim instances matching the query using DCOM
            </summary>
            <param name="Credential">The credentiuls to use for the connection.</param>
            <param name="Query">The query to use requesting information.</param>
            <param name="Dialect">Defaults to WQL.</param>
            <param name="Namespace">The namespace to look in (defaults to root\cimv2).</param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.ToString">
            <summary>
            Simple string representation
            </summary>
            <returns>Returns the computerName it is connection for</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Connection.ManagementConnectionProtocolState">
            <summary>
            The various types of state a connection-protocol may have
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionProtocolState.Unknown">
            <summary>
            The default initial state, before any tests are performed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionProtocolState.Success">
            <summary>
            A successful connection was last established
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionProtocolState.Error">
            <summary>
            Connecting using the relevant protocol failed last it was tried
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionProtocolState.Disabled">
            <summary>
            The relevant protocol has been disabled and should not be used
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Connection.ManagementConnectionType">
            <summary>
            The various ways to connect to a windows server fopr management purposes.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionType.None">
            <summary>
            No Connection-Type
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionType.CimRM">
            <summary>
            Cim over a WinRM connection
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionType.CimDCOM">
            <summary>
            Cim over a DCOM connection
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionType.Wmi">
            <summary>
            WMI Connection
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionType.PowerShellRemoting">
            <summary>
            Connecting with PowerShell remoting and performing WMI queries locally
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Connection.PSSessionContainer">
            <summary>
            The container that lists all sessions for a given runspace
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.Runspace">
            <summary>
            The runspace that owns the sessions
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.CountExpired">
            <summary>
            The count of expired sessions registered
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.Sessions">
            <summary>
            List of sessions and their associated computer names
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.ConnectionTimestamps">
            <summary>
            List of timestamps, when the last command was run against them
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.#ctor(System.Guid)">
            <summary>
            Creates a list of sessions the current runspace is connected to.
            </summary>
            <param name="Runspace">The Guid of the runspace that is the owner of the registered sessions</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.Get(System.String)">
            <summary>
            Returns the requested session.
            </summary>
            <param name="ComputerName">The name of the host whose connection to retrieve</param>
            <returns>The established connection to the host, null if none exists.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.Set(System.String,System.Management.Automation.Runspaces.PSSession)">
            <summary>
            Sets a session and writes its timestamp to the cache
            </summary>
            <param name="ComputerName">The hostname it connects to.</param>
            <param name="Session">The session that is being registered.</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.GetExpiredNames">
            <summary>
            Returns the name of hostnames with expired sessions
            </summary>
            <returns>THe hostnames whose session has expired</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.PurgeExpiredSession">
            <summary>
            Removes an expired session from the cache, an returns it, so it can be properly closed.
            </summary>
            <returns>Returns a session to disconnect</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Connection.SqlConnectionProtocol">
            <summary>
            The protocol to connect over via SMO
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.SqlConnectionProtocol.Any">
            <summary>
            Connect using any protocol available
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.SqlConnectionProtocol.TCP">
            <summary>
            Connect using TCP/IP
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.SqlConnectionProtocol.NP">
            <summary>
            Connect using named pipes or shared memory
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Database.BackupHistory">
            <summary>
            Object containing the information about the history of mankind ... or a database backup. WHo knows.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.ComputerName">
            <summary>
            The name of the computer running MSSQL Server
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.InstanceName">
            <summary>
            The Instance that was queried
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.SqlInstance">
            <summary>
            The full Instance name as seen from outside
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.Database">
            <summary>
            The Database that was backed up
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.UserName">
            <summary>
            The user that is running the backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.Start">
            <summary>
            When was the backup started
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.End">
            <summary>
            When did the backup end
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.Duration">
            <summary>
            What was the longest duration among the backups
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.Path">
            <summary>
            Where is the backup stored
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.TotalSize">
            <summary>
            What is the total size of the backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.CompressedBackupSize">
            <summary>
            What is the total compressesed size of the backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.CompressionRatio">
            <summary>
            What is the ratio of total size to compressed size of the backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.Type">
            <summary>
            The kind of backup this was
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.BackupSetId">
            <summary>
            The ID for the Backup job
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.DeviceType">
            <summary>
            What kind of backup-device was the backup stored to
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.Software">
            <summary>
            What is the name of the backup software?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.FullName">
            <summary>
            The full name of the backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.FileList">
            <summary>
            The files that are part of this backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.Position">
            <summary>
            The position of the backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.FirstLsn">
            <summary>
            The first Log Sequence Number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.DatabaseBackupLsn">
            <summary>
            The Log Squence Number that marks the beginning of the backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.CheckpointLsn">
            <summary>
            The checkpoint's Log Sequence Number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.LastLsn">
            <summary>
            The last Log Sequence Number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.SoftwareVersionMajor">
            <summary>
            The primary version number of the Sql Server
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.IsCopyOnly">
            <summary>
            Was the backup performed with the CopyOnlyOption
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.LastRecoveryForkGUID">
            <summary>
            Recovery Fork backup was takeon
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.RecoveryModel">
            <summary>
            Recovery Model of the database when backup was taken
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Database.Dependency">
            <summary>
            Class containing all dependency information over a database object
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.ComputerName">
            <summary>
            The name of the SQL server from whence the query came
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.ServiceName">
            <summary>
            Name of the service running the database containing the dependency
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.SqlInstance">
            <summary>
            The Instance the database containing the dependency is running in.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Dependent">
            <summary>
            The name of the dependent
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Type">
            <summary>
            The kind of object the dependent is
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Owner">
            <summary>
            The owner of the dependent (usually the Database)
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.IsSchemaBound">
            <summary>
            Whether the dependency is Schemabound. If it is, then the creation statement order is of utmost importance.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Parent">
            <summary>
            The immediate parent of the dependent. Useful in multi-tier dependencies.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.ParentType">
            <summary>
            The type of object the immediate parent is.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Script">
            <summary>
            The script used to create the object.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Tier">
            <summary>
            The tier in the dependency hierarchy tree. Used to determine, which dependency must be applied in which order.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Object">
            <summary>
            The smo object of the dependent.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Urn">
            <summary>
            The Uniform Resource Name of the dependent.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.OriginalResource">
            <summary>
            The object of the original resource, from which the dependency hierachy has been calculated.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord">
            <summary>
            An error record written by dbatools
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.CategoryInfo">
            <summary>
            The category of the error
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.ErrorDetails">
            <summary>
            The details on the error
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.Exception">
            <summary>
            The actual exception thrown
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.FullyQualifiedErrorId">
            <summary>
            The specific error identity, used to identify the target
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.InvocationInfo">
            <summary>
            The details of how this was called.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.ScriptStackTrace">
            <summary>
            The script's stacktrace
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.TargetObject">
            <summary>
            The object being processed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.FunctionName">
            <summary>
            The name of the function throwing the error
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.Timestamp">
            <summary>
            When was the error thrown
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.Message">
            <summary>
            The message that was written in a userfriendly manner
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.Runspace">
            <summary>
            The runspace the error occured on.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.#ctor">
            <summary>
            Create an empty record
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.#ctor(System.Management.Automation.ErrorRecord,System.String,System.DateTime,System.String)">
            <summary>
            Create a filled out error record
            </summary>
            <param name="Record">The original error record</param>
            <param name="FunctionName">The function that wrote the error</param>
            <param name="Timestamp">When was the error generated</param>
            <param name="Message">What message was passed when writing the error</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.#ctor(System.Management.Automation.ErrorRecord,System.String,System.DateTime,System.String,System.Guid)">
            <summary>
            Create a filled out error record
            </summary>
            <param name="Record">The original error record</param>
            <param name="FunctionName">The function that wrote the error</param>
            <param name="Timestamp">When was the error generated</param>
            <param name="Message">What message was passed when writing the error</param>
            <param name="Runspace">The ID of the runspace writing the error. Used to separate output between different runspaces in the same process.</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.dbaSystem.DebugHost">
            <summary>
            Hosts static debugging values and methods
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DebugHost.ImportTimeEntries">
            <summary>
            Lists the duration for the last import of dbatools.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.DebugHost.ImportTime">
            <summary>
            Returns the calculated time each phase took during the last import of dbatool.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.dbaSystem.StartTimeEntry">
            <summary>
            Entry containing the information of a step during the import sequence
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.StartTimeEntry.Action">
            <summary>
            The action that has been taken
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.StartTimeEntry.Timestamp">
            <summary>
            When was the action taken?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.StartTimeEntry.Runspace">
            <summary>
            The runspace the entry was written on
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.dbaSystem.StartTimeEntry.#ctor(System.String,System.DateTime,System.Guid)">
            <summary>
            Creates a new StartTimeEntry
            </summary>
            <param name="Action">The action that has been taken</param>
            <param name="Timestamp">When was the action taken?</param>
            <param name="Runspace">The runspace the entry was written on</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.dbaSystem.StartTimeResult">
            <summary>
            The processed result how long a given step took
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.StartTimeResult.Action">
            <summary>
            What action was taken?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.StartTimeResult.Duration">
            <summary>
            How long did things take?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.StartTimeResult.Start">
            <summary>
            When did this action start?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.StartTimeResult.End">
            <summary>
            When did this action end?
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.dbaSystem.StartTimeResult.#ctor(System.String,System.DateTime,System.DateTime)">
            <summary>
            Creates a new StartTimeResult with all values preconfigured
            </summary>
            <param name="Action">The action that was taken</param>
            <param name="Start">When did the action start?</param>
            <param name="End">When did the action end?</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.dbaSystem.SystemHost">
            <summary>
            Provides system-wide static resources regarding the dbatools system runtime in general
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.SystemHost.UnattendedMode">
            <summary>
            When this is set to true, functions must assume dbatools is in unattended mode. May not ask for user input of any kind.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.SystemHost.ModuleBase">
            <summary>
            Path where the module was located when imported
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.SystemHost.ModuleImported">
            <summary>
            Flag whether the module has ever been imported in the current process. If that is true, several things (such as importing libraries) is no longer necessary and will be skipped on import.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply">
            <summary>
            The reply the browser service gave
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.MachineName">
            <summary>
            The machine name of the computer
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.ComputerName">
            <summary>
            the computername of the computer
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.SqlInstance">
            <summary>
            The instance running on the computer
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.InstanceName">
            <summary>
            The name of the instance, running on the computer
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.TCPPort">
            <summary>
            The port number the instance is running under
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.Version">
            <summary>
            The version of the SQL Server
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.IsClustered">
            <summary>
            Whether the instance is part of a cluster or no.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.ToString">
            <summary>
            Override in order to make it look neater in PowerShell
            </summary>
            <returns></returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Discovery.DbaInstanceAvailability">
            <summary>
            Indiciator for whether an instance is known to be available or not
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceAvailability.Unknown">
            <summary>
            It is not known, whether the instance is available or not
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceAvailability.Available">
            <summary>
            The instance is known to be available
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceAvailability.Unavailable">
            <summary>
            The instance is known to be not available
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Discovery.DbaInstanceConfidenceLevel">
            <summary>
            How high is our confidence that this is a valid instance?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceConfidenceLevel.None">
            <summary>
            No confidence at all. There is virtually no way for this to be an instance
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceConfidenceLevel.Low">
            <summary>
            We have a few indications, but couldn't follow them up
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceConfidenceLevel.Medium">
            <summary>
            We're fairly sure this is legit, but can't guarantee it
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceConfidenceLevel.High">
            <summary>
            This absolutely is an instance
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Discovery.DbaInstanceDiscoveryType">
            <summary>
            What discovery mechanisms to use
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceDiscoveryType.IPRange">
            <summary>
            We shall sweep the network for instances, by targeting every IP within a range.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceDiscoveryType.Domain">
            <summary>
            We shall search for SQL SPNs in active directory
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceDiscoveryType.DataSourceEnumeration">
            <summary>
            We shall use the SSMS Data Sizrce Enumeration mechanism and hope for the best
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceDiscoveryType.All">
            <summary>
            We shall use all tools in our control to find stuff
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport">
            <summary>
            The report on a discovered instance
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.MachineName">
            <summary>
            The computername of the underlying machine. Usually equal to the computername, but may differ in case of clusters
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.ComputerName">
            <summary>
            The computername of the target
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.InstanceName">
            <summary>
            The name of the instance
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.FullName">
            <summary>
            The full server instance name
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.SqlInstance">
            <summary>
            The full name usable to connect via SMO
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.Port">
            <summary>
            The port number the server listens on
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.Timestamp">
            <summary>
            When the scan was concluded
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.TcpConnected">
            <summary>
            Was a TCP connect successful?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.SqlConnected">
            <summary>
            Was a connection via SQL successful (even if we got access denied)
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.DnsResolution">
            <summary>
            The DNS Resolution object
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.Ping">
            <summary>
            The ping resolution object
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.BrowseReply">
            <summary>
            The reply received from the browse request
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.Services">
            <summary>
            The windows services for the instance
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.SystemServices">
            <summary>
            The SQL Server services that do not belong to that instance alone
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.SPNs">
            <summary>
            Service Principal Names found
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.PortsScanned">
            <summary>
            The ports that have been scanned
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.Availability">
            <summary>
            What we know about its availability
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.Confidence">
            <summary>
            How confident we are, that this is a real instance
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.ScanTypes">
            <summary>
            What we used to scan the instance
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType">
            <summary>
            The mechanisms we use to determine, whether a given host contains a legit instance
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.TCPPort">
            <summary>
            Try connecting to specific ports
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.SqlConnect">
            <summary>
            Try to connect to discovered instances (improves confidence)
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.SqlService">
            <summary>
            Check the windows services on the target
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.DNSResolve">
            <summary>
            Try resolving a computername in DNS
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.SPN">
            <summary>
            Scan the SPNs for the targeted computer
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.Browser">
            <summary>
            Try contacting the local browser service and demand answers
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.Ping">
            <summary>
            See whether you can ping the host
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.All">
            <summary>
            Do EVERYTHING
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.Default">
            <summary>
            Do all the things we consider sane defaults
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Discovery.DbaPortReport">
            <summary>
            We tried to connect to a port, how did it go?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaPortReport.ComputerName">
            <summary>
            The name of the computer connected to
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaPortReport.Port">
            <summary>
            The number of the port we tried to connect to.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaPortReport.IsOpen">
            <summary>
            Whether the port was open
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Discovery.DbaPortReport.#ctor">
            <summary>
            Creates an empty report (serialization uses this)
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Discovery.DbaPortReport.#ctor(System.String,System.Int32,System.Boolean)">
            <summary>
            Creates a filled in report
            </summary>
            <param name="ComputerName">The name of the computer connected to</param>
            <param name="Port">The port we tried to connect to</param>
            <param name="IsOpen">Whether things worked out</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Discovery.DbaPortReport.ToString">
            <summary>
            Displays port connection reports in a user friendly manner
            </summary>
            <returns></returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Exceptions.BloodyHellGiveMeSomethingToWorkWithException">
            <summary>
            An exception that is thrown by parameter classes when given empty input
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Exceptions.BloodyHellGiveMeSomethingToWorkWithException.ParameterClass">
            <summary>
            The parameter class that did the throwing
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Exceptions.BloodyHellGiveMeSomethingToWorkWithException.#ctor(System.String,System.Exception)">
            <summary>
            Creates an exception with a message and a nested exception
            </summary>
            <param name="Message">The message to tell</param>
            <param name="Inner">The inner exception to nest</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Exceptions.BloodyHellGiveMeSomethingToWorkWithException.#ctor(System.String,System.String)">
            <summary>
            Creates an exception with a message and a ParameterClass
            </summary>
            <param name="Message">The message to tell</param>
            <param name="ParameterClass">The Parameter Class that threw the exception</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Exceptions.BloodyHellGiveMeSomethingToWorkWithException.#ctor(System.String,System.Exception,System.String)">
            <summary>
            Creates an exception with a message, a nested exception and a ParameterClass
            </summary>
            <param name="Message">The message to tell</param>
            <param name="Inner">The inner exception to nest</param>
            <param name="ParameterClass">The Parameter Class that threw the exception</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.General.ExecutionMode">
            <summary>
            What kind of mode do you want to run a command in?
            This allows the user to choose how a dbatools function handles a bump in the execution where terminating directly may not be actually mandated.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.General.ExecutionMode.Strict">
            <summary>
            When encountering issues, terminate, or skip the currently processed input, rather than continue.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.General.ExecutionMode.Lazy">
            <summary>
            Continue as able with a best-effort attempt. Simple verbose output should do the rest.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.General.ExecutionMode.Report">
            <summary>
            Continue, but provide output that can be used to identify the operations that had issues.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Maintenance.MaintenanceHost">
            <summary>
            Host class providing access to resources need to perform dbatools maintenance
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceHost.Tasks">
            <summary>
            The register of available tasks.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Maintenance.MaintenanceHost.HasDueTasks">
            <summary>
            Whether there are any due tasks
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Maintenance.MaintenanceHost.GetNextTask(System.String[])">
            <summary>
            Returns the next task to perform. Returns null when there are no more tasks to perform
            </summary>
            <param name="Exclusions">List of tasks not to return, even if they are ready to execute again. This avoids one misconfigured task starving all lower priority tasks</param>
            <returns>The next task to perform.</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Maintenance.MaintenancePriority">
            <summary>
            How high the priority of the task. Higher priority tasks take precedence over low priority tasks.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenancePriority.Trivial">
            <summary>
            This task is completely trivial and can be done whenever there is some spare time for it
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenancePriority.Low">
            <summary>
            The task is not very significant, but should be dealt with at some point
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenancePriority.Medium">
            <summary>
            Average priority task
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenancePriority.High">
            <summary>
            An important task that will take precedence over most other tasks
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenancePriority.Critical">
            <summary>
            A task so critical, that it should be considered to move it to synchronous execution instead.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask">
            <summary>
            An individual task assigned to the maintenance engine
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.Name">
            <summary>
            The name of the task to execute. No duplciates are possible.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.Once">
            <summary>
            Whether the task should be done once only
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.Interval">
            <summary>
            The interval at which the task should be performed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.Delay">
            <summary>
            If the task need not be performed right away, it can be delayed, in order to prioritize more important initialization tasks
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.Registered">
            <summary>
            When was the task first registered. Duplicate registration calls will not increment this value.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.LastExecution">
            <summary>
            When was the task last executed.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.Priority">
            <summary>
            How important is this task?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.ScriptBlock">
            <summary>
            The task code to execute
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.IsDue">
            <summary>
            Whether the task is due and should be executed
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.DbatoolsException">
            <summary>
            Wrapper class that can emulate any exception for purpose of serialization without blowing up the storage space consumed
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsException.GetException">
            <summary>
            Returns the original exception object that we interpreted. This is on purpose not a property, as we want to avoid messing with serialization size.
            </summary>
            <returns>The original exception that got thrown</returns>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.Message">
            <summary>
            The actual Exception Message
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.Source">
            <summary>
            The original source of the Exception
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.StackTrace">
            <summary>
            Where on the callstack did the exception occur?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.TargetSite">
            <summary>
            What was the target site on the code that caused it. This property has been altered to avoid export issues, if a string representation is not sufficient, access the original exception using GetException()
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.HResult">
            <summary>
            The HResult of the exception. Useful in debugging native code errors.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.HelpLink">
            <summary>
            Link to a proper help article.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.Data">
            <summary>
            Additional data that has been appended
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.InnerException">
            <summary>
            The inner exception in a chain of exceptions.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.ExceptionTypeName">
            <summary>
            The full namespace name of the exception that has been wrapped.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.ExceptionData">
            <summary>
            Contains additional properties other exceptions might contain.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.CategoryInfo">
            <summary>
            The category of the error
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.ErrorDetails">
            <summary>
            The details on the error
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.FullyQualifiedErrorId">
            <summary>
            The specific error identity, used to identify the target
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.InvocationInfo">
            <summary>
            The details of how this was called.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.ScriptStackTrace">
            <summary>
            The script's stacktrace
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.TargetObject">
            <summary>
            The object being processed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.FunctionName">
            <summary>
            The name of the function throwing the error
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.Timestamp">
            <summary>
            When was the error thrown
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.Runspace">
            <summary>
            The runspace the error occured on.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.ComputerName">
            <summary>
            The computer the error occured on.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsException.#ctor">
            <summary>
            Creates an empty exception object. Mostly for serialization support
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsException.#ctor(System.Exception)">
            <summary>
            Creates an exception based on an original exception object
            </summary>
            <param name="Except">The exception to wrap around</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsException.#ctor(System.Management.Automation.ErrorRecord)">
            <summary>
            Creates a rich information exception object based on a full error record as recorded by PowerShell
            </summary>
            <param name="Record">The error record to copy from</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsException.#ctor(System.Exception,System.String,System.DateTime,System.String,System.Guid,System.String)">
            <summary>
            Creates a new exception object with rich meta information from the PowerShell runtime.
            </summary>
            <param name="Except">The exception thrown</param>
            <param name="FunctionName">The name of the function in which the error occured</param>
            <param name="Timestamp">When did the error occur</param>
            <param name="Message">The message to add to the exception</param>
            <param name="Runspace">The ID of the runspace from which the exception was thrown. Useful in multi-runspace scenarios.</param>
            <param name="ComputerName">The computer the error occured on.</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsException.#ctor(System.Management.Automation.ErrorRecord,System.String,System.DateTime,System.String,System.Guid,System.String)">
            <summary>
            Creates a new exception object with rich meta information from the PowerShell runtime.
            </summary>
            <param name="Record">The error record written</param>
            <param name="FunctionName">The name of the function in which the error occured</param>
            <param name="Timestamp">When did the error occur</param>
            <param name="Message">The message to add to the exception</param>
            <param name="Runspace">The ID of the runspace from which the exception was thrown. Useful in multi-runspace scenarios.</param>
            <param name="ComputerName">The computer the error occured on.</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsException.ToString">
            <summary>
            Returns a string representation of the exception.
            </summary>
            <returns></returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord">
            <summary>
            Carrier class, designed to hold an arbitrary number of exceptions. Used for exporting to XML in nice per-incident packages.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.Runspace">
            <summary>
            Runspace where shit happened.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.ComputerName">
            <summary>
            The computer name the exception was written on
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.Timestamp">
            <summary>
            When did things go bad?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.FunctionName">
            <summary>
            Name of the function, where fail happened.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.ModuleName">
            <summary>
            The module of the function where fail happened
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.Tags">
            <summary>
            The tags that were applied to the failure
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.Message">
            <summary>
            The message the poor user was shown.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.ExceptionType">
            <summary>
            Displays the name of the exception, the make scanning exceptions easier.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.TargetObject">
            <summary>
            The target object of the first exception in the list, if any
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.Exceptions">
            <summary>
            List of Exceptions that are part of the incident (usually - but not always - only one).
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.#ctor">
            <summary>
            Creates an empty container. Ideal for the homeworker who loves doing it all himself.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.#ctor(Sqlcollaborative.Dbatools.Message.DbatoolsException)">
            <summary>
            Creates a container filled with the first exception.
            </summary>
            <param name="Exception"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.#ctor(System.Guid,System.String,System.DateTime,System.String,System.String,System.Collections.Generic.List{System.String},System.String)">
            <summary>
            Creates a container filled with the meta information but untouched by exceptions
            </summary>
            <param name="Runspace">The runspace where it all happened</param>
            <param name="ComputerName">The computer the error was recorded</param>
            <param name="Timestamp">When did it happen?</param>
            <param name="FunctionName">Where did it happen?</param>
            <param name="ModuleName">The name of the module where fail happened</param>
            <param name="Tags">The tags that were assigned to the failure</param>
            <param name="Message">What did the witness have to say?</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.LogEntry">
            <summary>
            An individual entry for the message log
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Message">
            <summary>
            The message logged
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Type">
            <summary>
            What kind of entry was this?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Timestamp">
            <summary>
            When was the message logged?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.FunctionName">
            <summary>
            What function wrote the message
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.ModuleName">
            <summary>
            The name of the module of the function that wrote the message
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Tags">
            <summary>
            The tags applied to the message
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Level">
            <summary>
            What level was the message?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Runspace">
            <summary>
            What runspace was the message written from?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.ComputerName">
            <summary>
            The computer the message was generated on
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.TargetObject">
            <summary>
            The object that was the focus of this message.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.File">
            <summary>
            The file from which the message was written.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Line">
            <summary>
            The line on which the message was written.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.CallStack">
            <summary>
            The callstack when the message was written.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Username">
            <summary>
            The user that did the writing.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.LogEntry.#ctor">
            <summary>
            Creates an empty log entry
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.LogEntry.#ctor(System.String,Sqlcollaborative.Dbatools.Message.LogEntryType,System.DateTime,System.String,System.String,System.Collections.Generic.List{System.String},Sqlcollaborative.Dbatools.Message.MessageLevel,System.Guid,System.String,System.Object,System.String,System.Int32,System.Collections.Generic.IEnumerable{System.Management.Automation.CallStackFrame},System.String)">
            <summary>
            Creates a filled out log entry
            </summary>
            <param name="Message">The message that was logged</param>
            <param name="Type">The type(s) of message written</param>
            <param name="Timestamp">When was the message logged</param>
            <param name="FunctionName">What function wrote the message</param>
            <param name="ModuleName">Name of the module the function writing this message came from</param>
            <param name="Tags">Tags that were applied to the message</param>
            <param name="Level">What level was the message written at.</param>
            <param name="Runspace">The ID of the runspace that wrote the message.</param>
            <param name="ComputerName">The computer the message was generated on.</param>
            <param name="TargetObject">The object this message was all about.</param>
            <param name="File">The file of the code that wrote the message.</param>
            <param name="Line">The line on which the message was written.</param>
            <param name="CallStack">The callstack that triggered the write.</param>
            <param name="Username">The user responsible for running the code that is writing the message.</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.LogEntryType">
            <summary>
            The kind of information the logged entry was.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntryType.None">
            <summary>
            This entry wasn't written to any stream
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntryType.Information">
            <summary>
            A message that was written to the current host equivalent, if available also to the information stream
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntryType.Verbose">
            <summary>
            A message that was written to the verbose stream
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntryType.Debug">
            <summary>
            A message that was written to the Debug stream
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntryType.Warning">
            <summary>
            A message written to the warning stream
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.LogHost">
            <summary>
            Provides static information storage for logging related settings, as well as housing the logging queues.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MaxErrorCount">
            <summary>
            The maximum numbers of error records maintained in-memory.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MaxMessageCount">
            <summary>
            The maximum number of messages that can be maintained in the in-memory message queue
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MaxMessagefileBytes">
            <summary>
            The maximum size of a given logfile. When reaching this limit, the file will be abandoned and a new log created. Set to 0 to not limit the size.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MaxMessagefileCount">
            <summary>
            The maximum number of logfiles maintained at a time. Exceeding this number will cause the oldest to be culled. Set to 0 to disable the limit.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MaxErrorFileBytes">
            <summary>
            The maximum size all error files combined may have. When this number is exceeded, the oldest entry is culled.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MaxTotalFolderSize">
            <summary>
            This is the upper limit of length all items in the log folder may have combined across all processes.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.LoggingPath">
            <summary>
            Path to where the logfiles live.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MaxLogFileAge">
            <summary>
            Any logfile older than this will automatically be cleansed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MessageLogFileEnabled">
            <summary>
            Governs, whether a log file for the system messages is written
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MessageLogEnabled">
            <summary>
            Governs, whether a log of recent messages is kept in memory
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.ErrorLogFileEnabled">
            <summary>
            Governs, whether log files for errors are written
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.ErrorLogEnabled">
            <summary>
            Governs, whether a log of recent errors is kept in memory
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.OutQueueError">
            <summary>
            The outbound queue for errors. These will be processed and written to xml
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.OutQueueLog">
            <summary>
            The outbound queue for logs. These will be processed and written to logfile
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.LogHost.GetErrors">
            <summary>
            Retrieves a copy of the Error stack
            </summary>
            <returns>All errors thrown by functions using the message or flowcontrol system</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.LogHost.GetLog">
            <summary>
            Retrieves a copy of the message log
            </summary>
            <returns>All messages logged this session.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.LogHost.WriteErrorEntry(System.Management.Automation.ErrorRecord[],System.String,System.String,System.Collections.Generic.List{System.String},System.DateTime,System.String,System.Guid,System.String)">
            <summary>
            Write an error record to the log
            </summary>
            <param name="Record">The actual error record as powershell wrote it</param>
            <param name="FunctionName">The name of the function writing the error</param>
            <param name="ModuleName">The name of the module the function writing the error came from</param>
            <param name="Tags">The tags that were assigned to the error event</param>
            <param name="Timestamp">When was the error written</param>
            <param name="Message">What message was passed to the user</param>
            <param name="Runspace">The runspace the message was written from</param>
            <param name="ComputerName">The computer the error was written on</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.LogHost.WriteLogEntry(System.String,Sqlcollaborative.Dbatools.Message.LogEntryType,System.DateTime,System.String,System.String,System.Collections.Generic.List{System.String},Sqlcollaborative.Dbatools.Message.MessageLevel,System.Guid,System.String,System.String,System.Int32,System.Collections.Generic.IEnumerable{System.Management.Automation.CallStackFrame},System.String,System.Object)">
            <summary>
            Write a new entry to the log
            </summary>
            <param name="Message">The message to log</param>
            <param name="Type">The type of the message logged</param>
            <param name="Timestamp">When was the message generated</param>
            <param name="FunctionName">What function wrote the message</param>
            <param name="ModuleName">What module did the function writing this message come from?</param>
            <param name="Tags">The tags that were applied to the message</param>
            <param name="Level">At what level was the function written</param>
            <param name="Runspace">The runspace the message is coming from</param>
            <param name="ComputerName">The computer the message was generated on</param>
            <param name="File">The file from which the message was written</param>
            <param name="Line">The line on which the message was written</param>
            <param name="TargetObject">The object associated with a given message.</param>
            <param name="CallStack">The callstack at the moment the message was written.</param>
            <param name="Username">The name of the user under which the code being executed</param>
            <returns>The entry that is being written</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.MessageEventSubscription">
            <summary>
            Condition and logic to be executed on message events
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.Name">
            <summary>
            Name of the event subscription, must be unique.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.ScriptBlock">
            <summary>
            Scriptblock to execute if the condition is met
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription._MessageFilter">
            <summary>
            The internally stored filter value for Message
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.MessageFilter">
            <summary>
            The value the Message is filtered by
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.MessageFilterSet">
            <summary>
            Whether filtering by Message was enabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription._ModuleNameFilter">
            <summary>
            The internally stored filter value for ModuleName
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.ModuleNameFilter">
            <summary>
            The value the ModuleName is filtered by
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.ModuleNameFilterSet">
            <summary>
            Whether filtering by ModuleName was enabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription._FunctionNameFilter">
            <summary>
            The internally stored filter value for FunctionName
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.FunctionNameFilter">
            <summary>
            The value the FunctionName is filtered by
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.FunctionNameFilterSet">
            <summary>
            Whether filtering by FunctionName was enabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription._TargetFilter">
            <summary>
            The internally stored filter value for Target
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.TargetFilter">
            <summary>
            The value the Target is filtered by
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.TargetFilterSet">
            <summary>
            Whether filtering by Target was enabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription._LevelFilter">
            <summary>
            The internally stored filter value for Level
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.LevelFilter">
            <summary>
            The value the Level is filtered by
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.LevelFilterSet">
            <summary>
            Whether filtering by Level was enabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription._TagFilter">
            <summary>
            The internally stored filter value for Tag
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.TagFilter">
            <summary>
            The value the Tag is filtered by
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.TagFilterSet">
            <summary>
            Whether filtering by Tag was enabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription._RunspaceFilter">
            <summary>
            The internally stored filter value for Runspace
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.RunspaceFilter">
            <summary>
            The value the Runspace is filtered by
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.RunspaceFilterSet">
            <summary>
            Whether filtering by Runspace was enabled
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.Applies(Sqlcollaborative.Dbatools.Message.LogEntry)">
            <summary>
            Checks, whether a given entry matches the filter defined in this subscription
            </summary>
            <param name="Entry">The entry to validate</param>
            <returns>Whether the subscription should react to this entry</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.MessageHost">
            <summary>
            Provides static resources to the messaging subsystem
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.MaximumInformation">
            <summary>
            The maximum message level to still display to the user directly.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.MaximumVerbose">
            <summary>
            The maxium message level where verbose information is still written.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.MaximumDebug">
            <summary>
            The maximum message level where debug information is still written.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.MinimumInformation">
            <summary>
            The minimum required message level for messages that will be shown to the user.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.MinimumVerbose">
            <summary>
            The minimum required message level where verbose information is written.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.MinimumDebug">
            <summary>
            The minimum required message level where debug information is written.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.InfoColor">
            <summary>
            The color stuff gets written to the console in
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.InfoColorEmphasis">
            <summary>
            The color important stuff gets written to the console in
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.InfoColorSubtle">
            <summary>
            The color background stuff gets written to the console in
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.DeveloperColor">
            <summary>
            The color stuff gets written to the console in, when developer mode is enabled and the message would not have been written after all
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.DeveloperMode">
            <summary>
            Enables the developer mode. In this all messages are written to the console, in order to make it easier to troubleshoot issues.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.NestedLevelDecrement">
            <summary>
            Message levels can decrease by nested level. This causes messages to have an increasingly reduced level as the size of the callstack increases. 
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.DisableVerbosity">
            <summary>
            Globally override all verbosity
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.EnableMessageTimestamp">
            <summary>
            Include message timestamps in verbose message output
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.EnableMessageDisplayCommand">
            <summary>
            Include the message display command in the verbose message output
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.EnableMessageBreadcrumbs">
            <summary>
            Include the entire callstack in the verbose message output
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.TransformErrorQueueSize">
            <summary>
            The size of the transform error queue. When adding more than this, the oldest entry will be discarded
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.ExceptionTransforms">
            <summary>
            Provides the option to transform exceptions based on the original exception type
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.TargetTransforms">
            <summary>
            Provides the option to transform target objects based on type. This is sometimes important when working with live state objects that should not be serialized.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.TransformErrors">
            <summary>
            The list of transformation errors that occured.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.MessageHost.GetTransformErrors">
            <summary>
            Returns the current queue of failed transformations
            </summary>
            <returns>The list of transformations that failed</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.MessageHost.WriteTransformError(System.Management.Automation.ErrorRecord,System.String,System.String,System.Object,Sqlcollaborative.Dbatools.Message.TransformType,System.Guid)">
            <summary>
            Writes a new transform error
            </summary>
            <param name="Record">The record of what went wrong</param>
            <param name="FunctionName">The name of the function writing the transformed message</param>
            <param name="ModuleName">The module the function writing the transformed message is part of</param>
            <param name="Object">The object that should have been transformed</param>
            <param name="Type">The type of transform that was attempted</param>
            <param name="Runspace">The runspace it all happened on</param>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.ExceptionTransformList">
            <summary>
            List of custom transforms for exceptions
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.TargetTransformlist">
            <summary>
            List of custom transforms for targets
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.MessageLevelModifiers">
            <summary>
            List of all modifiers that apply to message levels
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.Events">
            <summary>
            List of events that subscribe to messages being written
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.MessageLevel">
            <summary>
            The various levels of verbosity available.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.Critical">
            <summary>
            Very important message, should be shown to the user as a high priority
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.Important">
            <summary>
            Important message, the user should read this
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.Output">
            <summary>
            Important message, the user should read this
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.Significant">
            <summary>
            Message relevant to the user.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.VeryVerbose">
            <summary>
            Not important to the regular user, still of some interest to the curious
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.Verbose">
            <summary>
            Background process information, in case the user wants some detailed information on what is currently happening.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.SomewhatVerbose">
            <summary>
            A footnote in current processing, rarely of interest to the user
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.System">
            <summary>
            A message of some interest from an internal system persepctive, but largely irrelevant to the user.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.Debug">
            <summary>
            Something only of interest to a debugger
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.InternalComment">
            <summary>
            This message barely made the cut from being culled. Of purely development internal interest, and even there is 'interest' a strong word for it.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.Warning">
            <summary>
            This message is a warning, sure sign something went badly wrong
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.MessageLevelModifier">
            <summary>
            A modification to a given message's level
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.Name">
            <summary>
            Name of the modifier. Prevents duplication in a multi-runspace scenario.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.Modifier">
            <summary>
            The amount to modify the level by
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.IncludeFunctionName">
            <summary>
            Apply modifier only to messages from this function.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.ExcludeFunctionName">
            <summary>
            Apply modifier not when the message is written by this function.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.IncludeModuleName">
            <summary>
            Apply modifier only to messages from this module
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.ExcludeModuleName">
            <summary>
            Do not apply modifier to messages from this module
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.IncludeTags">
            <summary>
            Only apply this modifier to a message that includes at least one of these tags
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.ExcludeTags">
            <summary>
            Do not apply this modifier to a message that includes any of the following tags
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.AppliesTo(System.String,System.String,System.Collections.Generic.List{System.String})">
            <summary>
            Tests, whether a message a message should be modified by this modiier
            </summary>
            <param name="FunctionName">The name of the function writing the message</param>
            <param name="ModuleName">The name of the module, the function writing this message comes from</param>
            <param name="Tags">The tags of the message written</param>
            <returns>Whether the message applies</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.TransformCondition">
            <summary>
            A condition, under which the object shall be transaformed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformCondition.TypeName">
            <summary>
            Name of the type. All similar types (as determined by the '-like' operator) will be transformed.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformCondition.ModuleName">
            <summary>
            The name of the module to consider, using the -Like operator
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformCondition.FunctionName">
            <summary>
            The name of the function name to consider, using the -Like operator
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformCondition.ScriptBlock">
            <summary>
            The scriptblock that performs the transformation
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformCondition.Type">
            <summary>
            What kind of transformation is being performed?
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformCondition.#ctor(System.String,System.String,System.String,System.Management.Automation.ScriptBlock,Sqlcollaborative.Dbatools.Message.TransformType)">
            <summary>
            Initializes a transform condition
            </summary>
            <param name="TypeName">Only objects of similar name will be transformed</param>
            <param name="ModuleName">Only objects coming from similar modules will be considered</param>
            <param name="FunctionName">Only objects coming from similar functions will be considered</param>
            <param name="ScriptBlock">The scriptblock used for the transformation</param>
            <param name="Type">What kind of transformation this is</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.TransformError">
            <summary>
            An error occured during a message transformation
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformError.Record">
            <summary>
            The error record of what went wrong
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformError.FunctionName">
            <summary>
            The name of the function writing the message that failed to transform
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformError.ModuleName">
            <summary>
            The name of the module the command writing the message came from
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformError.Timestamp">
            <summary>
            When did it all happen?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformError.Object">
            <summary>
            The object that was supposed to be transformed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformError.Type">
            <summary>
            The kind of transform that failed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformError.Runspace">
            <summary>
            The runspace it all happened on
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformError.#ctor(System.Management.Automation.ErrorRecord,System.String,System.String,System.Object,Sqlcollaborative.Dbatools.Message.TransformType,System.Guid)">
            <summary>
            Creates a new transform error
            </summary>
            <param name="Record">The record of what went wrong</param>
            <param name="FunctionName">The name of the function writing the transformed message</param>
            <param name="ModuleName">The module the function writing the transformed message is part of</param>
            <param name="Object">The object that should have been transformed</param>
            <param name="Type">The type of transform that was attempted</param>
            <param name="Runspace">The runspace it all happened on</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.TransformList">
            <summary>
            List engine, managing the lists for a message transformation type
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformList.GetAll">
            <summary>
            Returns all entries in the list.
            </summary>
            <returns>The list of transforms contained within</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformList.IsListed(Sqlcollaborative.Dbatools.Message.TransformCondition)">
            <summary>
            Returns whether the actual object is part of the list
            </summary>
            <param name="Condition">The object to test for list membership</param>
            <returns>Whether the object is listed</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformList.IsContained(Sqlcollaborative.Dbatools.Message.TransformCondition)">
            <summary>
            Returns whether a condition with equal conditions already exists
            </summary>
            <param name="Condition">The condition to test</param>
            <returns>Whether the referenced condition is already listed</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformList.Add(Sqlcollaborative.Dbatools.Message.TransformCondition)">
            <summary>
            Adds a condition to the list, if there is no equivalent condition present.
            </summary>
            <param name="Condition">The condition to add</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformList.Remove(Sqlcollaborative.Dbatools.Message.TransformCondition)">
            <summary>
            Removes a condition from the lsit of conditional transforms
            </summary>
            <param name="Condition">The condition to remove</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformList.Get(System.String,System.String,System.String)">
            <summary>
            Returns the first transform whose filter is similar enough to work out.
            </summary>
            <param name="TypeName">The name of the type to check for a transform</param>
            <param name="ModuleName">The module of the command that wrote the message with the transformable object</param>
            <param name="Functionname">The command that wrote the message with the transformable object</param>
            <returns>Either a transform or null, if no fitting transform was found</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.TransformType">
            <summary>
            The messaging system provides these kinds of transformations for input.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformType.Target">
            <summary>
            A target transform can transform the target object specified. Used for live-state objects that should not be serialized on a second thread.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformType.Exception">
            <summary>
            An exception transform allows automatic transformation of exceptions. Primarily used to unwrap exceptions from an API that wraps all exceptions.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter">
            <summary>
            Input converter for Computer Management Information
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.Connection">
            <summary>
            The resolved connection object
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.Success">
            <summary>
            Whether input processing was successful
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.InputObject">
            <summary>
            The object actually passed to the class
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.op_Implicit(Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter)~Sqlcollaborative.Dbatools.Connection.ManagementConnection">
            <summary>
            Implicitly convert all connection parameter objects to the connection-type
            </summary>
            <param name="Input">The parameter object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.#ctor(System.String)">
            <summary>
            Creates a new DbaWmConnectionParameter based on an input-name
            </summary>
            <param name="ComputerName">The name of the computer the connection is stored for.</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.#ctor(Sqlcollaborative.Dbatools.Connection.ManagementConnection)">
            <summary>
            Creates a new DbaWmConnectionParameter based on an already existing connection object.
            </summary>
            <param name="Connection">The connection to accept</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.#ctor(System.Object)">
            <summary>
            Tries to convert a generic input object into a true input.
            </summary>
            <param name="Input">Any damn object in the world</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.#ctor(Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter)">
            <summary>
            Creates a new DbaCmConnectionParameter based on an instance parameter
            </summary>
            <param name="Instance">The instance to interpret</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter">
            <summary>
            Parameter class that handles the various kinds of credential input
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.Credential">
            <summary>
            The credential object received
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.UserName">
            <summary>
            The name of the credential object
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.Password">
            <summary>
            The password of the credential object
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.#ctor(System.Management.Automation.PSCredential)">
            <summary>
            Creates a credential parameter from a PSCredential object
            </summary>
            <param name="Credential">A PSCredential object</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.#ctor(System.Net.NetworkCredential)">
            <summary>
            Creates a credential parameter from a NetworkCredential object
            </summary>
            <param name="Credential">The credentials to use</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.#ctor(System.Object)">
            <summary>
            Creates a credential parameter from anything it nows how to handle
            </summary>
            <param name="Credential">The object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.op_Implicit(Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter)~System.Management.Automation.PSCredential">
            <summary>
            Implicitly converts from DbaCredentialParameter to PSCredential
            </summary>
            <param name="Input">The DbaCredentialParameter to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.op_Implicit(System.Management.Automation.PSCredential)~Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter">
            <summary>
            Implicitly converts a PSCredential object to DbaCredenitalParameter
            </summary>
            <param name="Input">The PSCredential to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.op_Implicit(Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter)~System.Net.NetworkCredential">
            <summary>
            Implicitly converts from DbaCredentialParameter to NetworkCredential
            </summary>
            <param name="Input">The DbaCredentialParameter to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.op_Implicit(System.Net.NetworkCredential)~Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter">
            <summary>
            Implicitly converts a NetworkCredential object to DbaCredenitalParameter
            </summary>
            <param name="Input">The NetworkCredential to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.GetNetworkCredential">
            <summary>
            Legacy wrapper. While there exists implicit conversion, this allows using the object as before, avoiding errors for unknown method.
            </summary>
            <returns>A network credential object with the same credentials as the original object</returns>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.CredentialStore">
            <summary>
            Cached credentials, if the user stors them under a name.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.GetTypeCode">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToBoolean(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToChar(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToSByte(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToByte(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToInt16(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToUInt16(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToInt32(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToUInt32(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToInt64(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToUInt64(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToSingle(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToDouble(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToDecimal(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToDateTime(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToString(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToType(System.Type,System.IFormatProvider)">
            <summary>
            Tries to convert the credential parameter to one of its supported types
            </summary>
            <param name="TargetType">The type to convert to</param>
            <param name="Format">Irrelevant</param>
            <returns></returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseParameter">
            <summary>
            Parameter class that accepts anything pointing at a database
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseParameter.InputObject">
            <summary>
            The original object passed to the parameter
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseParameter.Database">
            <summary>
            The SMO Database Object
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseParameter.Name">
            <summary>
            The name of the database
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseParameter.#ctor(System.String)">
            <summary>
            Accepts the name of a database and converts it to a DbaDatabaseParameter
            </summary>
            <param name="Name"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseParameter.#ctor(System.Object)">
            <summary>
            Accepts anything and tries to convert it to a live SMO Database object
            </summary>
            <param name="Item">The item to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseParameter.ToString">
            <summary>
            Overrides the regular tostring to show something pleasant and useful
            </summary>
            <returns>The name of the database</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseSmoParameter">
            <summary>
            Parameter class that only accepts live SMO Databases
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseSmoParameter.InputObject">
            <summary>
            The original object passed to the parameter
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseSmoParameter.Database">
            <summary>
            The SMO Database Object
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseSmoParameter.Name">
            <summary>
            The name of the database
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseSmoParameter.#ctor(System.Object)">
            <summary>
            Accepts anything and tries to convert it to a live SMO Database object
            </summary>
            <param name="Item">The item to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseSmoParameter.ToString">
            <summary>
            Overrides the regular tostring to show something pleasant and useful
            </summary>
            <returns>The name of the database</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType">
            <summary>
            What kind of object was bound to the parameter class?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType.Default">
            <summary>
            Anything, really. An unspecific not reusable type was bound
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType.Linked">
            <summary>
            A live smo linked server object was bound
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType.Server">
            <summary>
            A live smo server object was bound
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType.RegisteredServer">
            <summary>
            A Central Management Server RegisteredServer SMO object was bound
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType.ConnectionString">
            <summary>
            An actual connection string was specified. Connection strings are directly reused for SMO connections
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType.ConnectionStringLocalDB">
            <summary>
            A connection string pointing at a local, file-based DB
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType.SqlConnection">
            <summary>
            An already established sql connection to was created outside of SMO
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter">
            <summary>
            Input converter for instance information
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.ComputerName">
            <summary>
            Name of the computer as resolvable by DNS
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.InstanceName">
            <summary>
            Name of the instance on the target server
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.Port">
            <summary>
            The port over which to connect to the server. Only present if non-default
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.NetworkProtocol">
            <summary>
            The network protocol to connect over
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.IsLocalHost">
            <summary>
            Verifies, whether the specified computer is localhost or not.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.FullName">
            <summary>
            Full name of the instance, including the server-name
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.FullSmoName">
            <summary>
            Full name of the instance, including the server-name, used when connecting via SMO
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.SqlComputerName">
            <summary>
            Name of the computer as used in an SQL Statement
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.SqlInstanceName">
            <summary>
            Name of the instance as used in an SQL Statement
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.SqlFullName">
            <summary>
            Full name of the instance, including the server-name as used in an SQL statement
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.IsConnectionString">
            <summary>
            Whether the input is a connection string
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.InputObject">
            <summary>
            The original object passed to the parameter class.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.Type">
            <summary>
            What kind of object was bound to the parameter class? For efficiency's purposes.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.LinkedLive">
            <summary>
            Returns, whether a live SMO object was bound for the purpose of accessing LinkedServer functionality
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.LinkedServer">
            <summary>
            Returns the available Linked Server objects from live objects only
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.op_Implicit(Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter)~System.String">
            <summary>
            Converts the parameter class to its full name
            </summary>
            <param name="Input">The parameter class object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.#ctor(System.String)">
            <summary>
            Creates a DBA Instance Parameter from string
            </summary>
            <param name="Name">The name of the instance</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.#ctor(System.Net.IPAddress)">
            <summary>
            Creates a DBA Instance Parameter from an IPAddress
            </summary>
            <param name="Address"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.#ctor(System.Net.NetworkInformation.PingReply)">
            <summary>
            Creates a DBA Instance Parameter from the reply to a ping
            </summary>
            <param name="Ping">The result of a ping</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.#ctor(System.Net.IPHostEntry)">
            <summary>
            Creates a DBA Instance Parameter from the result of a dns resolution
            </summary>
            <param name="Entry">The result of a dns resolution, to be used for targetting the default instance</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.#ctor(System.Data.SqlClient.SqlConnection)">
            <summary>
            Creates a DBA Instance Parameter from an established SQL Connection
            </summary>
            <param name="Connection">The connection to reuse</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.#ctor(Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport)">
            <summary>
            Accept and understand discovery reports.
            </summary>
            <param name="Report">The report to interpret</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.#ctor(System.Object)">
            <summary>
            Creates a DBA Instance parameter from any object
            </summary>
            <param name="Input">Object to parse</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.ToString">
            <summary>
            Overrides the regular <c>ToString()</c> to show something pleasant and useful
            </summary>
            <returns>The <see cref="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.FullSmoName"/></returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.DbaSelectParameter">
            <summary>
            Class that automatically parses input chosen for the -Property parameter of Select-PSUObject
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaSelectParameter.InputObject">
            <summary>
            The original input object
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaSelectParameter.Value">
            <summary>
            The value as Select-Object wants it
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaSelectParameter.#ctor(System.String)">
            <summary>
            Builds a property parameter from string
            </summary>
            <param name="Value">The string to interpret</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaSelectParameter.#ctor(System.Collections.Hashtable)">
            <summary>
            Builds a select parameter from a hashtable (pretty straightforward)
            </summary>
            <param name="Hash">The hashtable to accept</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.ParameterContractAttribute">
            <summary>
            The attribute used to define the elements of a ParameterClass contract
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.ParameterContractAttribute.Type">
            <summary>
            Returns the type of the element this attribute is supposed to be attached to.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.ParameterContractAttribute.Behavior">
            <summary>
            Returns the behavior to expect from the contracted element. This sets the expectations on how this element is likely to act.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.ParameterContractAttribute.#ctor(Sqlcollaborative.Dbatools.Parameter.ParameterContractType,Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior)">
            <summary>
            Ceates a perfectly common parameter contract attribute. For use with all parameter classes' public elements.
            </summary>
            <param name="Type"></param>
            <param name="Behavior"></param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior">
            <summary>
            Defines how this element will behave
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior.NotContracted">
            <summary>
            This elements is not actually part of the contract. Generally you wouldn't want to add the attribute at all in that case. However, in some places it helps avoiding confusion.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior.Mandatory">
            <summary>
            This element may never be null and must be considered in all assignments. Even if the element is de facto not nullable, all constructors must assign it.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior.Optional">
            <summary>
            This element may contain data, but is not required to. In case of a method, it may simply do nothing
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior.Failable">
            <summary>
            This method may throw an error when executing and should always be handled with try/catch. Use this on methods that use external calls.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior.Arbiter">
            <summary>
            The content of the thus marked field determines the dependent's state. Generally, only if the arbiter is true, will the dependent elements be mandatory. This behavior may only be assigned to boolean fields.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior.Conditional">
            <summary>
            This behavior can be assigned together with the 'Mandatory' behavior. It means the field is only mandatory if an arbiter field is present and set to true.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior.Conversion">
            <summary>
            Converts content. Generally applied only to operators, but some methods may also convert information.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.ParameterContractType">
            <summary>
            Defines what kind of element is granted the contract
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractType.Field">
            <summary>
            The contracted element is a field containing a value
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractType.Method">
            <summary>
            The contracted element is a method, performing an action
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractType.Operator">
            <summary>
            The contracted element is an operator, facilitating type conversion. Generally into a dedicated object type this parameterclass abstracts.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Runspace.DbaRunspaceState">
            <summary>
            Contains the state a managed, unique runspace can be in.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Runspace.DbaRunspaceState.Running">
            <summary>
            The runspace is up and running
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Runspace.DbaRunspaceState.Stopping">
            <summary>
            The runspace has received the stop order, but has not yet obeyed it
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Runspace.DbaRunspaceState.Stopped">
            <summary>
            The runspace has followed its order to stop and is currently disabled
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer">
            <summary>
            Class that contains the logic necessary to manage a unique runspace
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.Name">
            <summary>
            The name of the runspace.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.RunspaceGuid">
            <summary>
            The Guid of the running Runspace
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.SetScript(System.Management.Automation.ScriptBlock)">
            <summary>
            Sets the script to execute in the runspace. Will NOT take immediate effect. Only after restarting the runspace will it be used.
            </summary>
            <param name="Script">The scriptblock to execute</param>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.State">
            <summary>
            The state the runspace currently is in.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.Start">
            <summary>
            Starts the Runspace.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.SetName(System.Management.Automation.Runspaces.Runspace)">
            <summary>
            Sets the name on a runspace. This WILL FAIL for PowerShell v3!
            </summary>
            <param name="Runspace">The runspace to be named</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.Stop">
            <summary>
            Gracefully stops the Runspace
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.Kill">
            <summary>
            Very ungracefully kills the runspace. Use only in the most dire emergency.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.SignalStopped">
            <summary>
            Signals the registered runspace has stopped execution
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.#ctor(System.String,System.Management.Automation.ScriptBlock)">
            <summary>
            Creates a new runspace container with the basic information needed
            </summary>
            <param name="Name">The name of the Runspace</param>
            <param name="Script">The code using the runspace logic</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Runspace.RunspaceHost">
            <summary>
            Provides hosting for all registered runspaces
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Runspace.RunspaceHost.StopTimeoutSeconds">
            <summary>
            The number of seconds before a Stop command is interrupted and instead the runspace is gracelessly shut down.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Runspace.RunspaceHost.Runspaces">
            <summary>
            The dictionary containing the definitive list of unique Runspace
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.TabExpansion.InstanceAccess">
            <summary>
            Contains information on access to an instance
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.InstanceAccess.InstanceName">
            <summary>
            The name of the instance to access
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.InstanceAccess.IsSysAdmin">
            <summary>
            Whether the account had sysadmin privileges. On multiple user usage, the cache will prefer sysadmin accounts.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.InstanceAccess.ConnectionObject">
            <summary>
            The actual connection object to connect with to the server
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.InstanceAccess.LastAccess">
            <summary>
            When was the instance last accessed using dbatools
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.InstanceAccess.LastUpdate">
            <summary>
            When was the instance's TEPP cache last updated
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.TabExpansion.ScriptContainer">
            <summary>
            Regular container to store scripts in, that are used in TEPP
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.ScriptContainer.Name">
            <summary>
            The name of the scriptblock
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.ScriptContainer.ScriptBlock">
            <summary>
            The scriptblock doing the logic
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.ScriptContainer.LastExecution">
            <summary>
            The last time the scriptblock was called. Must be updated by the scriptblock itself
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.ScriptContainer.LastDuration">
            <summary>
            The time it took to run the last time
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.TabExpansion.TabCompletionSet">
            <summary>
            Contains information used to transmit Tepp Assignment
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabCompletionSet.Command">
            <summary>
            The name of the command to complete. "*" if all commands that have the parameter should be selected instead
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabCompletionSet.Parameter">
            <summary>
            The parameter to complete
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabCompletionSet.Script">
            <summary>
            The name of the script to complete with
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TabExpansion.TabCompletionSet.#ctor(System.String,System.String,System.String)">
            <summary>
            Creates a new tab completion set object with all information prefilled
            </summary>
            <param name="Command">The name of the command to complete. "*" if all commands that have the parameter should be selected instead</param>
            <param name="Parameter">The parameter to complete</param>
            <param name="Script">The name of the script to complete with</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TabExpansion.TabCompletionSet.Applies(System.String,System.String)">
            <summary>
            Tests, whether the completion set applies to the specified parameter / command combination
            </summary>
            <param name="Command">The command to test</param>
            <param name="Parameter">The parameter of the command to test</param>
            <returns>Whether this completion set applies to the specified combination of parameter / command</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost">
            <summary>
            Class that handles the static fields supporting the dbatools TabExpansion implementation
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.Scripts">
            <summary>
            Field containing the scripts that were registered.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.Cache">
            <summary>
            The cache used by scripts utilizing TabExpansionPlusPlus in dbatools
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.InstanceAccess">
            <summary>
            List of instances and when they were last accessed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppGatherScriptsFast">
            <summary>
            Scripts that build the cache and are suitable for synchronous execution
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppGatherScriptsSlow">
            <summary>
            Scripts that build the cache and are not suitable for synchronous execution
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.DbatoolsCommands">
            <summary>
            A list of all commands imported into dbatools
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TabCompletionSets">
            <summary>
            List of completion sets that should be processed into Tepp Assignments. Only populate this list on first import.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppAssignment">
            <summary>
            Maps a TEPP scriptblock to a command and parameter
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.SetInstance(System.String,System.Object,System.Boolean)">
            <summary>
            Registers a new instance or updates an already existing one. Should only be called from Connect-SqlInstance and Connect-DbaSqlServer
            </summary>
            <param name="InstanceName">Name of the instance connected to</param>
            <param name="Connection">To connection object containing the relevant information for accessing the instance</param>
            <param name="IsSysAdmin">Whether the account connecting to the instnace has SA privileges</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.GetTeppScript(System.String,System.String)">
            <summary>
            Returns the assigned scriptblock for a given parameter
            </summary>
            <param name="Command">The command that should be completed</param>
            <param name="Parameter">The parameter completion is provided for</param>
            <returns>Either the relevant script container or null</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.SetTeppScript(System.String,System.String,System.String)">
            <summary>
            Assigns a registered script to the parameter of a command
            </summary>
            <param name="Command">The command for which to complete</param>
            <param name="Parameter">The parameter for which to complete</param>
            <param name="Script">To name of the script with which to complete</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.AddTabCompletionSet(System.String,System.String,System.String)">
            <summary>
            Adds a completion set to the list of items to process
            </summary>
            <param name="Command">The command to complete for (accepts wildcard matching)</param>
            <param name="Parameter">The parameter to complete for (accepts wildcard matching)</param>
            <param name="Script">The script to register</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.CalculateTabExpansion">
            <summary>
            Processes the content of TabCompletionSets and Scripts into TappAssignments based on the DbatoolsCommands list.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppDisabled">
            <summary>
            Whether TEPP in its entirety is disabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppAsyncDisabled">
            <summary>
            Whether asynchronous TEPP updating should be disabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppSyncDisabled">
            <summary>
            Whether synchronous TEPP updating should be disabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppUpdateInterval">
            <summary>
            The interval in which asynchronous TEPP cache updates are performed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppUpdateTimeout">
            <summary>
            After this timespan of no requests to a server, the updates to its cache are disabled.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.TypeConversion.DbaCredentialParameterConverter">
            <summary>
            Converts to and from DbaCredentialparameter
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TypeConversion.DbaCredentialParameterConverter.CanConvertTo(System.Object,System.Type)">
            <summary>
            Verifies, whether a conversion for the object to the target type is possible
            </summary>
            <param name="SourceValue">The object to convert</param>
            <param name="DestinationType">The type to convert to</param>
            <returns>Whether it's possible, duh!</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TypeConversion.DbaCredentialParameterConverter.ConvertTo(System.Object,System.Type,System.IFormatProvider,System.Boolean)">
            <summary>
            Converts from DbaCredentialparameter to whatever destination type is attempted
            </summary>
            <param name="sourceValue">The source object. Better be a DbaCredentialparameter!</param>
            <param name="destinationType">Should be a supported destination type</param>
            <param name="formatProvider">Irrelevant</param>
            <param name="ignoreCase">Irrelevant</param>
            <returns>The target content type</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TypeConversion.DbaCredentialParameterConverter.CanConvertFrom(System.Object,System.Type)">
            <summary>
            Verifies, whether a conversion for the object from the source type to DbaCredentialParameter is possible
            </summary>
            <param name="SourceValue">The object to convert</param>
            <param name="DestinationType">The source type to convert to</param>
            <returns>Whether it's possible, duh!</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TypeConversion.DbaCredentialParameterConverter.ConvertFrom(System.Object,System.Type,System.IFormatProvider,System.Boolean)">
            <summary>
            Converts a source object to DbaCredentialparameter
            </summary>
            <param name="sourceValue">The source object</param>
            <param name="destinationType">The destination type. Must be DbaCredentialParameter, or red stuff happens</param>
            <param name="formatProvider">Irrelevant</param>
            <param name="ignoreCase">Irrelevant</param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TypeConversion.DbaCredentialParameterConverter.IsSupportedType(System.Type)">
            <summary>
            Returns, whether a given type is supported for conversion
            </summary>
            <param name="type">The type to validate</param>
            <returns>Whether it's a supported conversion</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DateTimeExtension">
            <summary>
            Extends DateTime
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DateTimeExtension.CompareTo(System.DateTime,Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)">
            <summary>
            Adds a compareTo method to DateTime to compare with DbaDateTimeBase
            </summary>
            <param name="Base">The extended DateTime object</param>
            <param name="comparedTo">The DbaDateTimeBase to compare with</param>
            <returns></returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaDate">
            <summary>
            A dbatools-internal datetime wrapper for neater display
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.DateTime)">
            <summary>
            Constructs a generic timestamp object wrapper from an input timestamp object.
            </summary>
            <param name="Timestamp">The timestamp to wrap</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.String)">
            <summary>
            Parses a string into a datetime object.
            </summary>
            <param name="Time">The time-string to parse</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int64)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int64,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.ToString">
            <summary>
            Provids the default-formated string, using the defined default formatting.
            </summary>
            <returns>Formatted datetime-string</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaDate)~System.DateTime">
            <summary>
            Implicitly convert to DateTime
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.op_Implicit(System.DateTime)~Sqlcollaborative.Dbatools.Utility.DbaDate">
            <summary>
            Implicitly convert from DateTime
            </summary>
            <param name="Base">The object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaDate)~Sqlcollaborative.Dbatools.Utility.DbaDateTime">
            <summary>
            Implicitly convert to DbaDate
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaDate)~Sqlcollaborative.Dbatools.Utility.DbaTime">
            <summary>
            Implicitly convert to DbaTime
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.Generate(System.DateTime)">
            <summary>
            Generates a DbaDate object based off DateTime object. Will be null if Base is the start value (Tickes == 0).
            </summary>
            <param name="Base">The Datetime to base it off</param>
            <returns>The object to generate (or null)</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaDateTime">
            <summary>
            A dbatools-internal datetime wrapper for neater display
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.DateTime)">
            <summary>
            Constructs a generic timestamp object wrapper from an input timestamp object.
            </summary>
            <param name="Timestamp">The timestamp to wrap</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.String)">
            <summary>
            Parses a string into a datetime object.
            </summary>
            <param name="Time">The time-string to parse</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int64)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int64,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.ToString">
            <summary>
            Provids the default-formated string, using the defined default formatting.
            </summary>
            <returns>Formatted datetime-string</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaDateTime)~System.DateTime">
            <summary>
            Implicitly convert to DateTime
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.op_Implicit(System.DateTime)~Sqlcollaborative.Dbatools.Utility.DbaDateTime">
            <summary>
            Implicitly convert from DateTime
            </summary>
            <param name="Base">The object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaDateTime)~Sqlcollaborative.Dbatools.Utility.DbaDate">
            <summary>
            Implicitly convert to DbaDate
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaDateTime)~Sqlcollaborative.Dbatools.Utility.DbaTime">
            <summary>
            Implicitly convert to DbaTime
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.Generate(System.DateTime)">
            <summary>
            Generates a DbaDateTime object based off DateTime object. Will be null if Base is the start value (Tickes == 0).
            </summary>
            <param name="Base">The Datetime to base it off</param>
            <returns>The object to generate (or null)</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase">
            <summary>
            Base class for wrapping around a DateTime object
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase._timestamp">
            <summary>
            The core resource, containing the actual timestamp
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Date">
            <summary>
            Gets the date component of this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Day">
            <summary>
            Gets the day of the month represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.DayOfWeek">
            <summary>
            Gets the day of the week represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.DayOfYear">
            <summary>
            Gets the day of the year represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Hour">
            <summary>
            Gets the hour component of the date represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Kind">
            <summary>
            Gets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Millisecond">
            <summary>
            Gets the milliseconds component of the date represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Minute">
            <summary>
            Gets the minute component of the date represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Month">
            <summary>
            Gets the month component of the date represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Second">
            <summary>
            Gets the seconds component of the date represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Ticks">
            <summary>
            Gets the number of ticks that represent the date and time of this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.TimeOfDay">
            <summary>
            Gets the time of day for this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Year">
            <summary>
            Gets the year component of the date represented by this instance.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor">
            <summary>
            Constructor that should never be called, since this class should never be instantiated. It's there for implicit calls on child classes.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.DateTime)">
            <summary>
            Constructs a generic timestamp object wrapper from an input timestamp object.
            </summary>
            <param name="Timestamp">The timestamp to wrap</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.String)">
            <summary>
            Parses a string into a datetime object.
            </summary>
            <param name="Time">The time-string to parse</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int64)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int64,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Add(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddDays(System.Double)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddHours(System.Double)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddMilliseconds(System.Double)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddMinutes(System.Double)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddMonths(System.Int32)">
            <summary>
            
            </summary>
            <param name="months"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddSeconds(System.Double)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddTicks(System.Int64)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddYears(System.Int32)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.CompareTo(System.Object)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.CompareTo(System.DateTime)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Equals(System.Object)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Equals(System.DateTime)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.GetDateTimeFormats">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.GetDateTimeFormats(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="provider"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.GetDateTimeFormats(System.Char)">
            <summary>
            
            </summary>
            <param name="format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.GetDateTimeFormats(System.Char,System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="format"></param>
            <param name="provider"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.GetBaseObject">
            <summary>
            Retrieve base DateTime object, this is a wrapper for
            </summary>
            <returns>Base DateTime object</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.GetHashCode">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.GetTypeCode">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.IsDaylightSavingTime">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Subtract(System.DateTime)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Subtract(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToBinary">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToFileTime">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToFileTimeUtc">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToLocalTime">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToLongDateString">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToLongTimeString">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToOADate">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToShortDateString">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToShortTimeString">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToString(System.String)">
            <summary>
            
            </summary>
            <param name="format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToString(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="provider"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToString(System.String,System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="format"></param>
            <param name="provider"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToUniversalTime">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ParseDateTime(System.String)">
            <summary>
            Parses input string into datetime
            </summary>
            <param name="Value">The string to parse</param>
            <returns>The resultant datetime.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_Addition(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="Timestamp"></param>
            <param name="Duration"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_Subtraction(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="Timestamp"></param>
            <param name="Duration"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_Equality(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)">
            <summary>
            
            </summary>
            <param name="Timestamp1"></param>
            <param name="Timestamp2"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_Inequality(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)">
            <summary>
            
            </summary>
            <param name="Timestamp1"></param>
            <param name="Timestamp2"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_GreaterThan(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)">
            <summary>
            
            </summary>
            <param name="Timestamp1"></param>
            <param name="Timestamp2"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_LessThan(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)">
            <summary>
            
            </summary>
            <param name="Timestamp1"></param>
            <param name="Timestamp2"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_GreaterThanOrEqual(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)">
            <summary>
            
            </summary>
            <param name="Timestamp1"></param>
            <param name="Timestamp2"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_LessThanOrEqual(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)">
            <summary>
            
            </summary>
            <param name="Timestamp1"></param>
            <param name="Timestamp2"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)~System.DateTime">
            <summary>
            Implicitly convert DbaDateTimeBase to DateTime
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_Implicit(System.DateTime)~Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase">
            <summary>
            Implicitly convert DateTime to DbaDateTimeBase
            </summary>
            <param name="Base">The object to convert</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaTime">
            <summary>
            A dbatools-internal datetime wrapper for neater display
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.DateTime)">
            <summary>
            Constructs a generic timestamp object wrapper from an input timestamp object.
            </summary>
            <param name="Timestamp">The timestamp to wrap</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.String)">
            <summary>
            Parses a string into a datetime object.
            </summary>
            <param name="Time">The time-string to parse</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int64)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int64,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.ToString">
            <summary>
            Provids the default-formated string, using the defined default formatting.
            </summary>
            <returns>Formatted datetime-string</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaTime)~System.DateTime">
            <summary>
            Implicitly convert to DateTime
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.op_Implicit(System.DateTime)~Sqlcollaborative.Dbatools.Utility.DbaTime">
            <summary>
            Implicitly convert from DateTime
            </summary>
            <param name="Base">The object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaTime)~Sqlcollaborative.Dbatools.Utility.DbaDate">
            <summary>
            Implicitly convert to DbaDate
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaTime)~Sqlcollaborative.Dbatools.Utility.DbaDateTime">
            <summary>
            Implicitly convert to DbaTime
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaTime)~System.String">
            <summary>
            Implicitly convert to string
            </summary>
            <param name="Base">Object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.Generate(System.DateTime)">
            <summary>
            Generates a DbaDateTime object based off DateTime object. Will be null if Base is the start value (Tickes == 0).
            </summary>
            <param name="Base">The Datetime to base it off</param>
            <returns>The object to generate (or null)</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan">
            <summary>
            A wrapper class, encapsuling a regular TimeSpan object. Used to provide custom timespan display.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Days">
            <summary>
            Gets the days component of the time interval represented by the current TimeSpan structure.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Hours">
            <summary>
            Gets the hours component of the time interval represented by the current TimeSpan structure.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Milliseconds">
            <summary>
            Gets the milliseconds component of the time interval represented by the current TimeSpan structure.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Minutes">
            <summary>
            Gets the minutes component of the time interval represented by the current TimeSpan structure.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Seconds">
            <summary>
            Gets the seconds component of the time interval represented by the current TimeSpan structure.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Ticks">
            <summary>
            Gets the number of ticks that represent the value of the current TimeSpan structure.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.TotalDays">
            <summary>
            Gets the value of the current TimeSpan structure expressed in whole and fractional days.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.TotalHours">
            <summary>
            Gets the value of the current TimeSpan structure expressed in whole and fractional hours.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.TotalMilliseconds">
            <summary>
            Gets the value of the current TimeSpan structure expressed in whole and fractional milliseconds.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.TotalMinutes">
            <summary>
            Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.TotalSeconds">
            <summary>
            Gets the value of the current TimeSpan structure expressed in whole and fractional seconds.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.#ctor(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="Timespan"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.#ctor(System.String)">
            <summary>
            Converts a string into a timespan
            </summary>
            <param name="Timespan">The string to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.#ctor(System.Int64)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.#ctor(System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="hours"></param>
            <param name="minutes"></param>
            <param name="seconds"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.#ctor(System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="days"></param>
            <param name="hours"></param>
            <param name="minutes"></param>
            <param name="seconds"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="days"></param>
            <param name="hours"></param>
            <param name="minutes"></param>
            <param name="seconds"></param>
            <param name="milliseconds"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.ParseTimeSpan(System.String)">
            <summary>
            Parses an input string as timespan
            </summary>
            <param name="Value">The string to interpret</param>
            <returns>The interpreted timespan value</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Add(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="ts"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.CompareTo(System.Object)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.CompareTo(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.CompareTo(Sqlcollaborative.Dbatools.Utility.DbaTimeSpan)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Duration">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Equals(System.Object)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Equals(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="obj"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.GetBaseObject">
            <summary>
            Returns the wrapped base object
            </summary>
            <returns>The base object</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.GetHashCode">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Negate">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Subtract(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="ts"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.ToString">
            <summary>
            Returns the default string representation of the TimeSpan object
            </summary>
            <returns>The string representation of the DbaTimeSpan object</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.ToString(System.String)">
            <summary>
            
            </summary>
            <param name="format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.ToString(System.String,System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="format"></param>
            <param name="formatProvider"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaTimeSpan)~System.TimeSpan">
            <summary>
            Implicitly converts a DbaTimeSpan object into a TimeSpan object
            </summary>
            <param name="Base">The original object to revert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.op_Implicit(System.TimeSpan)~Sqlcollaborative.Dbatools.Utility.DbaTimeSpan">
            <summary>
            Implicitly converts a TimeSpan object into a DbaTimeSpan object
            </summary>
            <param name="Base">The original object to wrap</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty">
            <summary>
            Makes timespan great again
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.FromMilliseconds(System.Double)">
            <summary>
            Creates a new, pretty timespan object from milliseconds
            </summary>
            <param name="Milliseconds">The milliseconds to convert from.</param>
            <returns>A pretty timespan object</returns>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.Digits">
            <summary>
            The number of digits a pretty timespan should round to.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.#ctor(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="Timespan"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.#ctor(System.String)">
            <summary>
            Converts a string into a timespan
            </summary>
            <param name="Timespan">The string to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.#ctor(System.Int64)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.#ctor(System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="hours"></param>
            <param name="minutes"></param>
            <param name="seconds"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.#ctor(System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="days"></param>
            <param name="hours"></param>
            <param name="minutes"></param>
            <param name="seconds"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="days"></param>
            <param name="hours"></param>
            <param name="minutes"></param>
            <param name="seconds"></param>
            <param name="milliseconds"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.ToString">
            <summary>
            Creates extra-nice timespan formats
            </summary>
            <returns>Humanly readable timespans</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaValidatePatternAttribute">
            <summary>
            Validates that each parameter argument matches the RegexPattern
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaValidatePatternAttribute.RegexPattern">
            <summary>
            Gets the Regex pattern to be used in the validation
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaValidatePatternAttribute.Options">
            <summary>
            Gets or sets the Regex options to be used in the validation
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaValidatePatternAttribute.ErrorMessage">
             <summary>
             Gets or sets the custom error message pattern that is displayed to the user.
            
             The text representation of the object being validated and the validating regex is passed as
             the first and second formatting parameters to the ErrorMessage formatting pattern.
             <example>
             [ValidatePattern("\s+", ErrorMessage="The text '{0}' did not pass validation of regex '{1}'")]
             </example>
             </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaValidatePatternAttribute.ValidateElement(System.Object)">
            <summary>
            Validates that each parameter argument matches the RegexPattern
            </summary>
            <param name="element">object to validate</param>
            <exception cref="T:System.Management.Automation.ValidationMetadataException">if <paramref name="element"/> is not a string
             that matches the pattern
             and for invalid arguments</exception>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaValidatePatternAttribute.#ctor(System.String)">
            <summary>
            Initializes a new instance of the PsfValidatePatternAttribute class
            </summary>
            <param name="regexPattern">Pattern string to match</param>
            <exception cref="T:System.ArgumentException">for invalid arguments</exception>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaValidateScriptAttribute">
            <summary>
            Class for validating against a script block.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaValidateScriptAttribute.ErrorMessage">
             <summary>
             Gets or sets the custom error message that is displayed to the user.
            
             The item being validated and the validating scriptblock is passed as the first and second
             formatting argument.
            
             <example>
             [ValidateScript("$_ % 2", ErrorMessage = "The item '{0}' did not pass validation of script '{1}'")]
             </example>
             </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaValidateScriptAttribute.ScriptBlock">
            <summary>
            Gets the scriptblock to be used in the validation
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaValidateScriptAttribute.ValidateElement(System.Object)">
            <summary>
            Validates that each parameter argument matches the scriptblock
            </summary>
            <param name="element">object to validate</param>
            <exception cref="T:System.Management.Automation.ValidationMetadataException">if <paramref name="element"/> is invalid</exception>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaValidateScriptAttribute.#ctor(System.Management.Automation.ScriptBlock)">
            <summary>
            Initializes a new instance of the ValidateScriptBlockAttribute class
            </summary>
            <param name="scriptBlock">Scriptblock to match</param>
            <exception cref="T:System.ArgumentException">for invalid arguments</exception>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.RegexHelper">
            <summary>
            Static class that holds useful regex patterns, ready for use
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.HostName">
            <summary>
            Pattern that checks for a valid hostname
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.HostNameEx">
            <summary>
            Pattern that checks for valid hostnames within a larger text
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.IPv4">
            <summary>
            Pattern that checks for a valid IPv4 address
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.IPv4Ex">
            <summary>
            Pattern that checks for valid IPv4 addresses within a larger text
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.IPv6">
            <summary>
            Will match a valid IPv6 address
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.IPv6Ex">
            <summary>
            Will match any IPv6 address within a larger text
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.ComputerTarget">
            <summary>
            Will match any string that in its entirety represents a valid target for dns- or ip-based targeting. Combination of HostName, IPv4 and IPv6
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.Guid">
            <summary>
            Will match a valid Guid
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.GuidEx">
            <summary>
            Will match any number of valid Guids in a larger text
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.InstanceName">
            <summary>
            Will match a mostly valid instance name.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.InstanceNameEx">
            <summary>
            Will match any instance of a mostly valid instance name.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.SqlReservedKeyword">
            <summary>
            Matches a word against the list of officially reserved keywords
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.SqlReservedKeywordEx">
            <summary>
            Will match any reserved keyword in a larger text
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.SqlReservedKeywordOdbc">
            <summary>
            Matches a word against the list of officially reserved keywords for odbc
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.SqlReservedKeywordOdbcEx">
            <summary>
            Will match any reserved odbc-keyword in a larger text
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.SqlReservedKeywordFuture">
            <summary>
            Matches a word against the list of keywords that are likely to become reserved in the future
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.SqlReservedKeywordFutureEx">
            <summary>
            Will match against the list of keywords that are likely to become reserved in the future and are used in a larger text
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.Size">
            <summary>
            Class that reports File size.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.Size.Byte">
            <summary>
            Number of bytes contained in whatever object uses this object as a property
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.Size.Kilobyte">
            <summary>
            Kilobyte representation of the bytes
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.Size.Megabyte">
            <summary>
            Megabyte representation of the bytes
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.Size.Gigabyte">
            <summary>
            Gigabyte representation of the bytes
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.Size.Terabyte">
            <summary>
            Terabyte representation of the bytes
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.Size.Digits">
            <summary>
            Number if digits behind the dot.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.Size.Style">
            <summary>
            How the size object should be displayed.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.ToString">
            <summary>
            Shows the default string representation of size
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.Equals(System.Object)">
            <summary>
            Simple equality test
            </summary>
            <param name="obj">The object to test it against</param>
            <returns>True if equal, false elsewise</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.GetHashCode">
            <inheritdoc cref="M:System.Int64.GetHashCode"/>
            <remarks>The hashcode of the underlying size</remarks>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.#ctor">
            <summary>
            Creates an empty size.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.#ctor(System.Int64)">
            <summary>
            Creates a size with some content
            </summary>
            <param name="Byte">The length in bytes to set the size to</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.CompareTo(Sqlcollaborative.Dbatools.Utility.Size)">
            <inheritdoc cref="M:System.IComparable`1.CompareTo(`0)"/>
            <remarks>For sorting</remarks>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.CompareTo(System.Object)">
            <inheritdoc cref="M:System.IComparable.CompareTo(System.Object)"/>
            <remarks>For sorting</remarks>
            <exception cref="T:System.ArgumentException">If you compare with something invalid.</exception>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Addition(Sqlcollaborative.Dbatools.Utility.Size,Sqlcollaborative.Dbatools.Utility.Size)">
            <summary>
            Adds two sizes
            </summary>
            <param name="a">The first size to add</param>
            <param name="b">The second size to add</param>
            <returns>The sum of both sizes</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Subtraction(Sqlcollaborative.Dbatools.Utility.Size,Sqlcollaborative.Dbatools.Utility.Size)">
            <summary>
            Substracts two sizes
            </summary>
            <param name="a">The first size to substract</param>
            <param name="b">The second size to substract</param>
            <returns>The difference between both sizes</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Multiply(Sqlcollaborative.Dbatools.Utility.Size,System.Double)">
            <summary>
            Multiplies two sizes with each other
            </summary>
            <param name="a">The size to multiply</param>
            <param name="b">The size to multiply with</param>
            <returns>A multiplied size.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Division(Sqlcollaborative.Dbatools.Utility.Size,System.Double)">
            <summary>
            Divides one size by another. 
            </summary>
            <param name="a">The size to divide</param>
            <param name="b">The size to divide with</param>
            <returns>Divided size (note: Cut off)</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Multiply(Sqlcollaborative.Dbatools.Utility.Size,Sqlcollaborative.Dbatools.Utility.Size)">
            <summary>
            Multiplies two sizes with each other
            </summary>
            <param name="a">The size to multiply</param>
            <param name="b">The size to multiply with</param>
            <returns>A multiplied size.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Division(Sqlcollaborative.Dbatools.Utility.Size,Sqlcollaborative.Dbatools.Utility.Size)">
            <summary>
            Divides one size by another.
            </summary>
            <param name="a">The size to divide</param>
            <param name="b">The size to divide with</param>
            <returns>Divided size (note: Cut off)</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(System.Int32)~Sqlcollaborative.Dbatools.Utility.Size">
            <summary>
            Implicitly converts int to size
            </summary>
            <param name="a">The number to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(System.Decimal)~Sqlcollaborative.Dbatools.Utility.Size">
            <summary>
            Implicitly converts int to size
            </summary>
            <param name="a">The number to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(Sqlcollaborative.Dbatools.Utility.Size)~System.Int32">
            <summary>
            Implicitly converts size to int
            </summary>
            <param name="a">The size to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(System.Int64)~Sqlcollaborative.Dbatools.Utility.Size">
            <summary>
            Implicitly converts long to size
            </summary>
            <param name="a">The number to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(Sqlcollaborative.Dbatools.Utility.Size)~System.Int64">
            <summary>
            Implicitly converts size to long
            </summary>
            <param name="a">The size to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(System.String)~Sqlcollaborative.Dbatools.Utility.Size">
            <summary>
            Implicitly converts string to size
            </summary>
            <param name="a">The string to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(System.Double)~Sqlcollaborative.Dbatools.Utility.Size">
            <summary>
            Implicitly converts double to size
            </summary>
            <param name="a">The number to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(Sqlcollaborative.Dbatools.Utility.Size)~System.Double">
            <summary>
            Implicitly converts size to double
            </summary>
            <param name="a">The size to convert</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.SizeStyle">
            <summary>
            How size objects should be displayed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.SizeStyle.Dynamic">
            <summary>
            The size object is styled dependend on the number stored within.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.SizeStyle.Plain">
            <summary>
            The size object is shown as a plain number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.SizeStyle.Byte">
            <summary>
            The size object is styled as a byte number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.SizeStyle.Kilobyte">
            <summary>
            The size object is styled as a kilobyte number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.SizeStyle.Megabyte">
            <summary>
            The size object is styled as a megabyte number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.SizeStyle.Gigabyte">
            <summary>
            The size object is styled as a Gigabyte number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.SizeStyle.Terabyte">
            <summary>
            The size object is styled as a Terabyte number
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.UtilityHost">
            <summary>
            Provides static resources to utility-namespaced stuff
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.UtilityHost.DisableCustomDateTime">
            <summary>
            Restores all DateTime objects to their default display behavior
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.UtilityHost.DisableCustomTimeSpan">
            <summary>
            Restores all timespan objects to their default display behavior.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.UtilityHost.FormatDate">
            <summary>
            Formating string for date-style datetime objects.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.UtilityHost.FormatDateTime">
            <summary>
            Formating string for datetime-style datetime objects
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.UtilityHost.FormatTime">
            <summary>
            Formating string for time-style datetime objects
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.UtilityHost.SizeDigits">
            <summary>
            The number of digits a size object shows by default
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.UtilityHost.SizeStyle">
            <summary>
            The way size objects are usually displayed
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.UtilityHost.IsLike(System.String,System.String,System.Boolean)">
            <summary>
            Implement's VB's Like operator logic.
            </summary>
            <param name="CaseSensitive">Whether the comparison is case sensitive</param>
            <param name="Pattern">The pattern the string is compared with</param>
            <param name="String">The string that is being compared with a pattern</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.UtilityHost.CompressString(System.String)">
            <summary>
            Compress string using default zip algorithms
            </summary>
            <param name="String">The string to compress</param>
            <returns>Returns a compressed string.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.UtilityHost.ExpandString(System.String)">
            <summary>
            Expand a string using default zig algorithms
            </summary>
            <param name="CompressedString">The compressed string to expand</param>
            <returns>Returns an expanded string.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.UtilityHost.CharListToSet(System.String)">
            <summary>
            Converts a string of characters to a HashSet of characters. If the string
            contains character ranges, such as A-Z, all characters in the range are
            also added to the returned set of characters.
            </summary>
            <param name="charList">Character list string</param>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.UtilityHost.Callstack">
            <summary>
            Returns the current callstack
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.UtilityHost._CallstackNew">
            <summary>
            Returns the current callstack on PS4+
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.UtilityHost._CallstackOld">
            <summary>
            Returns the current callstack on PS3
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.Validation">
            <summary>
            Provides helper methods that aid in validating stuff.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Validation.IsLocalhost(System.String)">
            <summary>
            Tests whether a given string is the local host.
            Does NOT use DNS resolution, DNS aliases will NOT be recognized!
            </summary>
            <param name="Name">The name to test for being local host</param>
            <returns>Whether the name is localhost</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Validation.IsRecommendedInstanceName(System.String)">
            <summary>
            Tests whether a given string is a recommended instance name. Recommended names musst be legal, nbot on the ODBC list and not on the list of words likely to become reserved keywords in the future.
            </summary>
            <param name="InstanceName">The name to test. MAY contain server name, but will NOT test the server.</param>
            <returns>Whether the name is recommended</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Validation.IsValidComputerTarget(System.String)">
            <summary>
            Tests whether a given string is a valid target for targeting as a computer. Will first convert from idn name.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Validation.IsValidInstanceName(System.String,System.Boolean)">
            <summary>
            Tests whether a given string is a valid instance name.
            </summary>
            <param name="InstanceName">The name to test. MAY contain server name, but will NOT test the server.</param>
            <param name="Lenient">Setting this to true will make the validation ignore default and mssqlserver as illegal names (as they are illegal names for named instances, but legal for targeting)</param>
            <returns>Whether the name is legal</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Validation.LinkedServerResult">
            <summary>
            The results of testing linked server connectivity as seen from the server that was linked to.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.ComputerName">
            <summary>
            The name of the server running the tests
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.InstanceName">
            <summary>
            The name of the instance running the tests
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.SqlInstance">
            <summary>
            The full name of the instance running the tests
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.LinkedServerName">
            <summary>
            The name of the linked server, the connectivity with whom was tested
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.RemoteServer">
            <summary>
            The name of the remote computer running the linked server.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.Connectivity">
            <summary>
            The test result
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.Result">
            <summary>
            Text interpretation of the result. Contains error messages if the test failed.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.#ctor">
            <summary>
            Creates an empty object
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.#ctor(System.String,System.String,System.String,System.String,System.String,System.Boolean,System.String)">
            <summary>
            Creates a test result with prefilled values
            </summary>
            <param name="ComputerName">The name of the server running the tests</param>
            <param name="InstanceName">The name of the instance running the tests</param>
            <param name="SqlInstance">The full name of the instance running the tests</param>
            <param name="LinkedServerName">The name of the linked server, the connectivity with whom was tested</param>
            <param name="RemoteServer">The name of the remote computer running the linked server.</param>
            <param name="Connectivity">The test result</param>
            <param name="Result">Text interpretation of the result. Contains error messages if the test failed.</param>
        </member>
    </members>
</doc>
tools\dbatools\bin\netcoreapp2.1\dbatools.deps.json
{
  "runtimeTarget": {
    "name": ".NETCoreApp,Version=v2.1",
    "signature": "347fd959ec2fbdfda746c5752ff67a028ceedef4"
  },
  "compilationOptions": {},
  "targets": {
    ".NETCoreApp,Version=v2.1": {
      "dbatools/1.0.0": {
        "dependencies": {
          "Microsoft.Management.Infrastructure": "1.0.0",
          "System.Data.SqlClient": "4.5.1"
        },
        "runtime": {
          "dbatools.dll": {}
        }
      },
      "Microsoft.Management.Infrastructure/1.0.0": {
        "dependencies": {
          "System.Runtime.CompilerServices.VisualC": "4.3.0",
          "System.Runtime.Serialization.Xml": "4.3.0",
          "System.Security.SecureString": "4.3.0",
          "System.Threading.ThreadPool": "4.3.0"
        },
        "runtimeTargets": {
          "runtimes/unix/lib/netstandard1.6/Microsoft.Management.Infrastructure.Native.dll": {
            "rid": "unix",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "1.0.0.0"
          },
          "runtimes/unix/lib/netstandard1.6/Microsoft.Management.Infrastructure.dll": {
            "rid": "unix",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "10.0.10011.16384"
          },
          "runtimes/win-arm/lib/netstandard1.6/Microsoft.Management.Infrastructure.Native.dll": {
            "rid": "win-arm",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win-arm/lib/netstandard1.6/Microsoft.Management.Infrastructure.dll": {
            "rid": "win-arm",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win-arm64/lib/netstandard1.6/Microsoft.Management.Infrastructure.Native.dll": {
            "rid": "win-arm64",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win-arm64/lib/netstandard1.6/Microsoft.Management.Infrastructure.dll": {
            "rid": "win-arm64",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win10-x64/lib/netstandard1.6/Microsoft.Management.Infrastructure.Native.dll": {
            "rid": "win10-x64",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win10-x64/lib/netstandard1.6/Microsoft.Management.Infrastructure.dll": {
            "rid": "win10-x64",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win10-x86/lib/netstandard1.6/Microsoft.Management.Infrastructure.Native.dll": {
            "rid": "win10-x86",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win10-x86/lib/netstandard1.6/Microsoft.Management.Infrastructure.dll": {
            "rid": "win10-x86",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win7-x64/lib/netstandard1.6/Microsoft.Management.Infrastructure.Native.dll": {
            "rid": "win7-x64",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win7-x64/lib/netstandard1.6/Microsoft.Management.Infrastructure.dll": {
            "rid": "win7-x64",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win7-x86/lib/netstandard1.6/Microsoft.Management.Infrastructure.Native.dll": {
            "rid": "win7-x86",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win7-x86/lib/netstandard1.6/Microsoft.Management.Infrastructure.dll": {
            "rid": "win7-x86",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win8-x64/lib/netstandard1.6/Microsoft.Management.Infrastructure.Native.dll": {
            "rid": "win8-x64",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win8-x64/lib/netstandard1.6/Microsoft.Management.Infrastructure.dll": {
            "rid": "win8-x64",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win8-x86/lib/netstandard1.6/Microsoft.Management.Infrastructure.Native.dll": {
            "rid": "win8-x86",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win8-x86/lib/netstandard1.6/Microsoft.Management.Infrastructure.dll": {
            "rid": "win8-x86",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win81-x64/lib/netstandard1.6/Microsoft.Management.Infrastructure.Native.dll": {
            "rid": "win81-x64",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win81-x64/lib/netstandard1.6/Microsoft.Management.Infrastructure.dll": {
            "rid": "win81-x64",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win81-x86/lib/netstandard1.6/Microsoft.Management.Infrastructure.Native.dll": {
            "rid": "win81-x86",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win81-x86/lib/netstandard1.6/Microsoft.Management.Infrastructure.dll": {
            "rid": "win81-x86",
            "assetType": "runtime",
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win-arm/native/Microsoft.Management.Infrastructure.Native.Unmanaged.dll": {
            "rid": "win-arm",
            "assetType": "native",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win-arm/native/mi.dll": {
            "rid": "win-arm",
            "assetType": "native",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win-arm/native/miutils.dll": {
            "rid": "win-arm",
            "assetType": "native",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win-arm64/native/Microsoft.Management.Infrastructure.Native.Unmanaged.dll": {
            "rid": "win-arm64",
            "assetType": "native",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win-arm64/native/mi.dll": {
            "rid": "win-arm64",
            "assetType": "native",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win-arm64/native/miutils.dll": {
            "rid": "win-arm64",
            "assetType": "native",
            "fileVersion": "10.0.16299.15"
          },
          "runtimes/win10-x64/native/Microsoft.Management.Infrastructure.Native.Unmanaged.dll": {
            "rid": "win10-x64",
            "assetType": "native",
            "fileVersion": "10.0.14886.1000"
          },
          "runtimes/win10-x64/native/mi.dll": {
            "rid": "win10-x64",
            "assetType": "native",
            "fileVersion": "10.0.14886.1000"
          },
          "runtimes/win10-x64/native/miutils.dll": {
            "rid": "win10-x64",
            "assetType": "native",
            "fileVersion": "10.0.14886.1000"
          },
          "runtimes/win10-x86/native/Microsoft.Management.Infrastructure.Native.Unmanaged.dll": {
            "rid": "win10-x86",
            "assetType": "native",
            "fileVersion": "10.0.14394.1000"
          },
          "runtimes/win10-x86/native/mi.dll": {
            "rid": "win10-x86",
            "assetType": "native",
            "fileVersion": "10.0.14394.1000"
          },
          "runtimes/win10-x86/native/miutils.dll": {
            "rid": "win10-x86",
            "assetType": "native",
            "fileVersion": "10.0.14394.1000"
          },
          "runtimes/win7-x64/native/Microsoft.Management.Infrastructure.Native.Unmanaged.dll": {
            "rid": "win7-x64",
            "assetType": "native",
            "fileVersion": "10.0.14394.1000"
          },
          "runtimes/win7-x64/native/mi.dll": {
            "rid": "win7-x64",
            "assetType": "native",
            "fileVersion": "10.0.14394.1000"
          },
          "runtimes/win7-x64/native/miutils.dll": {
            "rid": "win7-x64",
            "assetType": "native",
            "fileVersion": "10.0.14394.1000"
          },
          "runtimes/win7-x86/native/Microsoft.Management.Infrastructure.Native.Unmanaged.dll": {
            "rid": "win7-x86",
            "assetType": "native",
            "fileVersion": "10.0.14394.1000"
          },
          "runtimes/win7-x86/native/mi.dll": {
            "rid": "win7-x86",
            "assetType": "native",
            "fileVersion": "10.0.14394.1000"
          },
          "runtimes/win7-x86/native/miutils.dll": {
            "rid": "win7-x86",
            "assetType": "native",
            "fileVersion": "10.0.14394.1000"
          },
          "runtimes/win8-x64/native/Microsoft.Management.Infrastructure.Native.Unmanaged.dll": {
            "rid": "win8-x64",
            "assetType": "native",
            "fileVersion": "10.0.14394.1000"
          },
          "runtimes/win8-x64/native/mi.dll": {
            "rid": "win8-x64",
            "assetType": "native",
            "fileVersion": "10.0.14394.1000"
          },
          "runtimes/win8-x64/native/miutils.dll": {
            "rid": "win8-x64",
            "assetType": "native",
            "fileVersion": "10.0.14394.1000"
          },
          "runtimes/win8-x86/native/Microsoft.Management.Infrastructure.Native.Unmanaged.dll": {
            "rid": "win8-x86",
            "assetType": "native",
            "fileVersion": "10.0.14394.1000"
          },
          "runtimes/win8-x86/native/mi.dll": {
            "rid": "win8-x86",
            "assetType": "native",
            "fileVersion": "10.0.14394.1000"
          },
          "runtimes/win8-x86/native/miutils.dll": {
            "rid": "win8-x86",
            "assetType": "native",
            "fileVersion": "10.0.14394.1000"
          },
          "runtimes/win81-x64/native/Microsoft.Management.Infrastructure.Native.Unmanaged.dll": {
            "rid": "win81-x64",
            "assetType": "native",
            "fileVersion": "10.0.14394.1000"
          },
          "runtimes/win81-x64/native/mi.dll": {
            "rid": "win81-x64",
            "assetType": "native",
            "fileVersion": "10.0.14394.1000"
          },
          "runtimes/win81-x64/native/miutils.dll": {
            "rid": "win81-x64",
            "assetType": "native",
            "fileVersion": "10.0.14394.1000"
          },
          "runtimes/win81-x86/native/Microsoft.Management.Infrastructure.Native.Unmanaged.dll": {
            "rid": "win81-x86",
            "assetType": "native",
            "fileVersion": "10.0.14394.1000"
          },
          "runtimes/win81-x86/native/mi.dll": {
            "rid": "win81-x86",
            "assetType": "native",
            "fileVersion": "10.0.14394.1000"
          },
          "runtimes/win81-x86/native/miutils.dll": {
            "rid": "win81-x86",
            "assetType": "native",
            "fileVersion": "10.0.14394.1000"
          }
        }
      },
      "Microsoft.Win32.Registry/4.5.0": {
        "dependencies": {
          "System.Security.AccessControl": "4.5.0",
          "System.Security.Principal.Windows": "4.5.0"
        },
        "runtimeTargets": {
          "runtime/unix/lib/_._": {
            "rid": "unix",
            "assetType": "runtime"
          },
          "runtime/win/lib/_._": {
            "rid": "win",
            "assetType": "runtime"
          }
        }
      },
      "runtime.native.System.Data.SqlClient.sni/4.4.0": {
        "dependencies": {
          "runtime.win-arm64.runtime.native.System.Data.SqlClient.sni": "4.4.0",
          "runtime.win-x64.runtime.native.System.Data.SqlClient.sni": "4.4.0",
          "runtime.win-x86.runtime.native.System.Data.SqlClient.sni": "4.4.0"
        }
      },
      "runtime.win-arm64.runtime.native.System.Data.SqlClient.sni/4.4.0": {
        "runtimeTargets": {
          "runtimes/win-arm64/native/sni.dll": {
            "rid": "win-arm64",
            "assetType": "native",
            "fileVersion": "4.6.25512.1"
          }
        }
      },
      "runtime.win-x64.runtime.native.System.Data.SqlClient.sni/4.4.0": {
        "runtimeTargets": {
          "runtimes/win-x64/native/sni.dll": {
            "rid": "win-x64",
            "assetType": "native",
            "fileVersion": "4.6.25512.1"
          }
        }
      },
      "runtime.win-x86.runtime.native.System.Data.SqlClient.sni/4.4.0": {
        "runtimeTargets": {
          "runtimes/win-x86/native/sni.dll": {
            "rid": "win-x86",
            "assetType": "native",
            "fileVersion": "4.6.25512.1"
          }
        }
      },
      "System.Collections/4.3.0": {
        "dependencies": {
          "System.Runtime": "4.3.0"
        }
      },
      "System.Collections.Concurrent/4.3.0": {
        "dependencies": {
          "System.Collections": "4.3.0",
          "System.Diagnostics.Debug": "4.3.0",
          "System.Diagnostics.Tracing": "4.3.0",
          "System.Globalization": "4.3.0",
          "System.Reflection": "4.3.0",
          "System.Resources.ResourceManager": "4.3.0",
          "System.Runtime": "4.3.0",
          "System.Runtime.Extensions": "4.3.0",
          "System.Threading": "4.3.0",
          "System.Threading.Tasks": "4.3.0"
        }
      },
      "System.Data.SqlClient/4.5.1": {
        "dependencies": {
          "Microsoft.Win32.Registry": "4.5.0",
          "System.Security.Principal.Windows": "4.5.0",
          "System.Text.Encoding.CodePages": "4.5.0",
          "runtime.native.System.Data.SqlClient.sni": "4.4.0"
        },
        "runtime": {
          "lib/netcoreapp2.1/System.Data.SqlClient.dll": {
            "assemblyVersion": "4.4.0.0",
            "fileVersion": "4.6.26606.5"
          }
        },
        "runtimeTargets": {
          "runtimes/unix/lib/netcoreapp2.1/System.Data.SqlClient.dll": {
            "rid": "unix",
            "assetType": "runtime",
            "assemblyVersion": "4.4.0.0",
            "fileVersion": "4.6.26606.5"
          },
          "runtimes/win/lib/netcoreapp2.1/System.Data.SqlClient.dll": {
            "rid": "win",
            "assetType": "runtime",
            "assemblyVersion": "4.4.0.0",
            "fileVersion": "4.6.26606.5"
          }
        }
      },
      "System.Diagnostics.Debug/4.3.0": {
        "dependencies": {
          "System.Runtime": "4.3.0"
        }
      },
      "System.Diagnostics.Tools/4.3.0": {
        "dependencies": {
          "System.Runtime": "4.3.0"
        }
      },
      "System.Diagnostics.Tracing/4.3.0": {
        "dependencies": {
          "System.Runtime": "4.3.0"
        }
      },
      "System.Globalization/4.3.0": {
        "dependencies": {
          "System.Runtime": "4.3.0"
        }
      },
      "System.IO/4.3.0": {
        "dependencies": {
          "System.Runtime": "4.3.0",
          "System.Text.Encoding": "4.3.0",
          "System.Threading.Tasks": "4.3.0"
        }
      },
      "System.IO.FileSystem/4.3.0": {
        "dependencies": {
          "System.IO": "4.3.0",
          "System.IO.FileSystem.Primitives": "4.3.0",
          "System.Runtime": "4.3.0",
          "System.Runtime.Handles": "4.3.0",
          "System.Text.Encoding": "4.3.0",
          "System.Threading.Tasks": "4.3.0"
        }
      },
      "System.IO.FileSystem.Primitives/4.3.0": {
        "dependencies": {
          "System.Runtime": "4.3.0"
        }
      },
      "System.Linq/4.3.0": {
        "dependencies": {
          "System.Collections": "4.3.0",
          "System.Diagnostics.Debug": "4.3.0",
          "System.Resources.ResourceManager": "4.3.0",
          "System.Runtime": "4.3.0",
          "System.Runtime.Extensions": "4.3.0"
        }
      },
      "System.Private.DataContractSerialization/4.3.0": {
        "dependencies": {
          "System.Collections": "4.3.0",
          "System.Collections.Concurrent": "4.3.0",
          "System.Diagnostics.Debug": "4.3.0",
          "System.Globalization": "4.3.0",
          "System.IO": "4.3.0",
          "System.Linq": "4.3.0",
          "System.Reflection": "4.3.0",
          "System.Reflection.Emit.ILGeneration": "4.3.0",
          "System.Reflection.Emit.Lightweight": "4.3.0",
          "System.Reflection.Extensions": "4.3.0",
          "System.Reflection.Primitives": "4.3.0",
          "System.Reflection.TypeExtensions": "4.3.0",
          "System.Resources.ResourceManager": "4.3.0",
          "System.Runtime": "4.3.0",
          "System.Runtime.Extensions": "4.3.0",
          "System.Runtime.Serialization.Primitives": "4.3.0",
          "System.Text.Encoding": "4.3.0",
          "System.Text.Encoding.Extensions": "4.3.0",
          "System.Text.RegularExpressions": "4.3.0",
          "System.Threading": "4.3.0",
          "System.Threading.Tasks": "4.3.0",
          "System.Xml.ReaderWriter": "4.3.0",
          "System.Xml.XDocument": "4.3.0",
          "System.Xml.XmlDocument": "4.3.0",
          "System.Xml.XmlSerializer": "4.3.0"
        }
      },
      "System.Reflection/4.3.0": {
        "dependencies": {
          "System.IO": "4.3.0",
          "System.Reflection.Primitives": "4.3.0",
          "System.Runtime": "4.3.0"
        }
      },
      "System.Reflection.Emit/4.3.0": {
        "dependencies": {
          "System.IO": "4.3.0",
          "System.Reflection": "4.3.0",
          "System.Reflection.Emit.ILGeneration": "4.3.0",
          "System.Reflection.Primitives": "4.3.0",
          "System.Runtime": "4.3.0"
        }
      },
      "System.Reflection.Emit.ILGeneration/4.3.0": {
        "dependencies": {
          "System.Reflection": "4.3.0",
          "System.Reflection.Primitives": "4.3.0",
          "System.Runtime": "4.3.0"
        }
      },
      "System.Reflection.Emit.Lightweight/4.3.0": {
        "dependencies": {
          "System.Reflection": "4.3.0",
          "System.Reflection.Emit.ILGeneration": "4.3.0",
          "System.Reflection.Primitives": "4.3.0",
          "System.Runtime": "4.3.0"
        }
      },
      "System.Reflection.Extensions/4.3.0": {
        "dependencies": {
          "System.Reflection": "4.3.0",
          "System.Runtime": "4.3.0"
        }
      },
      "System.Reflection.Primitives/4.3.0": {
        "dependencies": {
          "System.Runtime": "4.3.0"
        }
      },
      "System.Reflection.TypeExtensions/4.3.0": {
        "dependencies": {
          "System.Reflection": "4.3.0",
          "System.Runtime": "4.3.0"
        }
      },
      "System.Resources.ResourceManager/4.3.0": {
        "dependencies": {
          "System.Globalization": "4.3.0",
          "System.Reflection": "4.3.0",
          "System.Runtime": "4.3.0"
        }
      },
      "System.Runtime/4.3.0": {},
      "System.Runtime.CompilerServices.Unsafe/4.5.0": {
        "runtime": {
          "lib/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.dll": {
            "assemblyVersion": "4.0.4.0",
            "fileVersion": "0.0.0.0"
          }
        }
      },
      "System.Runtime.CompilerServices.VisualC/4.3.0": {
        "dependencies": {
          "System.Runtime": "4.3.0"
        }
      },
      "System.Runtime.Extensions/4.3.0": {
        "dependencies": {
          "System.Runtime": "4.3.0"
        }
      },
      "System.Runtime.Handles/4.3.0": {
        "dependencies": {
          "System.Runtime": "4.3.0"
        }
      },
      "System.Runtime.InteropServices/4.3.0": {
        "dependencies": {
          "System.Reflection": "4.3.0",
          "System.Reflection.Primitives": "4.3.0",
          "System.Runtime": "4.3.0",
          "System.Runtime.Handles": "4.3.0"
        }
      },
      "System.Runtime.Serialization.Primitives/4.3.0": {
        "dependencies": {
          "System.Resources.ResourceManager": "4.3.0",
          "System.Runtime": "4.3.0"
        }
      },
      "System.Runtime.Serialization.Xml/4.3.0": {
        "dependencies": {
          "System.IO": "4.3.0",
          "System.Private.DataContractSerialization": "4.3.0",
          "System.Runtime": "4.3.0",
          "System.Runtime.Serialization.Primitives": "4.3.0",
          "System.Text.Encoding": "4.3.0",
          "System.Xml.ReaderWriter": "4.3.0"
        }
      },
      "System.Security.AccessControl/4.5.0": {
        "dependencies": {
          "System.Security.Principal.Windows": "4.5.0"
        },
        "runtimeTargets": {
          "runtime/win/lib/_._": {
            "rid": "win",
            "assetType": "runtime"
          }
        }
      },
      "System.Security.Cryptography.Primitives/4.3.0": {
        "dependencies": {
          "System.Diagnostics.Debug": "4.3.0",
          "System.Globalization": "4.3.0",
          "System.IO": "4.3.0",
          "System.Resources.ResourceManager": "4.3.0",
          "System.Runtime": "4.3.0",
          "System.Threading": "4.3.0",
          "System.Threading.Tasks": "4.3.0"
        }
      },
      "System.Security.Principal.Windows/4.5.0": {
        "runtimeTargets": {
          "runtime/unix/lib/_._": {
            "rid": "unix",
            "assetType": "runtime"
          },
          "runtime/win/lib/_._": {
            "rid": "win",
            "assetType": "runtime"
          }
        }
      },
      "System.Security.SecureString/4.3.0": {
        "dependencies": {
          "System.Resources.ResourceManager": "4.3.0",
          "System.Runtime": "4.3.0",
          "System.Runtime.Handles": "4.3.0",
          "System.Runtime.InteropServices": "4.3.0",
          "System.Security.Cryptography.Primitives": "4.3.0",
          "System.Text.Encoding": "4.3.0",
          "System.Threading": "4.3.0"
        },
        "runtimeTargets": {
          "runtime/unix/lib/_._": {
            "rid": "unix",
            "assetType": "runtime"
          },
          "runtime/win/lib/_._": {
            "rid": "win",
            "assetType": "runtime"
          }
        }
      },
      "System.Text.Encoding/4.3.0": {
        "dependencies": {
          "System.Runtime": "4.3.0"
        }
      },
      "System.Text.Encoding.CodePages/4.5.0": {
        "dependencies": {
          "System.Runtime.CompilerServices.Unsafe": "4.5.0"
        },
        "runtime": {
          "lib/netstandard2.0/System.Text.Encoding.CodePages.dll": {
            "assemblyVersion": "4.1.1.0",
            "fileVersion": "4.6.26515.6"
          }
        },
        "runtimeTargets": {
          "runtimes/win/lib/netcoreapp2.0/System.Text.Encoding.CodePages.dll": {
            "rid": "win",
            "assetType": "runtime",
            "assemblyVersion": "4.1.1.0",
            "fileVersion": "4.6.26515.6"
          }
        }
      },
      "System.Text.Encoding.Extensions/4.3.0": {
        "dependencies": {
          "System.Runtime": "4.3.0",
          "System.Text.Encoding": "4.3.0"
        }
      },
      "System.Text.RegularExpressions/4.3.0": {
        "dependencies": {
          "System.Runtime": "4.3.0"
        }
      },
      "System.Threading/4.3.0": {
        "dependencies": {
          "System.Runtime": "4.3.0",
          "System.Threading.Tasks": "4.3.0"
        }
      },
      "System.Threading.Tasks/4.3.0": {
        "dependencies": {
          "System.Runtime": "4.3.0"
        }
      },
      "System.Threading.Tasks.Extensions/4.3.0": {
        "dependencies": {
          "System.Collections": "4.3.0",
          "System.Runtime": "4.3.0",
          "System.Threading.Tasks": "4.3.0"
        }
      },
      "System.Threading.ThreadPool/4.3.0": {
        "dependencies": {
          "System.Runtime": "4.3.0",
          "System.Runtime.Handles": "4.3.0"
        }
      },
      "System.Xml.ReaderWriter/4.3.0": {
        "dependencies": {
          "System.Collections": "4.3.0",
          "System.Diagnostics.Debug": "4.3.0",
          "System.Globalization": "4.3.0",
          "System.IO": "4.3.0",
          "System.IO.FileSystem": "4.3.0",
          "System.IO.FileSystem.Primitives": "4.3.0",
          "System.Resources.ResourceManager": "4.3.0",
          "System.Runtime": "4.3.0",
          "System.Runtime.Extensions": "4.3.0",
          "System.Runtime.InteropServices": "4.3.0",
          "System.Text.Encoding": "4.3.0",
          "System.Text.Encoding.Extensions": "4.3.0",
          "System.Text.RegularExpressions": "4.3.0",
          "System.Threading.Tasks": "4.3.0",
          "System.Threading.Tasks.Extensions": "4.3.0"
        }
      },
      "System.Xml.XDocument/4.3.0": {
        "dependencies": {
          "System.Collections": "4.3.0",
          "System.Diagnostics.Debug": "4.3.0",
          "System.Diagnostics.Tools": "4.3.0",
          "System.Globalization": "4.3.0",
          "System.IO": "4.3.0",
          "System.Reflection": "4.3.0",
          "System.Resources.ResourceManager": "4.3.0",
          "System.Runtime": "4.3.0",
          "System.Runtime.Extensions": "4.3.0",
          "System.Text.Encoding": "4.3.0",
          "System.Threading": "4.3.0",
          "System.Xml.ReaderWriter": "4.3.0"
        }
      },
      "System.Xml.XmlDocument/4.3.0": {
        "dependencies": {
          "System.Collections": "4.3.0",
          "System.Diagnostics.Debug": "4.3.0",
          "System.Globalization": "4.3.0",
          "System.IO": "4.3.0",
          "System.Resources.ResourceManager": "4.3.0",
          "System.Runtime": "4.3.0",
          "System.Runtime.Extensions": "4.3.0",
          "System.Text.Encoding": "4.3.0",
          "System.Threading": "4.3.0",
          "System.Xml.ReaderWriter": "4.3.0"
        }
      },
      "System.Xml.XmlSerializer/4.3.0": {
        "dependencies": {
          "System.Collections": "4.3.0",
          "System.Globalization": "4.3.0",
          "System.IO": "4.3.0",
          "System.Linq": "4.3.0",
          "System.Reflection": "4.3.0",
          "System.Reflection.Emit": "4.3.0",
          "System.Reflection.Emit.ILGeneration": "4.3.0",
          "System.Reflection.Extensions": "4.3.0",
          "System.Reflection.Primitives": "4.3.0",
          "System.Reflection.TypeExtensions": "4.3.0",
          "System.Resources.ResourceManager": "4.3.0",
          "System.Runtime": "4.3.0",
          "System.Runtime.Extensions": "4.3.0",
          "System.Text.RegularExpressions": "4.3.0",
          "System.Threading": "4.3.0",
          "System.Xml.ReaderWriter": "4.3.0",
          "System.Xml.XmlDocument": "4.3.0"
        }
      }
    }
  },
  "libraries": {
    "dbatools/1.0.0": {
      "type": "project",
      "serviceable": false,
      "sha512": ""
    },
    "Microsoft.Management.Infrastructure/1.0.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-farHXHRCm0ZaioRlsQtHjb18sZ+X2jluOv3L/aOucXW83BmfHfXC7t+GtKZSK7Gd1y2lFh6R/pr31IpvRvZbOg==",
      "path": "microsoft.management.infrastructure/1.0.0",
      "hashPath": "microsoft.management.infrastructure.1.0.0.nupkg.sha512"
    },
    "Microsoft.Win32.Registry/4.5.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-vduxuHEqRgRrTE8wYG8Wxj/+6wwzddOmZzjKZx6rFMc/91aUBxI5etAFYxesoNaIja5NpgSTcnk6cN8BeYXf9A==",
      "path": "microsoft.win32.registry/4.5.0",
      "hashPath": "microsoft.win32.registry.4.5.0.nupkg.sha512"
    },
    "runtime.native.System.Data.SqlClient.sni/4.4.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-A8v6PGmk+UGbfWo5Ixup0lPM4swuSwOiayJExZwKIOjTlFFQIsu3QnDXECosBEyrWSPryxBVrdqtJyhK3BaupQ==",
      "path": "runtime.native.system.data.sqlclient.sni/4.4.0",
      "hashPath": "runtime.native.system.data.sqlclient.sni.4.4.0.nupkg.sha512"
    },
    "runtime.win-arm64.runtime.native.System.Data.SqlClient.sni/4.4.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-LbrynESTp3bm5O/+jGL8v0Qg5SJlTV08lpIpFesXjF6uGNMWqFnUQbYBJwZTeua6E/Y7FIM1C54Ey1btLWupdg==",
      "path": "runtime.win-arm64.runtime.native.system.data.sqlclient.sni/4.4.0",
      "hashPath": "runtime.win-arm64.runtime.native.system.data.sqlclient.sni.4.4.0.nupkg.sha512"
    },
    "runtime.win-x64.runtime.native.System.Data.SqlClient.sni/4.4.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-38ugOfkYJqJoX9g6EYRlZB5U2ZJH51UP8ptxZgdpS07FgOEToV+lS11ouNK2PM12Pr6X/PpT5jK82G3DwH/SxQ==",
      "path": "runtime.win-x64.runtime.native.system.data.sqlclient.sni/4.4.0",
      "hashPath": "runtime.win-x64.runtime.native.system.data.sqlclient.sni.4.4.0.nupkg.sha512"
    },
    "runtime.win-x86.runtime.native.System.Data.SqlClient.sni/4.4.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-YhEdSQUsTx+C8m8Bw7ar5/VesXvCFMItyZF7G1AUY+OM0VPZUOeAVpJ4Wl6fydBGUYZxojTDR3I6Bj/+BPkJNA==",
      "path": "runtime.win-x86.runtime.native.system.data.sqlclient.sni/4.4.0",
      "hashPath": "runtime.win-x86.runtime.native.system.data.sqlclient.sni.4.4.0.nupkg.sha512"
    },
    "System.Collections/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-3Dcj85/TBdVpL5Zr+gEEBUuFe2icOnLalmEh9hfck1PTYbbyWuZgh4fmm2ysCLTrqLQw6t3TgTyJ+VLp+Qb+Lw==",
      "path": "system.collections/4.3.0",
      "hashPath": "system.collections.4.3.0.nupkg.sha512"
    },
    "System.Collections.Concurrent/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-ztl69Xp0Y/UXCL+3v3tEU+lIy+bvjKNUmopn1wep/a291pVPK7dxBd6T7WnlQqRog+d1a/hSsgRsmFnIBKTPLQ==",
      "path": "system.collections.concurrent/4.3.0",
      "hashPath": "system.collections.concurrent.4.3.0.nupkg.sha512"
    },
    "System.Data.SqlClient/4.5.1": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-qXTvTFkBds7bnN+ntBMHGvmH3pCAkfT4TE1z2Xvfqo4wKMQC77O4aXsYCc7dzCESC+/Gom6l0GLuebpFx7MDvg==",
      "path": "system.data.sqlclient/4.5.1",
      "hashPath": "system.data.sqlclient.4.5.1.nupkg.sha512"
    },
    "System.Diagnostics.Debug/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-ZUhUOdqmaG5Jk3Xdb8xi5kIyQYAA4PnTNlHx1mu9ZY3qv4ELIdKbnL/akbGaKi2RnNUWaZsAs31rvzFdewTj2g==",
      "path": "system.diagnostics.debug/4.3.0",
      "hashPath": "system.diagnostics.debug.4.3.0.nupkg.sha512"
    },
    "System.Diagnostics.Tools/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-UUvkJfSYJMM6x527dJg2VyWPSRqIVB0Z7dbjHst1zmwTXz5CcXSYJFWRpuigfbO1Lf7yfZiIaEUesfnl/g5EyA==",
      "path": "system.diagnostics.tools/4.3.0",
      "hashPath": "system.diagnostics.tools.4.3.0.nupkg.sha512"
    },
    "System.Diagnostics.Tracing/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-rswfv0f/Cqkh78rA5S8eN8Neocz234+emGCtTF3lxPY96F+mmmUen6tbn0glN6PMvlKQb9bPAY5e9u7fgPTkKw==",
      "path": "system.diagnostics.tracing/4.3.0",
      "hashPath": "system.diagnostics.tracing.4.3.0.nupkg.sha512"
    },
    "System.Globalization/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-kYdVd2f2PAdFGblzFswE4hkNANJBKRmsfa2X5LG2AcWE1c7/4t0pYae1L8vfZ5xvE2nK/R9JprtToA61OSHWIg==",
      "path": "system.globalization/4.3.0",
      "hashPath": "system.globalization.4.3.0.nupkg.sha512"
    },
    "System.IO/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-3qjaHvxQPDpSOYICjUoTsmoq5u6QJAFRUITgeT/4gqkF1bajbSmb1kwSxEA8AHlofqgcKJcM8udgieRNhaJ5Cg==",
      "path": "system.io/4.3.0",
      "hashPath": "system.io.4.3.0.nupkg.sha512"
    },
    "System.IO.FileSystem/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-3wEMARTnuio+ulnvi+hkRNROYwa1kylvYahhcLk4HSoVdl+xxTFVeVlYOfLwrDPImGls0mDqbMhrza8qnWPTdA==",
      "path": "system.io.filesystem/4.3.0",
      "hashPath": "system.io.filesystem.4.3.0.nupkg.sha512"
    },
    "System.IO.FileSystem.Primitives/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-6QOb2XFLch7bEc4lIcJH49nJN2HV+OC3fHDgsLVsBVBk3Y4hFAnOBGzJ2lUu7CyDDFo9IBWkSsnbkT6IBwwiMw==",
      "path": "system.io.filesystem.primitives/4.3.0",
      "hashPath": "system.io.filesystem.primitives.4.3.0.nupkg.sha512"
    },
    "System.Linq/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-5DbqIUpsDp0dFftytzuMmc0oeMdQwjcP/EWxsksIz/w1TcFRkZ3yKKz0PqiYFMmEwPSWw+qNVqD7PJ889JzHbw==",
      "path": "system.linq/4.3.0",
      "hashPath": "system.linq.4.3.0.nupkg.sha512"
    },
    "System.Private.DataContractSerialization/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-yDaJ2x3mMmjdZEDB4IbezSnCsnjQ4BxinKhRAaP6kEgL6Bb6jANWphs5SzyD8imqeC/3FxgsuXT6ykkiH1uUmA==",
      "path": "system.private.datacontractserialization/4.3.0",
      "hashPath": "system.private.datacontractserialization.4.3.0.nupkg.sha512"
    },
    "System.Reflection/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-KMiAFoW7MfJGa9nDFNcfu+FpEdiHpWgTcS2HdMpDvt9saK3y/G4GwprPyzqjFH9NTaGPQeWNHU+iDlDILj96aQ==",
      "path": "system.reflection/4.3.0",
      "hashPath": "system.reflection.4.3.0.nupkg.sha512"
    },
    "System.Reflection.Emit/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-228FG0jLcIwTVJyz8CLFKueVqQK36ANazUManGaJHkO0icjiIypKW7YLWLIWahyIkdh5M7mV2dJepllLyA1SKg==",
      "path": "system.reflection.emit/4.3.0",
      "hashPath": "system.reflection.emit.4.3.0.nupkg.sha512"
    },
    "System.Reflection.Emit.ILGeneration/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-59tBslAk9733NXLrUJrwNZEzbMAcu8k344OYo+wfSVygcgZ9lgBdGIzH/nrg3LYhXceynyvTc8t5/GD4Ri0/ng==",
      "path": "system.reflection.emit.ilgeneration/4.3.0",
      "hashPath": "system.reflection.emit.ilgeneration.4.3.0.nupkg.sha512"
    },
    "System.Reflection.Emit.Lightweight/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-oadVHGSMsTmZsAF864QYN1t1QzZjIcuKU3l2S9cZOwDdDueNTrqq1yRj7koFfIGEnKpt6NjpL3rOzRhs4ryOgA==",
      "path": "system.reflection.emit.lightweight/4.3.0",
      "hashPath": "system.reflection.emit.lightweight.4.3.0.nupkg.sha512"
    },
    "System.Reflection.Extensions/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-rJkrJD3kBI5B712aRu4DpSIiHRtr6QlfZSQsb0hYHrDCZORXCFjQfoipo2LaMUHoT9i1B7j7MnfaEKWDFmFQNQ==",
      "path": "system.reflection.extensions/4.3.0",
      "hashPath": "system.reflection.extensions.4.3.0.nupkg.sha512"
    },
    "System.Reflection.Primitives/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-5RXItQz5As4xN2/YUDxdpsEkMhvw3e6aNveFXUn4Hl/udNTCNhnKp8lT9fnc3MhvGKh1baak5CovpuQUXHAlIA==",
      "path": "system.reflection.primitives/4.3.0",
      "hashPath": "system.reflection.primitives.4.3.0.nupkg.sha512"
    },
    "System.Reflection.TypeExtensions/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-7u6ulLcZbyxB5Gq0nMkQttcdBTx57ibzw+4IOXEfR+sXYQoHvjW5LTLyNr8O22UIMrqYbchJQJnos4eooYzYJA==",
      "path": "system.reflection.typeextensions/4.3.0",
      "hashPath": "system.reflection.typeextensions.4.3.0.nupkg.sha512"
    },
    "System.Resources.ResourceManager/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-/zrcPkkWdZmI4F92gL/TPumP98AVDu/Wxr3CSJGQQ+XN6wbRZcyfSKVoPo17ilb3iOr0cCRqJInGwNMolqhS8A==",
      "path": "system.resources.resourcemanager/4.3.0",
      "hashPath": "system.resources.resourcemanager.4.3.0.nupkg.sha512"
    },
    "System.Runtime/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-JufQi0vPQ0xGnAczR13AUFglDyVYt4Kqnz1AZaiKZ5+GICq0/1MH/mO/eAJHt/mHW1zjKBJd7kV26SrxddAhiw==",
      "path": "system.runtime/4.3.0",
      "hashPath": "system.runtime.4.3.0.nupkg.sha512"
    },
    "System.Runtime.CompilerServices.Unsafe/4.5.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-6zBxkHYemB0kQiHP3vGXGRXejZVoNVuMn2paUuqKKi5Wyjkxfkp+D0rd0c3VrGwotidRINt6KpOi2smL4VkJKw==",
      "path": "system.runtime.compilerservices.unsafe/4.5.0",
      "hashPath": "system.runtime.compilerservices.unsafe.4.5.0.nupkg.sha512"
    },
    "System.Runtime.CompilerServices.VisualC/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-/dcn1oXqK/p/VnTYWNSf4OXlFIfzCRE/kqWz4+/r5B2S4zlKifB1FqklEEYs5zmE1JE3syvrJ5U4syOwsDQZbA==",
      "path": "system.runtime.compilerservices.visualc/4.3.0",
      "hashPath": "system.runtime.compilerservices.visualc.4.3.0.nupkg.sha512"
    },
    "System.Runtime.Extensions/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-guW0uK0fn5fcJJ1tJVXYd7/1h5F+pea1r7FLSOz/f8vPEqbR2ZAknuRDvTQ8PzAilDveOxNjSfr0CHfIQfFk8g==",
      "path": "system.runtime.extensions/4.3.0",
      "hashPath": "system.runtime.extensions.4.3.0.nupkg.sha512"
    },
    "System.Runtime.Handles/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-OKiSUN7DmTWeYb3l51A7EYaeNMnvxwE249YtZz7yooT4gOZhmTjIn48KgSsw2k2lYdLgTKNJw/ZIfSElwDRVgg==",
      "path": "system.runtime.handles/4.3.0",
      "hashPath": "system.runtime.handles.4.3.0.nupkg.sha512"
    },
    "System.Runtime.InteropServices/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-uv1ynXqiMK8mp1GM3jDqPCFN66eJ5w5XNomaK2XD+TuCroNTLFGeZ+WCmBMcBDyTFKou3P6cR6J/QsaqDp7fGQ==",
      "path": "system.runtime.interopservices/4.3.0",
      "hashPath": "system.runtime.interopservices.4.3.0.nupkg.sha512"
    },
    "System.Runtime.Serialization.Primitives/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-Wz+0KOukJGAlXjtKr+5Xpuxf8+c8739RI1C+A2BoQZT+wMCCoMDDdO8/4IRHfaVINqL78GO8dW8G2lW/e45Mcw==",
      "path": "system.runtime.serialization.primitives/4.3.0",
      "hashPath": "system.runtime.serialization.primitives.4.3.0.nupkg.sha512"
    },
    "System.Runtime.Serialization.Xml/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-nUQx/5OVgrqEba3+j7OdiofvVq9koWZAC7Z3xGI8IIViZqApWnZ5+lLcwYgTlbkobrl/Rat+Jb8GeD4WQESD2A==",
      "path": "system.runtime.serialization.xml/4.3.0",
      "hashPath": "system.runtime.serialization.xml.4.3.0.nupkg.sha512"
    },
    "System.Security.AccessControl/4.5.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-aVjTe36YkO8FzfNhMLoPEzv3gF9rphoW9ngFhG/MH4zzEPLx07sNrgCLwMP4Wx2leI6qarMrGv21OwQXYUKLmw==",
      "path": "system.security.accesscontrol/4.5.0",
      "hashPath": "system.security.accesscontrol.4.5.0.nupkg.sha512"
    },
    "System.Security.Cryptography.Primitives/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-7bDIyVFNL/xKeFHjhobUAQqSpJq9YTOpbEs6mR233Et01STBMXNAc/V+BM6dwYGc95gVh/Zf+iVXWzj3mE8DWg==",
      "path": "system.security.cryptography.primitives/4.3.0",
      "hashPath": "system.security.cryptography.primitives.4.3.0.nupkg.sha512"
    },
    "System.Security.Principal.Windows/4.5.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-WA9ETb/pY3BjnxKjBUHEgO59B7d/nnmjHFsqjJ2eDT780nD769CT1/bw2ia0Z6W7NqlcqokE6sKGKa6uw88XGA==",
      "path": "system.security.principal.windows/4.5.0",
      "hashPath": "system.security.principal.windows.4.5.0.nupkg.sha512"
    },
    "System.Security.SecureString/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-PnXp38O9q/2Oe4iZHMH60kinScv6QiiL2XH54Pj2t0Y6c2zKPEiAZsM/M3wBOHLNTBDFP0zfy13WN2M0qFz5jg==",
      "path": "system.security.securestring/4.3.0",
      "hashPath": "system.security.securestring.4.3.0.nupkg.sha512"
    },
    "System.Text.Encoding/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-BiIg+KWaSDOITze6jGQynxg64naAPtqGHBwDrLaCtixsa5bKiR8dpPOHA7ge3C0JJQizJE+sfkz1wV+BAKAYZw==",
      "path": "system.text.encoding/4.3.0",
      "hashPath": "system.text.encoding.4.3.0.nupkg.sha512"
    },
    "System.Text.Encoding.CodePages/4.5.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-16EVkWmNnoH3/Yj9c5s5VuLK5Uv/Dnkc3P2kMmnD7wJcUuvcHVvM2IhVJanf2hHRZUitH+cIkPCPHrBoCXc7Rw==",
      "path": "system.text.encoding.codepages/4.5.0",
      "hashPath": "system.text.encoding.codepages.4.5.0.nupkg.sha512"
    },
    "System.Text.Encoding.Extensions/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-YVMK0Bt/A43RmwizJoZ22ei2nmrhobgeiYwFzC4YAN+nue8RF6djXDMog0UCn+brerQoYVyaS+ghy9P/MUVcmw==",
      "path": "system.text.encoding.extensions/4.3.0",
      "hashPath": "system.text.encoding.extensions.4.3.0.nupkg.sha512"
    },
    "System.Text.RegularExpressions/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-RpT2DA+L660cBt1FssIE9CAGpLFdFPuheB7pLpKpn6ZXNby7jDERe8Ua/Ne2xGiwLVG2JOqziiaVCGDon5sKFA==",
      "path": "system.text.regularexpressions/4.3.0",
      "hashPath": "system.text.regularexpressions.4.3.0.nupkg.sha512"
    },
    "System.Threading/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-VkUS0kOBcUf3Wwm0TSbrevDDZ6BlM+b/HRiapRFWjM5O0NS0LviG0glKmFK+hhPDd1XFeSdU1GmlLhb2CoVpIw==",
      "path": "system.threading/4.3.0",
      "hashPath": "system.threading.4.3.0.nupkg.sha512"
    },
    "System.Threading.Tasks/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-LbSxKEdOUhVe8BezB/9uOGGppt+nZf6e1VFyw6v3DN6lqitm0OSn2uXMOdtP0M3W4iMcqcivm2J6UgqiwwnXiA==",
      "path": "system.threading.tasks/4.3.0",
      "hashPath": "system.threading.tasks.4.3.0.nupkg.sha512"
    },
    "System.Threading.Tasks.Extensions/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-npvJkVKl5rKXrtl1Kkm6OhOUaYGEiF9wFbppFRWSMoApKzt2PiPHT2Bb8a5sAWxprvdOAtvaARS9QYMznEUtug==",
      "path": "system.threading.tasks.extensions/4.3.0",
      "hashPath": "system.threading.tasks.extensions.4.3.0.nupkg.sha512"
    },
    "System.Threading.ThreadPool/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-k/+g4b7vjdd4aix83sTgC9VG6oXYKAktSfNIJUNGxPEj7ryEOfzHHhfnmsZvjxawwcD9HyWXKCXmPjX8U4zeSw==",
      "path": "system.threading.threadpool/4.3.0",
      "hashPath": "system.threading.threadpool.4.3.0.nupkg.sha512"
    },
    "System.Xml.ReaderWriter/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-GrprA+Z0RUXaR4N7/eW71j1rgMnEnEVlgii49GZyAjTH7uliMnrOU3HNFBr6fEDBCJCIdlVNq9hHbaDR621XBA==",
      "path": "system.xml.readerwriter/4.3.0",
      "hashPath": "system.xml.readerwriter.4.3.0.nupkg.sha512"
    },
    "System.Xml.XDocument/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-5zJ0XDxAIg8iy+t4aMnQAu0MqVbqyvfoUVl1yDV61xdo3Vth45oA2FoY4pPkxYAH5f8ixpmTqXeEIya95x0aCQ==",
      "path": "system.xml.xdocument/4.3.0",
      "hashPath": "system.xml.xdocument.4.3.0.nupkg.sha512"
    },
    "System.Xml.XmlDocument/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-lJ8AxvkX7GQxpC6GFCeBj8ThYVyQczx2+f/cWHJU8tjS7YfI6Cv6bon70jVEgs2CiFbmmM8b9j1oZVx0dSI2Ww==",
      "path": "system.xml.xmldocument/4.3.0",
      "hashPath": "system.xml.xmldocument.4.3.0.nupkg.sha512"
    },
    "System.Xml.XmlSerializer/4.3.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-MYoTCP7EZ98RrANESW05J5ZwskKDoN0AuZ06ZflnowE50LTpbR5yRg3tHckTVm5j/m47stuGgCrCHWePyHS70Q==",
      "path": "system.xml.xmlserializer/4.3.0",
      "hashPath": "system.xml.xmlserializer.4.3.0.nupkg.sha512"
    }
  }
}
tools\dbatools\bin\netcoreapp2.1\dbatools.dll
md5: C071E63932D16EB11E2CDC1CF133AD00 | sha1: B0259D2EE9811A433E1AEEB1AFE6C4F0EF37A55C | sha256: 2D6928D37E8DFD008A05E28373652182431866DB69C4521007686225483ABF59 | sha512: 73118BD626D4661EF8137D5B3A71E05766960596A2E9CC0B552DB2609C32BD93E62CA0ED09BF2C41C68AA66C114B3873D5C1222A98FF6C90AD3BC6324F202A38
tools\dbatools\bin\netcoreapp2.1\dbatools.pdb
 
tools\dbatools\bin\netcoreapp2.1\dbatools.xml
<?xml version="1.0"?>
<doc>
    <assembly>
        <name>dbatools</name>
    </assembly>
    <members>
        <member name="T:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand">
            <summary>
            Implements the Select-DbaObject command
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.InputObject">
            <summary>
            The actual input object that is being processed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.Property">
            <summary>
            The properties to select. Supports fancy DSL
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.ExcludeProperty">
            <summary>
            Properties to skip
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.ExpandProperty">
            <summary>
            A property to expand.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.Unique">
            <summary>
            Whether to exclude duplicates
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.Last">
            <summary>
            The last number of items to pick
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.First">
            <summary>
            Pick the first n items.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.Skip">
            <summary>
            Skip n items before picking items
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.SkipLast">
            <summary>
            Skip the last n items
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.Wait">
            <summary>
            
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.Index">
            <summary>
            
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.ShowProperty">
            <summary>
            THe properties to display by default
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.ShowExcludeProperty">
            <summary>
            The properties to NOT display by default
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.TypeName">
            <summary>
            The typename to assign to the psobject
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.KeepInputObject">
            <summary>
            Keep the original input object, just add to it.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand._NonclonedProperties">
            <summary>
            List of properties to NOT clone into the hashtable used against Select-Object
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand._NoAdjustment">
            <summary>
            Whether some adjustments to the object need to be done or whether the Select-Object output can be simply passed through.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand._DisplayPropertySet">
            <summary>
            The set controlling what properties will be shown by default
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand._Pipeline">
            <summary>
            THe pipeline that is wrapped around Select-Object
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.BeginProcessing">
            <summary>
            Implements the begin action of the command
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.ProcessRecord">
            <summary>
            Implements the process action of the command
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand.EndProcessing">
            <summary>
            Implements the end action of the command
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand">
            <summary>
            Implements the Set-PSFConfig command
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.FullName">
            <summary>
            The full name of the setting
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Module">
            <summary>
            The name of the module the setting belongs to.
            Is optional due to just specifying a name is legal, in which case the first name segment becomes the module name.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Name">
            <summary>
            The name of the setting within a module.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Value">
            <summary>
            The value to apply.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.PersistedValue">
            <summary>
            The persisted value to apply.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.PersistedType">
            <summary>
            The persisted type to apply.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Description">
            <summary>
            Add documentation to the setting.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Validation">
            <summary>
            The validation script to use.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Handler">
            <summary>
            The handling script to apply when changing the value.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Hidden">
            <summary>
            Whether the setting should be hidden from casual discovery.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Default">
            <summary>
            Whether the setting should be applied only when nothing exists yet.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.Initialize">
            <summary>
            Whether this is the configuration initialization call.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.SimpleExport">
            <summary>
            Enabling this will cause the module to use friendly json notation on export to file.
            This may result in loss of data precision, but is more userfriendly.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.ModuleExport">
            <summary>
            Whether this setting applies to module scope file export.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.DisableValidation">
            <summary>
            Do not apply the validation script when changing values.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.DisableHandler">
            <summary>
            Do not run the handler script when changing values.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.PassThru">
            <summary>
            Return the changed configuration setting.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.EnableException">
            <summary>
            Enable throwing exceptions.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._Config">
            <summary>
            The configuration item changed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._KillIt">
            <summary>
            Whether execution should be terminated silently.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._Initialize">
            <summary>
            Whether this is an initialization execution.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._Persisted">
            <summary>
            Whether persisted values need to be restored.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._Exists">
            <summary>
            Whether the setting already exists.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._PolicyEnforced">
            <summary>
            The setting to be affected was enforced by policy and cannot be changed by the user.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._NameModule">
            <summary>
            Processed name of module.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._NameName">
            <summary>
            Processed name of setting within module.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._NameFull">
            <summary>
            Processed full name of setting.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand._ValidationErrorMessage">
            <summary>
            The reason validation failed.
            Filled by ApplyValue.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.BeginProcessing">
            <summary>
            Implements the begin action of Set-PSFConfig
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.ProcessRecord">
            <summary>
            Implements the process action of Set-PSFConfig
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.ApplyValue(System.Object)">
            <summary>
            Applies a value to a configuration item, invoking validation and handler scriptblocks.
            </summary>
            <param name="Value">The value to apply</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand.ApplyCommonSettings">
            <summary>
            Abstracts out 
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand">
            <summary>
            Implements the Write-Message command, performing message handling and loggin
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Level">
            <summary>
            This parameter represents the verbosity of the message. The lower the number, the more important it is for a human user to read the message.
            By default, the levels are distributed like this:
            - 1-3 Direct verbose output to the user (using Write-Host)
            - 4-6 Output only visible when requesting extra verbosity (using Write-Verbose)
            - 1-9 Debugging information, written using Write-Debug
            
            In addition, it is possible to select the level "Warning" which moves the message out of the configurable range:
            The user will always be shown this message, unless he silences the entire verbosity.
            
            Possible levels:
            Critical (1), Important / Output / Host (2), Significant (3), VeryVerbose (4), Verbose (5), SomewhatVerbose (6), System (7), Debug (8), InternalComment (9), Warning (666)
            Either one of the strings or its respective number will do as input.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Message">
            <summary>
            The message to write/log. The function name and timestamp will automatically be prepended.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Tag">
            <summary>
            Tags to add to the message written.
            This allows filtering and grouping by category of message, targeting specific messages.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.FunctionName">
            <summary>
            The name of the calling function.
            Will be automatically set, but can be overridden when necessary.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.ModuleName">
            <summary>
            The name of the module, the calling function is part of.
            Will be automatically set, but can be overridden when necessary.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.File">
            <summary>
            The file in which Write-Message was called.
            Will be automatically set, but can be overridden when necessary.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Line">
            <summary>
            The line on which Write-Message was called.
            Will be automatically set, but can be overridden when necessary.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.ErrorRecord">
            <summary>
            If an error record should be noted with the message, add the full record here.
            Especially designed for use with Warning-mode, it can legally be used in either mode.
            The error will be added to the $Error variable and enqued in the logging/debugging system.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Exception">
            <summary>
            Allows specifying an inner exception as input object. This will be passed on to the logging and used for messages.
            When specifying both ErrorRecord AND Exception, Exception wins, but ErrorRecord is still used for record metadata.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Once">
            <summary>
            Setting this parameter will cause this function to write the message only once per session.
            The string passed here and the calling function's name are used to create a unique ID, which is then used to register the action in the configuration system.
            Thus will the lockout only be written if called once and not burden the system unduly.
            This lockout will be written as a hidden value, to see it use Get-DbaConfig -Force.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.OverrideExceptionMessage">
            <summary>
            Disables automatic appending of exception messages.
            Use in cases where you already have a speaking message interpretation and do not need the original message.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Target">
            <summary>
            Add the object the message is all about, in order to simplify debugging / troubleshooting.
            For example, when calling this from a function targeting a remote computer, the computername could be specified here, allowing all messages to easily be correlated to the object processed.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.EnableException">
            <summary>
            This parameters disables user-friendly warnings and enables the throwing of exceptions.
            This is less user friendly, but allows catching exceptions in calling scripts.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.Breakpoint">
            <summary>
            Enables breakpoints on the current message. By default, setting '-Debug' will NOT cause an interrupt on the current position.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._timestamp">
            <summary>
            The start time of the cmdlet
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._silent">
            <summary>
            Whether this cmdlet is run in silent mode
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._fromStopFunction">
            <summary>
            Whether this cmdlet was called by Stop-Function
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._callStack">
            <summary>
            The current callstack
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._stackDepth">
            <summary>
            How many items exist on the callstack
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._message">
            <summary>
            The message to write
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._messageSimple">
            <summary>
            The message simplified without timestamps. Used for logging.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._messageColor">
            <summary>
            The message to write in color
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._messageDeveloper">
            <summary>
            Non-colored version of developermode
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._messageDeveloperColor">
            <summary>
            Colored version of developermode
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._writeHostScript">
            <summary>
            Scriptblock that writes the host messages
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._Tags">
            <summary>
            List of tags to process
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._isDebug">
            <summary>
            Whether debug mode is enabled
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._errorQualifiedMessage">
            <summary>
            The input message with the error content included if desired
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._MessageSystem">
            <summary>
            The final message to use for internal logging
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._MessageStreams">
            <summary>
            The final message to use for writing to streams, such as verbose or warning
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._MessageHost">
            <summary>
            The final message to use for host messages (write using Write-HostColor)
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._BreadCrumbsString">
            <summary>
            Provide breadcrumb queue of the callstack
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand._BreadCrumbsStringColored">
            <summary>
            Provide a breadcrumb queue of the callstack in color tags
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.BeginProcessing">
            <summary>
            Processes the begin phase of the cmdlet
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.ProcessRecord">
            <summary>
            Processes the process phase of the cmdlet
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.ResolveTarget(System.Object)">
            <summary>
            Processes the target transform rules on an input object
            </summary>
            <param name="Item">The item to transform</param>
            <returns>The transformed object</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.ResolveException(System.Exception)">
            <summary>
            Processes the specified exception specified
            </summary>
            <param name="Item">The exception to process</param>
            <returns>The transformed exception</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.ResolveLevel(Sqlcollaborative.Dbatools.Message.MessageLevel)">
            <summary>
            Processs the input level and apply policy and rules
            </summary>
            <param name="Level">The original level of the message</param>
            <returns>The processed level</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.GetMessage">
            <summary>
            Builds the message item for display of Verbose, Warning and Debug streams
            </summary>
            <returns>The message to return</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.GetMessageSimple">
            <summary>
            Builds the base message for internal system use.
            </summary>
            <returns>The message to return</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.GetMessageColor">
            <summary>
            Builds the message item if needed and returns it
            </summary>
            <returns>The message to return</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.GetMessageDeveloper">
            <summary>
            Non-host output in developermode
            </summary>
            <returns>The string to write on messages that don't go straight to Write-HostColor</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Commands.WriteMessageCommand.GetMessageDeveloperColor">
            <summary>
            Host output in developermode
            </summary>
            <returns>The string to write on messages that go straight to Write-HostColor</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Computer.DiskSpace">
            <summary>
            Data Container for the output of Get-DbaDiskSpace
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.ComputerName">
            <summary>
            The computer that was scanned
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.Name">
            <summary>
            Name of the disk
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.Label">
            <summary>
            Label of the disk
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.Capacity">
            <summary>
            What's the total capacity of the disk?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.Free">
            <summary>
            How much is still free?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.PercentFree">
            <summary>
            How much is still free
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.BlockSize">
            <summary>
            What blocksize is the object set to
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.FileSystem">
            <summary>
            What filesystem is installed on the system
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.Type">
            <summary>
            What kind of drive is it?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.IsSqlDisk">
            <summary>
            Whether the drive is a sql disk. Nullable, because it is an optional property and may not always be included, thus a third state is necessary.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.Server">
            <summary>
            The computer that was scanned. Legacy-Name
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.DriveType">
            <summary>
            The type of drive this is in the legacy string notation
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.SizeInBytes">
            <summary>
            The total capacity in Bytes
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.FreeInBytes">
            <summary>
            The free space in Bytes
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.SizeInKB">
            <summary>
            The total capacity in KB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.FreeInKB">
            <summary>
            The free space in KB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.SizeInMB">
            <summary>
            The total capacity in MB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.FreeInMB">
            <summary>
            The free space in MB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.SizeInGB">
            <summary>
            The total capacity in GB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.FreeInGB">
            <summary>
            The free space in GB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.SizeInTB">
            <summary>
            The total capacity in TB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.FreeInTB">
            <summary>
            The free space in TB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.SizeInPB">
            <summary>
            The total capacity in PB
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Computer.DiskSpace.FreeInPB">
            <summary>
            The free space in PB
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Computer.DriveType">
            <summary>
            What kind of drive are you?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.DriveType.Unknown">
            <summary>
            The drive type is not actually known
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.DriveType.NoRootDirectory">
            <summary>
            The drive has no root directory
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.DriveType.RemovableDisk">
            <summary>
            The drive is a removable disk
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.DriveType.LocalDisk">
            <summary>
            The drive is a local disk
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.DriveType.NetworkDrive">
            <summary>
            The drive is a network drive
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.DriveType.CompactDisk">
            <summary>
            The drive is a compact disk
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.DriveType.RAMDisk">
            <summary>
            The drive is a RAM disk
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Computer.PageFileSetting">
            <summary>
            Data container, listing pagefile settings.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.ComputerName">
            <summary>
            The name of the computer
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.AutoPageFile">
            <summary>
            Whether Automatic PageFile management is enabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.FileName">
            <summary>
            The pagefile name
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.Status">
            <summary>
            The pagefile status
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.SystemManaged">
            <summary>
            Whether the pagefile is system managed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.LastModified">
            <summary>
            When were the settings last changed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.LastAccessed">
            <summary>
            When were the settings last accessed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.AllocatedBaseSize">
            <summary>
            The base allocated pagefile size in MB
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.InitialSize">
            <summary>
            The initial pagefile size in MB
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.MaximumSize">
            <summary>
            The maximum pagefile size in MB
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.PeakUsage">
            <summary>
            The maximum percent of the pagefile limit that has been used
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Computer.PageFileSetting.CurrentUsage">
            <summary>
            The currently used percentage of the pagefile limit that is in use.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Configuration.Config">
            <summary>
            Configuration Manager as well as individual configuration object.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.Name">
            <summary>
            The Name of the setting
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.FullName">
            <summary>
            The full name of the configuration entry, comprised of both Module and Name.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.Module">
            <summary>
            The module of the setting. Helps being able to group configurations.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.Description">
            <summary>
            A description of the specific setting
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.Type">
            <summary>
            The data type of the value stored in the configuration element.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.Value">
            <summary>
            The value stored in the configuration element
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.SafeValue">
            <summary>
            The value stored in the configuration element, but without deserializing objects.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.Unchanged">
            <summary>
            Whether the value of the configuration setting has been changed since its initialization.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.Handler">
            <summary>
            The handler script that is run whenever the configuration value is set.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.Validation">
            <summary>
            Validates the user input
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.Hidden">
            <summary>
            Setting this to true will cause the element to not be discovered unless using the '-Force' parameter on "Get-DbaConfig"
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.Initialized">
            <summary>
            Whether the setting has been initialized. This handles module imports and avoids modules overwriting settings when imported in multiple runspaces.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.PolicySet">
            <summary>
            Whether this setting was set by policy
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.PolicyEnforced">
            <summary>
            Whether this setting was set by policy and forbids changes to the configuration.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.SimpleExport">
            <summary>
            Enabling this causes export to json to use simple json serialization for data transmission.
            This is suitable for simple data that is not sensitive to conversion losses.
            Simple export leads to exports more easily readable to the human eye.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.ModuleExport">
            <summary>
            Whether this setting should be exported to a module specific file when exporting to json by modulename.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.Config.RegistryData">
            <summary>
            The finalized value to put into the registry value when using policy to set this setting.
            Deprecated property.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.Config.DefaultValue">
            <summary>
            The default value the configuration item was set to when initializing
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.Config.SetPersistedValue(Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType,System.String)">
            <summary>
            Applies the persisted value to the configuration item.
            This method should only be called by PSFramework internals
            </summary>
            <param name="Type">The type of data being specified</param>
            <param name="ValueString">The value string to register</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.Config.ResetValue">
            <summary>
            Resets the configuration value to its configured default value
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Configuration.ConfigScope">
            <summary>
            The location where a setting was applied
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigScope.UserDefault">
            <summary>
            The configuration is set as default value for the user
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigScope.UserMandatory">
            <summary>
            The configuration is enforced for the user
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigScope.SystemDefault">
            <summary>
            The configuration is set as default value for all users on the system
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigScope.SystemMandatory">
            <summary>
            The configuration is enforced for all users on the system.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigScope.FileUserLocal">
            <summary>
            The configuration is stored as Json in the per user local machine config directory.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigScope.FileUserShared">
            <summary>
            The configuration is stored as Json in the per user config directory shared across machines.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigScope.FileSystem">
            <summary>
            The configuration is stored as Json in the local computer config directory.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost">
            <summary>
            Host class providing static configuration settings that are constant across all runspaces within the process.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.Configurations">
            <summary>
            Hashtable containing all the configuration entries
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.Validation">
            <summary>
            Hashtable containing all the registered validations
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.ImportFromRegistryDone">
            <summary>
            Whether the import from registry has been completed. Prevents multiple imports and overwrites when importing the module multiple times.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.ConvertToPersistedValue(System.Object)">
            <summary>
            Converts any object into its persisted state.
            </summary>
            <param name="Item">The item to convert.</param>
            <returns>Its persisted state representation.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.ConvertFromPersistedValue(System.String,Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType)">
            <summary>
            Converts a persisted value back to its original data type
            </summary>
            <param name="PersistedValue">The value in its persisted state</param>
            <param name="Type">The type of the persisted value</param>
            <returns>The natural state of the value originally persisted</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.ConvertFromPersistedValue(System.String)">
            <summary>
            Converts a persisted value back to its original data type
            </summary>
            <param name="TypeQualifiedPersistedValue">The value in its persisted state, with a prefixed type identifier.</param>
            <returns>The natural state of the value originally persisted</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.Utf8ToBase64(System.String)">
            <summary>
            Converts a plain text into a base64 string
            </summary>
            <param name="Value">The string to convert</param>
            <returns>base64 encoded version of string.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationHost.Base64ToUtf8(System.String)">
            <summary>
            Converts a base64 encoded string into plain text
            </summary>
            <param name="Value">The string to convert</param>
            <returns>Plain Text string</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue">
            <summary>
            Contains all information about a configuration item's value
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.Value">
            <summary>
            The runtime value of the setting.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.PersistedValue">
            <summary>
            The value in its persisted state
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.PersistedType">
            <summary>
            The kind of 
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.TypeQualifiedPersistedValue">
            <summary>
            The type qualified representation of the persisted value
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.SafeValue">
            <summary>
            Ensures wanton Get-PSFConfig will not deserialize persisted objects that might have registered deserialization in their module.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue._Value">
            <summary>
            Internal storage for the Value property
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue._PersistedValue">
            <summary>
            Internal storage for the PersistedValue property
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.ToString">
            <summary>
            The string representation of its actual value
            </summary>
            <returns>Returns the type-qualified string representation of its value</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.#ctor(System.String,Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType)">
            <summary>
            Creates a value object from persisted data
            </summary>
            <param name="PersistedValue">The value that will be persisted</param>
            <param name="PersistedType">The type of the value to be persisted</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Configuration.ConfigurationValue.#ctor(System.Object)">
            <summary>
            Creates a value object from runtime data
            </summary>
            <param name="Value">The value that will be stored</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType">
            <summary>
            The data types supported by the configuration system.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Unknown">
            <summary>
            An unknown type, should be prevented
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Null">
            <summary>
            The value is as empty as the void.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Bool">
            <summary>
            The value is of a true/false kind
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Int">
            <summary>
            The value is a regular integer
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Double">
            <summary>
            The value is a double numeric value
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Long">
            <summary>
            The value is a long type
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.String">
            <summary>
            The value is a common string
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Timespan">
            <summary>
            The value is a regular timespan
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Datetime">
            <summary>
            The value is a plain datetime
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.ConsoleColor">
            <summary>
            The value is a fancy console color
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Array">
            <summary>
            The value is an array full of booty
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Hashtable">
            <summary>
            The value is a hashtable
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Configuration.ConfigurationValueType.Object">
            <summary>
            The value is something indeterminate, but possibly complex
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Connection.ConnectionHost">
            <summary>
            Provides static tools for managing connections
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.Connections">
            <summary>
            List of all registered connections.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.BadConnectionTimeout">
            <summary>
            The time interval that must pass, before a connection using a known to not work connection protocol is reattempted
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableCache">
            <summary>
            Globally disables all caching done by the Computer Management functions.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableBadCredentialCache">
            <summary>
            Disables the caching of bad credentials. dbatools caches bad logon credentials for wmi/cim and will not reuse them.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableCredentialAutoRegister">
            <summary>
            Disables the automatic registration of working credentials. dbatools will caches the last working credential when connecting using wmi/cim and will use those rather than using known bad credentials
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.OverrideExplicitCredential">
            <summary>
            Enabling this will force the use of the last credentials known to work, rather than even trying explicit credentials.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.EnableCredentialFailover">
            <summary>
            Enables automatic failover to working credentials, when passed credentials either are known, or turn out to not work.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableCimPersistence">
            <summary>
            Globally disables the persistence of Cim sessions used to connect to a target system.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableConnectionCimRM">
            <summary>
            Whether the CM connection using Cim over WinRM is disabled globally
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableConnectionCimDCOM">
            <summary>
            Whether the CM connection using Cim over DCOM is disabled globally
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableConnectionWMI">
            <summary>
            Whether the CM connection using WMI is disabled globally
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.DisableConnectionPowerShellRemoting">
            <summary>
            Whether the CM connection using PowerShell Remoting is disabled globally
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.SqlConnectionTimeout">
            <summary>
            The number of seconds before a sql connection attempt times out
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.PSSessions">
            <summary>
            List of all session containers used to maintain a cache
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ConnectionHost.PSSessionGet(System.Guid,System.String)">
            <summary>
            Returns a registered session for a given computer on a given runspace. Returns null if nothing is registered.
            </summary>
            <param name="Runspace">The host runspace that opened the session</param>
            <param name="ComputerName">The computer connected to</param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ConnectionHost.PSSessionSet(System.Guid,System.String,System.Management.Automation.Runspaces.PSSession)">
            <summary>
            Registeres a remote session under the owning runspace in its respective computer name
            </summary>
            <param name="Runspace">The runspace that owns the session</param>
            <param name="ComputerName">The computer the session connects to</param>
            <param name="Session">The session object</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ConnectionHost.PSSessionPurgeExpired">
            <summary>
            Searches the cache for an expired remoting session and purges it. After purging it from the list, it still needs to be closed!
            </summary>
            <returns>The session purged that then needs to be closed</returns>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ConnectionHost.PSSessionCountExpired">
            <summary>
            The number of expired sessions 
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.PSSessionTimeout">
            <summary>
            The time until established connections will be considered expired (if available)
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ConnectionHost.PSSessionCacheEnabled">
            <summary>
            Whether sessions should be cached at all
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Connection.ManagementConnection">
            <summary>
            Contains management connection information for a windows server
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.ComputerName">
            <summary>
            The computer to connect to
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.DisableBadCredentialCache">
            <summary>
            Locally disables the caching of bad credentials
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.DisableCredentialAutoRegister">
            <summary>
            Locally disables the caching of working credentials
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.OverrideExplicitCredential">
            <summary>
            Locally overrides explicit credentials with working ones that were cached
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.EnableCredentialFailover">
            <summary>
            Locally enables automatic failover to working credentials, when passed credentials either are known, or turn out to not work.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.DisableCimPersistence">
            <summary>
            Locally disables the persistence of Cim sessions used to connect to a target system.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.DisabledConnectionTypes">
            <summary>
            Connectiontypes that will never be used
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.RestoreDefaultConfiguration">
            <summary>
            Restores all deviations from public policy back to default
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.OverrideConnectionPolicy">
            <summary>
            Whether this connection adhers to the global connection lockdowns or not
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.CimRM">
            <summary>
            Did the last connection attempt using CimRM work?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.LastCimRM">
            <summary>
            When was the last connection attempt using CimRM?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.CimDCOM">
            <summary>
            Did the last connection attempt using CimDCOM work?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.LastCimDCOM">
            <summary>
            When was the last connection attempt using CimRM?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.Wmi">
            <summary>
            Did the last connection attempt using Wmi work?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.LastWmi">
            <summary>
            When was the last connection attempt using CimRM?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.PowerShellRemoting">
            <summary>
            Did the last connection attempt using PowerShellRemoting work?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.LastPowerShellRemoting">
            <summary>
            When was the last connection attempt using CimRM?
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.ReportSuccess(Sqlcollaborative.Dbatools.Connection.ManagementConnectionType)">
            <summary>
            Report the successful connection against the computer of this connection
            </summary>
            <param name="Type">What connection type succeeded?</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.ReportFailure(Sqlcollaborative.Dbatools.Connection.ManagementConnectionType)">
            <summary>
            Report the failure of connecting to the target computer
            </summary>
            <param name="Type">What connection type failed?</param>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.Credentials">
            <summary>
            Any registered credentials to use on the connection.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.WindowsCredentialsAreBad">
            <summary>
            Whether the default windows credentials are known to not work against the target.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.UseWindowsCredentials">
            <summary>
            Whether windows credentials are known to be good. Do not build conditions on them being false, just on true.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnection.KnownBadCredentials">
            <summary>
            Credentials known to not work. They will not be used when specified.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.AddBadCredential(System.Management.Automation.PSCredential)">
            <summary>
            Adds a credentials object to the list of credentials known to not work.
            </summary>
            <param name="Credential">The bad credential that must be punished</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.AddGoodCredential(System.Management.Automation.PSCredential)">
            <summary>
            Reports a credentials object as being legit.
            </summary>
            <param name="Credential">The functioning credential that we may want to use again</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetCredential(System.Management.Automation.PSCredential)">
            <summary>
            Calculates, which credentials to use. Will consider input, compare it with know not-working credentials or use the configured working credentials for that.
            </summary>
            <param name="Credential">Any credential object a user may have explicitly specified.</param>
            <returns>The Credentials to use</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.IsBadCredential(System.Management.Automation.PSCredential)">
            <summary>
            Tests whether the input credential is on the list known, bad credentials
            </summary>
            <param name="Credential">The credential to test</param>
            <returns>True if the credential is known to not work, False if it is not yet known to not work</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.RemoveBadCredential(System.Management.Automation.PSCredential)">
            <summary>
            Removes an item from the list of known bad credentials
            </summary>
            <param name="Credential">The credential to remove</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetConnectionType(Sqlcollaborative.Dbatools.Connection.ManagementConnectionType,System.Boolean)">
            <summary>
            Returns the next connection type to try.
            </summary>
            <param name="ExcludedTypes">Exclude any type already tried and failed</param>
            <param name="Force">Overrides the timeout on bad connections</param>
            <returns>The next type to try.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetConnectionTypesTimed(System.DateTime)">
            <summary>
            Returns a list of all available connection types whose inherent timeout has expired.
            </summary>
            <param name="Timestamp">All last connection failures older than this point in time are considered to be expired</param>
            <returns>A list of all valid connection types</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetConnectionTypesTimed(System.TimeSpan)">
            <summary>
            Returns a list of all available connection types whose inherent timeout has expired.
            </summary>
            <param name="Timespan">All last connection failures older than this far back into the past are considered to be expired</param>
            <returns>A list of all valid connection types</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.#ctor">
            <summary>
            Creates a new, empty connection object. Necessary for serialization.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.#ctor(System.String)">
            <summary>
            Creates a new default connection object, containing only its computer's name and default results.
            </summary>
            <param name="ComputerName">The computer targeted. Will be forced to lowercase.</param>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.CimWinRMOptions">
            <summary>
            The options ot use when establishing a CIM Session
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetDefaultCimWsmanOptions">
            <summary>
            Returns the default wsman options object
            </summary>
            <returns>Something very default-y</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetCimRMInstance(System.Management.Automation.PSCredential,System.String,System.String)">
            <summary>
            Get all cim instances of the appropriate class using WinRM
            </summary>
            <param name="Credential">The credentiuls to use for the connection.</param>
            <param name="Class">The class to query.</param>
            <param name="Namespace">The namespace to look in (defaults to root\cimv2).</param>
            <returns>Hopefully a mountainload of CimInstances</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.QueryCimRMInstance(System.Management.Automation.PSCredential,System.String,System.String,System.String)">
            <summary>
            Get all cim instances matching the query using WinRM
            </summary>
            <param name="Credential">The credentiuls to use for the connection.</param>
            <param name="Query">The query to use requesting information.</param>
            <param name="Dialect">Defaults to WQL.</param>
            <param name="Namespace">The namespace to look in (defaults to root\cimv2).</param>
            <returns></returns>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.ManagementConnection.CimDComOptions">
            <summary>
            The options ot use when establishing a CIM Session
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetDefaultCimDcomOptions">
            <summary>
            Returns the default DCom options object
            </summary>
            <returns>Something very default-y</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.GetCimDComInstance(System.Management.Automation.PSCredential,System.String,System.String)">
            <summary>
            Get all cim instances of the appropriate class using DCOM
            </summary>
            <param name="Credential">The credentiuls to use for the connection.</param>
            <param name="Class">The class to query</param>
            <param name="Namespace">The namespace to look in (defaults to root\cimv2)</param>
            <returns>Hopefully a mountainload of CimInstances</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.QueryCimDCOMInstance(System.Management.Automation.PSCredential,System.String,System.String,System.String)">
            <summary>
            Get all cim instances matching the query using DCOM
            </summary>
            <param name="Credential">The credentiuls to use for the connection.</param>
            <param name="Query">The query to use requesting information.</param>
            <param name="Dialect">Defaults to WQL.</param>
            <param name="Namespace">The namespace to look in (defaults to root\cimv2).</param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.ManagementConnection.ToString">
            <summary>
            Simple string representation
            </summary>
            <returns>Returns the computerName it is connection for</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Connection.ManagementConnectionProtocolState">
            <summary>
            The various types of state a connection-protocol may have
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionProtocolState.Unknown">
            <summary>
            The default initial state, before any tests are performed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionProtocolState.Success">
            <summary>
            A successful connection was last established
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionProtocolState.Error">
            <summary>
            Connecting using the relevant protocol failed last it was tried
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionProtocolState.Disabled">
            <summary>
            The relevant protocol has been disabled and should not be used
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Connection.ManagementConnectionType">
            <summary>
            The various ways to connect to a windows server fopr management purposes.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionType.None">
            <summary>
            No Connection-Type
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionType.CimRM">
            <summary>
            Cim over a WinRM connection
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionType.CimDCOM">
            <summary>
            Cim over a DCOM connection
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionType.Wmi">
            <summary>
            WMI Connection
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.ManagementConnectionType.PowerShellRemoting">
            <summary>
            Connecting with PowerShell remoting and performing WMI queries locally
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Connection.PSSessionContainer">
            <summary>
            The container that lists all sessions for a given runspace
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.Runspace">
            <summary>
            The runspace that owns the sessions
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.CountExpired">
            <summary>
            The count of expired sessions registered
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.Sessions">
            <summary>
            List of sessions and their associated computer names
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.ConnectionTimestamps">
            <summary>
            List of timestamps, when the last command was run against them
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.#ctor(System.Guid)">
            <summary>
            Creates a list of sessions the current runspace is connected to.
            </summary>
            <param name="Runspace">The Guid of the runspace that is the owner of the registered sessions</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.Get(System.String)">
            <summary>
            Returns the requested session.
            </summary>
            <param name="ComputerName">The name of the host whose connection to retrieve</param>
            <returns>The established connection to the host, null if none exists.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.Set(System.String,System.Management.Automation.Runspaces.PSSession)">
            <summary>
            Sets a session and writes its timestamp to the cache
            </summary>
            <param name="ComputerName">The hostname it connects to.</param>
            <param name="Session">The session that is being registered.</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.GetExpiredNames">
            <summary>
            Returns the name of hostnames with expired sessions
            </summary>
            <returns>THe hostnames whose session has expired</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Connection.PSSessionContainer.PurgeExpiredSession">
            <summary>
            Removes an expired session from the cache, an returns it, so it can be properly closed.
            </summary>
            <returns>Returns a session to disconnect</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Connection.SqlConnectionProtocol">
            <summary>
            The protocol to connect over via SMO
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.SqlConnectionProtocol.Any">
            <summary>
            Connect using any protocol available
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.SqlConnectionProtocol.TCP">
            <summary>
            Connect using TCP/IP
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Connection.SqlConnectionProtocol.NP">
            <summary>
            Connect using named pipes or shared memory
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Database.BackupHistory">
            <summary>
            Object containing the information about the history of mankind ... or a database backup. WHo knows.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.ComputerName">
            <summary>
            The name of the computer running MSSQL Server
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.InstanceName">
            <summary>
            The Instance that was queried
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.SqlInstance">
            <summary>
            The full Instance name as seen from outside
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.Database">
            <summary>
            The Database that was backed up
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.UserName">
            <summary>
            The user that is running the backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.Start">
            <summary>
            When was the backup started
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.End">
            <summary>
            When did the backup end
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.Duration">
            <summary>
            What was the longest duration among the backups
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.Path">
            <summary>
            Where is the backup stored
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.TotalSize">
            <summary>
            What is the total size of the backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.CompressedBackupSize">
            <summary>
            What is the total compressesed size of the backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.CompressionRatio">
            <summary>
            What is the ratio of total size to compressed size of the backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.Type">
            <summary>
            The kind of backup this was
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.BackupSetId">
            <summary>
            The ID for the Backup job
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.DeviceType">
            <summary>
            What kind of backup-device was the backup stored to
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.Software">
            <summary>
            What is the name of the backup software?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.FullName">
            <summary>
            The full name of the backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.FileList">
            <summary>
            The files that are part of this backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.Position">
            <summary>
            The position of the backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.FirstLsn">
            <summary>
            The first Log Sequence Number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.DatabaseBackupLsn">
            <summary>
            The Log Squence Number that marks the beginning of the backup
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.CheckpointLsn">
            <summary>
            The checkpoint's Log Sequence Number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.LastLsn">
            <summary>
            The last Log Sequence Number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.SoftwareVersionMajor">
            <summary>
            The primary version number of the Sql Server
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.IsCopyOnly">
            <summary>
            Was the backup performed with the CopyOnlyOption
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.LastRecoveryForkGUID">
            <summary>
            Recovery Fork backup was takeon
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.BackupHistory.RecoveryModel">
            <summary>
            Recovery Model of the database when backup was taken
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Database.Dependency">
            <summary>
            Class containing all dependency information over a database object
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.ComputerName">
            <summary>
            The name of the SQL server from whence the query came
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.ServiceName">
            <summary>
            Name of the service running the database containing the dependency
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.SqlInstance">
            <summary>
            The Instance the database containing the dependency is running in.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Dependent">
            <summary>
            The name of the dependent
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Type">
            <summary>
            The kind of object the dependent is
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Owner">
            <summary>
            The owner of the dependent (usually the Database)
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.IsSchemaBound">
            <summary>
            Whether the dependency is Schemabound. If it is, then the creation statement order is of utmost importance.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Parent">
            <summary>
            The immediate parent of the dependent. Useful in multi-tier dependencies.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.ParentType">
            <summary>
            The type of object the immediate parent is.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Script">
            <summary>
            The script used to create the object.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Tier">
            <summary>
            The tier in the dependency hierarchy tree. Used to determine, which dependency must be applied in which order.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Object">
            <summary>
            The smo object of the dependent.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.Urn">
            <summary>
            The Uniform Resource Name of the dependent.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Database.Dependency.OriginalResource">
            <summary>
            The object of the original resource, from which the dependency hierachy has been calculated.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord">
            <summary>
            An error record written by dbatools
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.CategoryInfo">
            <summary>
            The category of the error
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.ErrorDetails">
            <summary>
            The details on the error
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.Exception">
            <summary>
            The actual exception thrown
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.FullyQualifiedErrorId">
            <summary>
            The specific error identity, used to identify the target
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.InvocationInfo">
            <summary>
            The details of how this was called.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.ScriptStackTrace">
            <summary>
            The script's stacktrace
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.TargetObject">
            <summary>
            The object being processed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.FunctionName">
            <summary>
            The name of the function throwing the error
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.Timestamp">
            <summary>
            When was the error thrown
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.Message">
            <summary>
            The message that was written in a userfriendly manner
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.Runspace">
            <summary>
            The runspace the error occured on.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.#ctor">
            <summary>
            Create an empty record
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.#ctor(System.Management.Automation.ErrorRecord,System.String,System.DateTime,System.String)">
            <summary>
            Create a filled out error record
            </summary>
            <param name="Record">The original error record</param>
            <param name="FunctionName">The function that wrote the error</param>
            <param name="Timestamp">When was the error generated</param>
            <param name="Message">What message was passed when writing the error</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.dbaSystem.DbaErrorRecord.#ctor(System.Management.Automation.ErrorRecord,System.String,System.DateTime,System.String,System.Guid)">
            <summary>
            Create a filled out error record
            </summary>
            <param name="Record">The original error record</param>
            <param name="FunctionName">The function that wrote the error</param>
            <param name="Timestamp">When was the error generated</param>
            <param name="Message">What message was passed when writing the error</param>
            <param name="Runspace">The ID of the runspace writing the error. Used to separate output between different runspaces in the same process.</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.dbaSystem.DebugHost">
            <summary>
            Hosts static debugging values and methods
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.DebugHost.ImportTimeEntries">
            <summary>
            Lists the duration for the last import of dbatools.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.DebugHost.ImportTime">
            <summary>
            Returns the calculated time each phase took during the last import of dbatool.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.dbaSystem.StartTimeEntry">
            <summary>
            Entry containing the information of a step during the import sequence
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.StartTimeEntry.Action">
            <summary>
            The action that has been taken
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.StartTimeEntry.Timestamp">
            <summary>
            When was the action taken?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.StartTimeEntry.Runspace">
            <summary>
            The runspace the entry was written on
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.dbaSystem.StartTimeEntry.#ctor(System.String,System.DateTime,System.Guid)">
            <summary>
            Creates a new StartTimeEntry
            </summary>
            <param name="Action">The action that has been taken</param>
            <param name="Timestamp">When was the action taken?</param>
            <param name="Runspace">The runspace the entry was written on</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.dbaSystem.StartTimeResult">
            <summary>
            The processed result how long a given step took
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.StartTimeResult.Action">
            <summary>
            What action was taken?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.StartTimeResult.Duration">
            <summary>
            How long did things take?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.StartTimeResult.Start">
            <summary>
            When did this action start?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.StartTimeResult.End">
            <summary>
            When did this action end?
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.dbaSystem.StartTimeResult.#ctor(System.String,System.DateTime,System.DateTime)">
            <summary>
            Creates a new StartTimeResult with all values preconfigured
            </summary>
            <param name="Action">The action that was taken</param>
            <param name="Start">When did the action start?</param>
            <param name="End">When did the action end?</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.dbaSystem.SystemHost">
            <summary>
            Provides system-wide static resources regarding the dbatools system runtime in general
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.SystemHost.UnattendedMode">
            <summary>
            When this is set to true, functions must assume dbatools is in unattended mode. May not ask for user input of any kind.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.dbaSystem.SystemHost.ModuleBase">
            <summary>
            Path where the module was located when imported
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.dbaSystem.SystemHost.ModuleImported">
            <summary>
            Flag whether the module has ever been imported in the current process. If that is true, several things (such as importing libraries) is no longer necessary and will be skipped on import.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply">
            <summary>
            The reply the browser service gave
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.MachineName">
            <summary>
            The machine name of the computer
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.ComputerName">
            <summary>
            the computername of the computer
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.SqlInstance">
            <summary>
            The instance running on the computer
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.InstanceName">
            <summary>
            The name of the instance, running on the computer
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.TCPPort">
            <summary>
            The port number the instance is running under
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.Version">
            <summary>
            The version of the SQL Server
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.IsClustered">
            <summary>
            Whether the instance is part of a cluster or no.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply.ToString">
            <summary>
            Override in order to make it look neater in PowerShell
            </summary>
            <returns></returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Discovery.DbaInstanceAvailability">
            <summary>
            Indiciator for whether an instance is known to be available or not
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceAvailability.Unknown">
            <summary>
            It is not known, whether the instance is available or not
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceAvailability.Available">
            <summary>
            The instance is known to be available
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceAvailability.Unavailable">
            <summary>
            The instance is known to be not available
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Discovery.DbaInstanceConfidenceLevel">
            <summary>
            How high is our confidence that this is a valid instance?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceConfidenceLevel.None">
            <summary>
            No confidence at all. There is virtually no way for this to be an instance
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceConfidenceLevel.Low">
            <summary>
            We have a few indications, but couldn't follow them up
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceConfidenceLevel.Medium">
            <summary>
            We're fairly sure this is legit, but can't guarantee it
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceConfidenceLevel.High">
            <summary>
            This absolutely is an instance
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Discovery.DbaInstanceDiscoveryType">
            <summary>
            What discovery mechanisms to use
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceDiscoveryType.IPRange">
            <summary>
            We shall sweep the network for instances, by targeting every IP within a range.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceDiscoveryType.Domain">
            <summary>
            We shall search for SQL SPNs in active directory
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceDiscoveryType.DataSourceEnumeration">
            <summary>
            We shall use the SSMS Data Sizrce Enumeration mechanism and hope for the best
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceDiscoveryType.All">
            <summary>
            We shall use all tools in our control to find stuff
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport">
            <summary>
            The report on a discovered instance
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.MachineName">
            <summary>
            The computername of the underlying machine. Usually equal to the computername, but may differ in case of clusters
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.ComputerName">
            <summary>
            The computername of the target
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.InstanceName">
            <summary>
            The name of the instance
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.FullName">
            <summary>
            The full server instance name
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.SqlInstance">
            <summary>
            The full name usable to connect via SMO
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.Port">
            <summary>
            The port number the server listens on
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.Timestamp">
            <summary>
            When the scan was concluded
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.TcpConnected">
            <summary>
            Was a TCP connect successful?
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.SqlConnected">
            <summary>
            Was a connection via SQL successful (even if we got access denied)
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.DnsResolution">
            <summary>
            The DNS Resolution object
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.Ping">
            <summary>
            The ping resolution object
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.BrowseReply">
            <summary>
            The reply received from the browse request
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.Services">
            <summary>
            The windows services for the instance
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.SystemServices">
            <summary>
            The SQL Server services that do not belong to that instance alone
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.SPNs">
            <summary>
            Service Principal Names found
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.PortsScanned">
            <summary>
            The ports that have been scanned
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.Availability">
            <summary>
            What we know about its availability
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.Confidence">
            <summary>
            How confident we are, that this is a real instance
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport.ScanTypes">
            <summary>
            What we used to scan the instance
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType">
            <summary>
            The mechanisms we use to determine, whether a given host contains a legit instance
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.TCPPort">
            <summary>
            Try connecting to specific ports
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.SqlConnect">
            <summary>
            Try to connect to discovered instances (improves confidence)
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.SqlService">
            <summary>
            Check the windows services on the target
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.DNSResolve">
            <summary>
            Try resolving a computername in DNS
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.SPN">
            <summary>
            Scan the SPNs for the targeted computer
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.Browser">
            <summary>
            Try contacting the local browser service and demand answers
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.Ping">
            <summary>
            See whether you can ping the host
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.All">
            <summary>
            Do EVERYTHING
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType.Default">
            <summary>
            Do all the things we consider sane defaults
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Discovery.DbaPortReport">
            <summary>
            We tried to connect to a port, how did it go?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaPortReport.ComputerName">
            <summary>
            The name of the computer connected to
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaPortReport.Port">
            <summary>
            The number of the port we tried to connect to.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Discovery.DbaPortReport.IsOpen">
            <summary>
            Whether the port was open
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Discovery.DbaPortReport.#ctor">
            <summary>
            Creates an empty report (serialization uses this)
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Discovery.DbaPortReport.#ctor(System.String,System.Int32,System.Boolean)">
            <summary>
            Creates a filled in report
            </summary>
            <param name="ComputerName">The name of the computer connected to</param>
            <param name="Port">The port we tried to connect to</param>
            <param name="IsOpen">Whether things worked out</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Discovery.DbaPortReport.ToString">
            <summary>
            Displays port connection reports in a user friendly manner
            </summary>
            <returns></returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Exceptions.BloodyHellGiveMeSomethingToWorkWithException">
            <summary>
            An exception that is thrown by parameter classes when given empty input
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Exceptions.BloodyHellGiveMeSomethingToWorkWithException.ParameterClass">
            <summary>
            The parameter class that did the throwing
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Exceptions.BloodyHellGiveMeSomethingToWorkWithException.#ctor(System.String,System.Exception)">
            <summary>
            Creates an exception with a message and a nested exception
            </summary>
            <param name="Message">The message to tell</param>
            <param name="Inner">The inner exception to nest</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Exceptions.BloodyHellGiveMeSomethingToWorkWithException.#ctor(System.String,System.String)">
            <summary>
            Creates an exception with a message and a ParameterClass
            </summary>
            <param name="Message">The message to tell</param>
            <param name="ParameterClass">The Parameter Class that threw the exception</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Exceptions.BloodyHellGiveMeSomethingToWorkWithException.#ctor(System.String,System.Exception,System.String)">
            <summary>
            Creates an exception with a message, a nested exception and a ParameterClass
            </summary>
            <param name="Message">The message to tell</param>
            <param name="Inner">The inner exception to nest</param>
            <param name="ParameterClass">The Parameter Class that threw the exception</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.General.ExecutionMode">
            <summary>
            What kind of mode do you want to run a command in?
            This allows the user to choose how a dbatools function handles a bump in the execution where terminating directly may not be actually mandated.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.General.ExecutionMode.Strict">
            <summary>
            When encountering issues, terminate, or skip the currently processed input, rather than continue.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.General.ExecutionMode.Lazy">
            <summary>
            Continue as able with a best-effort attempt. Simple verbose output should do the rest.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.General.ExecutionMode.Report">
            <summary>
            Continue, but provide output that can be used to identify the operations that had issues.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Maintenance.MaintenanceHost">
            <summary>
            Host class providing access to resources need to perform dbatools maintenance
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceHost.Tasks">
            <summary>
            The register of available tasks.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Maintenance.MaintenanceHost.HasDueTasks">
            <summary>
            Whether there are any due tasks
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Maintenance.MaintenanceHost.GetNextTask(System.String[])">
            <summary>
            Returns the next task to perform. Returns null when there are no more tasks to perform
            </summary>
            <param name="Exclusions">List of tasks not to return, even if they are ready to execute again. This avoids one misconfigured task starving all lower priority tasks</param>
            <returns>The next task to perform.</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Maintenance.MaintenancePriority">
            <summary>
            How high the priority of the task. Higher priority tasks take precedence over low priority tasks.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenancePriority.Trivial">
            <summary>
            This task is completely trivial and can be done whenever there is some spare time for it
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenancePriority.Low">
            <summary>
            The task is not very significant, but should be dealt with at some point
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenancePriority.Medium">
            <summary>
            Average priority task
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenancePriority.High">
            <summary>
            An important task that will take precedence over most other tasks
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenancePriority.Critical">
            <summary>
            A task so critical, that it should be considered to move it to synchronous execution instead.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask">
            <summary>
            An individual task assigned to the maintenance engine
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.Name">
            <summary>
            The name of the task to execute. No duplciates are possible.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.Once">
            <summary>
            Whether the task should be done once only
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.Interval">
            <summary>
            The interval at which the task should be performed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.Delay">
            <summary>
            If the task need not be performed right away, it can be delayed, in order to prioritize more important initialization tasks
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.Registered">
            <summary>
            When was the task first registered. Duplicate registration calls will not increment this value.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.LastExecution">
            <summary>
            When was the task last executed.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.Priority">
            <summary>
            How important is this task?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.ScriptBlock">
            <summary>
            The task code to execute
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask.IsDue">
            <summary>
            Whether the task is due and should be executed
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.DbatoolsException">
            <summary>
            Wrapper class that can emulate any exception for purpose of serialization without blowing up the storage space consumed
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsException.GetException">
            <summary>
            Returns the original exception object that we interpreted. This is on purpose not a property, as we want to avoid messing with serialization size.
            </summary>
            <returns>The original exception that got thrown</returns>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.Message">
            <summary>
            The actual Exception Message
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.Source">
            <summary>
            The original source of the Exception
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.StackTrace">
            <summary>
            Where on the callstack did the exception occur?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.TargetSite">
            <summary>
            What was the target site on the code that caused it. This property has been altered to avoid export issues, if a string representation is not sufficient, access the original exception using GetException()
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.HResult">
            <summary>
            The HResult of the exception. Useful in debugging native code errors.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.HelpLink">
            <summary>
            Link to a proper help article.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.Data">
            <summary>
            Additional data that has been appended
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.InnerException">
            <summary>
            The inner exception in a chain of exceptions.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.ExceptionTypeName">
            <summary>
            The full namespace name of the exception that has been wrapped.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.ExceptionData">
            <summary>
            Contains additional properties other exceptions might contain.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.CategoryInfo">
            <summary>
            The category of the error
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.ErrorDetails">
            <summary>
            The details on the error
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.FullyQualifiedErrorId">
            <summary>
            The specific error identity, used to identify the target
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.InvocationInfo">
            <summary>
            The details of how this was called.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.ScriptStackTrace">
            <summary>
            The script's stacktrace
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.TargetObject">
            <summary>
            The object being processed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.FunctionName">
            <summary>
            The name of the function throwing the error
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.Timestamp">
            <summary>
            When was the error thrown
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.Runspace">
            <summary>
            The runspace the error occured on.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsException.ComputerName">
            <summary>
            The computer the error occured on.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsException.#ctor">
            <summary>
            Creates an empty exception object. Mostly for serialization support
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsException.#ctor(System.Exception)">
            <summary>
            Creates an exception based on an original exception object
            </summary>
            <param name="Except">The exception to wrap around</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsException.#ctor(System.Management.Automation.ErrorRecord)">
            <summary>
            Creates a rich information exception object based on a full error record as recorded by PowerShell
            </summary>
            <param name="Record">The error record to copy from</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsException.#ctor(System.Exception,System.String,System.DateTime,System.String,System.Guid,System.String)">
            <summary>
            Creates a new exception object with rich meta information from the PowerShell runtime.
            </summary>
            <param name="Except">The exception thrown</param>
            <param name="FunctionName">The name of the function in which the error occured</param>
            <param name="Timestamp">When did the error occur</param>
            <param name="Message">The message to add to the exception</param>
            <param name="Runspace">The ID of the runspace from which the exception was thrown. Useful in multi-runspace scenarios.</param>
            <param name="ComputerName">The computer the error occured on.</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsException.#ctor(System.Management.Automation.ErrorRecord,System.String,System.DateTime,System.String,System.Guid,System.String)">
            <summary>
            Creates a new exception object with rich meta information from the PowerShell runtime.
            </summary>
            <param name="Record">The error record written</param>
            <param name="FunctionName">The name of the function in which the error occured</param>
            <param name="Timestamp">When did the error occur</param>
            <param name="Message">The message to add to the exception</param>
            <param name="Runspace">The ID of the runspace from which the exception was thrown. Useful in multi-runspace scenarios.</param>
            <param name="ComputerName">The computer the error occured on.</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsException.ToString">
            <summary>
            Returns a string representation of the exception.
            </summary>
            <returns></returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord">
            <summary>
            Carrier class, designed to hold an arbitrary number of exceptions. Used for exporting to XML in nice per-incident packages.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.Runspace">
            <summary>
            Runspace where shit happened.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.ComputerName">
            <summary>
            The computer name the exception was written on
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.Timestamp">
            <summary>
            When did things go bad?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.FunctionName">
            <summary>
            Name of the function, where fail happened.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.ModuleName">
            <summary>
            The module of the function where fail happened
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.Tags">
            <summary>
            The tags that were applied to the failure
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.Message">
            <summary>
            The message the poor user was shown.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.ExceptionType">
            <summary>
            Displays the name of the exception, the make scanning exceptions easier.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.TargetObject">
            <summary>
            The target object of the first exception in the list, if any
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.Exceptions">
            <summary>
            List of Exceptions that are part of the incident (usually - but not always - only one).
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.#ctor">
            <summary>
            Creates an empty container. Ideal for the homeworker who loves doing it all himself.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.#ctor(Sqlcollaborative.Dbatools.Message.DbatoolsException)">
            <summary>
            Creates a container filled with the first exception.
            </summary>
            <param name="Exception"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.DbatoolsExceptionRecord.#ctor(System.Guid,System.String,System.DateTime,System.String,System.String,System.Collections.Generic.List{System.String},System.String)">
            <summary>
            Creates a container filled with the meta information but untouched by exceptions
            </summary>
            <param name="Runspace">The runspace where it all happened</param>
            <param name="ComputerName">The computer the error was recorded</param>
            <param name="Timestamp">When did it happen?</param>
            <param name="FunctionName">Where did it happen?</param>
            <param name="ModuleName">The name of the module where fail happened</param>
            <param name="Tags">The tags that were assigned to the failure</param>
            <param name="Message">What did the witness have to say?</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.LogEntry">
            <summary>
            An individual entry for the message log
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Message">
            <summary>
            The message logged
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Type">
            <summary>
            What kind of entry was this?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Timestamp">
            <summary>
            When was the message logged?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.FunctionName">
            <summary>
            What function wrote the message
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.ModuleName">
            <summary>
            The name of the module of the function that wrote the message
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Tags">
            <summary>
            The tags applied to the message
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Level">
            <summary>
            What level was the message?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Runspace">
            <summary>
            What runspace was the message written from?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.ComputerName">
            <summary>
            The computer the message was generated on
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.TargetObject">
            <summary>
            The object that was the focus of this message.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.File">
            <summary>
            The file from which the message was written.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Line">
            <summary>
            The line on which the message was written.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.CallStack">
            <summary>
            The callstack when the message was written.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntry.Username">
            <summary>
            The user that did the writing.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.LogEntry.#ctor">
            <summary>
            Creates an empty log entry
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.LogEntry.#ctor(System.String,Sqlcollaborative.Dbatools.Message.LogEntryType,System.DateTime,System.String,System.String,System.Collections.Generic.List{System.String},Sqlcollaborative.Dbatools.Message.MessageLevel,System.Guid,System.String,System.Object,System.String,System.Int32,System.Collections.Generic.IEnumerable{System.Management.Automation.CallStackFrame},System.String)">
            <summary>
            Creates a filled out log entry
            </summary>
            <param name="Message">The message that was logged</param>
            <param name="Type">The type(s) of message written</param>
            <param name="Timestamp">When was the message logged</param>
            <param name="FunctionName">What function wrote the message</param>
            <param name="ModuleName">Name of the module the function writing this message came from</param>
            <param name="Tags">Tags that were applied to the message</param>
            <param name="Level">What level was the message written at.</param>
            <param name="Runspace">The ID of the runspace that wrote the message.</param>
            <param name="ComputerName">The computer the message was generated on.</param>
            <param name="TargetObject">The object this message was all about.</param>
            <param name="File">The file of the code that wrote the message.</param>
            <param name="Line">The line on which the message was written.</param>
            <param name="CallStack">The callstack that triggered the write.</param>
            <param name="Username">The user responsible for running the code that is writing the message.</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.LogEntryType">
            <summary>
            The kind of information the logged entry was.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntryType.None">
            <summary>
            This entry wasn't written to any stream
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntryType.Information">
            <summary>
            A message that was written to the current host equivalent, if available also to the information stream
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntryType.Verbose">
            <summary>
            A message that was written to the verbose stream
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntryType.Debug">
            <summary>
            A message that was written to the Debug stream
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogEntryType.Warning">
            <summary>
            A message written to the warning stream
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.LogHost">
            <summary>
            Provides static information storage for logging related settings, as well as housing the logging queues.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MaxErrorCount">
            <summary>
            The maximum numbers of error records maintained in-memory.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MaxMessageCount">
            <summary>
            The maximum number of messages that can be maintained in the in-memory message queue
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MaxMessagefileBytes">
            <summary>
            The maximum size of a given logfile. When reaching this limit, the file will be abandoned and a new log created. Set to 0 to not limit the size.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MaxMessagefileCount">
            <summary>
            The maximum number of logfiles maintained at a time. Exceeding this number will cause the oldest to be culled. Set to 0 to disable the limit.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MaxErrorFileBytes">
            <summary>
            The maximum size all error files combined may have. When this number is exceeded, the oldest entry is culled.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MaxTotalFolderSize">
            <summary>
            This is the upper limit of length all items in the log folder may have combined across all processes.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.LoggingPath">
            <summary>
            Path to where the logfiles live.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MaxLogFileAge">
            <summary>
            Any logfile older than this will automatically be cleansed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MessageLogFileEnabled">
            <summary>
            Governs, whether a log file for the system messages is written
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.MessageLogEnabled">
            <summary>
            Governs, whether a log of recent messages is kept in memory
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.ErrorLogFileEnabled">
            <summary>
            Governs, whether log files for errors are written
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.ErrorLogEnabled">
            <summary>
            Governs, whether a log of recent errors is kept in memory
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.OutQueueError">
            <summary>
            The outbound queue for errors. These will be processed and written to xml
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.LogHost.OutQueueLog">
            <summary>
            The outbound queue for logs. These will be processed and written to logfile
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.LogHost.GetErrors">
            <summary>
            Retrieves a copy of the Error stack
            </summary>
            <returns>All errors thrown by functions using the message or flowcontrol system</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.LogHost.GetLog">
            <summary>
            Retrieves a copy of the message log
            </summary>
            <returns>All messages logged this session.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.LogHost.WriteErrorEntry(System.Management.Automation.ErrorRecord[],System.String,System.String,System.Collections.Generic.List{System.String},System.DateTime,System.String,System.Guid,System.String)">
            <summary>
            Write an error record to the log
            </summary>
            <param name="Record">The actual error record as powershell wrote it</param>
            <param name="FunctionName">The name of the function writing the error</param>
            <param name="ModuleName">The name of the module the function writing the error came from</param>
            <param name="Tags">The tags that were assigned to the error event</param>
            <param name="Timestamp">When was the error written</param>
            <param name="Message">What message was passed to the user</param>
            <param name="Runspace">The runspace the message was written from</param>
            <param name="ComputerName">The computer the error was written on</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.LogHost.WriteLogEntry(System.String,Sqlcollaborative.Dbatools.Message.LogEntryType,System.DateTime,System.String,System.String,System.Collections.Generic.List{System.String},Sqlcollaborative.Dbatools.Message.MessageLevel,System.Guid,System.String,System.String,System.Int32,System.Collections.Generic.IEnumerable{System.Management.Automation.CallStackFrame},System.String,System.Object)">
            <summary>
            Write a new entry to the log
            </summary>
            <param name="Message">The message to log</param>
            <param name="Type">The type of the message logged</param>
            <param name="Timestamp">When was the message generated</param>
            <param name="FunctionName">What function wrote the message</param>
            <param name="ModuleName">What module did the function writing this message come from?</param>
            <param name="Tags">The tags that were applied to the message</param>
            <param name="Level">At what level was the function written</param>
            <param name="Runspace">The runspace the message is coming from</param>
            <param name="ComputerName">The computer the message was generated on</param>
            <param name="File">The file from which the message was written</param>
            <param name="Line">The line on which the message was written</param>
            <param name="TargetObject">The object associated with a given message.</param>
            <param name="CallStack">The callstack at the moment the message was written.</param>
            <param name="Username">The name of the user under which the code being executed</param>
            <returns>The entry that is being written</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.MessageEventSubscription">
            <summary>
            Condition and logic to be executed on message events
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.Name">
            <summary>
            Name of the event subscription, must be unique.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.ScriptBlock">
            <summary>
            Scriptblock to execute if the condition is met
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription._MessageFilter">
            <summary>
            The internally stored filter value for Message
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.MessageFilter">
            <summary>
            The value the Message is filtered by
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.MessageFilterSet">
            <summary>
            Whether filtering by Message was enabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription._ModuleNameFilter">
            <summary>
            The internally stored filter value for ModuleName
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.ModuleNameFilter">
            <summary>
            The value the ModuleName is filtered by
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.ModuleNameFilterSet">
            <summary>
            Whether filtering by ModuleName was enabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription._FunctionNameFilter">
            <summary>
            The internally stored filter value for FunctionName
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.FunctionNameFilter">
            <summary>
            The value the FunctionName is filtered by
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.FunctionNameFilterSet">
            <summary>
            Whether filtering by FunctionName was enabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription._TargetFilter">
            <summary>
            The internally stored filter value for Target
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.TargetFilter">
            <summary>
            The value the Target is filtered by
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.TargetFilterSet">
            <summary>
            Whether filtering by Target was enabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription._LevelFilter">
            <summary>
            The internally stored filter value for Level
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.LevelFilter">
            <summary>
            The value the Level is filtered by
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.LevelFilterSet">
            <summary>
            Whether filtering by Level was enabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription._TagFilter">
            <summary>
            The internally stored filter value for Tag
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.TagFilter">
            <summary>
            The value the Tag is filtered by
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.TagFilterSet">
            <summary>
            Whether filtering by Tag was enabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageEventSubscription._RunspaceFilter">
            <summary>
            The internally stored filter value for Runspace
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.RunspaceFilter">
            <summary>
            The value the Runspace is filtered by
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.RunspaceFilterSet">
            <summary>
            Whether filtering by Runspace was enabled
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.MessageEventSubscription.Applies(Sqlcollaborative.Dbatools.Message.LogEntry)">
            <summary>
            Checks, whether a given entry matches the filter defined in this subscription
            </summary>
            <param name="Entry">The entry to validate</param>
            <returns>Whether the subscription should react to this entry</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.MessageHost">
            <summary>
            Provides static resources to the messaging subsystem
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.MaximumInformation">
            <summary>
            The maximum message level to still display to the user directly.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.MaximumVerbose">
            <summary>
            The maxium message level where verbose information is still written.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.MaximumDebug">
            <summary>
            The maximum message level where debug information is still written.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.MinimumInformation">
            <summary>
            The minimum required message level for messages that will be shown to the user.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.MinimumVerbose">
            <summary>
            The minimum required message level where verbose information is written.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.MinimumDebug">
            <summary>
            The minimum required message level where debug information is written.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.InfoColor">
            <summary>
            The color stuff gets written to the console in
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.InfoColorEmphasis">
            <summary>
            The color important stuff gets written to the console in
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.InfoColorSubtle">
            <summary>
            The color background stuff gets written to the console in
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.DeveloperColor">
            <summary>
            The color stuff gets written to the console in, when developer mode is enabled and the message would not have been written after all
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.DeveloperMode">
            <summary>
            Enables the developer mode. In this all messages are written to the console, in order to make it easier to troubleshoot issues.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.NestedLevelDecrement">
            <summary>
            Message levels can decrease by nested level. This causes messages to have an increasingly reduced level as the size of the callstack increases. 
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.DisableVerbosity">
            <summary>
            Globally override all verbosity
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.EnableMessageTimestamp">
            <summary>
            Include message timestamps in verbose message output
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.EnableMessageDisplayCommand">
            <summary>
            Include the message display command in the verbose message output
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.EnableMessageBreadcrumbs">
            <summary>
            Include the entire callstack in the verbose message output
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.TransformErrorQueueSize">
            <summary>
            The size of the transform error queue. When adding more than this, the oldest entry will be discarded
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.ExceptionTransforms">
            <summary>
            Provides the option to transform exceptions based on the original exception type
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.TargetTransforms">
            <summary>
            Provides the option to transform target objects based on type. This is sometimes important when working with live state objects that should not be serialized.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.TransformErrors">
            <summary>
            The list of transformation errors that occured.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.MessageHost.GetTransformErrors">
            <summary>
            Returns the current queue of failed transformations
            </summary>
            <returns>The list of transformations that failed</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.MessageHost.WriteTransformError(System.Management.Automation.ErrorRecord,System.String,System.String,System.Object,Sqlcollaborative.Dbatools.Message.TransformType,System.Guid)">
            <summary>
            Writes a new transform error
            </summary>
            <param name="Record">The record of what went wrong</param>
            <param name="FunctionName">The name of the function writing the transformed message</param>
            <param name="ModuleName">The module the function writing the transformed message is part of</param>
            <param name="Object">The object that should have been transformed</param>
            <param name="Type">The type of transform that was attempted</param>
            <param name="Runspace">The runspace it all happened on</param>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.ExceptionTransformList">
            <summary>
            List of custom transforms for exceptions
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.TargetTransformlist">
            <summary>
            List of custom transforms for targets
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.MessageLevelModifiers">
            <summary>
            List of all modifiers that apply to message levels
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageHost.Events">
            <summary>
            List of events that subscribe to messages being written
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.MessageLevel">
            <summary>
            The various levels of verbosity available.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.Critical">
            <summary>
            Very important message, should be shown to the user as a high priority
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.Important">
            <summary>
            Important message, the user should read this
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.Output">
            <summary>
            Important message, the user should read this
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.Significant">
            <summary>
            Message relevant to the user.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.VeryVerbose">
            <summary>
            Not important to the regular user, still of some interest to the curious
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.Verbose">
            <summary>
            Background process information, in case the user wants some detailed information on what is currently happening.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.SomewhatVerbose">
            <summary>
            A footnote in current processing, rarely of interest to the user
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.System">
            <summary>
            A message of some interest from an internal system persepctive, but largely irrelevant to the user.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.Debug">
            <summary>
            Something only of interest to a debugger
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.InternalComment">
            <summary>
            This message barely made the cut from being culled. Of purely development internal interest, and even there is 'interest' a strong word for it.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevel.Warning">
            <summary>
            This message is a warning, sure sign something went badly wrong
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.MessageLevelModifier">
            <summary>
            A modification to a given message's level
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.Name">
            <summary>
            Name of the modifier. Prevents duplication in a multi-runspace scenario.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.Modifier">
            <summary>
            The amount to modify the level by
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.IncludeFunctionName">
            <summary>
            Apply modifier only to messages from this function.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.ExcludeFunctionName">
            <summary>
            Apply modifier not when the message is written by this function.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.IncludeModuleName">
            <summary>
            Apply modifier only to messages from this module
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.ExcludeModuleName">
            <summary>
            Do not apply modifier to messages from this module
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.IncludeTags">
            <summary>
            Only apply this modifier to a message that includes at least one of these tags
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.ExcludeTags">
            <summary>
            Do not apply this modifier to a message that includes any of the following tags
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.MessageLevelModifier.AppliesTo(System.String,System.String,System.Collections.Generic.List{System.String})">
            <summary>
            Tests, whether a message a message should be modified by this modiier
            </summary>
            <param name="FunctionName">The name of the function writing the message</param>
            <param name="ModuleName">The name of the module, the function writing this message comes from</param>
            <param name="Tags">The tags of the message written</param>
            <returns>Whether the message applies</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.TransformCondition">
            <summary>
            A condition, under which the object shall be transaformed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformCondition.TypeName">
            <summary>
            Name of the type. All similar types (as determined by the '-like' operator) will be transformed.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformCondition.ModuleName">
            <summary>
            The name of the module to consider, using the -Like operator
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformCondition.FunctionName">
            <summary>
            The name of the function name to consider, using the -Like operator
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformCondition.ScriptBlock">
            <summary>
            The scriptblock that performs the transformation
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformCondition.Type">
            <summary>
            What kind of transformation is being performed?
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformCondition.#ctor(System.String,System.String,System.String,System.Management.Automation.ScriptBlock,Sqlcollaborative.Dbatools.Message.TransformType)">
            <summary>
            Initializes a transform condition
            </summary>
            <param name="TypeName">Only objects of similar name will be transformed</param>
            <param name="ModuleName">Only objects coming from similar modules will be considered</param>
            <param name="FunctionName">Only objects coming from similar functions will be considered</param>
            <param name="ScriptBlock">The scriptblock used for the transformation</param>
            <param name="Type">What kind of transformation this is</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.TransformError">
            <summary>
            An error occured during a message transformation
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformError.Record">
            <summary>
            The error record of what went wrong
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformError.FunctionName">
            <summary>
            The name of the function writing the message that failed to transform
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformError.ModuleName">
            <summary>
            The name of the module the command writing the message came from
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformError.Timestamp">
            <summary>
            When did it all happen?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformError.Object">
            <summary>
            The object that was supposed to be transformed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformError.Type">
            <summary>
            The kind of transform that failed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformError.Runspace">
            <summary>
            The runspace it all happened on
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformError.#ctor(System.Management.Automation.ErrorRecord,System.String,System.String,System.Object,Sqlcollaborative.Dbatools.Message.TransformType,System.Guid)">
            <summary>
            Creates a new transform error
            </summary>
            <param name="Record">The record of what went wrong</param>
            <param name="FunctionName">The name of the function writing the transformed message</param>
            <param name="ModuleName">The module the function writing the transformed message is part of</param>
            <param name="Object">The object that should have been transformed</param>
            <param name="Type">The type of transform that was attempted</param>
            <param name="Runspace">The runspace it all happened on</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.TransformList">
            <summary>
            List engine, managing the lists for a message transformation type
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformList.GetAll">
            <summary>
            Returns all entries in the list.
            </summary>
            <returns>The list of transforms contained within</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformList.IsListed(Sqlcollaborative.Dbatools.Message.TransformCondition)">
            <summary>
            Returns whether the actual object is part of the list
            </summary>
            <param name="Condition">The object to test for list membership</param>
            <returns>Whether the object is listed</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformList.IsContained(Sqlcollaborative.Dbatools.Message.TransformCondition)">
            <summary>
            Returns whether a condition with equal conditions already exists
            </summary>
            <param name="Condition">The condition to test</param>
            <returns>Whether the referenced condition is already listed</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformList.Add(Sqlcollaborative.Dbatools.Message.TransformCondition)">
            <summary>
            Adds a condition to the list, if there is no equivalent condition present.
            </summary>
            <param name="Condition">The condition to add</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformList.Remove(Sqlcollaborative.Dbatools.Message.TransformCondition)">
            <summary>
            Removes a condition from the lsit of conditional transforms
            </summary>
            <param name="Condition">The condition to remove</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Message.TransformList.Get(System.String,System.String,System.String)">
            <summary>
            Returns the first transform whose filter is similar enough to work out.
            </summary>
            <param name="TypeName">The name of the type to check for a transform</param>
            <param name="ModuleName">The module of the command that wrote the message with the transformable object</param>
            <param name="Functionname">The command that wrote the message with the transformable object</param>
            <returns>Either a transform or null, if no fitting transform was found</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Message.TransformType">
            <summary>
            The messaging system provides these kinds of transformations for input.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformType.Target">
            <summary>
            A target transform can transform the target object specified. Used for live-state objects that should not be serialized on a second thread.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Message.TransformType.Exception">
            <summary>
            An exception transform allows automatic transformation of exceptions. Primarily used to unwrap exceptions from an API that wraps all exceptions.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter">
            <summary>
            Input converter for Computer Management Information
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.Connection">
            <summary>
            The resolved connection object
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.Success">
            <summary>
            Whether input processing was successful
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.InputObject">
            <summary>
            The object actually passed to the class
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.op_Implicit(Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter)~Sqlcollaborative.Dbatools.Connection.ManagementConnection">
            <summary>
            Implicitly convert all connection parameter objects to the connection-type
            </summary>
            <param name="Input">The parameter object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.#ctor(System.String)">
            <summary>
            Creates a new DbaWmConnectionParameter based on an input-name
            </summary>
            <param name="ComputerName">The name of the computer the connection is stored for.</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.#ctor(Sqlcollaborative.Dbatools.Connection.ManagementConnection)">
            <summary>
            Creates a new DbaWmConnectionParameter based on an already existing connection object.
            </summary>
            <param name="Connection">The connection to accept</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.#ctor(System.Object)">
            <summary>
            Tries to convert a generic input object into a true input.
            </summary>
            <param name="Input">Any damn object in the world</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter.#ctor(Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter)">
            <summary>
            Creates a new DbaCmConnectionParameter based on an instance parameter
            </summary>
            <param name="Instance">The instance to interpret</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter">
            <summary>
            Parameter class that handles the various kinds of credential input
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.Credential">
            <summary>
            The credential object received
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.UserName">
            <summary>
            The name of the credential object
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.Password">
            <summary>
            The password of the credential object
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.#ctor(System.Management.Automation.PSCredential)">
            <summary>
            Creates a credential parameter from a PSCredential object
            </summary>
            <param name="Credential">A PSCredential object</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.#ctor(System.Net.NetworkCredential)">
            <summary>
            Creates a credential parameter from a NetworkCredential object
            </summary>
            <param name="Credential">The credentials to use</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.#ctor(System.Object)">
            <summary>
            Creates a credential parameter from anything it nows how to handle
            </summary>
            <param name="Credential">The object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.op_Implicit(Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter)~System.Management.Automation.PSCredential">
            <summary>
            Implicitly converts from DbaCredentialParameter to PSCredential
            </summary>
            <param name="Input">The DbaCredentialParameter to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.op_Implicit(System.Management.Automation.PSCredential)~Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter">
            <summary>
            Implicitly converts a PSCredential object to DbaCredenitalParameter
            </summary>
            <param name="Input">The PSCredential to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.op_Implicit(Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter)~System.Net.NetworkCredential">
            <summary>
            Implicitly converts from DbaCredentialParameter to NetworkCredential
            </summary>
            <param name="Input">The DbaCredentialParameter to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.op_Implicit(System.Net.NetworkCredential)~Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter">
            <summary>
            Implicitly converts a NetworkCredential object to DbaCredenitalParameter
            </summary>
            <param name="Input">The NetworkCredential to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.GetNetworkCredential">
            <summary>
            Legacy wrapper. While there exists implicit conversion, this allows using the object as before, avoiding errors for unknown method.
            </summary>
            <returns>A network credential object with the same credentials as the original object</returns>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.CredentialStore">
            <summary>
            Cached credentials, if the user stors them under a name.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.GetTypeCode">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToBoolean(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToChar(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToSByte(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToByte(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToInt16(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToUInt16(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToInt32(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToUInt32(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToInt64(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToUInt64(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToSingle(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToDouble(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToDecimal(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToDateTime(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToString(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="Format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaCredentialParameter.ToType(System.Type,System.IFormatProvider)">
            <summary>
            Tries to convert the credential parameter to one of its supported types
            </summary>
            <param name="TargetType">The type to convert to</param>
            <param name="Format">Irrelevant</param>
            <returns></returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseParameter">
            <summary>
            Parameter class that accepts anything pointing at a database
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseParameter.InputObject">
            <summary>
            The original object passed to the parameter
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseParameter.Database">
            <summary>
            The SMO Database Object
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseParameter.Name">
            <summary>
            The name of the database
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseParameter.#ctor(System.String)">
            <summary>
            Accepts the name of a database and converts it to a DbaDatabaseParameter
            </summary>
            <param name="Name"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseParameter.#ctor(System.Object)">
            <summary>
            Accepts anything and tries to convert it to a live SMO Database object
            </summary>
            <param name="Item">The item to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseParameter.ToString">
            <summary>
            Overrides the regular tostring to show something pleasant and useful
            </summary>
            <returns>The name of the database</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseSmoParameter">
            <summary>
            Parameter class that only accepts live SMO Databases
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseSmoParameter.InputObject">
            <summary>
            The original object passed to the parameter
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseSmoParameter.Database">
            <summary>
            The SMO Database Object
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseSmoParameter.Name">
            <summary>
            The name of the database
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseSmoParameter.#ctor(System.Object)">
            <summary>
            Accepts anything and tries to convert it to a live SMO Database object
            </summary>
            <param name="Item">The item to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaDatabaseSmoParameter.ToString">
            <summary>
            Overrides the regular tostring to show something pleasant and useful
            </summary>
            <returns>The name of the database</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType">
            <summary>
            What kind of object was bound to the parameter class?
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType.Default">
            <summary>
            Anything, really. An unspecific not reusable type was bound
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType.Linked">
            <summary>
            A live smo linked server object was bound
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType.Server">
            <summary>
            A live smo server object was bound
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType.RegisteredServer">
            <summary>
            A Central Management Server RegisteredServer SMO object was bound
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType.ConnectionString">
            <summary>
            An actual connection string was specified. Connection strings are directly reused for SMO connections
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType.ConnectionStringLocalDB">
            <summary>
            A connection string pointing at a local, file-based DB
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceInputType.SqlConnection">
            <summary>
            An already established sql connection to was created outside of SMO
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter">
            <summary>
            Input converter for instance information
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.ComputerName">
            <summary>
            Name of the computer as resolvable by DNS
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.InstanceName">
            <summary>
            Name of the instance on the target server
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.Port">
            <summary>
            The port over which to connect to the server. Only present if non-default
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.NetworkProtocol">
            <summary>
            The network protocol to connect over
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.IsLocalHost">
            <summary>
            Verifies, whether the specified computer is localhost or not.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.FullName">
            <summary>
            Full name of the instance, including the server-name
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.FullSmoName">
            <summary>
            Full name of the instance, including the server-name, used when connecting via SMO
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.SqlComputerName">
            <summary>
            Name of the computer as used in an SQL Statement
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.SqlInstanceName">
            <summary>
            Name of the instance as used in an SQL Statement
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.SqlFullName">
            <summary>
            Full name of the instance, including the server-name as used in an SQL statement
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.IsConnectionString">
            <summary>
            Whether the input is a connection string
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.InputObject">
            <summary>
            The original object passed to the parameter class.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.Type">
            <summary>
            What kind of object was bound to the parameter class? For efficiency's purposes.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.LinkedLive">
            <summary>
            Returns, whether a live SMO object was bound for the purpose of accessing LinkedServer functionality
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.LinkedServer">
            <summary>
            Returns the available Linked Server objects from live objects only
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.op_Implicit(Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter)~System.String">
            <summary>
            Converts the parameter class to its full name
            </summary>
            <param name="Input">The parameter class object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.#ctor(System.String)">
            <summary>
            Creates a DBA Instance Parameter from string
            </summary>
            <param name="Name">The name of the instance</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.#ctor(System.Net.IPAddress)">
            <summary>
            Creates a DBA Instance Parameter from an IPAddress
            </summary>
            <param name="Address"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.#ctor(System.Net.NetworkInformation.PingReply)">
            <summary>
            Creates a DBA Instance Parameter from the reply to a ping
            </summary>
            <param name="Ping">The result of a ping</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.#ctor(System.Net.IPHostEntry)">
            <summary>
            Creates a DBA Instance Parameter from the result of a dns resolution
            </summary>
            <param name="Entry">The result of a dns resolution, to be used for targetting the default instance</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.#ctor(System.Data.SqlClient.SqlConnection)">
            <summary>
            Creates a DBA Instance Parameter from an established SQL Connection
            </summary>
            <param name="Connection">The connection to reuse</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.#ctor(Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport)">
            <summary>
            Accept and understand discovery reports.
            </summary>
            <param name="Report">The report to interpret</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.#ctor(System.Object)">
            <summary>
            Creates a DBA Instance parameter from any object
            </summary>
            <param name="Input">Object to parse</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.ToString">
            <summary>
            Overrides the regular <c>ToString()</c> to show something pleasant and useful
            </summary>
            <returns>The <see cref="P:Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter.FullSmoName"/></returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.DbaSelectParameter">
            <summary>
            Class that automatically parses input chosen for the -Property parameter of Select-PSUObject
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaSelectParameter.InputObject">
            <summary>
            The original input object
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.DbaSelectParameter.Value">
            <summary>
            The value as Select-Object wants it
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaSelectParameter.#ctor(System.String)">
            <summary>
            Builds a property parameter from string
            </summary>
            <param name="Value">The string to interpret</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.DbaSelectParameter.#ctor(System.Collections.Hashtable)">
            <summary>
            Builds a select parameter from a hashtable (pretty straightforward)
            </summary>
            <param name="Hash">The hashtable to accept</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.ParameterContractAttribute">
            <summary>
            The attribute used to define the elements of a ParameterClass contract
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.ParameterContractAttribute.Type">
            <summary>
            Returns the type of the element this attribute is supposed to be attached to.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Parameter.ParameterContractAttribute.Behavior">
            <summary>
            Returns the behavior to expect from the contracted element. This sets the expectations on how this element is likely to act.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Parameter.ParameterContractAttribute.#ctor(Sqlcollaborative.Dbatools.Parameter.ParameterContractType,Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior)">
            <summary>
            Ceates a perfectly common parameter contract attribute. For use with all parameter classes' public elements.
            </summary>
            <param name="Type"></param>
            <param name="Behavior"></param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior">
            <summary>
            Defines how this element will behave
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior.NotContracted">
            <summary>
            This elements is not actually part of the contract. Generally you wouldn't want to add the attribute at all in that case. However, in some places it helps avoiding confusion.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior.Mandatory">
            <summary>
            This element may never be null and must be considered in all assignments. Even if the element is de facto not nullable, all constructors must assign it.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior.Optional">
            <summary>
            This element may contain data, but is not required to. In case of a method, it may simply do nothing
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior.Failable">
            <summary>
            This method may throw an error when executing and should always be handled with try/catch. Use this on methods that use external calls.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior.Arbiter">
            <summary>
            The content of the thus marked field determines the dependent's state. Generally, only if the arbiter is true, will the dependent elements be mandatory. This behavior may only be assigned to boolean fields.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior.Conditional">
            <summary>
            This behavior can be assigned together with the 'Mandatory' behavior. It means the field is only mandatory if an arbiter field is present and set to true.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractBehavior.Conversion">
            <summary>
            Converts content. Generally applied only to operators, but some methods may also convert information.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Parameter.ParameterContractType">
            <summary>
            Defines what kind of element is granted the contract
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractType.Field">
            <summary>
            The contracted element is a field containing a value
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractType.Method">
            <summary>
            The contracted element is a method, performing an action
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Parameter.ParameterContractType.Operator">
            <summary>
            The contracted element is an operator, facilitating type conversion. Generally into a dedicated object type this parameterclass abstracts.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Runspace.DbaRunspaceState">
            <summary>
            Contains the state a managed, unique runspace can be in.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Runspace.DbaRunspaceState.Running">
            <summary>
            The runspace is up and running
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Runspace.DbaRunspaceState.Stopping">
            <summary>
            The runspace has received the stop order, but has not yet obeyed it
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Runspace.DbaRunspaceState.Stopped">
            <summary>
            The runspace has followed its order to stop and is currently disabled
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer">
            <summary>
            Class that contains the logic necessary to manage a unique runspace
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.Name">
            <summary>
            The name of the runspace.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.RunspaceGuid">
            <summary>
            The Guid of the running Runspace
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.SetScript(System.Management.Automation.ScriptBlock)">
            <summary>
            Sets the script to execute in the runspace. Will NOT take immediate effect. Only after restarting the runspace will it be used.
            </summary>
            <param name="Script">The scriptblock to execute</param>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.State">
            <summary>
            The state the runspace currently is in.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.Start">
            <summary>
            Starts the Runspace.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.SetName(System.Management.Automation.Runspaces.Runspace)">
            <summary>
            Sets the name on a runspace. This WILL FAIL for PowerShell v3!
            </summary>
            <param name="Runspace">The runspace to be named</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.Stop">
            <summary>
            Gracefully stops the Runspace
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.Kill">
            <summary>
            Very ungracefully kills the runspace. Use only in the most dire emergency.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.SignalStopped">
            <summary>
            Signals the registered runspace has stopped execution
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Runspace.RunspaceContainer.#ctor(System.String,System.Management.Automation.ScriptBlock)">
            <summary>
            Creates a new runspace container with the basic information needed
            </summary>
            <param name="Name">The name of the Runspace</param>
            <param name="Script">The code using the runspace logic</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Runspace.RunspaceHost">
            <summary>
            Provides hosting for all registered runspaces
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Runspace.RunspaceHost.StopTimeoutSeconds">
            <summary>
            The number of seconds before a Stop command is interrupted and instead the runspace is gracelessly shut down.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Runspace.RunspaceHost.Runspaces">
            <summary>
            The dictionary containing the definitive list of unique Runspace
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.TabExpansion.InstanceAccess">
            <summary>
            Contains information on access to an instance
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.InstanceAccess.InstanceName">
            <summary>
            The name of the instance to access
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.InstanceAccess.IsSysAdmin">
            <summary>
            Whether the account had sysadmin privileges. On multiple user usage, the cache will prefer sysadmin accounts.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.InstanceAccess.ConnectionObject">
            <summary>
            The actual connection object to connect with to the server
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.InstanceAccess.LastAccess">
            <summary>
            When was the instance last accessed using dbatools
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.InstanceAccess.LastUpdate">
            <summary>
            When was the instance's TEPP cache last updated
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.TabExpansion.ScriptContainer">
            <summary>
            Regular container to store scripts in, that are used in TEPP
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.ScriptContainer.Name">
            <summary>
            The name of the scriptblock
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.ScriptContainer.ScriptBlock">
            <summary>
            The scriptblock doing the logic
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.ScriptContainer.LastExecution">
            <summary>
            The last time the scriptblock was called. Must be updated by the scriptblock itself
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.ScriptContainer.LastDuration">
            <summary>
            The time it took to run the last time
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.TabExpansion.TabCompletionSet">
            <summary>
            Contains information used to transmit Tepp Assignment
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabCompletionSet.Command">
            <summary>
            The name of the command to complete. "*" if all commands that have the parameter should be selected instead
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabCompletionSet.Parameter">
            <summary>
            The parameter to complete
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabCompletionSet.Script">
            <summary>
            The name of the script to complete with
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TabExpansion.TabCompletionSet.#ctor(System.String,System.String,System.String)">
            <summary>
            Creates a new tab completion set object with all information prefilled
            </summary>
            <param name="Command">The name of the command to complete. "*" if all commands that have the parameter should be selected instead</param>
            <param name="Parameter">The parameter to complete</param>
            <param name="Script">The name of the script to complete with</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TabExpansion.TabCompletionSet.Applies(System.String,System.String)">
            <summary>
            Tests, whether the completion set applies to the specified parameter / command combination
            </summary>
            <param name="Command">The command to test</param>
            <param name="Parameter">The parameter of the command to test</param>
            <returns>Whether this completion set applies to the specified combination of parameter / command</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost">
            <summary>
            Class that handles the static fields supporting the dbatools TabExpansion implementation
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.Scripts">
            <summary>
            Field containing the scripts that were registered.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.Cache">
            <summary>
            The cache used by scripts utilizing TabExpansionPlusPlus in dbatools
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.InstanceAccess">
            <summary>
            List of instances and when they were last accessed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppGatherScriptsFast">
            <summary>
            Scripts that build the cache and are suitable for synchronous execution
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppGatherScriptsSlow">
            <summary>
            Scripts that build the cache and are not suitable for synchronous execution
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.DbatoolsCommands">
            <summary>
            A list of all commands imported into dbatools
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TabCompletionSets">
            <summary>
            List of completion sets that should be processed into Tepp Assignments. Only populate this list on first import.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppAssignment">
            <summary>
            Maps a TEPP scriptblock to a command and parameter
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.SetInstance(System.String,System.Object,System.Boolean)">
            <summary>
            Registers a new instance or updates an already existing one. Should only be called from Connect-SqlInstance and Connect-DbaSqlServer
            </summary>
            <param name="InstanceName">Name of the instance connected to</param>
            <param name="Connection">To connection object containing the relevant information for accessing the instance</param>
            <param name="IsSysAdmin">Whether the account connecting to the instnace has SA privileges</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.GetTeppScript(System.String,System.String)">
            <summary>
            Returns the assigned scriptblock for a given parameter
            </summary>
            <param name="Command">The command that should be completed</param>
            <param name="Parameter">The parameter completion is provided for</param>
            <returns>Either the relevant script container or null</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.SetTeppScript(System.String,System.String,System.String)">
            <summary>
            Assigns a registered script to the parameter of a command
            </summary>
            <param name="Command">The command for which to complete</param>
            <param name="Parameter">The parameter for which to complete</param>
            <param name="Script">To name of the script with which to complete</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.AddTabCompletionSet(System.String,System.String,System.String)">
            <summary>
            Adds a completion set to the list of items to process
            </summary>
            <param name="Command">The command to complete for (accepts wildcard matching)</param>
            <param name="Parameter">The parameter to complete for (accepts wildcard matching)</param>
            <param name="Script">The script to register</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.CalculateTabExpansion">
            <summary>
            Processes the content of TabCompletionSets and Scripts into TappAssignments based on the DbatoolsCommands list.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppDisabled">
            <summary>
            Whether TEPP in its entirety is disabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppAsyncDisabled">
            <summary>
            Whether asynchronous TEPP updating should be disabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppSyncDisabled">
            <summary>
            Whether synchronous TEPP updating should be disabled
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppUpdateInterval">
            <summary>
            The interval in which asynchronous TEPP cache updates are performed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost.TeppUpdateTimeout">
            <summary>
            After this timespan of no requests to a server, the updates to its cache are disabled.
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.TypeConversion.DbaCredentialParameterConverter">
            <summary>
            Converts to and from DbaCredentialparameter
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TypeConversion.DbaCredentialParameterConverter.CanConvertTo(System.Object,System.Type)">
            <summary>
            Verifies, whether a conversion for the object to the target type is possible
            </summary>
            <param name="SourceValue">The object to convert</param>
            <param name="DestinationType">The type to convert to</param>
            <returns>Whether it's possible, duh!</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TypeConversion.DbaCredentialParameterConverter.ConvertTo(System.Object,System.Type,System.IFormatProvider,System.Boolean)">
            <summary>
            Converts from DbaCredentialparameter to whatever destination type is attempted
            </summary>
            <param name="sourceValue">The source object. Better be a DbaCredentialparameter!</param>
            <param name="destinationType">Should be a supported destination type</param>
            <param name="formatProvider">Irrelevant</param>
            <param name="ignoreCase">Irrelevant</param>
            <returns>The target content type</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TypeConversion.DbaCredentialParameterConverter.CanConvertFrom(System.Object,System.Type)">
            <summary>
            Verifies, whether a conversion for the object from the source type to DbaCredentialParameter is possible
            </summary>
            <param name="SourceValue">The object to convert</param>
            <param name="DestinationType">The source type to convert to</param>
            <returns>Whether it's possible, duh!</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TypeConversion.DbaCredentialParameterConverter.ConvertFrom(System.Object,System.Type,System.IFormatProvider,System.Boolean)">
            <summary>
            Converts a source object to DbaCredentialparameter
            </summary>
            <param name="sourceValue">The source object</param>
            <param name="destinationType">The destination type. Must be DbaCredentialParameter, or red stuff happens</param>
            <param name="formatProvider">Irrelevant</param>
            <param name="ignoreCase">Irrelevant</param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.TypeConversion.DbaCredentialParameterConverter.IsSupportedType(System.Type)">
            <summary>
            Returns, whether a given type is supported for conversion
            </summary>
            <param name="type">The type to validate</param>
            <returns>Whether it's a supported conversion</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DateTimeExtension">
            <summary>
            Extends DateTime
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DateTimeExtension.CompareTo(System.DateTime,Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)">
            <summary>
            Adds a compareTo method to DateTime to compare with DbaDateTimeBase
            </summary>
            <param name="Base">The extended DateTime object</param>
            <param name="comparedTo">The DbaDateTimeBase to compare with</param>
            <returns></returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaDate">
            <summary>
            A dbatools-internal datetime wrapper for neater display
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.DateTime)">
            <summary>
            Constructs a generic timestamp object wrapper from an input timestamp object.
            </summary>
            <param name="Timestamp">The timestamp to wrap</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.String)">
            <summary>
            Parses a string into a datetime object.
            </summary>
            <param name="Time">The time-string to parse</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int64)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int64,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.ToString">
            <summary>
            Provids the default-formated string, using the defined default formatting.
            </summary>
            <returns>Formatted datetime-string</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaDate)~System.DateTime">
            <summary>
            Implicitly convert to DateTime
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.op_Implicit(System.DateTime)~Sqlcollaborative.Dbatools.Utility.DbaDate">
            <summary>
            Implicitly convert from DateTime
            </summary>
            <param name="Base">The object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaDate)~Sqlcollaborative.Dbatools.Utility.DbaDateTime">
            <summary>
            Implicitly convert to DbaDate
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaDate)~Sqlcollaborative.Dbatools.Utility.DbaTime">
            <summary>
            Implicitly convert to DbaTime
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDate.Generate(System.DateTime)">
            <summary>
            Generates a DbaDate object based off DateTime object. Will be null if Base is the start value (Tickes == 0).
            </summary>
            <param name="Base">The Datetime to base it off</param>
            <returns>The object to generate (or null)</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaDateTime">
            <summary>
            A dbatools-internal datetime wrapper for neater display
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.DateTime)">
            <summary>
            Constructs a generic timestamp object wrapper from an input timestamp object.
            </summary>
            <param name="Timestamp">The timestamp to wrap</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.String)">
            <summary>
            Parses a string into a datetime object.
            </summary>
            <param name="Time">The time-string to parse</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int64)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int64,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.ToString">
            <summary>
            Provids the default-formated string, using the defined default formatting.
            </summary>
            <returns>Formatted datetime-string</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaDateTime)~System.DateTime">
            <summary>
            Implicitly convert to DateTime
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.op_Implicit(System.DateTime)~Sqlcollaborative.Dbatools.Utility.DbaDateTime">
            <summary>
            Implicitly convert from DateTime
            </summary>
            <param name="Base">The object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaDateTime)~Sqlcollaborative.Dbatools.Utility.DbaDate">
            <summary>
            Implicitly convert to DbaDate
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaDateTime)~Sqlcollaborative.Dbatools.Utility.DbaTime">
            <summary>
            Implicitly convert to DbaTime
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTime.Generate(System.DateTime)">
            <summary>
            Generates a DbaDateTime object based off DateTime object. Will be null if Base is the start value (Tickes == 0).
            </summary>
            <param name="Base">The Datetime to base it off</param>
            <returns>The object to generate (or null)</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase">
            <summary>
            Base class for wrapping around a DateTime object
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase._timestamp">
            <summary>
            The core resource, containing the actual timestamp
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Date">
            <summary>
            Gets the date component of this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Day">
            <summary>
            Gets the day of the month represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.DayOfWeek">
            <summary>
            Gets the day of the week represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.DayOfYear">
            <summary>
            Gets the day of the year represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Hour">
            <summary>
            Gets the hour component of the date represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Kind">
            <summary>
            Gets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Millisecond">
            <summary>
            Gets the milliseconds component of the date represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Minute">
            <summary>
            Gets the minute component of the date represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Month">
            <summary>
            Gets the month component of the date represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Second">
            <summary>
            Gets the seconds component of the date represented by this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Ticks">
            <summary>
            Gets the number of ticks that represent the date and time of this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.TimeOfDay">
            <summary>
            Gets the time of day for this instance.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Year">
            <summary>
            Gets the year component of the date represented by this instance.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor">
            <summary>
            Constructor that should never be called, since this class should never be instantiated. It's there for implicit calls on child classes.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.DateTime)">
            <summary>
            Constructs a generic timestamp object wrapper from an input timestamp object.
            </summary>
            <param name="Timestamp">The timestamp to wrap</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.String)">
            <summary>
            Parses a string into a datetime object.
            </summary>
            <param name="Time">The time-string to parse</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int64)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int64,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Add(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddDays(System.Double)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddHours(System.Double)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddMilliseconds(System.Double)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddMinutes(System.Double)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddMonths(System.Int32)">
            <summary>
            
            </summary>
            <param name="months"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddSeconds(System.Double)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddTicks(System.Int64)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.AddYears(System.Int32)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.CompareTo(System.Object)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.CompareTo(System.DateTime)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Equals(System.Object)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Equals(System.DateTime)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.GetDateTimeFormats">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.GetDateTimeFormats(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="provider"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.GetDateTimeFormats(System.Char)">
            <summary>
            
            </summary>
            <param name="format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.GetDateTimeFormats(System.Char,System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="format"></param>
            <param name="provider"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.GetBaseObject">
            <summary>
            Retrieve base DateTime object, this is a wrapper for
            </summary>
            <returns>Base DateTime object</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.GetHashCode">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.GetTypeCode">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.IsDaylightSavingTime">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Subtract(System.DateTime)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.Subtract(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToBinary">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToFileTime">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToFileTimeUtc">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToLocalTime">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToLongDateString">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToLongTimeString">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToOADate">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToShortDateString">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToShortTimeString">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToString(System.String)">
            <summary>
            
            </summary>
            <param name="format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToString(System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="provider"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToString(System.String,System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="format"></param>
            <param name="provider"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ToUniversalTime">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.ParseDateTime(System.String)">
            <summary>
            Parses input string into datetime
            </summary>
            <param name="Value">The string to parse</param>
            <returns>The resultant datetime.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_Addition(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="Timestamp"></param>
            <param name="Duration"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_Subtraction(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="Timestamp"></param>
            <param name="Duration"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_Equality(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)">
            <summary>
            
            </summary>
            <param name="Timestamp1"></param>
            <param name="Timestamp2"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_Inequality(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)">
            <summary>
            
            </summary>
            <param name="Timestamp1"></param>
            <param name="Timestamp2"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_GreaterThan(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)">
            <summary>
            
            </summary>
            <param name="Timestamp1"></param>
            <param name="Timestamp2"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_LessThan(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)">
            <summary>
            
            </summary>
            <param name="Timestamp1"></param>
            <param name="Timestamp2"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_GreaterThanOrEqual(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)">
            <summary>
            
            </summary>
            <param name="Timestamp1"></param>
            <param name="Timestamp2"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_LessThanOrEqual(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase,Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)">
            <summary>
            
            </summary>
            <param name="Timestamp1"></param>
            <param name="Timestamp2"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase)~System.DateTime">
            <summary>
            Implicitly convert DbaDateTimeBase to DateTime
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase.op_Implicit(System.DateTime)~Sqlcollaborative.Dbatools.Utility.DbaDateTimeBase">
            <summary>
            Implicitly convert DateTime to DbaDateTimeBase
            </summary>
            <param name="Base">The object to convert</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaTime">
            <summary>
            A dbatools-internal datetime wrapper for neater display
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.DateTime)">
            <summary>
            Constructs a generic timestamp object wrapper from an input timestamp object.
            </summary>
            <param name="Timestamp">The timestamp to wrap</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.String)">
            <summary>
            Parses a string into a datetime object.
            </summary>
            <param name="Time">The time-string to parse</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int64)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int64,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Globalization.Calendar,System.DateTimeKind)">
            <summary>
            
            </summary>
            <param name="year"></param>
            <param name="month"></param>
            <param name="day"></param>
            <param name="hour"></param>
            <param name="minute"></param>
            <param name="second"></param>
            <param name="millisecond"></param>
            <param name="calendar"></param>
            <param name="kind"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.ToString">
            <summary>
            Provids the default-formated string, using the defined default formatting.
            </summary>
            <returns>Formatted datetime-string</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaTime)~System.DateTime">
            <summary>
            Implicitly convert to DateTime
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.op_Implicit(System.DateTime)~Sqlcollaborative.Dbatools.Utility.DbaTime">
            <summary>
            Implicitly convert from DateTime
            </summary>
            <param name="Base">The object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaTime)~Sqlcollaborative.Dbatools.Utility.DbaDate">
            <summary>
            Implicitly convert to DbaDate
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaTime)~Sqlcollaborative.Dbatools.Utility.DbaDateTime">
            <summary>
            Implicitly convert to DbaTime
            </summary>
            <param name="Base">The source object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaTime)~System.String">
            <summary>
            Implicitly convert to string
            </summary>
            <param name="Base">Object to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTime.Generate(System.DateTime)">
            <summary>
            Generates a DbaDateTime object based off DateTime object. Will be null if Base is the start value (Tickes == 0).
            </summary>
            <param name="Base">The Datetime to base it off</param>
            <returns>The object to generate (or null)</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan">
            <summary>
            A wrapper class, encapsuling a regular TimeSpan object. Used to provide custom timespan display.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Days">
            <summary>
            Gets the days component of the time interval represented by the current TimeSpan structure.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Hours">
            <summary>
            Gets the hours component of the time interval represented by the current TimeSpan structure.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Milliseconds">
            <summary>
            Gets the milliseconds component of the time interval represented by the current TimeSpan structure.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Minutes">
            <summary>
            Gets the minutes component of the time interval represented by the current TimeSpan structure.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Seconds">
            <summary>
            Gets the seconds component of the time interval represented by the current TimeSpan structure.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Ticks">
            <summary>
            Gets the number of ticks that represent the value of the current TimeSpan structure.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.TotalDays">
            <summary>
            Gets the value of the current TimeSpan structure expressed in whole and fractional days.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.TotalHours">
            <summary>
            Gets the value of the current TimeSpan structure expressed in whole and fractional hours.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.TotalMilliseconds">
            <summary>
            Gets the value of the current TimeSpan structure expressed in whole and fractional milliseconds.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.TotalMinutes">
            <summary>
            Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.TotalSeconds">
            <summary>
            Gets the value of the current TimeSpan structure expressed in whole and fractional seconds.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.#ctor(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="Timespan"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.#ctor(System.String)">
            <summary>
            Converts a string into a timespan
            </summary>
            <param name="Timespan">The string to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.#ctor(System.Int64)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.#ctor(System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="hours"></param>
            <param name="minutes"></param>
            <param name="seconds"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.#ctor(System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="days"></param>
            <param name="hours"></param>
            <param name="minutes"></param>
            <param name="seconds"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="days"></param>
            <param name="hours"></param>
            <param name="minutes"></param>
            <param name="seconds"></param>
            <param name="milliseconds"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.ParseTimeSpan(System.String)">
            <summary>
            Parses an input string as timespan
            </summary>
            <param name="Value">The string to interpret</param>
            <returns>The interpreted timespan value</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Add(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="ts"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.CompareTo(System.Object)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.CompareTo(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.CompareTo(Sqlcollaborative.Dbatools.Utility.DbaTimeSpan)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Duration">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Equals(System.Object)">
            <summary>
            
            </summary>
            <param name="value"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Equals(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="obj"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.GetBaseObject">
            <summary>
            Returns the wrapped base object
            </summary>
            <returns>The base object</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.GetHashCode">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Negate">
            <summary>
            
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.Subtract(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="ts"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.ToString">
            <summary>
            Returns the default string representation of the TimeSpan object
            </summary>
            <returns>The string representation of the DbaTimeSpan object</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.ToString(System.String)">
            <summary>
            
            </summary>
            <param name="format"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.ToString(System.String,System.IFormatProvider)">
            <summary>
            
            </summary>
            <param name="format"></param>
            <param name="formatProvider"></param>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.op_Implicit(Sqlcollaborative.Dbatools.Utility.DbaTimeSpan)~System.TimeSpan">
            <summary>
            Implicitly converts a DbaTimeSpan object into a TimeSpan object
            </summary>
            <param name="Base">The original object to revert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpan.op_Implicit(System.TimeSpan)~Sqlcollaborative.Dbatools.Utility.DbaTimeSpan">
            <summary>
            Implicitly converts a TimeSpan object into a DbaTimeSpan object
            </summary>
            <param name="Base">The original object to wrap</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty">
            <summary>
            Makes timespan great again
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.FromMilliseconds(System.Double)">
            <summary>
            Creates a new, pretty timespan object from milliseconds
            </summary>
            <param name="Milliseconds">The milliseconds to convert from.</param>
            <returns>A pretty timespan object</returns>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.Digits">
            <summary>
            The number of digits a pretty timespan should round to.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.#ctor(System.TimeSpan)">
            <summary>
            
            </summary>
            <param name="Timespan"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.#ctor(System.String)">
            <summary>
            Converts a string into a timespan
            </summary>
            <param name="Timespan">The string to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.#ctor(System.Int64)">
            <summary>
            
            </summary>
            <param name="ticks"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.#ctor(System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="hours"></param>
            <param name="minutes"></param>
            <param name="seconds"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.#ctor(System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="days"></param>
            <param name="hours"></param>
            <param name="minutes"></param>
            <param name="seconds"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.#ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            
            </summary>
            <param name="days"></param>
            <param name="hours"></param>
            <param name="minutes"></param>
            <param name="seconds"></param>
            <param name="milliseconds"></param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty.ToString">
            <summary>
            Creates extra-nice timespan formats
            </summary>
            <returns>Humanly readable timespans</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaValidatePatternAttribute">
            <summary>
            Validates that each parameter argument matches the RegexPattern
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaValidatePatternAttribute.RegexPattern">
            <summary>
            Gets the Regex pattern to be used in the validation
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaValidatePatternAttribute.Options">
            <summary>
            Gets or sets the Regex options to be used in the validation
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaValidatePatternAttribute.ErrorMessage">
             <summary>
             Gets or sets the custom error message pattern that is displayed to the user.
            
             The text representation of the object being validated and the validating regex is passed as
             the first and second formatting parameters to the ErrorMessage formatting pattern.
             <example>
             [ValidatePattern("\s+", ErrorMessage="The text '{0}' did not pass validation of regex '{1}'")]
             </example>
             </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaValidatePatternAttribute.ValidateElement(System.Object)">
            <summary>
            Validates that each parameter argument matches the RegexPattern
            </summary>
            <param name="element">object to validate</param>
            <exception cref="T:System.Management.Automation.ValidationMetadataException">if <paramref name="element"/> is not a string
             that matches the pattern
             and for invalid arguments</exception>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaValidatePatternAttribute.#ctor(System.String)">
            <summary>
            Initializes a new instance of the PsfValidatePatternAttribute class
            </summary>
            <param name="regexPattern">Pattern string to match</param>
            <exception cref="T:System.ArgumentException">for invalid arguments</exception>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.DbaValidateScriptAttribute">
            <summary>
            Class for validating against a script block.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaValidateScriptAttribute.ErrorMessage">
             <summary>
             Gets or sets the custom error message that is displayed to the user.
            
             The item being validated and the validating scriptblock is passed as the first and second
             formatting argument.
            
             <example>
             [ValidateScript("$_ % 2", ErrorMessage = "The item '{0}' did not pass validation of script '{1}'")]
             </example>
             </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.DbaValidateScriptAttribute.ScriptBlock">
            <summary>
            Gets the scriptblock to be used in the validation
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaValidateScriptAttribute.ValidateElement(System.Object)">
            <summary>
            Validates that each parameter argument matches the scriptblock
            </summary>
            <param name="element">object to validate</param>
            <exception cref="T:System.Management.Automation.ValidationMetadataException">if <paramref name="element"/> is invalid</exception>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.DbaValidateScriptAttribute.#ctor(System.Management.Automation.ScriptBlock)">
            <summary>
            Initializes a new instance of the ValidateScriptBlockAttribute class
            </summary>
            <param name="scriptBlock">Scriptblock to match</param>
            <exception cref="T:System.ArgumentException">for invalid arguments</exception>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.RegexHelper">
            <summary>
            Static class that holds useful regex patterns, ready for use
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.HostName">
            <summary>
            Pattern that checks for a valid hostname
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.HostNameEx">
            <summary>
            Pattern that checks for valid hostnames within a larger text
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.IPv4">
            <summary>
            Pattern that checks for a valid IPv4 address
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.IPv4Ex">
            <summary>
            Pattern that checks for valid IPv4 addresses within a larger text
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.IPv6">
            <summary>
            Will match a valid IPv6 address
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.IPv6Ex">
            <summary>
            Will match any IPv6 address within a larger text
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.ComputerTarget">
            <summary>
            Will match any string that in its entirety represents a valid target for dns- or ip-based targeting. Combination of HostName, IPv4 and IPv6
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.Guid">
            <summary>
            Will match a valid Guid
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.GuidEx">
            <summary>
            Will match any number of valid Guids in a larger text
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.InstanceName">
            <summary>
            Will match a mostly valid instance name.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.InstanceNameEx">
            <summary>
            Will match any instance of a mostly valid instance name.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.SqlReservedKeyword">
            <summary>
            Matches a word against the list of officially reserved keywords
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.SqlReservedKeywordEx">
            <summary>
            Will match any reserved keyword in a larger text
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.SqlReservedKeywordOdbc">
            <summary>
            Matches a word against the list of officially reserved keywords for odbc
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.SqlReservedKeywordOdbcEx">
            <summary>
            Will match any reserved odbc-keyword in a larger text
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.SqlReservedKeywordFuture">
            <summary>
            Matches a word against the list of keywords that are likely to become reserved in the future
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.RegexHelper.SqlReservedKeywordFutureEx">
            <summary>
            Will match against the list of keywords that are likely to become reserved in the future and are used in a larger text
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.Size">
            <summary>
            Class that reports File size.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.Size.Byte">
            <summary>
            Number of bytes contained in whatever object uses this object as a property
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.Size.Kilobyte">
            <summary>
            Kilobyte representation of the bytes
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.Size.Megabyte">
            <summary>
            Megabyte representation of the bytes
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.Size.Gigabyte">
            <summary>
            Gigabyte representation of the bytes
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.Size.Terabyte">
            <summary>
            Terabyte representation of the bytes
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.Size.Digits">
            <summary>
            Number if digits behind the dot.
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.Size.Style">
            <summary>
            How the size object should be displayed.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.ToString">
            <summary>
            Shows the default string representation of size
            </summary>
            <returns></returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.Equals(System.Object)">
            <summary>
            Simple equality test
            </summary>
            <param name="obj">The object to test it against</param>
            <returns>True if equal, false elsewise</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.GetHashCode">
            <inheritdoc cref="M:System.Int64.GetHashCode"/>
            <remarks>The hashcode of the underlying size</remarks>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.#ctor">
            <summary>
            Creates an empty size.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.#ctor(System.Int64)">
            <summary>
            Creates a size with some content
            </summary>
            <param name="Byte">The length in bytes to set the size to</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.CompareTo(Sqlcollaborative.Dbatools.Utility.Size)">
            <inheritdoc cref="M:System.IComparable`1.CompareTo(`0)"/>
            <remarks>For sorting</remarks>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.CompareTo(System.Object)">
            <inheritdoc cref="M:System.IComparable.CompareTo(System.Object)"/>
            <remarks>For sorting</remarks>
            <exception cref="T:System.ArgumentException">If you compare with something invalid.</exception>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Addition(Sqlcollaborative.Dbatools.Utility.Size,Sqlcollaborative.Dbatools.Utility.Size)">
            <summary>
            Adds two sizes
            </summary>
            <param name="a">The first size to add</param>
            <param name="b">The second size to add</param>
            <returns>The sum of both sizes</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Subtraction(Sqlcollaborative.Dbatools.Utility.Size,Sqlcollaborative.Dbatools.Utility.Size)">
            <summary>
            Substracts two sizes
            </summary>
            <param name="a">The first size to substract</param>
            <param name="b">The second size to substract</param>
            <returns>The difference between both sizes</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Multiply(Sqlcollaborative.Dbatools.Utility.Size,System.Double)">
            <summary>
            Multiplies two sizes with each other
            </summary>
            <param name="a">The size to multiply</param>
            <param name="b">The size to multiply with</param>
            <returns>A multiplied size.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Division(Sqlcollaborative.Dbatools.Utility.Size,System.Double)">
            <summary>
            Divides one size by another. 
            </summary>
            <param name="a">The size to divide</param>
            <param name="b">The size to divide with</param>
            <returns>Divided size (note: Cut off)</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Multiply(Sqlcollaborative.Dbatools.Utility.Size,Sqlcollaborative.Dbatools.Utility.Size)">
            <summary>
            Multiplies two sizes with each other
            </summary>
            <param name="a">The size to multiply</param>
            <param name="b">The size to multiply with</param>
            <returns>A multiplied size.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Division(Sqlcollaborative.Dbatools.Utility.Size,Sqlcollaborative.Dbatools.Utility.Size)">
            <summary>
            Divides one size by another.
            </summary>
            <param name="a">The size to divide</param>
            <param name="b">The size to divide with</param>
            <returns>Divided size (note: Cut off)</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(System.Int32)~Sqlcollaborative.Dbatools.Utility.Size">
            <summary>
            Implicitly converts int to size
            </summary>
            <param name="a">The number to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(System.Decimal)~Sqlcollaborative.Dbatools.Utility.Size">
            <summary>
            Implicitly converts int to size
            </summary>
            <param name="a">The number to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(Sqlcollaborative.Dbatools.Utility.Size)~System.Int32">
            <summary>
            Implicitly converts size to int
            </summary>
            <param name="a">The size to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(System.Int64)~Sqlcollaborative.Dbatools.Utility.Size">
            <summary>
            Implicitly converts long to size
            </summary>
            <param name="a">The number to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(Sqlcollaborative.Dbatools.Utility.Size)~System.Int64">
            <summary>
            Implicitly converts size to long
            </summary>
            <param name="a">The size to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(System.String)~Sqlcollaborative.Dbatools.Utility.Size">
            <summary>
            Implicitly converts string to size
            </summary>
            <param name="a">The string to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(System.Double)~Sqlcollaborative.Dbatools.Utility.Size">
            <summary>
            Implicitly converts double to size
            </summary>
            <param name="a">The number to convert</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Size.op_Implicit(Sqlcollaborative.Dbatools.Utility.Size)~System.Double">
            <summary>
            Implicitly converts size to double
            </summary>
            <param name="a">The size to convert</param>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.SizeStyle">
            <summary>
            How size objects should be displayed
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.SizeStyle.Dynamic">
            <summary>
            The size object is styled dependend on the number stored within.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.SizeStyle.Plain">
            <summary>
            The size object is shown as a plain number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.SizeStyle.Byte">
            <summary>
            The size object is styled as a byte number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.SizeStyle.Kilobyte">
            <summary>
            The size object is styled as a kilobyte number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.SizeStyle.Megabyte">
            <summary>
            The size object is styled as a megabyte number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.SizeStyle.Gigabyte">
            <summary>
            The size object is styled as a Gigabyte number
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.SizeStyle.Terabyte">
            <summary>
            The size object is styled as a Terabyte number
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.UtilityHost">
            <summary>
            Provides static resources to utility-namespaced stuff
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.UtilityHost.DisableCustomDateTime">
            <summary>
            Restores all DateTime objects to their default display behavior
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.UtilityHost.DisableCustomTimeSpan">
            <summary>
            Restores all timespan objects to their default display behavior.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.UtilityHost.FormatDate">
            <summary>
            Formating string for date-style datetime objects.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.UtilityHost.FormatDateTime">
            <summary>
            Formating string for datetime-style datetime objects
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.UtilityHost.FormatTime">
            <summary>
            Formating string for time-style datetime objects
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.UtilityHost.SizeDigits">
            <summary>
            The number of digits a size object shows by default
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Utility.UtilityHost.SizeStyle">
            <summary>
            The way size objects are usually displayed
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.UtilityHost.IsLike(System.String,System.String,System.Boolean)">
            <summary>
            Implement's VB's Like operator logic.
            </summary>
            <param name="CaseSensitive">Whether the comparison is case sensitive</param>
            <param name="Pattern">The pattern the string is compared with</param>
            <param name="String">The string that is being compared with a pattern</param>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.UtilityHost.CompressString(System.String)">
            <summary>
            Compress string using default zip algorithms
            </summary>
            <param name="String">The string to compress</param>
            <returns>Returns a compressed string.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.UtilityHost.ExpandString(System.String)">
            <summary>
            Expand a string using default zig algorithms
            </summary>
            <param name="CompressedString">The compressed string to expand</param>
            <returns>Returns an expanded string.</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.UtilityHost.CharListToSet(System.String)">
            <summary>
            Converts a string of characters to a HashSet of characters. If the string
            contains character ranges, such as A-Z, all characters in the range are
            also added to the returned set of characters.
            </summary>
            <param name="charList">Character list string</param>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.UtilityHost.Callstack">
            <summary>
            Returns the current callstack
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.UtilityHost._CallstackNew">
            <summary>
            Returns the current callstack on PS4+
            </summary>
        </member>
        <member name="P:Sqlcollaborative.Dbatools.Utility.UtilityHost._CallstackOld">
            <summary>
            Returns the current callstack on PS3
            </summary>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Utility.Validation">
            <summary>
            Provides helper methods that aid in validating stuff.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Validation.IsLocalhost(System.String)">
            <summary>
            Tests whether a given string is the local host.
            Does NOT use DNS resolution, DNS aliases will NOT be recognized!
            </summary>
            <param name="Name">The name to test for being local host</param>
            <returns>Whether the name is localhost</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Validation.IsRecommendedInstanceName(System.String)">
            <summary>
            Tests whether a given string is a recommended instance name. Recommended names musst be legal, nbot on the ODBC list and not on the list of words likely to become reserved keywords in the future.
            </summary>
            <param name="InstanceName">The name to test. MAY contain server name, but will NOT test the server.</param>
            <returns>Whether the name is recommended</returns>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Validation.IsValidComputerTarget(System.String)">
            <summary>
            Tests whether a given string is a valid target for targeting as a computer. Will first convert from idn name.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Utility.Validation.IsValidInstanceName(System.String,System.Boolean)">
            <summary>
            Tests whether a given string is a valid instance name.
            </summary>
            <param name="InstanceName">The name to test. MAY contain server name, but will NOT test the server.</param>
            <param name="Lenient">Setting this to true will make the validation ignore default and mssqlserver as illegal names (as they are illegal names for named instances, but legal for targeting)</param>
            <returns>Whether the name is legal</returns>
        </member>
        <member name="T:Sqlcollaborative.Dbatools.Validation.LinkedServerResult">
            <summary>
            The results of testing linked server connectivity as seen from the server that was linked to.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.ComputerName">
            <summary>
            The name of the server running the tests
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.InstanceName">
            <summary>
            The name of the instance running the tests
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.SqlInstance">
            <summary>
            The full name of the instance running the tests
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.LinkedServerName">
            <summary>
            The name of the linked server, the connectivity with whom was tested
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.RemoteServer">
            <summary>
            The name of the remote computer running the linked server.
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.Connectivity">
            <summary>
            The test result
            </summary>
        </member>
        <member name="F:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.Result">
            <summary>
            Text interpretation of the result. Contains error messages if the test failed.
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.#ctor">
            <summary>
            Creates an empty object
            </summary>
        </member>
        <member name="M:Sqlcollaborative.Dbatools.Validation.LinkedServerResult.#ctor(System.String,System.String,System.String,System.String,System.String,System.Boolean,System.String)">
            <summary>
            Creates a test result with prefilled values
            </summary>
            <param name="ComputerName">The name of the server running the tests</param>
            <param name="InstanceName">The name of the instance running the tests</param>
            <param name="SqlInstance">The full name of the instance running the tests</param>
            <param name="LinkedServerName">The name of the linked server, the connectivity with whom was tested</param>
            <param name="RemoteServer">The name of the remote computer running the linked server.</param>
            <param name="Connectivity">The test result</param>
            <param name="Result">Text interpretation of the result. Contains error messages if the test failed.</param>
        </member>
    </members>
</doc>
tools\dbatools\bin\perfmontemplates\collectorsets.xml
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
  <Obj RefId="0">
    <TN RefId="0">
      <T>Deserialized.System.Management.Automation.PSCustomObject</T>
      <T>Deserialized.System.Object</T>
    </TN>
    <MS>
      <S N="Name">Long Running Queries</S>
      <S N="Source">Brad McGehee</S>
    </MS>
  </Obj>
  <Obj RefId="1">
    <TNRef RefId="0" />
    <MS>
      <S N="Name">PAL - SQL Server 2005</S>
      <S N="Source">Clint Huffman</S>
    </MS>
  </Obj>
  <Obj RefId="2">
    <TNRef RefId="0" />
    <MS>
      <S N="Name">PAL - SQL Server 2008 and R2</S>
      <S N="Source">Clint Huffman</S>
    </MS>
  </Obj>
  <Obj RefId="3">
    <TNRef RefId="0" />
    <MS>
      <S N="Name">PAL - SQL Server 2012</S>
      <S N="Source">Clint Huffman</S>
    </MS>
  </Obj>
  <Obj RefId="4">
    <TNRef RefId="0" />
    <MS>
      <S N="Name">PAL - SQL Server 2014 and Up</S>
      <S N="Source">Clint Huffman</S>
    </MS>
  </Obj>
</Objs>
tools\dbatools\bin\perfmontemplates\collectorsets\Long Running Queries.xml
<?xml version="1.0" encoding="UTF-16"?>
<DataCollectorSet>
	<Status>0</Status>
	<Duration>0</Duration>
	<Description>From Brad McGehee's article "Correlating SQL Server Profiler with Performance Monitor" on red-gate.com</Description>
	<DescriptionUnresolved>From Brad McGehee's article "Correlating SQL Server Profiler with Performance Monitor" on red-gate.com
	</DescriptionUnresolved>
	<DisplayName>Long Running Queries</DisplayName>
	<DisplayNameUnresolved>Long Running Queries</DisplayNameUnresolved>
	<SchedulesEnabled>-1</SchedulesEnabled>
	<LatestOutputLocation></LatestOutputLocation>
	<Name>Long Running Queries</Name>
	<OutputLocation></OutputLocation>
	<RootPath></RootPath>
	<Segment>0</Segment>
	<SegmentMaxDuration>0</SegmentMaxDuration>
	<SegmentMaxSize>0</SegmentMaxSize>
	<SerialNumber>3</SerialNumber>
	<Server>
	</Server>
	<Subdirectory>
	</Subdirectory>
	<SubdirectoryFormat>3</SubdirectoryFormat>
	<SubdirectoryFormatPattern>yyyyMMdd\-NNNNNN</SubdirectoryFormatPattern>
	<Task>
	</Task>
	<TaskRunAsSelf>0</TaskRunAsSelf>
	<TaskArguments>
	</TaskArguments>
	<TaskUserTextArguments>
	</TaskUserTextArguments>
	<UserAccount>SYSTEM</UserAccount>
	<Security></Security>
	<StopOnCompletion>0</StopOnCompletion>
	<PerformanceCounterDataCollector>
		<DataCollectorType>0</DataCollectorType>
		<Name>Long Running Queries Collector</Name>
		<FileName>Long Running Queries Collector</FileName>
		<FileNameFormat>1</FileNameFormat>
		<FileNameFormatPattern>
		</FileNameFormatPattern>
		<LogAppend>0</LogAppend>
		<LogCircular>0</LogCircular>
		<LogOverwrite>0</LogOverwrite>
		<LatestOutputLocation></LatestOutputLocation>
		<DataSourceName>
		</DataSourceName>
		<SampleInterval>15</SampleInterval>
		<SegmentMaxRecords>0</SegmentMaxRecords>
		<LogFileFormat>3</LogFileFormat>
		<Counter>\Memory\Available MBytes</Counter>
		<Counter>\Memory\Pages/sec</Counter>
		<Counter>\Processor(_Total)\% Processor Time</Counter>
		<Counter>\System\Processor Queue Length</Counter>
		<Counter>\LogicalDisk(*)\% Disk Read Time</Counter>
		<Counter>\LogicalDisk(*)\Avg. Disk Queue Length</Counter>
		<CounterDisplayName>\Memory\Available MBytes</CounterDisplayName>
		<CounterDisplayName>\Memory\Pages/sec</CounterDisplayName>
		<CounterDisplayName>\Processor(_Total)\% Processor Time</CounterDisplayName>
		<CounterDisplayName>\System\Processor Queue Length</CounterDisplayName>
		<CounterDisplayName>\LogicalDisk(*)\% Disk Read Time</CounterDisplayName>
		<CounterDisplayName>\LogicalDisk(*)\Avg. Disk Queue Length</CounterDisplayName>
	</PerformanceCounterDataCollector>
	<DataManager>
		<Enabled>0</Enabled>
		<CheckBeforeRunning>0</CheckBeforeRunning>
		<MinFreeDisk>0</MinFreeDisk>
		<MaxSize>0</MaxSize>
		<MaxFolderCount>0</MaxFolderCount>
		<ResourcePolicy>0</ResourcePolicy>
		<ReportFileName>report.html</ReportFileName>
		<RuleTargetFileName>report.xml</RuleTargetFileName>
		<EventsFileName>
		</EventsFileName>
	</DataManager>
</DataCollectorSet>
tools\dbatools\bin\perfmontemplates\collectorsets\PAL - SQL Server 2005.xml
<DataCollectorSet>
<Name>PAL - SQL Server 2005</Name>
<DisplayName>PAL - SQL Server 2005</DisplayName>
<DisplayNameUnresolved>PAL - SQL Server 2005</DisplayNameUnresolved>
<Description>Data Collector Sets from PAL, a performance monitor data aggregation tool by Microsoft. The toolset was created by Microsoft PFE Clint Huffman who worked with fellow experts to create a list specialized lists of counters. You can find the project at github.com/clinthuffman/PAL</Description>
<DescriptionUnresolved>Data Collector Sets from PAL, a performance monitor data aggregation tool by Microsoft. The toolset was created by Microsoft PFE Clint Huffman who worked with fellow experts to create a list specialized lists of counters. You can find the project at github.com/clinthuffman/PAL</DescriptionUnresolved>
<SubdirectoryFormat>3</SubdirectoryFormat>
<SubdirectoryFormatPattern>yyyyMMdd\-NNNNNN</SubdirectoryFormatPattern>
<PerformanceCounterDataCollector>
    <Name>PAL - SQL Server 2005 Collector</Name>
    <SampleInterval>15</SampleInterval>
    <Counter>\Cache\Dirty Pages</Counter>
    <Counter>\Cache\Lazy Write Flushes/sec</Counter>
    <Counter>\LogicalDisk(*)\% Free Space</Counter>
    <Counter>\LogicalDisk(*)\% Idle Time</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk Bytes/Read</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk Bytes/Transfer</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk Bytes/Write</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk Queue Length</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk sec/Read</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk sec/Transfer</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk sec/Write</Counter>
    <Counter>\LogicalDisk(*)\Current Disk Queue Length</Counter>
    <Counter>\LogicalDisk(*)\Disk Bytes/sec</Counter>
    <Counter>\LogicalDisk(*)\Disk Reads/sec</Counter>
    <Counter>\LogicalDisk(*)\Disk Transfers/sec</Counter>
    <Counter>\LogicalDisk(*)\Disk Writes/sec</Counter>
    <Counter>\LogicalDisk(*)\Free Megabytes</Counter>
    <Counter>\Memory\% Committed Bytes In Use</Counter>
    <Counter>\Memory\Available MBytes</Counter>
    <Counter>\Memory\Commit Limit</Counter>
    <Counter>\Memory\Committed Bytes</Counter>
    <Counter>\Memory\Free &amp; Zero Page List Bytes</Counter>
    <Counter>\Memory\Free System Page Table Entries</Counter>
    <Counter>\Memory\Long-Term Average Standby Cache Lifetime (s)</Counter>
    <Counter>\Memory\Pages Input/sec</Counter>
    <Counter>\Memory\Pages Output/sec</Counter>
    <Counter>\Memory\Pages/sec</Counter>
    <Counter>\Memory\Pool Nonpaged Bytes</Counter>
    <Counter>\Memory\Pool Paged Bytes</Counter>
    <Counter>\Memory\Pool Paged Resident Bytes</Counter>
    <Counter>\Memory\System Cache Resident Bytes</Counter>
    <Counter>\Memory\Transition Pages RePurposed/sec</Counter>
    <Counter>\Network Inspection System\Average inspection latency (sec/bytes)</Counter>
    <Counter>\Network Interface(*)\Bytes Received/sec</Counter>
    <Counter>\Network Interface(*)\Bytes Sent/sec</Counter>
    <Counter>\Network Interface(*)\Bytes Total/sec</Counter>
    <Counter>\Network Interface(*)\Current Bandwidth</Counter>
    <Counter>\Network Interface(*)\Output Queue Length</Counter>
    <Counter>\Network Interface(*)\Packets Outbound Errors</Counter>
    <Counter>\Network Interface(*)\Packets Received/sec</Counter>
    <Counter>\Network Interface(*)\Packets Sent/sec</Counter>
    <Counter>\Network Interface(*)\Packets/sec</Counter>
    <Counter>\Paging File(*)\% Usage</Counter>
    <Counter>\PhysicalDisk(*)\Avg. Disk Queue Length</Counter>
    <Counter>\PhysicalDisk(*)\Avg. Disk sec/Read</Counter>
    <Counter>\PhysicalDisk(*)\Avg. Disk sec/Write</Counter>
    <Counter>\PhysicalDisk(*)\Current Disk Queue Length</Counter>
    <Counter>\PhysicalDisk(*)\Disk Bytes/sec</Counter>
    <Counter>\Process(*)\% Processor Time</Counter>
    <Counter>\Process(*)\Handle Count</Counter>
    <Counter>\Process(*)\ID Process</Counter>
    <Counter>\Process(*)\IO Data Operations/sec</Counter>
    <Counter>\Process(*)\IO Other Operations/sec</Counter>
    <Counter>\Process(*)\IO Read Operations/sec</Counter>
    <Counter>\Process(*)\IO Write Operations/sec</Counter>
    <Counter>\Process(*)\Private Bytes</Counter>
    <Counter>\Process(*)\Thread Count</Counter>
    <Counter>\Process(*)\Virtual Bytes</Counter>
    <Counter>\Process(*)\Working Set</Counter>
    <Counter>\Process(sqlservr)\% Privileged Time</Counter>
    <Counter>\Processor Information(*)\% DPC Time</Counter>
    <Counter>\Processor Information(*)\% Interrupt Time</Counter>
    <Counter>\Processor Information(*)\% of Maximum Frequency</Counter>
    <Counter>\Processor Information(*)\% Privileged Time</Counter>
    <Counter>\Processor Information(*)\% Processor Time</Counter>
    <Counter>\Processor Information(*)\% User Time</Counter>
    <Counter>\Processor Information(*)\DPC Rate</Counter>
    <Counter>\Processor Information(*)\Parking Status</Counter>
    <Counter>\Processor(*)\% DPC Time</Counter>
    <Counter>\Processor(*)\% Interrupt Time</Counter>
    <Counter>\Processor(*)\% Privileged Time</Counter>
    <Counter>\Processor(*)\% Processor Time</Counter>
    <Counter>\Processor(*)\% User Time</Counter>
    <Counter>\Processor(*)\DPC Rate</Counter>
    <Counter>\Server\Pool Nonpaged Failures</Counter>
    <Counter>\Server\Pool Paged Failures</Counter>
    <Counter>\SQLServer:Access Methods\Forwarded Records/sec</Counter>
    <Counter>\SQLServer:Access Methods\FreeSpace Scans/sec</Counter>
    <Counter>\SQLServer:Access Methods\Full Scans/sec</Counter>
    <Counter>\SQLServer:Access Methods\Index Searches/sec</Counter>
    <Counter>\SQLServer:Access Methods\Page Splits/sec</Counter>
    <Counter>\SQLServer:Access Methods\Scan Point Revalidations/sec</Counter>
    <Counter>\SQLServer:Access Methods\Workfiles Created/sec</Counter>
    <Counter>\SQLServer:Access Methods\Worktables Created/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Buffer cache hit ratio</Counter>
    <Counter>\SQLServer:Buffer Manager\Checkpoint pages/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Free pages</Counter>
    <Counter>\SQLServer:Buffer Manager\Lazy writes/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Page life expectancy</Counter>
    <Counter>\SQLServer:Buffer Manager\Page lookups/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Page reads/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Page writes/sec</Counter>
    <Counter>\SQLServer:General Statistics\Logins/sec</Counter>
    <Counter>\SQLServer:General Statistics\Logouts/sec</Counter>
    <Counter>\SQLServer:General Statistics\User Connections</Counter>
    <Counter>\SQLServer:Latches\Latch Waits/sec</Counter>
    <Counter>\SQLServer:Latches\Total Latch Wait Time (ms)</Counter>
    <Counter>\SQLServer:Locks(*)\Lock Requests/sec</Counter>
    <Counter>\SQLServer:Locks(*)\Lock Timeouts/sec</Counter>
    <Counter>\SQLServer:Locks(*)\Lock Wait Time (ms)</Counter>
    <Counter>\SQLServer:Locks(*)\Lock Waits/sec</Counter>
    <Counter>\SQLServer:Locks(*)\Number of Deadlocks/sec</Counter>
    <Counter>\SQLServer:Memory Manager\Memory Grants Pending</Counter>
    <Counter>\SQLServer:Memory Manager\Target Server Memory(KB)</Counter>
    <Counter>\SQLServer:Memory Manager\Total Server Memory (KB)</Counter>
    <Counter>\SQLServer:SQL Statistics\Batch Requests/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\SQL Compilations/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\SQL Re-Compilations/sec</Counter>
    <Counter>\System\Context Switches/sec</Counter>
    <Counter>\System\Processor Queue Length</Counter>
    <Counter>\System\System Calls/sec</Counter>
    <Counter>\TCPv4\Connection Failures</Counter>
</PerformanceCounterDataCollector>
</DataCollectorSet>
tools\dbatools\bin\perfmontemplates\collectorsets\PAL - SQL Server 2008 and R2.xml
<DataCollectorSet>
<Name>PAL - SQL Server 2008 and R2</Name>
<DisplayName>PAL - SQL Server 2008 and R2</DisplayName>
<DisplayNameUnresolved>PAL - SQL Server 2008 and R2</DisplayNameUnresolved>
<Description>Data Collector Sets from PAL, a performance monitor data aggregation tool by Microsoft. The toolset was created by Microsoft PFE Clint Huffman who worked with fellow experts to create a list specialized lists of counters. You can find the project at github.com/clinthuffman/PAL</Description>
<DescriptionUnresolved>Data Collector Sets from PAL, a performance monitor data aggregation tool by Microsoft. The toolset was created by Microsoft PFE Clint Huffman who worked with fellow experts to create a list specialized lists of counters. You can find the project at github.com/clinthuffman/PAL</DescriptionUnresolved>
<SubdirectoryFormat>3</SubdirectoryFormat>
<SubdirectoryFormatPattern>yyyyMMdd\-NNNNNN</SubdirectoryFormatPattern>
<PerformanceCounterDataCollector>
    <Name>PAL - SQL Server 2008 and R2 Collector</Name>
    <SampleInterval>15</SampleInterval>
    <Counter>\Cache\Dirty Pages</Counter>
    <Counter>\Cache\Lazy Write Flushes/sec</Counter>
    <Counter>\LogicalDisk(*)\% Free Space</Counter>
    <Counter>\LogicalDisk(*)\% Idle Time</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk Bytes/Read</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk Bytes/Transfer</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk Bytes/Write</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk Queue Length</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk sec/Read</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk sec/Transfer</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk sec/Write</Counter>
    <Counter>\LogicalDisk(*)\Current Disk Queue Length</Counter>
    <Counter>\LogicalDisk(*)\Disk Bytes/sec</Counter>
    <Counter>\LogicalDisk(*)\Disk Reads/sec</Counter>
    <Counter>\LogicalDisk(*)\Disk Transfers/sec</Counter>
    <Counter>\LogicalDisk(*)\Disk Writes/sec</Counter>
    <Counter>\LogicalDisk(*)\Free Megabytes</Counter>
    <Counter>\Memory\% Committed Bytes In Use</Counter>
    <Counter>\Memory\Available MBytes</Counter>
    <Counter>\Memory\Commit Limit</Counter>
    <Counter>\Memory\Committed Bytes</Counter>
    <Counter>\Memory\Free &amp; Zero Page List Bytes</Counter>
    <Counter>\Memory\Free System Page Table Entries</Counter>
    <Counter>\Memory\Long-Term Average Standby Cache Lifetime (s)</Counter>
    <Counter>\Memory\Pages Input/sec</Counter>
    <Counter>\Memory\Pages Output/sec</Counter>
    <Counter>\Memory\Pages/sec</Counter>
    <Counter>\Memory\Pool Nonpaged Bytes</Counter>
    <Counter>\Memory\Pool Paged Bytes</Counter>
    <Counter>\Memory\Pool Paged Resident Bytes</Counter>
    <Counter>\Memory\System Cache Resident Bytes</Counter>
    <Counter>\Memory\Transition Pages RePurposed/sec</Counter>
    <Counter>\MSRS 2008 R2 Web Service\Cache Misses/Sec</Counter>
    <Counter>\MSRS 2008 R2 Web Service\Report Requests</Counter>
    <Counter>\MSRS 2008 R2 Web Service\Total Memory Cache Misses</Counter>
    <Counter>\MSRS 2008 R2 Web Service\Total Requests</Counter>
    <Counter>\Network Inspection System\Average inspection latency (sec/bytes)</Counter>
    <Counter>\Network Interface(*)\Bytes Received/sec</Counter>
    <Counter>\Network Interface(*)\Bytes Sent/sec</Counter>
    <Counter>\Network Interface(*)\Bytes Total/sec</Counter>
    <Counter>\Network Interface(*)\Current Bandwidth</Counter>
    <Counter>\Network Interface(*)\Output Queue Length</Counter>
    <Counter>\Network Interface(*)\Packets Outbound Errors</Counter>
    <Counter>\Network Interface(*)\Packets Received/sec</Counter>
    <Counter>\Network Interface(*)\Packets Sent/sec</Counter>
    <Counter>\Network Interface(*)\Packets/sec</Counter>
    <Counter>\Paging File(*)\% Usage</Counter>
    <Counter>\PhysicalDisk(*)\Avg. Disk Queue Length</Counter>
    <Counter>\PhysicalDisk(*)\Avg. Disk sec/Read</Counter>
    <Counter>\PhysicalDisk(*)\Avg. Disk sec/Write</Counter>
    <Counter>\PhysicalDisk(*)\Current Disk Queue Length</Counter>
    <Counter>\PhysicalDisk(*)\Disk Bytes/sec</Counter>
    <Counter>\Process(*)\Handle Count</Counter>
    <Counter>\Process(*)\ID Process</Counter>
    <Counter>\Process(*)\IO Data Operations/sec</Counter>
    <Counter>\Process(*)\IO Other Operations/sec</Counter>
    <Counter>\Process(*)\IO Read Operations/sec</Counter>
    <Counter>\Process(*)\IO Write Operations/sec</Counter>
    <Counter>\Process(*)\Private Bytes</Counter>
    <Counter>\Process(*)\Thread Count</Counter>
    <Counter>\Process(*)\Virtual Bytes</Counter>
    <Counter>\Process(*)\Working Set</Counter>
    <Counter>\Process(sqlservr)\% Privileged Time</Counter>
    <Counter>\Process(sqlservr)\% Processor Time</Counter>
    <Counter>\Processor Information(*)\% DPC Time</Counter>
    <Counter>\Processor Information(*)\% Interrupt Time</Counter>
    <Counter>\Processor Information(*)\% of Maximum Frequency</Counter>
    <Counter>\Processor Information(*)\% Privileged Time</Counter>
    <Counter>\Processor Information(*)\% Processor Time</Counter>
    <Counter>\Processor Information(*)\% User Time</Counter>
    <Counter>\Processor Information(*)\DPC Rate</Counter>
    <Counter>\Processor Information(*)\Parking Status</Counter>
    <Counter>\Processor(*)\% DPC Time</Counter>
    <Counter>\Processor(*)\% Interrupt Time</Counter>
    <Counter>\Processor(*)\% Privileged Time</Counter>
    <Counter>\Processor(*)\% Processor Time</Counter>
    <Counter>\Processor(*)\% User Time</Counter>
    <Counter>\Processor(*)\DPC Rate</Counter>
    <Counter>\ReportServer:Service\Errors Total</Counter>
    <Counter>\ReportServer:Service\Errors/sec</Counter>
    <Counter>\ReportServer:Service\Memory Pressure State</Counter>
    <Counter>\ReportServer:Service\Memory Shrink Amount</Counter>
    <Counter>\ReportServer:Service\Memory Shrink Notifications/sec</Counter>
    <Counter>\Server\Pool Nonpaged Failures</Counter>
    <Counter>\Server\Pool Paged Failures</Counter>
    <Counter>\SQLAgent:Jobs\Active jobs</Counter>
    <Counter>\SQLAgent:Jobs\Failed jobs</Counter>
    <Counter>\SQLAgent:Jobs\Job success rate</Counter>
    <Counter>\SQLAgent:Jobs\Successful jobs</Counter>
    <Counter>\SQLAgent:JobSteps\Active steps</Counter>
    <Counter>\SQLAgent:JobSteps\Total step retries</Counter>
    <Counter>\SQLServer:Access Methods\Forwarded Records/sec</Counter>
    <Counter>\SQLServer:Access Methods\FreeSpace Scans/sec</Counter>
    <Counter>\SQLServer:Access Methods\Full Scans/sec</Counter>
    <Counter>\SQLServer:Access Methods\Index Searches/sec</Counter>
    <Counter>\SQLServer:Access Methods\Page Splits/sec</Counter>
    <Counter>\SQLServer:Access Methods\Scan Point Revalidations/sec</Counter>
    <Counter>\SQLServer:Access Methods\Table Lock Escalations/sec</Counter>
    <Counter>\SQLServer:Access Methods\Workfiles Created/sec</Counter>
    <Counter>\SQLServer:Access Methods\Worktables Created/sec</Counter>
    <Counter>\SQLServer:Access Methods\Worktables From Cache Ratio</Counter>
    <Counter>\SQLServer:Buffer Manager\Buffer cache hit ratio</Counter>
    <Counter>\SQLServer:Buffer Manager\Checkpoint pages/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Free list stalls/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Free pages</Counter>
    <Counter>\SQLServer:Buffer Manager\Lazy writes/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Page life expectancy</Counter>
    <Counter>\SQLServer:Buffer Manager\Page lookups/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Page reads/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Page writes/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Readahead pages/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Stolen pages</Counter>
    <Counter>\SQLServer:Buffer Node(*)\Foreign pages</Counter>
    <Counter>\SQLServer:Buffer Node(*)\Page life expectancy</Counter>
    <Counter>\SQLServer:Databases(*)\Data File(s) Size (KB)</Counter>
    <Counter>\SQLServer:Databases(*)\Log Bytes Flushed/sec</Counter>
    <Counter>\SQLServer:Databases(*)\Log File(s) Size (KB)</Counter>
    <Counter>\SQLServer:Databases(*)\Log File(s) Used Size (KB)</Counter>
    <Counter>\SQLServer:Databases(*)\Log Flush Wait Time</Counter>
    <Counter>\SQLServer:Databases(*)\Log Flush Waits/sec</Counter>
    <Counter>\SQLServer:Databases(*)\Log Flushes/sec</Counter>
    <Counter>\SQLServer:Databases(*)\Log Growths</Counter>
    <Counter>\SQLServer:Databases(*)\Log Shrinks</Counter>
    <Counter>\SQLServer:Databases(*)\Log Truncations</Counter>
    <Counter>\SQLServer:Databases(*)\Percent Log Used</Counter>
    <Counter>\SQLServer:Deprecated Features(*)\Usage</Counter>
    <Counter>\SQLServer:General Statistics\Logins/sec</Counter>
    <Counter>\SQLServer:General Statistics\Logouts/sec</Counter>
    <Counter>\SQLServer:General Statistics\User Connections</Counter>
    <Counter>\SQLServer:Latches\Latch Waits/sec</Counter>
    <Counter>\SQLServer:Latches\Total Latch Wait Time (ms)</Counter>
    <Counter>\SQLServer:Locks(*)\Average Wait Time (ms)</Counter>
    <Counter>\SQLServer:Locks(*)\Lock Requests/sec</Counter>
    <Counter>\SQLServer:Locks(*)\Lock Timeouts/sec</Counter>
    <Counter>\SQLServer:Locks(*)\Lock Wait Time (ms)</Counter>
    <Counter>\SQLServer:Locks(*)\Lock Waits/sec</Counter>
    <Counter>\SQLServer:Locks(*)\Number of Deadlocks/sec</Counter>
    <Counter>\SQLServer:Memory Manager\Granted Workspace Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Manager\Maximum Workspace Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Manager\Memory Grants Outstanding</Counter>
    <Counter>\SQLServer:Memory Manager\Memory Grants Pending</Counter>
    <Counter>\SQLServer:Memory Manager\Target Server Memory(KB)</Counter>
    <Counter>\SQLServer:Memory Manager\Total Server Memory (KB)</Counter>
    <Counter>\SQLServer:Plan Cache(*)\Cache Hit Ratio</Counter>
    <Counter>\SQLServer:Resource Pool Stats(*)\CPU usage %</Counter>
    <Counter>\SQLServer:Resource Pool Stats(*)\Max memory (KB)</Counter>
    <Counter>\SQLServer:Resource Pool Stats(*)\Target memory (KB)</Counter>
    <Counter>\SQLServer:Resource Pool Stats(*)\Used memory (KB)</Counter>
    <Counter>\SQLServer:SQL Errors(*)\Errors/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\Auto-Param Attempts/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\Batch Requests/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\Failed Auto-Params/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\Safe Auto-Params/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\SQL Attention rate</Counter>
    <Counter>\SQLServer:SQL Statistics\SQL Compilations/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\SQL Re-Compilations/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\Unsafe Auto-Params/sec</Counter>
    <Counter>\SQLServer:SSIS Pipeline 10.0\Buffer memory</Counter>
    <Counter>\SQLServer:SSIS Pipeline 10.0\Buffers in use</Counter>
    <Counter>\SQLServer:SSIS Pipeline 10.0\Buffers spooled</Counter>
    <Counter>\SQLServer:SSIS Pipeline 10.0\Flat buffers in use</Counter>
    <Counter>\SQLServer:SSIS Pipeline 10.0\Private buffers in use</Counter>
    <Counter>\SQLServer:Transactions\Free Space in tempdb (KB)</Counter>
    <Counter>\SQLServer:Transactions\Longest Transaction Running Time</Counter>
    <Counter>\SQLServer:Transactions\NonSnapshot Version Transactions</Counter>
    <Counter>\SQLServer:Transactions\Snapshot Transactions</Counter>
    <Counter>\SQLServer:Transactions\Version Cleanup rate (KB/s)</Counter>
    <Counter>\SQLServer:Transactions\Version Generation rate (KB/s)</Counter>
    <Counter>\SQLServer:Workload Group Stats(*)\CPU usage %</Counter>
    <Counter>\SQLServer:Workload Group Stats(*)\Queued requests</Counter>
    <Counter>\SQLServer:Workload Group Stats(*)\Requests completed/sec</Counter>
    <Counter>\System\Context Switches/sec</Counter>
    <Counter>\System\Processor Queue Length</Counter>
    <Counter>\System\System Calls/sec</Counter>
    <Counter>\TCPv4\Connection Failures</Counter>
</PerformanceCounterDataCollector>
</DataCollectorSet>
tools\dbatools\bin\perfmontemplates\collectorsets\PAL - SQL Server 2012.xml
<DataCollectorSet>
<Name>PAL - SQL Server 2012</Name>
<DisplayName>PAL - SQL Server 2012</DisplayName>
<DisplayNameUnresolved>PAL - SQL Server 2012</DisplayNameUnresolved>
<Description>Data Collector Sets from PAL, a performance monitor data aggregation tool by Microsoft. The toolset was created by Microsoft PFE Clint Huffman who worked with fellow experts to create a list specialized lists of counters. You can find the project at github.com/clinthuffman/PAL</Description>
<DescriptionUnresolved>Data Collector Sets from PAL, a performance monitor data aggregation tool by Microsoft. The toolset was created by Microsoft PFE Clint Huffman who worked with fellow experts to create a list specialized lists of counters. You can find the project at github.com/clinthuffman/PAL</DescriptionUnresolved>
<SubdirectoryFormat>3</SubdirectoryFormat>
<SubdirectoryFormatPattern>yyyyMMdd\-NNNNNN</SubdirectoryFormatPattern>
<PerformanceCounterDataCollector>
    <Name>PAL - SQL Server 2012 Collector</Name>
    <SampleInterval>15</SampleInterval>
    <Counter>\Cache\Dirty Pages</Counter>
    <Counter>\Cache\Lazy Write Flushes/sec</Counter>
    <Counter>\LogicalDisk(*)\% Free Space</Counter>
    <Counter>\LogicalDisk(*)\% Idle Time</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk Bytes/Read</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk Bytes/Transfer</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk Bytes/Write</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk Queue Length</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk sec/Read</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk sec/Transfer</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk sec/Write</Counter>
    <Counter>\LogicalDisk(*)\Current Disk Queue Length</Counter>
    <Counter>\LogicalDisk(*)\Disk Bytes/sec</Counter>
    <Counter>\LogicalDisk(*)\Disk Reads/sec</Counter>
    <Counter>\LogicalDisk(*)\Disk Transfers/sec</Counter>
    <Counter>\LogicalDisk(*)\Disk Writes/sec</Counter>
    <Counter>\LogicalDisk(*)\Free Megabytes</Counter>
    <Counter>\Memory\% Committed Bytes In Use</Counter>
    <Counter>\Memory\Available MBytes</Counter>
    <Counter>\Memory\Commit Limit</Counter>
    <Counter>\Memory\Committed Bytes</Counter>
    <Counter>\Memory\Free &amp; Zero Page List Bytes</Counter>
    <Counter>\Memory\Free System Page Table Entries</Counter>
    <Counter>\Memory\Long-Term Average Standby Cache Lifetime (s)</Counter>
    <Counter>\Memory\Pages Input/sec</Counter>
    <Counter>\Memory\Pages Output/sec</Counter>
    <Counter>\Memory\Pages/sec</Counter>
    <Counter>\Memory\Pool Nonpaged Bytes</Counter>
    <Counter>\Memory\Pool Paged Bytes</Counter>
    <Counter>\Memory\Pool Paged Resident Bytes</Counter>
    <Counter>\Memory\System Cache Resident Bytes</Counter>
    <Counter>\Memory\Transition Pages RePurposed/sec</Counter>
    <Counter>\MSRS 2011 Web Service\Cache Misses/Sec</Counter>
    <Counter>\MSRS 2011 Web Service\Report Requests</Counter>
    <Counter>\MSRS 2011 Web Service\Total Memory Cache Misses</Counter>
    <Counter>\MSRS 2011 Web Service\Total Requests</Counter>
    <Counter>\Network Inspection System\Average inspection latency (sec/bytes)</Counter>
    <Counter>\Network Interface(*)\Bytes Received/sec</Counter>
    <Counter>\Network Interface(*)\Bytes Sent/sec</Counter>
    <Counter>\Network Interface(*)\Bytes Total/sec</Counter>
    <Counter>\Network Interface(*)\Current Bandwidth</Counter>
    <Counter>\Network Interface(*)\Output Queue Length</Counter>
    <Counter>\Network Interface(*)\Packets Outbound Errors</Counter>
    <Counter>\Network Interface(*)\Packets Received/sec</Counter>
    <Counter>\Network Interface(*)\Packets Sent/sec</Counter>
    <Counter>\Network Interface(*)\Packets/sec</Counter>
    <Counter>\Paging File(*)\% Usage</Counter>
    <Counter>\PhysicalDisk(*)\Avg. Disk Queue Length</Counter>
    <Counter>\PhysicalDisk(*)\Avg. Disk sec/Read</Counter>
    <Counter>\PhysicalDisk(*)\Avg. Disk sec/Write</Counter>
    <Counter>\PhysicalDisk(*)\Current Disk Queue Length</Counter>
    <Counter>\PhysicalDisk(*)\Disk Bytes/sec</Counter>
    <Counter>\Process(*)\Handle Count</Counter>
    <Counter>\Process(*)\ID Process</Counter>
    <Counter>\Process(*)\IO Data Operations/sec</Counter>
    <Counter>\Process(*)\IO Other Operations/sec</Counter>
    <Counter>\Process(*)\IO Read Operations/sec</Counter>
    <Counter>\Process(*)\IO Write Operations/sec</Counter>
    <Counter>\Process(*)\Private Bytes</Counter>
    <Counter>\Process(*)\Thread Count</Counter>
    <Counter>\Process(*)\Virtual Bytes</Counter>
    <Counter>\Process(*)\Working Set</Counter>
    <Counter>\Process(sqlservr)\% Privileged Time</Counter>
    <Counter>\Process(sqlservr)\% Processor Time</Counter>
    <Counter>\Processor Information(*)\% DPC Time</Counter>
    <Counter>\Processor Information(*)\% Interrupt Time</Counter>
    <Counter>\Processor Information(*)\% of Maximum Frequency</Counter>
    <Counter>\Processor Information(*)\% Privileged Time</Counter>
    <Counter>\Processor Information(*)\% Processor Time</Counter>
    <Counter>\Processor Information(*)\% User Time</Counter>
    <Counter>\Processor Information(*)\DPC Rate</Counter>
    <Counter>\Processor Information(*)\Parking Status</Counter>
    <Counter>\Processor(*)\% DPC Time</Counter>
    <Counter>\Processor(*)\% Interrupt Time</Counter>
    <Counter>\Processor(*)\% Privileged Time</Counter>
    <Counter>\Processor(*)\% Processor Time</Counter>
    <Counter>\Processor(*)\% User Time</Counter>
    <Counter>\Processor(*)\DPC Rate</Counter>
    <Counter>\ReportServer:Service\Errors Total</Counter>
    <Counter>\ReportServer:Service\Errors/sec</Counter>
    <Counter>\ReportServer:Service\Memory Pressure State</Counter>
    <Counter>\ReportServer:Service\Memory Shrink Amount</Counter>
    <Counter>\ReportServer:Service\Memory Shrink Notifications/sec</Counter>
    <Counter>\Server\Pool Nonpaged Failures</Counter>
    <Counter>\Server\Pool Paged Failures</Counter>
    <Counter>\SQLAgent:Jobs\Active jobs</Counter>
    <Counter>\SQLAgent:Jobs\Failed jobs</Counter>
    <Counter>\SQLAgent:Jobs\Job success rate</Counter>
    <Counter>\SQLAgent:Jobs\Successful jobs</Counter>
    <Counter>\SQLAgent:JobSteps\Active steps</Counter>
    <Counter>\SQLAgent:JobSteps\Total step retries</Counter>
    <Counter>\SQLServer:Access Methods\Forwarded Records/sec</Counter>
    <Counter>\SQLServer:Access Methods\FreeSpace Scans/sec</Counter>
    <Counter>\SQLServer:Access Methods\Full Scans/sec</Counter>
    <Counter>\SQLServer:Access Methods\Index Searches/sec</Counter>
    <Counter>\SQLServer:Access Methods\Page Splits/sec</Counter>
    <Counter>\SQLServer:Access Methods\Scan Point Revalidations/sec</Counter>
    <Counter>\SQLServer:Access Methods\Table Lock Escalations/sec</Counter>
    <Counter>\SQLServer:Access Methods\Workfiles Created/sec</Counter>
    <Counter>\SQLServer:Access Methods\Worktables Created/sec</Counter>
    <Counter>\SQLServer:Access Methods\Worktables From Cache Ratio</Counter>
    <Counter>\SQLServer:Availability Replica(*)\Bytes Received from Replica/sec</Counter>
    <Counter>\SQLServer:Availability Replica(*)\Bytes Sent to Replica/sec</Counter>
    <Counter>\SQLServer:Availability Replica(*)\Bytes Sent to Transport/sec</Counter>
    <Counter>\SQLServer:Availability Replica(_Total)\Receives from Replica/sec</Counter>
    <Counter>\SQLServer:Availability Replica(_Total)\Resent Messages/sec</Counter>
    <Counter>\SQLServer:Availability Replica(_Total)\Sends to Replica/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Background writer pages/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Buffer cache hit ratio</Counter>
    <Counter>\SQLServer:Buffer Manager\Checkpoint pages/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Free list stalls/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Free pages</Counter>
    <Counter>\SQLServer:Buffer Manager\Lazy writes/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Page life expectancy</Counter>
    <Counter>\SQLServer:Buffer Manager\Page lookups/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Page reads/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Page writes/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Readahead pages/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Target pages</Counter>
    <Counter>\SQLServer:Buffer Node(*)\Database pages</Counter>
    <Counter>\SQLServer:Buffer Node(*)\Foreign pages</Counter>
    <Counter>\SQLServer:Buffer Node(*)\Local node page lookups/sec</Counter>
    <Counter>\SQLServer:Buffer Node(*)\Page life expectancy</Counter>
    <Counter>\SQLServer:Buffer Node(*)\Remote node page lookups/sec</Counter>
    <Counter>\SQLServer:Database Replica(*)\Log Bytes Received/sec</Counter>
    <Counter>\SQLServer:Database Replica(*)\Mirrored Write Transactions/sec</Counter>
    <Counter>\SQLServer:Database Replica(*)\Recovery Queue</Counter>
    <Counter>\SQLServer:Database Replica(_Total)\Log remaining for undo</Counter>
    <Counter>\SQLServer:Database Replica(_Total)\Log Send Queue</Counter>
    <Counter>\SQLServer:Database Replica(_Total)\Redo blocked/sec</Counter>
    <Counter>\SQLServer:Database Replica(_Total)\Redo Bytes Remaining</Counter>
    <Counter>\SQLServer:Database Replica(_Total)\Redone Bytes/sec</Counter>
    <Counter>\SQLServer:Database Replica(_Total)\Total Log requiring undo</Counter>
    <Counter>\SQLServer:Database Replica(_Total)\Transaction Delay</Counter>
    <Counter>\SQLServer:Databases(*)\Active Transactions</Counter>
    <Counter>\SQLServer:Databases(*)\Backup/Restore Throughput/sec</Counter>
    <Counter>\SQLServer:Databases(*)\Bulk Copy Throughput/sec</Counter>
    <Counter>\SQLServer:Databases(*)\Data File(s) Size (KB)</Counter>
    <Counter>\SQLServer:Databases(*)\Log Bytes Flushed/sec</Counter>
    <Counter>\SQLServer:Databases(*)\Log File(s) Size (KB)</Counter>
    <Counter>\SQLServer:Databases(*)\Log File(s) Used Size (KB)</Counter>
    <Counter>\SQLServer:Databases(*)\Log Flush Wait Time</Counter>
    <Counter>\SQLServer:Databases(*)\Log Flush Waits/sec</Counter>
    <Counter>\SQLServer:Databases(*)\Log Flushes/sec</Counter>
    <Counter>\SQLServer:Databases(*)\Log Growths</Counter>
    <Counter>\SQLServer:Databases(*)\Log Shrinks</Counter>
    <Counter>\SQLServer:Databases(*)\Log Truncations</Counter>
    <Counter>\SQLServer:Databases(*)\Percent Log Used</Counter>
    <Counter>\SQLServer:Deprecated Features(*)\Usage</Counter>
    <Counter>\SQLServer:General Statistics\Active Temp Tables</Counter>
    <Counter>\SQLServer:General Statistics\Logins/sec</Counter>
    <Counter>\SQLServer:General Statistics\Logouts/sec</Counter>
    <Counter>\SQLServer:General Statistics\Temp Tables Creation Rate</Counter>
    <Counter>\SQLServer:General Statistics\Temp Tables For Destruction</Counter>
    <Counter>\SQLServer:General Statistics\User Connections</Counter>
    <Counter>\SQLServer:Latches\Latch Waits/sec</Counter>
    <Counter>\SQLServer:Latches\Total Latch Wait Time (ms)</Counter>
    <Counter>\SQLServer:Locks(*)\Average Wait Time (ms)</Counter>
    <Counter>\SQLServer:Locks(*)\Lock Requests/sec</Counter>
    <Counter>\SQLServer:Locks(*)\Lock Timeouts/sec</Counter>
    <Counter>\SQLServer:Locks(*)\Lock Wait Time (ms)</Counter>
    <Counter>\SQLServer:Locks(*)\Lock Waits/sec</Counter>
    <Counter>\SQLServer:Locks(*)\Number of Deadlocks/sec</Counter>
    <Counter>\SQLServer:Memory Manager\Granted Workspace Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Manager\Maximum Workspace Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Manager\Memory Grants Outstanding</Counter>
    <Counter>\SQLServer:Memory Manager\Memory Grants Pending</Counter>
    <Counter>\SQLServer:Memory Manager\Optimizer Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Manager\Stolen Server Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Manager\Target Server Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Manager\Target Server Memory(KB)</Counter>
    <Counter>\SQLServer:Memory Manager\Total Server Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Node(*)\Database Node Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Node(*)\Foreign Node Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Node(*)\Stolen Node Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Node(*)\Target Node Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Node(000)\Total Node Memory (KB)</Counter>
    <Counter>\SQLServer:Plan Cache(*)\Cache Hit Ratio</Counter>
    <Counter>\SQLServer:Resource Pool Stats(*)\CPU usage %</Counter>
    <Counter>\SQLServer:Resource Pool Stats(*)\Max memory (KB)</Counter>
    <Counter>\SQLServer:Resource Pool Stats(*)\Target memory (KB)</Counter>
    <Counter>\SQLServer:Resource Pool Stats(*)\Used memory (KB)</Counter>
    <Counter>\SQLServer:SQL Errors(*)\Errors/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\Auto-Param Attempts/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\Batch Requests/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\Failed Auto-Params/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\Safe Auto-Params/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\SQL Attention rate</Counter>
    <Counter>\SQLServer:SQL Statistics\SQL Compilations/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\SQL Re-Compilations/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\Unsafe Auto-Params/sec</Counter>
    <Counter>\SQLServer:Transactions\Free Space in tempdb (KB)</Counter>
    <Counter>\SQLServer:Transactions\Longest Transaction Running Time</Counter>
    <Counter>\SQLServer:Transactions\NonSnapshot Version Transactions</Counter>
    <Counter>\SQLServer:Transactions\Snapshot Transactions</Counter>
    <Counter>\SQLServer:Transactions\Transactions</Counter>
    <Counter>\SQLServer:Transactions\Version Cleanup rate (KB/s)</Counter>
    <Counter>\SQLServer:Transactions\Version Generation rate (KB/s)</Counter>
    <Counter>\SQLServer:Transactions\Version Store Size (KB)</Counter>
    <Counter>\SQLServer:User Settable(*)\Query</Counter>
    <Counter>\SQLServer:Workload Group Stats(*)\Active parallel threads</Counter>
    <Counter>\SQLServer:Workload Group Stats(*)\Active requests</Counter>
    <Counter>\SQLServer:Workload Group Stats(*)\CPU usage %</Counter>
    <Counter>\SQLServer:Workload Group Stats(*)\Queued requests</Counter>
    <Counter>\SQLServer:Workload Group Stats(*)\Reduced memory grants/sec</Counter>
    <Counter>\SQLServer:Workload Group Stats(*)\Requests completed/sec</Counter>
    <Counter>\SQLServer:Workload Group Stats(*)\Suboptimal plans/sec</Counter>
    <Counter>\System\Context Switches/sec</Counter>
    <Counter>\System\Processor Queue Length</Counter>
    <Counter>\System\System Calls/sec</Counter>
    <Counter>\TCPv4\Connection Failures</Counter>
</PerformanceCounterDataCollector>
</DataCollectorSet>
tools\dbatools\bin\perfmontemplates\collectorsets\PAL - SQL Server 2014 and Up.xml
<DataCollectorSet>
<Name>PAL - SQL Server 2014 and Up</Name>
<DisplayName>PAL - SQL Server 2014 and Up</DisplayName>
<DisplayNameUnresolved>PAL - SQL Server 2014 and Up</DisplayNameUnresolved>
<Description>Data Collector Sets from PAL, a performance monitor data aggregation tool by Microsoft. The toolset was created by Microsoft PFE Clint Huffman who worked with fellow experts to create a list specialized lists of counters. You can find the project at github.com/clinthuffman/PAL</Description>
<DescriptionUnresolved>Data Collector Sets from PAL, a performance monitor data aggregation tool by Microsoft. The toolset was created by Microsoft PFE Clint Huffman who worked with fellow experts to create a list specialized lists of counters. You can find the project at github.com/clinthuffman/PAL</DescriptionUnresolved>
<SubdirectoryFormat>3</SubdirectoryFormat>
<SubdirectoryFormatPattern>yyyyMMdd\-NNNNNN</SubdirectoryFormatPattern>
<PerformanceCounterDataCollector>
    <Name>PAL - SQL Server 2014 and Up Collector</Name>
    <SampleInterval>15</SampleInterval>
    <Counter>\Cache\Dirty Pages</Counter>
    <Counter>\Cache\Lazy Write Flushes/sec</Counter>
    <Counter>\LogicalDisk(*)\% Free Space</Counter>
    <Counter>\LogicalDisk(*)\% Idle Time</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk Bytes/Read</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk Bytes/Transfer</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk Bytes/Write</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk Queue Length</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk sec/Read</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk sec/Transfer</Counter>
    <Counter>\LogicalDisk(*)\Avg. Disk sec/Write</Counter>
    <Counter>\LogicalDisk(*)\Current Disk Queue Length</Counter>
    <Counter>\LogicalDisk(*)\Disk Bytes/sec</Counter>
    <Counter>\LogicalDisk(*)\Disk Reads/sec</Counter>
    <Counter>\LogicalDisk(*)\Disk Transfers/sec</Counter>
    <Counter>\LogicalDisk(*)\Disk Writes/sec</Counter>
    <Counter>\LogicalDisk(*)\Free Megabytes</Counter>
    <Counter>\Memory\% Committed Bytes In Use</Counter>
    <Counter>\Memory\Available MBytes</Counter>
    <Counter>\Memory\Commit Limit</Counter>
    <Counter>\Memory\Committed Bytes</Counter>
    <Counter>\Memory\Free &amp; Zero Page List Bytes</Counter>
    <Counter>\Memory\Free System Page Table Entries</Counter>
    <Counter>\Memory\Long-Term Average Standby Cache Lifetime (s)</Counter>
    <Counter>\Memory\Pages Input/sec</Counter>
    <Counter>\Memory\Pages Output/sec</Counter>
    <Counter>\Memory\Pages/sec</Counter>
    <Counter>\Memory\Pool Nonpaged Bytes</Counter>
    <Counter>\Memory\Pool Paged Bytes</Counter>
    <Counter>\Memory\Pool Paged Resident Bytes</Counter>
    <Counter>\Memory\System Cache Resident Bytes</Counter>
    <Counter>\Memory\Transition Pages RePurposed/sec</Counter>
    <Counter>\MSRS 2011 Web Service\Cache Misses/Sec</Counter>
    <Counter>\MSRS 2011 Web Service\Report Requests</Counter>
    <Counter>\MSRS 2011 Web Service\Total Memory Cache Misses</Counter>
    <Counter>\MSRS 2011 Web Service\Total Requests</Counter>
    <Counter>\Network Inspection System\Average inspection latency (sec/bytes)</Counter>
    <Counter>\Network Interface(*)\Bytes Received/sec</Counter>
    <Counter>\Network Interface(*)\Bytes Sent/sec</Counter>
    <Counter>\Network Interface(*)\Bytes Total/sec</Counter>
    <Counter>\Network Interface(*)\Current Bandwidth</Counter>
    <Counter>\Network Interface(*)\Output Queue Length</Counter>
    <Counter>\Network Interface(*)\Packets Outbound Errors</Counter>
    <Counter>\Network Interface(*)\Packets Received/sec</Counter>
    <Counter>\Network Interface(*)\Packets Sent/sec</Counter>
    <Counter>\Network Interface(*)\Packets/sec</Counter>
    <Counter>\Paging File(*)\% Usage</Counter>
    <Counter>\PhysicalDisk(*)\Avg. Disk Queue Length</Counter>
    <Counter>\PhysicalDisk(*)\Avg. Disk sec/Read</Counter>
    <Counter>\PhysicalDisk(*)\Avg. Disk sec/Write</Counter>
    <Counter>\PhysicalDisk(*)\Current Disk Queue Length</Counter>
    <Counter>\PhysicalDisk(*)\Disk Bytes/sec</Counter>
    <Counter>\Process(*)\Handle Count</Counter>
    <Counter>\Process(*)\ID Process</Counter>
    <Counter>\Process(*)\IO Data Operations/sec</Counter>
    <Counter>\Process(*)\IO Other Operations/sec</Counter>
    <Counter>\Process(*)\IO Read Operations/sec</Counter>
    <Counter>\Process(*)\IO Write Operations/sec</Counter>
    <Counter>\Process(*)\Private Bytes</Counter>
    <Counter>\Process(*)\Thread Count</Counter>
    <Counter>\Process(*)\Virtual Bytes</Counter>
    <Counter>\Process(*)\Working Set</Counter>
    <Counter>\Process(sqlservr)\% Privileged Time</Counter>
    <Counter>\Process(sqlservr)\% Processor Time</Counter>
    <Counter>\Processor Information(*)\% DPC Time</Counter>
    <Counter>\Processor Information(*)\% Interrupt Time</Counter>
    <Counter>\Processor Information(*)\% of Maximum Frequency</Counter>
    <Counter>\Processor Information(*)\% Privileged Time</Counter>
    <Counter>\Processor Information(*)\% Processor Time</Counter>
    <Counter>\Processor Information(*)\% User Time</Counter>
    <Counter>\Processor Information(*)\DPC Rate</Counter>
    <Counter>\Processor Information(*)\Parking Status</Counter>
    <Counter>\Processor(*)\% DPC Time</Counter>
    <Counter>\Processor(*)\% Interrupt Time</Counter>
    <Counter>\Processor(*)\% Privileged Time</Counter>
    <Counter>\Processor(*)\% Processor Time</Counter>
    <Counter>\Processor(*)\% User Time</Counter>
    <Counter>\Processor(*)\DPC Rate</Counter>
    <Counter>\ReportServer:Service\Errors Total</Counter>
    <Counter>\ReportServer:Service\Errors/sec</Counter>
    <Counter>\ReportServer:Service\Memory Pressure State</Counter>
    <Counter>\ReportServer:Service\Memory Shrink Amount</Counter>
    <Counter>\ReportServer:Service\Memory Shrink Notifications/sec</Counter>
    <Counter>\Server\Pool Nonpaged Failures</Counter>
    <Counter>\Server\Pool Paged Failures</Counter>
    <Counter>\SQLAgent:Jobs\Active jobs</Counter>
    <Counter>\SQLAgent:Jobs\Failed jobs</Counter>
    <Counter>\SQLAgent:Jobs\Job success rate</Counter>
    <Counter>\SQLAgent:Jobs\Successful jobs</Counter>
    <Counter>\SQLAgent:JobSteps\Active steps</Counter>
    <Counter>\SQLAgent:JobSteps\Total step retries</Counter>
    <Counter>\SQLServer:Access Methods\Forwarded Records/sec</Counter>
    <Counter>\SQLServer:Access Methods\FreeSpace Scans/sec</Counter>
    <Counter>\SQLServer:Access Methods\Full Scans/sec</Counter>
    <Counter>\SQLServer:Access Methods\Index Searches/sec</Counter>
    <Counter>\SQLServer:Access Methods\Page Splits/sec</Counter>
    <Counter>\SQLServer:Access Methods\Scan Point Revalidations/sec</Counter>
    <Counter>\SQLServer:Access Methods\Table Lock Escalations/sec</Counter>
    <Counter>\SQLServer:Access Methods\Workfiles Created/sec</Counter>
    <Counter>\SQLServer:Access Methods\Worktables Created/sec</Counter>
    <Counter>\SQLServer:Access Methods\Worktables From Cache Ratio</Counter>
    <Counter>\SQLServer:Availability Replica(*)\Bytes Received from Replica/sec</Counter>
    <Counter>\SQLServer:Availability Replica(*)\Bytes Sent to Replica/sec</Counter>
    <Counter>\SQLServer:Availability Replica(*)\Bytes Sent to Transport/sec</Counter>
    <Counter>\SQLServer:Availability Replica(_Total)\Receives from Replica/sec</Counter>
    <Counter>\SQLServer:Availability Replica(_Total)\Resent Messages/sec</Counter>
    <Counter>\SQLServer:Availability Replica(_Total)\Sends to Replica/sec</Counter>
    <Counter>\SQLServer:Buffer Manager(*)\Extension page unreferenced time</Counter>
    <Counter>\SQLServer:Buffer Manager\Background writer pages/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Buffer cache hit ratio</Counter>
    <Counter>\SQLServer:Buffer Manager\Checkpoint pages/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Extension free pages</Counter>
    <Counter>\SQLServer:Buffer Manager\Extension outstanding IO counter</Counter>
    <Counter>\SQLServer:Buffer Manager\Free list stalls/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Free pages</Counter>
    <Counter>\SQLServer:Buffer Manager\Lazy writes/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Page life expectancy</Counter>
    <Counter>\SQLServer:Buffer Manager\Page lookups/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Page reads/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Page writes/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Readahead pages/sec</Counter>
    <Counter>\SQLServer:Buffer Manager\Target pages</Counter>
    <Counter>\SQLServer:Buffer Node(*)\Database pages</Counter>
    <Counter>\SQLServer:Buffer Node(*)\Foreign pages</Counter>
    <Counter>\SQLServer:Buffer Node(*)\Local node page lookups/sec</Counter>
    <Counter>\SQLServer:Buffer Node(*)\Page life expectancy</Counter>
    <Counter>\SQLServer:Buffer Node(*)\Remote node page lookups/sec</Counter>
    <Counter>\SQLServer:Database Replica(*)\Log Bytes Received/sec</Counter>
    <Counter>\SQLServer:Database Replica(*)\Mirrored Write Transactions/sec</Counter>
    <Counter>\SQLServer:Database Replica(*)\Recovery Queue</Counter>
    <Counter>\SQLServer:Database Replica(_Total)\Log remaining for undo</Counter>
    <Counter>\SQLServer:Database Replica(_Total)\Log Send Queue</Counter>
    <Counter>\SQLServer:Database Replica(_Total)\Redo blocked/sec</Counter>
    <Counter>\SQLServer:Database Replica(_Total)\Redo Bytes Remaining</Counter>
    <Counter>\SQLServer:Database Replica(_Total)\Redone Bytes/sec</Counter>
    <Counter>\SQLServer:Database Replica(_Total)\Total Log requiring undo</Counter>
    <Counter>\SQLServer:Database Replica(_Total)\Transaction Delay</Counter>
    <Counter>\SQLServer:Databases(*)\Active Transactions</Counter>
    <Counter>\SQLServer:Databases(*)\Backup/Restore Throughput/sec</Counter>
    <Counter>\SQLServer:Databases(*)\Bulk Copy Throughput/sec</Counter>
    <Counter>\SQLServer:Databases(*)\Data File(s) Size (KB)</Counter>
    <Counter>\SQLServer:Databases(*)\Log Bytes Flushed/sec</Counter>
    <Counter>\SQLServer:Databases(*)\Log File(s) Size (KB)</Counter>
    <Counter>\SQLServer:Databases(*)\Log File(s) Used Size (KB)</Counter>
    <Counter>\SQLServer:Databases(*)\Log Flush Wait Time</Counter>
    <Counter>\SQLServer:Databases(*)\Log Flush Waits/sec</Counter>
    <Counter>\SQLServer:Databases(*)\Log Flushes/sec</Counter>
    <Counter>\SQLServer:Databases(*)\Log Growths</Counter>
    <Counter>\SQLServer:Databases(*)\Log Shrinks</Counter>
    <Counter>\SQLServer:Databases(*)\Log Truncations</Counter>
    <Counter>\SQLServer:Databases(*)\Percent Log Used</Counter>
    <Counter>\SQLServer:Deprecated Features(*)\Usage</Counter>
    <Counter>\SQLServer:General Statistics\Active Temp Tables</Counter>
    <Counter>\SQLServer:General Statistics\Logins/sec</Counter>
    <Counter>\SQLServer:General Statistics\Logouts/sec</Counter>
    <Counter>\SQLServer:General Statistics\Temp Tables Creation Rate</Counter>
    <Counter>\SQLServer:General Statistics\Temp Tables For Destruction</Counter>
    <Counter>\SQLServer:General Statistics\User Connections</Counter>
    <Counter>\SQLServer:Latches\Latch Waits/sec</Counter>
    <Counter>\SQLServer:Latches\Total Latch Wait Time (ms)</Counter>
    <Counter>\SQLServer:Locks(*)\Average Wait Time (ms)</Counter>
    <Counter>\SQLServer:Locks(*)\Lock Requests/sec</Counter>
    <Counter>\SQLServer:Locks(*)\Lock Timeouts/sec</Counter>
    <Counter>\SQLServer:Locks(*)\Lock Wait Time (ms)</Counter>
    <Counter>\SQLServer:Locks(*)\Lock Waits/sec</Counter>
    <Counter>\SQLServer:Locks(*)\Number of Deadlocks/sec</Counter>
    <Counter>\SQLServer:Memory Manager\Granted Workspace Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Manager\Maximum Workspace Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Manager\Memory Grants Outstanding</Counter>
    <Counter>\SQLServer:Memory Manager\Memory Grants Pending</Counter>
    <Counter>\SQLServer:Memory Manager\Optimizer Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Manager\Stolen Server Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Manager\Target Server Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Manager\Target Server Memory(KB)</Counter>
    <Counter>\SQLServer:Memory Manager\Total Server Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Node(*)\Database Node Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Node(*)\Foreign Node Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Node(*)\Stolen Node Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Node(*)\Target Node Memory (KB)</Counter>
    <Counter>\SQLServer:Memory Node(000)\Total Node Memory (KB)</Counter>
    <Counter>\SQLServer:Plan Cache(*)\Cache Hit Ratio</Counter>
    <Counter>\SQLServer:Resource Pool Stats(*)\CPU usage %</Counter>
    <Counter>\SQLServer:Resource Pool Stats(*)\Max memory (KB)</Counter>
    <Counter>\SQLServer:Resource Pool Stats(*)\Target memory (KB)</Counter>
    <Counter>\SQLServer:Resource Pool Stats(*)\Used memory (KB)</Counter>
    <Counter>\SQLServer:SQL Errors(*)\Errors/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\Auto-Param Attempts/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\Batch Requests/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\Failed Auto-Params/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\Safe Auto-Params/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\SQL Attention rate</Counter>
    <Counter>\SQLServer:SQL Statistics\SQL Compilations/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\SQL Re-Compilations/sec</Counter>
    <Counter>\SQLServer:SQL Statistics\Unsafe Auto-Params/sec</Counter>
    <Counter>\SQLServer:Transactions\Free Space in tempdb (KB)</Counter>
    <Counter>\SQLServer:Transactions\Longest Transaction Running Time</Counter>
    <Counter>\SQLServer:Transactions\NonSnapshot Version Transactions</Counter>
    <Counter>\SQLServer:Transactions\Snapshot Transactions</Counter>
    <Counter>\SQLServer:Transactions\Transactions</Counter>
    <Counter>\SQLServer:Transactions\Version Cleanup rate (KB/s)</Counter>
    <Counter>\SQLServer:Transactions\Version Generation rate (KB/s)</Counter>
    <Counter>\SQLServer:Transactions\Version Store Size (KB)</Counter>
    <Counter>\SQLServer:User Settable(*)\Query</Counter>
    <Counter>\SQLServer:Workload Group Stats(*)\Active parallel threads</Counter>
    <Counter>\SQLServer:Workload Group Stats(*)\Active requests</Counter>
    <Counter>\SQLServer:Workload Group Stats(*)\CPU usage %</Counter>
    <Counter>\SQLServer:Workload Group Stats(*)\Queued requests</Counter>
    <Counter>\SQLServer:Workload Group Stats(*)\Reduced memory grants/sec</Counter>
    <Counter>\SQLServer:Workload Group Stats(*)\Requests completed/sec</Counter>
    <Counter>\SQLServer:Workload Group Stats(*)\Suboptimal plans/sec</Counter>
    <Counter>\System\Context Switches/sec</Counter>
    <Counter>\System\Processor Queue Length</Counter>
    <Counter>\System\System Calls/sec</Counter>
    <Counter>\TCPv4\Connection Failures</Counter>
</PerformanceCounterDataCollector>
</DataCollectorSet>
tools\dbatools\bin\projects\dbatools\.vs\dbatools\v15\.suo
 
tools\dbatools\bin\PSScriptAnalyzerRules.psd1
@{
    IncludeRules = @(
                    'PSAvoidUsingCmdletAliases',
                    'PSAvoidUsingWriteHost',
                    'PSAvoidDefaultValueSwitchParameter',
                    'PSReservedCmdletChar',
                    'PSReservedParams',
                    'PSAvoidUsingUserNameAndPassWordParams',
                    'PSAvoidUsingPlaintTextForPassword',
                    'PSAvoidUsingWMICmdlet',
                    'PSAvoidUsingWriteHost',
                    'PSMisleadingBacktick',
                    'PSMissingModuleMainifestField',
                    'PSPossibleIncorrectComparisonWithNull',
                    'PSUseApprovedVerbs',
                    'PSUseOutputTypeCorrectly',
                    'PSShouldProcess',
                    'PSUserToExportFieldsInManifest',
                    'PSUseSingularNouns',
                    'PSAvoidUsingInvokeExpression',
                    'PSUseShouldProcessForStateChangingFunctions',
                    'PSUseDeclaredVarsMoreThanAssignments'
                    )
}

tools\dbatools\bin\smo\Accessibility.dll
md5: FC53B66F0B862A05CF533B44A1CAEDBB | sha1: 5E5BD9F1A9E6D8EA047E17BE5BE2D387CA1AB8E9 | sha256: 3594B22AB2FD554E1890B48D5E64C0A6A70A0CABD00B7453E8C921C11C08D5E6 | sha512: D45E01CA7A48124667FAA37A51F9452E95E69DC72C718D583E17A77888976C6B8378ED82CF0B9DB7BF1177E8D77FB0FC5A04846396D70867DA45BFCBE2DEB592
tools\dbatools\bin\smo\coreclr\Microsoft.Data.Tools.Schema.Sql.dll
md5: C949159E35D7BC0CE907F5F9863B44F8 | sha1: 9032020AA97E427CF64B7B7F2D9975BAC9FB5DDF | sha256: 1BD2BCAC522CABD9973B096BC4451CE148C1133D266B780CA084F418A552C2A8 | sha512: F56794D462619DA3E2294663DE2AFE81655ADBA247210F54157B799CDC071C404FD7CB1DE74B9095C40EDD4B8FCB90D8E2F0D52DBB2DBB38B9E465FB70D031EE
tools\dbatools\bin\smo\coreclr\Microsoft.Data.Tools.Sql.BatchParser.dll
md5: 7A8973D169B8DB417BD63FD476682B25 | sha1: 166E192615363BA4683ABCA46B1BE73B988E6EA0 | sha256: 8E25B727FCD8E5DAA76DB626325CE742487E7F59BB12F54B69FE542C60F3DFF1 | sha512: 2262458CCEFAB75E53481BE6CB19D5747B17A6D1B107FA63C3DC5A1CE14F270255261CE7B1942B3C7C48954B7665D936FD23CA5D98A66BE83AAF20BDD38F4FC4
tools\dbatools\bin\smo\coreclr\Microsoft.Data.Tools.Utilities.dll
md5: F6B41E593517B2EF5439D83719C5042E | sha1: B0DB12985A2DB9161389059FC35DAC273C1593B2 | sha256: 69C4506E42EA98069D89916CF53D7937D8B3D569EFDED4BAA287F67B5BAC2605 | sha512: C4742C9DB589A607C29E50AC7A5924A28C91F9C33E4E6C4847494ADBC167ACAEB47DFB26214DA24F442EF7EFEF75056575B205B4018AEB59485E0F7B39D8732F
tools\dbatools\bin\smo\coreclr\Microsoft.SqlServer.ConnectionInfo.dll
md5: 87C68BAE8942C6634787A8635FF21DCD | sha1: 1BE70E360582B34646CCACEA245542880D4C1F65 | sha256: 1C14F3FCAABD17338F606E3F576A4BACCEDB51697B5E369A26ED086D0BBD47B8 | sha512: D3AFBE4818B06DDF19B87EE3245655B1F3793C24ACBCFBBCC8D1AAC7FCFA65F7769406AE6188F22B1C23093FC79D0D48ED191E4EE050A5E31B22133F4833C6DC
tools\dbatools\bin\smo\coreclr\Microsoft.SqlServer.Dac.dll
md5: DA50A395F84D20AB342D661670BB2E88 | sha1: D2FAACC7621D68FA6B3C94DB81D61B0FEE25BD79 | sha256: 19424A535BD8F3B4053FCC4E58B6B029AF26E2B920695FF1524A4AF111DCA6B5 | sha512: E65656A1DA259701C5218C0059297FD00F72DE759730AF347304B030A87DDCB92E501E454553D597011FCC1D5C761C8A6A4C197A90B6FEE91C1AA37604DE26F5
tools\dbatools\bin\smo\coreclr\Microsoft.SqlServer.Dac.Extensions.dll
md5: F50C79A8C827DE7EF9CE07018AB1FC52 | sha1: 4FF1BE4B40AE66DDF7F417DDCE4972BD0B56DC4D | sha256: 106604D0FE26C3F3FA1749CD6777EA5270AD467B958E5180D788DC0F6CCDB450 | sha512: C38BD847A5EA5B0BC1ABABC77889A2BA05284E5FF8CA09F6DB9488FFC671E4C6B26D4E111359791921F4DE1A0A359383D77412EE41C23FD8E54F07BC4F880679
tools\dbatools\bin\smo\coreclr\Microsoft.SqlServer.Management.Dmf.dll
md5: E67B50A873949BA1FFDD48DF0AC04DEC | sha1: 664B57EFFC0128B6396545CDE4852DB50BFC6EF8 | sha256: 3CE94BD138CAF3BB208809DA90BB38E5EC6172470C567717184CC0CDC964B43D | sha512: D36AE3C6096E533579D69DC11DC637C89B96BABEFFC4B9D85F595CBF62745A54AA130894F7BDF32991A1B86E537A8EB5F336CDA54DAD92C15C48BD4B465D617F
tools\dbatools\bin\smo\coreclr\Microsoft.SqlServer.Management.PSProvider.dll
md5: 725CFF103DB829F0A48174CDE0CB9E99 | sha1: 6A9CB5025C71E92B9CAE7B7A479A6A7B54452F40 | sha256: 291D74136F08202DEAF64DEABD45F4DA44132A509344DD4300314D7A765943A5 | sha512: CC35FCA06C0D39D4DDEAFB4FBEB753DC288F724745BD9AE36B6F52C66A1BD06C4E1F5D20F4C2D3624CDDBFA20C6C435863F7C442075D007CF634B47F0F227FBB
tools\dbatools\bin\smo\coreclr\Microsoft.SqlServer.Management.PSSnapins.dll
md5: 2F726594DFB553FD15322C69EDE08B74 | sha1: BBD5CC49B538D02E30EC1B6F7FFD9A039B05BBD4 | sha256: EACBAAD09C5624DF9985116E9449960DD0701BF12B13BEEA8F32BDD69712B13C | sha512: 597D4EA2EA7ECA3CEF1096A7EA0EA6F71774781A9DCE86EF3E277E670FF3647406709FE55DA7BCD5FB27F56E486B320F1E9BBE4E2C9CF930082A6F304F37855E
tools\dbatools\bin\smo\coreclr\Microsoft.SqlServer.Management.Sdk.Sfc.dll
md5: 76E51C34730068F32B9B7A6C49091252 | sha1: 32E101CE10BE9A22719ED1C85198ABECA7C66726 | sha256: F2FBF444E1F532E8582185CCDFDC010FB58EE4369875A9AF5EAB7B43C6CBB59B | sha512: 8955E205756E3A7F296B99DFAB7C2FD0AA0628E4EE4C01FFC66527C3F41862E5DBFA17BCAD30D4FA569A7ED8BBE6A17086A12485BC3367DD07F4E53340780D78
tools\dbatools\bin\smo\coreclr\Microsoft.SqlServer.Management.XEvent.dll
md5: 8852BE0260AAFC00E2E49757F7F3D6D3 | sha1: 682C57866A0C07F7042235D50DBADAEBD3D0F808 | sha256: E496E40C48181463645064C16698AE60FE556C6B5F9ED51DCC8C6B6368A83DD9 | sha512: FDE8C5BBAF3256B7C534BCF5D0ACA200BE431B5D215E4B554385144991EC07C712DE71A8500532D43DA74E0DFFD315F4AB0990D6EA85DE00FAA7DED579F8BDEE
tools\dbatools\bin\smo\coreclr\Microsoft.SqlServer.Management.XEventDbScoped.dll
md5: 458299069ACAC4233D7D16C375B68F12 | sha1: 32BB3DD482CB7E67BAFC806174B89ED723D744E8 | sha256: 740CC31E11E16B5BB65BCA083D0A4AE0254E59942EE4A410F1998519C0C2A7EB | sha512: EEC8CBAAD52EA17377F46C0D8C915866FD4A5C27BF5D73689B292190A738035B9CF83C5C4A48573EB3A05526585E1DC714411D3FF873F3596B9B71F8E69B35B7
tools\dbatools\bin\smo\coreclr\Microsoft.SqlServer.Management.XEventDbScopedEnum.dll
md5: 29D513C4A3E722E31658D48D392162B6 | sha1: 600D3E6E5FCE1A12251F9025AA1D0688EF7ED00E | sha256: F8625A1BCE507258D11D437E24865FD4FFFED25F7B3D9E62EDE60B705776CFB7 | sha512: D104727FEE1AB645E40DCF14DBFB2F9BE69D36A95862C56D84299DB7C074D5730B11E29C1134ABDEE4C7B8EB9CDB6DA91D5A4599B6722F0B37F476D927D71AE3
tools\dbatools\bin\smo\coreclr\Microsoft.SqlServer.Management.XEventEnum.dll
md5: 86400F50F84A857F2B101CFFD06A2738 | sha1: AB316809D2844849AC1F2971C5EF99EFCFBE8B66 | sha256: C3D4C5F0B0128BAC2E3608B95A1BBC9C313ACB4330ED7BE412494E7B90416E99 | sha512: 9D38E2D3497945492BFE6D620D2E2BAE3BDA6681A9D9AAF3F130224627D0AAE6CAFDC54278E25F4C3507A90AB7124666AAF6FF1A337A5E78A044533463F9D8E9
tools\dbatools\bin\smo\coreclr\Microsoft.SqlServer.Smo.dll
md5: 9A097C9540BF37ED08B9C554D55C430F | sha1: D1B1FC2D2308B8CD10261A2B44FF127595084EAD | sha256: C1514D8239F492E79C42E38FF95E8B745B25A7662991CD3F0301F1136F9B17B0 | sha512: 9805E72C3378412DB26C5B7EAFAABAF42715715C607B7073610BFB8A5F4EBB743A89459D104FA7D89A42E49D49D5224BC0E4133B170E99579FEF3E73061E4222
tools\dbatools\bin\smo\coreclr\Microsoft.SqlServer.SmoExtended.dll
md5: EDF3EFF15A707E08BD8BD0AA4A8DF4C2 | sha1: A5F75CACFB7D6D5211EB4008CA6759AD16609738 | sha256: BE90CE5E335D3FF0BBB51B96FC1BF0575D47466D3BC78DAEAEA927FF60659EB1 | sha512: 1167A05D1A3273E035C29C1284E2CEE396F034F607487E06153A0E70BF22F83937B1E12A712782ABDBA4B90569A74CF8B879FBE5E4B5478035194A16E09211DF
tools\dbatools\bin\smo\coreclr\Microsoft.SqlServer.SqlEnum.dll
md5: F4E0078E482C8A26FB8E1BB767B22C68 | sha1: 0030462F3F7CC23FE406DDF32BDC2C9DD51E724A | sha256: CE00B225FF860295DA3CCCAEFA2730EA2D96C35C4D84F49189DC282FE3665219 | sha512: FF5CF7666B0EBE6CCF4A2FD66364708BEB3D584B4B895EC3BE48FADECE152FA40E068F07BA8C43EE2714867652CB164F755B3E61D3F1BE603CE7AA40EBCECD1C
tools\dbatools\bin\smo\coreclr\Microsoft.SqlServer.TransactSql.ScriptDom.dll
md5: BBB18E7001990AB4A2D88C147873D4AD | sha1: 524FDD20925B492CEEF5BB9FA56C998BF2F966EC | sha256: 2C8359841EF323BB41A4FD09E3A396E449EDE04D8BCD482E25413029155729ED | sha512: C0FC3177FE7AC359C67C9DE7E63394C6558494A95013404C8FDE0F0F982DCC1AB58D889B4AB3789B3F385EFA723E097607DB363635F16D681FD919BDA86F452A
tools\dbatools\bin\smo\coreclr\Microsoft.SqlServer.Types.dll
md5: D373482D61BB8B6DCFE0627BBBA47E20 | sha1: EDEC514041860AA053FFF21360C949D73197AD24 | sha256: E8FC85F664E3B436E55338831E995FBAD058B428024B9B50B4011AAA37EC1E00 | sha512: C14ADF6A11DAF9446E15A5BAAD1079F115E9F879C8C29B09C2324B508116CD7B73620830957C7EAA72CBF403F796271B980A087BC0907317FBAFBE5274BAA9CB
tools\dbatools\bin\smo\coreclr\System.Security.SecureString.dll
md5: CFB05BA0EA20FDA5485D22778C9C01CB | sha1: F11292760F86B90387A8FA44B0FBDED381170764 | sha256: 8DB04A3AC0369DAF0BF0AEAEBC947E4D91AF4CF853144D2C1F1977B893FBE4A6 | sha512: C62869D398E97F0DDF065043D228BB1E3EC1CCE537461A1FF29CF4C925108F232BED7F39EC9853F5A5432000AA716BF9C1B90B16852B66AA819B84D0859517AA
tools\dbatools\bin\smo\Microsoft.AnalysisServices.AppLocal.Core.dll
md5: 2ACB72F8B7FFFB8D53BC79C412FBD19A | sha1: 6B54CBF8F4305176C4F11737D75FA54C5D694904 | sha256: EAF198781427C8F148022C38FA89E8D6E77DCAD420F5EFC028FAB3E45452D7A3 | sha512: D3AABA6CFE2C6E84E6C04C46E4B9022DAE1B130A95E0D3442EF9F44A9300ED03A17022CFD575DD1FA1A6C188E2B92728293027011C0CB115488B335584473F47
tools\dbatools\bin\smo\Microsoft.AnalysisServices.AppLocal.dll
md5: FCAA6034315522B0A10F18B522A89602 | sha1: F6990976F55616AA986CCEC2719BDB17FA9C00C3 | sha256: 7C8FD89AF1C118D5DC0C46BEC6484358467E6EA278EFB8C5B4CA6B63C62B717D | sha512: 6D622B81BE12A2079BFE7724A5892245F43CEC0581EEFBA33B8A7241AF6E80DD58D239E7D2A42C47E499591865C3A098984C218ED74F6303B559067049E90EEA
tools\dbatools\bin\smo\Microsoft.Azure.KeyVault.Core.dll
md5: 8C454E6D06D56C19F355F702B15EBB15 | sha1: 6D4322B7BC25A50E0C5EFC80DD71824592D3A040 | sha256: 3A1475D6F1A99AB2A85AFEDFF3DB6454D901EBF1DE1D58E294EA2CB16516648A | sha512: 6D1C221430668BE2C7DAAE9D27AAA621038F8F52F5AC3CF9A6D02D10F33E85718E08017E5CF6CDB9E2CB10CE66EB9212DCC6C88FB17C4FB486C7D71720B6BDFB
tools\dbatools\bin\smo\Microsoft.Data.Edm.dll
md5: 383FE8CAD1F26D4A307FFD490B96D307 | sha1: B5D13E6B49B72825627B44C3501091A12580F741 | sha256: 2488A00E8045A929110BC35F4719D40C653C89F1799CB97767CB01FE94CF3E3B | sha512: E8F7A59764BE375BED343E3F60F12A7537973DA219D2101796CCCD455EB70ECD8AF784C0A2A7D96D7FB3D6A4DA73C784889DEC086019CF0D26CB700E738BB042
tools\dbatools\bin\smo\Microsoft.Data.OData.dll
md5: F631F51807B66AC4E3C9869122FC1309 | sha1: 496EBB02213A694101849ADFCE095F4671459D5B | sha256: 9E635E1F33493D570A5C42B394450569B14FF418026FE530CA364FC4AB395778 | sha512: 26FB696407D8218E80995732FA176BD7EDE900C358004AF4B7F5D359863A4ABC1B9462B6BCA3540C72A6A342CFED962252B06D58B63A469148EA48AE6D47AF53
tools\dbatools\bin\smo\Microsoft.Data.Tools.Components.dll
md5: FB02906D3F269BEEB3035CCA0F411E61 | sha1: 204B41159B0A875D24CD5762A98C6CC474A44CE2 | sha256: 5D97EC841E7A696EA54BEB6E499F52B203DED61335C82D63DE2D72C3FCD9121E | sha512: 6F5F9FB92A30038C9839E2524682ED45F0A96604E496D24B3D62E06B2D643CEB8AFD24A641B0DB0C89E52624F5C198033BE482F2539F6F0F29ED9208F56A9C9E
tools\dbatools\bin\smo\Microsoft.Data.Tools.Contracts.dll
md5: E388AB530054F8C12D01549D1106F57D | sha1: 5BD95EF1303E453B75E443D3E3F6CEB9C327C767 | sha256: 0570A8B2D205954D402DAC7CDE1C5D52C3774E6D96404959D5DD70FAA6248D52 | sha512: 03C5ACB9A4C0E5A49C3B86E2ABAE2B11485BD644E44B157E89B59C716945DB69F6BC2538BF744B6AA0C5B9F39D645B7ECC778BC12F804772F6AE4381E3622357
tools\dbatools\bin\smo\Microsoft.Data.Tools.Schema.Sql.dll
md5: 54A947A8CED5A122FFA7B0A84041420E | sha1: C631EA3C22410A317252CAF41950B75F4C5488BE | sha256: 17AB90D36B5E3E3F4D76E80213C9B539448FDD46FAFD2CBD306465044C1629EC | sha512: A7AF2D5E7A3E8DACDD44B9492C4A14C78633B51D0AEE58EDFE88EFC9D231C78F3CC42D66948DB8A1C58F44434B864EAE9D367C4E8F7B19A4099847D59A9DE07F
tools\dbatools\bin\smo\Microsoft.Data.Tools.Schema.SqlTasks.targets
 
tools\dbatools\bin\smo\Microsoft.Data.Tools.Schema.Tasks.Sql.dll
md5: B5AFC86E733FE19DAE8A6DFB71901A4E | sha1: F076620639B6EAF2A086292D46F479457730ACAA | sha256: 6387E707E5A9983C27879462AE1A9FE0AD336A27425113EE064380B7B006CD71 | sha512: 44469F97E547AE8B8EB18557BB2B607C3EAF914B0A1F9FC2691FA46493D6CDD554E52FA9F0147A7560D3C5D2E7F5B006ACDB65558340C9C5433016965AC0EC72
tools\dbatools\bin\smo\Microsoft.Data.Tools.Schema.Utilities.Sql.dll
md5: B3A6CA5EE94FF2E86811D687658555C1 | sha1: 5D22774B875DEC5AC4BDF36BF69C05E7E6280A81 | sha256: 1C3B90F76D5E7908C15688F5138EECDBC208D3C4D33ACE7CA79BCC52B3A17F14 | sha512: A76524B0D47BA4E5AE36A3EB9523AB598ABE7BB9F0C7354E2FDC278C3DFDA4CD2051749F36E8309E1D85ADD6392BEC93BB858E1622A3EE7F07B016A7AF24C314
tools\dbatools\bin\smo\Microsoft.Data.Tools.Utilities.dll
md5: C6CC649FA71CA67148297E8A5993DBE3 | sha1: 82CDF6397A03D9B8931A6BC8D6296951F790FB35 | sha256: EFF493CEFF05385D55183A1FBC45311AD92781A5484FB0E15A725016B7EFB8D9 | sha512: 6D655FE5BBE7A6B644F9A21F54613189DB9C55BD560B7D9565873650137ECB8EBAFC4DE1F04E4338E8EC670716394ECE9850C0DA654111D27F54FEDF9E15B474
tools\dbatools\bin\smo\Microsoft.DataTransfer.Common.Utils.dll
md5: B628255C8F1E2AFBCCF2D8DBF02779E4 | sha1: 2F53622D555DDD30882CF128AD69C38A1F4E392C | sha256: 25C8FBEA431843B4150E2E4A770139C3B52C8D3EEBA983D38B03313F00271D7E | sha512: 702F2036C303BD97C7A6A76EE79B03A0B46D604A0FAD306FEEE023D6857CACFFDBD291E95D094607AF5A90456F3C971E5939D91A43E8C37BBBEE911BA24B2BFB
tools\dbatools\bin\smo\Microsoft.Practices.TransientFaultHandling.Core.dll
md5: 04C9A563ED69D537D753B5A45F870B44 | sha1: 28EBC515826108FA736A5D34DDDCAE86A52FFC10 | sha256: 09AE9F682D0E610AE4C560891EB103C2F1E16B18780CC60856EEA5B953402F5D | sha512: 963CA4299050C8ECCE9D1DDD5DD569A9CC1E241880D6294D5E8D3CDD2E05A42B3ABB483013C96BF5F18B27BF1C39BF68484503F61D66DCA587C527CA7675CF22
tools\dbatools\bin\smo\Microsoft.SqlServer.BatchParser.dll
md5: 9B2DA9E2F4CA29792614DA567EEE4DB4 | sha1: C44D1E8DEBBF1E197F4DF8F1FB7786EDDB00420E | sha256: 28DB74E05232B7C15F2832C548B77998164730D959564A3652CAD4937F445221 | sha512: 9449A2A614A9D06723B7687F933DB42984414DDDD4EAE8C0D807251E21199FD6ED8A3221BC29AA813121EE4D609785F7D085140725B5274F3AE3EBFFCDBAC3C7
tools\dbatools\bin\smo\Microsoft.SqlServer.BatchParserClient.dll
md5: C253D24E75845D8BA3B483CB5937E725 | sha1: 80B24C4001B0D6D99842048272B9CE8C17020557 | sha256: 01B28FA8B11AF5100098DD026E4C636736D932C0FDFBA00ED7C85054E1AE628B | sha512: B3A9B16342B0AC540B833FD57DE9D739E3507CDCB0503492BE42C5747561444812F8F024D5D443E9241744FDFB3A1303E762AC65DCA3DD0DF6EA6B322ACE4C11
tools\dbatools\bin\smo\Microsoft.SqlServer.BulkInsertTaskConnections.dll
md5: 336D96B873E2C70F6C81370F19521E09 | sha1: 3E9DEA38211CB0FA680127CAABD358F9DA54F270 | sha256: DFD6BE0724F0ECF76A1DA670B40A5D155C3B9043E598411B79813FF4B21984E4 | sha512: A02E4B667BCFAEB68D12515D38FA5F7CBBBE6983EEC989947941FA5FD63A717CC5F6A38E8B8FB24058D3D348959B0BA1A3D043EB211BB70CDA47B1684174CCE7
tools\dbatools\bin\smo\Microsoft.SqlServer.ConnectionInfo.dll
md5: 7446B5C8FFCBA09039ABF785D1BB4A88 | sha1: 6AD988335E008315F06A43A722DF69AB5B4722F0 | sha256: 3407221FE6F297E845AEB91A4886BB7B268A79CA2A73E273BDC2D36ECA26ADA6 | sha512: 752433FCFAE9F16292B07F18A9416A7FE786F82038BB7E0C30E79FD1B2ED68BC9DB60143B68F29B05CE412DB8ACE34E3A7609CDBE0FF14B0AB28AEEE98A43CB9
tools\dbatools\bin\smo\Microsoft.SqlServer.ConnectionInfoExtended.dll
md5: 9208D9667BAE268B63C09BF8E6C79FE4 | sha1: A3DA904733DE2F8161A1103F8061C4392D97BA6C | sha256: F0A1A6600895B521AFE9C17F545D851DB218BCCE93C76A3E96608115F4F4DEBC | sha512: DADDBD541CF0DE43E9D0BEDA524453EBEE533BDC30957E8F71C3D1F5CC76D0D3339061FB06C2FA9F9F92258E5E31FF13E6179F77FA30B1B984E1419E1FE589A7
tools\dbatools\bin\smo\Microsoft.SqlServer.Dac.dll
md5: 11CE124B92362C6DAF66E038515A2DF5 | sha1: E11F403F9A92ED69CB5D3ECFF464B9286D50587C | sha256: DF15554804BB08351DF170434E2E994475F6AA3F5B6A465CA30052A13F6EAF0A | sha512: 5036C4855CE72374BC688010D4A0E5F0A9F55F08B5B4D5421C8A53EB4CB7DB53AC42493AA79D7774682427FAFDC38A47D083E16D5973E49BC821EFB88BFDD424
tools\dbatools\bin\smo\Microsoft.SqlServer.Dac.Extensions.dll
md5: 2DD7BA70365204298B4A381D500F433C | sha1: AF2655A5220761227E33EF89583346C7FFD9CD72 | sha256: 2A7D545774CAD03C72F3E6E5B06B65F75A716052B0A2D36E48DA3124BF0B54FD | sha512: 490F1D96C33FAEA13F73109D6068C887D86B86E7BDEA002DCBA42AB2DE3C47E8E63ED1C345AF252163D72FC6FE7045635A1C64BA8B3ACB3A9C50E7FF63584817
tools\dbatools\bin\smo\Microsoft.SqlServer.Dac.Extensions.xml
<?xml version="1.0"?>
<doc>
    <assembly>
        <name>Microsoft.SqlServer.Dac.Extensions</name>
    </assembly>
    <members>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisModelValidationMode">
            <summary>
            Determines the validation performed on the model prior to code analysis.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisModelValidationMode.Full">
            <summary>
            The TSqlModel is fully validated prior to code analysis.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisModelValidationMode.None">
            <summary>
            No validation is performed on the TSqlModel prior to code analysis
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisResult">
            <summary>
            The results of Code Analysis against a particular model. Will include any
            <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem"/>s found, in addition to any errors that occurred
            during analysis
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisResult.#ctor">
            <summary>
            Creates a <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisResult"/>
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisResult.GetAllErrors">
            <summary>
            Gets all errors, whether during initialization or during the analysis process. This
            does not include the <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisResult.Problems"/> found during analysis since these are
            returned separately.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisResult.SerializeResultsToXml(System.String)">
            <summary>
            Serializes the results in XML format to an output file.
            
            Only the problems discovered during analysis are output. No errors that occurred during
            the analysis process will be output.  
            </summary>
            <param name="outputFilename">
            The filename for the output file. 
            This should be a fully qualified path to the file, or if a relative file path is used
            then the resolved path will be relative to the location of the executable running for 
            your process.
            If a relative file path is used this w
            </param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisResult.SerializeResultsToXml(System.IO.Stream)">
            <summary>
            Serializes the results in XML format to an output stream. For backwards compatibility 
            
            Only the problems discovered during analysis are output. No errors that occurred during
            the analysis process will be output. 
            </summary>
            <param name="output">
            An output stream to write the XML results to. This must support write
            </param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisResult.Problems">
            <summary>
            Any problems discovered by the rules run during code analysis
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisResult.AnalysisErrors">
            <summary>
            Errors and messages that occurred during analysis. 
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisResult.InitializationErrors">
            <summary>
            Gets errors that occurred during initialization of code analysis, rule lookup,
            and anything other than the analysis itself.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisResult.SuppressionErrors">
            <summary>
            Gets errors that occurred during calling of the message suppression routine.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisResult.AnalysisSucceeded">
            <summary>
            Was analysis completed successfully? Analysis may fail for a number of reasons, for instance
            if errors already exist in the model before processing.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService">
            <summary>
            A service that runs code analysis against a model and provides results to the caller.
             
            Note that this class is not thread-safe since multiple simulataneous calls to <see cref="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.Analyze(Microsoft.SqlServer.Dac.Model.TSqlModel)"/> are
            not supported. However it is possible to call <see cref="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.Cancel"/> from a thread while a separate thread is
            waiting on the <see cref="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.Analyze(Microsoft.SqlServer.Dac.Model.TSqlModel)"/> method to complete.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.GetRules">
            <summary>
            Gets the rules loaded by the service. The current state of these rules (enabled, disabled, rule problem severity)
            can be queried, as can information about the rule such as its ID and metadata. 
            </summary>
            <returns>
            list of <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor"/> objects representing rules discovered by the service, their metadata and status
            </returns>
            <remarks>To discover any problems loading rules, <see cref="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.GetRuleLoadErrors"/> should be called</remarks>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.GetRuleLoadErrors">
            <summary>
            Gets any errors that may have occurred during loading of the analysis rules.
            This causes rules to be loaded by the service.
            </summary>
            <returns>A list of errors that occurred during rule loading.</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.ApplyRuleSettings(Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings)">
            <summary>
            Applies the specified rule settings against the service's configuration. 
            </summary>
            <param name="settings"><see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings"/> describing which rules should be run</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.SetProblemSuppressor(System.Predicate{Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblemSuppressionContext})">
            <summary>
            Sets the problem suppression predicate to be applied when suppressing rules. 
            This is an optional feature that supports ignoring problems raised by a rule.
            The problem might be suppressed based on the element the problem was raised against, or the source 
            that the problem was found in. 
            </summary>
            <param name="shouldSuppressProblem">
            Predicate that should examine the suppression context and decide whether the problem needs to be suppressed
            </param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.Cancel">
            <summary>
            Cancels execution of the analysis service
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.Analyze(Microsoft.SqlServer.Dac.Model.TSqlModel)">
            <summary>
            Performs the analysis of the model. This will initialize all required resources, run analysis
            and report back results to the caller. 
            
            If the <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.ResultsFile"/> and/or <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.CodeAnalysisSucceededFile"/>
            are specified then these will be deleted at the start of the analysis, and new files created at the
            end of the analysis
            </summary>
            <param name="model">The <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> to be analyzed</param>
            <returns>
            <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisResult"/> describing the problems found and any errors that
            occurred during processing
            </returns>
            <exception cref="T:System.ArgumentNullException">If the <paramref name="model"/> is null</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.Execute">
            <summary>
            Main entry point for task execution.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.ExecuteValidateElementStatusStep">
            <summary>
            Ensure the model builds successfully - otherwise there is no point in continuing analysis
            since for SCA it's assumed that the model is valid already.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.ExecuteInitializeMessageSuppressionStep">
            <summary>
            Wrap whatever message suppression logic has been defined in a routine that will
            call into that code and catch any errors thrown by customer logic
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.SuppressProblemCallback(Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblemSuppressionContext)">
            <summary>
            Check if the rule in context is suppressed. Handles exceptions thrown by the problem suppression code
            so that execution does not get stopped due to issues in external code
            </summary>
            <param name="context"></param>
            <returns>Return true if rule is suppressed for modelElement; false otherwise</returns>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.ResultsFile">
            <summary>
            Optional path to a results file. If this is specified, the analysis service will save all results to
            an XML file at the end of analysis. If no file path is specified then this will not be done automatically,
            but <see cref="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisResult.SerializeResultsToXml(System.String)"/> can be used to output the results after
            analysis has completed.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.CodeAnalysisSucceededFile">
            <summary>
            Optional path to a file that is created if analysis succeeds. This can be used to check whether analysis
            should be run or not - for instance if analyzing a dacpac, comparing the modification time for the dacpac versus
            the analysis success file can tell you whether the dacpac is more recent than the last analysis.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.ValidationMode">
            <summary>
            Determines the validation performed on the model prior to code analysis. This can be used to bypass
            the requirement that a TSqlModel be valid prior to analysis by a code analysis rule.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.CancellationToken">
            <summary>
            The <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.CancellationToken"/> used to indicate whether execution should be canceled. 
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.IsCanceled">
            <summary>
            Gets a value that indicates whether the analysis was canceled
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisServiceFactory">
            <summary>
            Factory class that supports creation of <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService"/> objects.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisServiceFactory.CreateAnalysisService(Microsoft.SqlServer.Dac.Model.TSqlModel)">
            <summary>
            Creates an analysis service with the standard properties and all rules turned on by default.
            
            This is a convenience method that takes the <see cref="P:Microsoft.SqlServer.Dac.Model.TSqlModel.Version"/> from the model
            and passes it to the <see cref="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisServiceFactory.CreateAnalysisService(Microsoft.SqlServer.Dac.Model.SqlServerVersion)"/>
            method.
            </summary>
            <param name="model">
            The <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> that will be analyzed. The version of the model must be known at the
            time the service is created since only rules compatible with that <see cref="T:Microsoft.SqlServer.Dac.Model.SqlServerVersion"/>
            will be loaded and run.
            </param>
            <returns>
            A <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService"/> that can analyze the contents of the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/>
            </returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisServiceFactory.CreateAnalysisService(Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisServiceSettings)">
            <summary>
            Creates an analysis service and configures it using the <paramref name="settings"/> passed to the method.
            
            The settings are a convenient way to set up the service in one step, but if you wish to
            specify some settings after creating the service this is possible via methods and properties on
            the <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService"/> itself.
            
            This is a convenience method that takes the <see cref="P:Microsoft.SqlServer.Dac.Model.TSqlModel.Version"/> from the model
            and passes it to the <see cref="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisServiceFactory.CreateAnalysisService(Microsoft.SqlServer.Dac.Model.SqlServerVersion)"/>
            method.
            </summary>
            <param name="model">
            The <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> that will be analyzed. This must be known at the time the
            service is created since only rules compatible with the <see cref="T:Microsoft.SqlServer.Dac.Model.SqlServerVersion"/> for the model
            will be loaded and run.
            </param>
            <param name="settings">Settings object defining how to configure the service</param>
            <returns>A <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService"/> that can analyze the contents of the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisServiceFactory.CreateAnalysisService(Microsoft.SqlServer.Dac.Model.SqlServerVersion)">
            <summary>
            Creates an analysis service with the standard properties and all rules turned on by default.
            
            </summary>
            <param name="version">
            The expected <see cref="T:Microsoft.SqlServer.Dac.Model.SqlServerVersion"/> of models to be analyzed. This should be known at the time the
            service is created since only rules compatible with this <see cref="T:Microsoft.SqlServer.Dac.Model.SqlServerVersion"/> 
            will be loaded and run. 
            </param>
            <returns>
            A <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService"/> that can analyze the contents of the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/>
            </returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisServiceFactory.CreateAnalysisService(Microsoft.SqlServer.Dac.Model.SqlServerVersion,Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisServiceSettings)">
            <summary>
            Creates an analysis service and configures it using the <paramref name="settings"/> passed to the method.
            
            The settings are a convenient way to set up the service in one step, but if you wish to
            specify some settings after creating the service this is possible via methods and properties on
            the <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService"/> itself.
            </summary>
            <param name="version">
            The expected <see cref="T:Microsoft.SqlServer.Dac.Model.SqlServerVersion"/> of models to be analyzed. This must be known at the time the
            service is created since only rules compatible with this <see cref="T:Microsoft.SqlServer.Dac.Model.SqlServerVersion"/> 
            will be loaded and run. 
            </param>
            <param name="settings">Settings object defining how to configure the service</param>
            <returns>A <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService"/> that can analyze the contents of the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/></returns>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisServiceSettings">
            <summary>
            Defines the optional configuration settings for a <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService"/>. This can determine which
            rules are run, how to suppress certain problems, and where to save results to.
            
            These settings can also be set on the <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService"/> after it has been created, but are included
            here to make construction more convenient.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisServiceSettings.#ctor">
            <summary>
            Creates a new <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisServiceSettings"/> object.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisServiceSettings.RuleSettings">
            <summary>
            Optional rule settings define what rules should be run during analysis and the severity of the problems created. 
            If no <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings"/> are specified the default behavior is to run all discovered rules.
            
            This property is applied using <see cref="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.ApplyRuleSettings(Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings)"/>. 
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisServiceSettings.ShouldSuppressProblem">
            <summary>
            An optional predicate that can be used to suppress problems raised by rules during analysis.
            See <see cref="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.SetProblemSuppressor(System.Predicate{Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblemSuppressionContext})"/> for more information.
            
            This property is applied using <see cref="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.SetProblemSuppressor(System.Predicate{Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblemSuppressionContext})"/>. 
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisServiceSettings.ResultsFile">
            <summary>
            Optional path to a results file. If this is specified, the analysis service will save all results to
            an XML file at the end of analysis. If no file path is specified then this will not be done automatically,
            but <see cref="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisResult.SerializeResultsToXml(System.String)"/> can be used to output the results after
            analysis has completed.
            
            This property directly maps to <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.ResultsFile"/>.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisServiceSettings.CodeAnalysisSucceededFile">
            <summary>
            Optional path to a file that is created if analysis succeeds. This can be used to check whether analysis
            should be run or not - for instance if analyzing a dacpac, comparing the modification time for the dacpac versus
            the analysis success file can tell you whether the dacpac is more recent than the last analysis.
            
            This property directly maps to <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService.CodeAnalysisSucceededFile"/>.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisServiceSettings.ValidationMode">
            <summary>
            Determines the validation performed on the model prior to code analysis. This can be used to bypass
            the requirement that a TSqlModel be valid prior to analysis by a code analysis rule.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Internal.RuleUtils">
            <summary>
            Internal rule utilities that will never meet the conditions for sharing with the public via an open API
            or inclusion in a sample project
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Internal.RuleUtils.TryGetTSqlObject(Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.Data.Tools.Schema.Sql.SchemaModel.ISqlModelElement,Microsoft.SqlServer.Dac.Model.TSqlObject@)">
            <summary>
            Tries to map an internal element to a public element. 
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Internal.RuleUtils.GetSchemaObjectName(Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.Model.TSqlObject)">
            <summary>
            Get the schema object name in EscapedFullyQualifiedName format from an ISqlModelElement
            </summary>
            <param name="model"></param>
            <param name="element"></param>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Internal.RuleUtils.GetSchemaObjectName(Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.Model.ElementDescriptor)">
            <summary>
            Get the schema object name in EscapedFullyQualifiedName format from a Sql element Descriptor
            </summary>
            <param name="model"></param>
            <param name="elementDescriptor"></param>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Internal.RuleUtils.GetSchemaObjectName(Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.Model.ElementDescriptor,Microsoft.SqlServer.Dac.Model.ElementNameStyle)">
            <summary>
            Get the schema object name in user's choice of format from a Sql element Descriptor
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Internal.RuleUtils.GetSchemaObjectName(Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.Model.TSqlObject,Microsoft.SqlServer.Dac.Model.ElementNameStyle)">
            <summary>
            Get the schema object name in user's choice of format from an ISqlModelElement
            </summary> 
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.ProblemSuppressionException">
            <summary>
            Represents an exception that occurred when running the rule problem suppression test.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            <summary>
            Exception throw from DAC model errors.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.DacModelException.#ctor">
            <summary>
             Construct a new instance of the <see cref="T:Microsoft.SqlServer.Dac.Model.DacModelException"/> class.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.DacModelException.#ctor(System.String)">
            <summary>
            Construct a new instance of the <see cref="T:Microsoft.SqlServer.Dac.Model.DacModelException"/> class with the specified error message.
            </summary>
            <param name="message"></param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.DacModelException.#ctor(System.String,System.Exception)">
            <summary>
            Construct a new instance of the <see cref="T:Microsoft.SqlServer.Dac.Model.DacModelException"/> class with the specified error message
            and a reference to the inner exception that is the cause of this exception.
            </summary>
            <param name="message">
            The message that describes the error.
            </param>
            <param name="innerException">
            The exception that is the cause of the current exception, or a null reference if no inner exception is specified.
            </param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.DacModelException.#ctor(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext)">
             <summary>
            
             </summary>
             <param name="info"></param>
             <param name="context"></param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.DacModelException.GetObjectData(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext)">
            <summary>
            Write exception information to the supplied <see cref="T:System.Runtime.Serialization.SerializationInfo"/> object.
            </summary>
            <param name="info">
            <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data.
            </param>
            <param name="context">
            <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.
            </param>
            <exception cref="T:System.ArgumentNullException">
            If <paramref name="info"/> is a null reference.
            </exception>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelException.Messages">
            <summary>
            Get collection of additional error, warning, and informational messages associated with this exception.
            </summary>
            <value>
            Collection of additional messages associated with this exception.
            </value>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.ProblemSuppressionException.#ctor">
            <summary>
             Construct a new instance of the <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.ProblemSuppressionException"/> class.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.ProblemSuppressionException.#ctor(System.String)">
            <summary>
            Construct a new instance of the <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.ProblemSuppressionException"/> class with the specified error message.
            </summary>
            <param name="message"></param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.ProblemSuppressionException.#ctor(System.String,System.Exception)">
            <summary>
            Construct a new instance of the <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.ProblemSuppressionException"/> class with the specified error message
            and a reference to the inner exception that is the cause of this exception.
            </summary>
            <param name="message">
            The message that describes the error.
            </param>
            <param name="innerException">
            The exception that is the cause of the current exception, or a null reference if no inner exception is specified.
            </param>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.ProjectProblemSuppressor">
            <summary>
            Represents the problem suppressor used by SSDT projects. The <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.ProjectProblemSuppressor.ShouldSuppressProblem"/> method
            can be passed to <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisServiceSettings.ShouldSuppressProblem"/> in order to use this 
            class.
            
            This reads suppression information from a file with a name matching
            <see cref="F:Microsoft.SqlServer.Dac.CodeAnalysis.ProjectProblemSuppressor.SuppressionFilename"/> ("StaticCodeAnalysis.SuppressMessages.xml") in the root directory.
            
            All relative paths will be resolved relative to the project folder defined in the constructor
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.CodeAnalysis.ProjectProblemSuppressor.SuppressionFilename">
            <summary>
            The default file name for a message suppression file within a project.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.ProjectProblemSuppressor.CreateSuppressor(Microsoft.Data.Tools.Schema.Sql.RuleEngine.MessageSuppressionFileManager)">
            <summary>
            Internal factory method that creates a new <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.ProjectProblemSuppressor"/>.
            </summary>
            <param name="suppressionFileManager">
            The file manager to use for loading/saving suppression rules. 
            </param>
            <returns><see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.ProjectProblemSuppressor"/></returns>
            <exception cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.ProblemSuppressionException">
            Thrown if there was a problem parsing the XML
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.ProjectProblemSuppressor.CreateSuppressor(System.String)">
            <summary>
            Creates a new <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.ProjectProblemSuppressor"/>.
            </summary>
            <param name="projectFolder">
            The folder in which the XML Message suppression file is found. 
            Any rule suppressed using a relative file path will base the full path off
            this folder location. 
            </param>
            <returns><see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.ProjectProblemSuppressor"/> </returns>
            <exception cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.ProblemSuppressionException">
            Thrown if the Path to the XML file was invalid or if there was a problem parsing the XML
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.ProjectProblemSuppressor.CreateSuppressor(System.String,System.String)">
            <summary>
            Creates a new <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.ProjectProblemSuppressor"/>.
            </summary>
            <param name="projectFolder">
            The folder in which the XML Message suppression file is found. 
            Any rule suppressed using a relative file path will base the full path off
            this folder location. 
            </param>
            <param name="suppressionFilename">'
            The name of the XML message suppression file. This is expected to be under the project folder.
            </param>
            <returns><see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.ProjectProblemSuppressor"/> </returns>
            <exception cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.ProblemSuppressionException">
            Thrown if the Path to the XML file was invalid or if there was a problem parsing the XML
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.ProjectProblemSuppressor.ResetSuppressedProblems">
            <summary>
            Resets the suppressed problems to their default state. If an XML suppression file for the
            project existed already then the state will be reloaded from there, otherwise it will
            be reset so that no problems are suppressed.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.ProjectProblemSuppressor.UnsuppressRulesFromFile(System.String)">
            <summary>
            Removes all problem suppression directives for a particular filename.
            
            The updated set of problems to suppress will be immediately written out to the backing XML file that describes what
            rules should be suppressed for a given file. 
            </summary>
            <param name="fileName">path to the file</param>
            <exception cref="T:System.ArgumentNullException">If the <paramref name="fileName"/> is null</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.ProjectProblemSuppressor.GetSuppressedProblems">
            <summary>
            Gets information on what problems will be suppressed. Specifically, a set of
            <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.SuppressedProblemInfo"/> objects will be returned that defines each combination of a
            rule being suppressed and the file name for which the rule is suppressed.
            </summary>
            <returns>A list of <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.SuppressedProblemInfo"/> objects defining each combination of a
            rule being suppressed and the file name for which the rule is suppressed</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.ProjectProblemSuppressor.AddSuppressedProblems(System.Collections.Generic.IEnumerable{Microsoft.SqlServer.Dac.CodeAnalysis.SuppressedProblemInfo})">
            <summary>
            Adds one or more instances of <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.SuppressedProblemInfo"/> to the set of suppressed problems.
            The full set of suppressed problems will be immediately written out to the backing XML file.
            </summary>
            <param name="suppressedProblems">
            An IEnumerable of <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.SuppressedProblemInfo"/> objects defining each combination of a 
            file for which some problems should be suppressed, and the specific rule whose problems should be
            suppressed.
            </param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.ProjectProblemSuppressor.ShouldSuppressProblem">
            <summary>
            Gets the predicate that can be used to
            
            If any errors occur during
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor">
            <summary>
            Describes a rule discovered by the rule engine and supports configuration of its properties.
            Descriptors inherit properties from <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration"/>, to support enabling/disabling the rule during
            analysis and specifying the severity for problems created by the rule. 
            
            This class is not intended to be subclasses by external users - instances of <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor"/> are created
            by the analysis service.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration">
            <summary>
            Specifies how a rule should be configured - should this be enabled or disabled? What severity should be applied
            for the rule?
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration.#ctor(System.String)">
            <summary>
            Creates a new <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration"/> for a rule, using the default settings for <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration.Enabled"/>
            and <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration.Severity"/>.
            </summary>
            <param name="ruleId">ID of the rule this configuration specifies. Cannot be null or whitespace.</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration.#ctor(System.String,System.Boolean,Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblemSeverity)">
            <summary>
            Creates a new <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration"/> for a rule.
            </summary>
            <param name="ruleId">ID of the rule this configuration specifies. Cannot be null or whitespace.</param>
            <param name="enabled">Is this rule enabled or disabled?</param>
            <param name="severity">What is the severity of problems identified by this rule? Should be either 
            <see cref="F:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblemSeverity.Warning"/> or <see cref="F:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblemSeverity.Error"/>.</param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration.RuleId">
            <summary>
            Gets the unique Id used to identify the rule. This is the fully qualified ID, which would usually be
            in the form "My.Org.MyRuleName".
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration.Namespace">
            <summary>
            Gets the namespace for the rule. This is the part of the rule that precedes the final "." in the ID name.
            For instance for a rule ID "My.Org.MyRuleName", the namespace would be "My.Org".
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration.ShortRuleId">
            <summary>
            Gets the last part of the rule ID. This is the part of the rule that follows the final "." in the ID name.
            For instance for a rule ID "My.Org.MyRuleName", the short rule ID would be "MyRuleName".
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration.Enabled">
            <summary>
            Specifies if the rule is enabled and should be included in the code analysis.
            
            The default value is true
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration.Severity">
            <summary>
            What severity should problems created by the rule have?
            
            The default severity is <see cref="F:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblemSeverity.Warning"/>
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor.#ctor(System.String)">
            <summary>
            Protected constructor to be called by implementing classes.
            </summary>
            <param name="ruleId">ID of the rule being described</param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor.DisplayDescription">
            <summary>
            The description of the rule. This should be a short human readable description of what the
            rule is intended to warn against or block.
            
            This is automatically read from the <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor.Metadata"/> property
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor.DisplayName">
            <summary>
            Display name describing the rule.
            
            This is automatically read from the <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor.Metadata"/> property
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor.Rule">
            <summary>
            The actual instance of the <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.SqlAnalysisRule"/>
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor.Metadata">
            <summary>
            The <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.ISqlAnalysisRuleMetadata"/> describing the rule.
            This is a required property that must be defined by subclasses.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings">
            <summary>
            The settings used to configure rules used during analysis. 
            
            Before analysis begins, this settings object will be applied to the rules discovered 
            by the analysis service. If DisableRulesNotInSettings is set to true then any rules 
            not included in these settings will be disabled and not run during analysis. 
            
            These settings are applied by calling the <see cref="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings.ApplySettingsToRules(System.Collections.Generic.IEnumerable{Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration})"/> method
            on rules returned by the engine.
            
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings.#ctor">
            <summary>
            Creates a new <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings"/> object.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings.#ctor(System.Collections.Generic.IEnumerable{Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration})">
            <summary>
            Creates a new <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings"/> containing a set of rules.
            </summary>
            <param name="rules">The rules to include</param>
            <exception cref="T:System.ArgumentNullException">If <paramref name="rules"/> is null</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings.CreateFromSettingsString(System.String,System.Collections.Generic.IList{Microsoft.SqlServer.Dac.Extensibility.ExtensibilityError}@)">
            <summary>
            Creates a <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings"/> configuration based on a settings string like the one used
            inside SSDT project files. This string defines what rules should be disabled or have their problems treated as
            errors instead of warnings. Any rule not included in the settings string will be enabled by default.
            </summary>
            <param name="settingsString">
            A semicolon delimited string identifying rules to be disabled or have problems treated as errors.
            The format is "-My.Disabled.Rule;+!My.Enabled.RuleWithError;-!My.Disabled.RuleWithError". Hence disabled rules should have "-" 
            before their ID and enabled rules with errors should have "+!" before their ID. 
            Only rules that are to be disabled or have their problems treated as errors should be included in the settings string.
            
            If this parameter is null or contains no valid rules, a default empty configuration will be returned. This will result in all
            discovered rules being run.
            </param>
            <param name="errors">List of errors found when processing the list.</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings.ConvertToSettingsString">
            <summary>
            Converts the rule configuration info in this <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings"/> object into a
            settings string like the one used
            inside SSDT project files. This string defines what rules should be disabled or have their problems treated as
            errors instead of warnings. Any rule not included in the settings string will be enabled by default.
            </summary>
            <returns>
            A semicolon delimited string identifying rules to be disabled or have problems treated as errors.
            The format is "-My.Disabled.Rule;+!My.Enabled.RuleWithError;-!My.Disabled.RuleWithError". Hence disabled rules have "-" 
            before their ID and enabled rules with errors have "+!" before their ID. 
            Only rules that are to be disabled or have their problems treated as errors should be included in the settings string.
            </returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings.AddRange(System.Collections.Generic.IEnumerable{Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration})">
            <summary>
            Adds multiple <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration"/> objects to the list of rules
            </summary>
            <param name="rules">The rules to include</param>
            <exception cref="T:System.ArgumentNullException">If <paramref name="rules"/> is null</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings.Add(Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration)">
            <summary>
            Adds a new <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration"/> object to the list of rules
            </summary>
            <param name="item">item to be added</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings.Remove(Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration)">
            <summary>
            Removes a <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration"/> object from the list of rules.
            </summary>
            <param name="item">item to be removed</param>
            <returns>true if the item was successfully removed</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings.GetEnumerator">
            <summary>
            <see cref="M:System.Collections.IEnumerable.GetEnumerator"/>
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings.FindConfiguration(System.String)">
            <summary>
            Tries to find the <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration"/> that matches the specified
            <paramref name="ruleId"/>. If the configuration doesn't exist then null will be returned
            </summary>
            <param name="ruleId">The fully qualified rule ID</param>
            <returns><see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration"/>, or null if none matches the <paramref name="ruleId"/></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings.TryGetRuleConfiguration(System.String,Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration@)">
            <summary>
            Tries to find the <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration"/> that matches the specified
            <paramref name="ruleId"/>.  
            </summary>
            <param name="ruleId">The fully qualified rule ID</param>
            <param name="config">out <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration"/>, or null if none matches the <paramref name="ruleId"/></param>
            <returns>true if a configuration matching the specified <paramref name="ruleId"/> was found, false otherwise</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings.ApplySettingsToRules(System.Collections.Generic.IEnumerable{Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration})">
            <summary>
            Applies these settings to another set of rules.
            </summary>
            <param name="rules">The rules the settings should be applied to</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings.EnableRule(System.String)">
            <summary>
            Includes a rule for execution
            </summary>
            <param name="ruleId">Fully qualified Id for the rule</param>
            <exception cref="T:System.ArgumentException">If the <paramref name="ruleId"/> is null or whitespace</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings.DisableRule(System.String)">
            <summary>
            Excludes a rule from execution
            </summary>
            <param name="ruleId">Fully qualified Id for the rule</param>
            <exception cref="T:System.ArgumentException">If the <paramref name="ruleId"/> is null or whitespace</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings.TreatRuleProblemAsWarning(System.String)">
            <summary>
            Treat any problems found a rule as warnings
            </summary>
            <param name="ruleId">Fully qualified Id for the rule</param>
            <exception cref="T:System.ArgumentException">If the <paramref name="ruleId"/> is null or whitespace</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings.TreatRuleProblemAsError(System.String)">
            <summary>
            Treat any problems found a rule as errors
            </summary>
            <param name="ruleId">Fully qualified Id for the rule</param>
            <exception cref="T:System.ArgumentException">If the <paramref name="ruleId"/> is null or whitespace</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings.IsRuleDisabled(System.String)">
            <summary>
            Is a particular rule in the rule settings disabled?
            </summary>
            <param name="ruleId">Fully qualified Id for the rule</param>
            <returns>true if the problem is disabled; false otherwise</returns>
            <exception cref="T:System.ArgumentException">If the <paramref name="ruleId"/> is null or whitespace</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings.IsRuleProblemTreatedAsError(System.String)">
            <summary>
            Is a particular rule in the rule settings treated as error?
            </summary>
            <param name="ruleId">Fully qualified Id for the rule</param>
            <returns>true if the problem is treated as error; false otherwise</returns>
            <exception cref="T:System.ArgumentException">If the <paramref name="ruleId"/> is null or whitespace</exception>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisRuleSettings.DisableRulesNotInSettings">
            <summary>
            Should rules not found in these settings be disabled? The default is "false", so that
            any rules not explicitly covered in the settings will still be run during analysis. 
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleException">
            <summary>
            Represent an exception that may occur during a code analysis run
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.RuleException.#ctor">
            <summary>
            Initialize a new instance of <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleException"/> 
            Exception message and inner exceptions are set to null
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.RuleException.#ctor(System.String)">
            <summary>
            Initialize a new instance of <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleException"/>  with a message
            </summary>
            <param name="message">Exception message</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.RuleException.#ctor(System.String,System.Exception)">
            <summary>
            Initialize a new instance of <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleException"/> with a message and an inner exception
            </summary>
            <param name="message">Exception message</param>
            <param name="innerException">Inner exception to attached to this exception</param>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.CommonUtilities.ElementNameAstLocatorSchemaAnalyzer">
            <summary>
            The class to locate the accurate AST that defines the name for a model element
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer">
            <summary>
            The base class that defines analysis events. 
            
            This analyzer works against the <see cref="T:Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment"/>s that represent 
            the exact DDL language describing an object.
            
            This makes it easier to examine the actual script/fragment structure that represents 
            an object.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer.BeginBatch(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlBatch)">
            <summary>
            This method handles pre-batchprocessing
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer.EndBatch(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlBatch)">
            <summary>
            This method handles post-batchprocessing
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer.BeginDdlStatement(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment)">
            <summary>
            This method handles pre-DDL statement processing 
            </summary>
            <param name="fragment">Node that will be processed</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer.EndDdlStatement(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment)">
            <summary>
            This method handles post-DDL statement processing
            </summary>
            <param name="fragment">Node that was processed</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer.IdentifiedElement(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment,Microsoft.SqlServer.Dac.Model.ElementDescriptor)">
            <summary>
            This method handles the discovery of a new Symbol
            </summary>
            <param name="fragment">Fragment the symbol belongs to</param>
            <param name="elementDescriptor">The element descriptor</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer.BeginDmlStatement(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment)">
            <summary>
            This method handles the pre-DML statement processing
            </summary>
            <param name="fragment">Node that will be processed</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer.EndDmlStatement(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment)">
            <summary>
            This method handles the post-DML statement processing
            </summary>
            <param name="fragment">Node that will be processed</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer.VisitFragment(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment,Microsoft.SqlServer.Dac.Model.ElementDescriptor,Microsoft.SqlServer.Dac.Model.ElementDescriptorRelevance)">
            <summary>
            This method handles additional processing required for a node/schemaidentifier
            </summary>
            <param name="fragment">Node to be processed</param>
            <param name="elementDescriptor">Descriptor to be processed</param>
            <param name="relevance">Relevance</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer.VisitAmbiguousFragment(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment,System.Collections.Generic.IEnumerable{Microsoft.SqlServer.Dac.Model.PotentialElementDescriptor})">
            <summary>
            This method handles additional processing required for a node/schemaidentifier
            </summary>
            <param name="fragment">Node to be processed</param>
            <param name="possibilities">An enumerable of possible hits</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer.IdentifiedSupportingStatement(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment,Microsoft.SqlServer.Dac.Model.ElementDescriptor)">
            <summary>
            This method handles the discovery of a new supporting statement
            </summary>
            <param name="fragment">Node to be processed</param>
            <param name="elementDescriptor"></param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer.AnalyzeScript(Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment)">
            <summary>
            Runs the schema analysis against a fragment
            </summary>
            <param name="model"><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> the fragment is linked to</param>
            <param name="sqlFragment">the fragment to analyze</param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.CommonUtilities.ElementNameAstLocatorSchemaAnalyzer.NameAstNode">
            <summary>
            The TSqlFragment referring to the name of the element
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.CommonUtilities.ElementNameAstLocatorSchemaAnalyzer.ElementAstNode">
            <summary>
            The TSqlFragment referring to the element itself
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.SqlCodeAnalysisRule">
            <summary>
            Base class for SQL static code analysis rules. An analysis rule analyzes a model / model element and returns a list of
            problems found during analysis.
            
            Implementing classes must have a <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.ExportCodeAnalysisRuleAttribute"/> defined on the
            class definition to be discovered and used during code analysis. 
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.SqlAnalysisRule">
            <summary>
            Base class for all types of analysis rule. An analysis rule analyzes a model / model element and returns a list of
            problems found during analysis. 
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.SqlAnalysisRule.Analyze(Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleExecutionContext)">
            <summary>
            Performs analysis and returns a list of problems detected
            </summary>
            <param name="ruleExecutionContext">Contains the schema model and model element to analyze</param>
            <returns>The problems detected by the rule in the given element</returns>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlAnalysisRule.SupportedElementTypes">
            <summary>
            Types of elements checked by this rule. Required if the rule scope is <see cref="F:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleScope.Element"/>,
            for <see cref="F:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleScope.Model"/> scoped rules this is not relevant
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.DataTypeCompatibilityRule.Analyze(Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleExecutionContext)">
            <summary>
            perform actual analysis
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleSchemaAnalyzer">
            <summary>
            A type of <see cref="T:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer"/> that can be used by code analysis 
            rules to examine the internal structure of a <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>.
            This analyzer works against the <see cref="T:Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment"/>s that represents 
            the exact DDL language describing an object.
            
            This makes it easier to examine the actual script/fragment structure that represents an object.
            </summary>
            <remarks>
            For some data sources such as dacpacs, the backing script and <see cref="T:Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment"/>s 
            will be auto-generated by DacFx. Any analyzer that tries to enforce stylistic rules such as
            blocking the use of brackets to escape object names should be disabled when running against 
            those sources - they would be raising issues about the default DacFx style conventions rather
            than the actual code contents of a project.
            </remarks>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.RuleSchemaAnalyzer.#ctor(Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor,Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.Model.TSqlObject)">
            <summary>
            Creates a <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleSchemaAnalyzer"/> that helps analyze an element on behalf of a rule
            </summary>
            <param name="rule">
            <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor"/> defining a rule and its metadata properties.
            This can be used to get the description for a rule and add it to any <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem"/>, among other things
            being created, or query any other metadata information about the rule
            </param>
            <param name="schemaModel">The <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> being analyzed</param>
            <param name="element">A specific <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> whose backing <see cref="T:Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment"/>
            is to be analyzed</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.RuleSchemaAnalyzer.BeginBatch(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlBatch)">
            <summary>
            <see cref="M:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer.BeginBatch(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlBatch)"/>
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.RuleSchemaAnalyzer.EndBatch(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlBatch)">
            <summary>
            <see cref="M:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer.EndBatch(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlBatch)"/>
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.RuleSchemaAnalyzer.BeginDmlStatement(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment)">
            <summary>
            <see cref="M:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer.BeginDmlStatement(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment)"/>
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.RuleSchemaAnalyzer.EndDmlStatement(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment)">
            <summary>
            <see cref="M:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer.EndDmlStatement(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment)"/>
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.RuleSchemaAnalyzer.BeginDdlStatement(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment)">
            <summary>
            <see cref="M:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer.BeginDdlStatement(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment)"/>
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.RuleSchemaAnalyzer.EndDdlStatement(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment)">
            <summary>
            <see cref="M:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer.EndDdlStatement(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment)"/>
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.RuleSchemaAnalyzer.IdentifiedElement(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment,Microsoft.SqlServer.Dac.Model.ElementDescriptor)">
            <summary>
            <see cref="M:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer.IdentifiedElement(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment,Microsoft.SqlServer.Dac.Model.ElementDescriptor)"/>
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.RuleSchemaAnalyzer.VisitFragment(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment,Microsoft.SqlServer.Dac.Model.ElementDescriptor,Microsoft.SqlServer.Dac.Model.ElementDescriptorRelevance)">
            <summary>
            <see cref="M:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer.VisitFragment(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment,Microsoft.SqlServer.Dac.Model.ElementDescriptor,Microsoft.SqlServer.Dac.Model.ElementDescriptorRelevance)"/>
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.RuleSchemaAnalyzer.VisitAmbiguousFragment(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment,System.Collections.Generic.IEnumerable{Microsoft.SqlServer.Dac.Model.PotentialElementDescriptor})">
            <summary>
            <see cref="M:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer.VisitAmbiguousFragment(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment,System.Collections.Generic.IEnumerable{Microsoft.SqlServer.Dac.Model.PotentialElementDescriptor})"/>
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.RuleSchemaAnalyzer.AnalyzeScriptForSqlRule(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment,System.Collections.Generic.List{Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem})">
            <summary>
            Runs rule analysis against a fragment and adds any problems found to the 
            <paramref name="problems"/> list.
            </summary>
            <param name="sqlFragment">A fragment whose contents should be analyzed</param>
            <param name="problems">Problems found by the analyzer are added to this list</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.RuleSchemaAnalyzer.TryGetModelElementFromPossibilities(System.Collections.Generic.IEnumerable{Microsoft.SqlServer.Dac.Model.PotentialElementDescriptor},Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.Model.TSqlObject@,Microsoft.SqlServer.Dac.Model.ElementDescriptor@,Microsoft.SqlServer.Dac.Model.ElementDescriptorRelevance@)">
            <summary>
            Tries to determine the correct model element from a set of possible matching element descriptors.
            </summary>
            <param name="possibilities">Descriptors for  </param>
            <param name="model">The <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/></param>
            <param name="element">out <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> that matches the best possibility, or null if lookup failed</param>
            <param name="elementDescriptor">out <see cref="T:Microsoft.SqlServer.Dac.Model.ElementDescriptor"/> for the element that was matched, or
            null if the lookup failed</param>
            <param name="relevance">out <see cref="T:Microsoft.SqlServer.Dac.Model.ElementDescriptorRelevance"/> describing the relavance of the 
            <paramref name="elementDescriptor"/> to the <paramref name="element"/></param>
            <returns>true if the lookup succeeded</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.RuleSchemaAnalyzer.AddProblem(Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem)">
            <summary>
            add a problem found by the current analyzer
            </summary>
            <param name="problem"></param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.RuleSchemaAnalyzer.ClearProblems">
            <summary>
            clean up all the problems
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.RuleSchemaAnalyzer.DebugWriteLine(System.String)">
            <summary>
            Print a message to debug window in Debug mode
            </summary>
            <param name="msg"></param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.RuleSchemaAnalyzer.Problems">
            <summary>
            Get all problems identified by this analyzer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.RuleSchemaAnalyzer.SchemaModel">
            <summary>
            get the SQL schema manager used by the current analyzer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.RuleSchemaAnalyzer.Rule">
            <summary>
            Get the the rule associated with the current analyzer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.RuleSchemaAnalyzer.ModelElement">
            <summary>
            Get the element for which the current analyzer works
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.DataTypeCompatibilitySchemaAnalyzer.#ctor(Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor,Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.Model.TSqlObject)">
            <summary>
            constructor
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.TypeCompatibilityChecker">
            <summary>
            Note: This class relies on internal code that is shared with the internal validation rules. In order to minimize code 
            reuse and avoid unnecessarily duplicating code, some parts of this class directly use and call into the internal model.
            This is viewed as acceptable as upgrading to the public API isn't really necessary and would not provide significant
            benefits to external users.
            
            In addition, some internal objects such as dynamic column sources cannot be mapped to the public model and hence
            it is necessary to use the internal object model in cases where those objects might have issues
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.TypeCompatibilityChecker.CollectLocalColumnDefinitions(System.Collections.Generic.Dictionary{Microsoft.SqlServer.Dac.Model.ElementDescriptor,Microsoft.SqlServer.TransactSql.ScriptDom.ColumnDefinition})">
            <summary>
            convert TSql.DataType to TSqlDataTypeInfo
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.TypeCompatibilityChecker.CheckVariableAssignment(Microsoft.SqlServer.TransactSql.ScriptDom.VariableReference,Microsoft.Data.Tools.Schema.Sql.Common.TypeEvaluator.TSqlDataTypeInfo,Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment)">
            <summary>
            This method is used to check variable assignment from proc/function return value to a variable
            Use this if you know the type of proc/function return value
            </summary>
            <param name="variable"></param>
            <param name="fromDataType"></param>
            <param name="fragmentToReport"></param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.TypeCompatibilityChecker.CheckAssignmentSetClause(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment)">
            <summary>
            we currently support
              column_name = expression, 
              @variable = expression, and
              @variable = column = expression  
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.TypeCompatibilityChecker.CollectParameterInfo(Microsoft.SqlServer.Dac.Model.TSqlObject,System.Collections.Generic.IList{Microsoft.SqlServer.TransactSql.ScriptDom.ExecuteParameter},Microsoft.SqlServer.Dac.Model.ModelCollationComparer,System.Collections.Generic.Dictionary{System.String,Microsoft.Data.Tools.Schema.Sql.Common.TypeEvaluator.TSqlDataTypeInfo}@,System.Collections.ObjectModel.ReadOnlyCollection{Microsoft.Data.Tools.Schema.Sql.SchemaModel.ParameterValueInfo}@)">
            <summary>
            Return a dictionary with parameter name key and type info value
            Return a list of parameter value info that is resolved using parameters from subroutine and execute statement
            </summary>
            <param name="subroutine"></param>
            <param name="executeParameterList"></param>
            <param name="comparer"></param>
            <param name="parameterNameToTypeMap"></param>
            <param name="parameterValueInfo"></param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.TypeCompatibilityChecker.TryGetParameters(Microsoft.SqlServer.Dac.Model.TSqlObject,System.Collections.Generic.IEnumerable{Microsoft.SqlServer.Dac.Model.TSqlObject}@)">
            <summary>
            All object types that match a subroutine are expected to have a "Parameters" relationship which we can read.
            We look up the relationship class dynamically since it will vary between Procedures, ScalarFunctions and other
            types
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.TypeCompatibilityChecker.TryGetReturnType(Microsoft.SqlServer.Dac.Model.TSqlObject,Microsoft.Data.Tools.Schema.Sql.Common.TypeEvaluator.TSqlDataTypeInfo@)">
            <summary>
            Attempts to look up the return type for a function
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.TypeCompatibilityChecker.GetTypeInfoForInsertTarget(Microsoft.SqlServer.TransactSql.ScriptDom.InsertStatement)">
            <summary>
            Must use the internal model here since dynamic object column sources aren't modelable in the public model,
            and this is a situation where those appear.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.TypeCompatibilityChecker.GetTypeInfoForAllColumnsOfTable(Microsoft.Data.Tools.Schema.SchemaModel.IModelElement)">
            <summary>
            This method heavily uses the internal implementation - again this whole class struggles to use the
            public model
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.TypeCompatibilityChecker.GetTypeInfoForColumn(Microsoft.SqlServer.Dac.Model.ElementDescriptor)">
            <summary>
            Note: This method uses internal methods
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.TypeCompatibilityChecker.GetTypeInfoForUdtUddt(Microsoft.SqlServer.Dac.Model.ElementDescriptor)">
            <summary>
            get TSqlDataTypeInfo for the acutal data type of a UDT and UDDT based on its 
            SqlElementDescriptor.
            </summary>
            <param name="uddtDescriptor">ElementDescriptor for the UDDT or UDT</param>
            <returns>actual data type if found, null otherwise</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.TypeCompatibilityChecker.TryGetFunctionDefinition(Microsoft.SqlServer.TransactSql.ScriptDom.FunctionCall,Microsoft.SqlServer.TransactSql.ScriptDom.FunctionStatementBody@,System.Collections.Generic.List{Microsoft.Data.Tools.Schema.Sql.Common.TypeEvaluator.TSqlDataTypeInfo}@)">
            <summary>
            Again we've failed to fully use the public model in this method, if this can be reviewed
            at a future date then perhaps this can be fixed.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.TypeCompatibilityChecker.IsAScalarModule(Microsoft.SqlServer.Dac.Model.ElementDescriptor)">
            <summary>
            Verifies a descriptor is a type of scalar module (ScalarFunctions and Aggregates count as this) 
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.TypeCompatibilityChecker.GetTypeInfoForSequenceName(Microsoft.SqlServer.TransactSql.ScriptDom.SchemaObjectName)">
            <summary>
            This method heavily uses the internal implementation - again this whole class struggles to use the
            public model
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.IdentitySchemaAnalyzer">
            <summary>
            The SchemaAnalyzer checks for the usages of system function @@IDENTITY
            and reports its possibe misuse.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.IdentitySchemaAnalyzer.#ctor(Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor,Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.Model.TSqlObject)">
            <summary>
            Constructor with SqlAnalysisRule, SqlSchemaModel, and ISqlModelElement provided
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.OldStyleJoinSyntaxAnalysisRule.Analyze(Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleExecutionContext)">
            <summary>
            perform actual analysis
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.OldStyleJoinSyntaxSchemaAnalyzer.#ctor(Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor,Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.Model.TSqlObject)">
            <summary>
            constructor
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.PopulateOutputParametersRule.Analyze(Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleExecutionContext)">
            <summary>
            perform actual analysis
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.PopulateOutputParametersSchemaAnalyzer.#ctor(Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor,Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.Model.TSqlObject)">
            <summary>
            constructor
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.SelectAsteriskSchemaAnalyzer.#ctor(Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor,Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.Model.TSqlObject)">
            <summary>
            Creates a new <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.SelectAsteriskSchemaAnalyzer"/> to analyze a particular element in the model.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.SmallVariableLengthTypesRule">
            <summary>
            This rule checks if a small length (less than three) is used for variable-length types, 
            which include VARCHAR, NVARCHAR, and VARBINARY
            Such data types can be used in various scenarios:
                column of regular tables
                column of temporary tables
                column of common table expressions
                subroutine parameter 
                variable
                scalar function return type
                user defined data types
                
            TODO, yangg: we currently dont' handle temporary table columns, cte columns, and variables, 
                         since interpretation is not ready yet
            
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Design.SmallVariableLengthTypesRule.Analyze(Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleExecutionContext)">
            <summary>
            perform actual analysis
            </summary> 
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Naming.ReservedWordsForTypeNameAnalysisRule.Analyze(Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleExecutionContext)">
            <summary>
            perform actual analysis
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Naming.ReservedWordsForTypeNameSchemaAnalyzer.#ctor(Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor,Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.Model.TSqlObject)">
            <summary>
            Constructor with comparison manager 
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Naming.SpecialCharactersInObjectNameRule.DynamicObjectsLookup">
            <summary>
            Provides getters for the types that need to access dynamic objects - there's no clean way to do this.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Naming.SpecialCharactersInObjectNameRule.ProcessBodyScriptElements(Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.Model.TSqlObject,System.Collections.Generic.IList{Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem})">
            <summary>
            A subset of top-level types such as Procedures have a body script containing
            dynamic objects. We don't want to miss flagging errors in these, but these
            aren't accessible via the public model. To work around this we use the internal
            model implementation for this work
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Naming.SpPrefixForStoredProceduresRule.Analyze(Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleExecutionContext)">
            <summary>
            perform actual analysis
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Performance.ExtractDeterministicFunctionCallRule.Analyze(Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleExecutionContext)">
            <summary>
            perform actual analysis
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Performance.ExtractDeterministicFunctionCallSchemaAnalyzer.#ctor(Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor,Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.Model.TSqlObject)">
            <summary>
            constructor
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Performance.LikePercentRule">
            <summary>
            The base rule for checking LikePredicate, we suggest using "m%" instead of "%m".
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Performance.LikePercentRule.Analyze(Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleExecutionContext)">
            <summary>
            perform actual analysis
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Performance.LikePercentSchemaAnalyzer">
            <summary>
            This rule checks whether the patterns of the LIKE predicate from WHERE clauses start
            with "%" while match expression is a column, which can cause a table scan and degrade
            performance
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Performance.LikePercentSchemaAnalyzer.#ctor(Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor,Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.Model.TSqlObject)">
            <summary>
            constructor
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Performance.ColumnInsideExpressionChecker">
            <summary>
            the class is to find out all the columns participating in an expression but not part of function call or ISNULL
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Performance.MoveColumnToOneSideRule.Analyze(Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleExecutionContext)">
            <summary>
            perform actual analysis
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Performance.MoveColumnToOneSideSchemaAnalyzer">
            <summary>
            This rule suggests moving columns to one side of en expression in the WHERE clause, 
            thus to avoid table scan. 
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Performance.MoveColumnToOneSideSchemaAnalyzer.#ctor(Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor,Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.Model.TSqlObject)">
            <summary>
            constructor
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Performance.NonIndexedColumnFromInPredicateRule">
            <summary>
            When we see an In Predicate, we want to check whether there is Table Index
            that it could use to boost the performance. If not, we give a warning. This
            is because In Predicate is executed by a Table Scan instead of Index Seek, which
            hugely slows down the SQL query performance.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Performance.NonIndexedColumnFromInPredicateRule.Analyze(Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleExecutionContext)">
            <summary>
            perform actual analysis
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Performance.NonIndexedColumnFromInPredicateSchemaAnalyzer">
            <summary>
            This checks whether a column test expression of the IN predicate has an
            index or not. If it does not, the evaluation of the predicate can cause
            a table scan and degrade the performance.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Performance.NonIndexedColumnFromInPredicateSchemaAnalyzer.#ctor(Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor,Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.Model.TSqlObject)">
            <summary>
            constructor
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Performance.NonIndexedColumnFromInPredicateSchemaAnalyzer.ColumnHasIndex(Microsoft.SqlServer.Dac.Model.TSqlObject)">
            <summary>
            Check whether the specified column has index or not.
            </summary>
            <returns>true when the column has index; false, otherwise</returns>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Performance.CheckNullableColumnHelper">
            <summary>
            the class is to check whether a nullable column exists in an expression
            other than ISNULL function and IS NULL / IS NOT NULL operators
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Performance.NullableColumnRule">
            <summary>
            The base rule for Nullable Column Performance Rule.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Performance.NullableColumnRule.Analyze(Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleExecutionContext)">
            <summary>
            perform actual analysis
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.Performance.NullableColumnSchemaAnalyzer">
            <summary>
            This rule is to find out all the nullable columns used in WHERE predicates which
            do not act as operands of IS NULL / IS NOT NULL or arguments of ISNULL function
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.ExportCodeAnalysisRuleAttribute">
            <summary>
            Attribute defining a rule export, and the metadata about that rule. Implements ISqlAnalysisRuleMetadata,
            which should be used on the importer side to ensure type consistency
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.ISqlAnalysisRuleMetadata">
            <summary>
            The metadata describing a rule - its namespace, id, scope etc.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.ISqlAnalysisRuleMetadata.Description">
            <summary>
            The description of the rule. This should be a short human readable description of what the
            rule is intended to warn against or block.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.ISqlAnalysisRuleMetadata.RuleScope">
            <summary>
            The scope of this rule. Choose between <see cref="F:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleScope.Element"/> and <see cref="F:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleScope.Model"/>.
            Note that for element scoped rules, the <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlAnalysisRule.SupportedElementTypes"/> property must return
            one or more element types that can are supported for analysis by the rule
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.ISqlAnalysisRuleMetadata.Category">
            <summary>
            (Optional) Category used to group the rule in Visual Studio UI. This should never be localized
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.ExportCodeAnalysisRuleAttribute.#ctor(System.String,System.String)">
            <summary>
            Constructor
            </summary>
            <param name="id">Unique ID used to identify this rule. Required parameter, rule will not load if this is missing or empty</param>
            <param name="displayName">Display name to show in the Visual Studio UI. Required parameter, rule will not load if this is missing or empty</param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.ExportCodeAnalysisRuleAttribute.Description">
            <summary>
            The description of the rule. This should be a short human readable description of what the
            rule is intended to warn against or block. This field is localizable, but this should be done
            be subclassing <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.ExportCodeAnalysisRuleAttribute"/> and overriding the Description property. 
            </summary>
            <example>
            <code>
            // Example of an Attribute class that supports localized descriptions:
            public class TestLocalizedExportCodeAnalysisRuleAttribute : ExportCodeAnalysisRuleAttribute
            {
                private readonly string _descriptionResourceName;
                private string _descriptionValue;
            
                public TestLocalizedExportCodeAnalysisRuleAttribute(string id, string displayName, string descriptionResourceName)
                    : base(id, displayName)
                {
                    _descriptionResourceName = descriptionResourceName;
                }
            
                public override string Description
                {
                    get
                    {
                        if (_descriptionValue == null)
                        {
                            // Using the descriptionResourceName as the key for looking up the description in the resources file. 
                            // MyResources is a resource file in the same project as the LocalizedExportCodeAnalysisRuleAttribute class. 
                            // For each rule, and entry should be added to the resources file with the descriptionResourceName as the
                            // key and the description as the value
                            _descriptionValue = MyResources.ResourceManager.GetString(_descriptionResourceName);
                        }
                        return _descriptionValue;
                    }
                }
            }
            </code>
            </example>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.ExportCodeAnalysisRuleAttribute.RuleScope">
            <summary>
            <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.ISqlAnalysisRuleMetadata.RuleScope"/>
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.ExportCodeAnalysisRuleAttribute.Category">
            <summary>
            <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.ISqlAnalysisRuleMetadata.Category"/>
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.LocalizedExportCodeAnalysisRuleAttribute.GetAssembly">
            <summary>
            Rules in a different assembly would need to overwrite this
            </summary>
            <returns></returns>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString">
            <summary>
              A strongly-typed resource class, for looking up localized strings, etc.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.ResourceManager">
            <summary>
              Returns the cached ResourceManager instance used by this class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.Culture">
            <summary>
              Overrides the current thread's CurrentUICulture property for all
              resource lookups using this strongly typed resource class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.DataTypeCompatibility_ProblemDescription">
            <summary>
              Looks up a localized string similar to Data types of {0}({1}) and {2}({3}) are incompatible..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.DataTypeCompatibility_ProblemDescription_CompatibleCasting">
            <summary>
              Looks up a localized string similar to Expression is cast from {0} to {1}..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.DataTypeCompatibility_ProblemDescription_DataLossCasting">
            <summary>
              Looks up a localized string similar to Data loss might occur when casting from {0} to {1}..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.DataTypeCompatibility_ProblemDescription_ExplicitConversionReqruied">
            <summary>
              Looks up a localized string similar to Data types of {0} and {1} are not implicitly compatible. You must use the CONVERT or CAST function..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.DataTypeCompatibility_ProblemDescription_IncompatibleCasting">
            <summary>
              Looks up a localized string similar to Data types of {0} and {1} are incompatible..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.DataTypeCompatibility_ProblemDescription_IncorrectDataType">
            <summary>
              Looks up a localized string similar to The following data type is not valid in this context: {0}.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.DataTypeCompatibility_RuleName">
            <summary>
              Looks up a localized string similar to Maintain compatibility between data types..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.ExtractDeterministicFunctionCall_ProblemDescription">
            <summary>
              Looks up a localized string similar to Deterministic function call ({0}) might cause an unnecessary table scan..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.ExtractDeterministicFunctionCall_RuleName">
            <summary>
              Looks up a localized string similar to Extract deterministic function calls from WHERE predicates..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.Identity_ProblemDescription">
            <summary>
              Looks up a localized string similar to Potential misuse of system function @@IDENTITY..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.Identity_RuleName">
            <summary>
              Looks up a localized string similar to Consider using SCOPE_IDENTITY instead of @@IDENTITY..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.LikePercent_ProblemDescription">
            <summary>
              Looks up a localized string similar to Avoid using patterns that start with &quot;%&quot; in LIKE predicates.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.LikePercent_RuleName">
            <summary>
              Looks up a localized string similar to Avoid using patterns that start with “%” in LIKE predicates..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.MoveColumnToOneside_ProblemDescription">
            <summary>
              Looks up a localized string similar to A column in an expression to be compared in a predicate might cause a table scan and degrade performance..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.MoveColumnToOneside_RuleName">
            <summary>
              Looks up a localized string similar to In the comparison, simplify the expression that includes indexed columns..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.NonIndexedColumnFromInPredicate_ProblemDescription">
            <summary>
              Looks up a localized string similar to A column without an index that is used as an IN predicate test expression might degrade performance..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.NonIndexedColumnFromInPredicate_RuleName">
            <summary>
              Looks up a localized string similar to Avoid using columns that do not have an index as test expressions in IN predicates..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.NullableColumn_ProblemDescription">
            <summary>
              Looks up a localized string similar to Nullable columns can cause final results to be evaluated as NULL for the predicate..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.NullableColumn_RuleName">
            <summary>
              Looks up a localized string similar to Use ISNULL(column, default value) on nullable columns in expressions..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.OldStyleJoinSyntax_ProblemDescription">
            <summary>
              Looks up a localized string similar to Old-style JOIN syntax is used..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.OldStyleJoinSyntax_RuleName">
            <summary>
              Looks up a localized string similar to Avoid using deprecated syntax when you join tables or views..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.PopulateOutputParameters_ProblemDescription">
            <summary>
              Looks up a localized string similar to Output parameter ({0}) is not populated in all code paths..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.PopulateOutputParameters_RuleName">
            <summary>
              Looks up a localized string similar to Specify values for output parameters in all code paths..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.ReservedWordsForTypeName_FutureKeyword">
            <summary>
              Looks up a localized string similar to A future keyword.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.ReservedWordsForTypeName_Keyword">
            <summary>
              Looks up a localized string similar to A keyword.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.ReservedWordsForTypeName_OdbcKeyword">
            <summary>
              Looks up a localized string similar to An ODBC keyword.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.ReservedWordsForTypeName_ProblemDescription">
            <summary>
              Looks up a localized string similar to {0}({1}) is used as a type name..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.ReservedWordsForTypeName_RuleName">
            <summary>
              Looks up a localized string similar to Avoid using reserved words for type names..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.SelectAsterisk_ProblemDescription">
            <summary>
              Looks up a localized string similar to The shape of the result set produced by a SELECT * statement will change if the underlying table or view structure changes..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.SelectAsterisk_RuleName">
            <summary>
              Looks up a localized string similar to Avoid SELECT * in stored procedures, views, and table-valued functions..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.SmallVariableLengthTypes_OneElement">
            <summary>
              Looks up a localized string similar to one element.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.SmallVariableLengthTypes_ProblemDescription">
            <summary>
              Looks up a localized string similar to Avoid {0} of only {1}..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.SmallVariableLengthTypes_RuleName">
            <summary>
              Looks up a localized string similar to Avoid using types of variable length that are size 1 or 2..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.SmallVariableLengthTypes_TwoOrMoreElements">
            <summary>
              Looks up a localized string similar to {0} elements.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.SpecialCharactersInObjectName_ProblemDescription">
            <summary>
              Looks up a localized string similar to Object name({0}) contains special characters..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.SpecialCharactersInObjectName_RuleName">
            <summary>
              Looks up a localized string similar to Avoid using special characters in object names..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.SpPrefixForStoredProcedures_ProblemDescription">
            <summary>
              Looks up a localized string similar to Stored procedure({0}) includes sp_ prefix in its name..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Rules.SqlRulesResourceString.SpPrefixForStoredProcedures_RuleName">
            <summary>
              Looks up a localized string similar to Avoid using sp_ as a prefix for stored procedures..
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Internal.TsqlScriptDomUtils">
            <summary>
            Utility class for TransactSql.ScriptDom functionality. These functions will not be
            part of the public API, but they may be added to the public samples project so that users can
            understand how we use the ScriptDom APIs for writing rules.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Internal.TsqlScriptDomUtils.IsSubroutineViewOrTrigger(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment)">
            <summary>
            Checks if a fragment represents the body of a subroutine, a view, 
            or a trigger. These have similar characteristics, for instance the ability to
            include select statements against tables. 
            </summary>
            <param name="fragment"><see cref="T:Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment"/> representing part of a TSQL object definition</param>
            <returns>true if this is a subroutine, a view or a trigger body</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Internal.TsqlScriptDomUtils.RemoveParenthesis(Microsoft.SqlServer.TransactSql.ScriptDom.ScalarExpression)">
            <summary>
            recursively remove parenthesises of an TSql parser expression
            </summary>
            <param name="expression">Expression to parse</param>
            <returns>Expression without parenthesis</returns>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.CodeAnalysis.SqlCodeAnalysisConstants.StaticCodeAnalysisProblemCategory">
            <summary>
            Error category for static code analysis
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.MefRuleEngineResources">
            <summary>
              A strongly-typed resource class, for looking up localized strings, etc.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.MefRuleEngineResources.ResourceManager">
            <summary>
              Returns the cached ResourceManager instance used by this class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.MefRuleEngineResources.Culture">
            <summary>
              Overrides the current thread's CurrentUICulture property for all
              resource lookups using this strongly typed resource class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.MefRuleEngineResources.ElementsListFormat">
            <summary>
              Looks up a localized string similar to {0}, {1}.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.MefRuleEngineResources.InvalidRuleStatusPrefix">
            <summary>
              Looks up a localized string similar to Invalid prefix for rule key: {0}. Ignored..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.MefRuleEngineResources.MissingSupportedElements">
            <summary>
              Looks up a localized string similar to Rule &apos;{0}&apos; in assembly &apos;{1}&apos; was ignored because it is missing SupportedElementTypes. This is required for Element scope rules.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.MefRuleEngineResources.NoSupportedElementsFound">
            <summary>
              Looks up a localized string similar to Rule &apos;{0}&apos; in assembly &apos;{1}&apos; was ignored because it has no SupportedElementTypes that are top-level types. Only top-level types are processed during analysis. The following types were ignored: [{2}].
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.MefRuleEngineResources.UnsupportedElementsFound">
            <summary>
              Looks up a localized string similar to Rule &apos;{0}&apos; in assembly &apos;{1}&apos; has one or more SupportedElementTypes that are not top-level types. These following types will be ignored during analysis: [{2}].
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.RuleEngine">
            <summary>
            Responsible for executing rules against a SQLModel.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.RuleEngine.ExecuteRules(Microsoft.SqlServer.Dac.Model.TSqlModel,System.Collections.Generic.IList{Microsoft.SqlServer.Dac.Extensibility.ExtensibilityError}@)">
            <summary>
            Execute all enabled rules against the specified model and each model element found in the model
            </summary>
            <param name="schemaModel">The model against which the rules are executed</param>
            <param name="errors">The errors that occurred when executing rules</param>
            <returns>The problems detected by executing the rules</returns>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.RuleEngine.AllRuleDescriptions">
            <summary>
            Used for testing purposes
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.RuleEngine.ModelRuleDescriptions">
            <summary>
            Used for testing purposes
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.RuleEngine.ElementRuleDescriptions">
            <summary>
            Used for testing purposes
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.RuleLoader`1.CreateStandardProperties">
            <summary>
            Creates a <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.EngineProperties"/> that uses standard extension lookup 
            properties and returns this to the caller
            </summary>
            <returns><see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.EngineProperties"/></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.RuleLoader`1.SetRuleStoreFactory(Microsoft.SqlServer.Dac.CodeAnalysis.Engine.IRuleStoreFactory{`0})">
            <summary>
            For testing purposes only - injects a new rulestore factory for use when finding rules
            </summary>
            <param name="factory"></param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.RuleLoader`1.#ctor(Microsoft.SqlServer.Dac.CodeAnalysis.Engine.EngineProperties)">
            <summary>
            Initializes the <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.RuleLoader`1"/> 
            </summary>
            <param name="engineProperties"><see cref="T:Microsoft.SqlServer.Dac.Extensibility.CompositionProperties"/> defining how rules should be loaded</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.RuleLoader`1.GetAllRules(System.Collections.Generic.IList{Microsoft.SqlServer.Dac.Extensibility.ExtensibilityError}@)">
            <summary>
            Gets all rules.
            </summary>
            <param name="typeLoadErrors">Output <see cref="T:System.Collections.Generic.List`1"/> containing all errors that occurred during load. This will include general load errors
            for all contributors on the machine, plus load errors relating to version mismatch between requested contributor version
            and the available contributors on the machine</param>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.RuleLoader`1.CreateRuleEngine(System.Collections.Generic.IList{Microsoft.SqlServer.Dac.Extensibility.ExtensibilityError}@)">
            <summary>
            Creates a RuleEngine.
            </summary>
            <param name="errors">Errors found while processing rules - are there duplicate rules or rules that do not include required metadata</param>
            <returns></returns>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.IRuleStore">
            <summary>
            A RuleStore that stores analysis rules and their metadata. Rules are accessible in their original form
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.IRuleStore.GetRuleDescriptors(System.Collections.Generic.IList{Microsoft.SqlServer.Dac.Extensibility.ExtensibilityError}@)">
            <summary>
            Gets the Code Analysis rules and their metadata wrapped inside RuleDescriptorImpl objects. The EngineProperties are used to
            filter rules by platform and to run a rule descriptor updater (if present), which can flag the rule as enabled/disabled
            and update the severity 
            </summary>
            <param name="errors">Errors found while processing rules - are there duplicate rules or rules that do not include required metadata</param>
            <returns></returns>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.RuleStore">
            <summary>
            For now only ISqlCodeAnalysisRule is supported via MEF - can change in the future if other rule types are required.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.RuleStore.GetRuleDescriptors(System.Collections.Generic.IList{Microsoft.SqlServer.Dac.Extensibility.ExtensibilityError}@)">
            <summary>
            Gets the Code Analysis rules and their metadata wrapped inside RuleDescriptorImpl objects. The EngineProperties are used to
            filter rules by platform and to run a rule descriptor updater (if present), which can flag the rule as enabled/disabled
            and update the severity 
            </summary>
            <param name="errors">Errors found while processing rules - are there duplicate rules or rules that do not include required metadata</param>
            <returns></returns>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.IRuleStoreFactory`1">
            <summary>
            Factory for loading rules via MEF extensibility. 
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.IRuleStoreFactory`1.CreateRuleStore(Microsoft.SqlServer.Dac.CodeAnalysis.Engine.EngineProperties,System.Collections.Generic.IList{Microsoft.SqlServer.Dac.Extensibility.ExtensibilityError}@)">
            <summary>
            Creates an IRuleStore with rules found by MEF
            </summary>
            <param name="properties">Properties defining the configuration for extensibility loading etc</param>
            <param name="errors">Errors found while loading rule extensions </param>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.RuleStoreFactory`1.SetExtensionManagerFactory(Microsoft.SqlServer.Dac.Extensibility.IExtensionManagerFactory)">
            <summary>
            For testing purposes only - injects a new IExtensionManagerFactory which supplies types
            </summary>
            <param name="factory"></param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.SourceCodePositionProvider.TryGetSourceInformation(Microsoft.SqlServer.Dac.Model.TSqlObject,Microsoft.SqlServer.Dac.SourceInformation@)">
            <summary>
            Tries to find source information for a given TSqlObject
            </summary>
            <returns>true if source information was found</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.SourceCodePositionProvider.TryGetSourceInformation(Microsoft.SqlServer.Dac.Model.TSqlObject,Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment,Microsoft.SqlServer.Dac.SourceInformation@)">
            <summary>
            Tries to find source information for a given TSqlObject
            </summary>
            <returns>true if source information was found</returns>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblemSuppressionContext">
            <summary>
            The context information for suppressing a SCA problem
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblemSuppressionContext.#ctor(Microsoft.SqlServer.Dac.CodeAnalysis.RuleDescriptor,Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem,Microsoft.SqlServer.Dac.Model.TSqlModel)">
            <summary>
            Initialize a new instance of SqlRuleProblemSuppressionContext
            </summary>
            <param name="rule">The Rule detecting the problem</param>
            <param name="problem">The problem</param>
            <param name="schemaModel">The Schema Model being analyzed</param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblemSuppressionContext.ModelElement">
            <summary>
            The element for which a problem was discovered
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblemSuppressionContext.SchemaModel">
            <summary>
            The Schema Model the rule is checking against
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblemSuppressionContext.Problem">
            <summary>
            The <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem"/> discovered by an analysis rule
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblemSuppressionContext.Rule">
            <summary>
            The Rule detecting the problem
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.EngineProperties">
            <summary>
            Properties to use when creating a rules engine. 
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.EngineProperties.RuleSettingsString">
            <summary>
            Optional string that can be used to disable rules
            and set rule severity
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.EngineProperties.SuppressProblem">
            <summary>
            The predicate to suppress problems detected by a rule against an element
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.Engine.EngineProperties.ExecuteCanceled">
            <summary>
            Callback function that tests whether to abort executing rules
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.ScaResources">
            <summary>
              A strongly-typed resource class, for looking up localized strings, etc.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.ScaResources.ResourceManager">
            <summary>
              Returns the cached ResourceManager instance used by this class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.ScaResources.Culture">
            <summary>
              Overrides the current thread's CurrentUICulture property for all
              resource lookups using this strongly typed resource class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.ScaResources.CodeAnalysis_ModelIsNotScriptBacked">
            <summary>
              Looks up a localized string similar to Static Code Analysis: Some rules may not run as expected because the model being analyzed does not contain scripts representing your schema objects. When analyzing code from a data source such as a Dacpac it is recommended that the source should be loaded as script-backed model to ensure correct rule operation.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.ScaResources.CodeAnalysisTask_Error">
            <summary>
              Looks up a localized string similar to Error.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.ScaResources.CodeAnalysisTask_InvalidElement">
            <summary>
              Looks up a localized string similar to {0} elements are in an error state.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.ScaResources.CodeAnalysisTask_MultipleProblemsFound">
            <summary>
              Looks up a localized string similar to Static Code Analysis: {0} problems have been detected..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.ScaResources.CodeAnalysisTask_NoProblemsFound">
            <summary>
              Looks up a localized string similar to Static Code Analysis: No problems have been detected..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.ScaResources.CodeAnalysisTask_OneProblemFound">
            <summary>
              Looks up a localized string similar to Static Code Analysis: One problem has been detected..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.ScaResources.CodeAnalysisTask_ProblemFormat">
            <summary>
              Looks up a localized string similar to {0}: {1}.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.ScaResources.CodeAnalysisTask_ResultsSavedIn">
            <summary>
              Looks up a localized string similar to The results are saved in {0}..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.ScaResources.SqlCodeAnalysisTask_Unknown">
            <summary>
              Looks up a localized string similar to Unknown.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.ScaResources.SqlCodeAnalysisTask_Warning">
            <summary>
              Looks up a localized string similar to Warning.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleExecutionContext">
            <summary>
            Defines the fields necessary for analysis, including the schema model and 
            model element to analyze.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleExecutionContext.SchemaModel">
            <summary>
            The <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> being analyzed.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleExecutionContext.ModelElement">
            <summary>
            The <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> being analyzed.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleExecutionContext.RuleDescriptor">
            <summary>
            Describes the rule being executed, and can be used to access the 
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleExecutionContext.ScriptFragment">
            <summary>
            Gets the script fragment which defines the element being analyzed, if this is available. 
            May be null. 
            
            Tries to get the most suitable <see cref="T:Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment"/> for use during the rule analysis process.
            If the TSqlObject was originally built from a scripted source then the original source fragment will be returned.
            Otherwise a new AST will be generated from the <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleExecutionContext.ModelElement"/>/&gt;.
            This ensures that when reporting <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem"/>s the most accurate source information can be included
            in the error messages. 
            </summary>
            <remarks>
            See <see cref="M:Microsoft.SqlServer.Dac.TSqlModelUtils.TryGetFragmentForAnalysis(Microsoft.SqlServer.Dac.Model.TSqlObject,Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment@)"/> for implementation details
            </remarks>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem">
            <summary>
            Describes a problem found by a rule during analysis. Contains relevant information
            such as the Rule that found the problem, the SqlObject causing the problem, 
            the severity, and the error message to display.
            
            Source position information (source name, start line and column) are initially inferred based on
            the <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem.ModelElement"/> and <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem.Fragment"/> passed into the constructor. Note that if
            a <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem.Fragment"/> is passed in then the start line/column for that <see cref="T:Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment"/>
            will be used (if present), otherwise the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>'s values will be used (if present).
            Note that certain models such as those generated from a dacpac may not have source position
            information.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem.#ctor(System.String,Microsoft.SqlServer.Dac.Model.TSqlObject)">
            <summary>
            Constructs a new <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem"/>. Source position information
            (source name, start line and column) is inferred based on the <paramref name="modelElement"/>
            parameter, as long as this information is present in the model.
            </summary>
            <param name="description">Description of the problem</param>
            <param name="modelElement">The element that caused the problem  </param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem.#ctor(System.String,Microsoft.SqlServer.Dac.Model.TSqlObject,Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment)">
            <summary>
            Constructs a new <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem"/>. Source position information
            (source name, start line and column) is inferred based on the <paramref name="modelElement"/>
            and <paramref name="fragment"/> parameters, as long as this information is present in the model.
            </summary>
            <param name="description">Description of the problem</param>
            <param name="modelElement">The element that caused the problem</param>
            <param name="fragment"><see cref="T:Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment"/> specifying the precise </param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem.SetSourceInformation(Microsoft.SqlServer.Dac.SourceInformation)">
            <summary>
            Sets source position information (source name, start line and column) for this <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem"/>,
            overriding any position information inferred when the rule was created. 
            </summary>
            <param name="sourceInformation"><see cref="T:Microsoft.SqlServer.Dac.SourceInformation"/> specifying the values to set for the
            <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem.SourceName"/>, <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem.StartLine"/> and <see cref="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem.StartColumn"/> fields</param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem.Rule">
            <summary>
            Description of the rule used to detect the current problem. Does not need to be set by the rule itself
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem.RuleId">
            <summary>
            Id of the rule that created this <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem"/>
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem.ModelElement">
            <summary>
            The <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> causing the current problem
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem.Fragment">
            <summary>
            <see cref="T:Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment"/> causing the problem
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem.Description">
            <summary>
            Problem description
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem.Severity">
            <summary>
            The severity of this problem, can be error, warning.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem.ErrorMessageString">
            <summary>
            The string for displaying the error message, based on rule information
            and the problem description
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem.SourceName">
            <summary>
            Name of the source this problem was found in. This is determined based on the 
            model element passed into the constructor. May be null if no source information
            was available. For instance models loaded from Dacpac files may not have source
            information available
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem.StartLine">
            <summary>
            The line the problem begins at, if known
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem.StartColumn">
            <summary>
            The column the problem begins at, if known
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblemSeverity">
            <summary>
            The type of message for reporting problems
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblemSeverity.Unknown">
            <summary>
            Unknown severity
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblemSeverity.Warning">
            <summary>
            Warning
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblemSeverity.Error">
            <summary>
            Error
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleScope">
            <summary>
            The scope examined by a static code analysis rule.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleScope.Element">
            <summary>
            The rule examines a single element.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleScope.Model">
            <summary>
            The rule examines the entire model.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.CodeAnalysis.SuppressedProblemInfo">
            <summary>
            Information about a problem being suppressed for a particular source. 
            This information includes the source name and the rule whose problems should be suppressed.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.SuppressedProblemInfo.#ctor(System.String,Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration)">
            <summary>
            Creates a <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.SuppressedProblemInfo"/> for a given source name and rule
            </summary>
            <param name="sourceName">
            Name of the source to be suppressed. This is commonly the path to a file on disk.
            </param>
            <param name="rule">Information about the rule whose problems should be suppressed</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.SuppressedProblemInfo.Equals(System.Object)">
            <summary>
            <see cref="M:System.Object.Equals(System.Object)"/>
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.CodeAnalysis.SuppressedProblemInfo.GetHashCode">
            <summary>
            <see cref="M:System.Object.GetHashCode"/>
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.SuppressedProblemInfo.SourceName">
            <summary>
            Gets the name of the source to be suppressed. This is commonly the path to a file on disk.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.CodeAnalysis.SuppressedProblemInfo.Rule">
            <summary>
            Gets a <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.RuleConfiguration"/> with information about the rule 
            whose problems should be suppressed
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Compare.DacSchemaComparisonMessage">
            <summary>
            Represents a problem encountered during schema comparison.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.DacSchemaComparisonMessage.Exception">
            <summary>
            Exception associated with the error, or null
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Compare.SchemaCompareApiResources">
            <summary>
              A strongly-typed resource class, for looking up localized strings, etc.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareApiResources.ResourceManager">
            <summary>
              Returns the cached ResourceManager instance used by this class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareApiResources.Culture">
            <summary>
              Overrides the current thread's CurrentUICulture property for all
              resource lookups using this strongly typed resource class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareApiResources.ComparisonResultStateDoesNotAllowPublish">
            <summary>
              Looks up a localized string similar to Performing publish is not possible for this comparison result..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareApiResources.ComparisonResultStateDoesNotAllowScriptGeneration">
            <summary>
              Looks up a localized string similar to Performing script generation is not possible for this comparison result..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareApiResources.InvalidConnectionString">
            <summary>
              Looks up a localized string similar to The specified connection string is not valid..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareApiResources.OperationFailedDueToAnUnexpectedException">
            <summary>
              Looks up a localized string similar to The operation failed..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareApiResources.OperationFailedDueToException0">
            <summary>
              Looks up a localized string similar to The operation failed. The error was: {0}.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareApiResources.OperationFailedDueToSourceDrift">
            <summary>
              Looks up a localized string similar to The operation could not continue because the source database was modified after schema comparison was completed..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareApiResources.OperationFailedDueToSourceModelErrors">
            <summary>
              Looks up a localized string similar to The operation could not continue because the source model contains errors..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareApiResources.OperationFailedDueToTargetDrift">
            <summary>
              Looks up a localized string similar to The operation could not continue because the target database was modified after schema comparison was completed..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareApiResources.OperationFailedDueToTargetModelErrors">
            <summary>
              Looks up a localized string similar to The operation could not continue because the target model contains errors..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareApiResources.Path0DoesntContainValidScmpFile">
            <summary>
              Looks up a localized string similar to The path &apos;{0}&apos; does not contain a valid schema compare file (.scmp file)..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareApiResources.SchemaComparisonOnlySupportsDacpacAndDatabase">
            <summary>
              Looks up a localized string similar to SchemaComparison only supports database and dacpac endpoint types..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareApiResources.UnableToDeserializeScmpFile">
            <summary>
              Looks up a localized string similar to The specified file could not be opened as a schema comparison file.  The file might be corrupt or it might refer to a target or source endpoint that is not of type database or dacpac. Only database endpoints and dacpac endpoints are supported..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareApiResources.UpdateScriptsForDacpacsRequireDbName">
            <summary>
              Looks up a localized string similar to A non-empty database name must be specified in order to generate an update script for a SchemaCompareDacpacEndpoint..
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Compare.SchemaCompareEndpoint">
            <summary>
            Refers to a source or target for schema comparison
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Compare.SchemaCompareDacpacEndpoint">
            <summary>
            Refers to a dacpac file as either a source or target for schema comparison
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Compare.SchemaCompareDacpacEndpoint.#ctor(System.String)">
            <summary>
            Constructs a schema compare endpoint that refers to a dacpac file
            </summary>
            <param name="dacpacFilePath">Path to a dacpac file</param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareDacpacEndpoint.FilePath">
            <summary>
            The dacpac file path
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Compare.SchemaCompareDatabaseEndpoint">
            <summary>
            Refers to a database as either a source or target for schema comparison
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Compare.SchemaCompareDatabaseEndpoint.#ctor(System.String)">
            <summary>
            Constructs a schema compare endpoint that refers to a database
            </summary>
            <param name="connectionString">A connection string to a database instance</param>
            <exception cref="T:System.ArgumentNullException">The supplied connection string is null.</exception>
            <exception cref="T:System.FormatException">Invalid value within the connection string (for example, when a Boolean or numeric value was expected but not supplied).</exception>
            <exception cref="T:System.ArgumentException">The supplied connectionString is not valid.</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Compare.SchemaCompareDatabaseEndpoint.#ctor(System.String,System.Security.SecureString)">
            <summary>
            Constructs a schema compare endpoint that refers to a database
            </summary>
            <param name="connectionString">A connection string to a database instance</param>
            <param name="password"><see cref="T:System.Security.SecureString"/> that supplies the password for the database connection used by this instance.</param>
            <exception cref="T:System.ArgumentNullException">The supplied connection string or password is null.</exception>
            <exception cref="T:System.FormatException">Invalid value within the connection string (for example, when a Boolean or numeric value was expected but not supplied).</exception>
            <exception cref="T:System.ArgumentException">The supplied connectionString is not valid.</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Compare.SchemaCompareDatabaseEndpoint.#ctor(Microsoft.Data.Tools.Schema.Common.SqlClient.SqlConnectionFactory)">
            <summary>
            Constructs a schema compare endpoint that refers to a database
            </summary>
            <param name="connectionFactory">A connection string to a database instance</param>
            <exception cref="T:System.ArgumentNullException">The supplied connection factory is null.</exception>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareDatabaseEndpoint.DatabaseName">
            <summary>
            The database name
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Compare.SchemaComparison">
            <summary>
            Class that allows comparing schema between two types of entities: databases and dacpac files
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Compare.SchemaComparison.#ctor(System.String)">
            <summary>
            SchemaComparison constructor that uses a schema compare file (.scmp file) for
            all comparison settings.  Only dacpac and/or database endpoints may be compared.
            </summary>
            <param name="scmpFilePath">The path to a schema compare file (.scmp file)</param>
            <exception cref="T:System.ArgumentException">If either the source or the target endpoint is neither a database nor a dacpac file.</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Compare.SchemaComparison.#ctor(Microsoft.SqlServer.Dac.Compare.SchemaCompareEndpoint,Microsoft.SqlServer.Dac.Compare.SchemaCompareEndpoint)">
            <summary>
            SchemaComparison constructor that takes endpoints that specify the source and target for comparison.
            </summary>
            <param name="source">A <see cref="T:Microsoft.SqlServer.Dac.Compare.SchemaCompareEndpoint"/> that refers to a schema source.</param>
            <param name="target">An <see cref="T:Microsoft.SqlServer.Dac.Compare.SchemaCompareEndpoint"/> that refers to a target.  Comparison will update the target to match the source.</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Compare.SchemaComparison.Compare">
            <summary>
            Performs schema comparison, populating comparison results.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Compare.SchemaComparison.SaveToFile(System.String,System.Boolean)">
            <summary>
            Saves the SchemaComparison as an scmp file.
            </summary>
            <param name="filePath"></param>
            <param name="overwrite">When true, any existing file at filePath will be overwritten. If false, save will throw an
            IOException if a file already exists at filePath.</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Compare.SchemaComparison.SaveToStream(System.IO.Stream)">
            <summary>
            Saves the SchemaComparison as an scmp file into a stream
            </summary>
            <param name="stream">A stream that supports writing.</param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaComparison.Source">
            <summary>
            The <see cref="T:Microsoft.SqlServer.Dac.Compare.SchemaCompareEndpoint"/> that refers to a schema source.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaComparison.Target">
            <summary>
            The <see cref="T:Microsoft.SqlServer.Dac.Compare.SchemaCompareEndpoint"/> that refers to a target.  Comparison will update the target to match the source.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaComparison.ExcludedSourceObjects">
            <summary>
            Elements in the source database model to exclude from comparison.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaComparison.ExcludedTargetObjects">
            <summary>
            Elements in the target database model to exclude from comparison.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaComparison.Options">
            <summary>
            Options that affect the behavior of package deployment.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Compare.SchemaDifferenceType">
            <summary>
            Represents the different possible types of <see cref="T:Microsoft.SqlServer.Dac.Compare.SchemaDifference"/>
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Compare.SchemaDifferenceType.Object">
            <summary>
            A model object (for example: column, parameter)
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Compare.SchemaDifferenceType.Property">
            <summary>
            A property of a model object (for example: Name, Collation)
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Compare.SchemaComparisonResult">
            <summary>
            Class that provides information about the differences between a source and target database.
            Differences are represented in a tree structure.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Compare.SchemaComparisonResult.Include(Microsoft.SqlServer.Dac.Compare.SchemaDifference)">
            <summary>
            Used to try to include a difference as part of the set of update actions that are scripted or published.
            </summary>
            <param name="node">The tree node to (possibly) modify</param>
            <returns>Returns true if, after completion, the node's state is included</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Compare.SchemaComparisonResult.Exclude(Microsoft.SqlServer.Dac.Compare.SchemaDifference)">
            <summary>
            Used to try to exclude a difference as part of the set of update actions that are scripted or published.
            </summary>
            <param name="node">The tree node to (possibly) modify</param>
            <returns>Returns true if, after completion, the node's state is not included</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Compare.SchemaComparisonResult.GetErrors">
            <summary>
            Provides an enumeration of errors that prevent successful schema compare operations.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Compare.SchemaComparisonResult.GenerateScript(System.String)">
            <summary>
            Generates a T-SQL update script that makes the target schema consistent with the source schema.
            </summary>
            <param name="databaseName">The name of the target database.</param>
            <returns>SchemaCompareScriptGenerationResult </returns>
            <exception cref="T:System.ArgumentException">If the target is a dacpac and a null or empty databaseName value was provided.</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Compare.SchemaComparisonResult.PublishChangesToTarget">
            <summary>
            Generates and then executes a T-SQL update script that makes the target schema consistent with the source schema.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaComparisonResult.IsValid">
            <summary>
            Indicates whether comparison resulted in a valid, usable result
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaComparisonResult.IsEqual">
            <summary>
            Indicates whether the source and target endpoints are equal
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaComparisonResult.SourceModel">
            <summary>
            The source database model
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaComparisonResult.TargetModel">
            <summary>
            The target database model
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaComparisonResult.Differences">
            <summary>
            A tree that contains results of schema comparison of source and target endpoints.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Compare.SchemaCompareScriptGenerationResult">
            <summary>
            Result of generating scripts
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareScriptGenerationResult.Script">
            <summary>
            The generated script
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareScriptGenerationResult.MasterScript">
            <summary>
            When needed (e.g. for Azure SQL Database), a separate script to be executed against the master database on the target server
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareScriptGenerationResult.Success">
            <summary>
            Indicates whether generating the script was successful.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareScriptGenerationResult.Message">
            <summary>
            Provides context information in the event of an error.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaCompareScriptGenerationResult.Exception">
            <summary>
            Provides error information in the event of an exception.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Compare.SchemaComparePublishResult">
            <summary>
            Result of publishing comparison result
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaComparePublishResult.Script">
            <summary>
            The generated script
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaComparePublishResult.MasterScript">
            <summary>
            When needed (e.g. for Azure SQL Database), a separate script to be executed against the master database on the target server
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaComparePublishResult.Success">
            <summary>
            Indicates whether generating the script was successful.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaComparePublishResult.Errors">
            <summary>
            Any errors encountered while publishing
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Compare.SchemaDifference">
            <summary>
            Represents an object or property difference found during comparison of two database models.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaDifference.DifferenceType">
            <summary>
            Represents the type of this <see cref="T:Microsoft.SqlServer.Dac.Compare.SchemaDifference"/> node
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaDifference.UpdateAction">
            <summary>
            The update action required to make the schema of the target equal to the source schema.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaDifference.Included">
            <summary>
            Indicates whether this node and all of its children will be included during script generation or publish of the comparison result.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaDifference.IsExcludable">
            <summary>
            Indicates whether this node can be excluded from script generation and publish of the comparison result.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaDifference.Parent">
            <summary>
            The parent difference (of type <see cref="F:Microsoft.SqlServer.Dac.Compare.SchemaDifferenceType.Object"/>), if any, of this difference
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaDifference.Children">
            <summary>
            Object or property differences, if any, that relate to this difference.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaDifference.SourceObject">
            <summary>
            Object from the source database model
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaDifference.TargetObject">
            <summary>
            Object from the target database model
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaDifference.Name">
            <summary>
            Node name
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Compare.SchemaComparisonExcludedObjectId">
            <summary>
            Represents an object by name and type for use in <see cref="T:Microsoft.SqlServer.Dac.Compare.SchemaComparison"/> operations.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Compare.SchemaComparisonExcludedObjectId.#ctor(Microsoft.SqlServer.Dac.Model.ModelTypeClass,Microsoft.SqlServer.Dac.Model.ObjectIdentifier)">
            <summary>
            Constructs an identifier that refers to an object by type and name.
            </summary>
            <param name="typeClass">The type of an object</param>
            <param name="identifier">The ObjectIdentifier (name) of an object</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Compare.SchemaComparisonExcludedObjectId.#ctor(Microsoft.SqlServer.Dac.Model.ModelTypeClass,Microsoft.SqlServer.Dac.Model.ObjectIdentifier,Microsoft.SqlServer.Dac.Model.ModelTypeClass,Microsoft.SqlServer.Dac.Model.ObjectIdentifier)">
            <summary>
            Constructs an identifier that refers to an object by type and name.
            </summary>
            <param name="typeClass">The type of an object</param>
            <param name="identifier">The ObjectIdentifier (name) of an object</param>
            <param name="parentTypeClass">The type of the parent object. This is used to refer to an unnamed object by reference to its (named) parent.</param>
            <param name="parentIdentifier">The name of the parent object. This is used to refer to an unnamed object by reference to its (named) parent.</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Compare.SchemaComparisonExcludedObjectId.#ctor(System.String,Microsoft.SqlServer.Dac.Model.ObjectIdentifier)">
            <summary>
            Constructs an identifier that refers to an object by type and name.
            </summary>
            <param name="typeName">The type name used by schema comparison</param>
            <param name="identifier">The possibly null ObjectIdentifier (name) of an object</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Compare.SchemaComparisonExcludedObjectId.#ctor(System.String,Microsoft.SqlServer.Dac.Model.ObjectIdentifier,System.String,Microsoft.SqlServer.Dac.Model.ObjectIdentifier)">
            <summary>
            Constructs an identifier that refers to an object by type and name.
            </summary>
            <param name="typeName">The type name used by schema comparison</param>
            <param name="identifier">The possibly null ObjectIdentifier (name) of an object</param>
            <param name="parentTypeName">The type name of the parent object. This is used to refer to an unnamed object by reference to its (named) parent.</param>
            <param name="parentIdentifier">The name of the parent object. This is used to refer to an unnamed object by reference to its (named) parent.</param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaComparisonExcludedObjectId.TypeName">
            <summary>
            The type name used by schema comparison
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaComparisonExcludedObjectId.Identifier">
            <summary>
            Specifies the name of an object
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaComparisonExcludedObjectId.ParentTypeName">
            <summary>
            The type name of the parent object. This is used to refer to an unnamed object by reference to its (named) parent.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Compare.SchemaComparisonExcludedObjectId.ParentIdentifier">
            <summary>
            Specifies the name of the parent object. This is used to refer to an unnamed object by reference to its (named) parent.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Compare.SchemaUpdateAction">
            <summary>
            Represents a schema update action
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Compare.SchemaUpdateAction.Delete">
            <summary>
            Delete - removing an object from the database
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Compare.SchemaUpdateAction.Change">
            <summary>
            Change - modifying an object in the database
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Compare.SchemaUpdateAction.Add">
            <summary>
            Add - adding an object to the database
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacPackageExtensions">
            <summary>
            Provides extension methods to support manipulation of DacPackage objects.
            These extension methods work on an existing <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/>
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacPackageExtensions.UpdateModel(Microsoft.SqlServer.Dac.DacPackage,Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.PackageMetadata)">
            <summary>
            Updates the model in a <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/>, replacing the current model with a new one.
            
            Before updating, the model will be validated and if errors are encountered a <see cref="T:Microsoft.SqlServer.Dac.DacServicesException"/> 
            will be thrown. If callers wish to block on warnings as well as errors, they must validate the model by calling
            <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.Validate"/> and checking if any errors or warnings are included in the messages returned.
            
            Note: only the model is replaced - all other artifacts such as refactor log, pre-deployment script,
            post-deployment script and and contributor artifacts are not altered. If any of these artifacts
            rely on elements that are no longer in the updated model then deployment may fail. It is the 
            responsibility of the caller to ensure that these artifacts are consistent with the new model.
            The <see cref="T:System.IO.Packaging.Package"/> API can be used to update other artifacts such as the refactor log and scripts
            and keep them consistent with the updated model.
            These artifacts are stored as package parts and are identified by their URI. 
            Package parts can be examined using <see cref="M:System.IO.Packaging.Package.GetParts"/>. Please refer to the 
            <see cref="T:System.IO.Packaging.Package"/> API for further information about updating package parts.
            
            </summary>
            <param name="dacPackage"><see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> to be updated</param>
            <param name="newModel"><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> representing the model to save into the package.</param>
            <param name="packageMetadata"><see cref="T:Microsoft.SqlServer.Dac.PackageMetadata"/> describing the name, version and description to use
            for the <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/>, or null if the package information should remain the same. </param>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">If the <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> contains data.</exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">If there are any errors saving the model to the package,
            including errors validating the model.
            </exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">If the <paramref name="dacPackage"/> was not loaded with <see cref="F:System.IO.FileAccess.ReadWrite"/>.</exception>
            <exception cref="T:System.ArgumentNullException">If the <paramref name="dacPackage"/> or <paramref name="newModel"/> parameters are null.</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacPackageExtensions.BuildPackage(System.String,Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.PackageMetadata)">
            <summary>
            Creates a package with the specified <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> and saves it to the specified location.
            </summary>
            <param name="packageFilePath">Path to the package file.</param>
            <param name="model"><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> representing the model to save into the package.</param>
            <param name="packageMetadata">Metadata information that describes the package.</param>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">If there are any errors during package serialization, including errors validating the model.</exception>
            <exception cref="T:System.ArgumentNullException">If the <paramref name="packageFilePath"/> or <paramref name="model"/> parameters are null.</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacPackageExtensions.BuildPackage(System.String,Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.PackageMetadata,Microsoft.SqlServer.Dac.PackageOptions)">
            <summary>
            Creates a package with the specified <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> and saves it to the specified location.
            In addition to the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/>, other artifacts such as refactor log and deployment contributors can be specified in <paramref name="packageOptions"/>.
            </summary>
            <param name="packageFilePath">Path to the package file.</param>
            <param name="model"><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> representing the model to save into the package.</param>
            <param name="packageMetadata">Metadata information that describes the package.</param>
            <param name="packageOptions"><see cref="T:Microsoft.SqlServer.Dac.PackageOptions"/> defining advanced options and additional artifacts.</param>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">If there are any errors during package serialization, including errors validating the model.</exception>
            <exception cref="T:System.ArgumentNullException">If the <paramref name="packageFilePath"/> or <paramref name="model"/> parameters are null.</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacPackageExtensions.BuildPackage(System.IO.Stream,Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.PackageMetadata)">
            <summary>
            Creates a package with the specified <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> and saves it to the specified <see cref="T:System.IO.Stream"/>.
            </summary>
            <param name="stream"><see cref="T:System.IO.Stream"/> to which the package content will be serialized.</param>
            <param name="model"><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> representing the model to save into the package.</param>
            <param name="packageMetadata">Metadata information that describes the package.</param>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">If there are any errors during package serialization, including errors validating the model.</exception>
            <exception cref="T:System.ArgumentNullException">If the <paramref name="stream"/> or <paramref name="model"/> parameters are null.</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacPackageExtensions.BuildPackage(System.IO.Stream,Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.PackageMetadata,Microsoft.SqlServer.Dac.PackageOptions)">
            <summary>
            Creates a package with the specified <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> and saves it to the specified <see cref="T:System.IO.Stream"/>.
            In addition to the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/>, other artifacts such as refactor log and deployment contributors can be specified in <paramref name="packageOptions"/>.
            </summary>
            <param name="stream"><see cref="T:System.IO.Stream"/> to which the package content will be serialized.</param>
            <param name="model"><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> representing the model to save into the package.</param>
            <param name="packageMetadata">Metadata information that describes the package.</param>
            <param name="packageOptions"><see cref="T:Microsoft.SqlServer.Dac.PackageOptions"/> defining advanced options and additional artifacts.</param>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">If there are any errors during package serialization, including errors validating the model.</exception>
            <exception cref="T:System.ArgumentNullException">If the <paramref name="stream"/> or <paramref name="model"/> parameters are null.</exception>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.BuildContributor">
            <summary>
            Derivatives of the BuildContributor extension are executed during a 
            project build after the project's model has been constructed and verified.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.BuildContributor.OnExecute(Microsoft.SqlServer.Dac.Deployment.BuildContributorContext,System.Collections.Generic.IList{Microsoft.SqlServer.Dac.Extensibility.ExtensibilityError})">
            <summary>
            Called after the project's model has been completely built giving the build
            contributor an opportunity to examine the model and possible output
            additional files.
            </summary>
            <param name="context"><see cref="T:Microsoft.SqlServer.Dac.Deployment.BuildContributorContext"/> object</param>
            <param name="messages">Any messages to be published as part of the build process can be added to this List. 
            May relate to errors or can also be informational</param>
            <exception cref="T:Microsoft.SqlServer.Dac.Deployment.BuildFailedException">This type of exception should be thrown if the build cannot continue.</exception>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.BuildContributorContext">
            <summary>
            Provides the context for the build process that is used by <see cref="T:Microsoft.SqlServer.Dac.Deployment.BuildContributor"/> objects
            during project build. See documentation for the <see cref="P:Microsoft.SqlServer.Dac.Deployment.BuildContributorContext.Arguments"/> and <see cref="P:Microsoft.SqlServer.Dac.Deployment.BuildContributorContext.ExtensionFiles"/>
            properties for information on how to specify these inside a project file.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.BuildContributorContext.#ctor(System.Collections.Generic.Dictionary{System.String,System.Object},System.Collections.Generic.Dictionary{System.String,System.String},Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.Build.Framework.ITaskItem[])">
            <summary>
            Initializes a new instance of the <see cref="T:Microsoft.SqlServer.Dac.Deployment.BuildContributorContext"/> class.
            </summary>
            <param name="buildProperties">A <see cref="T:System.Collections.Generic.Dictionary`2"/> of named property values. Canno be null</param>
            <param name="arguments">A <see cref="T:System.Collections.Generic.Dictionary`2"/> of command-line arguments and values. Cannot be null.</param>
            <param name="buildModel">A reference to the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> of the project. Cannot be null.</param>
            <param name="extensionFiles">An array of <see cref="T:Microsoft.Build.Framework.ITaskItem"/> objects.</param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.BuildContributorContext.BuildProperties">
            <summary>
            Gets a dictionary of named properties and their values
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.BuildContributorContext.Arguments">
            <summary>
            Gets a dictionary of command-line arguments and their values.
            When building in SSDT, arguments are available when found in a .sqlproj file or a referenced .targets file. 
            For instance to add a "RunMyContributor" argument with a value of 
            "true", the following would be added:
            
            &lt;PropertyGroup&gt;
                &lt;ContributorArguments Condition="'$(Configuration)' == 'Debug''"&gt;
                    $(ContributorArguments);RunMyContributor=True;
                &lt;/ContributorArguments&gt;
            &lt;/PropertyGroup&gt;
            
            
            In this case the argument is only added for Debug configuration.
            Using the above configuration it is possible to collect information from the MSBuild environment
            and pass it to the contributor. 
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.BuildContributorContext.Model">
            <summary>
            Gets the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> of the project
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.BuildContributorContext.ExtensionFiles">
            <summary>
            Gets an array of <see cref="T:Microsoft.Build.Framework.ITaskItem"/> representing 
            Files from the project system which influence the build contributors.
            
            Input configuration files can be defined in a .sqlproj file as part of the MSBuild process. 
            Inside a .sqproj file, Build Configuration files are specified as follows:
            
            &lt;ItemGroup&gt;
              &lt;BuildExtensionConfiguration Include="MyContributorName.MyFileName1.sql" /&gt;
              &lt;BuildExtensionConfiguration Include="MyContributorName.MyFileName2.sql" /&gt;
            &lt;/ItemGroup&gt;
            
            
            Note that configuration files are accessible to all contributors. Contributors may employ a
            file naming pattern to identify which input files related to that contributor.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.BuildFailedException">
            <summary>
            A BuildFailedException should be thrown to indicate that the build cannot continue.
            This will stop the build process.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.BuildFailedException.#ctor(System.String)">
            <summary>
            Constructs a <see cref="T:Microsoft.SqlServer.Dac.Deployment.BuildFailedException"/> with a string exception message
            </summary>
            <param name="message">string describing the cause of the failure</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.BuildFailedException.#ctor(System.String,System.Exception)">
            <summary>
            Constructs a <see cref="T:Microsoft.SqlServer.Dac.Deployment.BuildFailedException"/> with a string exception message
            and an inner <see cref="T:System.Exception"/> providing more information about the failure
            </summary>
            <param name="message">string describing the cause of the failure</param>
            <param name="innerException"><see cref="T:System.Exception"/> that is the root cause of the failure</param>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.ContributorArgumentConfiguration">
            <summary>
            Instances of this class are created by Build and Deployment contributors during design-time to 
            initialize arguments that are passed to them at runtime. 
            
            In SSDT, these arguments must be specified using a ContributorArguments property
            in a .sqlproj file or a referenced .targets file. For instance to add a "RunMyContributor" argument with a value of 
            "true", the following would be added:
            &lt;PropertyGroup&gt;
                &lt;ContributorArguments Condition="'$(Configuration)' == 'Debug''"&gt;
                    $(ContributorArguments);RunMyContributor=True;
                &lt;/ContributorArguments&gt;
            &lt;PropertyGroup&gt;
            
            
            In this case the argument is only added for Debug configuration.
            Using the above configuration it is possible to collect information from the MSBuild environment
            and pass it to the contributor. 
            
            It is also possible to specify these when creating a package by using <see cref="M:Microsoft.SqlServer.Dac.DacPackageExtensions.BuildPackage(System.String,Microsoft.SqlServer.Dac.Model.TSqlModel,Microsoft.SqlServer.Dac.PackageMetadata,Microsoft.SqlServer.Dac.PackageOptions)"/> 
            and specifying <see cref="T:Microsoft.SqlServer.Dac.PackageOptions"/>.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.ContributorArgumentConfiguration.#ctor">
            <summary>
            Initializes a new instance of the <see cref="T:Microsoft.SqlServer.Dac.Deployment.ContributorArgumentConfiguration"/> class.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.ContributorArgumentConfiguration.#ctor(System.String,System.String)">
            <summary>
            Initializes a new instance of the <see cref="T:Microsoft.SqlServer.Dac.Deployment.ContributorArgumentConfiguration"/> class.
            </summary>
            <param name="name">The name of the argument.</param>
            <param name="value">The value of the argument.</param>
            <exception cref="T:System.ArgumentNullException">If the <paramref name="name"/> or <paramref name="value"/> parameters are null</exception>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ContributorArgumentConfiguration.Name">
            <summary>
            Gets or sets the name of the argument.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ContributorArgumentConfiguration.Value">
            <summary>
            Gets or sets the value of the argument expressed as a string.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationStream">
            <summary>
            Represents a streamable version of a configuration file that is used by DacFx in the deployment and build processes. 
            These streams enable deployment extensions to enhance and extend the design and deployment experience.
            
            Input configuration files can be defined in a .sqlproj file as part of the MSBuild process.
            The files are treated as streams, and will be passed to contributors
            via the <see cref="M:Microsoft.SqlServer.Dac.Deployment.DeploymentContributor.EstablishDeploymentConfiguration(Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationSetup)"/> method, where they can
            be copied as outputs that are stored in the generated dacpac. 
            
            These streams will then be made available 
            in the <see cref="M:Microsoft.SqlServer.Dac.Deployment.DeploymentContributor.ApplyDeploymentConfiguration(Microsoft.SqlServer.Dac.Deployment.DeploymentContributorContext,System.Collections.Generic.ICollection{Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationStream})"/>, where they can be
            consumed for configuration and data during deployment. At the end of the 
            <see cref="M:Microsoft.SqlServer.Dac.Deployment.DeploymentContributor.ApplyDeploymentConfiguration(Microsoft.SqlServer.Dac.Deployment.DeploymentContributorContext,System.Collections.Generic.ICollection{Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationStream})"/> method all streams will be disposed. 
            Contributors that need to obtain data from the streams must read and cache the data during this method -
            attempts to read from the stream during the <see cref="M:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanContributor.OnExecute(Microsoft.SqlServer.Dac.Deployment.DeploymentPlanContributorContext)"/> method
            will fail.
            
            Inside a .sqproj file, Deployment Configuration files are specified as follows:
            &lt;ItemGroup&gt;
              &lt;DeploymentExtensionConfiguration Include="MyContributorName.MyFileName1.sql" /&gt;
              &lt;DeploymentExtensionConfiguration Include="MyContributorName.MyFileName2.sql" /&gt;
            &lt;/ItemGroup&gt;
            
            Note that configuration streams are accessible to all contributors. Contributors may employ a
            file naming pattern to identify which input files related to that contributor.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationStream.#ctor(System.String)">
            <summary>
            Creates an instance of the <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationStream"/>
            </summary>
            <param name="filePath">A file path for which a stream can be created</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationStream.GetStream">
            <summary>
            Gets the <see cref="T:System.IO.Stream"/>
            </summary>
            <returns><see cref="T:System.IO.Stream"/></returns>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationStream.Filename">
            <summary>
            The filename used to represent this stream
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorInformation">
            <summary>
            Information that identifies a deployment contributor
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorInformation.ExtensionId">
            <summary>
            Id of the extension that implements the 
            deployment contributor
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorInformation.Version">
            <summary>
            Version of the deployment contributor extension (optional).
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DeploymentStepInternal">
            <summary>
            Base class for implementing deployment step types.
            It should not be used for writing extensions. Extensions
            must directly implement DeploymentStep
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DeploymentStep">
            <summary>
            Represents a step in a deployment plan.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentStep.ToString">
            <summary>
            Returns a string that describes this step.  The base returns the
            type of the step
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentStep.GenerateTSQL">
            <summary>
            Returns a list of strings that represent a set of TSQL script batches to be applied
            during deployment
            </summary>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentStep.GenerateBatchScript(System.IO.TextWriter)">
            <summary>
            Helper that writes the set of batch scripts to the provided writer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentStep.Next">
            <summary>
            Gets the next step in the container, which is a <see cref="T:System.Collections.Generic.LinkedListNode`1"/> of type DeploymentStep.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentStep.Previous">
            <summary>
            Gets the previous step in the container, which is a <see cref="T:System.Collections.Generic.LinkedListNode`1"/> of type DeploymentStep.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentStepInternal.#ctor">
            <summary>
            Internal custructor as class is meant for internal purpose
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentStepInternal.#ctor(Microsoft.Data.Tools.Schema.Sql.Deployment.DeploymentStep)">
            <summary>
            Internal custructor as class is meant for internal purpose
            </summary>
            <param name="internalStep"></param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentStepInternal.GenerateTSQL">
            <summary>
            Returns a list of strings that represent a set of TSQL script batches to be applied
            during deployment
            </summary>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentStepInternal.ToString">
            <summary>
            Returns a string that describes this step.  The base returns the
            type of the step
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.AlterElementStep">
            <summary>
            A step in a deployment plan that represent an alter to an element. 
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DeploymentScriptDomStep">
            <summary>
            Base class for script based deployment steps.
            Represents a deployment step that consists of an Abstract Syntax Tree (AST) and reference to a script Domain Object Model (DOM) generator.
            This class is for read-only purpose.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentScriptDomStep.Message">
            <summary>
            Gets an optional message describing the step
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentScriptDomStep.IsMessageInFirstBatch">
            <summary>
            Returns true if the step's message will be the first batch when calling
            GenerateTSql()
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentScriptDomStep.Script">
            <summary>
            Gets the script for this step.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentScriptDomStep.ScriptGenerator">
            <summary>
            Gets the ScriptGenerator for this step
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.AlterElementStep.SourceElement">
            <summary>
            Get the source element in the alter step
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.AlterElementStep.TargetElement">
            <summary>
            Gets the target element in the alter step
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.BeginPostDeploymentScriptStep">
            <summary>
            A step in the deployment plan that represents script deployment at the beginning the post-deployment.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.EmptyStep">
            <summary>
            Represents an empty step in deployment plan.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.BeginPreDeploymentScriptStep">
            <summary>
             A step in the deployment plan that represents script deployment at the beginning of pre-deployment.
             This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.CreateElementStep">
            <summary>
            The step in a deployment plan that represents a create of an element.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.CreateElementStep.SourceElement">
            <summary>
            Get the source element of the create element step
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DacBulkCopyStep">
            <summary>
            The DacBulkCopyStep uploads / streams data from the dac package to the target db.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DacDeleteFromTablesStep">
            <summary>
            The step in deployment plan that represents delete from table.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DacDropSystemVersioningStep">
            <summary>
            The step in deployment plan that represents drop of a temporal system-versioning clause
            and system-time PERIOD.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DacRestoreSystemVersioningStep">
            <summary>
            The step in deployment plan that represents creation of a temporal system-versioning clause
            and system-time PERIOD on the appropriate temporal columns.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlAddSystemVersioningStep">
            <summary>
            The step in deployment plan that represents creation of a temporal system-versioning clause
            and system-time PERIOD on the appropriate temporal columns.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlDropSystemVersioningStep">
            <summary>
            The step in deployment plan that represents drop of a temporal system-versioning clause
            and system-time PERIOD.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DacDropTemporalSchemaBoundElementStep">
            <summary>
            The step in deployment plan that represents drop of an temporal table schema-bound objects
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DacDisableForeignKeysStep">
            <summary>
            The step in deployment plan that represents disabling foreign keys.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DacRestoreConstraintsStep">
            <summary>
            The step in deployment plan that represents restoring constraints.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DacSaveConstraintsStep">
            <summary>
            The step in deployment plan that represents saving constraints.
            This class is for read-only purpose.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DeploymentScriptStep">
            <summary>
            The step in deployment plan that represents deploying scripts.
            This class can be instantiated and used by extensions.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentScriptStep.#ctor(System.String)">
            <summary>
            Creates an instance of <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentScriptStep"/>
            </summary>
            <param name="text">script to deploy</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentScriptStep.#ctor(System.Collections.Generic.IEnumerable{System.String})">
            <summary>
            Initializes a <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentScriptStep"/> with multiple TSQL scripts
            </summary>
            <param name="batches"><see cref="T:System.Collections.Generic.IEnumerable`1"/> of strings representing
            TSQL scripts</param>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DropElementStep">
            <summary>
            A step in deployment step that represents dropping a sql object.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DropElementStep.TargetElement">
            <summary>
            Gets the target element
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.EndPostDeploymentScriptStep">
            <summary>
            A step in the deployment plan that represents script deployment at the end of post-deployment.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.EndPreDeploymentScriptStep">
            <summary>
            A step in the deployment plan that represents script deployment at the end of pre-deployment.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlBeginAltersStep">
            <summary>
            Instances of this class mark the portion of the deployment plan where
            ALTERs (and CREATEs) are performed.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlBeginDropsStep">
            <summary>
            An instance of this class marks the beginning of the "drops" portion of the
            deployment plan.  Drops occur in the plan before Alters.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlBeginPreservationStep">
            <summary>
            This class marks the start (in a deployment plan) of the preservation of intent section of the
            plan.  These operations are ones taken to affect refactoring changes.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlBeginTransactionStep">
            <summary>
            This step marks the beginning of the transactional section of a deployment plan.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlChangeDatabaseStep">
            <summary>
            The step in deployment step that represents change database.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlChangeDatabaseStep.DatabaseName">
            <summary>
            Gets the database name
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlCreateDatabaseStep">
            <summary>
            The step in deployment that represents database creation.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlDropDatabaseStep">
            <summary>
            The step in deployment that represents database drop.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlCreateTrackingTableStep">
            <summary>
            The step in deployment that represents the creation of the tracking table (__ScriptTrackingLogs).
            This table is used to improve the reliability of deployment to SQL Azure.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlDropTrackingTableStep">
            <summary>
            The step in deployment that represents drop of the tracking table (__ScriptTrackingLogs).
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlEndAltersStep">
            <summary>
            Instances of this class mark the portion of the deployment plan where
            ALTERs (and CREATEs) are completed.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlEndDropsStep">
            <summary>
            An instance of this class marks the end of the "drops" portion of the
            deployment plan.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlEndPreservationStep">
            <summary>
            This class marks the end (in a deployment plan) of the preservation of intent section of the
            plan.  These operations are ones taken to affect refactoring changes.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlEndTransactionStep">
            <summary>
            This step marks the end of the transactional section of a deployment script.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlFinalizeDatabaseAccessStep">
            <summary>
            This step is represents a step in the SQL deployment plan that finalizes the access settings to the database.  These
            settings include Read-Only or Read-Write access, restricted, single user or multi-user, and online versus offline.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlMoveSchemaStep">
            <summary>
            In the deployment plan, instances of this step represent moving the element from a previous schema to
            the new one.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlMoveSchemaStep.MovedElement">
            <summary>
            Gets the moved element
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlMoveSchemaStep.NewSchema">
            <summary>
            Gets the new schema
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlMoveSchemaStep.PreviousName">
            <summary>
            Gets the previous name
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlPrintStep">
            <summary>
            A type of step in a Sql deployment plan that signifies a SQL "print" statement.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlRenameStep">
            <summary>
            Represents a step in the deployment plan that renames a element.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlRenameStep.RenamedElement">
            <summary>
            Gets the renamed object
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlRenameStep.OldName">
            <summary>
            Gets the old name of the object
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlRenameStep.NewName">
            <summary>
            Gets the new name of the object
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlTableMigrationStep">
            <summary>
            Represents a data motion step in a sql deployment plan.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlTableMigrationStep.SourceTable">
            <summary>
            Gets the source table object
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlTableMigrationStep.TargetTable">
            <summary>
            Gets the target table object
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlColumnEncryptionMigrationStep">
            <summary>
            Represents a data motion step for column encryption in a sql deployment plan.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlColumnEncryptionMigrationStep.SourceTable">
            <summary>
            Gets the source table object
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlColumnEncryptionMigrationStep.TargetTable">
            <summary>
            Gets the target table object
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlEnableDatabaseChangeTrackingStep">
            <summary>
            Represents a step which will enable change tracking on the database
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlDisableDatabaseChangeTrackingStep">
            <summary>
            Represents a step which will disable change tracking on the database
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlColumnEncryptionSPRefreshStep">
            <summary>
            Represents a step which will execute sp_refresh stored procedures
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlColumnEncryptionRenameToOriginalStep">
            <summary>
            Represents a rename back to original step for column encryption in a sql deployment plan.
            This class is for read-only purpose and cannot be instantiated.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlColumnEncryptionRenameToOriginalStep.SourceTable">
            <summary>
            Gets the source table object
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlColumnEncryptionRenameToOriginalStep.TargetTable">
            <summary>
            Gets the target table object
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.ExportBuildContributorAttribute">
            <summary>
            Concrete classes implementing <see cref="T:Microsoft.SqlServer.Dac.Deployment.BuildContributor"/> must add the 
            <see cref="T:Microsoft.SqlServer.Dac.Deployment.ExportBuildContributorAttribute"/> attribute to their class definition. This ensures 
            they will be detected and available for use during build.
            <see cref="T:Microsoft.SqlServer.Dac.Deployment.BuildContributor"/>s require a unique ID which can be based on their fully qualified type name, or explicitly
            passed as a string
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.ExportBuildContributorAttribute.#ctor(System.String,System.String)">
            <summary>
            Initializes a <see cref="T:Microsoft.SqlServer.Dac.Deployment.ExportBuildContributorAttribute"/>
            </summary>
            <param name="id">Unique Id used to identify the export </param>
            <param name="version">Optional string defining the version number of the extension. 
            Must be a valid version string </param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.ExportBuildContributorAttribute.#ctor(System.Type,System.String)">
            <summary>
            Intializes a <see cref="T:Microsoft.SqlServer.Dac.Deployment.ExportBuildContributorAttribute"/>
            </summary>
            <param name="implementingType">The Concrete type that extends <see cref="T:Microsoft.SqlServer.Dac.Deployment.BuildContributor"/> - this is used
            to generate the unique Id for this Export </param>
            <param name="version">Optional string defining the version number of the extension. 
            Must be a valid version string </param>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanExecutor">
            <summary>
            This class represents a deployment constributor that executes the deployment plan.  An
            example of a constributor would be one who executes deployment steps to create a 
            report about actions performed during a deployment
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanContributor">
            <summary>
            Represents a contributor to the deployment process
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DeploymentContributor">
            <summary>
            The base class for deployment contributors.  Subclasses of this class
            participate in a deployment by modifying a deployment plan or by executing
            the plan
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentContributor.#ctor">
            <summary>
            Initializes a new instance of the <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentContributor"/> class.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentContributor.Dispose">
            <summary>
            Inherited from <see cref="M:System.IDisposable.Dispose"/>
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentContributor.Dispose(System.Boolean)">
            <summary>
            
            </summary>
            <param name="disposing"></param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentContributor.PublishMessage(Microsoft.SqlServer.Dac.Extensibility.ExtensibilityError)">
            <summary>
            Publishes a message to the deployment engine. The deployment engine will process and report the message to consumers.
            </summary>
            <param name="message">A <see cref="T:Microsoft.SqlServer.Dac.Extensibility.ExtensibilityError"/> that contains the message to publish</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentContributor.OnEstablishDeploymentConfiguration(Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationSetup)">
            <summary>
            Called by the build process in DacFx to give your code an opportunity to modify deployment configuration.
            </summary>
            <param name="setup">The current <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationSetup"/> object.</param>
            <exception cref="T:Microsoft.SqlServer.Dac.Deployment.BuildFailedException">If there is a critical error that should stop the build process
            from continuing, implementing contributors may throw a <see cref="T:Microsoft.SqlServer.Dac.Deployment.BuildFailedException"/>.</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentContributor.OnApplyDeploymentConfiguration(Microsoft.SqlServer.Dac.Deployment.DeploymentContributorContext,System.Collections.Generic.ICollection{Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationStream})">
            <summary>
            Called by the deployment process in DacFx to give your code an opportunity to collect configuration information from the provided files.
            At the end of the method all streams will be disposed. 
            Contributors that need to obtain data from the streams must read and cache the data during this method -
            attempts to read from the stream during a later method such as the <see cref="M:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanContributor.OnExecute(Microsoft.SqlServer.Dac.Deployment.DeploymentPlanContributorContext)"/> method
            will fail.
            </summary>
            <param name="context">A <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorContext"/> object</param>
            <param name="configurationStreams">An <see cref="T:System.Collections.Generic.ICollection`1"/> of <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationStream"/> objects</param>
            <exception cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentFailedException">If there is a critical error that should stop the deployment process
            from continuing, implementing contributors may throw a <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentFailedException"/>.</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentContributor.Cancel">
            <summary>
            Cancels execution of the contributor
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentContributor.Canceled">
            <summary>
            Gets a value that indicates whether the contributor was canceled
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentContributor.CancellationToken">
            <summary>
            The <see cref="P:Microsoft.SqlServer.Dac.Deployment.DeploymentContributor.CancellationToken"/> used to indicate whether contributor execution should be canceled
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanContributor.OnExecute(Microsoft.SqlServer.Dac.Deployment.DeploymentPlanContributorContext)">
            <summary>
            Called by the deployment engine to allow custom contributors to execute their unique tasks
            </summary>
            <param name="context">A <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorContext"/> object</param>
            <exception cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentFailedException">If there is a critical error the should stop the deployment process
            from continuing, implementing contributors may throw a <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentFailedException"/>.</exception>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.ExportDeploymentPlanExecutorAttribute">
            <summary>
            Concrete classes implementing <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanExecutor"/> must add the 
            <see cref="T:Microsoft.SqlServer.Dac.Deployment.ExportDeploymentPlanExecutorAttribute"/> attribute to their class definition. This ensures 
            they will be detected and available for use during SQL Deployment.
            <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanExecutor"/>s require a unique ID which can be based on their fully qualified type name, or explicitly
            passed as a string
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.ExportDeploymentPlanExecutorAttribute.#ctor(System.String,System.String)">
            <summary>
            Initializes a <see cref="T:Microsoft.SqlServer.Dac.Deployment.ExportDeploymentPlanExecutorAttribute"/>
            </summary>
            <param name="id">Unique Id used to identify the export </param>
            <param name="version">Optional string defining the version number of the extension. 
            Must be a valid version string </param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.ExportDeploymentPlanExecutorAttribute.#ctor(System.Type,System.String)">
            <summary>
            Intializes a <see cref="T:Microsoft.SqlServer.Dac.Deployment.ExportDeploymentPlanExecutorAttribute"/>
            </summary>
            <param name="implementingType">The Concrete type that extends <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanExecutor"/> - this is used
            to generate the unique Id for this Export </param>
            <param name="version">Optional string defining the version number of the extension. 
            Must be a valid version string </param>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationSetup">
            <summary>
            Represents the current setup for <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentContributor"/> objects. 
            The setup object can be used by deployment contributors during build operations to cause files 
            to be copied as outputs that are stored in the generated dacpac, or to create new files 
            that are stored in the dacpac. See the <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationStream"/> API
            for more information about specifying inputs.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationSetup.EnumerateInputs">
            <summary>
            Returns an enumerable collection of <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationStream"/> objects.
            </summary>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationSetup.OpenNewOutput(System.String,System.Collections.Generic.IDictionary{System.String,System.String})">
            <summary>
            Returns a new output configuration file stream that is open for read and write.
            </summary>
            <param name="fileName">A partial file name.</param>
            <param name="metadata">The metadata to be saved to the file.</param>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationSetup.CopyInputToOutput(Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationStream)">
            <summary>
            Copies an input stream's contents into an output stream that is stored inside a package
            </summary>
            <param name="stream"><see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationStream"/> to be copied</param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationSetup.Properties">
            <summary>
            Gets a dictionary that contains the current properties and settings.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorConfigurationSetup.SqlCmdVariables">
            <summary>
            Gets the SqlCmd variables defined
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorContext">
            <summary>
            Provides a context for <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentContributor"/> objects in DacFx
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorContext.Arguments">
            <summary>
            Gets or sets a dictionary of named arguments and their values.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorContext.Options">
            <summary>
            Gets the options being used for this deployment
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorContext.IsAzureSource">
            <summary>
            Does the <see cref="P:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorContext.Source"/> model a SQL Azure database.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorContext.IsAzureTarget">
            <summary>
            Does the <see cref="P:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorContext.Target"/> model a SQL Azure database.
            
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorContext.Source">
            <summary>
            Gets the Source <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/>
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentContributorContext.Target">
            <summary>
            Gets the Target <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/>
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DeploymentFailedException">
            <summary>
            Represents an exception that occurs during deployment.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentFailedException.#ctor">
            <summary>
            Initializes a new instance of the <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentFailedException"/> class
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentFailedException.#ctor(System.String)">
            <summary>
            Initializes a new instance of the <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentFailedException"/> class
            </summary>
            <param name="message">Indicates the reason for the exception.</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentFailedException.#ctor(System.String,System.Exception)">
            <summary>
            Initializes a new instance of the <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentFailedException"/> class 
            </summary>
            <param name="message">Indicates the reason for the exception.</param>
            <param name="innerException">Indicates a nested exception.</param>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DeploymentPlan">
            <summary>
            Represents the plan that is generated for Deployment. 
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentPlan.AddFirst(Microsoft.SqlServer.Dac.Deployment.DeploymentStep)">
            <summary>
            
            </summary>
            <param name="newStep"></param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentPlan.AddBefore(Microsoft.SqlServer.Dac.Deployment.DeploymentStep,Microsoft.SqlServer.Dac.Deployment.DeploymentStep)">
            <summary>
            
            </summary>
            <param name="step"></param>
            <param name="newStep"></param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentPlan.AddAfter(Microsoft.SqlServer.Dac.Deployment.DeploymentStep,Microsoft.SqlServer.Dac.Deployment.DeploymentStep)">
            <summary>
            
            </summary>
            <param name="step"></param>
            <param name="newStep"></param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentPlan.AddLast(Microsoft.SqlServer.Dac.Deployment.DeploymentStep)">
            <summary>
            
            </summary>
            <param name="newStep"></param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentPlan.AddLast(System.Collections.Generic.IEnumerable{Microsoft.SqlServer.Dac.Deployment.DeploymentStep})">
            <summary>
            
            </summary>
            <param name="steps"></param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentPlan.Remove(Microsoft.SqlServer.Dac.Deployment.DeploymentStep)">
            <summary>
            
            </summary>
            <param name="step"></param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentPlan.StepCount">
            <summary>
            Total number of steps in the plan
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentPlan.Head">
            <summary>
            Gets the first deployment step
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentPlan.Tail">
            <summary>
            Gets the last deployment step
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanHandle">
            <summary>
            
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanHandle.Head">
            <summary>
            Returns the head on the plan or null if the plan is empty
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanHandle.Tail">
            <summary>
            Returns the tail of the plan or null if the plan is empty
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanContributorContext">
            <summary>
            Provides a context for <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanContributor"/> objects.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanContributorContext.ComparisonResult">
            <summary>
            Gets the <see cref="T:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResult"/>
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanContributorContext.PlanHandle">
            <summary>
            Gets the <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanHandle"/>
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanContributorContext.DeploymentMasterPath">
            <summary>
            Set if a deployment script is also being generated against an Azure target
            (which requires that the portion executed against master be its own script)
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanContributorContext.DeploymentScriptPath">
            <summary>
            Set if a deployment script is also being generated.  This
            enables other deployment contributors to correlate error messages back to a script/file
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanModifier">
            <summary>
            Represents a constributor that can modify a deployment plan
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanModifier.AddBefore(Microsoft.SqlServer.Dac.Deployment.DeploymentPlanHandle,Microsoft.SqlServer.Dac.Deployment.DeploymentStep,Microsoft.SqlServer.Dac.Deployment.DeploymentStep)">
            <summary>
            Provides a way for subclasses to modify the plan by adding a
            step after the specified step
            </summary>
            <param name="handle">The <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanHandle"/> for the plan</param>
            <param name="step">Identifies the <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentStep"/> before which the <paramref name="newStep"/> will be added.</param>
            <param name="newStep">The <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentStep"/> to be added</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanModifier.AddAfter(Microsoft.SqlServer.Dac.Deployment.DeploymentPlanHandle,Microsoft.SqlServer.Dac.Deployment.DeploymentStep,Microsoft.SqlServer.Dac.Deployment.DeploymentStep)">
            <summary>
            Provides a way to modify the existing plan by adding a step after the existing step
            </summary>
            <param name="handle">The <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanHandle"/> for the plan</param>
            <param name="step">Identifies the <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentStep"/> after which the <paramref name="newStep"/> will be added.</param>
            <param name="newStep">The <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentStep"/> to be added</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanModifier.Remove(Microsoft.SqlServer.Dac.Deployment.DeploymentPlanHandle,Microsoft.SqlServer.Dac.Deployment.DeploymentStep)">
            <summary>
            Provides a way to remove the specified step from the plan
            </summary>
            <param name="handle">The <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanHandle"/> for the plan</param>
            <param name="step">Identifies the <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentStep"/> to be removed.</param>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.ExportDeploymentPlanModifierAttribute">
            <summary>
            Concrete classes implementing <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanModifier"/> must add the 
            <see cref="T:Microsoft.SqlServer.Dac.Deployment.ExportDeploymentPlanModifierAttribute"/> attribute to their class definition. This ensures 
            they will be detected and available for use during SQL Deployment.
            <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanModifier"/>s require a unique ID which can be based on their fully qualified type name, or explicitly
            passed as a string
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.ExportDeploymentPlanModifierAttribute.#ctor(System.String,System.String)">
            <summary>
            Initializes a <see cref="T:Microsoft.SqlServer.Dac.Deployment.ExportDeploymentPlanModifierAttribute"/>
            </summary>
            <param name="id">Unique Id used to identify the export </param>
            <param name="version">Optional string defining the version number of the extension. 
            Must be a valid version string </param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.ExportDeploymentPlanModifierAttribute.#ctor(System.Type,System.String)">
            <summary>
            Intializes a <see cref="T:Microsoft.SqlServer.Dac.Deployment.ExportDeploymentPlanModifierAttribute"/>
            </summary>
            <param name="implementingType">The Concrete type that extends <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanModifier"/> - this is used
            to generate the unique Id for this <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentPlanModifier"/> Export </param>
            <param name="version">Optional string defining the version number of the extension. 
            Must be a valid version string </param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.Internal.ContributorLoader`1.CreateLoader">
            <summary>
            Creates a <see cref="T:Microsoft.SqlServer.Dac.Deployment.Internal.ContributorLoader`1"/> that uses standard extension lookup 
            properties and returns this to the caller
            </summary>
            <returns><see cref="T:Microsoft.SqlServer.Dac.Deployment.Internal.ContributorLoader`1"/></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.Internal.ContributorLoader`1.#ctor(Microsoft.SqlServer.Dac.Extensibility.CompositionProperties)">
            <summary>
            Initializes the <see cref="T:Microsoft.SqlServer.Dac.Deployment.Internal.ContributorLoader`1"/> 
            </summary>
            <param name="compositionProperties"><see cref="T:Microsoft.SqlServer.Dac.Extensibility.CompositionProperties"/> defining how contributors should be loaded</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.Internal.ContributorLoader`1.GetMatchingExtensions(System.Collections.Generic.IEnumerable{Microsoft.Data.Tools.Schema.Sql.Deployment.ContributorInfo},System.Collections.Generic.List{Microsoft.SqlServer.Dac.Extensibility.ExtensibilityError}@)">
            <summary>
            Gets all matching extensions for a set of required contributors.
            </summary>
            <param name="requiredContributors"><see cref="T:System.Collections.Generic.IEnumerable`1"/> specifying contributos to load and any version matching requirements</param>
            <param name="typeLoadErrors">Output <see cref="T:System.Collections.Generic.List`1"/> containing all errors that occurred during load. This will include general load errors
            for all contributors on the machine, plus load errors relating to version mismatch between requested contributor version
            and the available contributors on the machine</param>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.Internal.ContributorLoader`1.GetAllExtensions(System.Collections.Generic.List{Microsoft.SqlServer.Dac.Extensibility.ExtensibilityError}@)">
            <summary>
            Gets all extensions matching the Contributor type.
            </summary>
            <param name="typeLoadErrors">Output <see cref="T:System.Collections.Generic.List`1"/> containing all errors that occurred during load. This will include general load errors
            for all contributors on the machine, plus load errors relating to version mismatch between requested contributor version
            and the available contributors on the machine</param>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.Internal.ContributorLoader`1.LoadSupportedContributorIds(System.Collections.Generic.IEnumerable{Microsoft.Data.Tools.Schema.Sql.Deployment.ContributorInfo},System.Collections.Generic.Dictionary{System.String,`0}@,System.Collections.Generic.List{Microsoft.SqlServer.Dac.Extensibility.ExtensibilityError}@)">
            <summary>
            Finds and loads all contributors that match the expected <see cref="T:Microsoft.Data.Tools.Schema.Sql.Deployment.ContributorInfo"/> data
            </summary>
            <param name="expectedContributors">Input enumerable of <see cref="T:Microsoft.Data.Tools.Schema.Sql.Deployment.ContributorInfo"/>s defining the contributors being queried</param>
            <param name="loadedContributors"><see cref="T:System.Collections.Generic.Dictionary`2"/> mapping contributor ID to an instance of the contributor</param>
            <param name="loadErrors">Any <see cref="T:Microsoft.SqlServer.Dac.Extensibility.ExtensibilityError"/>s encountered while loading the contributors</param>
            <returns>List of <see cref="T:Microsoft.Data.Tools.Schema.Sql.Deployment.ContributorInfo"/>s describing the contributors that matched the query</returns>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.ModelComparisonChangeDefinitionService">
            <summary>
            Service that provides data about a <see cref="T:Microsoft.SqlServer.Dac.Deployment.ModelComparisonChangeDefinition"/>
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResultService">
            <summary>
            Service providing data required for a ModelComparisonResult
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResultService.IsEqual">
            <summary>
            If compared elements are equal
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResultService.ElementsEqual">
            <summary>
            List of elements that have no changes
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResultService.ElementGroupsEqual">
            <summary>
            List of element groups that are equal
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResultService.ElementsToAdd">
            <summary>
            List of elements exists in source, does not exist in target
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResultService.ElementsToDrop">
            <summary>
            List of elements exists in target, does not exist in source
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResultService.ElementsChanged">
            <summary>
            List of elements are changed.
            The result will keyed by elements in source, and it will have
            what are the changes together with that changed element.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResultService.ElementsPropertyChanged">
            <summary>
            List of elements changed because of properties are changed.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResultService.ElementsRelationshipEntryChanged">
            <summary>
            List of elements changed because of relationship entries are added or dropped
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResultService.ElementsComposingChildrenChanged">
            <summary>
            List of elements changed because of composed children are changed.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResultService.ElementsHierarchicalChildrenChanged">
            <summary>
            List of elements changed because of hierarchical dhildren are changed.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.Internal.InternalDeploymentContributorHelper`1">
            <summary>
            Helper class that converts and relays calls from Internal <see cref="T:Microsoft.Data.Tools.Schema.Sql.Deployment.DeploymentContributor"/> API
            to public external API
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.Internal.InternalDeploymentContributorHelper`1.ProcessContributorMethodCall(System.String,`0,System.Action{`0})">
            <summary>
            Calls a method on a contributor, handling message passing requirements. 
            Rethrows public <see cref="T:Microsoft.SqlServer.Dac.Deployment.DeploymentFailedException"/>s as internal
            <see cref="T:Microsoft.Data.Tools.Schema.Sql.Deployment.DeploymentFailedException"/>s.
            </summary>
            <param name="contributorId">Id of the contributor to be called </param>
            <param name="contributor">contributor to be called</param>
            <param name="contributorMethodCall">Action that </param>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.Internal.InternalDeploymentPlanContributorHelper`1">
            <summary>
            Helper class that converts and relays calls from Internal <see cref="T:Microsoft.Data.Tools.Schema.Sql.Deployment.DeploymentPlanContributor"/> API
            to public external API
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.Internal.InternalDeploymentPlanExecutor">
            <summary>
            A shim between the public API and the internal DacFx API. Responsible for loading all public DeploymentPlanExecutor contributors, and 
            relaying the calls from the internal API to the public API
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.Internal.InternalDeploymentPlanModifier">
            <summary>
            A shim between the public API and the internal DacFx API. Responsible for loading all public DeploymentPlanModifier contributors, and 
            relaying the calls from the internal API to the public API
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.Internal.InternalDeploymentPlanRelay">
            <summary>
            Acts as a relay between the internal and public DeploymentPlans. Converts
            Internal DeploymentStep objects to Public objects, and vice versa. 
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.Internal.InternalDeploymentPlanRelay.InternalStep">
            <summary>
            Wraps a step from the public API, ensuring it can be used by the internal API
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService">
            <summary>
            Service that provides data about a <see cref="T:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions"/>
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.AllowDropBlockingAssemblies">
            <summary>
            Get boolean that specifies whether CLR deployment will cause blocking assemblies to be dropped.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.AllowIncompatiblePlatform">
            <summary>
            Get boolean that specifies whether deployment will block due to platform compatibility.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.BackupDatabaseBeforeChanges">
            <summary>
            Get boolean that specifies whether a database backup will be performed before proceeding 
            with the actual deployment actions.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.BlockOnPossibleDataLoss">
            <summary>
            Get boolean that specifies whether deployment should stop if the operation could cause data loss.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.BlockWhenDriftDetected">
            <summary>
            Get boolean that specifies whether the system will check for differences between the 
            present state of the database and the registered state of the database and block deployment 
            if changes are detected.  Even if this option is set to true, drift detection will only occur 
            on a database if it was previously deployed with the <see cref="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.RegisterDataTierApplication"/> option enabled.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.CommentOutSetVarDeclarations">
            <summary>
            Get boolean that specifies whether the declaration of SQLCMD variables are commented 
            out in the script header.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.CompareUsingTargetCollation">
            <summary>
            Get boolean that specifies whether the target collation will be used for identifier 
            comparison.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.CreateNewDatabase">
            <summary>
            Get boolean that specifies whether the existing database will be dropped
            and a new database created before proceeding with the actual deployment actions.
            Acquires single-user mode before dropping the existing database.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.DeployDatabaseInSingleUserMode">
            <summary>
            Get boolean that specifies whether the system will acquire single-user mode on the target
            database during the duration of the deployment operation.
            </summary>
            <remarks>
            The database will be returned to multi-user mode after all changes are applied.
            Database may remain in single-user mode if an error occurs during execution.
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.DisableAndReenableDdlTriggers">
            <summary>
            Get boolean that specifies if all DDL triggers will be disabled for the duration of the 
            deployment operation and then re-enabled after all changes are applied.  
            </summary>
            <remarks>
            Triggers may remain disabled if an error occurs during execution.
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.DoNotAlterChangeDataCaptureObjects">
            <summary>
            Get boolean that specifies whether items configured for Change Data Capture (CDC)
            should be altered during deployment.  
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.DoNotAlterReplicatedObjects">
            <summary>
            Get boolean that specifies whether items configured for Replication
            should be altered during deployment.  
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.DropConstraintsNotInSource">
            <summary>
            Get boolean that specifies whether to drop all constraints that do not
            exist in the source model.  
            </summary>
            <remarks>
            This applies to check, default, foreign key, primary key, and unique constraints.
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.DropDmlTriggersNotInSource">
            <summary>
            Get boolean that specifies whether to drop all DML triggers that do not
            exist in the source model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.DropExtendedPropertiesNotInSource">
            <summary>
            Get boolean that specifies whether to drop all extended properties that do 
            not exist in the source model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.DropIndexesNotInSource">
            <summary>
            Get boolean that specifies whether to drop all indexes that do not
            exist in the source model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.DropObjectsNotInSource">
            <summary>
            Get boolean that specifies whether objects that exist in the target but not source should be dropped during deployment.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.DropPermissionsNotInSource">
            <summary>
            Get boolean that specifies whether to drop all permissions that do not
            exist in the source model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.DropRoleMembersNotInSource">
            <summary>
            Get boolean that specifies whether to drop all role memberships that do not
            exist in the source model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.DropStatisticsNotInSource">
            <summary>
            Get boolean that specifies whether to drop all statistics that do not
            exist in the source model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.GenerateSmartDefaults">
            <summary>
            Get boolean that specifies whether default values should be generated to populate NULL columns that are constrained to NOT NULL values.
            </summary>
            <remarks>
            This is useful when needing to add a new NOT NULL column to an existing table with data.
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreAnsiNulls">
            <summary>
            Get boolean that specifies whether to exclude the ANSI_NULL option from 
            consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreAuthorizer">
            <summary>
            Get boolean that specifies whether to exclude the AUTHORIZATION option from 
            consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreColumnCollation">
            <summary>
            Get boolean that specifies whether to exclude the collation specifier from 
            consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreColumnOrder">
            <summary>
            Get boolean that specifies whether to exclude from consideration 
            the order of columns in tables when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreComments">
            <summary>
            Get boolean that specifies whether to exclude comments from 
            consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreCryptographicProviderFilePath">
            <summary>
            Get boolean that specifies whether to exclude the file specification 
            of a cryptographic provider from consideration when comparing the source and 
            target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreDdlTriggerOrder">
            <summary>
            Get boolean that specifies whether to exclude DDL trigger order from 
            consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreDdlTriggerState">
            <summary>
            Get boolean that specifies whether to exclude DDL trigger state from 
            consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreDefaultSchema">
            <summary>
            Get boolean that specifies whether to exclude the DEFAULT_SCHEMA option from 
            consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreDmlTriggerOrder">
            <summary>
            Get boolean that specifies whether to exclude DML trigger order from 
            consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreDmlTriggerState">
            <summary>
            Get boolean that specifies whether to exclude DML trigger state from 
            consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreExtendedProperties">
            <summary>
            Get boolean that specifies whether to exclude all extended properties from 
            consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreFileAndLogFilePath">
            <summary>
            Get boolean that specifies whether to exclude the FILENAME option of 
            FILE objects from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreFilegroupPlacement">
            <summary>
            Get boolean that specifies whether to exclude the filegroup specifier 
            from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreFileSize">
            <summary>
            Get boolean that specifies whether to exclude the SIZE option of FILE objects 
            from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreFillFactor">
            <summary>
            Get boolean that specifies whether to exclude the FILLFACTOR option
            from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreFullTextCatalogFilePath">
            <summary>
            Get boolean that specifies whether to exclude the path specification of 
            FULLTEXT CATALOG objects from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreIdentitySeed">
            <summary>
            Get boolean that specifies whether to exclude the seed value of IDENTITY columns 
            from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreIncrement">
            <summary>
            Get boolean that specifies whether to exclude the increment value of IDENTITY columns 
            from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreIndexOptions">
            <summary>
            Get boolean that specifies whether to exclude differences in index options 
            from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreIndexPadding">
            <summary>
            Get boolean that specifies whether to exclude the PAD_INDEX option 
            from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreKeywordCasing">
            <summary>
            Get boolean that specifies whether to exclude difference in the casing of keywords 
            from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreLockHintsOnIndexes">
            <summary>
            Get boolean that specifies whether to exclude the ALLOW_ROW_LOCKS and 
            ALLOW_PAGE_LOGKS options from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreLoginSids">
            <summary>
            Get boolean that specifies whether to exclude the SID option of the LOGIN object 
            from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreNotForReplication">
            <summary>
            Get boolean that specifies whether to exclude the NOT FOR REPLICATION option 
            from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreObjectPlacementOnPartitionScheme">
            <summary>
            Get boolean that specifies whether to exclude the partition scheme object
            from consideration when comparing the source and target model for the following
            objects: Table, Index, Unique Key, Primary Key, and Queue.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnorePartitionSchemes">
            <summary>
            Get boolean that specifies whether to exclude the parameter type and 
            boundary VALUES of a PARTITION FUNCTION from consideration when comparing the 
            source and target model.  Also excludes FILEGROUP and partition function of a 
            PARTITION SCHEMA from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnorePermissions">
            <summary>
            Get boolean that specifies whether to exclude all permission statements 
            from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreQuotedIdentifiers">
            <summary>
            Get boolean that specifies whether to exclude the QUOTED_IDENTIFIER option 
            from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreRoleMembership">
            <summary>
            Get boolean that specifies whether to exclude all ROLE MEMBERSHIP objects 
            from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreRouteLifetime">
            <summary>
            Get boolean that specifies whether to exclude the LIFETIME option of ROUTE objects 
            from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreSemicolonBetweenStatements">
            <summary>
            Get boolean that specifies whether to exclude the existence or absence of semi-colons 
            from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreTableOptions">
            <summary>
            Get boolean that specifies whether the options on the target table are updated 
            to match the source table.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreUserSettingsObjects">
            <summary>
            Get boolean that specifies whether to exclude user settings 
            from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreWhitespace">
            <summary>
            Get boolean that specifies whether to exclude whitespace 
            from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreWithNocheckOnCheckConstraints">
            <summary>
            Get boolean that specifies whether to exclude the CHECK|NO CHECK option of a CHECK 
            constraint object from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IgnoreWithNocheckOnForeignKeys">
            <summary>
            Get boolean that specifies whether to exclude the CHECK|NO CHECK option of a FOREIGN KEY  
            constraint object from consideration when comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IncludeCompositeObjects">
            <summary>
            Get boolean that specifies whether to include referenced, external elements that also 
            compose the source model and then update the target database in a single deployment operation.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.IncludeTransactionalScripts">
            <summary>
            Get boolean that specifies whether to use transations during the deployment operation 
            and commit the transaction after all changes are successfully applied.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.NoAlterStatementsToChangeClrTypes">
            <summary>
            Get boolean that specifies whether to force a change to CLR assemblies by dropping and recreating them.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.PopulateFilesOnFileGroups">
            <summary>
            Get boolean that specifies whether files are supplied for filegroups defined in the deployment source.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.RegisterDataTierApplication">
            <summary>
            Get boolean that specifies whether the database will be registered as a Data-Tier Application.  
            If the target database is already a registered Data-Tier Application, then the registration will be updated.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.ScriptDatabaseCollation">
            <summary>
            Get boolean that specifies whether the target database should be altered to match the 
            source model's collation.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.ScriptDatabaseCompatibility">
            <summary>
            Get boolean that specifies whether the target database should be altered to match the 
            source model's compatibility level.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.ScriptDatabaseOptions">
            <summary>
            Get boolean that specifies whether the database options in the target database should 
            be updated to match the source model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.ScriptDeployStateChecks">
            <summary>
            Get boolean that specifies whether the target database should be checked to ensure that 
            it exists, is online and can be updated.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.ScriptFileSize">
            <summary>
            Get boolean that specifies whether a file size is specified when adding files to file groups.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.ScriptNewConstraintValidation">
            <summary>
            Get boolean that specifies whether constraints are validated after all changes are applied.
            </summary>
            <remarks>
            Constraints are always added with NOCHECK option; as a result their validation is skipped during creation.
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.ScriptRefreshModule">
            <summary>
            Get boolean that specifies whether referencing procedures are refreshed when referenced objects are updated.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.TargetConnectionString">
            <summary>
            Get string that specifies the target connection string
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.TargetDatabaseExists">
            <summary>
            Gets boolean that if set specifies whether the target database exists
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.TargetDatabaseName">
            <summary>
            Gets string that specifies the target database name
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.TargetingServerless">
            <summary>
            Get boolean that specifies whether the target server is LocalDB
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.TreatVerificationErrorsAsWarnings">
            <summary>
            Get boolean that specifies whether the deployment operation should proceed when errors are 
            generated during plan verification.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.UnmodifiableObjectWarnings">
            <summary>
            Get boolean that specifies whether the deployment operation should proceed when errors are 
            generated during plan verification.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.VerifyCollationCompatibility">
            <summary>
            Get boolean that specifies whether deployment will verify that the collation specified in the 
            source model is compatible with the collation specified in the target model.
            </summary>
            <value>
            True to continue if errors are generated during plan verification; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.VerifyDeployment">
            <summary>
            Get boolean that specifies whether the plan verification phase is executed or not.
            </summary>
            <value>
            True to perform plan verification; otherwise, false to skip it.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptionsService.SqlCommandVariableValues">
            <summary>
            Get dictionary of SQL command variable values, keyed by variable name.
            </summary>
            <value>
            Dictionary of SQL command variable values, keyed by variable name.
            </value>
            <remarks>
            Valid values must be provided for every variable before deployment, or failures may occur during deployment.
            </remarks>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.ModelComparisonChangeDefinition">
            <summary>
            Contains change details for a TSqlObject.
            Including changed properties, added/dropped/ordinal changed relationship entries,
            added/dropped/changed/ordinal changed composing children and 
            added/dropped/changed/ordinal changed hierarchical children.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.ModelComparisonChangeDefinition.#ctor(Microsoft.SqlServer.Dac.Deployment.ModelComparisonChangeDefinitionService)">
            <summary>
            Constructs a ModelComparisonChangeDefinition that uses a <see cref="T:Microsoft.SqlServer.Dac.Deployment.ModelComparisonChangeDefinitionService"/>
            to retrive definition data
            </summary>
            <param name="definitionService"></param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ModelComparisonChangeDefinition.TargetObject">
            <summary>
            Gets the target object of the change definition
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResult">
            <summary>
            SchemaModel compare result.
            Contains same elements list, elements needed to add to target list,
            elements needed to drop in target list, and changed elements list.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResult.#ctor(Microsoft.SqlServer.Dac.Deployment.ModelComparisonResultService)">
            <summary>
            Constructs a ModelComparisonResult using a <see cref="T:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResultService"/>
            to obtain the result data
            </summary>
            <param name="resultService"></param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResult.IsEqual">
            <summary>
            If compared elements are equal
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResult.ElementsEqual">
            <summary>
            List of elements that have no changes
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResult.ElementGroupsEqual">
            <summary>
            List of element groups that are equal
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResult.ElementsToAdd">
            <summary>
            List of elements exists in source, does not exist in target
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResult.ElementsToDrop">
            <summary>
            List of elements exists in target, does not exist in source
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResult.ElementsChanged">
            <summary>
            List of elements are changed.
            The result will keyed by elements in source, and it will have
            what are the changes together with that changed element.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResult.ElementsPropertyChanged">
            <summary>
            List of elements changed because of properties are changed.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResult.ElementsRelationshipEntryChanged">
            <summary>
            List of elements changed because of relationship entries are added or dropped
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResult.ElementsComposingChildrenChanged">
            <summary>
            List of elements changed because of composed children are changed.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.ModelComparisonResult.ElementsHierarchicalChildrenChanged">
            <summary>
            List of elements changed because of hierarchical dhildren are changed.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SchemaDeploymentResources">
            <summary>
              A strongly-typed resource class, for looking up localized strings, etc.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SchemaDeploymentResources.ResourceManager">
            <summary>
              Returns the cached ResourceManager instance used by this class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SchemaDeploymentResources.Culture">
            <summary>
              Overrides the current thread's CurrentUICulture property for all
              resource lookups using this strongly typed resource class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SchemaDeploymentResources.DeployPlan_StepDoesNotHaveInternalMapping">
            <summary>
              Looks up a localized string similar to This step has no mapping in the internal deployment plan..
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions">
            <summary>
            Contains deployment options values used for deployment
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.AllowDropBlockingAssemblies">
            <summary>
            Get boolean that specifies whether CLR deployment will cause blocking assemblies to be dropped.
            </summary>
            <value>
            True to drop blocking assemblies during CLR deployment; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.AllowIncompatiblePlatform">
            <summary>
            Get boolean that specifies whether deployment will block due to platform compatibility.
            </summary>
            <value>
            True to block deployment to incompatible platforms; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.BackupDatabaseBeforeChanges">
            <summary>
            Get boolean that specifies whether a database backup will be performed before proceeding 
            with the actual deployment actions.
            </summary>
            <value>
            True to perform a database backup prior to deployment; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.BlockOnPossibleDataLoss">
            <summary>
            Get boolean that specifies whether deployment should stop if the operation could cause data loss.
            </summary>
            <value>
            True to stop deployment if possible data loss if detected; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.BlockWhenDriftDetected">
            <summary>
            Get boolean that specifies whether the system will check for differences between the 
            present state of the database and the registered state of the database and block deployment 
            if changes are detected.  Even if this option is set to true, drift detection will only occur 
            on a database if it was previously deployed with the <see cref="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.RegisterDataTierApplication"/> option enabled.
            </summary>
            <value>
            True to error is drift is detected; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.CommentOutSetVarDeclarations">
            <summary>
            Get boolean that specifies whether the declaration of SQLCMD variables are commented 
            out in the script header.
            </summary>
            <value>
            True to comment out these declarations; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.CompareUsingTargetCollation">
            <summary>
            Get boolean that specifies whether the source collation will be used for identifier 
            comparison.
            </summary>
            <value>
            False to use the source collation; otherwise, true to use the target collation.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.CreateNewDatabase">
            <summary>
            Get boolean that specifies whether the existing database will be dropped
            and a new database created before proceeding with the actual deployment actions.
            Acquires single-user mode before dropping the existing database.
            </summary>
            <value>
            True to drop and re-create the database; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.DeployDatabaseInSingleUserMode">
            <summary>
            Get boolean that specifies whether the system will acquire single-user mode on the target
            database during the duration of the deployment operation.
            </summary>
            <value>
            True to acquire single-user mode during deployment; otherwise, false.
            Default is false.
            </value>
            <remarks>
            The database will be returned to multi-user mode after all changes are applied.
            Database may remain in single-user mode if an error occurs during execution.
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.DisableAndReenableDdlTriggers">
            <summary>
            Get boolean that specifies if all DDL triggers will be disabled for the duration of the 
            deployment operation and then re-enabled after all changes are applied.  
            </summary>
            <value>
            True to disable DDL triggers during deployment; otherwise, false.
            Default is true.
            </value>
            <remarks>
            Triggers may remain disabled if an error occurs during execution.
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.DoNotAlterChangeDataCaptureObjects">
            <summary>
            Get boolean that specifies whether items configured for Change Data Capture (CDC)
            should be altered during deployment.  
            </summary>
            <value>
            True to not alter objects configured for CDC; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.DoNotAlterReplicatedObjects">
            <summary>
            Get boolean that specifies whether items configured for Replication
            should be altered during deployment.  
            </summary>
            <value>
            True to not alter objects configured for Replication; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.DropConstraintsNotInSource">
            <summary>
            Get boolean that specifies whether to drop all constraints that do not
            exist in the source model.  
            </summary>
            <value>
            True to drop constraints not in the source model; otherwise, false.
            Default is true.
            </value>
            <remarks>
            This applies to check, default, foreign key, primary key, and unique constraints.
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.DropDmlTriggersNotInSource">
            <summary>
            Get boolean that specifies whether to drop all DML triggers that do not
            exist in the source model.
            </summary>
            <value>
            True to drop DML triggers not in the source model; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.DropExtendedPropertiesNotInSource">
            <summary>
            Get boolean that specifies whether to drop all extended properties that do 
            not exist in the source model.
            </summary>
            <value>
            True to drop extended properties not in the source model; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.DropIndexesNotInSource">
            <summary>
            Get boolean that specifies whether to drop all indexes that do not
            exist in the source model.
            </summary>
            <value>
            True to drop indexes not in the source model; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.DropObjectsNotInSource">
            <summary>
            Get boolean that specifies whether objects that exist in the target but not source should be dropped during deployment.
            </summary>
            <value>
            True if objects that exist in the target but not source should be dropped; otherwise false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.DropPermissionsNotInSource">
            <summary>
            Get boolean that specifies whether to drop all permissions that do not
            exist in the source model.
            </summary>
            <value>
            True to drop permissions not in the source model; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.DropRoleMembersNotInSource">
            <summary>
            Get boolean that specifies whether to drop all role memberships that do not
            exist in the source model.
            </summary>
            <value>
            True to drop role memberships not in the source model; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.DropStatisticsNotInSource">
            <summary>
            Get boolean that specifies whether to drop all statistics that do not
            exist in the source model.
            </summary>
            <value>
            True to drop statistics not in the source model; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.GenerateSmartDefaults">
            <summary>
            Get boolean that specifies whether default values should be generated to populate NULL columns that are constrained to NOT NULL values.
            </summary>
            <value>
            True if default values should be generated; otherwise false.
            Default is false.
            </value>
            <remarks>
            This is useful when needing to add a new NOT NULL column to an existing table with data.
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreAnsiNulls">
            <summary>
            Get boolean that specifies whether to exclude the ANSI_NULL option from 
            consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the ANSI_NULL option; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreAuthorizer">
            <summary>
            Get boolean that specifies whether to exclude the AUTHORIZATION option from 
            consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the AUTHORIZATION option; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreColumnCollation">
            <summary>
            Get boolean that specifies whether to exclude the collation specifier from 
            consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the collation specifier; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreColumnOrder">
            <summary>
            Get boolean that specifies whether to exclude from consideration 
            the order of columns in tables when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in column order; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreComments">
            <summary>
            Get boolean that specifies whether to exclude comments from 
            consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in comments; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreCryptographicProviderFilePath">
            <summary>
            Get boolean that specifies whether to exclude the file specification 
            of a cryptographic provider from consideration when comparing the source and 
            target model.
            </summary>
            <value>
            True to ignore differences in a cryptographic provider's  file specification; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreDdlTriggerOrder">
            <summary>
            Get boolean that specifies whether to exclude DDL trigger order from 
            consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in DDL trigger order; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreDdlTriggerState">
            <summary>
            Get boolean that specifies whether to exclude DDL trigger state from 
            consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in DDL trigger state; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreDefaultSchema">
            <summary>
            Get boolean that specifies whether to exclude the DEFAULT_SCHEMA option from 
            consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the DEFAULT_SCHEMA options; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreDmlTriggerOrder">
            <summary>
            Get boolean that specifies whether to exclude DML trigger order from 
            consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in DDL trigger order; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreDmlTriggerState">
            <summary>
            Get boolean that specifies whether to exclude DML trigger state from 
            consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in DML trigger state; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreExtendedProperties">
            <summary>
            Get boolean that specifies whether to exclude all extended properties from 
            consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in extended properties; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreFileAndLogFilePath">
            <summary>
            Get boolean that specifies whether to exclude the FILENAME option of 
            FILE objects from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the FILENAME option of FILE objects; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreFilegroupPlacement">
            <summary>
            Get boolean that specifies whether to exclude the filegroup specifier 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the filegroup specifier; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreFileSize">
            <summary>
            Get boolean that specifies whether to exclude the SIZE option of FILE objects 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the SIZE option of FILE objects; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreFillFactor">
            <summary>
            Get boolean that specifies whether to exclude the FILLFACTOR option
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the FILLFACTOR option; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreFullTextCatalogFilePath">
            <summary>
            Get boolean that specifies whether to exclude the path specification of 
            FULLTEXT CATALOG objects from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the path specification of FULLTEXT CATALOG objects; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreIdentitySeed">
            <summary>
            Get boolean that specifies whether to exclude the seed value of IDENTITY columns 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the seed value of IDENTITY columns; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreIncrement">
            <summary>
            Get boolean that specifies whether to exclude the increment value of IDENTITY columns 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the increment value of IDENTITY columns; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreIndexOptions">
            <summary>
            Get boolean that specifies whether to exclude differences in index options 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in index options; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreIndexPadding">
            <summary>
            Get boolean that specifies whether to exclude the PAD_INDEX option 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the PAD_INDEX option; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreKeywordCasing">
            <summary>
            Get boolean that specifies whether to exclude difference in the casing of keywords 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the casing of keywords; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreLockHintsOnIndexes">
            <summary>
            Get boolean that specifies whether to exclude the ALLOW_ROW_LOCKS and 
            ALLOW_PAGE_LOGKS options from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore the ALLOW_ROW_LOCKS and ALLOW_PAGE_LOGKS options; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreLoginSids">
            <summary>
            Get boolean that specifies whether to exclude the SID option of the LOGIN object 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore the SID option of the LOGIN object; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreNotForReplication">
            <summary>
            Get boolean that specifies whether to exclude the NOT FOR REPLICATION option 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore the NOT FOR REPLICATION option; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreObjectPlacementOnPartitionScheme">
            <summary>
            Get boolean that specifies whether to exclude the partition scheme object
            from consideration when comparing the source and target model for the following
            objects: Table, Index, Unique Key, Primary Key, and Queue.
            </summary>
            <value>
            True to ignore partition schemes; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnorePartitionSchemes">
            <summary>
            Get boolean that specifies whether to exclude the parameter type and 
            boundary VALUES of a PARTITION FUNCTION from consideration when comparing the 
            source and target model.  Also excludes FILEGROUP and partition function of a 
            PARTITION SCHEMA from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore aspects of partition functions and schemes; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnorePermissions">
            <summary>
            Get boolean that specifies whether to exclude all permission statements 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore all permission statements; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreQuotedIdentifiers">
            <summary>
            Get boolean that specifies whether to exclude the QUOTED_IDENTIFIER option 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore the QUOTED_IDENTIFIER option; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreRoleMembership">
            <summary>
            Get boolean that specifies whether to exclude all ROLE MEMBERSHIP objects 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore ROLE MEMBERSHIP objects; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreRouteLifetime">
            <summary>
            Get boolean that specifies whether to exclude the LIFETIME option of ROUTE objects 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore the LIFETIME option of ROUTE objects; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreSemicolonBetweenStatements">
            <summary>
            Get boolean that specifies whether to exclude the existence or absence of semi-colons 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore semi-colons; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreTableOptions">
            <summary>
            Get boolean that specifies whether the options on the target table are updated 
            to match the source table.
            </summary>
            <value>
            True to ignore difference in table options and not update the target table; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreUserSettingsObjects">
            <summary>
            Get boolean that specifies whether to exclude user settings 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in user settings; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreWhitespace">
            <summary>
            Get boolean that specifies whether to exclude whitespace 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences whitespace; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreWithNocheckOnCheckConstraints">
            <summary>
            Get boolean that specifies whether to exclude the CHECK|NO CHECK option of a CHECK 
            constraint object from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore the CHECK|NO CHECK option of a CHECK constraint object; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IgnoreWithNocheckOnForeignKeys">
            <summary>
            Get boolean that specifies whether to exclude the CHECK|NO CHECK option of a FOREIGN KEY  
            constraint object from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore the CHECK|NO CHECK option of a FOREIGN KEY constraint object; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IncludeCompositeObjects">
            <summary>
            Get boolean that specifies whether to include referenced, external elements that also 
            compose the source model and then update the target database in a single deployment operation.
            </summary>
            <value>
            True to include composite objects; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.IncludeTransactionalScripts">
            <summary>
            Get boolean that specifies whether to use transations during the deployment operation 
            and commit the transaction after all changes are successfully applied.
            </summary>
            <value>
            True to use transactions during deployment; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.NoAlterStatementsToChangeClrTypes">
            <summary>
            Get boolean that specifies whether to force a change to CLR assemblies by dropping and recreating them.
            </summary>
            <value>
            True if CLR assemblies should be dropped; otherwise false to allow ALTER statements to change CLR assemblies.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.PopulateFilesOnFileGroups">
            <summary>
            Get boolean that specifies whether files are supplied for filegroups defined in the deployment source.
            </summary>
            <value>
            True to specify files for filegroups; otherwise false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.RegisterDataTierApplication">
            <summary>
            Get boolean that specifies whether the database will be registered as a Data-Tier Application.  
            If the target database is already a registered Data-Tier Application, then the registration will be updated.
            </summary>
            <value>
            True to register the database as a Data-Tier Application; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.ScriptDatabaseCollation">
            <summary>
            Get boolean that specifies whether the target database should be altered to match the 
            source model's collation.
            </summary>
            <value>
            True to alter the target database's collation; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.ScriptDatabaseCompatibility">
            <summary>
            Get boolean that specifies whether the target database should be altered to match the 
            source model's compatibility level.
            </summary>
            <value>
            True to alter the target database's compatibility level; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.ScriptDatabaseOptions">
            <summary>
            Get boolean that specifies whether the database options in the target database should 
            be updated to match the source model.
            </summary>
            <value>
            True to alter the target database's options; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.ScriptDeployStateChecks">
            <summary>
            Get boolean that specifies whether the target database should be checked to ensure that 
            it exists, is online and can be updated.
            </summary>
            <value>
            True to perform state checks on the target database; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.ScriptFileSize">
            <summary>
            Get boolean that specifies whether a file size is specified when adding files to file groups.
            </summary>
            <value>
            True to specify a file size when adding files to file groups; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.ScriptNewConstraintValidation">
            <summary>
            Get boolean that specifies whether constraints are validated after all changes are applied.
            </summary>
            <value>
            True to validate check constraints; otherwise, false.
            Default is true.
            </value>
            <remarks>
            Constraints are always added with NOCHECK option; as a result their validation is skipped during creation.
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.ScriptRefreshModule">
            <summary>
            Get boolean that specifies whether referencing procedures are refreshed when referenced objects are updated.
            </summary>
            <value>
            True to refresh referencing procedures; otherwise false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.TargetConnectionString">
            <summary>
            Get string that specifies the target connection string
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.TargetDatabaseExists">
            <summary>
            Gets boolean that if set specifies whether the target database exists
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.TargetDatabaseName">
            <summary>
            Gets string that specifies the target database name
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.TargetingServerless">
            <summary>
            Get boolean that specifies whether the target server is LocalDB
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.TreatVerificationErrorsAsWarnings">
            <summary>
            Get boolean that specifies whether to treat errors that occur during publish verification as warnings. 
            The check is performed against the generated deployment plan before the plan is executed against the target database. 
            Plan verification detects problems, such as the loss of target-only objects (for example, indexes), that must be 
            dropped to make a change. Verification also detects situations where dependencies (such as tables or views) exist 
            because of a reference to a composite project, but do not exist in the target database. You might choose to treat 
            verification errors as warnings to get a complete list of issues instead of allowing the publish 
            action to stop when the first error occurs.
            </summary>
            <value>
            True to treat errors as warnings; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.UnmodifiableObjectWarnings">
            <summary>
            Get boolean that specifies whether warnings should be generated when differences are found 
            in objects that cannot be modified, for example, if the file size or file paths were different for a file.
            </summary>
            <value>
            True to generate warnings; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.VerifyCollationCompatibility">
            <summary>
            Get boolean that specifies whether deployment will verify that the collation specified in the 
            source model is compatible with the collation specified in the target model.
            </summary>
            <value>
            True to continue if errors are generated during plan verification; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.VerifyDeployment">
            <summary>
            Get boolean that specifies whether the plan verification phase is executed or not.
            </summary>
            <value>
            True to perform plan verification; otherwise, false to skip it.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.SqlDeploymentOptions.SqlCommandVariableValues">
            <summary>
            Get dictionary of SQL command variable values, keyed by variable name.
            </summary>
            <value>
            Dictionary of SQL command variable values, keyed by variable name.
            </value>
            <remarks>
            Valid values must be provided for every variable before deployment, or failures may occur during deployment.
            </remarks>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes">
            <summary>
            Defines the type of objects to query from the model.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes.None">
            <summary>
            Filter out all elements.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes.UserDefined">
            <summary>
            Query user defined objects.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes.BuiltIn">
            <summary>
            Query built in system objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes.SameDatabase">
            <summary>
            Query user defined objects from referenced models where the referenced model is for the same database.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes.System">
            <summary>
            Query System objects that are not treated as built in. These are objects that appear when the master
            database is referenced
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes.DifferentDatabaseSameServer">
            <summary>
            Query references to external objects that are from a different database on the same server.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes.DifferentDatabaseDifferentServer">
            <summary>
            Query references to external objects that are from a different database on a different same server.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes.Default">
            <summary>
            Default query scope is to query both <see cref="F:Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes.UserDefined"/>
            and <see cref="F:Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes.BuiltIn"/> query scopes
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes.All">
            <summary>
            All elements in the model, including references to external elements.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DacModelError">
            <summary>
            Represents a model blocking error.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelError.ErrorType">
            <summary>
            Type of model blocking error
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelError.ErrorCode">
            <summary>
            DacModelError error code
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelError.Line">
            <summary>
            Line Number of the error
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelError.Column">
            <summary>
            Column Number of the error
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelError.Prefix">
            <summary>
            DacModelError prefix
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelError.Message">
            <summary>
            Message from DacModelError
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelError.SourceName">
            <summary>
            The TSqlObject with error. 
            Can be null if the object creation failed completely.
            Could be a partially constructed object in case of partial failures in object creation.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelError.SourceType">
            <summary>
            Type of the TSqlObject associated with the error
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelError.Severity">
            <summary>
            Severity of the error
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DisplayServices">
            <summary>
            Provides a set of services for providing user-visible values for objects in the public model API.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.DisplayServices.GetEscapedNameString(System.String)">
            <summary>
            Pass in a short name string, return back an escaped version of the name string.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.DisplayServices.GetElementName(Microsoft.SqlServer.Dac.Model.TSqlObject,Microsoft.SqlServer.Dac.Model.ElementNameStyle)">
            <summary>
            Get element name string using different display style.
            </summary>
            <param name="element"><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> </param>
            <param name="style"></param>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.DisplayServices.GetDisplayName(Microsoft.SqlServer.Dac.Model.ObjectIdentifier,Microsoft.SqlServer.Dac.Model.EscapeStyle,System.Boolean)">
            <summary>
            Get display name of an identifier, with the option to configure use of full/short name and whether to escape name parts.
            </summary>
            <param name="identifier">The name identifier that can contain multiple parts.</param>
            <param name="escapeStyle"><see cref="T:Microsoft.SqlServer.Dac.Model.EscapeStyle"/> defining whether the parts of the name should be escaped or not</param>
            <param name="fullName">Indicates if the name is constructed in full or only the significant last part is used.</param>
            <returns>Display name</returns>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ElementNameStyle">
            <summary>
            Defines the different naming styles supported by the display services
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ElementNameStyle.Unknown">
            <summary>
            Unknown or undefined style - should be avoided
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ElementNameStyle.SimpleName">
            <summary>
            A non-escaped short name style.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ElementNameStyle.EscapedSimpleName">
            <summary>
            An escaped short name style.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ElementNameStyle.FullyQualifiedName">
            <summary>
            A non-escaped fully qualified name style.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ElementNameStyle.EscapedFullyQualifiedName">
            <summary>
            An escaped fully qualified name style.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.EscapeStyle">
            <summary>
            Enum to specify escape style for displaying model name
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EscapeStyle.Escape">
            <summary>
            Names should be escaped
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EscapeStyle.DontEscape">
            <summary>
            Names should not be escaped
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EscapeStyle.EscapeIfNecessary">
            <summary>
            Names should be escaped if not doing so would cause errors
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ElementWithCommentedScriptBody`1">
            <summary>
            Base class for elements with commented out script body
            Parses the given script with all known prior platform parsers until the script is successfully parsed.
            On successful parssing, extracts the TSqlStatment specified by the type parameter T
            </summary>
            <typeparam name="T">The create sql statement</typeparam>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ElementWithCommentedScriptBody`1.GetParsedFragment">
            <summary>
            Parse the script with all known prior parsers
            </summary>
            <returns>Successfully parsed TSqlFragment parsed. null if not able to parse</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ElementWithCommentedScriptBody`1.ExtractSingleTSqlStatement">
            <summary>
            Extract the single TSQLStatment contained within the successfully parsed script.
            </summary>
            <returns>Single TSQLStatment within the successfully parsed script.</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ElementWithCommentedScriptBody`1.GetTSqlScriptWithCommentedScriptBody">
            <summary>
            Implemented by inherited members to comment out the script body of the Statement
            </summary>
            <returns>TSqlScipt of the element with commented out script body</returns>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ElementWithCommentedScriptBody`1.SqlPlatform">
            <summary>
            The SqlPlatform parser to first employ when trying to parse the script
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ElementWithCommentedScriptBody`1.ParsedFragment">
            <summary>
            Contains the successfully parsed TSqlFragment parsed by some prior platform parser.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ElementWithCommentedScriptBody`1.Statement">
            <summary>
            The single TSQLStatment contained within the script that was successfully parsed by some prior platform parser.
            Unpon construction, null value for Statement denotes either script was not successfully parsed or there were more than one statements.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ModelAnnotationPropertyContext">
            <summary>
            Property context for properties that are converted from annotations in the internal model.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ExternalDefinitionMetadataContext">
            <summary>
            <see cref="T:Microsoft.SqlServer.Dac.Model.ModelMetadataContext"/> implementation that handles external definition actions. These
            define a mapping from an internal <see cref="T:Microsoft.Data.Tools.Schema.SchemaModel.ModelElementClass"/> to a value in a public Enum type.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ElementDescriptor">
            <summary>
            Describes a SQL model element without instantiating a <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> in the
            <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/>.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ElementDescriptor.GetModelElement(Microsoft.SqlServer.Dac.Model.TSqlModel)">
            <summary>
            Gets the corresponding <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> that matches this descriptor from a model.
            If no object matches the descriptor then null will be returned
            </summary>
            <param name="model"><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> the object should be found in</param>
            <returns>
            <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> that this <see cref="T:Microsoft.SqlServer.Dac.Model.ElementDescriptor"/> maps to, or null
            if no object definitively matches this descriptor
            </returns>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ElementDescriptor.IsEmpty">
            <summary>
            Returns if descriptor is empty (doesn't contain any identifiers).  It is possible for
            a descriptor to have a generated name - i.e. based on the context of a statement
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ElementDescriptor.HasUsableName">
            <summary>
            Helper to signify whether this descriptor has a name that is usable - i.e. the
            name parts represent the name of a SQL object.  
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ElementDescriptor.IgnoreName">
            <summary>
            Gets if name should be ignored for this descriptor.  It is possible for a
            descriptor to have no name AND IgnoreName == false
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ElementDescriptor.TypeClass">
            <summary>
            Returns back the type class that maps to the ElementType.  
            
            If there is no public mapping for the internal type then null will be returned.
            
            If the internal type maps to more than one element class the first element class
            is returned.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ElementDescriptor.Identifiers">
            <summary>
            The parts of the elements name.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ElementDescriptor.ExternalReferenceParts">
            <summary>
            Returns external parts for elements name
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ElementDescriptorRelevance">
            <summary>
            Specifies how a fragment being visited is related to a descriptor
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ElementDescriptorRelevance.None">
            <summary>
            No relevance or unknown relevance
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ElementDescriptorRelevance.ContainerId">
            <summary>
            The descriptor is related to an object that contains the fragment 
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ElementDescriptorRelevance.SelfId">
            <summary>
            The descriptor represents the same concept as the fragment 
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.CreateProcedureStatementWithCommentedScriptBody">
            <summary>
            Represents substituting a CreateProcedureStatement with commented out script body
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.CreateViewStatementWithCommentedScriptBody">
            <summary>
            Represents substituting a CreateViewStatement with commented out script body
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ModelCollationComparer">
            <summary>
            Comparer that can compare strings and <see cref="T:Microsoft.SqlServer.Dac.Model.ObjectIdentifier"/>s using the collation of a <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/>.
            This can be very useful when comparing objects in the model since comparisons will be consistent with the expected comparison
            results in SQL Server
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelCollationComparer.Equals(System.String,System.String)">
            <summary>
            Compare if two objects are equal.
            </summary>
            <param name="x">Source object.</param>
            <param name="y">Target object.</param>
            <returns>True if equal, otherwise false.</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelCollationComparer.Equals(System.Collections.Generic.IList{System.String},System.Collections.Generic.IList{System.String})">
            <summary>
            Test if two identifiers are equal using collation of this comparer.
            </summary>
            <param name="x">List of name parts in the first identifier.</param>
            <param name="y">List of name parts in the second identifier.</param>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelCollationComparer.Equals(Microsoft.SqlServer.Dac.Model.ObjectIdentifier,Microsoft.SqlServer.Dac.Model.ObjectIdentifier)">
            <summary>
            Test if two identifiers are equal using collation of this comparer.
            </summary>
            <param name="x">The first <see cref="T:Microsoft.SqlServer.Dac.Model.ObjectIdentifier"/>.</param>
            <param name="y">The second <see cref="T:Microsoft.SqlServer.Dac.Model.ObjectIdentifier"/>.</param>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelCollationComparer.GetHashCode(Microsoft.SqlServer.Dac.Model.ObjectIdentifier)">
            <summary>
            Gets a Hashcode for the object that's compatible with the 
            <see cref="M:Microsoft.SqlServer.Dac.Model.ModelCollationComparer.Equals(Microsoft.SqlServer.Dac.Model.ObjectIdentifier,Microsoft.SqlServer.Dac.Model.ObjectIdentifier)"/> method of this comparer
            </summary>
            <param name="obj">The object to get a hashcode for</param>
            <returns>hashcode</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelCollationComparer.GetHashCode(System.Collections.Generic.IList{System.String})">
            <summary>
            Gets a Hashcode for the object that's compatible with the 
            <see cref="M:Microsoft.SqlServer.Dac.Model.ModelCollationComparer.Equals(System.Collections.Generic.IList{System.String},System.Collections.Generic.IList{System.String})"/> method of this comparer
            </summary>
            <param name="obj">The object to get a hashcode for</param>
            <returns>hashcode</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelCollationComparer.GetHashCode(System.String)">
            <summary>
            Gets a Hashcode for the object that's compatible with the 
            <see cref="M:Microsoft.SqlServer.Dac.Model.ModelCollationComparer.Equals(System.String,System.String)"/> method of this comparer
            </summary>
            <param name="obj">The object to get a hashcode for</param>
            <returns>hashcode</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelCollationComparer.Compare(System.String,System.String)">
            <summary>
            Compare two objects using collation of this comparer.
            </summary>
            <param name="x">Source object.</param>
            <param name="y">Target object.</param>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelCollationComparer.Compare(System.Collections.Generic.IList{System.String},System.Collections.Generic.IList{System.String})">
            <summary>
            Compare two objects using collation of this comparer.
            </summary>
            <param name="x">Source object.</param>
            <param name="y">Target object.</param>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelCollationComparer.Compare(Microsoft.SqlServer.Dac.Model.ObjectIdentifier,Microsoft.SqlServer.Dac.Model.ObjectIdentifier)">
            <summary>
            Compare two objects using collation of this comparer.
            </summary>
            <param name="x">Source object.</param>
            <param name="y">Target object.</param>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.InternalModelUtils.IsInlineConstraintOrIndex(Microsoft.Data.Tools.Schema.SchemaModel.IModelElement)">
            <summary>
            Checks if an internal element represents an inline constraint or annotation
            </summary>
            <param name="element">The element to check</param>
            <returns>True if the element is an inline constraint or index. False otherwise.</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.InternalModelUtils.TryGetSingleReferencedElementInfo(Microsoft.Data.Tools.Schema.SchemaModel.ModelRelationshipClass,Microsoft.Data.Tools.Schema.SchemaModel.IModelElement,Microsoft.Data.Tools.Schema.SchemaModel.IModelElement@,Microsoft.Data.Tools.Schema.SchemaModel.ModelIdentifier@)">
            <summary>
            Tries to get info from a relationship on an element. The relationship must have single cardinality.
            If successful the information returned will at a minimum be the <see cref="T:Microsoft.Data.Tools.Schema.SchemaModel.ModelIdentifier"/>
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.PotentialElementDescriptor">
            <summary>
            This class represents an ambigous element descriptor, where it's not fully clear which
            element in the model a descriptor might map to
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PotentialElementDescriptor.Relevance">
            <summary>
            Gets the Relevance associated with the potential descriptor
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SchemaAnalysisService">
            <summary>
            Internal service that links the public <see cref="T:Microsoft.SqlServer.Dac.Model.SchemaAnalyzer"/> code to the internal
            analyzer codebase
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SchemaAnalysisService.CreateAnalysisService(Microsoft.SqlServer.Dac.Model.SchemaAnalyzer)">
            <summary>
            Factory method to construct a service. May want to move this into the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObjectService"/>
            if we ever wanted to abstract away implementation details even further
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SimpleModelRelationshipContext">
            <summary>
            Default Property context for all properties.
            </summary>
            <remarks>
            Provides default implementation for relationship access through the public model.
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SimpleModelRelationshipContext.CollapsedRelationshipClasses">
            <summary>
            The possible relationships for the collapsed reference lookup
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DacModelMessage">
            <summary>
            Represents an error or a warning raised during model validation.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DacModelResources">
            <summary>
              A strongly-typed resource class, for looking up localized strings, etc.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.ResourceManager">
            <summary>
              Returns the cached ResourceManager instance used by this class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.Culture">
            <summary>
              Overrides the current thread's CurrentUICulture property for all
              resource lookups using this strongly typed resource class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.AddObjectsErrorAddingObjects">
            <summary>
              Looks up a localized string similar to Add or update objects failed due to the following errors: .
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.AddObjectsModelErrorsExist">
            <summary>
              Looks up a localized string similar to Cannot add or update objects. The model has build blocking errors:.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.AstNotRetrieved">
            <summary>
              Looks up a localized string similar to The AST could not be retrieved for the specified object..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.AstNotSupportedError">
            <summary>
              Looks up a localized string similar to AST retrieval not supported for the specified object..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.AutoGeneratedCommentedScriptBodyText">
            <summary>
              Looks up a localized string similar to \nAuto generated text: The original script body has been commented in order to add this object to the model.\n.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.ConvertObject_SourceNameDifferentFromObjectSource">
            <summary>
              Looks up a localized string similar to Cannot convert object to script. The source name &apos;{0}&apos; does not match existing source name &apos;{1}&apos;. Changing source names is not supported..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.ConvertObject_SourceNameExists">
            <summary>
              Looks up a localized string similar to Cannot convert object to script. The source name &apos;{0}&apos; is already in use in this model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.ConvertObject_WhitespaceNotAllowed">
            <summary>
              Looks up a localized string similar to Source name cannot consist of whitespace.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.DacpacLoadReferenceError">
            <summary>
              Looks up a localized string similar to Cannot load package &apos;{0}&apos;. Required references are missing..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.DeleteObjectsErrorDeletingObjects">
            <summary>
              Looks up a localized string similar to Delete objects failed due to the following errors: .
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.DeleteObjectsModelErrorsExist">
            <summary>
              Looks up a localized string similar to Cannot delete objects from the model. The model has build blocking errors:.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.ErrorScriptNameValidation">
            <summary>
              Looks up a localized string similar to {0}: parameter {1} cannot be null, the empty string, all whitespace, or end in &quot;.xsd&quot;.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.GetObjectsTopLevelTypesRequiredError">
            <summary>
              Looks up a localized string similar to Type &apos;{0}&apos; is not a top-level type. Only top-level types can be queried for using the TSqlModel GetObject(s) methods..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.InconsistentPropertyTypes">
            <summary>
              Looks up a localized string similar to Not all property types match expected type &apos;{0}&apos;..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.InternalPropertyMappingInvalid">
            <summary>
              Looks up a localized string similar to Internal Error. No internal property mapped on internal type {0} for public property {1}..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.InternalPropertyTypeMismatchErrorMessage">
            <summary>
              Looks up a localized string similar to Internal Error. Data types for internal properties &apos;{0}.{1}&apos; and &apos;{2}.{3}&apos; do not match..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.InternalRelationshipMappingInvalid">
            <summary>
              Looks up a localized string similar to No internal relationship mapped on internal type {0} for public relationship {1}..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.InternalTypeMappingInvalid">
            <summary>
              Looks up a localized string similar to Internal Error. No public type mapping was found for internal type {0}, for element with id {1}..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.InvalidContextObjectErrorMessage">
            <summary>
              Looks up a localized string similar to Internal Error. Context object must implement ISqlModelElement..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.InvalidContextObjectForDefaultErrorMessage">
            <summary>
              Looks up a localized string similar to Internal Error. There is no context object to derive a default from..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.InvalidMetadataContextErrorMessage">
            <summary>
              Looks up a localized string similar to Metadata {0} has an invalid context type..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.InvalidMetadataTypeErrorMessage">
            <summary>
              Looks up a localized string similar to Data type {1} for metadata {0} cannot be cast to {2}..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.InvalidModelElementErrorMessage">
            <summary>
              Looks up a localized string similar to Internal Error. Internal elements must implement IModelElement..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.InvalidNavigationPathRelationship">
            <summary>
              Looks up a localized string similar to Relationship &apos;{0}.{1}&apos; cannot be used for type collapsing navigation as it is a one-to-many relationship..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.InvalidPropertyContextErrorMessage">
            <summary>
              Looks up a localized string similar to Property {0} has an invalid context type..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.InvalidPropertyTypeErrorMessage">
            <summary>
              Looks up a localized string similar to Data type {1} for property {0} cannot be cast to {2}..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.InvalidRelationshipContextErrorMessage">
            <summary>
              Looks up a localized string similar to Relationship {0} has an invalid context type..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.InvalidTypeErrorMessage">
            <summary>
              Looks up a localized string similar to Data type {0} cannot be cast to {1}..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.InvalidTypeNameErrorMessage">
            <summary>
              Looks up a localized string similar to The type name {0} is not valid..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.LoadScriptBackedModelFailed">
            <summary>
              Looks up a localized string similar to Loading source as a script-backed model failed due to the following errors:.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.MetadataDoesNotMapEnumErrorMessage">
            <summary>
              Looks up a localized string similar to Internal error. Type &apos;{0}&apos; is not an Enum, expected Enum for GetMetadata.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.MetadataNotSupportedOnTypeErrorMessage">
            <summary>
              Looks up a localized string similar to ModelMetadataClass {0} is not supported on type {1}..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.MissingMetadataMappingErrorMessage">
            <summary>
              Looks up a localized string similar to Metadata context must be mapped to at least one internal property..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.MissingPropertyMappingErrorMessage">
            <summary>
              Looks up a localized string similar to Internal Error. Property context must be mapped to at least one internal property..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.MissingReference">
            <summary>
              Looks up a localized string similar to No file was supplied for reference {0}; model load might fail. When {1} was created, the original referenced file was located {2}..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.MissingReference_NoPackagePath">
            <summary>
              Looks up a localized string similar to No file was supplied for reference {0}; model load might fail. When package was created, the original referenced file was located {1}..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.MissingRelationshipMappingErrorMessage">
            <summary>
              Looks up a localized string similar to Context must include at least one internal relationship mapping.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.ModelDisposedError">
            <summary>
              Looks up a localized string similar to The underlying model has been disposed..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.ModelErrorsExist">
            <summary>
              Looks up a localized string similar to The model has build blocking errors:.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.MoreThanOneObjectMatchedId">
            <summary>
              Looks up a localized string similar to More than one object matched the ID &apos;{0}&apos;..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.NoValidEnumForMetadata">
            <summary>
              Looks up a localized string similar to Type &apos;{0}&apos; does not have a mapping for the int value &apos;{1}&apos;.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.PropertiesNotSupportedForRelationshipError">
            <summary>
              Looks up a localized string similar to Properties are not supported on ModelRelationshipInstances for Relationship {0}.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.PropertyNotSupportedOnRelationshipErrorMessage">
            <summary>
              Looks up a localized string similar to ModelPropertyClass {0} is not supported on relationship {1}..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.PropertyNotSupportedOnTypeErrorMessage">
            <summary>
              Looks up a localized string similar to ModelPropertyClass {0} is not supported on type {1}..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.PublicContributorThrewExceptionMessage">
            <summary>
              Looks up a localized string similar to DeploymentContributor &apos;{0}&apos; threw exception. Message is: &apos;{1}&apos;.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.RelationshipNotSupportedOnTypeErrorMessage">
            <summary>
              Looks up a localized string similar to ModelRelationshipClass {0} is not supported on type {1}..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.SaveModelErrorsExist">
            <summary>
              Looks up a localized string similar to Cannot save package to file. The model has build blocking errors:.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.ScriptNotRetrieved">
            <summary>
              Looks up a localized string similar to The script could not be retrieved for the specified object..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.ScriptNotSupportedError">
            <summary>
              Looks up a localized string similar to Script retrieval not supported for the specified object..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.ServiceDisposedError">
            <summary>
              Looks up a localized string similar to The underlying model service has been disposed..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.UpdateModelErr">
            <summary>
              Looks up a localized string similar to Error updating model..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.UpdateModelErr_PackageContainsData">
            <summary>
              Looks up a localized string similar to Cannot update the model as the package contains data. This is not supported since it could cause errors during deployment.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DacModelResources.UpdateModelErr_UnsupportedDacpacVersion">
            <summary>
              Looks up a localized string similar to Updating package with version &apos;{0}&apos; is not supported. Only packages with version 3.0 or higher are supported for update..
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes">
            <summary>
            Defines the type of objects to query from the model.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.None">
            <summary>
            Filter out all elements.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.UserDefined">
            <summary>
            Query user defined objects.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.BuiltIn">
            <summary>
            Query built in system objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.SameDatabase">
            <summary>
            Query user defined objects from referenced models where the referenced model is for the same database.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.System">
            <summary>
            Query System objects that are not treated as built in. These are objects that appear when the master
            database is referenced
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.Default">
            <summary>
            Default query scope is to query both <see cref="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.UserDefined"/>
            and <see cref="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.BuiltIn"/> query scopes
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.All">
            <summary>
            All elements in the model, not including references to external elements in non-system databases.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlElementDescriptor.Equals(System.Object)">
            <summary>
            <see cref="M:System.Object.Equals(System.Object)"/>
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlElementDescriptor.GetHashCode">
            <summary>
            <see cref="M:System.Object.GetHashCode"/>
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SqlModelCollationComparer">
            <summary>
            Internal SQL implementation of the <see cref="T:Microsoft.SqlServer.Dac.Model.ModelCollationComparer"/>. Uses the
            comparer built into an internal model for the comparison
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SqlSchemaModelLoader">
            <summary>
            Responsible for loading a model from a dacpac
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SqlSchemaModelLoader.ModelHeaderDataLoader">
            <summary>
            Loads references, SqlCmd variables, and refactor log data from a dacpac
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObjectService.ConvertToScriptedModel(System.Threading.CancellationToken)">
            <summary>
            Converts objects in a given scope into scriptable objects by deleting the internal representation of
            user defined objects and recreating them with a script-backed representation
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObjectService.ConvertToScriptedObject(Microsoft.SqlServer.Dac.Model.TSqlObject,System.String)">
            <summary>
            Converts a specific top-level object in the model into a scripted representation of itself. This is done
            by scripting out the element, then dropping this element, and finally adding it back in and resolving the model
            </summary>
            <returns>New copy of the TSqlObject, which will now be script-backed</returns>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">If the object could not be scripted out, this class of object is never scriptable,
            or errors were found in the model during the script process </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.#ctor(Microsoft.SqlServer.Dac.Model.TSqlModelSchema,Microsoft.Data.Tools.Schema.SchemaModel.DataSchemaModel)">
            <summary>
            Internal for testing purposes only. Use SqlSchemaModelObjectService(InternalModel.DataSchemaModel model)for
            product code.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.#ctor(Microsoft.Data.Tools.Schema.SchemaModel.DataSchemaModel)">
            <summary>
            Public constructor to be used by product code
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.CreateParserRepository">
            <summary>
            Initialize TSqlParserRepository
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.SetScriptBacked(System.Boolean)">
            <summary>
            Internal method that enables setting whether the model is script-backed or not. This can be used to
            warn about code analysis running against a non-scripted model, for instance.
            </summary>
            <param name="isScriptBacked"></param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.TryGetObject(Microsoft.Data.Tools.Schema.SchemaModel.IModelElement,Microsoft.SqlServer.Dac.Model.TSqlObject@)">
            <summary>
            Internal utility method - wraps an internal model element in a public TSqlObject. Should never be exposed as part of the service.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.GetObjects(System.String,Microsoft.SqlServer.Dac.Model.ModelTypeClass[])">
            <summary>
            Retrieves all TSqlObjects in a given source document filtered by ModelTypeClass specified by the types parameter
            </summary>
            <param name="sourceName">Name of the source document</param>
            <param name="types">Array of ModelTypeClass that the resulting TSqlObject should be filtered on. 
            If the parameter is a empty list, all objects will be returned.</param>
            <returns>List of TSqlObjects</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.GetModelErrors">
            <summary>
            Retrieves all model errors.
            </summary>
            <returns>List of model errors</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.GetModelIdForNamedObjectId(Microsoft.SqlServer.Dac.Model.ObjectIdentifier)">
            <summary>
            Gets the internal that matches a public ID
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.GetAsValidIModelElement(System.Object)">
            <summary>
            Converts an object to an IModelElement, throwing if the cast is invalid
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.IsToplevelObject(Microsoft.SqlServer.Dac.Model.TSqlObject)">
            <summary>
            Returns if an object's create script is a top level T-SQL statement.
            </summary>
            <param name="tSqlObject"><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> to query.</param>
            <returns>True if object's create statement is a top level statement.</returns>
            <exception cref="T:System.ArgumentNullException">If <paramref name="tSqlObject"/> is null.</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.TryGetAst(Microsoft.SqlServer.Dac.Model.TSqlObject,Microsoft.SqlServer.TransactSql.ScriptDom.TSqlScript@)">
            <summary>
            Generates the AST for the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>.
            </summary>
            <returns>True is AST generated.</returns>
            <param name="ast">Generated AST.</param>
            <param name="tSqlObject"><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> to query.</param>
            <exception cref="T:System.ArgumentNullException">Thrown if <paramref name="tSqlObject"/> is null.</exception>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">Thrown if the <see cref="P:Microsoft.SqlServer.Dac.Model.TSqlObject.ContextObject"/> property of <paramref name="tSqlObject"/> does not implement correct type.</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.TryGetScript(Microsoft.SqlServer.Dac.Model.TSqlObject,System.String@)">
            <summary>
            Generates the script for the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>.
            </summary>
            <returns>True is script generated.</returns>
            <param name="tSqlObject">The <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> to be scripted</param>
            <param name="script">Generated script.</param>
            <exception cref="T:System.ArgumentNullException">Thrown if <paramref name="tSqlObject"/> is null.</exception>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">Thrown if the <see cref="P:Microsoft.SqlServer.Dac.Model.TSqlObject.ContextObject"/> property of <paramref name="tSqlObject"/> does not implement correct type.</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.CreateCacheIdentifier(System.String)">
            <summary>
            Creates an identifier that is compatible with the internal model's treatment of source names.
            Internally the ScriptCache checks for "MSSQLL::" at the beginning of a source name. 
            
            This indicates that the name isn't a path and shouldn't be auto-expanded based on the current working directory.
            We don't want to treat source names passed into the public API as paths, especially since this would result in 
            the current working directory being added in front of any source name that wasn't a fully qualified path. 
            
            The tradeoff is external users of the API don't get the benefit of us auto-resolving relative paths for them,
            but that's an acceptable tradeoff
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.GetSourceNameFromCacheId(System.String)">
            <summary>
            Removes the "MSSQL::" string from the beginning of a cache identifier to get the source name.
            see <see cref="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.CreateCacheIdentifier(System.String)"/> for more information on why this behavior is needed
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.ExecutePackageOperationWithErrorHandling(System.Action)">
            <summary>
            Performs error handling around an operation on a DacPackage, such as creating or updating
            the package. There are a standard set of exceptions that can be thrown in this case
            </summary>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">Thrown if any error occurs when operating on the package</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.GetSourceInformationInternal(Microsoft.Data.Tools.Schema.SchemaModel.ISourceInformation)">
            <summary>
            Gets source info from an internal source by stripping any cache ID info from the source name
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.ConvertToScriptedObject(Microsoft.SqlServer.Dac.Model.TSqlObject,System.String)">
            <summary>
            Converts a specific top-level object in the model into a scripted representation of itself. This is done
            by scripting out the element, then dropping this element, and finally adding it back in and resolving the model
            </summary>
            <returns>New copy of the TSqlObject, which will now be script-backed</returns>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">If the object could not be scripted out, this class of object is never scriptable,
            or errors were found in the model during the script process </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.ConvertToScriptedObject(Microsoft.SqlServer.Dac.Model.TSqlObject,System.String,System.String)">
            <summary>
            For simplicity, keeping this method private for now. Consider exposing publicly as a perf improvement in scenarios where 
            caller clearly knows that they want to directly replace an unscripted model element (e.g. a table) with a new definition.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.ConvertToScriptedModel(System.Threading.CancellationToken)">
            <summary>
            Converts all user-defined objects in the model into scripted representations of themselves. This is done
            by scripting out the elements we're going to drop, then dropping all these elements, and finally adding them
            back in and resolving the model
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.CollectObjectsToBeRecreated(System.Collections.Generic.Dictionary{System.String,System.Tuple{Microsoft.SqlServer.Dac.Model.TSqlObject,System.String}},System.Threading.CancellationToken)">
            <summary>
            One step in converting objects to a scripted model: Must create script representations of each object to be deleted, 
            since we would like to remove them all and re-add them with only one Resolve operation. Otherwise we would have to 
            resolve after each delete and recreation to avoid unresolved references causing problems during scripting
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.DropAndRecreateElements(System.Collections.Generic.Dictionary{System.String,System.Tuple{Microsoft.SqlServer.Dac.Model.TSqlObject,System.String}},System.Threading.CancellationToken)">
            <summary>
            One step in converting objects to a scripted model: 
            for each of the objects to be dropped and recreated the element, its composed children and inline hierarchical 
            children are all deleted. Then they are added back into the model via the scripted representation of the objects.
            
            Note that this does not call Resolve on the model in order to support multiple updates followed by a single
            resolve, hence the caller must ensure the model is resolved once all these operations are completed.  
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.DoAddOrUpdateSubstitutedObject(Microsoft.Data.Tools.Schema.Sql.SchemaModel.ISqlModelElement,System.String,Microsoft.SqlServer.Dac.Model.TSqlObjectOptions,System.String,System.String)">
            <summary>
            If adding an object to the model fails due to model blocking errors and if the ModelLoadOption is set to not throw on errors,
            the original object is substituted with a replacement object whose errant parts are removed. These errors are common in case of objects with
            old deprecated syntax. 
            This method substitutes stored procedures and views with equivalent new objects that has commented out script body.
            In case of other types of objects, an empty element with just the name of the errant object is added to the model.
            </summary>
            <param name="element">The element that originally failed to add to the model.</param>
            <param name="sourceName">source name of the object</param>
            <param name="options">TSqlObjectOptions for the object</param>
            <param name="script">Script of the object</param>
            <param name="cacheIdentifier">cache identifier for the object</param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.ModelBuilder">
            <summary>
            Internal for testing purposes only
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.DataSchemaModel">
            <summary>
            Internal, only to be accessed by internal services as required.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.ScopeFilter._includeAll">
            <summary>
            If query scope includes all elements, even externals
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.ScopeFilter._includeAllNonExternal">
            <summary>
            If query scope includes all elements, except
            non-Composite external
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.ScopeFilter._includeUserDefined">
            <summary>
            If query scope includes user defined elements
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.ScopeFilter._includeBuiltIn">
            <summary>
            if query scope includes built-in elements
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.ScopeFilter._includeSameDatabase">
            <summary>
            If query scope includes external elements in the same database
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.ScopeFilter._includeSystem">
            <summary>
            If query scope includes elements from system dacpac ("master" reference)
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.ScopeFilter._includeDifferentDatabaseSameServer">
            <summary>
            If query scope includes external elements in a different database on this server (for return of ID only)
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.ScopeFilter._includeDifferentDatabaseDifferentServer">
            <summary>
            If query scope includes external elements in a different database on a separate server (for return of ID only)
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.ScopeFilter.SetupScopeVariables(Microsoft.SqlServer.Dac.Model.DacQueryScopes)">
            <summary>
            Converts <see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> into filter criteria to use when querying the internal model.
            </summary>
            <param name="queryScopes">QueryScope to expand.</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.ScopeFilter.SetupScopeVariables(Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes)">
            <summary>
            Converts <see cref="T:Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes"/> into filter criteria to use when querying the internal model.
            </summary>
            <param name="queryScopes">QueryScope to expand.</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.ScopeFilter.ShouldReturnElement(Microsoft.Data.Tools.Schema.SchemaModel.IModelElement)">
            <summary>
            Determines if the element matches the query criteria. Fully external elements 
            should never be returned from this method, though system elements may be supported.
            </summary>
            <param name="element">Element to consider</param>
            <returns>true if element matches query criteria. Otherwise false.</returns>
            /// <remarks></remarks>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.ScopeFilter.ShouldReturnIdForElement(Microsoft.Data.Tools.Schema.SchemaModel.IModelElement)">
            <summary>
            Determines if the element ID can be returned - external elements will support
            return of the external ID in a relationship instance, but should never support
            return of the actual element. 
            </summary>
            <param name="element">Element to consider</param>
            <returns>true if element matches query criteria. Otherwise false.</returns>
            /// <remarks></remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SqlSchemaModelObjectService.ScopeFilter.QueryFilter">
            <summary>
            filter used when retrieving element
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ModelErrorSeverity">
            <summary>
            Represents the severity level of the model error
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelErrorSeverity.Unknown">
            <summary>
            Severity is unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelErrorSeverity.Error">
            <summary>
            Model error
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelErrorSeverity.Warning">
            <summary>
            Warning in the model
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ModelErrorType">
            <summary>
            The model error type. Represents the various classification of model blocking errors.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelErrorType.ParserError">
            <summary>
            Represents a parser error in an object in the model
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelErrorType.InterpreterError">
            <summary>
            Represents a interpreter error in an object in the model
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelErrorType.ModelValidationError">
            <summary>
            Any other model blocking validation errors.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ModelExtractOptions">
            <summary>
            Defines options that affect the behavior of loading a model from a database.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelExtractOptions.#ctor">
            <summary>
            Construct a new instance of the <see cref="T:Microsoft.SqlServer.Dac.Model.ModelExtractOptions"/> class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelExtractOptions.ExtractReferencedServerScopedElements">
            <summary>
            Get or set boolean that specifies whether server-scoped elements referenced by the source should be extracted.
            </summary>
            <value>
            True if references server-scoped elements should be extracted; otherwise false.
            Default value is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelExtractOptions.ExtractApplicationScopedObjectsOnly">
            <summary>
            Get or set boolean that specifies the scope of objects extracted from the source.
            </summary>
            <value>
            True if only application-scoped objects should be extracted;
            otherwise false to extract all object types.
            Default value is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelExtractOptions.IgnoreExtendedProperties">
            <summary>
            Get or set boolean that specifies whether extended properties should be ignored.
            </summary>
            <value>
            True if extended properties will be ignored; otherwise false.
            Default value is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelExtractOptions.IgnorePermissions">
            <summary>
            Get or set boolean that specifies whether permissions should be ignored.
            </summary>
            <value>
            True if permissions will be ignored; otherwise false.
            Default value is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelExtractOptions.IgnoreUserLoginMappings">
            <summary>
            Get or set boolean that specifies whether mappings between users and logins should be extracted from the source.
            </summary>
            <value>
            True if user login mappings will be ignored; otherwise false.
            Default value is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelExtractOptions.Storage">
            <summary>
            Get the type of backing storage for the schema model used during extraction.
            </summary>
            <value>
            Enumeration value that specifies the type of backing storage for the schema model used during extraction.
            Default value is File.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelExtractOptions.VerifyExtraction">
            <summary>
            Get or set boolean that specifies whether the extracted package should be verified.
            </summary>
            <value>
            True if the package should be verified; otherwise false.
            Default value is false.
            </value> 
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelExtractOptions.LoadAsScriptBackedModel">
            <summary>
            Should the model be loaded so that objects are backed up by scripted representations? In this case objects in the 
            <see cref="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.UserDefined"/> scope will have a source name and source position information. 
            
            When loading from a Dacpac or any other non-scripted source the model will not have source information. This
            means that when running static code analysis using the <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService"/> some rules may not work 
            correctly, and that existing objects in the model could not be replaced using the 
            <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.AddOrUpdateObjects(System.String,System.String,Microsoft.SqlServer.Dac.Model.TSqlObjectOptions)"/> method since there
            is no script with their original definition. For scenarios that use the <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService"/> setting this
            to true is strongly recommended. Similarly if you wish to update existing objects in the model setting this to true may
            be useful.
            
            Note that there is a potentially significant performance cost involved in creating a scripted model. All 
            top level objects in the <see cref="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.UserDefined"/> scope will be scripted out as strings 
            and then replaced with their scripted representations, after which the model will then have to fully resolve all 
            relationships. This will cause a one-time performance hit at the time the model is loaded. 
            </summary>
            <remarks>Default value is false, since there is a performance hit involved in creating a script-backed model from a 
            non-scripted source</remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelExtractOptions.ExtractUsageProperties">
            <summary>
            Usage properties include Table.RowCount, Table.IndexSize, Table.DataSize, Table.UsedPages and Table.DataPages.
            When true, these properties are extracted from the database and are accessible in the model.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ModelLoadOptions">
            <summary>
            Options for loading a model from a data source such as a Dacpac file.
            
            These options can be very important depending on the scenario. For instance
            when running static code analysis using the <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService"/> it is strongly recommended that 
            the <see cref="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.LoadAsScriptBackedModel"/> option be set to true, as many rules expect a fully scripted source and
            may not operate as expected on a non script-backed model. 
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.#ctor">
            <summary>
            Constructs an instance of <see cref="T:Microsoft.SqlServer.Dac.Model.ModelLoadOptions"/> with the default options, which are
            to use <see cref="F:Microsoft.SqlServer.Dac.DacSchemaModelStorageType.Memory"/> storage and to set
            <see cref="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.LoadAsScriptBackedModel"/> to be false.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.#ctor(Microsoft.SqlServer.Dac.DacSchemaModelStorageType,System.Boolean)">
            <summary>
            Constructs an instance of <see cref="T:Microsoft.SqlServer.Dac.Model.ModelLoadOptions"/> with the specified options.
            </summary>
            <param name="modelStorageType">Value for the <see cref="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.ModelStorageType"/> property</param>
            <param name="loadAsScriptBackedModel">Value for the <see cref="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.LoadAsScriptBackedModel"/> property</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.#ctor(Microsoft.SqlServer.Dac.DacSchemaModelStorageType,System.Boolean,System.Boolean)">
            <summary>
            Constructs an instance of <see cref="T:Microsoft.SqlServer.Dac.Model.ModelLoadOptions"/> with the specified options.
            </summary>
            <param name="modelStorageType">Value for the <see cref="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.ModelStorageType"/> property</param>
            <param name="loadAsScriptBackedModel">Value for the <see cref="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.LoadAsScriptBackedModel"/> property</param>
            <param name="throwOnModelErrors">Value for the <see cref="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.ThrowOnModelErrors"/> property</param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.ModelStorageType">
            <summary>
            Should the model be stored in memory or should a file-backed storage be used?
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.LoadAsScriptBackedModel">
            <summary>
            Should the model be loaded so that objects are backed up by scripted representations? In this case objects in the 
            <see cref="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.UserDefined"/> scope will have a source name and source position information. 
            
            When loading from a Dacpac or any other non-scripted source the model will not have source information. This
            means that when running static code analysis using the <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService"/> some rules may not work 
            correctly, and that existing objects in the model could not be replaced using the 
            <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.AddOrUpdateObjects(System.String,System.String,Microsoft.SqlServer.Dac.Model.TSqlObjectOptions)"/> method since there
            is no script with their original definition. For scenarios that use the <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService"/> setting this
            to true is strongly recommended. Similarly if you wish to update existing objects in the model setting this to true may
            be useful.
            
            Note that there is a potentially significant performance cost involved in creating a scripted model. All 
            top level objects in the <see cref="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.UserDefined"/> scope will be scripted out as strings 
            and then replaced with their scripted representations, after which the model will then have to fully resolve all 
            relationships. This will cause a one-time performance hit at the time the model is loaded. 
            </summary>
            <remarks>Default value is false, since there is a performance hit involved in creating a script-backed model from a 
            non-scripted source</remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.ThrowOnModelErrors">
            <summary>
            Defines whether the model edit APIs throw a <see cref="T:Microsoft.SqlServer.Dac.Model.DacModelException"/> if there are any blocking errors present in the model.
            
            When adding a new object or deleting/modifying existing objects in the model using API calls such as 
            <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.AddObjects(System.String)"/>, <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.AddOrUpdateObjects(System.String,System.String,Microsoft.SqlServer.Dac.Model.TSqlObjectOptions)"/>, <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.DeleteObjects(System.String)"/> 
            and <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.ConvertToScriptedObject(Microsoft.SqlServer.Dac.Model.TSqlObject,System.String)"/>, the model throws <see cref="T:Microsoft.SqlServer.Dac.Model.DacModelException"/> signaling 
            the presence of model blocking errors. Model blocking errors indicates the presence of serious errors such as parser, interpreter and other errors in the objects.
            Setting this option to false allows building the model even if it has such serious errors. Subsequently those objects with model errors can be retrieved using the
            <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.GetModelErrors"/> method.
            
            When objects with model blocking errors are added to the model, the object is edited such that errant parts are removed or commented out in a 
            best effort manner to preserve the parts of the object that do not have errors. For instance a stored procedure that has a parser error in the procedure body 
            will have its body commented out before adding to the model. As a worst case the object is completely dropped while preserving the model errors.
            
            Note that current implementation handles objects with model errors as follows
            1) Sql procedures and views are added to the model with commented body.
            2) Other object types are completely dropped while preserving the model errors.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ModelMetadataClass">
            <summary>
            The metadata class for metadata properties.
            </summary>
            <remarks>
            <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModelSchema"/> metadata classes provide access to the structure and instance data
            within a <c>TSqlSchemaModel</c> instance.
            </remarks>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelMetadataClass.GetValue``1(Microsoft.SqlServer.Dac.Model.TSqlObject)">
            <summary>
            Returns the metadata property value.
            </summary>
            <typeparam name="T"><see cref="T:System.Type"/> of the metadata property value.</typeparam>
            <param name="instance"><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> instance to get the metadata property value from.</param>
            <returns>Metadata property value.</returns>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelMetadataClass.Name">
            <summary>
            Metadata property name.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelMetadataClass.DataType">
            <summary>
            Data type of the metadata property.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelMetadataClass.OwningType">
            <summary>
            Owning <see cref="T:Microsoft.SqlServer.Dac.Model.ModelTypeClass"/> for the <see cref="T:Microsoft.SqlServer.Dac.Model.ModelMetadataClass"/>.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ModelPropertyClass">
            <summary>
            The metadata class for properties.
            </summary>
            <remarks>
            <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModelSchema"/> metadata classes provide access to the structure and instance data
            within a <c>TSqlSchemaModel</c> instance.
            </remarks>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelPropertyClass.GetValue``1(Microsoft.SqlServer.Dac.Model.TSqlObject)">
            <summary>
            Returns the property value.
            </summary>
            <typeparam name="T"><see cref="T:System.Type"/> of the property value.</typeparam>
            <param name="instance"><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> instance to get the property value from.</param>
            <returns>Property value.</returns>
            <exception cref="T:System.InvalidCastException">
            If the property value cannot be cast to <typeparamref name="T"/>.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelPropertyClass.GetDefaultValue``1(Microsoft.SqlServer.Dac.Model.SqlServerVersion)">
            <summary>
            Returns the default property value.
            
            Note: for <see cref="F:Microsoft.SqlServer.Dac.Model.SqlServerVersion.SqlAzure"/> the default value may depend on the
            <see cref="P:Microsoft.SqlServer.Dac.Model.TSqlModel.EngineVersion"/> being targeted. This method assumes the current default
            version is being used. To get a default value based on a particular for a particular EngineVersion, please use
            <see cref="M:Microsoft.SqlServer.Dac.Model.ModelPropertyClass.GetDefaultValue``1(Microsoft.SqlServer.Dac.Model.SqlServerVersion,System.Int32)"/>.
            </summary>
            <typeparam name="T"><see cref="T:System.Type"/> of the property value.</typeparam>
            <param name="version">The <see cref="T:Microsoft.SqlServer.Dac.Model.SqlServerVersion"/> to return the default value for.</param>
            <returns>Default value for specified <see cref="T:Microsoft.SqlServer.Dac.Model.SqlServerVersion"/>.</returns>
            <exception cref="T:System.InvalidCastException">
            If the property value cannot be cast to <typeparamref name="T"/>.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelPropertyClass.GetDefaultValue(Microsoft.SqlServer.Dac.Model.SqlServerVersion)">
            <summary>
            Returns the default property value.
            
            Note: for <see cref="F:Microsoft.SqlServer.Dac.Model.SqlServerVersion.SqlAzure"/> the default value may depend on the
            <see cref="P:Microsoft.SqlServer.Dac.Model.TSqlModel.EngineVersion"/> being targeted. This method assumes the current default
            version is being used. To get a default value based on a particular for a particular EngineVersion, please use
            <see cref="M:Microsoft.SqlServer.Dac.Model.ModelPropertyClass.GetDefaultValue(Microsoft.SqlServer.Dac.Model.SqlServerVersion,System.Int32)"/>.
            </summary>
            <param name="version">The <see cref="T:Microsoft.SqlServer.Dac.Model.SqlServerVersion"/> to return the default value for.</param>
            <returns>Default value for specified <see cref="T:Microsoft.SqlServer.Dac.Model.SqlServerVersion"/>.</returns>        
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelPropertyClass.IsDefaultValue(Microsoft.SqlServer.Dac.Model.TSqlObject,Microsoft.SqlServer.Dac.Model.SqlServerVersion)">
            <summary>
            Returns if the value is the platform default value.
            
            Note: for <see cref="F:Microsoft.SqlServer.Dac.Model.SqlServerVersion.SqlAzure"/> the default value may depend on the
            <see cref="P:Microsoft.SqlServer.Dac.Model.TSqlModel.EngineVersion"/> being targeted. This method assumes the current default
            version is being used. To validate the  default value based on a particular for a particular EngineVersion, please use
            <see cref="M:Microsoft.SqlServer.Dac.Model.ModelPropertyClass.IsDefaultValue(Microsoft.SqlServer.Dac.Model.TSqlObject,Microsoft.SqlServer.Dac.Model.SqlServerVersion,System.Int32)"/>.
            </summary>
            <param name="instance"><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> instance to determine the default property value for.</param>
            <param name="version">The <see cref="T:Microsoft.SqlServer.Dac.Model.SqlServerVersion"/> to determine the default value for.</param>
            <returns>True if the property is the platform default. Otherwise false.</returns>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If the supplied <paramref name="instance"/> is not the owner of this property.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelPropertyClass.GetDefaultValue``1(Microsoft.SqlServer.Dac.Model.SqlServerVersion,System.Int32)">
            <summary>
            Returns the default property value.
            Note: for <see cref="F:Microsoft.SqlServer.Dac.Model.SqlServerVersion.SqlAzure"/> the default value may depend on the
            <see cref="P:Microsoft.SqlServer.Dac.Model.TSqlModel.EngineVersion"/> being targeted. 
            </summary>
            <typeparam name="T"><see cref="T:System.Type"/> of the property value.</typeparam>
            <param name="version">The <see cref="T:Microsoft.SqlServer.Dac.Model.SqlServerVersion"/> to return the default value for.</param>
            <param name="engineVersion">
            Optional value for the engine version. This maps to the
            <see cref="P:Microsoft.SqlServer.Dac.Model.TSqlModel.EngineVersion"/> property on a model.
            </param>
            <returns>Default value for specified <see cref="T:Microsoft.SqlServer.Dac.Model.SqlServerVersion"/>.</returns>
            <exception cref="T:System.InvalidCastException">
            If the property value cannot be cast to <typeparamref name="T"/>.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelPropertyClass.GetDefaultValue(Microsoft.SqlServer.Dac.Model.SqlServerVersion,System.Int32)">
            <summary>
            Returns the default property value.
            </summary>
            <param name="version">The <see cref="T:Microsoft.SqlServer.Dac.Model.SqlServerVersion"/> to return the default value for.</param>
            <param name="engineVersion">
            Optional value for the engine version. This maps to the <see cref="P:Microsoft.SqlServer.Dac.Model.TSqlModel.EngineVersion"/> property on a model.
            </param>
            <returns>Default value for specified <see cref="T:Microsoft.SqlServer.Dac.Model.SqlServerVersion"/>.</returns>        
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelPropertyClass.IsDefaultValue(Microsoft.SqlServer.Dac.Model.TSqlObject,Microsoft.SqlServer.Dac.Model.SqlServerVersion,System.Int32)">
            <summary>
            Returns if the value is the platform default value.
            </summary>
            <param name="instance"><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> instance to determine the default property value for.</param>
            <param name="version">The <see cref="T:Microsoft.SqlServer.Dac.Model.SqlServerVersion"/> to determine the default value for.</param>
            <param name="engineVersion">
            Optional value for the engine version. This maps to the <see cref="P:Microsoft.SqlServer.Dac.Model.TSqlModel.EngineVersion"/> property on a model.
            </param>
            <returns>True if the property is the platform default. Otherwise false.</returns>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If the supplied <paramref name="instance"/> is not the owner of this property.
            </exception>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelPropertyClass.Name">
            <summary>
            Property name.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelPropertyClass.DataType">
            <summary>
            Data type of the property.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelPropertyClass.SupportedPlatforms">
            <summary>
            The <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlPlatforms"/> versions on which this relationship is supported.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelPropertyClass.OwningType">
            <summary>
            Owning <see cref="T:Microsoft.SqlServer.Dac.Model.ModelTypeClass"/> for the property, where this 
            property is attached to a Type. Null if this property is on a 
            <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/>
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelPropertyClass.OwningRelationship">
            <summary>
            Owning <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/> for the property, where this 
            property is attached to a Relationship. Null if this property is on a 
            <see cref="T:Microsoft.SqlServer.Dac.Model.ModelTypeClass"/>
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass">
            <summary>
            The metadata class for relationships.
            </summary>
            <remarks>
            <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModelSchema"/> metadata classes provide access to the structure and instance data
            within a <c>TSqlSchemaModel</c> instance.
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass.Name">
            <summary>
            Relationship name.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass.Type">
            <summary>
            Type of the relationship.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass.FromObjectClass">
            <summary>
            The <see cref="T:Microsoft.SqlServer.Dac.Model.ModelTypeClass"/> of the referencing object for the relationship.
            This represents the class of objects the relationship comes from
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass.SupportedPlatforms">
            <summary>
            The <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlPlatforms"/> versions on which this relationship is supported.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass.Properties">
            <summary>
            Properties for the relationship.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance">
            <summary>
            Represents a reference from one <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> to another, which might be unresolved.
            </summary>
            <remarks>
            <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModelSchema"/> metadata classes provide access to the structure and instance data
            within a <c>TSqlModelSchema</c> instance.
            </remarks>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.GetProperty``1(Microsoft.SqlServer.Dac.Model.ModelPropertyClass)">
            <summary>
            Retrieves properties for this relationship instance.
            </summary>
            <typeparam name="T"><see cref="T:System.Type"/> of the property value.</typeparam>
            <param name="property"><see cref="T:Microsoft.SqlServer.Dac.Model.ModelPropertyClass"/> property to retrieve.</param>
            <returns>Property value.</returns>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If the supplied <paramref name="property"/> is not supported on this instance.
            </exception>
            <exception cref="T:System.InvalidCastException">
            If the property type cannot be cast to T.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.GetProperty(Microsoft.SqlServer.Dac.Model.ModelPropertyClass)">
            <summary>
            Retrieves properties for this relationship instance.
            </summary>
            <param name="property"><see cref="T:Microsoft.SqlServer.Dac.Model.ModelPropertyClass"/> property to retrieve.</param>
            <returns>Property value.</returns>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If the supplied <paramref name="property"/> is not supported on this instance.
            </exception>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.Relationship">
            <summary>
            The <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/> this instance represents.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.FromObject">
            <summary>
            The <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> this instance is from. This is the referencing object
            </summary>
            <remarks>
            This property returns null if the relationship is unresolved or refers to elements outside the current <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/>.
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.Object">
            <summary>
            The <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> this instance references. This is the referenced object.
            </summary>
            <remarks>
            This property returns null if the relationship is unresolved or refers to elements outside the current <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/>.
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.ObjectName">
            <summary>
            The <see cref="T:Microsoft.SqlServer.Dac.Model.ObjectIdentifier"/> representing the name of the referenced object.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.PropertyContext">
            <summary>
            The context boject to use for property lookup - if this isn't set then <see cref="M:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.GetProperty``1(Microsoft.SqlServer.Dac.Model.ModelPropertyClass)"/>
            is not supported on this <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance"/>. For internal use only
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.Item(Microsoft.SqlServer.Dac.Model.ModelPropertyClass)">
            <summary>
            Retrieves properties for this relationship instance.
            </summary>
            <param name="property"><see cref="T:Microsoft.SqlServer.Dac.Model.ModelPropertyClass"/> property to retrieve.</param>
            <returns>Property value.</returns>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If the supplied <paramref name="property"/> is not supported on this instance.
            </exception>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ModelSchema">
            <summary>
            Model schema for TSqlModel
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelSchema.InitializeModelSchema">
            <summary>
            The ModelSchema has static state that is extremely useful when navigating a model's
            contents.  Under normal circumstances (use of ) the static state is indirectly initialized and clients 
            can use the state oblivious to how it has been initialized.  In other heads (commandline / API / unit tests) it is possible
            for the static state to be uninitialized prior to it's being used causing unexpected nulls and failures.  When implementing
            a new head that may directly use the ModelSchema prior to instantiating a TSqlModel call this method prior to
            accessing any static state.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelSchema.GetViewSubroutineAndTriggerClasses">
            <summary>
            Gets the set of classes representing Views, Subroutines and Triggers. This is a common set of classes used during
            analysis
            </summary>
            <returns>The <see cref="T:Microsoft.SqlServer.Dac.Model.ModelTypeClass"/>es representing view, subroutines and triggers</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelSchema.GetSubroutineClasses">
            <summary>
            Gets the set of classes representing Subroutines. This is a common set of classes used during
            analysis
            </summary>
            <returns>The <see cref="T:Microsoft.SqlServer.Dac.Model.ModelTypeClass"/>es representing subroutines</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ModelSchema.GetColumnSourceClasses">
            <summary>
            Gets the set of classes representing a potential source of columns. Tables, Views, Functions can all be 
            a source for this
            </summary>
            <returns>The <see cref="T:Microsoft.SqlServer.Dac.Model.ModelTypeClass"/>es representing view, subroutines and triggers</returns>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.SchemaInstance">
            <summary>
            Instance of the model schema
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Column">
            <summary>
            Model type class for Column
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.TableValuedFunction">
            <summary>
            Model type class for TableValuedFunction
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ScalarFunction">
            <summary>
            Model type class for ScalarFunction
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ClrTableOption">
            <summary>
            Model type class for ClrTableOption
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Aggregate">
            <summary>
            Model type class for Aggregate
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ApplicationRole">
            <summary>
            Model type class for ApplicationRole
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Index">
            <summary>
            Model type class for Index
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Assembly">
            <summary>
            Model type class for Assembly
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.AssemblySource">
            <summary>
            Model type class for AssemblySource
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.AsymmetricKey">
            <summary>
            Model type class for AsymmetricKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.AuditAction">
            <summary>
            Model type class for AuditAction
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.AuditActionGroup">
            <summary>
            Model type class for AuditActionGroup
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.AuditActionSpecification">
            <summary>
            Model type class for AuditActionSpecification
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.BrokerPriority">
            <summary>
            Model type class for BrokerPriority
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.BuiltInServerRole">
            <summary>
            Model type class for BuiltInServerRole
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.DataType">
            <summary>
            Model type class for DataType
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Certificate">
            <summary>
            Model type class for Certificate
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.CheckConstraint">
            <summary>
            Model type class for CheckConstraint
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ClrTypeMethod">
            <summary>
            Model type class for ClrTypeMethod
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ClrTypeMethodParameter">
            <summary>
            Model type class for ClrTypeMethodParameter
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ClrTypeProperty">
            <summary>
            Model type class for ClrTypeProperty
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ColumnStoreIndex">
            <summary>
            Model type class for ColumnStoreIndex
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Contract">
            <summary>
            Model type class for Contract
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Credential">
            <summary>
            Model type class for Credential
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.DatabaseCredential">
            <summary>
            Model type class for DatabaseCredential
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.CryptographicProvider">
            <summary>
            Model type class for CryptographicProvider
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.DatabaseAuditSpecification">
            <summary>
            Model type class for DatabaseAuditSpecification
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.DatabaseDdlTrigger">
            <summary>
            Model type class for DatabaseDdlTrigger
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.DatabaseEncryptionKey">
            <summary>
            Model type class for DatabaseEncryptionKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.DatabaseEventNotification">
            <summary>
            Model type class for DatabaseEventNotification
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.DatabaseMirroringLanguageSpecifier">
            <summary>
            Model type class for DatabaseMirroringLanguageSpecifier
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.DatabaseOptions">
            <summary>
            Model type class for DatabaseOptions
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.DataCompressionOption">
            <summary>
            Model type class for DataCompressionOption
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Default">
            <summary>
            Model type class for Default
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.DefaultConstraint">
            <summary>
            Model type class for DefaultConstraint
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.DmlTrigger">
            <summary>
            Model type class for DmlTrigger
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Endpoint">
            <summary>
            Model type class for Endpoint
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ErrorMessage">
            <summary>
            Model type class for ErrorMessage
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.EventGroup">
            <summary>
            Model type class for EventGroup
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.EventSession">
            <summary>
            Model type class for EventSession
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.DatabaseEventSession">
            <summary>
            Model type class for DatabaseEventSession
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.EventSessionAction">
            <summary>
            Model type class for EventSessionAction
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.EventSessionDefinitions">
            <summary>
            Model type class for EventSessionDefinitions
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.EventSessionSetting">
            <summary>
            Model type class for EventSessionSetting
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.EventSessionTarget">
            <summary>
            Model type class for EventSessionTarget
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.EventTypeSpecifier">
            <summary>
            Model type class for EventTypeSpecifier
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ExtendedProcedure">
            <summary>
            Model type class for ExtendedProcedure
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ExtendedProperty">
            <summary>
            Model type class for ExtendedProperty
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ExternalDataSource">
            <summary>
            Model type class for ExternalDataSource
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ExternalFileFormat">
            <summary>
            Model type class for ExternalFileFormat
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ExternalTable">
            <summary>
            Model type class for ExternalTable
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.SqlFile">
            <summary>
            Model type class for SqlFile
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Filegroup">
            <summary>
            Model type class for Filegroup
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ForeignKeyConstraint">
            <summary>
            Model type class for ForeignKeyConstraint
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.FullTextCatalog">
            <summary>
            Model type class for FullTextCatalog
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.FullTextIndex">
            <summary>
            Model type class for FullTextIndex
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.FullTextIndexColumnSpecifier">
            <summary>
            Model type class for FullTextIndexColumnSpecifier
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.FullTextStopList">
            <summary>
            Model type class for FullTextStopList
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.HttpProtocolSpecifier">
            <summary>
            Model type class for HttpProtocolSpecifier
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.LinkedServer">
            <summary>
            Model type class for LinkedServer
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.LinkedServerLogin">
            <summary>
            Model type class for LinkedServerLogin
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Login">
            <summary>
            Model type class for Login
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.MasterKey">
            <summary>
            Model type class for MasterKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.MessageType">
            <summary>
            Model type class for MessageType
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.PartitionFunction">
            <summary>
            Model type class for PartitionFunction
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.PartitionScheme">
            <summary>
            Model type class for PartitionScheme
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.PartitionValue">
            <summary>
            Model type class for PartitionValue
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Permission">
            <summary>
            Model type class for Permission
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.PrimaryKeyConstraint">
            <summary>
            Model type class for PrimaryKeyConstraint
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Procedure">
            <summary>
            Model type class for Procedure
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Queue">
            <summary>
            Model type class for Queue
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.QueueEventNotification">
            <summary>
            Model type class for QueueEventNotification
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.RemoteServiceBinding">
            <summary>
            Model type class for RemoteServiceBinding
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ResourceGovernor">
            <summary>
            Model type class for ResourceGovernor
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ResourcePool">
            <summary>
            Model type class for ResourcePool
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Role">
            <summary>
            Model type class for Role
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.RoleMembership">
            <summary>
            Model type class for RoleMembership
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Route">
            <summary>
            Model type class for Route
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Rule">
            <summary>
            Model type class for Rule
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Schema">
            <summary>
            Model type class for Schema
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.SearchProperty">
            <summary>
            Model type class for SearchProperty
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.SearchPropertyList">
            <summary>
            Model type class for SearchPropertyList
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.SecurityPolicy">
            <summary>
            Model type class for SecurityPolicy
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.SecurityPredicate">
            <summary>
            Model type class for SecurityPredicate
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Sequence">
            <summary>
            Model type class for Sequence
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ServerAudit">
            <summary>
            Model type class for ServerAudit
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ServerAuditSpecification">
            <summary>
            Model type class for ServerAuditSpecification
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ServerDdlTrigger">
            <summary>
            Model type class for ServerDdlTrigger
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ServerEventNotification">
            <summary>
            Model type class for ServerEventNotification
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ServerOptions">
            <summary>
            Model type class for ServerOptions
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ServerRoleMembership">
            <summary>
            Model type class for ServerRoleMembership
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Service">
            <summary>
            Model type class for Service
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.ServiceBrokerLanguageSpecifier">
            <summary>
            Model type class for ServiceBrokerLanguageSpecifier
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Signature">
            <summary>
            Model type class for Signature
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.SignatureEncryptionMechanism">
            <summary>
            Model type class for SignatureEncryptionMechanism
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.SoapLanguageSpecifier">
            <summary>
            Model type class for SoapLanguageSpecifier
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.SoapMethodSpecification">
            <summary>
            Model type class for SoapMethodSpecification
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.SpatialIndex">
            <summary>
            Model type class for SpatialIndex
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Statistics">
            <summary>
            Model type class for Statistics
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Parameter">
            <summary>
            Model type class for Parameter
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.SymmetricKey">
            <summary>
            Model type class for SymmetricKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.SymmetricKeyPassword">
            <summary>
            Model type class for SymmetricKeyPassword
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Synonym">
            <summary>
            Model type class for Synonym
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.Table">
            <summary>
            Model type class for Table
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.FileTable">
            <summary>
            Model type class for FileTable
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.TableType">
            <summary>
            Model type class for TableType
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.TableTypeCheckConstraint">
            <summary>
            Model type class for TableTypeCheckConstraint
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.TableTypeColumn">
            <summary>
            Model type class for TableTypeColumn
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.TableTypeDefaultConstraint">
            <summary>
            Model type class for TableTypeDefaultConstraint
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.TableTypeIndex">
            <summary>
            Model type class for TableTypeIndex
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.TableTypePrimaryKeyConstraint">
            <summary>
            Model type class for TableTypePrimaryKeyConstraint
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.TableTypeUniqueConstraint">
            <summary>
            Model type class for TableTypeUniqueConstraint
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.TcpProtocolSpecifier">
            <summary>
            Model type class for TcpProtocolSpecifier
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.UniqueConstraint">
            <summary>
            Model type class for UniqueConstraint
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.User">
            <summary>
            Model type class for User
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.UserDefinedServerRole">
            <summary>
            Model type class for UserDefinedServerRole
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.UserDefinedType">
            <summary>
            Model type class for UserDefinedType
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.View">
            <summary>
            Model type class for View
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.WorkloadGroup">
            <summary>
            Model type class for WorkloadGroup
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.XmlIndex">
            <summary>
            Model type class for XmlIndex
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.SelectiveXmlIndex">
            <summary>
            Model type class for SelectiveXmlIndex
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.XmlNamespace">
            <summary>
            Model type class for XmlNamespace
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.PromotedNodePathForXQueryType">
            <summary>
            Model type class for PromotedNodePathForXQueryType
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.PromotedNodePathForSqlType">
            <summary>
            Model type class for PromotedNodePathForSqlType
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ModelSchema.XmlSchemaCollection">
            <summary>
            Model type class for XmlSchemaCollection
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ColumnType">
            <summary>
            Specifies the type of Column a TSqlObject represents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ColumnType.Column">
            <summary>
            Column
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ColumnType.ComputedColumn">
            <summary>
            ComputedColumn
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ColumnType.ColumnSet">
            <summary>
            ColumnSet
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.TableTypeColumnType">
            <summary>
            Specifies the type of TableTypeColumn a TSqlObject represents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TableTypeColumnType.Column">
            <summary>
            Column
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TableTypeColumnType.ComputedColumn">
            <summary>
            ComputedColumn
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.FunctionType">
            <summary>
            Specifies the type of Function a TSqlObject represents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.FunctionType.InlineTableValuedFunction">
            <summary>
            InlineTableValuedFunction
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.FunctionType.MultiStatementTableValuedFunction">
            <summary>
            MultiStatementTableValuedFunction
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SqlDataType">
            <summary>
            SQL Server built-in data types
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.Unknown">
            <summary>
            Nothing was defined.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.BigInt">
            <summary>
            Integer (whole number) data from -2^63 (-9,223,372,036,854,775,808) through 2^63-1 (9,223,372,036,854,775,807).
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.Int">
            <summary>
            Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647).
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.SmallInt">
            <summary>
            Integer data from -2^15 (-32,768) through 2^15 - 1 (32,767).
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.TinyInt">
            <summary>
            Integer data from 0 through 255.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.Bit">
            <summary>
            Integer data with either a 1 or 0 value.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.Decimal">
            <summary>
            Fixed precision and scale numeric data from -10^38 +1 through 10^38 -1.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.Numeric">
            <summary>
            Functionally equivalent to decimal.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.Money">
            <summary>
            Monetary data values from -2^63 (-922,337,203,685,477.5808) through 2^63 - 1 (+922,337,203,685,477.5807), with accuracy to a ten-thousandth of a monetary unit.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.SmallMoney">
            <summary>
            Monetary data values from -214,748.3648 through +214,748.3647, with accuracy to a ten-thousandth of a monetary unit.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.Float">
            <summary>
            Floating precision number data with the following valid values: -1.79E + 308 through -2.23E - 308, 0 and 2.23E + 308 through 1.79E + 308.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.Real">
            <summary>
            Floating precision number data with the following valid values: -3.40E + 38 through -1.18E - 38, 0 and 1.18E - 38 through 3.40E + 38.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.DateTime">
            <summary>
            Date and time data from January 1, 1753, through December 31, 9999, with an accuracy of three-hundredths of a second, or 3.33 milliseconds.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.SmallDateTime">
            <summary>
            Date and time data from January 1, 1900, through June 6, 2079, with an accuracy of one minute.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.Char">
            <summary>
            Fixed-length non-Unicode character data with a maximum length of 8,000 characters.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.VarChar">
            <summary>
            Variable-length non-Unicode data with a maximum of 8,000 characters.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.Text">
            <summary>
            Variable-length non-Unicode data with a maximum length of 2^31 - 1 (2,147,483,647) characters.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.NChar">
            <summary>
            Fixed-length Unicode data with a maximum length of 4,000 characters.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.NVarChar">
            <summary>
            Variable-length Unicode data with a maximum length of 4,000 characters. sysname is a system-supplied user-defined data type that is functionally equivalent to nvarchar(128) and is used to reference database object names.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.NText">
            <summary>
            Variable-length Unicode data with a maximum length of 2^30 - 1 (1,073,741,823) characters.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.Binary">
            <summary>
            Fixed-length binary data with a maximum length of 8,000 bytes.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.VarBinary">
            <summary>
            Variable-length binary data with a maximum length of 8,000 bytes.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.Image">
            <summary>
            Variable-length binary data with a maximum length of 2^31 - 1 (2,147,483,647) bytes.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.Cursor">
            <summary>
            A reference to a cursor.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.Variant">
            <summary>
            A data type that stores values of various SQL Server-supported data types, except text, ntext, timestamp, and sql_variant.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.Table">
            <summary>
            A special data type used to store a result set for later processing.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.Timestamp">
            <summary>
            A database-wide unique number that gets updated every time a row gets updated.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.UniqueIdentifier">
            <summary>
            Is a 16-byte GUID
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.Xml">
            <summary>
            xml data type
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.Date">
            <summary>
            Date-only
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.Time">
            <summary>
            Time only
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.DateTime2">
            <summary>
            Combination of data and time types, better precision than DataTime
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.DateTimeOffset">
            <summary>
            Same as DateTime2 with timezone offset added
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlDataType.Rowversion">
            <summary>
            (Alias for Timestamp) A database-wide unique number that gets updated every time a row gets updated.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.PermissionType">
            <summary>
            Sql permissions
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.Insert">
            <summary>
            Insert
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.Select">
            <summary>
            Select
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.Update">
            <summary>
            Update
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.Delete">
            <summary>
            Delete
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.References">
            <summary>
            References
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateDatabase">
            <summary>
            CreateDatabase
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateDefault">
            <summary>
            CreateDefault
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateFunction">
            <summary>
            CreateFunction
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateProcedure">
            <summary>
            CreateProcedure
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateRule">
            <summary>
            CreateRule
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateTable">
            <summary>
            CreateTable
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateView">
            <summary>
            CreateView
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.BackupDatabase">
            <summary>
            BackupDatabase
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.BackupLog">
            <summary>
            BackupLog
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AdministerBulkOperations">
            <summary>
            AdministerBulkOperations
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.Alter">
            <summary>
            Alter
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyApplicationRole">
            <summary>
            AlterAnyApplicationRole
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyAssembly">
            <summary>
            AlterAnyAssembly
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyAsymmetricKey">
            <summary>
            AlterAnyAsymmetricKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyCertificate">
            <summary>
            AlterAnyCertificate
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyConnection">
            <summary>
            AlterAnyConnection
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyContract">
            <summary>
            AlterAnyContract
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyCredential">
            <summary>
            AlterAnyCredential
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyDatabase">
            <summary>
            AlterAnyDatabase
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyDatabaseDdlTrigger">
            <summary>
            AlterAnyDatabaseDdlTrigger
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyDatabaseEventNotification">
            <summary>
            AlterAnyDatabaseEventNotification
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyDataspace">
            <summary>
            AlterAnyDataspace
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyEndpoint">
            <summary>
            AlterAnyEndpoint
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyEventNotification">
            <summary>
            AlterAnyEventNotification
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyFulltextCatalog">
            <summary>
            AlterAnyFulltextCatalog
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyLinkedServer">
            <summary>
            AlterAnyLinkedServer
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyLogin">
            <summary>
            AlterAnyLogin
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyMessageType">
            <summary>
            AlterAnyMessageType
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyRemoteServiceBinding">
            <summary>
            AlterAnyRemoteServiceBinding
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyRole">
            <summary>
            AlterAnyRole
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyRoute">
            <summary>
            AlterAnyRoute
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnySchema">
            <summary>
            AlterAnySchema
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyService">
            <summary>
            AlterAnyService
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnySymmetricKey">
            <summary>
            AlterAnySymmetricKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyUser">
            <summary>
            AlterAnyUser
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterResources">
            <summary>
            AlterResources
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterServerState">
            <summary>
            AlterServerState
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterSettings">
            <summary>
            AlterSettings
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterTrace">
            <summary>
            AlterTrace
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.Authenticate">
            <summary>
            Authenticate
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AuthenticateServer">
            <summary>
            AuthenticateServer
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.Checkpoint">
            <summary>
            Checkpoint
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.Connect">
            <summary>
            Connect
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.ConnectReplication">
            <summary>
            ConnectReplication
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.ConnectSql">
            <summary>
            ConnectSql
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.Control">
            <summary>
            Control
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.ControlServer">
            <summary>
            ControlServer
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateAggregate">
            <summary>
            CreateAggregate
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateAnyDatabase">
            <summary>
            CreateAnyDatabase
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateAssembly">
            <summary>
            CreateAssembly
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateAsymmetricKey">
            <summary>
            CreateAsymmetricKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateCertificate">
            <summary>
            CreateCertificate
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateContract">
            <summary>
            CreateContract
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateDatabaseDdlEventNotification">
            <summary>
            CreateDatabaseDdlEventNotification
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateDdlEventNotification">
            <summary>
            CreateDdlEventNotification
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateEndpoint">
            <summary>
            CreateEndpoint
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateFulltextCatalog">
            <summary>
            CreateFulltextCatalog
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateMessageType">
            <summary>
            CreateMessageType
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateQueue">
            <summary>
            CreateQueue
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateRemoteServiceBinding">
            <summary>
            CreateRemoteServiceBinding
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateRole">
            <summary>
            CreateRole
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateRoute">
            <summary>
            CreateRoute
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateSchema">
            <summary>
            CreateSchema
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateService">
            <summary>
            CreateService
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateSymmetricKey">
            <summary>
            CreateSymmetricKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateSynonym">
            <summary>
            CreateSynonym
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateTraceEventNotification">
            <summary>
            CreateTraceEventNotification
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateType">
            <summary>
            CreateType
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateXmlSchemaCollection">
            <summary>
            CreateXmlSchemaCollection
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.Execute">
            <summary>
            Execute
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.ExternalAccessAssembly">
            <summary>
            ExternalAccessAssembly
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.Impersonate">
            <summary>
            Impersonate
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.Receive">
            <summary>
            Receive
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.Send">
            <summary>
            Send
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.Showplan">
            <summary>
            Showplan
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.Shutdown">
            <summary>
            Shutdown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.SubscribeQueryNotifications">
            <summary>
            SubscribeQueryNotifications
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.TakeOwnership">
            <summary>
            TakeOwnership
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.UnsafeAssembly">
            <summary>
            UnsafeAssembly
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.ViewAnyDatabase">
            <summary>
            ViewAnyDatabase
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.ViewAnyDefinition">
            <summary>
            ViewAnyDefinition
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.ViewChangeTracking">
            <summary>
            ViewChangeTracking
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.ViewDatabaseState">
            <summary>
            ViewDatabaseState
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.ViewDefinition">
            <summary>
            ViewDefinition
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.ViewServerState">
            <summary>
            ViewServerState
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.All">
            <summary>
            All
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyDatabaseAudit">
            <summary>
            AlterAnyDatabaseAudit
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyServerAudit">
            <summary>
            AlterAnyServerAudit
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateSequence">
            <summary>
            CreateSequence
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyServerRole">
            <summary>
            AlterAnyServerRole
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateServerRole">
            <summary>
            CreateServerRole
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.CreateAvailabilityGroup">
            <summary>
            CreateAvailabilityGroup
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyAvailabilityGroup">
            <summary>
            AlterAnyAvailabilityGroup
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyDatabaseEventSession">
            <summary>
            AlterAnyDatabaseEventSession
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.ConnectAnyDatabase">
            <summary>
            ConnectAnyDatabase
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.ImpersonateAnyLogin">
            <summary>
            ImpersonateAnyLogin
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.SelectAllUserSecurables">
            <summary>
            SelectAllUserSecurables
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnySecurityPolicy">
            <summary>
            AlterAnySecurityPolicy
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyColumnEncryptionKey">
            <summary>
            AlterAnyColumnEncryptionKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyColumnMasterKey">
            <summary>
            AlterAnyColumnMasterKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.Unmask">
            <summary>
            Unmask
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyMask">
            <summary>
            AlterAnyMask
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.ViewAnyColumnMasterKeyDefinition">
            <summary>
            ViewAnyColumnMasterKeyDefinition
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.ViewAnyColumnEncryptionKeyDefinition">
            <summary>
            ViewAnyColumnEncryptionKeyDefinition
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyExternalDataSource">
            <summary>
            AlterAnyExternalDataSource
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionType.AlterAnyExternalFileFormat">
            <summary>
            AlterAnyExternalFileFormat
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.AuthenticationModes">
            <summary>
            SQL Server 2005 authentication mode
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuthenticationModes.None">
            <summary>
            None
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuthenticationModes.Basic">
            <summary>
            Basic
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuthenticationModes.Digest">
            <summary>
            Digest
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuthenticationModes.Integrated">
            <summary>
            Integrated
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuthenticationModes.Ntlm">
            <summary>
            Ntlm
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuthenticationModes.Kerberos">
            <summary>
            Kerberos
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuthenticationModes.Negotiate">
            <summary>
            Negotiate
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.LockEscalationMethod">
            <summary>
            The types of lock escalation methods
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.LockEscalationMethod.Table">
            <summary>
            Table
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.LockEscalationMethod.Disable">
            <summary>
            Disable
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.LockEscalationMethod.Auto">
            <summary>
            Auto
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.CharacterSet">
            <summary>
            Possible character sets for SOAP endpoints
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.CharacterSet.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.CharacterSet.Sql">
            <summary>
            Sql
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.CharacterSet.Xml">
            <summary>
            Xml
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DatabaseMirroringRole">
            <summary>
            Database mirroring role types for SQL Server 2005
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DatabaseMirroringRole.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DatabaseMirroringRole.Witness">
            <summary>
            Witness
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DatabaseMirroringRole.Partner">
            <summary>
            Partner
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DatabaseMirroringRole.All">
            <summary>
            All
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.PageVerifyMode">
            <summary>
            Database page verify mode for SQL Server 2005
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PageVerifyMode.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PageVerifyMode.Checksum">
            <summary>
            Checksum
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PageVerifyMode.TornPageDetection">
            <summary>
            TornPageDetection
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PageVerifyMode.None">
            <summary>
            None
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.EncryptionMode">
            <summary>
            Encryption mode for service broker endpoints
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EncryptionMode.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EncryptionMode.Disabled">
            <summary>
            Disabled
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EncryptionMode.Supported">
            <summary>
            Supported
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EncryptionMode.Required">
            <summary>
            Required
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.HttpPorts">
            <summary>
            Listening port types associated with an endpoint.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.HttpPorts.None">
            <summary>
            None
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.HttpPorts.Clear">
            <summary>
            Clear
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.HttpPorts.Ssl">
            <summary>
            Ssl
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SoapLoginType">
            <summary>
            Possible values for LOGIN_TYPE option in SOAP endpoint
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SoapLoginType.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SoapLoginType.Mixed">
            <summary>
            Mixed
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SoapLoginType.Windows">
            <summary>
            Windows
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ParameterizationOption">
            <summary>
            Parameterization options for database
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ParameterizationOption.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ParameterizationOption.Simple">
            <summary>
            Simple
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ParameterizationOption.Forced">
            <summary>
            Forced
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ServiceBrokerEncryptionAlgorithm">
            <summary>
            Possible encryption algorithm options for service broker endpoints
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ServiceBrokerEncryptionAlgorithm.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ServiceBrokerEncryptionAlgorithm.Aes">
            <summary>
            Aes
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ServiceBrokerEncryptionAlgorithm.RC4">
            <summary>
            RC4
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ServiceBrokerOption">
            <summary>
            Possible service broker options for database
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ServiceBrokerOption.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ServiceBrokerOption.EnableBroker">
            <summary>
            EnableBroker
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ServiceBrokerOption.DisableBroker">
            <summary>
            DisableBroker
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ServiceBrokerOption.NewBroker">
            <summary>
            NewBroker
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ServiceBrokerOption.ErrorBrokerConversations">
            <summary>
            ErrorBrokerConversations
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SoapFormat">
            <summary>
            Possible webmethod formats for SOAP endpoints
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SoapFormat.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SoapFormat.AllResults">
            <summary>
            AllResults
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SoapFormat.RowsetsOnly">
            <summary>
            RowsetsOnly
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SoapFormat.None">
            <summary>
            None
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SoapSchema">
            <summary>
            Possible schema options for webmethods in SOAP endpoints
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SoapSchema.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SoapSchema.None">
            <summary>
            None
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SoapSchema.Standard">
            <summary>
            Standard
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SoapSchema.Default">
            <summary>
            Default
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.AssemblyPermissionSet">
            <summary>
            Possible permission sets for an assembly
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AssemblyPermissionSet.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AssemblyPermissionSet.Safe">
            <summary>
            Safe
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AssemblyPermissionSet.ExternalAccess">
            <summary>
            ExternalAccess
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AssemblyPermissionSet.Unsafe">
            <summary>
            Unsafe
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.AsymmetricKeyAlgorithm">
            <summary>
            Algorithm for an asymmetric keys
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AsymmetricKeyAlgorithm.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AsymmetricKeyAlgorithm.Rsa512">
            <summary>
            Rsa512
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AsymmetricKeyAlgorithm.Rsa1024">
            <summary>
            Rsa1024
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AsymmetricKeyAlgorithm.Rsa2048">
            <summary>
            Rsa2048
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SymmetricKeyAlgorithm">
            <summary>
            Algorithms used for symmetric keys
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SymmetricKeyAlgorithm.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SymmetricKeyAlgorithm.Des">
            <summary>
            Des
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SymmetricKeyAlgorithm.TripleDes">
            <summary>
            TripleDes
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SymmetricKeyAlgorithm.RC2">
            <summary>
            RC2
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SymmetricKeyAlgorithm.RC4">
            <summary>
            RC4
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SymmetricKeyAlgorithm.DesX">
            <summary>
            DesX
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SymmetricKeyAlgorithm.Aes128">
            <summary>
            Aes128
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SymmetricKeyAlgorithm.Aes192">
            <summary>
            Aes192
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SymmetricKeyAlgorithm.Aes256">
            <summary>
            Aes256
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SymmetricKeyAlgorithm.RC4128">
            <summary>
            RC4128
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.AuditActionGroupType">
            <summary>
            SQL Server audit action groups
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.None">
            <summary>
            None
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.SuccessfulLogin">
            <summary>
            SuccessfulLogin
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.Logout">
            <summary>
            Logout
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.ServerStateChange">
            <summary>
            ServerStateChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.FailedLogin">
            <summary>
            FailedLogin
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.LoginChangePassword">
            <summary>
            LoginChangePassword
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.ServerRoleMemberChange">
            <summary>
            ServerRoleMemberChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.ServerPrincipalImpersonation">
            <summary>
            ServerPrincipalImpersonation
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.ServerObjectOwnershipChange">
            <summary>
            ServerObjectOwnershipChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.DatabaseMirroringLogin">
            <summary>
            DatabaseMirroringLogin
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.BrokerLogin">
            <summary>
            BrokerLogin
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.ServerPermissionChange">
            <summary>
            ServerPermissionChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.ServerObjectPermissionChange">
            <summary>
            ServerObjectPermissionChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.ServerOperation">
            <summary>
            ServerOperation
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.TraceChange">
            <summary>
            TraceChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.ServerObjectChange">
            <summary>
            ServerObjectChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.ServerPrincipalChange">
            <summary>
            ServerPrincipalChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.DatabasePermissionChange">
            <summary>
            DatabasePermissionChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.SchemaObjectPermissionChange">
            <summary>
            SchemaObjectPermissionChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.DatabaseRoleMemberChange">
            <summary>
            DatabaseRoleMemberChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.ApplicationRoleChangePassword">
            <summary>
            ApplicationRoleChangePassword
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.SchemaObjectAccess">
            <summary>
            SchemaObjectAccess
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.BackupRestore">
            <summary>
            BackupRestore
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.Dbcc">
            <summary>
            Dbcc
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.AuditChange">
            <summary>
            AuditChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.DatabaseChange">
            <summary>
            DatabaseChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.DatabaseObjectChange">
            <summary>
            DatabaseObjectChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.DatabasePrincipalChange">
            <summary>
            DatabasePrincipalChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.SchemaObjectChange">
            <summary>
            SchemaObjectChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.DatabasePrincipalImpersonation">
            <summary>
            DatabasePrincipalImpersonation
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.DatabaseObjectOwnershipChange">
            <summary>
            DatabaseObjectOwnershipChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.DatabaseOwnershipChange">
            <summary>
            DatabaseOwnershipChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.SchemaObjectOwnershipChange">
            <summary>
            SchemaObjectOwnershipChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.DatabaseObjectPermissionChange">
            <summary>
            DatabaseObjectPermissionChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.DatabaseOperation">
            <summary>
            DatabaseOperation
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.DatabaseObjectAccess">
            <summary>
            DatabaseObjectAccess
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.SuccessfulDatabaseAuthenticationGroup">
            <summary>
            SuccessfulDatabaseAuthenticationGroup
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.FailedDatabaseAuthenticationGroup">
            <summary>
            FailedDatabaseAuthenticationGroup
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.DatabaseLogoutGroup">
            <summary>
            DatabaseLogoutGroup
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.UserChangePasswordGroup">
            <summary>
            UserChangePasswordGroup
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.UserDefinedAuditGroup">
            <summary>
            UserDefinedAuditGroup
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.TransactionBegin">
            <summary>
            TransactionBegin
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.TransactionCommit">
            <summary>
            TransactionCommit
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.TransactionRollback">
            <summary>
            TransactionRollback
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.StatementRollback">
            <summary>
            StatementRollback
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditActionGroupType.TransactionGroup">
            <summary>
            TransactionGroup
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.AuditTarget">
            <summary>
            SQL Server audit targets
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditTarget.File">
            <summary>
            File
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditTarget.ApplicationLog">
            <summary>
            ApplicationLog
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuditTarget.SecurityLog">
            <summary>
            SecurityLog
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ChangeTrackingOption">
            <summary>
            Change tracking options
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ChangeTrackingOption.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ChangeTrackingOption.Auto">
            <summary>
            Auto
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ChangeTrackingOption.Manual">
            <summary>
            Manual
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ChangeTrackingOption.Off">
            <summary>
            Off
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SymmetricKeyCreationDisposition">
            <summary>
            Asymmetric key creation disposition
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SymmetricKeyCreationDisposition.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SymmetricKeyCreationDisposition.CreateNew">
            <summary>
            CreateNew
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SymmetricKeyCreationDisposition.OpenExisting">
            <summary>
            OpenExisting
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DatabaseAuditAction">
            <summary>
            Database-level auditable action
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DatabaseAuditAction.Select">
            <summary>
            Select
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DatabaseAuditAction.Update">
            <summary>
            Update
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DatabaseAuditAction.Insert">
            <summary>
            Insert
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DatabaseAuditAction.Delete">
            <summary>
            Delete
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DatabaseAuditAction.Execute">
            <summary>
            Execute
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DatabaseAuditAction.Receive">
            <summary>
            Receive
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DatabaseAuditAction.References">
            <summary>
            References
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.RecoveryMode">
            <summary>
            Database recovery mode
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.RecoveryMode.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.RecoveryMode.Simple">
            <summary>
            Simple
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.RecoveryMode.BulkLogged">
            <summary>
            BulkLogged
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.RecoveryMode.Full">
            <summary>
            Full
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DelayedDurabilityMode">
            <summary>
            Database Delayed Durability mode
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DelayedDurabilityMode.Disabled">
            <summary>
            Disabled
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DelayedDurabilityMode.Allowed">
            <summary>
            Allowed
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DelayedDurabilityMode.Forced">
            <summary>
            Forced
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.UserAccessOption">
            <summary>
            User access mode for the database
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.UserAccessOption.Multiple">
            <summary>
            Multiple
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.UserAccessOption.Restricted">
            <summary>
            Restricted
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.UserAccessOption.Single">
            <summary>
            Single
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.CompressionLevel">
            <summary>
            Compression level for data
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.CompressionLevel.None">
            <summary>
            None
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.CompressionLevel.Row">
            <summary>
            Row
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.CompressionLevel.Page">
            <summary>
            Page
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.CompressionLevel.ColumnStore">
            <summary>
            ColumnStore
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.CompressionLevel.ColumnStoreArchive">
            <summary>
            ColumnStoreArchive
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Degree">
            <summary>
            Grid density level in spatial index
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.Degree.None">
            <summary>
            None
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.Degree.Low">
            <summary>
            Low
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.Degree.Medium">
            <summary>
            Medium
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.Degree.High">
            <summary>
            High
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.State">
            <summary>
            State of the endpoint
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.State.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.State.Disabled">
            <summary>
            Disabled
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.State.Started">
            <summary>
            Started
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.State.Stopped">
            <summary>
            Stopped
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.EventGroupType">
            <summary>
            Sql event groups
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlApplicationRoleEvents">
            <summary>
            DdlApplicationRoleEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlAssemblyEvents">
            <summary>
            DdlAssemblyEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlAuthorizationDatabaseEvents">
            <summary>
            DdlAuthorizationDatabaseEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlAvailabilityGroupEvents">
            <summary>
            DdlAvailabilityGroupEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlCertificateEvents">
            <summary>
            DdlCertificateEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlContractEvents">
            <summary>
            DdlContractEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlDatabaseAuditEvents">
            <summary>
            DdlDatabaseAuditEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlDatabaseLevelEvents">
            <summary>
            DdlDatabaseLevelEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlDatabaseSecurityEvents">
            <summary>
            DdlDatabaseSecurityEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlEventNotificationEvents">
            <summary>
            DdlEventNotificationEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlFunctionEvents">
            <summary>
            DdlFunctionEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlGdrDatabaseEvents">
            <summary>
            DdlGdrDatabaseEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlIndexEvents">
            <summary>
            DdlIndexEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlMessageTypeEvents">
            <summary>
            DdlMessageTypeEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlPartitionEvents">
            <summary>
            DdlPartitionEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlPartitionFunctionEvents">
            <summary>
            DdlPartitionFunctionEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlPartitionSchemeEvents">
            <summary>
            DdlPartitionSchemeEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlProcedureEvents">
            <summary>
            DdlProcedureEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlQueueEvents">
            <summary>
            DdlQueueEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlRemoteServiceBindingEvents">
            <summary>
            DdlRemoteServiceBindingEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlRoleEvents">
            <summary>
            DdlRoleEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlRouteEvents">
            <summary>
            DdlRouteEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlSchemaEvents">
            <summary>
            DdlSchemaEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlSecurityPolicyEvents">
            <summary>
            DdlSecurityPolicyEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlColumnMasterKeyEvents">
            <summary>
            DdlColumnMasterKeyEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlColumnEncryptionKeyEvents">
            <summary>
            DdlColumnEncryptionKeyEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlExternalResourcePoolEvents">
            <summary>
            DdlExternalResourcePoolEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlExternalLibraryEvents">
            <summary>
            DdlExternalLibraryEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlServiceEvents">
            <summary>
            DdlServiceEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlSsbEvents">
            <summary>
            DdlSsbEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlStatisticsEvents">
            <summary>
            DdlStatisticsEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlSynonymEvents">
            <summary>
            DdlSynonymEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlTableEvents">
            <summary>
            DdlTableEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlTableViewEvents">
            <summary>
            DdlTableViewEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlTriggerEvents">
            <summary>
            DdlTriggerEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlTypeEvents">
            <summary>
            DdlTypeEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlUserEvents">
            <summary>
            DdlUserEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlViewEvents">
            <summary>
            DdlViewEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlXmlSchemaCollectionEvents">
            <summary>
            DdlXmlSchemaCollectionEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlAuthorizationServerEvents">
            <summary>
            DdlAuthorizationServerEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlEndpointEvents">
            <summary>
            DdlEndpointEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlEvents">
            <summary>
            DdlEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlGdrServerEvents">
            <summary>
            DdlGdrServerEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlLoginEvents">
            <summary>
            DdlLoginEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlServerLevelEvents">
            <summary>
            DdlServerLevelEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlServerSecurityEvents">
            <summary>
            DdlServerSecurityEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlAsymmetricKeyEvents">
            <summary>
            DdlAsymmetricKeyEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlBrokerPriorityEvents">
            <summary>
            DdlBrokerPriorityEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlCryptoSignatureEvents">
            <summary>
            DdlCryptoSignatureEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlDatabaseAuditSpecificationEvents">
            <summary>
            DdlDatabaseAuditSpecificationEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlDatabaseEncryptionKeyEvents">
            <summary>
            DdlDatabaseEncryptionKeyEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlDefaultEvents">
            <summary>
            DdlDefaultEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlExtendedPropertyEvents">
            <summary>
            DdlExtendedPropertyEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlFullTextCatalogEvents">
            <summary>
            DdlFullTextCatalogEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlFullTextStopListEvents">
            <summary>
            DdlFullTextStopListEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlMasterKeyEvents">
            <summary>
            DdlMasterKeyEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlPlanGuideEvents">
            <summary>
            DdlPlanGuideEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlRuleEvents">
            <summary>
            DdlRuleEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlSearchPropertyListEvents">
            <summary>
            DdlSearchPropertyListEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlSequenceEvents">
            <summary>
            DdlSequenceEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlSymmetricKeyEvents">
            <summary>
            DdlSymmetricKeyEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlCredentialEvents">
            <summary>
            DdlCredentialEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlDatabaseEvents">
            <summary>
            DdlDatabaseEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlCryptographicProviderEvents">
            <summary>
            DdlCryptographicProviderEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlEventSessionEvents">
            <summary>
            DdlEventSessionEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlExtendedProcedureEvents">
            <summary>
            DdlExtendedProcedureEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlLinkedServerEvents">
            <summary>
            DdlLinkedServerEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlLinkedServerLoginEvents">
            <summary>
            DdlLinkedServerLoginEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlMessageEvents">
            <summary>
            DdlMessageEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlRemoteServerEvents">
            <summary>
            DdlRemoteServerEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlResourceGovernorEvents">
            <summary>
            DdlResourceGovernorEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlResourcePool">
            <summary>
            DdlResourcePool
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlServerAuditEvents">
            <summary>
            DdlServerAuditEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlServerAuditSpecificationEvents">
            <summary>
            DdlServerAuditSpecificationEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlServiceMasterKeyEvents">
            <summary>
            DdlServiceMasterKeyEvents
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.DdlWorkloadGroup">
            <summary>
            DdlWorkloadGroup
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.TrcClr">
            <summary>
            TrcClr
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.TrcDatabase">
            <summary>
            TrcDatabase
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.TrcDeprecation">
            <summary>
            TrcDeprecation
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.TrcErrorsAndWarnings">
            <summary>
            TrcErrorsAndWarnings
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.TrcFullText">
            <summary>
            TrcFullText
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.TrcLocks">
            <summary>
            TrcLocks
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.TrcObjects">
            <summary>
            TrcObjects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.TrcOledb">
            <summary>
            TrcOledb
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.TrcPerformance">
            <summary>
            TrcPerformance
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.TrcQueryNotifications">
            <summary>
            TrcQueryNotifications
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.TrcSecurityAudit">
            <summary>
            TrcSecurityAudit
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.TrcServer">
            <summary>
            TrcServer
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.TrcStoredProcedures">
            <summary>
            TrcStoredProcedures
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.TrcTSql">
            <summary>
            TrcTSql
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.TrcUserConfigurable">
            <summary>
            TrcUserConfigurable
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventGroupType.TrcAllEvents">
            <summary>
            TrcAllEvents
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.EventType">
            <summary>
            Sql Server event types
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AddRoleMember">
            <summary>
            AddRoleMember
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterApplicationRole">
            <summary>
            AlterApplicationRole
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterAssembly">
            <summary>
            AlterAssembly
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterAuthorizationDatabase">
            <summary>
            AlterAuthorizationDatabase
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterAvailabilityGroup">
            <summary>
            AlterAvailabilityGroup
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterCertificate">
            <summary>
            AlterCertificate
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterColumnEncryptionKey">
            <summary>
            AlterColumnEncryptionKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterDatabaseAudit">
            <summary>
            AlterDatabaseAudit
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterFunction">
            <summary>
            AlterFunction
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterIndex">
            <summary>
            AlterIndex
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterMessageType">
            <summary>
            AlterMessageType
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterPartitionFunction">
            <summary>
            AlterPartitionFunction
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterPartitionScheme">
            <summary>
            AlterPartitionScheme
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterProcedure">
            <summary>
            AlterProcedure
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterQueue">
            <summary>
            AlterQueue
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterRemoteServiceBinding">
            <summary>
            AlterRemoteServiceBinding
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterRole">
            <summary>
            AlterRole
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterRoute">
            <summary>
            AlterRoute
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterSchema">
            <summary>
            AlterSchema
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterSecurityPolicy">
            <summary>
            AlterSecurityPolicy
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterService">
            <summary>
            AlterService
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterTable">
            <summary>
            AlterTable
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterTrigger">
            <summary>
            AlterTrigger
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterUser">
            <summary>
            AlterUser
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterView">
            <summary>
            AlterView
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterXmlSchemaCollection">
            <summary>
            AlterXmlSchemaCollection
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateApplicationRole">
            <summary>
            CreateApplicationRole
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateAssembly">
            <summary>
            CreateAssembly
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateAvailabilityGroup">
            <summary>
            CreateAvailabilityGroup
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateCertificate">
            <summary>
            CreateCertificate
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateContract">
            <summary>
            CreateContract
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateColumnEncryptionKey">
            <summary>
            CreateColumnEncryptionKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateColumnMasterKey">
            <summary>
            CreateColumnMasterKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateDatabaseAudit">
            <summary>
            CreateDatabaseAudit
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateEventNotification">
            <summary>
            CreateEventNotification
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateFunction">
            <summary>
            CreateFunction
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateIndex">
            <summary>
            CreateIndex
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateMessageType">
            <summary>
            CreateMessageType
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreatePartitionFunction">
            <summary>
            CreatePartitionFunction
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreatePartitionScheme">
            <summary>
            CreatePartitionScheme
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateProcedure">
            <summary>
            CreateProcedure
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateQueue">
            <summary>
            CreateQueue
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateRemoteServiceBinding">
            <summary>
            CreateRemoteServiceBinding
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateRole">
            <summary>
            CreateRole
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateRoute">
            <summary>
            CreateRoute
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateSchema">
            <summary>
            CreateSchema
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateSecurityPolicy">
            <summary>
            CreateSecurityPolicy
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateService">
            <summary>
            CreateService
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateStatistics">
            <summary>
            CreateStatistics
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateSynonym">
            <summary>
            CreateSynonym
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateTable">
            <summary>
            CreateTable
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateTrigger">
            <summary>
            CreateTrigger
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateType">
            <summary>
            CreateType
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateUser">
            <summary>
            CreateUser
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateView">
            <summary>
            CreateView
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateXmlIndex">
            <summary>
            CreateXmlIndex
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateXmlSchemaCollection">
            <summary>
            CreateXmlSchemaCollection
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DenyDatabase">
            <summary>
            DenyDatabase
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropApplicationRole">
            <summary>
            DropApplicationRole
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropAvailabilityGroup">
            <summary>
            DropAvailabilityGroup
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropAssembly">
            <summary>
            DropAssembly
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropCertificate">
            <summary>
            DropCertificate
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropColumnEncryptionKey">
            <summary>
            DropColumnEncryptionKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterDatabaseScopedConfiguration">
            <summary>
            AlterDatabaseScopedConfiguration
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateExternalResourcePool">
            <summary>
            CreateExternalResourcePool
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterExternalResourcePool">
            <summary>
            AlterExternalResourcePool
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropExternalResourcePool">
            <summary>
            DropExternalResourcePool
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateExternalLibrary">
            <summary>
            CreateExternalLibrary
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterExternalLibrary">
            <summary>
            AlterExternalLibrary
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropExternalLibrary">
            <summary>
            DropExternalLibrary
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropColumnMasterKey">
            <summary>
            DropColumnMasterKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropContract">
            <summary>
            DropContract
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropDatabaseAudit">
            <summary>
            DropDatabaseAudit
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropEventNotification">
            <summary>
            DropEventNotification
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropFunction">
            <summary>
            DropFunction
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropIndex">
            <summary>
            DropIndex
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropMessageType">
            <summary>
            DropMessageType
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropPartitionFunction">
            <summary>
            DropPartitionFunction
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropPartitionScheme">
            <summary>
            DropPartitionScheme
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropProcedure">
            <summary>
            DropProcedure
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropQueue">
            <summary>
            DropQueue
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropRemoteServiceBinding">
            <summary>
            DropRemoteServiceBinding
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropRole">
            <summary>
            DropRole
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropRoleMember">
            <summary>
            DropRoleMember
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropRoute">
            <summary>
            DropRoute
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropSchema">
            <summary>
            DropSchema
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropSecurityPolicy">
            <summary>
            DropSecurityPolicy
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropService">
            <summary>
            DropService
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropStatistics">
            <summary>
            DropStatistics
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropSynonym">
            <summary>
            DropSynonym
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropTable">
            <summary>
            DropTable
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropTrigger">
            <summary>
            DropTrigger
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropType">
            <summary>
            DropType
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropUser">
            <summary>
            DropUser
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropView">
            <summary>
            DropView
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropXmlSchemaCollection">
            <summary>
            DropXmlSchemaCollection
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.GrantDatabase">
            <summary>
            GrantDatabase
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.RevokeDatabase">
            <summary>
            RevokeDatabase
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.UpdateStatistics">
            <summary>
            UpdateStatistics
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AddServerRoleMember">
            <summary>
            AddServerRoleMember
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterAuthorizationServer">
            <summary>
            AlterAuthorizationServer
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterDatabase">
            <summary>
            AlterDatabase
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterEndpoint">
            <summary>
            AlterEndpoint
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterLogin">
            <summary>
            AlterLogin
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateDatabase">
            <summary>
            CreateDatabase
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateEndpoint">
            <summary>
            CreateEndpoint
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateLogin">
            <summary>
            CreateLogin
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DenyServer">
            <summary>
            DenyServer
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropDatabase">
            <summary>
            DropDatabase
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropEndpoint">
            <summary>
            DropEndpoint
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropLogin">
            <summary>
            DropLogin
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropServerRoleMember">
            <summary>
            DropServerRoleMember
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.GrantServer">
            <summary>
            GrantServer
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.RevokeServer">
            <summary>
            RevokeServer
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AddSignature">
            <summary>
            AddSignature
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AddSignatureSchemaObject">
            <summary>
            AddSignatureSchemaObject
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterAsymmetricKey">
            <summary>
            AlterAsymmetricKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterBrokerPriority">
            <summary>
            AlterBrokerPriority
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterDatabaseAuditSpecification">
            <summary>
            AlterDatabaseAuditSpecification
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterDatabaseEncryptionKey">
            <summary>
            AlterDatabaseEncryptionKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterExtendedProperty">
            <summary>
            AlterExtendedProperty
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterFullTextCatalog">
            <summary>
            AlterFullTextCatalog
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterFullTextIndex">
            <summary>
            AlterFullTextIndex
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterFullTextStopList">
            <summary>
            AlterFullTextStopList
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterMasterKey">
            <summary>
            AlterMasterKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterPlanGuide">
            <summary>
            AlterPlanGuide
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterSymmetricKey">
            <summary>
            AlterSymmetricKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.BindDefault">
            <summary>
            BindDefault
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.BindRule">
            <summary>
            BindRule
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateAsymmetricKey">
            <summary>
            CreateAsymmetricKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateBrokerPriority">
            <summary>
            CreateBrokerPriority
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateDatabaseAuditSpecification">
            <summary>
            CreateDatabaseAuditSpecification
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateDatabaseEncryptionKey">
            <summary>
            CreateDatabaseEncryptionKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateDefault">
            <summary>
            CreateDefault
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateExtendedProperty">
            <summary>
            CreateExtendedProperty
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateFullTextCatalog">
            <summary>
            CreateFullTextCatalog
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateFullTextIndex">
            <summary>
            CreateFullTextIndex
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateFullTextStopList">
            <summary>
            CreateFullTextStopList
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateMasterKey">
            <summary>
            CreateMasterKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreatePlanGuide">
            <summary>
            CreatePlanGuide
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateRule">
            <summary>
            CreateRule
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateSpatialIndex">
            <summary>
            CreateSpatialIndex
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateSymmetricKey">
            <summary>
            CreateSymmetricKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropAsymmetricKey">
            <summary>
            DropAsymmetricKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropBrokerPriority">
            <summary>
            DropBrokerPriority
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropDatabaseAuditSpecification">
            <summary>
            DropDatabaseAuditSpecification
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropDatabaseEncryptionKey">
            <summary>
            DropDatabaseEncryptionKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropDefault">
            <summary>
            DropDefault
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropExtendedProperty">
            <summary>
            DropExtendedProperty
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropFullTextCatalog">
            <summary>
            DropFullTextCatalog
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropFullTextIndex">
            <summary>
            DropFullTextIndex
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropFullTextStopList">
            <summary>
            DropFullTextStopList
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropMasterKey">
            <summary>
            DropMasterKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropPlanGuide">
            <summary>
            DropPlanGuide
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropRule">
            <summary>
            DropRule
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropSignature">
            <summary>
            DropSignature
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropSignatureSchemaObject">
            <summary>
            DropSignatureSchemaObject
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropSymmetricKey">
            <summary>
            DropSymmetricKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.Rename">
            <summary>
            Rename
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.UnbindDefault">
            <summary>
            UnbindDefault
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.UnbindRule">
            <summary>
            UnbindRule
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterCredential">
            <summary>
            AlterCredential
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterCryptographicProvider">
            <summary>
            AlterCryptographicProvider
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterEventSession">
            <summary>
            AlterEventSession
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterInstance">
            <summary>
            AlterInstance
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterLinkedServer">
            <summary>
            AlterLinkedServer
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterMessage">
            <summary>
            AlterMessage
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterRemoteServer">
            <summary>
            AlterRemoteServer
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterResourceGovernorConfig">
            <summary>
            AlterResourceGovernorConfig
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterResourcePool">
            <summary>
            AlterResourcePool
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterServerAudit">
            <summary>
            AlterServerAudit
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterServerAuditSpecification">
            <summary>
            AlterServerAuditSpecification
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterServiceMasterKey">
            <summary>
            AlterServiceMasterKey
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterWorkloadGroup">
            <summary>
            AlterWorkloadGroup
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateCredential">
            <summary>
            CreateCredential
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateCryptographicProvider">
            <summary>
            CreateCryptographicProvider
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateEventSession">
            <summary>
            CreateEventSession
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateExtendedProcedure">
            <summary>
            CreateExtendedProcedure
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateLinkedServer">
            <summary>
            CreateLinkedServer
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateLinkedServerLogin">
            <summary>
            CreateLinkedServerLogin
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateMessage">
            <summary>
            CreateMessage
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateRemoteServer">
            <summary>
            CreateRemoteServer
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateResourcePool">
            <summary>
            CreateResourcePool
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateServerAudit">
            <summary>
            CreateServerAudit
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateServerAuditSpecification">
            <summary>
            CreateServerAuditSpecification
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateWorkloadGroup">
            <summary>
            CreateWorkloadGroup
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropCredential">
            <summary>
            DropCredential
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropCryptographicProvider">
            <summary>
            DropCryptographicProvider
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropEventSession">
            <summary>
            DropEventSession
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropExtendedProcedure">
            <summary>
            DropExtendedProcedure
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropLinkedServer">
            <summary>
            DropLinkedServer
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropLinkedServerLogin">
            <summary>
            DropLinkedServerLogin
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropMessage">
            <summary>
            DropMessage
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropRemoteServer">
            <summary>
            DropRemoteServer
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropResourcePool">
            <summary>
            DropResourcePool
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropServerAudit">
            <summary>
            DropServerAudit
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropServerAuditSpecification">
            <summary>
            DropServerAuditSpecification
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropWorkloadGroup">
            <summary>
            DropWorkloadGroup
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AssemblyLoad">
            <summary>
            AssemblyLoad
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditAddDbUserEvent">
            <summary>
            AuditAddDbUserEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditAddLoginEvent">
            <summary>
            AuditAddLoginEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditAddLoginToServerRoleEvent">
            <summary>
            AuditAddLoginToServerRoleEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditAddMemberToDbRoleEvent">
            <summary>
            AuditAddMemberToDbRoleEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditAddRoleEvent">
            <summary>
            AuditAddRoleEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditAppRoleChangePasswordEvent">
            <summary>
            AuditAppRoleChangePasswordEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditBackupRestoreEvent">
            <summary>
            AuditBackupRestoreEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditChangeAuditEvent">
            <summary>
            AuditChangeAuditEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditChangeDatabaseOwner">
            <summary>
            AuditChangeDatabaseOwner
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditDatabaseManagementEvent">
            <summary>
            AuditDatabaseManagementEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditDatabaseObjectAccessEvent">
            <summary>
            AuditDatabaseObjectAccessEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditDatabaseObjectGdrEvent">
            <summary>
            AuditDatabaseObjectGdrEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditDatabaseObjectManagementEvent">
            <summary>
            AuditDatabaseObjectManagementEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditDatabaseObjectTakeOwnershipEvent">
            <summary>
            AuditDatabaseObjectTakeOwnershipEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditDatabaseOperationEvent">
            <summary>
            AuditDatabaseOperationEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditDatabasePrincipalImpersonationEvent">
            <summary>
            AuditDatabasePrincipalImpersonationEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditDatabasePrincipalManagementEvent">
            <summary>
            AuditDatabasePrincipalManagementEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditDatabaseScopeGdrEvent">
            <summary>
            AuditDatabaseScopeGdrEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditDbccEvent">
            <summary>
            AuditDbccEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditLogin">
            <summary>
            AuditLogin
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditLoginChangePasswordEvent">
            <summary>
            AuditLoginChangePasswordEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditLoginChangePropertyEvent">
            <summary>
            AuditLoginChangePropertyEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditLoginFailed">
            <summary>
            AuditLoginFailed
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditLoginGdrEvent">
            <summary>
            AuditLoginGdrEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditLogout">
            <summary>
            AuditLogout
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditSchemaObjectAccessEvent">
            <summary>
            AuditSchemaObjectAccessEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditSchemaObjectGdrEvent">
            <summary>
            AuditSchemaObjectGdrEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditSchemaObjectManagementEvent">
            <summary>
            AuditSchemaObjectManagementEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditSchemaObjectTakeOwnershipEvent">
            <summary>
            AuditSchemaObjectTakeOwnershipEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditServerAlterTraceEvent">
            <summary>
            AuditServerAlterTraceEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditServerObjectGdrEvent">
            <summary>
            AuditServerObjectGdrEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditServerObjectManagementEvent">
            <summary>
            AuditServerObjectManagementEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditServerObjectTakeOwnershipEvent">
            <summary>
            AuditServerObjectTakeOwnershipEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditServerOperationEvent">
            <summary>
            AuditServerOperationEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditServerPrincipalImpersonationEvent">
            <summary>
            AuditServerPrincipalImpersonationEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditServerPrincipalManagementEvent">
            <summary>
            AuditServerPrincipalManagementEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditServerScopeGdrEvent">
            <summary>
            AuditServerScopeGdrEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.BlockedProcessReport">
            <summary>
            BlockedProcessReport
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.BrokerQueueDisabled">
            <summary>
            BrokerQueueDisabled
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DataFileAutoGrow">
            <summary>
            DataFileAutoGrow
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DataFileAutoShrink">
            <summary>
            DataFileAutoShrink
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DatabaseMirroringStateChange">
            <summary>
            DatabaseMirroringStateChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DeadlockGraph">
            <summary>
            DeadlockGraph
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DeprecationAnnouncement">
            <summary>
            DeprecationAnnouncement
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DeprecationFinalSupport">
            <summary>
            DeprecationFinalSupport
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.ErrorLog">
            <summary>
            ErrorLog
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.EventLog">
            <summary>
            EventLog
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.Exception">
            <summary>
            Exception
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.ExchangeSpillEvent">
            <summary>
            ExchangeSpillEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.ExecutionWarnings">
            <summary>
            ExecutionWarnings
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.FtCrawlAborted">
            <summary>
            FtCrawlAborted
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.FtCrawlStarted">
            <summary>
            FtCrawlStarted
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.FtCrawlStopped">
            <summary>
            FtCrawlStopped
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.HashWarning">
            <summary>
            HashWarning
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.LockDeadlock">
            <summary>
            LockDeadlock
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.LockDeadlockChain">
            <summary>
            LockDeadlockChain
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.LockEscalation">
            <summary>
            LockEscalation
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.LogFileAutoGrow">
            <summary>
            LogFileAutoGrow
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.LogFileAutoShrink">
            <summary>
            LogFileAutoShrink
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.MissingColumnStatistics">
            <summary>
            MissingColumnStatistics
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.MissingJoinPredicate">
            <summary>
            MissingJoinPredicate
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.MountTape">
            <summary>
            MountTape
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.ObjectAltered">
            <summary>
            ObjectAltered
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.ObjectCreated">
            <summary>
            ObjectCreated
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.ObjectDeleted">
            <summary>
            ObjectDeleted
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.OledbCallEvent">
            <summary>
            OledbCallEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.OledbDataReadEvent">
            <summary>
            OledbDataReadEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.OledbErrors">
            <summary>
            OledbErrors
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.OledbProviderInformation">
            <summary>
            OledbProviderInformation
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.OledbQueryInterfaceEvent">
            <summary>
            OledbQueryInterfaceEvent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.QnDynamics">
            <summary>
            QnDynamics
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.QnParameterTable">
            <summary>
            QnParameterTable
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.QnSubscription">
            <summary>
            QnSubscription
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.QnTemplate">
            <summary>
            QnTemplate
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.QueueActivation">
            <summary>
            QueueActivation
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.ServerMemoryChange">
            <summary>
            ServerMemoryChange
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.ShowPlanAllForQueryCompile">
            <summary>
            ShowPlanAllForQueryCompile
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.ShowPlanXmlForQueryCompile">
            <summary>
            ShowPlanXmlForQueryCompile
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.ShowPlanXml">
            <summary>
            ShowPlanXml
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.ShowPlanXmlStatisticsProfile">
            <summary>
            ShowPlanXmlStatisticsProfile
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.SortWarnings">
            <summary>
            SortWarnings
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.SpCacheInsert">
            <summary>
            SpCacheInsert
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.SpCacheMiss">
            <summary>
            SpCacheMiss
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.SpCacheRemove">
            <summary>
            SpCacheRemove
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.SpRecompile">
            <summary>
            SpRecompile
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.SqlStmtRecompile">
            <summary>
            SqlStmtRecompile
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.TraceFileClose">
            <summary>
            TraceFileClose
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.UserErrorMessage">
            <summary>
            UserErrorMessage
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.UserConfigurable0">
            <summary>
            UserConfigurable0
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.UserConfigurable1">
            <summary>
            UserConfigurable1
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.UserConfigurable2">
            <summary>
            UserConfigurable2
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.UserConfigurable3">
            <summary>
            UserConfigurable3
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.UserConfigurable4">
            <summary>
            UserConfigurable4
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.UserConfigurable5">
            <summary>
            UserConfigurable5
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.UserConfigurable6">
            <summary>
            UserConfigurable6
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.UserConfigurable7">
            <summary>
            UserConfigurable7
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.UserConfigurable8">
            <summary>
            UserConfigurable8
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.UserConfigurable9">
            <summary>
            UserConfigurable9
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.XQueryStaticType">
            <summary>
            XQueryStaticType
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AuditFullText">
            <summary>
            AuditFullText
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.BitmapWarning">
            <summary>
            BitmapWarning
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CpuThresholdExceeded">
            <summary>
            CpuThresholdExceeded
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DatabaseSuspectDataPage">
            <summary>
            DatabaseSuspectDataPage
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateSequence">
            <summary>
            CreateSequence
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterSequence">
            <summary>
            AlterSequence
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropSequence">
            <summary>
            DropSequence
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateServerRole">
            <summary>
            CreateServerRole
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterServerRole">
            <summary>
            AlterServerRole
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropServerRole">
            <summary>
            DropServerRole
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterServerConfiguration">
            <summary>
            AlterServerConfiguration
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.CreateSearchPropertyList">
            <summary>
            CreateSearchPropertyList
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.AlterSearchPropertyList">
            <summary>
            AlterSearchPropertyList
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventType.DropSearchPropertyList">
            <summary>
            DropSearchPropertyList
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DataSourceType">
            <summary>
            External data source type options
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DataSourceType.Hadoop">
            <summary>
            Hadoop
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DataSourceType.RDBMS">
            <summary>
            RDBMS
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DataSourceType.ShardMapManager">
            <summary>
            ShardMapManager
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.DataSourceType.BlobStorage">
            <summary>
            BlobStorage
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.FileFormatType">
            <summary>
            External file format type options.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.FileFormatType.DelimitedText">
            <summary>
            DelimitedText
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.FileFormatType.RcFile">
            <summary>
            RcFile
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.FileFormatType.Orc">
            <summary>
            Orc
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.FileFormatType.Parquet">
            <summary>
            Parquet
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.RejectType">
            <summary>
            External table reject type options.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.RejectType.Value">
            <summary>
            Value
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.RejectType.Percentage">
            <summary>
            Percentage
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.MemoryPartitionMode">
            <summary>
            Memory partion mode for event session
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.MemoryPartitionMode.None">
            <summary>
            None
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.MemoryPartitionMode.PerNode">
            <summary>
            PerNode
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.MemoryPartitionMode.PerCpu">
            <summary>
            PerCpu
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.EventRetentionMode">
            <summary>
            Event retention mode for event session
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventRetentionMode.AllowSingleEventLoss">
            <summary>
            AllowSingleEventLoss
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventRetentionMode.AllowMultipleEventLoss">
            <summary>
            AllowMultipleEventLoss
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventRetentionMode.NoEventLoss">
            <summary>
            NoEventLoss
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ForeignKeyAction">
            <summary>
            Actions taken when a key to which existing foreign key points is updated or deleted
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ForeignKeyAction.NoAction">
            <summary>
            NoAction
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ForeignKeyAction.Cascade">
            <summary>
            Cascade
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ForeignKeyAction.SetNull">
            <summary>
            SetNull
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ForeignKeyAction.SetDefault">
            <summary>
            SetDefault
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Tessellation">
            <summary>
            Grid tessellation in spatial index
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.Tessellation.None">
            <summary>
            None
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.Tessellation.Geometry">
            <summary>
            Geometry
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.Tessellation.Geography">
            <summary>
            Geography
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.Tessellation.AutoGeometry">
            <summary>
            AutoGeometry
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.Tessellation.AutoGeography">
            <summary>
            AutoGeography
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.LoginEncryptionOption">
            <summary>
            SQL login encryption options
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.LoginEncryptionOption.Encrypt">
            <summary>
            Encrypt
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.LoginEncryptionOption.AlreadyEncrypted">
            <summary>
            AlreadyEncrypted
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.LoginEncryptionOption.AlreadyEncryptedOld">
            <summary>
            AlreadyEncryptedOld
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.MemoryUnit">
            <summary>
            Memory units for use in SQL models
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.MemoryUnit.Unspecified">
            <summary>
            Unspecified
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.MemoryUnit.Percent">
            <summary>
            Percent
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.MemoryUnit.Bytes">
            <summary>
            Bytes
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.MemoryUnit.KB">
            <summary>
            KB
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.MemoryUnit.MB">
            <summary>
            MB
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.MemoryUnit.GB">
            <summary>
            GB
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.MemoryUnit.TB">
            <summary>
            TB
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.MemoryUnit.PB">
            <summary>
            PB
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.MemoryUnit.EB">
            <summary>
            EB
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.MessageSentBy">
            <summary>
            Specifies message sender type
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.MessageSentBy.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.MessageSentBy.Initiator">
            <summary>
            Initiator
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.MessageSentBy.Target">
            <summary>
            Target
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.MessageSentBy.Any">
            <summary>
            Any
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ValidationMethod">
            <summary>
            Specifies message validation method
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ValidationMethod.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ValidationMethod.None">
            <summary>
            None
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ValidationMethod.Empty">
            <summary>
            Empty
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ValidationMethod.WellFormedXml">
            <summary>
            WellFormedXml
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ValidationMethod.ValidXml">
            <summary>
            ValidXml
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.PartitionRange">
            <summary>
            Specifies to which side of interval, left or right, the boundary value belongs
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PartitionRange.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PartitionRange.Left">
            <summary>
            Left
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PartitionRange.Right">
            <summary>
            Right
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Payload">
            <summary>
            Payload types for endpoints
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.Payload.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.Payload.Soap">
            <summary>
            Soap
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.Payload.TSql">
            <summary>
            TSql
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.Payload.ServiceBroker">
            <summary>
            ServiceBroker
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.Payload.DatabaseMirroring">
            <summary>
            DatabaseMirroring
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.PermissionAction">
            <summary>
            SQL permission action types
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionAction.Grant">
            <summary>
            Grant
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.PermissionAction.Deny">
            <summary>
            Deny
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SecondaryXmlIndexType">
            <summary>
            Types of secondary XML index
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SecondaryXmlIndexType.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SecondaryXmlIndexType.Path">
            <summary>
            Path
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SecondaryXmlIndexType.Property">
            <summary>
            Property
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SecondaryXmlIndexType.Value">
            <summary>
            Value
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Protocol">
            <summary>
            Protocol types for endpoints
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.Protocol.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.Protocol.Http">
            <summary>
            Http
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.Protocol.Tcp">
            <summary>
            Tcp
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.TimeUnit">
            <summary>
            Describes the unit for retention period.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TimeUnit.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TimeUnit.Seconds">
            <summary>
            Seconds
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TimeUnit.Days">
            <summary>
            Days
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TimeUnit.Hours">
            <summary>
            Hours
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TimeUnit.Minutes">
            <summary>
            Minutes
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SamplingStyle">
            <summary>
            Sampling styles used to create statistics
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SamplingStyle.Automatic">
            <summary>
            Automatic
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SamplingStyle.Fullscan">
            <summary>
            Fullscan
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SamplingStyle.SamplePercentRows">
            <summary>
            SamplePercentRows
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SamplingStyle.SampleAbsoluteRows">
            <summary>
            SampleAbsoluteRows
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.OrderRestriction">
            <summary>
            Trigger oder restriction types
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.OrderRestriction.None">
            <summary>
            None
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.OrderRestriction.IsFirst">
            <summary>
            IsFirst
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.OrderRestriction.IsLast">
            <summary>
            IsLast
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.TriggerType">
            <summary>
            Trigger types
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TriggerType.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TriggerType.For">
            <summary>
            For
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TriggerType.After">
            <summary>
            After
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TriggerType.InsteadOf">
            <summary>
            InsteadOf
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.AuthenticationType">
            <summary>
            Database user Authentication type
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuthenticationType.None">
            <summary>
            User without a login, Application Role, Database Role,  Certificate mapped user or Asymmetric key mapped user
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuthenticationType.InstanceAuthentication">
            <summary>
            User with login 
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuthenticationType.DatabaseAuthentication">
            <summary>
            User with a password
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuthenticationType.WindowsAuthentication">
            <summary>
            Windows user with login, Windows user without a login or Windows group
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.AuthenticationType.ExternalAuthenticationProvider">
            <summary>
            User supplied by an external authentication provider (e.g. Azure Active Directory).
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.XmlStyle">
            <summary>
            XML data type style
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.XmlStyle.Unknown">
            <summary>
            Unknown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.XmlStyle.Content">
            <summary>
            Content
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.XmlStyle.Document">
            <summary>
            Document
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Containment">
            <summary>
            Database Containment types
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.Containment.None">
            <summary>
            None
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.Containment.Partial">
            <summary>
            Partial
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.FailureAction">
            <summary>
            Action type for audit failure
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.FailureAction.Continue">
            <summary>
            Continue
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.FailureAction.Shutdown">
            <summary>
            Shutdown
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.FailureAction.FailOperation">
            <summary>
            FailOperation
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.NonTransactedFileStreamAccess">
            <summary>
            FILESTREAM non-transactional access option values
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.NonTransactedFileStreamAccess.Off">
            <summary>
            Off
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.NonTransactedFileStreamAccess.ReadOnly">
            <summary>
            ReadOnly
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.NonTransactedFileStreamAccess.Full">
            <summary>
            Full
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Durability">
            <summary>
            Durability of a table
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.Durability.SchemaAndData">
            <summary>
            Table is durable.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.Durability.SchemaOnly">
            <summary>
            Table is non-durable.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.EventSessionScope">
            <summary>
            Scope of the event session
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventSessionScope.Server">
            <summary>
            Server
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.EventSessionScope.Database">
            <summary>
            Database
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ColumnGeneratedAlwaysType">
            <summary>
            Column system-versioned generated always type
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ColumnGeneratedAlwaysType.None">
            <summary>
            Column is not a generated always type of column.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ColumnGeneratedAlwaysType.GeneratedAlwaysAsRowStart">
            <summary>
            Column has a type of 'generated always as row start'.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.ColumnGeneratedAlwaysType.GeneratedAlwaysAsRowEnd">
            <summary>
            Column has a type of 'generated always as row end'.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.UserType">
            <summary>
            User type (for use with Azure active directory users).
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.UserType.None">
            <summary>
            No specified Azure active directory user type.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.UserType.ExternalUser">
            <summary>
            An Azure active directory user.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.UserType.ExternalGroup">
            <summary>
            An Azure active directory group.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SecurityPredicateOperation">
            <summary>
            The operation to which a security predicate applies
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SecurityPredicateOperation.All">
            <summary>
            All
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SecurityPredicateOperation.AfterInsert">
            <summary>
            AfterInsert
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SecurityPredicateOperation.AfterUpdate">
            <summary>
            AfterUpdate
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SecurityPredicateOperation.BeforeUpdate">
            <summary>
            BeforeUpdate
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SecurityPredicateOperation.BeforeDelete">
            <summary>
            BeforeDelete
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SecurityPredicateType">
            <summary>
            The type of the security predicate
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SecurityPredicateType.Filter">
            <summary>
            Filter
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SecurityPredicateType.Block">
            <summary>
            Block
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.QueryStoreCaptureMode">
            <summary>
            Query Store SIZE_BASED_CLEANUP_MODE option values
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.QueryStoreCaptureMode.All">
            <summary>
            Query Store captures all queries. This is the default configuration value
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.QueryStoreCaptureMode.Auto">
            <summary>
            Query Store captures relevant queries based on execution count and resource consumption.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.QueryStoreCaptureMode.None">
            <summary>
            Query Store does not capture new queries.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.QueryStoreDesiredState">
            <summary>
            Query Store Operation Mode/Desired State option values
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.QueryStoreDesiredState.Off">
            <summary>
            Query Store feature is OFF.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.QueryStoreDesiredState.ReadOnly">
            <summary>
            Query Store does not record new data.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.QueryStoreDesiredState.ReadWrite">
            <summary>
            Query store records new data.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Column">
            <summary>
            Model schema container class for Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.TypeClass">
            <summary>
            Type class for Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.ColumnType">
            <summary>
            ColumnType metadata class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.Collation">
            <summary>
            Collation property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.IsIdentityNotForReplication">
            <summary>
            IsIdentityNotForReplication property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.Nullable">
            <summary>
            Nullable property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.IsRowGuidCol">
            <summary>
            IsRowGuidCol property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.Sparse">
            <summary>
            Sparse property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.Expression">
            <summary>
            Expression property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.Persisted">
            <summary>
            Persisted property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.PersistedNullable">
            <summary>
            PersistedNullable property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.Scale">
            <summary>
            Scale property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.Precision">
            <summary>
            Precision property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.Length">
            <summary>
            Length property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.IsMax">
            <summary>
            IsMax property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.XmlStyle">
            <summary>
            XmlStyle property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.EncryptionAlgorithmName">
            <summary>
            EncryptionAlgorithmName property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.EncryptionType">
            <summary>
            EncryptionType property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.GeneratedAlwaysType">
            <summary>
            GeneratedAlwaysType property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.GraphType">
            <summary>
            GraphType property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.IdentityIncrement">
            <summary>
            IdentityIncrement property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.IdentitySeed">
            <summary>
            IdentitySeed property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.IsFileStream">
            <summary>
            IsFileStream property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.IsHidden">
            <summary>
            IsHidden property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.IsIdentity">
            <summary>
            IsIdentity property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.IsPseudoColumn">
            <summary>
            IsPseudoColumn property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.MaskingFunction">
            <summary>
            MaskingFunction property class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.ExpressionDependencies">
            <summary>
            ExpressionDependencies relationship class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.XmlSchemaCollection">
            <summary>
            XmlSchemaCollection relationship class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.DataType">
            <summary>
            DataType relationship class of Column
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Column.ColumnEncryptionKey">
            <summary>
            ColumnEncryptionKey relationship class of Column
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.TableValuedFunction">
            <summary>
            Model schema container class for TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.TypeClass">
            <summary>
            Type class for TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.FunctionType">
            <summary>
            FunctionType metadata class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.ReturnsNullOnNullInput">
            <summary>
            ReturnsNullOnNullInput property class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.AnsiNullsOn">
            <summary>
            AnsiNullsOn property class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.CalledOnNullInput">
            <summary>
            CalledOnNullInput property class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.ExecuteAsCaller">
            <summary>
            ExecuteAsCaller property class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.WithEncryption">
            <summary>
            WithEncryption property class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.ExecuteAsOwner">
            <summary>
            ExecuteAsOwner property class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.QuotedIdentifierOn">
            <summary>
            QuotedIdentifierOn property class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.WithSchemaBinding">
            <summary>
            WithSchemaBinding property class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.ExecuteAsSelf">
            <summary>
            ExecuteAsSelf property class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.ReturnTableVariableName">
            <summary>
            ReturnTableVariableName property class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.ClassName">
            <summary>
            ClassName property class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.DataAccess">
            <summary>
            DataAccess property class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.FillRowMethodName">
            <summary>
            FillRowMethodName property class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.Deterministic">
            <summary>
            Deterministic property class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.Precise">
            <summary>
            Precise property class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.MethodName">
            <summary>
            MethodName property class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.SystemDataAccess">
            <summary>
            SystemDataAccess property class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.IsNativeCompiled">
            <summary>
            IsNativeCompiled property class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.IsReplicated">
            <summary>
            IsReplicated property class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.Assembly">
            <summary>
            Assembly relationship class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.TableOption">
            <summary>
            TableOption relationship class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.ReturnType">
            <summary>
            ReturnType relationship class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.BodyDependencies">
            <summary>
            BodyDependencies relationship class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.Columns">
            <summary>
            Columns relationship class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.Login">
            <summary>
            Login relationship class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.Parameters">
            <summary>
            Parameters relationship class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.Schema">
            <summary>
            Schema relationship class of TableValuedFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableValuedFunction.User">
            <summary>
            User relationship class of TableValuedFunction
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ScalarFunction">
            <summary>
            Model schema container class for ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.TypeClass">
            <summary>
            Type class for ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.ReturnsNullOnNullInput">
            <summary>
            ReturnsNullOnNullInput property class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.AnsiNullsOn">
            <summary>
            AnsiNullsOn property class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.CalledOnNullInput">
            <summary>
            CalledOnNullInput property class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.ExecuteAsCaller">
            <summary>
            ExecuteAsCaller property class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.WithEncryption">
            <summary>
            WithEncryption property class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.ExecuteAsOwner">
            <summary>
            ExecuteAsOwner property class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.QuotedIdentifierOn">
            <summary>
            QuotedIdentifierOn property class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.WithSchemaBinding">
            <summary>
            WithSchemaBinding property class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.ExecuteAsSelf">
            <summary>
            ExecuteAsSelf property class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.ClassName">
            <summary>
            ClassName property class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.DataAccess">
            <summary>
            DataAccess property class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.FillRowMethodName">
            <summary>
            FillRowMethodName property class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.Deterministic">
            <summary>
            Deterministic property class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.Precise">
            <summary>
            Precise property class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.MethodName">
            <summary>
            MethodName property class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.SystemDataAccess">
            <summary>
            SystemDataAccess property class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.IsNativeCompiled">
            <summary>
            IsNativeCompiled property class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.IsReplicated">
            <summary>
            IsReplicated property class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.Assembly">
            <summary>
            Assembly relationship class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.ReturnType">
            <summary>
            ReturnType relationship class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.BodyDependencies">
            <summary>
            BodyDependencies relationship class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.Login">
            <summary>
            Login relationship class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.Parameters">
            <summary>
            Parameters relationship class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.Schema">
            <summary>
            Schema relationship class of ScalarFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ScalarFunction.User">
            <summary>
            User relationship class of ScalarFunction
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ClrTableOption">
            <summary>
            Model schema container class for ClrTableOption
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ClrTableOption.TypeClass">
            <summary>
            Type class for ClrTableOption
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ClrTableOption.ClassName">
            <summary>
            ClassName property class of ClrTableOption
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ClrTableOption.OrderColumns">
            <summary>
            OrderColumns relationship class of ClrTableOption
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ClrTableOption.OrderColumnsRelationship">
            <summary>
            Model schema container class for OrderColumnsRelationship
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ClrTableOption.OrderColumnsRelationship.RelationshipClass">
            <summary>
            Relationship class for OrderColumnsRelationship
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ClrTableOption.OrderColumnsRelationship.Ascending">
            <summary>
            Ascending property class of OrderColumnsRelationship
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Aggregate">
            <summary>
            Model schema container class for Aggregate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Aggregate.TypeClass">
            <summary>
            Type class for Aggregate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Aggregate.InvariantToDuplicates">
            <summary>
            InvariantToDuplicates property class of Aggregate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Aggregate.InvariantToNulls">
            <summary>
            InvariantToNulls property class of Aggregate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Aggregate.NullIfEmpty">
            <summary>
            NullIfEmpty property class of Aggregate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Aggregate.ClassName">
            <summary>
            ClassName property class of Aggregate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Aggregate.Format">
            <summary>
            Format property class of Aggregate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Aggregate.MaxByteSize">
            <summary>
            MaxByteSize property class of Aggregate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Aggregate.ReturnType">
            <summary>
            ReturnType relationship class of Aggregate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Aggregate.Assembly">
            <summary>
            Assembly relationship class of Aggregate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Aggregate.Parameters">
            <summary>
            Parameters relationship class of Aggregate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Aggregate.Schema">
            <summary>
            Schema relationship class of Aggregate
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ApplicationRole">
            <summary>
            Model schema container class for ApplicationRole
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ApplicationRole.TypeClass">
            <summary>
            Type class for ApplicationRole
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ApplicationRole.Password">
            <summary>
            Password property class of ApplicationRole
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ApplicationRole.DefaultSchema">
            <summary>
            DefaultSchema relationship class of ApplicationRole
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Index">
            <summary>
            Model schema container class for Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.TypeClass">
            <summary>
            Type class for Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.AllowPageLocks">
            <summary>
            AllowPageLocks property class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.AllowRowLocks">
            <summary>
            AllowRowLocks property class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.IgnoreDuplicateKey">
            <summary>
            IgnoreDuplicateKey property class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.RecomputeStatistics">
            <summary>
            RecomputeStatistics property class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.IncrementalStatistics">
            <summary>
            IncrementalStatistics property class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.Clustered">
            <summary>
            Clustered property class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.Disabled">
            <summary>
            Disabled property class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.FileStreamNull">
            <summary>
            FileStreamNull property class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.WithPadIndex">
            <summary>
            WithPadIndex property class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.Unique">
            <summary>
            Unique property class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.FilterPredicate">
            <summary>
            FilterPredicate property class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.Hash">
            <summary>
            Hash property class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.BucketCount">
            <summary>
            BucketCount property class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.FillFactor">
            <summary>
            FillFactor property class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.Columns">
            <summary>
            Columns relationship class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.BodyDependencies">
            <summary>
            BodyDependencies relationship class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.DataCompressionOptions">
            <summary>
            DataCompressionOptions relationship class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.Filegroup">
            <summary>
            Filegroup relationship class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.FileStreamFilegroup">
            <summary>
            FileStreamFilegroup relationship class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.FileStreamPartitionScheme">
            <summary>
            FileStreamPartitionScheme relationship class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.IncludedColumns">
            <summary>
            IncludedColumns relationship class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.IndexedObject">
            <summary>
            IndexedObject relationship class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.PartitionColumn">
            <summary>
            PartitionColumn relationship class of Index
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.PartitionScheme">
            <summary>
            PartitionScheme relationship class of Index
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Index.ColumnsRelationship">
            <summary>
            Model schema container class for ColumnsRelationship
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.ColumnsRelationship.RelationshipClass">
            <summary>
            Relationship class for ColumnsRelationship
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Index.ColumnsRelationship.Ascending">
            <summary>
            Ascending property class of ColumnsRelationship
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Assembly">
            <summary>
            Model schema container class for Assembly
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Assembly.TypeClass">
            <summary>
            Type class for Assembly
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Assembly.Visible">
            <summary>
            Visible property class of Assembly
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Assembly.PermissionSet">
            <summary>
            PermissionSet property class of Assembly
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Assembly.AssemblySources">
            <summary>
            AssemblySources relationship class of Assembly
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Assembly.Authorizer">
            <summary>
            Authorizer relationship class of Assembly
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Assembly.ReferencedAssemblies">
            <summary>
            ReferencedAssemblies relationship class of Assembly
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.AssemblySource">
            <summary>
            Model schema container class for AssemblySource
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AssemblySource.TypeClass">
            <summary>
            Type class for AssemblySource
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AssemblySource.Source">
            <summary>
            Source property class of AssemblySource
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.AsymmetricKey">
            <summary>
            Model schema container class for AsymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AsymmetricKey.TypeClass">
            <summary>
            Type class for AsymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AsymmetricKey.Password">
            <summary>
            Password property class of AsymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AsymmetricKey.EncryptedWithPassword">
            <summary>
            EncryptedWithPassword property class of AsymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AsymmetricKey.Algorithm">
            <summary>
            Algorithm property class of AsymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AsymmetricKey.CreationDisposition">
            <summary>
            CreationDisposition property class of AsymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AsymmetricKey.ExecutableFile">
            <summary>
            ExecutableFile property class of AsymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AsymmetricKey.File">
            <summary>
            File property class of AsymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AsymmetricKey.ProviderKeyName">
            <summary>
            ProviderKeyName property class of AsymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AsymmetricKey.Assembly">
            <summary>
            Assembly relationship class of AsymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AsymmetricKey.Authorizer">
            <summary>
            Authorizer relationship class of AsymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AsymmetricKey.Provider">
            <summary>
            Provider relationship class of AsymmetricKey
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.AuditAction">
            <summary>
            Model schema container class for AuditAction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AuditAction.TypeClass">
            <summary>
            Type class for AuditAction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AuditAction.Action">
            <summary>
            Action property class of AuditAction
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.AuditActionGroup">
            <summary>
            Model schema container class for AuditActionGroup
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AuditActionGroup.TypeClass">
            <summary>
            Type class for AuditActionGroup
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AuditActionGroup.ActionGroup">
            <summary>
            ActionGroup property class of AuditActionGroup
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.AuditActionSpecification">
            <summary>
            Model schema container class for AuditActionSpecification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AuditActionSpecification.TypeClass">
            <summary>
            Type class for AuditActionSpecification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AuditActionSpecification.AuditsDatabase">
            <summary>
            AuditsDatabase property class of AuditActionSpecification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AuditActionSpecification.AuditActions">
            <summary>
            AuditActions relationship class of AuditActionSpecification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AuditActionSpecification.Principals">
            <summary>
            Principals relationship class of AuditActionSpecification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.AuditActionSpecification.SecuredObject">
            <summary>
            SecuredObject relationship class of AuditActionSpecification
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.BrokerPriority">
            <summary>
            Model schema container class for BrokerPriority
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.BrokerPriority.TypeClass">
            <summary>
            Type class for BrokerPriority
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.BrokerPriority.RemoteServiceName">
            <summary>
            RemoteServiceName property class of BrokerPriority
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.BrokerPriority.PriorityLevel">
            <summary>
            PriorityLevel property class of BrokerPriority
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.BrokerPriority.ContractName">
            <summary>
            ContractName relationship class of BrokerPriority
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.BrokerPriority.LocalServiceName">
            <summary>
            LocalServiceName relationship class of BrokerPriority
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.BuiltInServerRole">
            <summary>
            Model schema container class for BuiltInServerRole
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.BuiltInServerRole.TypeClass">
            <summary>
            Type class for BuiltInServerRole
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DataType">
            <summary>
            Model schema container class for DataType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DataType.TypeClass">
            <summary>
            Type class for DataType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DataType.UddtNullable">
            <summary>
            UddtNullable property class of DataType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DataType.UddtIsMax">
            <summary>
            UddtIsMax property class of DataType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DataType.UddtLength">
            <summary>
            UddtLength property class of DataType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DataType.UddtPrecision">
            <summary>
            UddtPrecision property class of DataType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DataType.UddtScale">
            <summary>
            UddtScale property class of DataType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DataType.SqlDataType">
            <summary>
            SqlDataType property class of DataType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DataType.Schema">
            <summary>
            Schema relationship class of DataType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DataType.Type">
            <summary>
            Type relationship class of DataType
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Certificate">
            <summary>
            Model schema container class for Certificate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Certificate.TypeClass">
            <summary>
            Type class for Certificate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Certificate.ActiveForBeginDialog">
            <summary>
            ActiveForBeginDialog property class of Certificate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Certificate.EncryptedWithPassword">
            <summary>
            EncryptedWithPassword property class of Certificate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Certificate.EncryptionPassword">
            <summary>
            EncryptionPassword property class of Certificate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Certificate.ExpiryDate">
            <summary>
            ExpiryDate property class of Certificate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Certificate.StartDate">
            <summary>
            StartDate property class of Certificate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Certificate.Subject">
            <summary>
            Subject property class of Certificate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Certificate.PrivateKeyFilePath">
            <summary>
            PrivateKeyFilePath property class of Certificate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Certificate.ExistingKeysFilePath">
            <summary>
            ExistingKeysFilePath property class of Certificate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Certificate.IsExistingKeyFileExecutable">
            <summary>
            IsExistingKeyFileExecutable property class of Certificate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Certificate.PrivateKeyDecryptionPassword">
            <summary>
            PrivateKeyDecryptionPassword property class of Certificate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Certificate.PrivateKeyEncryptionPassword">
            <summary>
            PrivateKeyEncryptionPassword property class of Certificate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Certificate.Authorizer">
            <summary>
            Authorizer relationship class of Certificate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Certificate.ExistingKeysAssembly">
            <summary>
            ExistingKeysAssembly relationship class of Certificate
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.CheckConstraint">
            <summary>
            Model schema container class for CheckConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.CheckConstraint.TypeClass">
            <summary>
            Type class for CheckConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.CheckConstraint.Expression">
            <summary>
            Expression property class of CheckConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.CheckConstraint.Disabled">
            <summary>
            Disabled property class of CheckConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.CheckConstraint.NotForReplication">
            <summary>
            NotForReplication property class of CheckConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.CheckConstraint.ExpressionDependencies">
            <summary>
            ExpressionDependencies relationship class of CheckConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.CheckConstraint.Host">
            <summary>
            Host relationship class of CheckConstraint
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ClrTypeMethod">
            <summary>
            Model schema container class for ClrTypeMethod
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ClrTypeMethod.TypeClass">
            <summary>
            Type class for ClrTypeMethod
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ClrTypeMethod.Name">
            <summary>
            Name property class of ClrTypeMethod
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ClrTypeMethod.Parameters">
            <summary>
            Parameters relationship class of ClrTypeMethod
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ClrTypeMethod.ReturnType">
            <summary>
            ReturnType relationship class of ClrTypeMethod
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ClrTypeMethodParameter">
            <summary>
            Model schema container class for ClrTypeMethodParameter
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ClrTypeMethodParameter.TypeClass">
            <summary>
            Type class for ClrTypeMethodParameter
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ClrTypeMethodParameter.Name">
            <summary>
            Name property class of ClrTypeMethodParameter
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ClrTypeMethodParameter.IsOutput">
            <summary>
            IsOutput property class of ClrTypeMethodParameter
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ClrTypeMethodParameter.DataType">
            <summary>
            DataType relationship class of ClrTypeMethodParameter
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ClrTypeProperty">
            <summary>
            Model schema container class for ClrTypeProperty
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ClrTypeProperty.TypeClass">
            <summary>
            Type class for ClrTypeProperty
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ClrTypeProperty.Name">
            <summary>
            Name property class of ClrTypeProperty
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ClrTypeProperty.ClrType">
            <summary>
            ClrType relationship class of ClrTypeProperty
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ColumnStoreIndex">
            <summary>
            Model schema container class for ColumnStoreIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ColumnStoreIndex.TypeClass">
            <summary>
            Type class for ColumnStoreIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ColumnStoreIndex.Disabled">
            <summary>
            Disabled property class of ColumnStoreIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ColumnStoreIndex.Clustered">
            <summary>
            Clustered property class of ColumnStoreIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ColumnStoreIndex.FilterPredicate">
            <summary>
            FilterPredicate property class of ColumnStoreIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ColumnStoreIndex.CompressionDelay">
            <summary>
            CompressionDelay property class of ColumnStoreIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ColumnStoreIndex.Columns">
            <summary>
            Columns relationship class of ColumnStoreIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ColumnStoreIndex.BodyDependencies">
            <summary>
            BodyDependencies relationship class of ColumnStoreIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ColumnStoreIndex.DataCompressionOptions">
            <summary>
            DataCompressionOptions relationship class of ColumnStoreIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ColumnStoreIndex.Filegroup">
            <summary>
            Filegroup relationship class of ColumnStoreIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ColumnStoreIndex.IndexedObject">
            <summary>
            IndexedObject relationship class of ColumnStoreIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ColumnStoreIndex.PartitionColumn">
            <summary>
            PartitionColumn relationship class of ColumnStoreIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ColumnStoreIndex.PartitionScheme">
            <summary>
            PartitionScheme relationship class of ColumnStoreIndex
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ColumnStoreIndex.ColumnsRelationship">
            <summary>
            Model schema container class for ColumnsRelationship
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ColumnStoreIndex.ColumnsRelationship.RelationshipClass">
            <summary>
            Relationship class for ColumnsRelationship
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ColumnStoreIndex.ColumnsRelationship.Ascending">
            <summary>
            Ascending property class of ColumnsRelationship
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Contract">
            <summary>
            Model schema container class for Contract
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Contract.TypeClass">
            <summary>
            Type class for Contract
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Contract.Messages">
            <summary>
            Messages relationship class of Contract
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Contract.Authorizer">
            <summary>
            Authorizer relationship class of Contract
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Contract.MessagesRelationship">
            <summary>
            Model schema container class for MessagesRelationship
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Contract.MessagesRelationship.RelationshipClass">
            <summary>
            Relationship class for MessagesRelationship
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Contract.MessagesRelationship.Default">
            <summary>
            Default property class of MessagesRelationship
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Contract.MessagesRelationship.SentBy">
            <summary>
            SentBy property class of MessagesRelationship
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Credential">
            <summary>
            Model schema container class for Credential
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Credential.TypeClass">
            <summary>
            Type class for Credential
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Credential.Identity">
            <summary>
            Identity property class of Credential
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Credential.Secret">
            <summary>
            Secret property class of Credential
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Credential.CryptographicProvider">
            <summary>
            CryptographicProvider relationship class of Credential
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DatabaseCredential">
            <summary>
            Model schema container class for DatabaseCredential
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseCredential.TypeClass">
            <summary>
            Type class for DatabaseCredential
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseCredential.Identity">
            <summary>
            Identity property class of DatabaseCredential
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseCredential.Secret">
            <summary>
            Secret property class of DatabaseCredential
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.CryptographicProvider">
            <summary>
            Model schema container class for CryptographicProvider
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.CryptographicProvider.TypeClass">
            <summary>
            Type class for CryptographicProvider
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.CryptographicProvider.DllPath">
            <summary>
            DllPath property class of CryptographicProvider
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.CryptographicProvider.Enabled">
            <summary>
            Enabled property class of CryptographicProvider
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DatabaseAuditSpecification">
            <summary>
            Model schema container class for DatabaseAuditSpecification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseAuditSpecification.TypeClass">
            <summary>
            Type class for DatabaseAuditSpecification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseAuditSpecification.WithState">
            <summary>
            WithState property class of DatabaseAuditSpecification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseAuditSpecification.AuditActionGroups">
            <summary>
            AuditActionGroups relationship class of DatabaseAuditSpecification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseAuditSpecification.AuditActions">
            <summary>
            AuditActions relationship class of DatabaseAuditSpecification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseAuditSpecification.ServerAudit">
            <summary>
            ServerAudit relationship class of DatabaseAuditSpecification
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DatabaseDdlTrigger">
            <summary>
            Model schema container class for DatabaseDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseDdlTrigger.TypeClass">
            <summary>
            Type class for DatabaseDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseDdlTrigger.AnsiNullsOn">
            <summary>
            AnsiNullsOn property class of DatabaseDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseDdlTrigger.ExecuteAsCaller">
            <summary>
            ExecuteAsCaller property class of DatabaseDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseDdlTrigger.Disabled">
            <summary>
            Disabled property class of DatabaseDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseDdlTrigger.WithEncryption">
            <summary>
            WithEncryption property class of DatabaseDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseDdlTrigger.ExecuteAsOwner">
            <summary>
            ExecuteAsOwner property class of DatabaseDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseDdlTrigger.QuotedIdentifierOn">
            <summary>
            QuotedIdentifierOn property class of DatabaseDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseDdlTrigger.ExecuteAsSelf">
            <summary>
            ExecuteAsSelf property class of DatabaseDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseDdlTrigger.TriggerType">
            <summary>
            TriggerType property class of DatabaseDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseDdlTrigger.ClassName">
            <summary>
            ClassName property class of DatabaseDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseDdlTrigger.MethodName">
            <summary>
            MethodName property class of DatabaseDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseDdlTrigger.Assembly">
            <summary>
            Assembly relationship class of DatabaseDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseDdlTrigger.BodyDependencies">
            <summary>
            BodyDependencies relationship class of DatabaseDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseDdlTrigger.EventGroup">
            <summary>
            EventGroup relationship class of DatabaseDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseDdlTrigger.EventType">
            <summary>
            EventType relationship class of DatabaseDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseDdlTrigger.Login">
            <summary>
            Login relationship class of DatabaseDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseDdlTrigger.User">
            <summary>
            User relationship class of DatabaseDdlTrigger
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DatabaseEncryptionKey">
            <summary>
            Model schema container class for DatabaseEncryptionKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEncryptionKey.TypeClass">
            <summary>
            Type class for DatabaseEncryptionKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEncryptionKey.Algorithm">
            <summary>
            Algorithm property class of DatabaseEncryptionKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEncryptionKey.Certificate">
            <summary>
            Certificate relationship class of DatabaseEncryptionKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEncryptionKey.AsymmetricKey">
            <summary>
            AsymmetricKey relationship class of DatabaseEncryptionKey
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DatabaseEventNotification">
            <summary>
            Model schema container class for DatabaseEventNotification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEventNotification.TypeClass">
            <summary>
            Type class for DatabaseEventNotification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEventNotification.WithFanIn">
            <summary>
            WithFanIn property class of DatabaseEventNotification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEventNotification.BrokerService">
            <summary>
            BrokerService property class of DatabaseEventNotification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEventNotification.BrokerInstanceSpecifier">
            <summary>
            BrokerInstanceSpecifier property class of DatabaseEventNotification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEventNotification.EventGroup">
            <summary>
            EventGroup relationship class of DatabaseEventNotification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEventNotification.EventType">
            <summary>
            EventType relationship class of DatabaseEventNotification
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DatabaseMirroringLanguageSpecifier">
            <summary>
            Model schema container class for DatabaseMirroringLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseMirroringLanguageSpecifier.TypeClass">
            <summary>
            Type class for DatabaseMirroringLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseMirroringLanguageSpecifier.WindowsAuthenticationMode">
            <summary>
            WindowsAuthenticationMode property class of DatabaseMirroringLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseMirroringLanguageSpecifier.UseCertificateFirst">
            <summary>
            UseCertificateFirst property class of DatabaseMirroringLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseMirroringLanguageSpecifier.EncryptionAlgorithmPart1">
            <summary>
            EncryptionAlgorithmPart1 property class of DatabaseMirroringLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseMirroringLanguageSpecifier.EncryptionAlgorithmPart2">
            <summary>
            EncryptionAlgorithmPart2 property class of DatabaseMirroringLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseMirroringLanguageSpecifier.EncryptionMode">
            <summary>
            EncryptionMode property class of DatabaseMirroringLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseMirroringLanguageSpecifier.RoleType">
            <summary>
            RoleType property class of DatabaseMirroringLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseMirroringLanguageSpecifier.AuthenticationCertificate">
            <summary>
            AuthenticationCertificate relationship class of DatabaseMirroringLanguageSpecifier
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DatabaseOptions">
            <summary>
            Model schema container class for DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.TypeClass">
            <summary>
            Type class for DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.CompatibilityLevel">
            <summary>
            CompatibilityLevel property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.AllowSnapshotIsolation">
            <summary>
            AllowSnapshotIsolation property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.AnsiNullDefaultOn">
            <summary>
            AnsiNullDefaultOn property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.AnsiNullsOn">
            <summary>
            AnsiNullsOn property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.AnsiPaddingOn">
            <summary>
            AnsiPaddingOn property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.AnsiWarningsOn">
            <summary>
            AnsiWarningsOn property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.ArithAbortOn">
            <summary>
            ArithAbortOn property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.AutoClose">
            <summary>
            AutoClose property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.AutoCreateStatistics">
            <summary>
            AutoCreateStatistics property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.AutoCreateStatisticsIncremental">
            <summary>
            AutoCreateStatisticsIncremental property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.AutoShrink">
            <summary>
            AutoShrink property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.AutoUpdateStatisticsAsync">
            <summary>
            AutoUpdateStatisticsAsync property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.AutoUpdateStatistics">
            <summary>
            AutoUpdateStatistics property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.HonorBrokerPriority">
            <summary>
            HonorBrokerPriority property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.ChangeTrackingAutoCleanup">
            <summary>
            ChangeTrackingAutoCleanup property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.ChangeTrackingEnabled">
            <summary>
            ChangeTrackingEnabled property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.ConcatNullYieldsNull">
            <summary>
            ConcatNullYieldsNull property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.CursorCloseOnCommit">
            <summary>
            CursorCloseOnCommit property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.CursorDefaultGlobalScope">
            <summary>
            CursorDefaultGlobalScope property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.DateCorrelationOptimizationOn">
            <summary>
            DateCorrelationOptimizationOn property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.DBChainingOn">
            <summary>
            DBChainingOn property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.WithEncryption">
            <summary>
            WithEncryption property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.FullTextEnabled">
            <summary>
            FullTextEnabled property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.NestedTriggersOn">
            <summary>
            NestedTriggersOn property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.NumericRoundAbortOn">
            <summary>
            NumericRoundAbortOn property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.DatabaseStateOffline">
            <summary>
            DatabaseStateOffline property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.QuotedIdentifierOn">
            <summary>
            QuotedIdentifierOn property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.TransactionIsolationReadCommittedSnapshot">
            <summary>
            TransactionIsolationReadCommittedSnapshot property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.ReadOnly">
            <summary>
            ReadOnly property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.RecursiveTriggersOn">
            <summary>
            RecursiveTriggersOn property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.SupplementalLoggingOn">
            <summary>
            SupplementalLoggingOn property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.TornPageProtectionOn">
            <summary>
            TornPageProtectionOn property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.TransformNoiseWords">
            <summary>
            TransformNoiseWords property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.Trustworthy">
            <summary>
            Trustworthy property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.VardecimalStorageFormatOn">
            <summary>
            VardecimalStorageFormatOn property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.UserAccessOption">
            <summary>
            UserAccessOption property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.DelayedDurabilityMode">
            <summary>
            DelayedDurabilityMode property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.MemoryOptimizedElevateToSnapshot">
            <summary>
            MemoryOptimizedElevateToSnapshot property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.ChangeTrackingRetentionPeriod">
            <summary>
            ChangeTrackingRetentionPeriod property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.ChangeTrackingRetentionUnit">
            <summary>
            ChangeTrackingRetentionUnit property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.Collation">
            <summary>
            Collation property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.Containment">
            <summary>
            Containment property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.DefaultFullTextLanguage">
            <summary>
            DefaultFullTextLanguage property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.DefaultLanguage">
            <summary>
            DefaultLanguage property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.FileStreamDirectoryName">
            <summary>
            FileStreamDirectoryName property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.LegacyCardinalityEstimation">
            <summary>
            LegacyCardinalityEstimation property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.LegacyCardinalityEstimationForSecondary">
            <summary>
            LegacyCardinalityEstimationForSecondary property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.MaxDop">
            <summary>
            MaxDop property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.MaxDopForSecondary">
            <summary>
            MaxDopForSecondary property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.NonTransactedFileStreamAccess">
            <summary>
            NonTransactedFileStreamAccess property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.PageVerifyMode">
            <summary>
            PageVerifyMode property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.ParameterizationOption">
            <summary>
            ParameterizationOption property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.ParameterSniffing">
            <summary>
            ParameterSniffing property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.ParameterSniffingForSecondary">
            <summary>
            ParameterSniffingForSecondary property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.QueryOptimizerHotfixes">
            <summary>
            QueryOptimizerHotfixes property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.QueryOptimizerHotfixesForSecondary">
            <summary>
            QueryOptimizerHotfixesForSecondary property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.QueryStoreCaptureMode">
            <summary>
            QueryStoreCaptureMode property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.QueryStoreDesiredState">
            <summary>
            QueryStoreDesiredState property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.QueryStoreFlushInterval">
            <summary>
            QueryStoreFlushInterval property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.QueryStoreIntervalLength">
            <summary>
            QueryStoreIntervalLength property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.QueryStoreMaxPlansPerQuery">
            <summary>
            QueryStoreMaxPlansPerQuery property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.QueryStoreMaxStorageSize">
            <summary>
            QueryStoreMaxStorageSize property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.QueryStoreStaleQueryThreshold">
            <summary>
            QueryStoreStaleQueryThreshold property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.RecoveryMode">
            <summary>
            RecoveryMode property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.RemoteDataEnabled">
            <summary>
            RemoteDataEnabled property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.ServiceBrokerOption">
            <summary>
            ServiceBrokerOption property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.TargetRecoveryTimePeriod">
            <summary>
            TargetRecoveryTimePeriod property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.TargetRecoveryTimeUnit">
            <summary>
            TargetRecoveryTimeUnit property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.TemporalHistoryRetentionEnabled">
            <summary>
            TemporalHistoryRetentionEnabled property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.TwoDigitYearCutoff">
            <summary>
            TwoDigitYearCutoff property class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.DefaultFilegroup">
            <summary>
            DefaultFilegroup relationship class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.DefaultFileStreamFilegroup">
            <summary>
            DefaultFileStreamFilegroup relationship class of DatabaseOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseOptions.GenericDatabaseScopedConfigurationOptions">
            <summary>
            GenericDatabaseScopedConfigurationOptions relationship class of DatabaseOptions
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DataCompressionOption">
            <summary>
            Model schema container class for DataCompressionOption
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DataCompressionOption.TypeClass">
            <summary>
            Type class for DataCompressionOption
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DataCompressionOption.CompressionLevel">
            <summary>
            CompressionLevel property class of DataCompressionOption
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DataCompressionOption.PartitionNumber">
            <summary>
            PartitionNumber property class of DataCompressionOption
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Default">
            <summary>
            Model schema container class for Default
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Default.TypeClass">
            <summary>
            Type class for Default
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Default.Expression">
            <summary>
            Expression property class of Default
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Default.BoundObjects">
            <summary>
            BoundObjects relationship class of Default
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Default.Schema">
            <summary>
            Schema relationship class of Default
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DefaultConstraint">
            <summary>
            Model schema container class for DefaultConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DefaultConstraint.TypeClass">
            <summary>
            Type class for DefaultConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DefaultConstraint.Expression">
            <summary>
            Expression property class of DefaultConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DefaultConstraint.Disabled">
            <summary>
            Disabled property class of DefaultConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DefaultConstraint.WithValues">
            <summary>
            WithValues property class of DefaultConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DefaultConstraint.Host">
            <summary>
            Host relationship class of DefaultConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DefaultConstraint.TargetColumn">
            <summary>
            TargetColumn relationship class of DefaultConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DefaultConstraint.ExpressionDependencies">
            <summary>
            ExpressionDependencies relationship class of DefaultConstraint
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DmlTrigger">
            <summary>
            Model schema container class for DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.TypeClass">
            <summary>
            Type class for DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.AnsiNullsOn">
            <summary>
            AnsiNullsOn property class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.ExecuteAsCaller">
            <summary>
            ExecuteAsCaller property class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.Disabled">
            <summary>
            Disabled property class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.WithEncryption">
            <summary>
            WithEncryption property class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.NotForReplication">
            <summary>
            NotForReplication property class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.ExecuteAsOwner">
            <summary>
            ExecuteAsOwner property class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.QuotedIdentifierOn">
            <summary>
            QuotedIdentifierOn property class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.ExecuteAsSelf">
            <summary>
            ExecuteAsSelf property class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.WithAppend">
            <summary>
            WithAppend property class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.TriggerType">
            <summary>
            TriggerType property class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.ClassName">
            <summary>
            ClassName property class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.DeleteOrderRestriction">
            <summary>
            DeleteOrderRestriction property class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.InsertOrderRestriction">
            <summary>
            InsertOrderRestriction property class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.IsDeleteTrigger">
            <summary>
            IsDeleteTrigger property class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.IsInsertTrigger">
            <summary>
            IsInsertTrigger property class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.IsNativeCompiled">
            <summary>
            IsNativeCompiled property class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.IsSchemaBound">
            <summary>
            IsSchemaBound property class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.IsUpdateTrigger">
            <summary>
            IsUpdateTrigger property class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.MethodName">
            <summary>
            MethodName property class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.UpdateOrderRestriction">
            <summary>
            UpdateOrderRestriction property class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.TriggerObject">
            <summary>
            TriggerObject relationship class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.Assembly">
            <summary>
            Assembly relationship class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.BodyDependencies">
            <summary>
            BodyDependencies relationship class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.Login">
            <summary>
            Login relationship class of DmlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DmlTrigger.User">
            <summary>
            User relationship class of DmlTrigger
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Endpoint">
            <summary>
            Model schema container class for Endpoint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Endpoint.TypeClass">
            <summary>
            Type class for Endpoint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Endpoint.Payload">
            <summary>
            Payload property class of Endpoint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Endpoint.Protocol">
            <summary>
            Protocol property class of Endpoint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Endpoint.State">
            <summary>
            State property class of Endpoint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Endpoint.Authorizer">
            <summary>
            Authorizer relationship class of Endpoint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Endpoint.PayloadSpecifier">
            <summary>
            PayloadSpecifier relationship class of Endpoint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Endpoint.ProtocolSpecifier">
            <summary>
            ProtocolSpecifier relationship class of Endpoint
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ErrorMessage">
            <summary>
            Model schema container class for ErrorMessage
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ErrorMessage.TypeClass">
            <summary>
            Type class for ErrorMessage
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ErrorMessage.WithLog">
            <summary>
            WithLog property class of ErrorMessage
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ErrorMessage.Language">
            <summary>
            Language property class of ErrorMessage
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ErrorMessage.MessageNumber">
            <summary>
            MessageNumber property class of ErrorMessage
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ErrorMessage.MessageText">
            <summary>
            MessageText property class of ErrorMessage
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ErrorMessage.Severity">
            <summary>
            Severity property class of ErrorMessage
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.EventGroup">
            <summary>
            Model schema container class for EventGroup
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventGroup.TypeClass">
            <summary>
            Type class for EventGroup
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventGroup.Group">
            <summary>
            Group property class of EventGroup
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.EventSession">
            <summary>
            Model schema container class for EventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSession.TypeClass">
            <summary>
            Type class for EventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSession.StartupState">
            <summary>
            StartupState property class of EventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSession.TrackCausality">
            <summary>
            TrackCausality property class of EventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSession.MaxDispatchLatency">
            <summary>
            MaxDispatchLatency property class of EventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSession.MaxEventSizeUnit">
            <summary>
            MaxEventSizeUnit property class of EventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSession.MaxMemoryUnit">
            <summary>
            MaxMemoryUnit property class of EventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSession.EventRetentionMode">
            <summary>
            EventRetentionMode property class of EventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSession.MaxEventSize">
            <summary>
            MaxEventSize property class of EventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSession.MaxMemory">
            <summary>
            MaxMemory property class of EventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSession.MemoryPartitionMode">
            <summary>
            MemoryPartitionMode property class of EventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSession.SessionScope">
            <summary>
            SessionScope property class of EventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSession.EventDefinitions">
            <summary>
            EventDefinitions relationship class of EventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSession.EventTargets">
            <summary>
            EventTargets relationship class of EventSession
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.DatabaseEventSession">
            <summary>
            Model schema container class for DatabaseEventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEventSession.TypeClass">
            <summary>
            Type class for DatabaseEventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEventSession.StartupState">
            <summary>
            StartupState property class of DatabaseEventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEventSession.TrackCausality">
            <summary>
            TrackCausality property class of DatabaseEventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEventSession.MaxDispatchLatency">
            <summary>
            MaxDispatchLatency property class of DatabaseEventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEventSession.MaxEventSizeUnit">
            <summary>
            MaxEventSizeUnit property class of DatabaseEventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEventSession.MaxMemoryUnit">
            <summary>
            MaxMemoryUnit property class of DatabaseEventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEventSession.EventRetentionMode">
            <summary>
            EventRetentionMode property class of DatabaseEventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEventSession.MaxEventSize">
            <summary>
            MaxEventSize property class of DatabaseEventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEventSession.MaxMemory">
            <summary>
            MaxMemory property class of DatabaseEventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEventSession.MemoryPartitionMode">
            <summary>
            MemoryPartitionMode property class of DatabaseEventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEventSession.SessionScope">
            <summary>
            SessionScope property class of DatabaseEventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEventSession.EventDefinitions">
            <summary>
            EventDefinitions relationship class of DatabaseEventSession
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.DatabaseEventSession.EventTargets">
            <summary>
            EventTargets relationship class of DatabaseEventSession
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.EventSessionAction">
            <summary>
            Model schema container class for EventSessionAction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSessionAction.TypeClass">
            <summary>
            Type class for EventSessionAction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSessionAction.ActionName">
            <summary>
            ActionName property class of EventSessionAction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSessionAction.EventModuleGuid">
            <summary>
            EventModuleGuid property class of EventSessionAction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSessionAction.EventPackageName">
            <summary>
            EventPackageName property class of EventSessionAction
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.EventSessionDefinitions">
            <summary>
            Model schema container class for EventSessionDefinitions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSessionDefinitions.TypeClass">
            <summary>
            Type class for EventSessionDefinitions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSessionDefinitions.WhereExpression">
            <summary>
            WhereExpression property class of EventSessionDefinitions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSessionDefinitions.EventModuleGuid">
            <summary>
            EventModuleGuid property class of EventSessionDefinitions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSessionDefinitions.EventName">
            <summary>
            EventName property class of EventSessionDefinitions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSessionDefinitions.EventPackageName">
            <summary>
            EventPackageName property class of EventSessionDefinitions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSessionDefinitions.Actions">
            <summary>
            Actions relationship class of EventSessionDefinitions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSessionDefinitions.AttributeSettings">
            <summary>
            AttributeSettings relationship class of EventSessionDefinitions
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.EventSessionSetting">
            <summary>
            Model schema container class for EventSessionSetting
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSessionSetting.TypeClass">
            <summary>
            Type class for EventSessionSetting
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSessionSetting.SettingValue">
            <summary>
            SettingValue property class of EventSessionSetting
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSessionSetting.SettingName">
            <summary>
            SettingName property class of EventSessionSetting
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.EventSessionTarget">
            <summary>
            Model schema container class for EventSessionTarget
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSessionTarget.TypeClass">
            <summary>
            Type class for EventSessionTarget
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSessionTarget.EventModuleGuid">
            <summary>
            EventModuleGuid property class of EventSessionTarget
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSessionTarget.EventPackageName">
            <summary>
            EventPackageName property class of EventSessionTarget
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSessionTarget.TargetName">
            <summary>
            TargetName property class of EventSessionTarget
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventSessionTarget.ParameterSettings">
            <summary>
            ParameterSettings relationship class of EventSessionTarget
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.EventTypeSpecifier">
            <summary>
            Model schema container class for EventTypeSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventTypeSpecifier.TypeClass">
            <summary>
            Type class for EventTypeSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventTypeSpecifier.EventType">
            <summary>
            EventType property class of EventTypeSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.EventTypeSpecifier.Order">
            <summary>
            Order property class of EventTypeSpecifier
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ExtendedProcedure">
            <summary>
            Model schema container class for ExtendedProcedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExtendedProcedure.TypeClass">
            <summary>
            Type class for ExtendedProcedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExtendedProcedure.ExeccuteAsCaller">
            <summary>
            ExeccuteAsCaller property class of ExtendedProcedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExtendedProcedure.WithEncryption">
            <summary>
            WithEncryption property class of ExtendedProcedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExtendedProcedure.ExecuteAsOwner">
            <summary>
            ExecuteAsOwner property class of ExtendedProcedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExtendedProcedure.ExecuteAsSelf">
            <summary>
            ExecuteAsSelf property class of ExtendedProcedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExtendedProcedure.Login">
            <summary>
            Login relationship class of ExtendedProcedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExtendedProcedure.Parameters">
            <summary>
            Parameters relationship class of ExtendedProcedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExtendedProcedure.Schema">
            <summary>
            Schema relationship class of ExtendedProcedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExtendedProcedure.User">
            <summary>
            User relationship class of ExtendedProcedure
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ExtendedProperty">
            <summary>
            Model schema container class for ExtendedProperty
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExtendedProperty.TypeClass">
            <summary>
            Type class for ExtendedProperty
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExtendedProperty.Value">
            <summary>
            Value property class of ExtendedProperty
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExtendedProperty.Host">
            <summary>
            Host relationship class of ExtendedProperty
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ExternalDataSource">
            <summary>
            Model schema container class for ExternalDataSource
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalDataSource.TypeClass">
            <summary>
            Type class for ExternalDataSource
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalDataSource.DatabaseName">
            <summary>
            DatabaseName property class of ExternalDataSource
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalDataSource.DataSourceType">
            <summary>
            DataSourceType property class of ExternalDataSource
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalDataSource.Location">
            <summary>
            Location property class of ExternalDataSource
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalDataSource.ResourceManagerLocation">
            <summary>
            ResourceManagerLocation property class of ExternalDataSource
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalDataSource.ShardMapName">
            <summary>
            ShardMapName property class of ExternalDataSource
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalDataSource.Credential">
            <summary>
            Credential relationship class of ExternalDataSource
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ExternalFileFormat">
            <summary>
            Model schema container class for ExternalFileFormat
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalFileFormat.TypeClass">
            <summary>
            Type class for ExternalFileFormat
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalFileFormat.DataCompression">
            <summary>
            DataCompression property class of ExternalFileFormat
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalFileFormat.DateFormat">
            <summary>
            DateFormat property class of ExternalFileFormat
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalFileFormat.FieldTerminator">
            <summary>
            FieldTerminator property class of ExternalFileFormat
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalFileFormat.FormatType">
            <summary>
            FormatType property class of ExternalFileFormat
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalFileFormat.SerDeMethod">
            <summary>
            SerDeMethod property class of ExternalFileFormat
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalFileFormat.StringDelimiter">
            <summary>
            StringDelimiter property class of ExternalFileFormat
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalFileFormat.UseTypeDefault">
            <summary>
            UseTypeDefault property class of ExternalFileFormat
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ExternalTable">
            <summary>
            Model schema container class for ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.TypeClass">
            <summary>
            Type class for ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.DistributionPolicyType">
            <summary>
            DistributionPolicyType property class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.ExternalObjectName">
            <summary>
            ExternalObjectName property class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.ExternalSchemaName">
            <summary>
            ExternalSchemaName property class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.IsAnsiNullsOn">
            <summary>
            IsAnsiNullsOn property class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.IsFileStreamNull">
            <summary>
            IsFileStreamNull property class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.IsQuotedIdentifierOn">
            <summary>
            IsQuotedIdentifierOn property class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.IsTableLockOnBulkLoad">
            <summary>
            IsTableLockOnBulkLoad property class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.Location">
            <summary>
            Location property class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.LockEscalation">
            <summary>
            LockEscalation property class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.RejectSampleValue">
            <summary>
            RejectSampleValue property class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.RejectType">
            <summary>
            RejectType property class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.RejectValue">
            <summary>
            RejectValue property class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.Columns">
            <summary>
            Columns relationship class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.DataCompressionOptions">
            <summary>
            DataCompressionOptions relationship class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.DataSourceName">
            <summary>
            DataSourceName relationship class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.FileFormatName">
            <summary>
            FileFormatName relationship class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.Filegroup">
            <summary>
            Filegroup relationship class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.FileStreamFilegroup">
            <summary>
            FileStreamFilegroup relationship class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.FileStreamPartitionScheme">
            <summary>
            FileStreamPartitionScheme relationship class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.PartitionColumn">
            <summary>
            PartitionColumn relationship class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.PartitionScheme">
            <summary>
            PartitionScheme relationship class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.Schema">
            <summary>
            Schema relationship class of ExternalTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ExternalTable.ShardingColumn">
            <summary>
            ShardingColumn relationship class of ExternalTable
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SqlFile">
            <summary>
            Model schema container class for SqlFile
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SqlFile.TypeClass">
            <summary>
            Type class for SqlFile
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SqlFile.Offline">
            <summary>
            Offline property class of SqlFile
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SqlFile.Unlimited">
            <summary>
            Unlimited property class of SqlFile
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SqlFile.FileGrowth">
            <summary>
            FileGrowth property class of SqlFile
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SqlFile.FileGrowthUnit">
            <summary>
            FileGrowthUnit property class of SqlFile
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SqlFile.FileName">
            <summary>
            FileName property class of SqlFile
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SqlFile.IsLogFile">
            <summary>
            IsLogFile property class of SqlFile
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SqlFile.MaxSize">
            <summary>
            MaxSize property class of SqlFile
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SqlFile.MaxSizeUnit">
            <summary>
            MaxSizeUnit property class of SqlFile
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SqlFile.Size">
            <summary>
            Size property class of SqlFile
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SqlFile.SizeUnit">
            <summary>
            SizeUnit property class of SqlFile
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SqlFile.Filegroup">
            <summary>
            Filegroup relationship class of SqlFile
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Filegroup">
            <summary>
            Model schema container class for Filegroup
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Filegroup.TypeClass">
            <summary>
            Type class for Filegroup
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Filegroup.ContainsFileStream">
            <summary>
            ContainsFileStream property class of Filegroup
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Filegroup.ReadOnly">
            <summary>
            ReadOnly property class of Filegroup
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Filegroup.ContainsMemoryOptimizedData">
            <summary>
            ContainsMemoryOptimizedData property class of Filegroup
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ForeignKeyConstraint">
            <summary>
            Model schema container class for ForeignKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ForeignKeyConstraint.TypeClass">
            <summary>
            Type class for ForeignKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ForeignKeyConstraint.Disabled">
            <summary>
            Disabled property class of ForeignKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ForeignKeyConstraint.NotForReplication">
            <summary>
            NotForReplication property class of ForeignKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ForeignKeyConstraint.DeleteAction">
            <summary>
            DeleteAction property class of ForeignKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ForeignKeyConstraint.UpdateAction">
            <summary>
            UpdateAction property class of ForeignKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ForeignKeyConstraint.Host">
            <summary>
            Host relationship class of ForeignKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ForeignKeyConstraint.Columns">
            <summary>
            Columns relationship class of ForeignKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ForeignKeyConstraint.ForeignColumns">
            <summary>
            ForeignColumns relationship class of ForeignKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ForeignKeyConstraint.ForeignTable">
            <summary>
            ForeignTable relationship class of ForeignKeyConstraint
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.FullTextCatalog">
            <summary>
            Model schema container class for FullTextCatalog
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextCatalog.TypeClass">
            <summary>
            Type class for FullTextCatalog
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextCatalog.AccentSensitivity">
            <summary>
            AccentSensitivity property class of FullTextCatalog
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextCatalog.IsDefault">
            <summary>
            IsDefault property class of FullTextCatalog
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextCatalog.Path">
            <summary>
            Path property class of FullTextCatalog
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextCatalog.Authorizer">
            <summary>
            Authorizer relationship class of FullTextCatalog
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextCatalog.Filegroup">
            <summary>
            Filegroup relationship class of FullTextCatalog
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.FullTextIndex">
            <summary>
            Model schema container class for FullTextIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextIndex.TypeClass">
            <summary>
            Type class for FullTextIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextIndex.ChangeTracking">
            <summary>
            ChangeTracking property class of FullTextIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextIndex.UseSystemStopList">
            <summary>
            UseSystemStopList property class of FullTextIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextIndex.Disabled">
            <summary>
            Disabled property class of FullTextIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextIndex.Replicated">
            <summary>
            Replicated property class of FullTextIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextIndex.StopListOff">
            <summary>
            StopListOff property class of FullTextIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextIndex.UniqueIndexName">
            <summary>
            UniqueIndexName relationship class of FullTextIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextIndex.Catalog">
            <summary>
            Catalog relationship class of FullTextIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextIndex.Columns">
            <summary>
            Columns relationship class of FullTextIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextIndex.Filegroup">
            <summary>
            Filegroup relationship class of FullTextIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextIndex.IndexedObject">
            <summary>
            IndexedObject relationship class of FullTextIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextIndex.SearchPropertyList">
            <summary>
            SearchPropertyList relationship class of FullTextIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextIndex.StopList">
            <summary>
            StopList relationship class of FullTextIndex
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.FullTextIndexColumnSpecifier">
            <summary>
            Model schema container class for FullTextIndexColumnSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextIndexColumnSpecifier.TypeClass">
            <summary>
            Type class for FullTextIndexColumnSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextIndexColumnSpecifier.PartOfStatisticalSemantics">
            <summary>
            PartOfStatisticalSemantics property class of FullTextIndexColumnSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextIndexColumnSpecifier.LanguageId">
            <summary>
            LanguageId property class of FullTextIndexColumnSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextIndexColumnSpecifier.Column">
            <summary>
            Column relationship class of FullTextIndexColumnSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextIndexColumnSpecifier.TypeColumn">
            <summary>
            TypeColumn relationship class of FullTextIndexColumnSpecifier
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.FullTextStopList">
            <summary>
            Model schema container class for FullTextStopList
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextStopList.TypeClass">
            <summary>
            Type class for FullTextStopList
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FullTextStopList.Authorizer">
            <summary>
            Authorizer relationship class of FullTextStopList
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.HttpProtocolSpecifier">
            <summary>
            Model schema container class for HttpProtocolSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.HttpProtocolSpecifier.TypeClass">
            <summary>
            Type class for HttpProtocolSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.HttpProtocolSpecifier.CompressionEnabled">
            <summary>
            CompressionEnabled property class of HttpProtocolSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.HttpProtocolSpecifier.ListeningOnAllNoneReservedSites">
            <summary>
            ListeningOnAllNoneReservedSites property class of HttpProtocolSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.HttpProtocolSpecifier.ListeningOnAllSites">
            <summary>
            ListeningOnAllSites property class of HttpProtocolSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.HttpProtocolSpecifier.AuthenticationMode">
            <summary>
            AuthenticationMode property class of HttpProtocolSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.HttpProtocolSpecifier.AuthenticationRealm">
            <summary>
            AuthenticationRealm property class of HttpProtocolSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.HttpProtocolSpecifier.ClearPort">
            <summary>
            ClearPort property class of HttpProtocolSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.HttpProtocolSpecifier.DefaultLogonDomain">
            <summary>
            DefaultLogonDomain property class of HttpProtocolSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.HttpProtocolSpecifier.Path">
            <summary>
            Path property class of HttpProtocolSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.HttpProtocolSpecifier.Ports">
            <summary>
            Ports property class of HttpProtocolSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.HttpProtocolSpecifier.SslPort">
            <summary>
            SslPort property class of HttpProtocolSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.HttpProtocolSpecifier.Website">
            <summary>
            Website property class of HttpProtocolSpecifier
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.LinkedServer">
            <summary>
            Model schema container class for LinkedServer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServer.TypeClass">
            <summary>
            Type class for LinkedServer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServer.CollationCompatible">
            <summary>
            CollationCompatible property class of LinkedServer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServer.DataAccess">
            <summary>
            DataAccess property class of LinkedServer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServer.LazySchemaValidationEnabled">
            <summary>
            LazySchemaValidationEnabled property class of LinkedServer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServer.RemoteProcTransactionPromotionEnabled">
            <summary>
            RemoteProcTransactionPromotionEnabled property class of LinkedServer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServer.RpcEnabled">
            <summary>
            RpcEnabled property class of LinkedServer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServer.RpcOutEnabled">
            <summary>
            RpcOutEnabled property class of LinkedServer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServer.ProviderName">
            <summary>
            ProviderName property class of LinkedServer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServer.Catalog">
            <summary>
            Catalog property class of LinkedServer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServer.CollationName">
            <summary>
            CollationName property class of LinkedServer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServer.ConnectTimeout">
            <summary>
            ConnectTimeout property class of LinkedServer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServer.DataSource">
            <summary>
            DataSource property class of LinkedServer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServer.IsDistributor">
            <summary>
            IsDistributor property class of LinkedServer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServer.IsPublisher">
            <summary>
            IsPublisher property class of LinkedServer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServer.IsSubscriber">
            <summary>
            IsSubscriber property class of LinkedServer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServer.Location">
            <summary>
            Location property class of LinkedServer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServer.ProductName">
            <summary>
            ProductName property class of LinkedServer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServer.ProviderString">
            <summary>
            ProviderString property class of LinkedServer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServer.QueryTimeout">
            <summary>
            QueryTimeout property class of LinkedServer
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServer.UseRemoteCollation">
            <summary>
            UseRemoteCollation property class of LinkedServer
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.LinkedServerLogin">
            <summary>
            Model schema container class for LinkedServerLogin
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServerLogin.TypeClass">
            <summary>
            Type class for LinkedServerLogin
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServerLogin.UseSelf">
            <summary>
            UseSelf property class of LinkedServerLogin
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServerLogin.LinkedServerLoginName">
            <summary>
            LinkedServerLoginName property class of LinkedServerLogin
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServerLogin.LinkedServerPassword">
            <summary>
            LinkedServerPassword property class of LinkedServerLogin
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServerLogin.LinkedServer">
            <summary>
            LinkedServer relationship class of LinkedServerLogin
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.LinkedServerLogin.LocalLogin">
            <summary>
            LocalLogin relationship class of LinkedServerLogin
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Login">
            <summary>
            Model schema container class for Login
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Login.TypeClass">
            <summary>
            Type class for Login
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Login.CheckExpiration">
            <summary>
            CheckExpiration property class of Login
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Login.CheckPolicy">
            <summary>
            CheckPolicy property class of Login
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Login.Disabled">
            <summary>
            Disabled property class of Login
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Login.MappedToWindowsLogin">
            <summary>
            MappedToWindowsLogin property class of Login
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Login.PasswordHashed">
            <summary>
            PasswordHashed property class of Login
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Login.PasswordMustChange">
            <summary>
            PasswordMustChange property class of Login
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Login.DefaultDatabase">
            <summary>
            DefaultDatabase property class of Login
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Login.DefaultLanguage">
            <summary>
            DefaultLanguage property class of Login
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Login.EncryptionOption">
            <summary>
            EncryptionOption property class of Login
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Login.Password">
            <summary>
            Password property class of Login
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Login.Sid">
            <summary>
            Sid property class of Login
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Login.AsymmetricKey">
            <summary>
            AsymmetricKey relationship class of Login
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Login.Certificate">
            <summary>
            Certificate relationship class of Login
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Login.Credential">
            <summary>
            Credential relationship class of Login
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.MasterKey">
            <summary>
            Model schema container class for MasterKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.MasterKey.TypeClass">
            <summary>
            Type class for MasterKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.MasterKey.Password">
            <summary>
            Password property class of MasterKey
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.MessageType">
            <summary>
            Model schema container class for MessageType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.MessageType.TypeClass">
            <summary>
            Type class for MessageType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.MessageType.ValidationMethod">
            <summary>
            ValidationMethod property class of MessageType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.MessageType.Authorizer">
            <summary>
            Authorizer relationship class of MessageType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.MessageType.XmlSchemaCollection">
            <summary>
            XmlSchemaCollection relationship class of MessageType
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.PartitionFunction">
            <summary>
            Model schema container class for PartitionFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PartitionFunction.TypeClass">
            <summary>
            Type class for PartitionFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PartitionFunction.Range">
            <summary>
            Range property class of PartitionFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PartitionFunction.ParameterType">
            <summary>
            ParameterType relationship class of PartitionFunction
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PartitionFunction.BoundaryValues">
            <summary>
            BoundaryValues relationship class of PartitionFunction
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.PartitionScheme">
            <summary>
            Model schema container class for PartitionScheme
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PartitionScheme.TypeClass">
            <summary>
            Type class for PartitionScheme
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PartitionScheme.AllToOneFilegroup">
            <summary>
            AllToOneFilegroup property class of PartitionScheme
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PartitionScheme.Filegroups">
            <summary>
            Filegroups relationship class of PartitionScheme
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PartitionScheme.PartitionFunction">
            <summary>
            PartitionFunction relationship class of PartitionScheme
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.PartitionScheme.FilegroupsRelationship">
            <summary>
            Model schema container class for FilegroupsRelationship
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PartitionScheme.FilegroupsRelationship.RelationshipClass">
            <summary>
            Relationship class for FilegroupsRelationship
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PartitionScheme.FilegroupsRelationship.IsDefault">
            <summary>
            IsDefault property class of FilegroupsRelationship
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.PartitionValue">
            <summary>
            Model schema container class for PartitionValue
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PartitionValue.TypeClass">
            <summary>
            Type class for PartitionValue
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PartitionValue.Expression">
            <summary>
            Expression property class of PartitionValue
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PartitionValue.ExpressionDependencies">
            <summary>
            ExpressionDependencies relationship class of PartitionValue
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Permission">
            <summary>
            Model schema container class for Permission
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Permission.TypeClass">
            <summary>
            Type class for Permission
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Permission.WithAllPrivileges">
            <summary>
            WithAllPrivileges property class of Permission
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Permission.WithGrantOption">
            <summary>
            WithGrantOption property class of Permission
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Permission.PermissionType">
            <summary>
            PermissionType property class of Permission
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Permission.PermissionAction">
            <summary>
            PermissionAction property class of Permission
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Permission.ExcludedColumns">
            <summary>
            ExcludedColumns relationship class of Permission
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Permission.Grantee">
            <summary>
            Grantee relationship class of Permission
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Permission.Grantor">
            <summary>
            Grantor relationship class of Permission
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Permission.RevokedGrantOptionColumns">
            <summary>
            RevokedGrantOptionColumns relationship class of Permission
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Permission.SecuredObject">
            <summary>
            SecuredObject relationship class of Permission
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint">
            <summary>
            Model schema container class for PrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.TypeClass">
            <summary>
            Type class for PrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.AllowPageLocks">
            <summary>
            AllowPageLocks property class of PrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.AllowRowLocks">
            <summary>
            AllowRowLocks property class of PrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.IgnoreDuplicateKey">
            <summary>
            IgnoreDuplicateKey property class of PrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.RecomputeStatistics">
            <summary>
            RecomputeStatistics property class of PrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.Clustered">
            <summary>
            Clustered property class of PrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.Disabled">
            <summary>
            Disabled property class of PrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.FileStreamNull">
            <summary>
            FileStreamNull property class of PrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.WithPadIndex">
            <summary>
            WithPadIndex property class of PrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.Hash">
            <summary>
            Hash property class of PrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.BucketCount">
            <summary>
            BucketCount property class of PrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.FillFactor">
            <summary>
            FillFactor property class of PrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.Host">
            <summary>
            Host relationship class of PrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.Columns">
            <summary>
            Columns relationship class of PrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.DataCompressionOptions">
            <summary>
            DataCompressionOptions relationship class of PrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.Filegroup">
            <summary>
            Filegroup relationship class of PrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.FileStreamFilegroup">
            <summary>
            FileStreamFilegroup relationship class of PrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.FileStreamPartitionScheme">
            <summary>
            FileStreamPartitionScheme relationship class of PrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.PartitionColumn">
            <summary>
            PartitionColumn relationship class of PrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.PartitionScheme">
            <summary>
            PartitionScheme relationship class of PrimaryKeyConstraint
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.ColumnsRelationship">
            <summary>
            Model schema container class for ColumnsRelationship
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.ColumnsRelationship.RelationshipClass">
            <summary>
            Relationship class for ColumnsRelationship
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PrimaryKeyConstraint.ColumnsRelationship.Ascending">
            <summary>
            Ascending property class of ColumnsRelationship
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Procedure">
            <summary>
            Model schema container class for Procedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Procedure.TypeClass">
            <summary>
            Type class for Procedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Procedure.AnsiNullsOn">
            <summary>
            AnsiNullsOn property class of Procedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Procedure.ExecuteAsCaller">
            <summary>
            ExecuteAsCaller property class of Procedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Procedure.WithEncryption">
            <summary>
            WithEncryption property class of Procedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Procedure.ForReplication">
            <summary>
            ForReplication property class of Procedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Procedure.ExecuteAsOwner">
            <summary>
            ExecuteAsOwner property class of Procedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Procedure.QuotedIdentifierOn">
            <summary>
            QuotedIdentifierOn property class of Procedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Procedure.WithRecompile">
            <summary>
            WithRecompile property class of Procedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Procedure.ExecuteAsSelf">
            <summary>
            ExecuteAsSelf property class of Procedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Procedure.WithNativeCompilation">
            <summary>
            WithNativeCompilation property class of Procedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Procedure.WithSchemaBinding">
            <summary>
            WithSchemaBinding property class of Procedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Procedure.ClassName">
            <summary>
            ClassName property class of Procedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Procedure.IsReplicated">
            <summary>
            IsReplicated property class of Procedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Procedure.MethodName">
            <summary>
            MethodName property class of Procedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Procedure.ParentProcedure">
            <summary>
            ParentProcedure relationship class of Procedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Procedure.Assembly">
            <summary>
            Assembly relationship class of Procedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Procedure.BodyDependencies">
            <summary>
            BodyDependencies relationship class of Procedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Procedure.Login">
            <summary>
            Login relationship class of Procedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Procedure.Parameters">
            <summary>
            Parameters relationship class of Procedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Procedure.Schema">
            <summary>
            Schema relationship class of Procedure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Procedure.User">
            <summary>
            User relationship class of Procedure
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Queue">
            <summary>
            Model schema container class for Queue
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Queue.TypeClass">
            <summary>
            Type class for Queue
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Queue.ActivationStatusOn">
            <summary>
            ActivationStatusOn property class of Queue
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Queue.ActivationExecuteAsCaller">
            <summary>
            ActivationExecuteAsCaller property class of Queue
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Queue.ActivationExecuteAsOwner">
            <summary>
            ActivationExecuteAsOwner property class of Queue
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Queue.PoisonMessageHandlingStatusOn">
            <summary>
            PoisonMessageHandlingStatusOn property class of Queue
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Queue.RetentionOn">
            <summary>
            RetentionOn property class of Queue
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Queue.ActivationExecuteAsSelf">
            <summary>
            ActivationExecuteAsSelf property class of Queue
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Queue.StatusOn">
            <summary>
            StatusOn property class of Queue
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Queue.ActivationMaxQueueReaders">
            <summary>
            ActivationMaxQueueReaders property class of Queue
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Queue.ActivationProcedure">
            <summary>
            ActivationProcedure relationship class of Queue
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Queue.Columns">
            <summary>
            Columns relationship class of Queue
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Queue.Filegroup">
            <summary>
            Filegroup relationship class of Queue
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Queue.Login">
            <summary>
            Login relationship class of Queue
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Queue.PartitionColumn">
            <summary>
            PartitionColumn relationship class of Queue
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Queue.PartitionScheme">
            <summary>
            PartitionScheme relationship class of Queue
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Queue.Schema">
            <summary>
            Schema relationship class of Queue
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Queue.User">
            <summary>
            User relationship class of Queue
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.QueueEventNotification">
            <summary>
            Model schema container class for QueueEventNotification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.QueueEventNotification.TypeClass">
            <summary>
            Type class for QueueEventNotification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.QueueEventNotification.WithFanIn">
            <summary>
            WithFanIn property class of QueueEventNotification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.QueueEventNotification.BrokerService">
            <summary>
            BrokerService property class of QueueEventNotification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.QueueEventNotification.BrokerInstanceSpecifier">
            <summary>
            BrokerInstanceSpecifier property class of QueueEventNotification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.QueueEventNotification.EventGroup">
            <summary>
            EventGroup relationship class of QueueEventNotification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.QueueEventNotification.EventType">
            <summary>
            EventType relationship class of QueueEventNotification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.QueueEventNotification.Queue">
            <summary>
            Queue relationship class of QueueEventNotification
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.RemoteServiceBinding">
            <summary>
            Model schema container class for RemoteServiceBinding
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.RemoteServiceBinding.TypeClass">
            <summary>
            Type class for RemoteServiceBinding
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.RemoteServiceBinding.Anonymous">
            <summary>
            Anonymous property class of RemoteServiceBinding
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.RemoteServiceBinding.Service">
            <summary>
            Service property class of RemoteServiceBinding
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.RemoteServiceBinding.User">
            <summary>
            User relationship class of RemoteServiceBinding
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.RemoteServiceBinding.Authorizer">
            <summary>
            Authorizer relationship class of RemoteServiceBinding
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ResourceGovernor">
            <summary>
            Model schema container class for ResourceGovernor
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ResourceGovernor.TypeClass">
            <summary>
            Type class for ResourceGovernor
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ResourceGovernor.Enabled">
            <summary>
            Enabled property class of ResourceGovernor
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ResourceGovernor.ClassifierFunction">
            <summary>
            ClassifierFunction relationship class of ResourceGovernor
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ResourcePool">
            <summary>
            Model schema container class for ResourcePool
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ResourcePool.TypeClass">
            <summary>
            Type class for ResourcePool
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ResourcePool.CapCpuPercent">
            <summary>
            CapCpuPercent property class of ResourcePool
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ResourcePool.MaxCpuPercent">
            <summary>
            MaxCpuPercent property class of ResourcePool
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ResourcePool.MaxIopsPerVolume">
            <summary>
            MaxIopsPerVolume property class of ResourcePool
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ResourcePool.MaxMemoryPercent">
            <summary>
            MaxMemoryPercent property class of ResourcePool
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ResourcePool.MinCpuPercent">
            <summary>
            MinCpuPercent property class of ResourcePool
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ResourcePool.MinIopsPerVolume">
            <summary>
            MinIopsPerVolume property class of ResourcePool
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ResourcePool.MinMemoryPercent">
            <summary>
            MinMemoryPercent property class of ResourcePool
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Role">
            <summary>
            Model schema container class for Role
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Role.TypeClass">
            <summary>
            Type class for Role
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Role.Authorizer">
            <summary>
            Authorizer relationship class of Role
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.RoleMembership">
            <summary>
            Model schema container class for RoleMembership
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.RoleMembership.TypeClass">
            <summary>
            Type class for RoleMembership
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.RoleMembership.Member">
            <summary>
            Member relationship class of RoleMembership
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.RoleMembership.Role">
            <summary>
            Role relationship class of RoleMembership
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Route">
            <summary>
            Model schema container class for Route
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Route.TypeClass">
            <summary>
            Type class for Route
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Route.BrokerInstance">
            <summary>
            BrokerInstance property class of Route
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Route.ServiceName">
            <summary>
            ServiceName property class of Route
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Route.Address">
            <summary>
            Address property class of Route
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Route.Lifetime">
            <summary>
            Lifetime property class of Route
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Route.MirrorAddress">
            <summary>
            MirrorAddress property class of Route
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Route.Authorizer">
            <summary>
            Authorizer relationship class of Route
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Rule">
            <summary>
            Model schema container class for Rule
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Rule.TypeClass">
            <summary>
            Type class for Rule
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Rule.Expression">
            <summary>
            Expression property class of Rule
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Rule.BoundObjects">
            <summary>
            BoundObjects relationship class of Rule
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Rule.Schema">
            <summary>
            Schema relationship class of Rule
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Schema">
            <summary>
            Model schema container class for Schema
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Schema.TypeClass">
            <summary>
            Type class for Schema
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Schema.Authorizer">
            <summary>
            Authorizer relationship class of Schema
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SearchProperty">
            <summary>
            Model schema container class for SearchProperty
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SearchProperty.TypeClass">
            <summary>
            Type class for SearchProperty
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SearchProperty.Description">
            <summary>
            Description property class of SearchProperty
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SearchProperty.Identifier">
            <summary>
            Identifier property class of SearchProperty
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SearchProperty.PropertySetGuid">
            <summary>
            PropertySetGuid property class of SearchProperty
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SearchProperty.SearchPropertyList">
            <summary>
            SearchPropertyList relationship class of SearchProperty
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SearchPropertyList">
            <summary>
            Model schema container class for SearchPropertyList
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SearchPropertyList.TypeClass">
            <summary>
            Type class for SearchPropertyList
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SearchPropertyList.Authorizer">
            <summary>
            Authorizer relationship class of SearchPropertyList
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SecurityPolicy">
            <summary>
            Model schema container class for SecurityPolicy
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SecurityPolicy.TypeClass">
            <summary>
            Type class for SecurityPolicy
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SecurityPolicy.Enabled">
            <summary>
            Enabled property class of SecurityPolicy
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SecurityPolicy.IsSchemaBound">
            <summary>
            IsSchemaBound property class of SecurityPolicy
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SecurityPolicy.NotForReplication">
            <summary>
            NotForReplication property class of SecurityPolicy
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SecurityPolicy.Predicates">
            <summary>
            Predicates relationship class of SecurityPolicy
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SecurityPolicy.Schema">
            <summary>
            Schema relationship class of SecurityPolicy
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SecurityPredicate">
            <summary>
            Model schema container class for SecurityPredicate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SecurityPredicate.TypeClass">
            <summary>
            Type class for SecurityPredicate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SecurityPredicate.BodyScript">
            <summary>
            BodyScript property class of SecurityPredicate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SecurityPredicate.Operation">
            <summary>
            Operation property class of SecurityPredicate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SecurityPredicate.PredicateType">
            <summary>
            PredicateType property class of SecurityPredicate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SecurityPredicate.BodyDependencies">
            <summary>
            BodyDependencies relationship class of SecurityPredicate
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SecurityPredicate.TargetObject">
            <summary>
            TargetObject relationship class of SecurityPredicate
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Sequence">
            <summary>
            Model schema container class for Sequence
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Sequence.TypeClass">
            <summary>
            Type class for Sequence
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Sequence.NoMaxValue">
            <summary>
            NoMaxValue property class of Sequence
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Sequence.NoMinValue">
            <summary>
            NoMinValue property class of Sequence
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Sequence.IncrementValue">
            <summary>
            IncrementValue property class of Sequence
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Sequence.CacheSize">
            <summary>
            CacheSize property class of Sequence
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Sequence.IsCached">
            <summary>
            IsCached property class of Sequence
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Sequence.IsCycling">
            <summary>
            IsCycling property class of Sequence
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Sequence.MaxValue">
            <summary>
            MaxValue property class of Sequence
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Sequence.MinValue">
            <summary>
            MinValue property class of Sequence
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Sequence.StartValue">
            <summary>
            StartValue property class of Sequence
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Sequence.DataType">
            <summary>
            DataType relationship class of Sequence
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Sequence.Schema">
            <summary>
            Schema relationship class of Sequence
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ServerAudit">
            <summary>
            Model schema container class for ServerAudit
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerAudit.TypeClass">
            <summary>
            Type class for ServerAudit
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerAudit.Disabled">
            <summary>
            Disabled property class of ServerAudit
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerAudit.ReserveDiskSpace">
            <summary>
            ReserveDiskSpace property class of ServerAudit
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerAudit.UnlimitedFileSize">
            <summary>
            UnlimitedFileSize property class of ServerAudit
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerAudit.UnlimitedMaxRolloverFiles">
            <summary>
            UnlimitedMaxRolloverFiles property class of ServerAudit
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerAudit.OnFailure">
            <summary>
            OnFailure property class of ServerAudit
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerAudit.PredicateExpression">
            <summary>
            PredicateExpression property class of ServerAudit
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerAudit.AuditGuid">
            <summary>
            AuditGuid property class of ServerAudit
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerAudit.AuditTarget">
            <summary>
            AuditTarget property class of ServerAudit
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerAudit.FilePath">
            <summary>
            FilePath property class of ServerAudit
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerAudit.MaxFiles">
            <summary>
            MaxFiles property class of ServerAudit
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerAudit.MaxRolloverFiles">
            <summary>
            MaxRolloverFiles property class of ServerAudit
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerAudit.MaxSize">
            <summary>
            MaxSize property class of ServerAudit
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerAudit.MaxSizeUnit">
            <summary>
            MaxSizeUnit property class of ServerAudit
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerAudit.QueueDelay">
            <summary>
            QueueDelay property class of ServerAudit
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ServerAuditSpecification">
            <summary>
            Model schema container class for ServerAuditSpecification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerAuditSpecification.TypeClass">
            <summary>
            Type class for ServerAuditSpecification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerAuditSpecification.StateOn">
            <summary>
            StateOn property class of ServerAuditSpecification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerAuditSpecification.AuditActionGroups">
            <summary>
            AuditActionGroups relationship class of ServerAuditSpecification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerAuditSpecification.ServerAudit">
            <summary>
            ServerAudit relationship class of ServerAuditSpecification
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ServerDdlTrigger">
            <summary>
            Model schema container class for ServerDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerDdlTrigger.TypeClass">
            <summary>
            Type class for ServerDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerDdlTrigger.AnsiNullsOn">
            <summary>
            AnsiNullsOn property class of ServerDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerDdlTrigger.ExecuteAsCaller">
            <summary>
            ExecuteAsCaller property class of ServerDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerDdlTrigger.Disabled">
            <summary>
            Disabled property class of ServerDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerDdlTrigger.WithEncryption">
            <summary>
            WithEncryption property class of ServerDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerDdlTrigger.ExecuteAsOwner">
            <summary>
            ExecuteAsOwner property class of ServerDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerDdlTrigger.QuotedIdentifierOn">
            <summary>
            QuotedIdentifierOn property class of ServerDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerDdlTrigger.ExecuteAsSelf">
            <summary>
            ExecuteAsSelf property class of ServerDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerDdlTrigger.TriggerType">
            <summary>
            TriggerType property class of ServerDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerDdlTrigger.ClassName">
            <summary>
            ClassName property class of ServerDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerDdlTrigger.IsLogon">
            <summary>
            IsLogon property class of ServerDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerDdlTrigger.MethodName">
            <summary>
            MethodName property class of ServerDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerDdlTrigger.Assembly">
            <summary>
            Assembly relationship class of ServerDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerDdlTrigger.BodyDependencies">
            <summary>
            BodyDependencies relationship class of ServerDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerDdlTrigger.EventGroup">
            <summary>
            EventGroup relationship class of ServerDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerDdlTrigger.EventType">
            <summary>
            EventType relationship class of ServerDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerDdlTrigger.Login">
            <summary>
            Login relationship class of ServerDdlTrigger
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerDdlTrigger.User">
            <summary>
            User relationship class of ServerDdlTrigger
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ServerEventNotification">
            <summary>
            Model schema container class for ServerEventNotification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerEventNotification.TypeClass">
            <summary>
            Type class for ServerEventNotification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerEventNotification.WithFanIn">
            <summary>
            WithFanIn property class of ServerEventNotification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerEventNotification.BrokerService">
            <summary>
            BrokerService property class of ServerEventNotification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerEventNotification.BrokerInstanceSpecifier">
            <summary>
            BrokerInstanceSpecifier property class of ServerEventNotification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerEventNotification.EventGroup">
            <summary>
            EventGroup relationship class of ServerEventNotification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerEventNotification.EventType">
            <summary>
            EventType relationship class of ServerEventNotification
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ServerOptions">
            <summary>
            Model schema container class for ServerOptions
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerOptions.TypeClass">
            <summary>
            Type class for ServerOptions
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ServerRoleMembership">
            <summary>
            Model schema container class for ServerRoleMembership
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerRoleMembership.TypeClass">
            <summary>
            Type class for ServerRoleMembership
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerRoleMembership.Member">
            <summary>
            Member relationship class of ServerRoleMembership
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServerRoleMembership.Role">
            <summary>
            Role relationship class of ServerRoleMembership
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Service">
            <summary>
            Model schema container class for Service
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Service.TypeClass">
            <summary>
            Type class for Service
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Service.UseDefaultContract">
            <summary>
            UseDefaultContract property class of Service
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Service.Authorizer">
            <summary>
            Authorizer relationship class of Service
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Service.Contracts">
            <summary>
            Contracts relationship class of Service
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Service.Queue">
            <summary>
            Queue relationship class of Service
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ServiceBrokerLanguageSpecifier">
            <summary>
            Model schema container class for ServiceBrokerLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServiceBrokerLanguageSpecifier.TypeClass">
            <summary>
            Type class for ServiceBrokerLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServiceBrokerLanguageSpecifier.WindowsAuthenticationMode">
            <summary>
            WindowsAuthenticationMode property class of ServiceBrokerLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServiceBrokerLanguageSpecifier.UseCertificateFirst">
            <summary>
            UseCertificateFirst property class of ServiceBrokerLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServiceBrokerLanguageSpecifier.MessageForwardingEnabled">
            <summary>
            MessageForwardingEnabled property class of ServiceBrokerLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServiceBrokerLanguageSpecifier.EncryptionAlgorithmPart1">
            <summary>
            EncryptionAlgorithmPart1 property class of ServiceBrokerLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServiceBrokerLanguageSpecifier.EncryptionAlgorithmPart2">
            <summary>
            EncryptionAlgorithmPart2 property class of ServiceBrokerLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServiceBrokerLanguageSpecifier.EncryptionMode">
            <summary>
            EncryptionMode property class of ServiceBrokerLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServiceBrokerLanguageSpecifier.MessageForwardSize">
            <summary>
            MessageForwardSize property class of ServiceBrokerLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ServiceBrokerLanguageSpecifier.AuthenticationCertificate">
            <summary>
            AuthenticationCertificate relationship class of ServiceBrokerLanguageSpecifier
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Signature">
            <summary>
            Model schema container class for Signature
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Signature.TypeClass">
            <summary>
            Type class for Signature
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Signature.IsCounterSignature">
            <summary>
            IsCounterSignature property class of Signature
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Signature.EncryptionMechanism">
            <summary>
            EncryptionMechanism relationship class of Signature
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Signature.SignedObject">
            <summary>
            SignedObject relationship class of Signature
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SignatureEncryptionMechanism">
            <summary>
            Model schema container class for SignatureEncryptionMechanism
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SignatureEncryptionMechanism.TypeClass">
            <summary>
            Type class for SignatureEncryptionMechanism
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SignatureEncryptionMechanism.Password">
            <summary>
            Password property class of SignatureEncryptionMechanism
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SignatureEncryptionMechanism.SignedBlob">
            <summary>
            SignedBlob property class of SignatureEncryptionMechanism
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SignatureEncryptionMechanism.AsymmetricKey">
            <summary>
            AsymmetricKey relationship class of SignatureEncryptionMechanism
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SignatureEncryptionMechanism.Certificate">
            <summary>
            Certificate relationship class of SignatureEncryptionMechanism
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SoapLanguageSpecifier">
            <summary>
            Model schema container class for SoapLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapLanguageSpecifier.TypeClass">
            <summary>
            Type class for SoapLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapLanguageSpecifier.BatchesEnabled">
            <summary>
            BatchesEnabled property class of SoapLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapLanguageSpecifier.SessionsEnabled">
            <summary>
            SessionsEnabled property class of SoapLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapLanguageSpecifier.SessionTimeoutNever">
            <summary>
            SessionTimeoutNever property class of SoapLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapLanguageSpecifier.CharacterSet">
            <summary>
            CharacterSet property class of SoapLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapLanguageSpecifier.DatabaseName">
            <summary>
            DatabaseName property class of SoapLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapLanguageSpecifier.HeaderLimit">
            <summary>
            HeaderLimit property class of SoapLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapLanguageSpecifier.IsDefaultDatabase">
            <summary>
            IsDefaultDatabase property class of SoapLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapLanguageSpecifier.IsDefaultNamespace">
            <summary>
            IsDefaultNamespace property class of SoapLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapLanguageSpecifier.IsDefaultWsdlSpName">
            <summary>
            IsDefaultWsdlSpName property class of SoapLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapLanguageSpecifier.LoginType">
            <summary>
            LoginType property class of SoapLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapLanguageSpecifier.Namespace">
            <summary>
            Namespace property class of SoapLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapLanguageSpecifier.SchemaType">
            <summary>
            SchemaType property class of SoapLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapLanguageSpecifier.SessionTimeout">
            <summary>
            SessionTimeout property class of SoapLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapLanguageSpecifier.WsdlSpName">
            <summary>
            WsdlSpName property class of SoapLanguageSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapLanguageSpecifier.WebMethods">
            <summary>
            WebMethods relationship class of SoapLanguageSpecifier
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SoapMethodSpecification">
            <summary>
            Model schema container class for SoapMethodSpecification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapMethodSpecification.TypeClass">
            <summary>
            Type class for SoapMethodSpecification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapMethodSpecification.SchemaType">
            <summary>
            SchemaType property class of SoapMethodSpecification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapMethodSpecification.Format">
            <summary>
            Format property class of SoapMethodSpecification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapMethodSpecification.WebMethodAlias">
            <summary>
            WebMethodAlias property class of SoapMethodSpecification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapMethodSpecification.WebMethodNamespace">
            <summary>
            WebMethodNamespace property class of SoapMethodSpecification
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SoapMethodSpecification.RelatedMethod">
            <summary>
            RelatedMethod relationship class of SoapMethodSpecification
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SpatialIndex">
            <summary>
            Model schema container class for SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.TypeClass">
            <summary>
            Type class for SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.AllowPageLocks">
            <summary>
            AllowPageLocks property class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.AllowRowLocks">
            <summary>
            AllowRowLocks property class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.IgnoreDuplicateKey">
            <summary>
            IgnoreDuplicateKey property class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.RecomputeStatistics">
            <summary>
            RecomputeStatistics property class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.GridLevel1Density">
            <summary>
            GridLevel1Density property class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.GridLevel2Density">
            <summary>
            GridLevel2Density property class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.GridLevel3Density">
            <summary>
            GridLevel3Density property class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.GridLevel4Density">
            <summary>
            GridLevel4Density property class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.Disabled">
            <summary>
            Disabled property class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.WithPadIndex">
            <summary>
            WithPadIndex property class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.CellsPerObject">
            <summary>
            CellsPerObject property class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.DataCompression">
            <summary>
            DataCompression property class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.FillFactor">
            <summary>
            FillFactor property class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.Tessellation">
            <summary>
            Tessellation property class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.XMax">
            <summary>
            XMax property class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.XMin">
            <summary>
            XMin property class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.YMax">
            <summary>
            YMax property class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.YMin">
            <summary>
            YMin property class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.Column">
            <summary>
            Column relationship class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.Filegroup">
            <summary>
            Filegroup relationship class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.IndexedObject">
            <summary>
            IndexedObject relationship class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.PartitionColumn">
            <summary>
            PartitionColumn relationship class of SpatialIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SpatialIndex.PartitionScheme">
            <summary>
            PartitionScheme relationship class of SpatialIndex
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Statistics">
            <summary>
            Model schema container class for Statistics
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Statistics.TypeClass">
            <summary>
            Type class for Statistics
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Statistics.StatsStream">
            <summary>
            StatsStream property class of Statistics
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Statistics.FilterPredicate">
            <summary>
            FilterPredicate property class of Statistics
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Statistics.Incremental">
            <summary>
            Incremental property class of Statistics
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Statistics.NoRecompute">
            <summary>
            NoRecompute property class of Statistics
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Statistics.SampleSize">
            <summary>
            SampleSize property class of Statistics
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Statistics.SamplingStyle">
            <summary>
            SamplingStyle property class of Statistics
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Statistics.OnObject">
            <summary>
            OnObject relationship class of Statistics
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Statistics.Columns">
            <summary>
            Columns relationship class of Statistics
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Statistics.ExpressionDependencies">
            <summary>
            ExpressionDependencies relationship class of Statistics
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Parameter">
            <summary>
            Model schema container class for Parameter
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Parameter.TypeClass">
            <summary>
            Type class for Parameter
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Parameter.DefaultExpression">
            <summary>
            DefaultExpression property class of Parameter
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Parameter.ReadOnly">
            <summary>
            ReadOnly property class of Parameter
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Parameter.Varying">
            <summary>
            Varying property class of Parameter
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Parameter.Scale">
            <summary>
            Scale property class of Parameter
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Parameter.Precision">
            <summary>
            Precision property class of Parameter
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Parameter.Length">
            <summary>
            Length property class of Parameter
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Parameter.IsMax">
            <summary>
            IsMax property class of Parameter
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Parameter.XmlStyle">
            <summary>
            XmlStyle property class of Parameter
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Parameter.IsNullable">
            <summary>
            IsNullable property class of Parameter
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Parameter.IsOutput">
            <summary>
            IsOutput property class of Parameter
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Parameter.XmlSchemaCollection">
            <summary>
            XmlSchemaCollection relationship class of Parameter
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Parameter.DataType">
            <summary>
            DataType relationship class of Parameter
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SymmetricKey">
            <summary>
            Model schema container class for SymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SymmetricKey.TypeClass">
            <summary>
            Type class for SymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SymmetricKey.Algorithm">
            <summary>
            Algorithm property class of SymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SymmetricKey.CreationDisposition">
            <summary>
            CreationDisposition property class of SymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SymmetricKey.IdentityValue">
            <summary>
            IdentityValue property class of SymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SymmetricKey.KeySource">
            <summary>
            KeySource property class of SymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SymmetricKey.ProviderKeyName">
            <summary>
            ProviderKeyName property class of SymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SymmetricKey.AsymmetricKeys">
            <summary>
            AsymmetricKeys relationship class of SymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SymmetricKey.Certificates">
            <summary>
            Certificates relationship class of SymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SymmetricKey.Passwords">
            <summary>
            Passwords relationship class of SymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SymmetricKey.SymmetricKeys">
            <summary>
            SymmetricKeys relationship class of SymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SymmetricKey.Authorizer">
            <summary>
            Authorizer relationship class of SymmetricKey
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SymmetricKey.Provider">
            <summary>
            Provider relationship class of SymmetricKey
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SymmetricKeyPassword">
            <summary>
            Model schema container class for SymmetricKeyPassword
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SymmetricKeyPassword.TypeClass">
            <summary>
            Type class for SymmetricKeyPassword
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SymmetricKeyPassword.Password">
            <summary>
            Password property class of SymmetricKeyPassword
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Synonym">
            <summary>
            Model schema container class for Synonym
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Synonym.TypeClass">
            <summary>
            Type class for Synonym
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Synonym.ForObjectName">
            <summary>
            ForObjectName property class of Synonym
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Synonym.ForObject">
            <summary>
            ForObject relationship class of Synonym
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Synonym.Schema">
            <summary>
            Schema relationship class of Synonym
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.Table">
            <summary>
            Model schema container class for Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.TypeClass">
            <summary>
            Type class for Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.AnsiNullsOn">
            <summary>
            AnsiNullsOn property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.ChangeDataCaptureEnabled">
            <summary>
            ChangeDataCaptureEnabled property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.ChangeTrackingEnabled">
            <summary>
            ChangeTrackingEnabled property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.FileStreamNull">
            <summary>
            FileStreamNull property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.LargeValueTypesOutOfRow">
            <summary>
            LargeValueTypesOutOfRow property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.QuotedIdentifierOn">
            <summary>
            QuotedIdentifierOn property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.TableLockOnBulkLoad">
            <summary>
            TableLockOnBulkLoad property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.TrackColumnsUpdated">
            <summary>
            TrackColumnsUpdated property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.VardecimalStorageFormatEnabled">
            <summary>
            VardecimalStorageFormatEnabled property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.MemoryOptimized">
            <summary>
            MemoryOptimized property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.RowCount">
            <summary>
            RowCount property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.DataSize">
            <summary>
            DataSize property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.IndexSize">
            <summary>
            IndexSize property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.DataPages">
            <summary>
            DataPages property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.UsedPages">
            <summary>
            UsedPages property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.Durability">
            <summary>
            Durability property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.IsAutoGeneratedHistoryTable">
            <summary>
            IsAutoGeneratedHistoryTable property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.IsEdge">
            <summary>
            IsEdge property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.IsNode">
            <summary>
            IsNode property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.IsReplicated">
            <summary>
            IsReplicated property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.LockEscalation">
            <summary>
            LockEscalation property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.RemoteDataEnabled">
            <summary>
            RemoteDataEnabled property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.RetentionUnit">
            <summary>
            RetentionUnit property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.RetentionValue">
            <summary>
            RetentionValue property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.TextInRowSize">
            <summary>
            TextInRowSize property class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.Columns">
            <summary>
            Columns relationship class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.DataCompressionOptions">
            <summary>
            DataCompressionOptions relationship class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.Filegroup">
            <summary>
            Filegroup relationship class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.FilegroupForTextImage">
            <summary>
            FilegroupForTextImage relationship class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.FileStreamFilegroup">
            <summary>
            FileStreamFilegroup relationship class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.FileStreamPartitionScheme">
            <summary>
            FileStreamPartitionScheme relationship class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.PartitionColumn">
            <summary>
            PartitionColumn relationship class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.PartitionScheme">
            <summary>
            PartitionScheme relationship class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.Schema">
            <summary>
            Schema relationship class of Table
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.Table.TemporalSystemVersioningHistoryTable">
            <summary>
            TemporalSystemVersioningHistoryTable relationship class of Table
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.FileTable">
            <summary>
            Model schema container class for FileTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FileTable.TypeClass">
            <summary>
            Type class for FileTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FileTable.AnsiNullsOn">
            <summary>
            AnsiNullsOn property class of FileTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FileTable.FileStreamNull">
            <summary>
            FileStreamNull property class of FileTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FileTable.QuotedIdentifierOn">
            <summary>
            QuotedIdentifierOn property class of FileTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FileTable.TableLockOnBulkLoad">
            <summary>
            TableLockOnBulkLoad property class of FileTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FileTable.FileTableNamespaceEnabled">
            <summary>
            FileTableNamespaceEnabled property class of FileTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FileTable.FileTableCollateFilename">
            <summary>
            FileTableCollateFilename property class of FileTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FileTable.FileTableDirectory">
            <summary>
            FileTableDirectory property class of FileTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FileTable.LockEscalation">
            <summary>
            LockEscalation property class of FileTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FileTable.Columns">
            <summary>
            Columns relationship class of FileTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FileTable.DataCompressionOptions">
            <summary>
            DataCompressionOptions relationship class of FileTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FileTable.Filegroup">
            <summary>
            Filegroup relationship class of FileTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FileTable.FileStreamFilegroup">
            <summary>
            FileStreamFilegroup relationship class of FileTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FileTable.FileStreamPartitionScheme">
            <summary>
            FileStreamPartitionScheme relationship class of FileTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FileTable.PartitionColumn">
            <summary>
            PartitionColumn relationship class of FileTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FileTable.PartitionScheme">
            <summary>
            PartitionScheme relationship class of FileTable
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.FileTable.Schema">
            <summary>
            Schema relationship class of FileTable
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.TableType">
            <summary>
            Model schema container class for TableType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableType.TypeClass">
            <summary>
            Type class for TableType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableType.MemoryOptimized">
            <summary>
            MemoryOptimized property class of TableType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableType.Columns">
            <summary>
            Columns relationship class of TableType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableType.Constraints">
            <summary>
            Constraints relationship class of TableType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableType.Indexes">
            <summary>
            Indexes relationship class of TableType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableType.Schema">
            <summary>
            Schema relationship class of TableType
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.TableTypeCheckConstraint">
            <summary>
            Model schema container class for TableTypeCheckConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeCheckConstraint.TypeClass">
            <summary>
            Type class for TableTypeCheckConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeCheckConstraint.Expression">
            <summary>
            Expression property class of TableTypeCheckConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeCheckConstraint.ExpressionDependencies">
            <summary>
            ExpressionDependencies relationship class of TableTypeCheckConstraint
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.TableTypeColumn">
            <summary>
            Model schema container class for TableTypeColumn
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeColumn.TypeClass">
            <summary>
            Type class for TableTypeColumn
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeColumn.TableTypeColumnType">
            <summary>
            TableTypeColumnType metadata class of TableTypeColumn
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeColumn.Collation">
            <summary>
            Collation property class of TableTypeColumn
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeColumn.IdentityIncrement">
            <summary>
            IdentityIncrement property class of TableTypeColumn
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeColumn.IdentitySeed">
            <summary>
            IdentitySeed property class of TableTypeColumn
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeColumn.IsIdentity">
            <summary>
            IsIdentity property class of TableTypeColumn
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeColumn.Nullable">
            <summary>
            Nullable property class of TableTypeColumn
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeColumn.IsRowGuidCol">
            <summary>
            IsRowGuidCol property class of TableTypeColumn
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeColumn.Expression">
            <summary>
            Expression property class of TableTypeColumn
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeColumn.Persisted">
            <summary>
            Persisted property class of TableTypeColumn
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeColumn.PersistedNullable">
            <summary>
            PersistedNullable property class of TableTypeColumn
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeColumn.Scale">
            <summary>
            Scale property class of TableTypeColumn
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeColumn.Precision">
            <summary>
            Precision property class of TableTypeColumn
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeColumn.Length">
            <summary>
            Length property class of TableTypeColumn
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeColumn.IsMax">
            <summary>
            IsMax property class of TableTypeColumn
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeColumn.XmlStyle">
            <summary>
            XmlStyle property class of TableTypeColumn
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeColumn.ExpressionDependencies">
            <summary>
            ExpressionDependencies relationship class of TableTypeColumn
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeColumn.XmlSchemaCollection">
            <summary>
            XmlSchemaCollection relationship class of TableTypeColumn
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeColumn.DataType">
            <summary>
            DataType relationship class of TableTypeColumn
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.TableTypeDefaultConstraint">
            <summary>
            Model schema container class for TableTypeDefaultConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeDefaultConstraint.TypeClass">
            <summary>
            Type class for TableTypeDefaultConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeDefaultConstraint.Expression">
            <summary>
            Expression property class of TableTypeDefaultConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeDefaultConstraint.TargetColumn">
            <summary>
            TargetColumn relationship class of TableTypeDefaultConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeDefaultConstraint.ExpressionDependencies">
            <summary>
            ExpressionDependencies relationship class of TableTypeDefaultConstraint
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.TableTypeIndex">
            <summary>
            Model schema container class for TableTypeIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeIndex.TypeClass">
            <summary>
            Type class for TableTypeIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeIndex.Hash">
            <summary>
            Hash property class of TableTypeIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeIndex.BucketCount">
            <summary>
            BucketCount property class of TableTypeIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeIndex.IsDisabled">
            <summary>
            IsDisabled property class of TableTypeIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeIndex.IsUnique">
            <summary>
            IsUnique property class of TableTypeIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeIndex.Columns">
            <summary>
            Columns relationship class of TableTypeIndex
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.TableTypePrimaryKeyConstraint">
            <summary>
            Model schema container class for TableTypePrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypePrimaryKeyConstraint.TypeClass">
            <summary>
            Type class for TableTypePrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypePrimaryKeyConstraint.IgnoreDuplicateKey">
            <summary>
            IgnoreDuplicateKey property class of TableTypePrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypePrimaryKeyConstraint.Clustered">
            <summary>
            Clustered property class of TableTypePrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypePrimaryKeyConstraint.Hash">
            <summary>
            Hash property class of TableTypePrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypePrimaryKeyConstraint.BucketCount">
            <summary>
            BucketCount property class of TableTypePrimaryKeyConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypePrimaryKeyConstraint.Columns">
            <summary>
            Columns relationship class of TableTypePrimaryKeyConstraint
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.TableTypePrimaryKeyConstraint.ColumnsRelationship">
            <summary>
            Model schema container class for ColumnsRelationship
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypePrimaryKeyConstraint.ColumnsRelationship.RelationshipClass">
            <summary>
            Relationship class for ColumnsRelationship
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypePrimaryKeyConstraint.ColumnsRelationship.Ascending">
            <summary>
            Ascending property class of ColumnsRelationship
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.TableTypeUniqueConstraint">
            <summary>
            Model schema container class for TableTypeUniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeUniqueConstraint.TypeClass">
            <summary>
            Type class for TableTypeUniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeUniqueConstraint.IgnoreDuplicateKey">
            <summary>
            IgnoreDuplicateKey property class of TableTypeUniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeUniqueConstraint.Clustered">
            <summary>
            Clustered property class of TableTypeUniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeUniqueConstraint.Hash">
            <summary>
            Hash property class of TableTypeUniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeUniqueConstraint.BucketCount">
            <summary>
            BucketCount property class of TableTypeUniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeUniqueConstraint.Columns">
            <summary>
            Columns relationship class of TableTypeUniqueConstraint
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.TableTypeUniqueConstraint.ColumnsRelationship">
            <summary>
            Model schema container class for ColumnsRelationship
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeUniqueConstraint.ColumnsRelationship.RelationshipClass">
            <summary>
            Relationship class for ColumnsRelationship
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TableTypeUniqueConstraint.ColumnsRelationship.Ascending">
            <summary>
            Ascending property class of ColumnsRelationship
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.TcpProtocolSpecifier">
            <summary>
            Model schema container class for TcpProtocolSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TcpProtocolSpecifier.TypeClass">
            <summary>
            Type class for TcpProtocolSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TcpProtocolSpecifier.ListeningOnAllIPs">
            <summary>
            ListeningOnAllIPs property class of TcpProtocolSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TcpProtocolSpecifier.ListenerIPv4">
            <summary>
            ListenerIPv4 property class of TcpProtocolSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TcpProtocolSpecifier.ListenerIPv6">
            <summary>
            ListenerIPv6 property class of TcpProtocolSpecifier
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TcpProtocolSpecifier.ListenerPort">
            <summary>
            ListenerPort property class of TcpProtocolSpecifier
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.UniqueConstraint">
            <summary>
            Model schema container class for UniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.TypeClass">
            <summary>
            Type class for UniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.AllowPageLocks">
            <summary>
            AllowPageLocks property class of UniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.AllowRowLocks">
            <summary>
            AllowRowLocks property class of UniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.IgnoreDuplicateKey">
            <summary>
            IgnoreDuplicateKey property class of UniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.RecomputeStatistics">
            <summary>
            RecomputeStatistics property class of UniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.Clustered">
            <summary>
            Clustered property class of UniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.Disabled">
            <summary>
            Disabled property class of UniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.FileStreamNull">
            <summary>
            FileStreamNull property class of UniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.WithPadIndex">
            <summary>
            WithPadIndex property class of UniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.Hash">
            <summary>
            Hash property class of UniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.BucketCount">
            <summary>
            BucketCount property class of UniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.FillFactor">
            <summary>
            FillFactor property class of UniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.Host">
            <summary>
            Host relationship class of UniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.Columns">
            <summary>
            Columns relationship class of UniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.DataCompressionOptions">
            <summary>
            DataCompressionOptions relationship class of UniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.Filegroup">
            <summary>
            Filegroup relationship class of UniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.FileStreamFilegroup">
            <summary>
            FileStreamFilegroup relationship class of UniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.FileStreamPartitionScheme">
            <summary>
            FileStreamPartitionScheme relationship class of UniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.PartitionColumn">
            <summary>
            PartitionColumn relationship class of UniqueConstraint
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.PartitionScheme">
            <summary>
            PartitionScheme relationship class of UniqueConstraint
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.UniqueConstraint.ColumnsRelationship">
            <summary>
            Model schema container class for ColumnsRelationship
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.ColumnsRelationship.RelationshipClass">
            <summary>
            Relationship class for ColumnsRelationship
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UniqueConstraint.ColumnsRelationship.Ascending">
            <summary>
            Ascending property class of ColumnsRelationship
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.User">
            <summary>
            Model schema container class for User
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.User.TypeClass">
            <summary>
            Type class for User
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.User.WithoutLogin">
            <summary>
            WithoutLogin property class of User
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.User.AuthenticationType">
            <summary>
            AuthenticationType property class of User
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.User.DefaultLanguage">
            <summary>
            DefaultLanguage property class of User
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.User.Password">
            <summary>
            Password property class of User
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.User.Sid">
            <summary>
            Sid property class of User
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.User.UserType">
            <summary>
            UserType property class of User
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.User.AsymmetricKey">
            <summary>
            AsymmetricKey relationship class of User
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.User.Certificate">
            <summary>
            Certificate relationship class of User
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.User.DefaultSchema">
            <summary>
            DefaultSchema relationship class of User
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.User.Login">
            <summary>
            Login relationship class of User
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.UserDefinedServerRole">
            <summary>
            Model schema container class for UserDefinedServerRole
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UserDefinedServerRole.TypeClass">
            <summary>
            Type class for UserDefinedServerRole
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UserDefinedServerRole.Authorizer">
            <summary>
            Authorizer relationship class of UserDefinedServerRole
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.UserDefinedType">
            <summary>
            Model schema container class for UserDefinedType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UserDefinedType.TypeClass">
            <summary>
            Type class for UserDefinedType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UserDefinedType.ByteOrdered">
            <summary>
            ByteOrdered property class of UserDefinedType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UserDefinedType.FixedLength">
            <summary>
            FixedLength property class of UserDefinedType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UserDefinedType.ClassName">
            <summary>
            ClassName property class of UserDefinedType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UserDefinedType.Format">
            <summary>
            Format property class of UserDefinedType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UserDefinedType.MaxByteSize">
            <summary>
            MaxByteSize property class of UserDefinedType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UserDefinedType.ValidationMethodName">
            <summary>
            ValidationMethodName property class of UserDefinedType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UserDefinedType.Assembly">
            <summary>
            Assembly relationship class of UserDefinedType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UserDefinedType.Methods">
            <summary>
            Methods relationship class of UserDefinedType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UserDefinedType.Properties">
            <summary>
            Properties relationship class of UserDefinedType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.UserDefinedType.Schema">
            <summary>
            Schema relationship class of UserDefinedType
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.View">
            <summary>
            Model schema container class for View
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.View.TypeClass">
            <summary>
            Type class for View
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.View.AnsiNullsOn">
            <summary>
            AnsiNullsOn property class of View
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.View.WithEncryption">
            <summary>
            WithEncryption property class of View
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.View.WithViewMetadata">
            <summary>
            WithViewMetadata property class of View
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.View.QuotedIdentifierOn">
            <summary>
            QuotedIdentifierOn property class of View
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.View.Replicated">
            <summary>
            Replicated property class of View
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.View.WithSchemaBinding">
            <summary>
            WithSchemaBinding property class of View
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.View.WithCheckOption">
            <summary>
            WithCheckOption property class of View
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.View.SelectStatement">
            <summary>
            SelectStatement property class of View
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.View.BodyDependencies">
            <summary>
            BodyDependencies relationship class of View
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.View.Columns">
            <summary>
            Columns relationship class of View
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.View.Schema">
            <summary>
            Schema relationship class of View
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.WorkloadGroup">
            <summary>
            Model schema container class for WorkloadGroup
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.WorkloadGroup.TypeClass">
            <summary>
            Type class for WorkloadGroup
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.WorkloadGroup.GroupMaxRequests">
            <summary>
            GroupMaxRequests property class of WorkloadGroup
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.WorkloadGroup.Importance">
            <summary>
            Importance property class of WorkloadGroup
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.WorkloadGroup.MaxDop">
            <summary>
            MaxDop property class of WorkloadGroup
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.WorkloadGroup.RequestMaxCpuTimeSec">
            <summary>
            RequestMaxCpuTimeSec property class of WorkloadGroup
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.WorkloadGroup.RequestMaxMemoryGrantPercent">
            <summary>
            RequestMaxMemoryGrantPercent property class of WorkloadGroup
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.WorkloadGroup.RequestMemoryGrantTimeoutSec">
            <summary>
            RequestMemoryGrantTimeoutSec property class of WorkloadGroup
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.WorkloadGroup.ResourcePool">
            <summary>
            ResourcePool relationship class of WorkloadGroup
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.XmlIndex">
            <summary>
            Model schema container class for XmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.XmlIndex.TypeClass">
            <summary>
            Type class for XmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.XmlIndex.AllowPageLocks">
            <summary>
            AllowPageLocks property class of XmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.XmlIndex.AllowRowLocks">
            <summary>
            AllowRowLocks property class of XmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.XmlIndex.IgnoreDuplicateKey">
            <summary>
            IgnoreDuplicateKey property class of XmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.XmlIndex.RecomputeStatistics">
            <summary>
            RecomputeStatistics property class of XmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.XmlIndex.Disabled">
            <summary>
            Disabled property class of XmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.XmlIndex.WithPadIndex">
            <summary>
            WithPadIndex property class of XmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.XmlIndex.SecondaryXmlIndexType">
            <summary>
            SecondaryXmlIndexType property class of XmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.XmlIndex.FillFactor">
            <summary>
            FillFactor property class of XmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.XmlIndex.IsPrimary">
            <summary>
            IsPrimary property class of XmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.XmlIndex.PrimaryXmlIndex">
            <summary>
            PrimaryXmlIndex relationship class of XmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.XmlIndex.Column">
            <summary>
            Column relationship class of XmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.XmlIndex.IndexedObject">
            <summary>
            IndexedObject relationship class of XmlIndex
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SelectiveXmlIndex">
            <summary>
            Model schema container class for SelectiveXmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SelectiveXmlIndex.TypeClass">
            <summary>
            Type class for SelectiveXmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SelectiveXmlIndex.Disabled">
            <summary>
            Disabled property class of SelectiveXmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SelectiveXmlIndex.WithPadIndex">
            <summary>
            WithPadIndex property class of SelectiveXmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SelectiveXmlIndex.AllowRowLocks">
            <summary>
            AllowRowLocks property class of SelectiveXmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SelectiveXmlIndex.AllowPageLocks">
            <summary>
            AllowPageLocks property class of SelectiveXmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SelectiveXmlIndex.IgnoreDuplicateKey">
            <summary>
            IgnoreDuplicateKey property class of SelectiveXmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SelectiveXmlIndex.RecomputeStatistics">
            <summary>
            RecomputeStatistics property class of SelectiveXmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SelectiveXmlIndex.FillFactor">
            <summary>
            FillFactor property class of SelectiveXmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SelectiveXmlIndex.IsPrimary">
            <summary>
            IsPrimary property class of SelectiveXmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SelectiveXmlIndex.PrimarySelectiveXmlIndex">
            <summary>
            PrimarySelectiveXmlIndex relationship class of SelectiveXmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SelectiveXmlIndex.PrimaryPromotedPath">
            <summary>
            PrimaryPromotedPath relationship class of SelectiveXmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SelectiveXmlIndex.Column">
            <summary>
            Column relationship class of SelectiveXmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SelectiveXmlIndex.IndexedObject">
            <summary>
            IndexedObject relationship class of SelectiveXmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SelectiveXmlIndex.PromotedPaths">
            <summary>
            PromotedPaths relationship class of SelectiveXmlIndex
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.SelectiveXmlIndex.XmlNamespaces">
            <summary>
            XmlNamespaces relationship class of SelectiveXmlIndex
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.XmlNamespace">
            <summary>
            Model schema container class for XmlNamespace
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.XmlNamespace.TypeClass">
            <summary>
            Type class for XmlNamespace
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.XmlNamespace.NamespaceUri">
            <summary>
            NamespaceUri property class of XmlNamespace
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.XmlNamespace.Prefix">
            <summary>
            Prefix property class of XmlNamespace
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.PromotedNodePathForXQueryType">
            <summary>
            Model schema container class for PromotedNodePathForXQueryType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PromotedNodePathForXQueryType.TypeClass">
            <summary>
            Type class for PromotedNodePathForXQueryType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PromotedNodePathForXQueryType.IsSingleton">
            <summary>
            IsSingleton property class of PromotedNodePathForXQueryType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PromotedNodePathForXQueryType.MaxLength">
            <summary>
            MaxLength property class of PromotedNodePathForXQueryType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PromotedNodePathForXQueryType.NodePath">
            <summary>
            NodePath property class of PromotedNodePathForXQueryType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PromotedNodePathForXQueryType.Type">
            <summary>
            Type property class of PromotedNodePathForXQueryType
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.PromotedNodePathForSqlType">
            <summary>
            Model schema container class for PromotedNodePathForSqlType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PromotedNodePathForSqlType.TypeClass">
            <summary>
            Type class for PromotedNodePathForSqlType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PromotedNodePathForSqlType.Scale">
            <summary>
            Scale property class of PromotedNodePathForSqlType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PromotedNodePathForSqlType.Precision">
            <summary>
            Precision property class of PromotedNodePathForSqlType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PromotedNodePathForSqlType.Length">
            <summary>
            Length property class of PromotedNodePathForSqlType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PromotedNodePathForSqlType.IsMax">
            <summary>
            IsMax property class of PromotedNodePathForSqlType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PromotedNodePathForSqlType.IsSingleton">
            <summary>
            IsSingleton property class of PromotedNodePathForSqlType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PromotedNodePathForSqlType.NodePath">
            <summary>
            NodePath property class of PromotedNodePathForSqlType
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.PromotedNodePathForSqlType.DataType">
            <summary>
            DataType relationship class of PromotedNodePathForSqlType
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.XmlSchemaCollection">
            <summary>
            Model schema container class for XmlSchemaCollection
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.XmlSchemaCollection.TypeClass">
            <summary>
            Type class for XmlSchemaCollection
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.XmlSchemaCollection.Expression">
            <summary>
            Expression property class of XmlSchemaCollection
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.XmlSchemaCollection.Schema">
            <summary>
            Schema relationship class of XmlSchemaCollection
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ModelTypeClass">
            <summary>
             The metadata class for <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>s.
            </summary>
            <remarks>
            <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModelSchema"/> metadata classes provide access to the structure and instance data
            within a <c>TSqlModelSchema</c> instance.
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelTypeClass.Name">
            <summary>
            Type name.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelTypeClass.SupportedPlatforms">
            <summary>
            The <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlPlatforms"/> versions on which this type is supported.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelTypeClass.Properties">
            <summary>
            Properties for the type.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelTypeClass.Relationships">
            <summary>
            Relationships for the type.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ModelTypeClass.Metadata">
            <summary>
            Metadata properties for the type.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ObjectIdentifier">
             <summary>
            
             </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ObjectIdentifier.#ctor(System.String[])">
            <summary>
            Creates a object identifier with a name.
            </summary>
            <param name="parts">The parts of the identifier</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ObjectIdentifier.#ctor(System.Collections.Generic.IList{System.String})">
            <summary>
            Creates a object identifier with a name.
            </summary>
            <param name="parts">The parts of the identifier</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ObjectIdentifier.#ctor(System.Collections.Generic.IEnumerable{System.String})">
            <summary>
            Creates a object identifier with a name.
            </summary>
            <param name="parts">The parts of the identifier</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ObjectIdentifier.#ctor(System.Collections.Generic.IList{System.String},System.Collections.Generic.IList{System.String})">
            <summary>
            Creates a object identifier with a name that includes external parts.
            </summary>
            <param name="externalParts">External reference parts - used in 3 or 4 part references to
            objects in other databases or servers </param>
            <param name="parts">The parts of the identifier</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.ObjectIdentifier.ToString">
            <summary>
             Formats and escapes name parts into a single string
            </summary>
            <returns>escaped name.</returns>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ObjectIdentifier.Parts">
            <summary>
            Gets the parts of the identifier.
            </summary>
            <returns>The parts of the identifier.</returns>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ObjectIdentifier.HasName">
            <summary>
            Does this ObjectIdentifier have any <see cref="P:Microsoft.SqlServer.Dac.Model.ObjectIdentifier.Parts"/>
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ObjectIdentifier.ExternalParts">
            <summary>
            Gets the external reference parts.  Null if the identifier is not external.
            </summary>
            <returns>The external reference parts.</returns>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.ObjectIdentifier.HasExternalParts">
            <summary>
            Does this ObjectIdentifier have any <see cref="P:Microsoft.SqlServer.Dac.Model.ObjectIdentifier.ExternalParts"/>
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.RelationshipType">
            <summary>
            Relationship types.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.RelationshipType.Composing">
            <summary>
            A relationship where the child object cannot be created outside the parent's DDL create statement.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.RelationshipType.Hierarchical">
            <summary>
            A relationship where the child object can be created outside the parent's DDL create statement.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.RelationshipType.Peer">
            <summary>
            A relationship where the related object must be created outside the parent's DDL create statement.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.ScriptPropertyContext">
            <summary>
            Customized Context object for properties of type <see cref="T:Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlScriptProperty"/>.    
            </summary>
            <remarks>
            Returns the value of the script string.
            </remarks>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SimpleModelPropertyContext">
            <summary>
            Default Property context for all properties.
            </summary>
            <remarks>
            Provides default implementation for property access through the public model.
            </remarks>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.SqlSchemaModelCreator.GetCollationToUse(System.String,Microsoft.Data.Tools.Schema.SchemaModel.SqlPlatforms)">
            <summary>
            Internal for test use only
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.SqlServerVersion">
            <summary>
            Specific SQL Server releases.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlServerVersion.Sql90">
             <summary>
            on-premises, version 9.0
             </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlServerVersion.Sql100">
            <summary>
            on-premises, version 10.0
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlServerVersion.SqlAzure">
            <summary>
            Azure
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlServerVersion.Sql110">
            <summary>
            on-premises, version 11.0
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlServerVersion.Sql120">
            <summary>
            on-premises, version 12.0
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlServerVersion.Sql130">
            <summary>
            on-premises, version 13.0
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.SqlServerVersion.Sql140">
            <summary>
            on-premises, version 14.0
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.TSqlModel">
            <summary>
            Represents a model of a SQL Server database schema.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.LoadFromDacpac(System.IO.Stream,Microsoft.SqlServer.Dac.Model.ModelLoadOptions)">
            <summary>
            Loads a model from a <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> or <see cref="T:Microsoft.SqlServer.Dac.BacPackage"/>
            using the specified <paramref name="options"/> to configure what kind of storage to use, and whether to load a script-backed
            model or not.
            </summary>
            <param name="dacpacStream">A stream that contains the serialized dacpac.</param>
            <param name="options">
            The <see cref="T:Microsoft.SqlServer.Dac.Model.ModelLoadOptions"/> defining how the model should be loaded. For models to be analyzed in static code analysis,
            it's recommended that the <see cref="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.LoadAsScriptBackedModel"/> be set to true. This is important since some
            rules may not work as expected unless this is true.
            </param>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If there are problems loading the package from the specified <paramref name="dacpacStream"/>. 
            This may occur if the package does not load correctly or if references required by
            the package are not found using the original path to the reference.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.LoadFromDacpac(System.IO.Stream,Microsoft.SqlServer.Dac.Model.ModelLoadOptions,System.Threading.CancellationToken)">
            <summary>
            Loads a model from a <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> or <see cref="T:Microsoft.SqlServer.Dac.BacPackage"/>
            using the specified <paramref name="options"/> to configure what kind of storage to use, and whether to load a script-backed
            model or not.
            </summary>
            <param name="dacpacStream">A stream that contains the serialized dacpac.</param>
            <param name="options">
            The <see cref="T:Microsoft.SqlServer.Dac.Model.ModelLoadOptions"/> defining how the model should be loaded. For models to be analyzed in static code analysis,
            it's recommended that the <see cref="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.LoadAsScriptBackedModel"/> be set to true. This is important since some
            rules may not work as expected unless this is true.
            </param>
            <param name="cancellationToken">A token used for cancelling model loading.</param>
            <exception cref="T:System.OperationCanceledException">When the load operation is canceled.</exception>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If there are problems loading the package from the specified <paramref name="dacpacStream"/>. 
            This may occur if the package does not load correctly or if references required by
            the package are not found using the original path to the reference.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.LoadFromDacpac(System.String,Microsoft.SqlServer.Dac.Model.ModelLoadOptions,System.Threading.CancellationToken)">
            <summary>
            Loads a model from a <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> or <see cref="T:Microsoft.SqlServer.Dac.BacPackage"/>
            using the specified <paramref name="options"/> to configure what kind of storage to use, and whether to load a script-backed
            model or not.
            </summary>
            <param name="fileName">File path to package.</param> 
            <param name="options">
            The <see cref="T:Microsoft.SqlServer.Dac.Model.ModelLoadOptions"/> defining how the model should be loaded. For models to be analyzed in static code analysis,
            it's recommended that the <see cref="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.LoadAsScriptBackedModel"/> be set to true. This is important since some
            rules may not work as expected unless this is true.
            </param>
            <param name="cancellationToken">A token used for cancelling model loading.</param>
            <exception cref="T:System.OperationCanceledException">When the load operation is canceled.</exception>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If there are problems loading the package from the specified <paramref name="fileName"/>. 
            This may occur if the package does not load correctly or if references required by
            the package are not found in either the same directory as the package, or using the original path
            to the reference.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.LoadFromDacpac(System.String,Microsoft.SqlServer.Dac.Model.ModelLoadOptions)">
            <summary>
            Loads a model from a <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> or <see cref="T:Microsoft.SqlServer.Dac.BacPackage"/>
            using the specified <paramref name="options"/> to configure what kind of storage to use, and whether to load a script-backed
            model or not.
            </summary>
            <param name="fileName">File path to package.</param> 
            <param name="options">
            The <see cref="T:Microsoft.SqlServer.Dac.Model.ModelLoadOptions"/> defining how the model should be loaded. For models to be analyzed in static code analysis,
            it's recommended that the <see cref="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.LoadAsScriptBackedModel"/> be set to true. This is important since some
            rules may not work as expected unless this is true.
            </param>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If there are problems loading the package from the specified <paramref name="fileName"/>. 
            This may occur if the package does not load correctly or if references required by
            the package are not found in either the same directory as the package, or using the original path
            to the reference.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.LoadFromDatabase(System.String,Microsoft.SqlServer.Dac.Model.ModelExtractOptions,System.Nullable{System.Threading.CancellationToken})">
            <summary>
            Loads a model from a database using the specified <paramref name="options"/>.
            </summary>
            <param name="connectionString">A connection string specifying the database and catalog to load.</param>
            <param name="options">
            Optional <see cref="T:Microsoft.SqlServer.Dac.Model.ModelExtractOptions"/> instance used to specify options that affect the behavior of package extraction.
            For models to be analyzed in static code analysis, it's recommended that the 
            <see cref="P:Microsoft.SqlServer.Dac.Model.ModelExtractOptions.LoadAsScriptBackedModel"/> be set to true. This is important since some
            rules may not work as expected unless this is true.</param> 
            <param name="cancellationToken">Optional cancellation token used to cancel a load operation.</param>
            <exception cref="T:System.ArgumentNullException">If connectionString is null.</exception>
            <exception cref="T:System.ArgumentException">If connectionString is not a valid connection string
            or options.Storage is not a valid value of the enumerated type.</exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If there are problems extracting the model from the specified database. 
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.LoadFromDatabaseWithAuthProvider(System.String,Microsoft.SqlServer.Dac.IUniversalAuthProvider,Microsoft.SqlServer.Dac.Model.ModelExtractOptions,System.Nullable{System.Threading.CancellationToken})">
            <summary>
            Loads a model from a database using the specified <paramref name="options"/>.
            </summary>
            <param name="connectionString">A connection string specifying the database and catalog to load.</param>
            <param name="authProvider"> 
            Optional universal authentication provider used to authenticate a <see cref="T:System.Data.SqlClient.SqlConnection"/> when opening a connection.</param>
            <param name="options">
            Optional <see cref="T:Microsoft.SqlServer.Dac.Model.ModelExtractOptions"/> instance used to specify options that affect the behavior of package extraction.
            For models to be analyzed in static code analysis, it's recommended that the 
            <see cref="P:Microsoft.SqlServer.Dac.Model.ModelExtractOptions.LoadAsScriptBackedModel"/> be set to true. This is important since some
            rules may not work as expected unless this is true.</param> 
            <param name="cancellationToken">Optional cancellation token used to cancel a load operation.</param>
            <exception cref="T:System.ArgumentNullException">If connectionString is null.</exception>
            <exception cref="T:System.ArgumentException">If connectionString is not a valid connection string
            or options.Storage is not a valid value of the enumerated type.</exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If there are problems extracting the model from the specified database. 
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.LoadFromDatabase(System.String,System.Security.SecureString,Microsoft.SqlServer.Dac.Model.ModelExtractOptions,System.Nullable{System.Threading.CancellationToken})">
            <summary>
            Loads a model from a database using the specified <paramref name="options"/>.
            </summary>
            <param name="connectionString">A connection string specifying the database and catalog to load.</param>
            <param name="password">This password string used when connecting to the specified database.</param>
            <param name="options">
            Optional <see cref="T:Microsoft.SqlServer.Dac.Model.ModelExtractOptions"/> instance used to specify options that affect the behavior of package extraction.
            For models to be analyzed in static code analysis, it's recommended that the 
            <see cref="P:Microsoft.SqlServer.Dac.Model.ModelExtractOptions.LoadAsScriptBackedModel"/> be set to true. This is important since some
            rules may not work as expected unless this is true.</param> 
            <param name="cancellationToken">Optional cancellation token used to cancel a load operation.</param>
            <exception cref="T:System.ArgumentNullException">If connectionString is null.</exception>
            <exception cref="T:System.ArgumentException">If connectionString is not a valid connection string
            or options.Storage is not a valid value of the enumerated type.</exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If there are problems extracting the model from the specified database. 
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.#ctor(System.String)">
            <summary>
            Loads a model from a <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> or <see cref="T:Microsoft.SqlServer.Dac.BacPackage"/>.
            
            This is equivalent to calling <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.LoadFromDacpac(System.String,Microsoft.SqlServer.Dac.Model.ModelLoadOptions)"/> with default values.
            </summary>
            <param name="fileName">File path to package.</param> 
            <remarks>
            By default DacSchemaModelStorageType.Memory is used for the model storage format.
            The dacpac model will not be script-backed as the <see cref="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.LoadAsScriptBackedModel"/> will be set to false.
            Using <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.LoadFromDacpac(System.String,Microsoft.SqlServer.Dac.Model.ModelLoadOptions)"/> with <see cref="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.LoadAsScriptBackedModel"/>
            set to true is recommended if the model will be used by the <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService"/> for static code analysis.
            </remarks>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If there are problems loading the package from the specified <paramref name="fileName"/>. 
            This may occur if the package does not load correctly or if references required by
            the package are not found in either the same directory as the package, or using the original path
            to the reference.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.#ctor(System.String,Microsoft.SqlServer.Dac.DacSchemaModelStorageType)">
            <summary>
            Loads a model from a <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> or <see cref="T:Microsoft.SqlServer.Dac.BacPackage"/>.
            
            This is equivalent to calling <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.LoadFromDacpac(System.String,Microsoft.SqlServer.Dac.Model.ModelLoadOptions)"/> with default values for
            everything except the <paramref name="modelStorageType"/>.
            </summary>
            <param name="fileName">File path to package.</param>
            <param name="modelStorageType">
            Backing storage type for package instance.
            </param>
            <remarks>
            The dacpac model will not be script-backed as the <see cref="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.LoadAsScriptBackedModel"/> will be set to false.
            Using <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.LoadFromDacpac(System.String,Microsoft.SqlServer.Dac.Model.ModelLoadOptions)"/> with <see cref="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.LoadAsScriptBackedModel"/>
            set to true is recommended if the model will be used by the <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService"/> for static code analysis.
            </remarks>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If there are problems loading the package from the specified <paramref name="fileName"/>. 
            This may occur if the package does not load correctly or if references required by
            the package are not found in either the same directory as the package, or using the original path
            to the reference.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.#ctor(System.String,Microsoft.SqlServer.Dac.DacSchemaModelStorageType,System.Threading.CancellationToken)">
            <summary>
            Loads a model from a <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> or <see cref="T:Microsoft.SqlServer.Dac.BacPackage"/>.
            
            This is equivalent to calling <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.LoadFromDacpac(System.String,Microsoft.SqlServer.Dac.Model.ModelLoadOptions)"/> with default values for
            everything except the <paramref name="modelStorageType"/>.
            </summary>
            <param name="fileName">File path to package.</param>
            <param name="modelStorageType">
            Backing storage type for package instance.
            </param>
            <param name="cancellationToken">A token used for cancelling model loading.</param>
            <remarks>
            The dacpac model will not be script-backed as the <see cref="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.LoadAsScriptBackedModel"/> will be set to false.
            Using <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.LoadFromDacpac(System.String,Microsoft.SqlServer.Dac.Model.ModelLoadOptions)"/> with <see cref="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.LoadAsScriptBackedModel"/>
            set to true is recommended if the model will be used by the <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService"/> for static code analysis.
            </remarks>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If there are problems loading the package from the specified <paramref name="fileName"/>. 
            This may occur if the package does not load correctly or if references required by
            the package are not found in either the same directory as the package, or using the original path
            to the reference.
            </exception>
            <exception cref="T:System.OperationCanceledException">When the load operation is canceled.</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.#ctor(Microsoft.SqlServer.Dac.Model.SqlServerVersion,Microsoft.SqlServer.Dac.Model.TSqlModelOptions)">
            <summary>
            Creates an empty model that targets a specific <see cref="T:Microsoft.SqlServer.Dac.Model.SqlServerVersion"/>
            </summary>
            <param name="modelTargetVersion">The version of SQL Server to target</param>
            <param name="modelCreationOptions">Options defining model properties, 
            including the collation and how to store the model (in memory or file backed)
            </param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.GetObjectService">
            <summary>
            Internal method - for testing and utility purposes only
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.GetObject(Microsoft.SqlServer.Dac.Model.ModelTypeClass,Microsoft.SqlServer.Dac.Model.ObjectIdentifier,Microsoft.SqlServer.Dac.Model.DacQueryScopes)">
            <summary>
            Returns <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>s  of the specified <paramref name="objectType" value="type"/> and <paramref name="id" value="identity"/>.
            Only top level <see cref="T:Microsoft.SqlServer.Dac.Model.ModelTypeClass"/> types are supported by this method - the <paramref name="objectType" value="type"/> parameter
            must be in the types returned from the <see cref="P:Microsoft.SqlServer.Dac.Model.TSqlModelSchema.TopLevelTypes"/> method or the call will fail.
            </summary>
            <param name="objectType">Type filter. Must be in the list of <see cref="T:Microsoft.SqlServer.Dac.Model.ModelTypeClass"/> types returned from
            the <see cref="P:Microsoft.SqlServer.Dac.Model.TSqlModelSchema.TopLevelTypes"/> method or the call will fail. </param>
            <param name="id">Unique identity of <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> to return.</param>
            <param name="queryScopes">Scope filter for queried objects.</param>
            <returns>Single TSqlObject or null.</returns>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If the supplied <paramref name="objectType"/> and <paramref name="id"/> result in multiple <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>s,
            or if the <paramref name="objectType"/> is not a top level type.
            </exception>
            <exception cref="T:System.ArgumentNullException">
            If the supplied <paramref name="id"/> is null.
            </exception>
            <exception cref="T:System.ArgumentNullException">
            If the supplied <paramref name="objectType"/> is null.
            </exception>
            <exception cref="T:System.Runtime.Remoting.RemotingException">
            If communication with the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObjectService"/> fails.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.GetObjects(Microsoft.SqlServer.Dac.Model.DacQueryScopes,Microsoft.SqlServer.Dac.Model.ModelTypeClass[])">
            <summary>
            Returns all <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>s matching the list of <paramref name="typeFilters"/>.
            Only top level <see cref="T:Microsoft.SqlServer.Dac.Model.ModelTypeClass"/> types are supported by this method - all types in the
            <paramref name="typeFilters" value="type"/> parameter
            must be present in the <see cref="P:Microsoft.SqlServer.Dac.Model.TSqlModelSchema.TopLevelTypes"/> or the call will fail.
            </summary>
            <param name="queryScopes">Scope filter for queried objects. Must be in the list of <see cref="T:Microsoft.SqlServer.Dac.Model.ModelTypeClass"/> types returned from
            the <see cref="P:Microsoft.SqlServer.Dac.Model.TSqlModelSchema.TopLevelTypes"/> method or the call will fail.</param>
            <param name="typeFilters">List of <see cref="T:Microsoft.SqlServer.Dac.Model.ModelTypeClass"/>s to return.</param>
            <returns>All <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>s that match <paramref name="typeFilters"/>.</returns>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If any of the types in the <paramref name="typeFilters"/> parameter are not a top level type.
            </exception>
            <remarks>
            If no <paramref name="typeFilters"/> are supplied all <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>s are returned.
            </remarks>
            <exception cref="T:System.Runtime.Remoting.RemotingException">
            If communication with the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObjectService"/> fails.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.GetObjects(Microsoft.SqlServer.Dac.Model.ModelTypeClass,Microsoft.SqlServer.Dac.Model.ObjectIdentifier,Microsoft.SqlServer.Dac.Model.DacQueryScopes)">
            <summary>
            Returns all <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>s that match the <see cref="T:Microsoft.SqlServer.Dac.Model.ModelTypeClass"/> and <see cref="T:Microsoft.SqlServer.Dac.Model.ObjectIdentifier"/>.
            Only top level <see cref="T:Microsoft.SqlServer.Dac.Model.ModelTypeClass"/> types are supported by this method - the <paramref name="objectType" value="type"/> parameter
            must be in the types returned from the <see cref="P:Microsoft.SqlServer.Dac.Model.TSqlModelSchema.TopLevelTypes"/> method or the call will fail.
            </summary>
            <param name="objectType">Type Filter. Must be in the list of <see cref="T:Microsoft.SqlServer.Dac.Model.ModelTypeClass"/> types returned from
            the <see cref="P:Microsoft.SqlServer.Dac.Model.TSqlModelSchema.TopLevelTypes"/> method or the call will fail.</param>
            <param name="id">Identity of the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>s to return.</param>
            <param name="queryScopes">Scope filter for queried objects.</param>
            <returns>All <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>s that match the <paramref name="objectType"/> and <paramref name="id"/>.</returns>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If the <paramref name="objectType"/> is not a top level type.
            </exception>
            <exception cref="T:System.ArgumentNullException">
            If the supplied <paramref name="id"/> is null.
            </exception>
            <exception cref="T:System.ArgumentNullException">
            If the supplied <paramref name="objectType"/> is null.
            </exception>
            <exception cref="T:System.Runtime.Remoting.RemotingException">
            If communication with the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObjectService"/> fails.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.GetObjects(System.String,Microsoft.SqlServer.Dac.Model.ModelTypeClass[])">
            <summary>
            Returns all <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>s in a given <paramref name="sourceName"/> document filtered by <see cref="T:Microsoft.SqlServer.Dac.Model.ModelTypeClass"/>s
            specified by the <paramref name="typeFilters"/> parameter.
            </summary>
            <param name="sourceName">Name of the source document</param>
            <param name="typeFilters">Array of ModelTypeClass that the resulting <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> should be filtered on.</param>
            <returns>List of <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>s</returns>
            <remarks>
            If no <paramref name="typeFilters"/> are supplied all <see cref="T:Microsoft.SqlServer.Dac.Model.ModelTypeClass"/>s are returned.
            </remarks>
            <exception cref="T:System.Runtime.Remoting.RemotingException">
            If communication with the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObjectService"/> fails.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.GetModelErrors">
            <summary>
            Returns all <see cref="T:Microsoft.SqlServer.Dac.Model.DacModelError"/>s that are present in the model.
            </summary>
            <remarks>
            Load the model with <see cref="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.ThrowOnModelErrors"/> set to false to retrieve model errors.
            Refer <see cref="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.ThrowOnModelErrors"/> for more information on model errors.
            </remarks>
            <exception cref="T:System.Runtime.Remoting.RemotingException">
            If communication with the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObjectService"/> fails.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.AddObjects(System.String)">
            <summary>
            Adds objects to the model based on the contents of a TSql Script string. 
            The script should consist of valid TSql DDL statements.
            
            Objects added using this method cannot be updated or deleted at a later point 
            as update/delete requires a script name to be specified when adding the objects. If this
            is a requirement use the <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.AddOrUpdateObjects(System.String,System.String,Microsoft.SqlServer.Dac.Model.TSqlObjectOptions)"/> 
            method instead.
            </summary>
            <param name="inputScript">Script containing TSql DDL statements</param>
            <exception cref="T:System.ArgumentNullException">
            If the supplied <paramref name="inputScript"/> is null.
            </exception>
            <exception cref="T:System.Runtime.Remoting.RemotingException">
            If communication with the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObjectService"/> fails.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.AddObjects(System.String,Microsoft.SqlServer.Dac.Model.TSqlObjectOptions)">
            <summary>
            Add Objects to the model based on the contents of a TSql Script string, 
            plus additional metadata defined by a <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObjectOptions"/> object
            The script should consist of valid TSql DDL statements. 
            
            Objects added using this method cannot be updated or deleted at a later point 
            as update/delete requires a script name to be specified when adding the objects. If this
            is a requirement use the <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.AddOrUpdateObjects(System.String,System.String,Microsoft.SqlServer.Dac.Model.TSqlObjectOptions)"/> 
            method instead.
            </summary>
            <param name="inputScript">Script containing TSql DDL statements</param>
            <param name="options">Options defining how to interpret the script</param>
            <exception cref="T:System.ArgumentNullException">
            If the supplied <paramref name="inputScript"/> is null.
            </exception>
            <exception cref="T:System.Runtime.Remoting.RemotingException">
            If communication with the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObjectService"/> fails.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.AddObjects(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlScript)">
            <summary>
            Adds objects to the model based on the contents of a <see cref="T:Microsoft.SqlServer.TransactSql.ScriptDom.TSqlScript"/> object. 
            The script should be valid TSql with no parse errors. 
            
            Objects added using this method cannot be updated or deleted at a later point 
            as update/delete requires a script name to be specified when adding the objects. If this
            is a requirement use the <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.AddOrUpdateObjects(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlScript,System.String,Microsoft.SqlServer.Dac.Model.TSqlObjectOptions)"/> 
            method instead.
            </summary>
            <param name="inputScript">The <see cref="T:Microsoft.SqlServer.TransactSql.ScriptDom.TSqlScript"/> to add</param>
            <exception cref="T:System.ArgumentNullException">
            If the supplied <paramref name="inputScript"/> is null.
            </exception>
            <exception cref="T:System.Runtime.Remoting.RemotingException">
            If communication with the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObjectService"/> fails.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.AddObjects(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlScript,Microsoft.SqlServer.Dac.Model.TSqlObjectOptions)">
            <summary>
            Add Objects to the model based on the contents of a <see cref="T:Microsoft.SqlServer.TransactSql.ScriptDom.TSqlScript"/> object, 
            plus additional metadata defined by a <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObjectOptions"/> object
            The script should be valid TSql with no parse errors. 
            
            Objects added using this method cannot be updated or deleted at a later point 
            as update/delete requires a script name to be specified when adding the objects. If this
            is a requirement use the <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.AddOrUpdateObjects(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlScript,System.String,Microsoft.SqlServer.Dac.Model.TSqlObjectOptions)"/> 
            method instead.
            </summary>
            <param name="inputScript">The <see cref="T:Microsoft.SqlServer.TransactSql.ScriptDom.TSqlScript"/> to add</param>
            <param name="options">Options defining how to interpret the script</param>
            <exception cref="T:System.ArgumentNullException">
            If the supplied <paramref name="inputScript"/> is null.
            </exception>
            <exception cref="T:System.Runtime.Remoting.RemotingException">
            If communication with the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObjectService"/> fails.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.AddOrUpdateObjects(System.String,System.String,Microsoft.SqlServer.Dac.Model.TSqlObjectOptions)">
            <summary>
            Adds or updates the objects defined for a specified <paramref name="sourceName"/> with the
            objects defined in the <paramref name="inputScript"/>. If any objects were previously added
            with the same <paramref name="sourceName"/> these will be completely replaced
            The object definitions are based on the contents of a TSql Script string 
            plus additional metadata defined by a <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObjectOptions"/> object
            The script should consist of valid TSql DDL statements. 
            </summary>
            <param name="inputScript">Script containing TSql DDL statements</param>
            <param name="sourceName">
            A name to identify the <paramref name="inputScript"/>, for example a 
            fileName such as "MyTable.sql" or simply an alias like "dbo.Table". 
            Scripts are cached and TSqlObjects are linked to the source name.
            Any future Update/Delete operations will remove all existing objects
            with the same script name and replace them with the new objects.
            </param>
            <param name="options">Options defining how to interpret the script</param>
            <exception cref="T:System.ArgumentNullException">
            If the supplied <paramref name="inputScript"/> is null.
            </exception>
            <exception cref="T:System.ArgumentException">
            If the supplied <paramref name="sourceName"/> is null or whitespace, or if it ends
            in ".xsd". 
            Note: source names ending in ".xsd" are currently not supported. These relate 
            to Xml Schema Collections and adding of these is currently not supported in the public API.
            </exception>
            <exception cref="T:System.Runtime.Remoting.RemotingException">
            If communication with the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObjectService"/> fails.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.AddOrUpdateObjects(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlScript,System.String,Microsoft.SqlServer.Dac.Model.TSqlObjectOptions)">
            <summary>
            Adds or updates the objects defined for a specified <paramref name="sourceName"/> with the
            objects defined in the <paramref name="inputScript"/>. If any objects were previously added
            with the same <paramref name="sourceName"/> these will be completely replaced
            The object definitions are based on the contents of a <see cref="T:Microsoft.SqlServer.TransactSql.ScriptDom.TSqlScript"/> object
            plus additional metadata defined by a <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObjectOptions"/> object
            The script should consist of valid TSql DDL statements. 
            </summary>
            <param name="inputScript">Script containing TSql DDL statements</param>
            <param name="sourceName">
            A name to identify the <paramref name="inputScript"/>, for example a 
            fileName such as "MyTable.sql" or simply an alias like "dbo.Table". 
            Scripts are cached and TSqlObjects are linked to the source name.
            Any future Update/Delete operations will remove all existing objects
            with the same script name and replace them with the new objects.
            </param>
            <param name="options">Options defining how to interpret the script</param>
            <exception cref="T:System.ArgumentNullException">
            If the supplied <paramref name="inputScript"/> is null.
            </exception>
            <exception cref="T:System.ArgumentException">
            If the supplied <paramref name="sourceName"/> is null or whitespace, or if it ends
            in ".xsd". 
            Note: source names ending in ".xsd" are currently not supported. These relate 
            to Xml Schema Collections and adding of these is currently not supported in the public API.
            </exception>
            <exception cref="T:System.Runtime.Remoting.RemotingException">
            If communication with the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObjectService"/> fails.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.DeleteObjects(System.String)">
            <summary>
            Deletes any objects that were added to the model with the specified <paramref name="sourceName"/>.
            </summary>
            <param name="sourceName">
            A name to identify the source to be deleted, for example a 
            fileName such as "MyTable.sql" or simply an alias like "dbo.Table". 
            Scripts are cached and TSqlObjects are linked to the source name.
            </param>
            <exception cref="T:System.ArgumentException">
            If the supplied <paramref name="sourceName"/> is null or whitespace, or if it ends
            in ".xsd". 
            Note: source names ending in ".xsd" are currently not supported. These relate 
            to Xml Schema Collections and adding of these is currently not supported in the public API.
            </exception>
            <exception cref="T:System.Runtime.Remoting.RemotingException">
            If communication with the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObjectService"/> fails.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.ConvertToScriptedObject(Microsoft.SqlServer.Dac.Model.TSqlObject,System.String)">
            <summary>
            Converts a specific top-level object in the model into a scripted representation of itself.
            This is useful when starting from a database sourced model and the caller wishes to modify this
            object's contents.  
            </summary>
            <param name="tSqlObject">Object to convert. Must not be null</param>
            <param name="sourceName">Optional source name. If left null a default name will be generated
            for the object. This name can be found using <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetSourceInformation"/>'s 
            SourceName property.
            </param>
            <returns>New copy of the TSqlObject, which will now be script-backed.
            Or if the object was already script-backed, will simply return this object
            </returns>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            Thrown if the object could not be scripted out, this class of object is never scriptable,
            or errors were found in the model during the script process
            </exception>
            <exception cref="T:System.ArgumentException">If the oject is null, or if whitespace is used for the source name</exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.Validate">
            <summary>
            Validates the model and returns a list of messages with any errors/warnings.
            </summary>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.CheckVersionCompatibility(Microsoft.SqlServer.Dac.Model.SqlServerVersion,System.Threading.CancellationToken)">
            <summary>
            Validates the model to determine whether it contains any elements that are not compatible with a target version of SQL Server or Azure SQL Database, 
            and returns any errors or warnings.
            </summary>
            <param name="targetVersion">The target sql version of the export</param>
            <param name="cancelToken">A token used for cancelling the model check.</param>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.CopyModelOptions">
            <summary>
            Copies the <see cref="T:Microsoft.SqlServer.Dac.Model.DatabaseOptions"/> for the model to a <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModelOptions"/> object.
            This is useful if you wish to duplicate the options for a model when creating a new model.
            </summary>
            <returns><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModelOptions"/> with settings matching the database options of the 
            model</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModel.Dispose">
            <summary>
            Releases all resources used by the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> object.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModel.Version">
            <summary>
            The specific SQL Server release targeted by the model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModel.EngineVersion">
            <summary>
            The specific engine version targeted by the model.
            
            For On Premises platforms this will be consistent with the <see cref="T:Microsoft.SqlServer.Dac.Model.SqlServerVersion"/> - for instance
            <see cref="F:Microsoft.SqlServer.Dac.Model.SqlServerVersion.Sql90"/> will have an engine version of 9.
            
            For Microsoft Azure SQL Database the minimum valid version is 11, and the engine version will affect
            what features are supported in the model.  
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModel.IsScriptBacked">
            <summary>
            Is this a model that is backed by scripts? In this case objects in the 
            <see cref="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.UserDefined"/> scope will have source position information including 
            a source name and information. This is important for scenarios such as use of the 
            <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.CodeAnalysisService"/>. 
            
            Any empty <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> created will be script-backed by default. Models loaded
            from a Dacpac will only be scipt backed if the <see cref="P:Microsoft.SqlServer.Dac.Model.ModelLoadOptions.LoadAsScriptBackedModel"/>
            option is enabled. Note that creating a script-backed model will take longer than using a standard model
            loaded from a Dacpac
            
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModel.DisplayServices">
            <summary>
            Gets the <see cref="P:Microsoft.SqlServer.Dac.Model.TSqlModel.DisplayServices"/> that support producing display properties for
            objects in the model.  
            </summary>
            <returns><see cref="P:Microsoft.SqlServer.Dac.Model.TSqlModel.DisplayServices"/></returns>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModel.CollationComparer">
            <summary>
            Comparer that can compare strings and <see cref="T:Microsoft.SqlServer.Dac.Model.ObjectIdentifier"/>s using the collation of this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/>.
            This can be very useful when comparing objects in the model since comparisons will be consistent with the expected comparison
            results in SQL Server
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.TSqlModelOptions">
            <summary>
            Defines model wide options
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.#ctor">
            <summary>
            Constructs the TSqlModelOptions
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.#ctor(Microsoft.SqlServer.Dac.Model.TSqlModelOptions)">
            <summary>
            Constructs the TSqlModelOptions based on an existing options object
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.Copy(Microsoft.SqlServer.Dac.Model.TSqlModelOptions,Microsoft.SqlServer.Dac.Model.TSqlModelOptions)">
            <summary>
            Copies deployment options between objects.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.Collation">
            <summary>
            Specifies the Collation to use for the model. This is a 
            string such as "SQL_Latin1_General_CP1_CI_AS", which must
            be a valid SQL Server Collation Name
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.StorageType">
            <summary>
            Specifies the storage type - in memory or file backed. 
            Default value is <see cref="F:Microsoft.SqlServer.Dac.DacSchemaModelStorageType.Memory"/>
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.AllowSnapshotIsolation">
            <summary>
            Specifies the ALLOW_SNAPSHOT_ISOLATION database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.TransactionIsolationReadCommittedSnapshot">
            <summary>
            Specifies the READ_COMMITTED_SNAPSHOT database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.MemoryOptimizedElevateToSnapshot">
            <summary>
            Specifies the MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.AnsiNullDefaultOn">
            <summary>
            Specifies the ANSI_NULL_DEFAULT database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.AnsiNullsOn">
            <summary>
            Specifies the ANSI_NULLS database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.AnsiPaddingOn">
            <summary>
            Specifies the ANSI_PADDING database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.AnsiWarningsOn">
            <summary>
            Specifies the ANSI_WARNINGS database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.ArithAbortOn">
            <summary>
            Specifies the ARITH_ABORT database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.AutoClose">
            <summary>
            Specifies the AUTO_CLOSE database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.AutoCreateStatistics">
            <summary>
            Specifies the AUTO_CREATE_STATISTICS database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.AutoCreateStatisticsIncremental">
            <summary>
            Specifies the AUTO_CREATE_STATISTICS INCREMENTAL database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.AutoShrink">
            <summary>
            Specifies the AUTO_SHRINK database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.AutoUpdateStatistics">
            <summary>
            Specifies the AUTO_UPDATE_STATISTICS database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.AutoUpdateStatisticsAsync">
            <summary>
            Specifies the AUTO_UPDATE_STATISTICS_ASYNC database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.ChangeTrackingAutoCleanup">
            <summary>
            Specifies the AUTO_CLEANUP database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.ChangeTrackingEnabled">
            <summary>
            Specifies the CHANGE_TRACKING database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.ChangeTrackingRetentionPeriod">
            <summary>
            Specifies the period of the CHANGE_RETENTION database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.ChangeTrackingRetentionUnit">
            <summary>
            Specifies the unit of the CHANGE_RETENTION database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.CompatibilityLevel">
            <summary>
            Specifies the COMPATIBILITY_LEVEL database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.ConcatNullYieldsNull">
            <summary>
            Specifies the CONCAT_NULL_YIELDS_NULL database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.Containment">
            <summary>
            Specifies the CONTAINMENT database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.CursorCloseOnCommit">
            <summary>
            Specifies the CURSOR_CLOSE_ON_COMMIT database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.CursorDefaultGlobalScope">
            <summary>
            Specifies the CURSOR_DEFAULT database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.DatabaseStateOffline">
            <summary>
            Specifies the ONLINE | OFFLINE database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.DateCorrelationOptimizationOn">
            <summary>
            Specifies the DATE_CORRELATION_OPTIMIZATION database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.DefaultFullTextLanguage">
            <summary>
            Specifies the DEFAULT_FULLTEXT_LANGUAGE database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.DefaultLanguage">
            <summary>
            Specifies the DEFAULT_LANGUAGE database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.DBChainingOn">
            <summary>
            Specifies the DB_CHAINING database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.DbScopedConfigLegacyCardinalityEstimation">
            <summary>
            Specifies the Database Scoped Configuration LEGACY_CARDINALITY_ESTIMATION option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.DbScopedConfigLegacyCardinalityEstimationSecondary">
            <summary>
            Specifies the Database Scoped Configuration LEGACY_CARDINALITY_ESTIMATION option for secondaries.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.DbScopedConfigMaxDOP">
            <summary>
            Specifies the Database Scoped Configuration MAXDOP option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.DbScopedConfigMaxDOPSecondary">
            <summary>
            Specifies the Database Scoped Configuration MAXDOP option for secondaries.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.DbScopedConfigParameterSniffing">
            <summary>
            Specifies the Database Scoped Configuration PARAMETER_SNIFFING option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.DbScopedConfigParameterSniffingSecondary">
            <summary>
            Specifies the Database Scoped Configuration PARAMETER_SNIFFING option for secondaries.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.DbScopedConfigQueryOptimizerHotfixes">
            <summary>
            Specifies the Database Scoped Configuration QUERY_OPTIMIZER_HOTFIXES option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.DbScopedConfigQueryOptimizerHotfixesSecondary">
            <summary>
            Specifies the Database Scoped Configuration QUERY_OPTIMIZER_HOTFIXES option for secondaries.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.FileStreamDirectoryName">
            <summary>
            Specifies the DIRECTORY_NAME database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.FullTextEnabled">
            <summary>
            Specifies the sp_fulltext_database database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.HonorBrokerPriority">
            <summary>
            Specifies the HONOR_BROKER_PRIORITY database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.NestedTriggersOn">
            <summary>
            Specifies the NESTED_TRIGGER database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.NonTransactedFileStreamAccess">
            <summary>
            Specifies the NON_TRANSACTED_ACCESS database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.NumericRoundAbortOn">
            <summary>
            Specifies the NUMERIC_ROUNDABORT database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.PageVerifyMode">
            <summary>
            Specifies the PAGE_VERIFY database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.ParameterizationOption">
            <summary>
            Specifies the PARAMETERIZATION database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.QueryStoreCaptureMode">
            <summary>
            Specifies the query capture mode of QUERY_STORE database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.QueryStoreDesiredState">
            <summary>
            Specifies the operation mode of QUERY_STORE database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.QueryStoreFlushInterval">
            <summary>
            Specifies the Flush_Interval_Seconds setting of the QUERY_STORE database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.QueryStoreIntervalLength">
            <summary>
            Specifies the Interval_Length_Minutes setting of the QUERY_STORE database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.QueryStoreMaxStorageSize">
            <summary>
            Specifies the Max_Storage_Size_MB setting of the QUERY_STORE database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.QueryStoreMaxPlansPerQuery">
            <summary>
            Specifies the Max_Plans_Per_Query setting of the QUERY_STORE database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.QueryStoreStaleQueryThreshold">
            <summary>
            Specifies the Stale_Query_Threshold_Days setting of the QUERY_STORE database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.QuotedIdentifierOn">
            <summary>
            Specifies the QUOTED_IDENTIFIER database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.ReadOnly">
            <summary>
            Specifies the READ_ONLY | READ_WRITE database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.RecoveryMode">
            <summary>
            Specifies the RECOVERY database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.DelayedDurabilityMode">
            <summary>
            Specifies the DELAYED_DURABILITY database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.RecursiveTriggersOn">
            <summary>
            Specifies the RECURSIVE_TRIGGERS database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.ServiceBrokerOption">
            <summary>
            Specifies the ENABLE_BROKER | DISABLE_BROKER | NEW_BROKER | ERROR_BROKER_CONVERSATIONS database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.EngineVersion">
            <summary>
            Specifies what engine version should be targeted by the model.
            For On Premises platforms this value will be ignored as the engine version is fixed based on the platform.
            For the <see cref="F:Microsoft.SqlServer.Dac.Model.SqlServerVersion.SqlAzure"/> platform this value will be set and used
            to specify what T-SQL language features are supported. 
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.SupplementalLoggingOn">
            <summary>
            Specifies the SUPPLEMENTAL_LOGGING database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.TargetRecoveryTimePeriod">
            <summary>
            Specifies the period of the TARGET_RECOVERY_TIME database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.TargetRecoveryTimeUnit">
            <summary>
            Specifies the unit of the TARGET_RECOVERY_TIME database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.TornPageProtectionOn">
            <summary>
            Specifies the TORN_PAGE_DETECTION database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.TransformNoiseWords">
            <summary>
            Specifies the TRANSFORM_NOISE_WORDS database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.Trustworthy">
            <summary>
            Specifies the TRUSTWORTHY database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.TwoDigitYearCutoff">
            <summary>
            Specifies the TWO_DIGIT_YEAR_CUTOFF database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.VardecimalStorageFormatOn">
            <summary>
            Specifies the sp_db_vardecimal_storage_format database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.UserAccessOption">
            <summary>
            Specifies the SINGLE_USER | RESTRICTED_USER | MULTI_USER database option.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelOptions.WithEncryption">
            <summary>
            Specifies the ENCRYPTION database option.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.TSqlModelSchema">
            <summary>
            Defines a schema for a relational TSQL database model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelSchema.TopLevelTypes">
            <summary>
            All top level types supported in the model. These are the only types that
            can be queried for via the <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.GetObject(Microsoft.SqlServer.Dac.Model.ModelTypeClass,Microsoft.SqlServer.Dac.Model.ObjectIdentifier,Microsoft.SqlServer.Dac.Model.DacQueryScopes)"/> and 
            <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.GetObjects(Microsoft.SqlServer.Dac.Model.DacQueryScopes,Microsoft.SqlServer.Dac.Model.ModelTypeClass[])"/> 
            API calls.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlModelSchema.AllTypes">
            <summary>
            All types supported in the model. This will include types that are cannot be queried for using
            the <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.GetObject(Microsoft.SqlServer.Dac.Model.ModelTypeClass,Microsoft.SqlServer.Dac.Model.ObjectIdentifier,Microsoft.SqlServer.Dac.Model.DacQueryScopes)"/> and 
            <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlModel.GetObjects(Microsoft.SqlServer.Dac.Model.DacQueryScopes,Microsoft.SqlServer.Dac.Model.ModelTypeClass[])"/> 
            API calls.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.TSqlObject">
            <summary>
            Represents an instance of an object for a SQL Server database schema.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.TryGetAst(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlScript@)">
            <summary>
            Attempts to generate an AST for the object. AST generation is only supported for top-level objects, with certain
            objects such as the <see cref="T:Microsoft.SqlServer.Dac.Model.DatabaseOptions"/> and inline constraints not supporting AST generation even though
            they are top level types.
            
            The generated AST is a newly generated object that defines the information about this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> and any objects
            that would be scripted together with it. For example a Table would also script out the Columns and inline constraint definitions of a Table. 
            This method can be used to copy object information from one model to another, or to script out information about
            objects in the model.
            </summary>
            <param name="objectAst">Returns the generated AST if the call succeeded.</param>
            <returns>True if AST generated. Otherwise false.</returns>
            <remarks>
            The Ast will not have information about the original source position, such as the original source name and original
            position in an input script.
            </remarks>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetAst">
            <summary>
            Generates a new <see cref="T:Microsoft.SqlServer.TransactSql.ScriptDom.TSqlScript"/> representing the AST for the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>, if this is
            supported for the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>. AST generation is only supported for top-level objects, with certain
            objects such as the <see cref="T:Microsoft.SqlServer.Dac.Model.DatabaseOptions"/> and inline constraints not supporting AST generation even though
            they are top level types. If it's unknown whether the object is capable of being scripted
            then the <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlObject.TryGetAst(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlScript@)"/> method should be used instead.
            
            The generated AST is a newly generated object that defines the information about this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> and any objects
            that would be scripted together with it. For example a Table would also script out the Columns and inline constraint definitions of a Table. 
            This method can be used to copy object information from one model to another, or to script out information about
            objects in the model.
            </summary>
            <remarks>
            The AST will not have information about the original source position, such as the original source name and original
            position in an input script.
            </remarks>
            <returns>The generated AST object.</returns>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> is not a top level statement object or if it does not support AST generation (for example
            if it is a <see cref="T:Microsoft.SqlServer.Dac.Model.DatabaseOptions"/> or a constraint that was originally defined inline with a Table).
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.TryGetScript(System.String@)">
            <summary>
            Attempts to generate a CREATE script from the objects AST. AST generation is only supported for top-level objects, with certain
            objects such as the <see cref="T:Microsoft.SqlServer.Dac.Model.DatabaseOptions"/> and inline constraints not supporting AST generation even though
            they are top level types. If it's unknown whether the object is capable of being scripted
            then the <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlObject.TryGetAst(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlScript@)"/> method should be used instead.
            </summary>
            <param name="objectScript">The DDL Creation script for the object </param>
            <returns>True if the DDL creation script was created.</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetScript">
            <summary>
            Generates a CREATE script from the objects AST. AST generation is only supported for top-level objects, with certain
            objects such as the <see cref="T:Microsoft.SqlServer.Dac.Model.DatabaseOptions"/> and inline constraints not supporting AST generation even though
            they are top level types. If it's unknown whether the object is capable of being scripted
            then the <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlObject.TryGetAst(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlScript@)"/> method should be used instead.
            </summary>
            <returns>DDL Creation script</returns>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> is not a top level statement object or if it does not support script generation (for example
            if it is a <see cref="T:Microsoft.SqlServer.Dac.Model.DatabaseOptions"/> or a constraint that was originally defined inline with a Table).
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetSourceFragment">
            <summary>
            Note: Internal only for now. Dacpacs and database-targeted models will not have any source fragment information. 
             
            Gets the <see cref="T:Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment"/> which defines the object - may be null. This is the fragment from the original source,
            with original source position information (if available). 
            
            This should not be used when copying the object to a different model or when doing any external 
            manipulation of the object - in those cases the <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlObject.TryGetAst(Microsoft.SqlServer.TransactSql.ScriptDom.TSqlScript@)"/> method should be used to get a 
            self-contained AST describing this Object.
            </summary>
            <returns><see cref="T:Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment"/>, or null if this was not present</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetProperty``1(Microsoft.SqlServer.Dac.Model.ModelPropertyClass)">
            <summary>
            Returns the property value.
            </summary>
            <typeparam name="T">Property type.</typeparam>
            <param name="property">Property.</param>
            <returns>Property Value.</returns>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If <paramref name="property"/> does not exists on the object.
            </exception>
            <exception cref="T:System.InvalidCastException">
            If the property type cannot be cast to T.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetProperty(Microsoft.SqlServer.Dac.Model.ModelPropertyClass)">
            <summary>
            Returns the property value.
            </summary>
            <param name="property">Property.</param>
            <returns>Property Value.</returns>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If <paramref name="property"/> does not exists on the object.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetMetadata``1(Microsoft.SqlServer.Dac.Model.ModelMetadataClass)">
            <summary>
            Returns the metadata property value.
            </summary>
            <typeparam name="T">Metadata property type.</typeparam>
            <param name="metadata">Metadata property name.</param>
            <returns>Metadata property value.</returns>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If <paramref name="metadata"/> does not exists on the object.
            </exception>
            <exception cref="T:System.InvalidCastException">
            If the metadata property type cannot be cast to T.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetMetadata(Microsoft.SqlServer.Dac.Model.ModelMetadataClass)">
            <summary>
            Returns the metadata property value.
            </summary>
            <param name="metadata">Metadata property name.</param>
            <returns>Metadata property value.</returns>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If <paramref name="metadata"/> does not exists on the object.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetParent">
            <summary>
            Returns the parent <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>, if it is within the
            <see cref="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.Default"/> scope and if there is only one <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>
            that could be the parent for this object..
            </summary>
            <returns>Parent object others null.</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetParent(Microsoft.SqlServer.Dac.Model.DacQueryScopes)">
            <summary>
            Returns the parent <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>, if it is within the
            specified <see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> scope and if there is only one <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>
            that could be the parent for this object.
            </summary>
            <param name="queryScopes"><see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> defining the scope objects must exist in.</param>
            <returns>Parent object or else null.</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetChildren">
            <summary>
            Returns all <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> child objects within the <see cref="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.Default"/> scope.
            </summary>
            <returns>All children.</returns>
            <remarks>
            References to elements not in the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> are not returned.
            </remarks>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetChildren(Microsoft.SqlServer.Dac.Model.DacQueryScopes)">
            <summary>
            Returns all <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> child objects within the specified
            <see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> scope.
            </summary>
            <param name="queryScopes"><see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> defining the scope objects must exist in.</param>
            <returns>All children.</returns>
            <remarks>
            References to elements not in the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> are not returned.
            </remarks>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferenced">
            <summary>
            Gets all referenced objects within the <see cref="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.Default"/> scope
            </summary>
            <returns><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>s referenced by this object</returns>
            <remarks>
            References to elements not in the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> are not returned. Use <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferencedRelationshipInstances"/> for a listing
            of all possible referenced elements.
            </remarks>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferenced(Microsoft.SqlServer.Dac.Model.DacQueryScopes)">
            <summary>
            Gets all referenced objects within a given <see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> scope.
            </summary>
            <param name="queryScopes"><see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> defining the scope objects must exist in.</param>
            <returns><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>s referenced by this object</returns>
            <remarks>
            References to elements not in the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> are not returned. Use <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferencedRelationshipInstances"/> for a listing
            of all possible referenced elements.
            </remarks>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferenced(Microsoft.SqlServer.Dac.Model.ModelRelationshipClass)">
            <summary>
            Gets referenced objects for a given <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/>,
            where objects are within the <see cref="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.Default"/> scope
            </summary>
            <param name="relationshipType"><see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/> defining the relationship class to query for</param>
            <returns><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>s referenced by this object for a given <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/></returns>
            <remarks>
            References to elements not in the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> are not returned. Use <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferencedRelationshipInstances"/> for a listing
            of all possible referenced elements.
            </remarks>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferenced(Microsoft.SqlServer.Dac.Model.ModelRelationshipClass,Microsoft.SqlServer.Dac.Model.DacQueryScopes)">
            <summary>
            Gets referenced objects for a given <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/>,
            where objects are within a given <see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> scope.
            </summary>
            <param name="relationshipType"><see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/> defining the relationship to query for</param>
            <param name="queryScopes"><see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> defining the scope objects must exist in.</param>
            <returns><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>s referenced by this object for a given <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/></returns>
            <remarks>
            References to elements not in the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/> are not returned. Use <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferencedRelationshipInstances"/> for a listing
            of all possible referenced elements.
            </remarks>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferencedRelationshipInstances">
            <summary>
            For each object referenced by this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>, returns the <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance"/> defining
            the relationship data. This will include the referenced object if it exists, the <see cref="T:Microsoft.SqlServer.Dac.Model.ObjectIdentifier"/> used to identify the
            referenced object, and any properties specific to this relationship.
            Only objects within the <see cref="F:Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes.Default"/> scope will be returned.
            </summary>
            <returns><see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance"/>s defining the relationships between this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> and the objects
            referenced by it</returns>
            <remarks>
            The <see cref="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.Object"/> field may be null if the element is not in the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/>. In these cases the
            <see cref="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.ObjectName"/> field can be used to query information about the referenced object
            </remarks>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferencedRelationshipInstances(Microsoft.SqlServer.Dac.Model.DacQueryScopes)">
            <summary>
            For each object referenced by this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>, returns the <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance"/> defining
            the relationship data. This will include the referenced object if it exists, the <see cref="T:Microsoft.SqlServer.Dac.Model.ObjectIdentifier"/> used to identify the
            referenced object, and any properties specific to this relationship.
            Only objects within the specified <see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> scope will be returned.
            To return non-composite or system references the <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferencedRelationshipInstances(Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes)"/> method should be called instead
            </summary>
            <param name="queryScopes"><see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> defining the scope objects must exist in.</param>
            <returns><see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance"/>s defining the relationships between this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> and the objects
            referenced by it</returns>
            <remarks>
            The <see cref="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.Object"/> field may be null if the element is not in the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/>. In these cases the
            <see cref="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.ObjectName"/> field can be used to query information about the referenced object
            </remarks>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferencedRelationshipInstances(Microsoft.SqlServer.Dac.Model.ModelRelationshipClass)">
            <summary>
            For objects referenced by this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> with a specific <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/>, 
            returns the <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance"/> defining
            the relationship data. This will include the referenced object if it exists, the <see cref="T:Microsoft.SqlServer.Dac.Model.ObjectIdentifier"/> used to identify the
            referenced object, and any properties specific to this relationship.
            Only objects within the <see cref="F:Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes.Default"/> scope will be returned.
            </summary>
            <param name="relationshipType"><see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/> defining the relationship class to query for</param>
            <returns><see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance"/>s defining the relationships between this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> and the objects
            referenced by it</returns>
            <remarks>
            The <see cref="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.Object"/> field may be null if the element is not in the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/>. In these cases the
            <see cref="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.ObjectName"/> field can be used to query information about the referenced object
            </remarks>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferencedRelationshipInstances(Microsoft.SqlServer.Dac.Model.ModelRelationshipClass,Microsoft.SqlServer.Dac.Model.DacQueryScopes)">
            <summary>
            For objects referenced by this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> with a specific <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/>, 
            returns the <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance"/> defining
            the relationship data. This will include the referenced object if it exists, the <see cref="T:Microsoft.SqlServer.Dac.Model.ObjectIdentifier"/> used to identify the
            referenced object, and any properties specific to this relationship.
            Only objects within the specified <see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> scope will be returned.
            To return non-composite or system references the <see cref="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferencedRelationshipInstances(Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes)"/> method should be called instead
            </summary>
            <param name="relationshipType"><see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/> defining the relationship class to query for</param>
            <param name="queryScopes"><see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> defining the scope objects must exist in.</param>
            <returns><see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance"/>s defining the relationships between this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> and the objects
            referenced by it</returns>
            <remarks>
            The <see cref="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.Object"/> field may be null if the element is not in the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/>. In these cases the
            <see cref="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.ObjectName"/> field can be used to query information about the referenced object
            </remarks>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferencedRelationshipInstances(Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes)">
            <summary>
            For each object referenced by this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>, returns the <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance"/> defining
            the relationship data. This will include the referenced object if it exists, the <see cref="T:Microsoft.SqlServer.Dac.Model.ObjectIdentifier"/> used to identify the
            referenced object, and any properties specific to this relationship.
            Only objects within the specified <see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> scope will be returned.
            To return non-composite or system references the scope must be set to include externals. In addition, in this case only the
            <see cref="T:Microsoft.SqlServer.Dac.Model.ObjectIdentifier"/> of the referenced object will be returned
            </summary>
            <param name="queryScopes"><see cref="T:Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes"/> defining the scope objects must exist in.</param>
            <returns><see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance"/>s defining the relationships between this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> and the objects
            referenced by it</returns>
            <remarks>
            The <see cref="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.Object"/> field may be null if the element is not in the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/>. In these cases the
            <see cref="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.ObjectName"/> field can be used to query information about the referenced object
            </remarks>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferencedRelationshipInstances(Microsoft.SqlServer.Dac.Model.ModelRelationshipClass,Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes)">
            <summary>
            For objects referenced by this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> with a specific <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/>, 
            returns the <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance"/> defining
            the relationship data. This will include the referenced object if it exists, the <see cref="T:Microsoft.SqlServer.Dac.Model.ObjectIdentifier"/> used to identify the
            referenced object, and any properties specific to this relationship.
            Only objects within the specified <see cref="T:Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes"/> scope will be returned.
            To return non-composite or system references the scope must be set to include externals. In addition, in this case only the
            <see cref="T:Microsoft.SqlServer.Dac.Model.ObjectIdentifier"/> of the referenced object will be returned
            </summary>
            <param name="relationshipType"><see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/> defining the relationship class to query for</param>
            <param name="queryScopes"><see cref="T:Microsoft.SqlServer.Dac.Model.DacExternalQueryScopes"/> defining the scope objects must exist in.</param>
            <returns><see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance"/>s defining the relationships between this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> and the objects
            referenced by it</returns>
            <remarks>
            The <see cref="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.Object"/> field may be null if the element is not in the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/>. In these cases the
            <see cref="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.ObjectName"/> field can be used to query information about the referenced object
            </remarks>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.VerifyRelationshipOwner(Microsoft.SqlServer.Dac.Model.ModelRelationshipClass)">
            <summary>
            Verifies this object's class owns the relationship. Only valid for referenced relationships - referencing could be anything
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferencing">
            <summary>
            Gets all referencing objects within the <see cref="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.Default"/> scope
            </summary>
            <returns><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>s referencing this object</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferencing(Microsoft.SqlServer.Dac.Model.DacQueryScopes)">
            <summary>
            Gets all referencing objects within a given <see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> scope.
            </summary>
            <param name="queryScopes"><see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> defining the scope objects must exist in.</param>
            <returns><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>s referencing this object</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferencing(Microsoft.SqlServer.Dac.Model.ModelRelationshipClass)">
            <summary>
            Gets referencing objects, 
            where the relationship is defined by a specific <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/> 
            and where objects are within the <see cref="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.Default"/> scope
            </summary>
            <param name="relationshipType"><see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/> defining the relationship class to query for</param>
            <returns><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>s referencing this object for a given <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferencing(Microsoft.SqlServer.Dac.Model.ModelRelationshipClass,Microsoft.SqlServer.Dac.Model.DacQueryScopes)">
            <summary>
            Gets referencing objects, 
            where the relationship is defined by a specific <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/> 
            and where objects are within a given <see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> scope.
            </summary>
            <param name="relationshipType"><see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/> defining the relationship to query for</param>
            <param name="queryScopes"><see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> defining the scope objects must exist in.</param>
            <returns><see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>s referencing this object for a given <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferencingRelationshipInstances">
            <summary>
            For each object referencing this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>, returns the <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance"/> defining
            the relationship data. 
            This will include the referencing object - definedby the <see cref="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.FromObject"/> field, 
            and any properties specific to this relationship.
            Only objects within the specified <see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> scope will be returned.
            </summary>
            <returns><see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance"/>s defining the relationships between this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> and the objects
            referencing it</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferencingRelationshipInstances(Microsoft.SqlServer.Dac.Model.DacQueryScopes)">
            <summary>
            For each object referencing this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>, returns the <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance"/> defining
            the relationship data. 
            This will include the referencing object - definedby the <see cref="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.FromObject"/> field, 
            and any properties specific to this relationship.
            Only objects within the <see cref="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.Default"/> scope will be returned.
            </summary>
            <param name="queryScopes"><see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> defining the scope objects must exist in.</param>
            <returns><see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance"/>s defining the relationships between this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> and the objects
            referencing it</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferencingRelationshipInstances(Microsoft.SqlServer.Dac.Model.ModelRelationshipClass)">
            <summary>
            For each object referencing this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> with a specific <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/>,
            returns the <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance"/> defining the relationship data. 
            This will include the referencing object - definedby the <see cref="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.FromObject"/> field, 
            and any properties specific to this relationship.
            Only objects within the <see cref="F:Microsoft.SqlServer.Dac.Model.DacQueryScopes.Default"/> scope will be returned.
            </summary>
            <param name="relationshipType"><see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/> defining the relationship class to query for</param>
            <returns><see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance"/>s defining the relationships between this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> and the objects
            referencing it
            </returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetReferencingRelationshipInstances(Microsoft.SqlServer.Dac.Model.ModelRelationshipClass,Microsoft.SqlServer.Dac.Model.DacQueryScopes)">
            <summary>
            For each object referencing this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> with a specific <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/>,
            returns the <see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance"/> defining the relationship data. 
            This will include the referencing object - definedby the <see cref="P:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance.FromObject"/> field, 
            and any properties specific to this relationship.
            Only objects within the specified <see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> scope will be returned.
            </summary>
            <param name="relationshipType"><see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipClass"/> defining the relationship class to query for</param>
            <param name="queryScopes"><see cref="T:Microsoft.SqlServer.Dac.Model.DacQueryScopes"/> defining the scope objects must exist in.</param>
            <returns><see cref="T:Microsoft.SqlServer.Dac.Model.ModelRelationshipInstance"/>s defining the relationships between this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> and the objects
            referencing it
            </returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetSourceInformation">
            <summary>
            Gets the <see cref="T:Microsoft.SqlServer.Dac.SourceInformation"/> for this object, if this is available
            </summary>
            <returns>
            If source information is available returns the <see cref="T:Microsoft.SqlServer.Dac.SourceInformation"/> specifying the name of the script 
            this object is found in, plus start line and column. These values may be null or -1 if no source position information is present
            </returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.Equals(System.Object)">
            <summary>
            Checks if this <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> is equal to another <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> 
            </summary>
            <param name="obj">object to compare</param>
            <returns>true if they are equal</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.GetHashCode">
            <summary>
            Gets the Hashcode for this object
            </summary>
            <returns>int hashcode</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Model.TSqlObject.UpdateContextObject(System.Object)">
            <summary>
            Internal method that updates the context object for the public <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>
            wrapper. Should only be called if the original context object is no longer valid, for instance
            if it has been deleted from the model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlObject.Name">
            <summary>
            Identity of the object.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlObject.ObjectType">
            <summary>
            Type of the object.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlObject.Item(Microsoft.SqlServer.Dac.Model.ModelPropertyClass)">
            <summary>
            Returns the property value.
            </summary>
            <param name="property">Property.</param>
            <returns>Property value.</returns>
            <exception cref="T:Microsoft.SqlServer.Dac.Model.DacModelException">
            If <paramref name="property"/> does not exists on the object.
            </exception>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlObject.ContextObject">
            <summary>
            Returns the context object for this Sql Object
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.TSqlObjectOptions">
            <summary>
            Defines options to be used for specific TSqlObjects 
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlObjectOptions.QuotedIdentifier">
            <summary>
            Specifies if the QUOTED_IDENTIFIER setting for objects is on or off
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Model.TSqlObjectOptions.AnsiNulls">
            <summary>
            Specifies if the the ANSI_NULLS connection setting for objects is on or off
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Model.TSqlPlatforms">
            <summary>
            Specific SQL Server releases.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TSqlPlatforms.Sql90">
             <summary>
            on-premises, version 9.0
             </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TSqlPlatforms.Sql100">
            <summary>
            on-premises, version 10.0
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TSqlPlatforms.SqlAzure">
            <summary>
            Microsoft Azure SQL Database, version 11
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TSqlPlatforms.Sql110">
            <summary>
            on-premises, version 11.0
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TSqlPlatforms.Sql120">
            <summary>
            on-premises, version 12.0
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TSqlPlatforms.Sql130">
            <summary>
            on-premises, version 13.0
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TSqlPlatforms.SqlAzureV12">
            <summary>
            Microsoft Azure SQL Database, version 12
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TSqlPlatforms.Sql140">
            <summary>
            on-premises, version 14.0
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TSqlPlatforms.OnPremises">
            <summary>
            All on-premises versions
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TSqlPlatforms.Cloud">
            <summary>
            All cloud releases
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.Model.TSqlPlatforms.All">
            <summary>
            Combination of all SQL Server categories
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.PackageMetadata">
            <summary>
            Metadata information that describes a package.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.PackageMetadata.Name">
            <summary>
            Package name
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.PackageMetadata.Version">
            <summary>
            Package version
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.PackageMetadata.Description">
            <summary>
            Package description
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.PackageOptions">
            <summary>
            Defines advanced options and additional artifacts for package creation.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.PackageOptions.TreatWarningsAsErrors">
            <summary>
            Indicates whether warnings should be treated as errors during model validation 
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.PackageOptions.IgnoreValidationErrors">
            <summary>
            Indicates the list of errors that will be ignored during validation
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.PackageOptions.RefactorLogPath">
            <summary>
            Path to the file to be added as the refactor log content to the .dacpac
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.PackageOptions.DeploymentContributors">
            <summary>
            List of contributors that are required in order to deploy the .dacpac
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.PackageOptions.ContributorArguments">
            <summary>
            List of contributors that are required in order to deploy the .dacpac
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.PackageOptions.DeploymentContributorConfigurationStreams">
            <summary>
            List of contributors that are required in order to deploy the .dacpac
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.SourceInformation">
            <summary>
            Represents information about an item of interest in the model, 
            for example a <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem"/>. 
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.SourceInformation.#ctor(System.String,System.Int32,System.Int32)">
            <summary>
            Initializes an instance of a <see cref="T:Microsoft.SqlServer.Dac.SourceInformation"/> object.
            </summary>
            <param name="sourceName">Name representing the source for the information</param>
            <param name="startLine">start line, if known. May be -1 or 0 if the position is not known.</param>
            <param name="startColumn">start column, if known. May be -1 or 0 if the position is not known.</param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.SourceInformation.SourceName">
            <summary>
            Name representing the source for the information
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.SourceInformation.StartLine">
            <summary>
            The start line. May be -1 or 0 if the position is not known.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.SourceInformation.StartColumn">
            <summary>
            The start column. May be -1 or 0 if the position is not known.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.TSqlModelUtils">
            <summary>
            Provides utility methods for the public model APIs.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.TSqlModelUtils.TryGetFragmentForAnalysis(Microsoft.SqlServer.Dac.Model.TSqlObject,Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment@)">
            <summary>
            Tries to get the most suitable <see cref="T:Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment"/> for use during the rule analysis process.
            If the TSqlObject was originally built from a scripted source then the original source fragment will be returned.
            
            Otherwise a new AST will be generated from the <paramref name="tSqlObject"/>.
             
            This ensures that when reporting <see cref="T:Microsoft.SqlServer.Dac.CodeAnalysis.SqlRuleProblem"/>s the most accurate source information can be included
            in the error messages. 
            
            Note that a fragment will only be returned if this is
            supported for the <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/>. AST generation is only supported for top-level objects, with certain
            objects such as the <see cref="T:Microsoft.SqlServer.Dac.Model.DatabaseOptions"/> and inline constraints not supporting AST generation even though
            they are top level types.
            </summary>
            <param name="tSqlObject">The <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlObject"/> whose fragment is being requested</param>
            <param name="fragment">The <see cref="T:Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment"/> for the <paramref name="tSqlObject"/>, if it is possible to
            get fragment information for the object</param>
            <returns>true if the fragment was obtained, false otherwise.</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.TSqlModelUtils.CalculatePlatformCompatibility(Microsoft.SqlServer.Dac.Model.SqlServerVersion)">
            <summary>
            Maps from a <see cref="T:Microsoft.SqlServer.Dac.Model.SqlServerVersion"/> to the <see cref="T:Microsoft.SqlServer.Dac.Extensibility.TSqlPlatformCompatibility"/> enum that matches it. The
            platform compatibility can be used to filter out extensions that don't support that platform, for instance code analysis
            rules.
            </summary>
            <param name="version">A <see cref="T:Microsoft.SqlServer.Dac.Model.SqlServerVersion"/>, for example the version for a <see cref="T:Microsoft.SqlServer.Dac.Model.TSqlModel"/></param>
            <returns>
            <see cref="T:Microsoft.SqlServer.Dac.Extensibility.TSqlPlatformCompatibility"/> indicating the compatibility level required for extensions. If no specific 
            version was passed into the method then the default will be to use <see cref="F:Microsoft.SqlServer.Dac.Extensibility.TSqlPlatformCompatibility.All"/> so
            that all extensions are loaded. 
            </returns>
        </member>
        <member name="T:AssemblyRef">
            <summary>
            Sets public key string for friend assemblies.
            </summary>
        </member>
        <member name="F:AssemblyRef.ProductPublicKey">
            <summary>No signing</summary>
        </member>
    </members>
</doc>
tools\dbatools\bin\smo\Microsoft.SqlServer.Dac.xml
<?xml version="1.0"?>
<doc>
    <assembly>
        <name>Microsoft.SqlServer.Dac</name>
    </assembly>
    <members>
        <member name="T:Microsoft.SqlServer.Dac.BacPackage">
            <summary>
            Representation of the artifact that contains the definition and data of a data-tier application.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.BacPackage.Dispose">
            <summary>
            Release the resources held by this instance.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.BacPackage.Unpack(System.String)">
            <summary>
            Place the contents of this package into the directory specified by <paramref name="directoryPath"/>.
            </summary>
            <param name="directoryPath">
            Base directory in which to place the package contents.
            </param>
            <exception cref="T:System.ArgumentException">
            If <paramref name="directoryPath"/> is a null reference or empty string.
            </exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If an error occurs while attempting to unpack the package.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.BacPackage.Load(System.String)">
            <summary>
            Load a package file specified by <paramref name="fileName"/>.
            </summary>
            <param name="fileName">
            Path to the package file.
            </param>
            <returns>
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> instance that represents the package loaded from the specified file.
            </returns>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If there is a problem reading the package; or if the package contains exported data.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.BacPackage.Load(System.String,Microsoft.SqlServer.Dac.DacSchemaModelStorageType)">
            <summary>
            Load a package file specified by <paramref name="fileName"/>.
            </summary>
            <param name="fileName">
            Path to the package file.
            </param>
            <param name="modelStorageType">
            Backing storage type for package instance.
            </param>
            <returns>
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> instance that represents the package loaded from the specified file.
            </returns>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If there is a problem reading the package; or if the package does not contain exported data.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.BacPackage.Load(System.IO.Stream)">
            <summary>
            Load a package from the specified <see cref="T:System.IO.Stream"/>.
            </summary>
            <param name="stream">
            Stream from which to read the package.
            </param>
            <returns>
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> instance that represents the package loaded from the specified file.
            </returns>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If there is a problem reading the package; or if the package does not contain exported data.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.BacPackage.Load(System.IO.Stream,Microsoft.SqlServer.Dac.DacSchemaModelStorageType)">
            <summary>
            Load a package from the specified <see cref="T:System.IO.Stream"/>.
            </summary>
            <param name="stream">
            Stream from which to read the package.
            </param>
            <param name="modelStorageType">
            Backing storage type for package instance.
            </param>
            <returns>
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> instance that represents the package loaded from the specified file.
            </returns>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If there is a problem reading the package; or if the package does not contain exported data.
            </exception>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.IUniversalAuthProvider">
            <summary>
            Implement this interface to create a string access token. This access token will be used to set 
            the <see cref="P:System.Data.SqlClient.SqlConnection.AccessToken"/> for any SqlConnection instances created when connecting to a database.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.IUniversalAuthProvider.GetValidAccessToken">
            <summary>
            Returns an valid access token.
            </summary>
            <returns>The access token to be used to set the AccessToken property of the SqlConnection.</returns>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.PublishResult">
            <summary>
            Contains the results of a publish or script operation. This will contain at least one of the <see cref="P:Microsoft.SqlServer.Dac.PublishResult.DeploymentReport"/>
            or <see cref="P:Microsoft.SqlServer.Dac.PublishResult.DatabaseScript"/> properties depending on what was requested in the <see cref="T:Microsoft.SqlServer.Dac.PublishOptions"/>
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.PublishResult.#ctor(System.String,System.String,System.String)">
            <summary>
            Constructs a <see cref="T:Microsoft.SqlServer.Dac.PublishResult"/> with the specified contents
            </summary>
            <param name="deployReport">set as the <see cref="P:Microsoft.SqlServer.Dac.PublishResult.DeploymentReport"/> to return</param>
            <param name="dbScript">set as the <see cref="P:Microsoft.SqlServer.Dac.PublishResult.DatabaseScript"/> to return</param>
            <param name="masterScript">set as the <see cref="P:Microsoft.SqlServer.Dac.PublishResult.MasterDbScript"/> to return</param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.PublishResult.DeploymentReport">
            <summary>
            A Deployment Report, if one was requested.
            This report is a high-level summary of actions being performed during deployment.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.PublishResult.DatabaseScript">
            <summary>
            The DB-level deployment script, if one was requested.
            This script contains all operations that must be done against the database during deployment.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.PublishResult.MasterDbScript">
            <summary>
            The master database-level deployment script, if one was requested.
            This script is only created if Azure SQL DB is the target as USE statements are not supported on that platform.
            It contains all operations that must be done against the master database, for instance Create Database statements
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.PublishOptions">
            <summary>
            Configures options for what will be reported when performing certain operations from <see cref="T:Microsoft.SqlServer.Dac.DacServices"/>,
            in particular whether a DeployReport and/or DeployScript will be generated
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.PublishOptions.#ctor">
            <summary>
            Configures options for what will be reported when performing certain operations from <see cref="T:Microsoft.SqlServer.Dac.DacServices"/>,
            in particular whether a DeployReport and/or DeployScript will be generated
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.PublishOptions.GenerateDeploymentScript">
            <summary>
            Sets whether Deployment Script(s) should be generated during deploy.
            If true, a script to update the database will be generated, and a script to
            update Master may also be generated if the target is an Azure SQL DB and this
            database has not yet been created.
            </summary>
            <value>Defaults to true</value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.PublishOptions.GenerateDeploymentReport">
            <summary>
            Sets whether a Deployment Report should be generated during deploy.
            This report is a high-level summary of actions being performed during deployment.
            </summary>
            <value>Defaults to false</value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.PublishOptions.DatabaseScriptPath">
            <summary>
            Optional path to write the DB-level deployment script, if <see cref="P:Microsoft.SqlServer.Dac.PublishOptions.GenerateDeploymentScript"/> is true.
            This script contains all operations that must be done against the database during deployment.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.PublishOptions.MasterDbScriptPath">
            <summary>
            Optional path to write the master database-level deployment script, if <see cref="P:Microsoft.SqlServer.Dac.PublishOptions.GenerateDeploymentScript"/> is true.
            This script is only created if Azure SQL DB is the target as USE statements are not supported on that platform.
            It contains all operations that must be done against the master database, for instance Create Database statements
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.PublishOptions.DeployOptions">
            <summary>
            Optional <see cref="T:Microsoft.SqlServer.Dac.DacDeployOptions"/> to configure a range of deployment options. 
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.PublishOptions.CancelToken">
            <summary>
            Nullable <see cref="T:System.Threading.CancellationToken"/> to allow the caller to cancel a deployment
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.KeyVault.DacKeyVaultService">
            <summary>
            Provides a service for discovering and configuring a <see cref="T:Microsoft.SqlServer.Dac.KeyVault.KeyVaultAuthenticator"/> to handle key vault access requests.
            These requests will occur during deployment if an encrypted table is being altered. It also supports initialization of general 
            key vault support in an application
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.KeyVault.DacKeyVaultService.SetExtensionProperties(Microsoft.SqlServer.Dac.Extensibility.ExtensionProperties)">
            <summary>
            Internal for testing purposes only
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.KeyVault.DacKeyVaultService.SetDependencyManager(Microsoft.SqlServer.Dac.Extensibility.IDependencyManager)">
            <summary>
            Internal for testing purposes only.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.KeyVault.DacKeyVaultService.UpdateAuthInfo(Microsoft.SqlServer.Dac.KeyVault.KeyVaultAuthInfoBase)">
            <summary>
            Passes a <see cref="T:Microsoft.SqlServer.Dac.KeyVault.KeyVaultAuthInfoBase"/> object to the <see cref="T:Microsoft.SqlServer.Dac.KeyVault.KeyVaultAuthenticator"/>, to support scenarios
            where a user changes authentication method, for instance by logging into a different Azure account
            </summary>
            <param name="authInfo"></param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.KeyVault.DacKeyVaultService.InitializeAuthenticator">
            <summary>
            Gives the authenticator the opportunity to register with the core AlwaysEncrypted callstack. This is important
            in scenarios where Interactive authentication is being used and this is the global authenticator to be used in the application
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.KeyVault.DacKeyVaultService.Validate(System.Collections.Generic.IList{System.String},System.Threading.CancellationToken)">
            <summary>
            Callback function to validate the presence of AKV token for Column Master Key access
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.KeyVault.DacKeyVaultService.Instance">
            <summary>
            Singleton instance object for the <see cref="T:Microsoft.SqlServer.Dac.KeyVault.DacKeyVaultService"/>. 
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.KeyVault.DacKeyVaultService.DependencyManager">
            <summary>
            Get DependencyManager
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.KeyVault.DacKeyVaultService.Trace">
            <summary>
            Trace object to use for tracing
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.KeyVault.DacKeyVaultService.BlockifMissingAuthentication">
            <summary>
            Gives a way to set early failure if Azure Key Vault Provider is not setup.
            When this is true, deployment fails to start if there is no Provider defined
            contrary to default mode which lets the deployment go through and fails only when key is actually used.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.KeyVault.ClientAndSecretAuthInfo">
            <summary>
            Authentication info for client ID and Secret, which is commonly supported in command line scenarios.
            This can be obtained by using the Azure SDK to log into Azure and obtain this information.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.KeyVault.KeyVaultAuthInfoBase">
            <summary>
            Data class to define authentication info that can be passed to a <see cref="T:Microsoft.SqlServer.Dac.KeyVault.KeyVaultAuthenticator"/> when
            configuring 
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.KeyVault.ClientAndSecretAuthInfo.#ctor(System.String,System.String)">
            <summary>
            Constructor
            </summary>
            <param name="clientId">Must not be null or whitespace</param>
            <param name="secret">Must not be null</param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.KeyVault.ClientAndSecretAuthInfo.ClientId">
            <summary>
            Client ID used to log in to Azure
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.KeyVault.ClientAndSecretAuthInfo.Secret">
            <summary>
            Secret that verifies the authentication to Azure
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.KeyVault.KeyVaultAuthenticator">
            <summary>
            Base class for any Azure Key Vault authentication provider. This is responsible for logging into Azure, obtaining
            access keys and returning to the caller. 
            Notes: Only one provider is allowed per process, with the first to register being the successful provider. In order to
            support <see cref="T:Microsoft.SqlServer.Dac.DacServices"/> and related APIs being used in multiple UI tools and the SqlPackage command line the
            binding to Azure Authentication DLLs is loosely coupled to the core Dac Framework using MEF. A default provider is available
            for use in SqlPackage and other command line scenarios, supporting basic credential based authentication. This can be 
            overridden in order to integrate with custom authentication pipelines or into your UI application by extending this method
            and providing an <see cref="T:Microsoft.SqlServer.Dac.Extensibility.ExportableAttribute"/> with typeof(KeyVaultAuthenticator), a unique ID and high priority
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.KeyVault.KeyVaultAuthenticator.GetToken(System.String,System.String,System.String)">
            <summary>
            Azure Key Vault authentication callback
            </summary>
            <param name="authority"></param>
            <param name="resource"></param>
            <param name="scope"></param>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.KeyVault.KeyVaultAuthenticator.UpdateAuthInfo(Microsoft.SqlServer.Dac.KeyVault.KeyVaultAuthInfoBase)">
            <summary>
            Passes a <see cref="T:Microsoft.SqlServer.Dac.KeyVault.KeyVaultAuthInfoBase"/> object to the KeyVaultAuthenticator, to support scenarios
            where a user changes authentication method, for instance by logging into a different Azure account
            </summary>
            <param name="authInfo"></param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.KeyVault.KeyVaultAuthenticator.InitializeAuthenticator">
            <summary>
            Gives the authenticator the opportunity to register with the core AlwaysEncrypted callstack. This is important
            in scenarios where Interactive authentication is being used and this is the global authenticator to be used in the application
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.KeyVault.KeyVaultAuthenticator.Validate(System.Collections.Generic.IList{System.String},System.Threading.CancellationToken)">
            <summary>
            Called before Dac operations that may cause data movement against a table with encrypted columns will occur,
            for instance deployment of a dacpac
            </summary>
            <param name="keyVaultUrls">
            A list of URLs representing every Key Vault referenced by column master keys, where the key is involved in a data motion
            operation. 
            </param>
            <param name="cancelToken"></param>
            <returns></returns>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.KeyVault.KeyVaultValidationResult">
            <summary>
            Result returned from a key vault validator. Indicates success or failure, and any 
            relevant error messages
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.KeyVault.KeyVaultValidationResult.#ctor">
            <summary>
            Default constructor
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.KeyVault.KeyVaultValidationResult.AddError(System.String)">
            <summary>
            Adds an error to the list of Validation errors
            </summary>
            <param name="message"></param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.KeyVault.KeyVaultValidationResult.IsValid">
            <summary>
            Was validation successful?
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.KeyVault.KeyVaultValidationResult.ValidationErrors">
            <summary>
            Errors that caused validation to fail, if any
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.NestedDeploymentPropertyAttribute">
            <summary>
            This class supports the product infrastructure and is not intended to be used directly 
            from your code.
            Indicates that a deployment property should be expanded for commandline property overriding
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.NestedDeploymentPropertyAttribute.#ctor">
            <summary>
            Default Constructor
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacExportOptions">
            <summary>
            Defines options that affect the behavior of package export from a database.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacExportOptions.#ctor">
            <summary>
            Construct a new instance of the <see cref="T:Microsoft.SqlServer.Dac.DacExportOptions"/> class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacExportOptions.CommandTimeout">
            <summary>
            Specifies the command timeout in seconds when executing queries against SQLServer.
            </summary>
            <value>
            The command timeout in seconds.
            Default is 60
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacExportOptions.Storage">
            <summary>
            Get the type of backing storage for the schema model used during extraction.
            </summary>
            <value>
            Enumeration value that specifies the type of backing storage for the schema model used during extraction.
            Default value is File.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacExportOptions.TargetEngineVersion">
            <summary>
            Specifies what the target engine version is expected to be. 
            This is used during export to define the allowed engine version to validate against
            and whether the features of the database match the capabilities of that engine version.
            </summary>
            <value>
            The latest version of Azure contains support for additional capabilities. When this value is
            <see cref="F:Microsoft.SqlServer.Dac.EngineVersion.Default"/> or <see cref="F:Microsoft.SqlServer.Dac.EngineVersion.V11"/>,
            the export operation will fail if the target database is found to contain any objects that
            require a newer engine version.
            
            The default value for this option is <see cref="F:Microsoft.SqlServer.Dac.EngineVersion.Latest"/>, which means that 
            validation will ensure that the export operation will only fail if the target database is 
            found to contain any objects that are not supported in the latest engine version.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacExportOptions.VerifyFullTextDocumentTypesSupported">
            <summary>
            Get or set boolean that specifies whether the supported full-text document types for Microsoft Azure SQL Database v12 should be verified.
            </summary>
            <value>
            True if the package should be verified; otherwise false.
            Default value is false.
            </value> 
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacImportOptions">
            <summary>
            Defines options that affect the behavior of package import to a database.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacImportOptions.#ctor">
            <summary>
            Construct a new instance of the <see cref="T:Microsoft.SqlServer.Dac.DacImportOptions"/> class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacImportOptions.ImportContributors">
            <summary>
            Specifies additional deployment contributors which should run.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacImportOptions.ImportContributorArguments">
            <summary>
            Specifies additional deployment contributor arguments.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacImportOptions.DatabaseSpecification">
            <summary>
            Defines optional parameters specific to a Microsoft Azure SQL Database.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacImportOptions.CommandTimeout">
            <summary>
            Specifies the command timeout in seconds when executing queries against SQLServer.
            </summary>
            <value>
            The command timeout in seconds.
            Default is 60
            </value>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacOperationProgressMessage">
            <summary>
             Progress message associated with the overal progress import or export operation.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacMessage">
            <summary>
            Data associated with an executing operation to report status updates or errors.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacMessage.ToString">
            <summary>
            Return a string that represents the current object.
            </summary>
            <returns>
            String that represents the current object.
            </returns>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacMessage.MessageType">
            <summary>
            Get the type of the event message.
            </summary>
            <value>
            Enumeration value that specifies the type of the event message.
            </value>
            <seealso cref="P:Microsoft.SqlServer.Dac.DacMessage.Message"/>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacMessage.Number">
            <summary>
            Get numeric value associated with the event message.
            </summary>
            <value>
            Numeric value associated with the message.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacMessage.Prefix">
            <summary>
            Get string prefix associated with the source of the event message.
            </summary>
            <value>
            String prefix associated with the source of the event message.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacMessage.Message">
            <summary>
            Get friendly message for the current status of an operation.
            </summary>
            <value>
            String message for the current status of an operation.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacOperationProgressMessage.Progress">
            <summary>
            Current progress in percent complete.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacDataProgressMessage">
            <summary>
             Data associated with an executing data operation to report status updates or errors related to progress.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDataProgressMessage.Progress">
            <summary>
            Current progress in percent complete.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDataProgressMessage.SchemaName">
            <summary>
            The schema name of the table whose progress is being reported.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDataProgressMessage.TableName">
            <summary>
            The name of the table whose progress is being reported.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacDeployOptions">
            <summary>
            Defines options that affect the behavior of package deployment to a database.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacDeployOptions.#ctor">
            <summary>
            Create a new instance of the <see cref="T:Microsoft.SqlServer.Dac.DacDeployOptions"/> class
            with default options.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacDeployOptions.EnableDnrOrdering(System.Boolean)">
            <summary>
            Interal mechanism to control deployment DNR ordering behavior
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacDeployOptions.#ctor(Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeploymentOptions)">
            <summary>
            Create a new instance of the <see cref="T:Microsoft.SqlServer.Dac.DacDeployOptions"/> class
            with specified options.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacDeployOptions.#ctor(Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeploymentOptions,System.Boolean)">
            <summary>
            Create a new instance of the <see cref="T:Microsoft.SqlServer.Dac.DacDeployOptions"/> class
            with specified options.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacDeployOptions.InitializeDefaults(Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeploymentOptions)">
            <summary>
            Initialize the expected defaults for this API.
            </summary>
            <remarks>
            Only defined where default values differ from the core defaults.
            When new options are added to SqlDeploymentOptions or a default value changed,
            all clients must determine if they must override the default.
            Redundantly specifying existing defaults doesn't reduce need for this
            process when adding options or changing defaults.  Unit tests should
            be employed to validating expectations for each deployment client
            that overrides default options (e.g. power-buffer, schema-compare, this api).
            When removing or renaming an option, the compiler will complain (good).
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.AdditionalDeploymentContributors">
            <summary>
            Specifies additional deployment contributors which should run - in addition
            to those specified in the dacpac.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.AdditionalDeploymentContributorArguments">
            <summary>
            Specifies additional deployment contributor arguments in addition to those already listed
            in the dacpac.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.AllowDropBlockingAssemblies">
            <summary>
            Get or set boolean that specifies whether CLR deployment will cause blocking assemblies to be dropped.
            </summary>
            <value>
            True to drop blocking assemblies during CLR deployment; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.AllowIncompatiblePlatform">
            <summary>
            Get or set boolean that specifies whether deployment will block due to platform compatibility.
            </summary>
            <value>
            True to block deployment to incompatible platforms; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.BackupDatabaseBeforeChanges">
            <summary>
            Get or set boolean that specifies whether a database backup will be performed before proceeding 
            with the actual deployment actions.
            </summary>
            <value>
            True to perform a database backup prior to deployment; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.BlockOnPossibleDataLoss">
            <summary>
            Get or set boolean that specifies whether deployment should stop if the operation could cause data loss.
            </summary>
            <value>
            True to stop deployment if possible data loss if detected; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.BlockWhenDriftDetected">
            <summary>
            Get or set boolean that specifies whether the system will check for differences between the 
            present state of the database and the registered state of the database and block deployment 
            if changes are detected.  Even if this option is set to true, drift detection will only occur 
            on a database if it was previously deployed with the <see cref="P:Microsoft.SqlServer.Dac.DacDeployOptions.RegisterDataTierApplication"/> option enabled.
            </summary>
            <value>
            True to error is drift is detected; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.CommandTimeout">
            <summary>
            Specifies the command timeout in seconds when executing queries against SQLServer.
            </summary>
            <value>
            The command timeout in seconds.
            Default is 60
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.CommentOutSetVarDeclarations">
            <summary>
            Get or set boolean that specifies whether the declaration of SQLCMD variables are commented 
            out in the script header.
            </summary>
            <value>
            True to comment out these declarations; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.CompareUsingTargetCollation">
            <summary>
            Get or set boolean that specifies whether the target collation will be used for identifier 
            comparison.
            </summary>
            <value>
            False to use the source collation; otherwise, true to use the target collation.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.CreateNewDatabase">
            <summary>
            Get or set boolean that specifies whether the existing database will be dropped
            and a new database created before proceeding with the actual deployment actions.
            Acquires single-user mode before dropping the existing database.
            </summary>
            <value>
            True to drop and re-create the database; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.DatabaseSpecification">
            <summary>
            Defines optional parameters specific to a Microsoft Azure SQL Database.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.DeployDatabaseInSingleUserMode">
            <summary>
            Get or set boolean that specifies whether the system will acquire single-user mode on the target
            database during the duration of the deployment operation.
            </summary>
            <value>
            True to acquire single-user mode during deployment; otherwise, false.
            Default is false.
            </value>
            <remarks>
            The database will be returned to multi-user mode after all changes are applied.
            Database may remain in single-user mode if an error occurs during execution.
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.DisableAndReenableDdlTriggers">
            <summary>
            Get or set boolean that specifies if all DDL triggers will be disabled for the duration of the 
            deployment operation and then re-enabled after all changes are applied.  
            </summary>
            <value>
            True to disable DDL triggers during deployment; otherwise, false.
            Default is true.
            </value>
            <remarks>
            Triggers may remain disabled if an error occurs during execution.
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.DoNotAlterChangeDataCaptureObjects">
            <summary>
            Get or set boolean that specifies whether items configured for Change Data Capture (CDC)
            should be altered during deployment.  
            </summary>
            <value>
            True to not alter objects configured for CDC; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.DoNotAlterReplicatedObjects">
            <summary>
            Get or set boolean that specifies whether items configured for Replication
            should be altered during deployment.  
            </summary>
            <value>
            True to not alter objects configured for Replication; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.DoNotDropObjectTypes">
            <summary>
            Get or set a collection of object types that will not be dropped from the target when
            no corresponding object exists in the source. Note that dropping and recreating objects
            of the specified type may still be necessary due to dependencies from other objects.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.DropConstraintsNotInSource">
            <summary>
            Get or set boolean that specifies whether to drop all constraints that do not
            exist in the source model.  
            </summary>
            <value>
            True to drop constraints not in the source model; otherwise, false.
            Default is true.
            </value>
            <remarks>
            This applies to check, default, foreign key, primary key, and unique constraints.
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.DropDmlTriggersNotInSource">
            <summary>
            Get or set boolean that specifies whether to drop all DML triggers that do not
            exist in the source model.
            </summary>
            <value>
            True to drop DML triggers not in the source model; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.DropExtendedPropertiesNotInSource">
            <summary>
            Get or set boolean that specifies whether to drop all extended properties that do 
            not exist in the source model.
            </summary>
            <value>
            True to drop extended properties not in the source model; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.DropIndexesNotInSource">
            <summary>
            Get or set boolean that specifies whether to drop all indexes that do not
            exist in the source model.
            </summary>
            <value>
            True to drop indexes not in the source model; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.DropObjectsNotInSource">
            <summary>
            Get or set boolean that specifies whether objects that exist in the target but not source should be dropped during deployment.
            </summary>
            <value>
            True if objects that exist in the target but not source should be dropped; otherwise false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.DropPermissionsNotInSource">
            <summary>
            Get or set boolean that specifies whether to drop all permissions that do not
            exist in the source model.
            </summary>
            <value>
            True to drop permissions not in the source model; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.DropRoleMembersNotInSource">
            <summary>
            Get or set boolean that specifies whether to drop all role memberships that do not
            exist in the source model.
            </summary>
            <value>
            True to drop role memberships not in the source model; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.DropStatisticsNotInSource">
            <summary>
            Get or set boolean that specifies whether to drop all role memberships that do not
            exist in the source model.
            </summary>
            <value>
            True to drop role memberships not in the source model; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.GenerateSmartDefaults">
            <summary>
            Get or set boolean that specifies whether default values should be generated to populate NULL columns that are constrained to NOT NULL values.
            </summary>
            <value>
            True if default values should be generated; otherwise false.
            Default is false.
            </value>
            <remarks>
            This is useful when needing to add a new NOT NULL column to an existing table with data.
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreAnsiNulls">
            <summary>
            Get or set boolean that specifies whether to exclude the ANSI_NULL option from 
            consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the ANSI_NULL option; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreAuthorizer">
            <summary>
            Get or set boolean that specifies whether to exclude the AUTHORIZATION option from 
            consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the AUTHORIZATION option; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreColumnCollation">
            <summary>
            Get or set boolean that specifies whether to exclude the collation specifier from 
            consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the collation specifier; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreColumnOrder">
            <summary>
            Get or set boolean that specifies whether to exclude from consideration 
            the order of columns in tables when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in column order; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreComments">
            <summary>
            Get or set boolean that specifies whether to exclude comments from 
            consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in comments; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreCryptographicProviderFilePath">
            <summary>
            Get or set boolean that specifies whether to exclude the file specification 
            of a cryptographic provider from consideration when comparing the source and 
            target model.
            </summary>
            <value>
            True to ignore differences in a cryptographic provider's  file specification; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreDdlTriggerOrder">
            <summary>
            Get or set boolean that specifies whether to exclude DDL trigger order from 
            consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in DDL trigger order; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreDdlTriggerState">
            <summary>
            Get or set boolean that specifies whether to exclude DDL trigger state from 
            consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in DDL trigger state; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreDefaultSchema">
            <summary>
            Get or set boolean that specifies whether to exclude the DEFAULT_SCHEMA option from 
            consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the DEFAULT_SCHEMA options; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreDmlTriggerOrder">
            <summary>
            Get or set boolean that specifies whether to exclude DML trigger order from 
            consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in DDL trigger order; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreDmlTriggerState">
            <summary>
            Get or set boolean that specifies whether to exclude DML trigger state from 
            consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in DML trigger state; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreExtendedProperties">
            <summary>
            Get or set boolean that specifies whether to exclude all extended properties from 
            consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in extended properties; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreFileAndLogFilePath">
            <summary>
            Get or set boolean that specifies whether to exclude the FILENAME option of 
            FILE objects from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the FILENAME option of FILE objects; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreFilegroupPlacement">
            <summary>
            Get or set boolean that specifies whether to exclude the filegroup specifier 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the filegroup specifier; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreFileSize">
            <summary>
            Get or set boolean that specifies whether to exclude the SIZE option of FILE objects 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the SIZE option of FILE objects; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreFillFactor">
            <summary>
            Get or set boolean that specifies whether to exclude the FILLFACTOR option
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the FILLFACTOR option; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreFullTextCatalogFilePath">
            <summary>
            Get or set boolean that specifies whether to exclude the path specification of 
            FULLTEXT CATALOG objects from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the path specification of FULLTEXT CATALOG objects; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreIdentitySeed">
            <summary>
            Get or set boolean that specifies whether to exclude the seed value of IDENTITY columns 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the seed value of IDENTITY columns; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreIncrement">
            <summary>
            Get or set boolean that specifies whether to exclude the increment value of IDENTITY columns 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the increment value of IDENTITY columns; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreIndexOptions">
            <summary>
            Get or set boolean that specifies whether to exclude differences in index options 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in index options; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreIndexPadding">
            <summary>
            Get or set boolean that specifies whether to exclude the PAD_INDEX option 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the PAD_INDEX option; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreKeywordCasing">
            <summary>
            Get or set boolean that specifies whether to exclude difference in the casing of keywords 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in the casing of keywords; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreLockHintsOnIndexes">
            <summary>
            Get or set boolean that specifies whether to exclude the ALLOW_ROW_LOCKS and 
            ALLOW_PAGE_LOGKS options from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore the ALLOW_ROW_LOCKS and ALLOW_PAGE_LOGKS options; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreLoginSids">
            <summary>
            Get or set boolean that specifies whether to exclude the SID option of the LOGIN object 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore the SID option of the LOGIN object; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.ExcludeObjectTypes">
            <summary>
            Get or set a collection of object types to exclude from consideration when
            comparing the source and target model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreNotForReplication">
            <summary>
            Get or set boolean that specifies whether to exclude the NOT FOR REPLICATION option 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore the NOT FOR REPLICATION option; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreObjectPlacementOnPartitionScheme">
            <summary>
            Get or set boolean that specifies whether to exclude the partition scheme object
            from consideration when comparing the source and target model for the following
            objects: Table, Index, Unique Key, Primary Key, and Queue.
            </summary>
            <value>
            True to ignore partition schemes; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnorePartitionSchemes">
            <summary>
            Get or set boolean that specifies whether to exclude the parameter type and 
            boundary VALUES of a PARTITION FUNCTION from consideration when comparing the 
            source and target model.  Also excludes FILEGROUP and partition function of a 
            PARTITION SCHEMA from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore aspects of partition functions and schemes; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnorePermissions">
            <summary>
            Get or set boolean that specifies whether to exclude all permission statements 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore all permission statements; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreQuotedIdentifiers">
            <summary>
            Get or set boolean that specifies whether to exclude the QUOTED_IDENTIFIER option 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore the QUOTED_IDENTIFIER option; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreRoleMembership">
            <summary>
            Get or set boolean that specifies whether to exclude all ROLE MEMBERSHIP objects 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore ROLE MEMBERSHIP objects; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreRouteLifetime">
            <summary>
            Get or set boolean that specifies whether to exclude the LIFETIME option of ROUTE objects 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore the LIFETIME option of ROUTE objects; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreSemicolonBetweenStatements">
            <summary>
            Get or set boolean that specifies whether to exclude the existence or absence of semi-colons 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore semi-colons; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreTableOptions">
            <summary>
            Get or set boolean that specifies whether the options on the target table are updated 
            to match the source table.
            </summary>
            <value>
            True to ignore difference in table options and not update the target table; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreUserSettingsObjects">
            <summary>
            Get or set boolean that specifies whether to exclude user settings 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences in user settings; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreWhitespace">
            <summary>
            Get or set boolean that specifies whether to exclude whitespace 
            from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore differences whitespace; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreWithNocheckOnCheckConstraints">
            <summary>
            Get or set boolean that specifies whether to exclude the CHECK|NO CHECK option of a CHECK 
            constraint object from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore the CHECK|NO CHECK option of a CHECK constraint object; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IgnoreWithNocheckOnForeignKeys">
            <summary>
            Get or set boolean that specifies whether to exclude the CHECK|NO CHECK option of a FOREIGN KEY  
            constraint object from consideration when comparing the source and target model.
            </summary>
            <value>
            True to ignore the CHECK|NO CHECK option of a FOREIGN KEY constraint object; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.AllowUnsafeRowLevelSecurityDataMovement">
            <summary>
            Get or set boolean that specifies whether to ignore blocking data motion on RLS enabled tables
            </summary>
            <value>
            True to ignore block on data motion when Row level security is enabled on a table
            Default is false i.e. data motion is blocked with RLS by default.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IncludeCompositeObjects">
            <summary>
            Get or set boolean that specifies whether to include referenced, external elements that also 
            compose the source model and then update the target database in a single deployment operation.
            </summary>
            <value>
            True to include composite objects; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.IncludeTransactionalScripts">
            <summary>
            Get or set boolean that specifies whether to use transations during the deployment operation 
            and commit the transaction after all changes are successfully applied.
            </summary>
            <value>
            True to use transactions during deployment; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.NoAlterStatementsToChangeClrTypes">
            <summary>
            Get or set boolean that specifies whether to force a change to CLR assemblies by dropping and recreating them.
            </summary>
            <value>
            True if CLR assemblies should be dropped; otherwise false to allow ALTER statements to change CLR assemblies.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.PopulateFilesOnFileGroups">
            <summary>
            Get or set boolean that specifies whether files are supplied for filegroups defined in the deployment source.
            </summary>
            <value>
            True to specify files for filegroups; otherwise false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.RegisterDataTierApplication">
            <summary>
            Get or set boolean that specifies whether the database will be registered as a Data-Tier Application.  
            If the target database is already a registered Data-Tier Application, then the registration will be updated.
            </summary>
            <value>
            True to register the database as a Data-Tier Application; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.RunDeploymentPlanExecutors">
            <summary>
            Specifies whether DeploymentPlanExecutor contributors should be run when other operations are executed.
            Default is false.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.ScriptDatabaseCollation">
            <summary>
            Get or set boolean that specifies whether the target database should be altered to match the 
            source model's collation.
            </summary>
            <value>
            True to alter the target database's collation; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.ScriptDatabaseCompatibility">
            <summary>
            Get or set boolean that specifies whether the target database should be altered to match the 
            source model's compatibility level.
            </summary>
            <value>
            True to alter the target database's compatibility level; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.ScriptDatabaseOptions">
            <summary>
            Get or set boolean that specifies whether the database options in the target database should 
            be updated to match the source model.
            </summary>
            <value>
            True to alter the target database's options; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.ScriptDeployStateChecks">
            <summary>
            Get or set boolean that specifies whether the target database should be checked to ensure that 
            it exists, is online and can be updated.
            </summary>
            <value>
            True to perform state checks on the target database; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.ScriptFileSize">
            <summary>
            Get or set boolean that specifies whether a file size is specified when adding files to file groups.
            </summary>
            <value>
            True to specify a file size when adding files to file groups; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.ScriptNewConstraintValidation">
            <summary>
            Get or set boolean that specifies whether constraints are validated after all changes are applied.
            </summary>
            <value>
            True to validate check constraints; otherwise, false.
            Default is true.
            </value>
            <remarks>
            Constraints are always added with NOCHECK option; as a result their validation is skipped during creation.
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.ScriptRefreshModule">
            <summary>
            Get or set boolean that specifies whether referencing procedures are refreshed when referenced objects are updated.
            </summary>
            <value>
            True to refresh referencing procedures; otherwise false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.TreatVerificationErrorsAsWarnings">
            <summary>
            Get or set boolean that specifies whether to treat errors that occur during publish verification as warnings. 
            The check is performed against the generated deployment plan before the plan is executed against the target database. 
            Plan verification detects problems, such as the loss of target-only objects (for example, indexes), that must be 
            dropped to make a change. Verification also detects situations where dependencies (such as tables or views) exist 
            because of a reference to a composite project, but do not exist in the target database. You might choose to treat 
            verification errors as warnings to get a complete list of issues instead of allowing the publish 
            action to stop when the first error occurs.
            </summary>
            <value>
            True to treat errors as warnings; otherwise, false.
            Default is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.UnmodifiableObjectWarnings">
            <summary>
            Get or set boolean that specifies whether warnings should be generated when differences are found 
            in objects that cannot be modified, for example, if the file size or file paths were different for a file.
            </summary>
            <value>
            True to generate warnings; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.VerifyCollationCompatibility">
            <summary>
            Get or set boolean that specifies whether deployment will verify that the collation specified in the 
            source model is compatible with the collation specified in the target model.
            </summary>
            <value>
            True to continue if errors are generated during plan verification; otherwise, false.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.VerifyDeployment">
            <summary>
            Get or set boolean that specifies whether the plan verification phase is executed or not.
            </summary>
            <value>
            True to perform plan verification; otherwise, false to skip it.
            Default is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacDeployOptions.SqlCommandVariableValues">
            <summary>
            Get dictionary of SQL command variable values, keyed by variable name.
            </summary>
            <value>
            Dictionary of SQL command variable values, keyed by variable name.
            </value>
            <remarks>
            Valid values must be provided for every variable before deployment, or failures may occur during deployment.
            </remarks>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacErrorResources">
            <summary>
              A strongly-typed resource class, for looking up localized strings, etc.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ResourceManager">
            <summary>
              Returns the cached ResourceManager instance used by this class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.Culture">
            <summary>
              Overrides the current thread's CurrentUICulture property for all
              resource lookups using this strongly typed resource class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.BacpacShouldNotContainDeploymentScripts">
            <summary>
              Looks up a localized string similar to BACPAC should not contain either pre-deployment or post-deployment scripts..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.CannotWriteToPackage">
            <summary>
              Looks up a localized string similar to Cannot apply updates to a package loaded for read only..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ConflictingExtendedPropertyDropSetting">
            <summary>
              Looks up a localized string similar to DropExtendedPropertiesNotInSource conflicts with the selected DoNotDropObjectType ExtendedProperties.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ConflictingPermissionsDropSetting">
            <summary>
              Looks up a localized string similar to DropPermissionsNotInSource conflicts with the selected DoNotDropObjectType Permissions.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ConflictingRoleMembershipDropSetting">
            <summary>
              Looks up a localized string similar to DropRoleMembersNotInSource conflicts with the selected DoNotDropObjectType RoleMembership.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.DacMessageFormat">
            <summary>
              Looks up a localized string similar to {0} {1}{2}: {3}.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ElementValidationFailureMessage">
            <summary>
              Looks up a localized string similar to Error validating element {0}: {1}.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorAttemptToUpgradeExistingDatabase">
            <summary>
              Looks up a localized string similar to Cannot deploy to existing database when upgrading has been disabled..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorBacpacValidationFailed">
            <summary>
              Looks up a localized string similar to Validation of the schema model for data package failed. Check the inner exception for details..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorCannotOpenBacPackageWithoutData">
            <summary>
              Looks up a localized string similar to Cannot create a BACPAC from a file that does not contain exported data..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorCannotOpenDacPackageWithData">
            <summary>
              Looks up a localized string similar to Cannot create a DAC package from a file that contains exported data..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorConnectingToDatabase">
            <summary>
              Looks up a localized string similar to Could not connect to database server..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorContainingUnsupportedFullTextDocumentTypesForAzureV12">
            <summary>
              Looks up a localized string similar to Indexing for document type {0} is not supported on {1}..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorCouldNotDetermineExistenceOfDatabase">
            <summary>
              Looks up a localized string similar to Unable to determine the existence of database &apos;{0}&apos;. You must have a user with the same password in master or database &apos;{0}&apos;..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorCouldNotDetermineProviderFromPackage">
            <summary>
              Looks up a localized string similar to Could not determine SQL platform from package..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorCouldNotDetermineServerVersion">
            <summary>
              Looks up a localized string similar to Database source is not a supported version of SQL Server {0}: {1}..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorDataTableNotFound">
            <summary>
              Looks up a localized string similar to Table with schema &quot;{0}&quot; and name &quot;{1}&quot; was specified for data import or export, but does not exist in the database schema..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorDeletingFile">
            <summary>
              Looks up a localized string similar to An error occurred when deleting file &apos;{0}&apos;.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorDeployingPackage">
            <summary>
              Looks up a localized string similar to Could not deploy package..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorExportingPackage">
            <summary>
              Looks up a localized string similar to Could not export schema and data from database..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorExtractAllTableDataTrueAndTablesNotNull">
            <summary>
              Looks up a localized string similar to Argument &apos;ExtractAllTableData&apos; has an invalid value:&apos;true&apos;. &apos;ExtractAllTableData&apos; cannot be &apos;true&apos; because individual user tables are also specified using the &apos;TableData&apos; argument. Set &apos;ExtractAllTableData&apos; to &apos;false&apos; to extract data from the specified user tables..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorExtractingFromFileTable">
            <summary>
              Looks up a localized string similar to Extracting data from FileTable {0}.{1} is not supported..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorExtractingPackageFromDatabase">
            <summary>
              Looks up a localized string similar to Could not extract package from specified database..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorForeignKeyCannotReferenceTable">
            <summary>
              Looks up a localized string similar to Foreign key {0} cannot reference table {1} when used as part of a data package..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorFoundUnsupportedElementsForDataPackage">
            <summary>
              Looks up a localized string similar to One or more unsupported elements were found in the schema used as part of a data package..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorGeneratingDeploymentReport">
            <summary>
              Looks up a localized string similar to Could not generate deployment report..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorGeneratingDeploymentResults">
            <summary>
              Looks up a localized string similar to Could not generate deployment results..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorGeneratingDeploymentScript">
            <summary>
              Looks up a localized string similar to Could not generate deployment script..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorGeneratingDriftReport">
            <summary>
              Looks up a localized string similar to Could not generate drift report..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorImportingPackage">
            <summary>
              Looks up a localized string similar to Could not import package..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorInvalidPropertyName">
            <summary>
              Looks up a localized string similar to The property {0} specified is not present in the resource {1}..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorLoadingConstraints">
            <summary>
              Looks up a localized string similar to Error loading constraint information from target database.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorLoadingPackage">
            <summary>
              Looks up a localized string similar to Could not load package..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorLoadingPackageFrom">
            <summary>
              Looks up a localized string similar to Could not load package from &apos;{0}&apos;..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorReadingDacMetadataFromPackage">
            <summary>
              Looks up a localized string similar to Could not load data-tier application metadata from package..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorReadingFromFile">
            <summary>
              Looks up a localized string similar to An error occurred reading the contents of file &apos;{0}&apos;.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorReadingModelFromPackage">
            <summary>
              Looks up a localized string similar to Could not load schema model from package..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorReadingModelHeader">
            <summary>
              Looks up a localized string similar to Could not read schema model header information from package..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorReadingProfile">
            <summary>
              Looks up a localized string similar to Could not read profile properties: {0}.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorReadingProfileProperties">
            <summary>
              Looks up a localized string similar to Could not read profile properties: {0}.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorReadingScriptFromPackage">
            <summary>
              Looks up a localized string similar to Could not load script from package..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorRegisteringApplication">
            <summary>
              Looks up a localized string similar to Could not register DAC information..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorSavingPackage">
            <summary>
              Looks up a localized string similar to Could not save package to file..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorStreamDoesNotSupportReading">
            <summary>
              Looks up a localized string similar to Stream does not support reading..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorStreamDoesNotSupportSeeking">
            <summary>
              Looks up a localized string similar to Stream does not support seeking..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorStreamDoesNotSupportWriting">
            <summary>
              Looks up a localized string similar to Stream does not support writing..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorTranslatingPackage">
            <summary>
              Looks up a localized string similar to Could not translate package..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorUnpacking_FileExists">
            <summary>
              Looks up a localized string similar to Cannot unpack to the same location twice. The file &apos;{0}&apos; already exists in the unpack directory.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorUnpackingPackage">
            <summary>
              Looks up a localized string similar to Could not unpack the package..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorUnregisteringApplication">
            <summary>
              Looks up a localized string similar to Could not unregister DAC information..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorUnsupportedClrElementForDataPackage">
            <summary>
              Looks up a localized string similar to Element {0} is an unsupported CLR element that is not allowed when used as part of a data package..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorUnsupportedContainedUserElementForDataPackage">
            <summary>
              Looks up a localized string similar to Element {0} is a contained user that is not supported when used as a part of a data package..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorUnsupportedElementForDataPackage">
            <summary>
              Looks up a localized string similar to The element {0} is not supported when used as part of a data package (.bacpac file)..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorUnsupportedElementPropertyForDataPackage">
            <summary>
              Looks up a localized string similar to Element {0} has an unsupported property {1} set and is not supported when used as part of a data package..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorUnsupportedFileStreamColumnForDataPackage">
            <summary>
              Looks up a localized string similar to Element {0} is an unsupported FILESTREAM column that is not allowed when used as part of a data package..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorUnsupportedMultiPartNameForSynonym">
            <summary>
              Looks up a localized string similar to {0} is not supported on Microsoft Azure SQL Database as it aliases the external element {1}..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorUnsupportUserDefinedTypeColumnForDataPackage">
            <summary>
              Looks up a localized string similar to Element {0} is an unsupported CLR User-defined type column that is not allowed when used as part of a data package..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorUpdatingDacHistory">
            <summary>
              Looks up a localized string similar to Could not update the dac history table..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorValidationFailed">
            <summary>
              Looks up a localized string similar to Validation of the schema model for data package failed..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ErrorVerifyingDeploymentPlan">
            <summary>
              Looks up a localized string similar to Verification of the deployment plan failed..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ExportedRowsMayBeIncomplete">
            <summary>
              Looks up a localized string similar to The row-level security policies of this database restrict some users&apos; ability to access data in these tables: &apos;{0}&apos;. Please verify that the credentials you&apos;re using have sufficient privileges to access all the data in these tables..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ExportedRowsMayContainSomeMaskedData">
            <summary>
              Looks up a localized string similar to The database permissions may restrict the ability of some users&apos; to see the actual data contained in these tables: &apos;{0}&apos;. Please verify that the credentials you&apos;re using have sufficient privileges to see all data unmasked..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.InvalidArgumentValue">
            <summary>
              Looks up a localized string similar to {0} is not a valid value for {1}..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.InvalidModelHeaderData">
            <summary>
              Looks up a localized string similar to The model header data from the package &apos;{0}&apos; is invalid..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.NoKeyVaultAuthenticatorFound">
            <summary>
              Looks up a localized string similar to Cannot proceed as Key Vault support is not present in the current application. For Key Vault support during deployment, install DacFramework.msi and run SqlPackage.exe from its install location..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.PackagingModelFailed">
            <summary>
              Looks up a localized string similar to Packaging the model failed..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ReferencedPackageDoesnotExist">
            <summary>
              Looks up a localized string similar to The referenced package &apos;{0}&apos; doesn&apos;t exist..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ScriptRequiresOneOfTwoOptions">
            <summary>
              Looks up a localized string similar to At least one of the options {0} or {1} must be enabled..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.TranslatingModelFailed">
            <summary>
              Looks up a localized string similar to Translating the model failed..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.UnknownPackageVersion">
            <summary>
              Looks up a localized string similar to The version of the supplied package, {0}, is incompatible with this version of the DAC Framework..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacErrorResources.ValidatingTheModelAgainstTargetPlatformFailed">
            <summary>
              Looks up a localized string similar to Validating the model against target platform failed..
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacExceptionMessage">
            <summary>
            Data associated with an error with exception information.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacExceptionMessage.Exception">
            <summary>
            Get exception associated with the event message.
            </summary>
            <value>
            Exception object associated with the message.
            </value>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacAzureEdition">
            <summary>
            List of possible editions for a Microsoft Azure SQL Database
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.DacAzureEdition.Web">
            <summary>
            CREATE DATABASE database_name EDITION = <b>'web'</b>
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.DacAzureEdition.Business">
            <summary>
            CREATE DATABASE database_name EDITION = <b>'business'</b>
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.DacAzureEdition.Basic">
            <summary>
            CREATE DATABASE database_name EDITION = <b>'basic'</b>
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.DacAzureEdition.Standard">
            <summary>
            CREATE DATABASE database_name EDITION = <b>'standard'</b>
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.DacAzureEdition.Premium">
            <summary>
            CREATE DATABASE database_name EDITION = <b>'premium'</b>
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.DacAzureEdition.PremiumRS">
            <summary>
            CREATE DATABASE database_name EDITION = <b>'premiumRS'</b>
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.DacAzureEdition.Default">
            <summary>
            CREATE DATABASE database_name
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacAzureDatabaseSpecification">
            <summary>
            Defines optional parameters specific to a Microsoft Azure SQL Database
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacAzureDatabaseSpecification.#ctor">
            <summary>
            Default constructor
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacAzureDatabaseSpecification.Edition">
            <summary>
            Database Edition
            </summary>
            <remarks>
            CREATE DATABASE database_name  [ COLLATE collation_name ]
            {
               ({edition_options} [, ...n]) 
            }
            
            {edition_options} ::= 
            {
               (MAXSIZE = { 100 MB | 500 MB | 1 | 5 | 10 | 20 | 30 ... 150 ... 500 } GB
                |<b>(EDITION = {'web' | 'business' | 'basic' | 'standard' | 'premium' | 'premiumRS'})</b>
                |<b>(SERVICE_OBJECTIVE = { 'shared' | 'basic' | 'S0' | 'S1' | 'S2' | 'S3' | 'P1' | 'P2' | 'P3' | 'P4' | 'P6' | 'P11' | 'P15' | 'PRS1' | 'PRS2' | 'PRS4' | 'PRS6' })</b>
            }
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacAzureDatabaseSpecification.MaximumSize">
            <summary>
            Maximum size, in GB
            </summary>
            <remarks>
            CREATE DATABASE database_name  [ COLLATE collation_name ]
            {
               ({edition_options} [, ...n]) 
            }
            
            {edition_options} ::= 
            {
               <b>(MAXSIZE = { 100 MB | 500 MB | 1 | 5 | 10 | 20 | 30 ... 150 ... 500 } GB</b>
                |(EDITION = {'web' | 'business' | 'basic' | 'standard' | 'premium' | 'premiumRS'})
                |(SERVICE_OBJECTIVE = { 'shared' | 'basic' | 'S0' | 'S1' | 'S2' | 'S3' | 'P1' | 'P2' | 'P3' | 'P4' | 'P6' | 'P11' | 'P15' | 'PRS1' | 'PRS2' | 'PRS4' | 'PRS6' })
            }
            </remarks>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacAzureDatabaseSpecification.ServiceObjective">
            <summary>
            Database Performance Level
            </summary>
            <remarks>
            CREATE DATABASE database_name  [ COLLATE collation_name ]
            {
               ({edition_options} [, ...n]) 
            }
            
            {edition_options} ::= 
            {
               (MAXSIZE = { 100 MB | 500 MB | 1 | 5 | 10 | 20 | 30 ... 150 ... 500 } GB  
                |(EDITION = {'web' | 'business' | 'basic' | 'standard' | 'premium' | 'premiumRS'})
                |<b>(SERVICE_OBJECTIVE = { 'shared' | 'basic' | 'S0' | 'S1' | 'S2' | 'S3' | 'P1' | 'P2' | 'P3' | 'P4' | 'P6' | 'P11' | 'P15' | 'PRS1' | 'PRS2' | 'PRS4' | 'PRS6' })</b>
            }
            </remarks>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacExtractOptions">
            <summary>
            Defines options that affect the behavior of package extraction.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacExtractOptions.#ctor">
            <summary>
            Construct a new instance of the <see cref="T:Microsoft.SqlServer.Dac.DacExtractOptions"/> class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacExtractOptions.CommandTimeout">
            <summary>
            Specifies the command timeout in seconds when executing queries against SQLServer.
            </summary>
            <value>
            The command timeout in seconds.
            Default is 60
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacExtractOptions.ExtractAllTableData">
            <summary>
            Get or set boolean that specifies whether data for all user tables will be extracted.
            </summary>
            <value>
            True if data for all user tables will be extracted; otherwise false.
            Default value is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacExtractOptions.ExtractReferencedServerScopedElements">
            <summary>
            Get or set boolean that specifies whether server-scoped elements referenced by the source should be extracted.
            </summary>
            <value>
            True if references server-scoped elements should be extracted; otherwise false.
            Default value is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacExtractOptions.ExtractApplicationScopedObjectsOnly">
            <summary>
            Get or set boolean that specifies the scope of objects extracted from the source.
            </summary>
            <value>
            True if only application-scoped objects should be extracted;
            otherwise false to extract all object types.
            Default value is true.
            </value>        
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacExtractOptions.IgnoreExtendedProperties">
            <summary>
            Get or set boolean that specifies whether extended properties should be ignored.
            </summary>
            <value>
            True if extended properties will be ignored; otherwise false.
            Default value is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacExtractOptions.IgnorePermissions">
            <summary>
            Get or set boolean that specifies whether permissions should be ignored.
            </summary>
            <value>
            True if permissions will be ignored; otherwise false.
            Default value is true.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacExtractOptions.IgnoreUserLoginMappings">
            <summary>
            Get or set boolean that specifies whether mappings between users and logins should be extracted from the source.
            </summary>
            <value>
            True if user login mappings will be ignored; otherwise false.
            Default value is false.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacExtractOptions.Storage">
            <summary>
            Get the type of backing storage for the schema model used during extraction.
            </summary>
            <value>
            Enumeration value that specifies the type of backing storage for the schema model used during extraction.
            Default value is File.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacExtractOptions.VerifyExtraction">
            <summary>
            Get or set boolean that specifies whether the extracted package should be verified.
            </summary>
            <value>
            True if the package should be verified; otherwise false.
            Default value is false.
            </value> 
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacExtractOptions.ExtractUsageProperties">
            <summary>
            Usage properties include Table.RowCount, Table.IndexSize, Table.DataSize, Table.UsedPages and Table.DataPages.
            When true, these properties are extracted from the database and are accessible in the model.
            </summary>
            <value>
            True if usage properties will be extracted; otherwise false.
            Default value is false.
            </value>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacMessageEventArgs">
            <summary>
            Data associated with event raised as an executing operation reports status updates or errors.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacMessageEventArgs.Message">
            <summary>
            Message information associated with this event instance.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacMessageType">
            <summary>
            Specifies the type (or severity) of message associated with a given event.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.DacMessageType.Message">
            <summary>
            Informational message.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.DacMessageType.Warning">
            <summary>
            Noncritical problem.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.DacMessageType.Error">
            <summary>
            Serious, possibly fatal issue.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacOperationStatus">
            <summary>
            Specifies the state of a service operation.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.DacOperationStatus.Pending">
            <summary>
            Operation has not yet started.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.DacOperationStatus.Running">
            <summary>
            Operation is executing.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.DacOperationStatus.Completed">
            <summary>
            Operation has finished execution.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.DacOperationStatus.Faulted">
            <summary>
            Operation did not complete execution.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.DacOperationStatus.Cancelled">
            <summary>
            Operation was cancelled.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacPackage">
            <summary>
            Representation of the artifact that contains the definition of a data-tier application.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacPackage.Dispose">
            <summary>
            Release the resources held by this instance.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacPackage.Unpack(System.String)">
            <summary>
            Place the contents of this package into the directory specified by <paramref name="directoryPath"/>.
            </summary>
            <param name="directoryPath">
            Base directory in which to place the package contents.
            </param>
            <exception cref="T:System.ArgumentException">
            If <paramref name="directoryPath"/> is a null reference or empty string.
            </exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If an error occurs while attempting to unpack the package.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacPackage.Unpack(Microsoft.SqlServer.Dac.IPackageSource,System.String)">
            <summary>
            Place the contents of this package into the directory specified by <paramref name="directoryPath"/>.
            </summary>
            <param name="packageSource">
            Object used to access package content.
            </param>
            <param name="directoryPath">
            Base directory in which to place the package contents.
            </param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacPackage.Load(System.String)">
            <summary>
            Load a package file specified by <paramref name="fileName"/>.
            </summary>
            <param name="fileName">
            Path to the package file.
            </param>
            <returns>
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> instance that represents the package loaded from the specified file.
            </returns>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If there is a problem reading the package; or if the package contains exported data.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacPackage.Load(System.String,Microsoft.SqlServer.Dac.DacSchemaModelStorageType)">
            <summary>
            Load a package file specified by <paramref name="fileName"/>.
            </summary>
            <param name="fileName">
            Path to the package file.
            </param>
            <param name="modelStorageType">
            Backing storage type for package instance.
            </param>
            <returns>
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> instance that represents the package loaded from the specified file.
            </returns>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If there is a problem reading the package; or if the package contains exported data.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacPackage.Load(System.String,Microsoft.SqlServer.Dac.DacSchemaModelStorageType,System.IO.FileAccess)">
            <summary>
            Load a package file specified by <paramref name="fileName"/>.
            </summary>
            <param name="fileName">
            Path to the package file.
            </param>
            <param name="modelStorageType">
            Backing storage type for package instance.
            </param>
            <param name="packageAccess">
            The access in which to open the package. Valid values are <see cref="F:System.IO.FileAccess.Read"/> or <see cref="F:System.IO.FileAccess.ReadWrite"/>.
            </param>
            <returns>
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> instance that represents the package loaded from the specified file.
            </returns>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If there is a problem reading the package; or if the package contains exported data.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacPackage.Load(System.IO.Stream)">
            <summary>
            Load a package from the specified <see cref="T:System.IO.Stream"/>.
            </summary>
            <param name="stream">
            Stream from which to read the package.
            </param>
            <returns>
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> instance that represents the package loaded from the specified <see cref="T:System.IO.Stream"/>.
            </returns>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If there is a problem reading the package; or if the package contains exported data.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacPackage.Load(System.IO.Stream,Microsoft.SqlServer.Dac.DacSchemaModelStorageType)">
            <summary>
            Load a package from the specified <see cref="T:System.IO.Stream"/>.
            </summary>
            <param name="stream">
            Stream from which to read the package.
            </param>
            <param name="modelStorageType">
            Backing storage type for package instance.
            </param>
            <returns>
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> instance that represents the package loaded from the specified <see cref="T:System.IO.Stream"/>.
            </returns>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If there is a problem reading the package; or if the package contains exported data.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacPackage.Load(System.IO.Stream,Microsoft.SqlServer.Dac.DacSchemaModelStorageType,System.IO.FileAccess)">
            <summary>
            Load a package from the specified <see cref="T:System.IO.Stream"/>.
            </summary>
            <param name="stream">
            Stream from which to read the package.
            </param>
            <param name="modelStorageType">
            Backing storage type for package instance.
            </param>
            <param name="packageAccess">
            The access in which to open the package. Valid values are <see cref="F:System.IO.FileAccess.Read"/> or <see cref="F:System.IO.FileAccess.ReadWrite"/>.
            </param>
            <returns>
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> instance that represents the package loaded from the specified <see cref="T:System.IO.Stream"/>.
            </returns>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If there is a problem reading the package; or if the package contains exported data.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacPackage.Save(System.IO.Stream,Microsoft.Data.Tools.Schema.SchemaModel.DataSchemaModel,Microsoft.Data.Tools.Schema.Sql.Dac.DacMetadata,System.Nullable{System.UInt32})">
            <summary>
            Write package with the supplied schema model and DAC metadata to the supplied <see cref="T:System.IO.Stream"/>.
            </summary>
            <param name="stream">
            <see cref="T:System.IO.Stream"/> to which to write the package.
            </param>
            <param name="model">
            Schema model to be serialized into package.
            </param>
            <param name="metadata">
            DAC metadata to be serialized into package.
            </param>
            <param name="minModelVersion">
            Optional minimum model schema version to use when saving model.
            </param>
            <returns>The model version used for the serialization</returns>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacPackage.Name">
            <summary>
            Get identifier for this package.
            </summary>
            <value>
            String identifier for this package.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacPackage.Description">
            <summary>
            Get an optional summary of this package.
            </summary>
            <value>
            String summary of this package; or null reference if there is no summary.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacPackage.Version">
            <summary>
            Get version information for this package.
            </summary>
            <value>
            <see cref="P:Microsoft.SqlServer.Dac.DacPackage.Version"/> structure that specifies the version information for this package.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacPackage.PreDeploymentScript">
            <summary>
            Get stream used to read and write script executed prior to deploying schema contained in this package.
            </summary>
            <value>
            <see cref="T:System.IO.Stream"/> instance used to read and write script contents.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacPackage.PostDeploymentScript">
            <summary>
            Get stream used to read and write script executed after deploying schema contained in this package.
            </summary>
            <value>
            <see cref="T:System.IO.Stream"/> instance used to read and write script contents.
            </value>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacProfile">
            <summary>
            Contains settings related to a specific deployment configuration.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacProfile.#ctor">
            <summary>
            Construct a new instance of the <see cref="T:Microsoft.SqlServer.Dac.DacProfile"/> class with a default set of deployment options.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacProfile.Load(System.String)">
            <summary>
            Create a <see cref="T:Microsoft.SqlServer.Dac.DacProfile"/> instance by reading serialized profile data from the specified file.
            </summary>
            <param name="fileName">
            Path to file with serialized profile data.
            </param>
            <returns>
            <see cref="T:Microsoft.SqlServer.Dac.DacProfile"/> instance initialized from the serialized file data.
            </returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacProfile.Load(System.IO.Stream)">
            <summary>
            Create a <see cref="T:Microsoft.SqlServer.Dac.DacProfile"/> instance by reading serialized profile data from the specified <see cref="T:System.IO.Stream"/>.
            </summary>
            <param name="stream">
            Stream from which to read serialized profile data.
            </param>
            <returns>
            <see cref="T:Microsoft.SqlServer.Dac.DacProfile"/> instance initialized from the serialized file data.
            </returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacProfile.LoadImpl(System.Func{Microsoft.Data.Tools.Schema.Sql.Deployment.PublishProfileSerializer})">
            <summary>
            Create a <see cref="T:Microsoft.SqlServer.Dac.DacProfile"/> instance by reading serialized profile data from the specified <see cref="T:System.IO.Stream"/>.
            </summary>
            <param name="serializerProvider">
            Provider that creates serializer from which to read parsed profile data.
            </param>
            <returns>
            <see cref="T:Microsoft.SqlServer.Dac.DacProfile"/> instance initialized from the serialized file data.
            </returns>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacProfile.DeployOptions">
            <summary>
            Get deployment options associated with this profile.
            </summary>
            <value>
            <see cref="T:Microsoft.SqlServer.Dac.DacDeployOptions"/> instance that specifies deployment options.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacProfile.TargetDatabaseName">
            <summary>
            Get or set name of database used as the target of a deployment.
            </summary>
            <value>
            String name of target database.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacProfile.TargetConnectionString">
            <summary>
            Get or set connection string for database server used as the target of a deployment.
            </summary>
            <value>
            String that specifies database server connection information.
            </value>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacProgressEventArgs">
            <summary>
            Data associated with event raised as an executing operation completes individual steps of processing.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacProgressEventArgs.Status">
            <summary>
            Get status of an active operation.
            </summary>
            <value>
            <see cref="T:Microsoft.SqlServer.Dac.DacOperationStatus"/> enumeration value that specifies the current status of an operation.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacProgressEventArgs.Message">
            <summary>
            Get a friendly message associated with the current step of an operation.
            </summary>
            <value>
            String message associated with the current step of an operation.
            </value>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacProgressEventArgs.OperationId">
            <summary>
            Gets the ID of the top level task the progress event relates to.
            </summary>
            <remarks>
                <ul>
                <li>Extract = 1</li>
                <li>Publish = 2</li>
                <li>ImportData = 3</li>
                <li>ExportData = 4</li>
                <li>Unregister = 5</li>
                <li>Register = 6</li>
                <li>DriftReport = 7</li>
                <li>DeployReport = 8</li>
                <li>Script = 9</li>
                </ul>
            </remarks>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacRetryMessage">
            <summary>
            This message is raised when the DacFx API retried a command or connection due to a
            transient error returned by the server.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacRetryMessage.RetryCount">
            <summary>
            The retry count when this error was encountered
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacRetryMessage.ServerErrorNumber">
            <summary>
            The number of the error from SQL Server or 0 if a different 
            exception was encountered (that invoked a retry)
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacSchemaModelStorageType">
            <summary>
            Specifies the type of backing storage for a schema model.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.DacSchemaModelStorageType.File">
            <summary>
            Model is back by file-based storage.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.DacSchemaModelStorageType.Memory">
            <summary>
            Model is stored completely in-memory.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacServicesException">
            <summary>
            Exception thrown for DAC service errors.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServicesException.#ctor">
            <summary>
            Construct a new instance of the <see cref="T:Microsoft.SqlServer.Dac.DacServicesException"/> class.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServicesException.#ctor(System.String)">
            <summary>
            Construct a new instance of the <see cref="T:Microsoft.SqlServer.Dac.DacServicesException"/> class with the specified error message.
            </summary>
            <param name="message">
            The message that describes the error.
            </param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServicesException.#ctor(System.String,System.Exception)">
            <summary>
            Construct a new instance of the <see cref="T:Microsoft.SqlServer.Dac.DacServicesException"/> class with the specified error message 
            and a reference to the inner exception that is the cause of this exception.
            </summary>
            <param name="message">
            The message that describes the error.
            </param>
            <param name="innerException">
            The exception that is the cause of the current exception, or a null reference if no inner exception is specified. 
            </param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServicesException.GetObjectData(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext)">
            <summary>
            Write exception information to the supplied <see cref="T:System.Runtime.Serialization.SerializationInfo"/> object.
            </summary>
            <param name="info">
            <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data.
            </param>
            <param name="context">
            <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.
            </param>
            <exception cref="T:System.ArgumentNullException">
            If <paramref name="info"/> is a null reference.
            </exception>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DacServicesException.Messages">
            <summary>
            Get collection of additional error, warning, and informational messages associated with this exception.
            </summary>
            <value>
            Collection of additional messages associated with this exception.
            </value>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DacServices">
            <summary>
            Provides operations to create and consume DAC packages represented by <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> instances.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.DacServices._userConnectionFactory">
            <summary>
            Connection factory using the connection string supplied by caller.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.Initialize">
            <summary>
            Called by classes within the API to initialize any static state
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.#ctor(System.String)">
            <summary>
            Construct a new instance of the <see cref="T:Microsoft.SqlServer.Dac.DacServices"/> class
            that operates against the database specified by the supplied connection string.
            </summary>
            <param name="connectionString">
            String that supplies connection information for the database connection used by this instance.
            </param>
            <exception cref="T:System.ArgumentNullException">
            If <paramref name="connectionString"/> is a null reference.
            </exception>
            <exception cref="T:System.ArgumentException">
            If the supplied <paramref name="connectionString"/> is not valid.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.#ctor(System.String,Microsoft.SqlServer.Dac.IUniversalAuthProvider)">
            <summary>
            Construct a new instance of the <see cref="T:Microsoft.SqlServer.Dac.DacServices"/> class
            that operates against the database specified by the supplied connection string and authentication provider.
            </summary>
            <param name="connectionString">
            String that supplies connection information for the database connection used by this instance.
            </param>
            <param name="authProvider">
            Provide the up-to-date access token for AAD Universal Login (smartcard, phone, etc) 
            </param>
            <exception cref="T:System.ArgumentNullException">
            If <paramref name="connectionString"/> is a null reference.
            If <paramref name="authProvider"/> is a null reference.
            </exception>
            <exception cref="T:System.ArgumentException">
            If the supplied <paramref name="connectionString"/> is not valid.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.#ctor(System.String,System.Security.SecureString)">
            <summary>
            Construct a new instance of the <see cref="T:Microsoft.SqlServer.Dac.DacServices"/> class
            that operates against the database specified by the supplied connection string.
            </summary>
            <param name="connectionString">
            String that supplies connection information for the database connection used by this instance.
            </param>
            <param name="password">
            SecureString that supplies password for the database connection used by this instance.
            </param>
            <exception cref="T:System.ArgumentNullException">
            If <paramref name="connectionString"/> is a null reference.
            </exception>
            <exception cref="T:System.ArgumentException">
            If the supplied <paramref name="connectionString"/> is not valid.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.Extract(System.String,System.String,System.String,System.Version,System.String,System.Collections.Generic.IEnumerable{System.Tuple{System.String,System.String}},Microsoft.SqlServer.Dac.DacExtractOptions,System.Nullable{System.Threading.CancellationToken})">
            <summary>
            Extract the schema from a database into a package.
            </summary>
            <param name="packageFileName">
            Path to the package file to be created.
            </param>
            <param name="databaseName">
            Name of the source database.
            </param>
            <param name="applicationName">
            String identifier for the DAC application.
            </param>
            <param name="applicationVersion">
            Version of the DAC application.
            </param>
            <param name="applicationDescription">
            Optional string summary of the DAC application.
            </param>
            <param name="tables">
            <para>
            Optional enumerable used to retrieve enumerator over set of tables for which reference data should be stored.
            For each <see cref="T:System.Tuple"/> in the enumeration the first item specifies the schema of the table, and the second specifies the base identifier of the table.
            </para>
            <para>
            If the value for this parameter is a null reference, no reference data will be stored.
            </para>
            </param>
            <param name="extractOptions">
            Optional <see cref="T:Microsoft.SqlServer.Dac.DacExtractOptions"/> instance used to specify options that affect the behavior of package extraction.
            </param>
            <param name="cancellationToken">
            Optional <see cref="T:System.Threading.CancellationToken"/> that can be used to indicate that the operation should be cancelled.
            Use of this object does not guarantee that the operation will be cancelled.
            </param>
            <exception cref="T:System.ArgumentException">
            If <paramref name="applicationName"/> is a null reference or empty string.
            </exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If a problem occurs during package extraction.
            </exception>
            <exception cref="T:System.OperationCanceledException">
            If the <see cref="T:System.Threading.CancellationToken"/> has a cancellation requested and the operation could be cancelled.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.Extract(System.IO.Stream,System.String,System.String,System.Version,System.String,System.Collections.Generic.IEnumerable{System.Tuple{System.String,System.String}},Microsoft.SqlServer.Dac.DacExtractOptions,System.Nullable{System.Threading.CancellationToken})">
            <summary>
            Extract the schema from a database into a package.
            </summary>
            <param name="packageStream">
            <see cref="T:System.IO.Stream"/> to which to write the package.
            </param>
            <param name="databaseName">
            Name of the source database.
            </param>
            <param name="applicationName">
            String identifier for the DAC application.
            </param>
            <param name="applicationVersion">
            Version of the DAC application.
            </param>
            <param name="applicationDescription">
            Optional string summary of the DAC application.
            </param>
            <param name="tables">
            <para>
            Optional enumerable used to retrieve enumerator over set of tables for which data should be exported.
            For each <see cref="T:System.Tuple"/> in the enumeration the first item specifies the schema of the table, and the second specifies the base identifier of the table.
            </para>
            <para>
            If the value for this parameter is a null reference, no data will be exported.
            </para>
            </param>
            <param name="extractOptions">
            Optional <see cref="T:Microsoft.SqlServer.Dac.DacExtractOptions"/> instance used to specify options that affect the behavior of package extraction.
            </param>
            <param name="cancellationToken">
            Optional <see cref="T:System.Threading.CancellationToken"/> that can be used to indicate that the operation should be cancelled.
            Use of this object does not guarantee that the operation will be cancelled.
            </param>
            <exception cref="T:System.ArgumentException">
            If <paramref name="applicationName"/> is a null reference or empty string.
            </exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If a problem occurs during package extraction; or the supplied stream is not suitable for writing the package.
            </exception>
            <exception cref="T:System.OperationCanceledException">
            If the <see cref="T:System.Threading.CancellationToken"/> has a cancellation requested and the operation could be cancelled.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.Script(Microsoft.SqlServer.Dac.DacPackage,System.String,Microsoft.SqlServer.Dac.PublishOptions)">
            <summary>
            Scripts the steps for a publish operation as a deployment script, deployment report, or both. 
            At least one of the <see cref="P:Microsoft.SqlServer.Dac.PublishOptions.GenerateDeploymentScript"/> or <see cref="P:Microsoft.SqlServer.Dac.PublishOptions.GenerateDeploymentReport"/> 
            options must be set to true. This method will not publish to the database 
            </summary>
            <param name="package">
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> containing schema to be deployed.
            </param>
            <param name="targetDatabaseName">
            Name of the target database for deployment.
            </param>
            <param name="publishOptions">
            Instance of <see cref="T:Microsoft.SqlServer.Dac.PublishOptions"/> that specifies what is reported back - the deployment script,
            deployment report, as well as how to configure various aspects of the deployment.
            </param>
            <returns><see cref="T:Microsoft.SqlServer.Dac.PublishResult"/>, containing the script(s) and/or report if requested by the caller</returns>
            <exception cref="T:System.ArgumentException">
            If the value for any of the required parameters is a null reference or an empty string.
            </exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If an error occurs during deployment.
            </exception>
            <exception cref="T:System.OperationCanceledException">
            If the <see cref="T:System.Threading.CancellationToken"/> has a cancellation requested and the operation could be cancelled.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.Script(Microsoft.SqlServer.Dac.DacPackage,Microsoft.SqlServer.Dac.DacPackage,System.String,Microsoft.SqlServer.Dac.PublishOptions)">
            <summary>
            Scripts the steps for a publish operation as a deployment script, deployment report, or both. 
            At least one of the <see cref="P:Microsoft.SqlServer.Dac.PublishOptions.GenerateDeploymentScript"/> or <see cref="P:Microsoft.SqlServer.Dac.PublishOptions.GenerateDeploymentReport"/> 
            options must be set to true. This method will not modify the target
            </summary>
            <param name="sourcePackage">
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> containing schema to be deployed.
            </param>
            <param name="targetPackage">
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> containing schema representing the target database.
            </param>
            <param name="targetDatabaseName">
            Name of the target database for deployment.
            </param>
            <param name="publishOptions">
            Instance of <see cref="T:Microsoft.SqlServer.Dac.PublishOptions"/> that specifies what is reported back - the deployment script,
            deployment report, as we all how to configure various aspects of the deployment.
            </param>
            <returns><see cref="T:Microsoft.SqlServer.Dac.PublishResult"/>, containing the script(s) and/or report if requested by the caller</returns>
            <exception cref="T:System.ArgumentException">
            If the value for any of the required parameters is a null reference or an empty string.
            </exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If an error occurs during deployment.
            </exception>
            <exception cref="T:System.OperationCanceledException">
            If the <see cref="T:System.Threading.CancellationToken"/> has a cancellation requested and the operation could be cancelled.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.Publish(Microsoft.SqlServer.Dac.DacPackage,System.String,Microsoft.SqlServer.Dac.PublishOptions)">
            <summary>
            Publish the supplied package to a database. This method supports returning the script used when publishing along with
            a deployment report summarizing the actions taken during Publish
            </summary>
            <param name="package">
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> containing schema to be deployed.
            </param>
            <param name="targetDatabaseName">
            Name of the target database for deployment.
            </param>
            <param name="publishOptions">
            Instance of <see cref="T:Microsoft.SqlServer.Dac.PublishOptions"/> that specifies what is reported back - the deployment script,
            deployment report, as we all how to configure various aspects of the deployment.
            </param>
            <returns><see cref="T:Microsoft.SqlServer.Dac.PublishResult"/>, containing the script(s) and/or report if requested by the caller</returns>
            <exception cref="T:System.ArgumentException">
            If the value for any of the required parameters is a null reference or an empty string.
            </exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If an error occurs during deployment.
            </exception>
            <exception cref="T:System.OperationCanceledException">
            If the <see cref="T:System.Threading.CancellationToken"/> has a cancellation requested and the operation could be cancelled.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.Deploy(Microsoft.SqlServer.Dac.DacPackage,System.String,System.Boolean,Microsoft.SqlServer.Dac.DacDeployOptions,System.Nullable{System.Threading.CancellationToken})">
            <summary>
            Deploy the supplied package to a database.
            </summary>
            <param name="package">
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> containing schema to be deployed.
            </param>
            <param name="targetDatabaseName">
            Name of the target database for deployment.
            </param>
            <param name="upgradeExisting">
            True to allow modification of existing database schema in order to match schema contained in source package;
            otherwise false to block modification of existing database.
            If the database does not exist this flag has no effect.
            </param>
            <param name="options">
            Instance of <see cref="T:Microsoft.SqlServer.Dac.DacDeployOptions"/> that specifies properties that affect various aspects of the deployment.
            </param>
            <param name="cancellationToken">
            Optional <see cref="T:System.Threading.CancellationToken"/> that can be used to indicate that the operation should be cancelled.
            Use of this object does not guarantee that the operation will be cancelled.
            </param>
            <exception cref="T:System.ArgumentException">
            If the value for any of the required parameters is a null reference or an empty string.
            </exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If <paramref name="upgradeExisting"/> is true and the target database exists;
            or if an error occurs during deployment.
            </exception>
            <exception cref="T:System.OperationCanceledException">
            If the <see cref="T:System.Threading.CancellationToken"/> has a cancellation requested and the operation could be cancelled.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.GenerateDeployScript(Microsoft.SqlServer.Dac.DacPackage,System.String,Microsoft.SqlServer.Dac.DacDeployOptions,System.Nullable{System.Threading.CancellationToken})">
            <summary>
            Create T-SQL script that can be used to deploy the schema of the supplied <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> to a database.
            </summary>
            <param name="package">
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> containing schema to be deployed.
            </param>
            <param name="targetDatabaseName">
            Name of the target database for deployment.
            </param>
            <param name="options">
            Instance of <see cref="T:Microsoft.SqlServer.Dac.DacDeployOptions"/> that specifies properties that affect various aspects of the deployment script creation.
            </param>
            <param name="cancellationToken">
            Optional <see cref="T:System.Threading.CancellationToken"/> that can be used to indicate that the operation should be cancelled.
            Use of this object does not guarantee that the operation will be cancelled.
            </param>
            <returns>
            String of T-SQL script used to create or update database schema based on the supplied <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/>.
            </returns>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If a problem occurs during script generation.
            </exception>
            <exception cref="T:System.OperationCanceledException">
            If the <see cref="T:System.Threading.CancellationToken"/> has a cancellation requested and the operation could be cancelled.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.GenerateDeployReport(Microsoft.SqlServer.Dac.DacPackage,System.String,Microsoft.SqlServer.Dac.DacDeployOptions,System.Nullable{System.Threading.CancellationToken})">
            <summary>
            Create XML report of the steps needed to deploy the schema of the supplied <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> to a database.
            </summary>
            <param name="package">
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> containing schema to be deployed.
            </param>
            <param name="targetDatabaseName">
            Name of the target database for deployment.
            </param>
            <param name="options">
            Instance of <see cref="T:Microsoft.SqlServer.Dac.DacDeployOptions"/> that specifies properties that affect various aspects of the deployment report creation.
            </param>
            <param name="cancellationToken">
            Optional <see cref="T:System.Threading.CancellationToken"/> that can be used to indicate that the operation should be cancelled.
            Use of this object does not guarantee that the operation will be cancelled.
            </param>
            <returns>
            String of XML that details the steps of the package deployment.
            </returns>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If a problem occurs during report generation.
            </exception>
            <exception cref="T:System.OperationCanceledException">
            If the <see cref="T:System.Threading.CancellationToken"/> has a cancellation requested and the operation could be cancelled.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.CreateController(Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeployment,Microsoft.Data.Tools.Schema.ErrorManager)">
            <summary>
            Creates an <see cref="T:Microsoft.Data.Tools.Schema.Sql.Deployment.IDeploymentController"/>, handling any errors thrown during contstruction
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.GenerateUniqueScriptFileName(System.String,System.Boolean)">
            <summary>
            Generate unique filename for a script
            </summary>
            <param name="databaseName">The target database name</param>
            <param name="isMaster">Is this the master database script</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.GenerateDriftReport(System.String,System.Nullable{System.Threading.CancellationToken})">
            <summary>
            Create XML report of the drift that has occurred since the database was last registered.
            </summary>
            <param name="targetDatabaseName">
            Name of the target database for deployment.
            </param>
            <param name="cancellationToken">
            Optional <see cref="T:System.Threading.CancellationToken"/> that can be used to indicate that the operation should be cancelled.
            Use of this object does not guarantee that the operation will be cancelled.
            </param>
            <returns>
            String of XML that details the database drift, or null if the database has not been registered.
            </returns>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If a problem occurs during report generation.
            </exception>
            <exception cref="T:System.OperationCanceledException">
            If the <see cref="T:System.Threading.CancellationToken"/> has a cancellation requested and the operation could be cancelled.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.GenerateDriftReport(System.String,Microsoft.SqlServer.Dac.DacSchemaModelStorageType,System.Nullable{System.Threading.CancellationToken})">
            <summary>
            Create XML report of the drift that has occurred since the database was last registered.
            </summary>
            <param name="targetDatabaseName">
            Name of the target database for deployment.
            </param>
            <param name="modelStorageType">
            Specifies the type of backing storage for a schema model.
            </param>
            <param name="cancellationToken">
            Optional <see cref="T:System.Threading.CancellationToken"/> that can be used to indicate that the operation should be cancelled.
            Use of this object does not guarantee that the operation will be cancelled.
            </param>
            <returns>
            String of XML that details the database drift, or null if the database has not been registered.
            </returns>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If a problem occurs during report generation.
            </exception>
            <exception cref="T:System.OperationCanceledException">
            If the <see cref="T:System.Threading.CancellationToken"/> has a cancellation requested and the operation could be cancelled.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.Register(System.String,System.String,System.Version,System.String)">
            <summary>
            Add DAC registration information for the specified target database.
            </summary>
            <param name="targetDatabaseName">
            Name of the database for which to add registration information.
            </param>
            <param name="applicationName">
            String identifier for the DAC application.
            </param>
            <param name="applicationVersion">
            Version of the DAC application.
            </param>
            <param name="applicationDescription">
            Optional string summary of the DAC application.
            </param>
            <exception cref="T:System.ArgumentException">
            If any of the required arguments are null or zero-length strings.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.Register(System.String,Microsoft.SqlServer.Dac.DacSchemaModelStorageType,System.String,System.Version,System.String)">
            <summary>
            Add DAC registration information for the specified target database.
            </summary>
            <param name="targetDatabaseName">
            Name of the database for which to add registration information.
            </param>
            <param name="modelStorageType">
            Specifies the type of backing storage for a schema model.
            </param>
            <param name="applicationName">
            String identifier for the DAC application.
            </param>
            <param name="applicationVersion">
            Version of the DAC application.
            </param>
            <param name="applicationDescription">
            Optional string summary of the DAC application.
            </param>
            <exception cref="T:System.ArgumentException">
            If any of the required arguments are null or zero-length strings.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.Unregister(System.String)">
            <summary>
            Remove DAC registration information for the specified target database.
            </summary>
            <param name="targetDatabaseName">
            Name of the database for which to remove registration information.
            </param>
            <exception cref="T:System.ArgumentException">
            If <paramref name="targetDatabaseName"/> is null or a zero-length string.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.ExportBacpac(System.String,System.String,System.Collections.Generic.IEnumerable{System.Tuple{System.String,System.String}},System.Nullable{System.Threading.CancellationToken})">
            <summary>
            Extract schema and export data from a database into a "bacpac" package.
            </summary>
            <param name="packageFileName">
            Path of the target package file.
            </param>
            <param name="databaseName">
            Name of the source database.
            </param>
            <param name="tables">
            <para>
            Optional enumerable used to retrieve enumerator over set of tables for which data should be exported.
            For each <see cref="T:System.Tuple"/> in the enumeration the first item specifies the schema of the table, and the second specifies the base identifier of the table.
            </para>
            <para>
            If the value for this parameter is a null reference, data for all tables will be exported.
            </para>
            </param>
            <param name="cancellationToken">
            Optional <see cref="T:System.Threading.CancellationToken"/> that can be used to indicate that the operation should be cancelled.
            Use of this object does not guarantee that the operation will be cancelled.
            </param>
            <exception cref="T:System.ArgumentException">
            If the value for any of the required parameters is a null reference or an empty string.
            </exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If an error occurs during schema deployment and data export;
            or if <paramref name="tables"/> specifies a table that does not exist in the schema contained in the supplied package.
            </exception>
            <exception cref="T:System.OperationCanceledException">
            If the <see cref="T:System.Threading.CancellationToken"/> has a cancellation requested and the operation could be cancelled.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.ExportBacpac(System.String,System.String,Microsoft.SqlServer.Dac.DacSchemaModelStorageType,System.Collections.Generic.IEnumerable{System.Tuple{System.String,System.String}},System.Nullable{System.Threading.CancellationToken})">
            <summary>
            Extract schema and export data from a database into a "bacpac" package.
            </summary>
            <param name="packageFileName">
            Path of the target package file.
            </param>
            <param name="databaseName">
            Name of the source database.
            </param>
            <param name="modelStorageType">
            Specifies the type of backing storage for a schema model.
            </param>
            <param name="tables">
            <para>
            Optional enumerable used to retrieve enumerator over set of tables for which data should be exported.
            For each <see cref="T:System.Tuple"/> in the enumeration the first item specifies the schema of the table, and the second specifies the base identifier of the table.
            </para>
            <para>
            If the value for this parameter is a null reference, data for all tables will be exported.
            </para>
            </param>
            <param name="cancellationToken">
            Optional <see cref="T:System.Threading.CancellationToken"/> that can be used to indicate that the operation should be cancelled.
            Use of this object does not guarantee that the operation will be cancelled.
            </param>
            <exception cref="T:System.ArgumentException">
            If the value for any of the required parameters is a null reference or an empty string.
            </exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If an error occurs during schema deployment and data export;
            or if <paramref name="tables"/> specifies a table that does not exist in the schema contained in the supplied package.
            </exception>
            <exception cref="T:System.OperationCanceledException">
            If the <see cref="T:System.Threading.CancellationToken"/> has a cancellation requested and the operation could be cancelled.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.ExportBacpac(System.String,System.String,Microsoft.SqlServer.Dac.DacExportOptions,System.Collections.Generic.IEnumerable{System.Tuple{System.String,System.String}},System.Nullable{System.Threading.CancellationToken})">
            <summary>
            Extract schema and export data from a database into a "bacpac" package.
            </summary>
            <param name="packageFileName">
            Path of the target package file.
            </param>
            <param name="databaseName">
            Name of the source database.
            </param>
            <param name="options">
             Instance of <see cref="T:Microsoft.SqlServer.Dac.DacExportOptions"/> that specifies properties that affect various aspects of the export.
            </param>
            <param name="tables">
            Optional enumerable used to retrieve enumerator over set of tables for which data should be exported.
            For each <see cref="T:System.Tuple"/> in the enumeration the first item specifies the schema of the table, and the second specifies the base identifier of the table.
            </param>
            <param name="cancellationToken">
            Optional <see cref="T:System.Threading.CancellationToken"/> that can be used to indicate that the operation should be cancelled.
            Use of this object does not guarantee that the operation will be cancelled.
            </param>
            <exception cref="T:System.ArgumentException">
            If the value for any of the required parameters is a null reference or an empty string.
            </exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If an error occurs during schema deployment and data export;
            or if <paramref name="options"/> specifies a table that does not exist in the schema contained in the supplied package.
            </exception>
            <exception cref="T:System.OperationCanceledException">
            If the <see cref="T:System.Threading.CancellationToken"/> has a cancellation requested and the operation could be cancelled.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.ExportBacpac(System.IO.Stream,System.String,System.Collections.Generic.IEnumerable{System.Tuple{System.String,System.String}},System.Nullable{System.Threading.CancellationToken})">
            <summary>
            Extract schema and export data from a database into a "bacpac" package.
            </summary>
            <param name="packageStream">
            <see cref="T:System.IO.Stream"/> to which to write the package.
            </param>
            <param name="databaseName">
            Name of the source database.
            </param>
            <param name="tables">
            <para>
            Optional enumerable used to retrieve enumerator over set of tables for which data should be exported.
            For each <see cref="T:System.Tuple"/> in the enumeration the first item specifies the schema of the table, and the second specifies the base identifier of the table.
            </para>
            <para>
            If the value for this parameter is a null reference, data for all tables will be exported.
            </para>
            </param>
            <param name="cancellationToken">
            Optional <see cref="T:System.Threading.CancellationToken"/> that can be used to indicate that the operation should be cancelled.
            Use of this object does not guarantee that the operation will be cancelled.
            </param>
            <exception cref="T:System.ArgumentException">
            If the value for any of the required parameters is a null reference or an empty string.
            </exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If an error occurs during schema deployment and data export;
            or if <paramref name="tables"/> specifies a table that does not exist in the schema contained in the supplied package;
            or the supplied stream is not suitable for writing the package.
            </exception>
            <exception cref="T:System.OperationCanceledException">
            If the <see cref="T:System.Threading.CancellationToken"/> has a cancellation requested and the operation could be cancelled.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.ExportBacpac(System.IO.Stream,System.String,Microsoft.SqlServer.Dac.DacSchemaModelStorageType,System.Collections.Generic.IEnumerable{System.Tuple{System.String,System.String}},System.Nullable{System.Threading.CancellationToken})">
            <summary>
            Extract schema and export data from a database into a "bacpac" package.
            </summary>
            <param name="packageStream">
            <see cref="T:System.IO.Stream"/> to which to write the package.
            </param>
            <param name="databaseName">
            Name of the source database.
            </param>
            <param name="modelStorageType">
            Specifies the type of backing storage for a schema model.
            </param>
            <param name="tables">
            <para>
            Optional enumerable used to retrieve enumerator over set of tables for which data should be exported.
            For each <see cref="T:System.Tuple"/> in the enumeration the first item specifies the schema of the table, and the second specifies the base identifier of the table.
            </para>
            <para>
            If the value for this parameter is a null reference, data for all tables will be exported.
            </para>
            </param>
            <param name="cancellationToken">
            Optional <see cref="T:System.Threading.CancellationToken"/> that can be used to indicate that the operation should be cancelled.
            Use of this object does not guarantee that the operation will be cancelled.
            </param>
            <exception cref="T:System.ArgumentException">
            If the value for any of the required parameters is a null reference or an empty string.
            </exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If an error occurs during schema deployment and data export;
            or if <paramref name="tables"/> specifies a table that does not exist in the schema contained in the supplied package;
            or the supplied stream is not suitable for writing the package.
            </exception>
            <exception cref="T:System.OperationCanceledException">
            If the <see cref="T:System.Threading.CancellationToken"/> has a cancellation requested and the operation could be cancelled.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.ExportBacpac(System.IO.Stream,System.String,Microsoft.SqlServer.Dac.DacExportOptions,System.Collections.Generic.IEnumerable{System.Tuple{System.String,System.String}},System.Nullable{System.Threading.CancellationToken})">
            <summary>
            Extract schema and export data from a database into a "bacpac" package.
            </summary>
            <param name="packageStream">
            <see cref="T:System.IO.Stream"/> to which to write the package.
            </param>
            <param name="databaseName">
            Name of the source database.
            </param>
            <param name="options">
            Optional instance of <see cref="T:Microsoft.SqlServer.Dac.DacExportOptions"/> that specifies properties that affect various aspects of the export.
            </param>
            <param name="tables">
            Optional enumerable used to retrieve enumerator over set of tables for which data should be exported.
            For each <see cref="T:System.Tuple"/> in the enumeration the first item specifies the schema of the table, and the second specifies the base identifier of the table.
            </param>
            <param name="cancellationToken">
            Optional <see cref="T:System.Threading.CancellationToken"/> that can be used to indicate that the operation should be cancelled.
            Use of this object does not guarantee that the operation will be cancelled.
            </param>
            <exception cref="T:System.ArgumentException">
            If the value for any of the required parameters is a null reference or an empty string.
            </exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If an error occurs during schema deployment and data export;
            or if <paramref name="options"/> specifies a table that does not exist in the schema contained in the supplied package.
            </exception>
            <exception cref="T:System.OperationCanceledException">
            If the <see cref="T:System.Threading.CancellationToken"/> has a cancellation requested and the operation could be cancelled.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.SetAmbientSetting(System.String,System.Object)">
            <summary>
            Populates ambient setting controlling
            deployment/retry behavior down the stack.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.CreateSettingsContext(Microsoft.SqlServer.Dac.DacLoggingContext)">
            <summary>
            Sets up a stack context to push a configured settings object to populate
            the ambient settings for consumption further down the stack
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.ImportBacpac(Microsoft.SqlServer.Dac.BacPackage,System.String,System.Nullable{System.Threading.CancellationToken})">
            <summary>
            Deploy schema and import table data from the supplied package to a database.
            </summary>
            <param name="package">
            <see cref="T:Microsoft.SqlServer.Dac.BacPackage"/> containing schema to be deployed and data to be imported.
            </param>
            <param name="targetDatabaseName">
            Name of the target database for deployment.
            </param>
            <param name="cancellationToken">
            Optional <see cref="T:System.Threading.CancellationToken"/> that can be used to indicate that the operation should be cancelled.
            Use of this object does not guarantee that the operation will be cancelled.
            </param>
            <exception cref="T:System.ArgumentException">
            If the value for any of the required parameters is a null reference or an empty string.
            </exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If an error occurs during schema deployment and data import.
            </exception>
            <exception cref="T:System.OperationCanceledException">
            If the <see cref="T:System.Threading.CancellationToken"/> has a cancellation requested and the operation could be cancelled.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.ImportBacpac(Microsoft.SqlServer.Dac.BacPackage,System.String,Microsoft.SqlServer.Dac.DacAzureDatabaseSpecification,System.Nullable{System.Threading.CancellationToken})">
            <summary>
            Deploy schema and import table data from the supplied package to a database.
            </summary>
            <param name="package">
            <see cref="T:Microsoft.SqlServer.Dac.BacPackage"/> containing schema to be deployed and data to be imported.
            </param>
            <param name="targetDatabaseName">
            Name of the target database for deployment.
            </param>
            <param name="creationDefaults">
            Optional default size and edition parameters used when creating a new Azure database.
            </param>
            <param name="cancellationToken">
            Optional <see cref="T:System.Threading.CancellationToken"/> that can be used to indicate that the operation should be cancelled.
            Use of this object does not guarantee that the operation will be cancelled.
            </param>
            <exception cref="T:System.ArgumentException">
            If the value for any of the required parameters is a null reference or an empty string.
            </exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If an error occurs during schema deployment and data import.
            </exception>
            <exception cref="T:System.OperationCanceledException">
            If the <see cref="T:System.Threading.CancellationToken"/> has a cancellation requested and the operation could be cancelled.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.ImportBacpac(Microsoft.SqlServer.Dac.BacPackage,System.String,Microsoft.SqlServer.Dac.DacImportOptions,System.Nullable{System.Threading.CancellationToken})">
            <summary>
            Deploy schema and import table data from the supplied package to a database.
            </summary>
            <param name="package">
            <see cref="T:Microsoft.SqlServer.Dac.BacPackage"/> containing schema to be deployed and data to be imported.
            </param>
            <param name="targetDatabaseName">
            Name of the target database for deployment.
            </param>
            <param name="importOptions">
             Instance of <see cref="T:Microsoft.SqlServer.Dac.DacImportOptions"/> that specifies properties that affect various aspects of the import.
            </param>
            <param name="cancellationToken">
            Optional <see cref="T:System.Threading.CancellationToken"/> that can be used to indicate that the operation should be cancelled.
            Use of this object does not guarantee that the operation will be cancelled.
            </param>
            <exception cref="T:System.ArgumentException">
            If the value for any of the required parameters is a null reference or an empty string.
            </exception>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If an error occurs during schema deployment and data import.
            </exception>
            <exception cref="T:System.OperationCanceledException">
            If the <see cref="T:System.Threading.CancellationToken"/> has a cancellation requested and the operation could be cancelled.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.SafeFileStreamGetter(System.String,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare,System.String)">
            <summary>
            Return FileStream after handling all acceptable exceptions.
            </summary>
            <param name="path">File path.</param>
            <param name="mode">File mode.</param>
            <param name="access">File access.</param>
            <param name="share">File share.</param>
            <param name="handledExceptionMessage">Message for handled exception.</param>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.SafeFileAction(System.Action,System.String)">
            <summary>
            Catches common error cases when doing I/O operations and throws a <see cref="T:Microsoft.SqlServer.Dac.DacServicesException"/> with a predefined error message
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.GenerateCreateScript(Microsoft.SqlServer.Dac.DacPackage,System.String,Microsoft.SqlServer.Dac.DacDeployOptions)">
            <summary>
            Create T-SQL script that can be used to deploy the schema of the supplied <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> to a database.
            </summary>
            <param name="package">
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> containing schema to be deployed.
            </param>
            <param name="targetDatabaseName">
            Name of the target database for deployment.
            </param>
            <param name="options">
            Instance of <see cref="T:Microsoft.SqlServer.Dac.DacDeployOptions"/> that specifies properties that affect various aspects of the deployment script creation.
            </param>
            <returns>
            String of T-SQL script used to create database schema based on the supplied <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/>.
            </returns>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If a problem occurs during script generation.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.GenerateCreateScript(System.IO.Stream,Microsoft.SqlServer.Dac.DacPackage,System.String,Microsoft.SqlServer.Dac.DacDeployOptions)">
            <summary>
            Create T-SQL script that can be used to deploy the schema of the supplied <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> to a database.
            </summary>
            <param name="outputStream">
            <see cref="T:System.IO.Stream"/> to which to write the deployment script.
            </param>
            <param name="package">
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> containing schema to be deployed.
            </param>
            <param name="targetDatabaseName">
            Name of the target database for deployment.
            </param>
            <param name="options">
            Instance of <see cref="T:Microsoft.SqlServer.Dac.DacDeployOptions"/> that specifies properties that affect various aspects of the deployment script creation.
            </param>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If a problem occurs during script generation.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.GenerateDeployScript(Microsoft.SqlServer.Dac.DacPackage,Microsoft.SqlServer.Dac.DacPackage,System.String,Microsoft.SqlServer.Dac.DacDeployOptions)">
            <summary>
            Create T-SQL script that can be used to deploy the differences between the schemas of the supplied source and target <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> instances to a database.
            </summary>
            <param name="sourcePackage">
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> containing the source schema to be compared.
            </param>
            <param name="targetPackage">
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> containing the target schema to be compared.
            </param>
            <param name="targetDatabaseName">
            Name of the target database for deployment.
            </param>
            <param name="options">
            Instance of <see cref="T:Microsoft.SqlServer.Dac.DacDeployOptions"/> that specifies properties that affect various aspects of the deployment script creation.
            </param>
            <returns>
            String of T-SQL script used to create or update database schema based on the supplied <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/>.
            </returns>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If a problem occurs during script generation.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.GenerateDeployScript(System.IO.Stream,Microsoft.SqlServer.Dac.DacPackage,Microsoft.SqlServer.Dac.DacPackage,System.String,Microsoft.SqlServer.Dac.DacDeployOptions)">
            <summary>
            Create T-SQL script that can be used to deploy the differences between the schemas of the supplied source and target <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> instances to a database.
            </summary>
            <param name="outputStream">
            <see cref="T:System.IO.Stream"/> to which to write the deployment script.
            </param>
            <param name="sourcePackage">
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> containing the source schema to be compared.
            </param>
            <param name="targetPackage">
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> containing the target schema to be compared.
            </param>
            <param name="targetDatabaseName">
            Name of the target database for deployment.
            </param>
            <param name="options">
            Instance of <see cref="T:Microsoft.SqlServer.Dac.DacDeployOptions"/> that specifies properties that affect various aspects of the deployment script creation.
            </param>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If a problem occurs during script generation.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.GenerateDeployReport(Microsoft.SqlServer.Dac.DacPackage,Microsoft.SqlServer.Dac.DacPackage,System.String,Microsoft.SqlServer.Dac.DacDeployOptions)">
            <summary>
            Create XML report of the steps needed to deploy the differences between the schemas of the supplied source and target <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> instances to a database.
            </summary>
            <param name="sourcePackage">
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> containing the source schema to be compared.
            </param>
            <param name="targetPackage">
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> containing the target schema to be compared.
            </param>
            <param name="targetDatabaseName">
            Name of the target database for deployment.
            </param>
            <param name="options">
            Instance of <see cref="T:Microsoft.SqlServer.Dac.DacDeployOptions"/> that specifies properties that affect various aspects of the deployment report creation.
            </param>
            <returns>
            String of XML that details the steps of the deployment.
            </returns>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If a problem occurs during report generation.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.GenerateDeployReport(System.IO.Stream,Microsoft.SqlServer.Dac.DacPackage,Microsoft.SqlServer.Dac.DacPackage,System.String,Microsoft.SqlServer.Dac.DacDeployOptions)">
            <summary>
            Create XML report of the steps needed to deploy the differences between the schemas of the supplied source and target <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> instances to a database.
            </summary>
            <param name="outputStream">
            <see cref="T:System.IO.Stream"/> to which to write the deployment report.
            </param>
            <param name="sourcePackage">
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> containing the source schema to be compared.
            </param>
            <param name="targetPackage">
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> containing the target schema to be compared.
            </param>
            <param name="targetDatabaseName">
            Name of the target database for deployment.
            </param>
            <param name="options">
            Instance of <see cref="T:Microsoft.SqlServer.Dac.DacDeployOptions"/> that specifies properties that affect various aspects of the deployment report creation.
            </param>
            <exception cref="T:Microsoft.SqlServer.Dac.DacServicesException">
            If a problem occurs during report generation.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.ParseAndThrowIfUnsupportedConnectionStringBuilder(Microsoft.Data.Tools.Schema.Common.SqlClient.SqlConnectionFactory)">
            <summary>
            Evaluate the connection factory and determine if supplied connection factory is valid and supported by <see cref="T:Microsoft.SqlServer.Dac.DacServices"/>.
            </summary>
            <param name="connectionFactory">
            Connection factory to be validated.
            </param>
            <returns>Validated connection factory with only supported arguments present.</returns>
            <exception cref="T:System.ArgumentException">
            If the supplied <paramref name="connectionFactory"/> is not valid or if it specifies properties 
            or property values that are not supported by <see cref="T:Microsoft.SqlServer.Dac.DacServices"/>.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DacServices.ProbeIsolatedStorageAndSetAppDomainEvidenceIfNeccessary">
            <summary>
            Some CLR hosts do not set the AppDomain Evidence which is required for IsolatedStorage to function properly.  This 
            method probes if isolated storage is usable for the current user.  If isolated storage is not usable, it will attempt 
            to fix this by setting the AppDomain Evidence using private reflection.  Fixing isolated storage is a best effort
            attempt.  This method swallows all exceptions and lets the program proceed.
            </summary>cd
        </member>
        <member name="E:Microsoft.SqlServer.Dac.DacServices.ProgressChanged">
            <summary>
            Invoked as the state of an operation changes.
            </summary>
        </member>
        <member name="E:Microsoft.SqlServer.Dac.DacServices.Message">
            <summary>
            Invoked as an operation reports status updates or errors.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Data.DataException">
            <summary>
            This class is meant to be a public exception class - i.e. when throwing it ensure
            that the exception is meaningful to the end-developer.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Data.DataResources">
            <summary>
              A strongly-typed resource class, for looking up localized strings, etc.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Data.DataResources.ResourceManager">
            <summary>
              Returns the cached ResourceManager instance used by this class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Data.DataResources.Culture">
            <summary>
              Overrides the current thread's CurrentUICulture property for all
              resource lookups using this strongly typed resource class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Data.DataResources.CreateTargetModelFailed">
            <summary>
              Looks up a localized string similar to Failed to retrieve information from target database {0}.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Data.DataResources.DataPlanExecutionFailed">
            <summary>
              Looks up a localized string similar to Data plan execution failed with message {0}.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Data.DataResources.FailedDetectDspType">
            <summary>
              Looks up a localized string similar to Failed to retrieve information from target database to correctly model the database.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Data.DataResources.Skipped_SelectedColumn">
            <summary>
              Looks up a localized string similar to Excluded column [{0}].[{1}].[{2}] does not exist in the source model..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Data.DataResources.Skipped_SelectedTable">
            <summary>
              Looks up a localized string similar to Selected table [{0}].[{1}] does not have data and will not be populated..
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.DatabasePointer">
            <summary>
            Logically represents a database.  Can be used to retrieve information about the database
            such as a model and data
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.DatabasePointer.AddNewConstraints(Microsoft.Data.Tools.Schema.Sql.Deployment.ConstraintManager,Microsoft.Data.Tools.Schema.Common.SqlClient.SqlConnectionFactory)">
            <summary>
            Adds new constraints to the specified constraint manager.  Will throw a DataException if a error
            occurs with the connection to the DB
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.Data.DataDeployment">
            <summary>
            Represents a "top of stack" incremental data deployment engine.  This engine acts primarly as an orchestrator
            between other more fine-grained data deployment components.  It is meant to be a fire-and-dispose component, access to and control of 
            more fine grained components is left to direct manipulation of those components directly to avoid lifetime issues
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.Data.DataDeploymentOptions.AddSelectedTable(System.Tuple{System.String,System.String})">
            <summary>
            Adds a table to be considered when creating the data deployment plan
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.Data.DataDeploymentOptions.TableSelectionPolicy">
            <summary>
            Configures how tables will be selected for data deployment
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.Data.DataDeploymentOptions.StorageType">
            <summary>
            Storage to use when creating models of the source/target databases
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Deployment.Data.DataDeploymentOptions.TargetDatabaseName">
            <summary>
            Name of the target database.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.Data.DataPlanHandle">
            <summary>
            This class represents the disposable parts of the deployment plan.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.Data.DataPlanStrategy">
            <summary>
            Base class for different data deployment plan generation strategies
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.Data.PlanCreationContext">
            <summary>
            A data transfer object used to pass state between components used in plan creation
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.Data.PlanCreationContext.PopulateIncludedTables(System.Collections.Generic.HashSet{Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlElementDescriptor})">
             <summary>
             Called to populate selected data tables and columns based on
             policy specified in the options
            
             Assumption: the Options and Source model are populted before this method is called
             </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Deployment.Data.RipReplaceStrategy.AddToListIfNeeded(System.Collections.Generic.List{Microsoft.SqlServer.Dac.Deployment.Data.RipReplaceStrategy.GraphElem}@,Microsoft.Data.Tools.Schema.SchemaModel.IModelElement,Microsoft.SqlServer.Dac.Deployment.Data.RipReplaceStrategy.GraphElem)">
            <summary>
            This method adds new element to the list of schema-bound objects we're about to drop and re-create.
            If the input element is not present in the list, we create a new graph node and establish
            parent-child relationships. If already in the list, we just update parent-child relationship lists.
            </summary>
            <param name="list"></param>
            <param name="modelObject"></param>
            <param name="child"></param>
            <returns></returns>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Deployment.PlanExecutor">
            <summary>
            Executes a deployment plan against the specified target database
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceException">
            <summary>
            Thrown by the DeveloperInstanceManager 
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager">
            <summary>
            This class encapsulates dealing with the Serverless SQL Express technology SqlStudio uses
            as a default destination for database project deployment 
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.CreateLocaldbInstanceName(System.String)">
            <summary>
            Returns a localdb instance named based on the specified named.  The returned
            name is in the format of (localdb)\namePrefix
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.CreateInstance(System.String)">
            <summary>
            If necessary creates and then starts the specified instance and returns a connection string to connect 
            to master on the specified localdb instance.
            </summary>
            <returns>
            Returns a connection string to connect to the database.  Will throw DeveloperInstanceException
            if localdb is not installed or if an error occurs during creation of the connection string
            </returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.DetachDatabase(System.String,System.String)">
            <summary>
            If the specified database exists on the instance detach it from the instance.  
            Any connections/transactions open on the database will be closed as part of the detach.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.StopInstance(System.String)">
            <summary>
            Stops the specified instance if it is running
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.TeardownInstance(System.String)">
            <summary>
            Tears down an instance by stopping and then deleting the specified instance.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.CreateConnectionString(System.String)">
            <summary>
            Helper method that creates a connection string to 
            connect to the specified data source
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.ThrowCouldNotSetup">
            <summary>
            Helper method that throws the well known "could not setup" exception
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.CreateSafeInstanceName(System.String)">
            <summary>
            Helper to create a safe name prefix
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.DoesDatabaseExist(System.Data.SqlClient.SqlConnection,System.String)">
            <summary>
            Helper to check if a database exists
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.TestLocaldbConnectivityInstalled(System.String)">
            <summary>
            If not already tested, tests whether the localdb connectivity fix has been 
            installed.  This is a QFE ontop of .net framework 4.0.  It is assumed that the
            instance has already been started.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.SetupLocalDBInstance(System.String)">
            <summary>
            Sets up the LocalDB instance.  Returns named pipe if successful
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.BeginNewDatabaseWarmup(System.Data.SqlClient.SqlConnectionStringBuilder,System.String)">
            <summary>
            Helper method to "warmup" a new database after it has been created/attached
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.BuildCreateDatabase(System.String,System.String,System.String,System.IO.DirectoryInfo,System.IO.DirectoryInfo)">
            <summary>
            Creates an AST that represents a create database statement to create a database
            on a serverless instance
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.BuildDetachDatabase(System.String)">
            <summary>
            Builds an AST that will set the specified database to single user and detach it.
            </summary>
            <param name="dbName"></param>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.BuildDropDatabase(System.String)">
            <summary>
            Creates an AST to drop a database
            </summary>
            <param name="databaseName"></param>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.ExecuteScript(System.Data.SqlClient.SqlConnection,Microsoft.SqlServer.TransactSql.ScriptDom.TSqlScript)">
            <summary>
            Helper method that executes a set of batches against provided connection
            </summary>
            <param name="conn"></param>
            <param name="script"></param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.LocalDbInstalled">
            <summary>
            Returns true is localDb is install on the user's machine
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.LocalDbWrapper">
            <summary>
            This class encalsulates management of LocalDB instances via the native control .dll
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.LocalDbWrapper.Create(System.String)">
            <summary>
            Creates a new LocalDB instance using the specified instance name
            </summary>
            <returns>
            True if the instance was created or already existed
            </returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.LocalDbWrapper.Start(System.String,System.String@)">
            <summary>
            Starts the specified instance.  
            </summary>
            <param name="instanceName">The name of an instance that was already created</param>
            <param name="namedPipe">The named pipe that can be used to communicate with the instance</param>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.LocalDbWrapper.Stop(System.String)">
            <summary>
            Stops the specified instance
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.LocalDbWrapper.Delete(System.String)">
            <summary>
            Deletes the specified instance.  
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.LocalDbWrapper.VerifyInstalled">
            <summary>
            Helper method to verify that LocalDB is installed - it will throw if not installed.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.LocalDbWrapper.GetFunc``1(Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.LocalDbWrapper.SafeLibraryHandle,System.String)">
            <summary>
            Helper to return back the specified delegate to PInvoke the specified function
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.LocalDbWrapper.TryRetrieveApiLibPath(System.String,System.String@)">
            <summary>
            Helper method that looks in the registry to find the path to the control LocalDB library.
            The control library's constract specifies that the control library must be backwards compatible
            so we always load the latest instance of the control library and then specify the version we
            are conpatible with in subsequent calls into the library.  For instance, we may load LocalDB
            control library 12 and then specify that we want version 11 in a CreateInstance call.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.LocalDbWrapper.Installed">
            <summary>
            Returns true is LocalDB is installed
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.LocalDbWrapper.ReturnCodes">
            <summary>
            Encapsulates return codes from LocalDB
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.LocalDbWrapper.SafeLibraryHandle">
            <summary>
            Wraps the safe handle to the native library
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.LocalDbWrapper.LocalDBApi">
            <summary>
            Encapsulates the delegates that define the signatures of the functions on the control library.  These
            delegates are used to successfully PInvoke into the .dll
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.LocalDbWrapper.LocalDBFunctionNames">
            <summary>
            Encapsulates the names of the functions on the controller .dll
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Data.LocalDb.LocalDbInstanceManager.LocalDbWrapper.NativeMethods">
            <summary>
            Additional functions that we PInvoke to manage loading the control .dll and
            find the control function addresses.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DeployOperation.UpdateDatabaseData(Microsoft.Data.Tools.Schema.Sql.Dac.LoggingContext,System.Threading.CancellationToken)">
            <summary>
            Update's the target database's data using the model's / data that has already be created.  Assumption - this
            method is called after the controller has been initialized and used to update the target database
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DeployOperation.SnapshotConstraintState">
            <summary>
            Snapshots constraint state in the target database prior to the database being updated
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.EngineVersion">
            <summary>
            Represents an option specifying what engine version should be set or allowed.
            Currently this option is only used in operations related to Microsoft Azure SQL Database.
            
            For instance this can be used during export to define the allowed engine version to validate against
            and whether the features of the database match the capabilities of that engine version.
            
            Similarly when defining creation options for a public TSqlModel in the extensibility APIs, this can be
            used to define what the expected engine version of the model should be set to.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.EngineVersion.Default">
            <summary>
            Use the default engine version when creating the model.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.EngineVersion.Latest">
            <summary>
            Use the latest engine version when creating the model. 
            This will always attempt to set the highest supported engine version as the
            target, and will mean that the model will allow the latest set of T-SQL language
            features to be supported 
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.EngineVersion.V11">
            <summary>
            Version 11 
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.EngineVersion.V12">
            <summary>
            Version 12
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.Extensions.DacExtensions">
            <summary>
            Provides extensions for interacting with DAC packages represented by <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> or <see cref="T:Microsoft.SqlServer.Dac.BacPackage"/> instances.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Extensions.DacExtensions.GetCollationString(Microsoft.SqlServer.Dac.DacPackage)">
            <summary>
            Returns the database collation for the package.
            </summary>
            <param name="package">
            <see cref="T:Microsoft.SqlServer.Dac.DacPackage"/> containing collation information.
            </param>
            <returns>
            The SQL Server collation string, or null if the collation cannot be retrieved.
            </returns>
            <exception cref="T:System.ArgumentException">
            If the value for any of the required parameters is a null reference.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Extensions.DacExtensions.GetCollationString(Microsoft.SqlServer.Dac.BacPackage)">
            <summary>
            Returns the database collation for the package.
            </summary>
            <param name="package">
            <see cref="T:Microsoft.SqlServer.Dac.BacPackage"/> containing collation information.
            </param>
            <returns>
            The SQL Server collation string, or null if the collation cannot be retrieved.
            </returns>
            <exception cref="T:System.ArgumentException">
            If the value for any of the required parameters is a null reference.
            </exception>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Extensions.DacExtensions.SetServiceSetting(Microsoft.SqlServer.Dac.DacServices,System.String,System.Object)">
            <summary>
            Configures a setting on the supplied DacServices instance.
            </summary>
            <param name="service">The services instance to apply the setting</param>
            <param name="settingName">The name of the setting</param>
            <param name="settingValue">The value of the setting or null to remove the setting</param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.ExtractOperation.SchemaModel">
            <summary>
            Get <see cref="T:Microsoft.Data.Tools.Schema.SchemaModel.DataSchemaModel"/> instance that represents the extracted database schema.
            </summary>
            <value>
            <see cref="T:Microsoft.Data.Tools.Schema.SchemaModel.DataSchemaModel"/> instance created from extracted database schema.
            </value>
            <remarks>
            Use this property after executing this operation to retrieve the resulting model.
            Callers must handle disposal of this instance, as its lifetime is not managed by this class.
            </remarks>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.ModelValidation.CheckForUnsupportedAzureV1SchemaForBacpacData(Microsoft.Data.Tools.Schema.SchemaModel.DataSchemaModel,System.Collections.Generic.IEnumerable{Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlTableBase},System.Threading.CancellationToken,System.Action{Microsoft.SqlServer.Dac.DacMessage})">
            <summary>
            Determine if the supplied schema model contains any elements that are problematic
            when used with a package that contains data.
            </summary>
            <param name="model">
            <see cref="T:Microsoft.Data.Tools.Schema.SchemaModel.DataSchemaModel"/> to query for elements.
            </param>
            <param name="tables">
            Enumerable of data tables.
            </param>
            <param name="cancellationToken">
            <see cref="T:System.Threading.CancellationToken"/> that can be used to indicate that the operation should be cancelled.
            Use of this object does not guarantee that the operation will be cancelled.
            </param>
            <param name="errorHandler">
            Callback invoked when problematic elements are identified.
            A <see cref="T:Microsoft.SqlServer.Dac.DacMessage"/> instance is supplied that contains the details for the unsupported element.
            </param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.ModelValidation.CheckForSecurityPolicy(Microsoft.Data.Tools.Schema.SchemaModel.DataSchemaModel,System.Collections.Generic.IList{Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlTableBase},Microsoft.SqlServer.Dac.DacLoggingContext)">
            <summary>
            For platforms that support row-level security the exported rows set may be incomplete if the user
            is exporting a package under a database account that doesn't have enough privileges. Issue a warning
            so users can be aware of this situation
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.ModelValidation.CheckForUnmaskPermissionsNeeded(Microsoft.Data.Tools.Schema.SchemaModel.DataSchemaModel,System.Collections.Generic.IList{Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlTableBase},Microsoft.SqlServer.Dac.DacLoggingContext)">
            <summary>
            For platforms that support data masking the exported rows set may contain some masked data if the user
            is exporting a package under a database account that doesn't have enough privileges (UNMASK permission).
            Issue a warning so users can be aware of this situation.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.ObjectType">
            <summary>
            Defines object types that exist in SQL Server.
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.Aggregates">
            <summary>
            Aggregate objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.ApplicationRoles">
            <summary>
            Application role objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.Assemblies">
            <summary>
            Assembly objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.AssemblyFiles">
            <summary>
            Assembly files
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.AsymmetricKeys">
            <summary>
            Asymmetric key objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.BrokerPriorities">
            <summary>
            Broker priority objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.Certificates">
            <summary>
            Certificate objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.ColumnEncryptionKeys">
            <summary>
            Always Encrypted column encryption key objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.ColumnMasterKeys">
            <summary>
            Always Encrypted column master key objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.Contracts">
            <summary>
            Contract objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.DatabaseOptions">
            <summary>
            Database options
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.DatabaseRoles">
            <summary>
            Database role objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.DatabaseTriggers">
            <summary>
            Database DDL trigger objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.Defaults">
            <summary>
            Default objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.ExtendedProperties">
            <summary>
            Extended property objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.ExternalDataSources">
            <summary>
            External data source objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.ExternalFileFormats">
            <summary>
            External file format objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.ExternalTables">
            <summary>
            External table objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.Filegroups">
            <summary>
            Filegroup objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.FileTables">
            <summary>
            FileTable objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.FullTextCatalogs">
            <summary>
            Full-text catalog objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.FullTextStoplists">
            <summary>
            Full-text stoplist objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.MessageTypes">
            <summary>
            Message type objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.PartitionFunctions">
            <summary>
            Partition function objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.PartitionSchemes">
            <summary>
            Partition scheme objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.Permissions">
            <summary>
            Permission objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.Queues">
            <summary>
            Queue objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.RemoteServiceBindings">
            <summary>
            Remote service binding objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.RoleMembership">
            <summary>
            Role membership objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.Rules">
            <summary>
            Rule objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.ScalarValuedFunctions">
            <summary>
            Scalar valued function objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.SearchPropertyLists">
            <summary>
            Search property list objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.SecurityPolicies">
            <summary>
            Security policy objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.Sequences">
            <summary>
            Sequence objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.Services">
            <summary>
            Service objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.Signatures">
            <summary>
            Signature objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.StoredProcedures">
            <summary>
            Stored procedure objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.SymmetricKeys">
            <summary>
            Symmetric key objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.Synonyms">
            <summary>
            Synonym objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.Tables">
            <summary>
            Table objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.TableValuedFunctions">
            <summary>
            Table valued function objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.UserDefinedDataTypes">
            <summary>
            User defined data type (non-CLR) objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.UserDefinedTableTypes">
            <summary>
            User defined table type objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.ClrUserDefinedTypes">
            <summary>
            User defined type (CLR) objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.Users">
            <summary>
            User objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.Views">
            <summary>
            View objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.XmlSchemaCollections">
            <summary>
            Xml schema collection objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.Audits">
            <summary>
            Audit objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.Credentials">
            <summary>
            Credential objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.CryptographicProviders">
            <summary>
            Cryptographic provider objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.DatabaseAuditSpecifications">
            <summary>
            Database audit specification objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.DatabaseEncryptionKeys">
            <summary>
            Database encryption keys
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.DatabaseScopedCredentials">
            <summary>
            Database scoped credential objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.Endpoints">
            <summary>
            Endpoint objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.ErrorMessages">
            <summary>
            Error message objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.EventNotifications">
            <summary>
            Error notification objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.EventSessions">
            <summary>
            Event session objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.LinkedServerLogins">
            <summary>
            Linked server login objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.LinkedServers">
            <summary>
            Linked server objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.Logins">
            <summary>
            Login objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.MasterKeys">
            <summary>
            Master keys
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.Routes">
            <summary>
            Route objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.ServerAuditSpecifications">
            <summary>
            Server audit specification objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.ServerRoleMembership">
            <summary>
            Server role membership objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.ServerRoles">
            <summary>
            Server role objects
            </summary>
        </member>
        <member name="F:Microsoft.SqlServer.Dac.ObjectType.ServerTriggers">
            <summary>
            Server DDL trigger objects
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Operation.#ctor(System.String,System.Action{System.Object,System.Threading.CancellationToken})">
            <summary>
            Construct a new instance of the <see cref="T:Microsoft.SqlServer.Dac.Operation"/> class.
            </summary>
            <param name="caption">
            String describing the operation, suitable for display to user.
            </param>
            <param name="action">
            Delegate to invoke when the operation is executed.
            
            <para>
            The first parameter of the delegate is an opaque object that represents the operation.
            A concrete example of its usage is as the sender for events fired (indirectly) by this operation
            in order to correlate these events to the operation.
            </para>
            <para>
            The second parameter is a nullable <see cref="T:System.Threading.CancellationToken"/> that can be used
            to signal that the operation should be cancelled.
            </para>
            </param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.Operation.ToString">
            <summary>
            Return string representation of this instalce.
            </summary>
            <returns>
            String caption for this <see cref="T:Microsoft.SqlServer.Dac.Operation"/> instance.
            </returns>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationContext.OperationCancelled">
            <summary>
            Get boolean that indicates whether any operation associated with this context reported a cancellation.
            </summary>
            <value>
            True if an operation reported being cancelled; otherwise false.
            </value>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.OperationResources">
            <summary>
              A strongly-typed resource class, for looking up localized strings, etc.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.ResourceManager">
            <summary>
              Returns the cached ResourceManager instance used by this class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.Culture">
            <summary>
              Overrides the current thread's CurrentUICulture property for all
              resource lookups using this strongly typed resource class.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.BacpacModelValidationCaption">
            <summary>
              Looks up a localized string similar to Validating schema model for data package.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.CreatingDeploymentPlanCaption">
            <summary>
              Looks up a localized string similar to Creating deployment plan.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.DeployCaption">
            <summary>
              Looks up a localized string similar to Deploying package to database.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.DisablingIndexesCaption">
            <summary>
              Looks up a localized string similar to Disabling indexes.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.EnablingIndexesCaption">
            <summary>
              Looks up a localized string similar to Enabling indexes.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.ExecutingDeploymentPlanCaption">
            <summary>
              Looks up a localized string similar to Executing deployment plan.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.ExportCaption">
            <summary>
              Looks up a localized string similar to Exporting data from database.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.GenerateDeployReportCaption">
            <summary>
              Looks up a localized string similar to Generating deployment report.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.GenerateDeployScriptCaption">
            <summary>
              Looks up a localized string similar to Generating deployment script.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.GenerateDriftReportCaption">
            <summary>
              Looks up a localized string similar to Generating drift report.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.HistoryUpdateDisabled">
            <summary>
              Looks up a localized string similar to The dac history table will not be updated..
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.ImportCaption">
            <summary>
              Looks up a localized string similar to Importing package schema and data into database.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.PackageCaption">
            <summary>
              Looks up a localized string similar to Packaging model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.ProcessingTable">
            <summary>
              Looks up a localized string similar to Processing table: {0}.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.RegisterCaption">
            <summary>
              Looks up a localized string similar to Registering metadata for database.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.RemoveLoginsMessage">
            <summary>
              Looks up a localized string similar to Removing references from users to logins.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.ReportDeploymentPlanCaption">
            <summary>
              Looks up a localized string similar to Reporting deployment plan.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.ResolverCaption">
            <summary>
              Looks up a localized string similar to Resolving references in schema model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.ReverseEngineerCaption">
            <summary>
              Looks up a localized string similar to Extracting schema from database.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.TranslateCaption">
            <summary>
              Looks up a localized string similar to Translating package.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.UnregisterCaption">
            <summary>
              Looks up a localized string similar to Unregistering metadata for database.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.ValidationCaption">
            <summary>
              Looks up a localized string similar to Validating schema model.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OperationResources.VerifyingDeploymentPlanCaption">
            <summary>
              Looks up a localized string similar to Verifying deployment plan.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.OptionDescriptionAttribute">
            <summary>
            Customizes the description of an option.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.OptionDescriptionAttribute.#ctor(System.Type,System.String)">
            <summary>
            Creates a description for an option.
            </summary>
            <param name="resourceClassType">The resource class to extract the resource string from.</param>
            <param name="resourcePropertyName">The resource name to extract.</param>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OptionDescriptionAttribute.Description">
            <summary>
            The description of the property.    
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.DeploymentPropertyAliasAttribute">
            <summary>
            This class supports the product infrastructure and is not intended to be used directly 
            from your code.
            Defines an alias for the deployment property when used for commandline property overriding
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.DeploymentPropertyAliasAttribute.#ctor(System.String)">
            <summary>
            Defines an alias for a property.
            </summary>
        </member>
        <member name="P:Microsoft.SqlServer.Dac.DeploymentPropertyAliasAttribute.Alias">
            <summary>
            Returns the alias
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.OptionDisplayNameAttribute">
            <summary>
            Customizes the display name of an option.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.OptionDisplayNameAttribute.#ctor(System.Type,System.String)">
            <summary>
            Creates a display name for an option.
            </summary>
            <param name="resourceClassType">The resource class to extract the resource string from.</param>
            <param name="resourcePropertyName">The resource name to extract.</param>        
        </member>
        <member name="P:Microsoft.SqlServer.Dac.OptionDisplayNameAttribute.DisplayName">
            <summary>
            The display name for the property.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.IPackageSource">
            <summary>
            Encapsulates the sourcing of package content, 
            and exposes methods to instantiate various types of objects used to read the package content.
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.IPackageSource.OpenSqlPackage">
            <summary>
            Opens a readonly <see cref="T:Microsoft.Data.Tools.Schema.Sql.Build.SqlPackage"/> for the source
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.IPackageSource.OpenSqlPackageForUpdate">
            <summary>
            Opens a <see cref="T:Microsoft.Data.Tools.Schema.Sql.Build.SqlPackage"/> for the source, with the
            package set to an updateable state
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.IPackageSource.GetInputStream">
            <summary>
            Return a stream that can be used to read the package content.
            This stream must be disposed when it is no longer needed.
            </summary>
            <returns>
            <see cref="T:System.IO.Stream"/> used to read package content.
            </returns>
            <remarks>
            This method is a workaround for creating <see cref="T:Microsoft.Data.Tools.Schema.Sql.Dac.Data.BacpacPackage"/> instances from streams.
            It should not be used to create objects that are returned from other methods in this interface.
            </remarks>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.ReportMessageOperation">
            <summary>
            Reports all DataSchemaErrors added to an ErrorManager through the supplied MessageHandler.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.UnownedStream">
            <summary>
            Decorator for <see cref="T:System.IO.Stream"/> that avoids disposal of the underlying stream.
            </summary>
        </member>
        <member name="T:Microsoft.SqlServer.Dac.SqlConnectionStringBuilderHelper">
            <summary>
            Public class to support SQL Authentication configuration for DacFx
            </summary>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.SqlConnectionStringBuilderHelper.IsAuthenticationSupported">
            <summary>
            Checks whether "Authentication" is supported in the runtime environment
            The keyword "Authentication" is not supported until .Net4.6. If user uses a version of .Net less than 4.6, DacFx should avoid using "Authentication"
            </summary>
            <returns>true if "Authentication" is present in current .Net version</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.SqlConnectionStringBuilderHelper.SetAuthentication(System.Data.SqlClient.SqlConnectionStringBuilder,System.Data.SqlClient.SqlConnectionStringBuilder)">
            <summary>
            Set Authentication value from source builder to the target builder
            </summary>
            <param name="sourceBuilder">the source connection string builder</param>
            <param name="targetBuilder">the target connection string builder</param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.SqlConnectionStringBuilderHelper.SetAuthentication(System.Data.SqlClient.SqlConnectionStringBuilder,System.String)">
            <summary>
            Set Authentication using reflection
            </summary>
            <param name="sbConnectionString"></param>
            <param name="authenticationType"></param>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.SqlConnectionStringBuilderHelper.GetAuthenticationString(System.Data.SqlClient.SqlConnectionStringBuilder)">
            <summary>
            Get Authentication as string from connectionStringBuilder
            </summary>
            <param name="connectionStringBuilder"></param>
            <returns></returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.SqlConnectionStringBuilderHelper.IsAuthenticationSpecified(System.Data.SqlClient.SqlConnectionStringBuilder)">
            <summary>
            Determines whether a connection string builder has a value specified for the Authentication property.
            </summary>
            <param name="connectionStringBuilder">A connection string builder that might have authentication specified.</param>
            <returns>True if the authentication property is supported by the connection string builder and the authentication property is specified. False otherwise.</returns>
        </member>
        <member name="M:Microsoft.SqlServer.Dac.SqlConnectionStringBuilderHelper.GetConnectionStringWithAlwaysEncryptedSetting(System.Data.SqlClient.SqlConnectionStringBuilder,System.Boolean)">
            <summary>
            Sets AlwaysEncrypted setting in connection string if it is available in the .NET framework and returns the updated connection string
            No-op if there is not .NET 4.6
            </summary>
            <param name="connectionStringBuilder">A connection string builder that might have always encrypted setting specified.</param>
            <param name="enableAlwaysEncrypted">True, to enable always encrypted setting, else False</param>
            <returns>connection string with Column Encryption Setting set to Enabled or Disabled based on enableAlwaysEncrypted</returns>
        </member>
        <member name="T:AssemblyRef">
            <summary>
            Sets public key string for friend assemblies.
            </summary>
        </member>
        <member name="F:AssemblyRef.ProductPublicKey">
            <summary>No signing</summary>
        </member>
    </members>
</doc>
tools\dbatools\bin\smo\Microsoft.SqlServer.Diagnostics.Strace.dll
md5: 60A5B58D4811F7B789C46EA4A60C5D44 | sha1: E6AAE343BC4773003B778BF5093B614CDAE1A780 | sha256: 07513615219EC9F1D35F569F74F182F4A5DA7F993E7422EC3EBDA7236CC929DA | sha512: 8E2825B6A12AC3EBBF9182F37421B33139E71D1774F902A12D813F706D727E1ACCD1F0CB49972F0433CF91DD76D86667E3738AE8EDB22805763647BC48CCF9FD
tools\dbatools\bin\smo\Microsoft.SqlServer.Dmf.Common.dll
md5: F97ED27E3DFF82BB6916D9A7FCF4C96B | sha1: 619DD995541E9332B84B8ED78E67BA54EDCA1996 | sha256: 4A89D16E5729C78D05889392F92855B39B98CBABDB890593088EE70899E886DD | sha512: 13E9A1E31C20CA8DA65477016B686F22EE60801DDB81F20CE195D6521336231C45CB0505FCC162DEB6E4EB5FC97C1126937B935F90A6112B67BAC6EED72ABA86
tools\dbatools\bin\smo\Microsoft.SqlServer.Dmf.dll
md5: 8996E9E85A56CD6BE47185CB7EA7E054 | sha1: 040E099816CCD5C6894552B1F7FCF7D5938A86F9 | sha256: 359D48602701B565F9D78E88BDE599A8E57D900E80C4FF215EC953655C71F312 | sha512: 773726B775884F633CCCEFD9D4B44D9F004460EC2F3E6CDFC59B65C4AD80D1CEF3824B125B33BCC7AD1E15651D528C29618CCF1C5D8C8B58203DD0216FEDB71F
tools\dbatools\bin\smo\Microsoft.SqlServer.DmfSqlClrWrapper.dll
md5: 76CB51F60C62AED3179136345567052C | sha1: E5A923168B227C9161DB6EB325EFBBA98A29A593 | sha256: F1B48F092DD96FDCA48BF6D16CEA5087327EEA962D279A30CD1B221ECB295E97 | sha512: 6782765C846F97365DAE59F792851D555F83F6F3A8F8F754D827E59EA8BAF537B5D3D42156C4BDC16298EC06A39E3ABA27D8FCB2FE92581DF8F9A6922917A983
tools\dbatools\bin\smo\Microsoft.SqlServer.DtsServer.Interop.dll
md5: 217726D0FB27A5718769AF62538C1111 | sha1: E347612E002DD666D45BA10A8217D2A0847C2308 | sha256: 5633029110E2265F35B21BDB4A4A2561C260321A8C2F12C3BFC5A437E0B96A98 | sha512: 52CA20C1FF7A0E4294FD8DDCC859051E6296B9B4374E381BFC3990765F1B4998418EC361887518896D478D1FA41ABFBA7B7B3C5ABDACCBFD6220D355D6737E02
tools\dbatools\bin\smo\Microsoft.SqlServer.IntegrationServices.ClusterManagement.dll
md5: AD8E65431EB8DB24CF5FF5818F2EA91E | sha1: A32F02131517E57FCB83E22836FCB69BEE616959 | sha256: CFB08F61B05A200916FB0C38BF326582F1FA417D085DEFF558C27D65744FCAF8 | sha512: 6E4F1AC61A4A376FF77E1F269FF8840DA40E49CBB6D85960FCF1777BC08A917D90BE35D85FE10E10BB38F0E4A0DEE264B92D827AE7191012D81520C2B3442D76
tools\dbatools\bin\smo\Microsoft.SqlServer.IntegrationServices.ISServerDBUpgrade.dll
md5: 81246EDE8B7B4ABCA3A1E1E5BFD8E4DC | sha1: 38CB00A923BF9F895DDD5BAD9AA82D7135B55597 | sha256: E843499595D66EAAB818508EC84211735A49A7066965D5DC571FE2FA1E0ECCD8 | sha512: 475F646576E900C512BBDF2BC86C90F914FEA4F47F68951FE006FD8230F8D4E4F3BFA4198DE2C6EB62F541D2A9C86D9E040475D83821A75962F55A9741C1F296
tools\dbatools\bin\smo\Microsoft.SqlServer.IntegrationServices.Server.Common.dll
md5: D647ECCD24528FA56D7AC7BC8F2AE83E | sha1: 449020C537EC3194AAF257C1FC95D16430275263 | sha256: 12DE0550045DE4D9C9358FB8295529D293672E5B9E1C2B656A77B2D0F250D91D | sha512: 0E200918C96F4EBAAE6424F86890E256A1A78F14098C7111DC50A0D27CDC935B77D877AD816593CFDCD0BC5A1C86A02FC809A676B5C6083EAF5B8E6CD7A83005
tools\dbatools\bin\smo\Microsoft.SqlServer.IntegrationServices.Server.dll
md5: 004223AB64B373DCB3586615E3B8E4D4 | sha1: 0C4A3810F9D2866A7CEE78E3EBB2DA479EB7BDCF | sha256: E529EB3FBEBC65703A43618955FA734E85F3958A51D1BC8318D4B1234DCBF0E4 | sha512: 54EA36C5BB412EE78D8166CB3E03F7D8A9ED6CDCD9EAA98BD485A6C483B2070BCB7BD245FAEECEF6FFAD6710BAFA628879F99B189A2A26678FDE623249938022
tools\dbatools\bin\smo\Microsoft.SqlServer.IntegrationServices.Server.IPC.dll
md5: 012D68C5517F8F9C46321CA413BDA0A0 | sha1: AB98536551FD7AC656578F3DB3C7B430EC243A18 | sha256: 7E1701159A34FD657CCD8E364F973E84371A5317C23AF70735D75444A90EDAF2 | sha512: 3EBA6417A475928862CABBB05B2B1B9D351F1C67A782D5622EA117307738F2B6A4B9446EA1E6843276361B0EFB2D9AF40E27841C373593E84B2B20B6ADB52190
tools\dbatools\bin\smo\Microsoft.SqlServer.IntegrationServices.server.shared.dll
md5: 669589A39FB92BE6C172E80715F16BDE | sha1: 41E15C23E95935B59A587D0BA0BDAA563552A6F8 | sha256: 1CE7C5069F50B6F1E17CC94BFB1AA1C22D6CD240E33FF345EE09AF5A25B20A3A | sha512: 388E368C3C92700EF5E206DFD6E25CFD26CF86A500012750ED6A55AEAAF41B2FD295606222B9CEF395DB9795B73A534BE57FB04DEEA9401450A91562B806F691
tools\dbatools\bin\smo\Microsoft.SqlServer.IntegrationServices.SqlTaskScheduler.dll
md5: 85A7BAEF7FD06730AF3F01E6F0DCC6E3 | sha1: CCDC593F8DF2934C997DDF3D4596471019DC4F15 | sha256: 05DD2559C6639410472D57B1FADEDBC9CCA6EE91330ADD457F51FE8096E03268 | sha512: 8FFAC5289FBC1B653377332A5B03F0262F3CD6E761B2C1E877596607E1632F612B1E5D01B37AE588D6EA9FACC779E6A0C6DCE91AB6DD64B8A3F80A8E369B4FDE
tools\dbatools\bin\smo\Microsoft.SqlServer.IntegrationServices.TaskScheduler.dll
md5: 95F3B078B083EE46A1CD09C761B38CC8 | sha1: 1325FB4CC11A1DFFA405B274B23D9A2F0D1186AF | sha256: 64437046B67B757374662264C4A69BB1AFFA2C9F48A3AC25729716EB226E3302 | sha512: 3977034D77F146160C76758CEF6B21C27657C397294003BA66430B1F77339751DB65003B529811BC4BE31FA95362BA3857E2916439486C24C8354144766CC8C8
tools\dbatools\bin\smo\Microsoft.SqlServer.IntegrationServices.WorkerAgent.dll
md5: DB1BE51BC57A920A1677578687D1BB9D | sha1: 10E39F4C2560653F70E7DE20235A1C3F87A247D0 | sha256: CC67D9D707D0182979387A2B4576034DD744A3156E595CBD5E5EFB246CF228A1 | sha512: 7BBBF7D8313BA92DC7FB92402C5D08BB881EB3F4DA82C1BE4881B86D00525F352461DC6B15B83FC301A1E645CA5BAF9274EB2C8389F58C7B956F2C6B2AEE339F
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.AlwaysEncrypted.AzureKeyVaultProvider.dll
md5: E7603CA9A6D52FF1B94961FDBA21E907 | sha1: 93820B1A32F4339D7ACD231EC274B185555D8003 | sha256: 8354A28C3D206D09408391C2BC2F742313D7BA00CF819AB71F459C4CBA8EFAAF | sha512: 8796BC8EC8E0D19B2DC35B9DC580117C198A87EA238846F3DCB5D73A04530C71F98B43CDD4E8A811F0424C432EB50C8B9C39FF9E22425FBF3F41D5A2760AE58C
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.AlwaysEncrypted.Management.dll
md5: 218909BEBF9C6680C8272B80E138C203 | sha1: 856EE0E4CCF174B67FE7CAA67F32AF5B3D42590B | sha256: CF1E5D65439DA659F2E75B6D90BB70B3F2C41C8662748198E9BC140F8D3C5999 | sha512: 584C442B7CEE75DE2B310E89E64388CEC3215E71CE9802AECD343DA9B05AAD7C0592B12BCCB57C2B8EE03792336FE17698033E262839EA0A18C1024F5E35900F
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.AlwaysEncrypted.Types.dll
md5: 48A4AB642B38CE7A622393F14CF7FE3D | sha1: AE4D13678665596300E674B42F234CB31B4C2951 | sha256: B18D0599D9F09E0BFD994B738985CFB9BC9B16222E007520866532EBC23BBAF4 | sha512: C9ED2BAA2F57922394DC6EE69D246E889454B83994E46C579751007E02B148DB5854C1C874134BAB6B4BA99FD19C5B229FB8796683A2C7AC0B3E4485EC1CEC12
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.AzureAuthenticationManagement.dll
md5: 42DC8D5A51A02839A0F8CAD3193B0FDA | sha1: 7242310B52222C13120CBF8E9C2BBFC78B817BB4 | sha256: 7AC2D22FC6F209D9529CB75D41E2690AEBCBC8A50B52163FE46D370135ADB2C8 | sha512: 2292FE5EE8625F85C6FEA6F1D98CF9950C58606984E3ADEBA7AF4316EC164216B9E3BEAE02A5687BEA0BF7329C80867316267B3F2C508509D8B4D0D21C43D374
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.CloudAdapter.Client.dll
md5: C4E8BDA8352BAFC6479935E5BE681DE1 | sha1: D749BAB24DEA51365FC552F0DF27F7FBF7CC8C8D | sha256: A835EFA42DF0A03511F2000074FA2797C1CC0E191ADA5CC6855F1DD5BE718297 | sha512: 74921AB418C54B830F93C6CF9D75D5C6DF65A87A50FF00F6FD9B1E8BB3946FFB2DB1F45C536C8ED971E0E5633D807B8E770F58322271C8391C9C60C063CF5136
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.CloudAdapter.Data.dll
md5: 39833C208E63430932C4610B13609E74 | sha1: 3D788DA305935DCCC55D37A04E0A5F55642F7101 | sha256: B540D094ED65DAEA033124DCD59644501C33E5C675BA02658C020875E9036CEA | sha512: 4DF23A3A0C2E43C30D85FCF5626F688C1BBA58E1945097887F9FE86D40CBA1DF6D05B281DFB100AEDB3DE2185C9C3A6FE039751DD96AAC04719C6843B57A0563
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.Collector.dll
md5: 5E8707E3C01D543CB2CC187C9D751B13 | sha1: 48F677C285B243B3A9CB7E7F0A669885A36AEE30 | sha256: EA358BD759BF39E7AF61847FFD212D9F3F6792365818540FE4B7D34786B4D021 | sha512: DC42259F540C80C539B64B315A5AA721F57731B5B72C6A9C7F7AEA86001212C1B695A9575C452BB8B07983545945E58A1AD8CE3A9E741EA4B76952E2B94D2A88
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.CollectorEnum.dll
md5: F694E2DC474791E6DCF7AE2B45C87166 | sha1: 513ACDA265B9CA1737596876B5C7C6AF1A910DCA | sha256: B2CED4D657A9C6B088B34AFCF08C7861CB2D3C0AB86368E4CE29B071143A6B9A | sha512: 19ED17B7F89FB9C4A069DBDA9C039A9CB5BF5E0D2EF08A5400737A553371D8D75F8CC798B3BDD3FB776494F37323792A69A3501CD4AAD13D77B0EEE6802A1096
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.Dac.UniversalAuthProvider.dll
md5: E0B91845A09F9781E17E4D97A2DDDDB1 | sha1: 805CDED255C6E96405300DD38282DFB4448E42A8 | sha256: 118B5F900233D8829B441E2DF8D8112BD8D80D6EF01425288AF9516D582803A0 | sha512: F02AA7E0B8164C60056A59C23547C0AE3C1FE6CE8C6B2DB298FCF84DA4B7066126415497B5149BB4DB3DE13304744A6B4FED5CF5F9B4C639E89F33B725724A8B
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.HadrDmf.dll
md5: 668EDCC24CA7631D69A3AFD2A397FF64 | sha1: 4763D19FE90E5E3F60D2CCF1ECF68675A5254ACC | sha256: 43C3A35AFD6AE0E3687FCF10C68BDF77FB05867DE38BFC76BC23583B217D3B35 | sha512: E3A7DA94F4D1BAB7E689970E0A933737A870ED586D14F0203EBC62CC54CDFA4A8C2290D2DABF654F1D35AAA134DB7C768B8789658FDE8D294B0BC4B4CE2CDA2D
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.InMemoryOLTPMigrationAdvisor.dll
md5: 27744AA6BD5F100B8A80F1AFA3921EBE | sha1: 4BA98603E4D11DB78D51DD0547E9AFF49DC2DE78 | sha256: 19F283BE677540BF8889C71806BB66EA8D3E59B92EF6F6058E66F7CF9B3839BB | sha512: CE8F9663B537AD710D97992F53829DB11C64DD6259DB060289C6BCF566FF3253511D5F242058D084AA1B08AE3B0EE6CFAF7F65AC5F3C8B5C18B1112CED2B2B27
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.IntegrationServices.dll
md5: E3DDA0352B0088E2E98172332F431E6E | sha1: CF97B69757F6A4646F655B07DF305D29636BCE9A | sha256: 4DCE941B84109D54DD51461A548BFD8BB24E278A5C29CB125BE021913662DF29 | sha512: DB9B8DB6E0946F1C27D16C0E5EEFD56458185CFA01AC4F54CC3EE5FB721BC296B675C9BA0764DF46D3CD10040B144E81290E1F11CA5E64C344461EEBE4B439FD
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.IntegrationServicesEnum.dll
md5: 277465E94385E56877A2DD957576CB64 | sha1: 15A7EB00B77509DCF0536C1630DD4DA14AAF8B44 | sha256: DB4546E7CAD2261223EA2C47CC4BAAE99F694085D9348F370DF1CADF46FA0075 | sha512: D2903B3BDF1C96CC35B29A379482EB453F3F36C4BF8228C38412CA6CA7FC2F8FE5F61ADEEF4AC37DAE239E8AF73A86A8E6108630B7D71A7AFB35DD466A609610
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.RegisteredServers.dll
md5: 33E01BE5E65E6FAC06C95FFACE39EB51 | sha1: 74579D7B03125B349720772C1A97A4E00CAB1133 | sha256: ACB9E19B6A6CBC1B5CEE821A375ED4587D5C9D4AE5AA2DFA4F5CD62EBEF62749 | sha512: BFC124CFEAFDB4C197D7A2575252C318B48D29B6F0366AD482F296D8CE566DDC6F15C989D8932478E2969B500EEE21F737B806B7BA6A86DFE5A21DC14BBAC568
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.Sdk.Scripting.dll
md5: D3D12A68A3322D2B4BCABFDEC2A06720 | sha1: 5CF6A8AD74A678BBB90094953FD541C326B9B230 | sha256: F422258ADF43DE7C6E6EB8EEB55B3AB11E1E9F996CBE8A39E853E6E2241892CB | sha512: 847B4595930C96583A5883CE96330280B2B08176E58BDB2D36AABF321D5BC3A9031811A5EABCD1CCEDAEF2E2AF2209F5C0800F71F0DEB614F5DB576C59C1641E
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.Sdk.Sfc.dll
md5: A5D4E993C5F6C782AC33B49B68F1E27E | sha1: 5BD5CB47AFFFFD7E020D82189306BCB0FEC9A413 | sha256: 331194FC3A6A66982B6F775BBECF5199F7B8C5356A920BD44231160C63E02245 | sha512: 2CEC8182F0EAD3B73BB822FE9044AB8E2450159F7492577927830B11674A33AEDD8E454E0559E4694F3BAEF47EBF8320AC829F0A426338DB13FAD831F137F863
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.SDK.SqlStudio.dll
md5: 8EFB3CDBE1DE83CE0670C649B766A76D | sha1: 63743941BE3158C423CC678891B8AF57E6071008 | sha256: CDCC8AD5C0F3C20BE315FBC3C766A531C9BECC89AED80F92A16DC062ECA632F5 | sha512: B226AAE407AC080E8EF23C0D9125E4710B0BE878D0CB33C0D3D90CF11290ACA9CD816BC4DB626D4ABA2F667EC962FAD4903D637FC99DF7BD29C912025FA70F88
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.SmartAdminPolicies.dll
md5: 312A91796D44B1F2CE8D9D88BDD1B4E1 | sha1: C73C8477632C3547B38815A6C5A7141AF1902110 | sha256: 3C8DAA322542A081275EAF47FAF397A0E8D7B2E16FB4CF9BCED4A95C3F7D5A57 | sha512: 047C51512653A437C1B0176E1CF62975BC76783A584B2A3BC3EBC849C443C0A5624AAE6E259F44064EEFCFFBD1B842C759B45072F5312A2AF82FA5485759AAC4
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.Utility.dll
md5: E2F350C2D2E5F7BCCB538FC002B1D42B | sha1: B18679210D8A2539A813C2A742C61C8970214D29 | sha256: DA19A0C3E5E3759D49E9BEF4F9B6AFAC6933DCF033F5A2A7D5ABF7B056FB90D2 | sha512: 2EAAB9572048A25D20B9D8EB707EC302C795692D807FE4DF90DBE2DAA3C708B7BAEAAD536C0D426AA10D7C4BE29BE139193690A761008DD850740ECBB21E7B66
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.UtilityEnum.dll
md5: 808537ADDDBC7F9D7CB7C0C590DF692C | sha1: A59A90B4A2EB2106BCAD60E8FD2262F83794E018 | sha256: 81EF6AB722C276E6E022BAF21C1E83E879D56592BB6319AB25FEAF90D798EA62 | sha512: 070F15885253EEFAF0832BFA2502900B292FB31DE10432EECF30E23444232DD8FC9E06036ACB46BAB808FE5D663DE19105F5D01E9EBBE319C417209ACD0F8814
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.XEvent.dll
md5: 277A3D4FB1362CCD4A33C7D4FF4A9EA4 | sha1: FFF47A49D5EA68C2B42663F85C07FFDF54D91807 | sha256: 74DCAF578AF7E821F8D7A278A551F4DC354C0B5929679A9CF9E849DE8CEA3EC0 | sha512: C8C75EB4C3ECFFE1B43FE6B1E7312077AD73938946E676A336160CAA427C6EBDC091F7910A41F17C7105280AC05F52E58927DEC71ED79117E8214067F50A5441
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.XEventDbScoped.dll
md5: 08BD89DB5649CFB1873974BEBF95F218 | sha1: 32AE7370218C0123F80679FA38E5A94B0F87D531 | sha256: 3934CC842ECAAF05B0F7EE5F39540688BC04ED0F43F188B6F5CB127B0136CD18 | sha512: F7BA41D2B997B3447E0DEFA758C4EF93045E1491D7C9F5C013897256178EE4F62386F78E2FB80E63E7B36D2A25FFB2C4FA84CCE088915CD4571E5901B6C9A301
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.XEventDbScopedEnum.dll
md5: 1E712AF4C36FB1E35F9BF79CA217E159 | sha1: FFEBD9FCB08005A35FA53963183B9E661F9B2263 | sha256: B3EAC5B9B2B5D608861FFDAAC7F788E027EE4329949621FFEC709DBD4D2232E9 | sha512: 2C1F9F494BD6F2551FC9083BE629DD840C68AA7C5E37323F071E0F5DFA239A6EAA6630ADCB7A46B73E8397C2529A595074BBE16CAB596D2F38DADED02BC857DB
tools\dbatools\bin\smo\Microsoft.SqlServer.Management.XEventEnum.dll
md5: 57BD65925D90B9ACD8234CA0785F4656 | sha1: 74A4919CD3A1099F00FB989F0AD93F9124C42C41 | sha256: 68562C7EA2F0070C8B81A15653F8950C4A2BE8CDE8D829BF2A2DDF4288B748FF | sha512: 2EEDDE3CF5700571A072F11C7DC6824549333EFAFDE684F511B0517595149088287706EB2C9B74D58C937721C19AF1AF49E8CBB92E1100F3ADD938C5322C591C
tools\dbatools\bin\smo\Microsoft.SqlServer.OlapEnum.dll
md5: 0B480897CB1E688BCAD14B4905BDD4F0 | sha1: 24EE4CBA735262D79FBB9B7AAECF9E288ED3EF14 | sha256: 969BD6F5B1C5D559782F8E87CBDD2C627CF639CF595BDDF4B559000D656328DB | sha512: 8D363FAF072519B8E9DDEA38462A8F12400D4025B0D6928B50718D315F8C7799B6CAC3E4CD421F184F5434ACEE4B83BA6ADED993965C53A69382887351C9B129
tools\dbatools\bin\smo\Microsoft.SqlServer.PolicyEnum.dll
md5: 581FB98877A22BA2A7EA3DF6B7130282 | sha1: 2F63F652416B40222FA444CF8E91405BBA26BA3B | sha256: 3A311FBBC53F5168E6E5030F7CF446A1E096B4F00A01590C8E369BCFCC5F1E19 | sha512: 2736E9F00D491382B87A4E79B04A49C41B203D8B82D74FEDE75026FAEC31A43CCBC9E07300F19E14A057A456CCE03DCE1CCA2FA651D4A6CABF7E257247115159
tools\dbatools\bin\smo\Microsoft.SqlServer.RegSvrEnum.dll
md5: 5890D898EDE91AAE18FE5A7A610DFEFC | sha1: 6E2504763E14B59FC847124DADCEC942C03B9247 | sha256: 997A08FBB4F698562CC497A061D23B60BE2B2889F4CBD3E74EC745C9C820D53E | sha512: 3614A66B9A6AE2CD21C7E4070CBF53AB1EEABF747EBE66E28E0CC0B6AD1A9B108179BBB3C09637F05B5B95CC39ED17FA721425A967B452AF030352EB91B55AC2
tools\dbatools\bin\smo\Microsoft.SqlServer.ReplEnum.dll
md5: 7D7BE01C1C2EBB973ABA33F7587FE04E | sha1: 2EE9CD9A998450729D79DD3A570948F61886510A | sha256: FA54A93E59A7FDEF47189A89B5B44ED466F1EEC092C3668A3FCEDB1975EF30A7 | sha512: 61CBA8EF9B02F457F6B057BB76BE697D05E8265EA2C10C020EF26EB31F603CB763A3550A71EFAE186CBB7376E3FE8802B1B1A797B666A4735A01395806BFB6D5
tools\dbatools\bin\smo\Microsoft.SqlServer.Replication.BusinessLogicSupport.dll
md5: CC304F5AA02D499866C037FE08EA24B0 | sha1: 21803E2AAE89A4F74E10453881A361F9DC59A8AA | sha256: DDE7397FDEB22206308931F6DA0DD2FE0E93F8AF97C1842C4D8B1688EBC7632E | sha512: FE21E3E0A37F1BC47A8F434005ED94DD6A94341D6099E4F288E6A1F78CADC98A7624564094C62022F6F80370C8C647D8F663A8DEC515300708C69326D0F24F79
tools\dbatools\bin\smo\Microsoft.SqlServer.Replication.dll
md5: 4E575BC1534DD45D1F32069A29D261CA | sha1: 34CC055999FC47534C70DE709037A7B7CD54D04E | sha256: 10F625817467AC23F55489CF84DA1C060859219BDD6B75B77A2CDD00F16509C4 | sha512: 6D06896FD901BAA6FFC066C8DEF634FA5214C0A222B9C2E534FCBC522EA82A44F2099B0872F93C2740AD7511CF02CD7B2AAADAADF6265FB5EAA4F1F50C4F9FB6
tools\dbatools\bin\smo\Microsoft.SqlServer.Rmo.dll
md5: 56A459CAB89BF18CD183490CE1BB7909 | sha1: E90C37447D7EA4EFAEEA58ABE3307CA97249213C | sha256: C16BE1791F423EE813AAC7E17E611A8A783FF2BA9B2BA12ED1A2992D5DC943FA | sha512: A9AA3F818D07E6D0F97B80FCAC994C7E50BDA286F489A7D20785C8A982B20E9088F9A38B3AF0D8B22D04449679704D887F3EF8B8986EF4CFADC0ACF99197BB97
tools\dbatools\bin\smo\Microsoft.SqlServer.ServiceBrokerEnum.dll
md5: CA09568CB5870FE4A7A431C726EF7894 | sha1: 72B0477EE1C843ADE4DADD0836636DA3C3A188BA | sha256: 7DE4C88949F8FAAE9AE8A9F6E494196FD4429DAD42F5E6269E9074FD70273F2F | sha512: D9FCFD3C67ADF76F1E9ED32EFFDE301BE99F8EAEDC38C11552772B097EE2EB94E8F92862184678A64EB6BD5BFC81B079B4F7BF44E6037E853EADA98ADB43F243
tools\dbatools\bin\smo\Microsoft.SqlServer.Smo.dll
md5: 6097BEBF3019EB269D6F0182899FDB51 | sha1: 90859109A74C7EAADD3D8E0A7BBC88198604F397 | sha256: F447685772B53977788255529661E372E43BB5FB776115E284BFD1A822E9E0C8 | sha512: 9AD640031D6323B4C90AE4968B45C1894FF4DEDD8B518FFF268FDE2C13E7E916EA9633F5BFDAEDE3C559E8436B72B3D511CB0B5C0FC0CF4F447511BC7F0D392F
tools\dbatools\bin\smo\Microsoft.SqlServer.SmoExtended.dll
md5: F5D99DB45C64A478C73D70531420DF36 | sha1: 397A46EF196684ABA88672B7305D7A908E421059 | sha256: 418903A38CA85F2EA4EA31E308AAFE3C3CCB11B272E4EC0379F6AF9D3954200E | sha512: B58A582324F989A66BE060413C1BC06169D7A6E632A55E5F3C9B6B2B8EE42E6BA88DC1CF6BB05AE1DF48E036B2AE2952DFFF2F9A3125052E3AF708F0DB3FB08B
tools\dbatools\bin\smo\Microsoft.SqlServer.SqlClrProvider.dll
md5: 6CC17DD0A193D295744060E928F023A9 | sha1: 4B44EEE2ED8DED8C80C2576EEB63B027F02FC035 | sha256: 10EAA6597D7088D87ED9381FBD6FCDDD54156D7A32C1BC0C6E3A2B209CD9B3C9 | sha512: BC4B6B6AFA566248E6507691F4AF1286ABEEA60773908E1E0484F6E3107689B2A0A45A9CC46C1D05DA91349B90F1EA8A85CCDCB0954471B19B85B83CC16A5D7C
tools\dbatools\bin\smo\Microsoft.SqlServer.SqlEnum.dll
md5: F61256335158769DB203C5B975A92C89 | sha1: ECF3EC80DE98A265CFABD03FA7D62D07C6D48371 | sha256: 0AE5D2C8762B761EC9DA84A7A2F6BED55B4054F8B6B6CC8F8B93CED2B0CB528C | sha512: 039082C55A3B5160E7A845F7797990B8CB266A9958077481EA7C613E37F49C0771657769739607A21A217199D189CB5EB43C49C37F194F5EA72DE70463D3358B
tools\dbatools\bin\smo\Microsoft.SqlServer.SqlTDiagm.dll
md5: 48FBD39370EE8AB525D703DCD560D059 | sha1: 0B4C3A5E9302FAE1C33B026FA3DAA22C47CEC364 | sha256: 32B79A8B4074B85489D7E0470D7E0EAE01992C7C14F6C8CF5578F4C855B5B304 | sha512: A295F434621D723B4F7FFE0C47E96AC73E10CA3AE71916054F127E25A223AD489E0B2C049BFA1FD9988000C82DB3C0AEF630C9A4CD27C5B9CAFBBC677647F581
tools\dbatools\bin\smo\Microsoft.SqlServer.SqlWmiManagement.dll
md5: 72A3A35A2991209FC316A9CA97FE93F7 | sha1: 1E81DCB081D49E9F149747754BF2D6A7598C5059 | sha256: CEF10D42FA3DDF73594685F4B6992C269E2A1D3B02B601E32E07D78C78801E5B | sha512: D3905773E84F45F41F590A1B2EFAAFDA73D181D1EB6CD8E43E0D87ADF05E16736A9E2B8B8BA74627356CAA505C9DFFEA5DDBF9AE8C4E704903773CE07E584B03
tools\dbatools\bin\smo\Microsoft.SqlServer.SString.dll
md5: 205163310761A94A9AC099CE9BDE75DD | sha1: 5B49C76A0B6B23B92FD487C4F2D48C4FD9E38F1A | sha256: 7266EC1582F9B9486D12C05BDF10787B844DB67262A3389F1119D4C747424C18 | sha512: 4F18CA9CB1CDFC954221C6E4F3FF84E845BA5D04FF4E2EF6431633BC8A21F6762A759777A19EB7C06C9CC951F852DED62EA59D2311BADC097C004D83D17DF976
tools\dbatools\bin\smo\Microsoft.SqlServer.TransactSql.ScriptDom.dll
md5: A0ED30A95E8F5D5DC8727141A4DE3EBE | sha1: C439A0A056A028467FE4AA9D5A0B69365A719448 | sha256: 89708A0EEAFEFA5153103613E45750B4774CAD15EE1FD38EB5DBC9F9FFD1A465 | sha512: B693B27A2960D8F4E87905DC70004B749D8B3D5ED08360CC91705F0CAC507688168CAE8B2479BAEC1DD2517579A9AA8952781528A533E3EB8A23095DD0ECCAFE
tools\dbatools\bin\smo\Microsoft.SqlServer.VulnerabilityAssessment.Model.dll
md5: 5CDDEC5F7A85FAB81229795D6B660E70 | sha1: C6FF70DC95C725789A1D3EF1F796E44408C1B1BA | sha256: B7FC87FB2BCBB26D124E4D97EEAC1B50B2D515C1377DEE90A857A70BA167888F | sha512: A9B86579858F45BF96A8B521E5951AC954CB97344258CC5BF0D08687049986D6DAB3EAEC27C5946CDE344657F7CF1D142E13CB43F0EBFFFF534A7D80E437BC64
tools\dbatools\bin\smo\Microsoft.SqlServer.WmiEnum.dll
md5: 93C592750C90C91F4DB29B30CCC95876 | sha1: 9A2C69ED060F6FB1B988C2EE6B33B2AF1A5DB377 | sha256: 52FBC6F7A51ED206540CF1B11C0D24FE1BC952CBFBD3AFAAC03BAB0FF5BE815F | sha512: E2860813ED0445CC09365899320306A2DF16ECCB5499FCA6569E561A83E640B851EC508D812705F4D1DC6733152650E74AFB56B135B79178FEFDDE7869BC0D25
tools\dbatools\bin\smo\Microsoft.SqlServer.XE.Core.dll
md5: E2534DF2B4AAAD8D152A4436B141F895 | sha1: 1EE6EA02FC5CF603FAFDCA4DF8587F467E66402C | sha256: 74013AB7594C22571AE440D348EB2280B1DEA3187E362281769593D21625A731 | sha512: 4532E4B44D354C423855A94D8812EC7F183234D9992CD030E939621888109FE8DDECF9BFBFBEF162FE3D4B1C6C578D23103963EC03EEACF0FD6447418B7C6250
tools\dbatools\bin\smo\Microsoft.SqlServer.XEvent.Configuration.dll
md5: CA315AB021FAE0283195955A28B22273 | sha1: CA1A95C2785AB0201A9F1CDE582FFB3A6FE5D15D | sha256: E379B6DD301EFFBCCC0F22DF1C4AAAC146529ED86D5D3C1D1E2346B6B7555F23 | sha512: 02C109B03FA403EF7705295FC5182AADAB83D365546FC99E577F24CBBD7CF72467151FBC431B8783EE48B98BF095EFE84615F08971F3BE6220D473AC6FD85FA3
tools\dbatools\bin\smo\Microsoft.SqlServer.XEvent.dll
md5: EDD9944177424E14524D0B611374EF62 | sha1: 0D9AB9196D10D422CB653243A0F246899F1E34AD | sha256: BF8FBFCF1E48CD08E320DCBCCA0817E0CD6F2DB2F6FC330E196C28146DD32D94 | sha512: 349CA5C0B0CF16AEB232D38B1DFCD869F6954CADB73642E564AF63B7EB59159DFE5644E7FA9CABF762752644F26A9520F4E3397CC255BD4A49E9577B897C4CD3
tools\dbatools\bin\smo\Microsoft.SqlServer.XEvent.Linq.dll
md5: AE6A7A45C02F5E6CA119DB7FE2AE9823 | sha1: 565A2E3169B915289202F6E0134E35B51427D6EF | sha256: 47F4E5566A37AA9E2C295695D3AF5E4777240E25821746922477856AE207B778 | sha512: 808DB8F41D649E0156A66869083C0A35CB0BC726EB9E4B550B966AAB3CA2923531E6E57424DC0C4A40E70FF712A1E779E6721D4C80B092C71507018A9FB80DB9
tools\dbatools\bin\smo\smo-deps.txt
$phase1 = @()
$leftover = @()
dir | %{

 $file = $_
 try
 {
 Add-Type -Path $_.FullName -ErrorAction Stop
 $phase1 += $_.FullName
 }
 catch { $leftover += $file.FullName }
}

$dep = @()
dir | %{
    try { Add-Type -Path $_.FullName -ErrorAction Stop }
    catch { $_.Exception.LoaderExceptions.FileName | %{ $dep += $_ }}
}
$dep | select -unique
tools\dbatools\bin\smo\sqlpackage.exe
md5: 6C1C817073FB51447EF5097D4E1ED382 | sha1: 74C64BEE4897FF3CB0868C7A8F41CF86524B41B6 | sha256: A42C4410CF8448F59D3C6D4FD0E06DE5BC3005F7AF1D14401B83A6B706F5EC54 | sha512: EA49143B8EE1E65EF4414F3F38BA0424376C6DF147811C0CBD9FCDD81C451C6573C0FE27A98DB4CD79A89F5399FDEEC4FA19EB4E886251B023AFA78BAA12999F
tools\dbatools\bin\smo\sqlpackage.exe.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/>
  </startup>
  <system.diagnostics>
    <!-- 
      Uncomment the settings below to enable tracing.
      Update the initializeData for the TextLogger with the desired trace file path.
    -->
    <!--
    <sources>
      <source name="Microsoft.Data.Tools.Diagnostics.Tracer" switchValue="Error">
        <listeners>
          <add name="TextLogger"
               type="System.Diagnostics.TextWriterTraceListener"
               initializeData="sqlpackage.trace.log"
               traceOutputOptions="DateTime, ThreadId" />
        </listeners>
      </source>
    </sources>
    -->
  </system.diagnostics>
  <!--
  The below runtime setting is a workaround for an issue resulting from a known breaking change in the SQL Server 2012 version of the System CLR Types. The original breaking change and resulting issue are both documented in the “SQL CLR Data Types” section of http://go.microsoft.com/fwlink/?LinkID=271559.
  -->
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.SqlServer.Types" publicKeyToken="89845dcd8080cc91" culture="neutral" />
        <bindingRedirect oldVersion="10.0.0.0-13.0.0.0" newVersion="14.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.SqlServer.TransactSql.ScriptDom" publicKeyToken="89845dcd8080cc91" culture="neutral"/>
        <bindingRedirect oldVersion="12.0.0.0-13.100.0.0" newVersion="14.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.SqlServer.Dac" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="11.0.0.0-13.0.0.0" newVersion="14.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.SqlServer.Dac.Extensions" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="11.0.0.0-13.0.0.0" newVersion="14.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
tools\dbatools\bin\sp_SQLskills_ConvertTraceToEEs.sql

/*****************************************************************************
*   FileName:  sp_SQLskills_ConvertTraceToExtendedEvents.sql
*
*   Summary:   Converts a SQL Trace definition on a SQL Server to a Extended
*                       Events Session using the SQLskills_Trace_XE_Column_Map table
*              to map the column definitions across.
*
*   Date:      October 2014
*
*   SQL Server Versions:
*                       2012, 2014
*         
******************************************************************************
*   Copyright (C) 2011 Jonathan M. Kehayias, SQLskills.com
*   All rights reserved. 
*
*   For more scripts and sample code, check out 
*      http://sqlskills.com/blogs/jonathan
*
*   You may alter this code for your own *non-commercial* purposes. You may
*   republish altered code as long as you include this copyright and give 
*      due credit. 
*
*
*   THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF 
*   ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED 
*   TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
*   PARTICULAR PURPOSE. 
*
******************************************************************************/

-- Slight modifications and performance optimizations 
-- by Gianluca Sartori and Chrissy LeMaire

DECLARE @TraceID INT = --TRACEID--
DECLARE @SessionName NVARCHAR(128) = '--SESSIONNAME--'
DECLARE @PrintOutput BIT = 1
DECLARE @Execute BIT = 0

SET NOCOUNT ON

CREATE TABLE [#SQLskills_Trace_XE_Column_Map](
       [trace_event_id] [int] NOT NULL,
       [trace_column_id] [int] NOT NULL,
       [event_package_name] [nvarchar](60) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
       [xe_event_name] [nvarchar](60) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
       [column_name] [nvarchar](256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
       [action_package_name] [nvarchar](60) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
       [xe_action_name] [nvarchar](60) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]

CREATE CLUSTERED INDEX CX_#SQLskills_Trace_XE_Column_Map ON [#SQLskills_Trace_XE_Column_Map](trace_event_id, trace_column_id)
INSERT INTO [#SQLskills_Trace_XE_Column_Map]
SELECT 
       te.trace_event_id,
       tc.trace_column_id AS trace_column_id,
       txem.package_name AS event_package_name,
       txem.xe_event_name,
       tab.column_name,
       CASE WHEN tab.column_name IS NOT NULL THEN NULL ELSE txam.package_name END AS action_package_name,
       CASE WHEN tab.column_name IS NOT NULL THEN NULL ELSE txam.xe_action_name END AS xe_action_name
FROM sys.trace_events AS te
JOIN sys.trace_categories AS cat
       ON te.category_id = cat.category_id
JOIN sys.trace_event_bindings AS teb
       ON te.trace_event_id = teb.trace_event_id
JOIN sys.trace_columns AS tc
       ON teb.trace_column_id = tc.trace_column_id
JOIN sys.trace_xe_event_map AS txem
       ON te.trace_event_id = txem.trace_event_id
LEFT JOIN (
          SELECT  p.name AS event_package_name,
                  o.name AS event_name,
                  oc.name AS column_name
          FROM sys.dm_xe_objects AS o
          INNER JOIN sys.dm_xe_object_columns AS oc 
              ON o.name = oc.object_name 	
              AND o.package_guid = oc.object_package_guid
          CROSS APPLY (
              SELECT name
              FROM sys.dm_xe_packages
              WHERE guid = o.package_guid
                  AND (capabilities IS NULL OR capabilities & 1 = 0)
          ) AS p
          WHERE (o.capabilities IS NULL OR o.capabilities & 1 = 0)
              AND o.object_type = 'event'
              AND oc.column_type = 'data'
       ) as tab
       ON tab.event_package_name COLLATE SQL_Latin1_General_CP1_CI_AS = txem.package_name COLLATE SQL_Latin1_General_CP1_CI_AS
              AND tab.event_name COLLATE SQL_Latin1_General_CP1_CI_AS = txem.xe_event_name COLLATE SQL_Latin1_General_CP1_CI_AS
              AND CASE
                        WHEN tc.name = 'ObjectID' THEN 'object_id'
                        WHEN tc.name = 'Type' THEN 'object_type'
                        --WHEN tc.name = 'NestLevel' THEN 'nest_level'
                        WHEN tc.name = 'ObjectName' THEN 'object_name'
                        WHEN tc.name = 'DatabaseID' THEN 'database_id'
                        WHEN tc.name = 'DatabaseName' THEN 'database_name'
                        WHEN tc.name = 'IndexID' THEN 'index_id'
                        WHEN tc.name = 'Reads' THEN 'logical_reads'
                        WHEN tc.name = 'CPU' THEN 'cpu_time'
                        WHEN tc.name = 'RowCounts' THEN 'row_count'
                        --WHEN tc.name = 'Severity' THEN 'error_severity'
                        --WHEN tc.name = 'Type' THEN 'object_type'
                        WHEN tc.name = 'Error' THEN 'error_number'
                        ELSE tc.name
                  END = tab.column_name
LEFT JOIN sys.trace_xe_action_map AS txam
       ON tc.trace_column_id = txam.trace_column_id
WHERE cat.name NOT IN ('User configurable')
  AND tc.name NOT IN ('EventClass', 'StartTime', 'EndTime')
  AND (tab.column_name IS NOT NULL
              OR txam.xe_action_name IS NOT NULL)
UNION ALL 
SELECT 
       CAST(trace_event_id AS INT) AS trace_event_id, 
--     trace_event_name, 
       CAST(trace_column_id AS INT) AS trace_column_id, 
--     trace_column_name, 
       event_package_name, 
       xe_event_name, 
       NULLIF(column_name, '') AS column_name, 
       NULLIF(action_package_name, '') AS action_package_name,
       NULLIF(xe_action_name, '') AS xe_action_name
FROM
(
       VALUES 
              ('10', 'RPC:Completed', '1', 'TextData', 'sqlserver', 'rpc_completed', 'statement', '', ''),
              ('10', 'RPC:Completed', '31', 'Error', 'sqlserver', 'rpc_completed', 'result', '', ''),
              ('11', 'RPC:Starting', '1', 'TextData', 'sqlserver', 'rpc_starting', 'statement', '', ''),
              ('12', 'SQL:BatchCompleted', '1', 'TextData', 'sqlserver', 'sql_batch_completed', 'batch_text', '', ''),
              ('12', 'SQL:BatchCompleted', '31', 'Error', 'sqlserver', 'sql_batch_completed', 'result', '', ''),
              ('13', 'SQL:BatchStarting', '1', 'TextData', 'sqlserver', 'sql_batch_starting', 'batch_text', '', ''),
              ('14', 'Audit Login', '1', 'TextData', 'sqlserver', 'login', 'options_text', '', ''),
              ('14', 'Audit Login', '2', 'BinaryData', 'sqlserver', 'login', 'options', '', ''),
              ('14', 'Audit Login', '25', 'IntegerData', 'sqlserver', 'login', 'packet_size', '', ''),
              ('17', 'ExistingConnection', '1', 'TextData', 'sqlserver', 'existing_connection', 'options_text', '', ''),
              ('17', 'ExistingConnection', '2', 'BinaryData', 'sqlserver', 'existing_connection', 'options', '', ''),
              ('17', 'ExistingConnection', '25', 'IntegerData', 'sqlserver', 'existing_connection', 'packet_size', '', ''),
              ('18', 'Audit Server Starts And Stops', '21', 'EventSubClass', 'sqlserver', 'server_start_stop', 'operation', '', ''),
              ('19', 'DTCTransaction', '2', 'BinaryData', 'sqlserver', 'dtc_transaction', 'unit_of_work_id', '', ''),
              ('19', 'DTCTransaction', '21', 'EventSubClass', 'sqlserver', 'dtc_transaction', 'transaction_state', '', ''),
              ('19', 'DTCTransaction', '25', 'IntegerData', 'sqlserver', 'dtc_transaction', 'isolation_level', '', ''),
              ('21', 'EventLog', '1', 'TextData', 'sqlserver', 'error_reported', 'message', '', ''),
              ('22', 'ErrorLog', '1', 'TextData', 'sqlserver', 'errorlog_written', 'message', '', ''),
              ('23', 'Lock:Released', '1', 'TextData', 'sqlserver', 'lock_released', 'resource_description', '', ''),
              ('23', 'Lock:Released', '2', 'BinaryData', 'sqlserver', 'lock_released', 'lockspace_workspace_id', '', ''),
              ('23', 'Lock:Released', '52', 'BigintData1', 'sqlserver', 'lock_released', 'resource_2', '', ''),
              ('23', 'Lock:Released', '56', 'ObjectID2', 'sqlserver', 'lock_released', 'associated_object_id', '', ''),
              ('23', 'Lock:Released', '57', 'Type', 'sqlserver', 'lock_released', 'resource_type', '', ''),
              ('23', 'Lock:Released', '58', 'OwnerID', 'sqlserver', 'lock_released', 'owner_type', '', ''),
              ('24', 'Lock:Acquired', '1', 'TextData', 'sqlserver', 'lock_acquired', 'resource_description', '', ''),
              ('24', 'Lock:Acquired', '2', 'BinaryData', 'sqlserver', 'lock_acquired', 'lockspace_workspace_id', '', ''),
              ('24', 'Lock:Acquired', '52', 'BigintData1', 'sqlserver', 'lock_acquired', 'resource_2', '', ''),
              ('24', 'Lock:Acquired', '56', 'ObjectID2', 'sqlserver', 'lock_acquired', 'associated_object_id', '', ''),
              ('24', 'Lock:Acquired', '57', 'Type', 'sqlserver', 'lock_acquired', 'resource_type', '', ''),
              ('24', 'Lock:Acquired', '58', 'OwnerID', 'sqlserver', 'lock_acquired', 'owner_type', '', ''),
              ('25', 'Lock:Deadlock', '1', 'TextData', 'sqlserver', 'lock_deadlock', 'resource_description', '', ''),
              ('25', 'Lock:Deadlock', '2', 'BinaryData', 'sqlserver', 'lock_deadlock', 'lockspace_workspace_id', '', ''),
              ('25', 'Lock:Deadlock', '25', 'IntegerData', 'sqlserver', 'lock_deadlock', 'deadlock_id', '', ''),
              ('25', 'Lock:Deadlock', '56', 'ObjectID2', 'sqlserver', 'lock_deadlock', 'associated_object_id', '', ''),
              ('25', 'Lock:Deadlock', '57', 'Type', 'sqlserver', 'lock_deadlock', 'resource_type', '', ''),
              ('25', 'Lock:Deadlock', '58', 'OwnerID', 'sqlserver', 'lock_deadlock', 'owner_type', '', ''),
              ('26', 'Lock:Cancel', '1', 'TextData', 'sqlserver', 'lock_cancel', 'resource_description', '', ''),
              ('26', 'Lock:Cancel', '2', 'BinaryData', 'sqlserver', 'lock_cancel', 'lockspace_workspace_id', '', ''),
              ('26', 'Lock:Cancel', '52', 'BigintData1', 'sqlserver', 'lock_cancel', 'resource_2', '', ''),
              ('26', 'Lock:Cancel', '56', 'ObjectID2', 'sqlserver', 'lock_cancel', 'associated_object_id', '', ''),
              ('26', 'Lock:Cancel', '57', 'Type', 'sqlserver', 'lock_cancel', 'resource_type', '', ''),
              ('26', 'Lock:Cancel', '58', 'OwnerID', 'sqlserver', 'lock_cancel', 'owner_type', '', ''),
              ('27', 'Lock:Timeout', '1', 'TextData', 'sqlserver', 'lock_timeout', 'resource_description', '', ''),
              ('27', 'Lock:Timeout', '2', 'BinaryData', 'sqlserver', 'lock_timeout', 'lockspace_workspace_id', '', ''),
              ('27', 'Lock:Timeout', '56', 'ObjectID2', 'sqlserver', 'lock_timeout', 'associated_object_id', '', ''),
              ('27', 'Lock:Timeout', '57', 'Type', 'sqlserver', 'lock_timeout', 'resource_type', '', ''),
              ('27', 'Lock:Timeout', '58', 'OwnerID', 'sqlserver', 'lock_timeout', 'owner_type', '', ''),
              ('28', 'Degree of Parallelism', '2', 'BinaryData', 'sqlserver', 'degree_of_parallelism', 'dop', '', ''),
              ('28', 'Degree of Parallelism', '21', 'EventSubClass', 'sqlserver', 'degree_of_parallelism', 'statement_type', '', ''),
              ('28', 'Degree of Parallelism', '25', 'IntegerData', 'sqlserver', 'degree_of_parallelism', 'workspace_memory_grant_kb', '', ''),
              ('34', 'SP:CacheMiss', '1', 'TextData', 'sqlserver', 'sp_cache_miss', 'cached_text', '', ''),
              ('34', 'SP:CacheMiss', '28', 'ObjectType', 'sqlserver', 'sp_cache_miss', 'object_type', '', ''),
              ('35', 'SP:CacheInsert', '1', 'TextData', 'sqlserver', 'sp_cache_insert', 'cached_text', '', ''),
              ('35', 'SP:CacheInsert', '28', 'ObjectType', 'sqlserver', 'sp_cache_insert', 'object_type', '', ''),
              ('36', 'SP:CacheRemove', '1', 'TextData', 'sqlserver', 'sp_cache_remove', 'cached_text', '', ''),
              ('36', 'SP:CacheRemove', '21', 'EventSubClass', 'sqlserver', 'sp_cache_remove', 'remove_method', '', ''),
              ('36', 'SP:CacheRemove', '28', 'ObjectType', 'sqlserver', 'sp_cache_remove', 'object_type', '', ''),
              ('37', 'SP:Recompile', '1', 'TextData', 'sqlserver', 'sql_statement_recompile', 'statement', '', ''),
              ('37', 'SP:Recompile', '21', 'EventSubClass', 'sqlserver', 'sql_statement_recompile', 'recompile_cause', '', ''),
              ('37', 'SP:Recompile', '28', 'ObjectType', 'sqlserver', 'sql_statement_recompile', 'object_type', '', ''),
              ('37', 'SP:Recompile', '29', 'NestLevel', 'sqlserver', 'sql_statement_recompile', 'nest_level', '', ''),
              ('37', 'SP:Recompile', '55', 'IntegerData2', 'sqlserver', 'sql_statement_recompile', 'offset_end', '', ''),
              ('38', 'SP:CacheHit', '1', 'TextData', 'sqlserver', 'sp_cache_hit', 'cached_text', '', ''),
              ('38', 'SP:CacheHit', '28', 'ObjectType', 'sqlserver', 'sp_cache_hit', 'object_type', '', ''),
              ('40', 'SQL:StmtStarting', '1', 'TextData', 'sqlserver', 'sql_statement_starting', 'statement', '', ''),
              ('40', 'SQL:StmtStarting', '29', 'NestLevel', 'sqlserver', 'sql_statement_starting', '', 'sqlserver', 'tsql_stack'),
              ('40', 'SQL:StmtStarting', '55', 'IntegerData2', 'sqlserver', 'sql_statement_starting', 'offset_end', '', ''),
              ('41', 'SQL:StmtCompleted', '1', 'TextData', 'sqlserver', 'sql_statement_completed', 'statement', '', ''),
              ('41', 'SQL:StmtCompleted', '25', 'IntegerData', 'sqlserver', 'sql_statement_completed', 'row_count', '', ''),
              ('41', 'SQL:StmtCompleted', '29', 'NestLevel', 'sqlserver', 'sql_statement_completed', '', 'sqlserver', 'tsql_stack'),
              ('41', 'SQL:StmtCompleted', '55', 'IntegerData2', 'sqlserver', 'sql_statement_completed', 'offset_end', '', ''),
              ('42', 'SP:Starting', '1', 'TextData', 'sqlserver', 'module_start', 'statement', '', ''),
              ('42', 'SP:Starting', '28', 'ObjectType', 'sqlserver', 'module_start', 'object_type', '', ''),
              ('42', 'SP:Starting', '29', 'NestLevel', 'sqlserver', 'module_start', '', 'sqlserver', 'tsql_stack'),
              ('42', 'SP:Starting', '62', 'SourceDatabaseID', 'sqlserver', 'module_start', 'source_database_id', '', ''),
              ('43', 'SP:Completed', '1', 'TextData', 'sqlserver', 'module_end', 'statement', '', ''),
              ('43', 'SP:Completed', '28', 'ObjectType', 'sqlserver', 'module_end', 'object_type', '', ''),
              ('43', 'SP:Completed', '29', 'NestLevel', 'sqlserver', 'module_end', '', 'sqlserver', 'tsql_stack'),
              ('43', 'SP:Completed', '62', 'SourceDatabaseID', 'sqlserver', 'module_end', 'source_database_id', '', ''),
              ('44', 'SP:StmtStarting', '1', 'TextData', 'sqlserver', 'sp_statement_starting', 'statement', '', ''),
              ('44', 'SP:StmtStarting', '28', 'ObjectType', 'sqlserver', 'sp_statement_starting', 'object_type', '', ''),
              ('44', 'SP:StmtStarting', '29', 'NestLevel', 'sqlserver', 'sp_statement_starting', 'nest_level', '', ''),
              ('44', 'SP:StmtStarting', '55', 'IntegerData2', 'sqlserver', 'sp_statement_starting', 'offset_end', '', ''),
              ('44', 'SP:StmtStarting', '62', 'SourceDatabaseID', 'sqlserver', 'sp_statement_starting', 'source_database_id', '', ''),
              ('45', 'SP:StmtCompleted', '1', 'TextData', 'sqlserver', 'sp_statement_completed', 'statement', '', ''),
              ('45', 'SP:StmtCompleted', '28', 'ObjectType', 'sqlserver', 'sp_statement_completed', 'object_type', '', ''),
              ('45', 'SP:StmtCompleted', '29', 'NestLevel', 'sqlserver', 'sp_statement_completed', 'nest_level', '', ''),
              ('45', 'SP:StmtCompleted', '55', 'IntegerData2', 'sqlserver', 'sp_statement_completed', 'offset_end', '', ''),
              ('45', 'SP:StmtCompleted', '62', 'SourceDatabaseID', 'sqlserver', 'sp_statement_completed', 'source_database_id', '', ''),
              ('46', 'Object:Created', '21', 'EventSubClass', 'sqlserver', 'object_created', 'ddl_phase', '', ''),
              --('46', 'Object:Created', '25', 'IntegerData', 'sqlserver', 'object_created', '', 'package0', 'attach_activity_id'),
              ('46', 'Object:Created', '28', 'ObjectType', 'sqlserver', 'object_created', 'object_type', '', ''),
              ('46', 'Object:Created', '56', 'ObjectID2', 'sqlserver', 'object_created', 'related_object_id', '', ''),
              ('47', 'Object:Deleted', '21', 'EventSubClass', 'sqlserver', 'object_deleted', 'ddl_phase', '', ''),
              --('47', 'Object:Deleted', '25', 'IntegerData', 'sqlserver', 'object_deleted', '', 'package0', 'attach_activity_id'),
              ('47', 'Object:Deleted', '28', 'ObjectType', 'sqlserver', 'object_deleted', 'object_type', '', ''),
              ('47', 'Object:Deleted', '56', 'ObjectID2', 'sqlserver', 'object_deleted', 'related_object_id', '', ''),
              ('50', 'SQLTransaction', '21', 'EventSubClass', 'sqlserver', 'sql_transaction', 'transaction_state', '', ''),
              ('50', 'SQLTransaction', '25', 'IntegerData', 'sqlserver', 'sql_transaction', 'transaction_type', '', ''),
              ('53', 'CursorOpen', '25', 'IntegerData', 'sqlserver', 'cursor_open', 'cursor_type', '', ''),
              ('53', 'CursorOpen', '33', 'Handle', 'sqlserver', 'cursor_open', 'protocol_execution_id', '', ''),
              ('54', 'TransactionLog', '22', 'ObjectID', 'sqlserver', 'transaction_log', 'alloc_unit_id', '', ''),
              ('54', 'TransactionLog', '24', 'IndexID', 'sqlserver', 'transaction_log', 'alloc_unit_id', '', ''),
              ('55', 'Hash Warning', '21', 'EventSubClass', 'sqlserver', 'hash_warning', 'hash_warning_type', '', ''),
              ('55', 'Hash Warning', '22', 'ObjectID', 'sqlserver', 'hash_warning', 'query_operation_node_id', '', ''),
              ('55', 'Hash Warning', '25', 'IntegerData', 'sqlserver', 'hash_warning', 'recursion_level', '', ''),
              ('58', 'Auto Stats', '1', 'TextData', 'sqlserver', 'auto_stats', 'statistics_list', '', ''),
              ('58', 'Auto Stats', '21', 'EventSubClass', 'sqlserver', 'auto_stats', 'status', '', ''),
              ('58', 'Auto Stats', '25', 'IntegerData', 'sqlserver', 'auto_stats', 'count', '', ''),
              ('58', 'Auto Stats', '31', 'Error', 'sqlserver', 'auto_stats', 'last_error', '', ''),
              ('58', 'Auto Stats', '55', 'IntegerData2', 'sqlserver', 'auto_stats', 'job_id', '', ''),
              ('58', 'Auto Stats', '57', 'Type', 'sqlserver', 'auto_stats', 'job_type', '', ''),
              ('59', 'Lock:Deadlock Chain', '1', 'TextData', 'sqlserver', 'lock_deadlock_chain', 'resource_description', '', ''),
              ('59', 'Lock:Deadlock Chain', '2', 'BinaryData', 'sqlserver', 'lock_deadlock_chain', 'lockspace_workspace_id', '', ''),
              ('59', 'Lock:Deadlock Chain', '21', 'EventSubClass', 'sqlserver', 'lock_deadlock_chain', 'resource_owner_type', '', ''),
              ('59', 'Lock:Deadlock Chain', '25', 'IntegerData', 'sqlserver', 'lock_deadlock_chain', 'deadlock_id', '', ''),
              ('59', 'Lock:Deadlock Chain', '56', 'ObjectID2', 'sqlserver', 'lock_deadlock_chain', 'associated_object_id', '', ''),
              ('59', 'Lock:Deadlock Chain', '57', 'Type', 'sqlserver', 'lock_deadlock_chain', 'resource_type', '', ''),
              ('59', 'Lock:Deadlock Chain', '58', 'OwnerID', 'sqlserver', 'lock_deadlock_chain', 'owner_type', '', ''),
              ('60', 'Lock:Escalation', '1', 'TextData', 'sqlserver', 'lock_escalation', 'statement', '', ''),
              ('60', 'Lock:Escalation', '21', 'EventSubClass', 'sqlserver', 'lock_escalation', 'escalation_cause', '', ''),
              ('60', 'Lock:Escalation', '25', 'IntegerData', 'sqlserver', 'lock_escalation', 'hobt_lock_count', '', ''),
              ('60', 'Lock:Escalation', '55', 'IntegerData2', 'sqlserver', 'lock_escalation', 'escalated_lock_count', '', ''),
              ('60', 'Lock:Escalation', '56', 'ObjectID2', 'sqlserver', 'lock_escalation', 'hobt_id', '', ''),
              ('60', 'Lock:Escalation', '57', 'Type', 'sqlserver', 'lock_escalation', 'resource_type', '', ''),
              ('60', 'Lock:Escalation', '58', 'OwnerID', 'sqlserver', 'lock_escalation', 'owner_type', '', ''),
              ('61', 'OLEDB Errors', '1', 'TextData', 'sqlserver', 'oledb_error', 'parameters', '', ''),
              ('61', 'OLEDB Errors', '31', 'Error', 'sqlserver', 'oledb_error', 'hresult', '', ''),
              ('61', 'OLEDB Errors', '45', 'LinkedServerName', 'sqlserver', 'oledb_error', 'linked_server_name', '', ''),
              ('61', 'OLEDB Errors', '46', 'ProviderName', 'sqlserver', 'oledb_error', 'provider_name', '', ''),
              ('61', 'OLEDB Errors', '47', 'MethodName', 'sqlserver', 'oledb_error', 'method_name', '', ''),
              ('67', 'Execution Warnings', '1', 'TextData', 'sqlserver', 'execution_warning', 'server_memory_grants', '', ''),
              ('67', 'Execution Warnings', '21', 'EventSubClass', 'sqlserver', 'execution_warning', 'warning_type', '', ''),
              ('68', 'Showplan Text (Unencoded)', '1', 'TextData', 'sqlserver', 'query_pre_execution_showplan', 'showplan_xml', '', ''),
              ('68', 'Showplan Text (Unencoded)', '2', 'BinaryData', 'sqlserver', 'query_pre_execution_showplan', 'estimated_cost', '', ''),
              ('68', 'Showplan Text (Unencoded)', '25', 'IntegerData', 'sqlserver', 'query_pre_execution_showplan', 'estimated_rows', '', ''),
              ('68', 'Showplan Text (Unencoded)', '28', 'ObjectType', 'sqlserver', 'query_pre_execution_showplan', 'object_type', '', ''),
              ('68', 'Showplan Text (Unencoded)', '29', 'NestLevel', 'sqlserver', 'query_pre_execution_showplan', 'nest_level', '', ''),
              ('69', 'Sort Warnings', '21', 'EventSubClass', 'sqlserver', 'sort_warning', 'sort_warning_type', '', ''),
              ('70', 'CursorPrepare', '33', 'Handle', 'sqlserver', 'cursor_prepare', 'protocol_execution_id', '', ''),
              ('71', 'Prepare SQL', '33', 'Handle', 'sqlserver', 'prepare_sql', 'statement_handle', '', ''),
              ('72', 'Exec Prepared SQL', '33', 'Handle', 'sqlserver', 'exec_prepared_sql', 'statement_handle', '', ''),
              ('73', 'Unprepare SQL', '33', 'Handle', 'sqlserver', 'unprepare_sql', 'statement_handle', '', ''),
              ('74', 'CursorExecute', '25', 'IntegerData', 'sqlserver', 'cursor_execute', 'cursor_type', '', ''),
              ('74', 'CursorExecute', '33', 'Handle', 'sqlserver', 'cursor_execute', 'protocol_execution_id', '', ''),
              ('76', 'CursorImplicitConversion', '2', 'BinaryData', 'sqlserver', 'cursor_implicit_conversion', 'final_cursor_type', '', ''),
              ('76', 'CursorImplicitConversion', '25', 'IntegerData', 'sqlserver', 'cursor_implicit_conversion', 'initial_cursor_type', '', ''),
              ('76', 'CursorImplicitConversion', '33', 'Handle', 'sqlserver', 'cursor_implicit_conversion', 'protocol_execution_id', '', ''),
              ('77', 'CursorUnprepare', '33', 'Handle', 'sqlserver', 'cursor_unprepare', 'protocol_execution_id', '', ''),
              ('78', 'CursorClose', '33', 'Handle', 'sqlserver', 'cursor_close', 'protocol_execution_id', '', ''),
              ('79', 'Missing Column Statistics', '1', 'TextData', 'sqlserver', 'missing_column_statistics', 'column_list', '', ''),
              ('81', 'Server Memory Change', '21', 'EventSubClass', 'sqlserver', 'server_memory_change', 'memory_change', '', ''),
              ('81', 'Server Memory Change', '25', 'IntegerData', 'sqlserver', 'server_memory_change', 'new_memory_size_mb', '', ''),
              ('92', 'Data File Auto Grow', '25', 'IntegerData', 'sqlserver', 'database_file_size_change', 'size_change_kb', '', ''),
              ('92', 'Data File Auto Grow', '36', 'FileName', 'sqlserver', 'database_file_size_change', 'file_name', '', ''),
              ('93', 'Log File Auto Grow', '25', 'IntegerData', 'sqlserver', 'database_file_size_change', 'size_change_kb', '', ''),
              ('93', 'Log File Auto Grow', '36', 'FileName', 'sqlserver', 'database_file_size_change', 'file_name', '', ''),
              ('94', 'Data File Auto Shrink', '25', 'IntegerData', 'sqlserver', 'database_file_size_change', 'size_change_kb', '', ''),
              ('94', 'Data File Auto Shrink', '36', 'FileName', 'sqlserver', 'database_file_size_change', 'file_name', '', ''),
              ('95', 'Log File Auto Shrink', '25', 'IntegerData', 'sqlserver', 'database_file_size_change', 'size_change_kb', '', ''),
              ('95', 'Log File Auto Shrink', '36', 'FileName', 'sqlserver', 'database_file_size_change', 'file_name', '', ''),
              ('96', 'Showplan Text', '2', 'BinaryData', 'sqlserver', 'query_pre_execution_showplan', 'estimated_cost', '', ''),
              ('96', 'Showplan Text', '25', 'IntegerData', 'sqlserver', 'query_pre_execution_showplan', 'estimated_rows', '', ''),
              ('96', 'Showplan Text', '28', 'ObjectType', 'sqlserver', 'query_pre_execution_showplan', 'object_type', '', ''),
              ('96', 'Showplan Text', '29', 'NestLevel', 'sqlserver', 'query_pre_execution_showplan', 'nest_level', '', ''),
              ('97', 'Showplan All', '2', 'BinaryData', 'sqlserver', 'query_pre_execution_showplan', 'estimated_cost', '', ''),
              ('97', 'Showplan All', '25', 'IntegerData', 'sqlserver', 'query_pre_execution_showplan', 'estimated_rows', '', ''),
              ('97', 'Showplan All', '28', 'ObjectType', 'sqlserver', 'query_pre_execution_showplan', 'object_type', '', ''),
              ('97', 'Showplan All', '29', 'NestLevel', 'sqlserver', 'query_pre_execution_showplan', 'nest_level', '', ''),
              ('98', 'Showplan Statistics Profile', '2', 'BinaryData', 'sqlserver', 'query_post_execution_showplan', 'estimated_cost', '', ''),
              ('98', 'Showplan Statistics Profile', '25', 'IntegerData', 'sqlserver', 'query_post_execution_showplan', 'estimated_rows', '', ''),
              ('98', 'Showplan Statistics Profile', '28', 'ObjectType', 'sqlserver', 'query_post_execution_showplan', 'object_type', '', ''),
              ('98', 'Showplan Statistics Profile', '29', 'NestLevel', 'sqlserver', 'query_post_execution_showplan', 'nest_level', '', ''),
              ('100', 'RPC Output Parameter', '1', 'TextData', 'sqlserver', 'rpc_completed', 'output_parameters', '', ''),
              ('119', 'OLEDB Call Event', '1', 'TextData', 'sqlserver', 'oledb_call', 'parameters', '', ''),
              ('119', 'OLEDB Call Event', '21', 'EventSubClass', 'sqlserver', 'oledb_call', 'opcode', '', ''),
              ('119', 'OLEDB Call Event', '31', 'Error', 'sqlserver', 'oledb_call', 'hresult', '', ''),
              ('119', 'OLEDB Call Event', '45', 'LinkedServerName', 'sqlserver', 'oledb_call', 'linked_server_name', '', ''),
              ('119', 'OLEDB Call Event', '46', 'ProviderName', 'sqlserver', 'oledb_call', 'provider_name', '', ''),
              ('119', 'OLEDB Call Event', '47', 'MethodName', 'sqlserver', 'oledb_call', 'method_name', '', ''),
              ('120', 'OLEDB QueryInterface Event', '1', 'TextData', 'sqlserver', 'oledb_query_interface', 'parameters', '', ''),
              ('120', 'OLEDB QueryInterface Event', '21', 'EventSubClass', 'sqlserver', 'oledb_query_interface', 'opcode', '', ''),
              ('120', 'OLEDB QueryInterface Event', '31', 'Error', 'sqlserver', 'oledb_query_interface', 'hresult', '', ''),
              ('120', 'OLEDB QueryInterface Event', '45', 'LinkedServerName', 'sqlserver', 'oledb_query_interface', 'linked_server_name', '', ''),
              ('120', 'OLEDB QueryInterface Event', '46', 'ProviderName', 'sqlserver', 'oledb_query_interface', 'provider_name', '', ''),
              ('120', 'OLEDB QueryInterface Event', '47', 'MethodName', 'sqlserver', 'oledb_query_interface', 'method_name', '', ''),
              ('121', 'OLEDB DataRead Event', '1', 'TextData', 'sqlserver', 'oledb_data_read', 'parameters', '', ''),
              ('121', 'OLEDB DataRead Event', '21', 'EventSubClass', 'sqlserver', 'oledb_data_read', 'opcode', '', ''),
              ('121', 'OLEDB DataRead Event', '31', 'Error', 'sqlserver', 'oledb_data_read', 'hresult', '', ''),
              ('121', 'OLEDB DataRead Event', '45', 'LinkedServerName', 'sqlserver', 'oledb_data_read', 'linked_server_name', '', ''),
              ('121', 'OLEDB DataRead Event', '46', 'ProviderName', 'sqlserver', 'oledb_data_read', 'provider_name', '', ''),
              ('121', 'OLEDB DataRead Event', '47', 'MethodName', 'sqlserver', 'oledb_data_read', 'method_name', '', ''),
              ('122', 'Showplan XML', '1', 'TextData', 'sqlserver', 'query_pre_execution_showplan', 'showplan_xml', '', ''),
              ('122', 'Showplan XML', '2', 'BinaryData', 'sqlserver', 'query_pre_execution_showplan', 'estimated_cost', '', ''),
              ('122', 'Showplan XML', '25', 'IntegerData', 'sqlserver', 'query_pre_execution_showplan', 'estimated_rows', '', ''),
              ('122', 'Showplan XML', '28', 'ObjectType', 'sqlserver', 'query_pre_execution_showplan', 'object_type', '', ''),
              ('122', 'Showplan XML', '29', 'NestLevel', 'sqlserver', 'query_pre_execution_showplan', 'nest_level', '', ''),
              ('124', 'Broker:Conversation', '1', 'TextData', 'sqlserver', 'broker_conversation', 'conversation_state', '', ''),
              ('124', 'Broker:Conversation', '21', 'EventSubClass', 'sqlserver', 'broker_conversation', 'conversation_action', '', ''),
              ('124', 'Broker:Conversation', '34', 'ObjectName', 'sqlserver', 'broker_conversation', 'conversation_handle', '', ''),
              ('124', 'Broker:Conversation', '38', 'RoleName', 'sqlserver', 'broker_conversation', 'is_initiator', '', ''),
              ('124', 'Broker:Conversation', '42', 'TargetLoginName', 'sqlserver', 'broker_conversation', 'service_contract_name', '', ''),
              ('124', 'Broker:Conversation', '47', 'MethodName', 'sqlserver', 'broker_conversation', 'conversation_group_id', '', ''),
              ('124', 'Broker:Conversation', '54', 'GUID', 'sqlserver', 'broker_conversation', 'conversation_id', '', ''),
              ('125', 'Deprecation Announcement', '1', 'TextData', 'sqlserver', 'deprecation_announcement', 'message', '', ''),
              ('125', 'Deprecation Announcement', '22', 'ObjectID', 'sqlserver', 'deprecation_announcement', 'feature_id', '', ''),
              ('125', 'Deprecation Announcement', '34', 'ObjectName', 'sqlserver', 'deprecation_announcement', 'feature', '', ''),
              ('125', 'Deprecation Announcement', '55', 'IntegerData2', 'sqlserver', 'deprecation_announcement', '', 'sqlserver', 'tsql_frame'),
              ('126', 'Deprecation Final Support', '1', 'TextData', 'sqlserver', 'deprecation_final_support', 'message', '', ''),
              ('126', 'Deprecation Final Support', '22', 'ObjectID', 'sqlserver', 'deprecation_final_support', 'feature_id', '', ''),
              ('126', 'Deprecation Final Support', '34', 'ObjectName', 'sqlserver', 'deprecation_final_support', 'feature', '', ''),
              ('126', 'Deprecation Final Support', '55', 'IntegerData2', 'sqlserver', 'deprecation_final_support', '', 'sqlserver', 'tsql_frame'),
              ('127', 'Exchange Spill Event', '21', 'EventSubClass', 'sqlserver', 'exchange_spill', 'opcode', '', ''),
              ('127', 'Exchange Spill Event', '22', 'ObjectID', 'sqlserver', 'exchange_spill', 'query_operation_node_id', '', ''),
              ('136', 'Broker:Conversation Group', '21', 'EventSubClass', 'sqlserver', 'broker_conversation_group', 'conversation_group_action', '', ''),
              ('136', 'Broker:Conversation Group', '54', 'GUID', 'sqlserver', 'broker_conversation_group', 'conversation_group_id', '', ''),
              ('137', 'Blocked process report', '1', 'TextData', 'sqlserver', 'blocked_process_report', 'blocked_process', '', ''),
              ('137', 'Blocked process report', '32', 'Mode', 'sqlserver', 'blocked_process_report', 'lock_mode', '', ''),
              ('138', 'Broker:Connection', '1', 'TextData', 'ucs', 'ucs_connection_setup', 'error_message', '', ''),
              ('138', 'Broker:Connection', '21', 'EventSubClass', 'ucs', 'ucs_connection_setup', 'setup_event', '', ''),
              ('138', 'Broker:Connection', '34', 'ObjectName', 'ucs', 'ucs_connection_setup', 'connection_id', '', ''),
              ('138', 'Broker:Connection', '54', 'GUID', 'ucs', 'ucs_connection_setup', 'address', '', ''),
              ('139', 'Broker:Forwarded Message Sent', '22', 'ObjectID', 'sqlserver', 'broker_forwarded_message_sent', 'time_to_live_sec', '', ''),
              ('139', 'Broker:Forwarded Message Sent', '23', 'Success', 'sqlserver', 'broker_forwarded_message_sent', 'live_time_sec', '', ''),
              ('139', 'Broker:Forwarded Message Sent', '24', 'IndexID', 'sqlserver', 'broker_forwarded_message_sent', 'remaining_hop_count', '', ''),
              ('139', 'Broker:Forwarded Message Sent', '25', 'IntegerData', 'sqlserver', 'broker_forwarded_message_sent', 'fragment_number', '', ''),
              ('139', 'Broker:Forwarded Message Sent', '36', 'FileName', 'sqlserver', 'broker_forwarded_message_sent', 'to_service_name', '', ''),
              ('139', 'Broker:Forwarded Message Sent', '37', 'OwnerName', 'sqlserver', 'broker_forwarded_message_sent', 'to_broker_name', '', ''),
              ('139', 'Broker:Forwarded Message Sent', '38', 'RoleName', 'sqlserver', 'broker_forwarded_message_sent', 'is_initiator', '', ''),
              ('139', 'Broker:Forwarded Message Sent', '39', 'TargetUserName', 'sqlserver', 'broker_forwarded_message_sent', 'from_service_name', '', ''),
              ('139', 'Broker:Forwarded Message Sent', '40', 'DBUserName', 'sqlserver', 'broker_forwarded_message_sent', 'from_broker_name', '', ''),
              ('139', 'Broker:Forwarded Message Sent', '42', 'TargetLoginName', 'sqlserver', 'broker_forwarded_message_sent', 'to_broker_name', '', ''),
              ('139', 'Broker:Forwarded Message Sent', '47', 'MethodName', 'sqlserver', 'broker_forwarded_message_sent', 'message_type_name', '', ''),
              ('139', 'Broker:Forwarded Message Sent', '52', 'BigintData1', 'sqlserver', 'broker_forwarded_message_sent', 'message_sequence', '', ''),
              ('139', 'Broker:Forwarded Message Sent', '54', 'GUID', 'sqlserver', 'broker_forwarded_message_sent', 'conversation_id', '', ''),
              ('140', 'Broker:Forwarded Message Dropped', '1', 'TextData', 'sqlserver', 'broker_forwarded_message_dropped', 'dropped_reason', '', ''),
              ('140', 'Broker:Forwarded Message Dropped', '20', 'Severity', 'sqlserver', 'broker_forwarded_message_dropped', 'error_severity', '', ''),
              ('140', 'Broker:Forwarded Message Dropped', '22', 'ObjectID', 'sqlserver', 'broker_forwarded_message_dropped', 'time_to_live_sec', '', ''),
              ('140', 'Broker:Forwarded Message Dropped', '24', 'IndexID', 'sqlserver', 'broker_forwarded_message_dropped', 'remaining_hop_count', '', ''),
              ('140', 'Broker:Forwarded Message Dropped', '25', 'IntegerData', 'sqlserver', 'broker_forwarded_message_dropped', 'fragment_number', '', ''),
              ('140', 'Broker:Forwarded Message Dropped', '30', 'State', 'sqlserver', 'broker_forwarded_message_dropped', 'error_state', '', ''),
              ('140', 'Broker:Forwarded Message Dropped', '36', 'FileName', 'sqlserver', 'broker_forwarded_message_dropped', 'to_service_name', '', ''),
              ('140', 'Broker:Forwarded Message Dropped', '37', 'OwnerName', 'sqlserver', 'broker_forwarded_message_dropped', 'to_broker_name', '', ''),
              ('140', 'Broker:Forwarded Message Dropped', '38', 'RoleName', 'sqlserver', 'broker_forwarded_message_dropped', 'is_initiator', '', ''),
              ('140', 'Broker:Forwarded Message Dropped', '39', 'TargetUserName', 'sqlserver', 'broker_forwarded_message_dropped', 'from_service_name', '', ''),
              ('140', 'Broker:Forwarded Message Dropped', '40', 'DBUserName', 'sqlserver', 'broker_forwarded_message_dropped', 'from_broker_name', '', ''),
              ('140', 'Broker:Forwarded Message Dropped', '42', 'TargetLoginName', 'sqlserver', 'broker_forwarded_message_dropped', 'to_broker_name', '', ''),
              ('140', 'Broker:Forwarded Message Dropped', '47', 'MethodName', 'sqlserver', 'broker_forwarded_message_dropped', 'message_type_name', '', ''),
              ('140', 'Broker:Forwarded Message Dropped', '52', 'BigintData1', 'sqlserver', 'broker_forwarded_message_dropped', 'message_sequence', '', ''),
              ('140', 'Broker:Forwarded Message Dropped', '54', 'GUID', 'sqlserver', 'broker_forwarded_message_dropped', 'conversation_id', '', ''),
              ('141', 'Broker:Message Classify', '21', 'EventSubClass', 'sqlserver', 'broker_message_classify', 'route_type', '', ''),
              ('141', 'Broker:Message Classify', '31', 'Error', 'sqlserver', 'broker_message_classify', 'delayed_error_number', '', ''),
              ('141', 'Broker:Message Classify', '36', 'FileName', 'sqlserver', 'broker_message_classify', 'to_service_name', '', ''),
              ('141', 'Broker:Message Classify', '37', 'OwnerName', 'sqlserver', 'broker_message_classify', 'to_broker_instance', '', ''),
              ('141', 'Broker:Message Classify', '38', 'RoleName', 'sqlserver', 'broker_message_classify', 'is_initiator', '', ''),
              ('141', 'Broker:Message Classify', '45', 'LinkedServerName', 'sqlserver', 'broker_message_classify', 'message_source', '', ''),
              ('141', 'Broker:Message Classify', '54', 'GUID', 'sqlserver', 'broker_message_classify', 'conversation_id', '', ''),
              ('142', 'Broker:Transmission', '20', 'Severity', 'sqlserver', 'broker_transmission_exception', 'error_severity', '', ''),
              ('142', 'Broker:Transmission', '30', 'State', 'sqlserver', 'broker_transmission_exception', 'error_state', '', ''),
              ('146', 'Showplan XML Statistics Profile', '1', 'TextData', 'sqlserver', 'query_post_execution_showplan', 'showplan_xml', '', ''),
              ('146', 'Showplan XML Statistics Profile', '2', 'BinaryData', 'sqlserver', 'query_post_execution_showplan', 'estimated_cost', '', ''),
              ('146', 'Showplan XML Statistics Profile', '25', 'IntegerData', 'sqlserver', 'query_post_execution_showplan', 'estimated_rows', '', ''),
              ('146', 'Showplan XML Statistics Profile', '28', 'ObjectType', 'sqlserver', 'query_post_execution_showplan', 'object_type', '', ''),
              ('146', 'Showplan XML Statistics Profile', '29', 'NestLevel', 'sqlserver', 'query_post_execution_showplan', 'nest_level', '', ''),
              ('148', 'Deadlock graph', '1', 'TextData', 'sqlserver', 'xml_deadlock_report', 'xml_report', '', ''),
              ('149', 'Broker:Remote Message Acknowledgement', '21', 'EventSubClass', 'sqlserver', 'broker_remote_message_acknowledgement', 'acknowledgement_type', '', ''),
              ('149', 'Broker:Remote Message Acknowledgement', '25', 'IntegerData', 'sqlserver', 'broker_remote_message_acknowledgement', 'acknowledgement_fragment_number', '', ''),
              ('149', 'Broker:Remote Message Acknowledgement', '38', 'RoleName', 'sqlserver', 'broker_remote_message_acknowledgement', 'is_initiator', '', ''),
              ('149', 'Broker:Remote Message Acknowledgement', '52', 'BigintData1', 'sqlserver', 'broker_remote_message_acknowledgement', 'acknowlegment_message_sequence', '', ''),
              ('149', 'Broker:Remote Message Acknowledgement', '53', 'BigintData2', 'sqlserver', 'broker_remote_message_acknowledgement', 'message_sequence', '', ''),
              ('149', 'Broker:Remote Message Acknowledgement', '54', 'GUID', 'sqlserver', 'broker_remote_message_acknowledgement', 'conversation_id', '', ''),
              ('149', 'Broker:Remote Message Acknowledgement', '55', 'IntegerData2', 'sqlserver', 'broker_remote_message_acknowledgement', 'fragment_number', '', ''),
              ('155', 'FT:Crawl Started', '1', 'TextData', 'sqlserver', 'full_text_crawl_started', 'crawl_operation', '', ''),
              ('160', 'Broker:Message Undeliverable', '1', 'TextData', 'sqlserver', 'broker_message_undeliverable', 'message_drop_reason', '', ''),
              ('160', 'Broker:Message Undeliverable', '20', 'Severity', 'sqlserver', 'broker_message_undeliverable', 'error_severity', '', ''),
              ('160', 'Broker:Message Undeliverable', '21', 'EventSubClass', 'sqlserver', 'broker_message_undeliverable', 'sequenced_message', '', ''),
              ('160', 'Broker:Message Undeliverable', '25', 'IntegerData', 'sqlserver', 'broker_message_undeliverable', 'message_fragment_number', '', ''),
              ('160', 'Broker:Message Undeliverable', '30', 'State', 'sqlserver', 'broker_message_undeliverable', 'error_state', '', ''),
              ('160', 'Broker:Message Undeliverable', '38', 'RoleName', 'sqlserver', 'broker_message_undeliverable', 'is_initiator', '', ''),
              ('160', 'Broker:Message Undeliverable', '52', 'BigintData1', 'sqlserver', 'broker_message_undeliverable', 'message_sequence_number', '', ''),
              ('160', 'Broker:Message Undeliverable', '53', 'BigintData2', 'sqlserver', 'broker_message_undeliverable', 'acknowledgement_sequence_number', '', ''),
              ('160', 'Broker:Message Undeliverable', '54', 'GUID', 'sqlserver', 'broker_message_undeliverable', 'conversation_id', '', ''),
              ('160', 'Broker:Message Undeliverable', '55', 'IntegerData2', 'sqlserver', 'broker_message_undeliverable', 'acknowledgement_fragment_number', '', ''),
              ('161', 'Broker:Corrupted Message', '1', 'TextData', 'sqlserver', 'broker_corrupted_message', 'corruption_description', '', ''),
              ('161', 'Broker:Corrupted Message', '20', 'Severity', 'sqlserver', 'broker_corrupted_message', 'error_severity', '', ''),
              ('161', 'Broker:Corrupted Message', '30', 'State', 'sqlserver', 'broker_corrupted_message', 'error_state', '', ''),
              ('162', 'User Error Message', '1', 'TextData', 'sqlserver', 'error_reported', 'message', '', ''),
              ('163', 'Broker:Activation', '1', 'TextData', 'sqlserver', 'broker_activation', 'activation_message', '', ''),
              ('163', 'Broker:Activation', '21', 'EventSubClass', 'sqlserver', 'broker_activation', 'activation_state', '', ''),
              ('163', 'Broker:Activation', '22', 'ObjectID', 'sqlserver', 'broker_activation', 'queue_id', '', ''),
              ('163', 'Broker:Activation', '25', 'IntegerData', 'sqlserver', 'broker_activation', 'active_task_count', '', ''),
              ('164', 'Object:Altered', '21', 'EventSubClass', 'sqlserver', 'object_altered', 'ddl_phase', '', ''),
              --('164', 'Object:Altered', '25', 'IntegerData', 'sqlserver', 'object_altered', '', 'package0', 'attach_activity_id'),
              ('164', 'Object:Altered', '28', 'ObjectType', 'sqlserver', 'object_altered', 'object_type', '', ''),
              ('164', 'Object:Altered', '56', 'ObjectID2', 'sqlserver', 'object_altered', 'related_object_id', '', ''),
              ('165', 'Performance statistics', '1', 'TextData', 'sqlserver', 'query_cache_removal_statistics', 'execution_statistics', '', ''),
              ('165', 'Performance statistics', '1', 'TextData', 'sqlserver', 'query_pre_execution_showplan', 'showplan_xml', '', ''),
              ('165', 'Performance statistics', '1', 'TextData', 'sqlserver', 'uncached_sql_batch_statistics', 'statement', '', ''),
              ('165', 'Performance statistics', '2', 'BinaryData', 'sqlserver', 'query_pre_execution_showplan', 'estimated_cost', '', ''),
              ('165', 'Performance statistics', '22', 'ObjectID', 'sqlserver', 'query_cache_removal_statistics', 'compiled_object_id', '', ''),
              ('165', 'Performance statistics', '25', 'IntegerData', 'sqlserver', 'query_cache_removal_statistics', 'begin_offset', '', ''),
              ('165', 'Performance statistics', '25', 'IntegerData', 'sqlserver', 'query_pre_execution_showplan', 'estimated_rows', '', ''),
              ('165', 'Performance statistics', '28', 'ObjectType', 'sqlserver', 'query_cache_removal_statistics', 'compiled_object_type', '', ''),
              ('165', 'Performance statistics', '28', 'ObjectType', 'sqlserver', 'query_pre_execution_showplan', 'object_type', '', ''),
              ('165', 'Performance statistics', '52', 'BigintData1', 'sqlserver', 'query_cache_removal_statistics', 'recompile_count', '', ''),
              ('165', 'Performance statistics', '55', 'IntegerData2', 'sqlserver', 'query_cache_removal_statistics', 'end_offset', '', ''),
              ('166', 'SQL:StmtRecompile', '1', 'TextData', 'sqlserver', 'sql_statement_recompile', 'statement', '', ''),
              ('166', 'SQL:StmtRecompile', '21', 'EventSubClass', 'sqlserver', 'sql_statement_recompile', 'recompile_cause', '', ''),
              ('166', 'SQL:StmtRecompile', '28', 'ObjectType', 'sqlserver', 'sql_statement_recompile', 'object_type', '', ''),
              ('166', 'SQL:StmtRecompile', '29', 'NestLevel', 'sqlserver', 'sql_statement_recompile', 'nest_level', '', ''),
              ('166', 'SQL:StmtRecompile', '55', 'IntegerData2', 'sqlserver', 'sql_statement_recompile', 'offset_end', '', ''),
              ('167', 'Database Mirroring State Change', '1', 'TextData', 'sqlserver', 'database_mirroring_state_change', 'state_change_desc', '', ''),
              ('167', 'Database Mirroring State Change', '25', 'IntegerData', 'sqlserver', 'database_mirroring_state_change', 'prior_state', '', ''),
              ('167', 'Database Mirroring State Change', '30', 'State', 'sqlserver', 'database_mirroring_state_change', 'new_state', '', ''),
              ('168', 'Showplan XML For Query Compile', '1', 'TextData', 'sqlserver', 'query_post_compilation_showplan', 'showplan_xml', '', ''),
              ('168', 'Showplan XML For Query Compile', '2', 'BinaryData', 'sqlserver', 'query_post_compilation_showplan', 'estimated_cost', '', ''),
              ('168', 'Showplan XML For Query Compile', '25', 'IntegerData', 'sqlserver', 'query_post_compilation_showplan', 'estimated_rows', '', ''),
              ('168', 'Showplan XML For Query Compile', '28', 'ObjectType', 'sqlserver', 'query_post_compilation_showplan', 'object_type', '', ''),
              ('168', 'Showplan XML For Query Compile', '29', 'NestLevel', 'sqlserver', 'query_post_compilation_showplan', 'nest_level', '', ''),
              ('169', 'Showplan All For Query Compile', '2', 'BinaryData', 'sqlserver', 'query_post_compilation_showplan', 'estimated_cost', '', ''),
              ('169', 'Showplan All For Query Compile', '25', 'IntegerData', 'sqlserver', 'query_post_compilation_showplan', 'estimated_rows', '', ''),
              ('169', 'Showplan All For Query Compile', '28', 'ObjectType', 'sqlserver', 'query_post_compilation_showplan', 'object_type', '', ''),
              ('169', 'Showplan All For Query Compile', '29', 'NestLevel', 'sqlserver', 'query_post_compilation_showplan', 'nest_level', '', ''),
              ('181', 'TM: Begin Tran starting', '1', 'TextData', 'sqlserver', 'begin_tran_starting', 'statement', '', ''),
              ('182', 'TM: Begin Tran completed', '1', 'TextData', 'sqlserver', 'begin_tran_completed', 'statement', '', ''),
              ('184', 'TM: Promote Tran completed', '2', 'BinaryData', 'sqlserver', 'promote_tran_completed', 'dtc_trasaction_token', '', ''),
              ('185', 'TM: Commit Tran starting', '1', 'TextData', 'sqlserver', 'commit_tran_starting', 'statement', '', ''),
              ('185', 'TM: Commit Tran starting', '21', 'EventSubClass', 'sqlserver', 'commit_tran_starting', 'new_transaction_started', '', ''),
              ('186', 'TM: Commit Tran completed', '1', 'TextData', 'sqlserver', 'commit_tran_completed', 'statement', '', ''),
              ('186', 'TM: Commit Tran completed', '21', 'EventSubClass', 'sqlserver', 'commit_tran_completed', 'new_transaction_started', '', ''),
              ('187', 'TM: Rollback Tran starting', '1', 'TextData', 'sqlserver', 'rollback_tran_starting', 'statement', '', ''),
              ('187', 'TM: Rollback Tran starting', '21', 'EventSubClass', 'sqlserver', 'rollback_tran_starting', 'new_transaction_started', '', ''),
              ('188', 'TM: Rollback Tran completed', '1', 'TextData', 'sqlserver', 'rollback_tran_completed', 'statement', '', ''),
              ('188', 'TM: Rollback Tran completed', '21', 'EventSubClass', 'sqlserver', 'rollback_tran_completed', 'new_transaction_started', '', ''),
              ('189', 'Lock:Timeout (timeout > 0)', '1', 'TextData', 'sqlserver', 'lock_timeout_greater_than_0', 'resource_description', '', ''),
              ('189', 'Lock:Timeout (timeout > 0)', '2', 'BinaryData', 'sqlserver', 'lock_timeout_greater_than_0', 'lockspace_workspace_id', '', ''),
              ('189', 'Lock:Timeout (timeout > 0)', '56', 'ObjectID2', 'sqlserver', 'lock_timeout_greater_than_0', 'associated_object_id', '', ''),
              ('189', 'Lock:Timeout (timeout > 0)', '57', 'Type', 'sqlserver', 'lock_timeout_greater_than_0', 'resource_type', '', ''),
              ('189', 'Lock:Timeout (timeout > 0)', '58', 'OwnerID', 'sqlserver', 'lock_timeout_greater_than_0', 'owner_type', '', ''),
              ('190', 'Progress Report: Online Index Operation', '21', 'EventSubClass', 'sqlserver', 'progress_report_online_index_operation', 'build_stage', '', ''),
              ('190', 'Progress Report: Online Index Operation', '52', 'BigintData1', 'sqlserver', 'progress_report_online_index_operation', 'rows_inserted', '', ''),
              ('190', 'Progress Report: Online Index Operation', '53', 'BigintData2', 'sqlserver', 'progress_report_online_index_operation', 'parallel_process_thread_id', '', ''),
              ('191', 'TM: Save Tran starting', '1', 'TextData', 'sqlserver', 'save_tran_starting', 'statement', '', ''),
              ('192', 'TM: Save Tran completed', '1', 'TextData', 'sqlserver', 'save_tran_completed', 'statement', '', ''),
              ('193', 'Background Job Error', '20', 'Severity', 'sqlserver', 'background_job_error', 'error_severity', '', ''),
              ('193', 'Background Job Error', '21', 'EventSubClass', 'sqlserver', 'background_job_error', 'job_failure_type', '', ''),
              ('193', 'Background Job Error', '25', 'IntegerData', 'sqlserver', 'background_job_error', 'retries', '', ''),
              ('193', 'Background Job Error', '30', 'State', 'sqlserver', 'background_job_error', 'error_state', '', ''),
              ('193', 'Background Job Error', '55', 'IntegerData2', 'sqlserver', 'background_job_error', 'job_id', '', ''),
              ('193', 'Background Job Error', '57', 'Type', 'sqlserver', 'background_job_error', 'job_type', '', ''),
              ('194', 'OLEDB Provider Information', '1', 'TextData', 'sqlserver', 'oledb_provider_information', 'parameters', '', ''),
              ('194', 'OLEDB Provider Information', '45', 'LinkedServerName', 'sqlserver', 'oledb_provider_information', 'linked_server_name', '', ''),
              ('194', 'OLEDB Provider Information', '46', 'ProviderName', 'sqlserver', 'oledb_provider_information', 'provider_name', '', ''),
              ('196', 'Assembly Load', '1', 'TextData', 'sqlserver', 'assembly_load', 'success', '', ''),
              ('196', 'Assembly Load', '22', 'ObjectID', 'sqlserver', 'assembly_load', 'assembly_id', '', ''),
              ('196', 'Assembly Load', '34', 'ObjectName', 'sqlserver', 'assembly_load', 'assembly_name', '', ''),
              ('198', 'XQuery Static Type', '1', 'TextData', 'sqlserver', 'xquery_static_type', 'inferred_type', '', ''),
              ('198', 'XQuery Static Type', '47', 'MethodName', 'sqlserver', 'xquery_static_type', 'oledb_method', '', ''),
              ('199', 'QN: Subscription', '1', 'TextData', 'sqlserver', 'qn_subscription', 'query_notification_xml_information', '', ''),
              ('199', 'QN: Subscription', '21', 'EventSubClass', 'sqlserver', 'qn_subscription', 'activity', '', ''),
              ('200', 'QN: Parameter table', '1', 'TextData', 'sqlserver', 'qn_parameter_table', 'query_notification_xml_information', '', ''),
              ('200', 'QN: Parameter table', '21', 'EventSubClass', 'sqlserver', 'qn_parameter_table', 'activity', '', ''),
              ('201', 'QN: Template', '1', 'TextData', 'sqlserver', 'qn_template', 'query_notification_xml_information', '', ''),
              ('201', 'QN: Template', '21', 'EventSubClass', 'sqlserver', 'qn_template', 'activity', '', ''),
              ('202', 'QN: Dynamics', '1', 'TextData', 'sqlserver', 'qn_dynamics', 'query_notification_xml_information', '', ''),
              ('202', 'QN: Dynamics', '21', 'EventSubClass', 'sqlserver', 'qn_dynamics', 'activity', '', ''),
              ('212', 'Bitmap Warning', '22', 'ObjectID', 'sqlserver', 'bitmap_disabled_warning', 'query_operation_node_id', '', ''),
              ('213', 'Database Suspect Data Page', '31', 'Error', 'sqlserver', 'database_suspect_data_page', 'page_error', '', ''),
              ('214', 'CPU threshold exceeded', '58', 'OwnerID', 'sqlserver', 'cpu_threshold_exceeded', 'session_id', '', ''),
              ('215', 'PreConnect:Starting', '21', 'EventSubClass', 'sqlserver', 'preconnect_starting', 'preconnect_type', '', ''),
              ('215', 'PreConnect:Starting', '28', 'ObjectType', 'sqlserver', 'preconnect_starting', 'object_type', '', ''),
              ('216', 'PreConnect:Completed', '21', 'EventSubClass', 'sqlserver', 'preconnect_completed', 'preconnect_type', '', ''),
              ('216', 'PreConnect:Completed', '28', 'ObjectType', 'sqlserver', 'preconnect_completed', 'object_type', '', ''),
              ('216', 'PreConnect:Completed', '30', 'State', 'sqlserver', 'preconnect_completed', 'error_state', '', ''),
              ('216', 'PreConnect:Completed', '39', 'TargetUserName', 'sqlserver', 'preconnect_completed', 'workload_group_name', '', '')
) AS tab (trace_event_id, trace_event_name, trace_column_id, trace_column_name, event_package_name, xe_event_name, column_name, action_package_name, xe_action_name)

-- Create table variable to hold the trace definition
DECLARE @TraceInfo TABLE
(
       eventid INT,
       te_name NVARCHAR(128) COLLATE SQL_Latin1_General_CP1_CI_AS,
       columnid INT,
       columnname NVARCHAR(128) COLLATE SQL_Latin1_General_CP1_CI_AS,
       event_package_name NVARCHAR(128) COLLATE SQL_Latin1_General_CP1_CI_AS,
       xe_event_name NVARCHAR(128) COLLATE SQL_Latin1_General_CP1_CI_AS,
       column_name NVARCHAR(128) COLLATE SQL_Latin1_General_CP1_CI_AS,
       action_package_name NVARCHAR(128) COLLATE SQL_Latin1_General_CP1_CI_AS,
       xe_action_name NVARCHAR(128) COLLATE SQL_Latin1_General_CP1_CI_AS,
       filter_operator NVARCHAR(128) COLLATE SQL_Latin1_General_CP1_CI_AS,
       filter_value sql_variant 
)

-- Query the trace functions to get the trace definition 
INSERT INTO @TraceInfo 
       (eventid, te_name, columnid, columnname, event_package_name, xe_event_name, 
        column_name, action_package_name, xe_action_name, filter_operator, filter_value)
SELECT 
       eventid,
       te.name,
       tgei.columnid,
       tc.name,
       event_package_name,
       xe_event_name,
       column_name,
       action_package_name,
       xe_action_name,
       CASE comparison_operator
              WHEN 0 THEN '='
              WHEN 1 THEN '<>'
              WHEN 2 THEN '>'
              WHEN 3 THEN '<'
              WHEN 4 THEN '>='
              WHEN 5 THEN '<='
              WHEN 6 THEN 'LIKE'
              WHEN 7 THEN 'NOT LIKE'
       END AS filter_operator,
       value AS filter_value
FROM sys.fn_trace_geteventinfo(@TraceID) AS tgei
LEFT JOIN sys.fn_trace_getfilterinfo(@TraceID) AS tfgi
       ON tgei.columnid = tfgi.columnid
              AND CAST(value AS NVARCHAR) NOT LIKE 'SQL Server Profiler%'
JOIN sys.trace_columns AS tc
       ON tgei.columnid = tc.trace_column_id
JOIN sys.trace_events AS te
       ON tgei.eventid = te.trace_event_id
LEFT JOIN [#SQLskills_Trace_XE_Column_Map] AS txcm
       ON tgei.eventid = txcm.trace_event_id
              AND tgei.columnid = txcm.trace_column_id
ORDER BY tgei.eventid, tgei.columnid

-- Generate the drop command for the Event Session if it already exists
DECLARE @DropCmd NVARCHAR(MAX) = 'IF EXISTS (SELECT 1 FROM sys.server_event_sessions WHERE name = '''+@SessionName+''')' + CHAR(10) +
'      DROP EVENT SESSION '+QUOTENAME(@SessionName)+' ON SERVER;' + CHAR(10)

-- Execute the drop command if @Execute = 1
IF @Execute = 1
       EXECUTE(@DropCmd);

-- Generate the start of the create statement for the Event Sesssion
DECLARE @sqlcmd NVARCHAR(MAX) = 'CREATE EVENT SESSION '+QUOTENAME(@SessionName)+ CHAR(10) +
'ON SERVER' + CHAR(10)

DECLARE @event_list NVARCHAR(MAX) = ''

-- Generate the Event list DDL definition for the event session
SELECT @event_list = @event_list + 
-- Add Events to Session
       CASE 
              WHEN event_package_name IS NULL 
                     THEN '/* ' + tab.te_name + ' is not implemented in Extended Events it may be a Server Audit Event */' + CHAR(10)
              WHEN event_package_name IS NOT NULL AND RowID <> 1
                     THEN '/* ' + tab.te_name + ' is implemented as the ' + tab.event_package_name + '.' + tab.xe_event_name + ' event in Extended Events */' + CHAR(10)
              ELSE
                     'ADD EVENT ' + event_package_name + '.' + xe_event_name + '(' + CHAR(10) +
                           -- Determine whether to create an Action List for Event
                           CASE 
                                  WHEN NOT EXISTS (SELECT 1
                                                                     FROM @TraceInfo AS ti
                                                                     WHERE ti.eventid = tab.eventid
                                                                       AND column_name IS NULL)
                                         OR RowID <> 1
                                         THEN ''
                                  ELSE 
                                         -- Build Action List for Event
                                         CHAR(9) + 'ACTION ' + CHAR(10) +
                                         CHAR(9) + '(' + CHAR(10) +
                                         STUFF((
                                                       SELECT 
                                                              CASE 
                                                                     WHEN action_package_name IS NULL AND columnname NOT IN ('StartTime', 'EndTime')
                                                                           THEN CHAR(9) + CHAR(9) + CHAR(9) + '-- ' + columnname + ' not implemented in XE for this event' + CHAR(10)
                                                                     WHEN num > 1 THEN  CHAR(9) + CHAR(9) + CHAR(9) + '-- ' + columnname + ' implemented by another Action in XE already' + CHAR(10)
                                                                     ELSE CHAR(9) + CHAR(9) + CHAR(9) + ', '+ action_package_name + '.' + xe_action_name  + CHAR(9) + '-- ' + columnname + ' from SQLTrace' + CHAR(10)
                                                              END
                                                       FROM (
                                                              SELECT eventid, action_package_name, xe_action_name, columnname, column_name, row_number() over (partition by eventid, action_package_name, xe_action_name order by columnname) AS num
                                                              FROM @TraceInfo AS ti
                                                              ) AS ti
                                                       WHERE ti.eventid = tab.eventid
                                                         AND column_name IS NULL
                                                       ORDER BY CASE WHEN xe_action_name IS NULL THEN 1 ELSE 0 END, xe_action_name
                                                       FOR XML PATH('')), 1, 4, CHAR(9) + CHAR(9) + CHAR(9)+' ') -- Actions
                                         + CHAR(9) + ')' + CHAR(10) 
                           END +
                     -- Build in Predicate information
                           CASE 
                                  WHEN NOT EXISTS (SELECT 1
                                                                     FROM @TraceInfo AS ti
                                                                     WHERE ti.eventid = tab.eventid
                                                                       AND filter_operator IS NOT NULL)
                                         THEN ''
                                  ELSE 
                                         CHAR(9) + 'WHERE ' + CHAR(10) +
                                         CHAR(9) + '(' + CHAR(10) +
                                         REPLACE(
                                                REPLACE(
                                                       STUFF(
                                                                     (
                                                                           SELECT 
                                                                                  CASE 
                                                                                         WHEN action_package_name IS NULL 
                                                                                                THEN CHAR(9) + CHAR(9) + CHAR(9) + 'AND ' + column_name + ' ' + filter_operator + ' ' + 
                                                                                                       CASE 
                                                                                                              WHEN SQL_VARIANT_PROPERTY(filter_value, 'BaseType') IN ('nvarchar', 'varchar', 'char', 'nchar') 
                                                                                                                     THEN '''%'+CAST(filter_value AS NVARCHAR)+'%'''
                                                                                                              ELSE CAST(filter_value AS NVARCHAR)
                                                                                                       END + CHAR(10)
                                                                                         ELSE CHAR(9) + CHAR(9) + CHAR(9) + 'AND '+ action_package_name + '.' + xe_action_name + ' ' + filter_operator + ' ' + 
                                                                                                       CASE 
                                                                                                              WHEN SQL_VARIANT_PROPERTY(filter_value, 'BaseType') IN ('nvarchar', 'varchar', 'char', 'nchar') 
                                                                                                                     THEN '''%'+CAST(filter_value AS NVARCHAR)+'%'''
                                                                                                              ELSE CAST(filter_value AS NVARCHAR)
                                                                                                       END + CHAR(10)
                                                                                  END
                                                                           FROM @TraceInfo AS ti
                                                                           WHERE ti.eventid = tab.eventid
                                                                             AND filter_operator IS NOT NULL
                                                                           ORDER BY xe_action_name
                                                                           FOR XML PATH('')
                                                                     ), 1, 7, CHAR(9) + CHAR(9) + CHAR(9)+'')
                                                              , '&gt;', '>')
                                                       , '&lt;', '<') -- Predicates
                                         + CHAR(9) + ')' 
                           END 
              + CHAR(10) + '),' + CHAR(10)
       END
FROM
(      
       SELECT eventid, te_name, event_package_name, xe_event_name, ROW_NUMBER() OVER (PARTITION BY event_package_name, xe_event_name ORDER BY eventid) AS RowID
       FROM
       (
              SELECT DISTINCT eventid, te_name, event_package_name, xe_event_name, ROW_NUMBER() OVER (PARTITION BY eventid ORDER BY event_package_name DESC) AS Row_ID
              FROM @TraceInfo
       ) AS tab2
       WHERE Row_ID = 1
) AS tab;

-- Add Event List to the output command
SET @sqlcmd = @sqlcmd + SUBSTRING(@event_list, 0, LEN(@event_list)-1)+CHAR(10)

-- Add target definitions to the output command based on trace configuration
SELECT @sqlcmd = @sqlcmd + 
CASE 
       WHEN path IS NULL THEN 'ADD TARGET package0.ring_buffer' + CHAR(10)
       ELSE 
'ADD TARGET package0.event_file' + CHAR(10) +
'(' + CHAR(10) +
'      SET filename = '''+ SUBSTRING(path, 0, LEN(path)-CHARINDEX('\', REVERSE(path))+1) + '\'+@SessionName+'.xel'',' + CHAR(10) +
'             max_file_size = ' + CAST(max_size AS NVARCHAR) + ',' + CHAR(10) +
'             max_rollover_files = ' + CAST(max_files AS NVARCHAR) + CHAR(10) +
')' + CHAR(10) 
END
FROM sys.traces   
WHERE id = @TraceID

-- Print the DDL for the Event Session
IF @PrintOutput = 1
BEGIN
       DECLARE @Position INT = 1, 
                     @Next INT = 0, 
                     @Delimeter NCHAR(1) = CHAR(10),
                     @WorkString VARCHAR(MAX) = @DropCmd + 'GO' + CHAR(10) + @sqlcmd;

       WHILE (1 = 1)
       BEGIN
              SELECT @Next = CHARINDEX(@Delimeter, @WorkString, @Position)

              IF (@Next = 0) 
                     BREAK

              IF (@Position <> @Next)
                     SELECT SUBSTRING(@WorkString, @Position, @Next - @Position) as SqlString

              SELECT @Position = @Next + 1
    END
END
DROP TABLE [#SQLskills_Trace_XE_Column_Map]
tools\dbatools\bin\sqlcmd\Resources\1033\license_SQLCMD.txt
MICROSOFT PRE-RELEASE SOFTWARE LICENSE TERMS
MICROSOFT SQL SERVER VNEXT COMMUNITY TECHNOLOGY PREVIEW 1 (CTP1)
These license terms are an agreement between Microsoft Corporation (or based on where you live, one of its affiliates) and you. Please read them. They apply to the pre-release software named above, which includes the media on which you received it, if any. The terms also apply to any Microsoft
•	updates,
•	supplements,
•	Internet-based services, and 
•	support services
for this software, unless other terms accompany those items. If so, those terms apply.
BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS.  YOU MAY CHOOSE NOT TO ACCEPT THESE TERMS, IN WHICH CASE YOU MAY NOT USE THE SOFTWARE (IF YOU HAVE NOT ALREADY INSTALLED IT) OR WITHDRAW YOUR ACCEPTANCE ANY TIME BY UNINSTALLING THE SOFTWARE. 
We collect data about how you interact with this software. This includes data about the performance of the services, any problems you experience with them, and the features you use. This also includes data about your device and the network you use to connect to our services, including IP address, device identifiers, regional and language settings. It includes information about the operating systems and other software installed on your device, including product keys. By using this software, you consent to Microsoft’s collection of usage and performance data related to your use of the software.

If you comply with these license terms, you have the rights below.
1.	INSTALLATION AND USE RIGHTS. 
a.	Installation and Use.
•	You may install any number of copies of the software on your premises solely to internally evaluate it and provide feedback to Microsoft. 
•	You may not test the software in a live operating environment unless Microsoft permits you to do so under another agreement.
b.	Third Party Programs.  
The software may include third party components with separate legal notices or governed by other agreements, as may be described in the ThirdPartyNotices file accompanying the software.  Even if such components are governed by other agreements, the disclaimers and the limitations on and exclusions of damages below also apply.
2.	TERM. The term of this agreement is until 6/30/2017.
3.	PRE-RELEASE SOFTWARE. This software is a pre-release version. It may not work the way a final version of the software will. We may change it for the final, commercial version. We also may not release a commercial version.
4.	FEEDBACK. If you give feedback about the software to Microsoft, you give to Microsoft, without charge, the right to use, share and commercialize your feedback in any way and for any purpose. You also give to third parties, without charge, any patent rights needed for their products, technologies and services to use or interface with any specific parts of a Microsoft software or service that includes the feedback. You will not give feedback that is subject to a license that requires Microsoft to license its software or documentation to third parties because we include your feedback in them. These rights survive this agreement.
5.	SCOPE OF LICENSE. The software is licensed, not sold. This agreement only gives you some rights to use the software. Microsoft reserves all other rights. Unless applicable law gives you more rights despite this limitation, you may use the software only as expressly permitted in this agreement. In doing so, you must comply with any technical limitations in the software that only allow you to use it in certain ways. You may not
•	disclose the results of any benchmark tests of the software to any third party without Microsoft’s prior written approval;
•	work around any technical limitations in the software;
•	reverse engineer, decompile or disassemble the software, except and only to the extent that applicable law expressly permits, despite this limitation;
•	make more copies of the software than specified in this agreement or allowed by applicable law, despite this limitation;
•	publish the software for others to copy;
•	rent, lease or lend the software;
•	transfer the software or this agreement to any third party; or
•	use the software for commercial software hosting services.
6.	EXPORT RESTRICTIONS. The software is subject to United States export laws and regulations. You must comply with all domestic and international export laws and regulations that apply to the software. These laws include restrictions on destinations, end users and end use. For additional information, see www.microsoft.com/exporting. 
7.	SUPPORT SERVICES. Because this software is “as is,” we may not provide support services for it.
8.	ENTIRE AGREEMENT. This agreement, and the terms for supplements, updates, Internet-based services and support services that you use, are the entire agreement for the software and support services.
9.	APPLICABLE LAW.
a.	United States. If you acquired the software in the United States, Washington state law governs the interpretation of this agreement and applies to claims for breach of it, regardless of conflict of laws principles. The laws of the state where you live govern all other claims, including claims under state consumer protection laws, unfair competition laws, and in tort.
b.	Outside the United States. If you acquired the software in any other country, the laws of that country apply.
10.	LEGAL EFFECT. This agreement describes certain legal rights. You may have other rights under the laws of your country. You may also have rights with respect to the party from whom you acquired the software. This agreement does not change your rights under the laws of your country if the laws of your country do not permit it to do so.
11.	DISCLAIMER OF WARRANTY. THE SOFTWARE IS LICENSED “AS-IS.” YOU BEAR THE RISK OF USING IT. MICROSOFT GIVES NO EXPRESS WARRANTIES, GUARANTEES OR CONDITIONS. YOU MAY HAVE ADDITIONAL CONSUMER RIGHTS OR STATUTORY GUARANTEES UNDER YOUR LOCAL LAWS WHICH THIS AGREEMENT CANNOT CHANGE. TO THE EXTENT PERMITTED UNDER YOUR LOCAL LAWS, MICROSOFT EXCLUDES THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
FOR AUSTRALIA – YOU HAVE STATUTORY GUARANTEES UNDER THE AUSTRALIAN CONSUMER LAW AND NOTHING IN THESE TERMS IS INTENDED TO AFFECT THOSE RIGHTS.
12.	LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. YOU CAN RECOVER FROM MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP TO U.S. $5.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT OR INCIDENTAL DAMAGES.
This limitation applies to
•	anything related to the software, services, content (including code) on third party Internet sites, or third party programs; and
•	claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence, or other tort to the extent permitted by applicable law.
It also applies even if Microsoft knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your country may not allow the exclusion or limitation of incidental, consequential or other damages.
Please note: As this software is distributed in Quebec, Canada, these license terms are provided below in French.
Remarque : Ce logiciel étant distribué au Québec, Canada, certaines des clauses dans ce contrat sont fournies ci-dessous en français.
EXCLUSIONS DE GARANTIE. Le logiciel est concédé sous licence « en l’état ». Vous assumez tous les risques liés à son utilisation. Microsoft n’accorde aucune garantie ou condition expresse. Vous pouvez bénéficier de droits des consommateurs supplémentaires dans le cadre du droit local, que ce contrat ne peut modifier. Lorsque cela est autorisé par le droit local, Microsoft exclut les garanties implicites de qualité, d’adéquation à un usage particulier et d’absence de contrefaçon.

LIMITATION ET EXCLUSION DE RECOURS ET DE DOMMAGES. Vous pouvez obtenir de Microsoft et de ses fournisseurs une indemnisation en cas de dommages directs limitée uniquement à hauteur de 5,00 $ US. Vous ne pouvez prétendre à aucune indemnisation pour les autres dommages, y compris les dommages spéciaux, indirects ou accessoires et pertes de bénéfices.
Cette limitation concerne :
•	toute affaire liée au logiciel, aux services ou au contenu (y compris le code) figurant sur des sites Internet tiers ou dans des programmes tiers et
•	les réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité stricte, de négligence ou d’une autre faute dans la limite autorisée par la loi en vigueur.
Elle s’applique également même si Microsoft connaissait l'éventualité d'un tel dommage. La limitation ou exclusion ci-dessus peut également ne pas vous être applicable, car votre pays n’autorise pas l’exclusion ou la limitation de responsabilité pour les dommages indirects, accessoires ou de quelque nature que ce soit.

EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d’autres droits prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de votre pays si celles-ci ne le permettent pas.


tools\dbatools\bin\sqlcmd\Resources\1033\SQLCMD.rll
 
tools\dbatools\bin\sqlcmd\SQLCMD.EXE
md5: 6F9AA3F25E87B31393521111E53481B8 | sha1: 8EBCE101C98ECDD15F3471F4268D0B835DBDC485 | sha256: EB9153A1B0EEF429572DD798179FC9016482A647049737EC0F5F02D1054DC49C | sha512: F3B21E59006672CC16B2F84EECA3231CA8818A0EC691131165C736F5F9FD6CFA4EE038A5DE0532C2A1C41C5B994DDF8D5EFC3B990A663B4CB5891855B1EC7DBF
tools\dbatools\bin\stig.sql
USE tempdb;
                GO

                IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = 'STIG')
                BEGIN
	                DROP SCHEMA STIG
                END
                GO

                CREATE SCHEMA STIG
                GO

            /*
            Objects defined in this file:

            VIEW STIG.database_role_members
                Based on the system view sys.database_role_members, this presents the list of
                database role memberships using roles' and users' names rather than their id numbers.
                Although membership in database roles is hierarchical, this view lists only the direct memberships.

            FUNCTION STIG.database_roles_of(@database_principal sysname)
                Given the name of a database principal (user or role), this table-valued function returns
                a list of all the roles it belongs to, both directly and indirectly.

            FUNCTION STIG.members_of_db_role(@database_role sysname)
                Given the name of a database role, this table-valued function returns
                a list of all the roles and users that belong to it, both directly and indirectly.

            VIEW STIG.database_permissions
                Based on the system view sys.database_permissions, this provides additional, descriptive material.
                The list includes only those permissions explicitly granted (or denied) to a database user or role;
                it does not include permissions that are implicit or inherited from a higher-level role.
                Securable items that exist but have no explicit permissions assigned are included in the
                list, with the columns that describe the grantor and grantee left null.

            FUNCTION STIG.database_effective_permissions(@Grantee sysname)
                Given the name of a database principal (user or role), this table-valued function 
                returns information about permissions granted (or denied) to that user or database role,
                either directly or inherited from a higher-level role.


            VIEW STIG.server_role_members
                Based on the system view sys.server_role_members, this presents the list of
                server role memberships using roles' and users' names rather than their id numbers.
                Although membership in server roles is hierarchical, this view lists only the direct memberships.

            FUNCTION STIG.server_roles_of(@server_principal sysname)
                Given the name of a server principal (login or role), this table-valued function returns
                a list of all the roles it belongs to, both directly and indirectly.

            FUNCTION STIG.members_of_server_role(@server_role sysname)
                Given the name of a server role, this table-valued function returns
                a list of all the roles and logins that belong to it, both directly and indirectly.

            VIEW STIG.server_permissions
                Based on the system view sys.server_permissions, this provides additional, descriptive material.
                The list includes only those permissions explicitly granted (or denied) to a server login or role;
                it does not include permissions that are implicit or inherited from a higher-level role.
                Securable items that exist but have no explicit permissions assigned are included in the
                list, with columns describing the grantor and grantee left null.

            FUNCTION STIG.server_effective_permissions(@Grantee sysname)
                Given the name of a server principal (login or server role), this table-valued function 
                returns information about permissions granted (or denied) to that login or role,
                either directly or inherited from a higher-level role.
            */


            BEGIN TRY DROP VIEW STIG.database_role_members END TRY BEGIN CATCH END CATCH;
            GO

            CREATE VIEW STIG.database_role_members
            --  Based on the system view sys.database_role_members, this presents the list of
            --  database role memberships using roles' and users' names rather than their id numbers.
            --  Although membership in database roles is hierarchical, this view lists only the direct memberships.
            AS SELECT
                R.name  AS [Role],
                M.name  AS [Member]
            FROM
                <TARGETDB>.sys.database_role_members X
                INNER JOIN <TARGETDB>.sys.database_principals R ON R.principal_id = X.role_principal_id
                INNER JOIN <TARGETDB>.sys.database_principals M ON M.principal_id = X.member_principal_id
            ;
            GO


            BEGIN TRY DROP FUNCTION STIG.database_roles_of END TRY BEGIN CATCH END CATCH;
            GO

            CREATE FUNCTION STIG.database_roles_of(@database_principal sysname)
            --  Membership in database roles is hierarchical.
            --  Given the name of a database principal (user or role), this table-valued function returns
            --  a list of all the roles it belongs to, both directly and indirectly.
                RETURNS @T TABLE
                    (
                    [Member]            sysname,
                    [Role]              sysname, 
                    [via Member]        sysname, 
                    [Membership Chain]  nvarchar(max)
                    )
            AS BEGIN;
                WITH Membership AS
                (
                SELECT
                    [Member] AS [Member],
                    [Role], 
                    [Member] AS [via Member], 
                    CAST([Member] AS varchar(max)) + ' < ' + CAST([Role] AS varchar(max)) AS [Membership Chain]
                FROM
                    STIG.database_role_members
                WHERE 
                    [Member] = @database_principal
    
                UNION ALL
    
                SELECT
                    X.[Member],
                    R.[Role],
                    R.[Member] AS [via Member],
                    X.[Membership Chain] + ' < ' + CAST(R.[Role] AS varchar(max)) AS [Membership Chain]
                FROM 
                    Membership X
                    INNER JOIN STIG.database_role_members R ON X.[Role] = R.[Member]
                )
                INSERT INTO @T SELECT * FROM Membership;
            ExitFunction:
                RETURN;
            END;
            GO


            BEGIN TRY DROP FUNCTION STIG.members_of_db_role END TRY BEGIN CATCH END CATCH;
            GO

            CREATE FUNCTION STIG.members_of_db_role(@database_role sysname)
            --  Membership in database roles is hierarchical.
            --  Given the name of a database role, this table-valued function returns
            --  a list of all the roles and users that belong to it, both directly and indirectly.
                RETURNS @T TABLE
                    (
                    [Role]              sysname,
                    [Member]            sysname,
                    [via Role]          sysname, 
                    [Membership Chain]  nvarchar(max)
                    )
            AS BEGIN;
                WITH Membership AS
                (
                SELECT
                    [Role] AS [Role],
                    [Member], 
                    [Role] AS [via Role], 
                    CAST([Role] AS varchar(max)) + ' > ' + CAST([Member] AS varchar(max)) AS [Membership Chain]
                FROM
                    STIG.database_role_members
                WHERE 
                    [Role] = @database_role

                UNION ALL

                SELECT
                    X.[Role] AS [Role],
                    R.[Member],
                    R.[Role] AS [via Role],
                    X.[Membership Chain] + ' > ' + CAST(R.[Member] AS varchar(max)) AS [Membership Chain]
                FROM 
                    Membership X
                    INNER JOIN STIG.database_role_members R ON X.[Member] = R.[Role]
                )
                INSERT INTO @T SELECT * FROM Membership;
            ExitFunction:
                RETURN;
            END;
            GO




            BEGIN TRY DROP VIEW STIG.database_permissions END TRY BEGIN CATCH END CATCH;
            GO

            CREATE VIEW STIG.database_permissions
            --  Based on the system view sys.database_permissions, this provides additional, descriptive material.
            --  The list includes only those permissions explicitly granted (or denied) to a database user or role;
            --  it does not include permissions that are implicit or inherited from a higher-level role.
            --  Securable items that exist but have no explicit permissions assigned are included in the
            --  list, with the columns that describe the grantor and grantee left null.
            AS SELECT DISTINCT
                @@SERVERNAME        AS [Current Server],
                @@SERVICENAME       AS [Current Instance],
                '<TARGETDB>'        AS [Current DB],
                SYSTEM_USER         AS [Current Login],
                USER                AS [Current User],

                CASE
                    WHEN DP.class_desc = 'OBJECT_OR_COLUMN'             THEN CASE WHEN DP.minor_id > 0 THEN 'COLUMN' ELSE OB.type_desc END
                    WHEN DP.class_desc IS NOT NULL                      THEN DP.class_desc
                    WHEN DP.class_desc IS NULL AND DB.name IS NOT NULL  THEN 'DATABASE'
                    WHEN DP.class_desc IS NULL AND OB.name IS NOT NULL  THEN 'OBJECT_OR_COLUMN'
                    WHEN DP.class_desc IS NULL AND SC.name IS NOT NULL  THEN 'SCHEMA'
                    WHEN DP.class_desc IS NULL AND PR.name IS NOT NULL  THEN 'DATABASE_PRINCIPAL'
                    WHEN DP.class_desc IS NULL AND AY.name IS NOT NULL  THEN 'ASSEMBLY'
                    WHEN DP.class_desc IS NULL AND TP.name IS NOT NULL  THEN 'TYPE'
                    WHEN DP.class_desc IS NULL AND XS.name IS NOT NULL  THEN 'XML_SCHEMA_COLLECTION'
                    WHEN DP.class_desc IS NULL AND MT.name IS NOT NULL  THEN 'MESSAGE_TYPE'
                    WHEN DP.class_desc IS NULL AND VC.name IS NOT NULL  THEN 'SERVICE_CONTRACT'
                    WHEN DP.class_desc IS NULL AND SV.name IS NOT NULL  THEN 'SERVICE'
                    WHEN DP.class_desc IS NULL AND RS.name IS NOT NULL  THEN 'REMOTE_SERVICE_BINDING'
                    WHEN DP.class_desc IS NULL AND RT.name IS NOT NULL  THEN 'ROUTE'
                    WHEN DP.class_desc IS NULL AND FT.name IS NOT NULL  THEN 'FULLTEXT_CATALOG'
                    WHEN DP.class_desc IS NULL AND SK.name IS NOT NULL  THEN 'SYMMETRIC_KEY'
                    WHEN DP.class_desc IS NULL AND AK.name IS NOT NULL  THEN 'ASYMMETRIC_KEY'
                    WHEN DP.class_desc IS NULL AND CT.name IS NOT NULL  THEN 'CERTIFICATE'
                    ELSE NULL 
                END                 AS [Securable Type or Class],
                CASE
                    WHEN DP.class_desc = 'DATABASE'                     THEN PS.name
                    WHEN DP.class_desc = 'OBJECT_OR_COLUMN'             THEN schema_name(OB.schema_id)
                    WHEN DP.class_desc = 'SCHEMA'                       THEN P3.name
                    WHEN DP.class_desc = 'DATABASE_PRINCIPAL'           THEN coalesce(PR.default_schema_name, PE.name)
                    WHEN DP.class_desc = 'ASSEMBLY'                     THEN P4.name
                    WHEN DP.class_desc = 'TYPE'                         THEN schema_name(TP.schema_id)
                    WHEN DP.class_desc = 'XML_SCHEMA_COLLECTION'        THEN schema_name(XS.schema_id)
                    WHEN DP.class_desc = 'MESSAGE_TYPE'                 THEN P5.name 
                    WHEN DP.class_desc = 'SERVICE_CONTRACT'             THEN P6.name 
                    WHEN DP.class_desc = 'SERVICE'                      THEN P7.name 
                    WHEN DP.class_desc = 'REMOTE_SERVICE_BINDING'       THEN P8.name 
                    WHEN DP.class_desc = 'ROUTE'                        THEN P9.name
                    WHEN DP.class_desc = 'FULLTEXT_CATALOG'             THEN PA.name
                    WHEN DP.class_desc = 'SYMMETRIC_KEY'                THEN PB.name
                    WHEN DP.class_desc = 'ASYMMETRIC_KEY'               THEN PC.name
                    WHEN DP.class_desc = 'CERTIFICATE'                  THEN PD.name
                    WHEN DP.class_desc IS NULL AND DB.name IS NOT NULL  THEN PS.name
                    WHEN DP.class_desc IS NULL AND OB.name IS NOT NULL  THEN schema_name(OB.schema_id)
                    WHEN DP.class_desc IS NULL AND SC.name IS NOT NULL  THEN P3.name
                    WHEN DP.class_desc IS NULL AND PR.name IS NOT NULL  THEN PR.default_schema_name
                    WHEN DP.class_desc IS NULL AND AY.name IS NOT NULL  THEN P4.name
                    WHEN DP.class_desc IS NULL AND TP.name IS NOT NULL  THEN schema_name(TP.schema_id)
                    WHEN DP.class_desc IS NULL AND XS.name IS NOT NULL  THEN schema_name(XS.schema_id)
                    WHEN DP.class_desc IS NULL AND MT.name IS NOT NULL  THEN P5.name
                    WHEN DP.class_desc IS NULL AND VC.name IS NOT NULL  THEN P6.name
                    WHEN DP.class_desc IS NULL AND SV.name IS NOT NULL  THEN P7.name
                    WHEN DP.class_desc IS NULL AND RS.name IS NOT NULL  THEN P8.name
                    WHEN DP.class_desc IS NULL AND RT.name IS NOT NULL  THEN P9.name
                    WHEN DP.class_desc IS NULL AND FT.name IS NOT NULL  THEN PA.name
                    WHEN DP.class_desc IS NULL AND SK.name IS NOT NULL  THEN PB.name
                    WHEN DP.class_desc IS NULL AND AK.name IS NOT NULL  THEN PC.name
                    WHEN DP.class_desc IS NULL AND CT.name IS NOT NULL  THEN PD.name
                    ELSE NULL 
                END                 AS [Schema/Owner],
                CASE
                    WHEN DP.class_desc = 'DATABASE'                     THEN DB.name
                    WHEN DP.class_desc = 'OBJECT_OR_COLUMN'             THEN OB.name
                    WHEN DP.class_desc = 'SCHEMA'                       THEN SC.name
                    WHEN DP.class_desc = 'DATABASE_PRINCIPAL'           THEN PR.name
                    WHEN DP.class_desc = 'ASSEMBLY'                     THEN AY.name
                    WHEN DP.class_desc = 'TYPE'                         THEN TP.name
                    WHEN DP.class_desc = 'XML_SCHEMA_COLLECTION'        THEN XS.name
                    WHEN DP.class_desc = 'MESSAGE_TYPE'                 THEN cast(MT.name as sql_variant)
                    WHEN DP.class_desc = 'SERVICE_CONTRACT'             THEN cast(VC.name as sql_variant)
                    WHEN DP.class_desc = 'SERVICE'                      THEN cast(SV.name as sql_variant)
                    WHEN DP.class_desc = 'REMOTE_SERVICE_BINDING'       THEN RS.name
                    WHEN DP.class_desc = 'ROUTE'                        THEN RT.name
                    WHEN DP.class_desc = 'FULLTEXT_CATALOG'             THEN FT.name
                    WHEN DP.class_desc = 'SYMMETRIC_KEY'                THEN SK.name
                    WHEN DP.class_desc = 'ASYMMETRIC_KEY'               THEN AK.name
                    WHEN DP.class_desc = 'CERTIFICATE'                  THEN CT.name
                    WHEN DP.class_desc IS NULL AND DB.name IS NOT NULL  THEN DB.name 
                    WHEN DP.class_desc IS NULL AND OB.name IS NOT NULL  THEN OB.name
                    WHEN DP.class_desc IS NULL AND SC.name IS NOT NULL  THEN SC.name
                    WHEN DP.class_desc IS NULL AND PR.name IS NOT NULL  THEN PR.name
                    WHEN DP.class_desc IS NULL AND AY.name IS NOT NULL  THEN AY.name
                    WHEN DP.class_desc IS NULL AND TP.name IS NOT NULL  THEN TP.name
                    WHEN DP.class_desc IS NULL AND XS.name IS NOT NULL  THEN XS.name
                    WHEN DP.class_desc IS NULL AND MT.name IS NOT NULL  THEN cast(MT.name as sql_variant)
                    WHEN DP.class_desc IS NULL AND VC.name IS NOT NULL  THEN cast(VC.name as sql_variant)
                    WHEN DP.class_desc IS NULL AND SV.name IS NOT NULL  THEN cast(SV.name as sql_variant)
                    WHEN DP.class_desc IS NULL AND RS.name IS NOT NULL  THEN RS.name
                    WHEN DP.class_desc IS NULL AND RT.name IS NOT NULL  THEN RT.name
                    WHEN DP.class_desc IS NULL AND FT.name IS NOT NULL  THEN FT.name
                    WHEN DP.class_desc IS NULL AND SK.name IS NOT NULL  THEN SK.name
                    WHEN DP.class_desc IS NULL AND AK.name IS NOT NULL  THEN AK.name
                    WHEN DP.class_desc IS NULL AND CT.name IS NOT NULL  THEN CT.name
                    ELSE NULL 
                END                 AS [Securable],
                CM.name             AS [Column],
                P1.type_desc        AS [Grantee Type],
                P1.name             AS [Grantee],
                DP.permission_name  AS [Permission],    
                DP.state_desc       AS [State],
                P2.name             AS [Grantor],
                P2.type_desc        AS [Grantor Type],
                CASE
                    WHEN DP.class_desc = 'DATABASE'                     THEN 'sys.databases'
                    WHEN DP.class_desc = 'OBJECT_OR_COLUMN'             THEN 'sys.all_objects'
                    WHEN DP.class_desc = 'SCHEMA'                       THEN 'sys.schemas'
                    WHEN DP.class_desc = 'DATABASE_PRINCIPAL'           THEN 'sys.database_principals'
                    WHEN DP.class_desc = 'ASSEMBLY'                     THEN 'sys.assemblies'
                    WHEN DP.class_desc = 'TYPE'                         THEN 'sys.types'
                    WHEN DP.class_desc = 'XML_SCHEMA_COLLECTION'        THEN 'sys.xml_schema_collections'
                    WHEN DP.class_desc = 'MESSAGE_TYPE'                 THEN 'sys.service_message_types'
                    WHEN DP.class_desc = 'SERVICE_CONTRACT'             THEN 'sys.database_principals'
                    WHEN DP.class_desc = 'SERVICE'                      THEN 'sys.services'
                    WHEN DP.class_desc = 'REMOTE_SERVICE_BINDING'       THEN 'sys.remote_service_bindings'
                    WHEN DP.class_desc = 'ROUTE'                        THEN 'sys.routes'
                    WHEN DP.class_desc = 'FULLTEXT_CATALOG'             THEN 'sys.database_principals'
                    WHEN DP.class_desc = 'SYMMETRIC_KEY'                THEN 'sys.symmetric_keys'
                    WHEN DP.class_desc = 'ASYMMETRIC_KEY'               THEN 'sys.asymmetric_keys'
                    WHEN DP.class_desc = 'CERTIFICATE'                  THEN 'sys.certificates'
                    WHEN DP.class_desc IS NULL AND DB.name IS NOT NULL  THEN 'sys.databases' 
                    WHEN DP.class_desc IS NULL AND OB.name IS NOT NULL  THEN 'sys.all_objects'
                    WHEN DP.class_desc IS NULL AND SC.name IS NOT NULL  THEN 'sys.schemas'
                    WHEN DP.class_desc IS NULL AND PR.name IS NOT NULL  THEN 'sys.database_principals'
                    WHEN DP.class_desc IS NULL AND AY.name IS NOT NULL  THEN 'sys.assemblies'
                    WHEN DP.class_desc IS NULL AND TP.name IS NOT NULL  THEN 'sys.types'
                    WHEN DP.class_desc IS NULL AND XS.name IS NOT NULL  THEN 'sys.xml_schema_collections'
                    WHEN DP.class_desc IS NULL AND MT.name IS NOT NULL  THEN 'sys.service_message_types'
                    WHEN DP.class_desc IS NULL AND VC.name IS NOT NULL  THEN 'sys.database_principals'
                    WHEN DP.class_desc IS NULL AND SV.name IS NOT NULL  THEN 'sys.services'
                    WHEN DP.class_desc IS NULL AND RS.name IS NOT NULL  THEN 'sys.remote_service_bindings'
                    WHEN DP.class_desc IS NULL AND RT.name IS NOT NULL  THEN 'sys.routes'
                    WHEN DP.class_desc IS NULL AND FT.name IS NOT NULL  THEN 'sys.database_principals'
                    WHEN DP.class_desc IS NULL AND SK.name IS NOT NULL  THEN 'sys.symmetric_keys'
                    WHEN DP.class_desc IS NULL AND AK.name IS NOT NULL  THEN 'sys.asymmetric_keys'
                    WHEN DP.class_desc IS NULL AND CT.name IS NOT NULL  THEN 'sys.certificates'
                    ELSE '<TARGETDB>.sys.database_permissions'
                END                 AS [Source View]
            FROM
                <TARGETDB>.sys.database_permissions DP
                LEFT OUTER JOIN <TARGETDB>.sys.database_principals P1
                    ON  P1.principal_id = DP.grantee_principal_id
                LEFT OUTER JOIN <TARGETDB>.sys.database_principals P2
                    ON  P2.principal_id = DP.grantor_principal_id

                FULL OUTER JOIN <TARGETDB>.sys.databases DB
                    ON  DB.database_id = db_id(db_name(DP.major_id))
                    AND DP.class_desc = 'DATABASE'
                LEFT OUTER JOIN <TARGETDB>.sys.server_principals PS
                    ON  PS.sid = DB.owner_sid

                FULL OUTER JOIN <TARGETDB>.sys.all_objects OB
                    ON  DP.major_id   = OB.[object_id]
                    AND DP.class_desc = 'OBJECT_OR_COLUMN'
                LEFT OUTER JOIN <TARGETDB>.sys.all_columns CM
                    ON  CM.[object_id] = DP.major_id
                    AND CM.[column_id] = DP.minor_id

                FULL OUTER JOIN <TARGETDB>.sys.schemas SC
                    ON  DP.major_id   = SC.[schema_id]
                    AND DP.class_desc = 'SCHEMA'
                LEFT OUTER JOIN <TARGETDB>.sys.database_principals P3
                    ON  P3.principal_id = SC.principal_id

                FULL OUTER JOIN <TARGETDB>.sys.database_principals PR
                    ON  DP.major_id   = PR.principal_id
                    AND DP.class_desc = 'DATABASE_PRINCIPAL'
                LEFT OUTER JOIN <TARGETDB>.sys.database_principals PE
                    ON  PE.principal_id = PR.owning_principal_id

                FULL OUTER JOIN <TARGETDB>.sys.assemblies AY
                    ON  DP.major_id   = AY.assembly_id
                    AND DP.class_desc = 'ASSEMBLY'
                LEFT OUTER JOIN <TARGETDB>.sys.database_principals P4
                    ON  P4.principal_id = AY.principal_id

                FULL OUTER JOIN <TARGETDB>.sys.types TP
                    ON  DP.major_id   = TP.user_type_id
                    AND DP.class_desc = 'TYPE'

                FULL OUTER JOIN <TARGETDB>.sys.xml_schema_collections XS
                    ON  DP.major_id   = XS.xml_collection_id
                    AND DP.class_desc = 'XML_SCHEMA_COLLECTION'

                FULL OUTER JOIN <TARGETDB>.sys.service_message_types MT
                    ON  DP.major_id   = MT.message_type_id
                    AND DP.class_desc = 'MESSAGE_TYPE'
                LEFT OUTER JOIN <TARGETDB>.sys.database_principals P5
                    ON  P5.principal_id = MT.principal_id

                FULL OUTER JOIN <TARGETDB>.sys.service_contracts VC
                    ON  DP.major_id   = VC.service_contract_id
                    AND DP.class_desc = 'SERVICE_CONTRACT'
                LEFT OUTER JOIN <TARGETDB>.sys.database_principals P6
                    ON  P6.principal_id = VC.principal_id

                FULL OUTER JOIN <TARGETDB>.sys.services SV
                    ON  DP.major_id   = SV.service_id
                    AND DP.class_desc = 'SERVICE'
                LEFT OUTER JOIN <TARGETDB>.sys.database_principals P7
                    ON  P7.principal_id = SV.principal_id

                FULL OUTER JOIN <TARGETDB>.sys.remote_service_bindings RS
                    ON  DP.major_id   = RS.remote_service_binding_id
                    AND DP.class_desc = 'REMOTE_SERVICE_BINDING'
                LEFT OUTER JOIN <TARGETDB>.sys.database_principals P8
                    ON  P8.principal_id = RS.principal_id

                FULL OUTER JOIN <TARGETDB>.sys.routes RT
                    ON  DP.major_id   = RT.route_id
                    AND DP.class_desc = 'ROUTE'
                LEFT OUTER JOIN <TARGETDB>.sys.database_principals P9
                    ON  P9.principal_id = RT.principal_id

                FULL OUTER JOIN <TARGETDB>.sys.fulltext_catalogs FT
                    ON  DP.major_id   = FT.fulltext_catalog_id
                    AND DP.class_desc = 'FULLTEXT_CATALOG'
                LEFT OUTER JOIN <TARGETDB>.sys.database_principals PA
                    ON  PA.principal_id = FT.principal_id

                FULL OUTER JOIN <TARGETDB>.sys.symmetric_keys SK
                    ON  DP.major_id   = SK.symmetric_key_id
                    AND DP.class_desc = 'SYMMETRIC_KEY'
                LEFT OUTER JOIN <TARGETDB>.sys.database_principals PB
                    ON  PB.principal_id = SK.principal_id

                FULL OUTER JOIN <TARGETDB>.sys.asymmetric_keys AK
                    ON  DP.major_id   = AK.asymmetric_key_id
                    AND DP.class_desc = 'ASYMMETRIC_KEY'
                LEFT OUTER JOIN <TARGETDB>.sys.database_principals PC
                    ON  PC.principal_id = AK.principal_id

                FULL OUTER JOIN <TARGETDB>.sys.certificates CT
                    ON  DP.major_id   = CT.certificate_id
                    AND DP.class_desc = 'CERTIFICATE'
                LEFT OUTER JOIN <TARGETDB>.sys.database_principals PD
                    ON  PD.principal_id = CT.principal_id    
            ;
            GO



            BEGIN TRY DROP FUNCTION STIG.database_effective_permissions END TRY BEGIN CATCH END CATCH;
            GO

            CREATE FUNCTION STIG.database_effective_permissions(@Grantee sysname)
            --  Given the name of a database principal (user or role), this table-valued function 
            --  returns information about permissions granted (or denied) to that user or database role,
            --  either directly or inherited from a higher-level role.
                RETURNS @T TABLE
                    (
                    [Current Server]            sysname         null,
                    [Current Instance]          sysname         null,
                    [Current DB]                sysname         null,
                    [Current Login]             sysname         null,
                    [Current User]              sysname         null,
                    [Securable Type or Class]   nvarchar(60)    null,
                    [Schema/Owner]              sysname         null,
                    [Securable]                 sql_variant     null,
                    [Column]                    sysname         null,
                    [Effective Grantee]         sysname         null,
                    [Membership Chain]          nvarchar(max)   null,
                    [Direct Grantee]            sysname         null,
                    [Direct Grantee Type]       nvarchar(60)    null,
                    [Permission]                sysname         null,
                    [State]                     nvarchar(60)    null,
                    [Grantor]                   sysname         null,
                    [Grantor Type]              nvarchar(60)    null,
                    [source view]               sysname         null
                    )
            AS BEGIN;
                WITH Targets AS
                (
                SELECT [Role] AS [Principal], [Membership Chain], len([Membership Chain]) AS [Membership Chain Length] FROM STIG.database_roles_of(@Grantee)
                UNION ALL
                SELECT @Grantee AS [Principal], @Grantee AS [Membership Chain], len(@Grantee) AS [Membership Chain Length]    
                )
                INSERT INTO @T
                    SELECT TOP 100000000
                        P.[Current Server],
                        P.[Current Instance],
                        P.[Current DB],
                        P.[Current Login],
                        P.[Current User],
                        P.[Securable Type or Class],
                        P.[Schema/Owner],
                        P.[Securable],
                        P.[Column],
                        @Grantee                AS [Effective Grantee],
                        T.[Membership Chain]    AS [Membership Chain],
                        P.[Grantee]             AS [Direct Grantee],
                        P.[Grantee Type]        AS [Direct Grantee Type],
                        P.[Permission],
                        P.[State],
                        P.[Grantor],
                        P.[Grantor Type],
                        P.[source view]
                    FROM
                        STIG.database_permissions P
                        INNER JOIN Targets T ON T.[Principal] = P.[Grantee]
                    ORDER BY
                        P.[Securable Type or Class],
                        P.[Schema/Owner],
                        P.[Securable],
                        P.[Column],
                        T.[Membership Chain Length]
                    ;
                    UPDATE T
                    SET [State] = [State] + ' (schema denied)'
                    FROM @T T
                    WHERE
                        T.[State] <> 'DENY'
                    AND    T.[Securable Type or Class] <> 'SCHEMA'
                    AND 0 <
                        (
                        SELECT count(*) FROM @T X
                        WHERE
                            X.[Securable Type or Class] = 'SCHEMA'
                        AND X.[Securable]               = T.[Schema/Owner]
                        AND X.[Permission]              = T.[Permission]
                        AND X.[State]                   = 'DENY'
                        )
                    ;
                    UPDATE T
                    SET [State] = [State] + ' (denied)'
                    FROM @T T
                    WHERE
                        T.[State] <> 'DENY'
                    AND 0 <
                        (
                        SELECT count(*) FROM @T X
                        WHERE
                            X.[Securable Type or Class] = T.[Securable Type or Class]
                        AND    X.[Schema/Owner]         = T.[Schema/Owner]
                        AND X.[Securable]               = T.[Securable]
                        AND    (X.[Column] = T.[Column] OR (X.[Column] IS NULL) AND (T.[Column] IS NULL))
                        AND X.[Permission]              = T.[Permission]
                        AND X.[State]                   = 'DENY'
                        )
                    ;
                    UPDATE T
                    SET [State] = [State] + ' (column(s) denied)'
                    FROM @T T
                    WHERE T.[Securable Type or Class] <> 'COLUMN'
                    AND 0 <
                        (
                        SELECT count(*) FROM @T X
                        WHERE
                            X.[Securable Type or Class] = 'COLUMN'
                        AND X.[Schema/Owner]            = T.[Schema/Owner]
                        AND X.[Securable]               = T.[Securable]
                        AND X.[Permission]              = T.[Permission]
                        AND X.[State]                   = 'DENY'
                        )
                    ;
            ExitFunction:
                RETURN;
            END;
            GO



            BEGIN TRY DROP VIEW STIG.server_role_members END TRY BEGIN CATCH END CATCH;
            GO

            CREATE VIEW STIG.server_role_members
            --  Based on the system view sys.server_role_members, this presents the list of
            --  server role memberships using roles' and logins' names rather than their id numbers.
            --  Although membership in server roles is hierarchical, this view lists only the direct memberships.
            AS SELECT
                R.name    AS [Role],
                M.name    AS [Member]
            FROM
                <TARGETDB>.sys.server_role_members X
                INNER JOIN <TARGETDB>.sys.server_principals R ON R.principal_id = X.role_principal_id
                INNER JOIN <TARGETDB>.sys.server_principals M ON M.principal_id = X.member_principal_id
            ;
            GO


            BEGIN TRY DROP FUNCTION STIG.server_roles_of END TRY BEGIN CATCH END CATCH;
            GO

            CREATE FUNCTION STIG.server_roles_of(@server_principal sysname)
            --  Membership in server roles is hierarchical.
            --  Given the name of a server principal (login or role), this table-valued function returns
            --  a list of all the roles it belongs to, both directly and indirectly.
                RETURNS @T TABLE
                    (
                    [Member]            sysname,
                    [Role]              sysname, 
                    [via Member]        sysname, 
                    [Membership Chain]  nvarchar(max)
                    )
            AS BEGIN;
                WITH Membership AS
                (
                SELECT
                    [Member] AS [Member],
                    [Role], 
                    [Member] AS [via Member], 
                    CAST([Member] AS varchar(max)) + ' < ' + CAST([Role] AS varchar(max)) AS [Membership Chain]
                FROM
                    STIG.server_role_members
                WHERE 
                    [Member] = @server_principal
    
                UNION ALL
    
                SELECT
                    X.[Member],
                    R.[Role],
                    R.[Member] AS [via Member],
                    X.[Membership Chain] + ' < ' + CAST(R.[Role] AS varchar(max)) AS [Membership Chain]
                FROM 
                    Membership X
                    INNER JOIN STIG.server_role_members R ON X.[Role] = R.[Member]
                )
                INSERT INTO @T SELECT * FROM Membership;
            ExitFunction:
                RETURN;
            END;
            GO


            BEGIN TRY DROP FUNCTION STIG.members_of_server_role END TRY BEGIN CATCH END CATCH;
            GO

            CREATE FUNCTION STIG.members_of_server_role(@server_role sysname)
            --  Membership in server roles is hierarchical.
            --  Given the name of a server role, this table-valued function returns
            --  a list of all the roles and logins that belong to it, both directly and indirectly.
                RETURNS @T TABLE
                    (
                    [Role]              sysname,
                    [Member]            sysname,
                    [via Role]          sysname, 
                    [Membership Chain]  nvarchar(max)
                    )
            AS BEGIN;
                WITH Membership AS
                (
                SELECT
                    [Role] AS [Role],
                    [Member], 
                    [Role] AS [via Role], 
                    CAST([Role] AS varchar(max)) + ' > ' + CAST([Member] AS varchar(max)) AS [Membership Chain]
                FROM
                    STIG.server_role_members
                WHERE 
                    [Role] = @server_role

                UNION ALL

                SELECT
                    X.[Role] AS [Role],
                    R.[Member],
                    R.[Role] AS [via Role],
                    X.[Membership Chain] + ' > ' + CAST(R.[Member] AS varchar(max)) AS [Membership Chain]
                FROM 
                    Membership X
                    INNER JOIN STIG.server_role_members R ON X.[Member] = R.[Role]
                )
                INSERT INTO @T SELECT * FROM Membership;
            ExitFunction:
                RETURN;
            END;
            GO



            BEGIN TRY DROP VIEW STIG.server_permissions END TRY BEGIN CATCH END CATCH;
            GO

            CREATE VIEW STIG.server_permissions
            --  Based on the system view sys.server_permissions, this provides additional, descriptive material.
            --  The list includes only those permissions explicitly granted (or denied) to a server login or role;
            --  it does not include permissions that are implicit or inherited from a higher-level role.
            --  Securable items that exist but have no explicit permissions assigned are included in the
            --  list, with columns describing the grantor and grantee left null.
            AS SELECT DISTINCT
                @@SERVERNAME          AS [Current Server],
                @@SERVICENAME         AS [Current Instance],
                '<TARGETDB>'             AS [Current DB],
                SYSTEM_USER           AS [Current Login],
                USER                  AS [Current User],
                CASE
                    WHEN SP.class_desc IS NOT NULL THEN 
                        CASE
                            WHEN SP.class_desc = 'SERVER' AND S.is_linked = 0 THEN 'SERVER'
                            WHEN SP.class_desc = 'SERVER' AND S.is_linked = 1 THEN 'SERVER (linked)'
                            ELSE SP.class_desc
                        END
                    WHEN E.name IS NOT NULL THEN 'ENDPOINT'
                    WHEN S.name IS NOT NULL AND S.is_linked = 0 THEN 'SERVER'
                    WHEN S.name IS NOT NULL AND S.is_linked = 1 THEN 'SERVER (linked)'
                    WHEN P.name IS NOT NULL THEN 'SERVER_PRINCIPAL'
                    ELSE '???' 
                END                    AS [Securable Class],
                CASE
                    WHEN E.name IS NOT NULL THEN E.name
                    WHEN S.name IS NOT NULL THEN S.name 
                    WHEN P.name IS NOT NULL THEN P.name
                    ELSE '???' 
                END                    AS [Securable],
                P1.name                AS [Grantee],
                P1.type_desc           AS [Grantee Type],
                sp.permission_name     AS [Permission],
                sp.state_desc          AS [State],
                P2.name                AS [Grantor],
                P2.type_desc           AS [Grantor Type],
                CASE
                    WHEN SP.class_desc = 'SERVER'                       THEN 'sys.servers'
                    WHEN SP.class_desc = 'ENDPOINT'                     THEN 'sys.endpoints'
                    WHEN SP.class_desc = 'SERVER_PRINCIPAL'             THEN 'sys.server_principals'
                    WHEN SP.class_desc IS NULL AND S.name IS NOT NULL   THEN 'sys.servers'
                    WHEN SP.class_desc IS NULL AND E.name IS NOT NULL   THEN 'sys.endpoints' 
                    WHEN SP.class_desc IS NULL AND P.name IS NOT NULL   THEN 'sys.server_principals'
                    ELSE 'sys.server_permissions'
                END                 AS [Source View]
            FROM
                <TARGETDB>.sys.server_permissions SP
                INNER JOIN <TARGETDB>.sys.server_principals P1
                    ON P1.principal_id = SP.grantee_principal_id
                INNER JOIN <TARGETDB>.sys.server_principals P2
                    ON P2.principal_id = SP.grantor_principal_id

                FULL OUTER JOIN sys.servers S
                    ON  SP.class_desc = 'SERVER'
                    AND S.server_id = SP.major_id

                FULL OUTER JOIN <TARGETDB>.sys.endpoints E
                    ON  SP.class_desc = 'ENDPOINT'
                    AND E.endpoint_id = SP.major_id

                FULL OUTER JOIN <TARGETDB>.sys.server_principals P
                    ON  SP.class_desc = 'SERVER_PRINCIPAL'        
                    AND P.principal_id = SP.major_id
            ;
            GO


            BEGIN TRY DROP FUNCTION STIG.server_effective_permissions END TRY BEGIN CATCH END CATCH;
            GO

            CREATE FUNCTION STIG.server_effective_permissions(@Grantee sysname)
            --  Given the name of a server principal (login or server role), this table-valued function 
            --  returns information about permissions granted (or denied) to that login or role,
            --  either directly or inherited from a higher-level role.
                RETURNS @T TABLE
                    (
                    [Current Server]            sysname         null,
                    [Current Instance]          sysname         null,
                    [Current DB]                sysname         null,
                    [Current Login]             sysname         null,
                    [Current User]              sysname         null,
                    [Securable Class]           nvarchar(60)    null,
                    [Securable]                 sql_variant     null,
                    [Effective Grantee]         sysname         null,
                    [Membership Chain]          nvarchar(max)   null,
                    [Direct Grantee]            sysname         null,
                    [Direct Grantee Type]       nvarchar(60)    null,
                    [Permission]                sysname         null,
                    [State]                     nvarchar(60)    null,
                    [Grantor]                   sysname         null,
                    [Grantor Type]              nvarchar(60)    null,
                    [source view]               sysname         null
                    )
            AS BEGIN;
                WITH Targets AS
                (
                SELECT [Role] AS [Principal], [Membership Chain], len([Membership Chain]) AS [Membership Chain Length] FROM STIG.server_roles_of(@Grantee)
                UNION ALL
                SELECT @Grantee AS [Principal], @Grantee AS [Membership Chain], len(@Grantee) AS [Membership Chain Length]    
                )
                INSERT INTO @T
                    SELECT TOP 100000000
                        P.[Current Server],
                        P.[Current Instance],
                        P.[Current DB],
                        P.[Current Login],
                        P.[Current User],
                        P.[Securable Class],
                        P.[Securable],
                        @Grantee                AS [Effective Grantee],
                        T.[Membership Chain]    AS [Membership Chain],
                        P.[Grantee]             AS [Direct Grantee],
                        P.[Grantee Type]        AS [Direct Grantee Type],
                        P.[Permission],
                        P.[State],
                        P.[Grantor],
                        P.[Grantor Type],
                        P.[source view]
                    FROM
                        STIG.server_permissions P
                        INNER JOIN Targets T ON T.[Principal] = P.[Grantee]
                    ORDER BY
                        P.[Securable Class],
                        P.[Securable],
                        T.[Membership Chain Length]
                    ;
                    UPDATE T
                    SET [State] = [State] + ' (denied)'
                    FROM @T T
                    WHERE
                        T.[State] <> 'DENY'
                    AND 0 <
                        (
                        SELECT count(*) FROM @T X
                        WHERE
                            X.[Securable Class] = T.[Securable Class]
                        AND X.[Securable]       = T.[Securable]
                        AND X.[Permission]      = T.[Permission]
                        AND X.[State]           = 'DENY'
                        )
                    ;
            ExitFunction:
                RETURN;
            END;
            GO
tools\dbatools\bin\third-party-licenses\sql-server-data-tools-license-terms-vs2017.md
---
title: "SQL Server Data Tools and Visual Studio 2017 - License Terms | Microsoft Docs"
ms.custom: ""
ms.date: "08/04/2017"
ms.prod: "sql-non-specified"
ms.prod_service: "sql-non-specified"
ms.service: ""
ms.component: "ssdt"
ms.reviewer: ""
ms.suite: "sql"
ms.technology: 
  - "tools-ssdt"
ms.tgt_pltfrm: ""
ms.topic: "article"
ms.assetid: 
caps.latest.revision: 5
author: "stevestein"
ms.author: "sstein"
manager: "craigg"
ms.workload: "On Demand"
---
# SQL Server Data Tools - License Terms
[!INCLUDE[appliesto-ss-asdb-asdw-pdw-md](../includes/appliesto-ss-asdb-asdw-pdw-md.md)]
## MICROSOFT SOFTWARE LICENSE TERMS  
  
**MICROSOFT SQL SERVER DATA TOOLS**  
**MICROSOFT SQL SERVER DATA TOOLS FOR VISUAL STUDIO 2017**
---  
These license terms are an agreement between Microsoft Corporation (or based on where you live, one of its affiliates) and you. Please read them. They apply to the software named above, which includes the media on which you received it, if any. The terms also apply to any Microsoft  
* updates,  
* supplements,  
* Internet-based services, and  
* support services  
  
for this software, unless other terms accompany those items. If so, those terms apply.  
  
**BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. YOU MAY CHOOSE NOT TO ACCEPT THESE TERMS, IN WHICH CASE YOU MAY NOT USE THE SOFTWARE (IF YOU HAVE NOT ALREADY INSTALLED IT) OR WITHDRAW YOUR ACCEPTANCE ANY TIME BY UNINSTALLING THE SOFTWARE.**
  
---  
**If you comply with these license terms, you have the rights below.**  
**1.    INSTALLATION AND USE RIGHTS.**  
  
&nbsp;&nbsp;**a.    Installation and Use.**  
  
   * You may install and use any number of copies of the software on your devices to design, develop and test your programs.  
   * If the software includes Microsoft Visual Studio 2017, you may only use Microsoft Visual Studio 2017 components with Microsoft SQL Server Data Tools.
     
&nbsp;&nbsp;**b.    Other Microsoft Programs.**  

   * The software includes other Microsoft SQL Server technologies, Microsoft Visual Studio  2017, .NET Framework, Visual C++ Redistributable for Visual Studio 2017, and Microsoft Report Viewer 2016 Runtime in conjunction with the software licensed here. These components are governed by separate agreements and their own product support policies, as described in the license terms found in the installation directory for that component or in the “Licenses” folder accompanying the software.  
  
**2.    ADDITIONAL LICENSING REQUIREMENTS AND/OR USE RIGHTS.**  
  
&nbsp;&nbsp;**a.    Distributable Code.**  
  
&nbsp;&nbsp;&nbsp;&nbsp;**i.    Right to Use and Distribute. If you comply with the terms below:**  
* You may copy and distribute the object code form of the Microsoft SQL Server Data-Tier Application Framework (“**Distributable Code**”) in programs you develop; and   
* You may permit distributors of your programs to copy and distribute the Distributable Code as part of those programs.  
  
&nbsp;&nbsp;&nbsp;&nbsp;**ii.   Distribution Requirements. For any Distributable Code you distribute, you must**  
* add significant primary functionality to it in your programs; 
* for any Distributable Code having a filename extension of .lib, distribute only the results of running such Distributable Code through a linker with your program; 
* distribute Distributable Code included in a setup program only as part of that setup program without modification; 
* require distributors and external end users to agree to the Microsoft license terms included as part of our software setup program; 
* display your valid copyright notice on your programs; and 
* indemnify, defend, and hold harmless Microsoft from any claims, including attorneys’ fees, related to the distribution or use of your programs
 
  
&nbsp;&nbsp;&nbsp;&nbsp;**iii.  Distribution Restrictions. You may not**  
* alter any copyright, trademark or patent notice in the Distributable Code; 
* use Microsoft’s trademarks in your programs’ names or in a way that suggests your programs come from or are endorsed by Microsoft; 
* distribute Distributable Code to run on a platform other than the Windows platform; 
* include Distributable Code in malicious, deceptive or unlawful programs; or 
* modify or distribute the source code of any Distributable Code so that any part of it becomes subject to an Excluded License. An Excluded License is one that requires, as a condition of use, modification or distribution, that 
* the code be disclosed or distributed in source code form; or 
* others have the right to modify it. 
  
  
**3.    INTERNET-BASED SERVICES.** Microsoft provides Internet-based services with the software. It may change or cancel them at any time.  You may not use these devices in any way that could harm them or impair anyone else’s use of them.  You may not use the services to try to gain unauthorized access to any service, data, account or network by any means.  
  
&nbsp;&nbsp;**a.    SQL Server Reporting Services Map Report Item.** The software may include features that retrieve content such as maps, images and other data through the Bing Maps (or successor branded) application programming interface (the “Bing Maps APIs”). The purpose of these features is to create reports displaying data on top of maps, aerial and hybrid imagery. If these features are included, you may use them to create and view dynamic or static documents. This may be done only in conjunction with and through methods and means of access integrated in the software. You may not otherwise copy, store, archive, or create a database of the content available through the Bing Maps APIs. You may not use the following for any purpose even if they are available through the Bing Maps APIs:  
* Bing Maps APIs to provide sensor based guidance/routing, or  
* any Road Traffic Data or Bird’s Eye Imagery (or associated metadata).  
Your use of Bing Maps is also governed by the Bing Maps End User Terms of Use available at http://go.microsoft.com/?linkid=9710837 and the Bing Maps Privacy Statement available at http://go.microsoft.com/fwlink/?LinkID=248686.  
  
&nbsp;&nbsp;**b.**  This software is designed to allow users of SQL Server Integration Services (SSIS) to (a) move data between on-premises data-stores and Microsoft online services and (b) trigger certain actions in Microsoft online services. In order to do this, the software uses Internet Protocols to (i) send data, including your own data as designated by you and data about the software’s configuration, to these services, and (ii) request data, including your own data as designated by you and data about the nature and configuration of your Microsoft online services, from these services. Once you configure the software to communicate with these services, you may not receive separate notices when the software connects to these services.  
  
**4.    FEEDBACK.** If you give feedback about the software to Microsoft, you give to Microsoft, without charge, the right to use, share and commercialize your feedback in any way and for any purpose. You also give to third parties, without charge, any patent rights needed for their products, technologies and services to use or interface with any specific parts of a Microsoft software or service that includes the feedback. You will not give feedback that is subject to a license that requires Microsoft to license its software or documentation to third parties because we include your feedback in them. These rights survive this agreement.  
  
**5.  THIRD PARTY NOTICES.** The software may include third party components with separate legal notices or governed by other agreements, as may be described in the ThirdPartyNotices file accompanying the software.  Even if such components are governed by other agreements, the disclaimers and the limitations on and exclusions of damages below also apply.  
  
**6.    .NET FRAMEWORK SOFTWARE.** The software contains Microsoft .NET Framework software. This software is part of Windows. The license terms for Windows apply to your use of the .NET Framework software.  
  
**7.    SCOPE OF LICENSE.** The software is licensed, not sold. This agreement only gives you some rights to use the software. Microsoft reserves all other rights. Unless applicable law gives you more rights despite this limitation, you may use the software only as expressly permitted in this agreement. In doing so, you must comply with any technical limitations in the software that only allow you to use it in certain ways. You may not  
  
* disclose the results of any benchmark tests of the software, other than the Microsoft .NET Framework (see separate term above), to any third party without Microsoft’s prior written approval;  
* work around any technical limitations in the software;  
* reverse engineer, decompile or disassemble the software, except and only to the extent that applicable law expressly permits, despite this limitation;  
* make more copies of the software than specified in this agreement or allowed by applicable law, despite this limitation;  
* publish the software for others to copy;  
* rent, lease or lend the software;  
* transfer the software or this agreement to any third party; or  
* use the software for commercial software hosting services.  
  
**8.    EXPORT RESTRICTIONS.** The software is subject to United States export laws and regulations. You must comply with all domestic and international export laws and regulations that apply to the software. These laws include restrictions on destinations, end users and end use. For additional information, see www.microsoft.com/exporting.  
  
**9.    UPDATES.** The software may install automatic updates, which cannot be turned off. By using the software, you agree to receive automatic updates without any additional notice, and permit Microsoft to download and install them for you. You agree to obtain these updates only from Microsoft or Microsoft authorized sources. If you do not want software updates, disconnect your device from the internet or uninstall the software.  
  
**10.   SUPPORT SERVICES.** Because this software is “as is,” we may not provide support services for it.  
  
**11.   ENTIRE AGREEMENT.** This agreement, and the terms for supplements, updates, Internet-based services and support services that you use, are the entire agreement for the software and support services.  
  
**12.   APPLICABLE LAW.**  
  
&nbsp;&nbsp;**a.    United States.** If you acquired the software in the United States, Washington state law governs the interpretation of this agreement and applies to claims for breach of it, regardless of conflict of laws principles. The laws of the state where you live govern all other claims, including claims under state consumer protection laws, unfair competition laws, and in tort.  
  
&nbsp;&nbsp;**b.    Outside the United States.** If you acquired the software in any other country, the laws of that country apply.  
  
**13.   LEGAL EFFECT.** This agreement describes certain legal rights. You may have other rights under the laws of your country. You may also have rights with respect to the party from whom you acquired the software. This agreement does not change your rights under the laws of your country if the laws of your country do not permit it to do so.  
  
**14.   DISCLAIMER OF WARRANTY. The software is licensed “as-is.” You bear the risk of using it. Microsoft gives no express warranties, guarantees or conditions. You may have additional consumer rights or statutory guarantees under your local laws which this agreement cannot change. To the extent permitted under your local laws, Microsoft excludes the implied warranties of merchantability, fitness for a particular purpose and non-infringement.**  
  
&nbsp;&nbsp;FOR AUSTRALIA – You have statutory guarantees under the Australian Consumer Law and nothing in these terms is intended to affect those rights.  
  
**15.   LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. You can recover from Microsoft and its suppliers only direct damages up to U.S. $5.00. You cannot recover any other damages, including consequential, lost profits, special, indirect or incidental damages.**  
  
This limitation applies to  
* anything related to the software, services, content (including code) on third party Internet sites, or third party programs; and  
* claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence, or other tort to the extent permitted by applicable law.  
  
It also applies even if Microsoft knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your country may not allow the exclusion or limitation of incidental, consequential or other damages.  
  
**Please note: As this software is distributed in Quebec, Canada, these license terms are provided below in French.**  
  
**Remarque : Ce logiciel étant distribué au Québec, Canada, certaines des clauses dans ce contrat sont fournies ci-dessous en français.**  
  
EXCLUSIONS DE GARANTIE. Le logiciel est concédé sous licence « en l’état ». Vous assumez tous les risques liés à son utilisation. Microsoft n’accorde aucune garantie ou condition expresse. Vous pouvez bénéficier de droits des consommateurs supplémentaires dans le cadre du droit local, que ce contrat ne peut modifier. Lorsque cela est autorisé par le droit local, Microsoft exclut les garanties implicites de qualité, d’adéquation à un usage particulier et d’absence de contrefaçon.  

LIMITATION ET EXCLUSION DE RECOURS ET DE DOMMAGES. Vous pouvez obtenir de Microsoft et de ses fournisseurs une indemnisation en cas de dommages directs limitée uniquement à hauteur de 5,00 $ US. Vous ne pouvez prétendre à aucune indemnisation pour les autres dommages, y compris les dommages spéciaux, indirects ou accessoires et pertes de bénéfices.  

Cette limitation concerne :  

toute affaire liée au logiciel, aux services ou au contenu (y compris le code) figurant sur des sites Internet tiers ou dans des programmes tiers et 
les réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité stricte, de négligence ou d’une autre faute dans la limite autorisée par la loi en vigueur.  

Elle s’applique également même si Microsoft connaissait l'éventualité d'un tel dommage. La limitation ou exclusion ci-dessus peut également ne pas vous être applicable, car votre pays n’autorise pas l’exclusion ou la limitation de responsabilité pour les dommages indirects, accessoires ou de quelque nature que ce soit.  

EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d’autres droits prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de votre pays si celles-ci ne le permettent pas.
tools\dbatools\bin\third-party-licenses\sql-server-data-tools-license-terms.md
---
title: "SQL Server Data Tools - License Terms | Microsoft Docs"
ms.custom: ""
ms.date: "01/19/2017"
ms.prod: "sql-non-specified"
ms.prod_service: "sql-non-specified"
ms.service: ""
ms.component: "ssdt"
ms.reviewer: ""
ms.suite: "sql"
ms.technology: 
  - "tools-ssdt"
ms.tgt_pltfrm: ""
ms.topic: "article"
ms.assetid: 0ac5aa53-cdc3-4ced-9ab9-690be02aa951
caps.latest.revision: 5
author: "stevestein"
ms.author: "sstein"
manager: "jhubbard"
ms.workload: "On Demand"
---
# SQL Server Data Tools - License Terms
[!INCLUDE[appliesto-ss-asdb-asdw-pdw-md](../includes/appliesto-ss-asdb-asdw-pdw-md.md)]
## MICROSOFT SOFTWARE LICENSE TERMS  
  
**MICROSOFT SQL SERVER DATA TOOLS**  
  
---  
These license terms are an agreement between Microsoft Corporation (or based on where you live, one of its affiliates) and you. Please read them. They apply to the software named above, which includes the media on which you received it, if any. The terms also apply to any Microsoft  
* updates,  
* supplements,  
* Internet-based services, and  
* support services  
  
for this software, unless other terms accompany those items. If so, those terms apply.  
  
**BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. YOU MAY CHOOSE NOT TO ACCEPT THESE TERMS, IN WHICH CASE YOU MAY NOT USE THE SOFTWARE (IF YOU HAVE NOT ALREADY INSTALLED IT) OR WITHDRAW YOUR ACCEPTANCE ANY TIME BY UNINSTALLING THE SOFTWARE.**  
  
---  
**If you comply with these license terms, you have the rights below.**  
**1.    INSTALLATION AND USE RIGHTS.**  
  
&nbsp;&nbsp;**a.    Installation and Use.**  
  
   * You may install and use any number of copies of the software on your devices to design, develop and test your programs.  
     
&nbsp;&nbsp;**b.    Other Microsoft Programs.** The software includes other Microsoft SQL Server technologies, Microsoft Visual Studio 2015 Shell (Isolated) Redistributable Package, Microsoft Visual Studio 2015 Shell (Integrated) Redistributable Package, Microsoft Visual Studio Tools for Applications 2015, .NET Framework, Visual C++ Redistributable for Visual Studio 2015, and Microsoft Report Viewer 2016 Runtime in conjunction with the software licensed here. These components are governed by separate agreements and their own product support policies, as described in the license terms found in the installation directory for that component or in the “Licenses” folder accompanying the software.  
  
**2.    ADDITIONAL LICENSING REQUIREMENTS AND/OR USE RIGHTS.**  
  
&nbsp;&nbsp;**a.    Distributable Code.**  
  
&nbsp;&nbsp;&nbsp;&nbsp;**i.    Right to Use and Distribute. If you comply with the terms below:**  
* You may copy and distribute the object code form of the Microsoft SQL Server Data-Tier Application Framework (“**Distributable Code**”) in programs you develop; and   
* You may permit distributors of your programs to copy and distribute the Distributable Code as part of those programs.  
  
&nbsp;&nbsp;&nbsp;&nbsp;**ii.   Distribution Requirements. For any Distributable Code you distribute, you must**  
* add significant primary functionality to it in your programs;  
* for any Distributable Code having a filename extension of .lib, distribute only the results of running such Distributable Code through a linker with your program;  
* distribute Distributable Code included in a setup program only as part of that setup program without modification;  
* require distributors and external end users to agree to the Microsoft license terms included as part of our software setup program;   
* display your valid copyright notice on your programs; and  
* indemnify, defend, and hold harmless Microsoft from any claims, including attorneys’ fees, related to the distribution or use of your programs.  
  
&nbsp;&nbsp;&nbsp;&nbsp;**iii.  Distribution Restrictions. You may not**  
* alter any copyright, trademark or patent notice in the Distributable Code;  
* use Microsoft’s trademarks in your programs’ names or in a way that suggests your programs come from or are endorsed by Microsoft;  
* distribute Distributable Code to run on a platform other than the Windows platform;  
* include Distributable Code in malicious, deceptive or unlawful programs; or  
* modify or distribute the source code of any Distributable Code so that any part of it becomes subject to an Excluded License. An Excluded License is one that requires, as a condition of use, modification or distribution, that  
* the code be disclosed or distributed in source code form; or  
* others have the right to modify it.  
  
**3.    INTERNET-BASED SERVICES.** Microsoft provides Internet-based services with the software. It may change or cancel them at any time.  You may not use these devices in any way that could harm them or impair anyone else’s use of them.  You may not use the services to try to gain unauthorized access to any service, data, account or network by any means.  
  
&nbsp;&nbsp;**a.    SQL Server Reporting Services Map Report Item.** The software may include features that retrieve content such as maps, images and other data through the Bing Maps (or successor branded) application programming interface (the “Bing Maps APIs”). The purpose of these features is to create reports displaying data on top of maps, aerial and hybrid imagery. If these features are included, you may use them to create and view dynamic or static documents. This may be done only in conjunction with and through methods and means of access integrated in the software. You may not otherwise copy, store, archive, or create a database of the content available through the Bing Maps APIs. You may not use the following for any purpose even if they are available through the Bing Maps APIs:  
* Bing Maps APIs to provide sensor based guidance/routing, or  
* any Road Traffic Data or Bird’s Eye Imagery (or associated metadata).  
Your use of Bing Maps is also governed by the Bing Maps End User Terms of Use available at http://go.microsoft.com/?linkid=9710837 and the Bing Maps Privacy Statement available at http://go.microsoft.com/fwlink/?LinkID=248686.  
  
&nbsp;&nbsp;**b.**  This software is designed to allow users of SQL Server Integration Services (SSIS) to (a) move data between on-premises data-stores and Microsoft online services and (b) trigger certain actions in Microsoft online services. In order to do this, the software uses Internet Protocols to (i) send data, including your own data as designated by you and data about the software’s configuration, to these services, and (ii) request data, including your own data as designated by you and data about the nature and configuration of your Microsoft online services, from these services. Once you configure the software to communicate with these services, you may not receive separate notices when the software connects to these services.  
  
**4.    FEEDBACK.** If you give feedback about the software to Microsoft, you give to Microsoft, without charge, the right to use, share and commercialize your feedback in any way and for any purpose. You also give to third parties, without charge, any patent rights needed for their products, technologies and services to use or interface with any specific parts of a Microsoft software or service that includes the feedback. You will not give feedback that is subject to a license that requires Microsoft to license its software or documentation to third parties because we include your feedback in them. These rights survive this agreement.  
  
**5.  THIRD PARTY NOTICES.** The software may include third party components with separate legal notices or governed by other agreements, as may be described in the ThirdPartyNotices file accompanying the software.  Even if such components are governed by other agreements, the disclaimers and the limitations on and exclusions of damages below also apply.  
  
**6.    .NET FRAMEWORK SOFTWARE.** The software contains Microsoft .NET Framework software. This software is part of Windows. The license terms for Windows apply to your use of the .NET Framework software.  
  
**7.    SCOPE OF LICENSE.** The software is licensed, not sold. This agreement only gives you some rights to use the software. Microsoft reserves all other rights. Unless applicable law gives you more rights despite this limitation, you may use the software only as expressly permitted in this agreement. In doing so, you must comply with any technical limitations in the software that only allow you to use it in certain ways. You may not  
  
* disclose the results of any benchmark tests of the software, other than the Microsoft .NET Framework (see separate term above), to any third party without Microsoft’s prior written approval;  
* work around any technical limitations in the software;  
* reverse engineer, decompile or disassemble the software, except and only to the extent that applicable law expressly permits, despite this limitation;  
* make more copies of the software than specified in this agreement or allowed by applicable law, despite this limitation;  
* publish the software for others to copy;  
* rent, lease or lend the software;  
* transfer the software or this agreement to any third party; or  
* use the software for commercial software hosting services.  
  
**8.    EXPORT RESTRICTIONS.** The software is subject to United States export laws and regulations. You must comply with all domestic and international export laws and regulations that apply to the software. These laws include restrictions on destinations, end users and end use. For additional information, see www.microsoft.com/exporting.  
  
**9.    UPDATES.** The software may install automatic updates, which cannot be turned off. By using the software, you agree to receive automatic updates without any additional notice, and permit Microsoft to download and install them for you. You agree to obtain these updates only from Microsoft or Microsoft authorized sources. If you do not want software updates, disconnect your device from the internet or uninstall the software.  
  
**10.   SUPPORT SERVICES.** Because this software is “as is,” we may not provide support services for it.  
  
**11.   ENTIRE AGREEMENT.** This agreement, and the terms for supplements, updates, Internet-based services and support services that you use, are the entire agreement for the software and support services.  
  
**12.   APPLICABLE LAW.**  
  
&nbsp;&nbsp;**a.    United States.** If you acquired the software in the United States, Washington state law governs the interpretation of this agreement and applies to claims for breach of it, regardless of conflict of laws principles. The laws of the state where you live govern all other claims, including claims under state consumer protection laws, unfair competition laws, and in tort.  
  
&nbsp;&nbsp;**b.    Outside the United States.** If you acquired the software in any other country, the laws of that country apply.  
  
**13.   LEGAL EFFECT.** This agreement describes certain legal rights. You may have other rights under the laws of your country. You may also have rights with respect to the party from whom you acquired the software. This agreement does not change your rights under the laws of your country if the laws of your country do not permit it to do so.  
  
**14.   DISCLAIMER OF WARRANTY. The software is licensed “as-is.” You bear the risk of using it. Microsoft gives no express warranties, guarantees or conditions. You may have additional consumer rights or statutory guarantees under your local laws which this agreement cannot change. To the extent permitted under your local laws, Microsoft excludes the implied warranties of merchantability, fitness for a particular purpose and non-infringement.**  
  
&nbsp;&nbsp;FOR AUSTRALIA – You have statutory guarantees under the Australian Consumer Law and nothing in these terms is intended to affect those rights.  
  
**15.   LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. You can recover from Microsoft and its suppliers only direct damages up to U.S. $5.00. You cannot recover any other damages, including consequential, lost profits, special, indirect or incidental damages.**  
  
This limitation applies to  
* anything related to the software, services, content (including code) on third party Internet sites, or third party programs; and  
* claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence, or other tort to the extent permitted by applicable law.  
  
It also applies even if Microsoft knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your country may not allow the exclusion or limitation of incidental, consequential or other damages.  
  
**Please note: As this software is distributed in Quebec, Canada, these license terms are provided below in French.**  
  
**Remarque : Ce logiciel étant distribué au Québec, Canada, certaines des clauses dans ce contrat sont fournies ci-dessous en français.**  
  
EXCLUSIONS DE GARANTIE. Le logiciel est concédé sous licence « en l’état ». Vous assumez tous les risques liés à son utilisation. Microsoft n’accorde aucune garantie ou condition expresse. Vous pouvez bénéficier de droits des consommateurs supplémentaires dans le cadre du droit local, que ce contrat ne peut modifier. Lorsque cela est autorisé par le droit local, Microsoft exclut les garanties implicites de qualité, d’adéquation à un usage particulier et d’absence de contrefaçon.  
  
LIMITATION ET EXCLUSION DE RECOURS ET DE DOMMAGES. Vous pouvez obtenir de Microsoft et de ses fournisseurs une indemnisation en cas de dommages directs limitée uniquement à hauteur de 5,00 $ US. Vous ne pouvez prétendre à aucune indemnisation pour les autres dommages, y compris les dommages spéciaux, indirects ou accessoires et pertes de bénéfices.  
  
Cette limitation concerne :  
  
toute affaire liée au logiciel, aux services ou au contenu (y compris le code) figurant sur des sites Internet tiers ou dans des programmes tiers et  
  
les réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité stricte, de négligence ou d’une autre faute dans la limite autorisée par la loi en vigueur.  
  
Elle s’applique également même si Microsoft connaissait l'éventualité d'un tel dommage. La limitation ou exclusion ci-dessus peut également ne pas vous être applicable, car votre pays n’autorise pas l’exclusion ou la limitation de responsabilité pour les dommages indirects, accessoires ou de quelque nature que ce soit.  
  
EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d’autres droits prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de votre pays si celles-ci ne le permettent pas.
tools\dbatools\bin\third-party-licenses\ThirdPartyNoticesDacFramework.rtf
 
tools\dbatools\bin\thor.png
 
tools\dbatools\bin\type-extensions.ps1
# Only update on first import
if (-not ([Sqlcollaborative.Dbatools.dbaSystem.SystemHost]::ModuleImported)) {
    # Implement query accelerator for the server object
    Update-TypeData -TypeName Microsoft.SqlServer.Management.Smo.Server -MemberName Query -MemberType ScriptMethod -Value {
        param (
            $Query,

            $Database = "master",

            $AllTables = $false
        )

        if ($AllTables) { ($this.Databases[$Database].ExecuteWithResults($Query)).Tables }
        else { ($this.Databases[$Database].ExecuteWithResults($Query)).Tables[0] }
    } -ErrorAction Ignore

    Update-TypeData -TypeName Microsoft.SqlServer.Management.Smo.Server -MemberName Invoke -MemberType ScriptMethod -Value {
        param (
            $Command,

            $Database = "master"
        )

        $this.Databases[$Database].ExecuteNonQuery($Command)
    } -ErrorAction Ignore

    Update-TypeData -TypeName Microsoft.SqlServer.Management.Smo.Database -MemberName Query -MemberType ScriptMethod -Value {
        param (
            $Query,

            $AllTables = $false
        )

        if ($AllTables) { ($this.ExecuteWithResults($Query)).Tables }
        else { ($this.ExecuteWithResults($Query)).Tables[0] }
    } -ErrorAction Ignore

    Update-TypeData -TypeName Microsoft.SqlServer.Management.Smo.Database -MemberName Invoke -MemberType ScriptMethod -Value {
        param (
            $Command
        )

        $this.ExecuteNonQuery($Command)
    } -ErrorAction Ignore
}
tools\dbatools\bin\typealiases.ps1
# Obtain a reference to the TypeAccelerators type
$TAType = [psobject].Assembly.GetType("System.Management.Automation.TypeAccelerators")

# Define our type aliases
$TypeAliasTable = @{
    DbaInstance              = "Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter"
    DbaCmConnectionParameter = "Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter"
    DbaInstanceParameter     = "Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter"
    dbargx                   = "Sqlcollaborative.Dbatools.Utility.RegexHelper"
    dbatime                  = "Sqlcollaborative.Dbatools.Utility.DbaTime"
    dbadatetime              = "Sqlcollaborative.Dbatools.Utility.DbaDateTime"
    dbadate                  = "Sqlcollaborative.Dbatools.Utility.DbaDate"
    dbatimespan              = "Sqlcollaborative.Dbatools.Utility.DbaTimeSpan"
    prettytimespan           = "Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty"
    dbasize                  = "Sqlcollaborative.Dbatools.Utility.Size"
    dbavalidate              = "Sqlcollaborative.Dbatools.Utility.Validation"
    DbaMode                  = "Sqlcollaborative.Dbatools.General.ExecutionMode"
    DbaCredential            = "Sqlcollaborative.Dbatools.Parameter.DbaCredentialparameter"
    DbaCredentialParameter   = "Sqlcollaborative.Dbatools.Parameter.DbaCredentialparameter"
    DbaDatabaseSmo           = "SqlCollaborative.Dbatools.Parameter.DbaDatabaseSmoParameter"
    DbaDatabaseSmoParameter  = "SqlCollaborative.Dbatools.Parameter.DbaDatabaseSmoParameter"
    DbaDatabase              = "SqlCollaborative.Dbatools.Parameter.DbaDatabaseParameter"
    DbaDatabaseParameter     = "SqlCollaborative.Dbatools.Parameter.DbaDatabaseParameter"
    DbaValidatePattern       = "Sqlcollaborative.Dbatools.Utility.DbaValidatePatternAttribute"
    DbaValidateScript        = "Sqlcollaborative.Dbatools.Utility.DbaValidateScriptAttribute"
}

# Add all type aliases
foreach ($TypeAlias in $TypeAliasTable.Keys) {
    try {
        $TAType::Add($TypeAlias, $TypeAliasTable[$TypeAlias])
    } catch {
    }
}
tools\dbatools\bin\XESmartTarget\CommandLine.dll
md5: EC0E2DD54144D6F6A317B7DAA715D418 | sha1: 62C2E04BBA8436912D9BCEC1EC4D4C7AFC843A47 | sha256: 4923528D3D18689D58FA30B3D822AB72A13BE21A57F13E0BC59B55B864424F7A | sha512: CCAF01F89FAB001EF2DED15B352E1DD2AB3967584A8720ACB7C6B7203240F9C896F7D46600B12E0E86B25B30779B1E5ED59CE97FB3F295AFB11D6391670265EF
tools\dbatools\bin\XESmartTarget\CsvHelper.dll
md5: C899757ED1CF951D4529025FCE183EC4 | sha1: 5C677F74BC6C460B1AFFEADFBA7F3CC4C81ED438 | sha256: 3C4F05B0EC0D23AEF09D09CE4AF8EA2C198FED0A154B72DFE353F350C6358EFA | sha512: EE823343B1E0EDCFCD3FA11249C8078B925A44D7E3A37B061C9D5DE86F7129E1BCAD2A7E182C8DD9D21CFD86698A0F2AA8FD8753152BFC3BA595FCD70C60BE64
tools\dbatools\bin\XESmartTarget\DouglasCrockford.JsMin.dll
md5: F5676A290241101B94366C062D8455CC | sha1: 4AF1BECC059E3F6F73AE1A8B29DF5B798F3A3C6F | sha256: 065884D15E79EA73630B430A7848F7ED6136FCFFC0B9E6C8AE37564EFACF3AE9 | sha512: 35426B8E728B0E5900B0C2A001824F2EABED3B5363AFF868A237CF9A182D71C419E5564D4D7EE9A1423554D0F18ACFD0958E4EF18487DA52D66CB5BF0B3C1732
tools\dbatools\bin\XESmartTarget\NLog.dll
md5: 169A2802F25F1F083432FC099F4B5E6C | sha1: E9AD81EA61A436303978AADC2E96F7968BCD2C5D | sha256: 4B8399F36A0ABEBD8B2A0DC58AF5D83F3A6AE5F2228AC49E1FE9F70497975635 | sha512: D4F6170448183D5839E44C3F5C971327824CC8B9A760DBEF325F3F866D4CA76AAB58D56A3BCE0A802FFC80CD67F0CF4C7A7DD62C48A9B0033098E2811185351B
tools\dbatools\bin\XESmartTarget\NLog.dll.nlog
 
tools\dbatools\bin\XESmartTarget\SmartFormat.dll
md5: 0B49B13390BF422346590320BB4AC4EC | sha1: 6EB23F32517DC5E7E1466E84AE5E244AE109EFCE | sha256: 59C1973BCD707DBD46FC1367CFFAC884D9BB1B5963553E34CB5555A071F6F606 | sha512: 203947FC6D8B33FDCD3735BC85914A20081B8D8E014B04BFB004D900D6BF4C76153B4212C8D77A3DC25ACF037CAF6EA40EB9B7937CBCD75BC324DC22D7A10AB9
tools\dbatools\bin\XESmartTarget\XESmartTarget.Core.dll
md5: C46795EBDE8392054108D1B8A15F52BB | sha1: 0F135490A1067797684D176E05013FDF8F7DE1EA | sha256: 73330EF03E9C01D02005EEE4CE98DCE2B313311D99F814791D411853DE44AF5E | sha512: ABCF30F6D69258DB2406D1FCD53ACCF320A8168CAD9DB39FD658D6C7E79A9FCDB6F6D21307D5B4CB2D95649647D30D19D43E8741A53C18AE3DE89BB6CAE6D74E
tools\dbatools\bin\xetemplates-metadata.xml
tools\dbatools\bin\XEtemplates\15 Second IO Error.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
   <event_session name="15 Second IO Error" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="false" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Everyday Extended Events</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->15 Second IO Error</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Captures query for reads > 15 seconds and writes > 15 seconds.</templateDescription>
      <event package="sqlserver" name="file_read_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="is_system" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="sql_text" />
         <parameter name="collect_io_data" value="1" />
         <parameter name="collect_path" value="1" />
         <predicate>
            <leaf>
               <comparator name="greater_than_uint64" package="package0" />
               <event name="file_read_completed" package="sqlserver" field="duration" />
               <value>15000</value>
            </leaf>
         </predicate>
      </event>
      <event package="sqlserver" name="file_write_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="is_system" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="sql_text" />
         <parameter name="collect_path" value="1" />
         <predicate>
            <leaf>
               <comparator name="greater_than_uint64" package="package0" />
               <event name="file_write_completed" package="sqlserver" field="duration" />
               <value>15000</value>
            </leaf>
         </predicate>
      </event>
      <target package="package0" name="event_file">
         <parameter name="filename" value="15_second_io_error" />
      </target>
   </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Activity Detail Tracking.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
  <event_session name="Activity Detail Tracking" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->System Monitoring</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Activity Detail Tracking</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Similar to the 'Default Trace' that exists in the SQL Trace system. Use this template to track general activity on your system. The difference between this template and the 'Default Trace' is that this template does not include security audit events. If you would like to audit your system you should use the SQL Server Audit feature.</templateDescription>
    <event package="sqlserver" name="database_file_size_change">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_id" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_principal_sid" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="session_server_principal_name" />
      <parameter name="collect_database_name" value="1" />
    </event>
    <event package="sqlserver" name="database_mirroring_state_change">
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="server_principal_sid" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="session_server_principal_name" />
      <action package="sqlserver" name="transaction_id" />
    </event>
    <event package="sqlserver" name="error_reported">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_principal_sid" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="session_server_principal_name" />
      <action package="sqlserver" name="transaction_id" />
      <predicate>
        <or>
          <or>
            <or>
              <or>
                <leaf>
                  <comparator name="equal_int64" package="package0"></comparator>
                  <event name="error_reported" package="sqlserver" field="error_number"></event>
                  <value>8957</value>
                </leaf>
                <leaf>
                  <comparator name="equal_int64" package="package0"></comparator>
                  <event name="error_reported" package="sqlserver" field="error_number"></event>
                  <value>17550</value>
                </leaf>
              </or>
              <leaf>
                <comparator name="equal_int64" package="package0"></comparator>
                <event name="error_reported" package="sqlserver" field="error_number"></event>
                <value>17551</value>
              </leaf>
            </or>
            <leaf>
              <comparator name="equal_int64" package="package0"></comparator>
              <event name="error_reported" package="sqlserver" field="error_number"></event>
              <value>15457</value>
            </leaf>
          </or>
          <leaf>
            <comparator name="greater_than_int64" package="package0"></comparator>
            <event name="error_reported" package="sqlserver" field="severity"></event>
            <value>18</value>
          </leaf>
        </or>
      </predicate>
    </event>
    <event package="sqlserver" name="full_text_crawl_started">
      <action package="sqlserver" name="database_id" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="session_server_principal_name" />
      <action package="sqlserver" name="transaction_id" />
    </event>
    <event package="sqlserver" name="full_text_crawl_stopped">
      <action package="sqlserver" name="database_id" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="session_server_principal_name" />
      <action package="sqlserver" name="transaction_id" />
    </event>
    <event package="sqlserver" name="hash_warning">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_principal_sid" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="session_resource_group_id" />
      <action package="sqlserver" name="session_server_principal_name" />
      <action package="sqlserver" name="transaction_id" />
      <action package="sqlserver" name="transaction_sequence" />
    </event>
    <event package="sqlserver" name="missing_column_statistics">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_principal_sid" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="session_resource_group_id" />
      <action package="sqlserver" name="session_server_principal_name" />
      <action package="sqlserver" name="transaction_id" />
      <action package="sqlserver" name="transaction_sequence" />
    </event>
    <event package="sqlserver" name="missing_join_predicate">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_principal_sid" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="session_resource_group_id" />
      <action package="sqlserver" name="session_server_principal_name" />
      <action package="sqlserver" name="transaction_id" />
      <action package="sqlserver" name="transaction_sequence" />
    </event>
    <event package="sqlserver" name="object_altered">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="client_pid" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_principal_sid" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="session_resource_group_id" />
      <action package="sqlserver" name="session_server_principal_name" />
      <action package="sqlserver" name="transaction_sequence" />
      <parameter name="collect_database_name" value="1" />
      <predicate>
        <or>
          <leaf>
            <comparator name="not_equal_uint64" package="package0"></comparator>
            <event name="object_altered" package="sqlserver" field="database_id"></event>
            <value>2</value>
          </leaf>
          <and>
            <leaf>
              <comparator name="greater_than_int64" package="package0"></comparator>
              <event name="object_altered" package="sqlserver" field="object_id"></event>
              <value>0</value>
            </leaf>
            <not>
              <leaf>
                <comparator name="like_i_sql_unicode_string" package="sqlserver"></comparator>
                <event name="object_altered" package="sqlserver" field="object_name"></event>
                <value><![CDATA[#%]]></value>
              </leaf>
            </not>
          </and>
        </or>
      </predicate>
    </event>
    <event package="sqlserver" name="object_created">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="client_pid" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_principal_sid" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="session_resource_group_id" />
      <action package="sqlserver" name="session_server_principal_name" />
      <action package="sqlserver" name="transaction_sequence" />
      <parameter name="collect_database_name" value="1" />
      <predicate>
        <or>
          <leaf>
            <comparator name="not_equal_uint64" package="package0"></comparator>
            <event name="object_created" package="sqlserver" field="database_id"></event>
            <value>2</value>
          </leaf>
          <and>
            <leaf>
              <comparator name="greater_than_int64" package="package0"></comparator>
              <event name="object_created" package="sqlserver" field="object_id"></event>
              <value>0</value>
            </leaf>
            <not>
              <leaf>
                <comparator name="like_i_sql_unicode_string" package="sqlserver"></comparator>
                <event name="object_created" package="sqlserver" field="object_name"></event>
                <value><![CDATA[#%]]></value>
              </leaf>
            </not>
          </and>
        </or>
      </predicate>
    </event>
    <event package="sqlserver" name="object_deleted">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="client_pid" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_principal_sid" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="session_resource_group_id" />
      <action package="sqlserver" name="session_server_principal_name" />
      <action package="sqlserver" name="transaction_sequence" />
      <parameter name="collect_database_name" value="1" />
      <predicate>
        <or>
          <leaf>
            <comparator name="not_equal_uint64" package="package0"></comparator>
            <event name="object_deleted" package="sqlserver" field="database_id"></event>
            <value>2</value>
          </leaf>
          <and>
            <leaf>
              <comparator name="greater_than_int64" package="package0"></comparator>
              <event name="object_deleted" package="sqlserver" field="object_id"></event>
              <value>0</value>
            </leaf>
            <not>
              <leaf>
                <comparator name="like_i_sql_unicode_string" package="sqlserver"></comparator>
                <event name="object_deleted" package="sqlserver" field="object_name"></event>
                <value><![CDATA[#%]]></value>
              </leaf>
            </not>
          </and>
        </or>
      </predicate>
    </event>
    <event package="sqlserver" name="plan_guide_unsuccessful">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_principal_sid" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="session_server_principal_name" />
      <action package="sqlserver" name="transaction_id" />
      <action package="sqlserver" name="transaction_sequence" />
    </event>
    <event package="sqlserver" name="server_memory_change">
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="session_server_principal_name" />
      <action package="sqlserver" name="transaction_id" />
      <action package="sqlserver" name="transaction_sequence" />
    </event>
    <event package="sqlserver" name="server_start_stop">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="client_pid" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_principal_sid" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="session_server_principal_name" />
    </event>
    <event package="sqlserver" name="sort_warning">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_principal_sid" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="session_resource_group_id" />
      <action package="sqlserver" name="session_server_principal_name" />
      <action package="sqlserver" name="transaction_id" />
      <action package="sqlserver" name="transaction_sequence" />
    </event>
  </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Activity Tracking.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
  <event_session name="Activity Tracking" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->System Monitoring</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Activity Tracking</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Similar to the 'Default Trace' that exists in the SQL Trace system. Use this template to track general activity on your system. The difference between this template and the 'Default Trace' is that this template does not include security audit events. If you would like to audit your system you should use the SQL Server Audit feature.</templateDescription>
    <event package="sqlserver" name="error_reported">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="transaction_id" />
      <predicate>
        <or>
          <or>
            <or>
              <or>
                <leaf>
                  <comparator name="equal_int64" package="package0"></comparator>
                  <event name="error_reported" package="sqlserver" field="error_number"></event>
                  <value>8957</value>
                </leaf>
                <leaf>
                  <comparator name="equal_int64" package="package0"></comparator>
                  <event name="error_reported" package="sqlserver" field="error_number"></event>
                  <value>17550</value>
                </leaf>
              </or>
              <leaf>
                <comparator name="equal_int64" package="package0"></comparator>
                <event name="error_reported" package="sqlserver" field="error_number"></event>
                <value>17551</value>
              </leaf>
            </or>
            <leaf>
              <comparator name="equal_int64" package="package0"></comparator>
              <event name="error_reported" package="sqlserver" field="error_number"></event>
              <value>15457</value>
            </leaf>
          </or>
          <leaf>
            <comparator name="greater_than_int64" package="package0"></comparator>
            <event name="error_reported" package="sqlserver" field="severity"></event>
            <value>18</value>
          </leaf>
        </or>
      </predicate>
    </event>
    <event package="sqlserver" name="full_text_crawl_started">
      <action package="sqlserver" name="database_id" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="transaction_id" />
    </event>
    <event package="sqlserver" name="fulltextlog_written">
      <action package="sqlserver" name="database_id" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="transaction_id" />
    </event>
    <event package="sqlserver" name="hash_warning">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="transaction_id" />

    </event>
    <event package="sqlserver" name="missing_column_statistics">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="transaction_id" />

    </event>
    <event package="sqlserver" name="missing_join_predicate">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="transaction_id" />
    </event>
    <event package="sqlserver" name="object_altered">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="client_pid" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="session_id" />
      <parameter name="collect_database_name" value="1" />
      <predicate>
        <or>
          <leaf>
            <comparator name="not_equal_uint64" package="package0"></comparator>
            <event name="object_altered" package="sqlserver" field="database_id"></event>
            <value>2</value>
          </leaf>
          <and>
            <leaf>
              <comparator name="greater_than_int64" package="package0"></comparator>
              <event name="object_altered" package="sqlserver" field="object_id"></event>
              <value>0</value>
            </leaf>
            <not>
              <leaf>
                <comparator name="like_i_sql_unicode_string" package="sqlserver"></comparator>
                <event name="object_altered" package="sqlserver" field="object_name"></event>
                <value><![CDATA[#%]]></value>
              </leaf>
            </not>
          </and>
        </or>
      </predicate>
    </event>
    <event package="sqlserver" name="object_created">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="client_pid" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="session_id" />

      <parameter name="collect_database_name" value="1" />
      <predicate>
        <or>
          <leaf>
            <comparator name="not_equal_uint64" package="package0"></comparator>
            <event name="object_created" package="sqlserver" field="database_id"></event>
            <value>2</value>
          </leaf>
          <and>
            <leaf>
              <comparator name="greater_than_int64" package="package0"></comparator>
              <event name="object_created" package="sqlserver" field="object_id"></event>
              <value>0</value>
            </leaf>
            <not>
              <leaf>
                <comparator name="like_i_sql_unicode_string" package="sqlserver"></comparator>
                <event name="object_created" package="sqlserver" field="object_name"></event>
                <value><![CDATA[#%]]></value>
              </leaf>
            </not>
          </and>
        </or>
      </predicate>
    </event>
    <event package="sqlserver" name="object_deleted">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="client_pid" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="session_id" />
      <parameter name="collect_database_name" value="1" />
      <predicate>
        <or>
          <leaf>
            <comparator name="not_equal_uint64" package="package0"></comparator>
            <event name="object_deleted" package="sqlserver" field="database_id"></event>
            <value>2</value>
          </leaf>
          <and>
            <leaf>
              <comparator name="greater_than_int64" package="package0"></comparator>
              <event name="object_deleted" package="sqlserver" field="object_id"></event>
              <value>0</value>
            </leaf>
            <not>
              <leaf>
                <comparator name="like_i_sql_unicode_string" package="sqlserver"></comparator>
                <event name="object_deleted" package="sqlserver" field="object_name"></event>
                <value><![CDATA[#%]]></value>
              </leaf>
            </not>
          </and>
        </or>
      </predicate>
    </event>
    <event package="sqlserver" name="sort_warning">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="session_id" />
      <action package="sqlserver" name="transaction_id" />
    </event>
  </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\AlwaysOn Health Enhanced.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventsconfig">
   <event_session name="AlwaysOn Health Enhanced" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="false" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
      <templateCategory><!-- _locID_text="templateCategory" _locComment = "" -->System Monitoring</templateCategory>
      <templateName><!-- _locID_text = "templateName" _locComment = "" -->AlwaysOn Health Enhanced</templateName>
      <templateDescription><!-- _locID_text = "templateDescription" _locComment = "" -->Enhanced version of AlwaysOn_health</templateDescription>
      <event package="sqlserver" name="alwayson_ddl_executed">
         <action package="sqlserver" name="server_instance_name" />
      </event>
      <event package="sqlserver" name="availability_group_lease_expired">
         <action package="sqlserver" name="server_instance_name" />
      </event>
      <event package="sqlserver" name="availability_replica_automatic_failover_validation">
         <action package="sqlserver" name="server_instance_name" />
      </event>
      <event package="sqlserver" name="availability_replica_manager_state_change">
         <action package="sqlserver" name="server_instance_name" />
      </event>
      <event package="sqlserver" name="availability_replica_state">
         <action package="sqlserver" name="server_instance_name" />
      </event>
      <event package="sqlserver" name="availability_replica_state_change">
         <action package="sqlserver" name="server_instance_name" />
      </event>
      <event package="sqlserver" name="error_reported">
         <action package="sqlserver" name="server_instance_name" />
         <predicate>
            <or>
               <or>
                  <or>
                     <or>
                        <or>
                           <or>
                              <or>
                                 <or>
                                    <or>
                                       <or>
                                          <or>
                                             <or>
                                                <or>
                                                   <or>
                                                      <or>
                                                         <or>
                                                            <or>
                                                               <or>
                                                                  <or>
                                                                     <or>
                                                                        <or>
                                                                           <or>
                                                                              <or>
                                                                                 <or>
                                                                                    <or>
                                                                                       <or>
                                                                                          <or>
                                                                                             <or>
                                                                                                <or>
                                                                                                   <or>
                                                                                                      <leaf>
                                                                                                         <comparator name="equal_int64" package="package0" />
                                                                                                         <event name="error_reported" package="sqlserver" field="error_number" />
                                                                                                         <value>9691</value>
                                                                                                      </leaf>
                                                                                                      <leaf>
                                                                                                         <comparator name="equal_int64" package="package0" />
                                                                                                         <event name="error_reported" package="sqlserver" field="error_number" />
                                                                                                         <value>35204</value>
                                                                                                      </leaf>
                                                                                                   </or>
                                                                                                   <leaf>
                                                                                                      <comparator name="equal_int64" package="package0" />
                                                                                                      <event name="error_reported" package="sqlserver" field="error_number" />
                                                                                                      <value>9693</value>
                                                                                                   </leaf>
                                                                                                </or>
                                                                                                <leaf>
                                                                                                   <comparator name="equal_int64" package="package0" />
                                                                                                   <event name="error_reported" package="sqlserver" field="error_number" />
                                                                                                   <value>26024</value>
                                                                                                </leaf>
                                                                                             </or>
                                                                                             <leaf>
                                                                                                <comparator name="equal_int64" package="package0" />
                                                                                                <event name="error_reported" package="sqlserver" field="error_number" />
                                                                                                <value>28047</value>
                                                                                             </leaf>
                                                                                          </or>
                                                                                          <leaf>
                                                                                             <comparator name="equal_int64" package="package0" />
                                                                                             <event name="error_reported" package="sqlserver" field="error_number" />
                                                                                             <value>26023</value>
                                                                                          </leaf>
                                                                                       </or>
                                                                                       <leaf>
                                                                                          <comparator name="equal_int64" package="package0" />
                                                                                          <event name="error_reported" package="sqlserver" field="error_number" />
                                                                                          <value>9692</value>
                                                                                       </leaf>
                                                                                    </or>
                                                                                    <leaf>
                                                                                       <comparator name="equal_int64" package="package0" />
                                                                                       <event name="error_reported" package="sqlserver" field="error_number" />
                                                                                       <value>28034</value>
                                                                                    </leaf>
                                                                                 </or>
                                                                                 <leaf>
                                                                                    <comparator name="equal_int64" package="package0" />
                                                                                    <event name="error_reported" package="sqlserver" field="error_number" />
                                                                                    <value>28036</value>
                                                                                 </leaf>
                                                                              </or>
                                                                              <leaf>
                                                                                 <comparator name="equal_int64" package="package0" />
                                                                                 <event name="error_reported" package="sqlserver" field="error_number" />
                                                                                 <value>28048</value>
                                                                              </leaf>
                                                                           </or>
                                                                           <leaf>
                                                                              <comparator name="equal_int64" package="package0" />
                                                                              <event name="error_reported" package="sqlserver" field="error_number" />
                                                                              <value>28080</value>
                                                                           </leaf>
                                                                        </or>
                                                                        <leaf>
                                                                           <comparator name="equal_int64" package="package0" />
                                                                           <event name="error_reported" package="sqlserver" field="error_number" />
                                                                           <value>28091</value>
                                                                        </leaf>
                                                                     </or>
                                                                     <leaf>
                                                                        <comparator name="equal_int64" package="package0" />
                                                                        <event name="error_reported" package="sqlserver" field="error_number" />
                                                                        <value>26022</value>
                                                                     </leaf>
                                                                  </or>
                                                                  <leaf>
                                                                     <comparator name="equal_int64" package="package0" />
                                                                     <event name="error_reported" package="sqlserver" field="error_number" />
                                                                     <value>9642</value>
                                                                  </leaf>
                                                               </or>
                                                               <leaf>
                                                                  <comparator name="equal_int64" package="package0" />
                                                                  <event name="error_reported" package="sqlserver" field="error_number" />
                                                                  <value>35201</value>
                                                               </leaf>
                                                            </or>
                                                            <leaf>
                                                               <comparator name="equal_int64" package="package0" />
                                                               <event name="error_reported" package="sqlserver" field="error_number" />
                                                               <value>35202</value>
                                                            </leaf>
                                                         </or>
                                                         <leaf>
                                                            <comparator name="equal_int64" package="package0" />
                                                            <event name="error_reported" package="sqlserver" field="error_number" />
                                                            <value>35206</value>
                                                         </leaf>
                                                      </or>
                                                      <leaf>
                                                         <comparator name="equal_int64" package="package0" />
                                                         <event name="error_reported" package="sqlserver" field="error_number" />
                                                         <value>35207</value>
                                                      </leaf>
                                                   </or>
                                                   <leaf>
                                                      <comparator name="equal_int64" package="package0" />
                                                      <event name="error_reported" package="sqlserver" field="error_number" />
                                                      <value>26069</value>
                                                   </leaf>
                                                </or>
                                                <leaf>
                                                   <comparator name="equal_int64" package="package0" />
                                                   <event name="error_reported" package="sqlserver" field="error_number" />
                                                   <value>26070</value>
                                                </leaf>
                                             </or>
                                             <and>
                                                <leaf>
                                                   <comparator name="greater_than_int64" package="package0" />
                                                   <event name="error_reported" package="sqlserver" field="error_number" />
                                                   <value>41047</value>
                                                </leaf>
                                                <leaf>
                                                   <comparator name="less_than_int64" package="package0" />
                                                   <event name="error_reported" package="sqlserver" field="error_number" />
                                                   <value>41056</value>
                                                </leaf>
                                             </and>
                                          </or>
                                          <leaf>
                                             <comparator name="equal_int64" package="package0" />
                                             <event name="error_reported" package="sqlserver" field="error_number" />
                                             <value>41142</value>
                                          </leaf>
                                       </or>
                                       <leaf>
                                          <comparator name="equal_int64" package="package0" />
                                          <event name="error_reported" package="sqlserver" field="error_number" />
                                          <value>41144</value>
                                       </leaf>
                                    </or>
                                    <leaf>
                                       <comparator name="equal_int64" package="package0" />
                                       <event name="error_reported" package="sqlserver" field="error_number" />
                                       <value>1480</value>
                                    </leaf>
                                 </or>
                                 <leaf>
                                    <comparator name="equal_int64" package="package0" />
                                    <event name="error_reported" package="sqlserver" field="error_number" />
                                    <value>823</value>
                                 </leaf>
                              </or>
                              <leaf>
                                 <comparator name="equal_int64" package="package0" />
                                 <event name="error_reported" package="sqlserver" field="error_number" />
                                 <value>824</value>
                              </leaf>
                           </or>
                           <leaf>
                              <comparator name="equal_int64" package="package0" />
                              <event name="error_reported" package="sqlserver" field="error_number" />
                              <value>829</value>
                           </leaf>
                        </or>
                        <leaf>
                           <comparator name="equal_int64" package="package0" />
                           <event name="error_reported" package="sqlserver" field="error_number" />
                           <value>35264</value>
                        </leaf>
                     </or>
                     <leaf>
                        <comparator name="equal_int64" package="package0" />
                        <event name="error_reported" package="sqlserver" field="error_number" />
                        <value>35265</value>
                     </leaf>
                  </or>
                  <leaf>
                     <comparator name="equal_int64" package="package0" />
                     <event name="error_reported" package="sqlserver" field="error_number" />
                     <value>41188</value>
                  </leaf>
               </or>
               <leaf>
                  <comparator name="equal_int64" package="package0" />
                  <event name="error_reported" package="sqlserver" field="error_number" />
                  <value>41189</value>
               </leaf>
            </or>
         </predicate>
      </event>
      <event package="sqlserver" name="hadr_db_partner_set_sync_state">
         <action package="sqlserver" name="server_instance_name" />
      </event>
      <event package="sqlserver" name="lock_redo_blocked">
         <action package="sqlserver" name="server_instance_name" />
      </event>
      <target package="package0" name="event_file">
         <parameter name="filename" value="AlwaysOn Health Enhanced" />
         <parameter name="max_file_size" value="5" />
         <parameter name="max_rollover_files" value="4" />
      </target>
   </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Blocked Process Report.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventsconfig">
   <event_session name="Blocked Process Report" maxMemory="8" eventRetentionMode="allowSingleEventLoss" trackCausality="false" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->System Monitoring</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Blocked Process Report</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Captures the blocked process report. In order to capture a blocked process report, you must have the blocked process threshold system configuration option enabled (To capture blocking processes, configure blocked threshold (Set-DbaSpConfigure -SqlInstance sql2017 -ConfigName BlockedProcessThreshold -Value 5). </templateDescription>
      <event package="sqlserver" name="blocked_process_report" />
      <target package="package0" name="event_file">
         <parameter name="filename" value="Blocked Process Report" />
      </target>
   </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Connection Detail Tracking.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
  <event_session name="Connection Detail Tracking" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->System Monitoring</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Connection Detail Tracking</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Tracks connection activity for a server. Normal connection activity is tracked using the login and logout events, and problems are recorded using the connectivity_ring_buffer_recorded event.</templateDescription>
    <event package="sqlserver" name="connectivity_ring_buffer_recorded">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_connection_id" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="context_info" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="session_id" />
    </event>
    <event package="sqlserver" name="login">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_connection_id" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="context_info" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="server_principal_name" />
      <parameter name="collect_options_text" value="1" />
    </event>
    <event package="sqlserver" name="logout">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_connection_id" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="context_info" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="session_id" />
    </event>
    <target package="package0" name="ring_buffer" />
  </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Connection Tracking.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
  <event_session name="Connection Tracking" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->System Monitoring</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Connection Tracking</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Tracks connection activity for a server. Normal connection activity is tracked using the login and logout events</templateDescription>
    <event package="sqlserver" name="login">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_connection_id" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="context_info" />
      <parameter name="collect_options_text" value="1" />
    </event>
    <event package="sqlserver" name="logout">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_connection_id" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="context_info" />
      <action package="sqlserver" name="session_id" />
    </event>
    <target package="package0" name="ring_buffer" />
  </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Count Query Locks.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
  <event_session name="Count Query Locks" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Locks and Blocks</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Count Query Locks</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Counts the number of locks acquired by each query based on the query_hash value. You can use this template to identify the most lock intensive queries for investigation and tuning.</templateDescription>
    <event package="sqlserver" name="lock_acquired">
      <action package="sqlserver" name="query_hash" />
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <event name="lock_acquired" package="sqlserver" field="database_id"></event>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <target package="package0" name="histogram">
      <parameter name="filtering_event_name" value="sqlserver.lock_acquired" />
      <parameter name="source" value="sqlserver.query_hash" />
    </target>
  </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Database File IO.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
   <event_session name="Database File I/O" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="false" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Everyday Extended Events</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Database File IO</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Use event counter and histogram to see which database file(s) have the most reads and writes.</templateDescription>
      <event package="sqlserver" name="file_read_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="plan_handle" />
         <action package="sqlserver" name="sql_text" />
         <parameter name="collect_io_data" value="1" />
         <parameter name="collect_path" value="1" />
         <predicate>
            <leaf>
               <comparator name="greater_than_uint64" package="package0" />
               <global name="database_id" package="sqlserver" />
               <value>4</value>
            </leaf>
         </predicate>
      </event>
      <event package="sqlserver" name="file_write_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="plan_handle" />
         <action package="sqlserver" name="sql_text" />
         <parameter name="collect_path" value="1" />
         <predicate>
            <leaf>
               <comparator name="greater_than_uint64" package="package0" />
               <global name="database_id" package="sqlserver" />
               <value>4</value>
            </leaf>
         </predicate>
      </event>
      <target package="package0" name="event_counter" />
      <target package="package0" name="histogram">
         <parameter name="filtering_event_name" value="sqlserver.file_read_completed" />
         <parameter name="source" value="file_id" />
         <parameter name="source_type" value="0" />
      </target>
   </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Database Health 2012.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventsconfig">
   <event_session name="Database Health 2012" maxMemory="4" eventRetentionMode="allowMultipleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="perNode">
   <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Performance Store</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Database Health 2012</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Similar to system_health but for SQL Server 2012 databases by Ola Hallengren. This Extended Event captures most of the valuable data for troubleshooting such as deadlocks, blocking processes, slow statements, errors, file size changes, info for tempdb troubleshooting etc. To capture blocking processes, configure blocked threshold (Set-DbaSpConfigure -SqlInstance sql2017 -ConfigName BlockedProcessThreshold -Value 5)</templateDescription>
      <event package="sqlos" name="wait_info">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="plan_handle" />
         <action package="sqlserver" name="query_hash_signed" />
         <action package="sqlserver" name="query_plan_hash_signed" />
         <action package="sqlserver" name="request_id" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_resource_group_id" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="tsql_frame" />
         <action package="sqlserver" name="username" />
         <predicate>
            <and>
               <and>
                  <and>
                     <and>
                        <and>
                           <and>
                              <and>
                                 <leaf>
                                    <comparator name="equal_uint64" package="package0" />
                                    <event name="wait_info" package="sqlos" field="opcode" />
                                    <value>1</value>
                                 </leaf>
                                 <leaf>
                                    <comparator name="equal_boolean" package="package0" />
                                    <global name="is_system" package="sqlserver" />
                                    <value>false</value>
                                 </leaf>
                              </and>
                              <leaf>
                                 <comparator name="greater_than_equal_uint64" package="package0" />
                                 <event name="wait_info" package="sqlos" field="duration" />
                                 <value>5000</value>
                              </leaf>
                           </and>
                           <leaf>
                              <comparator name="not_equal_uint64" package="package0" />
                              <event name="wait_info" package="sqlos" field="wait_type" />
                              <value>225</value>
                           </leaf>
                        </and>
                        <leaf>
                           <comparator name="not_equal_uint64" package="package0" />
                           <event name="wait_info" package="sqlos" field="wait_type" />
                           <value>223</value>
                        </leaf>
                     </and>
                     <leaf>
                        <comparator name="not_equal_uint64" package="package0" />
                        <event name="wait_info" package="sqlos" field="wait_type" />
                        <value>377</value>
                     </leaf>
                  </and>
                  <leaf>
                     <comparator name="not_equal_uint64" package="package0" />
                     <event name="wait_info" package="sqlos" field="wait_type" />
                     <value>645</value>
                  </leaf>
               </and>
               <leaf>
                  <comparator name="not_equal_uint64" package="package0" />
                  <event name="wait_info" package="sqlos" field="wait_type" />
                  <value>738</value>
               </leaf>
            </and>
         </predicate>
      </event>
      <event package="sqlos" name="wait_info_external">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="plan_handle" />
         <action package="sqlserver" name="query_hash_signed" />
         <action package="sqlserver" name="query_plan_hash_signed" />
         <action package="sqlserver" name="request_id" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_resource_group_id" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="tsql_frame" />
         <action package="sqlserver" name="username" />
         <predicate>
            <and>
               <and>
                  <leaf>
                     <comparator name="equal_uint64" package="package0" />
                     <event name="wait_info_external" package="sqlos" field="opcode" />
                     <value>1</value>
                  </leaf>
                  <leaf>
                     <comparator name="equal_boolean" package="package0" />
                     <global name="is_system" package="sqlserver" />
                     <value>false</value>
                  </leaf>
               </and>
               <leaf>
                  <comparator name="greater_than_equal_uint64" package="package0" />
                  <event name="wait_info_external" package="sqlos" field="duration" />
                  <value>5000</value>
               </leaf>
            </and>
         </predicate>
      </event>
      <event package="sqlserver" name="blocked_process_report" />
      <event package="sqlserver" name="database_file_size_change">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="plan_handle" />
         <action package="sqlserver" name="request_id" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_resource_group_id" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="username" />
         <parameter name="collect_database_name" value="1" />
      </event>
      <event package="sqlserver" name="error_reported">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="plan_handle" />
         <action package="sqlserver" name="request_id" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_resource_group_id" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="tsql_frame" />
         <action package="sqlserver" name="username" />
         <predicate>
            <leaf>
               <comparator name="greater_than_int64" package="package0" />
               <event name="error_reported" package="sqlserver" field="severity" />
               <value>10</value>
            </leaf>
         </predicate>
      </event>
      <event package="sqlserver" name="module_end">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="plan_handle" />
         <action package="sqlserver" name="request_id" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_resource_group_id" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="tsql_frame" />
         <action package="sqlserver" name="username" />
         <predicate>
            <and>
               <leaf>
                  <comparator name="equal_boolean" package="package0" />
                  <global name="is_system" package="sqlserver" />
                  <value>false</value>
               </leaf>
               <leaf>
                  <comparator name="greater_than_equal_uint64" package="package0" />
                  <event name="module_end" package="sqlserver" field="duration" />
                  <value>5000000</value>
               </leaf>
            </and>
         </predicate>
      </event>
      <event package="sqlserver" name="rpc_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="request_id" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_resource_group_id" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="username" />
         <predicate>
            <and>
               <leaf>
                  <comparator name="equal_boolean" package="package0" />
                  <global name="is_system" package="sqlserver" />
                  <value>false</value>
               </leaf>
               <or>
                  <leaf>
                     <comparator name="greater_than_equal_uint64" package="package0" />
                     <event name="rpc_completed" package="sqlserver" field="duration" />
                     <value>5000000</value>
                  </leaf>
                  <leaf>
                     <comparator name="not_equal_uint64" package="package0" />
                     <event name="rpc_completed" package="sqlserver" field="result" />
                     <value>0</value>
                  </leaf>
               </or>
            </and>
         </predicate>
      </event>
      <event package="sqlserver" name="sql_batch_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="request_id" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_resource_group_id" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="username" />
         <parameter name="collect_batch_text" value="1" />
         <predicate>
            <and>
               <leaf>
                  <comparator name="equal_boolean" package="package0" />
                  <global name="is_system" package="sqlserver" />
                  <value>false</value>
               </leaf>
               <or>
                  <leaf>
                     <comparator name="greater_than_equal_uint64" package="package0" />
                     <event name="sql_batch_completed" package="sqlserver" field="duration" />
                     <value>5000000</value>
                  </leaf>
                  <leaf>
                     <comparator name="not_equal_uint64" package="package0" />
                     <event name="sql_batch_completed" package="sqlserver" field="result" />
                     <value>0</value>
                  </leaf>
               </or>
            </and>
         </predicate>
      </event>
      <event package="sqlserver" name="xml_deadlock_report" />
      <target package="package0" name="event_file">
         <parameter name="filename" value="Database Health 2012" />
         <parameter name="max_file_size" value="5" />
         <parameter name="max_rollover_files" value="100" />
      </target>
   </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Database Health 2014.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventsconfig">
   <event_session name="Database Health 2014" maxMemory="4" eventRetentionMode="allowMultipleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="perNode">
	<templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Performance Store</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Database Health 2014</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Similar to system_health but for SQL Server 2014 databases by Ola Hallengren. This Extended Event captures most of the valuable data for troubleshooting such as deadlocks, blocking processes, slow statements, errors, file size changes, info for tempdb troubleshooting etc. To capture blocking processes, configure blocked threshold (Set-DbaSpConfigure -SqlInstance sql2017 -ConfigName BlockedProcessThreshold -Value 5)</templateDescription>
            <event package="sqlos" name="wait_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="plan_handle" />
         <action package="sqlserver" name="query_hash_signed" />
         <action package="sqlserver" name="query_plan_hash_signed" />
         <action package="sqlserver" name="request_id" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_resource_group_id" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="tsql_frame" />
         <action package="sqlserver" name="username" />
         <predicate>
            <and>
               <and>
                  <and>
                     <and>
                        <and>
                           <and>
                              <leaf>
                                 <comparator name="equal_boolean" package="package0" />
                                 <global name="is_system" package="sqlserver" />
                                 <value>false</value>
                              </leaf>
                              <leaf>
                                 <comparator name="greater_than_equal_uint64" package="package0" />
                                 <event name="wait_completed" package="sqlos" field="duration" />
                                 <value>5000</value>
                              </leaf>
                           </and>
                           <leaf>
                              <comparator name="not_equal_uint64" package="package0" />
                              <event name="wait_completed" package="sqlos" field="wait_type" />
                              <value>233</value>
                           </leaf>
                        </and>
                        <leaf>
                           <comparator name="not_equal_uint64" package="package0" />
                           <event name="wait_completed" package="sqlos" field="wait_type" />
                           <value>231</value>
                        </leaf>
                     </and>
                     <leaf>
                        <comparator name="not_equal_uint64" package="package0" />
                        <event name="wait_completed" package="sqlos" field="wait_type" />
                        <value>395</value>
                     </leaf>
                  </and>
                  <leaf>
                     <comparator name="not_equal_uint64" package="package0" />
                     <event name="wait_completed" package="sqlos" field="wait_type" />
                     <value>666</value>
                  </leaf>
               </and>
               <leaf>
                  <comparator name="not_equal_uint64" package="package0" />
                  <event name="wait_completed" package="sqlos" field="wait_type" />
                  <value>766</value>
               </leaf>
            </and>
         </predicate>
      </event>
      <event package="sqlos" name="wait_info_external">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="plan_handle" />
         <action package="sqlserver" name="query_hash_signed" />
         <action package="sqlserver" name="query_plan_hash_signed" />
         <action package="sqlserver" name="request_id" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_resource_group_id" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="tsql_frame" />
         <action package="sqlserver" name="username" />
         <predicate>
            <and>
               <and>
                  <leaf>
                     <comparator name="equal_uint64" package="package0" />
                     <event name="wait_info_external" package="sqlos" field="opcode" />
                     <value>1</value>
                  </leaf>
                  <leaf>
                     <comparator name="equal_boolean" package="package0" />
                     <global name="is_system" package="sqlserver" />
                     <value>false</value>
                  </leaf>
               </and>
               <leaf>
                  <comparator name="greater_than_equal_uint64" package="package0" />
                  <event name="wait_info_external" package="sqlos" field="duration" />
                  <value>5000</value>
               </leaf>
            </and>
         </predicate>
      </event>
      <event package="sqlserver" name="blocked_process_report" />
      <event package="sqlserver" name="database_file_size_change">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="plan_handle" />
         <action package="sqlserver" name="request_id" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_resource_group_id" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="username" />
         <parameter name="collect_database_name" value="1" />
      </event>
      <event package="sqlserver" name="error_reported">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="plan_handle" />
         <action package="sqlserver" name="request_id" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_resource_group_id" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="tsql_frame" />
         <action package="sqlserver" name="username" />
         <predicate>
            <leaf>
               <comparator name="greater_than_int64" package="package0" />
               <event name="error_reported" package="sqlserver" field="severity" />
               <value>10</value>
            </leaf>
         </predicate>
      </event>
      <event package="sqlserver" name="module_end">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="plan_handle" />
         <action package="sqlserver" name="request_id" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_resource_group_id" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="tsql_frame" />
         <action package="sqlserver" name="username" />
         <predicate>
            <and>
               <leaf>
                  <comparator name="equal_boolean" package="package0" />
                  <global name="is_system" package="sqlserver" />
                  <value>false</value>
               </leaf>
               <leaf>
                  <comparator name="greater_than_equal_uint64" package="package0" />
                  <event name="module_end" package="sqlserver" field="duration" />
                  <value>5000000</value>
               </leaf>
            </and>
         </predicate>
      </event>
      <event package="sqlserver" name="rpc_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="request_id" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_resource_group_id" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="username" />
         <predicate>
            <and>
               <leaf>
                  <comparator name="equal_boolean" package="package0" />
                  <global name="is_system" package="sqlserver" />
                  <value>false</value>
               </leaf>
               <or>
                  <leaf>
                     <comparator name="greater_than_equal_uint64" package="package0" />
                     <event name="rpc_completed" package="sqlserver" field="duration" />
                     <value>5000000</value>
                  </leaf>
                  <leaf>
                     <comparator name="not_equal_uint64" package="package0" />
                     <event name="rpc_completed" package="sqlserver" field="result" />
                     <value>0</value>
                  </leaf>
               </or>
            </and>
         </predicate>
      </event>
      <event package="sqlserver" name="sql_batch_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="request_id" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_resource_group_id" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="username" />
         <parameter name="collect_batch_text" value="1" />
         <predicate>
            <and>
               <leaf>
                  <comparator name="equal_boolean" package="package0" />
                  <global name="is_system" package="sqlserver" />
                  <value>false</value>
               </leaf>
               <or>
                  <leaf>
                     <comparator name="greater_than_equal_uint64" package="package0" />
                     <event name="sql_batch_completed" package="sqlserver" field="duration" />
                     <value>5000000</value>
                  </leaf>
                  <leaf>
                     <comparator name="not_equal_uint64" package="package0" />
                     <event name="sql_batch_completed" package="sqlserver" field="result" />
                     <value>0</value>
                  </leaf>
               </or>
            </and>
         </predicate>
      </event>
      <event package="sqlserver" name="xml_deadlock_report">
         <action package="sqlserver" name="database_name" />
      </event>
      <target package="package0" name="event_file">
         <parameter name="filename" value="Database Health 2014" />
         <parameter name="max_file_size" value="5" />
         <parameter name="max_rollover_files" value="100" />
      </target>
   </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Database Health 2016 and Above.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventsconfig">
   <event_session name="Database Health 2016 and Above" maxMemory="4" eventRetentionMode="allowMultipleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="perNode">
      <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Performance Store</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Database Health 2016 and Above</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Similar to system_health but for SQL Server 2016+ databases by Ola Hallengren. This Extended Event captures most of the valuable data for troubleshooting such as deadlocks, blocking processes, slow statements, errors, file size changes, info for tempdb troubleshooting etc. To capture blocking processes, configure blocked threshold (Set-DbaSpConfigure -SqlInstance sql2017 -ConfigName BlockedProcessThreshold -Value 5)</templateDescription>
    <event package="sqlos" name="wait_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="plan_handle" />
         <action package="sqlserver" name="query_hash_signed" />
         <action package="sqlserver" name="query_plan_hash_signed" />
         <action package="sqlserver" name="request_id" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_resource_group_id" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="tsql_frame" />
         <action package="sqlserver" name="username" />
         <predicate>
            <and>
               <and>
                  <and>
                     <and>
                        <and>
                           <and>
                              <and>
                                 <and>
                                    <leaf>
                                       <comparator name="equal_boolean" package="package0" />
                                       <global name="is_system" package="sqlserver" />
                                       <value>false</value>
                                    </leaf>
                                    <leaf>
                                       <comparator name="greater_than_equal_uint64" package="package0" />
                                       <event name="wait_completed" package="sqlos" field="duration" />
                                       <value>5000</value>
                                    </leaf>
                                 </and>
                                 <leaf>
                                    <comparator name="not_equal_uint64" package="package0" />
                                    <event name="wait_completed" package="sqlos" field="wait_type" />
                                    <value>233</value>
                                 </leaf>
                              </and>
                              <leaf>
                                 <comparator name="not_equal_uint64" package="package0" />
                                 <event name="wait_completed" package="sqlos" field="wait_type" />
                                 <value>231</value>
                              </leaf>
                           </and>
                           <leaf>
                              <comparator name="not_equal_uint64" package="package0" />
                              <event name="wait_completed" package="sqlos" field="wait_type" />
                              <value>395</value>
                           </leaf>
                        </and>
                        <leaf>
                           <comparator name="not_equal_uint64" package="package0" />
                           <event name="wait_completed" package="sqlos" field="wait_type" />
                           <value>666</value>
                        </leaf>
                     </and>
                     <leaf>
                        <comparator name="not_equal_uint64" package="package0" />
                        <event name="wait_completed" package="sqlos" field="wait_type" />
                        <value>766</value>
                     </leaf>
                  </and>
                  <leaf>
                     <comparator name="not_equal_uint64" package="package0" />
                     <event name="wait_completed" package="sqlos" field="wait_type" />
                     <value>1114</value>
                  </leaf>
               </and>
               <leaf>
                  <comparator name="not_equal_uint64" package="package0" />
                  <event name="wait_completed" package="sqlos" field="wait_type" />
                  <value>1013</value>
               </leaf>
            </and>
         </predicate>
      </event>
      <event package="sqlos" name="wait_info_external">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="plan_handle" />
         <action package="sqlserver" name="query_hash_signed" />
         <action package="sqlserver" name="query_plan_hash_signed" />
         <action package="sqlserver" name="request_id" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_resource_group_id" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="tsql_frame" />
         <action package="sqlserver" name="username" />
         <predicate>
            <and>
               <and>
                  <leaf>
                     <comparator name="equal_uint64" package="package0" />
                     <event name="wait_info_external" package="sqlos" field="opcode" />
                     <value>1</value>
                  </leaf>
                  <leaf>
                     <comparator name="equal_boolean" package="package0" />
                     <global name="is_system" package="sqlserver" />
                     <value>false</value>
                  </leaf>
               </and>
               <leaf>
                  <comparator name="greater_than_equal_uint64" package="package0" />
                  <event name="wait_info_external" package="sqlos" field="duration" />
                  <value>5000</value>
               </leaf>
            </and>
         </predicate>
      </event>
      <event package="sqlserver" name="blocked_process_report" />
      <event package="sqlserver" name="database_file_size_change">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="plan_handle" />
         <action package="sqlserver" name="request_id" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_resource_group_id" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="username" />
         <parameter name="collect_database_name" value="1" />
      </event>
      <event package="sqlserver" name="error_reported">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="plan_handle" />
         <action package="sqlserver" name="request_id" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_resource_group_id" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="tsql_frame" />
         <action package="sqlserver" name="username" />
         <predicate>
            <leaf>
               <comparator name="greater_than_int64" package="package0" />
               <event name="error_reported" package="sqlserver" field="severity" />
               <value>10</value>
            </leaf>
         </predicate>
      </event>
      <event package="sqlserver" name="module_end">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="plan_handle" />
         <action package="sqlserver" name="request_id" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_resource_group_id" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="tsql_frame" />
         <action package="sqlserver" name="username" />
         <predicate>
            <and>
               <leaf>
                  <comparator name="equal_boolean" package="package0" />
                  <global name="is_system" package="sqlserver" />
                  <value>false</value>
               </leaf>
               <leaf>
                  <comparator name="greater_than_equal_uint64" package="package0" />
                  <event name="module_end" package="sqlserver" field="duration" />
                  <value>5000000</value>
               </leaf>
            </and>
         </predicate>
      </event>
      <event package="sqlserver" name="rpc_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="request_id" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_resource_group_id" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="username" />
         <predicate>
            <and>
               <leaf>
                  <comparator name="equal_boolean" package="package0" />
                  <global name="is_system" package="sqlserver" />
                  <value>false</value>
               </leaf>
               <or>
                  <leaf>
                     <comparator name="greater_than_equal_uint64" package="package0" />
                     <event name="rpc_completed" package="sqlserver" field="duration" />
                     <value>5000000</value>
                  </leaf>
                  <leaf>
                     <comparator name="not_equal_uint64" package="package0" />
                     <event name="rpc_completed" package="sqlserver" field="result" />
                     <value>0</value>
                  </leaf>
               </or>
            </and>
         </predicate>
      </event>
      <event package="sqlserver" name="sql_batch_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="request_id" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_resource_group_id" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="username" />
         <parameter name="collect_batch_text" value="1" />
         <predicate>
            <and>
               <leaf>
                  <comparator name="equal_boolean" package="package0" />
                  <global name="is_system" package="sqlserver" />
                  <value>false</value>
               </leaf>
               <or>
                  <leaf>
                     <comparator name="greater_than_equal_uint64" package="package0" />
                     <event name="sql_batch_completed" package="sqlserver" field="duration" />
                     <value>5000000</value>
                  </leaf>
                  <leaf>
                     <comparator name="not_equal_uint64" package="package0" />
                     <event name="sql_batch_completed" package="sqlserver" field="result" />
                     <value>0</value>
                  </leaf>
               </or>
            </and>
         </predicate>
      </event>
      <event package="sqlserver" name="xml_deadlock_report">
         <action package="sqlserver" name="database_name" />
      </event>
      <target package="package0" name="event_file">
         <parameter name="filename" value="Database Health 2016 and Above" />
         <parameter name="max_file_size" value="5" />
         <parameter name="max_rollover_files" value="100" />
      </target>
   </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Deadlock Graphs.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
   <event_session name="Deadlock Graphs" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="false" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Everyday Extended Events</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Deadlock Graphs</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Captures deadlock information. Careful, the Deadlock tab is sneaky!</templateDescription>
      <event package="sqlserver" name="database_xml_deadlock_report">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="plan_handle" />
         <action package="sqlserver" name="sql_text" />
      </event>
      <event package="sqlserver" name="xml_deadlock_report">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="plan_handle" />
         <action package="sqlserver" name="sql_text" />
      </event>
      <target package="package0" name="event_file">
         <parameter name="filename" value="capture_deadlock_graphs" />
      </target>
   </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Default Profiler Trace.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
   <event_session name="Default Profiler Trace" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="false" dispatchLatency="1" maxEventSize="0" memoryPartitionMode="none">
      <templateCategory><!-- _locID_text="templateCategory" _locComment = "" -->System Monitoring</templateCategory>
      <templateName><!-- _locID_text = "templateName" _locComment = "" -->Default Profiler Trace</templateName>
      <templateDescription><!-- _locID_text = "templateDescription" _locComment = "" -->The default profiler trace, converted using sp_SQLskills_ConvertTraceToExtendedEvents.</templateDescription>
      <event package="sqlserver" name="existing_connection">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="server_principal_name" />
         <action package="sqlserver" name="session_id" />
      </event>
      <event package="sqlserver" name="login">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="server_principal_name" />
         <action package="sqlserver" name="session_id" />
      </event>
      <event package="sqlserver" name="logout">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="server_principal_name" />
         <action package="sqlserver" name="session_id" />
      </event>
      <event package="sqlserver" name="rpc_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="server_principal_name" />
         <action package="sqlserver" name="session_id" />
      </event>
      <event package="sqlserver" name="sql_batch_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="server_principal_name" />
         <action package="sqlserver" name="session_id" />
      </event>
      <event package="sqlserver" name="sql_batch_starting">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="server_principal_name" />
         <action package="sqlserver" name="session_id" />
      </event>
      <target package="package0" name="ring_buffer" />
   </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Deprecated Feature Usage.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
   <event_session name="Deprecated Feature Usage" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Features</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Deprecated Feature Usage</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Tracks deprecated feature usage.</templateDescription>
      <event package="sqlserver" name="deprecation_announcement">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_nt_username" />
         <action package="sqlserver" name="sql_text" />
         <action package="sqlserver" name="username" />
         <predicate>
            <and>
               <leaf>
                  <comparator name="greater_than_uint64" package="package0" />
                  <global name="database_id" package="sqlserver" />
                  <value>4</value>
               </leaf>
               <leaf>
                  <comparator name="not_equal_i_sql_unicode_string" package="sqlserver" />
                  <global name="client_app_name" package="sqlserver" />
                  <value><![CDATA[Microsoft SQL Server Management Studio - Transact-SQL IntelliSense]]></value>
               </leaf>
            </and>
         </predicate>
      </event>
      <event package="sqlserver" name="deprecation_final_support">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="session_nt_username" />
         <action package="sqlserver" name="sql_text" />
         <action package="sqlserver" name="username" />
         <predicate>
            <and>
               <leaf>
                  <comparator name="greater_than_uint64" package="package0" />
                  <global name="database_id" package="sqlserver" />
                  <value>4</value>
               </leaf>
               <leaf>
                  <comparator name="not_equal_i_sql_unicode_string" package="sqlserver" />
                  <global name="client_app_name" package="sqlserver" />
                  <value><![CDATA[Microsoft SQL Server Management Studio - Transact-SQL IntelliSense]]></value>
               </leaf>
            </and>
         </predicate>
      </event>
      <target package="package0" name="event_file">
         <parameter name="filename" value="Deprecated Feature Usage" />
         <parameter name="max_rollover_files" value="25" />
      </target>
   </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Failing Queries.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventsconfig">
   <event_session name="Failing Queries" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="false" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Query Execution</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Failing Queries</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Tracks failed queries.</templateDescription>   
	  <event package="sqlserver" name="error_reported">
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="sql_text" />
         <action package="sqlserver" name="tsql_stack" />
         <action package="sqlserver" name="username" />
         <predicate>
            <leaf>
               <comparator name="greater_than_int64" package="package0" />
               <event name="error_reported" package="sqlserver" field="severity" />
               <value>10</value>
            </leaf>
         </predicate>
      </event>
   </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Function Executions.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
   <event_session name="Function Executions" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="false" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Everyday Extended Events</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Function Executions</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Use this to count the number of times a function is executed from a single SELECT statement.</templateDescription>
      <event package="sqlserver" name="sp_statement_completed">
         <action package="sqlserver" name="sql_text" />
         <action package="sqlserver" name="tsql_stack" />
      </event>
      <event package="sqlserver" name="sql_statement_completed">
         <action package="sqlserver" name="sql_text" />
         <action package="sqlserver" name="tsql_stack" />
      </event>
      <target package="package0" name="ring_buffer" />
   </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Index Page Splits.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
   <event_session name="Index Page Splits" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="false" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Everyday Extended Events</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Index Page Splits</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->See index page splits in action.</templateDescription>
      <event package="sqlserver" name="page_split">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="sql_text" />
      </event>
      <target package="package0" name="event_file">
         <parameter name="filename" value="page_splits" />
         <parameter name="max_rollover_files" value="0" />
      </target>
   </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Log File IO Detail Tracking.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
  <event_session name="Log File IO Detail Tracking" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="false" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->System Monitoring</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Log File IO Detail Tracking</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Monitors the IO for database log files on a server by tracking asynchronous IO, database log flushes, file writes, spinlock backoffs of type LOGFLUSHQ and waits of type WRITELOG. This template collects data in two ways: raw data is collected to a ring buffer and spinlock backoff information is aggregated based on the input buffer (sql_text). The session is filtered for a single log file per database; if you have multiple log files you can modify the filter for the file_write_completed and file_written events to include more than just file_id = 2.</templateDescription>
    <event package="sqlos" name="async_io_completed" />
    <event package="sqlos" name="async_io_requested" />
    <event package="sqlos" name="spinlock_backoff">
      <action package="sqlserver" name="sql_text" />
      <predicate>
        <leaf>
          <comparator name="equal_uint64" package="package0"></comparator>
          <event name="spinlock_backoff" package="sqlos" field="type"></event>
          <value>85</value>
        </leaf>
      </predicate>
    </event>
    <event package="sqlos" name="wait_info">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <leaf>
            <comparator name="equal_uint64" package="package0"></comparator>
            <event name="wait_info" package="sqlos" field="opcode"></event>
            <value>1</value>
          </leaf>
          <leaf>
            <comparator name="equal_uint64" package="package0"></comparator>
            <event name="wait_info" package="sqlos" field="wait_type"></event>
            <value>182</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="databases_log_flush" />
    <event package="sqlserver" name="file_write_completed">
      <parameter name="collect_path" value="1" />
      <predicate>
        <leaf>
          <comparator name="equal_uint64" package="package0"></comparator>
          <event name="file_write_completed" package="sqlserver" field="file_id"></event>
          <value>2</value>
        </leaf>
      </predicate>
    </event>
    <event package="sqlserver" name="file_written">
      <parameter name="collect_path" value="1" />
      <predicate>
        <leaf>
          <comparator name="equal_uint64" package="package0"></comparator>
          <event name="file_written" package="sqlserver" field="file_id"></event>
          <value>2</value>
        </leaf>
      </predicate>
    </event>
    <target package="package0" name="histogram">
      <parameter name="filtering_event_name" value="sqlos.spinlock_backoff" />
      <parameter name="source" value="sqlserver.sql_text" />
    </target>
    <target package="package0" name="ring_buffer" />
  </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Log File IO Tracking.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
  <event_session name="Log File IO Tracking" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="false" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->System Monitoring</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Log File IO Tracking</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Monitors the IO for database log files by tracking waits of type WRITELOG.</templateDescription>
    <event package="sqlos" name="wait_info">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <leaf>
            <comparator name="equal_uint64" package="package0"></comparator>
            <event name="wait_info" package="sqlos" field="opcode"></event>
            <value>1</value>
          </leaf>
          <leaf>
            <comparator name="equal_uint64" package="package0"></comparator>
            <event name="wait_info" package="sqlos" field="wait_type"></event>
            <value>182</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <target package="package0" name="ring_buffer" />
  </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Login Tracker.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventsconfig">
   <event_session name="Login Tracker" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="false" dispatchLatency="1" maxEventSize="0" memoryPartitionMode="none">
       <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->System Monitoring</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Login Tracker</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Monitors logins to databases</templateDescription>
      <event package="sqlserver" name="sql_statement_starting">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="server_instance_name" />
         <action package="sqlserver" name="server_principal_name" />
         <parameter name="collect_statement" value="0" />
         <predicate>
            <and>
               <and>
                  <and>
                     <leaf>
                        <comparator name="equal_boolean" package="package0" />
                        <global name="is_system" package="sqlserver" />
                        <value>false</value>
                     </leaf>
                     <not>
                        <leaf>
                           <comparator name="like_i_sql_unicode_string" package="sqlserver" />
                           <global name="client_app_name" package="sqlserver" />
                           <value><![CDATA[%dbatools%]]></value>
                        </leaf>
                     </not>
                  </and>
                  <not>
                     <leaf>
                        <comparator name="like_i_sql_unicode_string" package="sqlserver" />
                        <global name="client_app_name" package="sqlserver" />
                        <value><![CDATA[%management studio%]]></value>
                     </leaf>
                  </not>
               </and>
               <leaf>
                  <comparator name="not_equal_i_sql_unicode_string" package="sqlserver" />
                  <global name="database_name" package="sqlserver" />
                  <value><![CDATA[tempdb]]></value>
               </leaf>
            </and>
         </predicate>
      </event>
      <target package="package0" name="event_file">
         <parameter name="filename" value="Login Tracker" />
         <parameter name="max_file_size" value="10" />
      </target>
   </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Long Running Queries.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventsconfig">
   <event_session name="Long Running Queries" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Query Execution</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Long Running Queries</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Tracks queries that take longer than 10 seconds to run.</templateDescription>
      <event package="sqlserver" name="rpc_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="query_hash" />
         <action package="sqlserver" name="server_principal_name" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="sql_text" />
         <predicate>
            <and>
               <and>
                  <leaf>
                     <comparator name="greater_than_uint64" package="package0" />
                     <global name="database_id" package="sqlserver" />
                     <value>4</value>
                  </leaf>
                  <leaf>
                     <comparator name="equal_boolean" package="package0" />
                     <global name="is_system" package="sqlserver" />
                     <value>false</value>
                  </leaf>
               </and>
               <leaf>
                  <comparator name="greater_than_equal_uint64" package="package0" />
                  <event name="rpc_completed" package="sqlserver" field="duration" />
                  <value>10000000</value>
               </leaf>
            </and>
         </predicate>
      </event>
      <event package="sqlserver" name="sql_batch_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="query_hash" />
         <action package="sqlserver" name="session_id" />
         <parameter name="collect_batch_text" value="1" />
         <predicate>
            <and>
               <and>
                  <leaf>
                     <comparator name="greater_than_uint64" package="package0" />
                     <global name="database_id" package="sqlserver" />
                     <value>4</value>
                  </leaf>
                  <leaf>
                     <comparator name="equal_boolean" package="package0" />
                     <global name="is_system" package="sqlserver" />
                     <value>false</value>
                  </leaf>
               </and>
               <leaf>
                  <comparator name="greater_than_equal_uint64" package="package0" />
                  <event name="sql_batch_completed" package="sqlserver" field="duration" />
                  <value>10000000</value>
               </leaf>
            </and>
         </predicate>
      </event>
      <target package="package0" name="event_file">
         <parameter name="filename" value="Long Running Queries" />
         <parameter name="max_file_size" value="100" />
      </target>
      <target package="package0" name="ring_buffer" />
   </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Overly Complex Queries.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventsconfig">
   <event_session name="Overly Complex Queries" maxMemory="100" eventRetentionMode="allowSingleEventLoss" trackCausality="false" dispatchLatency="5" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Performance Store</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Overly Complex Queries</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Captures queries that report errors 16 and 8623. This generally means that the query was unnecessarily complex.</templateDescription>
      <event package="sqlserver" name="error_reported">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="client_pid" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="nt_username" />
         <action package="sqlserver" name="plan_handle" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="sql_text" />
         <action package="sqlserver" name="transaction_id" />
         <action package="sqlserver" name="tsql_frame" />
         <action package="sqlserver" name="username" />
         <predicate>
            <and>
               <leaf>
                  <comparator name="equal_int64" package="package0" />
                  <event name="error_reported" package="sqlserver" field="severity" />
                  <value>16</value>
               </leaf>
               <leaf>
                  <comparator name="equal_int64" package="package0" />
                  <event name="error_reported" package="sqlserver" field="error_number" />
                  <value>8623</value>
               </leaf>
            </and>
         </predicate>
      </event>
      <target package="package0" name="event_file">
         <parameter name="filename" value="Overly Complex Queries" />
         <parameter name="max_file_size" value="200" />
         <parameter name="max_rollover_files" value="5" />
         <parameter name="metadatafile" value=" Overly Complex Queries.xem" />
      </target>
   </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Profiler SP Counts.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
  <event_session name="Profiler SP Counts" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Profiler Equivalents</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Profiler SP Counts</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Matches the 'SP_Counts' template in Profiler. 	Captures stored procedure execution behavior over time. </templateDescription>
    <event package="sqlserver" name="module_start">
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="sqlserver" name="server_instance_name" />
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <global name="database_id" package="sqlserver"></global>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
  </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Profiler Standard.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
  <event_session name="Profiler Standard" maxMemory="8" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="1" maxEventSize="0" memoryPartitionMode="perCpu">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Profiler Equivalents</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Profiler Standard</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Matches the 'Standard' template in Profiler. Generic starting point for creating a trace. Captures all stored procedures and Transact-SQL batches that are run. Use to monitor general database server activity.</templateDescription>    
    <event package="sqlserver" name="login">
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="session_id" />
      <parameter name="collect_options_text" value="1" />
    </event>
    <event package="sqlserver" name="logout">
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="session_id" />
    </event>
    <event package="sqlserver" name="existing_connection">
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="session_id" />
      <parameter name="collect_options_text" value="1" />
    </event>
    <event package="sqlserver" name="rpc_completed">
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <leaf>
          <comparator name="equal_boolean" package="package0"></comparator>
          <global name="is_system" package="sqlserver"></global>
          <value>false</value>
        </leaf>
      </predicate>
    </event>
    <event package="sqlserver" name="sql_batch_completed">
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <leaf>
          <comparator name="equal_boolean" package="package0"></comparator>
          <global name="is_system" package="sqlserver"></global>
          <value>false</value>
        </leaf>
      </predicate>
    </event>
    <event package="sqlserver" name="sql_batch_starting">
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <leaf>
          <comparator name="equal_boolean" package="package0"></comparator>
          <global name="is_system" package="sqlserver"></global>
          <value>false</value>
        </leaf>
      </predicate>
    </event>
    <event package="sqlserver" name="attention">
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <leaf>
          <comparator name="equal_boolean" package="package0"></comparator>
          <global name="is_system" package="sqlserver"></global>
          <value>false</value>
        </leaf>
      </predicate>
    </event>
  </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Profiler TSQL Duration.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
  <event_session name="Profiler TSQL Duration" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Profiler Equivalents</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Profiler TSQL Duration</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Matches the 'TSQL_Duration' template in Profiler. Captures all Transact-SQL statements submitted to SQL Server by clients and their execution time (in microseconds). Use to identify slow queries. </templateDescription>
    <event package="sqlserver" name="rpc_completed">
      <action package="sqlserver" name="session_id" />              
      <parameter name="collect_data_stream" value="1" />      
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <global name="database_id" package="sqlserver"></global>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="sql_batch_completed">
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <global name="database_id" package="sqlserver"></global>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
  </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Profiler TSQL Locks.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
  <event_session name="Profiler TSQL Locks" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Profiler Equivalents</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Profiler TSQL Locks</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Matches the 'TSQL_Locks' template in Profiler. Captures all of the Transact-SQL statements that are submitted to SQL Server by clients along with exceptional lock events. Use to troubleshoot deadlocks, lock time-out, and lock escalation events. </templateDescription>
    <event package="sqlserver" name="blocked_process_report">
      <action package="sqlserver" name="session_id" />      
    </event>
    <event package="sqlserver" name="lock_cancel">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_name" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="session_id" />
    </event>
    <event package="sqlserver" name="lock_deadlock">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_name" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="session_id" />
    </event>
    <event package="sqlserver" name="lock_deadlock_chain">
      <action package="sqlserver" name="database_name" />
      <action package="sqlserver" name="session_id" />
    </event>
    <event package="sqlserver" name="lock_escalation">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_name" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="session_id" />
    </event>
    <event package="sqlserver" name="lock_timeout_greater_than_0">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_name" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="session_id" />
    </event>
    <event package="sqlserver" name="sp_statement_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_name" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="session_id" />
      <parameter name="collect_statement" value="1" />
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <global name="database_id" package="sqlserver"></global>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="sp_statement_starting">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_name" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="session_id" />
      <parameter name="collect_statement" value="1" />
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <global name="database_id" package="sqlserver"></global>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="sql_statement_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="database_name" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <global name="database_id" package="sqlserver"></global>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>   
    <event package="sqlserver" name="sql_statement_starting">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="query_plan_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <and>
            <leaf>
              <comparator name="divides_by_uint64" package="package0"></comparator>
              <global name="session_id" package="sqlserver"></global>
              <value>5</value>
            </leaf>
            <leaf>
              <comparator name="greater_than_uint64" package="package0"></comparator>
              <global name="database_id" package="sqlserver"></global>
              <value>4</value>
            </leaf>
          </and>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="xml_deadlock_report">
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="session_id" />
    </event>
  </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Profiler TSQL Replay.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
  <event_session name="Profiler TSQL Replay" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Profiler Equivalents</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Profiler TSQL Replay</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Matches the 'TSQL_Replay' template in Profiler. Use to perform iterative tuning, such as benchmark testing.</templateDescription>
    <event package="sqlserver" name="attention">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="session_id" />      
    </event>
    <event package="sqlserver" name="cursor_close">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="session_id" />      
    </event>
    <event package="sqlserver" name="cursor_execute">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="session_id" />      
    </event>
    <event package="sqlserver" name="cursor_open">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="session_id" />      
    </event>
    <event package="sqlserver" name="cursor_prepare">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="session_id" />      
    </event>
    <event package="sqlserver" name="cursor_unprepare">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="session_id" />      
    </event>
    <event package="sqlserver" name="exec_prepared_sql">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="session_id" />      
    </event>
    <event package="sqlserver" name="existing_connection">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="session_id" />      
    </event>
    <event package="sqlserver" name="login">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="session_id" />      
      <parameter name="collect_options_text" value="1" />
    </event>
    <event package="sqlserver" name="logout">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="session_id" />      
    </event>
    <event package="sqlserver" name="prepare_sql">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="session_id" />      
    </event>    
    <event package="sqlserver" name="rpc_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="session_id" />      
    </event>
    <event package="sqlserver" name="rpc_starting">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="session_id" />      
    </event>
    <event package="sqlserver" name="sql_batch_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="session_id" />
    </event>
    <event package="sqlserver" name="sql_batch_starting">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="client_pid" />
      <action package="sqlserver" name="client_hostname" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="database_name" />
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="is_system" />
      <action package="sqlserver" name="nt_username" />
      <action package="sqlserver" name="request_id" />
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="server_instance_name" />
      <action package="sqlserver" name="session_id" />
    </event>
  </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Profiler TSQL SPs.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
  <event_session name="Profiler TSQL SPs" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Profiler Equivalents</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Profiler TSQL SPs</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Matches the 'TSQL_SPs' template in Profiler. Captures detailed information about all executing stored procedures. Use to analyze the component steps of stored procedures. Add the sql_statement_recompile event if you suspect that procedures are being recompiled.</templateDescription>
    <event package="sqlserver" name="existing_connection">
      <action package="sqlserver" name="database_id" />            
      <action package="sqlserver" name="database_name" />            
      <action package="sqlserver" name="session_id" />            
      <action package="sqlserver" name="server_instance_name" />            
    </event>
    <event package="sqlserver" name="login">
      <action package="sqlserver" name="database_id" />            
      <action package="sqlserver" name="database_name" />            
      <action package="sqlserver" name="session_id" />            
      <action package="sqlserver" name="server_instance_name" />            
      <parameter name="collect_options_text" value="1" />
    </event>
    <event package="sqlserver" name="logout">
      <action package="sqlserver" name="database_id" />            
      <action package="sqlserver" name="database_name" />            
      <action package="sqlserver" name="session_id" />            
      <action package="sqlserver" name="server_instance_name" />            
    </event>
    <event package="sqlserver" name="module_end">
      <action package="sqlserver" name="database_id" />            
      <action package="sqlserver" name="database_name" />            
      <action package="sqlserver" name="session_id" />            
      <action package="sqlserver" name="server_instance_name" />                  
    </event>
    <event package="sqlserver" name="module_start">
      <action package="sqlserver" name="database_id" />            
      <action package="sqlserver" name="database_name" />            
      <action package="sqlserver" name="session_id" />            
      <action package="sqlserver" name="server_instance_name" />            
    </event>       
    <event package="sqlserver" name="rpc_starting">
      <action package="sqlserver" name="database_id" />            
      <action package="sqlserver" name="database_name" />            
      <action package="sqlserver" name="session_id" />            
      <action package="sqlserver" name="server_instance_name" />            
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <global name="database_id" package="sqlserver"></global>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="sp_statement_starting">
      <action package="sqlserver" name="database_id" />            
      <action package="sqlserver" name="database_name" />            
      <action package="sqlserver" name="session_id" />            
      <action package="sqlserver" name="server_instance_name" />            
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <global name="database_id" package="sqlserver"></global>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>       
    <event package="sqlserver" name="sql_batch_starting">
      <action package="sqlserver" name="database_id" />            
      <action package="sqlserver" name="database_name" />            
      <action package="sqlserver" name="session_id" />            
      <action package="sqlserver" name="server_instance_name" />            
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <global name="database_id" package="sqlserver"></global>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>        
  </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Profiler TSQL.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
  <event_session name="Profiler TSQL" maxMemory="8" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="5" maxEventSize="0" memoryPartitionMode="perCpu">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Profiler Equivalents</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Profiler TSQL</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Matches the 'TSQL' template in Profiler. Captures all Transact-SQL statements that are submitted to SQL Server by clients and the time issued. Use to debug client applications.</templateDescription>
    <event package="sqlserver" name="login">
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="session_id" />
      <parameter name="collect_options_text" value="1" />
    </event>
    <event package="sqlserver" name="logout">
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="session_id" />
    </event>
    <event package="sqlserver" name="existing_connection">
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="session_id" />
    </event>
    <event package="sqlserver" name="rpc_starting">
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <leaf>
          <comparator name="equal_boolean" package="package0"></comparator>
          <global name="is_system" package="sqlserver"></global>
          <value>false</value>
        </leaf>
      </predicate>
    </event>
    <event package="sqlserver" name="sql_batch_starting">
      <action package="package0" name="event_sequence" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <leaf>
          <comparator name="equal_boolean" package="package0"></comparator>
          <global name="is_system" package="sqlserver"></global>
          <value>false</value>
        </leaf>
      </predicate>
    </event>
  </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Profiler Tuning.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
  <event_session name="Profiler Tuning" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Profiler Equivalents</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Profiler Tuning</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Matches the 'Tuning' template in Profiler. Captures information about stored procedures and Transact-SQL batch execution.</templateDescription>
    <event package="sqlserver" name="rpc_completed">
      <action package="sqlserver" name="database_id" />            
      <action package="sqlserver" name="database_name" />            
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="session_id" />                    
      <parameter name="collect_data_stream" value="1" />      
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <global name="database_id" package="sqlserver"></global>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="sp_statement_completed">
      <action package="sqlserver" name="database_id" />            
      <action package="sqlserver" name="database_name" />            
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="session_id" />                    
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <global name="database_id" package="sqlserver"></global>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="sql_batch_completed">
      <action package="sqlserver" name="database_id" />            
      <action package="sqlserver" name="database_name" />            
      <action package="sqlserver" name="server_principal_name" />
      <action package="sqlserver" name="session_id" />                    
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <global name="database_id" package="sqlserver"></global>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
  </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Queries and Resources.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
   <event_session name="Queries and Resources" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Everyday Extended Events</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Queries and Resources</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Captures query activity.</templateDescription>
      <event package="sqlserver" name="rpc_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="query_hash" />
         <action package="sqlserver" name="session_id" />
         <parameter name="collect_statement" value="1" />
         <predicate>
            <and>
               <leaf>
                  <comparator name="greater_than_uint64" package="package0" />
                  <global name="database_id" package="sqlserver" />
                  <value>4</value>
               </leaf>
               <leaf>
                  <comparator name="equal_boolean" package="package0" />
                  <global name="is_system" package="sqlserver" />
                  <value>false</value>
               </leaf>
            </and>
         </predicate>
      </event>
      <event package="sqlserver" name="sp_statement_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="query_hash" />
         <action package="sqlserver" name="query_plan_hash" />
         <action package="sqlserver" name="session_id" />
         <parameter name="collect_object_name" value="1" />
         <predicate>
            <and>
               <leaf>
                  <comparator name="greater_than_uint64" package="package0" />
                  <global name="database_id" package="sqlserver" />
                  <value>4</value>
               </leaf>
               <leaf>
                  <comparator name="equal_boolean" package="package0" />
                  <global name="is_system" package="sqlserver" />
                  <value>false</value>
               </leaf>
            </and>
         </predicate>
      </event>
      <event package="sqlserver" name="sql_batch_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="query_hash" />
         <action package="sqlserver" name="session_id" />
         <predicate>
            <and>
               <leaf>
                  <comparator name="greater_than_uint64" package="package0" />
                  <global name="database_id" package="sqlserver" />
                  <value>4</value>
               </leaf>
               <leaf>
                  <comparator name="equal_boolean" package="package0" />
                  <global name="is_system" package="sqlserver" />
                  <value>false</value>
               </leaf>
            </and>
         </predicate>
      </event>
      <event package="sqlserver" name="sql_statement_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="query_hash" />
         <action package="sqlserver" name="query_plan_hash" />
         <action package="sqlserver" name="session_id" />
         <predicate>
            <and>
               <leaf>
                  <comparator name="greater_than_uint64" package="package0" />
                  <global name="database_id" package="sqlserver" />
                  <value>4</value>
               </leaf>
               <leaf>
                  <comparator name="equal_boolean" package="package0" />
                  <global name="is_system" package="sqlserver" />
                  <value>false</value>
               </leaf>
            </and>
         </predicate>
      </event>
      <target package="package0" name="event_file">
         <parameter name="filename" value="capture_queries_and_resources" />
         <parameter name="max_rollover_files" value="0" />
      </target>
      <target package="package0" name="ring_buffer">
         <parameter name="max_memory" value="1048576" />
      </target>
   </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Query Batch Detail Sampling.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
  <event_session name="Query Batch Detail Sampling" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Query Execution</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Query Batch Detail Sampling</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Collects batch and RPC level statements as well as error information. You can use this template to understand the flow of queries that are executing on your system and track errors back to the queries that caused them. Events are only collected from 20% of the active sessions on the server at any given time. You can change the sampling rate by modifying the filter for the event session.</templateDescription>
    <event package="sqlserver" name="error_reported">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <and>
            <leaf>
              <comparator name="divides_by_uint64" package="package0"></comparator>
              <global name="session_id" package="sqlserver"></global>
              <value>5</value>
            </leaf>
            <leaf>
              <comparator name="greater_than_uint64" package="package0"></comparator>
              <global name="database_id" package="sqlserver"></global>
              <value>4</value>
            </leaf>
          </and>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="rpc_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <and>
            <leaf>
              <comparator name="divides_by_uint64" package="package0"></comparator>
              <global name="session_id" package="sqlserver"></global>
              <value>5</value>
            </leaf>
            <leaf>
              <comparator name="greater_than_uint64" package="package0"></comparator>
              <global name="database_id" package="sqlserver"></global>
              <value>4</value>
            </leaf>
          </and>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="sql_batch_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <and>
            <leaf>
              <comparator name="divides_by_uint64" package="package0"></comparator>
              <global name="session_id" package="sqlserver"></global>
              <value>5</value>
            </leaf>
            <leaf>
              <comparator name="greater_than_uint64" package="package0"></comparator>
              <global name="database_id" package="sqlserver"></global>
              <value>4</value>
            </leaf>
          </and>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <target package="package0" name="ring_buffer" />
  </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Query Batch Sampling.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
  <event_session name="Query Batch Sampling" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Query Execution</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Query Batch Sampling</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Collects batch and RPC level statements as well as error information. You can use this template to understand the flow of queries that are executing on your system and track errors back to the queries that caused them. Events are only collected from 20% of the active sessions on the server at any given time. You can change the sampling rate by modifying the filter for the event session.</templateDescription>
    <event package="sqlserver" name="error_reported">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
            <leaf>
              <comparator name="divides_by_uint64" package="package0"></comparator>
              <global name="session_id" package="sqlserver"></global>
              <value>5</value>
            </leaf>
            <leaf>
              <comparator name="greater_than_uint64" package="package0"></comparator>
              <global name="database_id" package="sqlserver"></global>
              <value>4</value>
            </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="rpc_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
			<leaf>
			  <comparator name="divides_by_uint64" package="package0"></comparator>
			  <global name="session_id" package="sqlserver"></global>
			  <value>5</value>
			</leaf>
			<leaf>
			  <comparator name="greater_than_uint64" package="package0"></comparator>
			  <global name="database_id" package="sqlserver"></global>
			  <value>4</value>
			</leaf>
		</and>
      </predicate>
    </event>
    <event package="sqlserver" name="sql_batch_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
			 <leaf>
			  <comparator name="divides_by_uint64" package="package0"></comparator>
			  <global name="session_id" package="sqlserver"></global>
			  <value>5</value>
			</leaf>
			<leaf>
			  <comparator name="greater_than_uint64" package="package0"></comparator>
			  <global name="database_id" package="sqlserver"></global>
			  <value>4</value>
			</leaf>
        </and>
      </predicate>
    </event>
    <target package="package0" name="ring_buffer" />
  </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Query Batch Tracking.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
  <event_session name="Query Batch Tracking" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Query Execution</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Query Batch Tracking</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Collects batch and RPC level statements as well as error information. You can use this template to understand the flow of queries that are executing on your system and track errors back to the queries that caused them. All batch events are collected in this session so collection size may be very large. To reduce the collection size, consider using the Query Batch Sampling template, which already includes a filter.</templateDescription>    
    <event package="sqlserver" name="error_reported">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <global name="database_id" package="sqlserver"></global>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="rpc_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <global name="database_id" package="sqlserver"></global>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="sql_batch_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <global name="database_id" package="sqlserver"></global>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <target package="package0" name="ring_buffer" />
  </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Query Detail Sampling.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
  <event_session name="Query Detail Sampling" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Query Execution</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Query Detail Sampling</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Collects detailed statement and error information. You can use this template to track each statement that has executed on your system as a result of query batches or stored procedures and track errors back to the specific statement that caused them. This template also collects the query hash and query plan hash for every statement it tracks. Events are only collected from 20% of the active sessions on the server at any given time. You can change the sampling rate by modifying the filter for the event session.</templateDescription>
    <event package="sqlserver" name="error_reported">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <and>
            <leaf>
              <comparator name="divides_by_uint64" package="package0"></comparator>
              <global name="session_id" package="sqlserver"></global>
              <value>5</value>
            </leaf>
            <leaf>
              <comparator name="greater_than_uint64" package="package0"></comparator>
              <global name="database_id" package="sqlserver"></global>
              <value>4</value>
            </leaf>
          </and>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="module_end">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="session_id" />
      <parameter name="collect_statement" value="1" />
      <predicate>
        <and>
          <and>
            <leaf>
              <comparator name="divides_by_uint64" package="package0"></comparator>
              <global name="session_id" package="sqlserver"></global>
              <value>5</value>
            </leaf>
            <leaf>
              <comparator name="greater_than_uint64" package="package0"></comparator>
              <global name="database_id" package="sqlserver"></global>
              <value>4</value>
            </leaf>
          </and>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="rpc_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <and>
            <leaf>
              <comparator name="divides_by_uint64" package="package0"></comparator>
              <global name="session_id" package="sqlserver"></global>
              <value>5</value>
            </leaf>
            <leaf>
              <comparator name="greater_than_uint64" package="package0"></comparator>
              <global name="database_id" package="sqlserver"></global>
              <value>4</value>
            </leaf>
          </and>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="sp_statement_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="query_plan_hash" />
      <action package="sqlserver" name="session_id" />
      <parameter name="collect_object_name" value="1" />
      <predicate>
        <and>
          <and>
            <leaf>
              <comparator name="divides_by_uint64" package="package0"></comparator>
              <global name="session_id" package="sqlserver"></global>
              <value>5</value>
            </leaf>
            <leaf>
              <comparator name="greater_than_uint64" package="package0"></comparator>
              <global name="database_id" package="sqlserver"></global>
              <value>4</value>
            </leaf>
          </and>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="sql_batch_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <and>
            <leaf>
              <comparator name="divides_by_uint64" package="package0"></comparator>
              <global name="session_id" package="sqlserver"></global>
              <value>5</value>
            </leaf>
            <leaf>
              <comparator name="greater_than_uint64" package="package0"></comparator>
              <global name="database_id" package="sqlserver"></global>
              <value>4</value>
            </leaf>
          </and>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="sql_statement_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="query_plan_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <and>
            <leaf>
              <comparator name="divides_by_uint64" package="package0"></comparator>
              <global name="session_id" package="sqlserver"></global>
              <value>5</value>
            </leaf>
            <leaf>
              <comparator name="greater_than_uint64" package="package0"></comparator>
              <global name="database_id" package="sqlserver"></global>
              <value>4</value>
            </leaf>
          </and>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <target package="package0" name="ring_buffer" />
  </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Query Detail Tracking.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
  <event_session name="Query Detail Tracking" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Query Execution</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Query Detail Tracking</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Collects detailed statement and error information. You can use this template to track each statement has executed on your system as a result of query batches or stored procedures and then track errors back to the specific statement that caused them. This template also collects the query hash and query plan hash for every statement it tracks. All statement events are collected in this session so collection size may be very large. To reduce the collection size consider using the Query Detail Sampling template, which already includes a filter.</templateDescription>
    <event package="sqlserver" name="error_reported">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <global name="database_id" package="sqlserver"></global>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="module_end">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="session_id" />
      <parameter name="collect_statement" value="1" />
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <global name="database_id" package="sqlserver"></global>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="rpc_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <global name="database_id" package="sqlserver"></global>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="sp_statement_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="query_plan_hash" />
      <action package="sqlserver" name="session_id" />
      <parameter name="collect_object_name" value="1" />
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <global name="database_id" package="sqlserver"></global>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="sql_batch_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <global name="database_id" package="sqlserver"></global>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="sql_statement_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="query_plan_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <leaf>
            <comparator name="greater_than_uint64" package="package0"></comparator>
            <global name="database_id" package="sqlserver"></global>
            <value>4</value>
          </leaf>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <target package="package0" name="ring_buffer" />
  </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Query Timeouts.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
   <event_session name="Query Timeouts" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="5" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Query Execution</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Query Timeouts</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Tracks query timeouts.</templateDescription>
      <event package="sqlserver" name="sql_statement_completed">
         <action package="sqlserver" name="query_hash" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="tsql_stack" />
      </event>
      <event package="sqlserver" name="sql_statement_starting">
         <action package="sqlserver" name="query_hash" />
         <action package="sqlserver" name="session_id" />
         <action package="sqlserver" name="tsql_stack" />
      </event>
      <target package="package0" name="pair_matching">
         <parameter name="begin_event" value="sqlserver.sql_statement_starting" />
         <parameter name="begin_matching_actions" value="sqlserver.session_id, sqlserver.tsql_stack" />
         <parameter name="end_event" value="sqlserver.sql_statement_completed" />
         <parameter name="end_matching_actions" value="sqlserver.session_id, sqlserver.tsql_stack" />
         <parameter name="respond_to_memory_pressure" value="0" />
      </target>
   </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Query Wait Statistics Detail.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
  <event_session name="Query Wait Statistics Detail" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="true" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Query Execution</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Query Wait Statistics Detail</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Tracks internal and external wait statistics for individual query statements, batches and RPCs. This template also collects the query hash and query plan hash for every statement it tracks. Events are only collected from 20% of the active sessions on the server at any given time. You can change the sampling rate by modifying the filter for the event session.</templateDescription>
    <event package="sqlos" name="wait_info">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="query_plan_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <and>
            <leaf>
              <comparator name="divides_by_uint64" package="package0"></comparator>
              <global name="session_id" package="sqlserver"></global>
              <value>5</value>
            </leaf>
            <leaf>
              <comparator name="greater_than_uint64" package="package0"></comparator>
              <global name="database_id" package="sqlserver"></global>
              <value>4</value>
            </leaf>
          </and>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlos" name="wait_info_external">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="query_plan_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <and>
            <leaf>
              <comparator name="divides_by_uint64" package="package0"></comparator>
              <global name="session_id" package="sqlserver"></global>
              <value>5</value>
            </leaf>
            <leaf>
              <comparator name="greater_than_uint64" package="package0"></comparator>
              <global name="database_id" package="sqlserver"></global>
              <value>4</value>
            </leaf>
          </and>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="rpc_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <and>
            <leaf>
              <comparator name="divides_by_uint64" package="package0"></comparator>
              <global name="session_id" package="sqlserver"></global>
              <value>5</value>
            </leaf>
            <leaf>
              <comparator name="greater_than_uint64" package="package0"></comparator>
              <global name="database_id" package="sqlserver"></global>
              <value>4</value>
            </leaf>
          </and>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="rpc_starting">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <and>
            <leaf>
              <comparator name="divides_by_uint64" package="package0"></comparator>
              <global name="session_id" package="sqlserver"></global>
              <value>5</value>
            </leaf>
            <leaf>
              <comparator name="greater_than_uint64" package="package0"></comparator>
              <global name="database_id" package="sqlserver"></global>
              <value>4</value>
            </leaf>
          </and>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="sp_statement_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="query_plan_hash" />
      <action package="sqlserver" name="session_id" />
      <parameter name="collect_object_name" value="1" />
      <parameter name="collect_statement" value="1" />
      <predicate>
        <and>
          <and>
            <leaf>
              <comparator name="divides_by_uint64" package="package0"></comparator>
              <global name="session_id" package="sqlserver"></global>
              <value>5</value>
            </leaf>
            <leaf>
              <comparator name="greater_than_uint64" package="package0"></comparator>
              <global name="database_id" package="sqlserver"></global>
              <value>4</value>
            </leaf>
          </and>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="sp_statement_starting">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="query_plan_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <and>
            <leaf>
              <comparator name="divides_by_uint64" package="package0"></comparator>
              <global name="session_id" package="sqlserver"></global>
              <value>5</value>
            </leaf>
            <leaf>
              <comparator name="greater_than_uint64" package="package0"></comparator>
              <global name="database_id" package="sqlserver"></global>
              <value>4</value>
            </leaf>
          </and>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="sql_batch_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <and>
            <leaf>
              <comparator name="divides_by_uint64" package="package0"></comparator>
              <global name="session_id" package="sqlserver"></global>
              <value>5</value>
            </leaf>
            <leaf>
              <comparator name="greater_than_uint64" package="package0"></comparator>
              <global name="database_id" package="sqlserver"></global>
              <value>4</value>
            </leaf>
          </and>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="sql_batch_starting">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <and>
            <leaf>
              <comparator name="divides_by_uint64" package="package0"></comparator>
              <global name="session_id" package="sqlserver"></global>
              <value>5</value>
            </leaf>
            <leaf>
              <comparator name="greater_than_uint64" package="package0"></comparator>
              <global name="database_id" package="sqlserver"></global>
              <value>4</value>
            </leaf>
          </and>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="sql_statement_completed">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="query_plan_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <and>
            <leaf>
              <comparator name="divides_by_uint64" package="package0"></comparator>
              <global name="session_id" package="sqlserver"></global>
              <value>5</value>
            </leaf>
            <leaf>
              <comparator name="greater_than_uint64" package="package0"></comparator>
              <global name="database_id" package="sqlserver"></global>
              <value>4</value>
            </leaf>
          </and>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <event package="sqlserver" name="sql_statement_starting">
      <action package="sqlserver" name="client_app_name" />
      <action package="sqlserver" name="database_id" />
      <action package="sqlserver" name="query_hash" />
      <action package="sqlserver" name="query_plan_hash" />
      <action package="sqlserver" name="session_id" />
      <predicate>
        <and>
          <and>
            <leaf>
              <comparator name="divides_by_uint64" package="package0"></comparator>
              <global name="session_id" package="sqlserver"></global>
              <value>5</value>
            </leaf>
            <leaf>
              <comparator name="greater_than_uint64" package="package0"></comparator>
              <global name="database_id" package="sqlserver"></global>
              <value>4</value>
            </leaf>
          </and>
          <leaf>
            <comparator name="equal_boolean" package="package0"></comparator>
            <global name="is_system" package="sqlserver"></global>
            <value>false</value>
          </leaf>
        </and>
      </predicate>
    </event>
    <target package="package0" name="event_file">
      <parameter name="filename" value="query_wait_analysis" />
    </target>
  </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Query Wait Statistics.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
   <event_session name="Query Wait Statistics" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="false" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Everyday Extended Events</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Query Wait Statistics</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Tracks internal and external wait statistics.</templateDescription>
      <event package="sqlos" name="wait_completed">
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="is_system" />
         <action package="sqlserver" name="session_id" />
         <parameter name="collect_wait_resource" value="1" />
         <predicate>
            <and>
               <leaf>
                  <comparator name="greater_than_uint64" package="package0" />
                  <global name="database_id" package="sqlserver" />
                  <value>4</value>
               </leaf>
               <leaf>
                  <comparator name="not_equal_boolean" package="package0" />
                  <global name="is_system" package="sqlserver" />
                  <value>false</value>
               </leaf>
            </and>
         </predicate>
      </event>
      <event package="sqlos" name="wait_info">
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="is_system" />
         <action package="sqlserver" name="session_id" />
         <predicate>
            <and>
               <leaf>
                  <comparator name="greater_than_uint64" package="package0" />
                  <global name="database_id" package="sqlserver" />
                  <value>4</value>
               </leaf>
               <leaf>
                  <comparator name="not_equal_boolean" package="package0" />
                  <global name="is_system" package="sqlserver" />
                  <value>false</value>
               </leaf>
            </and>
         </predicate>
      </event>
      <event package="sqlos" name="wait_info_external">
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="is_system" />
         <action package="sqlserver" name="session_id" />
         <predicate>
            <and>
               <leaf>
                  <comparator name="greater_than_uint64" package="package0" />
                  <global name="database_id" package="sqlserver" />
                  <value>4</value>
               </leaf>
               <leaf>
                  <comparator name="not_equal_boolean" package="package0" />
                  <global name="is_system" package="sqlserver" />
                  <value>false</value>
               </leaf>
            </and>
         </predicate>
      </event>
      <target package="package0" name="ring_buffer">
         <parameter name="max_memory" value="102400" />
      </target>
   </event_session>
</event_sessions>
tools\dbatools\bin\XEtemplates\Stored Procedure Parameters.xml
<event_sessions xmlns="http://schemas.microsoft.com/sqlserver/2008/07/extendedeventconfig">
   <event_session name="Stored Procedure Parameters" maxMemory="4" eventRetentionMode="allowSingleEventLoss" trackCausality="false" dispatchLatency="30" maxEventSize="0" memoryPartitionMode="none">
    <templateCategory>
      <!-- _locID_text="templateCategory" _locComment = "" -->Everyday Extended Events</templateCategory>
    <templateName>
      <!-- _locID_text = "templateName" _locComment = "" -->Stored Procedure Parameters</templateName>
    <templateDescription>
      <!-- _locID_text = "templateDescription" _locComment = "" -->Captures what parameters were used when a stored procedure was executed.</templateDescription>
      <event package="sqlserver" name="rpc_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="query_hash" />
         <action package="sqlserver" name="query_plan_hash" />
         <action package="sqlserver" name="sql_text" />
         <parameter name="collect_output_parameters" value="1" />
         <parameter name="collect_statement" value="1" />
         <predicate>
            <leaf>
               <comparator name="greater_than_uint64" package="package0" />
               <global name="database_id" package="sqlserver" />
               <value>4</value>
            </leaf>
         </predicate>
      </event>
      <event package="sqlserver" name="sql_batch_completed">
         <action package="sqlserver" name="client_app_name" />
         <action package="sqlserver" name="client_hostname" />
         <action package="sqlserver" name="database_id" />
         <action package="sqlserver" name="database_name" />
         <action package="sqlserver" name="query_hash" />
         <action package="sqlserver" name="query_plan_hash" />
         <action package="sqlserver" name="sql_text" />
         <predicate>
            <leaf>
               <comparator name="greater_than_uint64" package="package0" />
               <global name="database_id" package="sqlserver" />
               <value>4</value>
            </leaf>
         </predicate>
      </event>
      <target package="package0" name="event_file">
         <parameter name="filename" value="capture_parameters" />
         <parameter name="max_rollover_files" value="0" />
      </target>
   </event_session>
</event_sessions>
tools\dbatools\changelog.md
# Changelog
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
    and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.9.720] - 2018-12-16
### Fixed
* Enhanced outputs of Invoke-DbaDbDataMasking
* Save-DbaDiagnosticQuery to work with lightly malformed links

## [0.9.719] - 2018-12-15
### Added
* Piping to Get-DbaDbSpace

### Changed
* Logic to make UseLastBackup in Start-DbaMigration to be easier

## [0.9.718] - 2018-12-14
### Added
* Added a progress bar and made the output more reasonable

## [0.9.717] - 2018-12-14
### Fixed
* Added more flexibility to masking commands
* Updated SQL Build info

## [0.9.715] - 2018-12-12
### Fixed
* LogShipping in v2012

### Added
* Added check for ps v2 for those that bypass psd1
* Pipeline support for Get-DbaDbSpace
* xplat support notification to find-dbacommand / docs.dbatools.io
* More integration tests
* New commands: Invoke-DbaDbDataMasking and New-DbaDbMaskingConfig

## [0.9.714] - 2018-12-10
### Fixed
* Get-DbaBackupHistory - fully honors need to exclude system dbs
* Fixed docs/typos in various commands

## [0.9.712] - 2018-12-9
### Changed
* Renamed DbaOrphanUwer series

### Added
* More integration tests!
* Docs update
* Schema output to Copy-DbaDbTableData

### Fixed
* Variable bug fix in Invoke-DbaLogShipping

## [0.9.711] - 2018-12-7
### Added
* Multi-threading to Update-DbaInstance
* System db export capabilities to Export-DbaDacPackage

### Fixed
* Ag replica now works when run outside of New-DbaAvailabilityGroup

## [0.9.710] - 2018-12-5
### Fixed
* Start-DbaMigration xplat support

## [0.9.709] - 2018-12-4
### Fixed
* Invoke-DbaAgFailover try/catch wrap to make errors pretty.
* Renamed Set-DbaJobOwner to Set-DbaAgentJobOwner
* Failed logic in Remove-DbaOrphanUser
* Removed ability to specify both KeepDays and Database from Remove-DbaDbBackupRestoreHistory

# Added
* VSCode default settings
* Pipe support in Test-DbaDbOwner

## [0.9.708] - 2018-12-4
### Fixed
* Sync AG bug having to do with read-only dbs

# Added
* Update-DbaInstance final touches

## [0.9.707] - 2018-12-3
### Fixed
* Explicit export of cmdlet module members (fixes older OS/PS issues)

## [0.9.705] - 2018-12-3
### Fixed
* Docker support for AGs

## [0.9.704] - 2018-12-3
### Fixed
* Issue where the dll was repeatedly copied in Windows
* Command exports

## [0.9.703] - 2018-12-3
### Added
* Faster import by uisng zip instead of big ol' ps1

## [0.9.702] - 2018-12-2
### Fixed
* Core support for Copy-DbaDbDatatable, Write-DbaDataTable,
* Parameter names for Copy-DbaDbQueryStoreOption

### Added
* Core support for Import-DbaCsv

## [0.9.700] - 2018-12-1
### Added
* For real true xplat including library and configs 🎉🎉🎉🎉🎉
* Added Update-DbaInstance 🎉🎉🎉🎉🎉

## [0.9.538] - 2018-11-30

### Fixed
* ComputerName resolution for fqdn in Connect-*Instance
* Stop-Function -Continue bug in Set-DbaPrivilege

## [0.9.537] - 2018-11-29
### Added
* Invoke-DbaDbccFreeCache
* Get-DbaDbccUserOption
* Added PolyBase support to Get-DbaService

## [0.9.535] - 2018-11-29
### Fixed
- Backup recoveryfork bug
- Standardized output for Copy command notes
- New-DbaAgentJobStep issue with server / SubSystemServer

### Added
* Get-DbaDbccHelp
* Get-DbaDbccMemoryStatus
* Get-DbaDbccProcCache

## [0.9.534] - 2018-11-29
### Fixed
- Removed mandatory=$false on parameters because it's implied

### Added
* Get-DbaAgentServer
* Set-DbaAgentServer
* Path parameter to audit copies


## [0.9.533] - 2018-11-27
### Fixed
- Removed mandatory=$false on parameters because it's implied

### Added
- Extra include and exclude options to `Sync-DbaAvailabilityGroup`
- Extra column parameters to `Import-DbaCsv`

## [0.9.532] - 2018-11-26
### Fixed
- Publish-DbaDacpackage param issues introduced by core fixes
- Resolve-DbaNetworkName resolution issue introduced by core fixes
- Some long-standing `Get-DbaBackupHistory -Force` problems were resolved

### Added
- Added VS Code recommendations

## [0.9.531] - 2018-11-24
### Added
- Support for Core and Certs
- Solution file upgraded to Core combination and VS 2017

## [0.9.531] - 2018-11-24
### Added
- Support for Core and Certs
- Solution file upgraded to Core combination and VS 2017

## [0.9.530] - 2018-11-24
### Fixed
- Fixed non-Windows imports. "Fixed" used loosely - disabled configuration to speed up import. Xplat still not fully delivered.

### Added
- Seeding support to Add-DbaAgDatabase
- More integration tests!
- Category and Database filters to Get-DbaAgentJob

## [0.9.525] - 2018-11-23
### Added
- CROSS PLATFORM SUPPORT INCLUDING MACOS AND LINUX 🎉

![image](https://user-images.githubusercontent.com/8278033/48960127-ac3c3980-ef6a-11e8-90ca-1e8e56df8ee0.png)

## [0.9.524] - 2018-11-23
### Added
- $script:core for easy core detection in functions

### Fixed
- Resolve-Path added to core import routine

## [0.9.523] - 2018-11-23
### Added
- Support for Dacfx for core 🎉

### Fixed
- Weird thing in Core where a string comparison didn't work so it tried to copy dbatools.dll onto itself
- Get-DbaDbFile now works for CS collation

## [0.9.522] - 2018-11-23
### Added
- Support for PS Core on Windows 🎉
- SMO core DLLs from the SqlServer module

### Fixed
- AG versioning bugs

## [0.9.521] - 2018-11-22
### Added
- This changelog.md! 🎉

### Removed
- Extra DLLs that did not seem necessary

### Changed
- Updated Glen Berry's scripts


## changelog background and additional info

### Types of changes
* Added for new features.
* Changed for changes in existing functionality.
* Deprecated for soon-to-be removed features.
* Removed for now removed features.
* Fixed for any bug fixes.
* Security in case of vulnerabilities.

### Guiding Principles
* Changelogs are for humans, not machines.
* There should be an entry for every single version.
* The same types of changes should be grouped.
* Versions and sections should be linkable.
* The latest version comes first.
* The release date of each version is displayed.
* Mention whether you follow Semantic Versioning.
tools\dbatools\contributing.md
Here, we'll help you understand how to contribute to the project, and talk about fun stuff like styles and guidelines.
# Contributing
Let's sum this up saying that we'd love your help. We're slowly getting ready for the 1.0 release albeit a bit too slowly!

There are several ways to contribute:
 - Create new commands (PowerShell/T-SQL knowledge required)
 - Report bugs (everyone can do it)
 - Tests (Pester knowledge required)
 - Documentation: functions, website, this guide, everything can be improved (everyone can)
 - Code review (PowerShell/T-SQL knowledge required)

If you wanna help reaching 1.0
   - Standardize param names (@wsmelton)
   - Create tests for existing functions (@cl and @niphlod)
   - Review existing function documentation (@alevyinroc or @gbargsley)
   - Prepare for 1.0 with "code style" (Bill of Health, more on that later)

We strive to make any area doubtless. In any case, the Slack channel is pretty active and every area has one (or more) volunteers to refer to in case of doubts.

## Documentation
Documentation is really the area we welcome any help possible. The documentation refers to both the CBH (Comment Based Help) and the [website documentation](https://dbatools.io/functions). The CBH documentation is included with each command and is the content you see when you run `Get-Help Function-Name`. If any of that content is not clear enough or if the examples in the functions are not working, you should say so (e.g. raise an issue on GitHub or comment in Slack). Even if you are a casual user or a PowerShell newbie, we need your angle to make it as straight forward and clear as possible.

## Contribute New Commands
Start out reviewing the [list of functions on the website](https://dbatools.io/functions/), or pulling the list from the module with `Get-Command -Module dbatools -CommandType Function | Out-GridView`. If you find something similar already exists, open [a new issue on GitHub](https://GitHub.com/sqlcollaborative/dbatools/issues/new) to request an enhancement to that command. New ideas already accepted can be found on [Feature](https://github.com/sqlcollaborative/dbatools/labels/Feature) tagged issues. If nothing similar pops up, either ping @cl on Slack with your idea about the new command or open a new issue on GitHub with details or requirements you need.

## Report Bugs
[Open a new issue](https://dbatools.io/new-issue/) on GitHub and fill in all the details. The title should report the affected function, followed by a brief description (e.g. _Get-DbaDatabase - Add property x to default view_). The provided template holds most of the details coders need to fix the issue.

## Fix Bugs
We have a [step-by-step guide](https://dbatools.io/firstpull) if you don't know Github enough.
[Open a PR](https://GitHub.com/sqlcollaborative/dbatools/pulls) targeting ideally just one ps1 file (the PR needs to target the *development* branch), with the name of the function being fixed as a title. Everyone will chime in reviewing the code and either approve the PR or request changes. The more targeted and focused the PR, the easier to merge, the fastest to go into the next release. Keep them as simple as possible to speed up the process.

## Standardize Parameters and Variables
As a reference: when we refer to parameters these are the `$SqlInstance` type variables within the `param()` block that allow a function to accept input. A variable will be any `$whateverName` used within a function's code.

We chose to follow the standards below when creating parameters and variables for a function:

1) Any variable used in the parameter block must have first letter of each word capitalized. (e.g. `$SqlInstance`, `$ExcludeLogin`)
2) Any variable used in the parameter block **is required** to be singular.
3) Any variable not part of the parameter block, that is multiple words, will follow the camelCase format. (e.g. `$currentLogin`, `$dbLogin`)
4) Refrain from using single character variable names (e.g. `$i` or `$x`). Try to make them "readable" in the sense that if someone sees the variable name they can get a hint what it presents (e.g. `$db`, `$operatorName`).

When you are working with "objects" in SQL Server, say with databases, what variable name you use should be based on what operation you are doing. You can find examples of various situations in the current code of the module to see more detailed examples. As an example: in situations where you are looping over the databases for an instance, try to use a plural variable name for the collection and then single or abbreviated name in the loop for each object of that collection. e.g. `foreach ($db in $databases) {...`.

[This page](https://github.com/sqlcollaborative/dbatools/wiki/Standard-Documentation) sums up what we currently use. We aim at standardizing and reducing to a set of self-documenting and reusable parameters. If you have any questions around the above do not hesitate to ask in Slack.

## Standardize formatting and indentation

We favour consistency throughout the project and accept PRs coming from anybody. Just know that you can reformat your new function leveraging Invoke-DbaFormatter which does the groundwork for you.

## Tests
Remember that tests are needed to make sure dbatools code behaves properly. The ultimate goal is for any user to be able to run dbatools' tests within their environment and, depending on the result, be sure everything works as expected. Dbatools works on a matrix of environments that will hardly be fully covered by a Continuous Integration system. That being said, we have AppVeyor (see later) set up to run at each and every commit.

### How to write tests
To save resources and be more flexible, we split tests with tags into two main categories, "UnitTests" and "IntegrationTests". Below is a starting list of things to consider when writing your test:
- "UnitTests" do not require an instance to be up and running, and are easily the most flexible to be ran on every user computer. - "IntegrationTests" instead require one or more active instances, and there is a bit of setup to do in order to run them.
- Every one of the "IntegrationTests" may need to create a resource (e.g. a database).
- Every resource should be named with the "dbatoolsci_" prefix. _The test should attempt to clean up after itself leaving a pristine environment._
- Try to write tests thinking they may run in each and every user's test environment.

The dbatools-templates repository holds examples, but you can also inspect/copy/cannibalize existing tests. You'll see that every test file is named with a simple convention _Verb-Noun*.Tests.ps1_, and this is required by [Pester](https://GitHub.com/pester/Pester), which is the de-facto standard for running tests in PowerShell.

Tests make sure a "contract" is made between the code and its behavior: once a test is formalized, changes to the code itself or enhancement will be written making sure existing functionality is retained, making the entire dbatools experience more stable.

TODO: how to run tests in your environment, tests\manual.pester.ps1

### AppVeyor setup

AppVeyor is hooked up to test any commit, including PRs. Each commit triggers 5 builds, each referred to as a "scenario":
 - 2008R2 : a server with a single SQL Server 2008 R2 Express Edition instance available ($script:instance1)
 - 2016 : a server with a single SQL Server 2016 Developer Edition instance available ($script:instance2)
 - 2016_service: used to test service restarts
 - 2016_2017 : a server with two instances available, 2016 and 2017 Developer Edition
 - default: a server with two instances available, one SQL Server 2008 R2 Express Edition and a SQL Server 2016 Developer Edition

Builds are split among "scenario"(s) because not every test requires everything to be up and running, and resources on AppVeyor are constrained.

Ideally:
 1) Whenever possible, write UnitTests.
 2) You should write IntegrationTests ideally running in **EITHER** the 2008R2 or the 2016 "scenario".
 3) Default and 216_2017 are the most resource constrained and are left to run the Copy-* commands which are the only ones **needing** two active instances.
 4) If you want to write tests that, e.g, target **BOTH** 2008R2 and 2016, try to avoid writing tests that need both instances to be active at the same time.

AppVeyor is set up to recognize what "scenario" is required by your test, simply inspecting for the presence of combinations of "$script:instance1", "$script:instance2" and "$script:instance3". If you need to fall into case (4), write two test files, e.g. _Get-DbaFoo.first.Tests.ps1 (targeting $script:instance1 only) and _Get-DbaFoo.second.Tests.ps1_ (targeting $script:instance2 only). If you don't want to wait for the entire test suite to run (i.e. you need to run only Get-DbaFoo on AppVeyor), you can use a "magic command" within the commit message, namely `(do Get-DbaFoo)` . This will run only test files within the test folder matching this mask `tests\*Get-DbaFoo*.Tests.ps1`.

TODO: how to run your own AppVeyor before pushing a PR

### Code Coverage, AKA improving tests
A recent introduction in our CI pipeline is code coverage. [Dbatools' CodeCov](https://codecov.io/gh/sqlcollaborative/dbatools/branch/development) shows the percentage of the coverage. Each commit on GitHub triggers a build on AppVeyor. Every build on AppVeyor triggers a code coverage calculation, which is reported to codecov.io for public consumption. The more code covered the more stable the code will be. Once it reaches 100%, you can be pretty sure there will be zero surprises when you'll use the command.

If you want to start contributing new tests, choose the ones with no coverage. You can also inspect functions with low coverage and improve existing tests (https://dbatools.io/improving-tests/)


## Bill of Health

In order to reach 1.0, on top of everything discussed above, we choose to wait for each and every command to adhere to a fixed set of standards. Given most of those "checks" are on a function-by-function basis (with one or more activities tied to each "check"), we came up with the "Bill of Health". You can find it bill at [sqlcollaborative.github.io/boh](https://sqlcollaborative.github.io/boh).

When each and every function is healthy enough, the module itself will be ready for 1.0 release. We may continue to use the same approach (with different checks) for later releases.

There are a few checks which need a core developer to manually sign off the "check", but there are a lot everyone else can fix too, namely ScriptAnalyzer and CodeCoverage.
tools\dbatools\dbatools.psd1
#
# Module manifest for module 'dbatools'
#
# Generated by: Chrissy LeMaire
#
# Generated on: 9/8/2015
#
@{

    # Script module or binary module file associated with this manifest.
    RootModule             = 'dbatools.psm1'

    # Version number of this module.
    ModuleVersion          = '0.9.737'

    # ID used to uniquely identify this module
    GUID                   = '9d139310-ce45-41ce-8e8b-d76335aa1789'

    # Author of this module
    Author                 = 'Chrissy LeMaire'

    # Company or vendor of this module
    CompanyName            = 'dbatools.io'

    # Copyright statement for this module
    Copyright              = 'Copyright (c) 2018 by dbatools, licensed under MIT'

    # Description of the functionality provided by this module
    Description            = "The community module that enables SQL Server Pros to automate database development and server administration"

    # Minimum version of the Windows PowerShell engine required by this module
    PowerShellVersion      = '3.0'

    # Name of the Windows PowerShell host required by this module
    PowerShellHostName     = ''

    # Minimum version of the Windows PowerShell host required by this module
    PowerShellHostVersion  = ''

    # Minimum version of the .NET Framework required by this module
    DotNetFrameworkVersion = ''

    # Minimum version of the common language runtime (CLR) required by this module
    CLRVersion             = ''

    # Processor architecture (None, X86, Amd64, IA64) required by this module
    ProcessorArchitecture  = ''

    # Modules that must be imported into the global environment prior to importing this module
    RequiredModules        = @()

    # Assemblies that must be loaded prior to importing this module
    RequiredAssemblies     = @()

    # Script files () that are run in the caller's environment prior to importing this module
    ScriptsToProcess       = @()

    # Type files (xml) to be loaded when importing this module
    TypesToProcess         = @("xml\dbatools.Types.ps1xml")

    # Format files (xml) to be loaded when importing this module
    # "xml\dbatools.Format.ps1xml"
    FormatsToProcess       = @("xml\dbatools.Format.ps1xml")

    # Modules to import as nested modules of the module specified in ModuleToProcess
    NestedModules          = @()

    # Functions to export from this module
    # Specific functions to export for Core, etc are also found in psm1
    # FunctionsToExport specifically helps with AUTO-LOADING so do not remove
    FunctionsToExport      = @(
        'Start-DbaMigration',
        'Copy-DbaDatabase',
        'Copy-DbaLogin',
        'Copy-DbaAgentServer',
        'Copy-DbaSpConfigure',
        'Copy-DbaDbMail',
        'Copy-DbaDbAssembly',
        'Copy-DbaAgentSchedule',
        'Copy-DbaAgentOperator',
        'Copy-DbaAgentJob',
        'Copy-DbaCustomError',
        'Copy-DbaServerAuditSpecification',
        'Copy-DbaEndpoint',
        'Copy-DbaServerAudit',
        'Copy-DbaServerRole',
        'Copy-DbaResourceGovernor',
        'Copy-DbaXESession',
        'Copy-DbaBackupDevice',
        'Copy-DbaServerTrigger',
        'Copy-DbaCmsRegServer',
        'Copy-DbaSysDbUserObject',
        'Copy-DbaAgentProxy',
        'Copy-DbaAgentAlert',
        'Get-DbaDetachedDatabaseInfo',
        'Restore-DbaBackupFromDirectory',
        'Copy-DbaAgentJobCategory',
        'Test-DbaPath',
        'Export-DbaLogin',
        'Watch-DbaDbLogin',
        'Expand-DbaDbLogFile',
        'Test-DbaMigrationConstraint',
        'Test-DbaNetworkLatency',
        'Find-DbaDuplicateIndex',
        'Remove-DbaDatabaseSafely',
        'Set-DbaTempdbConfig',
        'Test-DbaTempdbConfig',
        'Repair-DbaDbOrphanUser',
        'Remove-DbaDbOrphanUser',
        'Find-DbaDbUnusedIndex',
        'Get-DbaDbSpace',
        'Test-DbaDbOwner',
        'Set-DbaDbOwner',
        'Test-DbaJobOwner',
        'Set-DbaAgentJobOwner',
        'Test-DbaDbVirtualLogFile',
        'Get-DbaDbRestoreHistory',
        'Get-DbaTcpPort',
        'Test-DbaDbCompatibility',
        'Test-DbaDbCollation',
        'Test-DbaConnectionAuthScheme',
        'Test-DbaServerName',
        'Repair-DbaServerName',
        'Stop-DbaProcess',
        'Find-DbaOrphanedFile',
        'Get-DbaAvailabilityGroup',
        'Get-DbaLastGoodCheckDb',
        'Get-DbaProcess',
        'Get-DbaRunningJob',
        'Set-DbaMaxDop',
        'Test-DbaDbRecoveryModel',
        'Test-DbaMaxDop',
        'Remove-DbaBackup',
        'Get-DbaPermission',
        'Get-DbaLastBackup',
        'Connect-DbaInstance',
        'Get-DbaBackupHistory',
        'Read-DbaBackupHeader',
        'Test-DbaLastBackup',
        'Get-DbaMaxMemory',
        'Set-DbaMaxMemory',
        'Get-DbaDbSnapshot',
        'Remove-DbaDbSnapshot',
        'Get-DbaDbRoleMember',
        'Get-DbaServerRoleMember',
        'Resolve-DbaNetworkName',
        'Export-DbaAvailabilityGroup',
        'Write-DbaDataTable',
        'New-DbaDbSnapshot',
        'Restore-DbaDbSnapshot',
        'Get-DbaServerTrigger',
        'Get-DbaDbTrigger',
        'Get-DbaDbState',
        'Set-DbaDbState',
        'Get-DbaHelpIndex',
        'Get-DbaAgentAlert',
        'Get-DbaAgentOperator',
        'Get-DbaSpConfigure',
        'Rename-DbaLogin',
        'Find-DbaAgentJob',
        'Find-DbaDatabase',
        'Get-DbaXESession',
        'Test-DbaOptimizeForAdHoc',
        'Find-DbaStoredProcedure',
        'Measure-DbaBackupThroughput',
        'Get-DbaDatabase',
        'Find-DbaUserObject',
        'Get-DbaDependency',
        'Find-DbaCommand',
        'Backup-DbaDatabase',
        'New-DbaDirectory',
        'Get-DbaDbQueryStoreOption',
        'Set-DbaDbQueryStoreOption',
        'Restore-DbaDatabase',
        'Copy-DbaDbQueryStoreOption',
        'Get-DbaExecutionPlan',
        'Export-DbaExecutionPlan',
        'Set-DbaSpConfigure',
        'Test-DbaIdentityUsage',
        'Get-DbaDbAssembly',
        'Get-DbaAgentJob',
        'Get-DbaCustomError',
        'Get-DbaCredential',
        'Get-DbaBackupDevice',
        'Get-DbaAgentProxy',
        'Get-DbaDbEncryption',
        'Remove-DbaDatabase',
        'Get-DbaQueryExecutionTime',
        'Get-DbaTempdbUsage',
        'Find-DbaDbGrowthEvent',
        'Test-DbaLinkedServerConnection',
        'Get-DbaDbFile',
        'Read-DbaTransactionLog',
        'Get-DbaDbTable',
        'Invoke-DbaDbShrink',
        'Get-DbaEstimatedCompletionTime',
        'Get-DbaLinkedServer',
        'New-DbaAgentJob',
        'Get-DbaLogin',
        'New-DbaScriptingOption',
        'Save-DbaDiagnosticQueryScript',
        'Invoke-DbaDiagnosticQuery',
        'Export-DbaDiagnosticQuery',
        'Invoke-DbaWhoIsActive',
        'Set-DbaAgentJob',
        'Remove-DbaAgentJob',
        'New-DbaAgentJobStep',
        'Set-DbaAgentJobStep',
        'Remove-DbaAgentJobStep',
        'New-DbaAgentSchedule',
        'Set-DbaAgentSchedule',
        'Remove-DbaAgentSchedule',
        'Backup-DbaDbCertificate',
        'Get-DbaDbCertificate',
        'Get-DbaEndpoint',
        'Get-DbaDbMasterKey',
        'Get-DbaSchemaChangeHistory',
        'Get-DbaServerAudit',
        'Get-DbaServerAuditSpecification',
        'Get-DbaProductKey',
        'Get-DbatoolsLog',
        'Restore-DbaDbCertificate',
        'New-DbaDbCertificate',
        'New-DbaDbMasterKey',
        'New-DbaServiceMasterKey',
        'Remove-DbaDbCertificate',
        'Remove-DbaDbMasterKey',
        'New-DbaConnectionStringBuilder',
        'Get-DbaInstanceProperty',
        'Get-DbaInstanceUserOption',
        'New-DbaConnectionString',
        'Get-DbaAgentSchedule',
        'Read-DbaTraceFile',
        'Get-DbaServerInstallDate',
        'Backup-DbaDbMasterKey',
        'Get-DbaAgentJobHistory',
        'Get-DbaMaintenanceSolutionLog',
        'Invoke-DbaDbLogShipRecovery',
        'Find-DbaTrigger',
        'Find-DbaView',
        'Invoke-DbaDbUpgrade',
        'Get-DbaDbUser',
        'Get-DbaAgentLog',
        'Get-DbaDbMailLog',
        'Get-DbaDbMailHistory',
        'Get-DbaDbView',
        'Get-DbaDbUdf',
        'Get-DbaDbPartitionFunction',
        'Get-DbaDbPartitionScheme',
        'Get-DbaDefaultPath',
        'Get-DbaDbStoredProcedure',
        'Test-DbaDbCompression',
        'Mount-DbaDatabase',
        'Dismount-DbaDatabase',
        'Get-DbaAgReplica',
        'Get-DbaAgDatabase',
        'Get-DbaModule',
        'Sync-DbaLoginPermission',
        'New-DbaCredential',
        'Get-DbaFile',
        'Set-DbaDbCompression',
        'Get-DbaTraceFlag',
        'Invoke-DbaCycleErrorLog',
        'Get-DbaAvailableCollation',
        'Get-DbaUserPermission',
        'Get-DbaAgHadr',
        'Find-DbaSimilarTable',
        'Get-DbaTrace',
        'Get-DbaSuspectPage',
        'Get-DbaWaitStatistic',
        'Clear-DbaWaitStatistics',
        'Get-DbaTopResourceUsage',
        'New-DbaLogin',
        'Get-DbaAgListener',
        'Invoke-DbaDbClone',
        'Disable-DbaTraceFlag',
        'Enable-DbaTraceFlag',
        'Start-DbaAgentJob',
        'Stop-DbaAgentJob',
        'New-DbaAgentProxy',
        'Test-DbaDbLogShipStatus',
        'Get-DbaXESessionTarget',
        'New-DbaXESmartTargetResponse',
        'New-DbaXESmartTarget',
        'Get-DbaDbVirtualLogFile',
        'Get-DbaBackupInformation',
        'Start-DbaXESession',
        'Stop-DbaXESession',
        'Set-DbaDbRecoveryModel',
        'Get-DbaDbRecoveryModel',
        'Get-DbaWaitingTask',
        'Remove-DbaDbUser',
        'Get-DbaDump',
        'Invoke-DbaAdvancedRestore',
        'Format-DbaBackupInformation',
        'Get-DbaAgentJobStep',
        'Test-DbaBackupInformation',
        'Invoke-DbaBalanceDataFiles',
        'Select-DbaBackupInformation',
        'Publish-DbaDacPackage',
        'Copy-DbaDbTableData',
        'Invoke-DbaQuery',
        'Remove-DbaLogin',
        'Get-DbaAgentJobCategory',
        'New-DbaAgentJobCategory',
        'Remove-DbaAgentJobCategory',
        'Set-DbaAgentJobCategory',
        'Get-DbaDbRole',
        'Get-DbaServerRole',
        'Find-DbaBackup',
        'Remove-DbaXESession',
        'New-DbaXESession',
        'Get-DbaXEStore',
        'New-DbaXESmartTableWriter',
        'New-DbaXESmartReplay',
        'New-DbaXESmartEmail',
        'New-DbaXESmartQueryExec',
        'Start-DbaXESmartTarget',
        'Get-DbaDbOrphanUser',
        'Get-DbaOpenTransaction',
        'Get-DbaDbLogShipError',
        'Test-DbaBuild',
        'Get-DbaXESessionTemplate',
        'ConvertTo-DbaXESession',
        'Start-DbaTrace',
        'Stop-DbaTrace',
        'Remove-DbaTrace',
        'Set-DbaLogin',
        'Copy-DbaXESessionTemplate',
        'Get-DbaXEObject',
        'ConvertTo-DbaDataTable',
        'Find-DbaDisabledIndex',
        'Get-DbaXESmartTarget',
        'Remove-DbaXESmartTarget',
        'Stop-DbaXESmartTarget',
        'Get-DbaCmsRegServerGroup',
        'New-DbaDbUser',
        'Measure-DbaDiskSpaceRequirement',
        'New-DbaXESmartCsvWriter',
        'Invoke-DbaXeReplay',
        'Find-DbaInstance',
        'Test-DbaDiskSpeed',
        'Get-DbaDbExtentDiff',
        'Read-DbaAuditFile',
        'Get-DbaDbCompression',
        'Invoke-DbaDbDecryptObject',
        'Get-DbaDbForeignKey',
        'Get-DbaDbCheckConstraint',
        'Set-DbaAgentAlert',
        'Get-DbaWaitResource',
        'Get-DbaDbPageInfo',
        'Get-DbaConnection',
        'Test-DbaLoginPassword',
        'Get-DbaErrorLogConfig',
        'Set-DbaErrorLogConfig',
        'Get-DbaPlanCache',
        'Clear-DbaPlanCache',
        'ConvertTo-DbaTimeline',
        'Get-DbaDbMail',
        'Get-DbaDbMailAccount',
        'Get-DbaDbMailProfile',
        'Get-DbaDbMailConfig',
        'Get-DbaDbMailServer',
        'Get-DbaResourceGovernor',
        'Get-DbaRgResourcePool',
        'Get-DbaRgWorkloadGroup',
        'Get-DbaRgClassifierFunction',
        'Export-DbaInstance',
        'Invoke-DbatoolsRenameHelper',
        'Measure-DbatoolsImport',
        'Get-DbaDeprecatedFeature',
        'Test-DbaDeprecatedFeature'
        'Get-DbaDbFeatureUsage',
        'Stop-DbaEndpoint',
        'Start-DbaEndpoint',
        'Set-DbaDbMirror',
        'Repair-DbaDbMirror',
        'Remove-DbaEndpoint',
        'Remove-DbaDbMirrorMonitor',
        'Remove-DbaDbMirror',
        'New-DbaEndpoint',
        'Invoke-DbaDbMirroring',
        'Invoke-DbaDbMirrorFailover',
        'Get-DbaDbMirrorMonitor',
        'Get-DbaDbMirror',
        'Add-DbaDbMirrorMonitor',
        'Test-DbaEndpoint',
        'Get-DbaDbSharePoint',
        'Get-DbaDbMemoryUsage',
        'Clear-DbaLatchStatistics',
        'Get-DbaCpuRingBuffer',
        'Get-DbaIoLatency',
        'Get-DbaLatchStatistic',
        'Get-DbaSpinLockStatistic',
        'Add-DbaAgDatabase',
        'Add-DbaAgListener',
        'Add-DbaAgReplica',
        'Grant-DbaAgPermission',
        'Invoke-DbaAgFailover',
        'Join-DbaAvailabilityGroup',
        'New-DbaAvailabilityGroup',
        'Remove-DbaAgDatabase',
        'Remove-DbaAgListener',
        'Remove-DbaAvailabilityGroup',
        'Revoke-DbaAgPermission',
        'Get-DbaDbCompatibility',
        'Set-DbaDbCompatibility',
        'Invoke-DbatoolsFormatter',
        'Remove-DbaAgReplica',
        'Resume-DbaAgDbDataMovement',
        'Set-DbaAgListener',
        'Set-DbaAgReplica',
        'Set-DbaAvailabilityGroup',
        'Set-DbaEndpoint',
        'Suspend-DbaAgDbDataMovement',
        'Sync-DbaAvailabilityGroup',
        'Get-DbaMemoryCondition',
        'Remove-DbaDbBackupRestoreHistory',
        'New-DbaDatabase'
        'New-DbaDacOption',
        'Get-DbaDbccHelp',
        'Get-DbaDbccMemoryStatus',
        'Get-DbaDbccProcCache',
        'Get-DbaDbccUserOption',
        'Get-DbaAgentServer',
        'Set-DbaAgentServer',
        'Invoke-DbaDbccFreeCache',
        'Export-DbatoolsConfig',
        'Import-DbatoolsConfig',
        'Reset-DbatoolsConfig',
        'Unregister-DbatoolsConfig',
        'Join-DbaPath',
        'Resolve-DbaPath',
        'Invoke-DbaDbDataMasking',
        'New-DbaDbMaskingConfig',
        'Get-DbaDbccSessionBuffer',
        'Get-DbaDbccStatistic',
        'Get-DbaDbDbccOpenTran',
        'Invoke-DbaDbccDropCleanBuffer',
        'Invoke-DbaDbDbccCheckConstraint',
        'Invoke-DbaDbDbccCleanTable',
        'Invoke-DbaDbDbccUpdateUsage',
        # noncoresmo
        # SMO issues
        'Export-DbaUser',
        'Get-DbaSsisExecutionHistory',
        'Get-DbaRepDistributor',
        'Get-DbaCmsRegServerStore',
        'Copy-DbaPolicyManagement',
        'Copy-DbaDataCollector',
        'Get-DbaCmsRegServer',
        'Copy-DbaSsisCatalog',
        'New-DbaSsisCatalog',
        'Get-DbaSsisEnvironmentVariable',
        'Get-DbaPbmCategory',
        'Get-DbaPbmCategorySubscription',
        'Get-DbaPbmCondition',
        'Get-DbaPbmObjectSet',
        'Get-DbaPbmPolicy',
        'Get-DbaPbmStore',
        'Add-DbaCmsRegServer',
        'Add-DbaCmsRegServerGroup',
        'Export-DbaCmsRegServer',
        'Import-DbaCmsRegServer',
        'Move-DbaCmsRegServer',
        'Move-DbaCmsRegServerGroup',
        'Remove-DbaCmsRegServer',
        'Remove-DbaCmsRegServerGroup',
        'Get-DbaRepPublication',
        'Test-DbaRepLatency',
        'Export-DbaRepServerSetting',
        'Get-DbaRepServer',
        # windowsonly
        # solvable filesystem issues or other workarounds
        'Install-DbaSqlWatch',
        'Uninstall-DbaSqlWatch',
        'Get-DbaRegistryRoot',
        'Install-DbaMaintenanceSolution',
        'New-DbatoolsSupportPackage',
        'Export-DbaScript',
        'Get-DbaAgentJobOutputFile',
        'Set-DbaAgentJobOutputFile',
        'Get-DbaBuildReference',
        'New-DbaDacProfile'
        'Import-DbaXESessionTemplate',
        'Export-DbaXESessionTemplate',
        'Import-DbaSpConfigure',
        'Export-DbaSpConfigure'
        'Update-Dbatools',
        'Install-DbaWhoIsActive',
        'Install-DbaFirstResponderKit',
        'Read-DbaXEFile',
        'Watch-DbaXESession',
        'Test-DbaMaxMemory', # can be fixed by not testing remote when linux is detected
        'Rename-DbaDatabase', # can maybebe fixed by not remoting when linux is detected
        # CM and Windows functions
        'Update-DbaInstance',
        'Invoke-DbaPfRelog',
        'Get-DbaPfDataCollectorCounter',
        'Get-DbaPfDataCollectorCounterSample',
        'Get-DbaPfDataCollector',
        'Get-DbaPfDataCollectorSet',
        'Start-DbaPfDataCollectorSet',
        'Stop-DbaPfDataCollectorSet',
        'Export-DbaPfDataCollectorSetTemplate',
        'Get-DbaPfDataCollectorSetTemplate',
        'Import-DbaPfDataCollectorSetTemplate',
        'Remove-DbaPfDataCollectorSet',
        'Add-DbaPfDataCollectorCounter',
        'Remove-DbaPfDataCollectorCounter',
        'Get-DbaPfAvailableCounter',
        'Export-DbaXECsv',
        'Get-DbaOperatingSystem',
        'Get-DbaComputerSystem',
        'Set-DbaPrivilege',
        'Set-DbaTcpPort',
        'Set-DbaCmConnection',
        'Get-DbaUptime',
        'Get-DbaMemoryUsage',
        'Clear-DbaConnectionPool',
        'Get-DbaLocaleSetting',
        'Get-DbaFilestream',
        'Enable-DbaFilestream',
        'Disable-DbaFilestream',
        'Get-DbaCpuUsage',
        'Get-DbaPowerPlan',
        'Get-DbaWsfcAvailableDisk',
        'Get-DbaWsfcCluster',
        'Get-DbaWsfcDisk',
        'Get-DbaWsfcNetwork',
        'Get-DbaWsfcNetworkInterface',
        'Get-DbaWsfcNode',
        'Get-DbaWsfcResource',
        'Get-DbaWsfcResourceType',
        'Get-DbaWsfcRole',
        'Get-DbaWsfcSharedVolume',
        'Export-DbaCredential',
        'Export-DbaLinkedServer',
        'Get-DbaFeature',
        'Update-DbaServiceAccount',
        'Remove-DbaClientAlias',
        'Disable-DbaAgHadr',
        'Enable-DbaAgHadr',
        'Stop-DbaService',
        'Start-DbaService',
        'Restart-DbaService',
        'New-DbaClientAlias',
        'Get-DbaClientAlias',
        'Remove-DbaNetworkCertificate',
        'Enable-DbaForceNetworkEncryption',
        'Disable-DbaForceNetworkEncryption',
        'Get-DbaForceNetworkEncryption',
        'Remove-DbaComputerCertificate',
        'New-DbaComputerCertificate',
        'Get-DbaComputerCertificate',
        'Add-DbaComputerCertificate',
        'Get-DbaNetworkCertificate',
        'Set-DbaNetworkCertificate',
        'Invoke-DbaDbLogShipping',
        'New-DbaCmConnection',
        'Get-DbaCmConnection',
        'Remove-DbaCmConnection',
        'Test-DbaCmConnection',
        'Get-DbaCmObject',
        'Set-DbaStartupParameter',
        'Get-DbaNetworkActivity',
        'Get-DbaServerProtocol'
        'Watch-DbaUpdate',
        'Uninstall-DbaWatchUpdate',
        'Install-DbaWatchUpdate',
        'Get-DbaPrivilege',
        'Get-DbaMsdtc',
        'Get-DbaPageFileSetting',
        'Copy-DbaCredential',
        'Test-DbaConnection',
        'Reset-DbaAdmin',
        'Copy-DbaLinkedServer',
        'Get-DbaDiskSpace',
        'Test-DbaDiskAllocation',
        'Test-DbaPowerPlan',
        'Set-DbaPowerPlan',
        'Test-DbaDiskAlignment',
        'Get-DbaStartupParameter',
        'Get-DbaSpn',
        'Test-DbaSpn',
        'Set-DbaSpn',
        'Remove-DbaSpn',
        'Get-DbaService',
        'Get-DbaClientProtocol',
        'Get-DbaWindowsLog',
        # WPF
        'Show-DbaServerFileSystem',
        'Show-DbaDbList',
        # AD?
        'Test-DbaWindowsLogin',
        'Find-DbaLoginInGroup',
        # 3rd party non-core DLL or exe
        'Import-DbaCsv',
        'Export-DbaDacPackage', # relies on sqlpackage.exe
        # Config system
        'Get-DbatoolsConfig',
        'Get-DbatoolsConfigValue',
        'Register-DbatoolsConfig',
        # Unknown
        'Get-DbaErrorLog',
        'Get-DbaManagementObject',
        'Test-DbaManagementObject'
    )

    # Cmdlets to export from this module
    CmdletsToExport        = @(
        'Select-DbaObject',
        'Set-DbatoolsConfig'
    )

    # Variables to export from this module
    VariablesToExport      = ''

    # Aliases to export from this module
    # Aliases are stored in dbatools.psm1
    # KEEP Detach-DbaDatabase, Dismount-DbaDatabase and Start-SqlMigration FOREVER
    AliasesToExport        = '*'

    # List of all modules packaged with this module
    ModuleList             = @()

    # List of all files packaged with this module
    FileList               = ''

    PrivateData            = @{
        # PSData is module packaging and gallery metadata embedded in PrivateData
        # It's for rebuilding PowerShellGet (and PoshCode) NuGet-style packages
        # We had to do this because it's the only place we're allowed to extend the manifest
        # https://connect.microsoft.com/PowerShell/feedback/details/421837
        PSData = @{
            # The primary categorization of this module (from the TechNet Gallery tech tree).
            Category     = "Databases"

            # Keyword tags to help users find this module via navigations and search.
            Tags         = @('sqlserver', 'migrations', 'sql', 'dba', 'databases', 'mac', 'linux', 'core')

            # The web address of an icon which can be used in galleries to represent this module
            IconUri      = "https://dbatools.io/logo.png"

            # The web address of this module's project or support homepage.
            ProjectUri   = "https://dbatools.io"

            # The web address of this module's license. Points to a page that's embeddable and linkable.
            LicenseUri   = "https://opensource.org/licenses/MIT"

            # Release notes for this particular version of the module
            ReleaseNotes = "https://dbatools.io/changelog"

            # If true, the LicenseUrl points to an end-user license (not just a source license) which requires the user agreement before use.
            # RequireLicenseAcceptance = ""

            # Indicates this is a pre-release/testing version of the module.
            IsPrerelease = 'True'
        }
    }
}
# SIG # Begin signature block
# MIIcYgYJKoZIhvcNAQcCoIIcUzCCHE8CAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUHTHnrjlRca7RRsDMrpixM0aG
# iYaggheRMIIFGjCCBAKgAwIBAgIQAsF1KHTVwoQxhSrYoGRpyjANBgkqhkiG9w0B
# AQsFADByMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYD
# VQQLExB3d3cuZGlnaWNlcnQuY29tMTEwLwYDVQQDEyhEaWdpQ2VydCBTSEEyIEFz
# c3VyZWQgSUQgQ29kZSBTaWduaW5nIENBMB4XDTE3MDUwOTAwMDAwMFoXDTIwMDUx
# MzEyMDAwMFowVzELMAkGA1UEBhMCVVMxETAPBgNVBAgTCFZpcmdpbmlhMQ8wDQYD
# VQQHEwZWaWVubmExETAPBgNVBAoTCGRiYXRvb2xzMREwDwYDVQQDEwhkYmF0b29s
# czCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAI8ng7JxnekL0AO4qQgt
# Kr6p3q3SNOPh+SUZH+SyY8EA2I3wR7BMoT7rnZNolTwGjUXn7bRC6vISWg16N202
# 1RBWdTGW2rVPBVLF4HA46jle4hcpEVquXdj3yGYa99ko1w2FOWzLjKvtLqj4tzOh
# K7wa/Gbmv0Si/FU6oOmctzYMI0QXtEG7lR1HsJT5kywwmgcjyuiN28iBIhT6man0
# Ib6xKDv40PblKq5c9AFVldXUGVeBJbLhcEAA1nSPSLGdc7j4J2SulGISYY7ocuX3
# tkv01te72Mv2KkqqpfkLEAQjXgtM0hlgwuc8/A4if+I0YtboCMkVQuwBpbR9/6ys
# Z+sCAwEAAaOCAcUwggHBMB8GA1UdIwQYMBaAFFrEuXsqCqOl6nEDwGD5LfZldQ5Y
# MB0GA1UdDgQWBBRcxSkFqeA3vvHU0aq2mVpFRSOdmjAOBgNVHQ8BAf8EBAMCB4Aw
# EwYDVR0lBAwwCgYIKwYBBQUHAwMwdwYDVR0fBHAwbjA1oDOgMYYvaHR0cDovL2Ny
# bDMuZGlnaWNlcnQuY29tL3NoYTItYXNzdXJlZC1jcy1nMS5jcmwwNaAzoDGGL2h0
# dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9zaGEyLWFzc3VyZWQtY3MtZzEuY3JsMEwG
# A1UdIARFMEMwNwYJYIZIAYb9bAMBMCowKAYIKwYBBQUHAgEWHGh0dHBzOi8vd3d3
# LmRpZ2ljZXJ0LmNvbS9DUFMwCAYGZ4EMAQQBMIGEBggrBgEFBQcBAQR4MHYwJAYI
# KwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmRpZ2ljZXJ0LmNvbTBOBggrBgEFBQcwAoZC
# aHR0cDovL2NhY2VydHMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0U0hBMkFzc3VyZWRJ
# RENvZGVTaWduaW5nQ0EuY3J0MAwGA1UdEwEB/wQCMAAwDQYJKoZIhvcNAQELBQAD
# ggEBANuBGTbzCRhgG0Th09J0m/qDqohWMx6ZOFKhMoKl8f/l6IwyDrkG48JBkWOA
# QYXNAzvp3Ro7aGCNJKRAOcIjNKYef/PFRfFQvMe07nQIj78G8x0q44ZpOVCp9uVj
# sLmIvsmF1dcYhOWs9BOG/Zp9augJUtlYpo4JW+iuZHCqjhKzIc74rEEiZd0hSm8M
# asshvBUSB9e8do/7RhaKezvlciDaFBQvg5s0fICsEhULBRhoyVOiUKUcemprPiTD
# xh3buBLuN0bBayjWmOMlkG1Z6i8DUvWlPGz9jiBT3ONBqxXfghXLL6n8PhfppBhn
# daPQO8+SqF5rqrlyBPmRRaTz2GQwggUwMIIEGKADAgECAhAECRgbX9W7ZnVTQ7Vv
# lVAIMA0GCSqGSIb3DQEBCwUAMGUxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdp
# Q2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xJDAiBgNVBAMTG0Rp
# Z2lDZXJ0IEFzc3VyZWQgSUQgUm9vdCBDQTAeFw0xMzEwMjIxMjAwMDBaFw0yODEw
# MjIxMjAwMDBaMHIxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMx
# GTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xMTAvBgNVBAMTKERpZ2lDZXJ0IFNI
# QTIgQXNzdXJlZCBJRCBDb2RlIFNpZ25pbmcgQ0EwggEiMA0GCSqGSIb3DQEBAQUA
# A4IBDwAwggEKAoIBAQD407Mcfw4Rr2d3B9MLMUkZz9D7RZmxOttE9X/lqJ3bMtdx
# 6nadBS63j/qSQ8Cl+YnUNxnXtqrwnIal2CWsDnkoOn7p0WfTxvspJ8fTeyOU5JEj
# lpB3gvmhhCNmElQzUHSxKCa7JGnCwlLyFGeKiUXULaGj6YgsIJWuHEqHCN8M9eJN
# YBi+qsSyrnAxZjNxPqxwoqvOf+l8y5Kh5TsxHM/q8grkV7tKtel05iv+bMt+dDk2
# DZDv5LVOpKnqagqrhPOsZ061xPeM0SAlI+sIZD5SlsHyDxL0xY4PwaLoLFH3c7y9
# hbFig3NBggfkOItqcyDQD2RzPJ6fpjOp/RnfJZPRAgMBAAGjggHNMIIByTASBgNV
# HRMBAf8ECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIBhjATBgNVHSUEDDAKBggrBgEF
# BQcDAzB5BggrBgEFBQcBAQRtMGswJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmRp
# Z2ljZXJ0LmNvbTBDBggrBgEFBQcwAoY3aHR0cDovL2NhY2VydHMuZGlnaWNlcnQu
# Y29tL0RpZ2lDZXJ0QXNzdXJlZElEUm9vdENBLmNydDCBgQYDVR0fBHoweDA6oDig
# NoY0aHR0cDovL2NybDQuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0QXNzdXJlZElEUm9v
# dENBLmNybDA6oDigNoY0aHR0cDovL2NybDMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0
# QXNzdXJlZElEUm9vdENBLmNybDBPBgNVHSAESDBGMDgGCmCGSAGG/WwAAgQwKjAo
# BggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNlcnQuY29tL0NQUzAKBghghkgB
# hv1sAzAdBgNVHQ4EFgQUWsS5eyoKo6XqcQPAYPkt9mV1DlgwHwYDVR0jBBgwFoAU
# Reuir/SSy4IxLVGLp6chnfNtyA8wDQYJKoZIhvcNAQELBQADggEBAD7sDVoks/Mi
# 0RXILHwlKXaoHV0cLToaxO8wYdd+C2D9wz0PxK+L/e8q3yBVN7Dh9tGSdQ9RtG6l
# jlriXiSBThCk7j9xjmMOE0ut119EefM2FAaK95xGTlz/kLEbBw6RFfu6r7VRwo0k
# riTGxycqoSkoGjpxKAI8LpGjwCUR4pwUR6F6aGivm6dcIFzZcbEMj7uo+MUSaJ/P
# QMtARKUT8OZkDCUIQjKyNookAv4vcn4c10lFluhZHen6dGRrsutmQ9qzsIzV6Q3d
# 9gEgzpkxYz0IGhizgZtPxpMQBvwHgfqL2vmCSfdibqFT+hKUGIUukpHqaGxEMrJm
# oecYpJpkUe8wggZqMIIFUqADAgECAhADAZoCOv9YsWvW1ermF/BmMA0GCSqGSIb3
# DQEBBQUAMGIxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAX
# BgNVBAsTEHd3dy5kaWdpY2VydC5jb20xITAfBgNVBAMTGERpZ2lDZXJ0IEFzc3Vy
# ZWQgSUQgQ0EtMTAeFw0xNDEwMjIwMDAwMDBaFw0yNDEwMjIwMDAwMDBaMEcxCzAJ
# BgNVBAYTAlVTMREwDwYDVQQKEwhEaWdpQ2VydDElMCMGA1UEAxMcRGlnaUNlcnQg
# VGltZXN0YW1wIFJlc3BvbmRlcjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
# ggEBAKNkXfx8s+CCNeDg9sYq5kl1O8xu4FOpnx9kWeZ8a39rjJ1V+JLjntVaY1sC
# SVDZg85vZu7dy4XpX6X51Id0iEQ7Gcnl9ZGfxhQ5rCTqqEsskYnMXij0ZLZQt/US
# s3OWCmejvmGfrvP9Enh1DqZbFP1FI46GRFV9GIYFjFWHeUhG98oOjafeTl/iqLYt
# WQJhiGFyGGi5uHzu5uc0LzF3gTAfuzYBje8n4/ea8EwxZI3j6/oZh6h+z+yMDDZb
# esF6uHjHyQYuRhDIjegEYNu8c3T6Ttj+qkDxss5wRoPp2kChWTrZFQlXmVYwk/PJ
# YczQCMxr7GJCkawCwO+k8IkRj3cCAwEAAaOCAzUwggMxMA4GA1UdDwEB/wQEAwIH
# gDAMBgNVHRMBAf8EAjAAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMIMIIBvwYDVR0g
# BIIBtjCCAbIwggGhBglghkgBhv1sBwEwggGSMCgGCCsGAQUFBwIBFhxodHRwczov
# L3d3dy5kaWdpY2VydC5jb20vQ1BTMIIBZAYIKwYBBQUHAgIwggFWHoIBUgBBAG4A
# eQAgAHUAcwBlACAAbwBmACAAdABoAGkAcwAgAEMAZQByAHQAaQBmAGkAYwBhAHQA
# ZQAgAGMAbwBuAHMAdABpAHQAdQB0AGUAcwAgAGEAYwBjAGUAcAB0AGEAbgBjAGUA
# IABvAGYAIAB0AGgAZQAgAEQAaQBnAGkAQwBlAHIAdAAgAEMAUAAvAEMAUABTACAA
# YQBuAGQAIAB0AGgAZQAgAFIAZQBsAHkAaQBuAGcAIABQAGEAcgB0AHkAIABBAGcA
# cgBlAGUAbQBlAG4AdAAgAHcAaABpAGMAaAAgAGwAaQBtAGkAdAAgAGwAaQBhAGIA
# aQBsAGkAdAB5ACAAYQBuAGQAIABhAHIAZQAgAGkAbgBjAG8AcgBwAG8AcgBhAHQA
# ZQBkACAAaABlAHIAZQBpAG4AIABiAHkAIAByAGUAZgBlAHIAZQBuAGMAZQAuMAsG
# CWCGSAGG/WwDFTAfBgNVHSMEGDAWgBQVABIrE5iymQftHt+ivlcNK2cCzTAdBgNV
# HQ4EFgQUYVpNJLZJMp1KKnkag0v0HonByn0wfQYDVR0fBHYwdDA4oDagNIYyaHR0
# cDovL2NybDMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0QXNzdXJlZElEQ0EtMS5jcmww
# OKA2oDSGMmh0dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEFzc3VyZWRJ
# RENBLTEuY3JsMHcGCCsGAQUFBwEBBGswaTAkBggrBgEFBQcwAYYYaHR0cDovL29j
# c3AuZGlnaWNlcnQuY29tMEEGCCsGAQUFBzAChjVodHRwOi8vY2FjZXJ0cy5kaWdp
# Y2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURDQS0xLmNydDANBgkqhkiG9w0BAQUF
# AAOCAQEAnSV+GzNNsiaBXJuGziMgD4CH5Yj//7HUaiwx7ToXGXEXzakbvFoWOQCd
# 42yE5FpA+94GAYw3+puxnSR+/iCkV61bt5qwYCbqaVchXTQvH3Gwg5QZBWs1kBCg
# e5fH9j/n4hFBpr1i2fAnPTgdKG86Ugnw7HBi02JLsOBzppLA044x2C/jbRcTBu7k
# A7YUq/OPQ6dxnSHdFMoVXZJB2vkPgdGZdA0mxA5/G7X1oPHGdwYoFenYk+VVFvC7
# Cqsc21xIJ2bIo4sKHOWV2q7ELlmgYd3a822iYemKC23sEhi991VUQAOSK2vCUcIK
# SK+w1G7g9BQKOhvjjz3Kr2qNe9zYRDCCBs0wggW1oAMCAQICEAb9+QOWA63qAArr
# Pye7uhswDQYJKoZIhvcNAQEFBQAwZTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERp
# Z2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEkMCIGA1UEAxMb
# RGlnaUNlcnQgQXNzdXJlZCBJRCBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTIx
# MTExMDAwMDAwMFowYjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IElu
# YzEZMBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEhMB8GA1UEAxMYRGlnaUNlcnQg
# QXNzdXJlZCBJRCBDQS0xMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
# 6IItmfnKwkKVpYBzQHDSnlZUXKnE0kEGj8kz/E1FkVyBn+0snPgWWd+etSQVwpi5
# tHdJ3InECtqvy15r7a2wcTHrzzpADEZNk+yLejYIA6sMNP4YSYL+x8cxSIB8HqIP
# kg5QycaH6zY/2DDD/6b3+6LNb3Mj/qxWBZDwMiEWicZwiPkFl32jx0PdAug7Pe2x
# QaPtP77blUjE7h6z8rwMK5nQxl0SQoHhg26Ccz8mSxSQrllmCsSNvtLOBq6thG9I
# hJtPQLnxTPKvmPv2zkBdXPao8S+v7Iki8msYZbHBc63X8djPHgp0XEK4aH631XcK
# J1Z8D2KkPzIUYJX9BwSiCQIDAQABo4IDejCCA3YwDgYDVR0PAQH/BAQDAgGGMDsG
# A1UdJQQ0MDIGCCsGAQUFBwMBBggrBgEFBQcDAgYIKwYBBQUHAwMGCCsGAQUFBwME
# BggrBgEFBQcDCDCCAdIGA1UdIASCAckwggHFMIIBtAYKYIZIAYb9bAABBDCCAaQw
# OgYIKwYBBQUHAgEWLmh0dHA6Ly93d3cuZGlnaWNlcnQuY29tL3NzbC1jcHMtcmVw
# b3NpdG9yeS5odG0wggFkBggrBgEFBQcCAjCCAVYeggFSAEEAbgB5ACAAdQBzAGUA
# IABvAGYAIAB0AGgAaQBzACAAQwBlAHIAdABpAGYAaQBjAGEAdABlACAAYwBvAG4A
# cwB0AGkAdAB1AHQAZQBzACAAYQBjAGMAZQBwAHQAYQBuAGMAZQAgAG8AZgAgAHQA
# aABlACAARABpAGcAaQBDAGUAcgB0ACAAQwBQAC8AQwBQAFMAIABhAG4AZAAgAHQA
# aABlACAAUgBlAGwAeQBpAG4AZwAgAFAAYQByAHQAeQAgAEEAZwByAGUAZQBtAGUA
# bgB0ACAAdwBoAGkAYwBoACAAbABpAG0AaQB0ACAAbABpAGEAYgBpAGwAaQB0AHkA
# IABhAG4AZAAgAGEAcgBlACAAaQBuAGMAbwByAHAAbwByAGEAdABlAGQAIABoAGUA
# cgBlAGkAbgAgAGIAeQAgAHIAZQBmAGUAcgBlAG4AYwBlAC4wCwYJYIZIAYb9bAMV
# MBIGA1UdEwEB/wQIMAYBAf8CAQAweQYIKwYBBQUHAQEEbTBrMCQGCCsGAQUFBzAB
# hhhodHRwOi8vb2NzcC5kaWdpY2VydC5jb20wQwYIKwYBBQUHMAKGN2h0dHA6Ly9j
# YWNlcnRzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEFzc3VyZWRJRFJvb3RDQS5jcnQw
# gYEGA1UdHwR6MHgwOqA4oDaGNGh0dHA6Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9EaWdp
# Q2VydEFzc3VyZWRJRFJvb3RDQS5jcmwwOqA4oDaGNGh0dHA6Ly9jcmw0LmRpZ2lj
# ZXJ0LmNvbS9EaWdpQ2VydEFzc3VyZWRJRFJvb3RDQS5jcmwwHQYDVR0OBBYEFBUA
# EisTmLKZB+0e36K+Vw0rZwLNMB8GA1UdIwQYMBaAFEXroq/0ksuCMS1Ri6enIZ3z
# bcgPMA0GCSqGSIb3DQEBBQUAA4IBAQBGUD7Jtygkpzgdtlspr1LPUukxR6tWXHvV
# DQtBs+/sdR90OPKyXGGinJXDUOSCuSPRujqGcq04eKx1XRcXNHJHhZRW0eu7NoR3
# zCSl8wQZVann4+erYs37iy2QwsDStZS9Xk+xBdIOPRqpFFumhjFiqKgz5Js5p8T1
# zh14dpQlc+Qqq8+cdkvtX8JLFuRLcEwAiR78xXm8TBJX/l/hHrwCXaj++wc4Tw3G
# XZG5D2dFzdaD7eeSDY2xaYxP+1ngIw/Sqq4AfO6cQg7PkdcntxbuD8O9fAqg7iwI
# VYUiuOsYGk38KiGtSTGDR5V3cdyxG0tLHBCcdxTBnU8vWpUIKRAmMYIEOzCCBDcC
# AQEwgYYwcjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcG
# A1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTExMC8GA1UEAxMoRGlnaUNlcnQgU0hBMiBB
# c3N1cmVkIElEIENvZGUgU2lnbmluZyBDQQIQAsF1KHTVwoQxhSrYoGRpyjAJBgUr
# DgMCGgUAoHgwGAYKKwYBBAGCNwIBDDEKMAigAoAAoQKAADAZBgkqhkiG9w0BCQMx
# DAYKKwYBBAGCNwIBBDAcBgorBgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkq
# hkiG9w0BCQQxFgQU1tNpEWFDQLVeBG2+AD7LBSRfPhcwDQYJKoZIhvcNAQEBBQAE
# ggEAN98Iv/NURzSreXm0rlXX6zn641/7YLcLt3AmnSaYB04vWcK4Jlp94K4VZKLu
# 8TAt/nQdfjTStuvKyxa1l81VaCo1tDTnUbyDdm6DNC0y8Ye/5CXQ6cL+ybtIXxVV
# 8t0sAkNk0tNGW6n2p2lbBuxifYsYqVY5IDYOTwoB/zyDWmOba6F1BCFvdtbS/fyd
# UW4O1WNPxXRiDB+zLtLk0wsERAN/TUj1mukUCXloRXPSAIMMRCl8CQf57uOOyVt4
# 3eiZHGx+iDxXL2wm+K735jH+4VSkZ3bwd/775f9Grte0yshQweREZMs5Ep88TC/e
# euTPZH9WDsksiDy1swLbbdAA1aGCAg8wggILBgkqhkiG9w0BCQYxggH8MIIB+AIB
# ATB2MGIxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNV
# BAsTEHd3dy5kaWdpY2VydC5jb20xITAfBgNVBAMTGERpZ2lDZXJ0IEFzc3VyZWQg
# SUQgQ0EtMQIQAwGaAjr/WLFr1tXq5hfwZjAJBgUrDgMCGgUAoF0wGAYJKoZIhvcN
# AQkDMQsGCSqGSIb3DQEHATAcBgkqhkiG9w0BCQUxDxcNMTkwMTA4MTkwNzM0WjAj
# BgkqhkiG9w0BCQQxFgQUy/vN/kUHKCuz87duUrshy/g8spEwDQYJKoZIhvcNAQEB
# BQAEggEAOoSfgD9mwcEEl6K5YVNz/7OL7f1WHqcM50U3nihJ5SZtRiRwgvN/MRTP
# hxkVE1qKAAY9+P+HrFnRoOrf5U7xcd+LhbnDa56StjBndP9uFulTzHscyCs25U8r
# aZwtlGZbbGp2b4obWNRVujWIrOEgoagzSMSYg2r7j9MRHDXAEKg+KxGdSX9Nvrri
# yd9xLs30sqOPcB2UEFySti4YfpSU0B0cS62Jt1RMMJl8DVSg1gNcH2TXJ7V+Qc29
# HYpA2QVKB4A3MdMjFH+s0KWzIjR+wuTHU1k92NPEBNMsbsFGWIi5QTeMDrG0JhrE
# Jbll65GEqyOoNy67kNOKI6PU09yVaQ==
# SIG # End signature block
tools\dbatools\dbatools.psm1
$start = Get-Date

if (($PSVersionTable.PSVersion.Major -lt 6) -or ($PSVersionTable.Keys -contains "Platform" -and $PSVersionTable.Platform -eq "Win32NT")) {
    $script:isWindows = $true
} else {
    $script:isWindows = $false
}

if ($PSVersionTable.PSVersion.Major -lt 3) {
    # requires doesnt work on modules
    throw "This module only supports PowerShell v3 and above"
}

#region Import helper functions
function Import-ModuleFile {
    <#
    .SYNOPSIS
        Helps import dbatools files according to configuration

    .DESCRIPTION
        Helps import dbatools files according to configuration
        Always dotsource this function!

    .PARAMETER Path
        The full path to the file to import

    .EXAMPLE
        PS C:\> Import-ModuleFile -Path $function.FullName

        Imports the file stored at '$function.FullName'
    #>
    [CmdletBinding()]
    param (
        $Path
    )

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

function Write-ImportTime {
    <#
    .SYNOPSIS
        Writes an entry to the import module time debug list

    .DESCRIPTION
        Writes an entry to the import module time debug list

    .PARAMETER Text
        The message to write

    .EXAMPLE
        PS C:\> Write-ImportTime -Text "Starting SMO Import"

        Adds the message "Starting SMO Import" to the debug list
#>
    [CmdletBinding()]
    param (
        [string]$Text,
        $Timestamp = (Get-Date)
    )

    if ($dbatools_disableTimeMeasurements) { return }

    if (-not $script:dbatools_ImportPerformance) { $script:dbatools_ImportPerformance = @() }

    if (([System.Management.Automation.PSTypeName]'Sqlcollaborative.Dbatools.Configuration.Config').Type -eq $null) {
        $script:dbatools_ImportPerformance += New-Object PSObject -Property @{ Time = $timestamp; Action = $Text }
    } else {
        if ([Sqlcollaborative.Dbatools.dbaSystem.DebugHost]::ImportTimeEntries.Count -eq 0) {
            foreach ($entry in $script:dbatools_ImportPerformance) { [Sqlcollaborative.Dbatools.dbaSystem.DebugHost]::ImportTimeEntries.Add((New-Object Sqlcollaborative.Dbatools.dbaSystem.StartTimeEntry($entry.Action, $entry.Time, ([System.Management.Automation.Runspaces.Runspace]::DefaultRunspace.InstanceId)))) }
        }

        [Sqlcollaborative.Dbatools.dbaSystem.DebugHost]::ImportTimeEntries.Add((New-Object Sqlcollaborative.Dbatools.dbaSystem.StartTimeEntry($Text, $timestamp, ([System.Management.Automation.Runspaces.Runspace]::DefaultRunspace.InstanceId))))
    }
}

Write-ImportTime -Text "Start" -Timestamp $start
Write-ImportTime -Text "Loading import helper functions"
#endregion Import helper functions

# Not supporting the provider path at this time 2/28/2017
if (((Resolve-Path .\).Path).StartsWith("SQLSERVER:\")) {
    Write-Warning "SQLSERVER:\ provider not supported. Please change to another directory and reload the module."
    Write-Warning "Going to continue loading anyway, but expect issues."
}

Write-ImportTime -Text "Resolved path to not SQLSERVER PSDrive"

$script:PSModuleRoot = $PSScriptRoot

if (($PSVersionTable.Keys -contains "PSEdition") -and ($PSVersionTable.PSEdition -ne 'Desktop')) {
    $script:core = $true
} else {
    $script:core = $false
}

#region Import Defines
$dbatoolsSystemUserNode = Get-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\System" -ErrorAction Ignore
$dbatoolsSystemSystemNode = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\System" -ErrorAction Ignore

#region Dot Sourcing
# Detect whether at some level dotsourcing was enforced
$script:doDotSource = $false
if ($dbatools_dotsourcemodule) { $script:doDotSource = $true }
if ($dbatoolsSystemSystemNode.DoDotSource) { $script:doDotSource = $true }
if ($dbatoolsSystemUserNode.DoDotSource) { $script:doDotSource = $true }
#endregion Dot Sourcing

#region Copy DLL Mode
$script:copyDllMode = $false
if ($dbatools_copydllmode) { $script:copyDllMode = $true }
if ($dbatoolsSystemSystemNode.CopyDllMode) { $script:copyDllMode = $true }
if ($dbatoolsSystemUserNode.CopyDllMode) { $script:copyDllMode = $true }
#endregion Copy DLL Mode

#region Always Compile
$script:alwaysBuildLibrary = $false
if ($dbatools_alwaysbuildlibrary) { $script:alwaysBuildLibrary = $true }
if ($dbatoolsSystemSystemNode.AlwaysBuildLibrary) { $script:alwaysBuildLibrary = $true }
if ($dbatoolsSystemUserNode.AlwaysBuildLibrary) { $script:alwaysBuildLibrary = $true }
#endregion Always Compile

#region Serial Import
$script:serialImport = $false
if ($dbatools_serialimport) { $script:serialImport = $true }
if ($dbatoolsSystemSystemNode.SerialImport) { $script:serialImport = $true }
if ($dbatoolsSystemUserNode.SerialImport) { $script:serialImport = $true }
#endregion Serial Import

#region Multi File Import
$script:multiFileImport = $false
if ($dbatools_multiFileImport) { $script:multiFileImport = $true }
if ($dbatoolsSystemSystemNode.MultiFileImport) { $script:multiFileImport = $true }
if ($dbatoolsSystemUserNode.MultiFileImport) { $script:multiFileImport = $true }
if (Test-Path -Path "$script:PSModuleRoot\.git") { $script:multiFileImport = $true }
if (Test-Path -Path "$script:PSModuleRoot/.git") { $script:multiFileImport = $true }
#endregion Multi File Import

Write-ImportTime -Text "Validated defines"
#endregion Import Defines

if (($PSVersionTable.PSVersion.Major -le 5) -or $script:isWindows) {
    Get-ChildItem -Path (Resolve-Path "$script:PSModuleRoot\bin\") -Filter "*.dll" -Recurse | Unblock-File -ErrorAction Ignore
    Write-ImportTime -Text "Unblocking Files"
}


$script:DllRoot = (Resolve-Path -Path "$script:PSModuleRoot\bin\")

<#
# Removed this because it doesn't seem to work well xplat and on win7 and it doesn't provide enough value
# Define folder in which to copy dll files before importing
if (-not $script:copyDllMode) { $script:DllRoot = (Resolve-Path "$script:PSModuleRoot\bin\") }
else {
    $libraryTempPath = (Resolve-Path "$($env:TEMP)\dbatools-$(Get-Random -Minimum 1000000 -Maximum 9999999)")
    while (Test-Path -Path $libraryTempPath) {
        $libraryTempPath = (Resolve-Path "$($env:TEMP)\dbatools-$(Get-Random -Minimum 1000000 -Maximum 9999999)")
    }
    $script:DllRoot = $libraryTempPath
    $null = New-Item -Path $libraryTempPath -ItemType Directory
}
#>

if (-not ([System.Management.Automation.PSTypeName]'Microsoft.SqlServer.Management.Smo.Server').Type) {
    . Import-ModuleFile "$script:PSModuleRoot\internal\scripts\smoLibraryImport.ps1"
    Write-ImportTime -Text "Starting import SMO libraries"
}

<#

    Do the rest of the loading

#>

# This technique helps a little bit
# https://becomelotr.wordpress.com/2017/02/13/expensive-dot-sourcing/

# Load our own custom library
# Should always come before function imports
. Import-ModuleFile "$script:PSModuleRoot\bin\library.ps1"
. Import-ModuleFile "$script:PSModuleRoot\bin\typealiases.ps1"
Write-ImportTime -Text "Loading dbatools library"

# Tell the library where the module is based, just in case
[Sqlcollaborative.Dbatools.dbaSystem.SystemHost]::ModuleBase = $script:PSModuleRoot

if ($script:multiFileImport) {
    # All internal functions privately available within the toolset
    foreach ($function in (Get-ChildItem -Path (Resolve-Path -Path "$script:PSModuleRoot\internal\functions\") -Recurse | Where-Object Extension -EQ '.ps1')) {
        . Import-ModuleFile $function.FullName
    }
    Write-ImportTime -Text "Loading Internal Commands"

    . Import-ModuleFile -Path (Resolve-Path -Path "$script:PSModuleRoot\internal\scripts\cmdlets.ps1")
    Write-ImportTime -Text "Registering cmdlets"

    # All exported functions
    foreach ($function in (Get-ChildItem -Path (Resolve-Path -Path "$script:PSModuleRoot\functions\") -Recurse | Where-Object Extension -EQ '.ps1')) {
        . Import-ModuleFile $function.FullName
    }
    Write-ImportTime -Text "Loading Public Commands"

} else {
    Add-Type -Assembly System.IO.Compression.FileSystem
    $zip = [System.IO.Compression.ZipFile]::OpenRead((Resolve-Path -Path "$script:PSModuleRoot\allcommands.zip"))
    $stream = $zip.Entries.Open()
    $reader = New-Object IO.StreamReader($stream)
    $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create(($reader.ReadToEnd()))), $null, $null)
    $reader.Close()
    $stream.Close()
    $zip.Dispose()
    Write-ImportTime -Text "Loading Public and Private Commands"

    . Import-ModuleFile (Resolve-Path -Path "$script:PSModuleRoot\internal\scripts\cmdlets.ps1")
    Write-ImportTime -Text "Registering cmdlets"
}

# Load configuration system
# Should always go after library and path setting
. Import-ModuleFile "$script:PSModuleRoot\internal\configurations\configuration.ps1"
Write-ImportTime -Text "Configuration System"

# Resolving the path was causing trouble when it didn't exist yet
# Not converting the path separators based on OS was also an issue.
if (-not ([Sqlcollaborative.Dbatools.Message.LogHost]::LoggingPath)) {
    [Sqlcollaborative.Dbatools.Message.LogHost]::LoggingPath = Join-DbaPath $script:AppData "PowerShell" "dbatools"
}

# Run all optional code
# Note: Each optional file must include a conditional governing whether it's run at all.
# Validations were moved into the other files, in order to prevent having to update dbatools.psm1 every time
# 96ms
foreach ($function in (Get-ChildItem -Path (Resolve-Path -Path "$script:PSModuleRoot\optional\*.ps1"))) {
    . Import-ModuleFile $function.FullName
}
Write-ImportTime -Text "Loading Optional Commands"

# Process TEPP parameters
. Import-ModuleFile -Path (Resolve-Path -Path "$script:PSModuleRoot\internal\scripts\insertTepp.ps1")
Write-ImportTime -Text "Loading TEPP"


# Process transforms
. Import-ModuleFile -Path (Resolve-Path -Path "$script:PSModuleRoot\internal\scripts\message-transforms.ps1")
Write-ImportTime -Text "Loading Message Transforms"

# Load scripts that must be individually run at the end #
#-------------------------------------------------------#

# Start the logging system (requires the configuration system up and running)
. Import-ModuleFile -Path (Resolve-Path -Path "$script:PSModuleRoot\internal\scripts\logfilescript.ps1")
Write-ImportTime -Text "Script: Logging"

# Start the tepp asynchronous update system (requires the configuration system up and running)
. Import-ModuleFile -Path (Resolve-Path -Path "$script:PSModuleRoot\internal\scripts\updateTeppAsync.ps1")
Write-ImportTime -Text "Script: Asynchronous TEPP Cache"


# Start the maintenance system (requires pretty much everything else already up and running)
. Import-ModuleFile -Path (Resolve-Path -Path "$script:PSModuleRoot\internal\scripts\dbatools-maintenance.ps1")
Write-ImportTime -Text "Script: Maintenance"

#region Aliases
# I renamed this function to be more accurate - 1ms
# changed to a script var so it can be used in the Rename-DbatoolsCommand
$script:renames = @(
    @{
        "AliasName"  = "Copy-SqlAgentCategory"
        "Definition" = "Copy-DbaAgentJobCategory"
    },
    @{
        "AliasName"  = "Copy-SqlAlert"
        "Definition" = "Copy-DbaAgentAlert"
    },
    @{
        "AliasName"  = "Copy-SqlAudit"
        "Definition" = "Copy-DbaServerAudit"
    },
    @{
        "AliasName"  = "Copy-SqlAuditSpecification"
        "Definition" = "Copy-DbaServerAuditSpecification"
    },
    @{
        "AliasName"  = "Copy-SqlBackupDevice"
        "Definition" = "Copy-DbaBackupDevice"
    },
    @{
        "AliasName"  = "Copy-SqlCentralManagementServer"
        "Definition" = "Copy-DbaCmsRegServer"
    },
    @{
        "AliasName"  = "Copy-SqlCredential"
        "Definition" = "Copy-DbaCredential"
    },
    @{
        "AliasName"  = "Copy-SqlCustomError"
        "Definition" = "Copy-DbaCustomError"
    },
    @{
        "AliasName"  = "Copy-SqlDatabase"
        "Definition" = "Copy-DbaDatabase"
    },
    @{
        "AliasName"  = "Copy-SqlDatabaseAssembly"
        "Definition" = "Copy-DbaDbAssembly"
    },
    @{
        "AliasName"  = "Copy-SqlDatabaseMail"
        "Definition" = "Copy-DbaDbMail"
    },
    @{
        "AliasName"  = "Copy-SqlDataCollector"
        "Definition" = "Copy-DbaDataCollector"
    },
    @{
        "AliasName"  = "Copy-SqlEndpoint"
        "Definition" = "Copy-DbaEndpoint"
    },
    @{
        "AliasName"  = "Copy-SqlExtendedEvent"
        "Definition" = "Copy-DbaXESession"
    },
    @{
        "AliasName"  = "Copy-SqlJob"
        "Definition" = "Copy-DbaAgentJob"
    },
    @{
        "AliasName"  = "Copy-SqlJobServer"
        "Definition" = "Copy-SqlServerAgent"
    },
    @{
        "AliasName"  = "Copy-SqlLinkedServer"
        "Definition" = "Copy-DbaLinkedServer"
    },
    @{
        "AliasName"  = "Copy-SqlLogin"
        "Definition" = "Copy-DbaLogin"
    },
    @{
        "AliasName"  = "Copy-SqlOperator"
        "Definition" = "Copy-DbaAgentOperator"
    },
    @{
        "AliasName"  = "Copy-SqlPolicyManagement"
        "Definition" = "Copy-DbaPolicyManagement"
    },
    @{
        "AliasName"  = "Copy-SqlProxyAccount"
        "Definition" = "Copy-DbaAgentProxy"
    },
    @{
        "AliasName"  = "Copy-SqlResourceGovernor"
        "Definition" = "Copy-DbaResourceGovernor"
    },
    @{
        "AliasName"  = "Copy-SqlServerAgent"
        "Definition" = "Copy-DbaAgentServer"
    },
    @{
        "AliasName"  = "Copy-SqlServerTrigger"
        "Definition" = "Copy-DbaServerTrigger"
    },
    @{
        "AliasName"  = "Copy-SqlSharedSchedule"
        "Definition" = "Copy-DbaAgentSchedule"
    },
    @{
        "AliasName"  = "Copy-SqlSpConfigure"
        "Definition" = "Copy-DbaSpConfigure"
    },
    @{
        "AliasName"  = "Copy-SqlSsisCatalog"
        "Definition" = "Copy-DbaSsisCatalog"
    },
    @{
        "AliasName"  = "Copy-SqlSysDbUserObjects"
        "Definition" = "Copy-DbaSysDbUserObject"
    },
    @{
        "AliasName"  = "Copy-SqlUserDefinedMessage"
        "Definition" = "Copy-SqlCustomError"
    },
    @{
        "AliasName"  = "Expand-SqlTLogResponsibly"
        "Definition" = "Expand-DbaDbLogFile"
    },
    @{
        "AliasName"  = "Export-SqlLogin"
        "Definition" = "Export-DbaLogin"
    },
    @{
        "AliasName"  = "Export-SqlSpConfigure"
        "Definition" = "Export-DbaSpConfigure"
    },
    @{
        "AliasName"  = "Export-SqlUser"
        "Definition" = "Export-DbaUser"
    },
    @{
        "AliasName"  = "Find-SqlDuplicateIndex"
        "Definition" = "Find-DbaDuplicateIndex"
    },
    @{
        "AliasName"  = "Find-SqlUnusedIndex"
        "Definition" = "Find-DbaDbUnusedIndex"
    },
    @{
        "AliasName"  = "Get-SqlMaxMemory"
        "Definition" = "Get-DbaMaxMemory"
    },
    @{
        "AliasName"  = "Get-SqlRegisteredServerName"
        "Definition" = "Get-DbaCmsRegServer"
    },
    @{
        "AliasName"  = "Get-DbaCmsRegServerName"
        "Definition" = "Get-DbaCmsRegServer"
    },
    @{
        "AliasName"  = "Get-SqlServerKey"
        "Definition" = "Get-DbaProductKey"
    },
    @{
        "AliasName"  = "Import-SqlSpConfigure"
        "Definition" = "Import-DbaSpConfigure"
    },
    @{
        "AliasName"  = "Install-SqlWhoIsActive"
        "Definition" = "Install-DbaWhoIsActive"
    },
    @{
        "AliasName"  = "Remove-SqlDatabaseSafely"
        "Definition" = "Remove-DbaDatabaseSafely"
    },
    @{
        "AliasName"  = "Remove-SqlOrphanUser"
        "Definition" = "Remove-DbaDbOrphanUser"
    },
    @{
        "AliasName"  = "Repair-SqlOrphanUser"
        "Definition" = "Repair-DbaDbOrphanUser"
    },
    @{
        "AliasName"  = "Reset-SqlAdmin"
        "Definition" = "Reset-DbaAdmin"
    },
    @{
        "AliasName"  = "Reset-SqlSaPassword"
        "Definition" = "Reset-SqlAdmin"
    },
    @{
        "AliasName"  = "Restore-SqlBackupFromDirectory"
        "Definition" = "Restore-DbaBackupFromDirectory"
    },
    @{
        "AliasName"  = "Set-SqlMaxMemory"
        "Definition" = "Set-DbaMaxMemory"
    },
    @{
        "AliasName"  = "Set-SqlTempDbConfiguration"
        "Definition" = "Set-DbaTempdbConfig"
    },
    @{
        "AliasName"  = "Show-SqlDatabaseList"
        "Definition" = "Show-DbaDbList"
    },
    @{
        "AliasName"  = "Show-SqlMigrationConstraint"
        "Definition" = "Test-SqlMigrationConstraint"
    },
    @{
        "AliasName"  = "Show-SqlServerFileSystem"
        "Definition" = "Show-DbaServerFileSystem"
    },
    @{
        "AliasName"  = "Show-SqlWhoIsActive"
        "Definition" = "Invoke-DbaWhoIsActive"
    },
    @{
        "AliasName"  = "Start-SqlMigration"
        "Definition" = "Start-DbaMigration"
    },
    @{
        "AliasName"  = "Sync-SqlLoginPermissions"
        "Definition" = "Sync-DbaLoginPermission"
    },
    @{
        "AliasName"  = "Sync-DbaSqlLoginPermission"
        "Definition" = "Sync-DbaLoginPermission"
    },
    @{
        "AliasName"  = "Test-SqlConnection"
        "Definition" = "Test-DbaConnection"
    },
    @{
        "AliasName"  = "Test-SqlDiskAllocation"
        "Definition" = "Test-DbaDiskAllocation"
    },
    @{
        "AliasName"  = "Test-SqlMigrationConstraint"
        "Definition" = "Test-DbaMigrationConstraint"
    },
    @{
        "AliasName"  = "Test-SqlNetworkLatency"
        "Definition" = "Test-DbaNetworkLatency"
    },
    @{
        "AliasName"  = "Test-SqlPath"
        "Definition" = "Test-DbaPath"
    },
    @{
        "AliasName"  = "Test-SqlTempDbConfiguration"
        "Definition" = "Test-DbaTempdbConfig"
    },
    @{
        "AliasName"  = "Watch-SqlDbLogin"
        "Definition" = "Watch-DbaDbLogin"
    },
    @{
        "AliasName"  = "Get-DiskSpace"
        "Definition" = "Get-DbaDiskSpace"
    },
    @{
        "AliasName"  = "Restore-HallengrenBackup"
        "Definition" = "Restore-SqlBackupFromDirectory"
    },
    @{
        "AliasName"  = "Get-DbaDatabaseFreeSpace"
        "Definition" = "Get-DbaDbSpace"
    },
    @{
        "AliasName"  = "Set-DbaQueryStoreConfig"
        "Definition" = "Set-DbaDbQueryStoreOption"
    },
    @{
        "AliasName"  = "Get-DbaQueryStoreConfig"
        "Definition" = "Get-DbaDbQueryStoreOption"
    },
    @{
        "AliasName"  = "Connect-DbaServer"
        "Definition" = "Connect-DbaInstance"
    },
    @{
        "AliasName"  = "Get-DbaInstance"
        "Definition" = "Connect-DbaInstance"
    },
    @{
        "AliasName"  = "Get-DbaXEventSession"
        "Definition" = "Get-DbaXESession"
    },
    @{
        "AliasName"  = "Get-DbaXEventSessionTarget"
        "Definition" = "Get-DbaXESessionTarget"
    },
    @{
        "AliasName"  = "Read-DbaXEventFile"
        "Definition" = "Read-DbaXEFile"
    },
    @{
        "AliasName"  = "Watch-DbaXEventSession"
        "Definition" = "Watch-DbaXESession"
    },
    @{
        "AliasName"  = "Get-DbaDatabaseCertificate"
        "Definition" = "Get-DbaDbCertificate"
    },
    @{
        "AliasName"  = "New-DbaDatabaseCertificate"
        "Definition" = "New-DbaDbCertificate"
    },
    @{
        "AliasName"  = "Remove-DbaDatabaseCertificate"
        "Definition" = "Remove-DbaDbCertificate"
    },
    @{
        "AliasName"  = "Restore-DbaDatabaseCertificate"
        "Definition" = "Restore-DbaDbCertificate"
    },
    @{
        "AliasName"  = "Backup-DbaDatabaseCertificate"
        "Definition" = "Backup-DbaDbCertificate"
    },
    @{
        "AliasName"  = "Find-DbaDatabaseGrowthEvent"
        "Definition" = "Find-DbaDbGrowthEvent"
    },
    @{
        "AliasName"  = "Get-DbaTraceFile"
        "Definition" = "Get-DbaTrace"
    },
    @{
        "AliasName"  = "Out-DbaDataTable"
        "Definition" = "ConvertTo-DbaDataTable"
    },
    @{
        "AliasName"  = "Invoke-DbaCmd"
        "Definition" = "Invoke-DbaQuery"
    },
    @{
        "AliasName"  = "Test-DbaVirtualLogFile"
        "Definition" = "Test-DbaDbVirtualLogFile"
    },
    @{
        "AliasName"  = "Test-DbaFullRecoveryModel"
        "Definition" = "Test-DbaDbRecoveryModel"
    },
    @{
        "AliasName"  = "Get-DbaDatabaseSnapshot"
        "Definition" = "Get-DbaDbSnapshot"
    },
    @{
        "AliasName"  = "New-DbaDatabaseSnapshot"
        "Definition" = "New-DbaDbSnapshot"
    },
    @{
        "AliasName"  = "Remove-DbaDatabaseSnapshot"
        "Definition" = "Remove-DbaDbSnapshot"
    },
    @{
        "AliasName"  = "Restore-DbaDatabaseSnapshot"
        "Definition" = "Restore-DbaDbSnapshot"
    },
    @{
        "AliasName"  = "Get-DbaLog"
        "Definition" = "Get-DbaErrorLog"
    },
    @{
        "AliasName"  = "Test-DbaValidLogin"
        "Definition" = "Test-DbaWindowsLogin"
    },
    @{
        "AliasName"  = "Get-DbaJobCategory"
        "Definition" = "Get-DbaAgentJobCategory"
    },
    @{
        "AliasName"  = "Invoke-DbaDatabaseShrink"
        "Definition" = "Invoke-DbaDbShrink"
    },
    @{
        "AliasName"  = "Get-DbaPolicy"
        "Definition" = "Get-DbaPbmPolicy"
    },
    @{
        "AliasName"  = "Backup-DbaDatabaseMasterKey"
        "Definition" = "Backup-DbaDbMasterKey"
    },
    @{
        "AliasName"  = "Get-DbaDatabaseMasterKey"
        "Definition" = "Get-DbaDbMasterKey"
    },
    @{
        "AliasName"  = "Remove-DbaDatabaseMasterKey"
        "Definition" = "Remove-DbaDbMasterKey"
    },
    @{
        "AliasName"  = "New-DbaDatabaseMasterKey"
        "Definition" = "New-DbaDbMasterKey"
    },
    @{
        "AliasName"  = "Get-DbaDatabaseAssembly"
        "Definition" = "Get-DbaDbAssembly"
    },
    @{
        "AliasName"  = "Copy-DbaDatabaseAssembly"
        "Definition" = "Copy-DbaDbAssembly"
    },
    @{
        "AliasName"  = "Get-DbaDatabaseEncryption"
        "Definition" = "Get-DbaDbEncryption"
    },
    @{
        "AliasName"  = "Get-DbaDatabaseFile"
        "Definition" = "Get-DbaDbFile"
    },
    @{
        "AliasName"  = "Get-DbaDatabasePartitionFunction"
        "Definition" = "Get-DbaDbPartitionFunction"
    },
    @{
        "AliasName"  = "Get-DbaDatabasePartitionScheme"
        "Definition" = "Get-DbaDbPartitionScheme"
    },
    @{
        "AliasName"  = "Get-DbaDatabaseSpace"
        "Definition" = "Get-DbaDbSpace"
    },
    @{
        "AliasName"  = "Get-DbaDatabaseState"
        "Definition" = "Get-DbaDbState"
    },
    @{
        "AliasName"  = "Get-DbaDatabaseUdf"
        "Definition" = "Get-DbaDbUdf"
    },
    @{
        "AliasName"  = "Get-DbaDatabaseUser"
        "Definition" = "Get-DbaDbUser"
    },
    @{
        "AliasName"  = "Get-DbaDatabaseView"
        "Definition" = "Get-DbaDbView"
    },
    @{
        "AliasName"  = "Invoke-DbaDatabaseClone"
        "Definition" = "Invoke-DbaDbClone"
    },
    @{
        "AliasName"  = "Invoke-DbaDatabaseUpgrade"
        "Definition" = "Invoke-DbaDbUpgrade"
    },
    @{
        "AliasName"  = "Set-DbaDatabaseOwner"
        "Definition" = "Set-DbaDbOwner"
    },
    @{
        "AliasName"  = "Set-DbaDatabaseState"
        "Definition" = "Set-DbaDbState"
    },
    @{
        "AliasName"  = "Show-DbaDatabaseList"
        "Definition" = "Show-DbaDbList"
    },
    @{
        "AliasName"  = "Test-DbaDatabaseCollation"
        "Definition" = "Test-DbaDbCollation"
    },
    @{
        "AliasName"  = "Test-DbaDatabaseCompatibility"
        "Definition" = "Test-DbaDbCompatibility"
    },
    @{
        "AliasName"  = "Test-DbaDatabaseOwner"
        "Definition" = "Test-DbaDbOwner"
    },
    @{
        "AliasName"  = "Clear-DbaSqlConnectionPool"
        "Definition" = "Clear-DbaConnectionPool"
    },
    @{
        "AliasName"  = "Copy-DbaSqlDataCollector"
        "Definition" = "Copy-DbaDataCollector"
    },
    @{
        "AliasName"  = "Copy-DbaSqlPolicyManagement"
        "Definition" = "Copy-DbaPolicyManagement"
    },
    @{
        "AliasName"  = "Copy-DbaSqlServerAgent"
        "Definition" = "Copy-DbaAgentServer"
    },
    @{
        "AliasName"  = "Get-DbaSqlBuildReference"
        "Definition" = "Get-DbaBuildReference"
    },
    @{
        "AliasName"  = "Get-DbaSqlFeature"
        "Definition" = "Get-DbaFeature"
    },
    @{
        "AliasName"  = "Get-DbaSqlInstanceProperty"
        "Definition" = "Get-DbaInstanceProperty"
    },
    @{
        "AliasName"  = "Get-DbaSqlInstanceUserOption"
        "Definition" = "Get-DbaInstanceUserOption"
    },
    @{
        "AliasName"  = "Get-DbaSqlManagementObject"
        "Definition" = "Get-DbaManagementObject"
    },
    @{
        "AliasName"  = "Get-DbaSqlModule"
        "Definition" = "Get-DbaModule"
    },
    @{
        "AliasName"  = "Get-DbaSqlProductKey"
        "Definition" = "Get-DbaProductKey"
    },
    @{
        "AliasName"  = "Get-DbaSqlRegistryRoot"
        "Definition" = "Get-DbaRegistryRoot"
    },
    @{
        "AliasName"  = "Get-DbaSqlService"
        "Definition" = "Get-DbaService"
    },
    @{
        "AliasName"  = "Invoke-DbaSqlQuery"
        "Definition" = "Invoke-DbaQuery"
    },
    @{
        "AliasName"  = "New-DbaSqlConnectionString"
        "Definition" = "New-DbaConnectionString"
    },
    @{
        "AliasName"  = "New-DbaSqlConnectionStringBuilder"
        "Definition" = "New-DbaConnectionStringBuilder"
    },
    @{
        "AliasName"  = "New-DbaSqlDirectory"
        "Definition" = "New-DbaDirectory"
    },
    @{
        "AliasName"  = "Restart-DbaSqlService"
        "Definition" = "Restart-DbaService"
    },
    @{
        "AliasName"  = "Start-DbaSqlService"
        "Definition" = "Start-DbaService"
    },
    @{
        "AliasName"  = "Stop-DbaSqlService"
        "Definition" = "Stop-DbaService"
    },
    @{
        "AliasName"  = "Test-DbaSqlBuild"
        "Definition" = "Test-DbaBuild"
    },
    @{
        "AliasName"  = "Test-DbaSqlManagementObject"
        "Definition" = "Test-DbaManagementObject"
    },
    @{
        "AliasName"  = "Test-DbaSqlPath"
        "Definition" = "Test-DbaPath"
    },
    @{
        "AliasName"  = "Update-DbaSqlServiceAccount"
        "Definition" = "Update-DbaServiceAccount"
    },
    @{
        "AliasName"  = "Set-DbaTempDbConfiguration"
        "Definition" = "Set-DbaTempdbConfig"
    },
    @{
        "AliasName"  = "Test-DbaTempDbConfiguration"
        "Definition" = "Test-DbaTempdbConfig"
    },
    @{
        "AliasName"  = "Export-DbaDacpac"
        "Definition" = "Export-DbaDacPackage"
    },
    @{
        "AliasName"  = "Publish-DbaDacpac"
        "Definition" = "Publish-DbaDacPackage"
    },
    @{
        "AliasName"  = "Get-DbaConfig"
        "Definition" = "Get-DbatoolsConfig"
    },
    @{
        "AliasName"  = "Set-DbaConfig"
        "Definition" = "Set-DbatoolsConfig"
    },
    @{
        "AliasName"  = "Get-DbaConfigValue"
        "Definition" = "Get-DbatoolsConfigValue"
    },
    @{
        "AliasName"  = "Register-DbaConfig"
        "Definition" = "Register-DbatoolsConfig"
    },
    @{
        "AliasName"  = "New-DbaPublishProfile"
        "Definition" = "New-DbaDacProfile"
    },
    @{
        "AliasName"  = "Get-DbaDbQueryStoreOptions"
        "Definition" = "Get-DbaDbQueryStoreOption"
    },
    @{
        "AliasName"  = "Set-DbaDbQueryStoreOptions"
        "Definition" = "Set-DbaDbQueryStoreOption"
    },
    @{
        "AliasName"  = "Copy-DbaDatabaseMail"
        "Definition" = "Copy-DbaDbMail"
    },
    @{
        "AliasName"  = "Get-DbaUserLevelPermission"
        "Definition" = "Get-DbaUserPermission"
    },
    @{
        "AliasName"  = "Get-DbaDistributor"
        "Definition" = "Get-DbaRepDistributor"
    },
    @{
        "AliasName"  = "Get-DbaTable"
        "Definition" = "Get-DbaDbTable"
    },
    @{
        "AliasName"  = "Copy-DbaTableData"
        "Definition" = "Copy-DbaDbTableData"
    }, @{
        "AliasName"  = "Add-DbaRegisteredServer"
        "Definition" = "Add-DbaCmsRegServer"
    },
    @{
        "AliasName"  = "Add-DbaRegisteredServerGroup"
        "Definition" = "Add-DbaCmsRegServerGroup"
    },
    @{
        "AliasName"  = "Export-DbaRegisteredServer"
        "Definition" = "Export-DbaCmsRegServer"
    },
    @{
        "AliasName"  = "Get-DbaRegisteredServerGroup"
        "Definition" = "Get-DbaCmsRegServerGroup"
    },
    @{
        "AliasName"  = "Get-DbaRegisteredServerStore"
        "Definition" = "Get-DbaCmsRegServerStore"
    },
    @{
        "AliasName"  = "Import-DbaRegisteredServer"
        "Definition" = "Import-DbaCmsRegServer"
    },
    @{
        "AliasName"  = "Move-DbaRegisteredServer"
        "Definition" = "Move-DbaCmsRegServer"
    },
    @{
        "AliasName"  = "Move-DbaRegisteredServerGroup"
        "Definition" = "Move-DbaCmsRegServerGroup"
    },
    @{
        "AliasName"  = "Remove-DbaRegisteredServer"
        "Definition" = "Remove-DbaCmsRegServer"
    },
    @{
        "AliasName"  = "Remove-DbaRegisteredServerGroup"
        "Definition" = "Remove-DbaCmsRegServerGroup"
    },
    @{
        "AliasName"  = "Get-DbaLogShippingError"
        "Definition" = "Get-DbaDbLogShipError"
    },
    @{
        "AliasName"  = "Invoke-DbaLogShipping"
        "Definition" = "Invoke-DbaDbLogShipping"
    },
    @{
        "AliasName"  = "Invoke-DbaLogShippingRecovery"
        "Definition" = "Invoke-DbaDbLogShipRecovery"
    },
    @{
        "AliasName"  = "Test-DbaLogShippingStatus"
        "Definition" = "Test-DbaDbLogShipStatus"
    },
    @{
        "AliasName"  = "Get-DbaRoleMember"
        "Definition" = "Get-DbaDbRoleMember"
    },
    @{
        "AliasName"  = "Get-DbaRestoreHistory"
        "Definition" = "Get-DbaDbRestoreHistory"
    },
    @{
        "AliasName"  = "Expand-DbaTLogResponsibly"
        "Definition" = "Expand-DbaDbLogFile"
    },
    @{
        "AliasName"  = "Test-DbaRecoveryModel"
        "Definition" = "Test-DbaDbRecoveryModel"
    },
    @{
        "AliasName"  = "Copy-DbaAgentCategory"
        "Definition" = "Copy-DbaAgentJobCategory"
    },
    @{
        "AliasName"  = "Copy-DbaAgentProxyAccount"
        "Definition" = "Copy-DbaAgentProxy"
    },
    @{
        "AliasName"  = "Copy-DbaAgentSharedSchedule"
        "Definition" = "Copy-DbaAgentSchedule"
    },
    @{
        "AliasName"  = "Copy-DbaCentralManagementServer"
        "Definition" = "Copy-DbaCmsRegServer"
    },
    @{
        "AliasName"  = "Copy-DbaExtendedEvent"
        "Definition" = "Copy-DbaXESession"
    },
    @{
        "AliasName"  = "Copy-DbaQueryStoreConfig"
        "Definition" = "Copy-DbaDbQueryStoreOption"
    },
    @{
        "AliasName"  = "Import-DbaCsvToSql"
        "Definition" = "Import-DbaCsv"
    },
    @{
        "AliasName"  = "Set-DbaJobOwner"
        "Definition" = "Set-DbaAgentJobOwner"
    },
    @{
        "AliasName"  = "Get-DbaOrphanUser"
        "Definition" = "Get-DbaDbOrphanUser"
    },
    @{
        "AliasName"  = "Remove-DbaOrphanUser"
        "Definition" = "Remove-DbaDbOrphanUser"
    },
    @{
        "AliasName"  = "Repair-DbaOrphanUser"
        "Definition" = "Repair-DbaDbOrphanUser"
    }
)

$script:renames | ForEach-Object {
    if (-not (Test-Path Alias:$($_.AliasName))) { Set-Alias -Scope Global -Name $($_.AliasName) -Value $($_.Definition) }
}


# Leave forever
$forever = @(
    @{
        "AliasName"  = "Attach-DbaDatabase"
        "Definition" = "Mount-DbaDatabase"
    },
    @{
        "AliasName"  = "Detach-DbaDatabase"
        "Definition" = "Dismount-DbaDatabase"
    },
    @{
        "AliasName"  = "Get-DbaRegisteredServer"
        "Definition" = "Get-DbaCmsRegServer"
    }
)
$forever | ForEach-Object {
    if (-not (Test-Path Alias:$($_.AliasName))) { Set-Alias -Scope Global -Name $($_.AliasName) -Value $($_.Definition) }
}
#endregion Aliases

#region Post-Import Cleanup
Write-ImportTime -Text "Loading Aliases"

# region Commands
$script:xplat = @(
    'Start-DbaMigration',
    'Copy-DbaDatabase',
    'Copy-DbaLogin',
    'Copy-DbaAgentServer',
    'Copy-DbaSpConfigure',
    'Copy-DbaDbMail',
    'Copy-DbaDbAssembly',
    'Copy-DbaAgentSchedule',
    'Copy-DbaAgentOperator',
    'Copy-DbaAgentJob',
    'Copy-DbaCustomError',
    'Copy-DbaServerAuditSpecification',
    'Copy-DbaEndpoint',
    'Copy-DbaServerAudit',
    'Copy-DbaServerRole',
    'Copy-DbaResourceGovernor',
    'Copy-DbaXESession',
    'Copy-DbaServerTrigger',
    'Copy-DbaCmsRegServer',
    'Copy-DbaSysDbUserObject',
    'Copy-DbaAgentProxy',
    'Copy-DbaAgentAlert',
    'Get-DbaDetachedDatabaseInfo',
    'Restore-DbaBackupFromDirectory',
    'Copy-DbaAgentJobCategory',
    'Test-DbaPath',
    'Export-DbaLogin',
    'Watch-DbaDbLogin',
    'Expand-DbaDbLogFile',
    'Test-DbaMigrationConstraint',
    'Test-DbaNetworkLatency',
    'Find-DbaDuplicateIndex',
    'Remove-DbaDatabaseSafely',
    'Set-DbaTempdbConfig',
    'Test-DbaTempdbConfig',
    'Repair-DbaDbOrphanUser',
    'Remove-DbaDbOrphanUser',
    'Find-DbaDbUnusedIndex',
    'Get-DbaDbSpace',
    'Test-DbaDbOwner',
    'Set-DbaDbOwner',
    'Test-DbaJobOwner',
    'Set-DbaAgentJobOwner',
    'Test-DbaDbVirtualLogFile',
    'Get-DbaDbRestoreHistory',
    'Get-DbaTcpPort',
    'Test-DbaDbCompatibility',
    'Test-DbaDbCollation',
    'Test-DbaConnectionAuthScheme',
    'Test-DbaServerName',
    'Repair-DbaServerName',
    'Stop-DbaProcess',
    'Find-DbaOrphanedFile',
    'Get-DbaAvailabilityGroup',
    'Get-DbaLastGoodCheckDb',
    'Get-DbaProcess',
    'Get-DbaRunningJob',
    'Set-DbaMaxDop',
    'Test-DbaDbRecoveryModel',
    'Test-DbaMaxDop',
    'Remove-DbaBackup',
    'Get-DbaPermission',
    'Get-DbaLastBackup',
    'Connect-DbaInstance',
    'Get-DbaBackupHistory',
    'Read-DbaBackupHeader',
    'Test-DbaLastBackup',
    'Get-DbaMaxMemory',
    'Set-DbaMaxMemory',
    'Get-DbaDbSnapshot',
    'Remove-DbaDbSnapshot',
    'Get-DbaDbRoleMember',
    'Get-DbaServerRoleMember',
    'Resolve-DbaNetworkName',
    'Export-DbaAvailabilityGroup',
    'Write-DbaDataTable',
    'New-DbaDbSnapshot',
    'Restore-DbaDbSnapshot',
    'Get-DbaServerTrigger',
    'Get-DbaDbTrigger',
    'Get-DbaDbState',
    'Set-DbaDbState',
    'Get-DbaHelpIndex',
    'Get-DbaAgentAlert',
    'Get-DbaAgentOperator',
    'Get-DbaSpConfigure',
    'Rename-DbaLogin',
    'Find-DbaAgentJob',
    'Find-DbaDatabase',
    'Get-DbaXESession',
    'Test-DbaOptimizeForAdHoc',
    'Find-DbaStoredProcedure',
    'Measure-DbaBackupThroughput',
    'Get-DbaDatabase',
    'Find-DbaUserObject',
    'Get-DbaDependency',
    'Find-DbaCommand',
    'Backup-DbaDatabase',
    'New-DbaDirectory',
    'Get-DbaDbQueryStoreOption',
    'Set-DbaDbQueryStoreOption',
    'Restore-DbaDatabase',
    'Copy-DbaDbQueryStoreOption',
    'Get-DbaExecutionPlan',
    'Export-DbaExecutionPlan',
    'Set-DbaSpConfigure',
    'Test-DbaIdentityUsage',
    'Get-DbaDbAssembly',
    'Get-DbaAgentJob',
    'Get-DbaCustomError',
    'Get-DbaCredential',
    'Get-DbaBackupDevice',
    'Get-DbaAgentProxy',
    'Get-DbaDbEncryption',
    'Remove-DbaDatabase',
    'Get-DbaQueryExecutionTime',
    'Get-DbaTempdbUsage',
    'Find-DbaDbGrowthEvent',
    'Test-DbaLinkedServerConnection',
    'Get-DbaDbFile',
    'Read-DbaTransactionLog',
    'Get-DbaDbTable',
    'Invoke-DbaDbShrink',
    'Get-DbaEstimatedCompletionTime',
    'Get-DbaLinkedServer',
    'New-DbaAgentJob',
    'Get-DbaLogin',
    'New-DbaScriptingOption',
    'Save-DbaDiagnosticQueryScript',
    'Invoke-DbaDiagnosticQuery',
    'Export-DbaDiagnosticQuery',
    'Invoke-DbaWhoIsActive',
    'Set-DbaAgentJob',
    'Remove-DbaAgentJob',
    'New-DbaAgentJobStep',
    'Set-DbaAgentJobStep',
    'Remove-DbaAgentJobStep',
    'New-DbaAgentSchedule',
    'Set-DbaAgentSchedule',
    'Remove-DbaAgentSchedule',
    'Backup-DbaDbCertificate',
    'Get-DbaDbCertificate',
    'Get-DbaEndpoint',
    'Get-DbaDbMasterKey',
    'Get-DbaSchemaChangeHistory',
    'Get-DbaServerAudit',
    'Get-DbaServerAuditSpecification',
    'Get-DbaProductKey',
    'Get-DbatoolsLog',
    'Restore-DbaDbCertificate',
    'New-DbaDbCertificate',
    'New-DbaDbMasterKey',
    'New-DbaServiceMasterKey',
    'Remove-DbaDbCertificate',
    'Remove-DbaDbMasterKey',
    'New-DbaConnectionStringBuilder',
    'Get-DbaInstanceProperty',
    'Get-DbaInstanceUserOption',
    'New-DbaConnectionString',
    'Get-DbaAgentSchedule',
    'Read-DbaTraceFile',
    'Get-DbaServerInstallDate',
    'Backup-DbaDbMasterKey',
    'Get-DbaAgentJobHistory',
    'Get-DbaMaintenanceSolutionLog',
    'Invoke-DbaDbLogShipRecovery',
    'Find-DbaTrigger',
    'Find-DbaView',
    'Invoke-DbaDbUpgrade',
    'Get-DbaDbUser',
    'Get-DbaAgentLog',
    'Get-DbaDbMailLog',
    'Get-DbaDbMailHistory',
    'Get-DbaDbView',
    'Get-DbaDbUdf',
    'Get-DbaDbPartitionFunction',
    'Get-DbaDbPartitionScheme',
    'Get-DbaDefaultPath',
    'Get-DbaDbStoredProcedure',
    'Test-DbaDbCompression',
    'Mount-DbaDatabase',
    'Dismount-DbaDatabase',
    'Get-DbaAgReplica',
    'Get-DbaAgDatabase',
    'Get-DbaModule',
    'Sync-DbaLoginPermission',
    'New-DbaCredential',
    'Get-DbaFile',
    'Set-DbaDbCompression',
    'Get-DbaTraceFlag',
    'Invoke-DbaCycleErrorLog',
    'Get-DbaAvailableCollation',
    'Get-DbaUserPermission',
    'Get-DbaAgHadr',
    'Find-DbaSimilarTable',
    'Get-DbaTrace',
    'Get-DbaSuspectPage',
    'Get-DbaWaitStatistic',
    'Clear-DbaWaitStatistics',
    'Get-DbaTopResourceUsage',
    'New-DbaLogin',
    'Get-DbaAgListener',
    'Invoke-DbaDbClone',
    'Disable-DbaTraceFlag',
    'Enable-DbaTraceFlag',
    'Start-DbaAgentJob',
    'Stop-DbaAgentJob',
    'New-DbaAgentProxy',
    'Test-DbaDbLogShipStatus',
    'Get-DbaXESessionTarget',
    'New-DbaXESmartTargetResponse',
    'New-DbaXESmartTarget',
    'Get-DbaDbVirtualLogFile',
    'Get-DbaBackupInformation',
    'Start-DbaXESession',
    'Stop-DbaXESession',
    'Set-DbaDbRecoveryModel',
    'Get-DbaDbRecoveryModel',
    'Get-DbaWaitingTask',
    'Remove-DbaDbUser',
    'Get-DbaDump',
    'Invoke-DbaAdvancedRestore',
    'Format-DbaBackupInformation',
    'Get-DbaAgentJobStep',
    'Test-DbaBackupInformation',
    'Invoke-DbaBalanceDataFiles',
    'Select-DbaBackupInformation',
    'Publish-DbaDacPackage',
    'Copy-DbaDbTableData',
    'Invoke-DbaQuery',
    'Remove-DbaLogin',
    'Get-DbaAgentJobCategory',
    'New-DbaAgentJobCategory',
    'Remove-DbaAgentJobCategory',
    'Set-DbaAgentJobCategory',
    'Get-DbaDbRole',
    'Get-DbaServerRole',
    'Find-DbaBackup',
    'Remove-DbaXESession',
    'New-DbaXESession',
    'Get-DbaXEStore',
    'New-DbaXESmartTableWriter',
    'New-DbaXESmartReplay',
    'New-DbaXESmartEmail',
    'New-DbaXESmartQueryExec',
    'Start-DbaXESmartTarget',
    'Get-DbaDbOrphanUser',
    'Get-DbaOpenTransaction',
    'Get-DbaDbLogShipError',
    'Test-DbaBuild',
    'Get-DbaXESessionTemplate',
    'ConvertTo-DbaXESession',
    'Start-DbaTrace',
    'Stop-DbaTrace',
    'Remove-DbaTrace',
    'Set-DbaLogin',
    'Copy-DbaXESessionTemplate',
    'Get-DbaXEObject',
    'ConvertTo-DbaDataTable',
    'Find-DbaDisabledIndex',
    'Get-DbaXESmartTarget',
    'Remove-DbaXESmartTarget',
    'Stop-DbaXESmartTarget',
    'Get-DbaCmsRegServerGroup',
    'New-DbaDbUser',
    'Measure-DbaDiskSpaceRequirement',
    'New-DbaXESmartCsvWriter',
    'Invoke-DbaXeReplay',
    'Find-DbaInstance',
    'Test-DbaDiskSpeed',
    'Get-DbaDbExtentDiff',
    'Read-DbaAuditFile',
    'Get-DbaDbCompression',
    'Invoke-DbaDbDecryptObject',
    'Get-DbaDbForeignKey',
    'Get-DbaDbCheckConstraint',
    'Set-DbaAgentAlert',
    'Get-DbaWaitResource',
    'Get-DbaDbPageInfo',
    'Get-DbaConnection',
    'Test-DbaLoginPassword',
    'Get-DbaErrorLogConfig',
    'Set-DbaErrorLogConfig',
    'Get-DbaPlanCache',
    'Clear-DbaPlanCache',
    'ConvertTo-DbaTimeline',
    'Get-DbaDbMail',
    'Get-DbaDbMailAccount',
    'Get-DbaDbMailProfile',
    'Get-DbaDbMailConfig',
    'Get-DbaDbMailServer',
    'Get-DbaResourceGovernor',
    'Get-DbaRgResourcePool',
    'Get-DbaRgWorkloadGroup',
    'Get-DbaRgClassifierFunction',
    'Export-DbaInstance',
    'Invoke-DbatoolsRenameHelper',
    'Measure-DbatoolsImport',
    'Get-DbaDeprecatedFeature',
    'Test-DbaDeprecatedFeature'
    'Get-DbaDbFeatureUsage',
    'Stop-DbaEndpoint',
    'Start-DbaEndpoint',
    'Set-DbaDbMirror',
    'Repair-DbaDbMirror',
    'Remove-DbaEndpoint',
    'Remove-DbaDbMirrorMonitor',
    'Remove-DbaDbMirror',
    'New-DbaEndpoint',
    'Invoke-DbaDbMirroring',
    'Invoke-DbaDbMirrorFailover',
    'Get-DbaDbMirrorMonitor',
    'Get-DbaDbMirror',
    'Add-DbaDbMirrorMonitor',
    'Test-DbaEndpoint',
    'Get-DbaDbSharePoint',
    'Get-DbaDbMemoryUsage',
    'Clear-DbaLatchStatistics',
    'Get-DbaCpuRingBuffer',
    'Get-DbaIoLatency',
    'Get-DbaLatchStatistic',
    'Get-DbaSpinLockStatistic',
    'Add-DbaAgDatabase',
    'Add-DbaAgListener',
    'Add-DbaAgReplica',
    'Grant-DbaAgPermission',
    'Invoke-DbaAgFailover',
    'Join-DbaAvailabilityGroup',
    'New-DbaAvailabilityGroup',
    'Remove-DbaAgDatabase',
    'Remove-DbaAgListener',
    'Remove-DbaAvailabilityGroup',
    'Revoke-DbaAgPermission',
    'Get-DbaDbCompatibility',
    'Set-DbaDbCompatibility',
    'Invoke-DbatoolsFormatter',
    'Remove-DbaAgReplica',
    'Resume-DbaAgDbDataMovement',
    'Set-DbaAgListener',
    'Set-DbaAgReplica',
    'Set-DbaAvailabilityGroup',
    'Set-DbaEndpoint',
    'Suspend-DbaAgDbDataMovement',
    'Sync-DbaAvailabilityGroup',
    'Get-DbaMemoryCondition',
    'Remove-DbaDbBackupRestoreHistory',
    'New-DbaDatabase'
    'New-DbaDacOption',
    'Get-DbaDbccHelp',
    'Get-DbaDbccMemoryStatus',
    'Get-DbaDbccProcCache',
    'Get-DbaDbccUserOption',
    'Get-DbaAgentServer',
    'Set-DbaAgentServer',
    'Invoke-DbaDbccFreeCache'
    'Export-DbatoolsConfig',
    'Import-DbatoolsConfig',
    'Reset-DbatoolsConfig',
    'Unregister-DbatoolsConfig',
    'Join-DbaPath',
    'Resolve-DbaPath',
    'Import-DbaCsv',
    'Invoke-DbaDbDataMasking',
    'New-DbaDbMaskingConfig',
    'Get-DbaDbccSessionBuffer',
    'Get-DbaDbccStatistic',
    'Get-DbaDbDbccOpenTran',
    'Invoke-DbaDbccDropCleanBuffer',
    'Invoke-DbaDbDbccCheckConstraint',
    'Invoke-DbaDbDbccCleanTable',
    'Invoke-DbaDbDbccUpdateUsage'
)

$script:noncoresmo = @(
    # SMO issues
    'Export-DbaUser',
    'Get-DbaSsisExecutionHistory',
    'Get-DbaRepDistributor',
    'Get-DbaCmsRegServerStore',
    'Copy-DbaPolicyManagement',
    'Copy-DbaDataCollector',
    'Get-DbaCmsRegServer',
    'Copy-DbaSsisCatalog',
    'New-DbaSsisCatalog',
    'Get-DbaSsisEnvironmentVariable',
    'Get-DbaPbmCategory',
    'Get-DbaPbmCategorySubscription',
    'Get-DbaPbmCondition',
    'Get-DbaPbmObjectSet',
    'Get-DbaPbmPolicy',
    'Get-DbaPbmStore',
    'Add-DbaCmsRegServer',
    'Add-DbaCmsRegServerGroup',
    'Export-DbaCmsRegServer',
    'Import-DbaCmsRegServer',
    'Move-DbaCmsRegServer',
    'Move-DbaCmsRegServerGroup',
    'Remove-DbaCmsRegServer',
    'Remove-DbaCmsRegServerGroup',
    'Get-DbaRepPublication',
    'Test-DbaRepLatency',
    'Export-DbaRepServerSetting',
    'Get-DbaRepServer'
)
$script:windowsonly = @(
    # solvable filesystem issues or other workarounds
    'Copy-DbaBackupDevice',
    'Install-DbaSqlWatch',
    'Uninstall-DbaSqlWatch',
    'Get-DbaRegistryRoot',
    'Install-DbaMaintenanceSolution',
    'New-DbatoolsSupportPackage',
    'Export-DbaScript',
    'Get-DbaAgentJobOutputFile',
    'Set-DbaAgentJobOutputFile',
    'Get-DbaBuildReference',
    'New-DbaDacProfile'
    'Import-DbaXESessionTemplate',
    'Export-DbaXESessionTemplate',
    'Import-DbaSpConfigure',
    'Export-DbaSpConfigure'
    'Update-Dbatools',
    'Install-DbaWhoIsActive',
    'Install-DbaFirstResponderKit',
    'Read-DbaXEFile',
    'Watch-DbaXESession',
    'Test-DbaMaxMemory', # can be fixed by not testing remote when linux is detected
    'Rename-DbaDatabase', # can maybebe fixed by not remoting when linux is detected
    # CM and Windows functions
    'Update-DbaInstance',
    'Invoke-DbaPfRelog',
    'Get-DbaPfDataCollectorCounter',
    'Get-DbaPfDataCollectorCounterSample',
    'Get-DbaPfDataCollector',
    'Get-DbaPfDataCollectorSet',
    'Start-DbaPfDataCollectorSet',
    'Stop-DbaPfDataCollectorSet',
    'Export-DbaPfDataCollectorSetTemplate',
    'Get-DbaPfDataCollectorSetTemplate',
    'Import-DbaPfDataCollectorSetTemplate',
    'Remove-DbaPfDataCollectorSet',
    'Add-DbaPfDataCollectorCounter',
    'Remove-DbaPfDataCollectorCounter',
    'Get-DbaPfAvailableCounter',
    'Export-DbaXECsv',
    'Get-DbaOperatingSystem',
    'Get-DbaComputerSystem',
    'Set-DbaPrivilege',
    'Set-DbaTcpPort',
    'Set-DbaCmConnection',
    'Get-DbaUptime',
    'Get-DbaMemoryUsage',
    'Clear-DbaConnectionPool',
    'Get-DbaLocaleSetting',
    'Get-DbaFilestream',
    'Enable-DbaFilestream',
    'Disable-DbaFilestream',
    'Get-DbaCpuUsage',
    'Get-DbaPowerPlan',
    'Get-DbaWsfcAvailableDisk',
    'Get-DbaWsfcCluster',
    'Get-DbaWsfcDisk',
    'Get-DbaWsfcNetwork',
    'Get-DbaWsfcNetworkInterface',
    'Get-DbaWsfcNode',
    'Get-DbaWsfcResource',
    'Get-DbaWsfcResourceType',
    'Get-DbaWsfcRole',
    'Get-DbaWsfcSharedVolume',
    'Export-DbaCredential',
    'Export-DbaLinkedServer',
    'Get-DbaFeature',
    'Update-DbaServiceAccount',
    'Remove-DbaClientAlias',
    'Disable-DbaAgHadr',
    'Enable-DbaAgHadr',
    'Stop-DbaService',
    'Start-DbaService',
    'Restart-DbaService',
    'New-DbaClientAlias',
    'Get-DbaClientAlias',
    'Remove-DbaNetworkCertificate',
    'Enable-DbaForceNetworkEncryption',
    'Disable-DbaForceNetworkEncryption',
    'Get-DbaForceNetworkEncryption',
    'Remove-DbaComputerCertificate',
    'New-DbaComputerCertificate',
    'Get-DbaComputerCertificate',
    'Add-DbaComputerCertificate',
    'Get-DbaNetworkCertificate',
    'Set-DbaNetworkCertificate',
    'Invoke-DbaDbLogShipping',
    'New-DbaCmConnection',
    'Get-DbaCmConnection',
    'Remove-DbaCmConnection',
    'Test-DbaCmConnection',
    'Get-DbaCmObject',
    'Set-DbaStartupParameter',
    'Get-DbaNetworkActivity',
    'Get-DbaServerProtocol'
    'Watch-DbaUpdate',
    'Uninstall-DbaWatchUpdate',
    'Install-DbaWatchUpdate',
    'Get-DbaPrivilege',
    'Get-DbaMsdtc',
    'Get-DbaPageFileSetting',
    'Copy-DbaCredential',
    'Test-DbaConnection',
    'Reset-DbaAdmin',
    'Copy-DbaLinkedServer',
    'Get-DbaDiskSpace',
    'Test-DbaDiskAllocation',
    'Test-DbaPowerPlan',
    'Set-DbaPowerPlan',
    'Test-DbaDiskAlignment',
    'Get-DbaStartupParameter',
    'Get-DbaSpn',
    'Test-DbaSpn',
    'Set-DbaSpn',
    'Remove-DbaSpn',
    'Get-DbaService',
    'Get-DbaClientProtocol',
    'Get-DbaWindowsLog',
    # WPF
    'Show-DbaServerFileSystem',
    'Show-DbaDbList',
    # AD?
    'Test-DbaWindowsLogin',
    'Find-DbaLoginInGroup',
    # 3rd party non-core DLL or exe
    'Export-DbaDacPackage', # relies on sqlpackage.exe
    # Config system
    'Get-DbatoolsConfig',
    'Get-DbatoolsConfigValue',
    'Set-DbatoolsConfig',
    'Register-DbatoolsConfig',
    # Unknown
    'Get-DbaErrorLog',
    'Get-DbaManagementObject',
    'Test-DbaManagementObject'
)

# If a developer or appveyor calls the psm1 directly, they want all functions
# So do not explicity export because everything else is then implicity excluded
if (-not $script:multiFileImport) {
    if (($PSVersionTable.Keys -contains "Platform")) {
        if ($PSVersionTable.Platform -ne "Win32NT") {
            Export-ModuleMember -Function $script:xplat
        } else {
            Export-ModuleMember -Function $script:xplat
            Export-ModuleMember -Function $script:windowsonly
        }
    } else {
        Export-ModuleMember -Function $script:xplat
        Export-ModuleMember -Function $script:windowsonly
        Export-ModuleMember -Function $script:noncoresmo
    }

    Export-ModuleMember -Alias $script:renames
    Export-ModuleMember -Alias $forever
    
    Export-ModuleMember -Cmdlet Select-DbaObject, Set-DbatoolsConfig

    Write-ImportTime -Text "Exported module member"
}

$timeout = 20000
$timeSpent = 0
while ($script:smoRunspace.Runspace.RunspaceAvailability -eq 'Busy') {
    Start-Sleep -Milliseconds 50
    $timeSpent = $timeSpent + 50

    if ($timeSpent -ge $timeout) {
        Write-Warning @"
The module import has hit a timeout while waiting for some background tasks to finish.
This may result in some commands not working as intended.
This should not happen under reasonable circumstances, please file an issue at:
https://github.com/sqlcollaborative/dbatools/issues
Or contact us directly in the #dbatools channel of the SQL Server Community Slack Channel:
https://dbatools.io/slack/
Timeout waiting for temporary runspaces reached! The Module import will complete, but some things may not work as intended
"@
        $global:smoRunspace = $script:smoRunspace
        break
    }
}

if ($script:smoRunspace) {
    $script:smoRunspace.Runspace.Close()
    $script:smoRunspace.Runspace.Dispose()
    $script:smoRunspace.Dispose()
    Remove-Variable -Name smoRunspace -Scope script
}
Write-ImportTime -Text "Waiting for runspaces to finish"

if ($PSCommandPath -like "*.psm1") {
    Update-TypeData -AppendPath (Resolve-Path -Path "$script:PSModuleRoot\xml\dbatools.Types.ps1xml")
    Write-ImportTime -Text "Loaded type extensions"
}
#. Import-ModuleFile "$script:PSModuleRoot\bin\type-extensions.ps1"
#Write-ImportTime -Text "Loaded type extensions"

[Sqlcollaborative.Dbatools.dbaSystem.SystemHost]::ModuleImported = $true;

if (Get-Module -Name sqlserver, sqlps) {
    if (Get-DbatoolsConfigValue -FullName Import.SqlpsCheck) {
        Write-Warning -Message 'SQLPS or SqlServer was previously imported during this session. If you encounter weird issues with dbatools, please restart PowerShell, then import dbatools without loading SQLPS or SqlServer first.'
        Write-Warning -Message 'To disable this message, type: Set-DbatoolsConfig -Name Import.SqlpsCheck -Value $false -PassThru | Register-DbatoolsConfig'
    }
}

#endregion Post-Import Cleanup
# SIG # Begin signature block
# MIIcYgYJKoZIhvcNAQcCoIIcUzCCHE8CAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUr6A9mM0LexiFXedn/8vUuQgn
# 3nOggheRMIIFGjCCBAKgAwIBAgIQAsF1KHTVwoQxhSrYoGRpyjANBgkqhkiG9w0B
# AQsFADByMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYD
# VQQLExB3d3cuZGlnaWNlcnQuY29tMTEwLwYDVQQDEyhEaWdpQ2VydCBTSEEyIEFz
# c3VyZWQgSUQgQ29kZSBTaWduaW5nIENBMB4XDTE3MDUwOTAwMDAwMFoXDTIwMDUx
# MzEyMDAwMFowVzELMAkGA1UEBhMCVVMxETAPBgNVBAgTCFZpcmdpbmlhMQ8wDQYD
# VQQHEwZWaWVubmExETAPBgNVBAoTCGRiYXRvb2xzMREwDwYDVQQDEwhkYmF0b29s
# czCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAI8ng7JxnekL0AO4qQgt
# Kr6p3q3SNOPh+SUZH+SyY8EA2I3wR7BMoT7rnZNolTwGjUXn7bRC6vISWg16N202
# 1RBWdTGW2rVPBVLF4HA46jle4hcpEVquXdj3yGYa99ko1w2FOWzLjKvtLqj4tzOh
# K7wa/Gbmv0Si/FU6oOmctzYMI0QXtEG7lR1HsJT5kywwmgcjyuiN28iBIhT6man0
# Ib6xKDv40PblKq5c9AFVldXUGVeBJbLhcEAA1nSPSLGdc7j4J2SulGISYY7ocuX3
# tkv01te72Mv2KkqqpfkLEAQjXgtM0hlgwuc8/A4if+I0YtboCMkVQuwBpbR9/6ys
# Z+sCAwEAAaOCAcUwggHBMB8GA1UdIwQYMBaAFFrEuXsqCqOl6nEDwGD5LfZldQ5Y
# MB0GA1UdDgQWBBRcxSkFqeA3vvHU0aq2mVpFRSOdmjAOBgNVHQ8BAf8EBAMCB4Aw
# EwYDVR0lBAwwCgYIKwYBBQUHAwMwdwYDVR0fBHAwbjA1oDOgMYYvaHR0cDovL2Ny
# bDMuZGlnaWNlcnQuY29tL3NoYTItYXNzdXJlZC1jcy1nMS5jcmwwNaAzoDGGL2h0
# dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9zaGEyLWFzc3VyZWQtY3MtZzEuY3JsMEwG
# A1UdIARFMEMwNwYJYIZIAYb9bAMBMCowKAYIKwYBBQUHAgEWHGh0dHBzOi8vd3d3
# LmRpZ2ljZXJ0LmNvbS9DUFMwCAYGZ4EMAQQBMIGEBggrBgEFBQcBAQR4MHYwJAYI
# KwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmRpZ2ljZXJ0LmNvbTBOBggrBgEFBQcwAoZC
# aHR0cDovL2NhY2VydHMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0U0hBMkFzc3VyZWRJ
# RENvZGVTaWduaW5nQ0EuY3J0MAwGA1UdEwEB/wQCMAAwDQYJKoZIhvcNAQELBQAD
# ggEBANuBGTbzCRhgG0Th09J0m/qDqohWMx6ZOFKhMoKl8f/l6IwyDrkG48JBkWOA
# QYXNAzvp3Ro7aGCNJKRAOcIjNKYef/PFRfFQvMe07nQIj78G8x0q44ZpOVCp9uVj
# sLmIvsmF1dcYhOWs9BOG/Zp9augJUtlYpo4JW+iuZHCqjhKzIc74rEEiZd0hSm8M
# asshvBUSB9e8do/7RhaKezvlciDaFBQvg5s0fICsEhULBRhoyVOiUKUcemprPiTD
# xh3buBLuN0bBayjWmOMlkG1Z6i8DUvWlPGz9jiBT3ONBqxXfghXLL6n8PhfppBhn
# daPQO8+SqF5rqrlyBPmRRaTz2GQwggUwMIIEGKADAgECAhAECRgbX9W7ZnVTQ7Vv
# lVAIMA0GCSqGSIb3DQEBCwUAMGUxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdp
# Q2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xJDAiBgNVBAMTG0Rp
# Z2lDZXJ0IEFzc3VyZWQgSUQgUm9vdCBDQTAeFw0xMzEwMjIxMjAwMDBaFw0yODEw
# MjIxMjAwMDBaMHIxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMx
# GTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xMTAvBgNVBAMTKERpZ2lDZXJ0IFNI
# QTIgQXNzdXJlZCBJRCBDb2RlIFNpZ25pbmcgQ0EwggEiMA0GCSqGSIb3DQEBAQUA
# A4IBDwAwggEKAoIBAQD407Mcfw4Rr2d3B9MLMUkZz9D7RZmxOttE9X/lqJ3bMtdx
# 6nadBS63j/qSQ8Cl+YnUNxnXtqrwnIal2CWsDnkoOn7p0WfTxvspJ8fTeyOU5JEj
# lpB3gvmhhCNmElQzUHSxKCa7JGnCwlLyFGeKiUXULaGj6YgsIJWuHEqHCN8M9eJN
# YBi+qsSyrnAxZjNxPqxwoqvOf+l8y5Kh5TsxHM/q8grkV7tKtel05iv+bMt+dDk2
# DZDv5LVOpKnqagqrhPOsZ061xPeM0SAlI+sIZD5SlsHyDxL0xY4PwaLoLFH3c7y9
# hbFig3NBggfkOItqcyDQD2RzPJ6fpjOp/RnfJZPRAgMBAAGjggHNMIIByTASBgNV
# HRMBAf8ECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIBhjATBgNVHSUEDDAKBggrBgEF
# BQcDAzB5BggrBgEFBQcBAQRtMGswJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmRp
# Z2ljZXJ0LmNvbTBDBggrBgEFBQcwAoY3aHR0cDovL2NhY2VydHMuZGlnaWNlcnQu
# Y29tL0RpZ2lDZXJ0QXNzdXJlZElEUm9vdENBLmNydDCBgQYDVR0fBHoweDA6oDig
# NoY0aHR0cDovL2NybDQuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0QXNzdXJlZElEUm9v
# dENBLmNybDA6oDigNoY0aHR0cDovL2NybDMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0
# QXNzdXJlZElEUm9vdENBLmNybDBPBgNVHSAESDBGMDgGCmCGSAGG/WwAAgQwKjAo
# BggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNlcnQuY29tL0NQUzAKBghghkgB
# hv1sAzAdBgNVHQ4EFgQUWsS5eyoKo6XqcQPAYPkt9mV1DlgwHwYDVR0jBBgwFoAU
# Reuir/SSy4IxLVGLp6chnfNtyA8wDQYJKoZIhvcNAQELBQADggEBAD7sDVoks/Mi
# 0RXILHwlKXaoHV0cLToaxO8wYdd+C2D9wz0PxK+L/e8q3yBVN7Dh9tGSdQ9RtG6l
# jlriXiSBThCk7j9xjmMOE0ut119EefM2FAaK95xGTlz/kLEbBw6RFfu6r7VRwo0k
# riTGxycqoSkoGjpxKAI8LpGjwCUR4pwUR6F6aGivm6dcIFzZcbEMj7uo+MUSaJ/P
# QMtARKUT8OZkDCUIQjKyNookAv4vcn4c10lFluhZHen6dGRrsutmQ9qzsIzV6Q3d
# 9gEgzpkxYz0IGhizgZtPxpMQBvwHgfqL2vmCSfdibqFT+hKUGIUukpHqaGxEMrJm
# oecYpJpkUe8wggZqMIIFUqADAgECAhADAZoCOv9YsWvW1ermF/BmMA0GCSqGSIb3
# DQEBBQUAMGIxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAX
# BgNVBAsTEHd3dy5kaWdpY2VydC5jb20xITAfBgNVBAMTGERpZ2lDZXJ0IEFzc3Vy
# ZWQgSUQgQ0EtMTAeFw0xNDEwMjIwMDAwMDBaFw0yNDEwMjIwMDAwMDBaMEcxCzAJ
# BgNVBAYTAlVTMREwDwYDVQQKEwhEaWdpQ2VydDElMCMGA1UEAxMcRGlnaUNlcnQg
# VGltZXN0YW1wIFJlc3BvbmRlcjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
# ggEBAKNkXfx8s+CCNeDg9sYq5kl1O8xu4FOpnx9kWeZ8a39rjJ1V+JLjntVaY1sC
# SVDZg85vZu7dy4XpX6X51Id0iEQ7Gcnl9ZGfxhQ5rCTqqEsskYnMXij0ZLZQt/US
# s3OWCmejvmGfrvP9Enh1DqZbFP1FI46GRFV9GIYFjFWHeUhG98oOjafeTl/iqLYt
# WQJhiGFyGGi5uHzu5uc0LzF3gTAfuzYBje8n4/ea8EwxZI3j6/oZh6h+z+yMDDZb
# esF6uHjHyQYuRhDIjegEYNu8c3T6Ttj+qkDxss5wRoPp2kChWTrZFQlXmVYwk/PJ
# YczQCMxr7GJCkawCwO+k8IkRj3cCAwEAAaOCAzUwggMxMA4GA1UdDwEB/wQEAwIH
# gDAMBgNVHRMBAf8EAjAAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMIMIIBvwYDVR0g
# BIIBtjCCAbIwggGhBglghkgBhv1sBwEwggGSMCgGCCsGAQUFBwIBFhxodHRwczov
# L3d3dy5kaWdpY2VydC5jb20vQ1BTMIIBZAYIKwYBBQUHAgIwggFWHoIBUgBBAG4A
# eQAgAHUAcwBlACAAbwBmACAAdABoAGkAcwAgAEMAZQByAHQAaQBmAGkAYwBhAHQA
# ZQAgAGMAbwBuAHMAdABpAHQAdQB0AGUAcwAgAGEAYwBjAGUAcAB0AGEAbgBjAGUA
# IABvAGYAIAB0AGgAZQAgAEQAaQBnAGkAQwBlAHIAdAAgAEMAUAAvAEMAUABTACAA
# YQBuAGQAIAB0AGgAZQAgAFIAZQBsAHkAaQBuAGcAIABQAGEAcgB0AHkAIABBAGcA
# cgBlAGUAbQBlAG4AdAAgAHcAaABpAGMAaAAgAGwAaQBtAGkAdAAgAGwAaQBhAGIA
# aQBsAGkAdAB5ACAAYQBuAGQAIABhAHIAZQAgAGkAbgBjAG8AcgBwAG8AcgBhAHQA
# ZQBkACAAaABlAHIAZQBpAG4AIABiAHkAIAByAGUAZgBlAHIAZQBuAGMAZQAuMAsG
# CWCGSAGG/WwDFTAfBgNVHSMEGDAWgBQVABIrE5iymQftHt+ivlcNK2cCzTAdBgNV
# HQ4EFgQUYVpNJLZJMp1KKnkag0v0HonByn0wfQYDVR0fBHYwdDA4oDagNIYyaHR0
# cDovL2NybDMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0QXNzdXJlZElEQ0EtMS5jcmww
# OKA2oDSGMmh0dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEFzc3VyZWRJ
# RENBLTEuY3JsMHcGCCsGAQUFBwEBBGswaTAkBggrBgEFBQcwAYYYaHR0cDovL29j
# c3AuZGlnaWNlcnQuY29tMEEGCCsGAQUFBzAChjVodHRwOi8vY2FjZXJ0cy5kaWdp
# Y2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURDQS0xLmNydDANBgkqhkiG9w0BAQUF
# AAOCAQEAnSV+GzNNsiaBXJuGziMgD4CH5Yj//7HUaiwx7ToXGXEXzakbvFoWOQCd
# 42yE5FpA+94GAYw3+puxnSR+/iCkV61bt5qwYCbqaVchXTQvH3Gwg5QZBWs1kBCg
# e5fH9j/n4hFBpr1i2fAnPTgdKG86Ugnw7HBi02JLsOBzppLA044x2C/jbRcTBu7k
# A7YUq/OPQ6dxnSHdFMoVXZJB2vkPgdGZdA0mxA5/G7X1oPHGdwYoFenYk+VVFvC7
# Cqsc21xIJ2bIo4sKHOWV2q7ELlmgYd3a822iYemKC23sEhi991VUQAOSK2vCUcIK
# SK+w1G7g9BQKOhvjjz3Kr2qNe9zYRDCCBs0wggW1oAMCAQICEAb9+QOWA63qAArr
# Pye7uhswDQYJKoZIhvcNAQEFBQAwZTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERp
# Z2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEkMCIGA1UEAxMb
# RGlnaUNlcnQgQXNzdXJlZCBJRCBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTIx
# MTExMDAwMDAwMFowYjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IElu
# YzEZMBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEhMB8GA1UEAxMYRGlnaUNlcnQg
# QXNzdXJlZCBJRCBDQS0xMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
# 6IItmfnKwkKVpYBzQHDSnlZUXKnE0kEGj8kz/E1FkVyBn+0snPgWWd+etSQVwpi5
# tHdJ3InECtqvy15r7a2wcTHrzzpADEZNk+yLejYIA6sMNP4YSYL+x8cxSIB8HqIP
# kg5QycaH6zY/2DDD/6b3+6LNb3Mj/qxWBZDwMiEWicZwiPkFl32jx0PdAug7Pe2x
# QaPtP77blUjE7h6z8rwMK5nQxl0SQoHhg26Ccz8mSxSQrllmCsSNvtLOBq6thG9I
# hJtPQLnxTPKvmPv2zkBdXPao8S+v7Iki8msYZbHBc63X8djPHgp0XEK4aH631XcK
# J1Z8D2KkPzIUYJX9BwSiCQIDAQABo4IDejCCA3YwDgYDVR0PAQH/BAQDAgGGMDsG
# A1UdJQQ0MDIGCCsGAQUFBwMBBggrBgEFBQcDAgYIKwYBBQUHAwMGCCsGAQUFBwME
# BggrBgEFBQcDCDCCAdIGA1UdIASCAckwggHFMIIBtAYKYIZIAYb9bAABBDCCAaQw
# OgYIKwYBBQUHAgEWLmh0dHA6Ly93d3cuZGlnaWNlcnQuY29tL3NzbC1jcHMtcmVw
# b3NpdG9yeS5odG0wggFkBggrBgEFBQcCAjCCAVYeggFSAEEAbgB5ACAAdQBzAGUA
# IABvAGYAIAB0AGgAaQBzACAAQwBlAHIAdABpAGYAaQBjAGEAdABlACAAYwBvAG4A
# cwB0AGkAdAB1AHQAZQBzACAAYQBjAGMAZQBwAHQAYQBuAGMAZQAgAG8AZgAgAHQA
# aABlACAARABpAGcAaQBDAGUAcgB0ACAAQwBQAC8AQwBQAFMAIABhAG4AZAAgAHQA
# aABlACAAUgBlAGwAeQBpAG4AZwAgAFAAYQByAHQAeQAgAEEAZwByAGUAZQBtAGUA
# bgB0ACAAdwBoAGkAYwBoACAAbABpAG0AaQB0ACAAbABpAGEAYgBpAGwAaQB0AHkA
# IABhAG4AZAAgAGEAcgBlACAAaQBuAGMAbwByAHAAbwByAGEAdABlAGQAIABoAGUA
# cgBlAGkAbgAgAGIAeQAgAHIAZQBmAGUAcgBlAG4AYwBlAC4wCwYJYIZIAYb9bAMV
# MBIGA1UdEwEB/wQIMAYBAf8CAQAweQYIKwYBBQUHAQEEbTBrMCQGCCsGAQUFBzAB
# hhhodHRwOi8vb2NzcC5kaWdpY2VydC5jb20wQwYIKwYBBQUHMAKGN2h0dHA6Ly9j
# YWNlcnRzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEFzc3VyZWRJRFJvb3RDQS5jcnQw
# gYEGA1UdHwR6MHgwOqA4oDaGNGh0dHA6Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9EaWdp
# Q2VydEFzc3VyZWRJRFJvb3RDQS5jcmwwOqA4oDaGNGh0dHA6Ly9jcmw0LmRpZ2lj
# ZXJ0LmNvbS9EaWdpQ2VydEFzc3VyZWRJRFJvb3RDQS5jcmwwHQYDVR0OBBYEFBUA
# EisTmLKZB+0e36K+Vw0rZwLNMB8GA1UdIwQYMBaAFEXroq/0ksuCMS1Ri6enIZ3z
# bcgPMA0GCSqGSIb3DQEBBQUAA4IBAQBGUD7Jtygkpzgdtlspr1LPUukxR6tWXHvV
# DQtBs+/sdR90OPKyXGGinJXDUOSCuSPRujqGcq04eKx1XRcXNHJHhZRW0eu7NoR3
# zCSl8wQZVann4+erYs37iy2QwsDStZS9Xk+xBdIOPRqpFFumhjFiqKgz5Js5p8T1
# zh14dpQlc+Qqq8+cdkvtX8JLFuRLcEwAiR78xXm8TBJX/l/hHrwCXaj++wc4Tw3G
# XZG5D2dFzdaD7eeSDY2xaYxP+1ngIw/Sqq4AfO6cQg7PkdcntxbuD8O9fAqg7iwI
# VYUiuOsYGk38KiGtSTGDR5V3cdyxG0tLHBCcdxTBnU8vWpUIKRAmMYIEOzCCBDcC
# AQEwgYYwcjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcG
# A1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTExMC8GA1UEAxMoRGlnaUNlcnQgU0hBMiBB
# c3N1cmVkIElEIENvZGUgU2lnbmluZyBDQQIQAsF1KHTVwoQxhSrYoGRpyjAJBgUr
# DgMCGgUAoHgwGAYKKwYBBAGCNwIBDDEKMAigAoAAoQKAADAZBgkqhkiG9w0BCQMx
# DAYKKwYBBAGCNwIBBDAcBgorBgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkq
# hkiG9w0BCQQxFgQURUVtRkhuVDqnH8Y0nhzhyMFCUm0wDQYJKoZIhvcNAQEBBQAE
# ggEADwhOshU8MOn2kdiZKjVPSaplDY0HtiUosd4gEB6sVeQ9wB6bpYyS20ixjlqh
# Ha4LXLWq4EPwsIGaPaKFb6K7gX7lmCVkyZauFmLBbprWSxU7EQQNTVVk809bq/KA
# nPK90YGYRx4BvbumvYe0LXxXJgWTPGxMFAOCbe8xUS2AXnWSbIGfwzdu6dqJgf3X
# ueW6Ij9MMid2DYgLbR7bTjGR3IQE5tFMBkpSlReJVw7hSD4mq74WYKuXrQir3Lp2
# Zue5nAvK3rpl0fe08YLXJ7Q0edqWcILn9C97lRGF7i2YH/4ZQkwFHPpK9qya66x3
# 8qEMsdomXi81hZKz1thVXvYIXqGCAg8wggILBgkqhkiG9w0BCQYxggH8MIIB+AIB
# ATB2MGIxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNV
# BAsTEHd3dy5kaWdpY2VydC5jb20xITAfBgNVBAMTGERpZ2lDZXJ0IEFzc3VyZWQg
# SUQgQ0EtMQIQAwGaAjr/WLFr1tXq5hfwZjAJBgUrDgMCGgUAoF0wGAYJKoZIhvcN
# AQkDMQsGCSqGSIb3DQEHATAcBgkqhkiG9w0BCQUxDxcNMTkwMTA4MTkwNzM1WjAj
# BgkqhkiG9w0BCQQxFgQU/jy8ua785lOeUi+N3M2W9ZPQjsAwDQYJKoZIhvcNAQEB
# BQAEggEAB3WwkmZm87G8fJXgwgHsFmIycBc8B9UhknSE9l4HwsJi59gOpmkHKzvg
# d0X+3RAnOZQcfD4PFWG08aTBC5K424/o7vqZ9ay/teWEPS869kfeclurksWs63qo
# v8CgP7wrbrb4cHyTwuT5OebfYGr7d/8oVeFrU981KWLrrx5bOSbFgBGoCJS2Dd8r
# YeK6m0rFOY24ZtM7bTLmwmdYes0kHNggCY0l0hFAvcphOgdVXkbPj9C7E6ftYjuS
# +aABnS3I4d7fSuQqjSISJ9DGryev9kWuxyXtOgAHRwBBn1ePDcbSmg7l9RAQKIFU
# C9vXV4PLTPByQdhhI0jItcaGbxk07w==
# SIG # End signature block
tools\dbatools\en-us\about_dbatools.help.txt
TOPIC
	about_dbatools
	
SHORT DESCRIPTION
	Gives on overview over the advanced dbatools topics
	
LONG DESCRIPTION
	Welcome to the dbatools help central.
	This guide tries to show you how to best get help.
	
	Over the project's lifetime, dbatools has grown explosively and many
	features were added to cope with the sheer scale of this project. Thus,
	dbatools has become highly complex as far as a PowerShell module goes. With
	great complexity comes a great need for documentation.
	Which is where this article comes in.
	
	
	#-------------------------------------------------------------------------#
	#                           Table of Contents                             #
	#-------------------------------------------------------------------------#

	- Getting Help
	- Import Options
	
	
	#-------------------------------------------------------------------------#
	#                              Getting Help                               #
	#-------------------------------------------------------------------------#
	
	When something breaks unexpectedly, you'll probably want help. We have put
	together a guide to help you through our process:
	
	  Get-Help about_dbatools_support
	
	
	#-------------------------------------------------------------------------#
	#                             Import Options                              #
	#-------------------------------------------------------------------------#
	
	When designing the way the module is imported, we had to make several trade-
	offs. Not every decision we made is always the right way for everybody
	however, so we set up some options that let you decide, which way you
	prefer. Basically, we had to balance import time vs. security policies and
	resource cost. This guide explains what the settings do and how to set them:
	
	  Get-Help about_dbatools_importoptions
	
	
KEYWORDS
	dbatools general
tools\dbatools\en-us\about_dbatools_importoptions.help.txt
TOPIC
	about_dbatools_importoptions
	
SHORT DESCRIPTION
	Explains the various options of how to import dbatools.
	
LONG DESCRIPTION
	Welcome to our guide to importing dbatools. Since one glove fits NOT all,
	we have implemented various ways in which you can import the module. These
	options may have security implications, may be more aimed at developers, or
	may reduce resource need in return for slower import times.
	
	All these settings can be set by variable or registry key, making it
	possible to enforce these settings by policy.
	
	
	#-------------------------------------------------------------------------#
	#                                  Index                                  #
	#-------------------------------------------------------------------------#
	
	- Configuring settings
	- Serial import
	- Dotsource on import
	- Dll Copy on import
	- Build dbatools library on import
	
	
	#-------------------------------------------------------------------------#
	#                          Configuring settings                           #
	#-------------------------------------------------------------------------#
	
	Import settings can be set at three levels:
	
	- Per Script
	- Per User
	- Per Computer
	
	Per Script:
	When configured per script, declare the respective 'dbatools_XXXXX' variable
	to $true before import. The variable name is listed with the description of
	the individual options.
	Note that this must be done BEFORE importing dbatools. If the script is
	called from a powershell process that has dbatools already installed, it
	will be ignored and have no effect.
	
	Per User:
	The individual settings are DWORD properties found in the following key:
	
	  HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\System
	
	The value name is listed with the description of the individual options.
	Set the value to '1' in order to enable the option.
	
	Per Computer:
	The individual settings are DWORD properties found in the following key:
	
	  HKLM:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\System
	
	The value name is listed with the description of the individual options.
	Set the value to '1' in order to enable the option.
	
	Note on competing settings:
	This system works on an anybody-in basis. Meaning that if any single setting
	enables an import option, the others cannot disable the setting. A script
	that has been set to import serial will do so, even if the registry settings
	are explicitly set to '0'.
	
	
	#-------------------------------------------------------------------------#
	#                              Serial import                              #
	#-------------------------------------------------------------------------#
	
	  $dbatools_serialimport = $true | SerialImport: 1
	
	In order to optimize import speed, dbatools loads its components in
	parallel. This places a heavy load on CPU however. Since import speed isn't
	that important on unattended scripts, it is recommended to enable serial
	import for them, avoiding CPU spikes.
	
	
	#-------------------------------------------------------------------------#
	#                           Dotsource on import                           #
	#-------------------------------------------------------------------------#
	
	  $dbatools_dotsourcemodule = $true | DoDotSource: 1
	
	When loading the module, we read the files to memory and import straight,
	rather than importing the individual script files using dotsourcing. This is
	faster at no extra resource cost, especially on older PowerShell versions.
	The downside however is that the individual files are not checked for valid
	signatures. Company policy may require enabling this for security
	compliance. It also is often enabled by developers, as it makes debugging
	easier.
	
	
	#-------------------------------------------------------------------------#
	#                           Dll Copy on import                            #
	#-------------------------------------------------------------------------#
	
	  $dbatools_copydllmode = $true | CopyDllMode: 1
	
	The module includes a large number of dll files. These files will be locked
	as long as a PowerShell console using the module is open. This makes it
	impossible to update the module into the same folder (as older versions of
	PowerShell will do). In order to support a proper update, we support copy-
	ing the dll files and importing them from a separate folder. With that,
	users can then use our Update-Dbatools command to update the module while it
	is imported.
	Enabling this setting significantly increases import time and can be a
	security issue, only enable it for updating the module.
	
	
	#-------------------------------------------------------------------------#
	#                    Build dbatools library on import                     #
	#-------------------------------------------------------------------------#
	
	  $dbatools_alwaysbuildlibrary = $true | AlwaysBuildLibrary: 1
	
	This is a pure developer feature. Setting this will compile the dbatools
	library on every import. This feature requires an installed Visual Studio.
	This allows fast iterative tests on the library, but has no production use.
	
	
KEYWORDS
	dbatools import
tools\dbatools\en-us\about_dbatools_support.help.txt
TOPIC
	about_dbatools_support
	
SHORT DESCRIPTION
	Describes how to contact support and what information we need
	
LONG DESCRIPTION
	Welcome to the dbatools support guide.
	If you are reading this, odds are, something went wrong and you are looking
	for support. Sorry for the inconvenience - we try our best to have dbatools
	as free of bugs as we can manage. Doesn't always work out.
	
	This article describes how you can reach us and what information we need
	when you do.
	
	
	#-------------------------------------------------------------------------#
	#                           Table of Contents                             #
	#-------------------------------------------------------------------------#

	- Getting Help
	- Troubleshooting Support
	- A matter of timing
	- What happens now?
	- The world need not burn
	
	
	#-------------------------------------------------------------------------#
	#                              Getting Help                               #
	#-------------------------------------------------------------------------#
	
	When something breaks unexpectedly, you'll probably want help. Well, most of
	us in the team work on dbatools, because we a) have fun coding and b) like
	the community (there is no pay involved whatsoever). So, come see us in our
	Slack channel or file an issue on github. We will gladly attempt to help you
	with any technical issues using our module (we love our module, we'll remove
	any malfunctioning blemishes that we can!).
	
	In order to find us, you can visit us on Slack by following this link:
	https://dbatools.io/slack/
	This has the advantage of the easiest interaction and often the fastest
	resolution times for smaller issues.
	
	Alternatively, you can file an issue on github:
	https://github.com/sqlcollaborative/dbatools/issues
	(Don't worry: It's relatively straightforward and easy to do)
	
	When you describe an error, please be prepared to provide some information,
	such as what code you were trying to execute and what the error was. For
	more details on this, see the next chapter: "Troubleshooting Support"
	
	
	#-------------------------------------------------------------------------#
	#                         Troubleshooting Support                         #
	#-------------------------------------------------------------------------#
	
	When trying to figure out, what went wrong, we usually need information,
	quite a bit of it, in fact. Usual information we care about:
	- Code/line you were running
	- Output / Error / Warning received
	- Exception contents
	- Execution log
	- PowerShell Version
	- Operating System
	Now, we rarely need all of that, but often we don't know what of it we need
	before looking at it in more detail. That said, I highly recommend providing
	the first three points immediately, as they are fast to gather and already
	help a lot. We may ask for more as it comes up.
	
	# Code/line you were running #
	#----------------------------#
	
	Literally the code you executed. Make it as simple as possible and still
	produce the error. Make sure to replace sensitive data before posting it.
	If you can reduce it to a single line, that's great! (But don't sweat it if
	it's still more)
	
	# Output / Error / Warning received #
	#-----------------------------------#
	
	Generally, we catch errors and write warnings by default. Report what it
	wrote if that is the case. Same for red exception textes. Sometimes however,
	a command may just refuse to do anything at all. In that case it might just
	return nothing. If it doesn't write a warning or throw an exception, tell us
	what you expected it to do and what it did instead.
	Screenshots work very well for this.
	
	# Exception Contents #
	#--------------------#
	
	If the code threw an exception or wrote a warning, behind the scenes some
	code failed to work as designed. This failure information is usually the
	most valuable piece of information for troubleshooting. Generally, you can
	see that exception content by running the following line:
	
	  $error[0] | Select *
	
	Directly after the command failed. Screenshot it.
	
	# Execution Log #
	#---------------#
	
	Dbatools logs a lot of information about how a function processes its logic.
	You can access that information by running Get-DbatoolsLog. In order to 
	send in this information, start a new process and produce the error, then
	execute the following line:
	
	  Get-DbatoolsLog | Export-Csv messagelog.csv
	
	This will export the entire log into a csv file. You may want to edit out
	confidential information (replace it with something harmles) before
	submitting it.
	
	# PowerShell Version #
	#--------------------#
	
	We try to support versions 3-5.1 of PowerShell. Sometimes however we mess up
	and something doesn't work on all versions. Thus the actual PowerShell
	version is often of interest. You can find this information by running the
	following line:
	
	  $PSVersionTable
	
	# Operating System #
	#------------------#
	
	What version of Windows are you running your code on?
	
	# Ugh, this is a bit much, can't you just gather what you need yourself?! #
	#-------------------------------------------------------------------------#
	
	Yes, we can! We've got a command that gathers all the data that it can and
	bundles it in a zip file for submission. Beware though: It is seriously hard
	to hide or redact data from it, as it gathers a lot and stores it in an XML
	file that must be edited from PowerShell, if at all. If you don't
	particularly worry about sharing the data though, simply run this command:
	
	  New-DbatoolsSupportPackage
	
	It'll handle the gathering. Just submit the resultant zip file and we have
	all the information your console has to give.
	
	
	#-------------------------------------------------------------------------#
	#                            A matter of timing                           #
	#-------------------------------------------------------------------------#
	
	When gathering information for an error, we highly recommend taking the
	following steps:
	
	- Start a new PowerShell console
	- Perform the action necessary to reproduce the error
	- Gather data
	
	This has two key benefits:
	- The least amount of data gets collected, meaning we have to search through
	  less material to find the cause.
	- Reduces the likelyhood of accidentally sharing confidential data
	
	
	#-------------------------------------------------------------------------#
	#                            What happens now?                            #
	#-------------------------------------------------------------------------#
	
	Alright, you've gathered the data needed and told us about the issue? Good.
	What happens next usually depends on what kind of issue it is and where you
	went to report it:
	
	Reported on Slack
	- Minor bug: When you report what turns out to be a minor bug (minor
	  refering to the technical complexity of the issue, not your problem that
	  lead you to us), especially on the slack channels, odds are, on of us
	  picked it up and immediately resolved it. In this case we'll tell you
	  "it's handled" and that's it as far as you go: In the next release, the
	  issue will be gone.
	- Major issue: Some bugs are just too technically complex to solve on the
	  fly. In those cases we will ask you to file an issue or file it for you,
	  whichever you prefer. We'll try to see it resolved in a timely manner and
	  inform you as it has been resolved or ask you to try out a current build
	  and confirm it.
	
	Reported on GitHub
	The key differences between reporting a problem on Github and doing so on
	Slack is that are:
	
	a) We cannot ask questions directly as you post.
	b) Reporting the issue does not require team members to be present.
	
	We often ARE there, hanging out in Slack, but it is not automatically
	guaranteed. That being said, after you have filed an issue on GitHub, please
	keep track of that issue, as we will likely ask questions or ask you to test
	out solutions. Really, the process is mostly the same, only that since we
	can't make sure all the information we need is there when you report it, we
	may need to ask for it.
	
	
	#-------------------------------------------------------------------------#
	#                         The world need not burn                         #
	#-------------------------------------------------------------------------#
	
	Thank you for reading our advisory on receiving support. Note however: It is
	totally not necessary to wait until something breaks to contact us: Come on
	over into the slack channels and hang out, discuss sql server or the
	benefits of the	local breweries.
	
	
KEYWORDS
	dbatools general support help
tools\dbatools\functions\Add-DbaAgDatabase.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Add-DbaAgDatabase {
    <#
    .SYNOPSIS
        Adds a database to an availability group on a SQL Server instance.

    .DESCRIPTION
        Adds a database to an availability group on a SQL Server instance.

        Before joining the replica databases to the availablity group, the databases will be initialized with automatic seeding or full/log backup.

   .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.

        This should be the primary replica.

    .PARAMETER SqlCredential
        Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database or databases to add.

    .PARAMETER AvailabilityGroup
        The availability group where the databases will be added.

    .PARAMETER Secondary
        Not required - the command will figure this out. But if you'd like to be explicit about replicas, this will help.

    .PARAMETER SecondarySqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER InputObject
        Enables piping from Get-DbaDatabase, Get-DbaDbSharePoint and more.

    .PARAMETER SeedingMode
        Specifies how the secondary replica will be initially seeded.

        Automatic enables direct seeding. This method will seed the secondary replica over the network. This method does not require you to backup and restore a copy of the primary database on the replica.

        Manual requires you to create a backup of the database on the primary replica and manually restore that backup on the secondary replica.

        If not specified, the setting from the availability group replica will be used. Otherwise the setting will be updated.

    .PARAMETER SharedPath
        The network share where the backups will be backed up and restored from.

        Each SQL Server service account must have access to this share.

        NOTE: If a backup / restore is performed, the backups will be left in tact on the network share.

    .PARAMETER UseLastBackup
        Use the last full backup of database.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: AvailabilityGroup, HA, AG
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Add-DbaAgDatabase

    .EXAMPLE
        PS C:\> Add-DbaAgDatabase -SqlInstance sql2017a -AvailabilityGroup ag1 -Database db1, db2 -Confirm

        Adds db1 and db2 to ag1 on sql2017a. Prompts for confirmation.

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sql2017a | Out-GridView -Passthru | Add-DbaAgDatabase -AvailabilityGroup ag1

        Adds selected databases from sql2017a to ag1

    .EXAMPLE
        PS C:\> Get-DbaDbSharePoint -SqlInstance sqlcluster | Add-DbaAgDatabase -AvailabilityGroup SharePoint

        Adds SharePoint databases as found in SharePoint_Config on sqlcluster to ag1 on sqlcluster

    .EXAMPLE
        PS C:\> Get-DbaDbSharePoint -SqlInstance sqlcluster -ConfigDatabase SharePoint_Config_2019 | Add-DbaAgDatabase -AvailabilityGroup SharePoint

        Adds SharePoint databases as found in SharePoint_Config_2019 on sqlcluster to ag1 on sqlcluster
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(Mandatory)]
        [string]$AvailabilityGroup,
        [string[]]$Database,
        [DbaInstanceParameter[]]$Secondary,
        [PSCredential]$SecondarySqlCredential,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [ValidateSet('Automatic', 'Manual')]
        [string]$SeedingMode,
        [string]$SharedPath,
        [switch]$UseLastBackup,
        [switch]$EnableException
    )
    process {
        if ((Test-Bound -ParameterName SqlInstance)) {
            if ((Test-Bound -Not -ParameterName Database) -or (Test-Bound -Not -ParameterName AvailabilityGroup)) {
                Stop-Function -Message "You must specify one or more databases and one Availability Group when using the SqlInstance parameter."
                return
            }
        }

        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $instance -SqlCredential $SqlCredential -Database $Database
        }

        foreach ($db in $InputObject) {
            $allbackups = @{
            }

            $Primary = $db.Parent
            # check primary, should be run against primary
            $ag = Get-DbaAvailabilityGroup -SqlInstance $db.Parent -AvailabilityGroup $AvailabilityGroup

            if ($ag.AvailabilityDatabases.Name -contains $db.Name) {
                Stop-Function -Message "$($db.Name) is already joined to $($ag.Name)" -Continue
            }

            if (-not $Secondary) {
                $secondaryReplicas = $ag.AvailabilityReplicas | Where-Object Role -eq Secondary
            } else {
                $secondaryReplicas = Get-DbaAgReplica -SqlInstance $Secondary -SqlCredential $SecondarySqlCredential -AvailabilityGroup $ag.Name | Where-Object Role -eq Secondary
            }

            if ($SeedingMode -eq "Automatic") {
                # first check
                if ($Pscmdlet.ShouldProcess($Primary, "Backing up $db to NUL")) {
                    $null = Backup-DbaDatabase -BackupFileName NUL -SqlInstance $Primary -SqlCredential $SqlCredential -Database $db
                }
            }

            if ($Pscmdlet.ShouldProcess($ag.Parent.Name, "Adding availability group $db to $($db.Parent.Name)")) {
                try {
                    $agdb = New-Object Microsoft.SqlServer.Management.Smo.AvailabilityDatabase($ag, $db.Name)
                    # something is up with .net create(), force a stop
                    Invoke-Create -Object $agdb
                    Get-DbaAgDatabase -SqlInstance $ag.Parent -Database $db.Name
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
                }
            }

            foreach ($replica in $secondaryReplicas) {

                $agreplica = Get-DbaAgReplica -SqlInstance $Primary -SqlCredential $SqlCredential -AvailabilityGroup $ag.name -Replica $replica.Name

                if ($SeedingMode) {
                    $agreplica.SeedingMode = $SeedingMode
                    $agreplica.alter()
                }
                $agreplica.refresh()
                $SeedingModeReplica = $agreplica.SeedingMode

                $primarydb = Get-DbaDatabase -SqlInstance $Primary -SqlCredential $SqlCredential -Database $db.name

                if ($SeedingModeReplica -ne 'Automatic') {
                    try {
                        if (-not $allbackups[$db]) {
                            if ($UseLastBackup) {
                                $allbackups[$db] = Get-DbaBackupHistory -SqlInstance $primarydb.Parent -Database $primarydb.Name -IncludeCopyOnly -Last -EnableException
                            } else {
                                $fullbackup = $primarydb | Backup-DbaDatabase -BackupDirectory $SharedPath -Type Full -EnableException
                                $logbackup = $primarydb | Backup-DbaDatabase -BackupDirectory $SharedPath -Type Log -EnableException
                                $allbackups[$db] = $fullbackup, $logbackup
                            }
                            Write-Message -Level Verbose -Message "Backups still exist on $SharedPath"
                        }
                        if ($Pscmdlet.ShouldProcess("$Secondary", "restoring full and log backups of $primarydb from $Primary")) {
                            # keep going to ensure output is shown even if dbs aren't added well.
                            $null = $allbackups[$db] | Restore-DbaDatabase -SqlInstance $replica.Parent.Parent -WithReplace -NoRecovery -TrustDbBackupHistory -EnableException
                        }
                    } catch {
                        Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
                    }
                }

                $replicadb = Get-DbaAgDatabase -SqlInstance $replica.Parent.Parent -Database $db.Name -AvailabilityGroup $ag.Name   #credential of secondary !!

                if ($replicadb -and -not ($SeedingModeReplica -eq 'Automatic')) {
                    if ($Pscmdlet.ShouldProcess($ag.Parent.Name, "Joining availability group $db to $($db.Parent.Name)")) {
                        $timeout = 1
                        do {
                            try {
                                Write-Message -Level Verbose -Message "Trying to add $($replicadb.Name) to $($replica.Name)"
                                $timeout++
                                $replicadb.JoinAvailablityGroup()
                                $replicadb.Refresh()
                                Start-Sleep -Seconds 1
                            } catch {
                                Stop-Function -Message "Error joining database to availability group" -ErrorRecord $_ -Continue
                            }
                        } while (-not $replicadb.IsJoined -and $timeout -lt 10)

                        if ($replicadb.IsJoined) {
                            $replicadb
                        } else {
                            Stop-Function -Continue -Message "Could not join $($replicadb.Name) to $($replica.Name)"
                        }
                    }
                } else {
                    $replicadb
                }
            }
        }
    }
}
tools\dbatools\functions\Add-DbaAgListener.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Add-DbaAgListener {
    <#
    .SYNOPSIS
        Adds a listener to an availability group on a SQL Server instance.

    .DESCRIPTION
        Adds a listener to an availability group on a SQL Server instance.

   .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.

    .PARAMETER SqlCredential
        Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER AvailabilityGroup
        The Availability Group to which a listener will be bestowed upon.

    .PARAMETER IPAddress
        Sets the IP address of the availability group listener.

    .PARAMETER SubnetMask
        Sets the subnet IP mask of the availability group listener. Defaults to 255.255.255.0.

    .PARAMETER Port
        Sets the port number used to communicate with the availability group. Defaults to 1433.

    .PARAMETER Dhcp
        Indicates whether the listener uses DHCP.

    .PARAMETER Passthru
        Don't create the listener, just pass thru an object that can be further customized before creation.

    .PARAMETER InputObject
        Enables piping from Get-DbaAvailabilityGroup

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: AvailabilityGroup, HA, AG
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Add-DbaAgListener

    .EXAMPLE
        PS C:\> Add-DbaAgListener -SqlInstance sql2017 -AvailabilityGroup SharePoint -IPAddress 10.0.20.20

        Creates a listener on 10.0.20.20 port 1433 for the SharePoint availability group on sql2017.

    .EXAMPLE
        PS C:\> Get-DbaAvailabilityGroup -SqlInstance sql2017 -AvailabilityGroup availabilitygroup1 | Add-DbaAgListener -Dhcp

        Creates a listener on port 1433 with a dynamic IP for the group1 availability group on sql2017.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$AvailabilityGroup,
        [ipaddress]$IPAddress,
        [ipaddress]$SubnetMask = "255.255.255.0",
        [int]$Port = 1433,
        [switch]$Dhcp,
        [switch]$Passthru,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.AvailabilityGroup[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ((Test-Bound -ParameterName SqlInstance) -and (Test-Bound -Not -ParameterName AvailabilityGroup)) {
            Stop-Function -Message "You must specify one or more databases and one or more Availability Groups when using the SqlInstance parameter."
            return
        }

        if ($SqlInstance) {
            $InputObject += Get-DbaAvailabilityGroup -SqlInstance $SqlInstance -SqlCredential $SqlCredential -AvailabilityGroup $AvailabilityGroup
        }

        foreach ($ag in $InputObject) {
            if ((Test-Bound -Not -ParameterName Name)) {
                $Name = $ag.Name
            }
            if ($Pscmdlet.ShouldProcess($ag.Parent.Name, "Adding $($IPAddress.IPAddressToString) to $($ag.Name)")) {
                try {
                    $aglistener = New-Object Microsoft.SqlServer.Management.Smo.AvailabilityGroupListener -ArgumentList $ag, $Name
                    $aglistener.PortNumber = $Port
                    $listenerip = New-Object Microsoft.SqlServer.Management.Smo.AvailabilityGroupListenerIPAddress -ArgumentList $aglistener

                    if (Test-Bound -ParameterName IPAddress) {
                        $listenerip.IPAddress = $IPAddress.IPAddressToString
                        $listenerip.SubnetMask = $SubnetMask.IPAddressToString
                    }

                    $listenerip.IsDHCP = $Dhcp
                    $aglistener.AvailabilityGroupListenerIPAddresses.Add($listenerip)

                    if ($Passthru) {
                        return $aglistener
                    } else {
                        # something is up with .net create(), force a stop
                        Invoke-Create -Object $aglistener
                    }
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_
                }
                Get-DbaAgListener -SqlInstance $ag.Parent -AvailabilityGroup $ag.Name -Listener $Name
            }
        }
    }
}
tools\dbatools\functions\Add-DbaAgReplica.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Add-DbaAgReplica {
    <#
    .SYNOPSIS
        Adds a replica to an availability group on a SQL Server instance.

    .DESCRIPTION
        Adds a replica to an availability group on a SQL Server instance.

        Automatically creates a database mirroring endpoint if required.

   .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.

    .PARAMETER SqlCredential
        Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Name
        The name of the replica. Defaults to the SQL Server instance name.

    .PARAMETER AvailabilityMode
        Sets the availability mode of the availability group replica. Options are: AsynchronousCommit and SynchronousCommit. SynchronousCommit is default.

    .PARAMETER FailoverMode
        Sets the failover mode of the availability group replica. Options are Automatic and Manual. Automatic is default.

    .PARAMETER BackupPriority
        Sets the backup priority availability group replica. Default is 50.

    .PARAMETER Endpoint
        By default, this command will attempt to find a DatabaseMirror endpoint. If one does not exist, it will create it.

        If an endpoint must be created, the name "hadr_endpoint" will be used. If an alternative is preferred, use Endpoint.

    .PARAMETER Passthru
        Don't create the replica, just pass thru an object that can be further customized before creation.

    .PARAMETER InputObject
        Enables piping from Get-DbaAvailabilityGroup.

    .PARAMETER ConnectionModeInPrimaryRole
        Specifies the connection intent modes of an Availability Replica in primary role. AllowAllConnections by default.

    .PARAMETER ConnectionModeInSecondaryRole
        Specifies the connection modes of an Availability Replica in secondary role. AllowAllConnections by default.

    .PARAMETER ReadonlyRoutingConnectionUrl
        Sets the read only routing connection url for the availability replica.

    .PARAMETER SeedingMode
        Specifies how the secondary replica will be initially seeded.

        Automatic enables direct seeding. This method will seed the secondary replica over the network. This method does not require you to backup and restore a copy of the primary database on the replica.

        Manual requires you to create a backup of the database on the primary replica and manually restore that backup on the secondary replica.

    .PARAMETER Certificate
        Specifies that the endpoint is to authenticate the connection using the certificate specified by certificate_name to establish identity for authorization.

        The far endpoint must have a certificate with the public key matching the private key of the specified certificate.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: AvailabilityGroup, HA, AG
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Add-DbaAgReplica

    .EXAMPLE
        PS C:\> Get-DbaAvailabilityGroup -SqlInstance sql2017a -AvailabilityGroup SharePoint | Add-DbaAgReplica -SqlInstance sql2017b

        Adds sql2017b to the SharePoint availability group on sql2017a

    .EXAMPLE
        PS C:\> Get-DbaAvailabilityGroup -SqlInstance sql2017a -AvailabilityGroup SharePoint | Add-DbaAgReplica -SqlInstance sql2017b -FailoverMode Manual

        Adds sql2017b to the SharePoint availability group on sql2017a with a manual failover mode.
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$Name,
        [ValidateSet('AsynchronousCommit', 'SynchronousCommit')]
        [string]$AvailabilityMode = "SynchronousCommit",
        [ValidateSet('Automatic', 'Manual', 'External')]
        [string]$FailoverMode = "Automatic",
        [int]$BackupPriority = 50,
        [ValidateSet('AllowAllConnections', 'AllowReadWriteConnections')]
        [string]$ConnectionModeInPrimaryRole = 'AllowAllConnections',
        [ValidateSet('AllowAllConnections', 'AllowNoConnections', 'AllowReadIntentConnectionsOnly')]
        [string]$ConnectionModeInSecondaryRole = 'AllowAllConnections',
        [ValidateSet('Automatic', 'Manual')]
        [string]$SeedingMode = 'Automatic',
        [string]$Endpoint,
        [switch]$Passthru,
        [string]$ReadonlyRoutingConnectionUrl,
        [string]$Certificate,
        [parameter(ValueFromPipeline, Mandatory)]
        [Microsoft.SqlServer.Management.Smo.AvailabilityGroup]$InputObject,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 11
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($Certificate) {
                $cert = Get-DbaDbCertificate -SqlInstance $server -Certificate $Certificate
                if (-not $cert) {
                    Stop-Function -Message "Certificate $Certificate does not exist on $instance" -ErrorRecord $_ -Target $Certificate -Continue
                }
            }

            $ep = Get-DbaEndpoint -SqlInstance $server -Type DatabaseMirroring

            if (-not $ep) {
                if ($Pscmdlet.ShouldProcess($server.Name, "Adding endpoint named $Endpoint to $instance")) {
                    if (-not $Endpoint) {
                        $Endpoint = "hadr_endpoint"
                    }
                    $ep = New-DbaEndpoint -SqlInstance $server -Name hadr_endpoint -Type DatabaseMirroring -EndpointEncryption Supported -EncryptionAlgorithm Aes -Certificate $Certificate
                    $null = $ep | Start-DbaEndpoint
                }
            }

            if ((Test-Bound -Not -ParameterName Name)) {
                $Name = $server.DomainInstanceName
            }

            if ($Pscmdlet.ShouldProcess($server.Name, "Creating a replica for $($InputObject.Name) named $Name")) {
                try {
                    $replica = New-Object Microsoft.SqlServer.Management.Smo.AvailabilityReplica -ArgumentList $InputObject, $Name
                    $replica.EndpointUrl = $ep.Fqdn
                    $replica.FailoverMode = [Microsoft.SqlServer.Management.Smo.AvailabilityReplicaFailoverMode]::$FailoverMode
                    $replica.AvailabilityMode = [Microsoft.SqlServer.Management.Smo.AvailabilityReplicaAvailabilityMode]::$AvailabilityMode
                    if ($server.EngineEdition -ne "Standard") {
                        $replica.ConnectionModeInPrimaryRole = [Microsoft.SqlServer.Management.Smo.AvailabilityReplicaConnectionModeInPrimaryRole]::$ConnectionModeInPrimaryRole
                        $replica.ConnectionModeInSecondaryRole = [Microsoft.SqlServer.Management.Smo.AvailabilityReplicaConnectionModeInSecondaryRole]::$ConnectionModeInSecondaryRole
                    }
                    $replica.BackupPriority = $BackupPriority

                    if ($ReadonlyRoutingConnectionUrl) {
                        $replica.ReadonlyRoutingConnectionUrl = $ReadonlyRoutingConnectionUrl
                    }

                    if ($SeedingMode -and $server.VersionMajor -ge 13) {
                        $replica.SeedingMode = $SeedingMode
                    }

                    if ($Passthru) {
                        return $replica
                    }

                    $defaults = 'ComputerName', 'InstanceName', 'SqlInstance', 'AvailabilityGroup', 'Name', 'Role', 'RollupSynchronizationState', 'AvailabilityMode', 'BackupPriority', 'EndpointUrl', 'SessionTimeout', 'FailoverMode', 'ReadonlyRoutingList'
                    $InputObject.AvailabilityReplicas.Add($replica)
                    $agreplica = $InputObject.AvailabilityReplicas[$Name]
                    if ($InputObject.State -eq 'Existing') {
                        Invoke-Create -Object $replica
                        $null = Join-DbaAvailabilityGroup -SqlInstance $instance -SqlCredential $SqlCredential -AvailabilityGroup $InputObject.Name
                    }
                    Add-Member -Force -InputObject $agreplica -MemberType NoteProperty -Name ComputerName -value $agreplica.Parent.ComputerName
                    Add-Member -Force -InputObject $agreplica -MemberType NoteProperty -Name InstanceName -value $agreplica.Parent.InstanceName
                    Add-Member -Force -InputObject $agreplica -MemberType NoteProperty -Name SqlInstance -value $agreplica.Parent.SqlInstance
                    Add-Member -Force -InputObject $agreplica -MemberType NoteProperty -Name AvailabilityGroup -value $agreplica.Parent.Name
                    Add-Member -Force -InputObject $agreplica -MemberType NoteProperty -Name Replica -value $agreplica.Name # backwards compat

                    Select-DefaultView -InputObject $agreplica -Property $defaults
                } catch {
                    $msg = $_.Exception.InnerException.InnerException.Message
                    if (-not $msg) {
                        $msg = $_
                    }
                    Stop-Function -Message $msg -ErrorRecord $_ -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Add-DbaCmsRegServer.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Add-DbaCmsRegServer {
    <#
    .SYNOPSIS
        Adds registered servers to SQL Server Central Management Server (CMS)

    .DESCRIPTION
        Adds registered servers to SQL Server Central Management Server (CMS). If you need more flexiblity, look into Import-DbaCmsRegServer which
        accepts multiple kinds of input and allows you to add reg servers from different CMSes.

    .PARAMETER SqlInstance
        The target SQL Server instance

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER ServerName
        Server Name is the actual SQL instance name (labeled Server Name)

    .PARAMETER Name
        Name is basically the nickname in SSMS CMS interface (labeled Registered Server Name)

    .PARAMETER Description
        Adds a description for the registered server

    .PARAMETER Group
        Adds the registered server to a specific group.

    .PARAMETER InputObject
        Allows the piping of a registered server group

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.

        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.

        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: RegisteredServer, CMS
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Add-DbaCmsRegServer

    .EXAMPLE
        PS C:\> Add-DbaCmsRegServer -SqlInstance sql2008 -ServerName sql01

        Creates a registered server on sql2008's CMS which points to the SQL Server, sql01. When scrolling in CMS, the name "sql01" will be visible.

    .EXAMPLE
        PS C:\> Add-DbaCmsRegServer -SqlInstance sql2008 -ServerName sql01 -Name "The 2008 Clustered Instance" -Description "HR's Dedicated SharePoint instance"

        Creates a registered server on sql2008's CMS which points to the SQL Server, sql01. When scrolling in CMS, "The 2008 Clustered Instance" will be visible.
        Clearly this is hard to explain ;)

    .EXAMPLE
        PS C:\> Add-DbaCmsRegServer -SqlInstance sql2008 -ServerName sql01 -Group hr\Seattle

        Creates a registered server on sql2008's CMS which points to the SQL Server, sql01. When scrolling in CMS, the name "sql01" will be visible within the Seattle group which is in the hr group.

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServerGroup -SqlInstance sql2008 -Group hr\Seattle | Add-DbaCmsRegServer -ServerName sql01111

        Creates a registered server on sql2008's CMS which points to the SQL Server, sql01. When scrolling in CMS, the name "sql01" will be visible within the Seattle group which is in the hr group.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(Mandatory)]
        [string]$ServerName,
        [string]$Name = $ServerName,
        [string]$Description,
        [object]$Group,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.RegisteredServers.ServerGroup[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if (-not $InputObject -and -not $SqlInstance) {
            Stop-Function -Message "You must either pipe in a registered server group or specify a sqlinstance"
            return
        }

        # double check in case a null name was bound
        if (-not $Name) {
            $Name = $ServerName
        }

        foreach ($instance in $SqlInstance) {
            if (($Group)) {
                if ($Group -is [Microsoft.SqlServer.Management.RegisteredServers.ServerGroup]) {
                    $InputObject += Get-DbaCmsRegServerGroup -SqlInstance $instance -SqlCredential $SqlCredential -Group $Group.Name
                } else {
                    $InputObject += Get-DbaCmsRegServerGroup -SqlInstance $instance -SqlCredential $SqlCredential -Group $Group
                }
            } else {
                $InputObject += Get-DbaCmsRegServerGroup -SqlInstance $instance -SqlCredential $SqlCredential -Id 1
            }

            if (-not $InputObject) {
                Stop-Function -Message "No matching groups found on $instance" -Continue
            }
        }

        foreach ($reggroup in $InputObject) {
            $parentserver = Get-RegServerParent -InputObject $reggroup

            if ($null -eq $parentserver) {
                Stop-Function -Message "Something went wrong and it's hard to explain, sorry. This basically shouldn't happen." -Continue
            }

            $server = $parentserver.ServerConnection.SqlConnectionObject

            if ($Pscmdlet.ShouldProcess($parentserver.SqlInstance, "Adding $ServerName")) {
                try {
                    $newserver = New-Object Microsoft.SqlServer.Management.RegisteredServers.RegisteredServer($reggroup, $Name)
                    $newserver.ServerName = $ServerName
                    $newserver.Description = $Description
                    $newserver.Create()

                    Get-DbaCmsRegServer -SqlInstance $server -Name $Name -ServerName $ServerName
                } catch {
                    Stop-Function -Message "Failed to add $ServerName on $($parentserver.SqlInstance)" -ErrorRecord $_ -Continue
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Add-DbaRegisteredServer
    }
}
tools\dbatools\functions\Add-DbaCmsRegServerGroup.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Add-DbaCmsRegServerGroup {
    <#
    .SYNOPSIS
        Adds registered server groups to SQL Server Central Management Server (CMS)

    .DESCRIPTION
        Adds registered server groups to SQL Server Central Management Server (CMS). If you need more flexibility, look into Import-DbaCmsRegServer which accepts multiple kinds of input and allows you to add reg servers and groups from different CMS.

    .PARAMETER SqlInstance
        The target SQL Server instance

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Name
        The name of the registered server group

    .PARAMETER Description
        The description for the registered server group

    .PARAMETER Group
        The SQL Server Central Management Server group. If no groups are specified, the new group will be created at the root.

    .PARAMETER InputObject
        Allows results from Get-DbaCmsRegServerGroup to be piped in

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.

        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.

        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: RegisteredServer, CMS
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Add-DbaCmsRegServerGroup

    .EXAMPLE
        PS C:\> Add-DbaCmsRegServerGroup -SqlInstance sql2012 -Name HR

        Creates a registered server group called HR, in the root of sql2012's CMS

    .EXAMPLE
        PS C:\> Add-DbaCmsRegServerGroup -SqlInstance sql2012, sql2014 -Name sub-folder -Group HR

        Creates a registered server group on sql2012 and sql2014 called sub-folder within the HR group

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServerGroup -SqlInstance sql2012, sql2014 -Group HR | Add-DbaCmsRegServerGroup -Name sub-folder

        Creates a registered server group on sql2012 and sql2014 called sub-folder within the HR group of each server

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(Mandatory)]
        [string]$Name,
        [string]$Description,
        [string]$Group,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.RegisteredServers.ServerGroup[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if (-not $InputObject -and -not $SqlInstance) {
            Stop-Function -Message "You must either pipe in a registered server group or specify a sqlinstance"
            return
        }
        foreach ($instance in $SqlInstance) {
            if ((Test-Bound -ParameterName Group)) {
                $InputObject += Get-DbaCmsRegServerGroup -SqlInstance $instance -SqlCredential $SqlCredential -Group $Group
            } else {
                $InputObject += Get-DbaCmsRegServerGroup -SqlInstance $instance -SqlCredential $SqlCredential -Id 1
            }
        }

        foreach ($reggroup in $InputObject) {
            $parentserver = Get-RegServerParent -InputObject $reggroup
            $server = $parentserver.ServerConnection.ServerInstance.SqlConnectionObject

            if ($null -eq $parentserver) {
                Stop-Function -Message "Something went wrong and it's hard to explain, sorry. This basically shouldn't happen." -Continue
            }

            if ($Pscmdlet.ShouldProcess($parentserver.SqlInstance, "Adding $Name")) {
                try {
                    $newgroup = New-Object Microsoft.SqlServer.Management.RegisteredServers.ServerGroup($reggroup, $Name)
                    $newgroup.Description = $Description
                    $newgroup.Create()

                    Get-DbaCmsRegServerGroup -SqlInstance $parentserver.ServerConnection.SqlConnectionObject -Group (Get-RegServerGroupReverseParse -object $newgroup)
                    $parentserver.ServerConnection.Disconnect()
                } catch {
                    Stop-Function -Message "Failed to add $reggroup on $server" -ErrorRecord $_ -Continue
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Add-DbaRegisteredServerGroup
    }
}
tools\dbatools\functions\Add-DbaComputerCertificate.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Add-DbaComputerCertificate {
    <#
    .SYNOPSIS
        Adds a computer certificate - useful for older systems.

    .DESCRIPTION
        Adds a computer certificate from a local or remote computer.

    .PARAMETER ComputerName
        The target SQL Server instance or instances. Defaults to localhost.

    .PARAMETER Credential
        Allows you to login to $ComputerName using alternative credentials.

    .PARAMETER SecurePassword
        The password for the certificate, if it is password protected.

    .PARAMETER Certificate
        The target certificate object.

    .PARAMETER Path
        The local path to the target certificate object.

    .PARAMETER Store
        Certificate store. Default is LocalMachine.

    .PARAMETER Folder
        Certificate folder. Default is My (Personal).

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .NOTES
        Tags: Certificate
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Add-DbaComputerCertificate -ComputerName Server1 -Path C:\temp\cert.cer

        Adds the local C:\temp\cert.cer to the remote server Server1 in LocalMachine\My (Personal).

    .EXAMPLE
        PS C:\> Add-DbaComputerCertificate -Path C:\temp\cert.cer

        Adds the local C:\temp\cert.cer to the local computer's LocalMachine\My (Personal) certificate store.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [Alias("ServerInstance", "SqlServer", "SqlInstance")]
        [DbaInstance[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [Alias("Password")]
        [SecureString]$SecurePassword,
        [parameter(ValueFromPipeline)]
        [System.Security.Cryptography.X509Certificates.X509Certificate2[]]$Certificate,
        [string]$Path,
        [string]$Store = "LocalMachine",
        [string]$Folder = "My",
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {

        if ($Path) {
            if (!(Test-Path -Path $Path)) {
                Stop-Function -Message "Path ($Path) does not exist." -Category InvalidArgument
                return
            }

            try {
                # This may be too much, but oh well
                $bytes = [System.IO.File]::ReadAllBytes($Path)
                $Certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
                $Certificate.Import($bytes, $SecurePassword, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::DefaultKeySet)
            } catch {
                Stop-Function -Message "Can't import certificate." -ErrorRecord $_
                return
            }
        }

        #region Remoting Script
        $scriptBlock = {

            param (
                $CertificateData,

                [SecureString]$SecurePassword,

                $Store,

                $Folder
            )

            $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
            $cert.Import($CertificateData, $SecurePassword, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::DefaultKeySet)
            Write-Message -Level Verbose -Message "Importing cert to $Folder\$Store"
            $tempStore = New-Object System.Security.Cryptography.X509Certificates.X509Store($Folder, $Store)
            $tempStore.Open('ReadWrite')
            $tempStore.Add($cert)
            $tempStore.Close()

            Write-Message -Level Verbose -Message "Searching Cert:\$Store\$Folder"
            Get-ChildItem "Cert:\$Store\$Folder" -Recurse | Where-Object { $_.Thumbprint -eq $cert.Thumbprint }
        }
        #endregion Remoting Script
    }
    process {
        if (Test-FunctionInterrupt) { return }

        if (-not $Certificate) {
            Stop-Function -Message "You must specify either Certificate or Path" -Category InvalidArgument
            return
        }

        foreach ($cert in $Certificate) {

            try {
                $certData = $cert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::PFX, $SecurePassword)
            } catch {
                Stop-Function -Message "Can't export certificate" -ErrorRecord $_ -Continue
            }

            foreach ($computer in $ComputerName) {

                if ($PSCmdlet.ShouldProcess("local", "Connecting to $computer to import cert")) {
                    try {
                        Invoke-Command2 -ComputerName $computer -Credential $Credential -ArgumentList $certdata, $SecurePassword, $Store, $Folder -ScriptBlock $scriptblock -ErrorAction Stop |
                            Select-DefaultView -Property FriendlyName, DnsNameList, Thumbprint, NotBefore, NotAfter, Subject, Issuer
                    } catch {
                        Stop-Function -Message "Failure" -ErrorRecord $_ -Target $computer -Continue
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Add-DbaDbMirrorMonitor.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Add-DbaDbMirrorMonitor {
    <#
    .SYNOPSIS
        Creates a database mirroring monitor job that periodically updates the mirroring status for every mirrored database on the server instance.

    .DESCRIPTION
        Creates a database mirroring monitor job that periodically updates the mirroring status for every mirrored database on the server instance.

        Basically executes sp_dbmmonitoraddmonitoring.

    .PARAMETER SqlInstance
        The target SQL Server instance

    .PARAMETER SqlCredential
        Login to the target instance using alternate Windows or SQL Login Authentication. Accepts credential objects (Get-Credential).

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Mirror, HA
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Add-DbaDbMirrorMonitor

    .EXAMPLE
        PS C:\> Add-DbaDbMirrorMonitor -SqlInstance sql2008, sql2012

        Creates a database mirroring monitor job that periodically updates the mirroring status for every mirrored database on sql2008 and sql2012.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($Pscmdlet.ShouldProcess($instance, "add mirror monitoring")) {
                try {
                    $server.Query("msdb.dbo.sp_dbmmonitoraddmonitoring")
                    [pscustomobject]@{
                        ComputerName  = $server.ComputerName
                        InstanceName  = $server.ServiceName
                        SqlInstance   = $server.DomainInstanceName
                        MonitorStatus = "Added"
                    }
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Add-DbaPfDataCollectorCounter.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Add-DbaPfDataCollectorCounter {
    <#
    .SYNOPSIS
        Adds a Performance Data Collector Counter.

    .DESCRIPTION
        Adds a Performance Data Collector Counter.

    .PARAMETER ComputerName
        The target computer. Defaults to localhost.

    .PARAMETER Credential
        Allows you to login to $ComputerName using alternative credentials. To use:

        $cred = Get-Credential, then pass $cred object to the -Credential parameter.

    .PARAMETER CollectorSet
        The Collector Set name.

    .PARAMETER Collector
        The Collector name.

    .PARAMETER Counter
        The Counter name. This must be in the form of '\Processor(_Total)\% Processor Time'.

    .PARAMETER InputObject
        Accepts the object output by Get-DbaPfDataCollector via the pipeline.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: PerfMon
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Add-DbaPfDataCollectorCounter

    .EXAMPLE
        PS C:\> Add-DbaPfDataCollectorCounter -ComputerName sql2017 -CollectorSet 'System Correlation' -Collector DataCollector01  -Counter '\LogicalDisk(*)\Avg. Disk Queue Length'

        Adds the '\LogicalDisk(*)\Avg. Disk Queue Length' counter within the DataCollector01 collector within the System Correlation collector set on sql2017.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollector | Out-GridView -PassThru | Add-DbaPfDataCollectorCounter -Counter '\LogicalDisk(*)\Avg. Disk Queue Length' -Confirm

        Allows you to select which Data Collector you'd like to add the counter '\LogicalDisk(*)\Avg. Disk Queue Length' on localhost and prompts for confirmation.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [DbaInstance[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [Alias("DataCollectorSet")]
        [string[]]$CollectorSet,
        [Alias("DataCollector")]
        [string[]]$Collector,
        [Alias("Name")]
        [parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [object[]]$Counter,
        [parameter(ValueFromPipeline)]
        [object[]]$InputObject,
        [switch]$EnableException
    )
    begin {
        $setscript = {
            $setname = $args[0]; $Addxml = $args[1]
            $set = New-Object -ComObject Pla.DataCollectorSet
            $set.SetXml($Addxml)
            $set.Commit($setname, $null, 0x0003) #add or modify.
            $set.Query($setname, $Null)
        }
    }
    process {
        if ($InputObject.Credential -and (Test-Bound -ParameterName Credential -Not)) {
            $Credential = $InputObject.Credential
        }

        if (($InputObject | Get-Member -MemberType NoteProperty -ErrorAction SilentlyContinue).Count -le 3 -and $InputObject.ComputerName -and $InputObject.Name) {
            # it's coming from Get-DbaPfAvailableCounter
            $ComputerName = $InputObject.ComputerName
            $Counter = $InputObject.Name
            $InputObject = $null
        }

        if (-not $InputObject -or ($InputObject -and (Test-Bound -ParameterName ComputerName))) {
            foreach ($computer in $ComputerName) {
                $InputObject += Get-DbaPfDataCollector -ComputerName $computer -Credential $Credential -CollectorSet $CollectorSet -Collector $Collector
            }
        }

        if ($InputObject) {
            if (-not $InputObject.DataCollectorObject) {
                Stop-Function -Message "InputObject is not of the right type. Please use Get-DbaPfDataCollector or Get-DbaPfAvailableCounter."
                return
            }
        }

        foreach ($object in $InputObject) {
            $computer = $InputObject.ComputerName
            $null = Test-ElevationRequirement -ComputerName $computer -Continue
            $setname = $InputObject.DataCollectorSet
            $collectorname = $InputObject.Name
            $xml = [xml]($InputObject.DataCollectorSetXml)

            foreach ($countername in $counter) {
                $node = $xml.SelectSingleNode("//Name[.='$collectorname']")
                $newitem = $xml.CreateElement('Counter')
                $null = $newitem.PsBase.InnerText = $countername
                $null = $node.ParentNode.AppendChild($newitem)
                $newitem = $xml.CreateElement('CounterDisplayName')
                $null = $newitem.PsBase.InnerText = $countername
                $null = $node.ParentNode.AppendChild($newitem)
            }
            $plainxml = $xml.OuterXml

            if ($Pscmdlet.ShouldProcess("$computer", "Adding $counters to $collectorname with the $setname collection set")) {
                try {
                    $results = Invoke-Command2 -ComputerName $computer -Credential $Credential -ScriptBlock $setscript -ArgumentList $setname, $plainxml -ErrorAction Stop
                    Write-Message -Level Verbose -Message " $results"
                    Get-DbaPfDataCollectorCounter -ComputerName $computer -Credential $Credential -CollectorSet $setname -Collector $collectorname -Counter $counter
                } catch {
                    Stop-Function -Message "Failure importing $Countername to $computer." -ErrorRecord $_ -Target $computer -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Backup-DbaDatabase.ps1
function Backup-DbaDatabase {
    <#
    .SYNOPSIS
        Backup one or more SQL Sever databases from a single SQL Server SqlInstance.

    .DESCRIPTION
        Performs a backup of a specified type of 1 or more databases on a single SQL Server Instance. These backups may be Full, Differential or Transaction log backups.

    .PARAMETER SqlInstance
        The SQL Server instance hosting the databases to be backed up.

    .PARAMETER SqlCredential
        Credentials to connect to the SQL Server instance if the calling user does not have permission.

    .PARAMETER Database
        The database(s) to process. This list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude. This list is auto-populated from the server.

    .PARAMETER BackupFileName
        The name of the file to backup to. This is only accepted for single database backups.
        If no name is specified then the backup files will be named DatabaseName_yyyyMMddHHmm (i.e. "Database1_201714022131") with the appropriate extension.

        If the same name is used repeatedly, SQL Server will add backups to the same file at an incrementing position.

        SQL Server needs permissions to write to the specified location. Path names are based on the SQL Server (C:\ is the C drive on the SQL Server, not the machine running the script).

        Passing in NUL as the BackupFileName will backup to the NUL: device

    .PARAMETER TimeStampFormat
        By default the command timestamps backups using the format yyyyMMddHHmm. Using this parameter this can be overridden. The timestamp format should be defined using the Get-Date formats, illegal formats will cause an error to be thrown

    .PARAMETER BackupDirectory
        Path in which to place the backup files. If not specified, the backups will be placed in the default backup location for SqlInstance.
        If multiple paths are specified, the backups will be striped across these locations. This will overwrite the FileCount option.

        If the path does not exist, Sql Server will attempt to create it. Folders are created by the Sql Instance, and checks will be made for write permissions.

        File Names with be suffixed with x-of-y to enable identifying striped sets, where y is the number of files in the set and x ranges from 1 to y.

    .PARAMETER ReplaceInName
        If this switch is set, the following list of strings will be replaced in the BackupFileName and BackupDirectory strings:
            instancename - will be replaced with the instance Name
            servername - will be replaced with the server name
            dbname - will be replaced with the database name
            timestamp - will be replaced with the timestamp (either the default, or the format provided)
            backuptype - will be replaced with Full, Log or Differential as appropriate

    .PARAMETER CopyOnly
        If this switch is enabled, CopyOnly backups will be taken. By default function performs a normal backup, these backups interfere with the restore chain of the database. CopyOnly backups will not interfere with the restore chain of the database.

        For more details please refer to this MSDN article - https://msdn.microsoft.com/en-us/library/ms191495.aspx

    .PARAMETER Type
        The type of SQL Server backup to perform. Accepted values are "Full", "Log", "Differential", "Diff", "Database"

    .PARAMETER FileCount
        This is the number of striped copies of the backups you wish to create.    This value is overwritten if you specify multiple Backup Directories.

    .PARAMETER CreateFolder
        If this switch is enabled, each database will be backed up into a separate folder on each of the paths specified by BackupDirectory.

    .PARAMETER CompressBackup
        If this switch is enabled, the function will try to perform a compressed backup if supported by the version and edition of SQL Server. Otherwise, this function will use the server(s) default setting for compression.

    .PARAMETER MaxTransferSize
        Sets the size of the unit of transfer. Values must be a multiple of 64kb.

    .PARAMETER Blocksize
        Specifies the block size to use. Must be one of 0.5KB, 1KB, 2KB, 4KB, 8KB, 16KB, 32KB or 64KB. This can be specified in bytes.
        Refer to https://msdn.microsoft.com/en-us/library/ms178615.aspx for more detail

    .PARAMETER BufferCount
        Number of I/O buffers to use to perform the operation.
        Refer to https://msdn.microsoft.com/en-us/library/ms178615.aspx for more detail

    .PARAMETER Checksum
        If this switch is enabled, the backup checksum will be calculated.

    .PARAMETER Verify
        If this switch is enabled, the backup will be verified by running a RESTORE VERIFYONLY against the SqlInstance

    .PARAMETER WithFormat
        Formats the media as the first step of the backup operation. NOTE: This will set Initialize and SkipTapeHeader to $true.

    .PARAMETER Initialize
        Initializes the media as part of the backup operation.

    .PARAMETER SkipTapeHeader
        Initializes the media as part of the backup operation.

    .PARAMETER InputObject
        Internal parameter

    .PARAMETER AzureBaseUrl
        The URL to the base container of an Azure Storage account to write backups to.

        If specified, the only other parameters than can be used are "NoCopyOnly", "Type", "CompressBackup", "Checksum", "Verify", "AzureCredential", "CreateFolder".

    .PARAMETER AzureCredential
        The name of the credential on the SQL instance that can write to the AzureBaseUrl, only needed if using Storage access keys
        If using SAS credentials, the command will look for a credential with a name matching the AzureBaseUrl

    .PARAMETER NoRecovery
        This is passed in to perform a tail log backup if needed

    .PARAMETER BuildPath
        By default this command will not attempt to create missing paths, this switch will change the behaviour so that it will

    .PARAMETER IgnoreFileChecks
        This switch stops the function from checking for the validity of paths. This can be useful if SQL Server only has read access to the backup area.
        Note, that as we cannot check the path you may well end up with errors.

    .PARAMETER OutputScriptOnly
        Switch causes only the T-SQL script for the backup to be generated. Will not create any paths if they do not exist

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .NOTES
        Tags: DisasterRecovery, Backup, Restore
        Author: Stuart Moore (@napalmgram), stuart-moore.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Backup-DbaDatabase -SqlInstance Server1 -Database HR, Finance

        This will perform a full database backup on the databases HR and Finance on SQL Server Instance Server1 to Server1 default backup directory.

    .EXAMPLE
        PS C:\> Backup-DbaDatabase -SqlInstance sql2016 -BackupDirectory C:\temp -Database AdventureWorks2014 -Type Full

        Backs up AdventureWorks2014 to sql2016 C:\temp folder.

    .EXAMPLE
        PS C:\> Backup-DbaDatabase -SqlInstance sql2016 -AzureBaseUrl https://dbatoolsaz.blob.core.windows.net/azbackups/ -AzureCredential dbatoolscred -Type Full -CreateFolder

        Performs a full backup of all databases on the sql2016 instance to their own containers under the https://dbatoolsaz.blob.core.windows.net/azbackups/ container on Azure blog storage using the sql credential "dbatoolscred" registered on the sql2016 instance.

    .EXAMPLE
        PS C:\> Backup-DbaDatabase -SqlInstance sql2016 -AzureBaseUrl https://dbatoolsaz.blob.core.windows.net/azbackups/  -Type Full

        Performs a full backup of all databases on the sql2016 instance to the https://dbatoolsaz.blob.core.windows.net/azbackups/ container on Azure blog storage using the Shared Access Signature sql credential "https://dbatoolsaz.blob.core.windows.net/azbackups" registered on the sql2016 instance.

    .EXAMPLE
        PS C:\> Backup-Dbadatabase -SqlInstance Server1\Prod -Database db1 -BackupDirectory \\filestore\backups\servername\instancename\dbname\backuptype -Type Full -ReplaceInName

        Performs a full backup of db1 into the folder \\filestore\backups\server1\prod\db1

    .EXAMPLE
        PS C:\> Backup-Dbadatabase -SqlInstance Server1\Prod -BackupDirectory \\filestore\backups\servername\instancename\dbname\backuptype -BackupFileName dbname-backuptype-timestamp.trn -Type Log -ReplaceInName

        Performs a log backup for every database. For the database db1 this would results in backup files in \\filestore\backups\server1\prod\db1\Log\db1-log-31102018.trn

    .EXAMPLE
        PS C:\> Backup-DbaDatabase -SqlInstance Sql2017 -Database master -BackupFileName NUL

        Performs a backup of master, but sends the output to the NUL device (ie; throws it away)
    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] #For AzureCredential
    param (
        [parameter(ParameterSetName = "Pipe", Mandatory)]
        [DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [string[]]$BackupDirectory,
        [string]$BackupFileName,
        [switch]$ReplaceInName,
        [switch]$CopyOnly,
        [ValidateSet('Full', 'Log', 'Differential', 'Diff', 'Database')]
        [string]$Type = 'Database',
        [parameter(ParameterSetName = "NoPipe", Mandatory, ValueFromPipeline)]
        [object[]]$InputObject,
        [switch]$CreateFolder,
        [int]$FileCount = 0,
        [switch]$CompressBackup,
        [switch]$Checksum,
        [switch]$Verify,
        [int]$MaxTransferSize,
        [int]$BlockSize,
        [int]$BufferCount,
        [string]$AzureBaseUrl,
        [string]$AzureCredential,
        [switch]$NoRecovery,
        [switch]$BuildPath,
        [switch]$WithFormat,
        [switch]$Initialize,
        [switch]$SkipTapeHeader,
        [string]$TimeStampFormat,
        [switch]$IgnoreFileChecks,
        [switch]$OutputScriptOnly,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        if (-not (Test-Bound 'TimeStampFormat')) {
            Write-Message -Message 'Setting Default timestampformat' -Level Verbose
            $TimeStampFormat = "yyyyMMddHHmm"
        }
        if ($SqlInstance.length -ne 0) {
            try {
                $Server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential -AzureUnsupported
            } catch {
                Stop-Function -Message "Cannot connect to $SqlInstance" -ErrorRecord $_
                return
            }

            if ($Database) {
                $InputObject = $server.Databases | Where-Object Name -in $Database
            } else {
                $InputObject = $server.Databases | Where-Object Name -ne 'tempdb'
            }

            if ($ExcludeDatabase) {
                $InputObject = $InputObject | Where-Object Name -notin $ExcludeDatabase
            }

            if ($null -eq $BackupDirectory -and $backupfileName -ne 'NUL') {
                Write-Message -Message 'No backupfolder passed in, setting it to instance default' -Level Verbose
                $BackupDirectory = (Get-DbaDefaultPath -SqlInstance $SqlInstance).Backup
            }

            if ($BackupDirectory.Count -gt 1) {
                Write-Message -Level Verbose -Message "Multiple Backup Directories, striping"
                $Filecount = $BackupDirectory.Count
            }

            if ($InputObject.Count -gt 1 -and $BackupFileName -ne '' -and $True -ne $ReplaceInFile) {
                Stop-Function -Message "1 BackupFile specified, but more than 1 database."
                return
            }

            if (($MaxTransferSize % 64kb) -ne 0 -or $MaxTransferSize -gt 4mb) {
                Stop-Function -Message "MaxTransferSize value must be a multiple of 64kb and no greater than 4MB"
                return
            }
            if ($BlockSize) {
                if ($BlockSize -notin (0.5kb, 1kb, 2kb, 4kb, 8kb, 16kb, 32kb, 64kb)) {
                    Stop-Function -Message "Block size must be one of 0.5kb,1kb,2kb,4kb,8kb,16kb,32kb,64kb"
                    return
                }
            }
            if ('' -ne $AzureBaseUrl) {
                $AzureBaseUrl = $AzureBaseUrl.Trim("/")
                if ('' -ne $AzureCredential) {
                    Write-Message -Message "Azure Credential name passed in, will proceed assuming it's value" -Level Verbose
                    $FileCount = 1
                } else {
                    Write-Message -Message "AzureUrl and no credential, testing for SAS credential"
                    if (Get-DbaCredential -SqlInstance $server -Name $AzureBaseUrl) {
                        Write-Message -Message "Found a SAS backup credental" -Level Verbose
                    } else {
                        Stop-Function -Message "You must provide the credential name for the Azure Storage Account"
                        return
                    }
                }
                $BackupDirectory = $AzureBaseUrl
            }

            if ($OutputScriptOnly) {
                $IgnoreFileChecks = $true
            }
        }
    }

    process {
        if (!$SqlInstance -and !$InputObject) {
            Stop-Function -Message "You must specify a server and database or pipe some databases"
            return
        }

        Write-Message -Level Verbose -Message "$($InputObject.Count) database to backup"

        foreach ($Database in $InputObject) {
            $ProgressId = Get-Random
            $failures = @()
            $dbname = $Database.Name

            if ($dbname -eq "tempdb") {
                Stop-Function -Message "Backing up tempdb not supported" -Continue
            }

            if ('Normal' -notin ($Database.Status -split ',')) {
                Stop-Function -Message "Database status not Normal. $dbname skipped." -Continue
            }

            if ($Database.DatabaseSnapshotBaseName) {
                Stop-Function -Message "Backing up snapshots not supported. $dbname skipped." -Continue
            }

            if ($null -eq $server) { $server = $Database.Parent }

            Write-Message -Level Verbose -Message "Backup database $database"

            if ($null -eq $Database.RecoveryModel) {
                $Database.RecoveryModel = $server.Databases[$Database.Name].RecoveryModel
                Write-Message -Level Verbose -Message "$dbname is in $($Database.RecoveryModel) recovery model"
            }

            # Fixes one-off cases of StackOverflowException crashes, see issue 1481
            $dbRecovery = $Database.RecoveryModel.ToString()
            if ($dbRecovery -eq 'Simple' -and $Type -eq 'Log') {
                $failreason = "$database is in simple recovery mode, cannot take log backup"
                $failures += $failreason
                Write-Message -Level Warning -Message "$failreason"
            }

            $lastfull = $database.Refresh().LastBackupDate.Year

            if ($Type -notin @("Database", "Full") -and $lastfull -eq 1) {
                $failreason = "$database does not have an existing full backup, cannot take log or differentialbackup"
                $failures += $failreason
                Write-Message -Level Warning -Message "$failreason"
            }

            if ($CopyOnly -ne $true) {
                $CopyOnly = $false
            }

            $server.ConnectionContext.StatementTimeout = 0
            $backup = New-Object Microsoft.SqlServer.Management.Smo.Backup
            $backup.Database = $Database.Name
            $Suffix = "bak"

            if ($CompressBackup) {
                if ($database.EncryptionEnabled) {
                    Write-Message -Level Warning -Message "$dbname is enabled for encryption, will not compress"
                    $backup.CompressionOption = 2
                } elseif ($server.Edition -like 'Express*' -or ($server.VersionMajor -eq 10 -and $server.VersionMinor -eq 0 -and $server.Edition -notlike '*enterprise*') -or $server.VersionMajor -lt 10) {
                    Write-Message -Level Warning -Message "Compression is not supported with this version/edition of Sql Server"
                } else {
                    Write-Message -Level Verbose -Message "Compression enabled"
                    $backup.CompressionOption = 1
                }
            }

            if ($Checksum) {
                $backup.Checksum = $true
            }

            if ($Type -in 'Diff', 'Differential') {
                Write-Message -Level VeryVerbose -Message "Creating differential backup"
                $SMOBackuptype = "Database"
                $backup.Incremental = $true
                $outputType = 'Differential'
            }
            $Backup.NoRecovery = $false
            if ($Type -eq "Log") {
                Write-Message -Level VeryVerbose -Message "Creating log backup"
                $Suffix = "trn"
                $OutputType = 'Log'
                $SMOBackupType = 'Log'
                $Backup.NoRecovery = $NoRecovery
            }

            if ($Type -in 'Full', 'Database') {
                Write-Message -Level VeryVerbose -Message "Creating full backup"
                $SMOBackupType = "Database"
                $OutputType = 'Full'
            }

            $backup.CopyOnly = $copyonly
            $backup.Action = $SMOBackupType
            if ('' -ne $AzureBaseUrl -and $null -ne $AzureCredential) {
                $backup.CredentialName = $AzureCredential
            }

            Write-Message -Level Verbose -Message "Building file name"

            $BackupFinalName = ''
            $FinalBackupPath = @()
            $timestamp = Get-Date -Format $TimeStampFormat
            if ('NUL' -eq $BackupFileName) {
                $FinalBackupPath += 'NUL:'
                $IgnoreFileChecks = $true
            } elseif ('' -ne $BackupFileName) {
                $File = New-Object System.IO.FileInfo($BackupFileName)
                $BackupFinalName = $file.Name
                $suffix = $file.extension -Replace '^\.', ''
                if ( '' -ne (Split-Path $BackupFileName)) {
                    Write-Message -Level Verbose -Message "Fully qualified path passed in"
                    $FinalBackupPath += [IO.Path]::GetFullPath($file.DirectoryName)
                }
            } else {
                Write-Message -Level VeryVerbose -Message "Setting filename - $timestamp"
                $BackupFinalName = "$($dbname)_$timestamp.$suffix"
            }

            Write-Message -Level Verbose -Message "Building backup path"
            if ($FinalBackupPath.Count -eq 0) {
                $FinalBackupPath += $BackupDirectory
            }

            if ($BackupDirectory.Count -eq 1 -and $Filecount -gt 1) {
                for ($i = 0; $i -lt ($Filecount - 1); $i++) {
                    $FinalBackupPath += $FinalBackupPath[0]
                }
            }

            if ($AzureBaseUrl -or $AzureCredential) {
                $slash = "/"
            } else {
                $slash = "\"
            }
            if ($FinalBackupPath.Count -gt 1) {
                $File = New-Object System.IO.FileInfo($BackupFinalName)
                for ($i = 0; $i -lt $FinalBackupPath.Count; $i++) {
                    $FinalBackupPath[$i] = $FinalBackupPath[$i] + $slash + $($File.BaseName) + "-$($i+1)-of-$FileCount.$suffix"
                }
            } elseif ($FinalBackupPath[0] -ne 'NUL:') {
                $FinalBackupPath[0] = $FinalBackupPath[0] + $slash + $BackupFinalName
            }

            if ($CreateFolder -and $FinalBackupPath[0] -ne 'NUL:') {
                for ($i = 0; $i -lt $FinalBackupPath.Count; $i++) {
                    $parent = [IO.Path]::GetDirectoryName($FinalBackupPath[$i])
                    $leaf = [IO.Path]::GetFileName($FinalBackupPath[$i])
                    $FinalBackupPath[$i] = [IO.Path]::Combine($parent, $dbname, $leaf)
                }
            }

            if ($True -eq $ReplaceInName) {
                for ($i = 0; $i -lt $FinalBackupPath.count; $i++) {
                    $FinalBackupPath[$i] = $FinalBackupPath[$i] -replace ('dbname', $dbname)
                    $FinalBackupPath[$i] = $FinalBackupPath[$i] -replace ('instancename', $SqlInstance.InstanceName)
                    $FinalBackupPath[$i] = $FinalBackupPath[$i] -replace ('servername', $SqlInstance.ComputerName)
                    $FinalBackupPath[$i] = $FinalBackupPath[$i] -replace ('timestamp', $timestamp)
                    $FinalBackupPath[$i] = $FinalBackupPath[$i] -replace ('backuptype', $outputType)
                }
            }

            if (-not $IgnoreFileChecks -and -not $AzureBaseUrl) {
                $parentPaths = ($FinalBackupPath | ForEach-Object { Split-Path $_ } | Select-Object -Unique)
                foreach ($parentPath in $parentPaths) {
                    if (-not (Test-DbaPath -SqlInstance $server -Path $parentPath)) {
                        if (($BuildPath -eq $true) -or ($CreateFolder -eq $True)) {
                            $null = New-DbaDirectory -SqlInstance $server -Path $parentPath
                        } else {
                            $failreason += "SQL Server cannot check if $parentPath exists. You can try disabling this check with -IgnoreFileChecks"
                            $failures += $failreason
                            Write-Message -Level Warning -Message "$failreason"
                        }
                    }
                }
            }


            if ('' -eq $AzureBaseUrl -and $BackupDirectory) {
                $FinalBackupPath = $FinalBackupPath | ForEach-Object { [IO.Path]::GetFullPath($_) }
            }


            $script = $null
            $backupComplete = $false

            if (!$failures) {
                $Filecount = $FinalBackupPath.Count

                foreach ($backupfile in $FinalBackupPath) {
                    $device = New-Object Microsoft.SqlServer.Management.Smo.BackupDeviceItem
                    if ('' -ne $AzureBaseUrl) {
                        $device.DeviceType = "URL"
                    } else {
                        $device.DeviceType = "File"
                    }

                    if ($WithFormat) {
                        Write-Message -Message "WithFormat specified. Ensuring Initialize and SkipTapeHeader are set to true." -Level Verbose
                        $Initialize = $true
                        $SkipTapeHeader = $true
                    }

                    $backup.FormatMedia = $WithFormat
                    $backup.Initialize = $Initialize
                    $backup.SkipTapeHeader = $SkipTapeHeader
                    $device.Name = $backupfile
                    $backup.Devices.Add($device)
                }
                $humanBackupFile = $FinalBackupPath -Join ','
                Write-Message -Level Verbose -Message "Devices added"
                $percent = [Microsoft.SqlServer.Management.Smo.PercentCompleteEventHandler] {
                    Write-Progress -id $ProgressId -activity "Backing up database $dbname to $humanBackupFile" -percentcomplete $_.Percent -status ([System.String]::Format("Progress: {0} %", $_.Percent))
                }
                $backup.add_PercentComplete($percent)
                $backup.PercentCompleteNotification = 1
                $backup.add_Complete($complete)

                if ($MaxTransferSize) {
                    $backup.MaxTransferSize = $MaxTransferSize
                }
                if ($BufferCount) {
                    $backup.BufferCount = $BufferCount
                }
                if ($BlockSize) {
                    $backup.Blocksize = $BlockSize
                }

                Write-Progress -id $ProgressId -activity "Backing up database $dbname to $humanBackupFile" -percentcomplete 0 -status ([System.String]::Format("Progress: {0} %", 0))

                try {
                    if ($Pscmdlet.ShouldProcess($server.Name, "Backing up $dbname to $humanBackupFile")) {
                        $CurrentLsn = (Read-DbaTransactionLog -SqlInstance $server -Database $dbname -RowLimit 1).'Current LSN'
                        $NumericLSN = (Convert-DbaLSN -LSN $CurrentLsn).Numeric
                        if ($OutputScriptOnly -ne $True) {
                            $Filelist = @()
                            $FileList += $server.Databases[$dbname].FileGroups.Files | Select-Object @{ Name = "FileType"; Expression = { "D" } }, @{ Name = "Type"; Expression = { "D" } }, @{ Name = "LogicalName"; Expression = { $_.Name } }, @{ Name = "PhysicalName"; Expression = { $_.FileName } }
                            $FileList += $server.Databases[$dbname].LogFiles | Select-Object @{ Name = "FileType"; Expression = { "L" } }, @{ Name = "Type"; Expression = { "L" } }, @{ Name = "LogicalName"; Expression = { $_.Name } }, @{ Name = "PhysicalName"; Expression = { $_.FileName } }

                            $backup.SqlBackup($server)
                            $script = $backup.Script($server)
                            Write-Progress -id $ProgressId -activity "Backing up database $dbname to $backupfile" -status "Complete" -Completed
                            $BackupComplete = $true
                            if ($server.VersionMajor -eq '8') {
                                $HeaderInfo = Get-BackupAncientHistory -SqlInstance $server -Database $dbname
                            } else {
                                $HeaderInfo = Get-DbaBackupHistory -SqlInstance $server -Database $dbname -Last -IncludeCopyOnly -LastLsn $NumericLsn -RecoveryFork $database.RecoveryForkGuid  | Sort-Object -Property End -Descending | Select-Object -First 1
                            }
                            $Verified = $false
                            if ($Verify) {
                                $verifiedresult = [PSCustomObject]@{
                                    SqlInstance          = $server.name
                                    DatabaseName         = $dbname
                                    BackupComplete       = $BackupComplete
                                    BackupFilesCount     = $FinalBackupPath.Count
                                    BackupFile           = (Split-Path $FinalBackupPath -Leaf)
                                    BackupFolder         = (Split-Path $FinalBackupPath | Sort-Object -Unique)
                                    BackupPath           = ($FinalBackupPath | Sort-Object -Unique)
                                    Script               = $script
                                    Notes                = $failures -join (',')
                                    FullName             = ($FinalBackupPath | Sort-Object -Unique)
                                    FileList             = $FileList
                                    SoftwareVersionMajor = $server.VersionMajor
                                    Type                 = $outputType
                                    FirstLsn             = $HeaderInfo.FirstLsn
                                    DatabaseBackupLsn    = $HeaderInfo.DatabaseBackupLsn
                                    CheckPointLsn        = $HeaderInfo.CheckPointLsn
                                    LastLsn              = $HeaderInfo.LastLsn
                                    BackupSetId          = $HeaderInfo.BackupSetId
                                    LastRecoveryForkGUID = $HeaderInfo.LastRecoveryForkGUID
                                } | Restore-DbaDatabase -SqlInstance $server -DatabaseName DbaVerifyOnly -VerifyOnly -TrustDbBackupHistory -DestinationFilePrefix DbaVerifyOnly
                                if ($verifiedResult[0] -eq "Verify successful") {
                                    $failures += $verifiedResult[0]
                                    $Verified = $true
                                } else {
                                    $failures += $verifiedResult[0]
                                    $Verified = $false
                                }
                            }
                            $HeaderInfo | Add-Member -Type NoteProperty -Name BackupComplete -Value $BackupComplete
                            $HeaderInfo | Add-Member -Type NoteProperty -Name BackupFile -Value (Split-Path $FinalBackupPath -Leaf)
                            $HeaderInfo | Add-Member -Type NoteProperty -Name BackupFilesCount -Value $FinalBackupPath.Count
                            if ($FinalBackupPath[0] -eq 'NUL:') {
                                $pathresult = "NUL:"
                            } else {
                                $pathresult = (Split-Path $FinalBackupPath | Sort-Object -Unique)
                            }
                            $HeaderInfo | Add-Member -Type NoteProperty -Name BackupFolder -Value $pathresult
                            $HeaderInfo | Add-Member -Type NoteProperty -Name BackupPath -Value ($FinalBackupPath | Sort-Object -Unique)
                            $HeaderInfo | Add-Member -Type NoteProperty -Name DatabaseName -Value $dbname
                            $HeaderInfo | Add-Member -Type NoteProperty -Name Notes -Value ($failures -join (','))
                            $HeaderInfo | Add-Member -Type NoteProperty -Name Script -Value $script
                            $HeaderInfo | Add-Member -Type NoteProperty -Name Verified -Value $Verified
                        } else {
                            $backup.Script($server)
                        }
                    }
                } catch {
                    if ($NoRecovery -and ($_.Exception.InnerException.InnerException.InnerException -like '*cannot be opened. It is in the middle of a restore.')) {
                        Write-Message -Message "Exception thrown by db going into restoring mode due to recovery" -Leve Verbose
                    } else {
                        Write-Progress -id $ProgressId -activity "Backup" -status "Failed" -completed
                        Stop-Function -message "Backup Failed" -ErrorRecord $_ -Continue
                        $BackupComplete = $false
                    }
                }
            }
            $OutputExclude = 'FullName', 'FileList', 'SoftwareVersionMajor'
            if ($failures.Count -eq 0) {
                $OutputExclude += ('Notes', 'FirstLsn', 'DatabaseBackupLsn', 'CheckpointLsn', 'LastLsn', 'BackupSetId', 'LastRecoveryForkGuid')
            }
            $headerinfo | Select-DefaultView -ExcludeProperty $OutputExclude
            $BackupFileName = $null
        }
    }
}
tools\dbatools\functions\Backup-DbaDbCertificate.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Backup-DbaDbCertificate {
    <#
    .SYNOPSIS
        Exports database certificates from SQL Server using SMO.

    .DESCRIPTION
        Exports database certificates from SQL Server using SMO and outputs the .cer and .pvk files.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Certificate
        Exports certificate that matches the name(s).

    .PARAMETER Database
        Exports the encryptor for specific database(s).

    .PARAMETER ExcludeDatabase
        Database(s) to skip when exporting encryptors.

    .PARAMETER EncryptionPassword
        A string value that specifies the system path to encrypt the private key.

    .PARAMETER DecryptionPassword
        A string value that specifies the system path to decrypt the private key.

    .PARAMETER Path
        The path to output the files to. The path is relative to the SQL Server itself. If no path is specified, the default data directory will be used.

    .PARAMETER Suffix
        The suffix of the filename of the exported certificate.

    .PARAMETER InputObject
        Enables piping from Get-DbaDbCertificate

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .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.

    .NOTES
        Tags: Migration, Certificate
        Author: Jess Pomfret (@jpomfret)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Backup-DbaDbCertificate -SqlInstance Server1

        Exports all the certificates on the specified SQL Server to the default data path for the instance.

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> Backup-DbaDbCertificate -SqlInstance Server1 -SqlCredential $cred

        Connects using sqladmin credential and exports all the certificates on the specified SQL Server to the default data path for the instance.

    .EXAMPLE
        PS C:\> Backup-DbaDbCertificate -SqlInstance Server1 -Certificate Certificate1

        Exports only the certificate named Certificate1 on the specified SQL Server to the default data path for the instance.

    .EXAMPLE
        PS C:\> Backup-DbaDbCertificate -SqlInstance Server1 -Database AdventureWorks

        Exports only the certificates for AdventureWorks on the specified SQL Server to the default data path for the instance.

    .EXAMPLE
        PS C:\> Backup-DbaDbCertificate -SqlInstance Server1 -ExcludeDatabase AdventureWorks

        Exports all certificates except those for AdventureWorks on the specified SQL Server to the default data path for the instance.

    .EXAMPLE
        PS C:\> Backup-DbaDbCertificate -SqlInstance Server1 -Path \\Server1\Certificates -EncryptionPassword (ConvertTo-SecureString -force -AsPlainText GoodPass1234!!)

        Exports all the certificates and private keys on the specified SQL Server.

    .EXAMPLE
        PS C:\> $EncryptionPassword = ConvertTo-SecureString -AsPlainText "GoodPass1234!!" -force
        PS C:\> $DecryptionPassword = ConvertTo-SecureString -AsPlainText "Password4567!!" -force
        PS C:\> Backup-DbaDbCertificate -SqlInstance Server1 -EncryptionPassword $EncryptionPassword -DecryptionPassword $DecryptionPassword

        Exports all the certificates on the specified SQL Server using the supplied DecryptionPassword, since an EncryptionPassword is specified private keys are also exported.

    .EXAMPLE
        PS C:\> Backup-DbaDbCertificate -SqlInstance Server1 -Path \\Server1\Certificates

        Exports all certificates on the specified SQL Server to the specified path.

    .EXAMPLE
        PS C:\> Backup-DbaDbCertificate -SqlInstance Server1 -Suffix DbaTools

        Exports all certificates on the specified SQL Server to the specified path, appends DbaTools to the end of the filenames.

    .EXAMPLE
        PS C:\> Get-DbaDbCertificate -SqlInstance sql2016 | Backup-DbaDbCertificate

        Exports all certificates found on sql2016 to the default data directory.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess, ConfirmImpact = 'Low')]
    param (
        [parameter(Mandatory, ParameterSetName = "instance")]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(ParameterSetName = "instance")]
        [object[]]$Certificate,
        [parameter(ParameterSetName = "instance")]
        [object[]]$Database,
        [parameter(ParameterSetName = "instance")]
        [object[]]$ExcludeDatabase,
        [Security.SecureString]$EncryptionPassword,
        [Security.SecureString]$DecryptionPassword,
        [System.IO.FileInfo]$Path,
        [string]$Suffix = "$(Get-Date -format 'yyyyMMddHHmmssms')",
        [parameter(ValueFromPipeline, ParameterSetName = "collection")]
        [Microsoft.SqlServer.Management.Smo.Certificate[]]$InputObject,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        if (-not $EncryptionPassword -and $DecryptionPassword) {
            Stop-Function -Message "If you specify a decryption password, you must also specify an encryption password" -Target $DecryptionPassword
        }

        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Backup-DbaDatabaseCertificate

        function export-cert ($cert) {
            $certName = $cert.Name
            $db = $cert.Parent
            $server = $db.Parent
            $instance = $server.Name
            $actualPath = $Path

            if ($null -eq $actualPath) {
                $actualPath = Get-SqlDefaultPaths -SqlInstance $server -filetype Data
            }

            $actualPath = "$actualPath".TrimEnd('\')
            $fullCertName = "$actualPath\$certName$Suffix"
            $exportPathKey = "$fullCertName.pvk"

            if (!(Test-DbaPath -SqlInstance $server -Path $actualPath)) {
                Stop-Function -Message "$SqlInstance cannot access $actualPath" -Target $actualPath
            }

            if ($Pscmdlet.ShouldProcess($instance, "Exporting certificate $certName from $db on $instance to $actualPath")) {
                Write-Message -Level Verbose -Message "Exporting Certificate: $certName to $fullCertName"
                try {

                    $exportPathCert = "$fullCertName.cer"

                    # because the password shouldn't go to memory...
                    if ($EncryptionPassword.Length -gt 0 -and $DecryptionPassword.Length -gt 0) {

                        Write-Message -Level Verbose -Message "Both passwords passed in. Will export both cer and pvk."

                        $cert.export(
                            $exportPathCert,
                            $exportPathKey,
                            [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($EncryptionPassword)),
                            [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($DecryptionPassword))
                        )
                    } elseif ($EncryptionPassword.Length -gt 0 -and $DecryptionPassword.Length -eq 0) {
                        Write-Message -Level Verbose -Message "Only encryption password passed in. Will export both cer and pvk."

                        $cert.export(
                            $exportPathCert,
                            $exportPathKey,
                            [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($EncryptionPassword))
                        )
                    } else {
                        Write-Message -Level Verbose -Message "No passwords passed in. Will export just cer."
                        $exportPathKey = "Password required to export key"
                        $cert.export($exportPathCert)
                    }

                    [pscustomobject]@{
                        ComputerName   = $server.ComputerName
                        InstanceName   = $server.ServiceName
                        SqlInstance    = $server.DomainInstanceName
                        Database       = $db.Name
                        Certificate    = $certName
                        Path           = $exportPathCert
                        Key            = $exportPathKey
                        ExportPath     = $exportPathCert
                        ExportKey      = $exportPathKey
                        exportPathCert = $exportPathCert
                        exportPathKey  = $exportPathKey
                        Status         = "Success"
                    } | Select-DefaultView -ExcludeProperty exportPathCert, exportPathKey, ExportPath, ExportKey
                } catch {

                    if ($_.Exception.InnerException) {
                        $exception = $_.Exception.InnerException.ToString() -Split "System.Data.SqlClient.SqlException: "
                        $exception = ($exception[1] -Split "at Microsoft.SqlServer.Management.Common.ConnectionManager")[0]
                    } else {
                        $exception = $_.Exception
                    }
                    [pscustomobject]@{
                        ComputerName   = $server.ComputerName
                        InstanceName   = $server.ServiceName
                        SqlInstance    = $server.DomainInstanceName
                        Database       = $db.Name
                        Certificate    = $certName
                        Path           = $exportPathCert
                        Key            = $exportPathKey
                        ExportPath     = $exportPathCert
                        ExportKey      = $exportPathKey
                        exportPathCert = $exportPathCert
                        exportPathKey  = $exportPathKey
                        Status         = "Failure: $exception"
                    } | Select-DefaultView -ExcludeProperty exportPathCert, exportPathKey, ExportPath, ExportKey
                    Stop-Function -Message "$certName from $db on $instance cannot be exported." -Continue -Target $cert -ErrorRecord $_
                }
            }
        }
    }

    process {
        if (Test-FunctionInterrupt) { return }

        if ($SqlInstance) {
            $InputObject += Get-DbaDbCertificate -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase
        }

        foreach ($cert in $InputObject) {
            if ($cert.Name.StartsWith("##")) {
                Write-Message -Level Output -Message "Skipping system cert $cert"
            } else {
                export-cert $cert
            }
        }
    }
}
tools\dbatools\functions\Backup-DbaDbMasterKey.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Backup-DbaDbMasterKey {
    <#
    .SYNOPSIS
        Backs up specified database master key.

    .DESCRIPTION
        Backs up specified database master key.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Allows you to login to SQL Server using alternative credentials.

    .PARAMETER Database
        Backup master key from specific database(s).

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server.

    .PARAMETER Path
        The directory to export the key. If no path is specified, the default backup directory for the instance will be used.

    .PARAMETER Credential
        Pass a credential object for the password

    .PARAMETER SecurePassword
        The password to encrypt the exported key. This must be a SecureString.

    .PARAMETER InputObject
        Database object piped in from Get-DbaDatabase

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Certificate, Database
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Backup-DbaDbMasterKey -SqlInstance server1\sql2016
        ```
        ComputerName : SERVER1
        InstanceName : SQL2016
        SqlInstance  : SERVER1\SQL2016
        Database     : master
        Filename     : E:\MSSQL13.SQL2016\MSSQL\Backup\server1$sql2016-master-20170614162311.key
        Status       : Success
        ```

        Prompts for export password, then logs into server1\sql2016 with Windows credentials then backs up all database keys to the default backup directory.

    .EXAMPLE
        PS C:\> Backup-DbaDbMasterKey -SqlInstance Server1 -Database db1 -Path \\nas\sqlbackups\keys

        Logs into sql2016 with Windows credentials then backs up db1's keys to the \\nas\sqlbackups\keys directory.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [PSCredential]$Credential,
        [string[]]$Database,
        [string[]]$ExcludeDatabase,
        [Alias("Password")]
        [Security.SecureString]$SecurePassword,
        [string]$Path,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )
    begin {
        if ($Credential) {
            $SecurePassword = $Credential.Password
        }
    }
    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase
        }

        foreach ($db in $InputObject) {
            $server = $db.Parent

            if (Test-Bound -ParameterName Path -Not) {
                $Path = $server.BackupDirectory
            }

            if (-not $Path) {
                Stop-Function -Message "Path discovery failed. Please explicitly specify -Path" -Target $server -Continue
            }

            if (!(Test-DbaPath -SqlInstance $server -Path $Path)) {
                Stop-Function -Message "$instance cannot access $Path" -Target $server -ErrorRecord $_ -Continue
            }

            if (!$db.IsAccessible) {
                Write-Message -Level Warning -Message "Database $db is not accessible. Skipping."
                continue
            }

            $masterkey = $db.MasterKey

            if (!$masterkey) {
                Write-Message -Message "No master key exists in the $db database on $instance" -Target $db -Level Verbose
                continue
            }

            # If you pass a password param, then you will not be prompted for each database, but it wouldn't be a good idea to build in insecurity
            if (-not $SecurePassword -and -not $Credential) {
                $SecurePassword = Read-Host -AsSecureString -Prompt "You must enter Service Key password for $instance"
                $SecurePassword2 = Read-Host -AsSecureString -Prompt "Type the password again"

                if (([System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($SecurePassword))) -ne ([System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($SecurePassword2)))) {
                    Stop-Function -Message "Passwords do not match" -Continue
                }
            }

            $time = (Get-Date -Format yyyMMddHHmmss)
            $dbname = $db.name
            $Path = $Path.TrimEnd("\")
            $fileinstance = $instance.ToString().Replace('\', '$')
            $filename = "$Path\$fileinstance-$dbname-$time.key"

            if ($Pscmdlet.ShouldProcess($instance, "Backing up master key to $filename")) {
                try {
                    $masterkey.Export($filename, [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($SecurePassword)))
                    $status = "Success"
                } catch {
                    $status = "Failure"
                    Write-Message -Level Warning -Message "Backup failure: $($_.Exception.InnerException)"
                }

                Add-Member -Force -InputObject $masterkey -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                Add-Member -Force -InputObject $masterkey -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                Add-Member -Force -InputObject $masterkey -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                Add-Member -Force -InputObject $masterkey -MemberType NoteProperty -Name Database -value $dbname
                Add-Member -Force -InputObject $masterkey -MemberType NoteProperty -Name Filename -value $filename
                Add-Member -Force -InputObject $masterkey -MemberType NoteProperty -Name Status -value $status

                Select-DefaultView -InputObject $masterkey -Property ComputerName, InstanceName, SqlInstance, Database, 'Filename as Path', Status
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Backup-DbaDatabaseMasterKey
    }
}
tools\dbatools\functions\Clear-DbaConnectionPool.ps1
function Clear-DbaConnectionPool {
    <#
    .SYNOPSIS
        Resets (or empties) the connection pool.

    .DESCRIPTION
        This command resets (or empties) the connection pool.

        If there are connections in use at the time of the call, they are marked appropriately and will be discarded (instead of being returned to the pool) when Close() is called on them.

        Ref: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.clearallpools(v=vs.110).aspx

    .PARAMETER ComputerName
        Target computer(s). If no computer name is specified, the local computer is targeted.

    .PARAMETER Credential
        Alternate credential object to use for accessing the target computer(s).

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Connection
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Clear-DbaConnectionPool

    .EXAMPLE
        PS C:\> Clear-DbaConnectionPool

        Clears all local connection pools.

    .EXAMPLE
        PS C:\> Clear-DbaConnectionPool -ComputerName workstation27

        Clears all connection pools on workstation27.

    #>
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [Alias("cn", "host", "Server")]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [switch][Alias('Silent')]
        $EnableException
    )

    process {
        # TODO: https://jamessdixon.wordpress.com/2013/01/22/ado-net-and-connection-pooling

        foreach ($computer in $ComputerName) {
            try {
                if (-not $computer.IsLocalhost) {
                    Write-Message -Level Verbose -Message "Clearing all pools on remote computer $computer"
                    if (Test-Bound 'Credential') {
                        Invoke-Command2 -ComputerName $computer -Credential $Credential -ScriptBlock { [System.Data.SqlClient.SqlConnection]::ClearAllPools() }
                    } else {
                        Invoke-Command2 -ComputerName $computer -ScriptBlock { [System.Data.SqlClient.SqlConnection]::ClearAllPools() }
                    }
                } else {
                    Write-Message -Level Verbose -Message "Clearing all local pools"
                    if (Test-Bound 'Credential') {
                        Invoke-Command2 -Credential $Credential -ScriptBlock { [System.Data.SqlClient.SqlConnection]::ClearAllPools() }
                    } else {
                        Invoke-Command2 -ScriptBlock { [System.Data.SqlClient.SqlConnection]::ClearAllPools() }
                    }
                }
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Target $computer -Continue
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Clear-DbaSqlConnectionPool
    }
}
tools\dbatools\functions\Clear-DbaLatchStatistics.ps1
function Clear-DbaLatchStatistics {
    <#
    .SYNOPSIS
        Clears Latch Statistics

    .DESCRIPTION
        Reset the aggregated statistics - basically just executes DBCC SQLPERF (N'sys.dm_os_latch_stats', CLEAR)

    .PARAMETER SqlInstance
        Allows you to specify a comma separated list of servers to query.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: LatchStatistic, Waits
        Author: Patrick Flynn (@sqllensman)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Clear-DbaLatchStatistics

    .EXAMPLE
        PS C:\> Clear-DbaLatchStatistics -SqlInstance sql2008, sqlserver2012

        After confirmation, clears latch statistics on servers sql2008 and sqlserver2012

    .EXAMPLE
        PS C:\> Clear-DbaLatchStatistics -SqlInstance sql2008, sqlserver2012 -Confirm:$false

        Clears latch statistics on servers sql2008 and sqlserver2012, without prompting

    .EXAMPLE
        PS C:\> 'sql2008','sqlserver2012' | Clear-DbaLatchStatistics

        After confirmation, clears latch statistics on servers sql2008 and sqlserver2012

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> Clear-DbaLatchStatistics -SqlInstance sql2008 -SqlCredential $cred

        Connects using sqladmin credential and clears latch statistics on servers sql2008 and sqlserver2012
    #>
    [CmdletBinding(ConfirmImpact = 'High', SupportsShouldProcess)]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification = "Singular Noun doesn't make sense")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            Write-Message -Level Verbose -Message "Attempting to connect to $instance"

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($Pscmdlet.ShouldProcess($instance, "Performing CLEAR of sys.dm_os_latch_stats")) {
                try {
                    $server.Query("DBCC SQLPERF (N'sys.dm_os_latch_stats' , CLEAR);")
                    $status = "Success"
                } catch {
                    $status = $_.Exception
                }

                [PSCustomObject]@{
                    ComputerName = $server.NetName
                    InstanceName = $server.ServiceName
                    SqlInstance  = $server.DomainInstanceName
                    Status       = $status
                }
            }
        }
    }
}
tools\dbatools\functions\Clear-DbaPlanCache.ps1
function Clear-DbaPlanCache {
    <#
    .SYNOPSIS
        Removes ad-hoc and prepared plan caches is single use plans are over defined threshold.

    .DESCRIPTION
        Checks ad-hoc and prepared plan cache for each database, if over 100 MBs removes from the cache.

        This command automates that process.

        References: https://www.sqlskills.com/blogs/kimberly/plan-cache-adhoc-workloads-and-clearing-the-single-use-plan-cache-bloat/

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Threshold
        Memory used threshold.

    .PARAMETER InputObject
        Enables results to be piped in from Get-DbaPlanCache.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Memory
        Author: Tracy Boggiano, databasesuperhero.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Clear-DbaPlanCache

    .EXAMPLE
        PS C:\> Clear-DbaPlanCache -SqlInstance sql2017 -Threshold 200

        Logs into the SQL Server instance "sql2017" and removes plan caches if over 200 MB.

    .EXAMPLE
        PS C:\> Clear-DbaPlanCache -SqlInstance sql2017 -SqlCredential sqladmin

        Logs into the SQL instance using the SQL Login 'sqladmin' and then Windows instance as 'ad\sqldba'
        and removes if Threshold over 100 MB.

    .EXAMPLE
        PS C:\> Find-DbaInstance -ComputerName localhost | Get-DbaPlanCache | Clear-DbaPlanCache -Threshold 200

        Scans localhost for instances using the browser service, traverses all instances and gets the plan cache for each, clears them out if they are above 200 MB.
    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [int]$Threshold = 100,
        [parameter(ValueFromPipeline)]
        [object[]]$InputObject,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaPlanCache -SqlInstance $instance -SqlCredential $SqlCredential
        }

        foreach ($result in $InputObject) {
            if ($result.MB -ge $Threshold) {
                if ($Pscmdlet.ShouldProcess($($result.SqlInstance), "Cleared SQL Plans plan cache")) {
                    try {
                        $server = Connect-SqlInstance -SqlInstance $result.SqlInstance -SqlCredential $SqlCredential
                    } catch {
                        Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                    }

                    $server.Query("DBCC FREESYSTEMCACHE('SQL Plans')")
                    [PSCustomObject]@{
                        ComputerName = $result.ComputerName
                        InstanceName = $result.InstanceName
                        SqlInstance  = $result.SqlInstance
                        Size         = $result.Size
                        Status       = "Plan cache cleared"
                    }
                }
            } else {
                if ($Pscmdlet.ShouldProcess($($result.SqlInstance), "Results $($result.Size) below threshold")) {
                    [PSCustomObject]@{
                        ComputerName = $result.ComputerName
                        InstanceName = $result.InstanceName
                        SqlInstance  = $result.SqlInstance
                        Size         = $result.Size
                        Status       = "Plan cache size below threshold ($Threshold) "
                    }
                    Write-Message -Level Verbose -Message "Plan cache size below threshold ($Threshold) "
                }
            }
        }
    }
}
tools\dbatools\functions\Clear-DbaWaitStatistics.ps1
function Clear-DbaWaitStatistics {
    <#
    .SYNOPSIS
        Clears wait statistics

    .DESCRIPTION
        Reset the aggregated statistics - basically just executes DBCC SQLPERF (N'sys.dm_os_wait_stats', CLEAR)

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: WaitStatistic, Waits
        Author: Chrissy LeMaire (@cl)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Clear-DbaWaitStatistics

    .EXAMPLE
        PS C:\> Clear-DbaWaitStatistics -SqlInstance sql2008, sqlserver2012

        After confirmation, clears wait stats on servers sql2008 and sqlserver2012

    .EXAMPLE
        PS C:\> Clear-DbaWaitStatistics -SqlInstance sql2008, sqlserver2012 -Confirm:$false

        Clears wait stats on servers sql2008 and sqlserver2012, without prompting

    #>
    [CmdletBinding(ConfirmImpact = 'High', SupportsShouldProcess)]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification = "Singular Noun doesn't make sense")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($Pscmdlet.ShouldProcess($instance, "Performing CLEAR of sys.dm_os_wait_stats")) {
                try {
                    $server.Query("DBCC SQLPERF (N'sys.dm_os_wait_stats', CLEAR);")
                    $status = "Success"
                } catch {
                    $status = $_.Exception
                }

                [PSCustomObject]@{
                    ComputerName = $server.ComputerName
                    InstanceName = $server.ServiceName
                    SqlInstance  = $server.DomainInstanceName
                    Status       = $status
                }
            }
        }
    }
}
tools\dbatools\functions\configuration\Export-DbatoolsConfig.ps1
function Export-DbatoolsConfig
{
<#
    .SYNOPSIS
        Exports configuration items to a Json file.
    
    .DESCRIPTION
        Exports configuration items to a Json file.
    
    .PARAMETER FullName
        Select the configuration objects to export by filtering by their full name.
    
    .PARAMETER Module
        Select the configuration objects to export by filtering by their module name.
    
    .PARAMETER Name
        Select the configuration objects to export by filtering by their name.
    
    .PARAMETER Config
        The configuration object(s) to export.
        Returned by Get-DbatoolsConfig.
    
    .PARAMETER ModuleName
        Exports all configuration pertinent to a module to a predefined path.
        Exported configuration items include all settings marked as 'ModuleExport' that have been changed from the default value.
    
    .PARAMETER ModuleVersion
        The configuration version of the module-settings to write.
    
    .PARAMETER Scope
        Which predefined path to write module specific settings to.
        Only file scopes are considered.
        By default it writes to the suer profile.
    
    .PARAMETER OutPath
        The path (filename included) to export to.
        Will fail if the folder does not exist, will overwrite the file if it exists.
    
    .PARAMETER SkipUnchanged
        If set, configuration objects whose value was not changed from its original value will not be exported.
        (Note: Settings that were updated with the same value as the original default will still be considered changed)
    
    .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-DbatoolsConfig | Export-DbatoolsConfig -OutPath '~/export.json'
        
        Exports all current settings to json.
    
    .EXAMPLE
        Export-DbatoolsConfig -Module message -OutPath '~/export.json' -SkipUnchanged
        
        Exports all settings of the module 'message' that are no longer the original default values to json.
#>
    [CmdletBinding(DefaultParameterSetName = 'FullName')]
    Param (
        [Parameter(ParameterSetName = "FullName", Position = 0, Mandatory = $true)]
        [string]
        $FullName,
        
        [Parameter(ParameterSetName = "Module", Position = 0, Mandatory = $true)]
        [string]
        $Module,
        
        [Parameter(ParameterSetName = "Module", Position = 1)]
        [string]
        $Name = "*",
        
        [Parameter(ParameterSetName = "Config", Position = 0, Mandatory = $true, ValueFromPipeline = $true)]
        [Sqlcollaborative.Dbatools.Configuration.Config[]]
        $Config,
        
        [Parameter(ParameterSetName = "ModuleName", Mandatory = $true)]
        [string]
        $ModuleName,
        
        [Parameter(ParameterSetName = "ModuleName")]
        [int]
        $ModuleVersion = 1,
        
        [Parameter(ParameterSetName = "ModuleName")]
        [Sqlcollaborative.Dbatools.Configuration.ConfigScope]
        $Scope = "FileUserShared",
        
        [Parameter(Position = 1, Mandatory = $true, ParameterSetName = 'Config')]
        [Parameter(Position = 1, Mandatory = $true, ParameterSetName = 'FullName')]
        [Parameter(Position = 2, Mandatory = $true, ParameterSetName = 'Module')]
        [string]
        $OutPath,
        
        [switch]
        $SkipUnchanged,
        
        [switch]
        $EnableException
    )
    
    begin
    {
        Write-Message -Level InternalComment -Message "Bound parameters: $($PSBoundParameters.Keys -join ", ")" -Tag 'debug', 'start', 'param'
        
        $items = @()
        
        if (($Scope -band 15) -and ($ModuleName))
        {
            Stop-Function -Message "Cannot export modulecache to registry! Please pick a file scope for your export destination" -EnableException $EnableException -Category InvalidArgument -Tag 'fail', 'scope', 'registry'
            return
        }
    }
    process
    {
        if (Test-FunctionInterrupt) { return }
        
        if (-not $ModuleName)
        {
            foreach ($item in $Config) { $items += $item }
            if ($FullName) { $items = Get-DbatoolsConfig -FullName $FullName }
            if ($Module) { $items = Get-DbatoolsConfig -Module $Module -Name $Name }
        }
    }
    end
    {
        if (Test-FunctionInterrupt) { return }
        
        if (-not $ModuleName)
        {
            try { Write-DbatoolsConfigFile -Config ($items | Where-Object { -not $SkipUnchanged -or -not $_.Unchanged } ) -Path $OutPath -Replace }
            catch
            {
                Stop-Function -Message "Failed to export to file" -EnableException $EnableException -ErrorRecord $_ -Tag 'fail', 'export'
                return
            }
        }
        else
        {
            if ($Scope -band 16)
            {
                Write-DbatoolsConfigFile -Config (Get-DbatoolsConfig -Module $ModuleName -Force | Where-Object ModuleExport | Where-Object Unchanged -NE $true) -Path (Join-Path $script:path_FileUserLocal "$($ModuleName.ToLower())-$($ModuleVersion).json")
            }
            if ($Scope -band 32)
            {
                Write-DbatoolsConfigFile -Config (Get-DbatoolsConfig -Module $ModuleName -Force | Where-Object ModuleExport | Where-Object Unchanged -NE $true)  -Path (Join-Path $script:path_FileUserShared "$($ModuleName.ToLower())-$($ModuleVersion).json")
            }
            if ($Scope -band 64)
            {
                Write-DbatoolsConfigFile -Config (Get-DbatoolsConfig -Module $ModuleName -Force | Where-Object ModuleExport | Where-Object Unchanged -NE $true)  -Path (Join-Path $script:path_FileSystem "$($ModuleName.ToLower())-$($ModuleVersion).json")
            }
        }
    }
}
tools\dbatools\functions\configuration\Get-DbatoolsConfig.ps1
function Get-DbatoolsConfig {
    <#
    .SYNOPSIS
        Retrieves configuration elements by name.

    .DESCRIPTION
        Retrieves configuration elements by name.
        Can be used to search the existing configuration list.

    .PARAMETER FullName
        Default: "*"
        Search for configurations using the full name

    .PARAMETER Name
        Default: "*"
        The name of the configuration element(s) to retrieve.
        May be any string, supports wildcards.

    .PARAMETER Module
        Default: "*"
        Search configuration by module.

    .PARAMETER Force
        Overrides the default behavior and also displays hidden configuration values.

    .NOTES
        Tags: Config, Module
        Author: Friedrich Weinmann (@FredWeinmann)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbatoolsConfig 'Mail.To'

        Retrieves the configuration element for the key "Mail.To"

    .EXAMPLE
        PS C:\> Get-DbatoolsConfig -Force

        Retrieve all configuration elements from all modules, even hidden ones.

    #>
    [CmdletBinding(DefaultParameterSetName = "FullName")]
    param (
        [Parameter(ParameterSetName = "FullName", Position = 0)]
        [string]$FullName = "*",
        [Parameter(ParameterSetName = "Module", Position = 1)]
        [string]$Name = "*",
        [Parameter(ParameterSetName = "Module", Position = 0)]
        [string]$Module = "*",
        [switch]$Force
    )

    switch ($PSCmdlet.ParameterSetName) {
        "Module" {
            $Name = $Name.ToLower()
            $Module = $Module.ToLower()

            [Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations.Values | Where-Object { ($_.Name -like $Name) -and ($_.Module -like $Module) -and ((-not $_.Hidden) -or ($Force)) } | Sort-Object Module, Name
        }

        "FullName" {
            [Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations.Values | Where-Object { ("$($_.Module).$($_.Name)" -like $FullName) -and ((-not $_.Hidden) -or ($Force)) } | Sort-Object Module, Name
        }
    }
    Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaConfig
}
tools\dbatools\functions\configuration\Get-DbatoolsConfigValue.ps1
function Get-DbatoolsConfigValue {
    <#
    .SYNOPSIS
        Returns the configuration value stored under the specified name.

    .DESCRIPTION
        Returns the configuration value stored under the specified name.
        It requires the full name (<Module>.<Name>) and is usually only called by functions.

    .PARAMETER FullName
        The full name (<Module>.<Name>) of the configured value to return.

    .PARAMETER Fallback
        A fallback value to use, if no value was registered to a specific configuration element.
        This basically is a default value that only applies on a "per call" basis, rather than a system-wide default.

    .PARAMETER NotNull
        By default, this function returns null if one tries to retrieve the value from either a Configuration that does not exist or a Configuration whose value was set to null.
        However, sometimes it may be important that some value was returned.
        By specifying this parameter, the function will throw an error if no value was found at all.

    .NOTES
        Tags: Config, Module
        Author: Friedrich Weinmann (@FredWeinmann)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbatoolsConfigValue -Name 'System.MailServer'

        Returns the configured value that was assigned to the key 'System.MailServer'

    .EXAMPLE
        PS C:\> Get-DbatoolsConfigValue -Name 'Default.CoffeeMilk' -Fallback 0

        Returns the configured value for 'Default.CoffeeMilk'. If no such value is configured, it returns '0' instead.

    #>
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSPossibleIncorrectComparisonWithNull", "")]
    [CmdletBinding()]
    param (
        [Alias('Name')]
        [Parameter(Mandatory)]
        [string]$FullName,
        [object]$Fallback,
        [switch]$NotNull
    )
    Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaConfigValue
    $FullName = $FullName.ToLower()

    $temp = $null
    $temp = [Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations[$FullName].Value
    if ($temp -eq $null) { $temp = $Fallback }

    if ($NotNull -and ($temp -eq $null)) {
        Stop-Function -Message "No Configuration Value available for $Name" -EnableException $true -Category InvalidData -Target $FullName
    } else {
        return $temp
    }
}
tools\dbatools\functions\configuration\Import-DbatoolsConfig.ps1
function Import-DbatoolsConfig
{
<#
    .SYNOPSIS
        Imports a json configuration file into the configuration system.
    
    .DESCRIPTION
        Imports a json configuration file into the configuration system.
    
    .PARAMETER Path
        The path to the json file to import.
    
    .PARAMETER ModuleName
        Import configuration items specific to a module from the default configuration paths.
    
    .PARAMETER ModuleVersion
        The configuration version of the module-settings to load.
    
    .PARAMETER Scope
        Where to import the module specific configuration items form.
        Only file-based scopes are supported for this.
        By default, all locations are queried, with user settings beating system settings.
    
    .PARAMETER IncludeFilter
        If specified, only elements with names that are similar (-like) to names in this list will be imported.
    
    .PARAMETER ExcludeFilter
        Elements that are similar (-like) to names in this list will not be imported.
    
    .PARAMETER Peek
        Rather than applying the setting, return the configuration items that would have been applied.
    
    .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:\> Import-DbatoolsConfig -Path '.\config.json'
        
        Imports the configuration stored in '.\config.json'
    
    .EXAMPLE
        PS C:\> Import-DbatoolsConfig -ModuleName message
    
        Imports all the module specific settings that have been persisted in any of the default file system paths.
#>
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingEmptyCatchBlock", "")]
    [CmdletBinding(DefaultParameterSetName = "Path")]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "Path")]
        [string[]]
        $Path,
        
        [Parameter(ParameterSetName = "ModuleName", Mandatory = $true)]
        [string]
        $ModuleName,
        
        [Parameter(ParameterSetName = "ModuleName")]
        [int]
        $ModuleVersion = 1,
        
        [Parameter(ParameterSetName = "ModuleName")]
        [Sqlcollaborative.Dbatools.Configuration.ConfigScope]
        $Scope = "FileUserLocal, FileUserShared, FileSystem",
        
        [Parameter(ParameterSetName = "Path")]
        [string[]]
        $IncludeFilter,
        
        [Parameter(ParameterSetName = "Path")]
        [string[]]
        $ExcludeFilter,
        
        [Parameter(ParameterSetName = "Path")]
        [switch]
        $Peek,
        
        [switch]
        $EnableException
    )
    
    begin
    {
        Write-Message -Level InternalComment -Message "Bound parameters: $($PSBoundParameters.Keys -join ", ")" -Tag 'debug','start','param'
    }
    process
    {
        #region Explicit Path
        foreach ($item in $Path)
        {
            try
            {
                if ($item -like "http*") { $data = Read-DbatoolsConfigFile -Weblink $item -ErrorAction Stop }
                else
                {
                    $pathItem = $null
                    try { $pathItem = Resolve-DbaPath -Path $item -SingleItem -Provider FileSystem }
                    catch { }
                    if ($pathItem) { $data = Read-DbatoolsConfigFile -Path $pathItem -ErrorAction Stop }
                    else { $data = Read-DbatoolsConfigFile -RawJson $item -ErrorAction Stop }
                }
            }
            catch { Stop-Function -Message "Failed to import $item" -EnableException $EnableException -Tag 'fail', 'import' -ErrorRecord $_ -Continue -Target $item }
            
            :element foreach ($element in $data)
            {
                #region Exclude Filter
                foreach ($exclusion in $ExcludeFilter)
                {
                    if ($element.FullName -like $exclusion)
                    {
                        continue element
                    }
                }
                #endregion Exclude Filter
                
                #region Include Filter
                if ($IncludeFilter)
                {
                    $isIncluded = $false
                    foreach ($inclusion in $IncludeFilter)
                    {
                        if ($element.FullName -like $inclusion)
                        {
                            $isIncluded = $true
                            break
                        }
                    }
                    
                    if (-not $isIncluded) { continue }
                }
                #endregion Include Filter
                
                if ($Peek) { $element }
                else
                {
                    try
                    {
                        if (-not $element.KeepPersisted) { Set-DbatoolsConfig -FullName $element.FullName -Value $element.Value -EnableException }
                        else { Set-DbatoolsConfig -FullName $element.FullName -PersistedValue $element.Value -PersistedType $element.Type }
                    }
                    catch
                    {
                        Stop-Function -Message "Failed to set '$($element.FullName)'" -ErrorRecord $_ -EnableException $EnableException -Tag 'fail', 'import' -Continue -Target $item
                    }
                }
            }
        }
        #endregion Explicit Path
        
        if ($ModuleName)
        {
            $data = Read-DbatoolsConfigPersisted -Module $ModuleName -Scope $Scope -ModuleVersion $ModuleVersion
            
            foreach ($value in $data.Values)
            {
                if (-not $value.KeepPersisted) { Set-DbatoolsConfig -FullName $value.FullName -Value $value.Value -EnableException:$EnableException}
                else { Set-DbatoolsConfig -FullName $value.FullName -Value ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::ConvertFromPersistedValue($value.Value, $value.Type)) -EnableException:$EnableException }
            }
        }
    }
    end
    {
    
    }
}
tools\dbatools\functions\configuration\Register-DbatoolsConfig.ps1
function Register-DbatoolsConfig
{
<#
    .SYNOPSIS
        Registers an existing configuration object in registry.
    
    .DESCRIPTION
        Registers an existing configuration object in registry.
        This allows simple persisting of settings across powershell consoles.
        It also can be used to generate a registry template, which can then be used to create policies.
    
    .PARAMETER Config
        The configuration object to write to registry.
        Can be retrieved using Get-DbatoolsConfig.
    
    .PARAMETER FullName
        The full name of the setting to be written to registry.
    
    .PARAMETER Module
        The name of the module, whose settings should be written to registry.
    
    .PARAMETER Name
        Default: "*"
        Used in conjunction with the -Module parameter to restrict the number of configuration items written to registry.
    
    .PARAMETER Scope
        Default: UserDefault
        Who will be affected by this export how? Current user or all? Default setting or enforced?
        Legal values: UserDefault, UserMandatory, SystemDefault, SystemMandatory
    
    .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-DbatoolsConfig message.style.* | Register-DbatoolsConfig
    
        Retrieves all configuration items that that start with message.style. and registers them in registry for the current user.
    
    .EXAMPLE
        PS C:\> Register-DbatoolsConfig -FullName "message.consoleoutput.disable" -Scope SystemDefault
    
        Retrieves the configuration item "message.consoleoutput.disable" and registers it in registry as the default setting for all users on this machine.
    
    .EXAMPLE
        PS C:\> Register-DbatoolsConfig -Module Message -Scope SystemMandatory
    
        Retrieves all configuration items of the module Message, then registers them in registry to enforce them for all users on the current system.
#>
    [CmdletBinding(DefaultParameterSetName = "Default")]
    Param (
        [Parameter(ParameterSetName = "Default", Position = 0, ValueFromPipeline = $true)]
        [Sqlcollaborative.Dbatools.Configuration.Config[]]
        $Config,
        
        [Parameter(ParameterSetName = "Default", Position = 0, ValueFromPipeline = $true)]
        [string[]]
        $FullName,
        
        [Parameter(Mandatory = $true, ParameterSetName = "Name", Position = 0)]
        [string]
        $Module,
        
        [Parameter(ParameterSetName = "Name", Position = 1)]
        [string]
        $Name = "*",
        
        [Sqlcollaborative.Dbatools.Configuration.ConfigScope]
        $Scope = "UserDefault",
        
        [switch]
        $EnableException
    )
    
    begin
    {
        if ($script:NoRegistry -and ($Scope -band 14))
        {
            Stop-Function -Message "Cannot register configurations on non-windows machines to registry. Please specify a file-based scope" -Tag 'NotSupported' -Category NotImplemented
            return
        }
        
        # Linux and MAC default to local user store file
        if ($script:NoRegistry -and ($Scope -eq "UserDefault"))
        {
            $Scope = [Sqlcollaborative.Dbatools.Configuration.ConfigScope]::FileUserLocal
        }
        # Linux and MAC get redirection for SystemDefault to FileSystem
        if ($script:NoRegistry -and ($Scope -eq "SystemDefault"))
        {
            $Scope = [Sqlcollaborative.Dbatools.Configuration.ConfigScope]::FileSystem
        }
        
        $parSet = $PSCmdlet.ParameterSetName
        
        function Write-Config
        {
            [CmdletBinding()]
            Param (
                [Sqlcollaborative.Dbatools.Configuration.Config]
                $Config,
                
                [Sqlcollaborative.Dbatools.Configuration.ConfigScope]
                $Scope,
                
                [bool]
                $EnableException,
                
                [string]
                $FunctionName = (Get-PSCallStack)[0].Command
            )
            
            if (-not $Config -or ($Config.RegistryData -eq "<type not supported>"))
            {
                Stop-Function -Message "Invalid Input, cannot export $($Config.FullName), type not supported" -EnableException $EnableException -Category InvalidArgument -Tag "config", "fail" -Target $Config -FunctionName $FunctionName
                return
            }
            
            try
            {
                Write-Message -Level Verbose -Message "Registering $($Config.FullName) for $Scope" -Tag "Config" -Target $Config -FunctionName $FunctionName
                #region User Default
                if (1 -band $Scope)
                {
                    Ensure-RegistryPath -Path $script:path_RegistryUserDefault -ErrorAction Stop
                    Set-ItemProperty -Path $script:path_RegistryUserDefault -Name $Config.FullName -Value $Config.RegistryData -ErrorAction Stop
                }
                #endregion User Default
                
                #region User Mandatory
                if (2 -band $Scope)
                {
                    Ensure-RegistryPath -Path $script:path_RegistryUserEnforced -ErrorAction Stop
                    Set-ItemProperty -Path $script:path_RegistryUserEnforced -Name $Config.FullName -Value $Config.RegistryData -ErrorAction Stop
                }
                #endregion User Mandatory
                
                #region System Default
                if (4 -band $Scope)
                {
                    Ensure-RegistryPath -Path $script:path_RegistryMachineDefault -ErrorAction Stop
                    Set-ItemProperty -Path $script:path_RegistryMachineDefault -Name $Config.FullName -Value $Config.RegistryData -ErrorAction Stop
                }
                #endregion System Default
                
                #region System Mandatory
                if (8 -band $Scope)
                {
                    Ensure-RegistryPath -Path $script:path_RegistryMachineEnforced -ErrorAction Stop
                    Set-ItemProperty -Path $script:path_RegistryMachineEnforced -Name $Config.FullName -Value $Config.RegistryData -ErrorAction Stop
                }
                #endregion System Mandatory
            }
            catch
            {
                Stop-Function -Message "Failed to export $($Config.FullName), to scope $Scope" -EnableException $EnableException -Tag "config", "fail" -Target $Config -ErrorRecord $_ -FunctionName $FunctionName
                return
            }
        }
        
        function Ensure-RegistryPath
        {
            [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseApprovedVerbs", "")]
            [CmdletBinding()]
            Param (
                [string]
                $Path
            )
            
            if (-not (Test-Path $Path))
            {
                $null = New-Item $Path -Force
            }
        }
        
        # For file based persistence
        $configurationItems = @()
    }
    process
    {
        if (Test-FunctionInterrupt) { return }
        
        #region Registry Based
        if ($Scope -band 15)
        {
            switch ($parSet)
            {
                "Default"
                {
                    foreach ($item in $Config)
                    {
                        Write-Config -Config $item -Scope $Scope -EnableException $EnableException
                    }
                    
                    foreach ($item in $FullName)
                    {
                        if ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations.ContainsKey($item.ToLower()))
                        {
                            Write-Config -Config ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations[$item.ToLower()]) -Scope $Scope -EnableException $EnableException
                        }
                    }
                }
                "Name"
                {
                    foreach ($item in ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations.Values | Where-Object Module -EQ $Module | Where-Object Name -Like $Name))
                    {
                        Write-Config -Config $item -Scope $Scope -EnableException $EnableException
                    }
                }
            }
        }
        #endregion Registry Based
        
        #region File Based
        else
        {
            switch ($parSet)
            {
                "Default"
                {
                    foreach ($item in $Config)
                    {
                        if ($configurationItems.FullName -notcontains $item.FullName) { $configurationItems += $item }
                    }
                    
                    foreach ($item in $FullName)
                    {
                        if (($configurationItems.FullName -notcontains $item) -and ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations.ContainsKey($item.ToLower())))
                        {
                            $configurationItems += [Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations[$item.ToLower()]
                        }
                    }
                }
                "Name"
                {
                    foreach ($item in ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations.Values | Where-Object Module -EQ $Module | Where-Object Name -Like $Name))
                    {
                        if ($configurationItems.FullName -notcontains $item.FullName) { $configurationItems += $item }
                    }
                }
            }
        }
        #endregion File Based
    }
    end
    {
        if (Test-FunctionInterrupt) { return }
        
        #region Finish File Based Persistence
        if ($Scope -band 16)
        {
            Write-DbatoolsConfigFile -Config $configurationItems -Path (Join-Path $script:path_FileUserLocal "psf_config.json")
        }
        if ($Scope -band 32)
        {
            Write-DbatoolsConfigFile -Config $configurationItems -Path (Join-Path $script:path_FileUserShared "psf_config.json")
        }
        if ($Scope -band 64)
        {
            Write-DbatoolsConfigFile -Config $configurationItems -Path (Join-Path $script:path_FileSystem "psf_config.json")
        }
        #endregion Finish File Based Persistence
    }
}
tools\dbatools\functions\configuration\Reset-DbatoolsConfig.ps1
function Reset-DbatoolsConfig
{
<#
    .SYNOPSIS
        Reverts a configuration item to its default value.
    
    .DESCRIPTION
        This command can be used to revert a configuration item to the value it was initialized with.
        Generally, this amounts to reverting it to its default value.
        
        In order for a reset to be possible, two conditions must be met:
        - The setting must have been initialized.
        - The setting cannot have been enforced by policy.
    
    .PARAMETER ConfigurationItem
        A configuration object as returned by Get-DbatoolsConfig.
    
    .PARAMETER FullName
        The full name of the setting to reset, offering the maximum of precision.
    
    .PARAMETER Module
        The name of the module, from which configurations should be reset.
        Used in conjunction with the -Name parameter to filter a specific set of items.
    
    .PARAMETER Name
        Used in conjunction with the -Module parameter to select which settings to reset using wildcard comparison.
    
    .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:\> Reset-DbatoolsConfig -Module MyModule
    
        Resets all configuration items of the MyModule to default.
    
    .EXAMPLE
        PS C:\> Get-DbatoolsConfig | Reset-DbatoolsConfig
    
        Resets ALL configuration items to default.
    
    .EXAMPLE
        PS C:\> Reset-DbatoolsConfig -FullName MyModule.Group.Setting1
    
        Resets the configuration item named 'MyModule.Group.Setting1'.
#>
    [CmdletBinding(DefaultParameterSetName = 'Pipeline')]
    param (
        [Parameter(ValueFromPipeline = $true, ParameterSetName = 'Pipeline')]
        [Sqlcollaborative.Dbatools.Configuration.Config[]]
        $ConfigurationItem,
        
        [Parameter(ValueFromPipeline = $true, ParameterSetName = 'Pipeline')]
        [string[]]
        $FullName,
        
        [Parameter(Mandatory = $true, ParameterSetName = 'Module')]
        [string]
        $Module,
        
        [Parameter(ParameterSetName = 'Module')]
        [string]
        $Name = "*",
        
        [switch]
        $EnableException
    )
    
    process
    {
        #region By configuration Item
        foreach ($item in $ConfigurationItem)
        {
            if ($PSCmdlet.ShouldProcess($item.FullName, 'Reset to default value'))
            {
                try { $item.ResetValue() }
                catch { Stop-Function -Message "Failed to reset the configuration item." -ErrorRecord $_ -Continue -EnableException $EnableException }
            }
        }
        #endregion By configuration Item
        
        #region By FullName
        foreach ($nameItem in $FullName)
        {
            # The configuration items themselves can be cast to string, so they need to be filtered out,
            # otherwise on bind they would execute for this code-path as well.
            if ($nameItem -ceq "Sqlcollaborative.Dbatools.Configuration.Config") { continue }
            
            foreach ($item in (Get-DbatoolsConfig -FullName $nameItem))
            {
                if ($PSCmdlet.ShouldProcess($item.FullName, 'Reset to default value'))
                {
                    try { $item.ResetValue() }
                    catch { Stop-Function -Message "Failed to reset the configuration item." -ErrorRecord $_ -Continue -EnableException $EnableException }
                }
            }
        }
        #endregion By FullName
        if ($Module)
        {
            foreach ($item in (Get-DbatoolsConfig -Module $Module -Name $Name))
            {
                if ($PSCmdlet.ShouldProcess($item.FullName, 'Reset to default value'))
                {
                    try { $item.ResetValue() }
                    catch { Stop-Function -Message "Failed to reset the configuration item." -ErrorRecord $_ -Continue -EnableException $EnableException }
                }
            }
        }
    }
}
tools\dbatools\functions\configuration\Unregister-DbatoolsConfig.ps1
function Unregister-DbatoolsConfig
{
<#
    .SYNOPSIS
        Removes registered configuration settings.
    
    .DESCRIPTION
        Removes registered configuration settings.
        This function can be used to remove settings that have been persisted for either user or computer.
    
        Note: This command has no effect on configuration setings currently in memory.
    
    .PARAMETER ConfigurationItem
        A configuration object as returned by Get-DbatoolsConfig.
    
    .PARAMETER FullName
        The full name of the configuration setting to purge.
    
    .PARAMETER Module
        The module, amongst which settings should be unregistered.
    
    .PARAMETER Name
        The name of the setting to unregister.
        For use together with the module parameter, to limit the amount of settings that are unregistered.
    
    .PARAMETER Scope
        Settings can be set to either default or enforced, for user or the entire computer.
        By default, only DefaultSettings for the user are unregistered.
        Use this parameter to choose the actual scope for the command to process.
    
    .EXAMPLE
        PS C:\> Get-DbatoolsConfig | Unregister-DbatoolsConfig
    
        Completely removes all registered configurations currently loaded in memory.
        In most cases, this will mean removing all registered configurations.
    
    .EXAMPLE
        PS C:\> Unregister-DbatoolsConfig -Scope SystemDefault -FullName 'MyModule.Path.DefaultExport'
    
        Unregisters the setting 'MyModule.Path.DefaultExport' from the list of computer-wide defaults.
        Note: Changing system wide settings requires running the console with elevation.
    
    .EXAMPLE
        PS C:\> Unregister-DbatoolsConfig -Module MyModule
    
        Unregisters all configuration settings for the module MyModule.
#>
    [CmdletBinding(DefaultParameterSetName = 'Pipeline')]
    param (
        [Parameter(ValueFromPipeline = $true, ParameterSetName = 'Pipeline')]
        [Sqlcollaborative.Dbatools.Configuration.Config[]]
        $ConfigurationItem,
        
        [Parameter(ValueFromPipeline = $true, ParameterSetName = 'Pipeline')]
        [string[]]
        $FullName,
        
        [Parameter(Mandatory = $true, ParameterSetName = 'Module')]
        [string]
        $Module,
        
        [Parameter(ParameterSetName = 'Module')]
        [string]
        $Name = "*",
        
        [Sqlcollaborative.Dbatools.Configuration.ConfigScope]
        $Scope = "UserDefault"
    )
    
    begin
    {
        if (($PSVersionTable.PSVersion.Major -ge 6) -and ($PSVersionTable.OS -notlike "*Windows*") -and ($Scope -band 15))
        {
            Stop-Function -Message "Cannot unregister configurations from registry on non-windows machines." -Tag 'NotSupported' -Category ResourceUnavailable
            return
        }
        
        #region Initialize Collection
        $registryProperties = @()
        if ($Scope -band 1)
        {
            if (Test-Path $script:path_RegistryUserDefault) { $registryProperties += Get-ItemProperty -Path $script:path_RegistryUserDefault }
        }
        if ($Scope -band 2)
        {
            if (Test-Path $script:path_RegistryUserEnforced) { $registryProperties += Get-ItemProperty -Path $script:path_RegistryUserEnforced }
        }
        if ($Scope -band 4)
        {
            if (Test-Path $script:path_RegistryMachineDefault) { $registryProperties += Get-ItemProperty -Path $script:path_RegistryMachineDefault }
        }
        if ($Scope -band 8)
        {
            if (Test-Path $script:path_RegistryMachineEnforced) { $registryProperties += Get-ItemProperty -Path $script:path_RegistryMachineEnforced }
        }
        $pathProperties = @()
        if ($Scope -band 16)
        {
            $fileUserLocalSettings = @()
            if (Test-Path (Join-Path $script:path_FileUserLocal "psf_config.json")) { $fileUserLocalSettings = Get-Content (Join-Path $script:path_FileUserLocal "psf_config.json") -Encoding UTF8 | ConvertFrom-Json }
            if ($fileUserLocalSettings)
            {
                $pathProperties += [pscustomobject]@{
                    Path       = (Join-Path $script:path_FileUserLocal "psf_config.json")
                    Properties = $fileUserLocalSettings
                    Changed    = $false
                }
            }
        }
        if ($Scope -band 32)
        {
            $fileUserSharedSettings = @()
            if (Test-Path (Join-Path $script:path_FileUserShared "psf_config.json")) { $fileUserSharedSettings = Get-Content (Join-Path $script:path_FileUserShared "psf_config.json") -Encoding UTF8 | ConvertFrom-Json }
            if ($fileUserSharedSettings)
            {
                $pathProperties += [pscustomobject]@{
                    Path       = (Join-Path $script:path_FileUserShared "psf_config.json")
                    Properties = $fileUserSharedSettings
                    Changed    = $false
                }
            }
        }
        if ($Scope -band 64)
        {
            $fileSystemSettings = @()
            if (Test-Path (Join-Path $script:path_FileSystem "psf_config.json")) { $fileSystemSettings = Get-Content (Join-Path $script:path_FileSystem "psf_config.json") -Encoding UTF8 | ConvertFrom-Json }
            if ($fileSystemSettings)
            {
                $pathProperties += [pscustomobject]@{
                    Path       = (Join-Path $script:path_FileSystem "psf_config.json")
                    Properties = $fileSystemSettings
                    Changed    = $false
                }
            }
        }
        #endregion Initialize Collection
        
        $common = 'PSPath', 'PSParentPath', 'PSChildName', 'PSDrive', 'PSProvider'
    }
    process
    {
        if (Test-FunctionInterrupt) { return }
        # Silently skip since no action necessary
        if (-not ($pathProperties -or $registryProperties)) { return }
        
        foreach ($item in $ConfigurationItem)
        {
            # Registry
            foreach ($hive in ($registryProperties | Where-Object { $_.PSObject.Properties.Name -eq $item.FullName }))
            {
                Remove-ItemProperty -Path $hive.PSPath -Name $item.FullName
            }
            # Prepare file
            foreach ($fileConfig in ($pathProperties | Where-Object { $_.Properties.FullName -contains $item.FullName }))
            {
                $fileConfig.Properties = $fileConfig.Properties | Where-Object FullName -NE $item.FullName
                $fileConfig.Changed = $true
            }
        }
        
        foreach ($item in $FullName)
        {
            # Ignore string-casted configurations
            if ($item -ceq "Sqlcollaborative.Dbatools.Configuration.Config") { continue }
            
            # Registry
            foreach ($hive in ($registryProperties | Where-Object { $_.PSObject.Properties.Name -eq $item }))
            {
                Remove-ItemProperty -Path $hive.PSPath -Name $item
            }
            # Prepare file
            foreach ($fileConfig in ($pathProperties | Where-Object { $_.Properties.FullName -contains $item }))
            {
                $fileConfig.Properties = $fileConfig.Properties | Where-Object FullName -NE $item
                $fileConfig.Changed = $true
            }
        }
        
        if ($Module)
        {
            $compoundName = "{0}.{1}" -f $Module, $Name
            
            # Registry
            foreach ($hive in ($registryProperties | Where-Object { $_.PSObject.Properties.Name -like $compoundName }))
            {
                foreach ($propName in $hive.PSObject.Properties.Name)
                {
                    if ($propName -in $common) { continue }
                    
                    if ($propName -like $compoundName)
                    {
                        Remove-ItemProperty -Path $hive.PSPath -Name $propName
                    }
                }
            }
            # Prepare file
            foreach ($fileConfig in ($pathProperties | Where-Object { $_.Properties.FullName -like $compoundName }))
            {
                $fileConfig.Properties = $fileConfig.Properties | Where-Object FullName -NotLike $compoundName
                $fileConfig.Changed = $true
            }
        }
    }
    end
    {
        if (Test-FunctionInterrupt) { return }
        
        foreach ($fileConfig in $pathProperties)
        {
            if (-not $fileConfig.Changed) { continue }
            
            if ($fileConfig.Properties)
            {
                $fileConfig.Properties | ConvertTo-Json | Set-Content -Path $fileConfig.Path -Encoding UTF8
            }
            else
            {
                Remove-Item $fileConfig.Path
            }
        }
    }
}
tools\dbatools\functions\Connect-DbaInstance.ps1
function Connect-DbaInstance {
    <#
    .SYNOPSIS
        Creates a robust SMO SQL Server object.

    .DESCRIPTION
        This command is robust because it initializes properties that do not cause enumeration by default. It also supports both Windows and SQL Server authentication methods, and detects which to use based upon the provided credentials.

        By default, this command also sets the connection's ApplicationName property  to "dbatools PowerShell module - dbatools.io - custom connection". If you're doing anything that requires profiling, you can look for this client name.

        Alternatively, you can pass in whichever client name you'd like using the -ClientName parameter. There are a ton of other parameters for you to explore as well.

        See https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx
        and https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.aspx,
        and https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx

        To execute SQL commands, you can use $server.ConnectionContext.ExecuteReader($sql) or $server.Databases['master'].ExecuteNonQuery($sql)

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Credential object used to connect to the SQL Server Instance as a different user. This can be a Windows or SQL Server account. Windows users are determined by the existence of a backslash, so if you are intending to use an alternative Windows connection instead of a SQL login, ensure it contains a backslash.

    .PARAMETER Database
        The database(s) to process. This list is auto-populated from the server.

    .PARAMETER AccessToken
        Gets or sets the access token for the connection.

    .PARAMETER AppendConnectionString
        Appends to the current connection string. Note that you cannot pass authentication information using this method. Use -SqlInstance and optionally -SqlCredential to set authentication information.

    .PARAMETER ApplicationIntent
        Declares the application workload type when connecting to a server.

        Valid values are "ReadOnly" and "ReadWrite".

    .PARAMETER BatchSeparator
        A string to separate groups of SQL statements being executed. By default, this is "GO".

    .PARAMETER ClientName
        By default, this command sets the client's ApplicationName property to "dbatools PowerShell module - dbatools.io - custom connection" if you're doing anything that requires profiling, you can look for this client name. Using -ClientName allows you to set your own custom client application name.

    .PARAMETER ConnectTimeout
        The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error.

        Valid values are integers between 0 and 2147483647.

        When opening a connection to a Azure SQL Database, set the connection timeout to 30 seconds.

    .PARAMETER EncryptConnection
        If this switch is enabled, SQL Server uses SSL encryption for all data sent between the client and server if the server has a certificate installed.

        For more information, see Connection String Syntax. https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/connection-string-syntax

        Beginning in .NET Framework 4.5, when TrustServerCertificate is false and Encrypt is true, the server name (or IP address) in a SQL Server SSL certificate must exactly match the server name (or IP address) specified in the connection string. Otherwise, the connection attempt will fail. For information about support for certificates whose subject starts with a wildcard character (*), see Accepted wildcards used by server certificates for server authentication. https://support.microsoft.com/en-us/help/258858/accepted-wildcards-used-by-server-certificates-for-server-authenticati

    .PARAMETER FailoverPartner
        The name of the failover partner server where database mirroring is configured.

        If the value of this key is "" (an empty string), then Initial Catalog must be present in the connection string, and its value must not be "".

        The server name can be 128 characters or less.

        If you specify a failover partner but the failover partner server is not configured for database mirroring and the primary server (specified with the Server keyword) is not available, then the connection will fail.

        If you specify a failover partner and the primary server is not configured for database mirroring, the connection to the primary server (specified with the Server keyword) will succeed if the primary server is available.

    .PARAMETER LockTimeout
        Sets the time in seconds required for the connection to time out when the current transaction is locked.

    .PARAMETER MaxPoolSize
        Sets the maximum number of connections allowed in the connection pool for this specific connection string.

    .PARAMETER MinPoolSize
        Sets the minimum number of connections allowed in the connection pool for this specific connection string.

    .PARAMETER MultipleActiveResultSets
        If this switch is enabled, an application can maintain multiple active result sets (MARS).

        If this switch is not enabled, an application must process or cancel all result sets from one batch before it can execute any other batch on that connection.

    .PARAMETER MultiSubnetFailover
        If this switch is enabled, and your application is connecting to an AlwaysOn availability group (AG) on different subnets, detection of and connection to the currently active server will be faster. For more information about SqlClient support for Always On Availability Groups, see https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/sqlclient-support-for-high-availability-disaster-recovery

    .PARAMETER NetworkProtocol
        Explicitly sets the network protocol used to connect to the server.

        Valid values are "TcpIp","NamedPipes","Multiprotocol","AppleTalk","BanyanVines","Via","SharedMemory" and "NWLinkIpxSpx"

    .PARAMETER NonPooledConnection
        If this switch is enabled, a non-pooled connection will be requested.

    .PARAMETER PacketSize
        Sets the size in bytes of the network packets used to communicate with an instance of SQL Server. Must match at server.

    .PARAMETER PooledConnectionLifetime
        When a connection is returned to the pool, its creation time is compared with the current time and the connection is destroyed if that time span (in seconds) exceeds the value specified by Connection Lifetime. This is useful in clustered configurations to force load balancing between a running server and a server just brought online.

        A value of zero (0) causes pooled connections to have the maximum connection timeout.

    .PARAMETER SqlExecutionModes
        The SqlExecutionModes enumeration contains values that are used to specify whether the commands sent to the referenced connection to the server are executed immediately or saved in a buffer.

        Valid values include "CaptureSql", "ExecuteAndCaptureSql" and "ExecuteSql".

    .PARAMETER StatementTimeout
        Sets the number of seconds a statement is given to run before failing with a timeout error.

    .PARAMETER TrustServerCertificate
        When this switch is enabled, the channel will be encrypted while bypassing walking the certificate chain to validate trust.

    .PARAMETER WorkstationId
        Sets the name of the workstation connecting to SQL Server.

    .PARAMETER SqlConnectionOnly
        Instead of returning a rich SMO server object, this command will only return a SqlConnection object when setting this switch.

    .PARAMETER DisableException
        By default in most of our commands, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.

        This command, however, gifts you  with "sea of red" exceptions, by default, because it is useful for advanced scripting.

        Using this switch turns our "nice by default" feature on which makes errors into pretty warnings.

    .NOTES
        Tags: Connect, Connection
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Connect-DbaInstance

    .EXAMPLE
        PS C:\> Connect-DbaInstance -SqlInstance sql2014

        Creates an SMO Server object that connects using Windows Authentication

    .EXAMPLE
        PS C:\> $wincred = Get-Credential ad\sqladmin
        PS C:\> Connect-DbaInstance -SqlInstance sql2014 -SqlCredential $wincred

        Creates an SMO Server object that connects using alternative Windows credentials

    .EXAMPLE
        PS C:\> $sqlcred = Get-Credential sqladmin
        PS C:\> $server = Connect-DbaInstance -SqlInstance sql2014 -SqlCredential $sqlcred

        Login to sql2014 as SQL login sqladmin.

    .EXAMPLE
        PS C:\> $server = Connect-DbaInstance -SqlInstance sql2014 -ClientName "my connection"

        Creates an SMO Server object that connects using Windows Authentication and uses the client name "my connection". So when you open up profiler or use extended events, you can search for "my connection".

    .EXAMPLE
        PS C:\> $server = Connect-DbaInstance -SqlInstance sql2014 -AppendConnectionString "Packet Size=4096;AttachDbFilename=C:\MyFolder\MyDataFile.mdf;User Instance=true;"

        Creates an SMO Server object that connects to sql2014 using Windows Authentication, then it sets the packet size (this can also be done via -PacketSize) and other connection attributes.

    .EXAMPLE
        PS C:\> $server = Connect-DbaInstance -SqlInstance sql2014 -NetworkProtocol TcpIp -MultiSubnetFailover

        Creates an SMO Server object that connects using Windows Authentication that uses TCP/IP and has MultiSubnetFailover enabled.

    .EXAMPLE
        PS C:\> $server = Connect-DbaInstance sql2016 -ApplicationIntent ReadOnly

        Connects with ReadOnly ApplicationIntent.

    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [string]$AccessToken,
        [ValidateSet('ReadOnly', 'ReadWrite')]
        [string]$ApplicationIntent,
        [string]$BatchSeparator,
        [string]$ClientName = "dbatools PowerShell module - dbatools.io - custom connection",
        [int]$ConnectTimeout = ([Sqlcollaborative.Dbatools.Connection.ConnectionHost]::SqlConnectionTimeout),
        [switch]$EncryptConnection,
        [string]$FailoverPartner,
        [int]$LockTimeout,
        [int]$MaxPoolSize,
        [int]$MinPoolSize,
        [switch]$MultipleActiveResultSets,
        [switch]$MultiSubnetFailover,
        [ValidateSet('TcpIp', 'NamedPipes', 'Multiprotocol', 'AppleTalk', 'BanyanVines', 'Via', 'SharedMemory', 'NWLinkIpxSpx')]
        [string]$NetworkProtocol,
        [switch]$NonPooledConnection,
        [int]$PacketSize,
        [int]$PooledConnectionLifetime,
        [ValidateSet('CaptureSql', 'ExecuteAndCaptureSql', 'ExecuteSql')]
        [string]$SqlExecutionModes,
        [int]$StatementTimeout,
        [switch]$TrustServerCertificate,
        [string]$WorkstationId,
        [string]$AppendConnectionString,
        [switch]$SqlConnectionOnly,
        [switch]$DisableException
    )
    begin {
        if ($DisableException) {
            $EnableException = $false
        } else {
            $EnableException = $true
        }

        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Connect-DbaServer
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaInstance

        $loadedSmoVersion = [AppDomain]::CurrentDomain.GetAssemblies() | Where-Object {
            $_.Fullname -like "Microsoft.SqlServer.SMO,*"
        }

        if ($loadedSmoVersion) {
            $loadedSmoVersion = $loadedSmoVersion | ForEach-Object {
                if ($_.Location -match "__") {
                    ((Split-Path (Split-Path $_.Location) -Leaf) -split "__")[0]
                } else {
                    ((Get-ChildItem -Path $_.Location).VersionInfo.ProductVersion)
                }
            }
        }
        #'PrimaryFilePath' seems the culprit for slow SMO on databases
        $Fields2000_Db = 'Collation', 'CompatibilityLevel', 'CreateDate', 'ID', 'IsAccessible', 'IsFullTextEnabled', 'IsSystemObject', 'IsUpdateable', 'LastBackupDate', 'LastDifferentialBackupDate', 'LastLogBackupDate', 'Name', 'Owner', 'ReadOnly', 'RecoveryModel', 'ReplicationOptions', 'Status', 'Version'
        $Fields200x_Db = $Fields2000_Db + @('BrokerEnabled', 'DatabaseSnapshotBaseName', 'IsMirroringEnabled', 'Trustworthy')
        $Fields201x_Db = $Fields200x_Db + @('ActiveConnections', 'AvailabilityDatabaseSynchronizationState', 'AvailabilityGroupName', 'ContainmentType', 'EncryptionEnabled')

        $Fields2000_Login = 'CreateDate', 'DateLastModified', 'DefaultDatabase', 'DenyWindowsLogin', 'IsSystemObject', 'Language', 'LanguageAlias', 'LoginType', 'Name', 'Sid', 'WindowsLoginAccessType'
        $Fields200x_Login = $Fields2000_Login + @('AsymmetricKey', 'Certificate', 'Credential', 'ID', 'IsDisabled', 'IsLocked', 'IsPasswordExpired', 'MustChangePassword', 'PasswordExpirationEnabled', 'PasswordPolicyEnforced')
        $Fields201x_Login = $Fields200x_Login + @('PasswordHashAlgorithm')
    }
    process {
        foreach ($instance in $SqlInstance) {
            #region Safely convert input into instance parameters
            if ($instance.GetType() -eq [Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter]) {
                [DbaInstanceParameter]$ConvertedSqlInstance = $instance
                if ($ConvertedSqlInstance.Type -like "SqlConnection") {
                    [DbaInstanceParameter]$ConvertedSqlInstance = New-Object Microsoft.SqlServer.Management.Smo.Server($ConvertedSqlInstance.InputObject)
                }
            } else {
                [DbaInstanceParameter]$ConvertedSqlInstance = [DbaInstanceParameter]($instance | Select-Object -First 1)

                if ($instance.Count -gt 1) {
                    Write-Message -Level Warning -EnableException $true -Message "More than on server was specified when calling Connect-SqlInstance from $((Get-PSCallStack)[1].Command)"
                }
            }
            #endregion Safely convert input into instance parameters
            if ($instance.Type -like "Server") {
                if ($instance.InputObject.ConnectionContext.IsOpen -eq $false) {
                    $instance.InputObject.ConnectionContext.Connect()
                }
                if ($SqlConnectionOnly) {
                    return $instance.InputObject.ConnectionContext.SqlConnectionObject
                } else {
                    return $instance.InputObject
                }
            }
            if ($instance.Type -like "SqlConnection") {
                $server = New-Object Microsoft.SqlServer.Management.Smo.Server($instance.InputObject)

                if ($server.ConnectionContext.IsOpen -eq $false) {
                    $server.ConnectionContext.Connect()
                }
                if ($SqlConnectionOnly) {
                    return $server.ConnectionContext.SqlConnectionObject
                } else {
                    if (-not $server.ComputerName) {
                        if (-not $server.NetName -or $SqlInstance -match '\.') {
                            $parsedcomputername = $ConvertedSqlInstance.ComputerName
                        } else {
                            $parsedcomputername = $server.NetName
                        }
                        Add-Member -InputObject $server -NotePropertyName ComputerName -NotePropertyValue $parsedcomputername -Force
                    }
                    return $server
                }
            }

            if ($instance.IsConnectionString) {
                $server = New-Object Microsoft.SqlServer.Management.Smo.Server($instance.InputObject)
            } else {
                $server = New-Object Microsoft.SqlServer.Management.Smo.Server $instance.FullSmoName
            }

            if ($AppendConnectionString) {
                $connstring = $server.ConnectionContext.ConnectionString
                $server.ConnectionContext.ConnectionString = "$connstring;$appendconnectionstring"
                $server.ConnectionContext.Connect()
            } else {

                $server.ConnectionContext.ApplicationName = $ClientName

                if (Test-Bound -ParameterName 'AccessToken') {
                    $server.ConnectionContext.AccessToken = $AccessToken
                }
                if (Test-Bound -ParameterName 'BatchSeparator') {
                    $server.ConnectionContext.BatchSeparator = $BatchSeparator
                }
                if (Test-Bound -ParameterName 'ConnectTimeout') {
                    $server.ConnectionContext.ConnectTimeout = $ConnectTimeout
                }
                if (Test-Bound -ParameterName 'Database') {
                    $server.ConnectionContext.DatabaseName = $Database
                }
                if (Test-Bound -ParameterName 'EncryptConnection') {
                    $server.ConnectionContext.EncryptConnection = $true
                }
                if (Test-Bound -ParameterName 'LockTimeout') {
                    $server.ConnectionContext.LockTimeout = $LockTimeout
                }
                if (Test-Bound -ParameterName 'MaxPoolSize') {
                    $server.ConnectionContext.MaxPoolSize = $MaxPoolSize
                }
                if (Test-Bound -ParameterName 'MinPoolSize') {
                    $server.ConnectionContext.MinPoolSize = $MinPoolSize
                }
                if (Test-Bound -ParameterName 'MultipleActiveResultSets') {
                    $server.ConnectionContext.MultipleActiveResultSets = $true
                }
                if (Test-Bound -ParameterName 'NetworkProtocol') {
                    $server.ConnectionContext.NetworkProtocol = $NetworkProtocol
                }
                if (Test-Bound -ParameterName 'NonPooledConnection') {
                    $server.ConnectionContext.NonPooledConnection = $true
                }
                if (Test-Bound -ParameterName 'PacketSize') {
                    $server.ConnectionContext.PacketSize = $PacketSize
                }
                if (Test-Bound -ParameterName 'PooledConnectionLifetime') {
                    $server.ConnectionContext.PooledConnectionLifetime = $PooledConnectionLifetime
                }
                if (Test-Bound -ParameterName 'StatementTimeout') {
                    $server.ConnectionContext.StatementTimeout = $StatementTimeout
                }
                if (Test-Bound -ParameterName 'SqlExecutionModes') {
                    $server.ConnectionContext.SqlExecutionModes = $SqlExecutionModes
                }
                if (Test-Bound -ParameterName 'TrustServerCertificate') {
                    $server.ConnectionContext.TrustServerCertificate = $true
                }
                if (Test-Bound -ParameterName 'WorkstationId') {
                    $server.ConnectionContext.WorkstationId = $WorkstationId
                }

                $connstring = $server.ConnectionContext.ConnectionString
                if (Test-Bound -ParameterName 'MultiSubnetFailover') {
                    $connstring = "$connstring;MultiSubnetFailover=True"
                }
                if (Test-Bound -ParameterName 'FailoverPartner') {
                    $connstring = "$connstring;Failover Partner=$FailoverPartner"
                }
                if (Test-Bound -ParameterName 'ApplicationIntent') {
                    $connstring = "$connstring;ApplicationIntent=$ApplicationIntent"
                }

                if ($connstring -ne $server.ConnectionContext.ConnectionString) {
                    $server.ConnectionContext.ConnectionString = $connstring
                }

                try {
                    if ($null -ne $SqlCredential.UserName) {
                        $username = ($SqlCredential.UserName).TrimStart("\")

                        # support both ad\username and username@ad
                        if ($username -like "*\*" -or $username -like "*@*") {
                            if ($username -like "*\*") {
                                $domain, $login = $username.Split("\")
                                $authtype = "Windows Authentication with Credential"
                                if ($domain) {
                                    $formatteduser = "$login@$domain"
                                } else {
                                    $formatteduser = $username.Split("\")[1]
                                }
                            } else {
                                $formatteduser = $SqlCredential.UserName
                            }

                            $server.ConnectionContext.LoginSecure = $true
                            $server.ConnectionContext.ConnectAsUser = $true
                            $server.ConnectionContext.ConnectAsUserName = $formatteduser
                            $server.ConnectionContext.ConnectAsUserPassword = ($SqlCredential).GetNetworkCredential().Password
                        } else {
                            $authtype = "SQL Authentication"
                            $server.ConnectionContext.LoginSecure = $false
                            $server.ConnectionContext.set_Login($username)
                            $server.ConnectionContext.set_SecurePassword($SqlCredential.Password)
                        }
                    }

                    if ($NonPooled) {
                        $server.ConnectionContext.Connect()
                    } elseif ($authtype -eq "Windows Authentication with Credential") {
                        # Make it connect in a natural way, hard to explain.
                        $null = $server.Information.Version
                        if ($server.ConnectionContext.IsOpen -eq $false) {
                            $server.ConnectionContext.Connect()
                        }
                    } else {
                        $server.ConnectionContext.SqlConnectionObject.Open()
                    }
                } catch {
                    $originalException = $_.Exception
                    try {
                        $message = $originalException.InnerException.InnerException.ToString()
                    } catch {
                        $message = $originalException.ToString()
                    }
                    $message = ($message -Split '-->')[0]
                    $message = ($message -Split 'at System.Data.SqlClient')[0]
                    $message = ($message -Split 'at System.Data.ProviderBase')[0]

                    Stop-Function -Message "Can't connect to $instance" -ErrorRecord $_ -Continue
                }
            }

            if ($loadedSmoVersion -ge 11) {
                if ($server.VersionMajor -eq 8) {
                    # 2000
                    $initFieldsDb = New-Object System.Collections.Specialized.StringCollection
                    [void]$initFieldsDb.AddRange($Fields2000_Db)
                    $initFieldsLogin = New-Object System.Collections.Specialized.StringCollection
                    [void]$initFieldsLogin.AddRange($Fields2000_Login)
                    $server.SetDefaultInitFields([Microsoft.SqlServer.Management.Smo.Database], $initFieldsDb)
                    $server.SetDefaultInitFields([Microsoft.SqlServer.Management.Smo.Login], $initFieldsLogin)
                } elseif ($server.VersionMajor -eq 9 -or $server.VersionMajor -eq 10) {
                    # 2005 and 2008
                    $initFieldsDb = New-Object System.Collections.Specialized.StringCollection
                    [void]$initFieldsDb.AddRange($Fields200x_Db)
                    $initFieldsLogin = New-Object System.Collections.Specialized.StringCollection
                    [void]$initFieldsLogin.AddRange($Fields200x_Login)
                    $server.SetDefaultInitFields([Microsoft.SqlServer.Management.Smo.Database], $initFieldsDb)
                    $server.SetDefaultInitFields([Microsoft.SqlServer.Management.Smo.Login], $initFieldsLogin)
                } else {
                    # 2012 and above
                    $initFieldsDb = New-Object System.Collections.Specialized.StringCollection
                    [void]$initFieldsDb.AddRange($Fields201x_Db)
                    $initFieldsLogin = New-Object System.Collections.Specialized.StringCollection
                    [void]$initFieldsLogin.AddRange($Fields201x_Login)
                    $server.SetDefaultInitFields([Microsoft.SqlServer.Management.Smo.Database], $initFieldsDb)
                    $server.SetDefaultInitFields([Microsoft.SqlServer.Management.Smo.Login], $initFieldsLogin)
                }
            }

            if ($SqlConnectionOnly) {
                return $server.ConnectionContext.SqlConnectionObject
            } else {
                if (-not $server.ComputerName) {
                    if (-not $server.NetName -or $SqlInstance -match '\.') {
                        $parsedcomputername = $ConvertedSqlInstance.ComputerName
                    } else {
                        $parsedcomputername = $server.NetName
                    }
                    Add-Member -InputObject $server -NotePropertyName ComputerName -NotePropertyValue $parsedcomputername -Force
                }
            }
            $server
        }
    }
}
tools\dbatools\functions\ConvertTo-DbaDataTable.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function ConvertTo-DbaDataTable {
    <#
    .SYNOPSIS
        Creates a DataTable for an object.

    .DESCRIPTION
        Creates a DataTable based on an object's properties. This allows you to easily write to SQL Server tables.

        Thanks to Chad Miller, this is based on his script. https://gallery.technet.microsoft.com/scriptcenter/4208a159-a52e-4b99-83d4-8048468d29dd

        If the attempt to convert to data table fails, try the -Raw parameter for less accurate datatype detection.

    .PARAMETER InputObject
        The object to transform into a DataTable.

    .PARAMETER TimeSpanType
        Specifies the type to convert TimeSpan objects into. Default is 'TotalMilliseconds'. Valid options are: 'Ticks', 'TotalDays', 'TotalHours', 'TotalMinutes', 'TotalSeconds', 'TotalMilliseconds', and 'String'.

    .PARAMETER SizeType
        Specifies the type to convert DbaSize objects to. Default is 'Int64'. Valid options are 'Int32', 'Int64', and 'String'.

    .PARAMETER IgnoreNull
        If this switch is enabled, objects with null values will be ignored (empty rows will be added by default).

    .PARAMETER Raw
        If this switch is enabled, the DataTable will be created with strings. No attempt will be made to parse/determine data types.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DataTable, Table, Data
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io/
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/ConvertTo-DbaDataTable

    .OUTPUTS
        System.Object[]

    .EXAMPLE
        PS C:\> Get-Service | ConvertTo-DbaDataTable

        Creates a DataTable from the output of Get-Service.

    .EXAMPLE
        PS C:\> ConvertTo-DbaDataTable -InputObject $csv.cheesetypes

        Creates a DataTable from the CSV object $csv.cheesetypes.

    .EXAMPLE
        PS C:\> $dblist | ConvertTo-DbaDataTable

        Creates a DataTable from the $dblist object passed in via pipeline.

    .EXAMPLE
        PS C:\> Get-Process | ConvertTo-DbaDataTable -TimeSpanType TotalSeconds

        Creates a DataTable with the running processes and converts any TimeSpan property to TotalSeconds.

    #>
    [CmdletBinding()]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseOutputTypeCorrectly", "", Justification = "PSSA Rule Ignored by BOH")]
    [OutputType([System.Object[]])]
    param (
        [Parameter(Position = 0,
            Mandatory,
            ValueFromPipeline)]
        [AllowNull()]
        [PSObject[]]$InputObject,
        [Parameter(Position = 1)]
        [ValidateSet("Ticks",
            "TotalDays",
            "TotalHours",
            "TotalMinutes",
            "TotalSeconds",
            "TotalMilliseconds",
            "String")]
        [ValidateNotNullOrEmpty()]
        [string]$TimeSpanType = "TotalMilliseconds",
        [ValidateSet("Int64", "Int32", "String")]
        [string]$SizeType = "Int64",
        [switch]$IgnoreNull,
        [switch]$Raw,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        Write-Message -Level Debug -Message "Bound parameters: $($PSBoundParameters.Keys -join ", ")"
        Write-Message -Level Debug -Message "TimeSpanType = $TimeSpanType | SizeType = $SizeType"
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Alias Out-DbaDataTable

        function Convert-Type {
            # This function will check so that the type is an accepted type which could be used when inserting into a table.
            # If a type is accepted (included in the $type array) then it will be passed on, otherwise it will first change type before passing it on.
            # Special types will have both their types converted as well as the value.
            # TimeSpan is a special type and will be converted into the $timespantype. (default: TotalMilliseconds) so that the timespan can be stored in a database further down the line.
            [CmdletBinding()]
            param (
                $type,
                $value,
                $timespantype = 'TotalMilliseconds',
                $sizetype = 'Int64'
            )

            $types = [System.Collections.ArrayList]@(
                'System.Int32',
                'System.UInt32',
                'System.Int16',
                'System.UInt16',
                'System.Int64',
                'System.UInt64',
                'System.Decimal',
                'System.Single',
                'System.Double',
                'System.Byte',
                'System.SByte',
                'System.Boolean',
                'System.DateTime',
                'System.Guid',
                'System.Char'
            )

            # The $special variable is used to mark the return value if a conversion was made on the value itself.
            # If this is set to true the original value will later be ignored when updating the DataTable.
            # And the value returned from this function will be used instead. (cannot modify existing properties)
            $special = $false
            $specialType = ""

            # Special types need to be converted in some way.
            # This attempt is to convert timespan into something that works in a table.
            # I couldn't decide on what to convert it to so the user can decide.
            # If the parameter is not used, TotalMilliseconds will be used as default.
            # Ticks are more accurate but I think milliseconds are more useful most of the time.
            if (($type -eq 'System.TimeSpan') -or ($type -eq 'Sqlcollaborative.Dbatools.Utility.DbaTimeSpan') -or ($type -eq 'Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty')) {
                $special = $true
                if ($timespantype -eq 'String') {
                    $value = $value.ToString()
                    $type = 'System.String'
                } else {
                    # Let's use Int64 for all other types than string.
                    # We could match the type more closely with the timespantype but that can be added in the future if needed.
                    $value = $value.$timespantype
                    $type = 'System.Int64'
                }
                $specialType = 'Timespan'
            } elseif ($type -eq 'Sqlcollaborative.Dbatools.Utility.Size') {
                $special = $true
                switch ($sizetype) {
                    'Int64' {
                        $value = $value.Byte
                        $type = 'System.Int64'
                    }
                    'Int32' {
                        $value = $value.Byte
                        $type = 'System.Int32'
                    }
                    'String' {
                        $value = $value.ToString()
                        $type = 'System.String'
                    }
                }
                $specialType = 'Size'
            } elseif (-not ($type -in $types)) {
                # All types which are not found in the array will be converted into strings.
                # In this way we don't ignore it completely and it will be clear in the end why it looks as it does.
                $type = 'System.String'
            }

            # return a hashtable instead of an object. I like hashtables :)
            return @{ type = $type; Value = $value; Special = $special; SpecialType = $specialType }
        }

        function Convert-SpecialType {
            <#
            .SYNOPSIS
                Converts a value for a known column.

            .DESCRIPTION
                Converts a value for a known column.

            .PARAMETER Value
                The value to convert

            .PARAMETER Type
                The special type for which to convert

            .PARAMETER SizeType
                The size type defined by the user

            .PARAMETER TimeSpanType
                The timespan type defined by the user
        #>
            [CmdletBinding()]
            param (
                $Value,
                [ValidateSet('Timespan', 'Size')]
                [string]$Type,
                [string]$SizeType,
                [string]$TimeSpanType
            )

            switch ($Type) {
                'Size' {
                    if ($SizeType -eq 'String') { return $Value.ToString() }
                    else { return $Value.Byte }
                }
                'Timespan' {
                    if ($TimeSpanType -eq 'String') {
                        $Value.ToString()
                    } else {
                        $Value.$TimeSpanType
                    }
                }
            }
        }

        function Add-Column {
            <#
            .SYNOPSIS
                Adds a column to the datatable in progress.

            .DESCRIPTION
                Adds a column to the datatable in progress.

            .PARAMETER Property
                The property for which to add a column.

            .PARAMETER DataTable
                Autofilled. The table for which to add a column.

            .PARAMETER TimeSpanType
                Autofilled. How should timespans be handled?

            .PARAMETER SizeType
                Autofilled. How should sizes be handled?

            .PARAMETER Raw
                Autofilled. Whether the column should be string, no matter the input.
        #>
            [CmdletBinding()]
            param (
                [System.Management.Automation.PSPropertyInfo]$Property,
                [System.Data.DataTable]$DataTable = $datatable,
                [string]$TimeSpanType = $TimeSpanType,
                [string]$SizeType = $SizeType,
                [bool]$Raw = $Raw
            )

            $type = $property.TypeNameOfValue
            try {
                if ($Property.MemberType -like 'ScriptProperty') {
                    $type = $Property.GetType().FullName
                }
            } catch { $type = 'System.String' }

            $converted = Convert-Type -type $type -value $property.Value -timespantype $TimeSpanType -sizetype $SizeType

            $column = New-Object System.Data.DataColumn
            $column.ColumnName = $property.Name.ToString()
            if (-not $Raw) {
                $column.DataType = [System.Type]::GetType($converted.type)
            }
            $null = $DataTable.Columns.Add($column)
            $converted
        }

        $datatable = New-Object System.Data.DataTable

        # Accelerate subsequent lookups of columns and special type columns
        $columns = @()
        $specialColumns = @()
        $specialColumnsType = @{ }

        $ShouldCreateColumns = $true
    }

    process {
        #region Handle null objects
        if ($null -eq $InputObject) {
            if (-not $IgnoreNull) {
                $datarow = $datatable.NewRow()
                $datatable.Rows.Add($datarow)
            }

            # Only ends the current process block
            return
        }
        #endregion Handle null objects


        foreach ($object in $InputObject) {
            #region Handle null objects
            if ($null -eq $object) {
                if (-not $IgnoreNull) {
                    $datarow = $datatable.NewRow()
                    $datatable.Rows.Add($datarow)
                }
                continue
            }
            #endregion Handle null objects

            #Handle rows already being System.Data.DataRow
            if ($object.GetType().FullName -eq 'System.Data.DataRow') {
                if ($ShouldCreateColumns) {
                    $datatable = $object.Table.Copy()
                    $ShouldCreateColumns = $false
                }
                continue
            }

            # The new row to insert
            $datarow = $datatable.NewRow()

            #region Process Properties
            $objectProperties = $object.PSObject.Properties
            foreach ($property in $objectProperties) {
                #region Create Columns as needed
                if ($ShouldCreateColumns) {
                    $newColumn = Add-Column -Property $property
                    $columns += $property.Name
                    if ($newColumn.Special) {
                        $specialColumns += $property.Name
                        $specialColumnsType[$property.Name] = $newColumn.SpecialType
                    }
                }
                #endregion Create Columns as needed

                # Handle null properties, as well as properties with access errors
                try {
                    $propValueLength = $property.value.length
                } catch {
                    $propValueLength = 0
                }

                #region Insert value into column of row
                if ($propValueLength -gt 0) {
                    # If the typename was a special typename we want to use the value returned from Convert-Type instead.
                    # We might get error if we try to change the value for $property.value if it is read-only. That's why we use $converted.value instead.
                    if ($property.Name -in $specialColumns) {
                        $datarow.Item($property.Name) = Convert-SpecialType -Value $property.value -Type $specialColumnsType[$property.Name] -SizeType $SizeType -TimeSpanType $TimeSpanType
                    } else {
                        if ($property.value.ToString().length -eq 15) {
                            if ($property.value.ToString() -eq 'System.Object[]') {
                                $value = $property.value -join ", "
                            } elseif ($property.value.ToString() -eq 'System.String[]') {
                                $value = $property.value -join ", "
                            } else {
                                $value = $property.value
                            }
                        } else {
                            $value = $property.value
                        }

                        try {
                            $datarow.Item($property.Name) = $value
                        } catch {
                            if ($property.Name -notin $columns) {
                                try {
                                    $newColumn = Add-Column -Property $property
                                    $columns += $property.Name
                                    if ($newColumn.Special) {
                                        $specialColumns += $property.Name
                                        $specialColumnsType[$property.Name] = $newColumn.SpecialType
                                    }

                                    $datarow.Item($property.Name) = $newColumn.Value
                                } catch {
                                    Write-Message -Level Warning -Message "Failed to add property $($property.Name) from $object" -ErrorRecord $_ -Target $object
                                }
                            } else {
                                Write-Message -Level Warning -Message "Failed to add property $($property.Name) from $object" -ErrorRecord $_ -Target $object
                            }
                        }
                    }
                }
                #endregion Insert value into column of row
            }

            $datatable.Rows.Add($datarow)
            # If this is the first non-null object then the columns has just been created.
            # Set variable to false to skip creating columns from now on.
            if ($ShouldCreateColumns) {
                $ShouldCreateColumns = $false
            }
            #endregion Process Properties
        }
    }
    end {
        Write-Message -Level InternalComment -Message "Finished."
        , $datatable
    }
}
tools\dbatools\functions\ConvertTo-DbaTimeline.ps1
function ConvertTo-DbaTimeline {
    <#
    .SYNOPSIS
        Converts InputObject to a html timeline using Google Chart

    .DESCRIPTION
        This function accepts input as pipeline from the following dbatools functions:
        Get-DbaAgentJobHistory
        Get-DbaBackupHistory
        (more to come...)
        And generates Bootstrap based, HTML file with Google Chart Timeline

    .PARAMETER InputObject

        Pipe input, must an output from the above functions.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Chart
        Author: Marcin Gminski (@marcingminski)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Dependency: ConvertTo-JsDate, Convert-DbaTimelineStatusColor

    .LINK
        https://dbatools.io/ConvertTo-DbaTimeline

    .EXAMPLE
        PS C:\> Get-DbaAgentJobHistory -SqlInstance sql-1 -StartDate '2018-08-13 00:00' -EndDate '2018-08-13 23:59' -ExcludeJobSteps | ConvertTo-DbaTimeline | Out-File C:\temp\DbaAgentJobHistory.html -Encoding ASCII

        Creates an output file containing a pretty timeline for all of the agent job history results for sql-1 the whole day of 2018-08-13

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sqlcm | Get-DbaBackupHistory -Since '2018-08-13 00:00' | ConvertTo-DbaTimeline | Out-File C:\temp\DbaBackupHistory.html -Encoding ASCII

        Creates an output file containing a pretty timeline for the agent job history since 2018-08-13 for all of the registered servers on sqlcm

    .EXAMPLE
        PS C:\> $messageParameters = @{
        >> Subject = "Backup history for sql2017 and sql2016"
        >> Body = Get-DbaBackupHistory -SqlInstance sql2017, sql2016 -Since '2018-08-13 00:00' | ConvertTo-DbaTimeline
        >> From = "[email protected]"
        >> To = "[email protected]"
        >> SmtpServer = "smtp.ad.local"
        >> }
        >>
        PS C:\> Send-MailMessage @messageParameters -BodyAsHtml

        Sends an email to [email protected] with the results of Get-DbaBackupHistory. Note that viewing these reports may not be supported in all email clients.

    #>
    [CmdletBinding()]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseOutputTypeCorrectly", "", Justification = "PSSA Rule Ignored by BOH")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [object[]]$InputObject,
        [switch]$EnableException
    )
    begin {
        $body = $servers = @()
        $begin = @"
<html>
<head>
<!-- Developed by Marcin Gminski, https://marcin.gminski.net, 2018 -->
<!-- Load jQuery required to autosize timeline -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<!-- Load Bootstrap -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Load Google Charts library -->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<!-- a bit of custom styling to work with bootstrap grid -->
<style>

    html,body{height:100%;background-color:#c2c2c2;}
    .viewport {height:100%}

    .chart{
        background-color:#fff;
        text-align:left;
        padding:0;
        border:1px solid #7D7D7D;
        -webkit-box-shadow:1px 1px 3px 0 rgba(0,0,0,.45);
        -moz-box-shadow:1px 1px 3px 0 rgba(0,0,0,.45);
        box-shadow:1px 1px 3px 0 rgba(0,0,0,.45)
    }
    .badge-custom{background-color:#939}
    .container {
        height:100%;
    }
    .fill{
        width:100%;
        height:100%;
        min-height:100%;
        padding:10px;
    }
    .timeline-tooltip{
        border:1px solid #E0E0E0;
        font-family:Arial,Helvetica;
        font-size:10pt;
        padding:12px
    }
    .timeline-tooltip div{padding:6px}
    .timeline-tooltip span{font-weight:700}
</style>
    <script type="text/javascript">
    google.charts.load('43', {'packages':['timeline']});
    google.charts.setOnLoadCallback(drawChart);
    function drawChart() {
        var container = document.getElementById('Chart');
        var chart = new google.visualization.Timeline(container);
        var dataTable = new google.visualization.DataTable();
        dataTable.addColumn({type: 'string', id: 'vLabel'});
        dataTable.addColumn({type: 'string', id: 'hLabel'});
        dataTable.addColumn({type: 'string', role: 'style' });
        dataTable.addColumn({type: 'date', id: 'date_start'});
        dataTable.addColumn({type: 'date', id: 'date_end'});

        dataTable.addRows([
"@
    }

    process {
        # create server list to support multiple servers
        if ($InputObject[0].SqlInstance -notin $servers) {
            $servers += $InputObject[0].SqlInstance
        }
        # This is where do column mapping.

        # Check for types - this will help support if someone assigns a variable then pipes
        # AgentJobHistory is a forced type while backuphistory is a legit type
        if ($InputObject[0].TypeName -eq 'AgentJobHistory') {
            $CallerName = "Get-DbaAgentJobHistory"
            $data = $InputObject | Select-Object @{ Name = "SqlInstance"; Expression = { $_.SqlInstance } }, @{ Name = "InstanceName"; Expression = { $_.InstanceName } }, @{ Name = "vLabel"; Expression = { $_.Job -replace "\'", ''} }, @{ Name = "hLabel"; Expression = { $_.Status } }, @{ Name = "Style"; Expression = { $(Convert-DbaTimelineStatusColor($_.Status)) } }, @{ Name = "StartDate"; Expression = { $(ConvertTo-JsDate($_.StartDate)) } }, @{ Name = "EndDate"; Expression = { $(ConvertTo-JsDate($_.EndDate)) } }

        } elseif ($InputObject[0] -is [Sqlcollaborative.Dbatools.Database.BackupHistory]) {
            $CallerName = "Get-DbaBackupHistory"
            $data = $InputObject | Select-Object @{ Name = "SqlInstance"; Expression = { $_.SqlInstance } }, @{ Name = "InstanceName"; Expression = { $_.InstanceName } }, @{ Name = "vLabel"; Expression = { $_.Database } }, @{ Name = "hLabel"; Expression = { $_.Type } }, @{ Name = "StartDate"; Expression = { $(ConvertTo-JsDate($_.Start)) } }, @{ Name = "EndDate"; Expression = { $(ConvertTo-JsDate($_.End)) } }
        } else {
            # sorry to be so formal, can't help it ;)
            Stop-Function -Message "Unsupported input data. To request support for additional commands, please file an issue at dbatools.io/issues and we'll take a look"
            return
        }
        $body += "$($data | ForEach-Object{ "['$($_.vLabel)','$($_.hLabel)','$($_.Style)',$($_.StartDate), $($_.EndDate)]," })"
    }
    end {
        if (Test-FunctionInterrupt) { return }
        $end = @"
]);
        var paddingHeight = 20;
        var rowHeight = dataTable.getNumberOfRows() * 41;
        var chartHeight = rowHeight + paddingHeight;
        dataTable.insertColumn(2, {type: 'string', role: 'tooltip', p: {html: true}});
        var dateFormat = new google.visualization.DateFormat({
          pattern: 'dd/MM/yy HH:mm:ss'
        });
        for (var i = 0; i < dataTable.getNumberOfRows(); i++) {
          var duration = (dataTable.getValue(i, 5).getTime() - dataTable.getValue(i, 4).getTime()) / 1000;
          var hours = parseInt( duration / 3600 ) % 24;
          var minutes = parseInt( duration / 60 ) % 60;
          var seconds = duration % 60;
          var tooltip = '<div class="timeline-tooltip"><span>' +
            dataTable.getValue(i, 1).split(",").join("<br />")  + '</span></div><div class="timeline-tooltip"><span>' +
            dataTable.getValue(i, 0) + '</span>: ' +
            dateFormat.formatValue(dataTable.getValue(i, 4)) + ' - ' +
            dateFormat.formatValue(dataTable.getValue(i, 5)) + '</div>' +
            '<div class="timeline-tooltip"><span>Duration: </span>' +
            hours + 'h ' + minutes + 'm ' + seconds + 's ';
          dataTable.setValue(i, 2, tooltip);
        }
        var options = {
            timeline: {
                rowLabelStyle: { },
                barLabelStyle: { },
            },
            hAxis: {
                format: 'dd/MM HH:mm',
            },
        }
        // Autosize chart. It would not be enough to just count rows and expand based on row height as there can be overlapping rows.
        // this will draw the chart, get the size of the underlying div and apply that size to the parent container and redraw:
        chart.draw(dataTable, options);
        // get the size of the chold div:
        var realheight= parseInt(`$("#Chart div:first-child div:first-child div:first-child div svg").attr( "height"))+70;
        // set the height:
        options.height=realheight
        // draw again:
        chart.draw(dataTable, options);
    }
</script>
</head>
<body>
    <div class="container-fluid">
    <div class="pull-left"><h3><code>$($CallerName)</code> timeline for server <code>$($servers -join ', ')</code></h3></div><div class="pull-right text-right"><img class="text-right" style="vertical-align:bottom; margin-top: 10px;" src="https://dbatools.io/wp-content/uploads/2016/05/dbatools-logo-1.png" width=150></div>
         <div class="clearfix"></div>
         <div class="col-12">
            <div class="chart" id="Chart"></div>
         </div>
         <hr>
    <p><a href="https://dbatools.io">dbatools.io</a> - the community's sql powershell module. Find us on Twitter: <a href="https://twitter.com/psdbatools">@psdbatools</a> | Chart by <a href="https://twitter.com/marcingminski">@marcingminski</a></p>
</div>
</body>
</html>
"@
        $begin, $body, $end
    }
}
tools\dbatools\functions\ConvertTo-DbaXESession.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function ConvertTo-DbaXESession {
    <#
    .SYNOPSIS
        Uses a slightly modified version of sp_SQLskills_ConvertTraceToExtendedEvents.sql to convert Traces to Extended Events.

    .DESCRIPTION
        Uses a slightly modified version of sp_SQLskills_ConvertTraceToExtendedEvents.sql to convert Traces to Extended Events.

        T-SQL code by: Jonathan M. Kehayias, SQLskills.com. T-SQL can be found in this module directory and at
        https://www.sqlskills.com/blogs/jonathan/converting-sql-trace-to-extended-events-in-sql-server-2012/

    .PARAMETER InputObject
        Specifies a Trace object output by Get-DbaTrace.

    .PARAMETER Name
        The name of the Trace to convert. If the name exists, characters will be appended to it.

    .PARAMETER OutputScriptOnly
        Outputs the T-SQL script to create the XE session and does not execute it.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Trace, ExtendedEvent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaTrace -SqlInstance sql2017, sql2012 | Where Id -eq 2 | ConvertTo-DbaXESession -Name 'Test'

        Converts Trace with ID 2 to a Session named Test on SQL Server instances named sql2017 and sql2012 and creates the Session on each respective server.

    .EXAMPLE
        PS C:\> Get-DbaTrace -SqlInstance sql2014 | Out-GridView -PassThru | ConvertTo-DbaXESession -Name 'Test' | Start-DbaXESession

        Converts selected traces on sql2014 to sessions, creates the session, and starts it.

    .EXAMPLE
        PS C:\> Get-DbaTrace -SqlInstance sql2014 | Where Id -eq 1 | ConvertTo-DbaXESession -Name 'Test' -OutputScriptOnly

        Converts trace ID 1 on sql2014 to an Extended Event and outputs the resulting T-SQL.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [object[]]$InputObject,
        [parameter(Mandatory)]
        [string]$Name,
        [switch]$OutputScriptOnly,
        [switch]$EnableException
    )
    begin {
        $rawsql = Get-Content "$script:PSModuleRoot\bin\sp_SQLskills_ConvertTraceToEEs.sql" -Raw
    }
    process {
        foreach ($trace in $InputObject) {
            if (-not $trace.id -and -not $trace.Parent) {
                Stop-Function -Message "Input is of the wrong type. Use Get-DbaTrace." -Continue
                return
            }

            $server = $trace.Parent

            if ($server.VersionMajor -lt 11) {
                Stop-Function -Message "SQL Server version 2012+ required - $server not supported."
                return
            }

            $tempdb = $server.Databases['tempdb']
            $traceid = $trace.id

            if ((Get-DbaXESession -SqlInstance $server -Session $PSBoundParameters.Name)) {
                $oldname = $name
                $Name = "$name-$traceid"
                Write-Message -Level Output -Message "XE Session $oldname already exists on $server, trying $name."
            }

            if ((Get-DbaXESession -SqlInstance $server -Session $Name)) {
                $oldname = $name
                $Name = "$name-$(Get-Random)"
                Write-Message -Level Output -Message "XE Session $oldname already exists on $server, trying $name."
            }

            $sql = $rawsql.Replace("--TRACEID--", $traceid)
            $sql = $sql.Replace("--SESSIONNAME--", $name)

            try {
                Write-Message -Level Verbose -Message "Executing SQL in tempdb."
                $results = $tempdb.ExecuteWithResults($sql).Tables.Rows.SqlString
            } catch {
                Stop-Function -Message "Issue creating, dropping or executing sp_SQLskills_ConvertTraceToExtendedEvents in tempdb on $server." -Target $server -ErrorRecord $_
            }

            $results = $results -join "`r`n"

            if ($OutputScriptOnly) {
                $results
            } else {
                Write-Message -Level Verbose -Message "Creating XE Session $name."
                try {
                    $tempdb.ExecuteNonQuery($results)
                } catch {
                    Stop-Function -Message "Issue creating extended event $name on $server." -Target $server -ErrorRecord $_
                }
                Get-DbaXESession -SqlInstance $server -Session $name
            }
        }
    }
}
tools\dbatools\functions\Copy-DbaAgentAlert.ps1
function Copy-DbaAgentAlert {
    <#
    .SYNOPSIS
        Copy-DbaAgentAlert migrates alerts from one SQL Server to another.

    .DESCRIPTION
        By default, all alerts are copied. The -Alert parameter is auto-populated for command-line completion and can be used to copy only specific alerts.

        If the alert already exists on the destination, it will be skipped unless -Force is used.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Alert
        The alert(s) to process. This list is auto-populated from the server. If unspecified, all alerts will be processed.

    .PARAMETER ExcludeAlert
        The alert(s) to exclude. This list is auto-populated from the server.

    .PARAMETER IncludeDefaults
        Copy SQL Agent defaults such as FailSafeEmailAddress, ForwardingServer, and PagerSubjectTemplate.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER Force
        If this switch is enabled, the Alert will be dropped and recreated on Destination.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration, Agent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        https://dbatools.io/Copy-DbaAgentAlert

    .EXAMPLE
        PS C:\> Copy-DbaAgentAlert -Source sqlserver2014a -Destination sqlcluster

        Copies all alerts from sqlserver2014a to sqlcluster using Windows credentials. If alerts with the same name exist on sqlcluster, they will be skipped.

    .EXAMPLE
        PS C:\> Copy-DbaAgentAlert -Source sqlserver2014a -Destination sqlcluster -Alert PSAlert -SourceSqlCredential $cred -Force

        Copies a only the alert named PSAlert from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If an alert with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used.

    .EXAMPLE
        PS C:\> Copy-DbaAgentAlert -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force

        Shows what would happen if the command were executed using force.

    #>
    [cmdletbinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]$SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]$DestinationSqlCredential,
        [object[]]$Alert,
        [object[]]$ExcludeAlert,
        [switch]$IncludeDefaults,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential
            $serverAlerts = $sourceServer.JobServer.Alerts
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }
            $destAlerts = $destServer.JobServer.Alerts

            if ($IncludeDefaults -eq $true) {
                if ($PSCmdlet.ShouldProcess($destinstance, "Creating Alert Defaults")) {
                    $copyAgentAlertStatus = [pscustomobject]@{
                        SourceServer      = $sourceServer.Name
                        DestinationServer = $destServer.Name
                        Name              = "Alert Defaults"
                        Type              = "Alert Defaults"
                        Status            = $null
                        Notes             = $null
                        DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                    }
                    try {
                        Write-Message -Message "Creating Alert Defaults" -Level Verbose
                        $sql = $sourceServer.JobServer.AlertSystem.Script() | Out-String
                        $sql = $sql -replace [Regex]::Escape("'$source'"), "'$destinstance'"

                        Write-Message -Message $sql -Level Debug
                        $null = $destServer.Query($sql)

                        $copyAgentAlertStatus.Status = "Successful"
                    } catch {
                        $copyAgentAlertStatus.Status = "Failed"
                        $copyAgentAlertStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        Stop-Function -Message "Issue creating alert defaults." -Category InvalidOperation -ErrorRecord $_ -Target $destServer -Continue
                    }
                    $copyAgentAlertStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                }
            }

            foreach ($serverAlert in $serverAlerts) {
                $alertName = $serverAlert.name
                $copyAgentAlertStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Name              = $alertName
                    Type              = "Agent Alert"
                    Notes             = $null
                    Status            = $null
                    DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                }
                if (($Alert -and $Alert -notcontains $alertName) -or ($ExcludeAlert -and $ExcludeAlert -contains $alertName)) {
                    continue
                }

                if ($destAlerts.name -contains $serverAlert.name) {
                    if ($force -eq $false) {
                        if ($PSCmdlet.ShouldProcess($destinstance, "Alert [$alertName] exists at destination. Use -Force to drop and migrate.")) {
                            $copyAgentAlertStatus.Status = "Skipped"
                            $copyAgentAlertStatus.Notes = "Already exists on destination"
                            $copyAgentAlertStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            Write-Message -Message "Alert [$alertName] exists at destination. Use -Force to drop and migrate." -Level Verbose
                        }
                        continue
                    }

                    if ($PSCmdlet.ShouldProcess($destinstance, "Dropping alert $alertName and recreating")) {
                        try {
                            Write-Message -Message "Dropping Alert $alertName on $destServer." -Level Verbose

                            $sql = "EXEC msdb.dbo.sp_delete_alert @name = N'$($alertname)';"
                            Write-Message -Message $sql -Level Debug
                            $null = $destServer.Query($sql)
                            $destAlerts.Refresh()
                        } catch {
                            $copyAgentAlertStatus.Status = "Failed"
                            $copyAgentAlertStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            Stop-Function -Message "Issue dropping/recreating alert" -Category InvalidOperation -ErrorRecord $_ -Target $destServer -Continue
                        }
                    }
                }

                if ($destAlerts | Where-Object { $_.Severity -eq $serverAlert.Severity -and $_.MessageID -eq $serverAlert.MessageID -and $_.DatabaseName -eq $serverAlert.DatabaseName -and $_.EventDescriptionKeyword -eq $serverAlert.EventDescriptionKeyword }) {
                    if ($PSCmdlet.ShouldProcess($destinstance, "Checking for conflicts")) {
                        $conflictMessage = "Alert [$alertName] has already been defined to use"
                        if ($serverAlert.Severity -gt 0) { $conflictMessage += " severity $($serverAlert.Severity)" }
                        if ($serverAlert.MessageID -gt 0) { $conflictMessage += " error number $($serverAlert.MessageID)" }
                        if ($serverAlert.DatabaseName) { $conflictMessage += " on database '$($serverAlert.DatabaseName)'" }
                        if ($serverAlert.EventDescriptionKeyword) { $conflictMessage += " with error text '$($serverAlert.Severity)'" }
                        $conflictMessage += ". Skipping."

                        Write-Message -Level Verbose -Message $conflictMessage
                        $copyAgentAlertStatus.Status = "Skipped"
                        $copyAgentAlertStatus.Notes = $conflictMessage
                        $copyAgentAlertStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    }
                    continue
                }
                if ($serverAlert.JobName -and $destServer.JobServer.Jobs.Name -NotContains $serverAlert.JobName) {
                    Write-Message -Level Verbose -Message "Alert [$alertName] has job [$($serverAlert.JobName)] configured as response. The job does not exist on destination $destServer. Skipping."
                    if ($PSCmdlet.ShouldProcess($destinstance, "Checking for conflicts")) {
                        $copyAgentAlertStatus.Status = "Skipped"
                        $copyAgentAlertStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    }
                    continue
                }

                if ($PSCmdlet.ShouldProcess($destinstance, "Creating Alert $alertName")) {
                    try {
                        Write-Message -Message "Copying Alert $alertName" -Level Verbose
                        $sql = $serverAlert.Script() | Out-String
                        $sql = $sql -replace "@job_id=N'........-....-....-....-............", "@job_id=N'00000000-0000-0000-0000-000000000000"

                        Write-Message -Message $sql -Level Debug
                        $null = $destServer.Query($sql)

                        $copyAgentAlertStatus.Status = "Successful"
                        $copyAgentAlertStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    } catch {
                        $copyAgentAlertStatus.Status = "Failed"
                        $copyAgentAlertStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        Stop-Function -Message "Issue creating alert" -Category InvalidOperation -ErrorRecord $_ -Target $destServer -Continue
                    }
                }

                $destServer.JobServer.Alerts.Refresh()
                $destServer.JobServer.Jobs.Refresh()

                $newAlert = $destServer.JobServer.Alerts[$alertName]
                $notifications = $serverAlert.EnumNotifications()
                $jobName = $serverAlert.JobName

                # JobId = 00000000-0000-0000-0000-000 means the Alert does not execute/is attached to a SQL Agent Job.
                if ($serverAlert.JobId -ne '00000000-0000-0000-0000-000000000000') {
                    $copyAgentAlertStatus = [pscustomobject]@{
                        SourceServer      = $sourceServer.Name
                        DestinationServer = $destServer.Name
                        Name              = $alertName
                        Type              = "Agent Alert Job Association"
                        Notes             = "Associated with $jobName"
                        Status            = $null
                        DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                    }
                    if ($PSCmdlet.ShouldProcess($destinstance, "Adding $alertName to $jobName")) {
                        try {
                            <# THERE needs to be validation within this block to see if the $jobName actually exists on the source server. #>
                            Write-Message -Message "Adding $alertName to $jobName" -Level Verbose
                            $newJob = $destServer.JobServer.Jobs[$jobName]
                            $newJobId = ($newJob.JobId) -replace " ", ""
                            $sql = $sql -replace '00000000-0000-0000-0000-000000000000', $newJobId
                            $sql = $sql -replace 'sp_add_alert', 'sp_update_alert'

                            Write-Message -Message $sql -Level Debug
                            $null = $destServer.Query($sql)

                            $copyAgentAlertStatus.Status = "Successful"
                            $copyAgentAlertStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        } catch {
                            $copyAgentAlertStatus.Status = "Failed"
                            $copyAgentAlertStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            Stop-Function -Message "Issue adding alert to job" -Category InvalidOperation -ErrorRecord $_ -Target $destServer
                        }
                    }
                }

                if ($PSCmdlet.ShouldProcess($destinstance, "Moving Notifications $alertName")) {
                    try {
                        $copyAgentAlertStatus = [pscustomobject]@{
                            SourceServer      = $sourceServer.Name
                            DestinationServer = $destServer.Name
                            Name              = $alertName
                            Type              = "Agent Alert Notification"
                            Notes             = $null
                            Status            = $null
                            DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                        }
                        # can't add them this way, we need to modify the existing one or give all options that are supported.
                        foreach ($notify in $notifications) {
                            $notifyCollection = @()
                            if ($notify.UseNetSend -eq $true) {
                                Write-Message -Message "Adding net send" -Level Verbose
                                $notifyCollection += "NetSend"
                            }

                            if ($notify.UseEmail -eq $true) {
                                Write-Message -Message "Adding email" -Level Verbose
                                $notifyCollection += "NotifyEmail"
                            }

                            if ($notify.UsePager -eq $true) {
                                Write-Message -Message "Adding pager" -Level Verbose
                                $notifyCollection += "Pager"
                            }

                            $notifyMethods = $notifyCollection -join ", "
                            $newAlert.AddNotification($notify.OperatorName, [Microsoft.SqlServer.Management.Smo.Agent.NotifyMethods]$notifyMethods)
                        }
                        $copyAgentAlertStatus.Status = "Successful"
                        $copyAgentAlertStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    } catch {
                        $copyAgentAlertStatus.Status = "Failed"
                        $copyAgentAlertStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        Stop-Function -Message "Issue moving notifications for the alert" -Category InvalidOperation -ErrorRecord $_ -Target $destServer
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlAlert
    }
}
tools\dbatools\functions\Copy-DbaAgentJob.ps1
function Copy-DbaAgentJob {
    <#
    .SYNOPSIS
        Copy-DbaAgentJob migrates jobs from one SQL Server to another.

    .DESCRIPTION
        By default, all jobs are copied. The -Job parameter is auto-populated for command-line completion and can be used to copy only specific jobs.

        If the job already exists on the destination, it will be skipped unless -Force is used.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Job
        The job(s) to process. This list is auto-populated from the server. If unspecified, all jobs will be processed.

    .PARAMETER ExcludeJob
        The job(s) to exclude. This list is auto-populated from the server.

    .PARAMETER DisableOnSource
        If this switch is enabled, the job will be disabled on the source server.

    .PARAMETER DisableOnDestination
        If this switch is enabled, the newly migrated job will be disabled on the destination server.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER Force
        If this switch is enabled, the Job will be dropped and recreated on Destination.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration, Agent, Job
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Copy-DbaAgentJob

    .EXAMPLE
        PS C:\> Copy-DbaAgentJob -Source sqlserver2014a -Destination sqlcluster

        Copies all jobs from sqlserver2014a to sqlcluster, using Windows credentials. If jobs with the same name exist on sqlcluster, they will be skipped.

    .EXAMPLE
        PS C:\> Copy-DbaAgentJob -Source sqlserver2014a -Destination sqlcluster -Job PSJob -SourceSqlCredential $cred -Force

        Copies a single job, the PSJob job from sqlserver2014a to sqlcluster, using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If a job with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used.

    .EXAMPLE
        PS C:\> Copy-DbaAgentJob -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force

        Shows what would happen if the command were executed using force.
        
    .EXAMPLE
        PS C:\> Get-DbaAgentJob -SqlInstance sqlserver2014a | Where-Object Category -eq "Report Server" | ForEach-Object {Copy-DbaAgentJob -Source $_.SqlInstance -Job $_.Name -Destination sqlserver2014b}
        
        Copies all SSRS jobs (subscriptions) from AlwaysOn Primary SQL instance sqlserver2014a to AlwaysOn Secondary SQL instance sqlserver2014b
    #>
    [cmdletbinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]$SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]$DestinationSqlCredential,
        [object[]]$Job,
        [object[]]$ExcludeJob,
        [switch]$DisableOnSource,
        [switch]$DisableOnDestination,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }

        $serverJobs = $sourceServer.JobServer.Jobs
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }
            $destJobs = $destServer.JobServer.Jobs

            foreach ($serverJob in $serverJobs) {
                $jobName = $serverJob.name
                $jobId = $serverJob.JobId

                $copyJobStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Name              = $jobName
                    Type              = "Agent Job"
                    Status            = $null
                    Notes             = $null
                    DateTime          = [DbaDateTime](Get-Date)
                }

                if ($Job -and $jobName -notin $Job -or $jobName -in $ExcludeJob) {
                    Write-Message -Level Verbose -Message "Job [$jobName] filtered. Skipping."
                    continue
                }
                Write-Message -Message "Working on job: $jobName" -Level Verbose
                $sql = "
                SELECT sp.[name] AS MaintenancePlanName
                FROM msdb.dbo.sysmaintplan_plans AS sp
                INNER JOIN msdb.dbo.sysmaintplan_subplans AS sps
                    ON sps.plan_id = sp.id
                WHERE job_id = '$($jobId)'"
                Write-Message -Message $sql -Level Debug

                $MaintenancePlanName = $sourceServer.Query($sql).MaintenancePlanName

                if ($MaintenancePlanName) {
                    if ($Pscmdlet.ShouldProcess($destinstance, "Job [$jobName] is associated with Maintenance Plan: $MaintenancePlanNam")) {
                        $copyJobStatus.Status = "Skipped"
                        $copyJobStatus.Notes = "Job is associated with maintenance plan"
                        $copyJobStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        Write-Message -Level Verbose -Message "Job [$jobName] is associated with Maintenance Plan: $MaintenancePlanName"
                    }
                    continue
                }

                $dbNames = ($serverJob.JobSteps | where-object {$_.SubSystem -ne 'ActiveScripting'}).DatabaseName | Where-Object { $_.Length -gt 0 }
                $missingDb = $dbNames | Where-Object { $destServer.Databases.Name -notcontains $_ }

                if ($missingDb.Count -gt 0 -and $dbNames.Count -gt 0) {
                    if ($Pscmdlet.ShouldProcess($destinstance, "Database(s) $missingDb doesn't exist on destination. Skipping job [$jobName].")) {
                        $missingDb = ($missingDb | Sort-Object | Get-Unique) -join ", "
                        $copyJobStatus.Status = "Skipped"
                        $copyJobStatus.Notes = "Job is dependent on database: $missingDb"
                        $copyJobStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        Write-Message -Level Verbose -Message "Database(s) $missingDb doesn't exist on destination. Skipping job [$jobName]."
                    }
                    continue
                }

                $missingLogin = $serverJob.OwnerLoginName | Where-Object { $destServer.Logins.Name -notcontains $_ }

                if ($missingLogin.Count -gt 0) {
                    if ($force -eq $false) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Login(s) $missingLogin doesn't exist on destination. Use -Force to set owner to [sa]. Skipping job [$jobName].")) {
                            $missingLogin = ($missingLogin | Sort-Object | Get-Unique) -join ", "
                            $copyJobStatus.Status = "Skipped"
                            $copyJobStatus.Notes = "Job is dependent on login $missingLogin"
                            $copyJobStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            Write-Message -Level Verbose -Message "Login(s) $missingLogin doesn't exist on destination. Use -Force to set owner to [sa]. Skipping job [$jobName]."
                        }
                        continue
                    }
                }

                $proxyNames = ($serverJob.JobSteps | Where-Object ProxyName).ProxyName
                $missingProxy = $proxyNames | Where-Object { $destServer.JobServer.ProxyAccounts.Name -notcontains $_ }

                if ($missingProxy -and $proxyNames) {
                    if ($Pscmdlet.ShouldProcess($destinstance, "Proxy Account(s) $missingProxy doesn't exist on destination. Skipping job [$jobName].")) {
                        $missingProxy = ($missingProxy | Sort-Object | Get-Unique) -join ", "
                        $copyJobStatus.Status = "Skipped"
                        $copyJobStatus.Notes = "Job is dependent on proxy $missingProxy"
                        $copyJobStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        Write-Message -Level Verbose -Message "Proxy Account(s) $missingProxy doesn't exist on destination. Skipping job [$jobName]."
                    }
                    continue
                }

                $operators = $serverJob.OperatorToEmail, $serverJob.OperatorToNetSend, $serverJob.OperatorToPage | Where-Object { $_.Length -gt 0 }
                $missingOperators = $operators | Where-Object { $destServer.JobServer.Operators.Name -notcontains $_ }

                if ($missingOperators.Count -gt 0 -and $operators.Count -gt 0) {
                    if ($Pscmdlet.ShouldProcess($destinstance, "Operator(s) $($missingOperator) doesn't exist on destination. Skipping job [$jobName]")) {
                        $missingOperator = ($operators | Sort-Object | Get-Unique) -join ", "
                        $copyJobStatus.Status = "Skipped"
                        $copyJobStatus.Notes = "Job is dependent on operator $missingOperator"
                        $copyJobStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        Write-Message -Level Verbose -Message "Operator(s) $($missingOperator) doesn't exist on destination. Skipping job [$jobName]"
                    }
                    continue
                }

                if ($destJobs.name -contains $serverJob.name) {
                    if ($force -eq $false) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Job $jobName exists at destination. Use -Force to drop and migrate.")) {
                            $copyJobStatus.Status = "Skipped"
                            $copyJobStatus.Notes = "Already exists on destination"
                            $copyJobStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            Write-Message -Level Verbose -Message "Job $jobName exists at destination. Use -Force to drop and migrate."
                        }
                        continue
                    } else {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Dropping job $jobName and recreating")) {
                            try {
                                Write-Message -Message "Dropping Job $jobName" -Level Verbose
                                $destServer.JobServer.Jobs[$jobName].Drop()
                            } catch {
                                $copyJobStatus.Status = "Failed"
                                $copyJobStatus.Notes = (Get-ErrorMessage -Record $_).Message
                                $copyJobStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                Stop-Function -Message "Issue dropping job" -Target $jobName -ErrorRecord $_ -Continue
                            }
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destinstance, "Creating Job $jobName")) {
                    try {
                        Write-Message -Message "Copying Job $jobName" -Level Verbose
                        $sql = $serverJob.Script() | Out-String

                        if ($missingLogin.Count -gt 0 -and $force) {
                            $saLogin = Get-SqlSaLogin -SqlInstance $destServer
                            $sql = $sql -replace [Regex]::Escape("@owner_login_name=N'$missingLogin'"), [Regex]::Escape("@owner_login_name=N'$saLogin'")
                        }

                        Write-Message -Message $sql -Level Debug
                        $destServer.Query($sql)

                        $destServer.JobServer.Jobs.Refresh()
                        $destServer.JobServer.Jobs[$serverJob.name].IsEnabled = $sourceServer.JobServer.Jobs[$serverJob.name].IsEnabled
                        $destServer.JobServer.Jobs[$serverJob.name].Alter()
                    } catch {
                        $copyJobStatus.Status = "Failed"
                        $copyJobStatus.Notes = (Get-ErrorMessage -Record $_)
                        $copyJobStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        Stop-Function -Message "Issue copying job" -Target $jobName -ErrorRecord $_ -Continue
                    }
                }

                if ($DisableOnDestination) {
                    if ($Pscmdlet.ShouldProcess($destinstance, "Disabling $jobName")) {
                        Write-Message -Message "Disabling $jobName on $destinstance" -Level Verbose
                        $destServer.JobServer.Jobs[$serverJob.name].IsEnabled = $False
                        $destServer.JobServer.Jobs[$serverJob.name].Alter()
                    }
                }

                if ($DisableOnSource) {
                    if ($Pscmdlet.ShouldProcess($source, "Disabling $jobName")) {
                        Write-Message -Message "Disabling $jobName on $source" -Level Verbose
                        $serverJob.IsEnabled = $false
                        $serverJob.Alter()
                    }
                }
                if ($Pscmdlet.ShouldProcess($destinstance, "Reporting status of migration for $jobname")) {
                    $copyJobStatus.Status = "Successful"
                    $copyJobStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlJob
    }
}
tools\dbatools\functions\Copy-DbaAgentJobCategory.ps1
#ValidationTags#Messaging#
function Copy-DbaAgentJobCategory {
    <#
    .SYNOPSIS
        Copy-DbaAgentJobCategory migrates SQL Agent categories from one SQL Server to another. This is similar to sp_add_category.

        https://msdn.microsoft.com/en-us/library/ms181597.aspx

    .DESCRIPTION
        By default, all SQL Agent categories for Jobs, Operators and Alerts are copied.

        The -OperatorCategories parameter is auto-populated for command-line completion and can be used to copy only specific operator categories.
        The -AgentCategories parameter is auto-populated for command-line completion and can be used to copy only specific agent categories.
        The -JobCategories parameter is auto-populated for command-line completion and can be used to copy only specific job categories.

        If the category already exists on the destination, it will be skipped unless -Force is used.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER CategoryType
        Specifies the Category Type to migrate. Valid options are "Job", "Alert" and "Operator". When CategoryType is specified, all categories from the selected type will be migrated. For granular migrations, use the three parameters below.

    .PARAMETER OperatorCategory
        This parameter is auto-populated for command-line completion and can be used to copy only specific operator categories.

    .PARAMETER AgentCategory
        This parameter is auto-populated for command-line completion and can be used to copy only specific agent categories.

    .PARAMETER JobCategory
        This parameter is auto-populated for command-line completion and can be used to copy only specific job categories.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER Force
        If this switch is enabled, the Category will be dropped and recreated on Destination.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration, Agent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        https://dbatools.io/Copy-DbaAgentJobCategory

    .EXAMPLE
        PS C:\> Copy-DbaAgentJobCategory -Source sqlserver2014a -Destination sqlcluster

        Copies all operator categories from sqlserver2014a to sqlcluster using Windows authentication. If operator categories with the same name exist on sqlcluster, they will be skipped.

    .EXAMPLE
        PS C:\> Copy-DbaAgentJobCategory -Source sqlserver2014a -Destination sqlcluster -OperatorCategory PSOperator -SourceSqlCredential $cred -Force

        Copies a single operator category, the PSOperator operator category from sqlserver2014a to sqlcluster using SQL credentials to authenticate to sqlserver2014a and Windows credentials for sqlcluster. If an operator category with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used.

    .EXAMPLE
        PS C:\> Copy-DbaAgentJobCategory -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force

        Shows what would happen if the command were executed using force.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]$SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]$DestinationSqlCredential,
        [Parameter(ParameterSetName = 'SpecificAlerts')]
        [ValidateSet('Job', 'Alert', 'Operator')]
        [string[]]$CategoryType,
        [string[]]$JobCategory,
        [string[]]$AgentCategory,
        [string[]]$OperatorCategory,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Copy-DbaAgentCategory
        function Copy-JobCategory {
            <#
                .SYNOPSIS
                    Copy-JobCategory migrates job categories from one SQL Server to another.

                .DESCRIPTION
                    By default, all job categories are copied. The -JobCategories parameter is auto-populated for command-line completion and can be used to copy only specific job categories.

                    If the associated credential for the category does not exist on the destination, it will be skipped. If the job category already exists on the destination, it will be skipped unless -Force is used.
            #>
            param (
                [string[]]$jobCategories
            )

            process {

                $serverJobCategories = $sourceServer.JobServer.JobCategories | Where-Object ID -ge 100
                $destJobCategories = $destServer.JobServer.JobCategories | Where-Object ID -ge 100

                foreach ($jobCategory in $serverJobCategories) {
                    $categoryName = $jobCategory.Name

                    $copyJobCategoryStatus = [pscustomobject]@{
                        SourceServer      = $sourceServer.Name
                        DestinationServer = $destServer.Name
                        Name              = $categoryName
                        Type              = "Agent Job Category"
                        Status            = $null
                        Notes             = $null
                        DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                    }

                    if ($jobCategories.Count -gt 0 -and $jobCategories -notcontains $categoryName) {
                        continue
                    }

                    if ($destJobCategories.Name -contains $jobCategory.name) {
                        if ($force -eq $false) {
                            $copyJobCategoryStatus.Status = "Skipped"
                            $copyJobCategoryStatus.Notes = "Already exists on destination"
                            $copyJobCategoryStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            Write-Message -Level Verbose -Message "Job category $categoryName exists at destination. Use -Force to drop and migrate."
                            continue
                        } else {
                            if ($Pscmdlet.ShouldProcess($destinstance, "Dropping job category $categoryName")) {
                                try {
                                    Write-Message -Level Verbose -Message "Dropping Job category $categoryName"
                                    $destServer.JobServer.JobCategories[$categoryName].Drop()
                                } catch {
                                    $copyJobCategoryStatus.Status = "Failed"
                                    $copyJobCategoryStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                    Stop-Function -Message "Issue dropping job category" -Target $categoryName -ErrorRecord $_ -Continue
                                }
                            }
                        }
                    }

                    if ($Pscmdlet.ShouldProcess($destinstance, "Creating Job category $categoryName")) {
                        try {
                            Write-Message -Level Verbose -Message "Copying Job category $categoryName"
                            $sql = $jobCategory.Script() | Out-String
                            Write-Message -Level Debug -Message "SQL Statement: $sql"
                            $destServer.Query($sql)

                            $copyJobCategoryStatus.Status = "Successful"
                            $copyJobCategoryStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        } catch {
                            $copyJobCategoryStatus.Status = "Failed"
                            $copyJobCategoryStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            Stop-Function -Message "Issue copying job category" -Target $categoryName -ErrorRecord $_
                        }
                    }
                }
            }
        }

        function Copy-OperatorCategory {
            <#
                .SYNOPSIS
                    Copy-OperatorCategory migrates operator categories from one SQL Server to another.

                .DESCRIPTION
                    By default, all operator categories are copied. The -OperatorCategories parameter is auto-populated for command-line completion and can be used to copy only specific operator categories.

                    If the associated credential for the category does not exist on the destination, it will be skipped. If the operator category already exists on the destination, it will be skipped unless -Force is used.
            #>
            [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
            param (
                [string[]]$operatorCategories
            )
            process {
                $serverOperatorCategories = $sourceServer.JobServer.OperatorCategories | Where-Object ID -ge 100
                $destOperatorCategories = $destServer.JobServer.OperatorCategories | Where-Object ID -ge 100

                foreach ($operatorCategory in $serverOperatorCategories) {
                    $categoryName = $operatorCategory.Name

                    $copyOperatorCategoryStatus = [pscustomobject]@{
                        SourceServer      = $sourceServer.Name
                        DestinationServer = $destServer.Name
                        Type              = "Agent Operator Category"
                        Name              = $categoryName
                        Status            = $null
                        Notes             = $null
                        DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                    }

                    if ($operatorCategories.Count -gt 0 -and $operatorCategories -notcontains $categoryName) {
                        continue
                    }

                    if ($destOperatorCategories.Name -contains $operatorCategory.Name) {
                        if ($force -eq $false) {
                            $copyOperatorCategoryStatus.Status = "Skipped"
                            $copyOperatorCategoryStatus.Notes = "Already exists on destination"
                            $copyOperatorCategoryStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            Write-Message -Level Verbose -Message "Operator category $categoryName exists at destination. Use -Force to drop and migrate."
                            continue
                        } else {
                            if ($Pscmdlet.ShouldProcess($destinstance, "Dropping operator category $categoryName and recreating")) {
                                try {
                                    Write-Message -Level Verbose -Message "Dropping Operator category $categoryName"
                                    $destServer.JobServer.OperatorCategories[$categoryName].Drop()
                                    Write-Message -Level Verbose -Message "Copying Operator category $categoryName"
                                    $sql = $operatorCategory.Script() | Out-String
                                    Write-Message -Level Debug -Message $sql
                                    $destServer.Query($sql)
                                } catch {
                                    $copyOperatorCategoryStatus.Status = "Failed"
                                    $copyOperatorCategoryStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                    Stop-Function -Message "Issue dropping operator category" -Target $categoryName -ErrorRecord $_
                                }
                            }
                        }
                    } else {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Creating Operator category $categoryName")) {
                            try {
                                Write-Message -Level Verbose -Message "Copying Operator category $categoryName"
                                $sql = $operatorCategory.Script() | Out-String
                                Write-Message -Level Debug -Message $sql
                                $destServer.Query($sql)

                                $copyOperatorCategoryStatus.Status = "Successful"
                                $copyOperatorCategoryStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            } catch {
                                $copyOperatorCategoryStatus.Status = "Failed"
                                $copyOperatorCategoryStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                Stop-Function -Message "Issue copying operator category" -Target $categoryName -ErrorRecord $_
                            }
                        }
                    }
                }
            }
        }

        function Copy-AlertCategory {
            <#
                .SYNOPSIS
                    Copy-AlertCategory migrates alert categories from one SQL Server to another.

                .DESCRIPTION
                    By default, all alert categories are copied. The -AlertCategories parameter is auto-populated for command-line completion and can be used to copy only specific alert categories.

                    If the associated credential for the category does not exist on the destination, it will be skipped. If the alert category already exists on the destination, it will be skipped unless -Force is used.
            #>
            [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
            param (
                [string[]]$AlertCategories
            )

            process {
                if ($sourceServer.VersionMajor -lt 9 -or $destServer.VersionMajor -lt 9) {
                    throw "Server AlertCategories are only supported in SQL Server 2005 and above. Quitting."
                }

                $serverAlertCategories = $sourceServer.JobServer.AlertCategories | Where-Object ID -ge 100
                $destAlertCategories = $destServer.JobServer.AlertCategories | Where-Object ID -ge 100

                foreach ($alertCategory in $serverAlertCategories) {
                    $categoryName = $alertCategory.Name

                    $copyAlertCategoryStatus = [pscustomobject]@{
                        SourceServer      = $sourceServer.Name
                        DestinationServer = $destServer.Name
                        Type              = "Agent Alert Category"
                        Name              = $categoryName
                        Status            = $null
                        Notes             = $null
                        DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                    }

                    if ($alertCategories.Length -gt 0 -and $alertCategories -notcontains $categoryName) {
                        continue
                    }

                    if ($destAlertCategories.Name -contains $alertCategory.name) {
                        if ($force -eq $false) {
                            $copyAlertCategoryStatus.Status = "Skipped"
                            $copyAlertCategoryStatus.Notes = "Already exists on destination"
                            $copyAlertCategoryStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            Write-Message -Level Verbose -Message "Alert category $categoryName exists at destination. Use -Force to drop and migrate."
                            continue
                        } else {
                            if ($Pscmdlet.ShouldProcess($destinstance, "Dropping alert category $categoryName and recreating")) {
                                try {
                                    Write-Message -Level Verbose -Message "Dropping Alert category $categoryName"
                                    $destServer.JobServer.AlertCategories[$categoryName].Drop()
                                    Write-Message -Level Verbose -Message "Copying Alert category $categoryName"
                                    $sql = $alertcategory.Script() | Out-String
                                    Write-Message -Level Debug -Message "SQL Statement: $sql"
                                    $destServer.Query($sql)
                                } catch {
                                    $copyAlertCategoryStatus.Status = "Failed"
                                    $copyAlertCategoryStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                    Stop-Function -Message "Issue dropping alert category" -Target $categoryName -ErrorRecord $_
                                }
                            }
                        }
                    } else {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Creating Alert category $categoryName")) {
                            try {
                                Write-Message -Level Verbose -Message "Copying Alert category $categoryName"
                                $sql = $alertCategory.Script() | Out-String
                                Write-Message -Level Debug -Message $sql
                                $destServer.Query($sql)

                                $copyAlertCategoryStatus.Status = "Successful"
                                $copyAlertCategoryStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            } catch {
                                $copyAlertCategoryStatus.Status = "Failed"
                                $copyAlertCategoryStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                Stop-Function -Message "Issue creating alert category" -Target $categoryName -ErrorRecord $_
                            }
                        }
                    }
                }
            }
        }

        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }

            if ($CategoryType.count -gt 0) {

                switch ($CategoryType) {
                    "Job" {
                        Copy-JobCategory
                    }

                    "Alert" {
                        Copy-AlertCategory
                    }

                    "Operator" {
                        Copy-OperatorCategory
                    }
                }
                continue
            }

            if (($OperatorCategory.Count + $AlertCategory.Count + $jobCategory.Count) -gt 0) {

                if ($OperatorCategory.Count -gt 0) {
                    Copy-OperatorCategory -OperatorCategories $OperatorCategory
                }

                if ($AlertCategory.Count -gt 0) {
                    Copy-AlertCategory -AlertCategories $AlertCategory
                }

                if ($jobCategory.Count -gt 0) {
                    Copy-JobCategory -JobCategories $jobCategory
                }
                continue
            }
            Copy-OperatorCategory
            Copy-AlertCategory
            Copy-JobCategory
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlAgentCategory
    }
}
tools\dbatools\functions\Copy-DbaAgentOperator.ps1
function Copy-DbaAgentOperator {
    <#
    .SYNOPSIS
        Copy-DbaAgentOperator migrates operators from one SQL Server to another.

    .DESCRIPTION
        By default, all operators are copied. The -Operators parameter is auto-populated for command-line completion and can be used to copy only specific operators.

        If the associated credentials for the operator do not exist on the destination, it will be skipped. If the operator already exists on the destination, it will be skipped unless -Force is used.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Operator
        The operator(s) to process. This list is auto-populated from the server. If unspecified, all operators will be processed.

    .PARAMETER ExcludeOperator
        The operators(s) to exclude. This list is auto-populated from the server.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER Force
        If this switch is enabled, the Operator will be dropped and recreated on Destination.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration, Agent, Operator
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        https://dbatools.io/Copy-DbaAgentOperator

    .EXAMPLE
        PS C:\> Copy-DbaAgentOperator -Source sqlserver2014a -Destination sqlcluster

        Copies all operators from sqlserver2014a to sqlcluster using Windows credentials. If operators with the same name exist on sqlcluster, they will be skipped.

    .EXAMPLE
        PS C:\> Copy-DbaAgentOperator -Source sqlserver2014a -Destination sqlcluster -Operator PSOperator -SourceSqlCredential $cred -Force

        Copies only the PSOperator operator from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If an operator with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used.

    .EXAMPLE
        PS C:\> Copy-DbaAgentOperator -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force

        Shows what would happen if the command were executed using force.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]
        $SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]
        $DestinationSqlCredential,
        [object[]]$Operator,
        [object[]]$ExcludeOperator,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }
        $serverOperator = $sourceServer.JobServer.Operators
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }

            $destOperator = $destServer.JobServer.Operators
            $failsafe = $destServer.JobServer.AlertSystem | Select-Object FailSafeOperator
            foreach ($sOperator in $serverOperator) {
                $operatorName = $sOperator.Name

                $copyOperatorStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Name              = $operatorName
                    Type              = "Agent Operator"
                    Status            = $null
                    Notes             = $null
                    DateTime          = [DbaDateTime](Get-Date)
                }

                if ($Operator -and $Operator -notcontains $operatorName -or $ExcludeOperator -in $operatorName) {
                    continue
                }

                if ($destOperator.Name -contains $sOperator.Name) {
                    if ($force -eq $false) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Operator $operatorName exists at destination. Use -Force to drop and migrate.")) {
                            $copyOperatorStatus.Status = "Skipped"
                            $copyOperatorStatus.Notes = "Already exists on destination"
                            $copyOperatorStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            Write-Message -Level Verbose -Message "Operator $operatorName exists at destination. Use -Force to drop and migrate."
                        }
                        continue
                    } else {
                        if ($failsafe.FailSafeOperator -eq $operatorName) {
                            Write-Message -Level Verbose -Message "$operatorName is the failsafe operator. Skipping drop."
                            continue
                        }

                        if ($Pscmdlet.ShouldProcess($destinstance, "Dropping operator $operatorName and recreating")) {
                            try {
                                Write-Message -Level Verbose -Message "Dropping Operator $operatorName"
                                $destServer.JobServer.Operators[$operatorName].Drop()
                            } catch {
                                $copyOperatorStatus.Status = "Failed"
                                $copyOperatorStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                                Stop-Function -Message "Issue dropping operator" -Category InvalidOperation -ErrorRecord $_ -Target $destServer -Continue
                            }
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destinstance, "Creating Operator $operatorName")) {
                    try {
                        Write-Message -Level Verbose -Message "Copying Operator $operatorName"
                        $sql = $sOperator.Script() | Out-String
                        Write-Message -Level Debug -Message $sql
                        $destServer.Query($sql)

                        $copyOperatorStatus.Status = "Successful"
                        $copyOperatorStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    } catch {
                        $copyOperatorStatus.Status = "Failed"
                        $copyOperatorStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        Stop-Function -Message "Issue creating operator." -Category InvalidOperation -ErrorRecord $_ -Target $destServer
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlOperator
    }
}
tools\dbatools\functions\Copy-DbaAgentProxy.ps1
function Copy-DbaAgentProxy {
    <#
    .SYNOPSIS
        Copy-DbaAgentProxy migrates proxy accounts from one SQL Server to another.

    .DESCRIPTION
        By default, all proxy accounts are copied. The -ProxyAccounts parameter is auto-populated for command-line completion and can be used to copy only specific proxy accounts.

        If the associated credential for the account does not exist on the destination, it will be skipped. If the proxy account already exists on the destination, it will be skipped unless -Force is used.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER ProxyAccount
        Only migrate specific proxy accounts

    .PARAMETER ExcludeProxyAccount
        Migrate all proxy accounts except the ones explicitly excluded

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER Force
        If this switch is enabled, the Operator will be dropped and recreated on Destination.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration, Agent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        https://dbatools.io/Copy-DbaAgentProxy

    .EXAMPLE
        PS C:\> Copy-DbaAgentProxy -Source sqlserver2014a -Destination sqlcluster

        Copies all proxy accounts from sqlserver2014a to sqlcluster using Windows credentials. If proxy accounts with the same name exist on sqlcluster, they will be skipped.

    .EXAMPLE
        PS C:\> Copy-DbaAgentProxy -Source sqlserver2014a -Destination sqlcluster -ProxyAccount PSProxy -SourceSqlCredential $cred -Force

        Copies only the PSProxy proxy account from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If a proxy account with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used.

    .EXAMPLE
        PS C:\> Copy-DbaAgentProxy -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force

        Shows what would happen if the command were executed using force.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]$SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]$DestinationSqlCredential,
        [string[]]$ProxyAccount,
        [string[]]$ExcludeProxyAccount,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Copy-DbaAgentProxyAccount
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential -MinimumVersion 9
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }
        $serverProxyAccounts = $sourceServer.JobServer.ProxyAccounts
        if ($ProxyAccount) {
            $serverProxyAccounts | Where-Object Name -in $ProxyAccount
        }
        if ($ExcludeProxyAccount) {
            $serverProxyAccounts | Where-Object Name -notin $ProxyAccount
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }

            $destProxyAccounts = $destServer.JobServer.ProxyAccounts

            foreach ($account in $serverProxyAccounts) {
                $proxyName = $account.Name

                $copyAgentProxyAccountStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Name              = $null
                    Type              = "Agent Proxy"
                    Status            = $null
                    Notes             = $null
                    DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                }

                $credentialName = $account.CredentialName
                $copyAgentProxyAccountStatus.Name = $proxyName
                $copyAgentProxyAccountStatus.Type = "Credential"

                # Proxy accounts rely on Credential accounts
                if (-not $CredentialName) {
                    $copyAgentProxyAccountStatus.Status = "Skipped"
                    $copyAgentProxyAccountStatus.Notes = "Skipping migration of $proxyName due to misconfigured (empty) credential name"
                    $copyAgentProxyAccountStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    Write-Message -Level Verbose -Message "Skipping migration of $proxyName due to misconfigured (empty) credential name"
                    continue
                }

                try {
                    $credentialtest = $destServer.Credentials[$CredentialName]
                } catch {
                    #here to avoid an empty catch
                    $null = 1
                }

                if ($null -eq $credentialtest) {
                    $copyAgentProxyAccountStatus.Status = "Skipped"
                    $copyAgentProxyAccountStatus.Notes = "Associated credential account, $CredentialName, does not exist on $destinstance"
                    $copyAgentProxyAccountStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    Write-Message -Level Verbose -Message "Associated credential account, $CredentialName, does not exist on $destinstance"
                    continue
                }

                if ($destProxyAccounts.Name -contains $proxyName) {
                    $copyAgentProxyAccountStatus.Name = $proxyName
                    $copyAgentProxyAccountStatus.Type = "ProxyAccount"

                    if ($force -eq $false) {
                        $copyAgentProxyAccountStatus.Status = "Skipped"
                        $copyAgentProxyAccountStatus.Notes = "Already exists on destination"
                        $copyAgentProxyAccountStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        Stop-Function -Message "Server proxy account $proxyName exists at destination. Use -Force to drop and migrate." -Continue
                    } else {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Dropping server proxy account $proxyName and recreating")) {
                            try {
                                Write-Message -Level Verbose -Message "Dropping server proxy account $proxyName"
                                $destServer.JobServer.ProxyAccounts[$proxyName].Drop()
                            } catch {
                                $copyAgentProxyAccountStatus.Status = "Failed"
                                $copyAgentProxyAccountStatus.Notes = "Could not drop"
                                $copyAgentProxyAccountStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                Stop-Function -Message "Issue dropping proxy account" -Target $proxyName -ErrorRecord $_ -Continue
                            }
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destinstance, "Creating server proxy account $proxyName")) {
                    $copyAgentProxyAccountStatus.Name = $proxyName
                    $copyAgentProxyAccountStatus.Type = "ProxyAccount"

                    try {
                        Write-Message -Level Verbose -Message "Copying server proxy account $proxyName"
                        $sql = $account.Script() | Out-String
                        Write-Message -Level Debug -Message $sql
                        $destServer.Query($sql)

                        # Will fixing this misspelled status cause problems downstream?
                        $copyAgentProxyAccountStatus.Status = "Successful"
                        $copyAgentProxyAccountStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    } catch {
                        $exceptionstring = $_.Exception.InnerException.ToString()
                        if ($exceptionstring -match 'subsystem') {
                            $copyAgentProxyAccountStatus.Status = "Skipping"
                            $copyAgentProxyAccountStatus.Notes = "Failure"
                            $copyAgentProxyAccountStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                            Write-Message -Level Verbose -Message "One or more subsystems do not exist on the destination server. Skipping that part."
                        } else {
                            $copyAgentProxyAccountStatus.Status = "Failed"
                            $copyAgentProxyAccountStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                            Stop-Function -Message "Issue creating proxy account" -Target $proxyName -ErrorRecord $_
                        }
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlProxyAccount
    }
}
tools\dbatools\functions\Copy-DbaAgentSchedule.ps1
function Copy-DbaAgentSchedule {
    <#
    .SYNOPSIS
        Copy-DbaAgentSchedule migrates shared job schedules from one SQL Server to another.

    .DESCRIPTION
        All shared job schedules are copied.

        If the associated credential for the account does not exist on the destination, it will be skipped. If the shared job schedule already exists on the destination, it will be skipped unless -Force is used.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER Force
        If this switch is enabled, the Operator will be dropped and recreated on Destination.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration, Agent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        https://dbatools.io/Copy-DbaAgentSchedule

    .EXAMPLE
        PS C:\> Copy-DbaAgentSchedule -Source sqlserver2014a -Destination sqlcluster

        Copies all shared job schedules from sqlserver2014a to sqlcluster using Windows credentials. If shared job schedules with the same name exist on sqlcluster, they will be skipped.

    .EXAMPLE
        PS C:\> Copy-DbaAgentSchedule -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force

        Shows what would happen if the command were executed using force.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]
        $SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]
        $DestinationSqlCredential,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Copy-DbaAgentSharedSchedule
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential -MinimumVersion 9
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }
        $serverSchedules = $sourceServer.JobServer.SharedSchedules
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }

            $destSchedules = $destServer.JobServer.SharedSchedules
            foreach ($schedule in $serverSchedules) {
                $scheduleName = $schedule.Name
                $copySharedScheduleStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Type              = "Agent Schedule"
                    Name              = $scheduleName
                    Status            = $null
                    Notes             = $null
                    DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                }

                if ($schedules.Length -gt 0 -and $schedules -notcontains $scheduleName) {
                    continue
                }

                if ($destSchedules.Name -contains $scheduleName) {
                    if ($force -eq $false) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Shared job schedule $scheduleName exists at destination. Use -Force to drop and migrate.")) {
                            $copySharedScheduleStatus.Status = "Skipped"
                            $copySharedScheduleStatus.Notes = "Already exists on destination"
                            $copySharedScheduleStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            Write-Message -Level Verbose -Message "Shared job schedule $scheduleName exists at destination. Use -Force to drop and migrate."
                            continue
                        }
                    } else {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Schedule [$scheduleName] has associated jobs. Skipping.")) {
                            if ($destServer.JobServer.Jobs.JobSchedules.Name -contains $scheduleName) {
                                $copySharedScheduleStatus.Status = "Skipped"
                                $copySharedScheduleStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                Write-Message -Level Verbose -Message "Schedule [$scheduleName] has associated jobs. Skipping."
                            }
                            continue
                        } else {
                            if ($Pscmdlet.ShouldProcess($destinstance, "Dropping schedule $scheduleName and recreating")) {
                                try {
                                    Write-Message -Level Verbose -Message "Dropping schedule $scheduleName"
                                    $destServer.JobServer.SharedSchedules[$scheduleName].Drop()
                                } catch {
                                    $copySharedScheduleStatus.Status = "Failed"
                                    $copySharedScheduleStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                    Stop-Function -Message "Issue dropping schedule" -Target $scheduleName -ErrorRecord $_ -Continue
                                }
                            }
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destinstance, "Creating schedule $scheduleName")) {
                    try {
                        Write-Message -Level Verbose -Message "Copying schedule $scheduleName"
                        $sql = $schedule.Script() | Out-String

                        Write-Message -Level Debug -Message $sql
                        $destServer.Query($sql)

                        $copySharedScheduleStatus.Status = "Successful"
                        $copySharedScheduleStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    } catch {
                        $copySharedScheduleStatus.Status = "Failed"
                        $copySharedScheduleStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        Stop-Function -Message "Issue creating schedule" -Target $scheduleName -ErrorRecord $_ -Continue
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlSharedSchedule
    }
}
tools\dbatools\functions\Copy-DbaAgentServer.ps1
function Copy-DbaAgentServer {
    <#
    .SYNOPSIS
        Copy SQL Server Agent from one server to another.

    .DESCRIPTION
        A wrapper function that calls the associated Copy command for each of the object types seen in SSMS under SQL Server Agent. This also copies all of the the SQL Agent properties (job history max rows, DBMail profile name, etc.).

        You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER DisableJobsOnDestination
        If this switch is enabled, the jobs will be disabled on Destination after copying.

    .PARAMETER DisableJobsOnSource
        If this switch is enabled, the jobs will be disabled on Source after copying.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER Force
        If this switch is enabled, existing objects on Destination with matching names from Source will be dropped, then copied.

    .NOTES
        Tags: Migration, SqlServerAgent, SqlAgent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        https://dbatools.io/Copy-DbaAgentServer

    .EXAMPLE
        PS C:\> Copy-DbaAgentServer -Source sqlserver2014a -Destination sqlcluster

        Copies all job server objects from sqlserver2014a to sqlcluster using Windows credentials for authentication. If job objects with the same name exist on sqlcluster, they will be skipped.

    .EXAMPLE
        PS C:\> Copy-DbaAgentServer -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred

        Copies all job objects from sqlserver2014a to sqlcluster using SQL credentials to authentication to sqlserver2014a and Windows credentials to authenticate to sqlcluster.

    .EXAMPLE
        PS C:\> Copy-DbaAgentServer -Source sqlserver2014a -Destination sqlcluster -WhatIf

        Shows what would happen if the command were executed.

    #>
    [cmdletbinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]$SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]$DestinationSqlCredential,
        [Switch]$DisableJobsOnDestination,
        [Switch]$DisableJobsOnSource,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }
        Invoke-SmoCheck -SqlInstance $sourceServer
        $sourceAgent = $sourceServer.JobServer
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }
            Invoke-SmoCheck -SqlInstance $destServer
            # All of these support whatif inside of them
            Copy-DbaAgentJobCategory -Source $sourceServer -Destination $destServer -Force:$force

            $destServer.JobServer.JobCategories.Refresh()
            $destServer.JobServer.OperatorCategories.Refresh()
            $destServer.JobServer.AlertCategories.Refresh()

            Copy-DbaAgentOperator -Source $sourceServer -Destination $destServer -Force:$force
            $destServer.JobServer.Operators.Refresh()

            Copy-DbaAgentAlert -Source $sourceServer -Destination $destServer -Force:$force -IncludeDefaults
            $destServer.JobServer.Alerts.Refresh()

            Copy-DbaAgentProxy -Source $sourceServer -Destination $destServer -Force:$force
            $destServer.JobServer.ProxyAccounts.Refresh()

            Copy-DbaAgentSchedule -Source $sourceServer -Destination $destServer -Force:$force
            $destServer.JobServer.SharedSchedules.Refresh()

            $destServer.JobServer.Refresh()
            $destServer.Refresh()
            Copy-DbaAgentJob -Source $sourceServer -Destination $destServer -Force:$force -DisableOnDestination:$DisableJobsOnDestination -DisableOnSource:$DisableJobsOnSource

            # To do
            <#
            Copy-DbaAgentMasterServer -Source $sourceServer -Destination $destServer -Force:$force
            Copy-DbaAgentTargetServer -Source $sourceServer -Destination $destServer -Force:$force
            Copy-DbaAgentTargetServerGroup -Source $sourceServer -Destination $destServer -Force:$force
        #>

            <# Here are the properties which must be migrated separately #>
            $copyAgentPropStatus = [pscustomobject]@{
                SourceServer      = $sourceServer.Name
                DestinationServer = $destServer.Name
                Name              = "Server level properties"
                Type              = "Agent Properties"
                Status            = $null
                Notes             = $null
                DateTime          = [DbaDateTime](Get-Date)
            }

            if ($Pscmdlet.ShouldProcess($destinstance, "Copying Agent Properties")) {
                try {
                    Write-Message -Level Verbose -Message "Copying SQL Agent Properties"
                    $sql = $sourceAgent.Script() | Out-String
                    $sql = $sql -replace [Regex]::Escape("'$source'"), "'$destinstance'"
                    $sql = $sql -replace [Regex]::Escape("@errorlog_file="), [Regex]::Escape("--@errorlog_file=")
                    $sql = $sql -replace [Regex]::Escape("@auto_start="), [Regex]::Escape("--@auto_start=")
                    Write-Message -Level Debug -Message $sql
                    $null = $destServer.Query($sql)

                    $copyAgentPropStatus.Status = "Successful"
                    $copyAgentPropStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                } catch {
                    $message = $_.Exception.InnerException.InnerException.InnerException.Message
                    if (-not $message) { $message = $_.Exception.Message }
                    $copyAgentPropStatus.Status = "Failed"
                    $copyAgentPropStatus.Notes = $message
                    $copyAgentPropStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    Stop-Function -Message $message -Target $destinstance
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlServerAgent
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-DbaSqlServerAgent
    }
}
tools\dbatools\functions\Copy-DbaBackupDevice.ps1
function Copy-DbaBackupDevice {
    <#
    .SYNOPSIS
        Copies backup devices one by one. Copies both SQL code and the backup file itself.

    .DESCRIPTION
        Backups are migrated using Admin shares. If the destination directory does not exist, SQL Server's default backup directory will be used.

        If a backup device with same name exists on destination, it will not be dropped and recreated unless -Force is used.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER BackupDevice
        BackupDevice to be copied. Auto-populated list of devices. If not provided all BackupDevice(s) will be copied.

    .PARAMETER Force
        If this switch is enabled, backup device(s) will be dropped and recreated if they already exists on destination.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration, Backup
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        https://dbatools.io/Copy-DbaBackupDevice

    .EXAMPLE
        PS C:\> Copy-DbaBackupDevice -Source sqlserver2014a -Destination sqlcluster

        Copies all server backup devices from sqlserver2014a to sqlcluster using Windows credentials. If backup devices with the same name exist on sqlcluster, they will be skipped.

    .EXAMPLE
        PS C:\> Copy-DbaBackupDevice -Source sqlserver2014a -Destination sqlcluster -BackupDevice backup01 -SourceSqlCredential $cred -Force

        Copies only the backup device named backup01 from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a    and Windows credentials for sqlcluster. If a backup device with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used.

    .EXAMPLE
        PS C:\> Copy-DbaBackupDevice -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force

        Shows what would happen if the command were executed using force.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]$SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]$DestinationSqlCredential,
        [object[]]$BackupDevice,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        if (-not $script:isWindows) {
            Stop-Function -Message "Copy-DbaBackupDevice does not support Linux yet though it looks doable"
            return
        }
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }
        $serverBackupDevices = $sourceServer.BackupDevices
        $sourceNetBios = $Source.ComputerName
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }
            $destBackupDevices = $destServer.BackupDevices
            $destNetBios = $destinstance.ComputerName

            foreach ($currentBackupDevice in $serverBackupDevices) {
                $deviceName = $currentBackupDevice.Name

                $copyBackupDeviceStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Name              = $deviceName
                    Type              = "Backup Device"
                    Status            = $null
                    Notes             = $null
                    DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                }

                if ($BackupDevice -and $BackupDevice -notcontains $deviceName) {
                    continue
                }

                if ($destBackupDevices.Name -contains $deviceName) {
                    if ($force -eq $false) {
                        $copyBackupDeviceStatus.Status = "Skipped"
                        $copyBackupDeviceStatus.Notes = "Already exists on destination"
                        $copyBackupDeviceStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        Write-Message -Level Verbose -Message "backup device $deviceName exists at destination. Use -Force to drop and migrate."
                        continue
                    } else {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Dropping backup device $deviceName")) {
                            try {
                                Write-Message -Level Verbose -Message "Dropping backup device $deviceName"
                                $destServer.BackupDevices[$deviceName].Drop()
                            } catch {
                                $copyBackupDeviceStatus.Status = "Failed"
                                $copyBackupDeviceStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                                Stop-Function -Message "Issue dropping backup device" -Target $deviceName -ErrorRecord $_ -Continue
                            }
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destinstance, "Generating SQL code for $deviceName")) {
                    Write-Message -Level Verbose -Message "Scripting out SQL for $deviceName"
                    try {
                        $sql = $currentBackupDevice.Script() | Out-String
                        $sql = $sql -replace [Regex]::Escape("'$source'"), "'$destinstance'"
                    } catch {
                        $copyBackupDeviceStatus.Status = "Failed"
                        $copyBackupDeviceStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        Stop-Function -Message "Issue scripting out backup device" -Target $deviceName -ErrorRecord $_ -Continue
                    }
                }

                if ($Pscmdlet.ShouldProcess("console", "Stating that the actual file copy is about to occur")) {
                    Write-Message -Level Verbose -Message "Preparing to copy actual backup file"
                }

                $path = Split-Path $sourceServer.BackupDevices[$deviceName].PhysicalLocation
                $destPath = Join-AdminUnc $destNetBios $path
                $sourcepath = Join-AdminUnc $sourceNetBios $sourceServer.BackupDevices[$deviceName].PhysicalLocation

                Write-Message -Level Verbose -Message "Checking if directory $destPath exists"

                if ($(Test-DbaPath -SqlInstance $destServer -Path $path) -eq $false) {
                    $backupDirectory = $destServer.BackupDirectory
                    $destPath = Join-AdminUnc $destNetBios $backupDirectory

                    if ($Pscmdlet.ShouldProcess($destinstance, "Updating create code to use new path")) {
                        Write-Message -Level Verbose -Message "$path doesn't exist on $destinstance"
                        Write-Message -Level Verbose -Message "Using default backup directory $backupDirectory"

                        try {
                            Write-Message -Level Verbose -Message "Updating $deviceName to use $backupDirectory"
                            $sql = $sql -replace [Regex]::Escape($path), $backupDirectory
                        } catch {
                            $copyBackupDeviceStatus.Status = "Failed"
                            $copyBackupDeviceStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                            Stop-Function -Message "Issue updating script of backup device with new path" -Target $deviceName -ErrorRecord $_ -Continue
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destinstance, "Copying $sourcepath to $destPath using BITSTransfer")) {
                    try {
                        Start-BitsTransfer -Source $sourcepath -Destination $destPath -ErrorAction Stop
                        Write-Message -Level Verbose -Message "Backup device $deviceName successfully copied"
                    } catch {
                        $copyBackupDeviceStatus.Status = "Failed"
                        $copyBackupDeviceStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        Stop-Function -Message "Issue copying backup device to destination" -Target $deviceName -ErrorRecord $_ -Continue
                    }
                }

                if ($Pscmdlet.ShouldProcess($destinstance, "Adding backup device $deviceName")) {
                    Write-Message -Level Verbose -Message "Adding backup device $deviceName on $destinstance"
                    try {
                        $destServer.Query($sql)
                        $destServer.BackupDevices.Refresh()

                        $copyBackupDeviceStatus.Status = "Successful"
                        $copyBackupDeviceStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    } catch {
                        $copyBackupDeviceStatus.Status = "Failed"
                        $copyBackupDeviceStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        Stop-Function -Message "Issue adding backup device" -Target $deviceName -ErrorRecord $_ -Continue
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlBackupDevice
    }
}
tools\dbatools\functions\Copy-DbaCmsRegServer.ps1
function Copy-DbaCmsRegServer {
    <#
    .SYNOPSIS
        Migrates SQL Server Central Management groups and server instances from one SQL Server to another.

    .DESCRIPTION
        Copy-DbaCmsRegServer copies all groups, subgroups, and server instances from one SQL Server to another.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Group
        This is an auto-populated array that contains your Central Management Server top-level groups on Source. You can specify one, many or none.

        If Group is not specified, all groups in your Central Management Server will be copied.

    .PARAMETER SwitchServerName
        If this switch is enabled, all instance names will be changed from Source to Destination.

        Central Management Server does not allow you to add a shared registered server with the same name as the Configuration Server.

    .PARAMETER Force
        If this switch is enabled, group(s) will be dropped and recreated if they already exists on destination.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        https://dbatools.io/Copy-DbaCmsRegServer

    .EXAMPLE
        PS C:\> Copy-DbaCmsRegServer -Source sqlserver2014a -Destination sqlcluster

        All groups, subgroups, and server instances are copied from sqlserver2014a CMS to sqlcluster CMS.

    .EXAMPLE
        PS C:\> Copy-DbaCmsRegServer -Source sqlserver2014a -Destination sqlcluster -Group Group1,Group3

        Top-level groups Group1 and Group3 along with their subgroups and server instances are copied from sqlserver to sqlcluster.

    .EXAMPLE
        PS C:\> Copy-DbaCmsRegServer -Source sqlserver2014a -Destination sqlcluster -Group Group1,Group3 -SwitchServerName -SourceSqlCredential $SourceSqlCredential -DestinationSqlCredential $DestinationSqlCredential

        Top-level groups Group1 and Group3 along with their subgroups and server instances are copied from sqlserver to sqlcluster. When adding sql instances to sqlcluster, if the server name of the migrating instance is "sqlcluster", it will be switched to "sqlserver".

        If SwitchServerName is not specified, "sqlcluster" will be skipped.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]$SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]$DestinationSqlCredential,
        [Alias('CMSGroup')]
        [string[]]$Group,
        [switch]$SwitchServerName,
        [switch]$Force,
        [switch]$EnableException
    )
    begin {
        if (-not $script:isWindows) {
            Stop-Function -Message "Copy-DbaCmsRegServer does not support Linux - we're still waiting for the Core SMOs from Microsoft"
            return
        }
        
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Copy-DbaCentralManagementServer
        function Invoke-ParseServerGroup {
            [cmdletbinding()]
            param (
                $sourceGroup,
                $destinationGroup,
                $SwitchServerName
            )
            if ($destinationGroup.Name -eq "DatabaseEngineServerGroup" -and $sourceGroup.Name -ne "DatabaseEngineServerGroup") {
                $currentServerGroup = $destinationGroup
                $groupName = $sourceGroup.Name
                $destinationGroup = $destinationGroup.ServerGroups[$groupName]

                $copyDestinationGroupStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Name              = $groupName
                    Type              = "CMS Destination Group"
                    Status            = $null
                    Notes             = $null
                    DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                }

                if ($null -ne $destinationGroup) {

                    if ($force -eq $false) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Checking to see if $groupName exists")) {
                            $copyDestinationGroupStatus.Status = "Skipped"
                            $copyDestinationGroupStatus.Notes = "Already exists on destination"
                            $copyDestinationGroupStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            Write-Message -Level Verbose -Message "Destination group $groupName exists at destination. Use -Force to drop and migrate."
                        }
                        continue
                    }
                    if ($Pscmdlet.ShouldProcess($destinstance, "Dropping group $groupName")) {
                        try {
                            Write-Message -Level Verbose -Message "Dropping group $groupName"
                            $destinationGroup.Drop()
                        } catch {
                            $copyDestinationGroupStatus.Status = "Failed"
                            $copyDestinationGroupStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                            Stop-Function -Message "Issue dropping group" -Target $groupName -ErrorRecord $_ -Continue
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destinstance, "Creating group $groupName")) {
                    Write-Message -Level Verbose -Message "Creating group $($sourceGroup.Name)"
                    $destinationGroup = New-Object Microsoft.SqlServer.Management.RegisteredServers.ServerGroup($currentServerGroup, $sourceGroup.Name)
                    $destinationGroup.Create()

                    $copyDestinationGroupStatus.Status = "Successful"
                    $copyDestinationGroupStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                }
            }

            # Add Servers
            foreach ($instance in $sourceGroup.RegisteredServers) {
                $instanceName = $instance.Name
                $serverName = $instance.ServerName

                $copyInstanceStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Name              = $instanceName
                    Type              = "CMS Instance"
                    Status            = $null
                    Notes             = $null
                    DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                }

                if ($serverName.ToLower() -eq $toCmStore.DomainInstanceName.ToLower()) {
                    if ($Pscmdlet.ShouldProcess($destinstance, "Checking to see if server is the CMS equals current server name")) {
                        if ($SwitchServerName) {
                            $serverName = $fromCmStore.DomainInstanceName
                            $instanceName = $fromCmStore.DomainInstanceName
                            Write-Message -Level Verbose -Message "SwitchServerName was used and new CMS equals current server name. $($toCmStore.DomainInstanceName.ToLower()) changed to $serverName."
                        } else {
                            $copyInstanceStatus.Status = "Skipped"
                            $copyInstanceStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                            Write-Message -Level Verbose -Message "$serverName is Central Management Server. Add prohibited. Skipping."
                            continue
                        }
                    }
                }

                if ($destinationGroup.RegisteredServers.Name -contains $instanceName) {

                    if ($force -eq $false) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Checking to see if $instanceName in $groupName exists")) {
                            $copyInstanceStatus.Status = "Skipped"
                            $copyInstanceStatus.Notes = "Already exists on destination"
                            $copyInstanceStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                            Write-Message -Level Verbose -Message "Instance $instanceName exists in group $groupName at destination. Use -Force to drop and migrate."
                        }
                        continue
                    }

                    if ($Pscmdlet.ShouldProcess($destinstance, "Dropping instance $instanceName from $groupName and recreating")) {
                        try {
                            Write-Message -Level Verbose -Message "Dropping instance $instance from $groupName"
                            $destinationGroup.RegisteredServers[$instanceName].Drop()
                        } catch {
                            $copyInstanceStatus.Status = "Failed"
                            $copyInstanceStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                            Stop-Function -Message "Issue dropping instance from group" -Target $instanceName -ErrorRecord $_ -Continue
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destinstance, "Copying $instanceName")) {
                    $newServer = New-Object Microsoft.SqlServer.Management.RegisteredServers.RegisteredServer($destinationGroup, $instanceName)
                    $newServer.ServerName = $serverName
                    $newServer.Description = $instance.Description

                    if ($serverName -ne $fromCmStore.DomainInstanceName) {
                        $newServer.SecureConnectionString = $instance.SecureConnectionString.ToString()
                        $newServer.ConnectionString = $instance.ConnectionString.ToString()
                    }

                    try {
                        $newServer.Create()

                        $copyInstanceStatus.Status = "Successful"
                        $copyInstanceStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    } catch {
                        $copyInstanceStatus.Status = "Failed"
                        $copyInstanceStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        if ($_.Exception -match "same name") {
                            Stop-Function -Message "Could not add Switched Server instance name." -Target $instanceName -ErrorRecord $_ -Continue
                        } else {
                            Stop-Function -Message "Failed to add $serverName" -Target $instanceName -ErrorRecord $_ -Continue
                        }
                    }
                    Write-Message -Level Verbose -Message "Added Server $serverName as $instanceName to $($destinationGroup.Name)"
                }
            }

            # Add Groups
            foreach ($fromSubGroup in $sourceGroup.ServerGroups) {
                $fromSubGroupName = $fromSubGroup.Name
                $toSubGroup = $destinationGroup.ServerGroups[$fromSubGroupName]

                $copyGroupStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Name              = $fromSubGroupName
                    Type              = "CMS Group"
                    Status            = $null
                    Notes             = $null
                    DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                }

                if ($null -ne $toSubGroup) {
                    if ($force -eq $false) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Checking to see if subgroup $fromSubGroupName exists")) {
                            $copyGroupStatus.Status = "Skipped"
                            $copyGroupStatus.Notes = "Already exists on destination"
                            $copyGroupStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                            Write-Message -Level Verbose -Message "Subgroup $fromSubGroupName exists at destination. Use -Force to drop and migrate."
                        }
                        continue
                    }

                    if ($Pscmdlet.ShouldProcess($destinstance, "Dropping subgroup $fromSubGroupName recreating")) {
                        try {
                            Write-Message -Level Verbose -Message "Dropping subgroup $fromSubGroupName"
                            $toSubGroup.Drop()
                        } catch {
                            $copyGroupStatus.Status = "Failed"
                            $copyGroupStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                            Stop-Function -Message "Issue dropping subgroup" -Target $toSubGroup -ErrorRecord $_ -Continue
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destinstance, "Creating group $($fromSubGroup.Name)")) {
                    Write-Message -Level Verbose -Message "Creating group $($fromSubGroup.Name)"
                    $toSubGroup = New-Object Microsoft.SqlServer.Management.RegisteredServers.ServerGroup($destinationGroup, $fromSubGroup.Name)
                    $toSubGroup.create()

                    $copyGroupStatus.Status = "Successful"
                    $copyGroupStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                }

                Invoke-ParseServerGroup -sourceGroup $fromSubGroup -destinationgroup $toSubGroup -SwitchServerName $SwitchServerName
            }
        }

        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential -MinimumVersion 10
            $fromCmStore = Get-DbaCmsRegServerStore -SqlInstance $sourceServer
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }
    }

    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }
            $toCmStore = Get-DbaCmsRegServerStore -SqlInstance $destServer

            $stores = $fromCmStore.DatabaseEngineServerGroup
            if ($Group) {
                $stores = @();
                foreach ($groupName in $Group) {
                    $stores += $fromCmStore.DatabaseEngineServerGroup.ServerGroups[$groupName]
                }
            }

            foreach ($store in $stores) {
                Invoke-ParseServerGroup -sourceGroup $store -destinationgroup $toCmStore.DatabaseEngineServerGroup -SwitchServerName $SwitchServerName
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlCentralManagementServer
    }
}
tools\dbatools\functions\Copy-DbaCredential.ps1
function Copy-DbaCredential {
    <#
    .SYNOPSIS
        Copy-DbaCredential migrates SQL Server Credentials from one SQL Server to another while maintaining Credential passwords.

    .DESCRIPTION
        By using password decryption techniques provided by Antti Rantasaari (NetSPI, 2014), this script migrates SQL Server Credentials from one server to another while maintaining username and password.

        Credit: https://blog.netspi.com/decrypting-mssql-database-link-server-passwords/

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Credential
        This command requires access to the Windows OS via PowerShell remoting. Use this credential to connect to Windows using alternative credentials.

    .PARAMETER Name
        Only include specific names
        Note: if spaces exist in the credential name, you will have to type "" or '' around it.

    .PARAMETER ExcludeName
        Excluded credential names

    .PARAMETER Identity
        Only include specific identities
        Note: if spaces exist in the credential identity, you will have to type "" or '' around it.

    .PARAMETER ExcludeIdentity
        Excluded identities

    .PARAMETER Force
        If this switch is enabled, the Credential will be dropped and recreated if it already exists on Destination.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: WSMan, Migration
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires:
        - PowerShell Version 3.0
        - Administrator access on Windows
        - sysadmin access on SQL Server.
        - DAC access enabled for local (default)

    .LINK
        https://dbatools.io/Copy-DbaCredential

    .EXAMPLE
        PS C:\> Copy-DbaCredential -Source sqlserver2014a -Destination sqlcluster

        Copies all SQL Server Credentials on sqlserver2014a to sqlcluster. If Credentials exist on destination, they will be skipped.

    .EXAMPLE
        PS C:\> Copy-DbaCredential -Source sqlserver2014a -Destination sqlcluster -Name "PowerShell Proxy Account" -Force

        Copies over one SQL Server Credential (PowerShell Proxy Account) from sqlserver to sqlcluster. If the Credential already exists on the destination, it will be dropped and recreated.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]
        $SourceSqlCredential,
        [PSCredential]
        $Credential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]$DestinationSqlCredential,
        [string[]]$Name,
        [string[]]$ExcludeName,
        [Alias('CredentialIdentity')]
        [string[]]$Identity,
        [Alias('ExcludeCredentialIdentity')]
        [string[]]$ExcludeIdentity,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )
    
    begin {
        if (-not $script:isWindows) {
            Stop-Function -Message "Copy-DbaCredential is only supported on Windows"
            return
        }
        $null = Test-ElevationRequirement -ComputerName $Source.ComputerName

        function Copy-Credential {
            <#
                .SYNOPSIS
                    Copies Credentials from one server to another using a combination of SMO's .Script() and manual password updates.

                .OUTPUT
                    System.Data.DataTable
            #>
            [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "", Justification = "For Credentials")]
            param (
                [string[]]$Credentials,
                [bool]$Force
            )

            Write-Message -Level Verbose -Message "Collecting Credential logins and passwords on $($sourceServer.Name)"
            $sourceCredentials = Get-DecryptedObject -SqlInstance $sourceServer -Type Credential
            $credentialList = Get-DbaCredential -SqlInstance $sourceServer -Name $Name -ExcludeName $ExcludeName -Identity $Identity -ExcludeIdentity $ExcludeIdentity

            Write-Message -Level Verbose -Message "Starting migration"
            foreach ($credential in $credentialList) {
                $destServer.Credentials.Refresh()
                $credentialName = $credential.Name

                $copyCredentialStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Type              = "Credential"
                    Name              = $credentialName
                    Status            = $null
                    Notes             = $null
                    DateTime          = [DbaDateTime](Get-Date)
                }

                if ($null -ne $destServer.Credentials[$credentialName]) {
                    if (!$force) {
                        $copyCredentialStatus.Status = "Skipping"
                        $copyCredentialStatus.Notes = "Already exists on destination"
                        $copyCredentialStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        Write-Message -Level Verbose -Message "$credentialName exists $($destServer.Name). Skipping."
                        continue
                    } else {
                        if ($Pscmdlet.ShouldProcess($destinstance.Name, "Dropping $identity")) {
                            $destServer.Credentials[$credentialName].Drop()
                            $destServer.Credentials.Refresh()
                        }
                    }
                }

                Write-Message -Level Verbose -Message "Attempting to migrate $credentialName"
                try {
                    $currentCred = $sourceCredentials | Where-Object { $_.Name -eq "[$credentialName]" }
                    $sqlcredentialName = $credentialName.Replace("'", "''")
                    $identity = $currentCred.Identity.Replace("'", "''")
                    $password = $currentCred.Password.Replace("'", "''")
                    if ($Pscmdlet.ShouldProcess($destinstance.Name, "Copying $identity")) {
                        $destServer.Query("CREATE CREDENTIAL [$sqlcredentialName] WITH IDENTITY = N'$identity', SECRET = N'$password'")
                        $destServer.Credentials.Refresh()
                        Write-Message -Level Verbose -Message "$credentialName successfully copied"
                    }

                    $copyCredentialStatus.Status = "Successful"
                    $copyCredentialStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                } catch {
                    $copyCredentialStatus.Status = "Failed"
                    $copyCredentialStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                    Stop-Function -Message "Error creating credential" -Target $credentialName -ErrorRecord $_
                }
            }
        }

        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential -MinimumVersion 9
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance
            return
        }

        if ($null -ne $SourceSqlCredential.Username) {
            Write-Message -Level Verbose -Message "You are using SQL credentials and this script requires Windows admin access to the $Source server. Trying anyway."
        }

        $sourceNetBios = Resolve-NetBiosName $sourceServer

        Invoke-SmoCheck -SqlInstance $sourceServer

        Write-Message -Level Verbose -Message "Checking if Remote Registry is enabled on $source"
        try {
            Invoke-Command2 -ComputerName $sourceNetBios -Credential $credential -ScriptBlock { Get-ItemProperty -Path "HKLM:\SOFTWARE\" }
        } catch {
            Stop-Function -Message "Can't connect to registry on $source" -Target $sourceNetBios -ErrorRecord $_
            return
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }

        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }
            Invoke-SmoCheck -SqlInstance $destServer

            Copy-Credential $credentials -force:$force
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlCredential
    }
}
tools\dbatools\functions\Copy-DbaCustomError.ps1
function Copy-DbaCustomError {
    <#
    .SYNOPSIS
        Copy-DbaCustomError migrates custom errors (user defined messages), by the custom error ID, from one SQL Server to another.

    .DESCRIPTION
        By default, all custom errors are copied. The -CustomError parameter is auto-populated for command-line completion and can be used to copy only specific custom errors.

        If the custom error already exists on the destination, it will be skipped unless -Force is used. The us_english version must be created first. If you drop the us_english version, all the other languages will be dropped for that specific ID as well.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER CustomError
        The custom error(s) to process. This list is auto-populated from the server. If unspecified, all custom errors will be processed.

    .PARAMETER ExcludeCustomError
        The custom error(s) to exclude. This list is auto-populated from the server.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER Force
        If this switch is enabled, the custom error will be dropped and recreated if it already exists on Destination.

    .NOTES
        Tags: Migration, CustomError
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        https://dbatools.io/Copy-DbaCustomError

    .EXAMPLE
        PS C:\> Copy-DbaCustomError -Source sqlserver2014a -Destination sqlcluster

        Copies all server custom errors from sqlserver2014a to sqlcluster using Windows credentials. If custom errors with the same name exist on sqlcluster, they will be skipped.

    .EXAMPLE
        PS C:\> Copy-DbaCustomError -Source sqlserver2014a -SourceSqlCredential $scred -Destination sqlcluster -DestinationSqlCredential $dcred -CustomError 60000 -Force

        Copies only the custom error with ID number 60000 from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If a custom error with the same name exists on sqlcluster, it will be updated because -Force was used.

    .EXAMPLE
        PS C:\> Copy-DbaCustomError -Source sqlserver2014a -Destination sqlcluster -ExcludeCustomError 60000 -Force

        Copies all the custom errors found on sqlserver2014a except the custom error with ID number 60000 to sqlcluster. If a custom error with the same name exists on sqlcluster, it will be updated because -Force was used.

    .EXAMPLE
        PS C:\> Copy-DbaCustomError -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force

        Shows what would happen if the command were executed using force.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]
        $SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]
        $DestinationSqlCredential,
        [object[]]$CustomError,
        [object[]]$ExcludeCustomError,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential -MinimumVersion 9
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }
        $orderedCustomErrors = @($sourceServer.UserDefinedMessages | Where-Object Language -eq "us_english")
        $orderedCustomErrors += $sourceServer.UserDefinedMessages | Where-Object Language -ne "us_english"
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }
            # US has to go first
            $destCustomErrors = $destServer.UserDefinedMessages

            foreach ($currentCustomError in $orderedCustomErrors) {
                $customErrorId = $currentCustomError.ID
                $language = $currentCustomError.Language.ToString()

                $copyCustomErrorStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Type              = "Custom error"
                    Name              = $currentCustomError
                    Status            = $null
                    Notes             = $null
                    DateTime          = [DbaDateTime](Get-Date)
                }

                if ($CustomError -and ($customErrorId -notin $CustomError -or $customErrorId -in $ExcludeCustomError)) {
                    continue
                }

                if ($destCustomErrors.ID -contains $customErrorId) {
                    if ($force -eq $false) {
                        $copyCustomErrorStatus.Status = "Skipped"
                        $copyCustomErrorStatus.Notes = "Already exists on destination"
                        $copyCustomErrorStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        Write-Message -Level Verbose -Message "Custom error $customErrorId $language exists at destination. Use -Force to drop and migrate."
                        continue
                    } else {
                        If ($Pscmdlet.ShouldProcess($destinstance, "Dropping custom error $customErrorId $language and recreating")) {
                            try {
                                Write-Message -Level Verbose -Message "Dropping custom error $customErrorId (drops all languages for custom error $customErrorId)"
                                $destServer.UserDefinedMessages[$customErrorId, $language].Drop()
                            } catch {
                                $copyCustomErrorStatus.Status = "Failed"
                                $copyCustomErrorStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                                Stop-Function -Message "Issue dropping custom error" -Target $customErrorId -ErrorRecord $_ -Continue
                            }
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destinstance, "Creating custom error $customErrorId $language")) {
                    try {
                        Write-Message -Level Verbose -Message "Copying custom error $customErrorId $language"
                        $sql = $currentCustomError.Script() | Out-String
                        Write-Message -Level Debug -Message $sql
                        $destServer.Query($sql)

                        $copyCustomErrorStatus.Status = "Successful"
                        $copyCustomErrorStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    } catch {
                        $copyCustomErrorStatus.Status = "Failed"
                        $copyCustomErrorStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        Stop-Function -Message "Issue creating custom error" -Target $customErrorId -ErrorRecord $_
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlCustomError
    }
}
tools\dbatools\functions\Copy-DbaDatabase.ps1
function Copy-DbaDatabase {
    <#
    .SYNOPSIS
        Migrates SQL Server databases from one SQL Server to another.

    .DESCRIPTION
        This script provides the ability to migrate databases using detach/copy/attach or backup/restore. This script works with named instances, clusters and SQL Server Express Edition.

        By default, databases will be migrated to the destination SQL Server's default data and log directories. You can override this by specifying -ReuseSourceFolderStructure. Filestreams and filegroups are also migrated. Safety is emphasized.

    .PARAMETER Source
        Source SQL Server.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You may specify multiple servers.

        Note that when using -BackupRestore with multiple servers, the backup will only be performed once and backups will be deleted at the end (if you didn't specify -NoBackupCleanup).

        When using -DetachAttach with multiple servers, -Reattach must be specified.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Migrates only specified databases. This list is auto-populated from the server for tab completion. Multiple databases may be specified as a collection.

    .PARAMETER ExcludeDatabase
        Excludes specified databases when performing -AllDatabases migrations. This list is auto-populated from the Source for tab completion.

    .PARAMETER AllDatabases
        If this switch is enabled, all user databases will be migrated. System and support databases will not be migrated. Requires -BackupRestore or -DetachAttach.

    .PARAMETER BackupRestore
        If this switch is enabled, the copy-only backup and restore method will be used to migrate the database(s). This method requires that you specify -SharedPath in a valid UNC format (\\server\share).

        Backups will be immediately deleted after use unless -NoBackupCleanup is specified.

    .PARAMETER SharedPath
        Specifies the network location for the backup files. The SQL Server service accounts must have read/write permission on this path.

    .PARAMETER WithReplace
        If this switch is enabled, the restore is executed with WITH REPLACE.

    .PARAMETER NoRecovery
        If this switch is enabled, the restore is executed with WITH NORECOVERY. Ideal for staging.

    .PARAMETER NoBackupCleanup
        If this switch is enabled, backups generated by this cmdlet will not be deleted after they are restored. The default behavior is to delete these backups.

    .PARAMETER NumberFiles
        Number of files to split the backup. Default is 3.

    .PARAMETER DetachAttach
        If this switch is enabled, the detach/copy/attach method is used to perform database migrations. No files are deleted on Source. If Destination attachment fails, the Source database will be reattached. File copies are performed over administrative shares (\\server\x$\mssql) using BITS. If a database is being mirrored, the mirror will be broken prior to migration.

    .PARAMETER Reattach
        If this switch is enabled, all databases are reattached to Source after DetachAttach migration.

    .PARAMETER SetSourceReadOnly
        If this switch is enabled, all migrated databases are set to ReadOnly on Source prior to detach/attach & backup/restore.

        If -Reattach is used, databases are set to read-only after reattaching.

    .PARAMETER ReuseSourceFolderStructure
        If this switch is enabled, databases will be migrated to a data and log directory structure on Destination mirroring that used on Source. By default, the default data and log directories for Destination will be used when the databases are migrated.

        The structure on Source  will be kept exactly, so consider this if you're migrating between different versions and use part of Microsoft's default Sql structure (MSSql12.INSTANCE, etc)

        To reuse Destination folder structure, use the  -WithReplace switch.

    .PARAMETER IncludeSupportDbs
        If this switch is enabled, ReportServer, ReportServerTempDb, SSISDB, and distribution databases will be copied if they exist on Source. A log file named $SOURCE-$destinstance-$date-Sqls.csv will be written to the current directory.

        Use of this switch requires -BackupRestore or -DetachAttach as well.

    .PARAMETER InputObject
        Enables piped input from Get-DbaDatabase

    .PARAMETER UseLastBackup
        Use the last full, diff and logs instead of performing backups. Note that the backups must exist in a location accessible by all destination servers, such a network share.

    .PARAMETER Continue
        If specified, will to attempt to restore transaction log backups on top of existing database(s) in Recovering or Standby states. Only usable with -UseLastBackup

    .PARAMETER NoCopyOnly
        If this switch is enabled, backups will be taken without COPY_ONLY. This will break the LSN backup chain, which will interfere with the restore chain of the database.

        By default this switch is disabled, so backups will be taken with COPY_ONLY. This will preserve the LSN backup chain.

        For more details please refer to this MSDN article - https://msdn.microsoft.com/en-us/library/ms191495.aspx

    .PARAMETER NewName
        If a single database is being copied, this will be used to rename the database during the copy process. Any occurrence of the original database name in the physical file names will be replaced with NewName
        If specified with multiple databases a warning will be raised and the copy stopped

        This option is mutually exclusive of Prefix

    .PARAMETER Prefix
        All copied database names and physical files will be prefixed with this string

        This option is mutually exclusive of NewName

    .PARAMETER SetSourceOffline
        If this switch is enabled, the Source database will be set to Offline after being copied.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER Force
        If this switch is enabled, existing databases on Destination with matching names from Source will be dropped. If using -DetachReattach, mirrors will be broken and the database(s) dropped from Availability Groups.

    .NOTES
        Tags: Migration, Backup, Restore
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

        Limitations:
        - Doesn't cover what it doesn't cover (replication, certificates, etc)
        - SQL Server 2000 databases cannot be directly migrated to SQL Server 2012 and above.
        - Logins within SQL Server 2012 and above logins cannot be migrated to SQL Server 2008 R2 and below.

    .LINK
        https://dbatools.io/Copy-DbaDatabase

    .EXAMPLE
        PS C:\> Copy-DbaDatabase -Source sql2014a -Destination sql2014b -Database TestDB -BackupRestore -SharedPath \\fileshare\sql\migration

        Migrates a single user database TestDB using Backup and restore from instance sql2014a to sql2014b. Backup files are stored in \\fileshare\sql\migration.

    .EXAMPLE
        PS C:\> Copy-DbaDatabase -Source sql2012 -Destination sql2014, sql2016 -DetachAttach -Reattach

        Databases will be migrated from sql2012 to both sql2014 and sql2016 using the detach/copy files/attach method.The following will be performed: kick all users out of the database, detach all data/log files, move files across the network over an admin share (\\SqlSERVER\M$\MSSql...), attach file on destination server, reattach at source. If the database files (*.mdf, *.ndf, *.ldf) on *destination* exist and aren't in use, they will be overwritten.

    .EXAMPLE
        PS C:\> Copy-DbaDatabase -Source sql2014a -Destination sqlcluster, sql2016 -BackupRestore -UseLastBackup -Force

        Migrates all user databases to sqlcluster and sql2016 using the last Full, Diff and Log backups from sql204a. If the databases exists on the destinations, they will be dropped prior to attach.

        Note that the backups must exist in a location accessible by all destination servers, such a network share.

    .EXAMPLE
        PS C:\> Copy-DbaDatabase -Source sql2014a -Destination sqlcluster -ExcludeDatabase Northwind, pubs -IncludeSupportDbs -Force -BackupRestore -SharedPath \\fileshare\sql\migration

        Migrates all user databases except for Northwind and pubs by using backup/restore (copy-only). Backup files are stored in \\fileshare\sql\migration. If the database exists on the destination, it will be dropped prior to attach.

        It also includes the support databases (ReportServer, ReportServerTempDb, distribution).

    #>
    [CmdletBinding(DefaultParameterSetName = "DbBackup", SupportsShouldProcess)]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseOutputTypeCorrectly", "", Justification = "PSSA Rule Ignored by BOH")]
    param (
        [DbaInstanceParameter]$Source,
        [PSCredential]$SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]$DestinationSqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [Alias("All")]
        [parameter(ParameterSetName = "DbBackup")]
        [parameter(ParameterSetName = "DbAttachDetach")]
        [switch]$AllDatabases,
        [parameter(Mandatory, ParameterSetName = "DbBackup")]
        [switch]$BackupRestore,
        [Alias("NetworkShare")]
        [parameter(ParameterSetName = "DbBackup",
            HelpMessage = "Specify a valid network share in the format \\server\share that can be accessed by your account and the SQL Server service accounts for both Source and Destination.")]
        [string]$SharedPath,
        [parameter(ParameterSetName = "DbBackup")]
        [switch]$WithReplace,
        [parameter(ParameterSetName = "DbBackup")]
        [switch]$NoRecovery,
        [parameter(ParameterSetName = "DbBackup")]
        [switch]$NoBackupCleanup,
        [parameter(ParameterSetName = "DbBackup")]
        [ValidateRange(1, 64)]
        [int]$NumberFiles = 3,
        [parameter(Mandatory, ParameterSetName = "DbAttachDetach")]
        [switch]$DetachAttach,
        [parameter(ParameterSetName = "DbAttachDetach")]
        [switch]$Reattach,
        [parameter(ParameterSetName = "DbBackup")]
        [parameter(ParameterSetName = "DbAttachDetach")]
        [switch]$SetSourceReadOnly,
        [Alias("ReuseFolderStructure")]
        [parameter(ParameterSetName = "DbBackup")]
        [parameter(ParameterSetName = "DbAttachDetach")]
        [switch]$ReuseSourceFolderStructure,
        [parameter(ParameterSetName = "DbBackup")]
        [parameter(ParameterSetName = "DbAttachDetach")]
        [switch]$IncludeSupportDbs,
        [parameter(ParameterSetName = "DbBackup")]
        [switch]$UseLastBackup,
        [parameter(ParameterSetName = "DbBackup")]
        [switch]$Continue,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$NoCopyOnly,
        [switch]$SetSourceOffline,
        [string]$NewName,
        [string]$Prefix,
        [switch]$Force,
        [switch]$EnableException
    )
    begin {
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter NetworkShare -CustomMessage "Using the parameter NetworkShare is deprecated. This parameter will be removed in version 1.0.0 or before. Use SharedPath instead."

        $CopyOnly = -not $NoCopyOnly

        if ($BackupRestore -and (-not $SharedPath -and -not $UseLastBackup)) {
            Stop-Function -Message "When using -BackupRestore, you must specify -SharedPath or -UseLastBackup"
            return
        }
        if ($SharedPath -and $UseLastBackup) {
            Stop-Function -Message "-SharedPath cannot be used with -UseLastBackup because the backup path is determined by the paths in the last backups"
            return
        }
        if ($DetachAttach -and -not $Reattach -and $Destination.Count -gt 1) {
            Stop-Function -Message "When using -DetachAttach with multiple servers, you must specify -Reattach to reattach database at source"
            return
        }
        if ($Continue -and -not $UseLastBackup) {
            Stop-Function -Message "-Continue cannot be used without -UseLastBackup"
            return
        }

        function Join-Path {
            <#
        An internal command that does not require the local path to exist

        Boo, this does not work, but keeping it for future ref.
        #>
            [CmdletBinding()]
            param (
                [string]$Path,
                [string]$ChildPath
            )
            process {
                try {
                    [IO.Path]::Combine($Path, $ChildPath)
                } catch {
                    "$Path\$ChildPath"
                }
            }
        }

        function Join-AdminUnc {
            <#
        .SYNOPSIS
        Internal function. Parses a path to make it an admin UNC.
        #>
            [CmdletBinding()]
            param (
                [Parameter(Mandatory)]
                [ValidateNotNullOrEmpty()]
                [string]$servername,
                [Parameter(Mandatory)]
                [ValidateNotNullOrEmpty()]
                [string]$filepath

            )

            if ($script:sameserver -or (-not $script:isWindows)) {
                return $filepath
            }
            if (-not $filepath) {
                return
            }
            if ($filepath.StartsWith("\\")) {
                return $filepath
            }

            $servername = $servername.Split("\")[0]

            if ($filepath -and $filepath -ne [System.DbNull]::Value) {
                $newpath = Join-Path "\\$servername\" $filepath.replace(':', '$')
                return $newpath
            } else {
                return
            }
        }

        function Get-SqlFileStructure {
            $dbcollection = @{
            };
            $databaseProgressbar = 0

            foreach ($db in $databaseList) {
                Write-Progress -Id 1 -Activity "Processing database file structure" -PercentComplete ($databaseProgressbar / $dbCount * 100) -Status "Processing $databaseProgressbar of $dbCount."
                $dbName = $db.Name
                Write-Message -Level Verbose -Message $dbName

                $databaseProgressbar++
                $dbStatus = $db.status.toString()
                if ($dbStatus.StartsWith("Normal") -eq $false) {
                    continue
                }
                $destinstancefiles = @{
                }; $sourcefiles = @{
                }

                $where = "Filetype <> 'LOG' and Filetype <> 'FULLTEXT'"

                $datarows = $dbFileTable.Tables.Select("dbname = '$dbName' and $where")

                # Data Files
                foreach ($file in $datarows) {
                    # Destination File Structure
                    $d = @{
                    }
                    if ($ReuseSourceFolderStructure) {
                        $d.physical = $file.filename
                    } elseif ($WithReplace) {
                        $name = $file.Name
                        $destfile = $remoteDbFileTable.Tables[0].Select("dbname = '$dbName' and name = '$name'")
                        $d.physical = $destfile.filename

                        if ($null -eq $d.physical) {
                            $directory = Get-SqlDefaultPaths $destServer data
                            $fileName = Split-Path $file.filename -Leaf
                            $d.physical = "$directory\$fileName"
                        }
                    } else {
                        $directory = Get-SqlDefaultPaths $destServer data
                        $fileName = Split-Path $file.filename -Leaf
                        $d.physical = "$directory\$fileName"
                    }
                    $d.logical = $file.Name

                    $d.remotefilename = Join-AdminUNC $destNetBios $d.physical
                    $destinstancefiles.add($file.Name, $d)

                    # Source File Structure
                    $s = @{
                    }
                    $s.logical = $file.Name
                    $s.physical = $file.filename
                    $s.remotefilename = Join-AdminUNC $sourceNetBios $s.physical
                    $sourcefiles.add($file.Name, $s)
                }

                # Add support for Full Text Catalogs in SQL Server 2005 and below
                if ($sourceServer.VersionMajor -lt 10) {
                    try {
                        $fttable = $null = $sourceServer.Databases[$dbName].ExecuteWithResults('sp_help_fulltext_catalogs')
                        $allrows = $fttable.Tables[0].rows
                    } catch {
                        # Nothing, it's just not enabled
                        # here to avoid an empty catch
                        $null = 1
                    }

                    foreach ($ftc in $allrows) {
                        # Destination File Structure
                        $d = @{
                        }
                        $pre = "sysft_"
                        $name = $ftc.Name
                        $physical = $ftc.Path # RootPath
                        $logical = "$pre$name"
                        if ($ReuseSourceFolderStructure) {
                            $d.physical = $physical
                        } else {
                            $directory = Get-SqlDefaultPaths $destServer data
                            if ($destServer.VersionMajor -lt 10) {
                                $directory = "$directory\FTDATA"
                            }
                            $fileName = Split-Path($physical) -leaf
                            $d.physical = "$directory\$fileName"
                        }
                        $d.logical = $logical
                        $d.remotefilename = Join-AdminUNC $destNetBios $d.physical
                        $destinstancefiles.add($logical, $d)

                        # Source File Structure
                        $s = @{
                        }
                        $pre = "sysft_"
                        $name = $ftc.Name
                        $physical = $ftc.Path # RootPath
                        $logical = "$pre$name"

                        $s.logical = $logical
                        $s.physical = $physical
                        $s.remotefilename = Join-AdminUNC $sourceNetBios $s.physical
                        $sourcefiles.add($logical, $s)
                    }
                }

                $where = "Filetype = 'LOG'"
                $datarows = $dbFileTable.Tables[0].Select("dbname = '$dbName' and $where")

                # Log Files
                foreach ($file in $datarows) {
                    $d = @{
                    }
                    if ($ReuseSourceFolderStructure) {
                        $d.physical = $file.filename
                    } elseif ($WithReplace) {
                        $name = $file.Name
                        $destfile = $remoteDbFileTable.Tables[0].Select("dbname = '$dbName' and name = '$name'")
                        $d.physical = $destfile.filename

                        if ($null -eq $d.physical) {
                            $directory = Get-SqlDefaultPaths $destServer data
                            $fileName = Split-Path $file.filename -Leaf
                            $d.physical = "$directory\$fileName"
                        }
                    } else {
                        $directory = Get-SqlDefaultPaths $destServer log
                        $fileName = Split-Path $file.filename -Leaf
                        $d.physical = "$directory\$fileName"
                    }
                    $d.logical = $file.Name
                    $d.remotefilename = Join-AdminUNC $destNetBios $d.physical
                    $destinstancefiles.add($file.Name, $d)

                    $s = @{
                    }
                    $s.logical = $file.Name
                    $s.physical = $file.filename
                    $s.remotefilename = Join-AdminUNC $sourceNetBios $s.physical
                    $sourcefiles.add($file.Name, $s)
                }

                $location = @{
                }
                $location.add("Destination", $destinstancefiles)
                $location.add("Source", $sourcefiles)
                $dbcollection.Add($($db.Name), $location)
            }

            $fileStructure = [pscustomobject]@{
                "databases" = $dbcollection
            }
            Write-Progress -id 1 -Activity "Processing database file structure" -Status "Completed" -Completed
            return $fileStructure
        }

        function Dismount-SqlDatabase {
            [CmdletBinding()]
            param (
                [object]$server,
                [string]$dbName
            )

            $currentdb = $server.databases[$dbName]
            if ($currentdb.IsMirroringEnabled) {
                try {
                    Write-Message -Level Verbose -Message "Breaking mirror for $dbName"
                    $currentdb.ChangeMirroringState([Microsoft.SqlServer.Management.Smo.MirroringOption]::Off)
                    $currentdb.Alter()
                    $currentdb.Refresh()
                    Write-Message -Level Verbose -Message "Could not break mirror for $dbName. Skipping."
                } catch {
                    Stop-Function -Message "Issue breaking mirror." -Target $dbName -ErrorRecord $_
                    return $false
                }
            }

            if ($currentdb.AvailabilityGroupName) {
                $agName = $currentdb.AvailabilityGroupName
                Write-Message -Level Verbose -Message "Attempting remove from Availability Group $agName."
                try {
                    $server.AvailabilityGroups[$currentdb.AvailabilityGroupName].AvailabilityDatabases[$dbName].Drop()
                    Write-Message -Level Verbose -Message "Successfully removed $dbName from  detach from $agName on $($server.Name)."
                } catch {
                    Stop-Function -Message "Could not remove $dbName from $agName on $($server.Name)." -Target $dbName -ErrorRecord $_
                    return $false
                }
            }

            Write-Message -Level Verbose -Message "Attempting detach from $dbName from $source."

            ####### Using Sql to detach does not modify the $currentdb collection #######

            $server.KillAllProcesses($dbName)

            try {
                $sql = "ALTER DATABASE [$dbName] SET SINGLE_USER WITH ROLLBACK IMMEDIATE"
                Write-Message -Level Verbose -Message $sql
                $null = $server.Query($sql)
                Write-Message -Level Verbose -Message "Successfully set $dbName to single-user from $source."
            } catch {
                Stop-Function -Message "Issue setting database to single-user." -Target $dbName -ErrorRecord $_
            }

            try {
                $sql = "EXEC master.dbo.sp_detach_db N'$dbName'"
                Write-Message -Level Verbose -Message $sql
                $null = $server.Query($sql)
                Write-Message -Level Verbose -Message "Successfully detached $dbName from $source."
                return $true
            } catch {
                Stop-Function -Message "Issue detaching database." -Target $dbName -ErrorRecord $_
                return $false
            }
        }

        function Mount-SqlDatabase {
            [CmdletBinding()]
            param (
                [object]$server,
                [string]$dbName,
                [object]$fileStructure,
                [string]$dbOwner
            )

            if ($null -eq $server.Logins.Item($dbOwner)) {
                try {
                    $dbOwner = ($destServer.logins | Where-Object {
                            $_.id -eq 1
                        }).Name
                } catch {
                    $dbOwner = "sa"
                }
            }
            try {
                $null = $server.AttachDatabase($dbName, $fileStructure, $dbOwner, [Microsoft.SqlServer.Management.Smo.AttachOptions]::None)
                return $true
            } catch {
                Stop-Function -Message "Issue mounting database." -ErrorRecord $_
                return $false
            }
        }

        function Start-SqlFileTransfer {
            <#

            SYNOPSIS
            Internal function. Uses BITS to transfer detached files (.mdf, .ndf, .ldf, and filegroups) to
            another server over admin UNC paths. Locations of data files are kept in the
            custom object generated by Get-SqlFileStructure

            #>
            [CmdletBinding(SupportsShouldProcess)]
            param (
                [object]$fileStructure,
                [string]$dbName
            )
            $filestructure
            $copydb = $fileStructure.databases[$dbName]
            $dbsource = $copydb.source
            $dbdestination = $copydb.destination

            foreach ($file in $dbsource.keys) {
                if ($Pscmdlet.ShouldProcess($file, "Starting Sql File Transfer")) {
                    $remotefilename = $dbdestination[$file].remotefilename
                    $from = $dbsource[$file].remotefilename
                    try {
                        if (Test-Path $from -pathtype container) {
                            $null = New-Item -ItemType Directory -Path $remotefilename -Force
                            Start-BitsTransfer -Source "$from\*.*" -Destination $remotefilename

                            $directories = (Get-ChildItem -recurse $from | Where-Object {
                                    $_.PsIsContainer
                                }).FullName
                            foreach ($directory in $directories) {
                                $newdirectory = $directory.replace($from, $remotefilename)
                                $null = New-Item -ItemType Directory -Path $newdirectory -Force
                                Start-BitsTransfer -Source "$directory\*.*" -Destination $newdirectory
                            }
                        } else {
                            Write-Message -Level Verbose -Message "Copying $from for $dbName."
                            Start-BitsTransfer -Source $from -Destination $remotefilename
                        }
                    } catch {
                        try {
                            # Sometimes BITS trips out temporarily on cloned drives.
                            Start-BitsTransfer -Source $from -Destination $remotefilename
                        } catch {
                            Write-Message -Level Verbose -Message "Start-BitsTransfer did not succeed. Now attempting with Copy-Item - no progress bar will be shown."
                            try {
                                Copy-Item -Path $from -Destination $remotefilename -ErrorAction Stop
                                $remotefilename
                            } catch {
                                Write-Message -Level Verbose -Message "Access denied. This can happen for a number of reasons including issues with cloned disks."
                                Stop-Function -Message "Alternatively, you may need to run PowerShell as Administrator, especially when running on localhost." -Target $from -ErrorRecord $_
                                return
                            }
                        }
                    }
                }
            }
            return $true
        }

        function Start-SqlDetachAttach {
            <#

            .SYNOPSIS
            Internal function. Performs checks, then executes Dismount-SqlDatabase on a database, copies its files to the new server,    then performs Mount-SqlDatabase. $sourceServer and $destServer are SMO server objects.

            $fileStructure is a custom object generated by Get-SqlFileStructure

            #>
            [CmdletBinding(SupportsShouldProcess)]
            param (
                [object]$sourceServer,
                [object]$destServer,
                [object]$fileStructure,
                [string]$dbName
            )
            if ($Pscmdlet.ShouldProcess($dbname, "Starting detaching and re-attaching from $sourceServer to $destServer")) {
                $destfilestructure = New-Object System.Collections.Specialized.StringCollection
                $sourceFileStructure = New-Object System.Collections.Specialized.StringCollection
                $dbOwner = $sourceServer.databases[$dbName].owner
                $destDbName = $fileStructure.databases[$dbName].destinationDbName

                if ($null -eq $dbOwner) {
                    try {
                        $dbOwner = ($destServer.logins | Where-Object {
                                $_.id -eq 1
                            }).Name
                    } catch {
                        $dbOwner = "sa"
                    }
                }

                foreach ($file in $fileStructure.databases[$dbName].destination.values) {
                    $null = $destfilestructure.add($file.physical)
                }
                foreach ($file in $fileStructure.databases[$dbName].source.values) {
                    $null = $sourceFileStructure.add($file.physical)
                }

                $detachresult = Dismount-SqlDatabase $sourceServer $dbName

                if ($detachresult) {

                    $transfer = Start-SqlFileTransfer $fileStructure $dbName
                    if ($transfer -eq $false) {
                        Write-Message -Level Verbose -Message "Could not copy files."
                        return "Could not copy files."
                    }
                    $attachresult = Mount-SqlDatabase $destServer $destDbName $destfilestructure $dbOwner

                    if ($attachresult -eq $true) {
                        # add to added dbs because ATTACH was successful
                        Write-Message -Level Verbose -Message "Successfully attached $dbName to $destinstance."
                        return $true
                    } else {
                        # add to failed because ATTACH was unsuccessful
                        Write-Message -Level Verbose -Message "Could not attach $dbName."
                        return "Could not attach database."
                    }
                } else {
                    # add to failed because DETACH was unsuccessful
                    Write-Message -Level Verbose -Message "Could not detach $dbName."
                    return "Could not detach database."
                }
            }
        }
        $backupCollection = @()
    }
    process {
        if (Test-FunctionInterrupt) {
            return
        }

        # testing twice for whatif reasons
        if ($BackupRestore -and (-not $SharedPath -and -not $UseLastBackup)) {
            Stop-Function -Message "When using -BackupRestore, you must specify -SharedPath or -UseLastBackup"
            return
        }
        if ($SharedPath -and $UseLastBackup) {
            Stop-Function -Message "-SharedPath cannot be used with -UseLastBackup because the backup path is determined by the paths in the last backups"
            return
        }
        if ($DetachAttach -and -not $Reattach -and $Destination.Count -gt 1) {
            Stop-Function -Message "When using -DetachAttach with multiple servers, you must specify -Reattach to reattach database at source"
            return
        }
        if (($AllDatabases -or $IncludeSupportDbs -or $Database) -and !$DetachAttach -and !$BackupRestore) {
            Stop-Function -Message "You must specify -DetachAttach or -BackupRestore when migrating databases."
            return
        }

        if (-not $AllDatabases -and -not $IncludeSupportDbs -and -not $Database -and -not $InputObject) {
            Stop-Function -Message "You must specify a -AllDatabases or -Database to continue."
            return
        }

        if ((Test-Bound 'NewName') -and (Test-Bound 'Prefix')) {
            Stop-Function -Message "NewName and Prefix are exclusive options, cannot specify both"
            return
        }

        if ($InputObject) {
            $Source = $InputObject[0].Parent
            $Database = $InputObject.Name
        }


        if ($Database -contains "master" -or $Database -contains "msdb" -or $Database -contains "tempdb") {
            Stop-Function -Message "Migrating system databases is not currently supported." -Continue
        }

        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }

        Invoke-SmoCheck -SqlInstance $sourceServer
        $sourceNetBios = $sourceServer.ComputerName

        Write-Message -Level Verbose -Message "Ensuring user databases exist (counting databases)."

        if ($sourceserver.Databases.IsSystemObject -notcontains $false) {
            Stop-Function -Message "No user databases to migrate"
            return
        }

        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }

            if ($sourceServer.ComputerName -eq $destServer.ComputerName) {
                $script:sameserver = $true
            } else {
                $script:sameserver = $false
            }

            if ($script:sameserver -and $DetachAttach) {
                if (-not (Test-ElevationRequirement -ComputerName $sourceServer)) {
                    return
                }
            }

            $destVersionLower = $destServer.VersionMajor -lt $sourceServer.VersionMajor
            $destVersionMinorLow = ($destServer.VersionMajor -eq 10 -and $sourceServer.VersionMajor -eq 10) -and ($destServer.VersionMinor -lt $sourceServer.VersionMinor)

            if ($destVersionLower -or $destVersionMinorLow) {
                Stop-Function -Message "Error: copy database cannot be made from newer $($sourceServer.VersionString) to older $($destServer.VersionString) SQL Server version."
                return
            }

            if ($DetachAttach) {
                if ($sourceServer.ComputerName -eq $env:COMPUTERNAME -or $destServer.ComputerName -eq $env:COMPUTERNAME) {
                    if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
                        Write-Message -Level Verbose -Message "When running DetachAttach locally on the console, it's possible you'll need to Run As Administrator. Trying anyway."
                    }
                }
            }

            if ($SharedPath) {
                if ($(Test-DbaPath -SqlInstance $sourceServer -Path $SharedPath) -eq $false) {
                    Write-Message -Level Verbose -Message "$Source may not be able to access $SharedPath. Trying anyway."
                }

                if ($(Test-DbaPath -SqlInstance $destServer -Path $SharedPath) -eq $false) {
                    Write-Message -Level Verbose -Message "$destinstance may not be able to access $SharedPath. Trying anyway."
                }

                if ($SharedPath.StartsWith('\\')) {
                    try {
                        $shareServer = ($SharedPath -split "\\")[2]
                        $hostEntry = ([Net.Dns]::GetHostEntry($shareServer)).HostName -split "\."

                        if ($shareServer -ne $hostEntry[0]) {
                            Write-Message -Level Verbose -Message "Using CNAME records for the network share may present an issue if an SPN has not been created. Trying anyway. If it doesn't work, use a different (A record) hostname."
                        }
                    } catch {
                        Stop-Function -Message "Error validating unc path: $_"
                        return
                    }
                }
            }

            $destNetBios = $destserver.ComputerName

            Write-Message -Level Verbose -Message "Performing SMO version check."
            Invoke-SmoCheck -SqlInstance $destServer

            Write-Message -Level Verbose -Message "Checking to ensure the source isn't the same as the destination."
            if ($source -eq $destinstance) {
                Stop-Function -Message "Source and Destination SQL Servers instances are the same. Quitting." -Continue
            }

            Write-Message -Level Verbose -Message "Checking to ensure server is not SQL Server 7 or below."
            if ($sourceServer.VersionMajor -lt 8 -and $destServer.VersionMajor -lt 8) {
                Stop-Function -Message "This script can only be run on SQL Server 2000 and above. Quitting." -Continue
            }

            Write-Message -Level Verbose -Message "Checking to ensure detach/attach is not attempted on SQL Server 2000."
            if ($destServer.VersionMajor -lt 9 -and $DetachAttach) {
                Stop-Function -Message "Detach/Attach not supported when destination SQL Server is version 2000. Quitting." -Target $destServer -Continue
            }

            Write-Message -Level Verbose -Message "Checking to ensure SQL Server 2000 migration isn't directly attempted to SQL Server 2012."
            if ($sourceServer.VersionMajor -lt 9 -and $destServer.VersionMajor -gt 10) {
                Stop-Function -Message "SQL Server 2000 databases cannot be migrated to SQL Server versions 2012 and above. Quitting." -Target $destServer -Continue
            }

            Write-Message -Level Verbose -Message "Warning if migration from 2005 to 2012 and above and attach/detach is used."
            if ($sourceServer.VersionMajor -eq 9 -and $destServer.VersionMajor -gt 9 -and !$BackupRestore -and !$Force -and $DetachAttach) {
                Stop-Function -Message "Backup and restore is the safest method for migrating from SQL Server 2005 to other SQL Server versions. Please use the -BackupRestore switch or override this requirement by specifying -Force." -Continue
            }

            if ($sourceServer.Collation -ne $destServer.Collation) {
                Write-Message -Level Verbose -Message "Warning on different collation."
                Write-Message -Level Verbose -Message "Collation on $Source, $($sourceServer.Collation) differs from the $destinstance, $($destServer.Collation)."
            }

            Write-Message -Level Verbose -Message "Ensuring destination server version is equal to or greater than source."
            if ($sourceServer.VersionMajor -ge $destServer.VersionMajor) {
                if ($sourceServer.VersionMinor -gt $destServer.VersionMinor) {
                    Stop-Function -Message "Source SQL Server version build must be <= destination SQL Server for database migration." -Continue
                }
            }

            # SMO's filestreamlevel is sometimes null
            $sql = "select coalesce(SERVERPROPERTY('FilestreamConfiguredLevel'),0) as fs"
            $sourceFilestream = $sourceServer.ConnectionContext.ExecuteScalar($sql)
            $destFilestream = $destServer.ConnectionContext.ExecuteScalar($sql)
            if ($sourceFilestream -gt 0 -and $destFilestream -eq 0) {
                $fsWarning = $true
            }

            Write-Message -Level Verbose -Message "Writing warning about filestream being enabled."
            if ($fsWarning) {
                Write-Message -Level Verbose -Message "FILESTREAM enabled on $source but not $destinstance. Databases that use FILESTREAM will be skipped."
            }

            if ($DetachAttach -eq $true) {
                Write-Message -Level Verbose -Message "Checking access to remote directories."
                $remoteSourcePath = Join-AdminUNC $sourceNetBios (Get-SqlDefaultPaths -SqlInstance $sourceServer -filetype data)

                if ((Test-Path $remoteSourcePath) -ne $true -and $DetachAttach) {
                    Write-Message -Level Warning -Message "Can't access remote Sql directories on $source which is required to perform detach/copy/attach."
                    Write-Message -Level Warning -Message "You can manually try accessing $remoteSourcePath to diagnose any issues."
                    Stop-Function -Message "Halting database migration"
                    return
                }

                $remoteDestPath = Join-AdminUNC $destNetBios (Get-SqlDefaultPaths -SqlInstance $destServer -filetype data)
                If ((Test-Path $remoteDestPath) -ne $true -and $DetachAttach) {
                    Write-Message -Level Warning -Message "Can't access remote Sql directories on $destinstance which is required to perform detach/copy/attach."
                    Write-Message -Level Warning -Message "You can manually try accessing $remoteDestPath to diagnose any issues."
                    Stop-Function -Message "Halting database migration" -Continue
                }
            }

            if (($Database -or $ExcludeDatabase -or $IncludeSupportDbs) -and (!$DetachAttach -and !$BackupRestore)) {
                Stop-Function -Message "You did not select a migration method. Please use -BackupRestore or -DetachAttach."
                return
            }

            if ((!$Database -and !$AllDatabases -and !$IncludeSupportDbs) -and ($DetachAttach -or $BackupRestore)) {
                Stop-Function -Message "You did not select any databases to migrate. Please use -AllDatabases or -Database or -IncludeSupportDbs."
                return
            }

            Write-Message -Level Verbose -Message "Building database list."
            $databaseList = New-Object System.Collections.ArrayList
            $SupportDBs = "ReportServer", "ReportServerTempDB", "distribution"
            foreach ($currentdb in ($sourceServer.Databases | Where-Object IsAccessible)) {
                $dbName = $currentdb.Name
                $dbOwner = $currentdb.Owner

                if ($currentdb.Id -le 4) {
                    continue
                }
                if ($Database -and $Database -notcontains $dbName) {
                    continue
                }
                if ($IncludeSupportDBs -eq $false -and $SupportDBs -contains $dbName) {
                    continue
                }
                if ($IncludeSupportDBs -eq $true -and $SupportDBs -notcontains $dbName) {
                    if ($AllDatabases -eq $false -and $Database.length -eq 0) {
                        continue
                    }
                }
                $null = $databaseList.Add($currentdb)
            }

            Write-Message -Level Verbose -Message "Performing count."
            $dbCount = $databaseList.Count

            if ((Test-Bound 'NewName') -and $dbCount -gt 1) {
                Stop-Function -Message "Cannot use NewName when copying multiple databases"
                return
            }


            Write-Message -Level Verbose -Message "Building file structure inventory for $dbCount databases."

            if ($sourceServer.VersionMajor -eq 8) {
                $sql = "select DB_NAME (dbid) as dbname, name, filename, CASE WHEN groupid = 0 THEN 'LOG' ELSE 'ROWS' END as filetype from sysaltfiles"
            } else {
                $sql = "SELECT db.Name AS dbname, type_desc AS FileType, mf.Name, Physical_Name AS filename FROM sys.master_files mf INNER JOIN  sys.databases db ON db.database_id = mf.database_id"
            }

            $dbFileTable = $sourceServer.Databases['master'].ExecuteWithResults($sql)

            if ($destServer.VersionMajor -eq 8) {
                $sql = "select DB_NAME (dbid) as dbname, name, filename, CASE WHEN groupid = 0 THEN 'LOG' ELSE 'ROWS' END as filetype from sysaltfiles"
            } else {
                $sql = "SELECT db.Name AS dbname, type_desc AS FileType, mf.Name, Physical_Name AS filename FROM sys.master_files mf INNER JOIN  sys.databases db ON db.database_id = mf.database_id"
            }

            $remoteDbFileTable = $destServer.Databases['master'].ExecuteWithResults($sql)

            $fileStructure = Get-SqlFileStructure -sourceserver $sourceServer -destserver $destServer -databaselist $databaseList -ReuseSourceFolderStructure $ReuseSourceFolderStructure

            $elapsed = [System.Diagnostics.Stopwatch]::StartNew()
            $started = Get-Date
            $script:TimeNow = (Get-Date -UFormat "%m%d%Y%H%M%S")

            if ($AllDatabases -or $ExcludeDatabase -or $IncludeSupportDbs -or $Database) {
                foreach ($currentdb in $databaseList) {
                    $dbName = $currentdb.Name
                    $dbOwner = $currentdb.Owner
                    $destinationDbName = $dbName
                    if ((Test-Bound "NewName")) {
                        Write-Message -Level Verbose -Message "NewName specified, copying $dbname as $NewName"
                        $destinationDbName = $NewName
                        $replaceInFile = $True
                    }
                    if ($(Test-Bound "Prefix")) {
                        $destinationDbName = $prefix + $destinationDbName
                        Write-Message -Level Verbose -Message "Prefix supplied, copying $dbname as $destinationDbName"
                    }

                    $filestructure.databases[$dbname].Add('destinationDbName', $destinationDbName)
                    ForEach ($key in $filestructure.databases[$dbname].Destination.Keys) {
                        $splitFileName = Split-Path $fileStructure.databases[$dbname].Destination[$key].remotefilename -Leaf
                        $SplitPath = Split-Path $fileStructure.databases[$dbname].Destination[$key].remotefilename
                        if ($replaceInFile) {
                            $splitFileName = $splitFileName.replace($dbname, $destinationDbName)
                        }
                        $splitFileName = $prefix + $splitFileName
                        $filestructure.databases[$dbname].Destination.$key.remotefilename = Join-Path $SplitPath $splitFileName
                        $splitFileName = Split-Path $filestructure.databases[$dbname].Destination[$key].physical -Leaf
                        $SplitPath = Split-Path $fileStructure.databases[$dbname].Destination[$key].physical
                        if ($replaceInFile) {
                            $splitFileName = $splitFileName.replace($dbname, $destinationDbName)
                        }
                        $splitFileName = $prefix + $splitFileName
                        $filestructure.databases[$dbname].Destination.$key.physical = Join-Path $SplitPath $splitFileName
                    }

                    $copyDatabaseStatus = [pscustomobject]@{
                        SourceServer        = $sourceServer.Name
                        DestinationServer   = $destServer.Name
                        Name                = $dbName
                        DestinationDatabase = $DestinationDbname
                        Type                = "Database"
                        Status              = $null
                        Notes               = $null
                        DateTime            = [DbaDateTime](Get-Date)
                    }

                    Write-Message -Level Verbose -Message "`n######### Database: $dbName #########"
                    $dbStart = Get-Date

                    if ($ExcludeDatabase -contains $dbName) {
                        Write-Message -Level Verbose -Message "$dbName excluded. Skipping."
                        continue
                    }

                    Write-Message -Level Verbose -Message "Checking for accessibility."
                    if ($currentdb.IsAccessible -eq $false) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Skipping $dbName. Database is inaccessible.")) {
                            Write-Message -Level Verbose -Message "Skipping $dbName. Database is inaccessible."

                            $copyDatabaseStatus.Status = "Skipped"
                            $copyDatabaseStatus.Notes = "Database is not accessible"
                            $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        }
                        continue
                    }

                    if ($fsWarning) {
                        $fsRows = $dbFileTable.Tables[0].Select("dbname = '$dbName' and FileType = 'FileStream'")

                        if ($fsRows.Count -gt 0) {
                            if ($Pscmdlet.ShouldProcess($destinstance, "Skipping $dbName (contains FILESTREAM).")) {
                                Write-Message -Level Verbose -Message "Skipping $dbName (contains FILESTREAM)."
                                $copyDatabaseStatus.Status = "Skipped"
                                $copyDatabaseStatus.Notes = "Contains FILESTREAM"
                                $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            }
                            continue
                        }
                    }

                    if ($ReuseSourceFolderStructure) {
                        $fgRows = $dbFileTable.Tables[0].Select("dbname = '$dbName' and FileType = 'ROWS'")[0]
                        $remotePath = Split-Path $fgRows.Filename

                        if (!(Test-DbaPath -SqlInstance $destServer -Path $remotePath)) {
                            if ($Pscmdlet.ShouldProcess($destinstance, "$remotePath does not exist on $destinstance and ReuseSourceFolderStructure was specified")) {
                                # Stop-Function -Message "Cannot resolve $remotePath on $source. `n`nYou have specified ReuseSourceFolderStructure and exact folder structure does not exist. Halting script."
                                $copyDatabaseStatus.Status = "Failed"
                                $copyDatabaseStatus.Notes = "$remotePath does not exist on $destinstance and ReuseSourceFolderStructure was specified" #"Can't resolve $remotePath"
                                $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            }
                            continue
                        }
                    }

                    Write-Message -Level Verbose -Message "Checking Availability Group status."
                    if ($currentdb.AvailabilityGroupName -and !$force -and $DetachAttach) {
                        $agName = $currentdb.AvailabilityGroupName
                        Write-Message -Level Verbose -Message "Database is part of an Availability Group ($agName). Use -Force to drop from $agName and migrate. Alternatively, you can use the safer backup/restore method."
                        continue
                    }

                    $dbStatus = $currentdb.Status.ToString()

                    if ($dbStatus.StartsWith("Normal") -eq $false) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "$dbName is not in a Normal state. Skipping.")) {
                            Write-Message -Level Verbose -Message "$dbName is not in a Normal state. Skipping."

                            $copyDatabaseStatus.Status = "Skipped"
                            $copyDatabaseStatus.Notes = "Not in normal state"
                            $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        }
                        continue
                    }

                    if ($currentdb.ReplicationOptions -ne "None" -and $DetachAttach -eq $true) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "$dbName is part of replication. Skipping.")) {
                            Write-Message -Level Verbose -Message "$dbName is part of replication. Skipping."

                            $copyDatabaseStatus.Status = "Skipped"
                            $copyDatabaseStatus.Notes = "Part of replication"
                            $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        }
                        continue
                    }

                    if ($currentdb.IsMirroringEnabled -and !$force -and $DetachAttach) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Database is being mirrored. Use -Force to break mirror and migrate. Alternatively, you can use the safer backup/restore method.")) {
                            Write-Message -Level Verbose -Message "Database is being mirrored. Use -Force to break mirror and migrate. Alternatively, you can use the safer backup/restore method."

                            $copyDatabaseStatus.Status = "Skipped"
                            $copyDatabaseStatus.Notes = "Database is mirrored"
                            $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        }

                        continue
                    }

                    if (($null -ne $destServer.Databases[$DestinationdbName]) -and !$force -and !$WithReplace) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "$DestinationdbName exists at destination. Use -Force to drop and migrate. Aborting routine for this database.")) {
                            Write-Message -Level Verbose -Message "$DestinationdbName exists at destination. Use -Force to drop and migrate. Aborting routine for this database."

                            $copyDatabaseStatus.Status = "Skipped"
                            $copyDatabaseStatus.Notes = "Already exists on destination"
                            $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        }
                        continue
                    } elseif ($null -ne $destServer.Databases[$DestinationdbName] -and $force) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "DROP DATABASE $DestinationdbName")) {
                            Write-Message -Level Verbose -Message "$DestinationdbName already exists. -Force was specified. Dropping $DestinationdbName on $destinstance."
                            $removeresult = Remove-DbaDatabase -SqlInstance $destserver -Database $DestinationdbName -Confirm:$false
                            $dropResult = $removeresult.Status -eq 'Dropped'

                            if ($dropResult -eq $false) {
                                Write-Message -Level Verbose -Message "Database could not be dropped. Aborting routine for this database."

                                $copyDatabaseStatus.Status = "Failed"
                                $copyDatabaseStatus.Notes = "Could not drop database"
                                $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                continue
                            }
                        }
                    }

                    if ($force) {
                        $WithReplace = $true
                    }

                    Write-Message -Level Verbose -Message "Started: $dbStart."

                    if ($sourceServer.VersionMajor -ge 9) {
                        $sourceDbOwnerChaining = $sourceServer.Databases[$dbName].DatabaseOwnershipChaining
                        $sourceDbTrustworthy = $sourceServer.Databases[$dbName].Trustworthy
                        $sourceDbBrokerEnabled = $sourceServer.Databases[$dbName].BrokerEnabled
                    }

                    $sourceDbReadOnly = $sourceServer.Databases[$dbName].ReadOnly

                    if ($SetSourceReadOnly) {
                        If ($Pscmdlet.ShouldProcess($source, "Set $dbName to read-only")) {
                            Write-Message -Level Verbose -Message "Setting database to read-only."
                            try {
                                $result = Set-DbaDbState -SqlInstance $sourceServer -Database $dbName -ReadOnly -EnableException
                            } catch {
                                Stop-Function -Continue -Message "Couldn't set database to read-only. Aborting routine for this database" -ErrorRecord $_
                            }
                        }
                    }

                    if ($BackupRestore) {
                        if ($UseLastBackup) {
                            $whatifmsg = "Gathering last backup information for $dbName from $Source and restoring"
                        } else {
                            $whatifmsg = "Backup $dbName from $source and restoring"
                        }
                        If ($Pscmdlet.ShouldProcess($destinstance, $whatifmsg)) {
                            if ($UseLastBackup) {
                                $backupTmpResult = Get-DbaBackupHistory -SqlInstance $sourceServer -Database $dbName -IncludeCopyOnly -Last
                                if (-not $backupTmpResult) {
                                    $copyDatabaseStatus.Type = "Database (BackupRestore)"
                                    $copyDatabaseStatus.Status = "Failed"
                                    $copyDatabaseStatus.Notes = "No backups for $dbName on $source"
                                    $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                    continue
                                }
                            } else {
                                $backupTmpResult = $backupCollection | Where-Object Database -eq $dbName
                                if (-not $backupTmpResult) {
                                    $backupTmpResult = Backup-DbaDatabase -SqlInstance $sourceServer -Database $dbName -BackupDirectory $SharedPath -FileCount $numberfiles -CopyOnly:$CopyOnly
                                }
                                if ($backupTmpResult) {
                                    $backupCollection += $backupTmpResult
                                }
                                $backupResult = $BackupTmpResult.BackupComplete
                                if (-not $backupResult) {
                                    $serviceAccount = $sourceServer.ServiceAccount
                                    Write-Message -Level Verbose -Message "Backup Failed. Does SQL Server account $serviceAccount have access to $($SharedPath)? Aborting routine for this database."

                                    $copyDatabaseStatus.Status = "Failed"
                                    $copyDatabaseStatus.Notes = "Backup failed. Verify service account access to $SharedPath."
                                    $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                    continue
                                }
                            }
                            Write-Message -Level Verbose -Message "Reuse = $ReuseSourceFolderStructure."
                            try {
                                $msg = $null
                                $restoreResultTmp = $backupTmpResult | Restore-DbaDatabase -SqlInstance $destServer -DatabaseName $DestinationdbName -ReuseSourceFolderStructure:$ReuseSourceFolderStructure -NoRecovery:$NoRecovery -TrustDbBackupHistory -WithReplace:$WithReplace -Continue:$Continue -EnableException -ReplaceDbNameInFile
                            } catch {
                                $msg = $_.Exception.InnerException.InnerException.InnerException.InnerException.Message
                                Stop-Function -Message "Failure attempting to restore $dbName to $destinstance" -Exception $_.Exception.InnerException.InnerException.InnerException.InnerException
                            }
                            $restoreResult = $restoreResultTmp.RestoreComplete

                            if ($restoreResult -eq $true) {
                                Write-Message -Level Verbose -Message "Successfully restored $dbName to $destinstance."
                                $copyDatabaseStatus.Status = "Successful"
                                $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            } else {
                                if ($ReuseSourceFolderStructure) {
                                    Write-Message -Level Verbose -Message "Failed to restore $dbName to $destinstance. You specified -ReuseSourceFolderStructure. Does the exact same destination directory structure exist?"
                                    Write-Message -Level Verbose -Message "Aborting routine for this database."

                                    $copyDatabaseStatus.Status = "Failed"
                                    $copyDatabaseStatus.Notes = "Failed to restore. ReuseSourceFolderStructure was specified, verify same directory structure exist on destination."
                                    $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                    continue
                                } else {
                                    Write-Message -Level Verbose -Message "Failed to restore $dbName to $destinstance. Aborting routine for this database."

                                    $copyDatabaseStatus.Status = "Failed"
                                    if (-not $msg) {
                                        $msg = "Failed to restore database"
                                    }
                                    $copyDatabaseStatus.Notes = $msg
                                    $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                    continue
                                }
                            }
                            if (-not $NoBackupCleanUp -and $Destination.Count -eq 1) {
                                foreach ($backupFile in ($backupTmpResult.BackupPath)) {
                                    try {
                                        if (Test-Path $backupFile -ErrorAction Stop) {
                                            Write-Message -Level Verbose -Message "Deleting $backupFile."
                                            Remove-Item $backupFile -ErrorAction Stop
                                        }
                                    } catch {
                                        try {
                                            Write-Message -Level Verbose -Message "Trying alternate SQL method to delete $backupFile."
                                            $sql = "EXEC master.sys.xp_delete_file 0, '$backupFile'"
                                            Write-Message -Level Debug -Message $sql
                                            $null = $sourceServer.Query($sql)
                                        } catch {
                                            Write-Message -Level Verbose -Message "Cannot delete backup file $backupFile."

                                            # Set NoBackupCleanup so that there's a warning at the end
                                            $NoBackupCleanup = $true
                                        }
                                    }
                                }
                            }
                        }

                        $dbFinish = Get-Date
                        if ($NoRecovery -eq $false) {
                            # needed because the newly restored database doesn't show up
                            $destServer.Databases.Refresh()
                            $dbOwner = $sourceServer.Databases[$dbName].Owner
                            if ($null -eq $dbOwner -or $destServer.Logins.Name -notcontains $dbOwner) {
                                $dbOwner = Get-SaLoginName -SqlInstance $destServer
                            }
                            Write-Message -Level Verbose -Message "Updating database owner to $dbOwner."
                            $OwnerResult = Set-DbaDbOwner -SqlInstance $destServer -Database $dbName -TargetLogin $dbOwner -EnableException
                            if ($OwnerResult.Length -eq 0) {
                                Write-Message -Level Verbose -Message "Failed to update database owner."
                            }
                        }
                    }

                    if ($DetachAttach) {

                        $copyDatabaseStatus.Type = "Database (DetachAttach)"

                        $sourceFileStructure = New-Object System.Collections.Specialized.StringCollection
                        foreach ($file in $fileStructure.Databases[$dbName].Source.Values) {
                            $null = $sourceFileStructure.Add($file.Physical)
                        }

                        $dbOwner = $sourceServer.Databases[$dbName].Owner

                        if ($null -eq $dbOwner -or $destServer.Logins.Name -notcontains $dbOwner) {
                            $dbOwner = Get-SaLoginName -SqlInstance $destServer
                        }

                        if ($Pscmdlet.ShouldProcess($destinstance, "Detach $dbName from $source and attach, then update dbowner")) {
                            $migrationResult = Start-SqlDetachAttach $sourceServer $destServer $fileStructure $dbName

                            $dbFinish = Get-Date

                            if ($reattach -eq $true) {
                                $sourceServer.Databases.Refresh()
                                $destServer.Databases.Refresh()
                                $result = Mount-SqlDatabase $sourceServer $dbName $sourceFileStructure $dbOwner

                                if ($result -eq $true) {
                                    $sourceServer.Databases[$dbName].DatabaseOwnershipChaining = $sourceDbOwnerChaining
                                    $sourceServer.Databases[$dbName].Trustworthy = $sourceDbTrustworthy
                                    $sourceServer.Databases[$dbName].BrokerEnabled = $sourceDbBrokerEnabled
                                    $sourceServer.Databases[$dbName].Alter()

                                    if ($SetSourceReadOnly -or $sourceDbReadOnly) {
                                        try {
                                            $result = Set-DbaDbState -SqlInstance $sourceServer -Database $dbName -ReadOnly -EnableException
                                        } catch {
                                            Stop-Function -Message "Couldn't set database to read-only" -ErrorRecord $_
                                        }
                                    }
                                    Write-Message -Level Verbose -Message "Successfully reattached $dbName to $source."
                                } else {
                                    Write-Message -Level Verbose -Message "Could not reattach $dbName to $source."
                                    $copyDatabaseStatus.Status = "Failed"
                                    $copyDatabaseStatus.Notes = "Could not reattach database to $source"
                                    $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                }
                            }

                            if ($migrationResult -eq $true) {
                                Write-Message -Level Verbose -Message "Successfully attached $dbName to $destinstance."
                                $copyDatabaseStatus.Status = "Successful"
                                $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            } else {
                                Write-Message -Level Verbose -Message "Failed to attach $dbName to $destinstance. Aborting routine for this database."

                                $copyDatabaseStatus.Status = "Failed"
                                $copyDatabaseStatus.Notes = "Failed to attach database to destination"
                                $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                                continue
                            }
                        }
                    }
                    $NewDatabase = Get-DbaDatabase -SqlInstance $destServer -database $DestinationdbName

                    # restore potentially lost settings
                    if ($destServer.VersionMajor -ge 9 -and $NoRecovery -eq $false) {
                        if ($sourceDbOwnerChaining -ne $NewDatabase.DatabaseOwnershipChaining) {
                            if ($Pscmdlet.ShouldProcess($destinstance, "Updating DatabaseOwnershipChaining on $DestinationdbName")) {
                                try {
                                    $NewDatabase.DatabaseOwnershipChaining = $sourceDbOwnerChaining
                                    $NewDatabase.Alter()
                                    Write-Message -Level Verbose -Message "Successfully updated DatabaseOwnershipChaining for $sourceDbOwnerChaining on $DestinationdbName on $destinstance."
                                } catch {
                                    $copyDatabaseStatus.Status = "Successful - failed to apply DatabaseOwnershipChaining."
                                    $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                    Stop-Function -Message "Failed to update DatabaseOwnershipChaining for $sourceDbOwnerChaining on $DestinationdbName on $destinstance." -Target $destinstance -ErrorRecord $_ -Continue
                                }
                            }
                        }

                        if ($sourceDbTrustworthy -ne $NewDatabase.Trustworthy) {
                            if ($Pscmdlet.ShouldProcess($destinstance, "Updating Trustworthy on $DestinationdbName")) {
                                try {
                                    $NewDatabase.Trustworthy = $sourceDbTrustworthy
                                    $NewDatabase.Alter()
                                    Write-Message -Level Verbose -Message "Successfully updated Trustworthy to $sourceDbTrustworthy for $DestinationdbName on $destinstance"
                                } catch {
                                    $copyDatabaseStatus.Status = "Successful - failed to apply Trustworthy"
                                    $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                    Stop-Function -Message "Failed to update Trustworthy to $sourceDbTrustworthy for $DestinationdbName on $destinstance." -Target $destinstance -ErrorRecord $_ -Continue
                                }
                            }
                        }

                        if ($sourceDbBrokerEnabled -ne $NewDatabase.BrokerEnabled) {
                            if ($Pscmdlet.ShouldProcess($destinstance, "Updating BrokerEnabled on $dbName")) {
                                try {
                                    $NewDatabase.BrokerEnabled = $sourceDbBrokerEnabled
                                    $NewDatabase.Alter()
                                    Write-Message -Level Verbose -Message "Successfully updated BrokerEnabled to $sourceDbBrokerEnabled for $DestinationdbName on $destinstance."
                                } catch {
                                    $copyDatabaseStatus.Status = "Successful - failed to apply BrokerEnabled"
                                    $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                    Stop-Function -Message "Failed to update BrokerEnabled to $sourceDbBrokerEnabled for $DestinationdbName on $destinstance." -Target $destinstance -ErrorRecord $_ -Continue
                                }
                            }
                        }
                    }

                    if ($sourceDbReadOnly -ne $NewDatabase.ReadOnly -and -not $NoRecovery) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Updating ReadOnly status on $DestinationdbName")) {
                            try {
                                if ($sourceDbReadOnly) {
                                    $result = Set-DbaDbState -SqlInstance $destserver -Database $DestinationdbName -ReadOnly -EnableException
                                } else {
                                    $result = Set-DbaDbState -SqlInstance $destserver -Database $DestinationdbName -ReadWrite -EnableException
                                }
                            } catch {
                                $copyDatabaseStatus.Status = "Successful - failed to apply ReadOnly."
                                $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                Stop-Function -Message "Failed to update ReadOnly status on $DestinationdbName." -Target $destinstance -ErrorRecord $_ -Continue
                            }
                        }
                    }

                    if ($SetSourceOffline -and $sourceServer.databases[$DestinationdbName].status -notlike '*offline*') {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Setting $DestinationdbName offline on $source")) {
                            Stop-DbaProcess -SqlInstance $sourceServer -Database $DestinationdbName
                            Set-DbaDbState -SqlInstance $sourceServer -SqlCredential $SourceSqlCredential -database $DestinationdbName -Offline
                        }
                    }

                    $dbTotalTime = $dbFinish - $dbStart
                    $dbTotalTime = ($dbTotalTime.ToString().Split(".")[0])

                    Write-Message -Level Verbose -Message "Finished: $dbFinish."
                    Write-Message -Level Verbose -Message "Elapsed time: $dbTotalTime."

                } # end db by db processing
            }
        }
    }
    end {
        if (Test-FunctionInterrupt) {
            return
        }
        if (-not $NoBackupCleanUp -and $Destination.Count -gt 1) {
            foreach ($backupFile in ($backupCollection.BackupPath)) {
                try {
                    if (Test-Path $backupFile -ErrorAction Stop) {
                        Write-Message -Level Verbose -Message "Deleting $backupFile."
                        Remove-Item $backupFile -ErrorAction Stop
                    }
                } catch {
                    try {
                        Write-Message -Level Verbose -Message "Trying alternate SQL method to delete $backupFile."
                        $sql = "EXEC master.sys.xp_delete_file 0, '$backupFile'"
                        Write-Message -Level Debug -Message $sql
                        $null = $sourceServer.Query($sql)
                    } catch {
                        Write-Message -Level Verbose -Message "Cannot delete backup file $backupFile."
                    }
                }
            }
        }
        if (Test-FunctionInterrupt) {
            return
        }
        if ($null -ne $elapsed) {
            $totalTime = ($elapsed.Elapsed.toString().Split(".")[0])

            Write-Message -Level Verbose -Message "`nDatabase migration finished"
            Write-Message -Level Verbose -Message "Migration started: $started"
            Write-Message -Level Verbose -Message "Migration completed: $(Get-Date)"
            Write-Message -Level Verbose -Message "Total Elapsed time: $totalTime"

            if ($SharedPath -and $NoBackupCleanup) {
                Write-Message -Level Verbose -Message "Backups still exist at $SharedPath."
            }
        } else {
            Write-Message -Level Verbose -Message "No work was done, as we stopped during setup phase"
        }
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlDatabase
    }
}
tools\dbatools\functions\Copy-DbaDataCollector.ps1
function Copy-DbaDataCollector {
    <#
    .SYNOPSIS
        Migrates user SQL Data Collector collection sets. SQL Data Collector configuration is on the agenda, but it's hard.

    .DESCRIPTION
        By default, all data collector objects are migrated. If the object already exists on the destination, it will be skipped unless -Force is used.

        The -CollectionSet parameter is auto-populated for command-line completion and can be used to copy only specific objects.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2008 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination Sql Server. You must have sysadmin access and server version must be SQL Server version 2008 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER CollectionSet
        The collection set(s) to process - this list is auto-populated from the server. If unspecified, all collection sets will be processed.

    .PARAMETER ExcludeCollectionSet
        The collection set(s) to exclude - this list is auto-populated from the server

    .PARAMETER NoServerReconfig
        Upcoming parameter to enable server reconfiguration

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER Force
        If collection sets exists on destination server, it will be dropped and recreated.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration,DataCollection
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        https://dbatools.io/Copy-DbaDataCollector

    .EXAMPLE
        PS C:\> Copy-DbaDataCollector -Source sqlserver2014a -Destination sqlcluster

        Copies all Data Collector Objects and Configurations from sqlserver2014a to sqlcluster, using Windows credentials.

    .EXAMPLE
        PS C:\> Copy-DbaDataCollector -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred

        Copies all Data Collector Objects and Configurations from sqlserver2014a to sqlcluster, using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster.

    .EXAMPLE
        PS C:\> Copy-DbaDataCollector -Source sqlserver2014a -Destination sqlcluster -WhatIf

        Shows what would happen if the command were executed.

    .EXAMPLE
        PS C:\> Copy-DbaDataCollector -Source sqlserver2014a -Destination sqlcluster -CollectionSet 'Server Activity', 'Table Usage Analysis'

        Copies two Collection Sets, Server Activity and Table Usage Analysis, from sqlserver2014a to sqlcluster.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]
        $SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]
        $DestinationSqlCredential,
        [object[]]$CollectionSet,
        [object[]]$ExcludeCollectionSet,
        [switch]$NoServerReconfig,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        if (-not $script:isWindows) {
            Stop-Function -Message "Copy-DbaDataCollector does not support Linux - we're still waiting for the Core SMOs from Microsoft"
            return
        }
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential -MinimumVersion 10
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }
        $sourceSqlConn = $sourceServer.ConnectionContext.SqlConnectionObject
        $sourceSqlStoreConnection = New-Object Microsoft.SqlServer.Management.Sdk.Sfc.SqlStoreConnection $sourceSqlConn
        $sourceStore = New-Object Microsoft.SqlServer.Management.Collector.CollectorConfigStore $sourceSqlStoreConnection
        $configDb = $sourceStore.ScriptAlter().GetScript() | Out-String
        $configDb = $configDb -replace [Regex]::Escape("'$source'"), "'$destReplace'"
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {

            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }
            if ($NoServerReconfig -eq $false) {
                if ($Pscmdlet.ShouldProcess($destinstance, "Server reconfiguration not yet supported. Only Collection Set migration will be migrated at this time.")) {
                    Write-Message -Level Verbose -Message "Server reconfiguration not yet supported. Only Collection Set migration will be migrated at this time."
                    $NoServerReconfig = $true

                    <# for future use when this support is added #>
                    $copyServerConfigStatus = [pscustomobject]@{
                        SourceServer      = $sourceServer.Name
                        DestinationServer = $destServer.Name
                        Name              = $userName
                        Type              = "Data Collection Server Config"
                        Status            = "Skipped"
                        Notes             = "Not supported at this time"
                        DateTime          = [DbaDateTime](Get-Date)
                    }
                    $copyServerConfigStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                }
            }
            $destSqlConn = $destServer.ConnectionContext.SqlConnectionObject
            $destSqlStoreConnection = New-Object Microsoft.SqlServer.Management.Sdk.Sfc.SqlStoreConnection $destSqlConn
            $destStore = New-Object Microsoft.SqlServer.Management.Collector.CollectorConfigStore $destSqlStoreConnection

            if (!$NoServerReconfig) {
                if ($Pscmdlet.ShouldProcess($destinstance, "Attempting to modify Data Collector configuration")) {
                    try {
                        $sql = "Unknown at this time"
                        $destServer.Query($sql)
                        $destStore.Alter()
                    } catch {
                        $copyServerConfigStatus.Status = "Failed"
                        $copyServerConfigStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        Stop-Function -Message "Issue modifying Data Collector configuration" -Target $destServer -ErrorRecord $_
                    }
                }
            }

            if ($destStore.Enabled -eq $false) {
                Write-Message -Level Verbose -Message "The Data Collector must be setup initially for Collection Sets to be migrated. Setup the Data Collector and try again."
                continue
            }

            $storeCollectionSets = $sourceStore.CollectionSets | Where-Object { $_.IsSystem -eq $false }
            if ($CollectionSet) {
                $storeCollectionSets = $storeCollectionSets | Where-Object Name -In $CollectionSet
            }
            if ($ExcludeCollectionSet) {
                $storeCollectionSets = $storeCollectionSets | Where-Object Name -NotIn $ExcludeCollectionSet
            }

            Write-Message -Level Verbose -Message "Migrating collection sets"
            foreach ($set in $storeCollectionSets) {
                $collectionName = $set.Name

                $copyCollectionSetStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Name              = $collectionName
                    Type              = "Collection Set"
                    Status            = $null
                    Notes             = $null
                    DateTime          = [DbaDateTime](Get-Date)
                }

                if ($null -ne $destStore.CollectionSets[$collectionName]) {
                    if ($force -eq $false) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Collection Set '$collectionName' was skipped because it already exists on $destinstance. Use -Force to drop and recreate")) {
                            Write-Message -Level Verbose -Message "Collection Set '$collectionName' was skipped because it already exists on $destinstance. Use -Force to drop and recreate"

                            $copyCollectionSetStatus.Status = "Skipped"
                            $copyCollectionSetStatus.Notes = "Already exists on destination"
                            $copyCollectionSetStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        }
                        continue
                    } else {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Attempting to drop $collectionName")) {
                            Write-Message -Level Verbose -Message "Collection Set '$collectionName' exists on $destinstance"
                            Write-Message -Level Verbose -Message "Force specified. Dropping $collectionName."

                            try {
                                $destStore.CollectionSets[$collectionName].Drop()
                            } catch {
                                $copyCollectionSetStatus.Status = "Failed to drop on destination"
                                $copyCollectionSetStatus.Notes = (Get-ErrorMessage -Record $_)
                                $copyCollectionSetStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                Stop-Function -Message "Issue dropping collection" -Target $collectionName -ErrorRecord $_ -Continue
                            }
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destinstance, "Migrating collection set $collectionName")) {
                    try {
                        $sql = $set.ScriptCreate().GetScript() | Out-String
                        $sql = $sql -replace [Regex]::Escape("'$source'"), "'$destinstance'"
                        Write-Message -Level Debug -Message $sql
                        Write-Message -Level Verbose -Message "Migrating collection set $collectionName"
                        $destServer.Query($sql)

                        $copyCollectionSetStatus.Status = "Successful"
                        $copyCollectionSetStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    } catch {
                        $copyCollectionSetStatus.Status = "Failed to create collection"
                        $copyCollectionSetStatus.Notes = (Get-ErrorMessage -Record $_)

                        Stop-Function -Message "Issue creating collection set" -Target $collectionName -ErrorRecord $_
                    }

                    try {
                        if ($set.IsRunning) {
                            Write-Message -Level Verbose -Message "Starting collection set $collectionName"
                            $destStore.CollectionSets.Refresh()
                            $destStore.CollectionSets[$collectionName].Start()
                        }

                        $copyCollectionSetStatus.Status = "Successful started Collection"
                        $copyCollectionSetStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    } catch {
                        $copyCollectionSetStatus.Status = "Failed to start collection"
                        $copyCollectionSetStatus.Notes = (Get-ErrorMessage -Record $_)
                        $copyCollectionSetStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        Stop-Function -Message "Issue starting collection set" -Target $collectionName -ErrorRecord $_
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlDataCollector
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-DbaSqlDataCollector
        if (Test-FunctionInterrupt) { return }
    }
}
tools\dbatools\functions\Copy-DbaDbAssembly.ps1
function Copy-DbaDbAssembly {
    <#
    .SYNOPSIS
        Copy-DbaDbAssembly migrates assemblies from one SQL Server to another.

    .DESCRIPTION
        By default, all assemblies are copied.

        If the assembly already exists on the destination, it will be skipped unless -Force is used.

        This script does not yet copy dependencies or dependent objects.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Assembly
        The assembly(ies) to process. This list is auto-populated from the server. If unspecified, all assemblies will be processed.

    .PARAMETER ExcludeAssembly
        The assembly(ies) to exclude. This list is auto-populated from the server.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER Force
        If this switch is enabled, existing assemblies on Destination with matching names from Source will be dropped.

    .NOTES
        Tags: Migration, Assembly
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        http://dbatools.io/Get-SqlDatabaseAssembly

    .EXAMPLE
        PS C:\> Copy-DbaDbAssembly -Source sqlserver2014a -Destination sqlcluster

        Copies all assemblies from sqlserver2014a to sqlcluster using Windows credentials. If assemblies with the same name exist on sqlcluster, they will be skipped.

    .EXAMPLE
        PS C:\> Copy-DbaDbAssembly -Source sqlserver2014a -Destination sqlcluster -Assembly dbname.assemblyname, dbname3.anotherassembly -SourceSqlCredential $cred -Force

        Copies two assemblies, the dbname.assemblyname and dbname3.anotherassembly from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If an assembly with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used.

        In this example, anotherassembly will be copied to the dbname3 database on the server sqlcluster.

    .EXAMPLE
        PS C:\> Copy-DbaDbAssembly -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force

        Shows what would happen if the command were executed using force.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]$SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]$DestinationSqlCredential,
        [object[]]$Assembly,
        [object[]]$ExcludeAssembly,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential -MinimumVersion 9
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }
        $sourceAssemblies = @()
        foreach ($database in ($sourceServer.Databases | Where-Object IsAccessible)) {
            Write-Message -Level Verbose -Message "Processing $database on source"

            try {
                # a bug here requires a try/catch
                $userAssemblies = $database.Assemblies | Where-Object IsSystemObject -eq $false
                foreach ($assembly in $userAssemblies) {
                    $sourceAssemblies += $assembly
                }
            } catch {
                #here to avoid an empty catch
                $null = 1
            }
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }

            $destAssemblies = @()
            foreach ($database in $destServer.Databases) {
                Write-Message -Level VeryVerbose -Message "Processing $database on destination"
                try {
                    # a bug here requires a try/catch
                    $userAssemblies = $database.Assemblies | Where-Object IsSystemObject -eq $false
                    foreach ($assembly in $userAssemblies) {
                        $destAssemblies += $assembly
                    }
                } catch {
                    #here to avoid an empty catch
                    $null = 1
                }
            }
            foreach ($currentAssembly in $sourceAssemblies) {
                $assemblyName = $currentAssembly.Name
                $dbName = $currentAssembly.Parent.Name
                $destDb = $destServer.Databases[$dbName]
                Write-Message -Level VeryVerbose -Message "Processing $assemblyName on $dbname"
                $copyDbAssemblyStatus = [pscustomobject]@{
                    SourceServer        = $sourceServer.Name
                    SourceDatabase      = $dbName
                    DestinationServer   = $destServer.Name
                    DestinationDatabase = $destDb
                    type                = "Database Assembly"
                    Name                = $assemblyName
                    Status              = $null
                    Notes               = $null
                    DateTime            = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                }


                if (!$destDb) {
                    $copyDbAssemblyStatus.Status = "Skipped"
                    $copyDbAssemblyStatus.Notes = "Destination database does not exist"
                    $copyDbAssemblyStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                    Write-Message -Level Verbose -Message "Destination database $dbName does not exist. Skipping $assemblyName.";
                    continue
                }

                if ((Test-Bound -ParameterName Assembly) -and $Assembly -notcontains "$dbName.$assemblyName" -or $ExcludeAssembly -contains "$dbName.$assemblyName") {
                    continue
                }

                if ($currentAssembly.AssemblySecurityLevel -eq "External" -and -not $destDb.Trustworthy) {
                    if ($Pscmdlet.ShouldProcess($destinstance, "Setting $dbName to External")) {
                        Write-Message -Level Verbose -Message "Setting $dbName Security Level to External on $destinstance."
                        $sql = "ALTER DATABASE $dbName SET TRUSTWORTHY ON"
                        try {
                            Write-Message -Level Debug -Message $sql
                            $destServer.Query($sql)
                        } catch {
                            $copyDbAssemblyStatus.Status = "Failed"
                            $copyDbAssemblyStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                            Stop-Function -Message "Issue setting security level." -Target $destDb -ErrorRecord $_
                        }
                    }
                }

                if ($destServer.Databases[$dbName].Assemblies.Name -contains $currentAssembly.name) {
                    if ($force -eq $false) {
                        $copyDbAssemblyStatus.Status = "Skipped"
                        $copyDbAssemblyStatus.Notes = "Already exists on destination"
                        $copyDbAssemblyStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        Write-Message -Level Verbose -Message "Assembly $assemblyName exists at destination in the $dbName database. Use -Force to drop and migrate."
                        continue
                    } else {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Dropping assembly $assemblyName and recreating")) {
                            try {
                                Write-Message -Level Verbose -Message "Dropping assembly $assemblyName."
                                Write-Message -Level Verbose -Message "This won't work if there are dependencies."
                                $destServer.Databases[$dbName].Assemblies[$assemblyName].Drop()
                                Write-Message -Level Verbose -Message "Copying assembly $assemblyName."
                                $sql = $currentAssembly.Script()
                                Write-Message -Level Debug -Message $sql
                                $destServer.Query($sql, $dbName)
                            } catch {
                                $copyDbAssemblyStatus.Status = "Failed"
                                $copyDbAssemblyStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                                Stop-Function -Message "Issue dropping assembly." -Target $assemblyName -ErrorRecord $_ -Continue
                            }
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destinstance, "Creating assembly $assemblyName")) {
                    try {
                        Write-Message -Level Verbose -Message "Copying assembly $assemblyName from database."
                        $sql = $currentAssembly.Script()
                        Write-Message -Level Debug -Message $sql
                        $destServer.Query($sql, $dbName)

                        $copyDbAssemblyStatus.Status = "Successful"
                        $copyDbAssemblyStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                    } catch {
                        $copyDbAssemblyStatus.Status = "Failed"
                        $copyDbAssemblyStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        Stop-Function -Message "Issue creating assembly." -Target $assemblyName -ErrorRecord $_
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlDatabaseAssembly
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-DbaDatabaseAssembly
    }
}
tools\dbatools\functions\Copy-DbaDbMail.ps1
function Copy-DbaDbMail {
    <#
    .SYNOPSIS
        Migrates Mail Profiles, Accounts, Mail Servers and Mail Server Configs from one SQL Server to another.

    .DESCRIPTION
        By default, all mail configurations for Profiles, Accounts, Mail Servers and Configs are copied.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Type
        Specifies the object type to migrate. Valid options are "Job", "Alert" and "Operator". When Type is specified, all categories from the selected type will be migrated.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER Force
        If this switch is enabled, existing objects on Destination with matching names from Source will be dropped.

    .NOTES
        Tags: Migration, Mail
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        https://dbatools.io/Copy-DbaDbMail

    .EXAMPLE
        PS C:\> Copy-DbaDbMail -Source sqlserver2014a -Destination sqlcluster

        Copies all database mail objects from sqlserver2014a to sqlcluster using Windows credentials. If database mail objects with the same name exist on sqlcluster, they will be skipped.

    .EXAMPLE
        PS C:\> Copy-DbaDbMail -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred

        Copies all database mail objects from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster.

    .EXAMPLE
        PS C:\> Copy-DbaDbMail -Source sqlserver2014a -Destination sqlcluster -WhatIf

        Shows what would happen if the command were executed.

    .EXAMPLE
        PS C:\> Copy-DbaDbMail -Source sqlserver2014a -Destination sqlcluster -EnableException

        Performs execution of function, and will throw a terminating exception if something breaks

    #>
    [cmdletbinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [Parameter(ParameterSetName = 'SpecificTypes')]
        [ValidateSet('ConfigurationValues', 'Profiles', 'Accounts', 'mailServers')]
        [string[]]$Type,
        [PSCredential]$SourceSqlCredential,
        [PSCredential]$DestinationSqlCredential,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        function Copy-DbaDbMailConfig {
            [cmdletbinding(SupportsShouldProcess)]
            param ()

            Write-Message -Message "Migrating mail server configuration values." -Level Verbose
            $copyMailConfigStatus = [pscustomobject]@{
                SourceServer      = $sourceServer.Name
                DestinationServer = $destServer.Name
                Name              = "Server Configuration"
                Type              = "Mail Configuration"
                Status            = $null
                Notes             = $null
                DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
            }
            if ($pscmdlet.ShouldProcess($destinstance, "Migrating all mail server configuration values.")) {
                try {
                    $sql = $mail.ConfigurationValues.Script() | Out-String
                    $sql = $sql -replace [Regex]::Escape("'$source'"), "'$destinstance'"
                    Write-Message -Message $sql -Level Debug
                    $destServer.Query($sql) | Out-Null
                    $mail.ConfigurationValues.Refresh()
                    $copyMailConfigStatus.Status = "Successful"
                } catch {
                    $copyMailConfigStatus.Status = "Failed"
                    $copyMailConfigStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    Stop-Function -Message "Unable to migrate mail configuration." -Category InvalidOperation -InnerErrorRecord $_ -Target $destServer
                }
                $copyMailConfigStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
            }
        }

        function Copy-DbaDatabaseAccount {
            [cmdletbinding(SupportsShouldProcess)]
            $sourceAccounts = $sourceServer.Mail.Accounts
            $destAccounts = $destServer.Mail.Accounts

            Write-Message -Message "Migrating accounts." -Level Verbose
            foreach ($account in $sourceAccounts) {
                $accountName = $account.name
                $copyMailAccountStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Name              = $accountName
                    Type              = "Mail Account"
                    Status            = $null
                    Notes             = $null
                    DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                }

                if ($accounts.count -gt 0 -and $accounts -notcontains $accountName) {
                    continue
                }

                if ($destAccounts.name -contains $accountName) {
                    if ($force -eq $false) {
                        If ($pscmdlet.ShouldProcess($destinstance, "Account $accountName exists at destination. Use -Force to drop and migrate.")) {
                            $copyMailAccountStatus.Status = "Skipped"
                            $copyMailAccountStatus.Notes = "Already exists on destination"
                            $copyMailAccountStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            Write-Message -Message "Account $accountName exists at destination. Use -Force to drop and migrate." -Level Verbose
                        }
                        continue
                    }

                    If ($pscmdlet.ShouldProcess($destinstance, "Dropping account $accountName and recreating.")) {
                        try {
                            Write-Message -Message "Dropping account $accountName." -Level Verbose
                            $destServer.Mail.Accounts[$accountName].Drop()
                            $destServer.Mail.Accounts.Refresh()
                        } catch {
                            $copyMailAccountStatus.Status = "Failed"
                            $copyMailAccountStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            Stop-Function -Message "Issue dropping account." -Target $accountName -Category InvalidOperation -InnerErrorRecord $_ -Continue
                        }
                    }
                }

                if ($pscmdlet.ShouldProcess($destinstance, "Migrating account $accountName.")) {
                    try {
                        Write-Message -Message "Copying mail account $accountName." -Level Verbose
                        $sql = $account.Script() | Out-String
                        $sql = $sql -replace [Regex]::Escape("'$source'"), "'$destinstance'"
                        Write-Message -Message $sql -Level Debug
                        $destServer.Query($sql) | Out-Null
                        $copyMailAccountStatus.Status = "Successful"
                    } catch {
                        $copyMailAccountStatus.Status = "Failed"
                        $copyMailAccountStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        Stop-Function -Message "Issue copying mail account." -Target $accountName -Category InvalidOperation -InnerErrorRecord $_
                    }
                    $copyMailAccountStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                }
            }
        }

        function Copy-DbaDbMailProfile {

            $sourceProfiles = $sourceServer.Mail.Profiles
            $destProfiles = $destServer.Mail.Profiles

            Write-Message -Message "Migrating mail profiles." -Level Verbose
            foreach ($profile in $sourceProfiles) {

                $profileName = $profile.name
                $copyMailProfileStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Name              = $profileName
                    Type              = "Mail Profile"
                    Status            = $null
                    Notes             = $null
                    DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                }

                if ($profiles.count -gt 0 -and $profiles -notcontains $profileName) {
                    continue
                }

                if ($destProfiles.name -contains $profileName) {
                    if ($force -eq $false) {
                        If ($pscmdlet.ShouldProcess($destinstance, "Profile $profileName exists at destination. Use -Force to drop and migrate.")) {
                            $copyMailProfileStatus.Status = "Skipped"
                            $copyMailProfileStatus.Notes = "Already exists on destination"
                            $copyMailProfileStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            Write-Message -Message "Profile $profileName exists at destination. Use -Force to drop and migrate." -Level Verbose
                        }
                        continue
                    }

                    If ($pscmdlet.ShouldProcess($destinstance, "Dropping profile $profileName and recreating.")) {
                        try {
                            Write-Message -Message "Dropping profile $profileName." -Level Verbose
                            $destServer.Mail.Profiles[$profileName].Drop()
                            $destServer.Mail.Profiles.Refresh()
                        } catch {
                            $copyMailProfileStatus.Status = "Failed"
                            $copyMailProfileStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            Stop-Function -Message "Issue dropping profile." -Target $profileName -Category InvalidOperation -InnerErrorRecord $_ -Continue
                        }
                    }
                }

                if ($pscmdlet.ShouldProcess($destinstance, "Migrating mail profile $profileName.")) {
                    try {
                        Write-Message -Message "Copying mail profile $profileName." -Level Verbose
                        $sql = $profile.Script() | Out-String
                        $sql = $sql -replace [Regex]::Escape("'$source'"), "'$destinstance'"
                        Write-Message -Message $sql -Level Debug
                        $destServer.Query($sql) | Out-Null
                        $destServer.Mail.Profiles.Refresh()
                        $copyMailProfileStatus.Status = "Successful"
                    } catch {
                        $copyMailProfileStatus.Status = "Failed"
                        $copyMailProfileStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        Stop-Function -Message "Issue copying mail profile." -Target $profileName -Category InvalidOperation -InnerErrorRecord $_
                    }
                    $copyMailProfileStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                }
            }
        }

        function Copy-DbaDbMailServer {
            [cmdletbinding(SupportsShouldProcess)]
            $sourceMailServers = $sourceServer.Mail.Accounts.MailServers
            $destMailServers = $destServer.Mail.Accounts.MailServers

            Write-Message -Message "Migrating mail servers." -Level Verbose
            foreach ($mailServer in $sourceMailServers) {
                $mailServerName = $mailServer.name
                $copyMailServerStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Name              = $mailServerName
                    Type              = "Mail Server"
                    Status            = $null
                    Notes             = $null
                    DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                }
                if ($mailServers.count -gt 0 -and $mailServers -notcontains $mailServerName) {
                    continue
                }

                if ($destMailServers.name -contains $mailServerName) {
                    if ($force -eq $false) {
                        if ($pscmdlet.ShouldProcess($destinstance, "Mail server $mailServerName exists at destination. Use -Force to drop and migrate.")) {
                            $copyMailServerStatus.Status = "Skipped"
                            $copyMailServerStatus.Notes = "Already exists on destination"
                            $copyMailServerStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            Write-Message -Message "Mail server $mailServerName exists at destination. Use -Force to drop and migrate." -Level Verbose
                        }
                        continue
                    }

                    If ($pscmdlet.ShouldProcess($destinstance, "Dropping mail server $mailServerName and recreating.")) {
                        try {
                            Write-Message -Message "Dropping mail server $mailServerName." -Level Verbose
                            $destServer.Mail.Accounts.MailServers[$mailServerName].Drop()
                        } catch {
                            $copyMailServerStatus.Status = "Failed"
                            $copyMailServerStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            Stop-Function -Message "Issue dropping mail server." -Target $mailServerName -Category InvalidOperation -InnerErrorRecord $_ -Continue
                        }
                    }
                }

                if ($pscmdlet.ShouldProcess($destinstance, "Migrating account mail server $mailServerName.")) {
                    try {
                        Write-Message -Message "Copying mail server $mailServerName." -Level Verbose
                        $sql = $mailServer.Script() | Out-String
                        $sql = $sql -replace [Regex]::Escape("'$source'"), "'$destinstance'"
                        Write-Message -Message $sql -Level Debug
                        $destServer.Query($sql) | Out-Null
                        $copyMailServerStatus.Status = "Successful"
                    } catch {
                        $copyMailServerStatus.Status = "Failed"
                        $copyMailServerStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        Stop-Function -Message "Issue copying mail server" -Target $mailServerName -Category InvalidOperation -InnerErrorRecord $_
                    }
                    $copyMailServerStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                }
            }
        }

        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential -MinimumVersion 9
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }
        $mail = $sourceServer.mail
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }

            if ($type.Count -gt 0) {

                switch ($type) {
                    "ConfigurationValues" {
                        Copy-DbaDbMailConfig
                        $destServer.Mail.ConfigurationValues.Refresh()
                    }

                    "Profiles" {
                        Copy-DbaDbMailProfile
                        $destServer.Mail.Profiles.Refresh()
                    }

                    "Accounts" {
                        Copy-DbaDatabaseAccount
                        $destServer.Mail.Accounts.Refresh()
                    }

                    "mailServers" {
                        Copy-DbaDbMailServer
                    }
                }

                continue
            }

            if (($profiles.count + $accounts.count + $mailServers.count) -gt 0) {

                if ($profiles.count -gt 0) {
                    Copy-DbaDbMailProfile -Profiles $profiles
                    $destServer.Mail.Profiles.Refresh()
                }

                if ($accounts.count -gt 0) {
                    Copy-DbaDatabaseAccount -Accounts $accounts
                    $destServer.Mail.Accounts.Refresh()
                }

                if ($mailServers.count -gt 0) {
                    Copy-DbaDbMailServer -mailServers $mailServers
                }

                continue
            }

            Copy-DbaDbMailConfig
            $destServer.Mail.ConfigurationValues.Refresh()
            Copy-DbaDatabaseAccount
            $destServer.Mail.Accounts.Refresh()
            Copy-DbaDbMailProfile
            $destServer.Mail.Profiles.Refresh()
            Copy-DbaDbMailServer
            $copyMailConfigStatus
            $copyMailAccountStatus
            $copyMailProfileStatus
            $copyMailServerStatus
            $enableDBMailStatus

            <# ToDo: Use Get/Set-DbaSpConfigure once the dynamic parameters are replaced. #>

            if (($sourceDbMailEnabled -eq 1) -and ($destDbMailEnabled -eq 0)) {
                if ($pscmdlet.ShouldProcess($destinstance, "Enabling Database Mail")) {
                    $sourceDbMailEnabled = ($sourceServer.Configuration.DatabaseMailEnabled).ConfigValue
                    Write-Message -Message "$sourceServer DBMail configuration value: $sourceDbMailEnabled." -Level Verbose

                    $destDbMailEnabled = ($destServer.Configuration.DatabaseMailEnabled).ConfigValue
                    Write-Message -Message "$destServer DBMail configuration value: $destDbMailEnabled." -Level Verbose
                    $enableDBMailStatus = [pscustomobject]@{
                        SourceServer      = $sourceServer.name
                        DestinationServer = $destServer.name
                        Name              = "Enabled on Destination"
                        Type              = "Mail Configuration"
                        Status            = if ($destDbMailEnabled -eq 1) { "Enabled" } else { $null }
                        DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                    }
                    try {
                        Write-Message -Message "Enabling Database Mail on $destServer." -Level Verbose
                        $destServer.Configuration.DatabaseMailEnabled.ConfigValue = 1
                        $destServer.Alter()
                        $enableDBMailStatus.Status = "Successful"
                    } catch {
                        $enableDBMailStatus.Status = "Failed"
                        $enableDBMailStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        Stop-Function -Message "Cannot enable Database Mail." -Category InvalidOperation -ErrorRecord $_ -Target $destServer
                    }
                    $enableDBMailStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlDatabaseMail
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-DbaDatabaseMail
    }
}
tools\dbatools\functions\Copy-DbaDbQueryStoreOption.ps1
function Copy-DbaDbQueryStoreOption {
    <#
    .SYNOPSIS
        Copies the configuration of a Query Store enabled database and sets the copied configuration on other databases.

    .DESCRIPTION
        Copies the configuration of a Query Store enabled database and sets the copied configuration on other databases.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2016 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER SourceDatabase
        Specifies the database to copy the Query Store configuration from.

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2016 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER DestinationDatabase
        Specifies a list of databases that will receive a copy of the Query Store configuration of the SourceDatabase.

    .PARAMETER Exclude
        Specifies a list of databases which will NOT receive a copy of the Query Store configuration.

    .PARAMETER AllDatabases
        If this switch is enabled, the Query Store configuration will be copied to all databases on the destination instance.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: QueryStore
        Author: Enrico van de Laar (@evdlaar)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Copy-QueryStoreConfig

    .EXAMPLE
        PS C:\> Copy-DbaDbQueryStoreOption -Source ServerA\SQL -SourceDatabase AdventureWorks -Destination ServerB\SQL -AllDatabases

        Copy the Query Store configuration of the AdventureWorks database in the ServerA\SQL instance and apply it on all user databases in the ServerB\SQL Instance.

    .EXAMPLE
        PS C:\> Copy-DbaDbQueryStoreOption -Source ServerA\SQL -SourceDatabase AdventureWorks -Destination ServerB\SQL -DestinationDatabase WorldWideTraders

        Copy the Query Store configuration of the AdventureWorks database in the ServerA\SQL instance and apply it to the WorldWideTraders database in the ServerB\SQL Instance.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter]$Source,
        [PSCredential]$SourceSqlCredential,
        [parameter(Mandatory, ValueFromPipeline)]
        [object]$SourceDatabase,
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]$DestinationSqlCredential,
        [object[]]$DestinationDatabase,
        [object[]]$Exclude,
        [switch]$AllDatabases,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Copy-DbaQueryStoreConfig
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential
        } catch {
            Stop-Function -Message "Can't connect to $Source." -ErrorRecord $_ -Target $Source
            return
        }
    }

    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {
            # Grab the Query Store configuration from the SourceDatabase through the Get-DbaQueryStoreConfig function
            $SourceQSConfig = Get-DbaDbQueryStoreOption -SqlInstance $sourceServer -Database $SourceDatabase

            if (!$DestinationDatabase -and !$Exclude -and !$AllDatabases) {
                Stop-Function -Message "You must specify databases to execute against using either -DestinationDatabase, -Exclude or -AllDatabases." -Continue
            }

            foreach ($destinationServer in $destinstance) {

                try {
                    $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential
                } catch {
                    Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
                }

                # We have to exclude all the system databases since they cannot have the Query Store feature enabled
                $dbs = Get-DbaDatabase -SqlInstance $destServer -ExcludeSystem

                if ($DestinationDatabase.count -gt 0) {
                    $dbs = $dbs | Where-Object { $DestinationDatabase -contains $_.Name }
                }

                if ($Exclude.count -gt 0) {
                    $dbs = $dbs | Where-Object { $exclude -notcontains $_.Name }
                }

                if ($dbs.count -eq 0) {
                    Stop-Function -Message "No matching databases found. Check the spelling and try again." -Continue
                }

                foreach ($db in $dbs) {
                    # skipping the database if the source and destination are the same instance
                    if (($sourceServer.Name -eq $destinationServer) -and ($SourceDatabase -eq $db.Name)) {
                        continue
                    }
                    Write-Message -Message "Processing destination database: $db on $destinationServer." -Level Verbose
                    $copyQueryStoreStatus = [pscustomobject]@{
                        SourceServer      = $sourceServer.name
                        SourceDatabase    = $SourceDatabase
                        DestinationServer = $destinationServer
                        Name              = $db.name
                        Type              = "QueryStore Configuration"
                        Status            = $null
                        DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                    }

                    if ($db.IsAccessible -eq $false) {
                        $copyQueryStoreStatus.Status = "Skipped"
                        Stop-Function -Message "The database $db on server $destinationServer is not accessible. Skipping database." -Continue
                    }

                    Write-Message -Message "Executing Set-DbaQueryStoreConfig." -Level Verbose
                    # Set the Query Store configuration through the Set-DbaQueryStoreConfig function
                    if ($PSCmdlet.ShouldProcess("$db", "Copying QueryStoreConfig")) {
                        try {

                            $setDbaDbQueryStoreOptionParameters = @{

                                SqlInstance         = $destinationServer;
                                SqlCredential       = $DestinationSqlCredential;
                                Database            = $db.name;
                                State               = $SourceQSConfig.ActualState;
                                FlushInterval       = $SourceQSConfig.DataFlushIntervalInSeconds;
                                CollectionInterval  = $SourceQSConfig.StatisticsCollectionIntervalInMinutes;
                                MaxSize             = $SourceQSConfig.MaxStorageSizeInMB;
                                CaptureMode         = $SourceQSConfig.QueryCaptureMode;
                                CleanupMode         = $SourceQSConfig.SizeBasedCleanupMode;
                                StaleQueryThreshold = $SourceQSConfig.StaleQueryThresholdInDays;
                            }

                            $null = Set-DbaDbQueryStoreOption @setDbaDbQueryStoreOptionParameters;
                            $copyQueryStoreStatus.Status = "Successful"
                        } catch {
                            $copyQueryStoreStatus.Status = "Failed"
                            Stop-Function -Message "Issue setting Query Store on $db." -Target $db -ErrorRecord $_ -Continue
                        }
                        $copyQueryStoreStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Copy-DbaDbTableData.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Copy-DbaDbTableData {
    <#
    .SYNOPSIS
        Copies data between SQL Server tables.

    .DESCRIPTION
        Copies data between SQL Server tables using SQL Bulk Copy.
        The same can be achieved also doing
        $sourcetable = Invoke-DbaQuery -SqlInstance instance1 ... -As DataTable
        Write-DbaDataTable -SqlInstance ... -InputObject $sourcetable
        but it will force buffering the contents on the table in memory (high RAM usage for large tables).
        With this function, a streaming copy will be done in the most speedy and least resource-intensive way.

    .PARAMETER SqlInstance
        Source SQL Server.You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination Sql Server. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database to copy the table from.

    .PARAMETER DestinationDatabase
        The database to copy the table to. If not specified, it is assumed to be the same of Database

    .PARAMETER Table
        Define a specific table you would like to use as source. You can specify a three-part name like db.sch.tbl.
        If the object has special characters please wrap them in square brackets [ ].
        This dbo.First.Table will try to find table named 'Table' on schema 'First' and database 'dbo'.
        The correct way to find table named 'First.Table' on schema 'dbo' is passing dbo.[First.Table]

    .PARAMETER DestinationTable
        The table you want to use as destination. If not specified, it is assumed to be the same of Table

    .PARAMETER Query
        If you want to copy only a portion of a table or selected tables, specify the query.
        Ensure to select all required columns. Calculated Columns or columns with default values may be excluded.
        The tablename should be a full three-part name in form [Database].[Schema].[Table]

    .PARAMETER AutoCreateTable
        Creates the destination table if it does not already exist, based off of the "Export..." script of the source table.

    .PARAMETER BatchSize
        The BatchSize for the import defaults to 5000.

    .PARAMETER NotifyAfter
        Sets the option to show the notification after so many rows of import

    .PARAMETER NoTableLock
        If this switch is enabled, a table lock (TABLOCK) will not be placed on the destination table. By default, this operation will lock the destination table while running.

    .PARAMETER CheckConstraints
        If this switch is enabled, the SqlBulkCopy option to process check constraints will be enabled.

        Per Microsoft "Check constraints while data is being inserted. By default, constraints are not checked."

    .PARAMETER FireTriggers
        If this switch is enabled, the SqlBulkCopy option to fire insert triggers will be enabled.

        Per Microsoft "When specified, cause the server to fire the insert triggers for the rows being inserted into the Database."

    .PARAMETER KeepIdentity
        If this switch is enabled, the SqlBulkCopy option to preserve source identity values will be enabled.

        Per Microsoft "Preserve source identity values. When not specified, identity values are assigned by the destination."

    .PARAMETER KeepNulls
        If this switch is enabled, the SqlBulkCopy option to preserve NULL values will be enabled.

        Per Microsoft "Preserve null values in the destination table regardless of the settings for default values. When not specified, null values are replaced by default values where applicable."

    .PARAMETER Truncate
        If this switch is enabled, the destination table will be truncated after prompting for confirmation.

    .PARAMETER BulkCopyTimeOut
        Value in seconds for the BulkCopy operations timeout. The default is 30 seconds.

    .PARAMETER InputObject
        Enables piping of Table objects from Get-DbaDbTable

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration
        Author: Simone Bizzotto (@niphlod)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Copy-DbaDbTableData

    .EXAMPLE
        PS C:\> Copy-DbaDbTableData -SqlInstance sql1 -Destination sql2 -Database dbatools_from -Table dbo.test_table

        Copies all the data from table dbo.test_table in database dbatools_from on sql1 to table test_table in database dbatools_from on sql2.

    .EXAMPLE
        PS C:\> Copy-DbaDbTableData -SqlInstance sql1 -Destination sql2 -Database dbatools_from -DestinationDatabase dbatools_dest -Table [Schema].[test table]

        Copies all the data from table [Schema].[test table] in database dbatools_from on sql1 to table [Schema].[test table] in database dbatools_dest on sql2

    .EXAMPLE
        PS C:\> Get-DbaDbTable -SqlInstance sql1 -Database tempdb -Table tb1, tb2 | Copy-DbaDbTableData -DestinationTable tb3

        Copies all data from tables tb1 and tb2 in tempdb on sql1 to tb3 in tempdb on sql1

    .EXAMPLE
        PS C:\> Get-DbaDbTable -SqlInstance sql1 -Database tempdb -Table tb1, tb2 | Copy-DbaDbTableData -Destination sql2

        Copies data from tbl1 in tempdb on sql1 to tbl1 in tempdb on sql2
        then
        Copies data from tbl2 in tempdb on sql1 to tbl2 in tempdb on sql2

    .EXAMPLE
        PS C:\> Copy-DbaDbTableData -SqlInstance sql1 -Destination sql2 -Database dbatools_from -Table test_table -KeepIdentity -Truncate

        Copies all the data in table test_table from sql1 to sql2, using the database dbatools_from, keeping identity columns and truncating the destination

    .EXAMPLE
        PS C:\> $params = @{
        >> SourceSqlInstance = 'sql1'
        >> DestinationSqlInstance = 'sql2'
        >> Database = 'dbatools_from'
        >> DestinationDatabase = 'dbatools_dest'
        >> Table = '[Schema].[Table]'
        >> DestinationTable = '[dbo].[Table.Copy]'
        >> KeepIdentity = $true
        >> KeepNulls = $true
        >> Truncate = $true
        >> BatchSize = 10000
        >> }
        >>
        PS C:\> Copy-DbaDbTableData @params

        Copies all the data from table [Schema].[Table] in database dbatools_from on sql1 to table [dbo].[Table.Copy] in database dbatools_dest on sql2
        Keeps identity columns and Nulls, truncates the destination and processes in BatchSize of 10000.

       #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [Alias("ServerInstance", "SqlServer", "Source")]
        [DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]$DestinationSqlCredential,
        [string]$Database,
        [string]$DestinationDatabase,
        [string[]]$Table,
        [string]$Query,
        [switch]$AutoCreateTable,
        [int]$BatchSize = 50000,
        [int]$NotifyAfter = 5000,
        [string]$DestinationTable,
        [switch]$NoTableLock,
        [switch]$CheckConstraints,
        [switch]$FireTriggers,
        [switch]$KeepIdentity,
        [switch]$KeepNulls,
        [switch]$Truncate,
        [int]$bulkCopyTimeOut = 5000,
        [Parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Table[]]$InputObject,
        [switch]$EnableException
    )

    begin {
        # Getting the total rows copied is a challenge. Use SqlBulkCopyExtension.
        # http://stackoverflow.com/questions/1188384/sqlbulkcopy-row-count-when-complete

        $sourcecode = 'namespace System.Data.SqlClient {
            using Reflection;

            public static class SqlBulkCopyExtension
            {
                const String _rowsCopiedFieldName = "_rowsCopied";
                static FieldInfo _rowsCopiedField = null;

                public static int RowsCopiedCount(this SqlBulkCopy bulkCopy)
                {
                    if (_rowsCopiedField == null) _rowsCopiedField = typeof(SqlBulkCopy).GetField(_rowsCopiedFieldName, BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
                    return (int)_rowsCopiedField.GetValue(bulkCopy);
                }
            }
        }'

        Add-Type -ReferencedAssemblies System.Data.dll -TypeDefinition $sourcecode -ErrorAction Stop
        if (-not $script:core) {
            try {
                Add-Type -ReferencedAssemblies System.Data.dll -TypeDefinition $sourcecode -ErrorAction Stop
            } catch {
                $null = 1
            }
        }

        $bulkCopyOptions = 0
        $options = "TableLock", "CheckConstraints", "FireTriggers", "KeepIdentity", "KeepNulls", "Default"

        foreach ($option in $options) {
            $optionValue = Get-Variable $option -ValueOnly -ErrorAction SilentlyContinue
            if ($option -eq "TableLock" -and (!$NoTableLock)) {
                $optionValue = $true
            }
            if ($optionValue -eq $true) {
                $bulkCopyOptions += $([Data.SqlClient.SqlBulkCopyOptions]::$option).value__
            }
        }
    }

    process {
        if ((Test-Bound -Not -ParameterName Table, SqlInstance) -and (Test-Bound -Not -ParameterName InputObject)) {
            Stop-Function -Message "You must pipe in a table or specify SqlInstance, Database and Table."
            return
        }

        if ($SqlInstance) {
            if ((Test-Bound -Not -ParameterName Database)) {
                Stop-Function -Message "Database is required when passing a SqlInstance" -Target $Table
                return
            }

            if ((Test-Bound -Not -ParameterName Destination, DestinationDatabase, DestinationTable)) {
                Stop-Function -Message "Cannot copy $Table into itself. One of destination Server, Database or Table must be specified " -Target $Table
                return
            }

            try {
                $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $SqlInstance
                return
            }

            if ($Database -notin $server.Databases.Name) {
                Stop-Function -Message "Database $Database doesn't exist on $server"
                return
            }

            try {
                foreach ($tbl in $Table) {
                    $dbTable = Get-DbaDbTable -SqlInstance $server -Table $tbl -Database $Database -EnableException -Verbose:$false
                    if ($dbTable.Count -eq 1) {
                        $InputObject += $dbTable
                    } else {
                        Stop-Function -Message "The table $tbl matches $($dbTable.Count) objects. Unable to determine which object to copy" -Continue
                    }
                }
            } catch {
                Stop-Function -Message "Unable to determine source table : $Table"
                return
            }
        }

        foreach ($sqltable in $InputObject) {
            $Database = $sqltable.Parent.Name
            $server = $sqltable.Parent.Parent

            if ((Test-Bound -Not -ParameterName DestinationTable)) {
                $DestinationTable = '[' + $sqltable.Schema + '].[' + $sqltable.Name + ']'
            }

            $newTableParts = Get-TableNameParts $DestinationTable
            #using FQTN to determine database name
            if ($newTableParts.Database) {
                $DestinationDatabase = $newTableParts.Database
            } elseif ((Test-Bound -Not -ParameterName DestinationDatabase)) {
                $DestinationDatabase = $Database
            }

            if (-not $Destination) {
                $Destination = $server
            }

            foreach ($destinationserver in $Destination) {
                try {
                    $destServer = Connect-SqlInstance -SqlInstance $destinationserver -SqlCredential $DestinationSqlCredential
                } catch {
                    Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinationserver
                    return
                }

                if ($DestinationDatabase -notin $destServer.Databases.Name) {
                    Stop-Function -Message "Database $DestinationDatabase doesn't exist on $destServer"
                    return
                }

                $desttable = Get-DbaDbTable -SqlInstance $destServer -Table $DestinationTable -Database $DestinationDatabase -Verbose:$false | Select-Object -First 1
                if (-not $desttable -and $AutoCreateTable) {
                    try {
                        $tablescript = $sqltable | Export-DbaScript -Passthru | Out-String
                        #replacing table name
                        if ($newTableParts.Table) {
                            $rX = "(CREATE TABLE \[$([regex]::Escape($sqltable.Schema))\]\.\[)$([regex]::Escape($sqltable.Name))(\]\()"
                            $tablescript = $tablescript -replace $rX, "`$1$($newTableParts.Table)`$2"
                        }
                        #replacing table schema
                        if ($newTableParts.Schema) {
                            $rX = "(CREATE TABLE \[)$([regex]::Escape($sqltable.Schema))(\]\.\[$([regex]::Escape($newTableParts.Table))\]\()"
                            $tablescript = $tablescript -replace $rX, "`$1$($newTableParts.Schema)`$2"
                        }

                        if ($PSCmdlet.ShouldProcess($destServer, "Creating new table: $DestinationTable")) {
                            Write-Message -Message "New table script: $tablescript" -Level VeryVerbose
                            Invoke-DbaQuery -SqlInstance $destServer -Database $DestinationDatabase -Query "$tablescript" -EnableException # add some string assurance there
                            #table list was updated, let's grab a fresh one
                            $destServer.Databases[$DestinationDatabase].Tables.Refresh()
                            $desttable = Get-DbaDbTable -SqlInstance $destServer -Table $DestinationTable -Database $DestinationDatabase -Verbose:$false
                            Write-Message -Message "New table created: $desttable" -Level Verbose
                        }
                    } catch {
                        Stop-Function -Message "Unable to determine destination table: $DestinationTable" -ErrorRecord $_
                        return
                    }
                }
                if (-not $desttable) {
                    Stop-Function -Message "Table $DestinationTable cannot be found in $DestinationDatabase. Use -AutoCreateTable to automatically create the table on the destination." -Continue
                }

                $connstring = $destServer.ConnectionContext.ConnectionString

                if ($server.DatabaseEngineType -eq "SqlAzureDatabase") {
                    $fqtnfrom = "$sqltable"
                } else {
                    $fqtnfrom = "$($server.Databases[$Database]).$sqltable"
                }

                if ($destServer.DatabaseEngineType -eq "SqlAzureDatabase") {
                    $fqtndest = "$desttable"
                } else {
                    $fqtndest = "$($destServer.Databases[$DestinationDatabase]).$desttable"
                }

                if ($fqtndest -eq $fqtnfrom -and $server.Name -eq $destServer.Name) {
                    Stop-Function -Message "Cannot copy $fqtnfrom on $($server.Name) into $fqtndest on ($destServer.Name). Source and Destination must be different " -Target $Table
                    return
                }


                if (Test-Bound -ParameterName Query -Not) {
                    $Query = "SELECT * FROM $fqtnfrom"
                }
                try {
                    if ($Truncate -eq $true) {
                        if ($Pscmdlet.ShouldProcess($destServer, "Truncating table $fqtndest")) {
                            $null = $destServer.Databases[$DestinationDatabase].ExecuteNonQuery("TRUNCATE TABLE $fqtndest")
                        }
                    }
                    if ($Pscmdlet.ShouldProcess($server, "Copy data from $fqtnfrom")) {
                        $cmd = $server.ConnectionContext.SqlConnectionObject.CreateCommand()
                        $cmd.CommandText = $Query
                        if ($server.ConnectionContext.IsOpen -eq $false) {
                            $server.ConnectionContext.SqlConnectionObject.Open()
                        }
                        $bulkCopy = New-Object Data.SqlClient.SqlBulkCopy("$connstring;Database=$DestinationDatabase", $bulkCopyOptions)
                        $bulkCopy.DestinationTableName = $fqtndest
                        $bulkCopy.EnableStreaming = $true
                        $bulkCopy.BatchSize = $BatchSize
                        $bulkCopy.NotifyAfter = $NotifyAfter
                        $bulkCopy.BulkCopyTimeOut = $BulkCopyTimeOut

                        $elapsed = [System.Diagnostics.Stopwatch]::StartNew()
                        # Add RowCount output
                        $bulkCopy.Add_SqlRowsCopied( {
                                $RowsPerSec = [math]::Round($args[1].RowsCopied / $elapsed.ElapsedMilliseconds * 1000.0, 1)
                                Write-Progress -id 1 -activity "Inserting rows" -Status ([System.String]::Format("{0} rows ({1} rows/sec)", $args[1].RowsCopied, $RowsPerSec))
                            })
                    }

                    if ($Pscmdlet.ShouldProcess($destServer, "Writing rows to $fqtndest")) {
                        $reader = $cmd.ExecuteReader()
                        $bulkCopy.WriteToServer($reader)
                        if ($script:core) {
                            $RowsTotal = "Unsupported in Core"
                        } else {
                            $RowsTotal = [System.Data.SqlClient.SqlBulkCopyExtension]::RowsCopiedCount($bulkCopy)
                        }
                        $TotalTime = [math]::Round($elapsed.Elapsed.TotalSeconds, 1)
                        Write-Message -Level Verbose -Message "$RowsTotal rows inserted in $TotalTime sec"
                        if ($rowCount -is [int]) {
                            Write-Progress -id 1 -activity "Inserting rows" -status "Complete" -Completed
                        }

                        $bulkCopy.Close()
                        $bulkCopy.Dispose()
                        $reader.Close()

                        [pscustomobject]@{
                            SourceInstance      = $server.Name
                            SourceDatabase      = $Database
                            SourceSchema        = $sqltable.Schema
                            SourceTable         = $sqltable.Name
                            DestinationInstance = $destServer.name
                            DestinationDatabase = $DestinationDatabase
                            DestinationSchema   = $desttable.Schema
                            DestinationTable    = $desttable.Name
                            RowsCopied          = $rowstotal
                            Elapsed             = [prettytimespan]$elapsed.Elapsed
                        }
                    }
                } catch {
                    Stop-Function -Message "Something went wrong" -ErrorRecord $_ -Target $server -continue
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-DbaTableData
    }
}
tools\dbatools\functions\Copy-DbaEndpoint.ps1
function Copy-DbaEndpoint {
    <#
    .SYNOPSIS
        Copy-DbaEndpoint migrates server endpoints from one SQL Server to another.

    .DESCRIPTION
        By default, all endpoints are copied.

        If the endpoint already exists on the destination, it will be skipped unless -Force is used.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Endpoint
        The endpoint(s) to process. This list is auto-populated from the server. If unspecified, all endpoints will be processed.

    .PARAMETER ExcludeEndpoint
        The endpoint(s) to exclude. This list is auto-populated from the server.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER Force
        If this switch is enabled, existing endpoints on Destination with matching names from Source will be dropped.

    .NOTES
        Tags: Migration, Endpoint
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        https://dbatools.io/Copy-DbaEndpoint

    .EXAMPLE
        PS C:\> Copy-DbaEndpoint -Source sqlserver2014a -Destination sqlcluster

        Copies all server endpoints from sqlserver2014a to sqlcluster, using Windows credentials. If endpoints with the same name exist on sqlcluster, they will be skipped.

    .EXAMPLE
        PS C:\> Copy-DbaEndpoint -Source sqlserver2014a -SourceSqlCredential $cred -Destination sqlcluster -Endpoint tg_noDbDrop -Force

        Copies only the tg_noDbDrop endpoint from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If an endpoint with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used.

    .EXAMPLE
        PS C:\> Copy-DbaEndpoint -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force

        Shows what would happen if the command were executed using force.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]
        $SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]
        $DestinationSqlCredential,
        [object[]]$Endpoint,
        [object[]]$ExcludeEndpoint,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential -MinimumVersion 9
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }
        $serverEndpoints = $sourceServer.Endpoints | Where-Object IsSystemObject -eq $false
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }
            $destEndpoints = $destServer.Endpoints

            foreach ($currentEndpoint in $serverEndpoints) {
                $endpointName = $currentEndpoint.Name

                $copyEndpointStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Name              = $endpointName
                    Type              = "Endpoint"
                    Status            = $null
                    Notes             = $null
                    DateTime          = [DbaDateTime](Get-Date)
                }

                if ($Endpoint -and $Endpoint -notcontains $endpointName -or $ExcludeEndpoint -contains $endpointName) {
                    continue
                }

                if ($destEndpoints.Name -contains $endpointName) {
                    if ($force -eq $false) {
                        $copyEndpointStatus.Status = "Skipped"
                        $copyEndpointStatus.Notes = "Already exists on destination"
                        $copyEndpointStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        Write-Message -Level Verbose -Message "Server endpoint $endpointName exists at destination. Use -Force to drop and migrate."
                        continue
                    } else {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Dropping server endpoint $endpointName and recreating.")) {
                            try {
                                Write-Message -Level Verbose -Message "Dropping server endpoint $endpointName."
                                $destServer.Endpoints[$endpointName].Drop()
                            } catch {
                                $copyEndpointStatus.Status = "Failed"
                                $copyEndpointStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                                Stop-Function -Message "Issue dropping server endpoint." -Target $endpointName -ErrorRecord $_ -Continue
                            }
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destinstance, "Creating server endpoint $endpointName.")) {
                    try {
                        Write-Message -Level Verbose -Message "Copying server endpoint $endpointName."
                        $destServer.Query($currentEndpoint.Script()) | Out-Null

                        $copyEndpointStatus.Status = "Successful"
                        $copyEndpointStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    } catch {
                        $copyEndpointStatus.Status = "Failed"
                        $copyEndpointStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        Stop-Function -Message "Issue creating server endpoint." -Target $endpointName -ErrorRecord $_
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlEndpoint
    }
}
tools\dbatools\functions\Copy-DbaLinkedServer.ps1
function Copy-DbaLinkedServer {
    <#
    .SYNOPSIS
        Copy-DbaLinkedServer migrates Linked Servers from one SQL Server to another. Linked Server logins and passwords are migrated as well.

    .DESCRIPTION
        By using password decryption techniques provided by Antti Rantasaari (NetSPI, 2014), this script migrates SQL Server Linked Servers from one server to another, while maintaining username and password.

        Credit: https://blog.netspi.com/decrypting-mssql-database-link-server-passwords/

    .PARAMETER Source
        Source SQL Server (2005 and above). You must have sysadmin access to both SQL Server and Windows.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server (2005 and above). You must have sysadmin access to both SQL Server and Windows.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER LinkedServer
        The linked server(s) to process - this list is auto-populated from the server. If unspecified, all linked servers will be processed.

    .PARAMETER ExcludeLinkedServer
        The linked server(s) to exclude - this list is auto-populated from the server

    .PARAMETER UpgradeSqlClient
        Upgrade any SqlClient Linked Server to the current Version

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER Force
        By default, if a Linked Server exists on the source and destination, the Linked Server is not copied over. Specifying -force will drop and recreate the Linked Server on the Destination server.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: WSMan, Migration, LinkedServer
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers
        Limitations: This just copies the SQL portion. It does not copy files (i.e. a local SQLite database, or Microsoft Access DB), nor does it configure ODBC entries.

    .LINK
        https://dbatools.io/Copy-DbaLinkedServer

    .EXAMPLE
        PS C:\> Copy-DbaLinkedServer -Source sqlserver2014a -Destination sqlcluster

        Copies all SQL Server Linked Servers on sqlserver2014a to sqlcluster. If Linked Server exists on destination, it will be skipped.

    .EXAMPLE
        PS C:\> Copy-DbaLinkedServer -Source sqlserver2014a -Destination sqlcluster -LinkedServer SQL2K5,SQL2k -Force

        Copies over two SQL Server Linked Servers (SQL2K and SQL2K2) from sqlserver to sqlcluster. If the credential already exists on the destination, it will be dropped.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification = "Internal functions are ignored")]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]$SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]$DestinationSqlCredential,
        [object[]]$LinkedServer,
        [object[]]$ExcludeLinkedServer,
        [switch]$UpgradeSqlClient,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        if (-not $script:isWindows) {
            Stop-Function -Message "Copy-DbaCredential is only supported on Windows"
            return
        }
        $null = Test-ElevationRequirement -ComputerName $Source.ComputerName
        function Copy-DbaLinkedServers {
            param (
                [string[]]$LinkedServer,
                [bool]$force
            )

            Write-Message -Level Verbose -Message "Collecting Linked Server logins and passwords on $($sourceServer.Name)."
            $sourcelogins = Get-DecryptedObject -SqlInstance $sourceServer -Type LinkedServer

            $serverlist = $sourceServer.LinkedServers

            if ($LinkedServer) {
                $serverlist = $serverlist | Where-Object Name -In $LinkedServer
            }
            if ($ExcludeLinkedServer) {
                $serverList = $serverlist | Where-Object Name -NotIn $ExcludeLinkedServer
            }

            foreach ($currentLinkedServer in $serverlist) {
                $provider = $currentLinkedServer.ProviderName
                try {
                    $destServer.LinkedServers.Refresh()
                    $destServer.LinkedServers.LinkedServerLogins.Refresh()
                } catch {
                    #here to avoid an empty catch
                    $null = 1
                }

                $linkedServerName = $currentLinkedServer.Name
                $linkedServerDataSource = $currentLinkedServer.DataSource

                $copyLinkedServer = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Name              = $linkedServerName
                    DataSource        = $linkedServerDataSource
                    Type              = "Linked Server"
                    Status            = $null
                    Notes             = $provider
                    DateTime          = [DbaDateTime](Get-Date)
                }

                # This does a check to warn of missing OleDbProviderSettings but should only be checked on SQL on Windows
                if ($destServer.Settings.OleDbProviderSettings.Name.Length -ne 0) {
                    if (!$destServer.Settings.OleDbProviderSettings.Name -contains $provider -and !$provider.StartsWith("SQLN")) {
                        $copyLinkedServer.Status = "Skipped"
                        $copyLinkedServer.Notes = "Missing provider"
                        $copyLinkedServer | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        Write-Message -Level Verbose -Message "$($destServer.Name) does not support the $provider provider. Skipping $linkedServerName."
                        continue
                    }
                }

                if ($null -ne $destServer.LinkedServers[$linkedServerName]) {
                    if (!$force) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "$linkedServerName exists $($destServer.Name). Skipping.")) {
                            $copyLinkedServer.Status = "Skipped"
                            $copyLinkedServer.Notes = "Already exists on destination"
                            $copyLinkedServer | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                            Write-Message -Level Verbose -Message "$linkedServerName exists $($destServer.Name). Skipping."
                        }
                        continue
                    } else {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Dropping $linkedServerName")) {
                            if ($currentLinkedServer.Name -eq 'repl_distributor') {
                                Write-Message -Level Verbose -Message "repl_distributor cannot be dropped. Not going to try."
                                continue
                            }

                            $destServer.LinkedServers[$linkedServerName].Drop($true)
                            $destServer.LinkedServers.refresh()
                        }
                    }
                }

                Write-Message -Level Verbose -Message "Attempting to migrate: $linkedServerName."
                If ($Pscmdlet.ShouldProcess($destinstance, "Migrating $linkedServerName")) {
                    try {
                        $sql = $currentLinkedServer.Script() | Out-String
                        Write-Message -Level Debug -Message $sql

                        if ($UpgradeSqlClient -and $sql -match "sqlncli") {
                            $destProviders = $destServer.Settings.OleDbProviderSettings | Where-Object { $_.Name -like 'SQLNCLI*' }
                            $newProvider = $destProviders | Sort-Object Name -Descending | Select-Object -First 1 -ExpandProperty Name

                            Write-Message -Level Verbose -Message "Changing sqlncli to $newProvider"
                            $sql = $sql -replace ("sqlncli[0-9]+", $newProvider)
                        }

                        $destServer.Query($sql)

                        if ($copyLinkedServer.Name -ne $copyLinkedServer.DataSource) {
                            $sql2 = "EXEC sp_setnetname '$($copyLinkedServer.Name)', '$($copyLinkedServer.DataSource)'; "
                            $destServer.Query($sql2)
                        }

                        $destServer.LinkedServers.Refresh()
                        Write-Message -Level Verbose -Message "$linkedServerName successfully copied."

                        $copyLinkedServer.Status = "Successful"
                        $copyLinkedServer | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    } catch {
                        $copyLinkedServer.Status = "Failed"
                        $copyLinkedServer | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        Stop-Function -Message "Issue adding linked server $destServer." -Target $linkedServerName -InnerErrorRecord $_
                        $skiplogins = $true
                    }
                }

                if ($skiplogins -ne $true) {
                    $destlogins = $destServer.LinkedServers[$linkedServerName].LinkedServerLogins
                    $lslogins = $sourcelogins | Where-Object { $_.Name -eq $linkedServerName }

                    foreach ($login in $lslogins) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Migrating $($login.Login)")) {
                            $currentlogin = $destlogins | Where-Object { $_.RemoteUser -eq $login.Identity }

                            $copyLinkedServer.Type = $login.Identity

                            if ($currentlogin.RemoteUser.length -ne 0) {
                                try {
                                    $currentlogin.SetRemotePassword($login.Password)
                                    $currentlogin.Alter()

                                    $copyLinkedServer.Status = "Successful"
                                    $copyLinkedServer | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                } catch {
                                    $copyLinkedServer.Status = "Failed"
                                    $copyLinkedServer | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                                    Stop-Function -Message "Failed to copy login." -Target $login -InnerErrorRecord $_
                                }
                            }
                        }
                    }
                }
            }
        }

        if ($null -ne $SourceSqlCredential.Username) {
            Write-Message -Level Verbose -Message "You are using a SQL Credential. Note that this script requires Windows Administrator access on the source server. Attempting with $($SourceSqlCredential.Username)."
        }
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential
            return
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }
        if (!(Test-SqlSa -SqlInstance $sourceServer -SqlCredential $SourceSqlCredential)) {
            Stop-Function -Message "Not a sysadmin on $source. Quitting." -Target $sourceServer
            return
        }
        Write-Message -Level Verbose -Message "Getting NetBios name for $source."
        $sourceNetBios = Resolve-NetBiosName $sourceserver

        Write-Message -Level Verbose -Message "Checking if Remote Registry is enabled on $source."
        try {
            Invoke-Command2 -Raw -Credential $Credential -ComputerName $sourceNetBios -ScriptBlock { Get-ItemProperty -Path "HKLM:\SOFTWARE\" } -ErrorAction Stop
        } catch {
            Stop-Function -Message "Can't connect to registry on $source." -Target $sourceNetBios -ErrorRecord $_
            return
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }

        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }
            if (!(Test-SqlSa -SqlInstance $destServer -SqlCredential $DestinationSqlCredential)) {
                Stop-Function -Message "Not a sysadmin on $destinstance" -Target $destServer -Continue
            }

            # Magic happens here
            Copy-DbaLinkedServers $LinkedServer -Force:$force
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlLinkedServer
    }
}
tools\dbatools\functions\Copy-DbaLogin.ps1
function Copy-DbaLogin {
    <#
    .SYNOPSIS
        Migrates logins from source to destination SQL Servers. Supports SQL Server versions 2000 and newer.

    .DESCRIPTION
        SQL Server 2000: Migrates logins with SIDs, passwords, server roles and database roles.

        SQL Server 2005 & newer: Migrates logins with SIDs, passwords, defaultdb, server roles & securables, database permissions & securables, login attributes (enforce password policy, expiration, etc.)

        The login hash algorithm changed in SQL Server 2012, and is not backwards compatible with previous SQL Server versions. This means that while SQL Server 2000 logins can be migrated to SQL Server 2012, logins created in SQL Server 2012 can only be migrated to SQL Server 2012 and above.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Login
        The login(s) to process. Options for this list are auto-populated from the server. If unspecified, all logins will be processed.

    .PARAMETER ExcludeLogin
        The login(s) to exclude. Options for this list are auto-populated from the server.

    .PARAMETER ExcludeSystemLogins
        If this switch is enabled, NT SERVICE accounts will be skipped.

    .PARAMETER ExcludePermissionSync
        Skips permission syncs

    .PARAMETER SyncOnly
        If this switch is enabled, only SQL Server login permissions, roles, etc. will be synced. Logins and users will not be added or dropped.  If a matching Login does not exist on the destination, the Login will be skipped.
        Credential removal is not currently supported for this parameter.

    .PARAMETER SyncSaName
        If this switch is enabled, the name of the sa account will be synced between Source and Destination

    .PARAMETER OutFile
        Calls Export-DbaLogin and exports all logins to a T-SQL formatted file. This does not perform a copy, so no destination is required.

    .PARAMETER InputObject
        Takes the parameters required from a Login object that has been piped into the command

    .PARAMETER LoginRenameHashtable
        Pass a hash table into this parameter to be passed into Rename-DbaLogin to update the Login and mappings after the Login is completed.

    .PARAMETER KillActiveConnection
        If this switch and -Force are enabled, all active connections and sessions on Destination will be killed.

        A login cannot be dropped when it has active connections on the instance.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER Force
        If this switch is enabled, the Login(s) will be dropped and recreated on Destination. Logins that own Agent jobs cannot be dropped at this time.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration, Login
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        https://dbatools.io/Copy-DbaLogin

    .EXAMPLE
        PS C:\> Copy-DbaLogin -Source sqlserver2014a -Destination sqlcluster -Force

        Copies all logins from Source Destination. If a SQL Login on Source exists on the Destination, the Login on Destination will be dropped and recreated.

        If active connections are found for a login, the copy of that Login will fail as it cannot be dropped.

    .EXAMPLE
        PS C:\> Copy-DbaLogin -Source sqlserver2014a -Destination sqlcluster -Force -KillActiveConnection

        Copies all logins from Source Destination. If a SQL Login on Source exists on the Destination, the Login on Destination will be dropped and recreated.

        If any active connections are found they will be killed.

    .EXAMPLE
        PS C:\> Copy-DbaLogin -Source sqlserver2014a -Destination sqlcluster -ExcludeLogin realcajun -SourceSqlCredential $scred -DestinationSqlCredential $dcred

        Copies all Logins from Source to Destination except for realcajun using SQL Authentication to connect to both instances.

        If a Login already exists on the destination, it will not be migrated.

    .EXAMPLE
        PS C:\> Copy-DbaLogin -Source sqlserver2014a -Destination sqlcluster -Login realcajun, netnerds -force

        Copies ONLY Logins netnerds and realcajun. If Login realcajun or netnerds exists on Destination, the existing Login(s) will be dropped and recreated.

    .EXAMPLE
        PS C:\> Copy-DbaLogin -Source sqlserver2014a -Destination sqlcluster -SyncOnly

        Syncs only SQL Server login permissions, roles, etc. Does not add or drop logins or users.

        If a matching Login does not exist on Destination, the Login will be skipped.

    .EXAMPLE
        PS C:\> Copy-DbaLogin -LoginRenameHashtable @{ "PreviousUser" = "newlogin" } -Source $Sql01 -Destination Localhost -SourceSqlCredential $sqlcred

        Copies PreviousUser and then renames it to newlogin.

    .EXAMPLE
        PS C:\> Get-DbaLogin -SqlInstance sql2016 | Out-GridView -Passthru | Copy-DbaLogin -Destination sql2017

        Displays all available logins on sql2016 in a grid view, then copies all selected logins to sql2017.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(ParameterSetName = "SqlInstance", Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]$SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]$DestinationSqlCredential,
        [object[]]$Login,
        [object[]]$ExcludeLogin,
        [switch]$ExcludeSystemLogins,
        [switch]$SyncOnly,
        [parameter(ParameterSetName = "Live")]
        [parameter(ParameterSetName = "SqlInstance")]
        [switch]$SyncSaName,
        [parameter(ParameterSetName = "File", Mandatory)]
        [string]$OutFile,
        [parameter(ParameterSetName = "InputObject", ValueFromPipeline)]
        [object]$InputObject,
        [hashtable]$LoginRenameHashtable,
        [switch]$KillActiveConnection,
        [switch]$Force,
        [switch]$ExcludePermissionSync,
        [switch]$EnableException
    )

    begin {
        function Copy-Login {
            foreach ($sourceLogin in $sourceServer.Logins) {
                $userName = $sourceLogin.name

                $copyLoginStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Type              = "Login - $($sourceLogin.LoginType)"
                    Name              = $userName
                    DestinationLogin  = $userName
                    SourceLogin       = $userName
                    Status            = $null
                    Notes             = $null
                    DateTime          = [DbaDateTime](Get-Date)
                }

                if ($Login -and $Login -notcontains $userName -or $ExcludeLogin -contains $userName) { continue }

                if ($sourceLogin.id -eq 1) { continue }

                if ($userName.StartsWith("##") -or $userName -eq 'sa') {
                    Write-Message -Level Verbose -Message "Skipping $userName."
                    continue
                }

                $serverName = Resolve-NetBiosName $sourceServer

                $currentLogin = $sourceServer.ConnectionContext.truelogin

                if ($currentLogin -eq $userName -and $force) {
                    if ($Pscmdlet.ShouldProcess("console", "Stating $userName is skipped because it is performing the migration.")) {
                        Write-Message -Level Verbose -Message "Cannot drop login performing the migration. Skipping."
                        $copyLoginStatus.Status = "Skipped"
                        $copyLoginStatus.Notes = "Current login"
                        $copyLoginStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    }
                    continue
                }

                if (($destServer.LoginMode -ne [Microsoft.SqlServer.Management.Smo.ServerLoginMode]::Mixed) -and ($sourceLogin.LoginType -eq [Microsoft.SqlServer.Management.Smo.LoginType]::SqlLogin)) {
                    Write-Message -Level Verbose -Message "$Destination does not have Mixed Mode enabled. [$userName] is an SQL Login. Enable mixed mode authentication after the migration completes to use this type of login."
                }

                $userBase = ($userName.Split("\")[0]).ToLower()

                if ($serverName -eq $userBase -or $userName.StartsWith("NT ")) {
                    if ($sourceServer.ComputerName -ne $destServer.ComputerName) {
                        if ($Pscmdlet.ShouldProcess("console", "Stating $userName was skipped because it is a local machine name.")) {
                            Write-Message -Level Verbose -Message "$userName was skipped because it is a local machine name."
                            $copyLoginStatus.Status = "Skipped"
                            $copyLoginStatus.Notes = "Local machine name"
                            $copyLoginStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        }
                        continue
                    } else {
                        if ($ExcludeSystemLogins) {
                            if ($Pscmdlet.ShouldProcess("console", "$userName was skipped because ExcludeSystemLogins was specified.")) {
                                Write-Message -Level Verbose -Message "$userName was skipped because ExcludeSystemLogins was specified."

                                $copyLoginStatus.Status = "Skipped"
                                $copyLoginStatus.Notes = "System login"
                                $copyLoginStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                            }
                            continue
                        }

                        if ($Pscmdlet.ShouldProcess("console", "Stating local login $userName since the source and destination server reside on the same machine.")) {
                            Write-Message -Level Verbose -Message "Copying local login $userName since the source and destination server reside on the same machine."
                        }
                    }
                }

                if ($null -ne $destServer.Logins.Item($userName) -and !$force) {
                    if ($Pscmdlet.ShouldProcess("console", "Stating $userName is skipped because it exists at destination.")) {
                        Write-Message -Level Verbose -Message "$userName already exists in destination. Use -Force to drop and recreate."
                        $copyLoginStatus.Status = "Skipped"
                        $copyLoginStatus.Notes = "Already exists on destination"
                        $copyLoginStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    }
                    continue
                }

                if ($null -ne $destServer.Logins.Item($userName) -and $force) {
                    if ($userName -eq $destServer.ServiceAccount) {
                        if ($Pscmdlet.ShouldProcess("console", "$userName is the destination service account. Skipping drop.")) {
                            Write-Message -Level Verbose -Message "$userName is the destination service account. Skipping drop."

                            $copyLoginStatus.Status = "Skipped"
                            $copyLoginStatus.Notes = "Destination service account"
                            $copyLoginStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        }
                        continue
                    }

                    if ($Pscmdlet.ShouldProcess($destinstance, "Dropping $userName")) {

                        # Kill connections, delete user
                        Write-Message -Level Verbose -Message "Attempting to migrate $userName"
                        Write-Message -Level Verbose -Message "Force was specified. Attempting to drop $userName on $destinstance."

                        try {
                            $ownedDbs = $destServer.Databases | Where-Object Owner -eq $userName

                            foreach ($ownedDb in $ownedDbs) {
                                Write-Message -Level Verbose -Message "Changing database owner for $($ownedDb.name) from $userName to sa."
                                $ownedDb.SetOwner('sa')
                                $ownedDb.Alter()
                            }

                            $ownedJobs = $destServer.JobServer.Jobs | Where-Object OwnerLoginName -eq $userName

                            foreach ($ownedJob in $ownedJobs) {
                                Write-Message -Level Verbose -Message "Changing job owner for $($ownedJob.name) from $userName to sa."
                                $ownedJob.Set_OwnerLoginName('sa')
                                $ownedJob.Alter()
                            }

                            $activeConnections = $destServer.EnumProcesses() | Where-Object Login -eq $userName

                            if ($activeConnections -and $KillActiveConnection) {
                                if (!$destServer.Logins.Item($userName).IsDisabled) {
                                    $disabled = $true
                                    $destServer.Logins.Item($userName).Disable()
                                }

                                $activeConnections | ForEach-Object { $destServer.KillProcess($_.Spid) }
                                Write-Message -Level Verbose -Message "-KillActiveConnection was provided. There are $($activeConnections.Count) active connections killed."
                                # just in case the kill didn't work, it'll leave behind a disabled account
                                if ($disabled) { $destServer.Logins.Item($userName).Enable() }
                            } elseif ($activeConnections) {
                                Write-Message -Level Verbose -Message "There are $($activeConnections.Count) active connections found for the login $userName. Utilize -KillActiveConnection with -Force to kill the connections."
                            }
                            $destServer.Logins.Item($userName).Drop()

                            Write-Message -Level Verbose -Message "Successfully dropped $userName on $destinstance."
                        } catch {
                            $copyLoginStatus.Status = "Failed"
                            $copyLoginStatus.Notes = (Get-ErrorMessage -Record $_).Message
                            $copyLoginStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                            Stop-Function -Message "Could not drop $userName." -Category InvalidOperation -ErrorRecord $_ -Target $destServer -Continue 3>$null
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destinstance, "Adding SQL login $userName")) {

                    Write-Message -Level Verbose -Message "Attempting to add $userName to $destinstance."
                    $destLogin = New-Object Microsoft.SqlServer.Management.Smo.Login($destServer, $userName)

                    Write-Message -Level Verbose -Message "Setting $userName SID to source username SID."
                    $destLogin.Set_Sid($sourceLogin.Get_Sid())

                    $defaultDb = $sourceLogin.DefaultDatabase

                    Write-Message -Level Verbose -Message "Setting login language to $($sourceLogin.Language)."
                    $destLogin.Language = $sourceLogin.Language

                    if ($null -eq $destServer.databases[$defaultDb]) {
                        # we end up here when the default database on source doesn't exist on dest
                        # if source login is a sysadmin, then set the default database to master
                        # if not, set it to tempdb (see #303)
                        $OrigdefaultDb = $defaultDb
                        try { $sourcesysadmins = $sourceServer.roles['sysadmin'].EnumMemberNames() }
                        catch { $sourcesysadmins = $sourceServer.roles['sysadmin'].EnumServerRoleMembers() }
                        if ($sourcesysadmins -contains $userName) {
                            $defaultDb = "master"
                        } else {
                            $defaultDb = "tempdb"
                        }
                        Write-Message -Level Verbose -Message "$OrigdefaultDb does not exist on destination. Setting defaultdb to $defaultDb."
                    }

                    Write-Message -Level Verbose -Message "Set $userName defaultdb to $defaultDb."
                    $destLogin.DefaultDatabase = $defaultDb

                    $checkexpiration = "ON"; $checkpolicy = "ON"

                    if ($sourceLogin.PasswordPolicyEnforced -eq $false) { $checkpolicy = "OFF" }

                    if (!$sourceLogin.PasswordExpirationEnabled) { $checkexpiration = "OFF" }

                    $destLogin.PasswordPolicyEnforced = $sourceLogin.PasswordPolicyEnforced
                    $destLogin.PasswordExpirationEnabled = $sourceLogin.PasswordExpirationEnabled

                    # Attempt to add SQL Login User
                    if ($sourceLogin.LoginType -eq "SqlLogin") {
                        $destLogin.LoginType = "SqlLogin"
                        $sourceLoginname = $sourceLogin.name

                        switch ($sourceServer.versionMajor) {
                            0 { $sql = "SELECT CONVERT(VARBINARY(256),password) as hashedpass FROM master.dbo.syslogins WHERE loginname='$sourceLoginname'" }
                            8 { $sql = "SELECT CONVERT(VARBINARY(256),password) as hashedpass FROM dbo.syslogins WHERE name='$sourceLoginname'" }
                            9 { $sql = "SELECT CONVERT(VARBINARY(256),password_hash) as hashedpass FROM sys.sql_logins where name='$sourceLoginname'" }
                            default {
                                $sql = "SELECT CAST(CONVERT(VARCHAR(256), CAST(LOGINPROPERTY(name,'PasswordHash')
                        AS VARBINARY(256)), 1) AS NVARCHAR(max)) AS hashedpass FROM sys.server_principals
                        WHERE principal_id = $($sourceLogin.id)"
                            }
                        }

                        try {
                            $hashedPass = $sourceServer.ConnectionContext.ExecuteScalar($sql)
                        } catch {
                            $hashedPassDt = $sourceServer.Databases['master'].ExecuteWithResults($sql)
                            $hashedPass = $hashedPassDt.Tables[0].Rows[0].Item(0)
                        }

                        if ($hashedPass.GetType().Name -ne "String") {
                            $passString = "0x"; $hashedPass | ForEach-Object { $passString += ("{0:X}" -f $_).PadLeft(2, "0") }
                            $hashedPass = $passString
                        }

                        try {
                            $destLogin.Create($hashedPass, [Microsoft.SqlServer.Management.Smo.LoginCreateOptions]::IsHashed)
                            $destLogin.Refresh()
                            Write-Message -Level Verbose -Message "Successfully added $userName to $destinstance."

                            $copyLoginStatus.Status = "Successful"
                            $copyLoginStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        } catch {
                            try {
                                $sid = "0x"; $sourceLogin.sid | ForEach-Object { $sid += ("{0:X}" -f $_).PadLeft(2, "0") }
                                $sql = "CREATE LOGIN [$userName] WITH PASSWORD = $hashedPass HASHED, SID = $sid,
                                                DEFAULT_DATABASE = [$defaultDb], CHECK_POLICY = $checkpolicy,
                                                CHECK_EXPIRATION = $checkexpiration, DEFAULT_LANGUAGE = [$($sourceLogin.Language)]"

                                $null = $destServer.Query($sql)

                                $destLogin = $destServer.logins[$userName]
                                Write-Message -Level Verbose -Message "Successfully added $userName to $destinstance."

                                $copyLoginStatus.Status = "Successful"
                                $copyLoginStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                            } catch {
                                $copyLoginStatus.Status = "Failed"
                                $copyLoginStatus.Notes = (Get-ErrorMessage -Record $_).Message
                                $copyLoginStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                                Stop-Function -Message "Failed to add $userName to $destinstance." -Category InvalidOperation -ErrorRecord $_ -Target $destServer -Continue 3>$null
                            }
                        }
                    }
                    # Attempt to add Windows User
                    elseif ($sourceLogin.LoginType -eq "WindowsUser" -or $sourceLogin.LoginType -eq "WindowsGroup") {
                        Write-Message -Level Verbose -Message "Adding as login type $($sourceLogin.LoginType)"
                        $destLogin.LoginType = $sourceLogin.LoginType

                        Write-Message -Level Verbose -Message "Setting language as $($sourceLogin.Language)"
                        $destLogin.Language = $sourceLogin.Language

                        try {
                            $destLogin.Create()
                            $destLogin.Refresh()
                            Write-Message -Level Verbose -Message "Successfully added $userName to $destinstance."

                            $copyLoginStatus.Status = "Successful"
                            $copyLoginStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        } catch {
                            $copyLoginStatus.Status = "Failed"
                            $copyLoginStatus.Notes = (Get-ErrorMessage -Record $_).Message
                            $copyLoginStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                            Stop-Function -Message "Failed to add $userName to $destinstance" -Category InvalidOperation -ErrorRecord $_ -Target $destServer -Continue 3>$null
                        }
                    }
                    # This script does not currently support certificate mapped or asymmetric key users.
                    else {
                        Write-Message -Level Verbose -Message "$($sourceLogin.LoginType) logins not supported. $($sourceLogin.name) skipped."

                        $copyLoginStatus.Status = "Skipped"
                        $copyLoginStatus.Notes = "$($sourceLogin.LoginType) not supported"
                        $copyLoginStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        continue
                    }

                    if ($sourceLogin.IsDisabled) {
                        try {
                            $destLogin.Disable()
                        } catch {
                            $copyLoginStatus.Status = "Successful - but could not disable on destination"
                            $copyLoginStatus.Notes = (Get-ErrorMessage -Record $_).Message
                            $copyLoginStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                            Stop-Function -Message "$userName disabled on source, could not be disabled on $destinstance." -Category InvalidOperation -ErrorRecord $_ -Target $destServer  3>$null
                        }
                    }
                    if ($sourceLogin.DenyWindowsLogin) {
                        try {
                            $destLogin.DenyWindowsLogin = $true
                        } catch {
                            $copyLoginStatus.Status = "Successful - but could not deny login on destination"
                            $copyLoginStatus.Notes = (Get-ErrorMessage -Record $_).Message
                            $copyLoginStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                            Stop-Function -Message "$userName denied login on source, could not be denied login on $destinstance." -Category InvalidOperation -ErrorRecord $_ -Target $destServer 3>$null
                        }
                    }
                }

                if (-not $ExcludePermissionSync) {
                    if ($Pscmdlet.ShouldProcess($destinstance, "Updating SQL login $userName permissions")) {
                        Update-SqlPermission -sourceserver $sourceServer -sourcelogin $sourceLogin -destserver $destServer -destlogin $destLogin
                    }
                }

                if ($LoginRenameHashtable.Keys -contains $userName) {
                    $NewLogin = $LoginRenameHashtable[$userName]

                    if ($Pscmdlet.ShouldProcess($destinstance, "Renaming SQL Login $userName to $NewLogin")) {
                        try {
                            Rename-DbaLogin -SqlInstance $destServer -Login $userName -NewLogin $NewLogin

                            $copyLoginStatus.DestinationLogin = $NewLogin
                            $copyLoginStatus.Status = "Successful"
                            $copyLoginStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        } catch {
                            $copyLoginStatus.DestinationLogin = $NewLogin
                            $copyLoginStatus.Status = "Failed to rename"
                            $copyLoginStatus.Notes = (Get-ErrorMessage -Record $_).Message
                            $copyLoginStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                            Stop-Function -Message "Issue renaming $userName to $NewLogin" -Category InvalidOperation -ErrorRecord $_ -Target $destServer 3>$null
                        }
                    }
                }
            }
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }
        if ($InputObject) {
            $Source = $InputObject[0].Parent.Name
            $Sourceserver = $InputObject[0].Parent
            $Login = $InputObject.Name
        } else {
            try {
                $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
                return
            }
        }
        $sourceVersionMajor = $sourceServer.VersionMajor

        if ($OutFile) {
            Export-DbaLogin -SqlInstance $sourceServer -FilePath $OutFile -Login $Login -ExcludeLogin $ExcludeLogin
            continue
        }

        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }

            $destVersionMajor = $destServer.VersionMajor
            if ($sourceVersionMajor -gt 10 -and $destVersionMajor -lt 11) {
                Stop-Function -Message "Login migration from version $sourceVersionMajor to $destVersionMajor is not supported." -Category InvalidOperation -ErrorRecord $_ -Target $sourceServer
            }

            if ($sourceVersionMajor -lt 8 -or $destVersionMajor -lt 8) {
                Stop-Function -Message "SQL Server 7 and below are not supported." -Category InvalidOperation -ErrorRecord $_ -Target $sourceServer
            }

            if ($SyncOnly) {
                if ($Pscmdlet.ShouldProcess($destinstance, "Syncing $Login permissions")) {
                    Sync-DbaLoginPermission -Source $sourceServer -Destination $destServer -Login $Login -ExcludeLogin $ExcludeLogin
                    continue
                }
            }

            Write-Message -Level Verbose -Message "Attempting Login Migration."
            Copy-Login -sourceserver $sourceServer -destserver $destServer -Login $Login -Exclude $ExcludeLogin

            if ($SyncSaName) {
                $sa = $sourceServer.Logins | Where-Object id -eq 1
                $destSa = $destServer.Logins | Where-Object id -eq 1
                $saName = $sa.Name
                if ($saName -ne $destSa.name) {
                    Write-Message -Level Verbose -Message "Changing sa username to match source ($saName)."
                    if ($Pscmdlet.ShouldProcess($destinstance, "Changing sa username to match source ($saName)")) {
                        $destSa.Rename($saName)
                        $destSa.Alter()
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlLogin
    }
}
tools\dbatools\functions\Copy-DbaPolicyManagement.ps1
function Copy-DbaPolicyManagement {
    <#
    .SYNOPSIS
        Migrates SQL Policy Based Management Objects, including both policies and conditions.

    .DESCRIPTION
        By default, all policies and conditions are copied. If an object already exist on the destination, it will be skipped unless -Force is used.

        The -Policy and -Condition parameters are auto-populated for command-line completion and can be used to copy only specific objects.

    .PARAMETER Source
        Source SQL Server.You must have sysadmin access and server version must be SQL Server version 2008 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination Sql Server. You must have sysadmin access and server version must be SQL Server version 2008 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Policy
        The policy(ies) to process - this list is auto-populated from the server. If unspecified, all policies will be processed.

    .PARAMETER ExcludePolicy
        The policy(ies) to exclude - this list is auto-populated from the server

    .PARAMETER Condition
        The condition(s) to process - this list is auto-populated from the server. If unspecified, all conditions will be processed.

    .PARAMETER ExcludeCondition
        The condition(s) to exclude - this list is auto-populated from the server

    .PARAMETER Force
        If policies exists on destination server, it will be dropped and recreated.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        https://dbatools.io/Copy-DbaPolicyManagement

    .EXAMPLE
        PS C:\> Copy-DbaPolicyManagement -Source sqlserver2014a -Destination sqlcluster

        Copies all policies and conditions from sqlserver2014a to sqlcluster, using Windows credentials.

    .EXAMPLE
        PS C:\> Copy-DbaPolicyManagement -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred

        Copies all policies and conditions from sqlserver2014a to sqlcluster, using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster.

    .EXAMPLE
        PS C:\> Copy-DbaPolicyManagement -Source sqlserver2014a -Destination sqlcluster -WhatIf

        Shows what would happen if the command were executed.

    .EXAMPLE
        PS C:\> Copy-DbaPolicyManagement -Source sqlserver2014a -Destination sqlcluster -Policy 'xp_cmdshell must be disabled'

        Copies only one policy, 'xp_cmdshell must be disabled' from sqlserver2014a to sqlcluster. No conditions are migrated.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]
        $SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]
        $DestinationSqlCredential,
        [object[]]$Policy,
        [object[]]$ExcludePolicy,
        [object[]]$Condition,
        [object[]]$ExcludeCondition,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )
    
    begin {
        if (-not $script:isWindows) {
            Stop-Function -Message "Copy-DbaPolicyManagement does not support Linux - we're still waiting for the Core SMOs from Microsoft"
            return
        }
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential -MinimumVersion 10
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }
        $sourceSqlConn = $sourceServer.ConnectionContext.SqlConnectionObject
        $sourceSqlStoreConnection = New-Object Microsoft.SqlServer.Management.Sdk.Sfc.SqlStoreConnection $sourceSqlConn
        $sourceStore = New-Object  Microsoft.SqlServer.Management.DMF.PolicyStore $sourceSqlStoreConnection
        $storePolicies = $sourceStore.Policies | Where-Object { $_.IsSystemObject -eq $false }
        $storeConditions = $sourceStore.Conditions | Where-Object { $_.IsSystemObject -eq $false }
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }
            $destSqlConn = $destServer.ConnectionContext.SqlConnectionObject
            $destSqlStoreConnection = New-Object Microsoft.SqlServer.Management.Sdk.Sfc.SqlStoreConnection $destSqlConn
            $destStore = New-Object  Microsoft.SqlServer.Management.DMF.PolicyStore $destSqlStoreConnection

            if ($Policy) {
                $storePolicies = $storePolicies | Where-Object Name -In $Policy
            }
            if ($ExcludePolicy) {
                $storePolicies = $storePolicies | Where-Object Name -NotIn $ExcludePolicy
            }
            if ($Condition) {
                $storeConditions = $storeConditions | Where-Object Name -In $Condition
            }
            if ($ExcludeCondition) {
                $storeConditions = $storeConditions | Where-Object Name -NotIn $ExcludeCondition
            }

            if ($Policy -and $Condition) {
                $storeConditions = $null
                $storePolicies = $null
            }

            <#
                        Conditions
        #>

            Write-Message -Level Verbose -Message "Migrating conditions"
            foreach ($condition in $storeConditions) {
                $conditionName = $condition.Name

                $copyConditionStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Name              = $conditionName
                    Type              = "Policy Condition"
                    Status            = $null
                    Notes             = $null
                    DateTime          = [DbaDateTime](Get-Date)
                }

                if ($null -ne $destStore.Conditions[$conditionName]) {
                    if ($force -eq $false) {
                        Write-Message -Level Verbose -Message "condition '$conditionName' was skipped because it already exists on $destinstance. Use -Force to drop and recreate"

                        $copyConditionStatus.Status = "Skipped"
                        $copyConditionStatus.Notes = "Already exists on destination"
                        $copyConditionStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        continue
                    } else {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Attempting to drop $conditionName")) {
                            Write-Message -Level Verbose -Message "Condition '$conditionName' exists on $destinstance. Force specified. Dropping $conditionName."

                            try {
                                $dependentPolicies = $destStore.Conditions[$conditionName].EnumDependentPolicies()
                                foreach ($dependent in $dependentPolicies) {
                                    $dependent.Drop()
                                    $destStore.Conditions.Refresh()
                                }
                                $destStore.Conditions[$conditionName].Drop()
                            } catch {
                                $copyConditionStatus.Status = "Failed"
                                $copyConditionStatus.Notes = (Get-ErrorMessage -Record $_).Message
                                $copyConditionStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                Stop-Function -Message "Issue dropping condition on $destinstance" -Target $conditionName -ErrorRecord $_ -Continue
                            }
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destinstance, "Migrating condition $conditionName")) {
                    try {
                        $sql = $condition.ScriptCreate().GetScript() | Out-String
                        Write-Message -Level Debug -Message $sql
                        Write-Message -Level Verbose -Message "Copying condition $conditionName"
                        $null = $destServer.Query($sql)
                        $destStore.Conditions.Refresh()

                        $copyConditionStatus.Status = "Successful"
                        $copyConditionStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    } catch {
                        $copyConditionStatus.Status = "Failed"
                        $copyConditionStatus.Notes = (Get-ErrorMessage -Record $_).Message
                        $copyConditionStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        Stop-Function -Message "Issue creating condition on $destinstance" -Target $conditionName -ErrorRecord $_
                    }
                }
            }

            <#
                        Policies
        #>

            Write-Message -Level Verbose -Message "Migrating policies"
            foreach ($policy in $storePolicies) {
                $policyName = $policy.Name

                $copyPolicyStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Name              = $policyName
                    Type              = "Policy"
                    Status            = $null
                    Notes             = $null
                    DateTime          = [DbaDateTime](Get-Date)
                }

                if ($null -ne $destStore.Policies[$policyName]) {
                    if ($force -eq $false) {
                        Write-Message -Level Verbose -Message "Policy '$policyName' was skipped because it already exists on $destinstance. Use -Force to drop and recreate"

                        $copyPolicyStatus.Status = "Skipped"
                        $copyPolicyStatus.Notes = "Already exists on destination"
                        $copyPolicyStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        continue
                    } else {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Attempting to drop $policyName")) {
                            Write-Message -Level Verbose -Message "Policy '$policyName' exists on $destinstance. Force specified. Dropping $policyName."

                            try {
                                $destStore.Policies[$policyName].Drop()
                                $destStore.Policies.refresh()
                            } catch {
                                $copyPolicyStatus.Status = "Failed"
                                $copyPolicyStatus.Notes = (Get-ErrorMessage -Record $_).Message
                                $copyPolicyStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                                Stop-Function -Message "Issue dropping policy on $destinstance" -Target $policyName -ErrorRecord $_ -Continue
                            }
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destinstance, "Migrating policy $policyName")) {
                    try {
                        $destStore.Conditions.Refresh()
                        $destStore.Policies.Refresh()
                        $sql = $policy.ScriptCreateWithDependencies().GetScript() | Out-String
                        Write-Message -Level Debug -Message $sql
                        Write-Message -Level Verbose -Message "Copying policy $policyName"
                        $null = $destServer.Query($sql)

                        $copyPolicyStatus.Status = "Successful"
                        $copyPolicyStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    } catch {
                        $copyPolicyStatus.Status = "Failed"
                        $copyPolicyStatus.Notes = (Get-ErrorMessage -Record $_).Message
                        $copyPolicyStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        # This is usually because of a duplicate dependent from above. Just skip for now.
                        Stop-Function -Message "Issue creating policy on $destinstance" -Target $policyName -ErrorRecord $_ -Continue
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlPolicyManagement
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-DbaSqlPolicyManagement
    }
}
tools\dbatools\functions\Copy-DbaResourceGovernor.ps1
function Copy-DbaResourceGovernor {
    <#
    .SYNOPSIS
        Migrates Resource Pools

    .DESCRIPTION
        By default, all non-system resource pools are migrated. If the pool already exists on the destination, it will be skipped unless -Force is used.

        The -ResourcePool parameter is auto-populated for command-line completion and can be used to copy only specific objects.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2008 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2008 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER ResourcePool
        Specifies the resource pool(s) to process. Options for this list are auto-populated from the server. If unspecified, all resource pools will be processed.

    .PARAMETER ExcludeResourcePool
        Specifies the resource pool(s) to exclude. Options for this list are auto-populated from the server

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER Force
        If this switch is enabled, the policies will be dropped and recreated on Destination.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration, ResourceGovernor
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        https://dbatools.io/Copy-DbaResourceGovernor

    .EXAMPLE
        PS C:\> Copy-DbaResourceGovernor -Source sqlserver2014a -Destination sqlcluster

        Copies all all non-system resource pools from sqlserver2014a to sqlcluster using Windows credentials to connect to the SQL Server instances..

    .EXAMPLE
        PS C:\> Copy-DbaResourceGovernor -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred

        Copies all all non-system resource pools from sqlserver2014a to sqlcluster using SQL credentials to connect to sqlserver2014a and Windows credentials to connect to sqlcluster.

    .EXAMPLE
        PS C:\> Copy-DbaResourceGovernor -Source sqlserver2014a -Destination sqlcluster -WhatIf

        Shows what would happen if the command were executed.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]$SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]$DestinationSqlCredential,
        [object[]]$ResourcePool,
        [object[]]$ExcludeResourcePool,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential -MinimumVersion 10
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }
        $sourceClassifierFunction = Get-DbaRgClassifierFunction -SqlInstance $sourceServer

        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }
            $destClassifierFunction = Get-DbaRgClassifierFunction -SqlInstance $destServer

            $copyResourceGovSetting = [pscustomobject]@{
                SourceServer      = $sourceServer.Name
                DestinationServer = $destServer.Name
                Type              = "Resource Governor Settings"
                Name              = "All Settings"
                Status            = $null
                Notes             = $null
                DateTime          = [DbaDateTime](Get-Date)
            }

            $copyResourceGovClassifierFunc = [pscustomobject]@{
                SourceServer      = $sourceServer.Name
                DestinationServer = $destServer.Name
                Type              = "Resource Governor Settings"
                Name              = "Classifier Function"
                Status            = $null
                Notes             = $null
                DateTime          = [DbaDateTime](Get-Date)
            }

            if ($Pscmdlet.ShouldProcess($destinstance, "Updating Resource Governor settings")) {
                if ($destServer.Edition -notmatch 'Enterprise' -and $destServer.Edition -notmatch 'Datacenter' -and $destServer.Edition -notmatch 'Developer') {
                    Write-Message -Level Verbose -Message "The resource governor is not available in this edition of SQL Server. You can manipulate resource governor metadata but you will not be able to apply resource governor configuration. Only Enterprise edition of SQL Server supports resource governor."
                } else {
                    try {
                        Write-Message -Level Verbose -Message "Managing classifier function."
                        if (!$sourceClassifierFunction) {
                            $copyResourceGovClassifierFunc.Status = "Skipped"
                            $copyResourceGovClassifierFunc.Notes = $null
                            $copyResourceGovClassifierFunc | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        } else {
                            $fullyQualifiedFunctionName = $sourceClassifierFunction.Schema + "." + $sourceClassifierFunction.Name

                            if (!$destClassifierFunction) {
                                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential
                                $destFunction = $destServer.Databases["master"].UserDefinedFunctions[$sourceClassifierFunction.Name]
                                if ($destFunction) {
                                    Write-Message -Level Verbose -Message "Dropping the function with the source classifier function name."
                                    $destFunction.Drop()
                                }

                                Write-Message -Level Verbose -Message "Creating function."
                                $destServer.Query($sourceClassifierFunction.Script())

                                $sql = "ALTER RESOURCE GOVERNOR WITH (CLASSIFIER_FUNCTION = $fullyQualifiedFunctionName);"
                                Write-Message -Level Debug -Message $sql
                                Write-Message -Level Verbose -Message "Mapping Resource Governor classifier function."
                                $destServer.Query($sql)

                                $copyResourceGovClassifierFunc.Status = "Successful"
                                $copyResourceGovClassifierFunc.Notes = "The new classifier function has been created"
                                $copyResourceGovClassifierFunc | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                                $sql = "ALTER RESOURCE GOVERNOR RECONFIGURE;"
                                Write-Message -Level Debug -Message $sql
                                Write-Message -Level Verbose -Message "Reconfiguring Resource Governor."
                                $destServer.Query($sql)
                            } else {
                                if ($Force -eq $false) {
                                    $copyResourceGovClassifierFunc.Status = "Skipped"
                                    $copyResourceGovClassifierFunc.Notes = "Already exists on destination"
                                    $copyResourceGovClassifierFunc | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                } else {

                                    $sql = "ALTER RESOURCE GOVERNOR WITH (CLASSIFIER_FUNCTION = NULL);"
                                    Write-Message -Level Debug -Message $sql
                                    Write-Message -Level Verbose -Message "Disabling the Resource Governor."
                                    $destServer.Query($sql)

                                    $sql = "ALTER RESOURCE GOVERNOR RECONFIGURE;"
                                    Write-Message -Level Debug -Message $sql
                                    Write-Message -Level Verbose -Message "Reconfiguring Resource Governor."
                                    $destServer.Query($sql)

                                    Write-Message -Level Verbose -Message "Dropping the destination classifier function."
                                    $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential
                                    $destFunction = $destServer.Databases["master"].UserDefinedFunctions[$sourceClassifierFunction.Name]
                                    $destClassifierFunction.Drop()

                                    Write-Message -Level Verbose -Message "Re-creating the Resource Governor classifier function."
                                    $destServer.Query($sourceClassifierFunction.Script())

                                    $sql = "ALTER RESOURCE GOVERNOR WITH (CLASSIFIER_FUNCTION = $fullyQualifiedFunctionName);"
                                    Write-Message -Level Debug -Message $sql
                                    Write-Message -Level Verbose -Message "Mapping Resource Governor classifier function."
                                    $destServer.Query($sql)

                                    $sql = "ALTER RESOURCE GOVERNOR RECONFIGURE;"
                                    Write-Message -Level Debug -Message $sql
                                    Write-Message -Level Verbose -Message "Reconfiguring Resource Governor."
                                    $destServer.Query($sql)

                                    $copyResourceGovClassifierFunc.Status = "Successful"
                                    $copyResourceGovClassifierFunc.Notes = "The old classifier function has been overwritten."
                                    $copyResourceGovClassifierFunc | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                                }
                            }
                        }
                    } catch {
                        $copyResourceGovSetting.Status = "Failed"
                        $copyResourceGovSetting.Notes = (Get-ErrorMessage -Record $_)
                        $copyResourceGovSetting | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        $sql = "ALTER RESOURCE GOVERNOR RECONFIGURE;"
                        Write-Message -Level Debug -Message $sql
                        Write-Message -Level Verbose -Message "Reconfiguring Resource Governor."
                        $destServer.Query($sql)

                        Stop-Function -Message "Not able to update settings." -Target $destServer -ErrorRecord $_
                    }
                }
            }

            # Pools
            if ($ResourcePool) {
                $pools = $sourceServer.ResourceGovernor.ResourcePools | Where-Object Name -In $ResourcePool
            } elseif ($ExcludeResourcePool) {
                $pool = $sourceServer.ResourceGovernor.ResourcePools | Where-Object Name -NotIn $ExcludeResourcePool
            } else {
                $pools = $sourceServer.ResourceGovernor.ResourcePools | Where-Object { $_.Name -notin "internal", "default" }
            }

            Write-Message -Level Verbose -Message "Migrating pools."
            foreach ($pool in $pools) {
                $poolName = $pool.Name

                $copyResourceGovPool = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Type              = "Resource Governor Pool"
                    Name              = $poolName
                    Status            = $null
                    Notes             = $null
                    DateTime          = [DbaDateTime](Get-Date)
                }

                if ($null -ne $destServer.ResourceGovernor.ResourcePools[$poolName]) {
                    if ($force -eq $false) {
                        Write-Message -Level Verbose -Message "Pool '$poolName' was skipped because it already exists on $destinstance. Use -Force to drop and recreate."

                        $copyResourceGovPool.Status = "Skipped"
                        $copyResourceGovPool.Notes = "Already exists on destination"
                        $copyResourceGovPool | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        continue
                    } else {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Attempting to drop $poolName")) {
                            Write-Message -Level Verbose -Message "Pool '$poolName' exists on $destinstance."
                            Write-Message -Level Verbose -Message "Force specified. Dropping $poolName."

                            try {
                                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential
                                $destPool = $destServer.ResourceGovernor.ResourcePools[$poolName]
                                $workloadGroups = $destPool.WorkloadGroups
                                foreach ($workloadGroup in $workloadGroups) {
                                    $workloadGroup.Drop()
                                }
                                $destPool.Drop()
                                $destServer.ResourceGovernor.Alter()
                            } catch {
                                $copyResourceGovPool.Status = "Failed to drop from Destination"
                                $copyResourceGovPool.Notes = (Get-ErrorMessage -Record $_)
                                $copyResourceGovPool | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                                Stop-Function -Message "Unable to drop: $_ Moving on." -Target $destPool -ErrorRecord $_ -Continue

                                $sql = "ALTER RESOURCE GOVERNOR RECONFIGURE;"
                                Write-Message -Level Debug -Message $sql
                                Write-Message -Level Verbose -Message "Reconfiguring Resource Governor."
                                $destServer.Query($sql)
                            }
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destinstance, "Migrating pool $poolName")) {
                    try {
                        $sql = $pool.Script() | Out-String
                        Write-Message -Level Debug -Message $sql
                        Write-Message -Level Verbose -Message "Copying pool $poolName."
                        $destServer.Query($sql)

                        $copyResourceGovPool.Status = "Successful"
                        $copyResourceGovPool | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        $workloadGroups = $pool.WorkloadGroups
                        foreach ($workloadGroup in $workloadGroups) {
                            $workgroupName = $workloadGroup.Name

                            $copyResourceGovWorkGroup = [pscustomobject]@{
                                SourceServer      = $sourceServer.Name
                                DestinationServer = $destServer.Name
                                Type              = "Resource Governor Pool Workgroup"
                                Name              = $workgroupName
                                Status            = $null
                                Notes             = $null
                                DateTime          = [DbaDateTime](Get-Date)
                            }

                            $sql = $workloadGroup.Script() | Out-String
                            Write-Message -Level Debug -Message $sql
                            Write-Message -Level Verbose -Message "Copying $workgroupName."
                            $destServer.Query($sql)

                            $copyResourceGovWorkGroup.Status = "Successful"
                            $copyResourceGovWorkGroup | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                            $sql = "ALTER RESOURCE GOVERNOR RECONFIGURE;"
                            Write-Message -Level Debug -Message $sql
                            Write-Message -Level Verbose -Message "Reconfiguring Resource Governor."
                            $destServer.Query($sql)
                        }
                    } catch {
                        if ($copyResourceGovWorkGroup) {
                            $copyResourceGovWorkGroup.Status = "Failed"
                            $copyResourceGovWorkGroup.Notes = (Get-ErrorMessage -Record $_)
                            $copyResourceGovWorkGroup | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        }
                        Stop-Function -Message "Unable to migrate pool." -Target $pool -ErrorRecord $_
                    }
                }
            }

            if ($Pscmdlet.ShouldProcess($destinstance, "Reconfiguring")) {
                if ($destServer.Edition -notmatch 'Enterprise' -and $destServer.Edition -notmatch 'Datacenter' -and $destServer.Edition -notmatch 'Developer') {
                    Write-Message -Level Verbose -Message "The resource governor is not available in this edition of SQL Server. You can manipulate resource governor metadata but you will not be able to apply resource governor configuration. Only Enterprise edition of SQL Server supports resource governor."
                } else {

                    Write-Message -Level Verbose -Message "Reconfiguring Resource Governor."
                    try {
                        if (!$sourceServer.ResourceGovernor.Enabled) {
                            $sql = "ALTER RESOURCE GOVERNOR DISABLE"
                            $destServer.Query($sql)

                            $sql = "ALTER RESOURCE GOVERNOR RECONFIGURE;"
                            Write-Message -Level Debug -Message $sql
                            Write-Message -Level Verbose -Message "Reconfiguring Resource Governor."
                            $destServer.Query($sql)
                        } else {
                            $sql = "ALTER RESOURCE GOVERNOR RECONFIGURE"
                            $destServer.Query($sql)
                        }
                    } catch {
                        $altermsg = $_.Exception
                    }


                    $copyResourceGovReconfig = [pscustomobject]@{
                        SourceServer      = $sourceServer.Name
                        DestinationServer = $destServer.Name
                        Type              = "Reconfigure Resource Governor"
                        Name              = "Reconfigure Resource Governor"
                        Status            = "Successful"
                        Notes             = $altermsg
                        DateTime          = [DbaDateTime](Get-Date)
                    }
                    $copyResourceGovReconfig | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlResourceGovernor
    }
}
tools\dbatools\functions\Copy-DbaServerAudit.ps1
function Copy-DbaServerAudit {
    <#
    .SYNOPSIS
        Copy-DbaServerAudit migrates server audits from one SQL Server to another.

    .DESCRIPTION
        By default, all audits are copied. The -Audit parameter is auto-populated for command-line completion and can be used to copy only specific audits.

        If the audit already exists on the destination, it will be skipped unless -Force is used.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Audit
        The audit(s) to process. Options for this list are auto-populated from the server. If unspecified, all audits will be processed.

    .PARAMETER ExcludeAudit
        The audit(s) to exclude. Options for this list are auto-populated from the server.

    .PARAMETER Path
        Destination file path. If not specified, the file path of the source will be used (or the default data directory).

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER Force
        If this switch is enabled, the audits will be dropped and recreated on Destination.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        https://dbatools.io/Copy-DbaServerAudit

    .EXAMPLE
        PS C:\> Copy-DbaServerAudit -Source sqlserver2014a -Destination sqlcluster

        Copies all server audits from sqlserver2014a to sqlcluster, using Windows credentials. If audits with the same name exist on sqlcluster, they will be skipped.

    .EXAMPLE
        PS C:\> Copy-DbaServerAudit -Source sqlserver2014a -Destination sqlcluster -Audit tg_noDbDrop -SourceSqlCredential $cred -Force

        Copies a single audit, the tg_noDbDrop audit from sqlserver2014a to sqlcluster, using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If an audit with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used.

    .EXAMPLE
        PS C:\> Copy-DbaServerAudit -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force

        Shows what would happen if the command were executed using force.

    .EXAMPLE
        PS C:\> Copy-DbaServerAudit -Source sqlserver-0 -Destination sqlserver-1 -Audit audit1 -Path 'C:\audit1'

        Copies audit audit1 from sqlserver-0 to sqlserver-1. The file path on sqlserver-1 will be set to 'C:\audit1'.
    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]
        $SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]
        $DestinationSqlCredential,
        [object[]]$Audit,
        [object[]]$ExcludeAudit,
        [string]$Path,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential -MinimumVersion 10
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }
        $serverAudits = $sourceServer.Audits
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {

            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }
            $destAudits = $destServer.Audits
            foreach ($currentAudit in $serverAudits) {
                $auditName = $currentAudit.Name

                $copyAuditStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Name              = $auditName
                    Type              = "Server Audit"
                    Status            = $null
                    Notes             = $null
                    DateTime          = [DbaDateTime](Get-Date)
                }

                if ($Audit -and $auditName -notin $Audit -or $auditName -in $ExcludeAudit) {
                    continue
                }

                if ($Path) {
                    $currentAudit.FilePath = $Path
                }

                if ($destAudits.Name -contains $auditName) {
                    if ($force -eq $false) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Server audit $auditName exists at destination. Use -Force to drop and migrate.")) {
                            $copyAuditStatus.Status = "Skipped"
                            $copyAuditStatus.Notes = "Already exists on destination"
                            Write-Message -Level Verbose -Message "Server audit $auditName exists at destination. Use -Force to drop and migrate."
                        }
                        continue
                    } else {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Dropping server audit $auditName")) {
                            try {
                                Write-Message -Level Verbose -Message "Dropping server audit $auditName."
                                foreach ($spec in $destServer.ServerAuditSpecifications) {
                                    if ($auditSpecification.Auditname -eq $auditName) {
                                        $auditSpecification.Drop()
                                    }
                                }

                                $destServer.audits[$auditName].Disable()
                                $destServer.audits[$auditName].Alter()
                                $destServer.audits[$auditName].Drop()
                            } catch {
                                $copyAuditStatus.Status = "Failed"
                                $copyAuditStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                                Stop-Function -Message "Issue dropping audit from destination." -Target $auditName -ErrorRecord $_
                            }
                        }
                    }
                }

                if ($null -ne ($currentAudit.Filepath) -and -not (Test-DbaPath -SqlInstance $destServer -Path $currentAudit.Filepath)) {
                    if ($Force -eq $false) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "$($currentAudit.Filepath) does not exist on $destinstance. Skipping $auditName. Specify -Force to create the directory.")) {
                            $copyAuditStatus.Status = "Skipped"
                            $copyAuditStatus.Notes = "$($currentAudit.Filepath) does not exist on $destinstance. Skipping $auditName. Specify -Force to create the directory."
                            $copyAuditStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        }
                        continue
                    } else {
                        Write-Message -Level Verbose -Message "Force specified. Creating directory."

                        $destNetBios = Resolve-NetBiosName $destServer
                        $root = $currentAudit.Filepath.Substring(0, 3)
                        $rootUnc = Join-AdminUnc $destNetBios $root

                        if ((Test-Path $rootUnc) -eq $true) {
                            if ($Pscmdlet.ShouldProcess($destinstance, "Creating directory $($currentAudit.Filepath)")) {
                                try {
                                    $null = New-DbaDirectory -SqlInstance $destServer -Path $currentAudit.Filepath -EnableException
                                } catch {
                                    Write-Message -Level Warning -Message "Couldn't create directory $($currentAudit.Filepath). Using default data directory."
                                    $datadir = Get-SqlDefaultPaths $destServer data
                                    $currentAudit.FilePath = $datadir
                                }
                            }
                        } else {
                            $datadir = Get-SqlDefaultPaths $destServer data
                            $currentAudit.FilePath = $datadir
                        }
                    }
                }
                if ($Pscmdlet.ShouldProcess($destinstance, "Creating server audit $auditName")) {
                    try {
                        Write-Message -Level Verbose -Message "File path $($currentAudit.Filepath) exists on $destinstance."
                        Write-Message -Level Verbose -Message "Copying server audit $auditName."
                        $sql = $currentAudit.Script() | Out-String
                        $destServer.Query($sql)
                        $copyAuditStatus.Status = "Successful"
                        $copyAuditStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    } catch {
                        $copyAuditStatus.Status = "Failed"
                        $copyAuditStatus.Notes = (Get-ErrorMessage -Record $_)
                        $copyAuditStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        Stop-Function -Message "Issue creating audit." -Target $auditName -ErrorRecord $_
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlAudit
    }
}
tools\dbatools\functions\Copy-DbaServerAuditSpecification.ps1
function Copy-DbaServerAuditSpecification {
    <#
    .SYNOPSIS
        Copy-DbaServerAuditSpecification migrates server audit specifications from one SQL Server to another.

    .DESCRIPTION
        By default, all audits are copied. The -AuditSpecification parameter is auto-populated for command-line completion and can be used to copy only specific audits.

        If the audit specification already exists on the destination, it will be skipped unless -Force is used.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER AuditSpecification
        The Server Audit Specification(s) to process. Options for this list are auto-populated from the server. If unspecified, all Server Audit Specifications will be processed.

    .PARAMETER ExcludeAuditSpecification
        The Server Audit Specification(s) to exclude. Options for this list are auto-populated from the server

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER Force
        If this switch is enabled, the Audits Specifications will be dropped and recreated on Destination.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration,ServerAudit,AuditSpecification
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        https://dbatools.io/Copy-DbaServerAuditSpecification

    .EXAMPLE
        PS C:\> Copy-DbaServerAuditSpecification -Source sqlserver2014a -Destination sqlcluster

        Copies all server audits from sqlserver2014a to sqlcluster using Windows credentials to connect. If audits with the same name exist on sqlcluster, they will be skipped.

    .EXAMPLE
        PS C:\> Copy-DbaServerAuditSpecification -Source sqlserver2014a -Destination sqlcluster -AuditSpecification tg_noDbDrop -SourceSqlCredential $cred -Force

        Copies a single audit, the tg_noDbDrop audit from sqlserver2014a to sqlcluster using SQL credentials to connect to sqlserver2014a and Windows credentials to connect to sqlcluster. If an audit specification with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used.

    .EXAMPLE
        PS C:\> Copy-DbaServerAuditSpecification -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force

        Shows what would happen if the command were executed using force.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]$SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]$DestinationSqlCredential,
        [object[]]$AuditSpecification,
        [object[]]$ExcludeAuditSpecification,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential -MinimumVersion 10
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }

        if (!(Test-SqlSa -SqlInstance $sourceServer -SqlCredential $SourceSqlCredential)) {
            Stop-Function -Message "Not a sysadmin on $source. Quitting."
            return
        }

        $AuditSpecifications = $sourceServer.ServerAuditSpecifications
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }

            if (!(Test-SqlSa -SqlInstance $destServer -SqlCredential $DestinationSqlCredential)) {
                Stop-Function -Message "Not a sysadmin on $destinstance. Quitting."
                return
            }

            if ($destServer.VersionMajor -lt $sourceServer.VersionMajor) {
                Stop-Function -Message "Migration from version $($destServer.VersionMajor) to version $($sourceServer.VersionMajor) is not supported."
                return
            }
            $destAudits = $destServer.ServerAuditSpecifications
            foreach ($auditSpec in $AuditSpecifications) {
                $auditSpecName = $auditSpec.Name

                $copyAuditSpecStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Type              = "Server Audit Specification"
                    Name              = $auditSpecName
                    Status            = $null
                    Notes             = $null
                    DateTime          = [DbaDateTime](Get-Date)
                }

                if ($AuditSpecification -and $auditSpecName -notin $AuditSpecification -or $auditSpecName -in $ExcludeAuditSpecification) {
                    continue
                }

                $destServer.Audits.Refresh()
                if ($destServer.Audits.Name -notcontains $auditSpec.AuditName) {
                    if ($Pscmdlet.ShouldProcess($destinstance, "Audit $($auditSpec.AuditName) does not exist on $destinstance. Skipping $auditSpecName.")) {
                        $copyAuditSpecStatus.Status = "Skipped"
                        $copyAuditSpecStatus.Notes = "Audit $($auditSpec.AuditName) does not exist on $destinstance. Skipping $auditSpecName."
                        Write-Message -Level Warning -Message "Audit $($auditSpec.AuditName) does not exist on $destinstance. Skipping $auditSpecName."
                        $copyAuditSpecStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    }
                    continue
                }

                if ($destAudits.name -contains $auditSpecName) {
                    if ($force -eq $false) {
                        Write-Message -Level Verbose -Message "Server audit $auditSpecName exists at destination. Use -Force to drop and migrate."

                        $copyAuditSpecStatus.Status = "Skipped"
                        $copyAuditSpecStatus.Notes = "Already exists on destination"
                        $copyAuditSpecStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        continue
                    } else {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Dropping server audit $auditSpecName and recreating")) {
                            try {
                                Write-Message -Level Verbose -Message "Dropping server audit $auditSpecName"
                                $destServer.ServerAuditSpecifications[$auditSpecName].Drop()
                            } catch {
                                $copyAuditSpecStatus.Status = "Failed"
                                $copyAuditSpecStatus.Notes = (Get-ErrorMessage -Record $_)
                                $copyAuditSpecStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                                Stop-Function -Message "Issue dropping audit spec" -Target $auditSpecName -ErrorRecord $_ -Continue
                            }
                        }
                    }
                }
                if ($Pscmdlet.ShouldProcess($destinstance, "Creating server audit $auditSpecName")) {
                    try {
                        Write-Message -Level Verbose -Message "Copying server audit $auditSpecName"
                        $sql = $auditSpec.Script() | Out-String
                        Write-Message -Level Debug -Message $sql
                        $destServer.Query($sql)

                        $copyAuditSpecStatus.Status = "Successful"
                        $copyAuditSpecStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    } catch {
                        $copyAuditSpecStatus.Status = "Failed"
                        $copyAuditSpecStatus.Notes = (Get-ErrorMessage -Record $_)
                        $copyAuditSpecStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        Stop-Function -Message "Issue creating audit spec on destination" -Target $auditSpecName -ErrorRecord $_
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlAuditSpecification
    }
}
tools\dbatools\functions\Copy-DbaServerTrigger.ps1
function Copy-DbaServerTrigger {
    <#
    .SYNOPSIS
        Copy-DbaServerTrigger migrates server triggers from one SQL Server to another.

    .DESCRIPTION
        By default, all triggers are copied. The -ServerTrigger parameter is auto-populated for command-line completion and can be used to copy only specific triggers.

        If the trigger already exists on the destination, it will be skipped unless -Force is used.

    .PARAMETER Source
        Source SQL Server.You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination Sql Server. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER ServerTrigger
        The Server Trigger(s) to process - this list is auto-populated from the server. If unspecified, all Server Triggers will be processed.

    .PARAMETER ExcludeServerTrigger
        The Server Trigger(s) to exclude - this list is auto-populated from the server

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER Force
        Drops and recreates the Trigger if it exists

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        https://dbatools.io/Copy-DbaServerTrigger

    .EXAMPLE
        PS C:\> Copy-DbaServerTrigger -Source sqlserver2014a -Destination sqlcluster

        Copies all server triggers from sqlserver2014a to sqlcluster, using Windows credentials. If triggers with the same name exist on sqlcluster, they will be skipped.

    .EXAMPLE
        PS C:\> Copy-DbaServerTrigger -Source sqlserver2014a -Destination sqlcluster -ServerTrigger tg_noDbDrop -SourceSqlCredential $cred -Force

        Copies a single trigger, the tg_noDbDrop trigger from sqlserver2014a to sqlcluster, using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If a trigger with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used.

    .EXAMPLE
        PS C:\> Copy-DbaServerTrigger -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force

        Shows what would happen if the command were executed using force.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]
        $SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]
        $DestinationSqlCredential,
        [object[]]$ServerTrigger,
        [object[]]$ExcludeServerTrigger,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential -MinimumVersion 9
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }
        $serverTriggers = $sourceServer.Triggers
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }
            if ($destServer.VersionMajor -lt $sourceServer.VersionMajor) {
                Stop-Function -Message "Migration from version $($destServer.VersionMajor) to version $($sourceServer.VersionMajor) is not supported."
                return
            }
            $destTriggers = $destServer.Triggers

            foreach ($trigger in $serverTriggers) {
                $triggerName = $trigger.Name

                $copyTriggerStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Name              = $triggerName
                    Type              = "Server Trigger"
                    Status            = $null
                    Notes             = $null
                    DateTime          = [DbaDateTime](Get-Date)
                }

                if ($ServerTrigger -and $triggerName -notin $ServerTrigger -or $triggerName -in $ExcludeServerTrigger) {
                    continue
                }

                if ($destTriggers.Name -contains $triggerName) {
                    if ($force -eq $false) {
                        Write-Message -Level Verbose -Message "Server trigger $triggerName exists at destination. Use -Force to drop and migrate."

                        $copyTriggerStatus.Status = "Skipped"
                        $copyTriggerStatus.Notes = "Already exists on destination"
                        $copyTriggerStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                        continue
                    } else {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Dropping server trigger $triggerName and recreating")) {
                            try {
                                Write-Message -Level Verbose -Message "Dropping server trigger $triggerName"
                                $destServer.Triggers[$triggerName].Drop()
                            } catch {
                                $copyTriggerStatus.Status = "Failed"
                                $copyTriggerStatus.Notes = (Get-ErrorMessage -Record $_)
                                $copyTriggerStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                                Stop-Function -Message "Issue dropping trigger on destination" -Target $triggerName -ErrorRecord $_ -Continue
                            }
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destinstance, "Creating server trigger $triggerName")) {
                    try {
                        Write-Message -Level Verbose -Message "Copying server trigger $triggerName"
                        $sql = $trigger.Script() | Out-String
                        $sql = $sql -replace "CREATE TRIGGER", "`nGO`nCREATE TRIGGER"
                        $sql = $sql -replace "ENABLE TRIGGER", "`nGO`nENABLE TRIGGER"
                        Write-Message -Level Debug -Message $sql

                        foreach ($query in ($sql -split '\nGO\b')) {
                            $destServer.Query($query) | Out-Null
                        }

                        $copyTriggerStatus.Status = "Successful"
                        $copyTriggerStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    } catch {
                        $copyTriggerStatus.Status = "Failed"
                        $copyTriggerStatus.Notes = (Get-ErrorMessage -Record $_)
                        $copyTriggerStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        Stop-Function -Message "Issue creating trigger on destination" -Target $triggerName -ErrorRecord $_
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlServerTrigger
    }
}
tools\dbatools\functions\Copy-DbaSpConfigure.ps1
function Copy-DbaSpConfigure {
    <#
    .SYNOPSIS
        Copy-DbaSpConfigure migrates configuration values from one SQL Server to another.

    .DESCRIPTION
        By default, all configuration values are copied. The -ConfigName parameter is auto-populated for command-line completion and can be used to copy only specific configs.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER ConfigName
        Specifies the configuration setting to process. Options for this list are auto-populated from the server. If unspecified, all ConfigNames will be processed.

    .PARAMETER ExcludeConfigName
        Specifies the configuration settings to exclude. Options for this list are auto-populated from the server.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration, Configure, SpConfigure
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        https://dbatools.io/Copy-DbaSpConfigure

    .EXAMPLE
        PS C:\> Copy-DbaSpConfigure -Source sqlserver2014a -Destination sqlcluster

        Copies all sp_configure settings from sqlserver2014a to sqlcluster

    .EXAMPLE
        PS C:\> Copy-DbaSpConfigure -Source sqlserver2014a -Destination sqlcluster -ConfigName DefaultBackupCompression, IsSqlClrEnabled -SourceSqlCredential $cred

        Copies the values for IsSqlClrEnabled and DefaultBackupCompression from sqlserver2014a to sqlcluster using SQL credentials to authenticate to sqlserver2014a and Windows credentials to authenticate to sqlcluster.

    .EXAMPLE
        PS C:\> Copy-DbaSpConfigure -Source sqlserver2014a -Destination sqlcluster -ExcludeConfigName DefaultBackupCompression, IsSqlClrEnabled

        Copies all configs except for IsSqlClrEnabled and DefaultBackupCompression, from sqlserver2014a to sqlcluster.

    .EXAMPLE
        PS C:\> Copy-DbaSpConfigure -Source sqlserver2014a -Destination sqlcluster -WhatIf

        Shows what would happen if the command were executed.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [PSCredential]$SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]$DestinationSqlCredential,
        [object[]]$ConfigName,
        [object[]]$ExcludeConfigName,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential
            $sourceProps = Get-DbaSpConfigure -SqlInstance $sourceServer
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential
                $destProps = Get-DbaSpConfigure -SqlInstance $destServer
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }

            foreach ($sourceProp in $sourceProps) {
                $displayName = $sourceProp.DisplayName
                $sConfigName = $sourceProp.ConfigName
                $sConfiguredValue = $sourceProp.ConfiguredValue
                $requiresRestart = $sourceProp.IsDynamic

                $copySpConfigStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Name              = $sConfigName
                    Type              = "Configuration Value"
                    Status            = $null
                    Notes             = $null
                    DateTime          = [DbaDateTime](Get-Date)
                }

                if ($ConfigName -and $sConfigName -notin $ConfigName -or $sConfigName -in $ExcludeConfigName) {
                    continue
                }

                $destProp = $destProps | Where-Object ConfigName -eq $sConfigName
                if (!$destProp) {
                    Write-Message -Level Verbose -Message "Configuration $sConfigName ('$displayName') does not exist on the destination instance."

                    $copySpConfigStatus.Status = "Skipped"
                    $copySpConfigStatus.Notes = "Configuration does not exist on destination"
                    $copySpConfigStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                    continue
                }

                if ($Pscmdlet.ShouldProcess($destinstance, "Updating $sConfigName [$displayName]")) {
                    try {
                        $destOldConfigValue = $destProp.ConfiguredValue

                        if ($sConfiguredValue -ne $destOldConfigValue) {
                            $result = Set-DbaSpConfigure -SqlInstance $destServer -Name $sConfigName -Value $sConfiguredValue -EnableException -WarningAction SilentlyContinue
                            if ($result) {
                                Write-Message -Level Verbose -Message "Updated $($destProp.ConfigName) ($($destProp.DisplayName)) from $destOldConfigValue to $sConfiguredValue."
                            }
                        }
                        if ($requiresRestart -eq $false) {
                            Write-Message -Level Verbose -Message "Configuration option $sConfigName ($displayName) requires restart."
                            $copySpConfigStatus.Notes = "Requires restart"
                        }
                        $copySpConfigStatus.Status = "Successful"
                        $copySpConfigStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    } catch {
                        if ($_.Exception -match 'the same as the') {
                            $copySpConfigStatus.Status = "Successful"
                        } else {
                            $copySpConfigStatus.Status = "Failed"
                            $copySpConfigStatus.Notes = (Get-ErrorMessage -Record $_)
                        }
                        $copySpConfigStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        Stop-Function -Message "Could not set $($destProp.ConfigName) to $sConfiguredValue." -Target $sConfigName -ErrorRecord $_
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlSpConfigure
    }
}
tools\dbatools\functions\Copy-DbaSsisCatalog.ps1
#ValidationTags#Messaging#
function Copy-DbaSsisCatalog {
    <#
    .SYNOPSIS
        Copy-DbaSsisCatalog migrates Folders, SSIS projects, and environments from one SQL Server to another.

    .DESCRIPTION
        By default, all folders, projects, and environments are copied. The -Project parameter can be specified to copy only one project, if desired.

        The parameters get more granular from the Folder level. For example, specifying -Folder will only deploy projects/environments from within that folder.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2012 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2012 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Force
        If this switch is enabled, the SSIS Catalog will be dropped and recreated on Destination if it already exists.

    .PARAMETER Project
        Specifies a source Project name.

    .PARAMETER Folder
        Specifies a source folder name.

    .PARAMETER Environment
        Specifies an environment to copy.

    .PARAMETER EnableSqlClr
        If this switch is enabled and Destination does not have the SQL CLR configuration option enabled, user prompts for enabling it on Destination will be skipped. SQL CLR is required for SSISDB.

    .PARAMETER CreateCatalogPassword
        Specifies a secure string to use in creating an SSISDB catalog on Destination. If this is specified, prompts for the password will be skipped.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration, SSIS
        Author: Phil Schwartz (philschwartz.me, @pschwartzzz)

        dbatools PowerShell module (https://dbatools.io, [email protected])
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Copy-DbaSsisCatalog

    .EXAMPLE
        PS C:\> Copy-DbaSsisCatalog -Source sqlserver2014a -Destination sqlcluster

        Copies all folders, environments and SSIS Projects from sqlserver2014a to sqlcluster, using Windows credentials to authenticate to both instances. If folders with the same name exist on the destination they will be skipped, but projects will be redeployed.

    .EXAMPLE
        PS C:\> Copy-DbaSsisCatalog -Source sqlserver2014a -Destination sqlcluster -Project Archive_Tables -SourceSqlCredential $cred -Force

        Copies a single Project, the Archive_Tables Project, from sqlserver2014a to sqlcluster using SQL credentials to authenticate to sqlserver2014a and Windows credentials to authenticate to sqlcluster. If a Project with the same name exists on sqlcluster, it will be deleted and recreated because -Force was used.

    .EXAMPLE
        PS C:\> Copy-DbaSsisCatalog -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force

        Shows what would happen if the command were executed using force.

    .EXAMPLE
        PS C:\> $SecurePW = Read-Host "Enter password" -AsSecureString
        PS C:\> Copy-DbaSsisCatalog -Source sqlserver2014a -Destination sqlcluster -CreateCatalogPassword $SecurePW

        Deploy entire SSIS catalog to an instance without a destination catalog. User prompts for creating the catalog on Destination will be bypassed.

       #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]$SourceSqlCredential,
        [PSCredential]$DestinationSqlCredential,
        [String]$Project,
        [String]$Folder,
        [String]$Environment,
        [System.Security.SecureString]$CreateCatalogPassword,
        [Switch]$EnableSqlClr,
        [Switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )
    <# Developer note: The throw calls must stay in this command #>
    begin {
        function Get-RemoteIntegrationService {
            param (
                [Object]$Computer
            )
            $result = Get-DbaService -ComputerName $Computer -Type SSIS
            if ($result) {
                #Variable marked as unused by PSScriptAnalyzer
                #$running = $false
                foreach ($service in $result) {
                    if (!$service.State -eq "Running") {
                        Write-Message -Level Warning -Message "Service $($service.DisplayName) was found on the destination, but is currently not running."
                    } else {
                        Write-Message -Level Verbose -Message "Service $($service.DisplayName) was found running on the destination."
                        #$running = $true
                    }
                }
            } else {
                throw "No Integration Services service was found on the destination, please ensure the feature is installed and running."
            }
        }
        function Invoke-ProjectDeployment {
            param (
                [String]$Project,
                [String]$Folder
            )
            $sqlConn = New-Object System.Data.SqlClient.SqlConnection
            $sqlConn.ConnectionString = $sourceServer.ConnectionContext.ConnectionString
            if ($sqlConn.State -eq "Closed") {
                $sqlConn.Open()
            }
            try {
                Write-Message -Level Verbose -Message "Deploying project $Project from folder $Folder."
                $cmd = New-Object System.Data.SqlClient.SqlCommand
                $cmd.CommandType = "StoredProcedure"
                $cmd.connection = $sqlConn
                $cmd.CommandText = "SSISDB.Catalog.get_project"
                $cmd.Parameters.Add("@folder_name", $Folder) | out-null;
                $cmd.Parameters.Add("@project_name", $Project) | out-null;
                [byte[]]$results = $cmd.ExecuteScalar();
                if ($null -ne $results) {
                    $destFolder = $destinationFolders | Where-Object {
                        $_.Name -eq $Folder
                    }
                    $deployedProject = $destFolder.DeployProject($Project, $results)
                    if ($deployedProject.Status -ne "Success") {
                        Stop-Function -Message "An error occurred deploying project $Project." -Target $Project -Continue
                    }
                } else {
                    Stop-Function -Message "Failed deploying $Project from folder $Folder." -Target $Project -Continue
                }
            } catch {
                Stop-Function -Message "Failed to deploy project." -Target $Project -ErrorRecord $_
            } finally {
                if ($sqlConn.State -eq "Open") {
                    $sqlConn.Close()
                }
            }
        }
        function New-CatalogFolder {
            [CmdletBinding(SupportsShouldProcess)]
            param (
                [String]$Folder,
                [String]$Description,
                [Switch]$Force
            )
            if ($Pscmdlet.ShouldProcess($folder, "Creating new Catalog Folder")) {
                if ($Force) {
                    $remove = $destinationFolders | Where-Object {
                        $_.Name -eq $Folder
                    }
                    $envs = $remove.Environments.Name
                    foreach ($e in $envs) {
                        $remove.Environments[$e].Drop()
                    }
                    $projs = $remove.Projects.Name
                    foreach ($p in $projs) {
                        $remove.Projects[$p].Drop()
                    }
                    $remove.Drop()
                    $destinationCatalog.Alter()
                    $destinationCatalog.Refresh()
                }
                Write-Message -Level Verbose -Message "Creating folder $Folder."
                $destFolder = New-Object "$ISNamespace.CatalogFolder" ($destinationCatalog, $Folder, $Description)
                $destFolder.Create()
                $destFolder.Alter()
                $destFolder.Refresh()
            }
        }
        function New-FolderEnvironment {
            [CmdletBinding(SupportsShouldProcess)]
            param (
                [String]$Folder,
                [String]$Environment,
                [Switch]$Force
            )
            if ($Pscmdlet.ShouldProcess($folder, "Creating new Environment Folder")) {
                $envDestFolder = $destinationFolders | Where-Object {
                    $_.Name -eq $Folder
                }
                if ($force) {
                    $envDestFolder.Environments[$Environment].Drop()
                    $envDestFolder.Alter()
                    $envDestFolder.Refresh()
                }
                $srcEnv = ($sourceFolders | Where-Object {
                        $_.Name -eq $Folder
                    }).Environments[$Environment]
                $targetEnv = New-Object "$ISNamespace.EnvironmentInfo" ($envDestFolder, $srcEnv.Name, $srcEnv.Description)
                foreach ($var in $srcEnv.Variables) {
                    if ($var.Value.ToString() -eq "") {
                        $finalValue = ""
                    } else {
                        $finalValue = $var.Value
                    }
                    $targetEnv.Variables.Add($var.Name, $var.Type, $finalValue, $var.Sensitive, $var.Description)
                }
                Write-Message -Level Verbose -Message "Creating environment $Environment."
                $targetEnv.Create()
                $targetEnv.Alter()
                $targetEnv.Refresh()
            }
        }
        function New-SSISDBCatalog {
            [CmdletBinding(SupportsShouldProcess)]
            param (
                [System.Security.SecureString]$SecurePassword
            )
            if ($Pscmdlet.ShouldProcess("Creating New SSISDB Catalog")) {
                if (!$Password) {
                    Write-Message -Level Verbose -Message "SSISDB Catalog requires a password."
                    $pass1 = Read-Host "Enter a password" -AsSecureString
                    $plainTextPass1 = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass1))
                    $pass2 = Read-Host "Re-enter password" -AsSecureString
                    $plainTextPass2 = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass2))
                    if ($plainTextPass1 -ne $plainTextPass2) {
                        throw "Validation error, passwords entered do not match."
                    }
                    $plainTextPass = $plainTextPass1
                } else {
                    $plainTextPass = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password))
                }

                $catalog = New-Object "$ISNamespace.Catalog" ($destinationSSIS, "SSISDB", $plainTextPass)
                $catalog.Create()
                $catalog.Refresh()
            }
        }

        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential -MinimumVersion 11
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }

        try {
            $sourceSSIS = New-Object Microsoft.SqlServer.Management.IntegrationServices.IntegrationServices $sourceServer
        } catch {
            Stop-Function -Message "There was an error connecting to the source integration services." -Target $sourceServer -ErrorRecord $_
            return
        }

        $sourceCatalog = $sourceSSIS.Catalogs | Where-Object {
            $_.Name -eq "SSISDB"
        }
        if (!$sourceCatalog) {
            Stop-Function -Message "The source SSISDB catalog on $Source does not exist."
            return
        }
        $sourceFolders = $sourceCatalog.Folders
    }
    process {
        if (Test-FunctionInterrupt) {
            return
        }
        foreach ($destinstance in $Destination) {
            try {
                $destinationConnection = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential -MinimumVersion 1
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }

            try {
                Get-RemoteIntegrationService -Computer $destinstance.ComputerName
            } catch {
                Stop-Function -Message "An error occurred when checking the destination for Integration Services. Is Integration Services installed?" -Target $destinstance -ErrorRecord $_
            }

            try {
                $destinationSSIS = New-Object Microsoft.SqlServer.Management.IntegrationServices.IntegrationServices $destinationConnection
            } catch {
                Stop-Function -Message "There was an error connecting to the destination integration services." -Target $destinationCon -ErrorRecord $_
            }

            $destinationCatalog = $destinationSSIS.Catalogs | Where-Object {
                $_.Name -eq "SSISDB"
            }
            $destinationFolders = $destinationCatalog.Folders

            if (!$destinationCatalog) {
                if (!$destinationConnection.Configuration.IsSqlClrEnabled.ConfigValue) {
                    if ($Pscmdlet.ShouldProcess($destinstance, "Enabling SQL CLR configuration option.")) {
                        if (!$EnableSqlClr) {
                            $message = "The destination does not have SQL CLR configuration option enabled (required by SSISDB), would you like to enable it?"
                            $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Enable SQL CLR on $destinstance."
                            $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Exit."
                            $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
                            $result = $host.ui.PromptForChoice($null, $message, $options, 0)
                            switch ($result) {
                                0 {
                                    continue
                                }
                                1 {
                                    return
                                }
                            }
                        }
                        Write-Message -Level Verbose -Message "Enabling SQL CLR configuration option at the destination."
                        if ($destinationConnection.Configuration.ShowAdvancedOptions.ConfigValue -eq $false) {
                            $destinationConnection.Configuration.ShowAdvancedOptions.ConfigValue = $true
                            $changeback = $true
                        }

                        $destinationConnection.Configuration.IsSqlClrEnabled.ConfigValue = $true

                        if ($changeback -eq $true) {
                            $destinationConnection.Configuration.ShowAdvancedOptions.ConfigValue = $false
                        }
                        $destinationConnection.Configuration.Alter()
                    }
                } else {
                    Write-Message -Level Verbose -Message "SQL CLR configuration option is already enabled at the destination."
                }
                if ($Pscmdlet.ShouldProcess($destinstance, "Create destination SSISDB Catalog")) {
                    if (!$CreateCatalogPassword) {
                        $message = "The destination SSISDB catalog does not exist, would you like to create one?"
                        $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Create an SSISDB catalog on $destinstance."
                        $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Exit."
                        $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
                        $result = $host.ui.PromptForChoice($null, $message, $options, 0)
                        switch ($result) {
                            0 {
                                New-SSISDBCatalog
                            }
                            1 {
                                return
                            }
                        }
                    } else {
                        New-SSISDBCatalog -SecurePassword $CreateCatalogPassword
                    }

                    $destinationSSIS.Refresh()
                    $destinationCatalog = $destinationSSIS.Catalogs | Where-Object {
                        $_.Name -eq "SSISDB"
                    }
                    $destinationFolders = $destinationCatalog.Folders
                } else {
                    throw "The destination SSISDB catalog does not exist."
                }
            }
            if ($folder) {
                if ($sourceFolders.Name -contains $folder) {
                    $srcFolder = $sourceFolders | Where-Object {
                        $_.Name -eq $folder
                    }
                    if ($destinationFolders.Name -contains $folder) {
                        if (!$force) {
                            Write-Message -Level Warning -Message "Integration services catalog folder $folder exists at destination. Use -Force to drop and recreate."
                        } else {
                            if ($Pscmdlet.ShouldProcess($destinstance, "Dropping folder $folder and recreating")) {
                                try {
                                    New-CatalogFolder -Folder $srcFolder.Name -Description $srcFolder.Description -Force
                                } catch {
                                    Stop-Function -Message "Issue dropping folder" -Target $folder -ErrorRecord $_
                                }

                            }
                        }
                    } else {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Creating folder $folder")) {
                            try {
                                New-CatalogFolder -Folder $srcFolder.Name -Description $srcFolder.Description
                            } catch {
                                Stop-Function -Message "Issue creating folder" -Target $folder -ErrorRecord $_
                            }
                        }
                    }
                } else {
                    throw "The source folder provided does not exist in the source Integration Services catalog."
                }
            } else {
                foreach ($srcFolder in $sourceFolders) {
                    if ($destinationFolders.Name -notcontains $srcFolder.Name) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Creating folder $($srcFolder.Name)")) {
                            try {
                                New-CatalogFolder -Folder $srcFolder.Name -Description $srcFolder.Description
                            } catch {
                                Stop-Function -Message "Issue creating folder" -Target $srcFolder -ErrorRecord $_ -Continue
                            }
                        }
                    } else {
                        if (!$force) {
                            Write-Message -Level Warning -Message "Integration services catalog folder $($srcFolder.Name) exists at destination. Use -Force to drop and recreate."
                            continue
                        } else {
                            if ($Pscmdlet.ShouldProcess($destinstance, "Dropping folder $($srcFolder.Name) and recreating")) {
                                try {
                                    New-CatalogFolder -Folder $srcFolder.Name -Description $srcFolder.Description -Force
                                } catch {
                                    Stop-Function -Message "Issue dropping folder" -Target $srcFolder -ErrorRecord $_
                                }
                            }
                        }
                    }
                }
            }

            # Refresh folders for project and environment deployment
            if ($Pscmdlet.ShouldProcess($destinstance, "Refresh folders for project deployment")) {
                try {
                    $destinationFolders.Alter()
                } catch {
                    # Sometimes it says Alter() doesn't exist
                    # here to avoid an empty catch
                    $null = 1
                }
                $destinationFolders.Refresh()
            }

            if ($folder) {
                $sourceFolders = $sourceFolders | Where-Object {
                    $_.Name -eq $folder
                }
                if (!$sourceFolders) {
                    throw "The source folder $folder does not exist in the source Integration Services catalog."
                }
            }
            if ($project) {
                $folderDeploy = $sourceFolders | Where-Object {
                    $_.Projects.Name -eq $project
                }
                if (!$folderDeploy) {
                    throw "The project $project cannot be found in the source Integration Services catalog."
                } else {
                    foreach ($f in $folderDeploy) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Deploying project $project from folder $($f.Name)")) {
                            try {
                                Invoke-ProjectDeployment -Folder $f.Name -Project $project
                            } catch {
                                Stop-Function -Message "Issue deploying project" -Target $project -ErrorRecord $_
                            }
                        }
                    }
                }
            } else {
                foreach ($curFolder in $sourceFolders) {
                    foreach ($proj in $curFolder.Projects) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Deploying project $($proj.Name) from folder $($curFolder.Name)")) {
                            try {
                                Invoke-ProjectDeployment -Project $proj.Name -Folder $curFolder.Name
                            } catch {
                                Stop-Function -Message "Issue deploying project" -Target $proj -ErrorRecord $_
                            }
                        }
                    }
                }
            }

            if ($environment) {
                $folderDeploy = $sourceFolders | Where-Object {
                    $_.Environments.Name -eq $environment
                }
                if (!$folderDeploy) {
                    throw "The environment $environment cannot be found in the source Integration Services catalog."
                } else {
                    foreach ($f in $folderDeploy) {
                        if ($destinationFolders[$f.Name].Environments.Name -notcontains $environment) {
                            if ($Pscmdlet.ShouldProcess($destinstance, "Deploying environment $environment from folder $($f.Name)")) {
                                try {
                                    New-FolderEnvironment -Folder $f.Name -Environment $environment
                                } catch {
                                    Stop-Function -Message "Issue deploying environment" -Target $environment -ErrorRecord $_
                                }
                            }
                        } else {
                            if (!$force) {
                                Write-Message -Level Warning -Message "Integration services catalog environment $environment exists in folder $($f.Name) at destination. Use -Force to drop and recreate."
                            } else {
                                If ($Pscmdlet.ShouldProcess($destinstance, "Dropping existing environment $environment and deploying environment $environment from folder $($f.Name)")) {
                                    try {
                                        New-FolderEnvironment -Folder $f.Name -Environment $environment -Force
                                    } catch {
                                        Stop-Function -Message "Issue dropping existing environment" -Target $environment -ErrorRecord $_
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                foreach ($curFolder in $sourceFolders) {
                    foreach ($env in $curFolder.Environments) {
                        if ($destinationFolders[$curFolder.Name].Environments.Name -notcontains $env.Name) {
                            if ($Pscmdlet.ShouldProcess($destinstance, "Deploying environment $($env.Name) from folder $($curFolder.Name)")) {
                                try {
                                    New-FolderEnvironment -Environment $env.Name -Folder $curFolder.Name
                                } catch {
                                    Stop-Function -Message "Issue deploying environment" -Target $env -ErrorRecord $_
                                }
                            }
                        } else {
                            if (!$force) {
                                Write-Message -Level Warning -Message "Integration services catalog environment $($env.Name) exists in folder $($curFolder.Name) at destination. Use -Force to drop and recreate."
                                continue
                            } else {
                                if ($Pscmdlet.ShouldProcess($destinstance, "Deploying environment $($env.Name) from folder $($curFolder.Name)")) {
                                    try {
                                        New-FolderEnvironment -Environment $env.Name -Folder $curFolder.Name -Force
                                    } catch {
                                        Stop-Function -Message "Issue deploying environment" -Target $env -ErrorRecord $_
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlSsisCatalog
    }
}
tools\dbatools\functions\Copy-DbaSysDbUserObject.ps1
function Copy-DbaSysDbUserObject {
    <#
    .SYNOPSIS
        Imports all user objects found in source SQL Server's master, msdb and model databases to the destination.

    .DESCRIPTION
        Imports all user objects found in source SQL Server's master, msdb and model databases to the destination. This is useful because many DBAs store backup/maintenance procs/tables/triggers/etc (among other things) in master or msdb.

        It is also useful for migrating objects within the model database.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Classic
        Perform the migration the old way

    .PARAMETER Force
        Drop destination objects first. Has no effect if you use Classic. This doesn't work really well, honestly.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration, SystemDatabase, UserObject
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Copy-DbaSysDbUserObject

    .EXAMPLE
        PS C:\> Copy-DbaSysDbUserObject -Source $sourceServer -Destination $destserver

        Copies user objects from source to destination

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [DbaInstanceParameter]$Source,
        [PSCredential]$SourceSqlCredential,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]$DestinationSqlCredential,
        [switch]$Force,
        [switch]$Classic,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        function get-sqltypename ($type) {
            switch ($type) {
                "VIEW" { "view" }
                "SQL_TABLE_VALUED_FUNCTION" { "User table valued fsunction" }
                "DEFAULT_CONSTRAINT" { "User default constraint" }
                "SQL_STORED_PROCEDURE" { "User stored procedure" }
                "RULE" { "User rule" }
                "SQL_INLINE_TABLE_VALUED_FUNCTION" { "User inline table valued function" }
                "SQL_TRIGGER" { "User server trigger" }
                "SQL_SCALAR_FUNCTION" { "User scalar function" }
                default { $type }
            }
        }
    }
    process {
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }

        if (!(Test-SqlSa -SqlInstance $sourceServer -SqlCredential $SourceSqlCredential)) {
            Stop-Function -Message "Not a sysadmin on $source. Quitting."
            return
        }

        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }

            if (!(Test-SqlSa -SqlInstance $destServer -SqlCredential $DestinationSqlCredential)) {
                Stop-Function -Message "Not a sysadmin on $destinstance" -Continue
            }

            $systemDbs = "master", "model", "msdb"

            if (-not $Classic) {
                foreach ($systemDb in $systemDbs) {
                    $smodb = $sourceServer.databases[$systemDb]
                    $destdb = $destserver.databases[$systemDb]

                    $tables = $smodb.Tables | Where-Object IsSystemObject -ne $true
                    $schemas = $smodb.Schemas | Where-Object IsSystemObject -ne $true

                    foreach ($schema in $schemas) {
                        $copyobject = [pscustomobject]@{
                            SourceServer      = $sourceServer.Name
                            DestinationServer = $destServer.Name
                            Name              = $schema
                            Type              = "User schema in $systemDb"
                            Status            = $null
                            Notes             = $null
                            DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                        }

                        $destschema = $destdb.Schemas | Where-Object Name -eq $schema.Name
                        $schmadoit = $true

                        if ($destschema) {
                            if (-not $force) {
                                $copyobject.Status = "Skipped"
                                $copyobject.Notes = "Already exists on destination"
                                $schmadoit = $false
                            } else {
                                if ($PSCmdlet.ShouldProcess($destServer, "Dropping schema $schema in $systemDb")) {
                                    try {
                                        Write-Message -Level Verbose -Message "Force specified. Dropping $schema in $destdb on $destinstance"
                                        $destschema.Drop()
                                    } catch {
                                        $schmadoit = $false
                                        $copyobject.Status = "Failed"
                                        $copyobject.Notes = $_.Exception.InnerException.InnerException.InnerException.Message
                                    }
                                }
                            }
                        }

                        if ($schmadoit) {
                            $transfer = New-Object Microsoft.SqlServer.Management.Smo.Transfer $smodb
                            $null = $transfer.CopyAllObjects = $false
                            $null = $transfer.Options.WithDependencies = $true
                            $null = $transfer.ObjectList.Add($schema)
                            if ($PSCmdlet.ShouldProcess($destServer, "Attempting to add schema $($schema.Name) to $systemDb")) {
                                try {
                                    $sql = $transfer.ScriptTransfer()
                                    Write-Message -Level Debug -Message "$sql"
                                    $null = $destServer.Query($sql, $systemDb)
                                    $copyobject.Status = "Successful"
                                    $copyobject.Notes = "May have also created dependencies"
                                } catch {
                                    $copyobject.Status = "Failed"
                                    $copyobject.Notes = (Get-ErrorMessage -Record $_)
                                }
                            }
                        }

                        $copyobject | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    }

                    foreach ($table in $tables) {
                        $copyobject = [pscustomobject]@{
                            SourceServer      = $sourceServer.Name
                            DestinationServer = $destServer.Name
                            Name              = $table
                            Type              = "User table in $systemDb"
                            Status            = $null
                            Notes             = $null
                            DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                        }

                        $desttable = $destdb.Tables.Item($table.Name, $table.Schema)
                        $doit = $true

                        if ($desttable) {
                            if (-not $force) {
                                $copyobject.Status = "Skipped"
                                $copyobject.Notes = "Already exists on destination"
                                $doit = $false
                            } else {
                                if ($PSCmdlet.ShouldProcess($destServer, "Dropping table $table in $systemDb")) {
                                    try {
                                        Write-Message -Level Verbose -Message "Force specified. Dropping $table in $destdb on $destinstance"
                                        $desttable.Drop()
                                    } catch {
                                        $doit = $false
                                        $copyobject.Status = "Failed"
                                        $copyobject.Notes = $_.Exception.InnerException.InnerException.InnerException.Message
                                    }
                                }
                            }
                        }

                        if ($doit) {
                            $transfer = New-Object Microsoft.SqlServer.Management.Smo.Transfer $smodb
                            $null = $transfer.CopyAllObjects = $false
                            $null = $transfer.Options.WithDependencies = $true
                            $null = $transfer.ObjectList.Add($table)
                            if ($PSCmdlet.ShouldProcess($destServer, "Attempting to add table $table to $systemDb")) {
                                try {
                                    $sql = $transfer.ScriptTransfer()
                                    Write-Message -Level Debug -Message "$sql"
                                    $null = $destServer.Query($sql, $systemDb)
                                    $copyobject.Status = "Successful"
                                    $copyobject.Notes = "May have also created dependencies"
                                } catch {
                                    $copyobject.Status = "Failed"
                                    $copyobject.Notes = (Get-ErrorMessage -Record $_)
                                }
                            }
                        }
                        $copyobject | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    }

                    $userobjects = Get-DbaModule -SqlInstance $sourceserver -Database $systemDb -ExcludeSystemObjects | Sort-Object Type
                    Write-Message -Level Verbose -Message "Copying from $systemDb"
                    foreach ($userobject in $userobjects) {

                        $name = "[$($userobject.SchemaName)].[$($userobject.Name)]"
                        $db = $userobject.Database
                        $type = get-sqltypename $userobject.Type
                        $sql = $userobject.Definition
                        $schema = $userobject.SchemaName

                        $copyobject = [pscustomobject]@{
                            SourceServer      = $sourceServer.Name
                            DestinationServer = $destServer.Name
                            Name              = $name
                            Type              = "$type in $systemDb"
                            Status            = $null
                            Notes             = $null
                            DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                        }
                        Write-Message -Level Debug -Message $sql
                        try {
                            Write-Message -Level Verbose -Message "Searching for $name in $db on $destinstance"
                            $result = Get-DbaModule -SqlInstance $destServer -ExcludeSystemObjects -Database $db |
                                Where-Object { $psitem.Name -eq $userobject.Name -and $psitem.Type -eq $userobject.Type }
                            if ($result) {
                                Write-Message -Level Verbose -Message "Found $name in $db on $destinstance"
                                if (-not $Force) {
                                    $copyobject.Status = "Skipped"
                                    $copyobject.Notes = "Already exists on destination"
                                } else {
                                    $smobject = switch ($userobject.Type) {
                                        "VIEW" { $smodb.Views.Item($userobject.Name, $userobject.SchemaName) }
                                        "SQL_STORED_PROCEDURE" { $smodb.StoredProcedures.Item($userobject.Name, $userobject.SchemaName) }
                                        "RULE" { $smodb.Rules.Item($userobject.Name, $userobject.SchemaName) }
                                        "SQL_TRIGGER" { $smodb.Triggers.Item($userobject.Name, $userobject.SchemaName) }
                                        "SQL_TABLE_VALUED_FUNCTION" { $smodb.UserDefinedFunctions.Item($name) }
                                        "SQL_INLINE_TABLE_VALUED_FUNCTION" { $smodb.UserDefinedFunctions.Item($name) }
                                        "SQL_SCALAR_FUNCTION" { $smodb.UserDefinedFunctions.Item($name) }
                                    }

                                    if ($smobject) {
                                        Write-Message -Level Verbose -Message "Force specified. Dropping $smobject on $destdb on $destinstance using SMO"
                                        $transfer = New-Object Microsoft.SqlServer.Management.Smo.Transfer $smodb
                                        $null = $transfer.CopyAllObjects = $false
                                        $null = $transfer.Options.WithDependencies = $true
                                        $null = $transfer.ObjectList.Add($smobject)
                                        $null = $transfer.Options.ScriptDrops = $true
                                        $dropsql = $transfer.ScriptTransfer()
                                        Write-Message -Level Debug -Message "$dropsql"
                                        if ($PSCmdlet.ShouldProcess($destServer, "Attempting to drop $type $name from $systemDb")) {
                                            $null = $destdb.Query("$dropsql")
                                        }
                                    } else {
                                        if ($PSCmdlet.ShouldProcess($destServer, "Attempting to drop $type $name from $systemDb using T-SQL")) {
                                            $null = $destdb.Query("DROP FUNCTION $($userobject.name)")
                                        }
                                    }
                                    if ($PSCmdlet.ShouldProcess($destServer, "Attempting to add $type $name to $systemDb")) {
                                        $null = $destdb.Query("$sql")
                                        $copyobject.Status = "Successful"
                                    }
                                }
                            } else {
                                if ($PSCmdlet.ShouldProcess($destServer, "Attempting to add $type $name to $systemDb")) {
                                    $null = $destdb.Query("$sql")
                                    $copyobject.Status = "Successful"
                                }
                            }
                        } catch {
                            try {
                                $smobject = switch ($userobject.Type) {
                                    "VIEW" { $smodb.Views.Item($userobject.Name, $userobject.SchemaName) }
                                    "SQL_STORED_PROCEDURE" { $smodb.StoredProcedures.Item($userobject.Name, $userobject.SchemaName) }
                                    "RULE" { $smodb.Rules.Item($userobject.Name, $userobject.SchemaName) }
                                    "SQL_TRIGGER" { $smodb.Triggers.Item($userobject.Name, $userobject.SchemaName) }
                                }
                                if ($smobject) {
                                    $transfer = New-Object Microsoft.SqlServer.Management.Smo.Transfer $smodb
                                    $null = $transfer.CopyAllObjects = $false
                                    $null = $transfer.Options.WithDependencies = $true
                                    $null = $transfer.ObjectList.Add($smobject)
                                    $sql = $transfer.ScriptTransfer()
                                    Write-Message -Level Debug -Message "$sql"
                                    Write-Message -Level Verbose -Message "Adding $smoobject on $destdb on $destinstance"
                                    if ($PSCmdlet.ShouldProcess($destServer, "Attempting to add $type $name to $systemDb")) {
                                        $null = $destdb.Query("$sql")
                                    }
                                    $copyobject.Status = "Successful"
                                    $copyobject.Notes = "May have also installed dependencies"
                                } else {
                                    $copyobject.Status = "Failed"
                                    $copyobject.Notes = (Get-ErrorMessage -Record $_)
                                }
                            } catch {
                                $copyobject.Status = "Failed"
                                $copyobject.Notes = (Get-ErrorMessage -Record $_)
                            }
                        }
                        $copyobject | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    }
                }
            } else {
                foreach ($systemDb in $systemDbs) {
                    $sysdb = $sourceServer.databases[$systemDb]
                    $transfer = New-Object Microsoft.SqlServer.Management.Smo.Transfer $sysdb
                    $transfer.CopyAllObjects = $false
                    $transfer.CopyAllDatabaseTriggers = $true
                    $transfer.CopyAllDefaults = $true
                    $transfer.CopyAllRoles = $true
                    $transfer.CopyAllRules = $true
                    $transfer.CopyAllSchemas = $true
                    $transfer.CopyAllSequences = $true
                    $transfer.CopyAllSqlAssemblies = $true
                    $transfer.CopyAllSynonyms = $true
                    $transfer.CopyAllTables = $true
                    $transfer.CopyAllViews = $true
                    $transfer.CopyAllStoredProcedures = $true
                    $transfer.CopyAllUserDefinedAggregates = $true
                    $transfer.CopyAllUserDefinedDataTypes = $true
                    $transfer.CopyAllUserDefinedTableTypes = $true
                    $transfer.CopyAllUserDefinedTypes = $true
                    $transfer.CopyAllUserDefinedFunctions = $true
                    $transfer.CopyAllUsers = $true
                    $transfer.PreserveDbo = $true
                    $transfer.Options.AllowSystemObjects = $false
                    $transfer.Options.ContinueScriptingOnError = $true
                    $transfer.Options.IncludeDatabaseRoleMemberships = $true
                    $transfer.Options.Indexes = $true
                    $transfer.Options.Permissions = $true
                    $transfer.Options.WithDependencies = $false

                    Write-Message -Level Output -Message "Copying from $systemDb."
                    try {
                        $sqlQueries = $transfer.ScriptTransfer()

                        foreach ($sql in $sqlQueries) {
                            Write-Message -Level Debug -Message "$sql"
                            if ($PSCmdlet.ShouldProcess($destServer, $sql)) {
                                try {
                                    $destServer.Query($sql, $systemDb)
                                } catch {
                                    # Don't care - long story having to do with duplicate stuff
                                    # here to avoid an empty catch
                                    $null = 1
                                }
                            }
                        }
                    } catch {
                        # Don't care - long story having to do with duplicate stuff
                        # here to avoid an empty catch
                        $null = 1
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlSysDbUserObjects
    }
}
tools\dbatools\functions\Copy-DbaXESession.ps1
function Copy-DbaXESession {
    <#
    .SYNOPSIS
        Migrates SQL Extended Event Sessions except the two default sessions, AlwaysOn_health and system_health.

    .DESCRIPTION
        Migrates SQL Extended Event Sessions except the two default sessions, AlwaysOn_health and system_health.

        By default, all non-system Extended Events are migrated.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER XeSession
        The Extended Event Session(s) to process. This list is auto-populated from the server. If unspecified, all Extended Event Sessions will be processed.

    .PARAMETER ExcludeXeSession
        The Extended Event Session(s) to exclude. This list is auto-populated from the server.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER Force
        If this switch is enabled, existing Extended Events sessions on Destination with matching names from Source will be dropped.

    .NOTES
        Tags: Migration, ExtendedEvent, XEvent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        https://dbatools.io/Copy-DbaXESession

    .EXAMPLE
        PS C:\> Copy-DbaXESession -Source sqlserver2014a -Destination sqlcluster

        Copies all Extended Event sessions from sqlserver2014a to sqlcluster using Windows credentials.

    .EXAMPLE
        PS C:\> Copy-DbaXESession -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred

        Copies all Extended Event sessions from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster.

    .EXAMPLE
        PS C:\> Copy-DbaXESession -Source sqlserver2014a -Destination sqlcluster -WhatIf

        Shows what would happen if the command were executed.

    .EXAMPLE
        PS C:\> Copy-DbaXESession -Source sqlserver2014a -Destination sqlcluster -XeSession CheckQueries, MonitorUserDefinedException

        Copies only the Extended Events named CheckQueries and MonitorUserDefinedException from sqlserver2014a to sqlcluster.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter]$Source,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]
        $SourceSqlCredential,
        [PSCredential]
        $DestinationSqlCredential,
        [object[]]$XeSession,
        [object[]]$ExcludeXeSession,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Copy-DbaExtendedEvent
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential -MinimumVersion 11
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }
        $sourceSqlConn = $sourceServer.ConnectionContext.SqlConnectionObject
        $sourceSqlStoreConnection = New-Object Microsoft.SqlServer.Management.Sdk.Sfc.SqlStoreConnection $sourceSqlConn
        $sourceStore = New-Object  Microsoft.SqlServer.Management.XEvent.XEStore $sourceSqlStoreConnection
        $storeSessions = $sourceStore.Sessions | Where-Object { $_.Name -notin 'AlwaysOn_health', 'system_health' }
        if ($XeSession) {
            $storeSessions = $storeSessions | Where-Object Name -In $XeSession
        }
        if ($ExcludeXeSession) {
            $storeSessions = $storeSessions | Where-Object Name -NotIn $ExcludeXeSession
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential -MinimumVersion 11
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
            }

            $destSqlConn = $destServer.ConnectionContext.SqlConnectionObject
            $destSqlStoreConnection = New-Object Microsoft.SqlServer.Management.Sdk.Sfc.SqlStoreConnection $destSqlConn
            $destStore = New-Object  Microsoft.SqlServer.Management.XEvent.XEStore $destSqlStoreConnection

            Write-Message -Level Verbose -Message "Migrating sessions."
            foreach ($session in $storeSessions) {
                $sessionName = $session.Name

                $copyXeSessionStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Name              = $sessionName
                    Type              = "Extended Event"
                    Status            = $null
                    Notes             = $null
                    DateTime          = [DbaDateTime](Get-Date)
                }

                if ($null -ne $destStore.Sessions[$sessionName]) {
                    if ($force -eq $false) {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Extended Event Session '$sessionName' was skipped because it already exists on $destinstance.")) {
                            $copyXeSessionStatus.Status = "Skipped"
                            $copyXeSessionStatus.Notes = "Already exists on destination"
                            $copyXeSessionStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                            Write-Message -Level Verbose -Message "Extended Event Session '$sessionName' was skipped because it already exists on $destinstance."
                            Write-Message -Level Verbose -Message "Use -Force to drop and recreate."
                        }
                        continue
                    } else {
                        if ($Pscmdlet.ShouldProcess($destinstance, "Attempting to drop $sessionName")) {
                            Write-Message -Level Verbose -Message "Extended Event Session '$sessionName' exists on $destinstance."
                            Write-Message -Level Verbose -Message "Force specified. Dropping $sessionName."

                            try {
                                $destStore.Sessions[$sessionName].Drop()
                            } catch {
                                $copyXeSessionStatus.Status = "Failed"
                                $copyXeSessionStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                                Stop-Function -Message "Unable to drop session. Moving on." -Target $sessionName -ErrorRecord $_ -Continue
                            }
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destinstance, "Migrating session $sessionName")) {
                    try {
                        $sql = $session.ScriptCreate().GetScript() | Out-String

                        Write-Message -Level Debug -Message $sql
                        Write-Message -Level Verbose -Message "Migrating session $sessionName."
                        $null = $destServer.Query($sql)

                        if ($session.IsRunning -eq $true) {
                            $destStore.Sessions.Refresh()
                            $destStore.Sessions[$sessionName].Start()
                        }

                        $copyXeSessionStatus.Status = "Successful"
                        $copyXeSessionStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
                    } catch {
                        $copyXeSessionStatus.Status = "Failed"
                        $copyXeSessionStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject

                        Stop-Function -Message "Unable to create session." -Target $sessionName -ErrorRecord $_
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Copy-SqlExtendedEvent
    }
}
tools\dbatools\functions\Copy-DbaXESessionTemplate.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Copy-DbaXESessionTemplate {
    <#
    .SYNOPSIS
        Copies non-Microsoft templates from the dbatools template repository (\bin\xetemplates\) to $home\Documents\SQL Server Management Studio\Templates\XEventTemplates.

    .DESCRIPTION
        Copies non-Microsoft templates from the dbatools template repository (\bin\xetemplates\) to $home\Documents\SQL Server Management Studio\Templates\XEventTemplates.

        Useful for when you want to use the SSMS GUI.

    .PARAMETER Path
        The path to the template directory. Defaults to the dbatools template repository (\bin\xetemplates\).

    .PARAMETER Destination
        Path to the Destination directory, defaults to $home\Documents\SQL Server Management Studio\Templates\XEventTemplates.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Copy-DbaXESessionTemplate

    .EXAMPLE
        PS C:\> Copy-DbaXESessionTemplate

        Copies non-Microsoft templates from the dbatools template repository (\bin\xetemplates\) to $home\Documents\SQL Server Management Studio\Templates\XEventTemplates.

    .EXAMPLE
        PS C:\> Copy-DbaXESessionTemplate -Path C:\temp\xetemplates

        Copies your templates from C:\temp\xetemplates to $home\Documents\SQL Server Management Studio\Templates\XEventTemplates.

    #>
    [CmdletBinding()]
    param (
        [string[]]$Path = "$script:PSModuleRoot\bin\xetemplates",
        [string]$Destination = "$home\Documents\SQL Server Management Studio\Templates\XEventTemplates",
        [switch]$EnableException
    )
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($destinstance in $Destination) {
            if (-not (Test-Path -Path $destinstance)) {
                try {
                    $null = New-Item -ItemType Directory -Path $destinstance -ErrorAction Stop
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target $destinstance
                }
            }
            try {
                $files = (Get-DbaXESessionTemplate -Path $Path | Where-Object Source -ne Microsoft).Path
                foreach ($file in $files) {
                    Write-Message -Level Output -Message "Copying $($file.Name) to $destinstance."
                    Copy-Item -Path $file -Destination $destinstance -ErrorAction Stop
                }
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Target $path
            }
        }
    }
}
tools\dbatools\functions\Disable-DbaAgHadr.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Disable-DbaAgHadr {
    <#
    .SYNOPSIS
        Disables the Hadr service setting on the specified SQL Server.

    .DESCRIPTION
        In order to build an AG a cluster has to be built and then the Hadr enabled for the SQL Server
        service. This function disables that feature for the SQL Server service.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER Credential
        Credential object used to connect to the Windows server as a different user

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER Force
        Will restart SQL Server and SQL Server Agent service to apply the change.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Hadr, AG, AvailabilityGroup
        Author: Shawn Melton (@wsmelton), http://wsmelton.github.io

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Disable-DbaAgHadr

    .EXAMPLE
        PS C:\> Disable-DbaAgHadr -SqlInstance sql2016

        Sets Hadr service to disabled for the instance sql2016 but changes will not be applied until the next time the server restarts.

    .EXAMPLE
        PS C:\> Disable-DbaAgHadr -SqlInstance sql2016 -Force

        Sets Hadr service to disabled for the instance sql2016, and restart the service to apply the change.

    .EXAMPLE
        PS C:\> Disable-DbaAgHadr -SqlInstance sql2012\dev1 -Force

        Sets Hadr service to disabled for the instance dev1 on sq2012, and restart the service to apply the change.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$Credential,
        [switch]$Force,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            $computer = $computerFullName = $instance.ComputerName
            $instanceName = $instance.InstanceName
            if (-not (Test-ElevationRequirement -ComputerName $instance)) {
                return
            }
            $noChange = $false

            <#
            #Variable marked as unused by PSScriptAnalyzer
            switch ($instance.InstanceName) {
                'MSSQLSERVER' { $agentName = 'SQLSERVERAGENT' }
                default { $agentName = "SQLAgent`$$instanceName" }
            }
            #>

            try {
                Write-Message -Level Verbose -Message "Checking current Hadr setting for $computer"
                $currentState = Get-WmiHadr -SqlInstance $instance -Credential $Credential
            } catch {
                Stop-Function -Message "Failure to pull current state of Hadr setting on $computer" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $isHadrEnabled = $currentState.IsHadrEnabled
            Write-Message -Level InternalComment -Message "$instance Hadr current value: $isHadrEnabled"

            # hadr results from sql wmi can be iffy, skip the check
            <#
            if (-not $isHadrEnabled) {
                Write-Message -Level Warning -Message "Hadr is already disabled for instance: $($instance.FullName)"
                $noChange = $true
                continue
            }
            #>

            $scriptblock = {
                $instance = $args[0]
                $sqlService = $wmi.Services | Where-Object DisplayName -eq "SQL Server ($instance)"
                $sqlService.ChangeHadrServiceSetting(0)
            }

            if ($noChange -eq $false) {
                if ($PSCmdlet.ShouldProcess($instance, "Changing Hadr from $isHadrEnabled to 0 for $instance")) {
                    try {
                        Invoke-ManagedComputerCommand -ComputerName $computerFullName -Credential $Credential -ScriptBlock $scriptblock -ArgumentList $instancename
                    } catch {
                        Stop-Function -Continue -Message "Failure on $($instance.FullName) | This may be because AlwaysOn Availability Groups feature requires the x86(non-WOW) or x64 Enterprise Edition of SQL Server 2012 (or later version) running on Windows Server 2008 (or later version) with WSFC hotfix KB 2494036 installed."
                    }
                }
                if (Test-Bound 'Force') {
                    if ($PSCmdlet.ShouldProcess($instance, "Force provided, restarting Engine and Agent service for $instance on $computerFullName")) {
                        try {
                            $null = Stop-DbaService -ComputerName $computerFullName -InstanceName $instanceName -Type Agent, Engine
                            $null = Start-DbaService -ComputerName $computerFullName -InstanceName $instanceName -Type Agent, Engine
                        } catch {
                            Stop-Function -Message "Issue restarting $instance" -Target $instance -Continue
                        }
                    }
                }
                $newState = Get-WmiHadr -SqlInstance $instance -Credential $Credential

                if (Test-Bound -Not -ParameterName Force) {
                    Write-Message -Level Warning -Message "You must restart the SQL Server for it to take effect."
                }

                [PSCustomObject]@{
                    ComputerName  = $newState.ComputerName
                    InstanceName  = $newState.InstanceName
                    SqlInstance   = $newState.SqlInstance
                    IsHadrEnabled = $false
                }
            }
        }
    }
}
tools\dbatools\functions\Disable-DbaFilestream.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Disable-DbaFilestream {
    <#
    .SYNOPSIS
        Sets the status of FileStream on specified SQL Server instances both at the server level and the instance level

    .DESCRIPTION
        Connects to the specified SQL Server instances, and sets the status of the FileStream feature to the required value

        To perform the action, the SQL Server instance must be restarted. By default we will prompt for confirmation for this action, this can be overridden with the -Force switch

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Defaults to localhost.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Credential
        Login to the target server using alternative credentials.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER Force
        Restart SQL Instance after changes. Use this parameter with care as it overrides whatif.

    .PARAMETER WhatIf
        Shows what would happen if the command runs. The command is not run unless Force is specified.

    .PARAMETER Confirm
        Prompts you for confirmation before running the command.

    .NOTES
        Tags: Filestream
        Author: Stuart Moore ( @napalmgram ) | Chrissy LeMaire ( @cl )
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Disable-DbaFilestream -SqlInstance server1\instance2

        Prompts for confirmation. Disables filestream on the service and instance levels.

    .EXAMPLE
        PS C:\> Disable-DbaFilestream -SqlInstance server1\instance2 -Confirm:$false

        Does not prompt for confirmation. Disables filestream on the service and instance levels.

    .EXAMPLE
        PS C:\> Get-DbaFilestream -SqlInstance server1\instance2, server5\instance5, prod\hr | Where-Object InstanceAccessLevel -gt 0 | Disable-DbaFilestream -Force

        Using this pipeline you can scan a range of SQL instances and disable filestream on only those on which it's enabled.

       #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")]
    param (
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [DbaInstance[]]$SqlInstance,
        [Parameter(ValueFromPipelineByPropertyName)]
        [PSCredential]$SqlCredential,
        [Parameter(ValueFromPipelineByPropertyName)]
        [PSCredential]$Credential,
        [switch]$Force,
        [switch]$EnableException
    )
    begin {
        $FileStreamLevel = $level = 0

        $OutputLookup = @{
            0 = 'Disabled'
            1 = 'FileStream enabled for T-Sql access'
            2 = 'FileStream enabled for T-Sql and IO streaming access'
            3 = 'FileStream enabled for T-Sql, IO streaming, and remote clients'
        }
    }
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure connecting to $computer" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            # Instance level
            $filestreamstate = [int]$server.Configuration.FilestreamAccessLevel.RunningValue

            if ($Force -or $PSCmdlet.ShouldProcess($instance, "Changing from '$($OutputLookup[$filestreamstate])' to '$($OutputLookup[$level])' at the instance level")) {
                try {
                    $null = Set-DbaSpConfigure -SqlInstance $server -Name FilestreamAccessLevel -Value $level -EnableException
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
                }


                # Server level
                if ($server.IsClustered) {
                    $nodes = Get-DbaWsfcNode -ComputerName $instance -Credential $Credential
                    foreach ($node in $nodes.Name) {
                        $result = Set-FileSystemSetting -Instance $node -Credential $Credential -FilestreamLevel $FileStreamLevel
                    }
                } else {
                    $result = Set-FileSystemSetting -Instance $instance -Credential $Credential -FilestreamLevel $FileStreamLevel
                }

                if ($Force) {
                    #$restart replaced with $null as it was identified as a unused variable
                    $null = Restart-DbaService -ComputerName $instance.ComputerName -InstanceName $server.ServiceName -Type Engine -Force
                }

                Get-DbaFilestream -SqlInstance $instance -SqlCredential $SqlCredential -Credential $Credential

                if ($filestreamstate -ne $level -and -not $Force) {
                    Write-Message -Level Warning -Message "[$instance] $result"
                }
            }
        }
    }
}
tools\dbatools\functions\Disable-DbaForceNetworkEncryption.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#

function Disable-DbaForceNetworkEncryption {
    <#
    .SYNOPSIS
        Disables Force Encryption for a SQL Server instance

    .DESCRIPTION
        Disables Force Encryption for a SQL Server instance. Note that this requires access to the Windows Server, not the SQL instance itself.

        This setting is found in Configuration Manager.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Defaults to localhost.

    .PARAMETER Credential
        Allows you to login to the computer (not SQL Server instance) using alternative Windows credentials.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Certificate
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Disable-DbaForceNetworkEncryption

        Disables Force Encryption on the default (MSSQLSERVER) instance on localhost - requires (and checks for) RunAs admin.

    .EXAMPLE
        PS C:\> Disable-DbaForceNetworkEncryption -SqlInstance sql01\SQL2008R2SP2

        Disables Force Network Encryption for the SQL2008R2SP2 on sql01. Uses Windows Credentials to both login and modify the registry.

    .EXAMPLE
        PS C:\> Disable-DbaForceNetworkEncryption -SqlInstance sql01\SQL2008R2SP2 -WhatIf

        Shows what would happen if the command were executed.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [Parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "ComputerName")]
        [DbaInstanceParameter[]]$SqlInstance = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {

        foreach ($instance in $sqlinstance) {
            Write-Message -Level VeryVerbose -Message "Processing $instance." -Target $instance
            $null = Test-ElevationRequirement -ComputerName $instance -Continue

            Write-Message -Level Verbose -Message "Resolving hostname."
            $resolved = $null
            $resolved = Resolve-DbaNetworkName -ComputerName $instance -Turbo

            if ($null -eq $resolved) {
                Stop-Function -Message "Can't resolve $instance." -Target $instance -Continue -Category InvalidArgument
            }

            try {
                $sqlwmi = Invoke-ManagedComputerCommand -ComputerName $resolved.FullComputerName -ScriptBlock { $wmi.Services } -Credential $Credential -ErrorAction Stop | Where-Object DisplayName -eq "SQL Server ($($instance.InstanceName))"
            } catch {
                Stop-Function -Message "Failed to access $instance." -Target $instance -Continue -ErrorRecord $_
            }

            $regroot = ($sqlwmi.AdvancedProperties | Where-Object Name -eq REGROOT).Value
            $vsname = ($sqlwmi.AdvancedProperties | Where-Object Name -eq VSNAME).Value
            try {
                $instancename = $sqlwmi.DisplayName.Replace('SQL Server (', '').Replace(')', '') # Don't clown, I don't know regex :(
            } catch {
                # Probably because the instance name has been aliased or does not exist or something
                # here to avoid an empty catch
                $null = 1
            }
            $serviceaccount = $sqlwmi.ServiceAccount

            if ([System.String]::IsNullOrEmpty($regroot)) {
                $regroot = $sqlwmi.AdvancedProperties | Where-Object { $_ -match 'REGROOT' }
                $vsname = $sqlwmi.AdvancedProperties | Where-Object { $_ -match 'VSNAME' }

                if (![System.String]::IsNullOrEmpty($regroot)) {
                    $regroot = ($regroot -Split 'Value\=')[1]
                    $vsname = ($vsname -Split 'Value\=')[1]
                } else {
                    Stop-Function -Message "Can't find instance $vsname on $instance." -Continue -Category ObjectNotFound -Target $instance
                }
            }

            if ([System.String]::IsNullOrEmpty($vsname)) { $vsname = $instance }

            Write-Message -Level Output -Message "Regroot: $regroot" -Target $instance
            Write-Message -Level Output -Message "ServiceAcct: $serviceaccount" -Target $instance
            Write-Message -Level Output -Message "InstanceName: $instancename" -Target $instance
            Write-Message -Level Output -Message "VSNAME: $vsname" -Target $instance

            $scriptblock = {
                $regpath = "Registry::HKEY_LOCAL_MACHINE\$($args[0])\MSSQLServer\SuperSocketNetLib"
                $cert = (Get-ItemProperty -Path $regpath -Name Certificate).Certificate
                #Variable marked as unused by PSScriptAnalyzer
                #$oldvalue = (Get-ItemProperty -Path $regpath -Name ForceEncryption).ForceEncryption
                Set-ItemProperty -Path $regpath -Name ForceEncryption -Value $false
                $forceencryption = (Get-ItemProperty -Path $regpath -Name ForceEncryption).ForceEncryption

                [pscustomobject]@{
                    ComputerName          = $env:COMPUTERNAME
                    InstanceName          = $args[2]
                    SqlInstance           = $args[1]
                    ForceEncryption       = ($forceencryption -eq $true)
                    CertificateThumbprint = $cert
                }
            }

            if ($PScmdlet.ShouldProcess("local", "Connecting to $instance to modify the ForceEncryption value in $regroot for $($instance.InstanceName)")) {
                try {
                    Invoke-Command2 -ComputerName $resolved.FullComputerName -Credential $Credential -ArgumentList $regroot, $vsname, $instancename -ScriptBlock $scriptblock -ErrorAction Stop
                    Write-Message -Level Critical -Message "Force encryption was successfully set on $($resolved.FullComputerName) for the $instancename instance. You must now restart the SQL Server for changes to take effect." -Target $instance
                } catch {
                    Stop-Function -Message "Failed to connect to $($resolved.FullComputerName) using PowerShell remoting!" -ErrorRecord $_ -Target $instance -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Disable-DbaTraceFlag.ps1
function Disable-DbaTraceFlag {
    <#
    .SYNOPSIS
        Disable a Global Trace Flag that is currently running

    .DESCRIPTION
        The function will disable a Trace Flag that is currently running globally on the SQL Server instance(s) listed

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER TraceFlag
        Trace flag number to enable globally

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: TraceFlag, DBCC
        Author: Garry Bargsley (@gbargsley), http://blog.garrybargsley.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Disable-DbaTraceFlag

    .EXAMPLE
        PS C:\> Disable-DbaTraceFlag -SqlInstance sql2016 -TraceFlag 3226

        Disable the globally running trace flag 3226 on SQL Server instance sql2016

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(Mandatory)]
        [int[]]$TraceFlag,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $current = Get-DbaTraceFlag -SqlInstance $server -EnableException

            foreach ($tf in $TraceFlag) {
                $TraceFlagInfo = [pscustomobject]@{
                    SourceServer = $server.ComputerName
                    InstanceName = $server.ServiceName
                    SqlInstance  = $server.DomainInstanceName
                    TraceFlag    = $tf
                    Status       = $null
                    Notes        = $null
                    DateTime     = [DbaDateTime](Get-Date)
                }
                if ($tf -notin $current.TraceFlag) {
                    $TraceFlagInfo.Status = 'Skipped'
                    $TraceFlagInfo.Notes = "Trace Flag is not running."
                    $TraceFlagInfo
                    Write-Message -Level Warning -Message "Trace Flag $tf is not currently running on $instance"
                    continue
                }

                try {
                    $query = "DBCC TRACEOFF ($tf, -1)"
                    $server.Query($query)
                } catch {
                    $TraceFlagInfo.Status = "Failed"
                    $TraceFlagInfo.Notes = $_.Exception.Message
                    $TraceFlagInfo
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target $server -Continue
                }
                $TraceFlagInfo.Status = "Successful"
                $TraceFlagInfo
            }
        }
    }
}
tools\dbatools\functions\Dismount-DbaDatabase.ps1
function Dismount-DbaDatabase {
    <#
    .SYNOPSIS
        Detach a SQL Server Database.

    .DESCRIPTION
        This command detaches one or more SQL Server databases. If necessary, -Force can be used to break mirrors and remove databases from availability groups prior to detaching.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to detach.

    .PARAMETER FileStructure
        A StringCollection object value that contains a list database files. If FileStructure is not specified, BackupHistory will be used to guess the structure.

    .PARAMETER InputObject
        A collection of databases (such as returned by Get-DbaDatabase), to be detached.

    .PARAMETER UpdateStatistics
        If this switch is enabled, statistics for the database will be updated prior to detaching it.

    .PARAMETER Force
        If this switch is enabled and the database is part of a mirror, the mirror will be broken. If the database is part of an Availability Group, it will be removed from the AG.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Dismount-DbaDatabase

    .EXAMPLE
        PS C:\> Detach-DbaDatabase -SqlInstance sql2016b -Database SharePoint_Config, WSS_Logging

        Detaches SharePoint_Config and WSS_Logging from sql2016b

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sql2016b -Database 'PerformancePoint Service Application_10032db0fa0041df8f913f558a5dc0d4' | Detach-DbaDatabase -Force

        Detaches 'PerformancePoint Service Application_10032db0fa0041df8f913f558a5dc0d4' from sql2016b. Since Force was specified, if the database is part of mirror, the mirror will be broken prior to detaching.

        If the database is part of an Availability Group, it will first be dropped prior to detachment.

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sql2016b -Database WSS_Logging | Detach-DbaDatabase -Force -WhatIf

        Shows what would happen if the command were to execute (without actually executing the detach/break/remove commands).

    #>
    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = "Default")]
    param (
        [parameter(Mandatory, ParameterSetName = 'SqlInstance')]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(Mandatory, ParameterSetName = 'SqlInstance')]
        [string[]]$Database,
        [parameter(Mandatory, ParameterSetName = 'Pipeline', ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [Switch]$UpdateStatistics,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($Database) {
                $InputObject += $server.Databases | Where-Object Name -in $Database
            } else {
                $InputObject += $server.Databases
            }

            if ($ExcludeDatabase) {
                $InputObject = $InputObject | Where-Object Name -NotIn $ExcludeDatabase
            }
        }

        foreach ($db in $InputObject) {
            $db.Refresh()
            $server = $db.Parent

            if ($db.IsSystemObject) {
                Stop-Function -Message "$db is a system database and cannot be detached using this method." -Target $db -Continue
            }

            Write-Message -Level Verbose -Message "Checking replication status."
            if ($db.ReplicationOptions -ne "None") {
                Stop-Function -Message "Skipping $db  on $server because it is replicated." -Target $db -Continue
            }

            # repeat because different servers could be piped in
            $snapshots = (Get-DbaDbSnapshot -SqlInstance $server).SnapshotOf
            Write-Message -Level Verbose -Message "Checking for snaps"
            if ($db.Name -in $snapshots) {
                Write-Message -Level Warning -Message "Database $db has snapshots, you need to drop them before detaching. Skipping $db on $server."
                Continue
            }

            Write-Message -Level Verbose -Message "Checking mirror status"
            if ($db.IsMirroringEnabled -and !$Force) {
                Stop-Function -Message "$db on $server is being mirrored. Use -Force to break mirror or use the safer backup/restore method." -Target $db -Continue
            }

            Write-Message -Level Verbose -Message "Checking Availability Group status"

            if ($db.AvailabilityGroupName -and !$Force) {
                $ag = $db.AvailabilityGroupName
                Stop-Function -Message "$db on $server is part of an Availability Group ($ag). Use -Force to drop from $ag availability group to detach. Alternatively, you can use the safer backup/restore method." -Target $db -Continue
            }

            $sessions = Get-DbaProcess -SqlInstance $db.Parent -Database $db.Name

            if ($sessions -and !$Force) {
                Stop-Function -Message "$db on $server currently has connected users and cannot be dropped. Use -Force to kill all connections and detach the database." -Target $db -Continue
            }

            if ($force) {

                if ($sessions) {
                    If ($Pscmdlet.ShouldProcess($server, "Killing $($sessions.count) sessions which are connected to $db")) {
                        $null = $sessions | Stop-DbaProcess -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
                    }
                }

                if ($db.IsMirroringEnabled) {
                    If ($Pscmdlet.ShouldProcess($server, "Breaking mirror for $db on $server")) {
                        try {
                            Write-Message -Level Warning -Message "Breaking mirror for $db on $server."
                            $db.ChangeMirroringState([Microsoft.SqlServer.Management.Smo.MirroringOption]::Off)
                            $db.Alter()
                            $db.Refresh()
                        } catch {
                            Stop-Function -Message "Could not break mirror for $db on $server - not detaching." -Target $db -ErrorRecord $_ -Continue
                        }
                    }
                }

                if ($db.AvailabilityGroupName) {
                    $ag = $db.AvailabilityGroupName
                    If ($Pscmdlet.ShouldProcess($server, "Attempting remove $db on $server from Availability Group $ag")) {
                        try {
                            $server.AvailabilityGroups[$ag].AvailabilityDatabases[$db.name].Drop()
                            Write-Message -Level Verbose -Message "Successfully removed $db from  detach from $ag on $server."
                        } catch {
                            if ($_.Exception.InnerException) {
                                $exception = $_.Exception.InnerException.ToString() -Split "System.Data.SqlClient.SqlException: "
                                $exception = " | $(($exception[1] -Split "at Microsoft.SqlServer.Management.Common.ConnectionManager")[0])".TrimEnd()
                            }

                            Stop-Function -Message "Could not remove $db from $ag on $server $exception." -Target $db -ErrorRecord $_ -Continue
                        }
                    }
                }

                $sessions = Get-DbaProcess -SqlInstance $db.Parent -Database $db.Name

                if ($sessions) {
                    If ($Pscmdlet.ShouldProcess($server, "Killing $($sessions.count) sessions which are still connected to $db")) {
                        $null = $sessions | Stop-DbaProcess -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
                    }
                }
            }

            If ($Pscmdlet.ShouldProcess($server, "Detaching $db on $server")) {
                try {
                    $server.DetachDatabase($db.Name, $UpdateStatistics)

                    [pscustomobject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Database     = $db.name
                        DetachResult = "Success"
                    }
                } catch {
                    Stop-Function -Message "Failure" -Target $db -ErrorRecord $_ -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Enable-DbaAgHadr.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Enable-DbaAgHadr {
    <#
    .SYNOPSIS
        Enables the Hadr service setting on the specified SQL Server.

    .DESCRIPTION
        In order to build an AG a cluster has to be built and then the Hadr enabled for the SQL Server
        service. This function enables that feature for the SQL Server service.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER Credential
        Credential object used to connect to the Windows server as a different user

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER Force
        Will restart SQL Server and SQL Server Agent service to apply the change.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Hadr, HA, AG, AvailabilityGroup
        Author: Shawn Melton (@wsmelton), http://wsmelton.github.io

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Enable-DbaAgHadr

    .EXAMPLE
        PS C:\> Enable-DbaAgHadr -SqlInstance sql2016

        Sets Hadr service to enabled for the instance sql2016 but changes will not be applied until the next time the server restarts.

    .EXAMPLE
        PS C:\> Enable-DbaAgHadr -SqlInstance sql2016 -Force

        Sets Hadr service to enabled for the instance sql2016, and restart the service to apply the change.

    .EXAMPLE
        PS C:\> Enable-DbaAgHadr -SqlInstance sql2012\dev1 -Force

        Sets Hadr service to disabled for the instance dev1 on sq2012, and restart the service to apply the change.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$Credential,
        [switch]$Force,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            $computer = $computerFullName = $instance.ComputerName
            $instanceName = $instance.InstanceName
            if (-not (Test-ElevationRequirement -ComputerName $instance)) {
                return
            }
            $noChange = $false

            <#
            #Variable marked as unused by PSScriptAnalyzer
            switch ($instance.InstanceName) {
                'MSSQLSERVER' { $agentName = 'SQLSERVERAGENT' }
                default { $agentName = "SQLAgent`$$instanceName" }
            }
            #>

            try {
                Write-Message -Level Verbose -Message "Checking current Hadr setting for $computer"
                $currentState = Get-WmiHadr -SqlInstance $instance -Credential $Credential
            } catch {
                Stop-Function -Message "Failure to pull current state of Hadr setting on $computer" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            $isHadrEnabled = $currentState.IsHadrEnabled
            Write-Message -Level InternalComment -Message "$instance Hadr current value: $isHadrEnabled"

            # hadr results from sql wmi can be iffy, skip the check
            <#
            if ($isHadrEnabled) {
                Write-Message -Level Warning -Message "Hadr is already enabled for instance: $($instance.FullName)"
                $noChange = $true
                continue
            }
            #>

            $scriptblock = {
                $instance = $args[0]
                $sqlService = $wmi.Services | Where-Object DisplayName -eq "SQL Server ($instance)"
                $sqlService.ChangeHadrServiceSetting(1)
            }

            if ($noChange -eq $false) {
                if ($PSCmdlet.ShouldProcess($instance, "Changing Hadr from $isHadrEnabled to 1 for $instance")) {
                    try {
                        Invoke-ManagedComputerCommand -ComputerName $computerFullName -Credential $Credential -ScriptBlock $scriptblock -ArgumentList $instancename
                    } catch {
                        Stop-Function -Continue -Message "Failure on $($instance.FullName) | This may be because AlwaysOn Availability Groups feature requires the x86(non-WOW) or x64 Enterprise Edition of SQL Server 2012 (or later version) running on Windows Server 2008 (or later version) with WSFC hotfix KB 2494036 installed."
                    }
                }
            }

            if (Test-Bound -ParameterName Force) {
                if ($PSCmdlet.ShouldProcess($instance, "Force provided, restarting Engine and Agent service for $instance on $computerFullName")) {
                    try {
                        $null = Stop-DbaService -ComputerName $computerFullName -InstanceName $instanceName -Type Agent, Engine
                        $null = Start-DbaService -ComputerName $computerFullName -InstanceName $instanceName -Type Agent, Engine
                    } catch {
                        Stop-Function -Message "Issue restarting $instance" -Target $instance -Continue
                    }
                }
            }
            $newState = Get-WmiHadr -SqlInstance $instance -Credential $Credential

            if (Test-Bound -Not -ParameterName Force) {
                Write-Message -Level Warning -Message "You must restart the SQL Server for it to take effect."
            }

            [PSCustomObject]@{
                ComputerName  = $newState.ComputerName
                InstanceName  = $newState.InstanceName
                SqlInstance   = $newState.SqlInstance
                IsHadrEnabled = $true
            }
        }
    }
}
tools\dbatools\functions\Enable-DbaFilestream.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Enable-DbaFilestream {
    <#
    .SYNOPSIS
        Enables FileStream on specified SQL Server instances

    .DESCRIPTION
        Connects to the specified SQL Server instances, and Enables the FileStream feature to the required value

        To perform the action, the SQL Server instance must be restarted. By default we will prompt for confirmation for this action, this can be overridden with the -Force switch

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Defaults to localhost.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Credential
        Login to the target server using alternative credentials.

    .PARAMETER FileStreamLevel
        The level to of FileStream to be enabled:
        1 or TSql - T-Sql Access Only
        2 or TSqlIoStreaming - T-Sql and Win32 access enabled
        3 or TSqlIoStreamingRemoteClient T-Sql, Win32 and Remote access enabled

    .PARAMETER ShareName
        Specifies the Windows file share name to be used for storing the FILESTREAM data.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER Force
        Restart SQL Instance after changes. Use this parameter with care as it overrides whatif.

    .PARAMETER WhatIf
        Shows what would happen if the command runs. The command is not run unless Force is specified.

    .PARAMETER Confirm
        Prompts you for confirmation before running the command.

    .NOTES
        Tags: Filestream
        Author: Stuart Moore ( @napalmgram ) | Chrissy LeMaire ( @cl )
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Enable-DbaFilestream -SqlInstance server1\instance2 -FileStreamLevel TSql
        PS C:\> Enable-DbaFilestream -SqlInstance server1\instance2 -FileStreamLevel 1

        These commands are functionally equivalent, both will set Filestream level on server1\instance2 to T-Sql Only

    .EXAMPLE
        PS C:\> Get-DbaFilestream -SqlInstance server1\instance2, server5\instance5, prod\hr | Where-Object InstanceAccessLevel -eq 0 | Enable-DbaFilestream -FileStreamLevel TSqlIoStreamingRemoteClient -Force

        Using this pipeline you can scan a range of SQL instances and enable filestream on only those on which it's disabled.

       #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Medium")]
    param (
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [DbaInstance[]]$SqlInstance,
        [Parameter(ValueFromPipelineByPropertyName)]
        [PSCredential]$SqlCredential,
        [Parameter(ValueFromPipelineByPropertyName)]
        [PSCredential]$Credential,
        [ValidateSet("TSql", "TSqlIoStreaming", "TSqlIoStreamingRemoteClient", 1, 2, 3)]
        [string]$FileStreamLevel = 1,
        [string]$ShareName,
        [switch]$Force,
        [switch]$EnableException
    )
    begin {
        if ($FileStreamLevel -notin (1, 2, 3)) {
            $FileStreamLevel = switch ($FileStreamLevel) {
                "TSql" {
                    1
                }
                "TSqlIoStreaming" {
                    2
                }
                "TSqlIoStreamingRemoteClient" {
                    3
                }
            }
        }
        # = $finallevel removed as it was identified as a unused variable
        $level = [int]$FileStreamLevel
        $OutputLookup = @{
            0 = 'Disabled'
            1 = 'FileStream enabled for T-Sql access'
            2 = 'FileStream enabled for T-Sql and IO streaming access'
            3 = 'FileStream enabled for T-Sql, IO streaming, and remote clients'
        }
    }
    process {
        if ($ShareName -and $level -lt 2) {
            Stop-Function -Message "Filestream must be at least level 2 when using ShareName"
            return
        }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure connecting to $computer" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $filestreamstate = [int]$server.Configuration.FilestreamAccessLevel.ConfigValue

            if ($Force -or $PSCmdlet.ShouldProcess($instance, "Changing from '$($OutputLookup[$filestreamstate])' to '$($OutputLookup[$level])' at the instance level")) {
                # Server level
                if ($server.IsClustered) {
                    $nodes = Get-DbaWsfcNode -ComputerName $instance
                    foreach ($node in $nodes.Name) {
                        $result = Set-FileSystemSetting -Instance $node -Credential $Credential -ShareName $ShareName -FilestreamLevel $level
                    }
                } else {
                    $result = Set-FileSystemSetting -Instance $instance -Credential $Credential -ShareName $ShareName -FilestreamLevel $level
                }

                # Instance level
                if ($level -eq 3) {
                    $level = 2
                }

                try {
                    $null = Set-DbaSpConfigure -SqlInstance $server -Name FilestreamAccessLevel -Value $level -EnableException
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
                }

                if ($Force) {
                    #$restart replaced with $null as it was identified as a unused variable
                    $null = Restart-DbaService -ComputerName $server.ComputerName -InstanceName $server.ServiceName -Type Engine -Force
                }

                Get-DbaFilestream -SqlInstance $instance -SqlCredential $SqlCredential -Credential $Credential
                if ($filestreamstate -ne $level -and -not $Force) {
                    Write-Message -Level Warning -Message "[$instance] $result"
                }
            }
        }
    }
}
tools\dbatools\functions\Enable-DbaForceNetworkEncryption.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Enable-DbaForceNetworkEncryption {
    <#
    .SYNOPSIS
        Enables Force Encryption for a SQL Server instance.

    .DESCRIPTION
        Enables Force Encryption for a SQL Server instance. Note that this requires access to the Windows Server, not the SQL instance itself.

        This setting is found in Configuration Manager.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER Credential
        Allows you to login to the computer (not SQL Server instance) using alternative Windows credentials

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Certificate, Encryption
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Enable-DbaForceNetworkEncryption

        Enables Force Encryption on the default (MSSQLSERVER) instance on localhost. Requires (and checks for) RunAs admin.

    .EXAMPLE
        PS C:\> Enable-DbaForceNetworkEncryption -SqlInstance sql01\SQL2008R2SP2

        Enables Force Network Encryption for the SQL2008R2SP2 on sql01. Uses Windows Credentials to both connect and modify the registry.

    .EXAMPLE
        PS C:\> Enable-DbaForceNetworkEncryption -SqlInstance sql01\SQL2008R2SP2 -WhatIf

        Shows what would happen if the command were executed.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low", DefaultParameterSetName = 'Default')]
    param (
        [Parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "ComputerName")]
        [DbaInstanceParameter[]]
        $SqlInstance = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {

        foreach ($instance in $sqlinstance) {
            Write-Message -Level VeryVerbose -Message "Processing $instance." -Target $instance
            $null = Test-ElevationRequirement -ComputerName $instance -Continue

            Write-Message -Level Verbose -Message "Resolving hostname."
            $resolved = $null
            $resolved = Resolve-DbaNetworkName -ComputerName $instance -Turbo

            if ($null -eq $resolved) {
                Stop-Function -Message "Can't resolve $instance." -Target $instance -Continue -Category InvalidArgument
            }

            try {
                $sqlwmi = Invoke-ManagedComputerCommand -ComputerName $resolved.FullComputerName -ScriptBlock { $wmi.Services } -Credential $Credential -ErrorAction Stop | Where-Object DisplayName -eq "SQL Server ($($instance.InstanceName))"
            } catch {
                Stop-Function -Message "Failed to access $instance" -Target $instance -Continue -ErrorRecord $_
            }

            $regroot = ($sqlwmi.AdvancedProperties | Where-Object Name -eq REGROOT).Value
            $vsname = ($sqlwmi.AdvancedProperties | Where-Object Name -eq VSNAME).Value
            try {
                $instancename = $sqlwmi.DisplayName.Replace('SQL Server (', '').Replace(')', '') # Don't clown, I don't know regex :(
            } catch {
                # Probably because the instance name has been aliased or does not exist or something
                # here to avoid an empty catch
                $null = 1
            }
            $serviceaccount = $sqlwmi.ServiceAccount

            if ([System.String]::IsNullOrEmpty($regroot)) {
                $regroot = $sqlwmi.AdvancedProperties | Where-Object { $_ -match 'REGROOT' }
                $vsname = $sqlwmi.AdvancedProperties | Where-Object { $_ -match 'VSNAME' }

                if (![System.String]::IsNullOrEmpty($regroot)) {
                    $regroot = ($regroot -Split 'Value\=')[1]
                    $vsname = ($vsname -Split 'Value\=')[1]
                } else {
                    Stop-Function -Message "Can't find instance $vsname on $instance." -Continue -Category ObjectNotFound -Target $instance
                }
            }

            if ([System.String]::IsNullOrEmpty($vsname)) { $vsname = $instance }

            Write-Message -Level Output -Message "Regroot: $regroot" -Target $instance
            Write-Message -Level Output -Message "ServiceAcct: $serviceaccount" -Target $instance
            Write-Message -Level Output -Message "InstanceName: $instancename" -Target $instance
            Write-Message -Level Output -Message "VSNAME: $vsname" -Target $instance

            $scriptblock = {
                $regpath = "Registry::HKEY_LOCAL_MACHINE\$($args[0])\MSSQLServer\SuperSocketNetLib"
                $cert = (Get-ItemProperty -Path $regpath -Name Certificate).Certificate
                #Variable marked as unused by PSScriptAnalyzer
                #$oldvalue = (Get-ItemProperty -Path $regpath -Name ForceEncryption).ForceEncryption
                Set-ItemProperty -Path $regpath -Name ForceEncryption -Value $true
                $forceencryption = (Get-ItemProperty -Path $regpath -Name ForceEncryption).ForceEncryption

                [pscustomobject]@{
                    ComputerName          = $env:COMPUTERNAME
                    InstanceName          = $args[2]
                    SqlInstance           = $args[1]
                    ForceEncryption       = ($forceencryption -eq $true)
                    CertificateThumbprint = $cert
                }
            }

            if ($PScmdlet.ShouldProcess("local", "Connecting to $instance to modify the ForceEncryption value in $regroot for $($instance.InstanceName)")) {
                try {
                    Invoke-Command2 -ComputerName $resolved.FullComputerName -Credential $Credential -ArgumentList $regroot, $vsname, $instancename -ScriptBlock $scriptblock -ErrorAction Stop | Select-Object -Property * -ExcludeProperty PSComputerName, RunspaceId, PSShowComputerName
                    Write-Message -Level Critical -Message "Force encryption was successfully set on $($resolved.FullComputerName) for the $instancename instance. You must now restart the SQL Server for changes to take effect." -Target $instance
                } catch {
                    Stop-Function -Message "Failed to connect to $($resolved.FullComputerName) using PowerShell remoting!" -ErrorRecord $_ -Target $instance -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Enable-DbaTraceFlag.ps1
function Enable-DbaTraceFlag {
    <#
    .SYNOPSIS
        Enable Global Trace Flag(s)

    .DESCRIPTION
        The function will set one or multiple trace flags on the SQL Server instance(s) listed

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER TraceFlag
        Trace flag number(s) to enable globally

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: TraceFlag, DBCC
        Author: Garry Bargsley (@gbargsley), http://blog.garrybargsley.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Enable-DbaTraceFlag

    .EXAMPLE
        PS C:\> Enable-DbaTraceFlag -SqlInstance sql2016 -TraceFlag 3226

        Enable the trace flag 3226 on SQL Server instance sql2016

    .EXAMPLE
        PS C:\> Enable-DbaTraceFlag -SqlInstance sql2016 -TraceFlag 1117, 1118

        Enable multiple trace flags on SQL Server instance sql2016

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(Mandatory)]
        [int[]]$TraceFlag,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $CurrentRunningTraceFlags = Get-DbaTraceFlag -SqlInstance $server -EnableException

            # We could combine all trace flags but the granularity is worth it
            foreach ($tf in $TraceFlag) {
                $TraceFlagInfo = [PSCustomObject]@{
                    SourceServer = $server.ComputerName
                    InstanceName = $server.ServiceName
                    SqlInstance  = $server.DomainInstanceName
                    TraceFlag    = $tf
                    Status       = $null
                    Notes        = $null
                    DateTime     = [DbaDateTime](Get-Date)
                }
                if ($CurrentRunningTraceFlags.TraceFlag -contains $tf) {
                    $TraceFlagInfo.Status = 'Skipped'
                    $TraceFlagInfo.Notes = "The Trace flag is already running."
                    $TraceFlagInfo
                    Write-Message -Level Warning -Message "The Trace flag [$tf] is already running globally."
                    continue
                }

                try {
                    $query = "DBCC TRACEON ($tf, -1)"
                    $server.Query($query)
                    $server.Refresh()
                } catch {
                    $TraceFlagInfo.Status = "Failed"
                    $TraceFlagInfo.Notes = $_.Exception.Message
                    $TraceFlagInfo
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target $server -Continue
                }
                $TraceFlagInfo.Status = "Successful"
                $TraceFlagInfo
            }
        }
    }
}
tools\dbatools\functions\Expand-DbaDbLogFile.ps1
function Expand-DbaDbLogFile {
    <#
    .SYNOPSIS
        This command will help you to automatically grow your transaction log  file in a responsible way (preventing the generation of too many VLFs).

    .DESCRIPTION
        As you may already know, having a transaction log file with too many Virtual Log Files (VLFs) can hurt your database performance in many ways.

        Example:
        Too many VLFs can cause transaction log backups to slow down and can also slow down database recovery and, in extreme cases, even impact insert/update/delete performance.

        References:
        http://www.sqlskills.com/blogs/kimberly/transaction-log-vlfs-too-many-or-too-few/
        http://blogs.msdn.com/b/saponsqlserver/archive/2012/02/22/too-many-virtual-log-files-vlfs-can-cause-slow-database-recovery.aspx
        http://www.brentozar.com/blitz/high-virtual-log-file-vlf-count/

        In order to get rid of this fragmentation we need to grow the file taking the following into consideration:
        - How many VLFs are created when we perform a grow operation or when an auto-grow is invoked?

        Note: In SQL Server 2014 this algorithm has changed (http://www.sqlskills.com/blogs/paul/important-change-vlf-creation-algorithm-sql-server-2014/)

        Attention:
        We are growing in MB instead of GB because of known issue prior to SQL 2012:
        More detail here:
        http://www.sqlskills.com/BLOGS/PAUL/post/Bug-log-file-growth-broken-for-multiples-of-4GB.aspx
        and
        http://connect.microsoft.com/SqlInstance/feedback/details/481594/log-growth-not-working-properly-with-specific-growth-sizes-vlfs-also-not-created-appropriately
        or
        https://connect.microsoft.com/SqlInstance/feedback/details/357502/transaction-log-file-size-will-not-grow-exactly-4gb-when-filegrowth-4gb

        Understanding related problems:
        http://www.sqlskills.com/blogs/kimberly/transaction-log-vlfs-too-many-or-too-few/
        http://blogs.msdn.com/b/saponsqlserver/archive/2012/02/22/too-many-virtual-log-files-vlfs-can-cause-slow-database-recovery.aspx
        http://www.brentozar.com/blitz/high-virtual-log-file-vlf-count/

        Known bug before SQL Server 2012
        http://www.sqlskills.com/BLOGS/PAUL/post/Bug-log-file-growth-broken-for-multiples-of-4GB.aspx
        http://connect.microsoft.com/SqlInstance/feedback/details/481594/log-growth-not-working-properly-with-specific-growth-sizes-vlfs-also-not-created-appropriately
        https://connect.microsoft.com/SqlInstance/feedback/details/357502/transaction-log-file-size-will-not-grow-exactly-4gb-when-filegrowth-4gb

        How it works?
        The transaction log will grow in chunks until it reaches the desired size.
        Example: If you have a log file with 8192MB and you say that the target size is 81920MB (80GB) it will grow in chunks of 8192MB until it reaches 81920MB. 8192 -> 16384 -> 24576 ... 73728 -> 81920

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER Database
        The database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER TargetLogSize
        Specifies the target size of the transaction log file in megabytes.

    .PARAMETER IncrementSize
        Specifies the amount the transaction log should grow in megabytes. If this value differs from the suggested value based on your TargetLogSize, you will be prompted to confirm your choice.

        This value will be calculated if not specified.

    .PARAMETER LogFileId
        Specifies the file number(s) of additional transaction log files to grow.

        If this value is not specified, only the first transaction log file will be processed.

    .PARAMETER ShrinkLogFile
        If this switch is enabled, your transaction log files will be shrunk.

    .PARAMETER ShrinkSize
        Specifies the target size of the transaction log file for the shrink operation in megabytes.

    .PARAMETER BackupDirectory
        Specifies the location of your backups. Backups must be performed to shrink the transaction log.

        If this value is not specified, the SQL Server instance's default backup directory will be used.

    .PARAMETER ExcludeDiskSpaceValidation
        If this switch is enabled, the validation for enough disk space using Get-DbaDiskSpace command will be skipped.
        This can be useful when you know that you have enough space to grow your TLog but you don't have PowerShell Remoting enabled to validate it.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER ExcludeDatabase
        The database(s) to exclude. Options for this list are auto-populated from the server.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Storage, Backup
        Author: Claudio Silva (@ClaudioESSilva)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: ALTER DATABASE permission
        Limitations: Freespace cannot be validated on the directory where the log file resides in SQL Server 2005.
        This script uses Get-DbaDiskSpace dbatools command to get the TLog's drive free space

    .LINK
        https://dbatools.io/Expand-DbaDbLogFile

    .EXAMPLE
        PS C:\> Expand-DbaDbLogFile -SqlInstance sqlcluster -Database db1 -TargetLogSize 50000

        Grows the transaction log for database db1 on sqlcluster to 50000 MB and calculates the increment size.

    .EXAMPLE
        PS C:\> Expand-DbaDbLogFile -SqlInstance sqlcluster -Database db1, db2 -TargetLogSize 10000 -IncrementSize 200

        Grows the transaction logs for databases db1 and db2 on sqlcluster to 1000MB and sets the growth increment to 200MB.

    .EXAMPLE
        PS C:\> Expand-DbaDbLogFile -SqlInstance sqlcluster -Database db1 -TargetLogSize 10000 -LogFileId 9

        Grows the transaction log file  with FileId 9 of the db1 database on sqlcluster instance to 10000MB.

    .EXAMPLE
        PS C:\> Expand-DbaDbLogFile -SqlInstance sqlcluster -Database (Get-Content D:\DBs.txt) -TargetLogSize 50000

        Grows the transaction log of the databases specified in the file 'D:\DBs.txt' on sqlcluster instance to 50000MB.

    .EXAMPLE
        PS C:\> Expand-DbaDbLogFile -SqlInstance SqlInstance -Database db1,db2 -TargetLogSize 100 -IncrementSize 10 -ShrinkLogFile -ShrinkSize 10 -BackupDirectory R:\MSSQL\Backup

        Grows the transaction logs for databases db1 and db2 on SQL server SQLInstance to 100MB, sets the incremental growth to 10MB, shrinks the transaction log to 10MB and uses the directory R:\MSSQL\Backup for the required backups.

       #>
    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'Default')]
    param (
        [parameter(Position = 1, Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [parameter(Position = 3)]
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [parameter(Position = 4)]
        [object[]]$ExcludeDatabase,
        [parameter(Position = 5, Mandatory)]
        [Alias('TargetLogSizeMB')]
        [int]$TargetLogSize,
        [parameter(Position = 6)]
        [Alias('IncrementSizeMB')]
        [int]$IncrementSize = -1,
        [parameter(Position = 7)]
        [int]$LogFileId = -1,
        [parameter(Position = 8, ParameterSetName = 'Shrink', Mandatory)]
        [switch]$ShrinkLogFile,
        [parameter(Position = 9, ParameterSetName = 'Shrink', Mandatory)]
        [Alias('ShrinkSizeMB')]
        [int]$ShrinkSize,
        [parameter(Position = 10, ParameterSetName = 'Shrink')]
        [AllowEmptyString()]
        [string]$BackupDirectory,
        [switch]$ExcludeDiskSpaceValidation,
        [switch][Alias('Silent')]
        $EnableException
    )

    begin {
        Write-Message -Level Verbose -Message "Set ErrorActionPreference to Inquire."
        $ErrorActionPreference = 'Inquire'

        #Convert MB to KB (SMO works in KB)
        Write-Message -Level Verbose -Message "Convert variables MB to KB (SMO works in KB)."
        [int]$TargetLogSizeKB = $TargetLogSize * 1024
        [int]$LogIncrementSize = $IncrementSize * 1024
        [int]$ShrinkSizeKB = $ShrinkSize * 1024
        [int]$SuggestLogIncrementSize = 0
        [bool]$LogByFileID = if ($LogFileId -eq -1) {
            $false
        } else {
            $true
        }

        #Set base information
        Write-Message -Level Verbose -Message "Initialize the instance '$SqlInstance'."

        $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential

        if ($ShrinkLogFile -eq $true) {
            if ($BackupDirectory.length -eq 0) {
                $backupdirectory = $server.Settings.BackupDirectory
            }

            $pathexists = Test-DbaPath -SqlInstance $server -Path $backupdirectory

            if ($pathexists -eq $false) {
                Stop-Function -Message "Backup directory does not exist."
            }
        }
    }

    process {

        try {

            [datetime]$initialTime = Get-Date

            #control the iteration number
            $databaseProgressbar = 0;

            Write-Message -Level Verbose -Message "Resolving NetBIOS name."
            $sourcenetbios = Resolve-NetBiosName $server

            $databases = $server.Databases | Where-Object IsAccessible
            Write-Message -Level Verbose -Message "Number of databases found: $($databases.Count)."
            if ($Database) {
                $databases = $databases | Where-Object Name -In $Database
            }
            if ($ExcludeDatabase) {
                $databases = $databases | Where-Object Name -NotIn $ExcludeDatabase
            }

            #go through all databases
            Write-Message -Level Verbose -Message "Processing...foreach database..."
            foreach ($db in $databases.Name) {
                Write-Message -Level Verbose -Message "Working on $db."
                $databaseProgressbar += 1

                #set step to reutilize on logging operations
                [string]$step = "$databaseProgressbar/$($Databases.Count)"

                if ($server.Databases[$db]) {
                    Write-Progress `
                        -Id 1 `
                        -Activity "Using database: $db on Instance: '$SqlInstance'" `
                        -PercentComplete ($databaseProgressbar / $Databases.Count * 100) `
                        -Status "Processing - $databaseProgressbar of $($Databases.Count)"

                    #Validate which file will grow
                    if ($LogByFileID) {
                        $logfile = $server.Databases[$db].LogFiles.ItemById($LogFileId)
                    } else {
                        $logfile = $server.Databases[$db].LogFiles[0]
                    }

                    $numLogfiles = $server.Databases[$db].LogFiles.Count

                    Write-Message -Level Verbose -Message "$step - Use log file: $logfile."
                    $currentSize = $logfile.Size
                    $currentSizeMB = $currentSize / 1024

                    #Get the number of VLFs
                    $initialVLFCount = Test-DbaDbVirtualLogFile -SqlInstance $server -Database $db

                    Write-Message -Level Verbose -Message "$step - Log file current size: $([System.Math]::Round($($currentSize/1024.0), 2)) MB "
                    [long]$requiredSpace = ($TargetLogSizeKB - $currentSize)

                    if ($ExcludeDiskSpaceValidation -eq $false) {
                        Write-Message -Level Verbose -Message "Verifying if sufficient space exists ($([System.Math]::Round($($requiredSpace / 1024.0), 2))MB) on the volume to perform this task."

                        [long]$TotalTLogFreeDiskSpaceKB = 0
                        Write-Message -Level Verbose -Message "Get TLog drive free space"

                        try {
                            [object]$AllDrivesFreeDiskSpace = Get-DbaDiskSpace -ComputerName $sourcenetbios | Select-Object Name, SizeInKB

                            #Verify path using Split-Path on $logfile.FileName in backwards. This way we will catch the LUNs. Example: "K:\Log01" as LUN name. Need to add final backslash if not there
                            $DrivePath = Split-Path $logfile.FileName -parent
                            $DrivePath = if (!($DrivePath.EndsWith("\"))) { "$DrivePath\" }
                            else { $DrivePath }
                            Do {
                                if ($AllDrivesFreeDiskSpace | Where-Object { $DrivePath -eq "$($_.Name)" }) {
                                    $TotalTLogFreeDiskSpaceKB = ($AllDrivesFreeDiskSpace | Where-Object { $DrivePath -eq $_.Name }).SizeInKB
                                    $match = $true
                                    break
                                } else {
                                    $match = $false
                                    $DrivePath = Split-Path $DrivePath -parent
                                    $DrivePath = if (!($DrivePath.EndsWith("\"))) { "$DrivePath\" }
                                    else { $DrivePath }
                                }

                            }
                            while (!$match -or ([string]::IsNullOrEmpty($DrivePath)))

                            Write-Message -Level Verbose -Message "Total TLog Free Disk Space in MB: $([System.Math]::Round($($TotalTLogFreeDiskSpaceKB / 1024.0), 2))"

                        } catch {
                            #Could not validate the disk space. Will ask if we want to continue.
                            $TotalTLogFreeDiskSpaceKB = 0
                        }

                        if (($TotalTLogFreeDiskSpaceKB -le 0) -or ([string]::IsNullOrEmpty($TotalTLogFreeDiskSpaceKB))) {
                            $title = "Choose increment value for database '$db':"
                            $message = "Cannot validate freespace on drive where the log file resides. Do you wish to continue? (Y/N)"
                            $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Will continue"
                            $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Will exit"
                            $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
                            $result = $host.ui.PromptForChoice($title, $message, $options, 0)
                            #no
                            if ($result -eq 1) {
                                Write-Message -Level Warning -Message "You have cancelled the execution"
                                return
                            }
                        } elseif ($requiredSpace -gt $TotalTLogFreeDiskSpaceKB) {
                            Write-Message -Level Verbose -Message "There is not enough space on volume to perform this task. `r`n" `
                                "Available space: $([System.Math]::Round($($TotalTLogFreeDiskSpaceKB / 1024.0), 2))MB;`r`n" `
                                "Required space: $([System.Math]::Round($($requiredSpace / 1024.0), 2))MB;"
                            return
                        }
                    }

                    if ($currentSize -ige $TargetLogSizeKB -and ($ShrinkLogFile -eq $false)) {
                        Write-Message -Level Verbose -Message "$step - [INFO] The T-Log file '$logfile' size is already equal or greater than target size - No action required."
                    } else {
                        Write-Message -Level Verbose -Message "$step - [OK] There is sufficient free space to perform this task."

                        # If SQL Server version is greater or equal to 2012
                        if ($server.Version.Major -ge "11") {
                            switch ($TargetLogSize) {
                                { $_ -le 64 } { $SuggestLogIncrementSize = 64 }
                                { $_ -ge 64 -and $_ -lt 256 } { $SuggestLogIncrementSize = 256 }
                                { $_ -ge 256 -and $_ -lt 1024 } { $SuggestLogIncrementSize = 512 }
                                { $_ -ge 1024 -and $_ -lt 4096 } { $SuggestLogIncrementSize = 1024 }
                                { $_ -ge 4096 -and $_ -lt 8192 } { $SuggestLogIncrementSize = 2048 }
                                { $_ -ge 8192 -and $_ -lt 16384 } { $SuggestLogIncrementSize = 4096 }
                                { $_ -ge 16384 } { $SuggestLogIncrementSize = 8192 }
                            }
                        }
                        # 2008 R2 or under
                        else {
                            switch ($TargetLogSize) {
                                { $_ -le 64 } { $SuggestLogIncrementSize = 64 }
                                { $_ -ge 64 -and $_ -lt 256 } { $SuggestLogIncrementSize = 256 }
                                { $_ -ge 256 -and $_ -lt 1024 } { $SuggestLogIncrementSize = 512 }
                                { $_ -ge 1024 -and $_ -lt 4096 } { $SuggestLogIncrementSize = 1024 }
                                { $_ -ge 4096 -and $_ -lt 8192 } { $SuggestLogIncrementSize = 2048 }
                                { $_ -ge 8192 -and $_ -lt 16384 } { $SuggestLogIncrementSize = 4000 }
                                { $_ -ge 16384 } { $SuggestLogIncrementSize = 8000 }
                            }

                            if (($IncrementSize % 4096) -eq 0) {
                                Write-Message -Level Verbose -Message "Your instance version is below SQL 2012, remember the known BUG mentioned on HELP. `r`nUse Get-Help Expand-DbaTLogFileResponsibly to read help`r`nUse a different value for incremental size.`r`n"
                                return
                            }
                        }
                        Write-Message -Level Verbose -Message "Instance $server version: $($server.Version.Major) - Suggested TLog increment size: $($SuggestLogIncrementSize)MB"

                        # Shrink Log File to desired size before re-growth to desired size (You need to remove as many VLF's as possible to ensure proper growth)
                        $ShrinkSize = $ShrinkSizeKB / 1024
                        if ($ShrinkLogFile -eq $true) {
                            if ($server.Databases[$db].RecoveryModel -eq [Microsoft.SqlServer.Management.Smo.RecoveryModel]::Simple) {
                                Write-Message -Level Warning -Message "Database '$db' is in Simple RecoveryModel which does not allow log backups. Do not specify -ShrinkLogFile and -ShrinkSize parameters."
                                Continue
                            }

                            try {
                                $sql = "SELECT last_log_backup_lsn FROM sys.database_recovery_status WHERE database_id = DB_ID('$db')"
                                $sqlResult = $server.ConnectionContext.ExecuteWithResults($sql);

                                if ($sqlResult.Tables[0].Rows[0]["last_log_backup_lsn"] -is [System.DBNull]) {
                                    Write-Message -Level Warning -Message "First, you need to make a full backup before you can do Tlog backup on database '$db' (last_log_backup_lsn is null)."
                                    Continue
                                }
                            } catch {
                                Stop-Function -Message "Can't execute SQL on $server. `r`n $($_)" -Continue
                            }

                            If ($Pscmdlet.ShouldProcess($($server.name), "Backing up TLog for $db")) {
                                Write-Message -Level Verbose -Message "We are about to backup the Tlog for database '$db' to '$backupdirectory' and shrink the log."
                                Write-Message -Level Verbose -Message "Starting Size = $currentSizeMB."

                                $DefaultCompression = $server.Configuration.DefaultBackupCompression.ConfigValue

                                if ($currentSizeMB -gt $ShrinkSize) {
                                    $backupRetries = 1
                                    Do {
                                        try {
                                            $percent = $null
                                            $backup = New-Object Microsoft.SqlServer.Management.Smo.Backup
                                            $backup.Action = [Microsoft.SqlServer.Management.Smo.BackupActionType]::Log
                                            $backup.BackupSetDescription = "Transaction Log backup of " + $db
                                            $backup.BackupSetName = $db + " Backup"
                                            $backup.Database = $db
                                            $backup.MediaDescription = "Disk"
                                            $dt = get-date -format yyyyMMddHHmmssms
                                            $null = $backup.Devices.AddDevice($backupdirectory + "\" + $db + "_db_" + $dt + ".trn", 'File')
                                            if ($DefaultCompression -eq $true) {
                                                $backup.CompressionOption = 1
                                            } else {
                                                $backup.CompressionOption = 0
                                            }
                                            $null = [Microsoft.SqlServer.Management.Smo.PercentCompleteEventHandler] {
                                                Write-Progress -id 2 -ParentId 1 -activity "Backing up $db to $server" -percentcomplete $_.Percent -status ([System.String]::Format("Progress: {0} %", $_.Percent))
                                            }
                                            $backup.add_PercentComplete($percent)
                                            $backup.PercentCompleteNotification = 10
                                            $backup.add_Complete($complete)
                                            Write-Progress -id 2 -ParentId 1 -activity "Backing up $db to $server" -percentcomplete 0 -Status ([System.String]::Format("Progress: {0} %", 0))
                                            $backup.SqlBackup($server)
                                            Write-Progress -id 2 -ParentId 1 -activity "Backing up $db to $server" -status "Complete" -Completed
                                            $logfile.Shrink($ShrinkSize, [Microsoft.SqlServer.Management.SMO.ShrinkMethod]::TruncateOnly)
                                            $logfile.Refresh()
                                        } catch {
                                            Write-Progress -id 1 -activity "Backup" -status "Failed" -completed
                                            Stop-Function -Message "Backup failed for database" -ErrorRecord $_ -Target $db -Continue
                                            Continue
                                        }

                                    }
                                    while (($logfile.Size / 1024) -gt $ShrinkSize -and ++$backupRetries -lt 6)

                                    $currentSize = $logfile.Size
                                    Write-Message -Level Verbose -Message "TLog backup and truncate for database '$db' finished. Current TLog size after $backupRetries backups is $($currentSize/1024)MB"
                                }
                            }
                        }

                        # SMO uses values in KB
                        $SuggestLogIncrementSize = $SuggestLogIncrementSize * 1024

                        # If default, use $SuggestedLogIncrementSize
                        if ($IncrementSize -eq -1) {
                            $LogIncrementSize = $SuggestLogIncrementSize
                        } else {
                            $title = "Choose increment value for database '$db':"
                            $message = "The input value for increment size was $([System.Math]::Round($LogIncrementSize/1024, 0))MB. However the suggested value for increment is $($SuggestLogIncrementSize/1024)MB.`r`nDo you want to use the suggested value of $([System.Math]::Round($SuggestLogIncrementSize/1024, 0))MB insted of $([System.Math]::Round($LogIncrementSize/1024, 0))MB"
                            $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Uses recomended size."
                            $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Will use parameter value."
                            $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
                            $result = $host.ui.PromptForChoice($title, $message, $options, 0)
                            #yes
                            if ($result -eq 0) {
                                $LogIncrementSize = $SuggestLogIncrementSize
                            }
                        }

                        #start growing file
                        If ($Pscmdlet.ShouldProcess($($server.name), "Starting log growth. Increment chunk size: $($LogIncrementSize/1024)MB for database '$db'")) {
                            Write-Message -Level Verbose -Message "Starting log growth. Increment chunk size: $($LogIncrementSize/1024)MB for database '$db'"

                            Write-Message -Level Verbose -Message "$step - While current size less than target log size."

                            while ($currentSize -lt $TargetLogSizeKB) {

                                Write-Progress `
                                    -Id 2 `
                                    -ParentId 1 `
                                    -Activity "Growing file $logfile on '$db' database" `
                                    -PercentComplete ($currentSize / $TargetLogSizeKB * 100) `
                                    -Status "Remaining - $([System.Math]::Round($($($TargetLogSizeKB - $currentSize) / 1024.0), 2)) MB"

                                Write-Message -Level Verbose -Message "$step - Verifying if the log can grow or if it's already at the desired size."
                                if (($TargetLogSizeKB - $currentSize) -lt $LogIncrementSize) {
                                    Write-Message -Level Verbose -Message "$step - Log size is lower than the increment size. Setting current size equals $TargetLogSizeKB."
                                    $currentSize = $TargetLogSizeKB
                                } else {
                                    Write-Message -Level Verbose -Message "$step - Grow the $logfile file in $([System.Math]::Round($($LogIncrementSize / 1024.0), 2)) MB"
                                    $currentSize += $LogIncrementSize
                                }

                                #When -WhatIf Switch, do not run
                                if ($PSCmdlet.ShouldProcess("$step - File will grow to $([System.Math]::Round($($currentSize/1024.0), 2)) MB", "This action will grow the file $logfile on database $db to $([System.Math]::Round($($currentSize/1024.0), 2)) MB .`r`nDo you wish to continue?", "Perform grow")) {
                                    Write-Message -Level Verbose -Message "$step - Set size $logfile to $([System.Math]::Round($($currentSize/1024.0), 2)) MB"
                                    $logfile.size = $currentSize

                                    Write-Message -Level Verbose -Message "$step - Applying changes"
                                    $logfile.Alter()
                                    Write-Message -Level Verbose -Message "$step - Changes have been applied"

                                    #Will put the info like VolumeFreeSpace up to date
                                    $logfile.Refresh()
                                }
                            }

                            Write-Message -Level Verbose -Message "`r`n$step - [OK] Growth process for logfile '$logfile' on database '$db', has been finished."

                            Write-Message -Level Verbose -Message "$step - Grow $logfile log file on $db database finished."
                        }
                    }
                }
                #else verifying existence
                else {
                    Write-Message -Level Verbose -Message "Database '$db' does not exist on instance '$SqlInstance'."
                }

                #Get the number of VLFs
                $currentVLFCount = Test-DbaDbVirtualLogFile -SqlInstance $server -Database $db

                [pscustomobject]@{
                    ComputerName    = $server.ComputerName
                    InstanceName    = $server.ServiceName
                    SqlInstance     = $server.DomainInstanceName
                    Database        = $db
                    ID              = $logfile.ID
                    Name            = $logfile.Name
                    LogFileCount    = $numLogfiles
                    InitialSize     = [dbasize]($currentSizeMB * 1024 * 1024)
                    CurrentSize     = [dbasize]($TargetLogSize * 1024 * 1024)
                    InitialVLFCount = $initialVLFCount.Total
                    CurrentVLFCount = $currentVLFCount.Total
                } | Select-DefaultView -ExcludeProperty LogFileCount
            } #foreach database
        } catch {
            Stop-Function -Message "Logfile $logfile on database $db not processed. Error: $($_.Exception.Message). Line Number:  $($_InvocationInfo.ScriptLineNumber)" -Continue
        }
    }

    end {
        Write-Message -Level Verbose -Message "Process finished $((Get-Date) - ($initialTime))"
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Expand-SqlTLogResponsibly
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Parameter TargetLogSizeMB
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Parameter IncrementSizeMB
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Parameter ShrinkSizeMB
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Expand-DbaTLogResponsibly
    }
}
tools\dbatools\functions\Export-DbaAvailabilityGroup.ps1
#ValidationTags#Messaging#
function Export-DbaAvailabilityGroup {
    <#
    .SYNOPSIS
        Exports SQL Server Availability Groups to a T-SQL file.

    .DESCRIPTION
        Exports SQL Server Availability Groups creation scripts to a T-SQL file. This is a function that is not available in SSMS.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. SQL Server 2012 and above supported.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Path
        The directory name where the output files will be written. A sub directory with the format 'ServerName$InstanceName' will be created. A T-SQL scripts named 'AGName.sql' will be created under this subdirectory for each scripted Availability Group.

    .PARAMETER AvailabilityGroup
        The Availability Group(s) to export - this list is auto-populated from the server. If unspecified, all logins will be processed.

    .PARAMETER ExcludeAvailabilityGroup
        The Availability Group(s) to exclude - this list is auto-populated from the server.

    .PARAMETER NoClobber
        Do not overwrite existing export files.

    .PARAMETER WhatIf
        Shows you what it'd output if you were to run the command

    .PARAMETER Confirm
        Confirms each step/line of output

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Hadr, HA, AG, AvailabilityGroup
        Author: Chris Sommer (@cjsommer), cjsommer.com

        dbatools PowerShell module (https://dbatools.io)
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Export-DbaAvailabilityGroup

    .EXAMPLE
        PS C:\> Export-DbaAvailabilityGroup -SqlInstance sql2012

        Exports all Availability Groups from SQL server "sql2012". Output scripts are written to the Documents\SqlAgExports directory by default.

    .EXAMPLE
        PS C:\> Export-DbaAvailabilityGroup -SqlInstance sql2012 -Path C:\temp\availability_group_exports

        Exports all Availability Groups from SQL server "sql2012". Output scripts are written to the C:\temp\availability_group_exports directory.

    .EXAMPLE
        PS C:\> Export-DbaAvailabilityGroup -SqlInstance sql2012 -Path 'C:\dir with spaces\availability_group_exports' -AvailabilityGroup AG1,AG2

        Exports Availability Groups AG1 and AG2 from SQL server "sql2012". Output scripts are written to the C:\dir with spaces\availability_group_exports directory.

    .EXAMPLE
        PS C:\> Export-DbaAvailabilityGroup -SqlInstance sql2014 -Path C:\temp\availability_group_exports -NoClobber

        Exports all Availability Groups from SQL server "sql2014". Output scripts are written to the C:\temp\availability_group_exports directory. If the export file already exists it will not be overwritten.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$AvailabilityGroup,
        [object[]]$ExcludeAvailabilityGroup,
        [Alias("OutputLocation", "FilePath")]
        [string]$Path = "$([Environment]::GetFolderPath("MyDocuments"))\SqlAgExport",
        [switch]$NoClobber,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($server.IsHadrEnabled -eq $false) {
                Stop-Function -Message "Hadr is not enabled on this instance" -Continue
            } else {
                # Get all of the Availability Groups and filter if required
                $ags = $server.AvailabilityGroups
            }

            if (Test-Bound 'AvailabilityGroup') {
                $ags = $ags | Where-Object Name -In $AvailabilityGroup
            }
            if (Test-Bound 'ExcludeAvailabilityGroup') {
                $ags = $ags | Where-Object Name -NotIn $ExcludeAvailabilityGroup
            }

            if ($ags) {

                # Set and create the OutputLocation if it doesn't exist
                $sqlinst = $instance.ToString().Replace('\', '$')
                $outputLocation = "$Path\$sqlinst"

                if (!(Test-Path $outputLocation -PathType Container)) {
                    $null = New-Item -Path $outputLocation -ItemType Directory -Force
                }

                # Script each Availability Group
                foreach ($ag in $ags) {
                    $agName = $ag.Name

                    # Set the outfile name
                    if ($AppendDateToOutputFilename.IsPresent) {
                        $formatteddate = (Get-Date -Format 'yyyyMMdd_hhmm')
                        $outFile = "$outputLocation\${AGname}_${formatteddate}.sql"
                    } else {
                        $outFile = "$outputLocation\$agName.sql"
                    }

                    # Check NoClobber and script out the AG
                    if ($NoClobber.IsPresent -and (Test-Path -Path $outFile -PathType Leaf)) {
                        Write-Message -Level Warning -Message "OutputFile $outFile already exists. Skipping due to -NoClobber parameter"
                    } else {
                        Write-Message -Level Verbose -Message "Scripting Availability Group [$agName] on $instance to $outFile"

                        # Create comment block header for AG script
                        "/*" | Out-File -FilePath $outFile -Encoding ASCII -Force
                        " * Created by dbatools 'Export-DbaAvailabilityGroup' cmdlet on '$(Get-Date)'" | Out-File -FilePath $outFile -Encoding ASCII -Append
                        " * See https://dbatools.io/Export-DbaAvailabilityGroup for more help" | Out-File -FilePath $outFile -Encoding ASCII -Append

                        # Output AG and listener names
                        " *" | Out-File -FilePath $outFile -Encoding ASCII -Append
                        " * Availability Group Name: $($ag.name)" | Out-File -FilePath $outFile -Encoding ASCII -Append
                        $ag.AvailabilityGroupListeners | ForEach-Object { " * Listener Name: $($_.name)" } | Out-File -FilePath $outFile -Encoding ASCII -Append

                        # Output all replicas
                        " *" | Out-File -FilePath $outFile -Encoding ASCII -Append
                        $ag.AvailabilityReplicas | ForEach-Object { " * Replica: $($_.name)" } | Out-File -FilePath $outFile -Encoding ASCII -Append

                        # Output all databases
                        " *" | Out-File -FilePath $outFile -Encoding ASCII -Append
                        $ag.AvailabilityDatabases | ForEach-Object { " * Database: $($_.name)" } | Out-File -FilePath $outFile -Encoding ASCII -Append

                        # $ag | Select-Object -Property * | Out-File -FilePath $outFile -Encoding ASCII -Append

                        "*/" | Out-File -FilePath $outFile -Encoding ASCII -Append

                        # Script the AG
                        try {
                            $ag.Script() | Out-File -FilePath $outFile -Encoding ASCII -Append
                            Get-ChildItem $outFile
                        } catch {
                            Stop-Function -ErrorRecord $_ -Message "Error scripting out the availability groups. This is likely due to a bug in SMO." -Continue
                        }
                    }
                }
            } else {
                Write-Message -Level Output -Message "No Availability Groups detected on $instance"
            }
        }
    }
}
tools\dbatools\functions\Export-DbaCmsRegServer.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Export-DbaCmsRegServer {
    <#
    .SYNOPSIS
        Exports registered servers and registered server groups to file

    .DESCRIPTION
        Exports registered servers and registered server groups to file

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER CredentialPersistenceType
        Used to specify how the login and passwords are persisted. Valid values include None, PersistLoginName and PersistLoginNameAndPassword.

    .PARAMETER Path
        The path to the exported file. If no path is specified, one will be created.

    .PARAMETER InputObject
        Enables piping from Get-DbaCmsRegServer, Get-DbaCmsRegServerGroup, CSVs and other objects.

        If importing from CSV or other object, a column named ServerName is required. Optional columns include Name, Description and Group.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.

        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.

        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: RegisteredServer, CMS
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Export-DbaCmsRegServer

    .EXAMPLE
        PS C:\> Export-DbaCmsRegServer -SqlInstance sql2008

        Exports all Registered Server and Registered Server Groups on sql2008 to an automatically generated file name in the current directory

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sql2008, sql2012 | Export-DbaCmsRegServer

        Exports all registered servers on sql2008 and sql2012. Warning - each one will have its own individual file. Consider piping groups.

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServerGroup -SqlInstance sql2008, sql2012 | Export-DbaCmsRegServer

        Exports all registered servers on sql2008 and sql2012, organized by group.

    #>
    [CmdletBinding()]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "", Justification = "For Parameter CredentialPersistenceType")]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(ValueFromPipeline)]
        [object[]]$InputObject,
        [string]$Path,
        [ValidateSet("None", "PersistLoginName", "PersistLoginNameAndPassword")]
        [string]$CredentialPersistenceType = "None",
        [switch]$EnableException
    )
    begin {
        if ((Test-Bound -ParameterName Path)) {
            if ($Path -notmatch '\\') {
                $Path = ".\$Path"
            }

            $directory = Split-Path $Path
            if (-not (Test-Path $directory)) {
                New-Item -Path $directory -ItemType Directory
            }
        } else {
            $timeNow = (Get-Date -uformat "%m%d%Y%H%M%S")
        }
    }
    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaCmsRegServerGroup -SqlInstance $instance -SqlCredential $SqlCredential -Id 1
        }

        foreach ($object in $InputObject) {
            try {
                if ($object -is [Microsoft.SqlServer.Management.RegisteredServers.RegisteredServersStore]) {
                    $object = Get-DbaCmsRegServerGroup -SqlInstance $object.ServerConnection.SqlConnectionObject -Id 1
                }

                if ($object -is [Microsoft.SqlServer.Management.RegisteredServers.RegisteredServer]) {
                    if ((Test-Bound -ParameterName Path -Not)) {
                        $servername = $object.SqlInstance.Replace('\', '$')
                        $regservername = $object.Name.Replace('\', '$')
                        $Path = "$serverName-regserver-$regservername-$timeNow.xml"
                    }
                    $object.Export($Path, $CredentialPersistenceType)
                } elseif ($object -is [Microsoft.SqlServer.Management.RegisteredServers.ServerGroup]) {
                    if ((Test-Bound -ParameterName Path -Not)) {
                        $servername = $object.SqlInstance.Replace('\', '$')
                        $regservergroup = $object.Name.Replace('\', '$')
                        $Path = "$serverName-reggroup-$regservergroup-$timeNow.xml"
                    }
                    $object.Export($Path, $CredentialPersistenceType)
                } else {
                    Stop-Function -Message "InputObject is not a registered server or server group" -Continue
                }
                Get-ChildItem $Path -ErrorAction Stop
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_
            }
        }
    }

    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Export-DbaRegisteredServer
    }
}
tools\dbatools\functions\Export-DbaCredential.ps1
function Export-DbaCredential {
    <#
    .SYNOPSIS
        Exports credentials INCLUDING PASSWORDS, unless specified otherwise, to sql file.

    .DESCRIPTION
        Exports credentials INCLUDING PASSWORDS, unless specified otherwise, to sql file.

        Requires remote Windows access if exporting the password.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Credential
        Login to the target OS using alternative credentials. Accepts credential objects (Get-Credential)

    .PARAMETER Path
        The path to the exported sql file.

    .PARAMETER Identity
        The credentials to export. If unspecified, all credentials will be exported.

    .PARAMETER InputObject
        Allow credentials to be piped in from Get-DbaCredential

    .PARAMETER ExcludePassword
        Exports the SQL credential without any sensitive information.

    .PARAMETER InputObject
        Allow credentials to be piped in from Get-DbaCredential

    .PARAMETER Append
        Append to Path

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Credential
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Export-DbaCredential -SqlInstance sql2017 -Path C:\temp\cred.sql

        Exports credentials, including passwords, from sql2017 to the file C:\temp\cred.sql

    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [string[]]$Identity,
        [PSCredential]$SqlCredential,
        [PSCredential]$Credential,
        [string]$Path,
        [switch]$ExcludePassword,
        [switch]$Append,
        [Microsoft.SqlServer.Management.Smo.Credential[]]$InputObject,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential -MinimumVersion 9
                $InputObject += $server.Credentials
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($Identity) {
                $InputObject = $InputObject | Where-Object Identity -in $Identity
            }

            if (!(Test-SqlSa -SqlInstance $instance -SqlCredential $sqlcredential)) {
                Stop-Function -Message "Not a sysadmin on $instance. Quitting." -Target $instance -Continue
            }

            Write-Message -Level Verbose -Message "Getting NetBios name for $instance."
            $sourceNetBios = Resolve-NetBiosName $server

            Write-Message -Level Verbose -Message "Checking if Remote Registry is enabled on $instance."
            try {
                Invoke-Command2 -Raw -Credential $Credential -ComputerName $sourceNetBios -ScriptBlock { Get-ItemProperty -Path "HKLM:\SOFTWARE\" } -ErrorAction Stop
            } catch {
                Stop-Function -Message "Can't connect to registry on $instance." -Target $sourceNetBios -ErrorRecord $_
                return
            }

            if (-not (Test-Bound -ParameterName Path)) {
                $timenow = (Get-Date -uformat "%m%d%Y%H%M%S")
                $mydocs = [Environment]::GetFolderPath('MyDocuments')
                $path = "$mydocs\$($server.name.replace('\', '$'))-$timenow-credential.sql"
            }

            $sql = @()

            if ($ExcludePassword) {
                Stop-Function -Message "So sorry, there's no other way around it for now. The password has to be exported in plain text."
                return
            } else {
                try {
                    $creds = Get-DecryptedObject -SqlInstance $server -Type Credential
                } catch {
                    Stop-Function -Continue -Message "Failure" -ErrorRecord $_
                }
                foreach ($currentCred in $creds) {
                    $name = $currentCred.Name.Replace("'", "''")
                    $identity = $currentCred.Identity.Replace("'", "''")
                    $password = $currentCred.Password.Replace("'", "''")
                    $sql += "CREATE CREDENTIAL $name WITH IDENTITY = N'$identity', SECRET = N'$password'"
                }
            }

            try {
                if ($Append) {
                    Add-Content -Path $path -Value $sql
                } else {
                    Set-Content -Path $path -Value $sql
                }
                Get-ChildItem -Path $path
            } catch {
                Stop-Function -Message "Can't write to $path" -ErrorRecord $_ -Continue
            }


            Write-Message -Level Verbose -Message "Attempting to migrate $credentialName"
            Get-ChildItem -Path $path
        }
    }
}
tools\dbatools\functions\Export-DbaDacPackage.ps1
function Export-DbaDacPackage {
    <#
    .SYNOPSIS
        Exports a dacpac from a server.

    .DESCRIPTION
        Using SQLPackage, export a dacpac from an instance of SQL Server.

        Note - Extract from SQL Server is notoriously flaky - for example if you have three part references to external databases it will not work.

        For help with the extract action parameters and properties, refer to https://msdn.microsoft.com/en-us/library/hh550080(v=vs.103).aspx

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Allows you to login to servers using alternative logins instead Integrated, accepts Credential object created by Get-Credential

    .PARAMETER Path
        The directory where the .dacpac files will be exported to. Defaults to documents.

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER AllUserDatabases
        Run command against all user databases

    .PARAMETER Type
        Selecting the type of the export: Dacpac (default) or Bacpac.

    .PARAMETER Table
        List of the tables to include into the export. Should be provided as an array of strings: dbo.Table1, Table2, Schema1.Table3.

    .PARAMETER DacOption
        Export options for a corresponding export type. Can be created by New-DbaDacOption -Type Dacpac | Bacpac

    .PARAMETER ExtendedParameters
        Optional parameters used to extract the DACPAC. More information can be found at
        https://msdn.microsoft.com/en-us/library/hh550080.aspx

    .PARAMETER ExtendedProperties
        Optional properties used to extract the DACPAC. More information can be found at
        https://msdn.microsoft.com/en-us/library/hh550080.aspx

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration, Database, Dacpac
        Author: Richie lee (@richiebzzzt)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Export-DbaDacPackage

    .EXAMPLE
        PS C:\> Export-DbaDacPackage -SqlInstance sql2016 -Database SharePoint_Config

        Exports the dacpac for SharePoint_Config on sql2016 to $home\Documents\SharePoint_Config.dacpac

    .EXAMPLE
        PS C:\> $options = New-DbaDacOption -Type Dacpac -Action Export
        PS C:\> $options.ExtractAllTableData = $true
        PS C:\> $options.CommandTimeout = 0
        PS C:\> Export-DbaDacPackage -SqlInstance sql2016 -Database DB1 -Options $options

        Uses DacOption object to set the CommandTimeout to 0 then extracts the dacpac for DB1 on sql2016 to $home\Documents\DB1.dacpac including all table data.

    .EXAMPLE
        PS C:\> Export-DbaDacPackage -SqlInstance sql2016 -AllUserDatabases -ExcludeDatabase "DBMaintenance","DBMonitoring" C:\temp

        Exports dacpac packages for all USER databases, excluding "DBMaintenance" & "DBMonitoring", on sql2016 and saves them to C:\temp

    .EXAMPLE
        PS C:\> $moreparams = "/OverwriteFiles:$true /Quiet:$true"
        PS C:\> Export-DbaDacPackage -SqlInstance sql2016 -Database SharePoint_Config -Path C:\temp -ExtendedParameters $moreparams

        Using extended parameters to over-write the files and performs the extraction in quiet mode. Uses command line instead of SMO behind the scenes.
    #>
    [CmdletBinding(DefaultParameterSetName = 'SMO')]
    param
    (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$AllUserDatabases,
        [string]$Path = "$home\Documents",
        [parameter(ParameterSetName = 'SMO')]
        [Alias('ExtractOptions', 'ExportOptions', 'DacExtractOptions', 'DacExportOptions', 'Options', 'Option')]
        [object]$DacOption,
        [parameter(ParameterSetName = 'CMD')]
        [string]$ExtendedParameters,
        [parameter(ParameterSetName = 'CMD')]
        [string]$ExtendedProperties,
        [ValidateSet('Dacpac', 'Bacpac')]
        [string]$Type = 'Dacpac',
        [parameter(ParameterSetName = 'SMO')]
        [string[]]$Table,
        [switch]$EnableException
    )

    process {
        if ((Test-Bound -Not -ParameterName Database) -and (Test-Bound -Not -ParameterName ExcludeDatabase) -and (Test-Bound -Not -ParameterName AllUserDatabases)) {
            Stop-Function -Message "You must specify databases to execute against using either -Database, -ExcludeDatabase or -AllUserDatabases"
            return
        }

        if (-not (Test-Path $Path)) {
            Write-Message -Level Verbose "Assuming that $Path is a file path"
            $parentFolder = Split-Path $path -Parent
            if (-not (Test-Path $parentFolder)) {
                Stop-Function -Message "$parentFolder doesn't exist or access denied"
                return
            }
            $leaf = Split-Path $path -Leaf
            $fileName = Join-Path (Get-Item $parentFolder) $leaf
        } else {
            $fileItem = Get-Item $Path
            if ($fileItem -is [System.IO.DirectoryInfo]) {
                $parentFolder = $fileItem.FullName
            } elseif ($fileItem -is [System.IO.FileInfo]) {
                $fileName = $fileItem.FullName
            }
        }

        if (-not $script:core) {
            $dacfxPath = Resolve-Path -Path "$script:PSModuleRoot\bin\smo\Microsoft.SqlServer.Dac.dll"

            if ((Test-Path $dacfxPath) -eq $false) {
                Stop-Function -Message 'Dac Fx library not found.' -EnableException $EnableException
                return
            } else {
                try {
                    Add-Type -Path $dacfxPath
                    Write-Message -Level Verbose -Message "Dac Fx loaded."
                } catch {
                    Stop-Function -Message 'No usable version of Dac Fx found.' -ErrorRecord $_
                    return
                }
            }
        }

        #check that at least one of the DB selection parameters was specified
        if (!$AllUserDatabases -and !$Database) {
            Stop-Function -Message "Either -Database or -AllUserDatabases should be specified" -Continue
        }
        #Check Option object types - should have a specific type
        if ($Type -eq 'Dacpac') {
            if ($DacOption -and $DacOption -isnot [Microsoft.SqlServer.Dac.DacExtractOptions]) {
                Stop-Function -Message "Microsoft.SqlServer.Dac.DacExtractOptions object type is expected - got $($DacOption.GetType())."
                return
            }
        } elseif ($Type -eq 'Bacpac') {
            if ($DacOption -and $DacOption -isnot [Microsoft.SqlServer.Dac.DacExportOptions]) {
                Stop-Function -Message "Microsoft.SqlServer.Dac.DacExportOptions object type is expected - got $($DacOption.GetType())."
                return
            }
        }

        #Create a tuple to be used as a table filter
        if ($Table) {
            $tblList = New-Object 'System.Collections.Generic.List[Tuple[String, String]]'
            foreach ($tableItem in $Table) {
                $tableSplit = $tableItem.Split('.')
                if ($tableSplit.Count -gt 1) {
                    $tblName = $tableSplit[-1]
                    $schemaName = $tableSplit[-2]
                } else {
                    $tblName = [string]$tableSplit
                    $schemaName = 'dbo'
                }
                $tblList.Add((New-Object "tuple[String, String]" -ArgumentList $schemaName, $tblName))
            }
        } else {
            $tblList = $null
        }

        foreach ($instance in $sqlinstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            $cleaninstance = $instance.ToString().Replace('\', '-')
            if ($Database) {
                $dbs = Get-DbaDatabase -SqlInstance $server -OnlyAccessible -Database $Database -ExcludeDatabase $ExcludeDatabase
            } else {
                # all user databases by default
                $dbs = Get-DbaDatabase -SqlInstance $server -OnlyAccessible -ExcludeSystem -ExcludeDatabase $ExcludeDatabase
            }
            if (-not $dbs) {
                Stop-Function -Message "Databases not found on $instance" -Target $instance -Continue
            }

            foreach ($db in $dbs) {
                $resultstime = [diagnostics.stopwatch]::StartNew()
                $dbname = $db.name
                $connstring = $server.ConnectionContext.ConnectionString
                if ($connstring -notmatch 'Database=') {
                    $connstring = "$connstring;Database=$dbname"
                }
                if ($fileName) {
                    $currentFileName = $fileName
                } else {
                    if ($Type -eq 'Dacpac') { $ext = 'dacpac' }
                    elseif ($Type -eq 'Bacpac') { $ext = 'bacpac' }
                    $currentFileName = Join-Path $parentFolder "$cleaninstance-$dbname.$ext"
                }
                Write-Message -Level Verbose -Message "Using connection string $connstring"

                #using SMO by default
                if ($PsCmdlet.ParameterSetName -eq 'SMO') {
                    try {
                        $dacSvc = New-Object -TypeName Microsoft.SqlServer.Dac.DacServices -ArgumentList $connstring -ErrorAction Stop
                    } catch {
                        Stop-Function -Message "Could not connect to the connection string $connstring" -Target $instance -Continue
                    }
                    if (!$DacOption) {
                        $opts = New-DbaDacOption -Type $Type -Action Export
                    } else {
                        $opts = $DacOption
                    }

                    $null = $output = Register-ObjectEvent -InputObject $dacSvc -EventName "Message" -SourceIdentifier "msg" -Action { $EventArgs.Message.Message }

                    if ($Type -eq 'Dacpac') {
                        Write-Message -Level Verbose -Message "Initiating Dacpac extract to $currentFileName"
                        #not sure how to extract that info from the existing DAC application, leaving 1.0.0.0 for now
                        $version = New-Object System.Version -ArgumentList '1.0.0.0'
                        try {
                            $dacSvc.Extract($currentFileName, $dbname, $dbname, $version, $null, $tblList, $opts, $null)
                        } catch {
                            Stop-Function -Message "DacServices extraction failure" -ErrorRecord $_ -Continue
                        } finally {
                            Unregister-Event -SourceIdentifier "msg"
                        }
                    } elseif ($Type -eq 'Bacpac') {
                        Write-Message -Level Verbose -Message "Initiating Bacpac export to $currentFileName"
                        try {
                            $dacSvc.ExportBacpac($currentFileName, $dbname, $opts, $tblList, $null)
                        } catch {
                            Stop-Function -Message "DacServices export failure" -ErrorRecord $_ -Continue
                        } finally {
                            Unregister-Event -SourceIdentifier "msg"
                        }
                    }
                    $finalResult = ($output.output -join "`r`n" | Out-String).Trim()
                } elseif ($PsCmdlet.ParameterSetName -eq 'CMD') {
                    if ($Type -eq 'Dacpac') { $action = 'Extract' }
                    elseif ($Type -eq 'Bacpac') { $action = 'Export' }
                    $cmdConnString = $connstring.Replace('"', "'")

                    $sqlPackageArgs = "/action:$action /tf:""$currentFileName"" /SourceConnectionString:""$cmdConnString"" $ExtendedParameters $ExtendedProperties"

                    try {
                        $startprocess = New-Object System.Diagnostics.ProcessStartInfo
                        $startprocess.FileName = "$script:PSModuleRoot\bin\smo\sqlpackage.exe"
                        $startprocess.Arguments = $sqlPackageArgs
                        $startprocess.RedirectStandardError = $true
                        $startprocess.RedirectStandardOutput = $true
                        $startprocess.UseShellExecute = $false
                        $startprocess.CreateNoWindow = $true
                        $process = New-Object System.Diagnostics.Process
                        $process.StartInfo = $startprocess
                        $process.Start() | Out-Null
                        $stdout = $process.StandardOutput.ReadToEnd()
                        $stderr = $process.StandardError.ReadToEnd()
                        $process.WaitForExit()
                        Write-Message -level Verbose -Message "StandardOutput: $stdout"
                        $finalResult = $stdout
                    } catch {
                        Stop-Function -Message "SQLPackage Failure" -ErrorRecord $_ -Continue
                    }

                    if ($process.ExitCode -ne 0) {
                        Stop-Function -Message "Standard output - $stderr" -Continue
                    }
                }
                [pscustomobject]@{
                    ComputerName = $server.ComputerName
                    InstanceName = $server.ServiceName
                    SqlInstance  = $server.DomainInstanceName
                    Database     = $dbname
                    Path         = $currentFileName
                    Elapsed      = [prettytimespan]($resultstime.Elapsed)
                    Result       = $finalResult
                } | Select-DefaultView -ExcludeProperty ComputerName, InstanceName
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Export-DbaDacpac
    }
}
tools\dbatools\functions\Export-DbaDiagnosticQuery.ps1
function Export-DbaDiagnosticQuery {
    <#
    .SYNOPSIS
        Export-DbaDiagnosticQuery can convert output generated by Invoke-DbaDiagnosticQuery to CSV or Excel

    .DESCRIPTION
        The default output format of Invoke-DbaDiagnosticQuery is a custom object. It can also output to CSV and Excel.
        However, CSV output can generate a lot of files and Excel output depends on the ImportExcel module by Doug Finke (https://github.com/dfinke/ImportExcel)
        Export-DbaDiagnosticQuery can be used to convert from the default export type to the other available export types.

    .PARAMETER InputObject
        Specifies the objects to convert

    .PARAMETER ConvertTo
        Specifies the output type. Valid choices are Excel and CSV. CSV is the default.

    .PARAMETER Path
        Specifies the path to the output files.

    .PARAMETER Suffix
        Suffix for the filename. It's datetime by default.

    .PARAMETER NoPlanExport
        Use this switch to suppress exporting of .sqlplan files

    .PARAMETER NoQueryExport
        Use this switch to suppress exporting of .sql files

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Query
        Author: Andre Kamman (@AndreKamman), http://clouddba.io

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Export-DbaDiagnosticQuery

    .EXAMPLE
        PS C:\> Invoke-DbaDiagnosticQuery -SqlInstance sql2016 | Export-DbaDiagnosticQuery -Path c:\temp

        Converts output from Invoke-DbaDiagnosticQuery to multiple CSV files

    .EXAMPLE
        PS C:\> $output = Invoke-DbaDiagnosticQuery -SqlInstance sql2016
        PS C:\> Export-DbaDiagnosticQuery -InputObject $output -ConvertTo Excel

        Converts output from Invoke-DbaDiagnosticQuery to Excel worksheet(s) in the Documents folder

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [object[]]$InputObject,
        [ValidateSet("Excel", "Csv")]
        [string]$ConvertTo = "Csv",
        [System.IO.FileInfo]$Path = [Environment]::GetFolderPath("mydocuments"),
        [string]$Suffix = "$(Get-Date -format 'yyyyMMddHHmmssms')",
        [switch]$NoPlanExport,
        [switch]$NoQueryExport,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        if ($ConvertTo -eq "Excel") {
            try {
                Import-Module ImportExcel -ErrorAction Stop
            } catch {
                $message = "Failed to load module, exporting to Excel feature is not available
                            Install the module from: https://github.com/dfinke/ImportExcel
                            Valid alternative conversion format is csv"
                Stop-Function -Message $message
                return
            }
        }

        if (!$(Test-Path $Path)) {
            try {
                New-Item $Path -ItemType Directory -ErrorAction Stop | Out-Null
                Write-Message -Level Output -Message "Created directory $Path"
            } catch {
                Stop-Function -Message "Failed to create directory $Path" -Continue
            }
        }
    }

    process {
        if (Test-FunctionInterrupt) { return }

        foreach ($row in $InputObject) {
            $result = $row.Result
            $name = $row.Name
            $SqlInstance = $row.SqlInstance.Replace("\", "$")
            $dbname = $row.Database
            $number = $row.Number

            if ($null -eq $result) {
                Stop-Function -Message "Result was empty for $name" -Target $result -Continue
            }

            $queryname = Remove-InvalidFileNameChars -Name $Name
            $excelfilename = "$Path\$SqlInstance-DQ-$Suffix.xlsx"
            $exceldbfilename = "$Path\$SqlInstance-DQ-$dbname-$Suffix.xlsx"
            $csvdbfilename = "$Path\$SqlInstance-$dbname-DQ-$number-$queryname-$Suffix.csv"
            $csvfilename = "$Path\$SqlInstance-DQ-$number-$queryname-$Suffix.csv"

            $columnnameoptions = "Query Plan", "QueryPlan", "Query_Plan", "query_plan_xml"
            if (($result | Get-Member | Where-Object Name -in $columnnameoptions).Count -gt 0) {
                $plannr = 0
                $columnname = ($result | Get-Member | Where-Object Name -In $columnnameoptions).Name
                foreach ($plan in $result."$columnname") {
                    $plannr += 1
                    if ($row.DatabaseSpecific) {
                        $planfilename = "$Path\$SqlInstance-$dbname-DQ-$number-$queryname-$plannr-$Suffix.sqlplan"
                    } else {
                        $planfilename = "$Path\$SqlInstance-DQ-$number-$queryname-$plannr-$Suffix.sqlplan"
                    }

                    if (!$NoPlanExport) {
                        Write-Message -Level Output -Message "Exporting $planfilename"
                        if ($plan) {$plan | Out-File -FilePath $planfilename}
                    }
                }

                $result = $result | Select-Object * -ExcludeProperty "$columnname"
            }

            $columnnameoptions = "Complete Query Text", "QueryText", "Query Text", "Query_Text", "query_sql_text"
            if (($result | Get-Member | Where-Object Name -In $columnnameoptions ).Count -gt 0) {
                $sqlnr = 0
                $columnname = ($result | Get-Member | Where-Object Name -In $columnnameoptions).Name
                foreach ($sql in $result."$columnname") {
                    $sqlnr += 1
                    if ($row.DatabaseSpecific) {
                        $sqlfilename = "$Path\$SqlInstance-$dbname-DQ-$number-$queryname-$sqlnr-$Suffix.sql"
                    } else {
                        $sqlfilename = "$Path\$SqlInstance-DQ-$number-$queryname-$sqlnr-$Suffix.sql"
                    }

                    if (!$NoQueryExport) {
                        Write-Message -Level Output -Message "Exporting $sqlfilename"
                        if ($sql) {$sql | Out-File -FilePath $sqlfilename}
                    }
                }

                $result = $result | Select-Object * -ExcludeProperty "$columnname"
            }

            switch ($ConvertTo) {
                "Excel" {
                    if ($row.DatabaseSpecific) {
                        Write-Message -Level Output -Message "Exporting $exceldbfilename"
                        $result | Export-Excel -Path $exceldbfilename -WorkSheetname $Name -AutoSize -AutoFilter -BoldTopRow -FreezeTopRow
                    } else {
                        Write-Message -Level Output -Message "Exporting $excelfilename"
                        $result | Export-Excel -Path $excelfilename -WorkSheetname $Name -AutoSize -AutoFilter -BoldTopRow -FreezeTopRow
                    }
                }
                "csv" {
                    if ($row.DatabaseSpecific) {
                        Write-Message -Level Output -Message "Exporting $csvdbfilename"
                        $result | Export-Csv -Path $csvdbfilename -NoTypeInformation -Append
                    } else {
                        Write-Message -Level Output -Message "Exporting $csvfilename"
                        $result | Export-Csv -Path $csvfilename -NoTypeInformation -Append
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Export-DbaExecutionPlan.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Export-DbaExecutionPlan {
    <#
    .SYNOPSIS
        Exports execution plans to disk.

    .DESCRIPTION
        Exports execution plans to disk. Can pipe from Get-DbaExecutionPlan

        Thanks to
        https://www.simple-talk.com/sql/t-sql-programming/dmvs-for-query-plan-metadata/
        and
        http://www.scarydba.com/2017/02/13/export-plans-cache-sqlplan-file/
        for the idea and query.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Credential object used to connect to the SQL Server as a different user

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER SinceCreation
        Datetime object used to narrow the results to a date

    .PARAMETER SinceLastExecution
        Datetime object used to narrow the results to a date

    .PARAMETER Path
        The directory where all of the sqlxml files will be exported

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER PipedObject
        Internal parameter

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Performance, ExecutionPlan
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Export-DbaExecutionPlan

    .EXAMPLE
        PS C:\> Export-DbaExecutionPlan -SqlInstance sqlserver2014a -Path C:\Temp

        Exports all execution plans for sqlserver2014a. Files saved in to C:\Temp

    .EXAMPLE
        PS C:\> Export-DbaExecutionPlan -SqlInstance sqlserver2014a -Database db1, db2 -SinceLastExecution '2016-07-01 10:47:00' -Path C:\Temp

        Exports all execution plans for databases db1 and db2 on sqlserver2014a since July 1, 2016 at 10:47 AM. Files saved in to C:\Temp

    .EXAMPLE
        PS C:\> Get-DbaExecutionPlan -SqlInstance sqlserver2014a | Export-DbaExecutionPlan -Path C:\Temp

        Gets all execution plans for sqlserver2014a. Using Pipeline exports them all to C:\Temp

    .EXAMPLE
        PS C:\> Get-DbaExecutionPlan -SqlInstance sqlserver2014a | Export-DbaExecutionPlan -Path C:\Temp -WhatIf

        Gets all execution plans for sqlserver2014a. Then shows what would happen if the results where piped to Export-DbaExecutionPlan

    #>
    [cmdletbinding(SupportsShouldProcess, DefaultParameterSetName = "Default")]
    param (
        [parameter(ParameterSetName = 'NotPiped', Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [parameter(ParameterSetName = 'NotPiped')]
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [parameter(ParameterSetName = 'Piped', Mandatory)]
        [parameter(ParameterSetName = 'NotPiped', Mandatory)]
        [string]$Path,
        [parameter(ParameterSetName = 'NotPiped')]
        [datetime]$SinceCreation,
        [parameter(ParameterSetName = 'NotPiped')]
        [datetime]$SinceLastExecution,
        [Parameter(ParameterSetName = 'Piped', Mandatory, ValueFromPipeline)]
        [object[]]$PipedObject,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {

        function Export-Plan {
            param(
                [object]$object
            )
            $instanceName = $object.SqlInstance
            $dbName = $object.DatabaseName
            $queryPosition = $object.QueryPosition
            $sqlHandle = "0x"; $object.SqlHandle | ForEach-Object { $sqlHandle += ("{0:X}" -f $_).PadLeft(2, "0") }
            $sqlHandle = $sqlHandle.TrimStart('0x02000000').TrimEnd('0000000000000000000000000000000000000000')
            $shortName = "$instanceName-$dbName-$queryPosition-$sqlHandle"

            foreach ($queryPlan in $object.BatchQueryPlanRaw) {
                $fileName = "$path\$shortName-batch.sqlplan"

                try {
                    if ($Pscmdlet.ShouldProcess("localhost", "Writing XML file to $fileName")) {
                        $queryPlan.Save($fileName)
                    }
                } catch {
                    Stop-Function -Message "Skipped query plan for $fileName because it is null." -Target $fileName -ErrorRecord $_ -Continue
                }
            }

            foreach ($statementPlan in $object.SingleStatementPlanRaw) {
                $fileName = "$path\$shortName.sqlplan"

                try {
                    if ($Pscmdlet.ShouldProcess("localhost", "Writing XML file to $fileName")) {
                        $statementPlan.Save($fileName)
                    }
                } catch {
                    Stop-Function -Message "Skipped statement plan for $fileName because it is null." -Target $fileName -ErrorRecord $_ -Continue
                }
            }

            if ($Pscmdlet.ShouldProcess("console", "Showing output object")) {
                Add-Member -Force -InputObject $object -MemberType NoteProperty -Name OutputFile -Value $fileName
                Select-DefaultView -InputObject $object -Property ComputerName, InstanceName, SqlInstance, DatabaseName, SqlHandle, CreationTime, LastExecutionTime, OutputFile
            }
        }
    }

    process {
        if (!(Test-Path $Path)) {
            $null = New-Item -ItemType Directory -Path $Path
        }

        if ($PipedObject) {
            foreach ($object in $pipedobject) {
                Export-Plan $object
                return
            }
        }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $select = "SELECT DB_NAME(deqp.dbid) as DatabaseName, OBJECT_NAME(deqp.objectid) as ObjectName,
                    detqp.query_plan AS SingleStatementPlan,
                    deqp.query_plan AS BatchQueryPlan,
                    ROW_NUMBER() OVER ( ORDER BY Statement_Start_offset ) AS QueryPosition,
                    sql_handle as SqlHandle,
                    plan_handle as PlanHandle,
                    creation_time as CreationTime,
                    last_execution_time as LastExecutionTime"

            $from = " FROM sys.dm_exec_query_stats deqs
                        CROSS APPLY sys.dm_exec_text_query_plan(deqs.plan_handle,
                            deqs.statement_start_offset,
                            deqs.statement_end_offset) AS detqp
                        CROSS APPLY sys.dm_exec_query_plan(deqs.plan_handle) AS deqp
                        CROSS APPLY sys.dm_exec_sql_text(deqs.plan_handle) AS execText"

            if ($ExcludeDatabase -or $Database -or $SinceCreation -or $SinceLastExecution -or $ExcludeEmptyQueryPlan -eq $true) {
                $where = " WHERE "
            }

            $whereArray = @()

            if ($Database -gt 0) {
                $dbList = $Database -join "','"
                $whereArray += " DB_NAME(deqp.dbid) in ('$dbList') "
            }

            if (Test-Bound 'SinceCreation') {
                Write-Message -Level Verbose -Message "Adding creation time"
                $whereArray += " creation_time >= '" + $SinceCreation.ToString("yyyy-MM-dd HH:mm:ss") + "' "
            }

            if (Test-Bound 'SinceLastExecution') {
                Write-Message -Level Verbose -Message "Adding last execution time"
                $whereArray += " last_execution_time >= '" + $SinceLastExecution.ToString("yyyy-MM-dd HH:mm:ss") + "' "
            }

            if (Test-Bound 'ExcludeDatabase') {
                $dbList = $ExcludeDatabase -join "','"
                $whereArray += " DB_NAME(deqp.dbid) not in ('$dbList') "
            }

            if (Test-Bound 'ExcludeEmptyQueryPlan') {
                $whereArray += " detqp.query_plan is not null"
            }

            if ($where.Length -gt 0) {
                $whereArray = $whereArray -join " and "
                $where = "$where $whereArray"
            }

            $sql = "$select $from $where"
            Write-Message -Level Debug -Message "SQL Statement: $sql"
            try {
                $dataTable = $server.ConnectionContext.ExecuteWithResults($sql).Tables
            } catch {
                Stop-Function -Message "Issue collecting execution plans" -Target $instance -ErroRecord $_ -Continue
            }

            foreach ($row in ($dataTable.Rows)) {
                $sqlHandle = "0x"; $row.sqlhandle | ForEach-Object { $sqlHandle += ("{0:X}" -f $_).PadLeft(2, "0") }
                $planhandle = "0x"; $row.planhandle | ForEach-Object { $planhandle += ("{0:X}" -f $_).PadLeft(2, "0") }

                $object = [pscustomobject]@{
                    ComputerName           = $server.ComputerName
                    InstanceName           = $server.ServiceName
                    SqlInstance            = $server.DomainInstanceName
                    DatabaseName           = $row.DatabaseName
                    SqlHandle              = $sqlHandle
                    PlanHandle             = $planhandle
                    SingleStatementPlan    = $row.SingleStatementPlan
                    BatchQueryPlan         = $row.BatchQueryPlan
                    QueryPosition          = $row.QueryPosition
                    CreationTime           = $row.CreationTime
                    LastExecutionTime      = $row.LastExecutionTime
                    BatchQueryPlanRaw      = [xml]$row.BatchQueryPlan
                    SingleStatementPlanRaw = [xml]$row.SingleStatementPlan
                }
                Export-Plan $object
            }
        }
    }
}
tools\dbatools\functions\Export-DbaInstance.ps1
function Export-DbaInstance {
    <#
    .SYNOPSIS
        Exports SQL Server *ALL* database restore scripts, logins, database mail profiles/accounts, credentials, SQL Agent objects, linked servers,
        Central Management Server objects, server configuration settings (sp_configure), user objects in systems databases,
        system triggers and backup devices from one SQL Server to another.

        For more granular control, please use one of the -Exclude parameters and use the other functions available within the dbatools module.

    .DESCRIPTION
        Export-DbaInstance consolidates most of the export scripts in dbatools into one command.

        This is useful when you're looking to Export entire instances. It less flexible than using the underlying functions.
        Think of it as an easy button. Unless an -Exclude is specified, it exports:

        All database restore scripts.
        All logins.
        All database mail objects.
        All credentials.
        All objects within the Job Server (SQL Agent).
        All linked servers.
        All groups and servers within Central Management Server.
        All SQL Server configuration objects (everything in sp_configure).
        All user objects in system databases.
        All system triggers.
        All system backup devices.
        All Audits.
        All Endpoints.
        All Extended Events.
        All Policy Management objects.
        All Resource Governor objects.
        All Server Audit Specifications.
        All Custom Errors (User Defined Messages).
        All Server Roles.
        All Availability Groups.

    .PARAMETER SqlInstance
        The target SQL Server instances

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Credential
        Alternative Windows credentials for exporting Linked Servers and Credentials. Accepts credential objects (Get-Credential)

    .PARAMETER Path
        The path to the export file

    .PARAMETER SharedPath
        Specifies the network location for the backup files. The SQL Server service accounts on both Source and Destination must have read/write permission to access this location.

    .PARAMETER WithReplace
        If this switch is used, databases are restored from backup using WITH REPLACE. This is useful if you want to stage some complex file paths.

    .PARAMETER NoRecovery
        If this switch is used, databases will be left in the No Recovery state to enable further backups to be added.

    .PARAMETER IncludeDbMasterKey
        Exports the db master key then logs into the server to copy it to the $Path

    .PARAMETER Exclude
        Exclude one or more objects to export

        Databases
        Logins
        AgentServer
        Credentials
        LinkedServers
        SpConfigure
        CentralManagementServer
        DatabaseMail
        SysDbUserObjects
        SystemTriggers
        BackupDevices
        Audits
        Endpoints
        ExtendedEvents
        PolicyManagement
        ResourceGovernor
        ServerAuditSpecifications
        CustomErrors
        ServerRoles
        AvailabilityGroups
        ReplicationSettings

    .PARAMETER BatchSeparator
        Batch separator for scripting output. "GO" by default.

    .PARAMETER ScriptingOption
        Add scripting options to scripting output for all objects except Registered Servers and Extended Events.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Export
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Export-DbaInstance

    .EXAMPLE
        PS C:\> Export-DbaInstance -SqlInstance sqlserver\instance

        All databases, logins, job objects and sp_configure options will be exported from
        sqlserver\instance to an automatically generated folder name in Documents.

    .EXAMPLE
        PS C:\> Export-DbaInstance -SqlInstance sqlcluster -Exclude Databases, Logins -Path C:\dr\sqlcluster

        Exports everything but logins and database restore scripts to C:\dr\sqlcluster

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [PSCredential]$Credential,
        [string]$Path,
        [switch]$NoRecovery,
        [switch]$IncludeDbMasterKey,
        [ValidateSet('Databases', 'Logins', 'AgentServer', 'Credentials', 'LinkedServers', 'SpConfigure', 'CentralManagementServer', 'DatabaseMail', 'SysDbUserObjects', 'SystemTriggers', 'BackupDevices', 'Audits', 'Endpoints', 'ExtendedEvents', 'PolicyManagement', 'ResourceGovernor', 'ServerAuditSpecifications', 'CustomErrors', 'ServerRoles', 'AvailabilityGroups', 'ReplicationSettings')]
        [string[]]$Exclude,
        [string]$BatchSeparator = 'GO',
        [Microsoft.SqlServer.Management.Smo.ScriptingOptions]$ScriptingOption,
        [switch]$EnableException
    )
    begin {
        if ((Test-Bound -ParameterName Path)) {
            if (-not ((Get-Item $Path -ErrorAction Ignore) -is [System.IO.DirectoryInfo])) {
                Stop-Function -Message "Path must be a directory"
            }
        }

        if (-not $ScriptingOption) {
            $ScriptingOption = New-DbaScriptingOption
        }

        $elapsed = [System.Diagnostics.Stopwatch]::StartNew()
        $started = Get-Date

        $ScriptingOptions = New-Object Microsoft.SqlServer.Management.Smo.ScriptingOptions
        $ScriptingOptions.ScriptBatchTerminator = $true

    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($instance in $SqlInstance) {
            $stepCounter = $filecounter = 0
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if (-not (Test-Bound -ParameterName Path)) {
                $timenow = (Get-Date -uformat "%m%d%Y%H%M%S")
                $mydocs = [Environment]::GetFolderPath('MyDocuments')
                $path = "$mydocs\$($server.name.replace('\', '$'))-$timenow"
            }

            if (-not (Test-Path $Path)) {
                try {
                    $null = New-Item -ItemType Directory -Path $Path -ErrorAction Stop
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_
                    return
                }
            }

            if ($Exclude -notcontains 'SpConfigure') {
                $fileCounter++
                Write-Message -Level Verbose -Message "Exporting SQL Server Configuration"
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting SQL Server Configuration"
                Export-DbaSpConfigure -SqlInstance $server -Path "$Path\$fileCounter-sp_configure.sql"
                if (-not (Test-Path "$Path\$fileCounter-sp_configure.sql")) {
                    $fileCounter--
                }
            }

            if ($Exclude -notcontains 'CustomErrors') {
                $fileCounter++
                Write-Message -Level Verbose -Message "Exporting custom errors (user defined messages)"
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting custom errors (user defined messages)"
                $null = Get-DbaCustomError -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-customererrors.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                Get-ChildItem -ErrorAction Ignore -Path "$Path\$fileCounter-customererrors.sql"
                if (-not (Test-Path "$Path\$fileCounter-customererrors.sql")) {
                    $fileCounter--
                }
            }

            if ($Exclude -notcontains 'ServerRoles') {
                $fileCounter++
                Write-Message -Level Verbose -Message "Exporting server roles"
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting server roles"
                $null = Get-DbaServerRole -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-serverroles.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                Get-ChildItem -ErrorAction Ignore -Path "$Path\$fileCounter-serverroles.sql"
                if (-not (Test-Path "$Path\$fileCounter-serverroles.sql")) {
                    $fileCounter--
                }
            }

            if ($Exclude -notcontains 'Credentials') {
                $fileCounter++
                Write-Message -Level Verbose -Message "Exporting SQL credentials"
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting SQL credentials"
                $null = Export-DbaCredential -SqlInstance $server -Credential $Credential -Path "$Path\$fileCounter-credentials.sql" -Append
                Get-ChildItem -ErrorAction Ignore -Path "$Path\$fileCounter-credentials.sql"
                if (-not (Test-Path "$Path\$fileCounter-credentials.sql")) {
                    $fileCounter--
                }
            }

            if ($Exclude -notcontains 'DatabaseMail') {
                $fileCounter++
                Write-Message -Level Verbose -Message "Exporting database mail"
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting database mail"
                $null = Get-DbaDbMailConfig -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-dbmail.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                $null = Get-DbaDbMailAccount -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-dbmail.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                $null = Get-DbaDbMailProfile -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-dbmail.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                $null = Get-DbaDbMailServer -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-dbmail.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                $null = Get-DbaDbMail -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-dbmail.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                Get-ChildItem -ErrorAction Ignore -Path "$Path\$fileCounter-dbmail.sql"
                if (-not (Test-Path "$Path\$fileCounter-dbmail.sql")) {
                    $fileCounter--
                }
            }

            if ($Exclude -notcontains 'CentralManagementServer') {
                $fileCounter++
                Write-Message -Level Verbose -Message "Exporting Central Management Server"
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting Central Management Server"
                $null = Get-DbaCmsRegServerGroup -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-regserver.sql" -Append -BatchSeparator 'GO'
                $null = Get-DbaCmsRegServer -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-regserver.sql" -Append -BatchSeparator 'GO'
                Get-ChildItem -ErrorAction Ignore -Path "$Path\$fileCounter-regserver.sql"
                if (-not (Test-Path "$Path\$fileCounter-regserver.sql")) {
                    $fileCounter--
                }
            }

            if ($Exclude -notcontains 'BackupDevices') {
                $fileCounter++
                Write-Message -Level Verbose -Message "Exporting Backup Devices"
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting Backup Devices"
                $null = Get-DbaBackupDevice -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-backupdevices.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                Get-ChildItem -ErrorAction Ignore -Path "$Path\$fileCounter-backupdevices.sql"
                if (-not (Test-Path "$Path\$fileCounter-backupdevices.sql")) {
                    $fileCounter--
                }
            }

            if ($Exclude -notcontains 'LinkedServers') {
                $fileCounter++
                Write-Message -Level Verbose -Message "Exporting linked servers"
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting linked servers"
                Export-DbaLinkedServer -SqlInstance $server -Path "$Path\$fileCounter-linkedservers.sql" -Credential $Credential -Append
                if (-not (Test-Path "$Path\$fileCounter-linkedservers.sql")) {
                    $fileCounter--
                }
            }

            if ($Exclude -notcontains 'SystemTriggers') {
                $fileCounter++
                Write-Message -Level Verbose -Message "Exporting System Triggers"
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting System Triggers"
                $null = Get-DbaServerTrigger -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-servertriggers.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                $triggers = Get-Content -Path "$Path\$fileCounter-servertriggers.sql" -Raw -ErrorAction Ignore
                if ($triggers) {
                    $triggers = $triggers.ToString() -replace 'CREATE TRIGGER', "GO`r`nCREATE TRIGGER"
                    $triggers = $triggers.ToString() -replace 'ENABLE TRIGGER', "GO`r`nENABLE TRIGGER"
                    $null = $triggers | Set-Content -Path "$Path\$fileCounter-servertriggers.sql" -Force
                    Get-ChildItem -ErrorAction Ignore -Path "$Path\$fileCounter-servertriggers.sql"
                }
                if (-not (Test-Path "$Path\$fileCounter-servertriggers.sql")) {
                    $fileCounter--
                }
            }

            if ($Exclude -notcontains 'Databases') {
                $fileCounter++
                Write-Message -Level Verbose -Message "Exporting database restores"
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting database restores"
                Get-DbaBackupHistory -SqlInstance $server -Last | Restore-DbaDatabase -SqlInstance $server -NoRecovery:$NoRecovery -WithReplace -OutputScriptOnly -WarningAction SilentlyContinue | Out-File -FilePath "$Path\$fileCounter-databases.sql" -Append
                Get-ChildItem -ErrorAction Ignore -Path "$Path\$fileCounter-databases.sql"
                if (-not (Test-Path "$Path\$fileCounter-databases.sql")) {
                    $fileCounter--
                }
            }

            if ($Exclude -notcontains 'Logins') {
                $fileCounter++
                Write-Message -Level Verbose -Message "Exporting logins"
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting logins"
                Export-DbaLogin -SqlInstance $server -Path "$Path\$fileCounter-logins.sql" -Append -WarningAction SilentlyContinue
                if (-not (Test-Path "$Path\$fileCounter-logins.sql")) {
                    $fileCounter--
                }
            }

            if ($Exclude -notcontains 'Audits') {
                $fileCounter++
                Write-Message -Level Verbose -Message "Exporting Audits"
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting Audits"
                $null = Get-DbaServerAudit -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-audits.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                Get-ChildItem -ErrorAction Ignore -Path "$Path\$fileCounter-audits.sql"
                if (-not (Test-Path "$Path\$fileCounter-audits.sql")) {
                    $fileCounter--
                }
            }

            if ($Exclude -notcontains 'ServerAuditSpecifications') {
                $fileCounter++
                Write-Message -Level Verbose -Message "Exporting Server Audit Specifications"
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting Server Audit Specifications"
                $null = Get-DbaServerAuditSpecification -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-auditspecs.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                Get-ChildItem -ErrorAction Ignore -Path "$Path\$fileCounter-auditspecs.sql"
                if (-not (Test-Path "$Path\$fileCounter-auditspecs.sql")) {
                    $fileCounter--
                }
            }

            if ($Exclude -notcontains 'Endpoints') {
                $fileCounter++
                Write-Message -Level Verbose -Message "Exporting Endpoints"
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting Endpoints"
                $null = Get-DbaEndpoint -SqlInstance $server | Where-Object IsSystemObject -eq $false | Export-DbaScript -Path "$Path\$fileCounter-endpoints.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                Get-ChildItem -ErrorAction Ignore -Path "$Path\$fileCounter-endpoints.sql"
                if (-not (Test-Path "$Path\$fileCounter-endpoints.sql")) {
                    $fileCounter--
                }
            }

            if ($Exclude -notcontains 'PolicyManagement') {
                $fileCounter++
                Write-Message -Level Verbose -Message "Exporting Policy Management"
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting Policy Management"
                $null = Get-DbaPbmCondition -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-policymanagement.sql" -Append -BatchSeparator $BatchSeparator
                $null = Get-DbaPbmObjectSet -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-policymanagement.sql" -Append -BatchSeparator $BatchSeparator
                $null = Get-DbaPbmPolicy -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-policymanagement.sql" -Append -BatchSeparator $BatchSeparator
                Get-ChildItem -ErrorAction Ignore -Path "$Path\$fileCounter-policymanagement.sql"
                if (-not (Test-Path "$Path\$fileCounter-policymanagement.sql")) {
                    $fileCounter--
                }
            }

            if ($Exclude -notcontains 'ResourceGovernor') {
                $fileCounter++
                Write-Message -Level Verbose -Message "Exporting Resource Governor"
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting Resource Governor"
                $null = Get-DbaResourceGovernor -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-resourcegov.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                $null = Get-DbaRgClassifierFunction -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-resourcegov.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                $null = Get-DbaRgResourcePool -SqlInstance $server | Where-Object Name -notin 'default', 'internal' | Export-DbaScript -Path "$Path\$fileCounter-resourcegov.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                $null = Get-DbaRgWorkloadGroup -SqlInstance $server | Where-Object Name -notin 'default', 'internal' | Export-DbaScript -Path "$Path\$fileCounter-resourcegov.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                $null = Add-Content -Value "ALTER RESOURCE GOVERNOR RECONFIGURE" -Path "$Path\$stepCounter-resourcegov.sql"
                Get-ChildItem -ErrorAction Ignore -Path "$Path\$fileCounter-resourcegov.sql"
                if (-not (Test-Path "$Path\$fileCounter-resourcegov.sql")) {
                    $fileCounter--
                }
            }

            if ($Exclude -notcontains 'ExtendedEvents') {
                $fileCounter++
                Write-Message -Level Verbose -Message "Exporting Extended Events"
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting Extended Events"
                $null = Get-DbaXESession -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-extendedevents.sql" -Append -BatchSeparator 'GO'
                Get-ChildItem -ErrorAction Ignore -Path "$Path\$fileCounter-extendedevents.sql"
                if (-not (Test-Path "$Path\$fileCounter-extendedevents.sql")) {
                    $fileCounter--
                }
            }

            if ($Exclude -notcontains 'AgentServer') {
                $fileCounter++
                Write-Message -Level Verbose -Message "Exporting job server"

                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting job server"
                $null = Get-DbaAgentJobCategory -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-sqlagent.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                $null = Get-DbaAgentOperator -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-sqlagent.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                $null = Get-DbaAgentAlert -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-sqlagent.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                $null = Get-DbaAgentProxy -SqlInstance $server | Export-DbaScript  -Path "$Path\$fileCounter-sqlagent.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                $null = Get-DbaAgentSchedule -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-sqlagent.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                $null = Get-DbaAgentJob -SqlInstance $server | Export-DbaScript -Path "$Path\$fileCounter-sqlagent.sql" -Append -BatchSeparator $BatchSeparator -ScriptingOptionsObject $ScriptingOption
                Get-ChildItem -ErrorAction Ignore -Path "$Path\$fileCounter-sqlagent.sql"
                if (-not (Test-Path "$Path\$fileCounter-sqlagent.sql")) {
                    $fileCounter--
                }
            }

            if ($Exclude -notcontains 'ReplicationSettings') {
                $fileCounter++
                Write-Message -Level Verbose -Message "Exporting replication settings"
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting replication settings"
                $null = Export-DbaRepServerSetting -SqlInstance $instance -SqlCredential $SqlCredential -Path "$Path\$fileCounter-replication.sql"
                Get-ChildItem -ErrorAction Ignore -Path "$Path\$fileCounter-replication.sql"
                if (-not (Test-Path "$Path\$fileCounter-replication.sql")) {
                    $fileCounter--
                }
            }

            if ($Exclude -notcontains 'SysDbUserObjects') {
                $fileCounter++
                Write-Message -Level Verbose -Message "Exporting user objects in system databases (this can take a minute)."
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting user objects in system databases (this can take a minute)."
                $null = Get-DbaSysDbUserObjectScript -SqlInstance $server | Out-File -FilePath "$Path\$fileCounter-userobjectsinsysdbs.sql" -Append
                Get-ChildItem -ErrorAction Ignore -Path "$Path\$fileCounter-userobjectsinsysdbs.sql"
                if (-not (Test-Path "$Path\$fileCounter-userobjectsinsysdbs.sql")) {
                    $fileCounter--
                }
            }

            if ($Exclude -notcontains 'AvailabilityGroups') {
                $fileCounter++
                Write-Message -Level Verbose -Message "Exporting availability group"
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting availability groups"
                $null = Get-DbaAvailabilityGroup -SqlInstance $server -WarningAction SilentlyContinue | Export-DbaScript -Path "$Path\$fileCounter-DbaAvailabilityGroups.sql" -Append -BatchSeparator $BatchSeparator #-ScriptingOptionsObject $ScriptingOption
                Get-ChildItem -ErrorAction Ignore -Path "$Path\$fileCounter-DbaAvailabilityGroups.sql"
                if (-not (Test-Path "$Path\$fileCounter-DbaAvailabilityGroups.sql")) {
                    $fileCounter--
                }
            }

            Write-Progress -Activity "Performing Instance Export for $instance" -Completed
        }
    }
    end {
        $totaltime = ($elapsed.Elapsed.toString().Split(".")[0])
        Write-Message -Level Verbose -Message "SQL Server export complete."
        Write-Message -Level Verbose -Message "Export started: $started"
        Write-Message -Level Verbose -Message "Export completed: $(Get-Date)"
        Write-Message -Level Verbose -Message "Total Elapsed time: $totaltime"
    }
}
tools\dbatools\functions\Export-DbaLinkedServer.ps1
function Export-DbaLinkedServer {
    <#
    .SYNOPSIS
        Exports linked servers INCLUDING PASSWORDS, unless specified otherwise, to sql file.

    .DESCRIPTION
        Exports linked servers INCLUDING PASSWORDS, unless specified otherwise, to sql file.

        Requires remote Windows access if exporting the password.

    .PARAMETER SqlInstance
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2005 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative linked servers. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Credential
        Login to the target OS using alternative linked servers. Accepts credential objects (Get-Credential)

    .PARAMETER Path
        The path to the exported sql file.

    .PARAMETER LinkedServer
        The linked server(s) to export. If unspecified, all linked servers will be processed.

    .PARAMETER InputObject
        Allow credentials to be piped in from Get-DbaLinkedServer

    .PARAMETER ExcludePassword
        Exports the linked server without any sensitive information.

    .PARAMETER Append
        Append to Path

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: LinkedServer
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Export-DbaLinkedServer -SqlInstance sql2017 -Path C:\temp\ls.sql

        Exports the linked servers, including passwords, from sql2017 to the file C:\temp\ls.sql

    .EXAMPLE
        PS C:\> Export-DbaLinkedServer -SqlInstance sql2017 -Path C:\temp\ls.sql -ExcludePassword

        Exports the linked servers, without passwords, from sql2017 to the file C:\temp\ls.sql

    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [string[]]$LinkedServer,
        [PSCredential]$SqlCredential,
        [PSCredential]$Credential,
        [string]$Path,
        [switch]$ExcludePassword,
        [switch]$Append,
        [Microsoft.SqlServer.Management.Smo.LinkedServer[]]$InputObject,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential -MinimumVersion 9
                $InputObject += $server.LinkedServers
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($LinkedServer) {
                $InputObject = $InputObject | Where-Object Name -in $LinkedServer
            }

            if (-not $InputObject) {
                Write-Message -Level Verbose -Message "Nothing to export"
                continue
            }

            if (!(Test-SqlSa -SqlInstance $instance -SqlCredential $sqlcredential)) {
                Stop-Function -Message "Not a sysadmin on $instance. Quitting." -Target $instance -Continue
            }

            Write-Message -Level Verbose -Message "Getting NetBios name for $instance."
            $sourceNetBios = Resolve-NetBiosName $server

            Write-Message -Level Verbose -Message "Checking if Remote Registry is enabled on $instance."
            try {
                Invoke-Command2 -Raw -Credential $Credential -ComputerName $sourceNetBios -ScriptBlock { Get-ItemProperty -Path "HKLM:\SOFTWARE\" } -ErrorAction Stop
            } catch {
                Stop-Function -Message "Can't connect to registry on $instance." -Target $sourceNetBios -ErrorRecord $_
                return
            }

            if (-not (Test-Bound -ParameterName Path)) {
                $timenow = (Get-Date -uformat "%m%d%Y%H%M%S")
                $mydocs = [Environment]::GetFolderPath('MyDocuments')
                $path = "$mydocs\$($server.name.replace('\', '$'))-$timenow-linkedserver.sql"
            }

            $sql = @()

            if ($ExcludePassword) {
                $sql += $InputObject.Script()
            } else {
                try {
                    $decrypted = Get-DecryptedObject -SqlInstance $server -Type LinkedServer
                } catch {
                    Stop-Function -Continue -Message "Failure" -ErrorRecord $_
                }

                foreach ($ls in $InputObject) {
                    $currentls = $decrypted | Where-Object Name -eq $ls.Name

                    if ($currentls.Password) {
                        $password = $currentls.Password.Replace("'", "''")

                        $tempsql = $ls.Script()
                        $tempsql = $tempsql.Replace(' /* For security reasons the linked server remote logins password is changed with ######## */', '')
                        $tempsql = $tempsql.Replace("rmtpassword='########'", "rmtpassword='$password'")
                        $sql += $tempsql
                    } else {
                        $sql += $ls.Script()
                    }
                }
            }

            try {
                if ($Append) {
                    Add-Content -Path $path -Value $sql
                } else {
                    Set-Content -Path $path -Value $sql
                }
                Get-ChildItem -Path $path
            } catch {
                Stop-Function -Message "Can't write to $path" -ErrorRecord $_ -Continue
            }
        }
    }
}
tools\dbatools\functions\Export-DbaLogin.ps1
function Export-DbaLogin {
    <#
    .SYNOPSIS
        Exports Windows and SQL Logins to a T-SQL file. Export includes login, SID, password, default database, default language, server permissions, server roles, db permissions, db roles.

    .DESCRIPTION
        Exports Windows and SQL Logins to a T-SQL file. Export includes login, SID, password, default database, default language, server permissions, server roles, db permissions, db roles.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. SQL Server 2000 and above supported.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Login
        The login(s) to process. Options for this list are auto-populated from the server. If unspecified, all logins will be processed.

    .PARAMETER ExcludeLogin
        The login(s) to exclude. Options for this list are auto-populated from the server.

    .PARAMETER Database
        The database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER Path
        The file to write to.

    .PARAMETER NoClobber
        If this switch is enabled, a file already existing at the path specified by Path will not be overwritten.

    .PARAMETER Append
        If this switch is enabled, content will be appended to a file already existing at the path specified by Path. If the file does not exist, it will be created.

    .PARAMETER ExcludeJobs
        If this switch is enabled, Agent job ownership will not be exported.

    .PARAMETER ExcludeDatabases
        If this switch is enabled, mappings for databases will not be exported.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER ExcludeGoBatchSeparator
        If specified, will NOT script the 'GO' batch separator.

    .PARAMETER DestinationVersion
        To say to which version the script should be generated. If not specified will use instance major version.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .NOTES
        Tags: Export, Login
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Export-DbaLogin

    .EXAMPLE
        PS C:\> Export-DbaLogin -SqlInstance sql2005 -Path C:\temp\sql2005-logins.sql

        Exports the logins for SQL Server "sql2005" and writes them to the file "C:\temp\sql2005-logins.sql"

    .EXAMPLE
        PS C:\> Export-DbaLogin -SqlInstance sqlserver2014a -ExcludeLogin realcajun -SqlCredential $scred -Path C:\temp\logins.sql -Append

        Authenticates to sqlserver2014a using SQL Authentication. Exports all logins except for realcajun to C:\temp\logins.sql, and appends to the file if it exists. If not, the file will be created.

    .EXAMPLE
        PS C:\> Export-DbaLogin -SqlInstance sqlserver2014a -Login realcajun, netnerds -Path C:\temp\logins.sql

        Exports ONLY logins netnerds and realcajun FROM sqlserver2014a to the file  C:\temp\logins.sql

    .EXAMPLE
        PS C:\> Export-DbaLogin -SqlInstance sqlserver2014a -Login realcajun, netnerds -Database HR, Accounting

        Exports ONLY logins netnerds and realcajun FROM sqlserver2014a with the permissions on databases HR and Accounting

    .EXAMPLE
        PS C:\> Export-DbaLogin -SqlInstance sqlserver2008 -Login realcajun, netnerds -Path C:\temp\login.sql -ExcludeGoBatchSeparator

        Exports ONLY logins netnerds and realcajun FROM sqlserver2008 server, to the C:\temp\login.sql file without the 'GO' batch separator.

    .EXAMPLE
        PS C:\> Export-DbaLogin -SqlInstance sqlserver2008 -Login realcajun -Path C:\temp\users.sql -DestinationVersion SQLServer2016

        Exports login realcajun from sqlserver2008 to the file C:\temp\users.sql with syntax to run on SQL Server 2016

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]
        $SqlCredential,
        [object[]]$Login,
        [object[]]$ExcludeLogin,
        [Alias("Databases")]
        [object[]]$Database,
        [Alias("OutFile", "FilePath", "FileName")]
        [string]$Path,
        [Alias("NoOverwrite")]
        [switch]$NoClobber,
        [switch]$Append,
        [switch]$ExcludeDatabases,
        [switch]$ExcludeJobs,
        [Alias('Silent')]
        [switch]$EnableException,
        [switch]$ExcludeGoBatchSeparator,
        [ValidateSet('SQLServer2000', 'SQLServer2005', 'SQLServer2008/2008R2', 'SQLServer2012', 'SQLServer2014', 'SQLServer2016', 'SQLServer2017')]
        [string]$DestinationVersion
    )

    begin {

        if ($Path) {
            if ($Path -notlike "*\*") {
                $Path = ".\$Path"
            }
            $directory = Split-Path $Path
            $exists = Test-Path $directory

            if ($exists -eq $false) {
                Write-Message -Level Warning -Message "Parent directory $directory does not exist"
            }
        }

        $outsql = @()

    }
    process {
        if (Test-FunctionInterrupt) {
            return
        }

        $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $sqlcredential

        if ($ExcludeDatabases -eq $false -or $Database) {
            # if we got a database or a list of databases passed
            # and we need to enumerate mappings, login.enumdatabasemappings() takes forever
            # the cool thing though is that database.enumloginmappings() is fast. A lot.
            # if we get a list of databases passed (or even the default list of all the databases)
            # we save outself a call to enumloginmappings if there is no map at all
            $DbMapping = @()
            $DbsToMap = $server.Databases
            if ($Database) {
                $DbsToMap = $DbsToMap | Where-Object Name -in $Database
            }
            foreach ($db in $DbsToMap) {
                if ($db.IsAccessible -eq $false) {
                    continue
                }
                $dbmap = $db.EnumLoginMappings()
                foreach ($el in $dbmap) {
                    $DbMapping += [pscustomobject]@{
                        Database  = $db.Name
                        UserName  = $el.Username
                        LoginName = $el.LoginName
                    }
                }
            }
        }

        foreach ($sourceLogin in $server.Logins) {
            $userName = $sourceLogin.name

            if ($Login -and $Login -notcontains $userName -or $ExcludeLogin -contains $userName) {
                continue
            }

            if ($userName.StartsWith("##") -or $userName -eq 'sa') {
                Write-Message -Level Warning -Message "Skipping $userName"
                continue
            }

            $serverName = $server

            $userBase = ($userName.Split("\")[0]).ToLower()
            if ($serverName -eq $userBase -or $userName.StartsWith("NT ")) {
                if ($Pscmdlet.ShouldProcess("console", "Stating $userName is skipped because it is a local machine name")) {
                    Write-Message -Level Warning -Message "$userName is skipped because it is a local machine name"
                    continue
                }
            }

            if ($Pscmdlet.ShouldProcess("Outfile", "Adding T-SQL for login $userName")) {
                if ($Path) {
                    Write-Message -Level Verbose -Message "Exporting $userName"
                }

                $outsql += "`r`nUSE master`n"
                # Getting some attributes
                $defaultDb = $sourceLogin.DefaultDatabase
                $language = $sourceLogin.Language

                if ($sourceLogin.PasswordPolicyEnforced -eq $false) {
                    $checkPolicy = "OFF"
                } else {
                    $checkPolicy = "ON"
                }

                if (!$sourceLogin.PasswordExpirationEnabled) {
                    $checkExpiration = "OFF"
                } else {
                    $checkExpiration = "ON"
                }

                # Attempt to script out SQL Login
                if ($sourceLogin.LoginType -eq "SqlLogin") {
                    $sourceLoginName = $sourceLogin.name

                    switch ($server.versionMajor) {
                        0 {
                            $sql = "SELECT CONVERT(VARBINARY(256),password) AS hashedpass FROM master.dbo.syslogins WHERE loginname='$sourceLoginName'"
                        }
                        8 {
                            $sql = "SELECT CONVERT(VARBINARY(256),password) AS hashedpass FROM dbo.syslogins WHERE name='$sourceLoginName'"
                        }
                        9 {
                            $sql = "SELECT CONVERT(VARBINARY(256),password_hash) as hashedpass FROM sys.sql_logins WHERE name='$sourceLoginName'"
                        }
                        default {
                            $sql = "SELECT CAST(CONVERT(varchar(256), CAST(LOGINPROPERTY(name,'PasswordHash') AS VARBINARY(256)), 1) AS NVARCHAR(max)) AS hashedpass FROM sys.server_principals WHERE principal_id = $($sourceLogin.id)"
                        }
                    }

                    try {
                        $hashedPass = $server.ConnectionContext.ExecuteScalar($sql)
                    } catch {
                        $hashedPassDt = $server.Databases['master'].ExecuteWithResults($sql)
                        $hashedPass = $hashedPassDt.Tables[0].Rows[0].Item(0)
                    }

                    if ($hashedPass.GetType().Name -ne "String") {
                        $passString = "0x"; $hashedPass | ForEach-Object {
                            $passString += ("{0:X}" -f $_).PadLeft(2, "0")
                        }
                        $hashedPass = $passString
                    }

                    $sid = "0x"; $sourceLogin.sid | ForEach-Object {
                        $sid += ("{0:X}" -f $_).PadLeft(2, "0")
                    }
                    $outsql += "IF NOT EXISTS (SELECT loginname FROM master.dbo.syslogins WHERE name = '$userName') CREATE LOGIN [$userName] WITH PASSWORD = $hashedPass HASHED, SID = $sid, DEFAULT_DATABASE = [$defaultDb], CHECK_POLICY = $checkPolicy, CHECK_EXPIRATION = $checkExpiration, DEFAULT_LANGUAGE = [$language]"
                }
                # Attempt to script out Windows User
                elseif ($sourceLogin.LoginType -eq "WindowsUser" -or $sourceLogin.LoginType -eq "WindowsGroup") {
                    $outsql += "IF NOT EXISTS (SELECT loginname FROM master.dbo.syslogins WHERE name = '$userName') CREATE LOGIN [$userName] FROM WINDOWS WITH DEFAULT_DATABASE = [$defaultDb], DEFAULT_LANGUAGE = [$language]"
                }
                # This script does not currently support certificate mapped or asymmetric key users.
                else {
                    Write-Message -Level Warning -Message "$($sourceLogin.LoginType) logins not supported. $($sourceLogin.Name) skipped"
                    continue
                }

                if ($sourceLogin.IsDisabled) {
                    $outsql += "ALTER LOGIN [$userName] DISABLE"
                }

                if ($sourceLogin.DenyWindowsLogin) {
                    $outsql += "DENY CONNECT SQL TO [$userName]"
                }
            }

            # Server Roles: sysadmin, bulklogin, etc
            foreach ($role in $server.Roles) {
                $roleName = $role.Name

                # SMO changed over time
                try {
                    $roleMembers = $role.EnumMemberNames()
                } catch {
                    $roleMembers = $role.EnumServerRoleMembers()
                }

                if ($roleMembers -contains $userName) {
                    if (($server.VersionMajor -lt 11 -and [string]::IsNullOrEmpty($destinationVersion)) -or ($DestinationVersion -in "SQLServer2000", "SQLServer2005", "SQLServer2008/2008R2")) {
                        $outsql += "EXEC sys.sp_addsrvrolemember @rolename=N'$roleName', @loginame=N'$userName'"
                    } else {
                        $outsql += "ALTER SERVER ROLE [$roleName] ADD MEMBER [$userName]"
                    }
                }
            }

            if ($ExcludeJobs -eq $false) {
                $ownedJobs = $server.JobServer.Jobs | Where-Object { $_.OwnerLoginName -eq $userName }

                foreach ($ownedJob in $ownedJobs) {
                    $outsql += "`n`rUSE msdb`n"
                    $outsql += "EXEC msdb.dbo.sp_update_job @job_name=N'$ownedJob', @owner_login_name=N'$userName'"
                }
            }

            if ($server.VersionMajor -ge 9) {
                # These operations are only supported by SQL Server 2005 and above.
                # Securables: Connect SQL, View any database, Administer Bulk Operations, etc.

                $perms = $server.EnumServerPermissions($userName)
                $outsql += "`n`rUSE master`n"
                foreach ($perm in $perms) {
                    $permState = $perm.permissionstate
                    $permType = $perm.PermissionType
                    $grantor = $perm.grantor

                    if ($permState -eq "GrantWithGrant") {
                        $grantWithGrant = "WITH GRANT OPTION"
                        $permState = "GRANT"
                    } else {
                        $grantWithGrant = $null
                    }

                    $outsql += "$permState $permType TO [$userName] $grantWithGrant AS [$grantor]"
                }

                # Credential mapping. Credential removal not currently supported for Syncs.
                $loginCredentials = $server.Credentials | Where-Object { $_.Identity -eq $sourceLogin.Name }
                foreach ($credential in $loginCredentials) {
                    $credentialName = $credential.Name
                    $outsql += "PRINT '$userName is associated with the $credentialName credential'"
                }
            }

            if ($ExcludeDatabases -eq $false) {
                $dbs = $sourceLogin.EnumDatabaseMappings()

                if ($Database) {
                    $dbs = $dbs | Where-Object { $_.DBName -in $Database }
                }

                # Adding database mappings and securables
                foreach ($db in $dbs) {
                    $dbName = $db.dbname
                    $sourceDb = $server.Databases[$dbName]
                    $dbUserName = $db.username

                    $outsql += "`r`nUSE [$dbName]`n"
                    try {
                        $sql = $server.Databases[$dbName].Users[$dbUserName].Script()
                        $outsql += $sql
                    } catch {
                        Write-Message -Level Warning -Message "User cannot be found in selected database"
                    }

                    # Skipping updating dbowner

                    # Database Roles: db_owner, db_datareader, etc
                    foreach ($role in $sourceDb.Roles) {
                        if ($role.EnumMembers() -contains $dbUserName) {
                            $roleName = $role.Name
                            if (($server.VersionMajor -lt 11 -and [string]::IsNullOrEmpty($destinationVersion)) -or ($DestinationVersion -in "SQLServer2000", "SQLServer2005", "SQLServer2008/2008R2")) {
                                $outsql += "EXEC sys.sp_addrolemember @rolename=N'$roleName', @membername=N'$dbUserName'"
                            } else {
                                $outsql += "ALTER ROLE [$roleName] ADD MEMBER [$dbUserName]"
                            }
                        }
                    }

                    # Connect, Alter Any Assembly, etc
                    $perms = $sourceDb.EnumDatabasePermissions($dbUserName)
                    foreach ($perm in $perms) {
                        $permState = $perm.PermissionState
                        $permType = $perm.PermissionType
                        $grantor = $perm.Grantor

                        if ($permState -eq "GrantWithGrant") {
                            $grantWithGrant = "WITH GRANT OPTION"
                            $permState = "GRANT"
                        } else {
                            $grantWithGrant = $null
                        }

                        $outsql += "$permState $permType TO [$userName] $grantWithGrant AS [$grantor]"
                    }
                }
            }
        }
    }
    end {
        $sql = $sql | Where-Object { $_ -notlike "CREATE USER [dbo] FOR LOGIN * WITH DEFAULT_SCHEMA=[dbo]" }

        if ($ExcludeGoBatchSeparator) {
            $sql = $outsql
        } else {
            $sql = $outsql -join "`r`nGO`r`n"
            #add the final GO
            $sql += "`r`nGO"
        }

        if ($Path) {
            $sql | Out-File -Encoding UTF8 -FilePath $Path -Append:$Append -NoClobber:$NoClobber
            Get-ChildItem $Path
        } else {
            $sql
        }
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Export-SqlLogin
    }
}
tools\dbatools\functions\Export-DbaPfDataCollectorSetTemplate.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Export-DbaPfDataCollectorSetTemplate {
    <#
    .SYNOPSIS
        Exports a new Data Collector Set XML Template.

    .DESCRIPTION
        Exports a Data Collector Set XML Template from Get-DbaPfDataCollectorSet. Exports to "$home\Documents\Performance Monitor Templates" by default.

    .PARAMETER ComputerName
        The target computer. Defaults to localhost.

    .PARAMETER Credential
        Allows you to login to $ComputerName using alternative credentials. To use:

        $cred = Get-Credential, then pass $cred object to the -Credential parameter.

    .PARAMETER CollectorSet
        The name of the collector set(s) to export.

    .PARAMETER Path
        The path to export the file. Can be .xml or directory.

    .PARAMETER InputObject
        Accepts the object output by Get-DbaPfDataCollectorSetTemplate via the pipeline.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Performance, DataCollector
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Export-DbaPfDataCollectorSetTemplate

    .EXAMPLE
        PS C:\> Export-DbaPfDataCollectorSetTemplate -ComputerName sql2017 -Path C:\temp\pf

        Exports all data collector sets from to the C:\temp\pf folder.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorSet ComputerName sql2017 -CollectorSet 'System Correlation' | Export-DbaPfDataCollectorSetTemplate -Path C:\temp

        Exports the 'System Correlation' data collector set from sql2017 to C:\temp.

    #>
    [CmdletBinding()]
    param (
        [DbaInstance[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [Alias("DataCollectorSet")]
        [string[]]$CollectorSet,
        [string]$Path = "$home\Documents\Performance Monitor Templates",
        [Parameter(ValueFromPipeline)]
        [object[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ($InputObject.Credential -and (Test-Bound -ParameterName Credential -Not)) {
            $Credential = $InputObject.Credential
        }

        if (-not $InputObject -or ($InputObject -and (Test-Bound -ParameterName ComputerName))) {
            foreach ($computer in $ComputerName) {
                $InputObject += Get-DbaPfDataCollectorSet -ComputerName $computer -Credential $Credential -CollectorSet $CollectorSet
            }
        }

        foreach ($object in $InputObject) {
            if (-not $object.DataCollectorSetObject) {
                Stop-Function -Message "InputObject is not of the right type. Please use Get-DbaPfDataCollectorSet."
                return
            }

            $csname = Remove-InvalidFileNameChars -Name $object.Name

            if ($path.EndsWith(".xml")) {
                $filename = $path
            } else {
                $filename = "$path\$csname.xml"
                if (-not (Test-Path -Path $path)) {
                    $null = New-Item -Type Directory -Path $path
                }
            }
            Write-Message -Level Verbose -Message "Wrote $csname to $filename."
            Set-Content -Path $filename -Value $object.Xml -Encoding Unicode
            Get-ChildItem -Path $filename
        }
    }
}
tools\dbatools\functions\Export-DbaRepServerSetting.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Export-DbaRepServerSetting {
    <#
    .SYNOPSIS
        Exports replication server settings to file.

    .DESCRIPTION
        Exports replication server settings to file.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Path
        Specifies the path to a file which will contain the output.

    .PARAMETER Passthru
        Output script to console

    .PARAMETER NoClobber
        Do not overwrite file

    .PARAMETER Encoding
        Specifies the file encoding. The default is UTF8.

        Valid values are:
        -- ASCII: Uses the encoding for the ASCII (7-bit) character set.
        -- BigEndianUnicode: Encodes in UTF-16 format using the big-endian byte order.
        -- Byte: Encodes a set of characters into a sequence of bytes.
        -- String: Uses the encoding type for a string.
        -- Unicode: Encodes in UTF-16 format using the little-endian byte order.
        -- UTF7: Encodes in UTF-7 format.
        -- UTF8: Encodes in UTF-8 format.
        -- Unknown: The encoding type is unknown or invalid. The data can be treated as binary.

    .PARAMETER Append
        Append to file

    .PARAMETER ScriptOption
        Not real sure how to use this yet

    .PARAMETER InputObject
        Allows piping from Get-DbaRepServer

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Replication
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Export-DbaRepServerSetting -SqlInstance sql2017 -Path C:\temp\replication.sql

        Exports the replication settings on sql2017 to the file C:\temp\replication.sql

    .EXAMPLE
        PS C:\> Get-DbaRepServer -SqlInstance sql2017 | Export-DbaRepServerSettings -Path C:\temp\replication.sql

        Exports the replication settings on sql2017 to the file C:\temp\replication.sql

    #>
    [CmdletBinding()]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$Path,
        [object[]]$ScriptOption,
        [Parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Replication.ReplicationServer[]]$InputObject,
        [ValidateSet('ASCII', 'BigEndianUnicode', 'Byte', 'String', 'Unicode', 'UTF7', 'UTF8', 'Unknown')]
        [string]$Encoding = 'UTF8',
        [switch]$Passthru,
        [switch]$NoClobber,
        [switch]$Append,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaRepServer -SqlInstance $instance -SqlCredential $sqlcredential
        }

        foreach ($repserver in $InputObject) {
            $server = $repserver.SqlServerName
            if (-not (Test-Bound -ParameterName Path)) {
                $timenow = (Get-Date -uformat "%m%d%Y%H%M%S")
                $mydocs = [Environment]::GetFolderPath('MyDocuments')
                $path = "$mydocs\$($server.replace('\', '$'))-$timenow-replication.sql"
            }
            try {
                if (-not $ScriptOption) {
                    $out = $repserver.Script([Microsoft.SqlServer.Replication.ScriptOptions]::Creation `
                            -bor [Microsoft.SqlServer.Replication.ScriptOptions]::IncludeAll `
                            -bor [Microsoft.SqlServer.Replication.ScriptOptions]::EnableReplicationDB `
                            -bor [Microsoft.SqlServer.Replication.ScriptOptions]::IncludeInstallDistributor
                    )
                } else {
                    $out = $repserver.Script($scriptOption)
                }
            } catch {
                Stop-Function -ErrorRecord $_ -Message "Replication export failed. Is it setup?" -Continue
            }
            if ($Passthru) {
                "exec sp_dropdistributor @no_checks = 1, @ignore_distributor = 1" | Out-String
                $out | Out-String
            }

            if ($Path) {

                "exec sp_dropdistributor @no_checks = 1, @ignore_distributor = 1" | Out-File -FilePath $path -Encoding $encoding -Append
                $out | Out-File -FilePath $path -Encoding $encoding -Append
            }
        }
    }
}
tools\dbatools\functions\Export-DbaScript.ps1
function Export-DbaScript {
    <#
    .SYNOPSIS
        Exports scripts from SQL Management Objects (SMO)

    .DESCRIPTION
        Exports scripts from SQL Management Objects

    .PARAMETER InputObject
        A SQL Management Object such as the one returned from Get-DbaLogin

    .PARAMETER Path
        The output filename and location. If no path is specified, one will be created. If the file already exists, the output will be appended.

    .PARAMETER Encoding
        Specifies the file encoding. The default is UTF8.

        Valid values are:
        -- ASCII: Uses the encoding for the ASCII (7-bit) character set.
        -- BigEndianUnicode: Encodes in UTF-16 format using the big-endian byte order.
        -- Byte: Encodes a set of characters into a sequence of bytes.
        -- String: Uses the encoding type for a string.
        -- Unicode: Encodes in UTF-16 format using the little-endian byte order.
        -- UTF7: Encodes in UTF-7 format.
        -- UTF8: Encodes in UTF-8 format.
        -- Unknown: The encoding type is unknown or invalid. The data can be treated as binary.

    .PARAMETER Passthru
        Output script to console

    .PARAMETER ScriptingOptionsObject
        An SMO Scripting Object that can be used to customize the output - see New-DbaScriptingOption

    .PARAMETER BatchSeparator
        Specifies the Batch Separator to use. Default is None

    .PARAMETER NoPrefix
        Do not include a Prefix

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed

    .PARAMETER NoClobber
        Do not overwrite file

    .PARAMETER Append
        Append to file

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration, Backup, Export
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Export-DbaScript

    .EXAMPLE
        PS C:\> Get-DbaAgentJob -SqlInstance sql2016 | Export-DbaScript

        Exports all jobs on the SQL Server sql2016 instance using a trusted connection - automatically determines filename as .\sql2016-Job-Export-date.sql

    .EXAMPLE
        PS C:\> Get-DbaAgentJob -SqlInstance sql2016 | Export-DbaScript -Path C:\temp\export.sql -Append

        Exports all jobs on the SQL Server sql2016 instance using a trusted connection - Will append the output to the file C:\temp\export.sql if it already exists
        Script does not include Batch Separator and will not compile

    .EXAMPLE
        PS C:\> Get-DbaDbTable -SqlInstance sql2016 -Database MyDatabase -Table 'dbo.Table1', 'dbo.Table2' -SqlCredential sqladmin | Export-DbaScript -Path C:\temp\export.sql

        Exports only script for 'dbo.Table1' and 'dbo.Table2' in MyDatabase to C:temp\export.sql and uses the SQL login "sqladmin" to login to sql2016

    .EXAMPLE
        PS C:\> Get-DbaAgentJob -SqlInstance sql2016 -Job syspolicy_purge_history, 'Hourly Log Backups' -SqlCredential sqladmin | Export-DbaScript -Path C:\temp\export.sql -NoPrefix

        Exports only syspolicy_purge_history and 'Hourly Log Backups' to C:temp\export.sql and uses the SQL login "sqladmin" to login to sql2016
        Suppress the output of a Prefix

    .EXAMPLE
        PS C:\> $options = New-DbaScriptingOption
        PS C:\> $options.ScriptSchema = $true
        PS C:\> $options.IncludeDatabaseContext  = $true
        PS C:\> $options.IncludeHeaders = $false
        PS C:\> $Options.NoCommandTerminator = $false
        PS C:\> $Options.ScriptBatchTerminator = $true
        PS C:\> $Options.AnsiFile = $true
        PS C:\> Get-DbaAgentJob -SqlInstance sql2016 -Job syspolicy_purge_history, 'Hourly Log Backups' -SqlCredential sqladmin | Export-DbaScript -Path C:\temp\export.sql -ScriptingOptionsObject $options

        Exports only syspolicy_purge_history and 'Hourly Log Backups' to C:temp\export.sql and uses the SQL login "sqladmin" to login to sql2016
        Appends a batch separator at end of each script.

    .EXAMPLE
        PS C:\> Get-DbaAgentJob -SqlInstance sql2014 | Export-DbaScript -Passthru | ForEach-Object { $_.Replace('sql2014','sql2016') } | Set-Content -Path C:\temp\export.sql

        Exports jobs and replaces all instances of the servername "sql2014" with "sql2016" then writes to C:\temp\export.sql

    .EXAMPLE
        PS C:\> $options = New-DbaScriptingOption
        PS C:\> $options.ScriptSchema = $true
        PS C:\> $options.IncludeDatabaseContext  = $true
        PS C:\> $options.IncludeHeaders = $false
        PS C:\> $Options.NoCommandTerminator = $false
        PS C:\> $Options.ScriptBatchTerminator = $true
        PS C:\> $Options.AnsiFile = $true
        PS C:\> $Databases = Get-DbaDatabase -SqlInstance sql2016 -ExcludeDatabase master, model, msdb, tempdb
        PS C:\> foreach ($db in $Databases) {
        >>        Export-DbaScript -InputObject $db -Path C:\temp\export.sql -Append -Encoding UTF8 -ScriptingOptionsObject $options -NoPrefix
        >> }

        Exports Script for each database on sql2016 excluding system databases
        Uses Scripting options to ensure Batch Terminator is set
        Will append the output to the file C:\temp\export.sql if it already exists

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [object[]]$InputObject,
        [Alias("ScriptingOptionObject")]
        [Microsoft.SqlServer.Management.Smo.ScriptingOptions]$ScriptingOptionsObject,
        [string]$Path,
        [ValidateSet('ASCII', 'BigEndianUnicode', 'Byte', 'String', 'Unicode', 'UTF7', 'UTF8', 'Unknown')]
        [string]$Encoding = 'UTF8',
        [string]$BatchSeparator = '',
        [switch]$NoPrefix,
        [switch]$Passthru,
        [switch]$NoClobber,
        [switch]$Append,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $executingUser = [Security.Principal.WindowsIdentity]::GetCurrent().Name
        $commandName = $MyInvocation.MyCommand.Name
        $timeNow = (Get-Date -uformat "%m%d%Y%H%M%S")
        $prefixArray = @()
    }

    process {
        foreach ($object in $InputObject) {

            $typename = $object.GetType().ToString()

            if ($typename.StartsWith('Microsoft.SqlServer.')) {
                $shortype = $typename.Split(".")[-1]
            } else {
                Stop-Function -Message "InputObject is of type $typename which is not a SQL Management Object. Only SMO objects are supported." -Category InvalidData -Target $object -Continue
            }

            if ($shortype -in "LinkedServer", "Credential", "Login") {
                Write-Message -Level Warning -Message "Support for $shortype is limited at this time. No passwords, hashed or otherwise, will be exported if they exist."
            }

            # Just gotta add the stuff that Nic Cain added to his script

            if ($shortype -eq "Configuration") {
                Write-Message -Level Warning -Message "Support for $shortype is limited at this time."
            }

            # Find the server object to pass on to the function
            $parent = $object.parent

            do {
                if ($parent.Urn.Type -ne "Server") {
                    $parent = $parent.Parent
                }
            }
            until (($parent.Urn.Type -eq "Server") -or (-not $parent))

            if (-not $parent -and -not (Get-Member -InputObject $object -Name ScriptCreate) ) {
                Stop-Function -Message "Failed to find valid SMO server object in input: $object." -Category InvalidData -Target $object -Continue
            }

            try {
                $server = $parent
                if (-not $server) {
                    $server = $object.Parent
                }
                $serverName = $server.Name.Replace('\', '$')

                if ($ScriptingOptionsObject) {
                    $scripter = New-Object Microsoft.SqlServer.Management.Smo.Scripter $server
                    $scripter.Options = $ScriptingOptionsObject
                }

                if (!$passthru) {
                    if ($path) {
                        $actualPath = $path
                    } else {
                        $actualPath = "$serverName-$shortype-Export-$timeNow.sql"
                    }
                }

                if ($NoPrefix) {
                    $prefix = ""
                } else {
                    $prefix = "/*`n`tCreated by $executingUser using dbatools $commandName for objects on $serverName at $(Get-Date)`n`tSee https://dbatools.io/$commandName for more information`n*/"
                }

                if ($passthru) {
                    $prefix | Out-String
                } else {
                    if ($prefixArray -notcontains $actualPath) {

                        if ((Test-Path -Path $actualPath) -and $NoClobber) {
                            Stop-Function -Message "File already exists. If you want to overwrite it remove the -NoClobber parameter. If you want to append data, please Use -Append parameter." -Target $actualPath -Continue
                        }
                        #Only at the first output we use the passed variables Append & NoClobber. For this execution the next ones need to buse -Append
                        $prefix | Out-File -FilePath $actualPath -Encoding $encoding -Append:$Append -NoClobber:$NoClobber
                        $prefixArray += $actualPath
                    }
                }

                if ($Pscmdlet.ShouldProcess($env:computername, "Exporting $object from $server to $actualPath")) {
                    Write-Message -Level Verbose -Message "Exporting $object"

                    if ($passthru) {
                        if ($ScriptingOptionsObject) {
                            foreach ($script in $scripter.EnumScript($object)) {
                                if ($BatchSeparator -ne "") {
                                    $script = "$script`r`n$BatchSeparator`r`n"
                                }
                                $script | Out-String
                            }
                        } else {
                            if (Get-Member -Name ScriptCreate -InputObject $object) {
                                $script = $object.ScriptCreate().GetScript()
                            } else {
                                $script = $object.Script()
                            }

                            if ($BatchSeparator -ne "") {
                                $script = "$script`r`n$BatchSeparator`r`n"
                            }
                            $script  | Out-String
                        }
                    } else {
                        if ($ScriptingOptionsObject) {
                            if ($ScriptingOptionsObject.ScriptBatchTerminator) {
                                $ScriptingOptionsObject.AppendToFile = $true
                                $ScriptingOptionsObject.ToFileOnly = $true
                                $ScriptingOptionsObject.FileName = $actualPath
                                $object.Script($ScriptingOptionsObject)
                            } else {
                                foreach ($script in $scripter.EnumScript($object)) {
                                    if ($BatchSeparator -ne "") {
                                        $script = "$script`r`n$BatchSeparator`r`n"
                                    }
                                    $script | Out-File -FilePath $actualPath -Encoding $encoding -Append
                                }
                            }

                        } else {
                            if (Get-Member -Name ScriptCreate -InputObject $object) {
                                $script = $object.ScriptCreate().GetScript()
                            } else {
                                $script = $object.Script()
                            }
                            if ($BatchSeparator -ne "") {
                                $script = "$script`r`n$BatchSeparator`r`n"
                            }
                            $script | Out-File -FilePath $actualPath -Encoding $encoding -Append
                        }
                    }

                    if (-not $passthru) {
                        Write-Message -Level Verbose -Message "Exported $object on $($server.Name) to $actualPath"
                        Get-ChildItem -Path $actualPath
                    }
                }
            } catch {
                $message = $_.Exception.InnerException.InnerException.InnerException.Message
                if (-not $message) {
                    $message = $_.Exception
                }
                Stop-Function -Message "Failure on $($server.Name) | $message" -Target $server
            }
        }
    }
}
tools\dbatools\functions\Export-DbaSpConfigure.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Export-DbaSpConfigure {
    <#
    .SYNOPSIS
        Exports advanced sp_configure global configuration options to sql file.

    .DESCRIPTION
        Exports advanced sp_configure global configuration options to sql file.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input.
        You must have sysadmin access if needs to set 'show advanced options' to 1 and server version must be SQL Server version 2005 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Path
        Specifies the path to a file which will contain the sp_configure queries necessary to replicate the configuration settings on another instance. This file is suitable for input into Import-DbaSPConfigure.
        If not specified will output to My Documents folder with default name of ServerName-MMDDYYYYhhmmss-sp_configure.sql
        If a directory is passed then uses default name of ServerName-MMDDYYYYhhmmss-sp_configure.sql

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: SpConfig, Configure, Configuration
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Export-DbaSpConfigure

    .INPUTS
        A DbaInstanceParameter representing an array of SQL Server instances.

    .OUTPUTS
        Creates a new file for each SQL Server Instance

    .EXAMPLE
        PS C:\> Export-DbaSpConfigure -SqlInstance sourceserver

        Exports the SPConfigure settings on sourceserver. As no Path was defined outputs to My Documents folder with default name format of Servername-MMDDYYYYhhmmss-sp_configure.sql

    .EXAMPLE
        PS C:\> Export-DbaSpConfigure -SqlInstance sourceserver -Path C:\temp

        Exports the SPConfigure settings on sourceserver to the directory C:\temp using the default name format

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> Export-DbaSpConfigure -SqlInstance sourceserver -SqlCredential $cred -Path C:\temp\sp_configure.sql

        Exports the SPConfigure settings on sourceserver to the file C:\temp\sp_configure.sql. Uses SQL Authentication to connect. Will require SysAdmin rights if needs to set 'show advanced options'

    .EXAMPLE
        PS C:\> 'Server1', 'Server2' | Export-DbaSpConfigure -Path C:\temp\configure.sql

        Exports the SPConfigure settings for Server1 and Server2 using pipeline. As more than 1 Server adds prefix of Servername and date to the file name and saves to file like  C:\temp\Servername-MMDDYYYYhhmmss-configure.sql

    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$Path,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if (-not (Test-Bound -ParameterName Path)) {
                $timenow = (Get-Date -uformat "%m%d%Y%H%M%S")
                $mydocs = [Environment]::GetFolderPath('MyDocuments')
                $filepath = "$mydocs\$($server.name.replace('\', '$'))-$timenow-sp_configure.sql"
            }

            if (Test-Path $Path -PathType Container) {
                $timenow = (Get-Date -uformat "%m%d%Y%H%M%S")
                $filepath = Join-Path -Path $Path -ChildPath "$($server.name.replace('\', '$'))-$timenow-sp_configure.sql"
            } elseif (Test-Path $Path -PathType Leaf) {
                if ($SqlInstance.Count -gt 1) {
                    $timenow = (Get-Date -uformat "%m%d%Y%H%M%S")
                    $PathData = Get-ChildItem $Path
                    $filepath = "$($PathData.DirectoryName)\$($server.name.replace('\', '$'))-$timenow-$($PathData.Name)"
                } else {
                    $filepath = $Path
                }
            }

            If (-not $filepath) {
                $filepath = $Path
            }

            $topdir = Split-Path -Path $filepath

            if (-not (Test-Path -Path $topdir)) {
                New-Item -Path $topdir -ItemType Directory
            }

            $ShowAdvancedOptions = $server.Configuration.ShowAdvancedOptions.ConfigValue

            if ($ShowAdvancedOptions -eq 0) {
                try {
                    $server.Configuration.ShowAdvancedOptions.ConfigValue = $true
                    $server.Configuration.Alter($true)
                } catch {
                    Stop-Function -Message "Can't set 'show advanced options' to 1 on instance $instance" -ErrorRecord $_ -Continue
                }
            }

            try {
                Set-Content -Path $filepath "EXEC sp_configure 'show advanced options' , 1;  RECONFIGURE WITH OVERRIDE"
            } catch {
                Stop-Function -Message "Can't write to $filepath" -ErrorRecord $_ -Continue
            }

            foreach ($sourceprop in $server.Configuration.Properties) {
                $displayname = $sourceprop.DisplayName
                $configvalue = $sourceprop.ConfigValue
                Add-Content -Path $filepath "EXEC sp_configure '$displayname' , $configvalue;"
            }

            if ($ShowAdvancedOptions -eq 0) {
                Add-Content -Path $filepath "EXEC sp_configure 'show advanced options' , 0;"
                Add-Content -Path $filepath "RECONFIGURE WITH OVERRIDE"

                $server.Configuration.ShowAdvancedOptions.ConfigValue = $false
                $server.Configuration.Alter($true)
            }
            Get-ChildItem -Path $filepath
        }
    }

    end {
        Write-Message -Level Verbose -Message "Server configuration export finished"

        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Export-SqlSpConfigure
    }
}
tools\dbatools\functions\Export-DbaUser.ps1
function Export-DbaUser {
    <#
    .SYNOPSIS
        Exports users creation and its permissions to a T-SQL file or host.

    .DESCRIPTION
        Exports users creation and its permissions to a T-SQL file or host. Export includes user, create and add to role(s), database level permissions, object level permissions.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. SQL Server 2000 and above supported.

    .PARAMETER SqlCredential
        Allows you to login to servers using alternative credentials

        $scred = Get-Credential, then pass $scred object to the -SqlCredential parameter

        Windows Authentication will be used if SqlCredential is not specified

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER User
        Export only the specified database user(s). If not specified will export all users from the database(s)

    .PARAMETER DestinationVersion
        To say to which version the script should be generated. If not specified will use database compatibility level

    .PARAMETER Path
        Specifies the full path of a file to write the script to.

    .PARAMETER NoClobber
        Do not overwrite file

    .PARAMETER Append
        Append to file

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER ScriptingOptionsObject
        A Microsoft.SqlServer.Management.Smo.ScriptingOptions object with the options that you want to use to generate the t-sql script.
        You can use the NEw-DbaScriptingOption to generate it.

    .PARAMETER ExcludeGoBatchSeparator
        If specified, will NOT script the 'GO' batch separator.

    .NOTES
        Tags: User, Export
        Author: Claudio Silva (@ClaudioESSilva)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Export-DbaUser

    .EXAMPLE
        PS C:\> Export-DbaUser -SqlInstance sql2005 -Path C:\temp\sql2005-users.sql

        Exports SQL for the users in server "sql2005" and writes them to the file "C:\temp\sql2005-users.sql"

    .EXAMPLE
        PS C:\> Export-DbaUser -SqlInstance sqlserver2014a $scred -Path C:\temp\users.sql -Append

        Authenticates to sqlserver2014a using SQL Authentication. Exports all users to C:\temp\users.sql, and appends to the file if it exists. If not, the file will be created.

    .EXAMPLE
        PS C:\> Export-DbaUser -SqlInstance sqlserver2014a -User User1, User2 -Path C:\temp\users.sql

        Exports ONLY users User1 and User2 from sqlserver2014a to the file  C:\temp\users.sql

    .EXAMPLE
        PS C:\> Export-DbaUser -SqlInstance sqlserver2008 -User User1 -Path C:\temp\users.sql -DestinationVersion SQLServer2016

        Exports user User1 from sqlserver2008 to the file C:\temp\users.sql with syntax to run on SQL Server 2016

    .EXAMPLE
        PS C:\> Export-DbaUser -SqlInstance sqlserver2008 -Database db1,db2 -Path C:\temp\users.sql

        Exports ONLY users from db1 and db2 database on sqlserver2008 server, to the C:\temp\users.sql file.

    .EXAMPLE
        PS C:\> $options = New-DbaScriptingOption
        PS C:\> $options.ScriptDrops = $false
        PS C:\> $options.WithDependencies = $true
        PS C:\> Export-DbaUser -SqlInstance sqlserver2008 -Database db1,db2 -Path C:\temp\users.sql -ScriptingOptionsObject $options

        Exports ONLY users from db1 and db2 database on sqlserver2008 server, to the C:\temp\users.sql file.
        It will not script drops but will script dependencies.

    .EXAMPLE
        PS C:\> Export-DbaUser -SqlInstance sqlserver2008 -Database db1,db2 -Path C:\temp\users.sql -ExcludeGoBatchSeparator

        Exports ONLY users from db1 and db2 database on sqlserver2008 server, to the C:\temp\users.sql file without the 'GO' batch separator.


    #>
    [CmdletBinding(DefaultParameterSetName = "Default")]
    [OutputType([String])]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]
        $SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [object[]]$User,
        [ValidateSet('SQLServer2000', 'SQLServer2005', 'SQLServer2008/2008R2', 'SQLServer2012', 'SQLServer2014', 'SQLServer2016', 'SQLServer2017')]
        [string]$DestinationVersion,
        [Alias("OutFile", "FilePath", "FileName")]
        [string]$Path,
        [Alias("NoOverwrite")]
        [switch]$NoClobber,
        [switch]$Append,
        [Alias('Silent')]
        [switch]$EnableException,
        [Microsoft.SqlServer.Management.Smo.ScriptingOptions]$ScriptingOptionsObject = $null,
        [switch]$ExcludeGoBatchSeparator
    )

    begin {
        if ($Path) {
            if ($Path -notlike "*\*") { $Path = ".\$Path" }
            $directory = Split-Path $Path
            $exists = Test-Path $directory

            if ($exists -eq $false) {
                Stop-Function -Message "Parent directory $directory does not exist"
                return
            }
        }

        $outsql = @()

        $versions = @{
            'SQLServer2000'        = 'Version80'
            'SQLServer2005'        = 'Version90'
            'SQLServer2008/2008R2' = 'Version100'
            'SQLServer2012'        = 'Version110'
            'SQLServer2014'        = 'Version120'
            'SQLServer2016'        = 'Version130'
            'SQLServer2017'        = 'Version140'
        }

        $versionName = @{
            'Version80'  = 'SQLServer2000'
            'Version90'  = 'SQLServer2005'
            'Version100' = 'SQLServer2008/2008R2'
            'Version110' = 'SQLServer2012'
            'Version120' = 'SQLServer2014'
            'Version130' = 'SQLServer2016'
            'Version140' = 'SQLServer2017'
        }

    }
    process {
        if (Test-FunctionInterrupt) { return }

        try {
            $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
        }

        if (!$database) {
            $databases = $server.Databases | Where-Object { $ExcludeDatabase -notcontains $_.Name -and $_.IsAccessible -eq $true }
        } else {
            if ($pipedatabase) {
                $databases = $pipedatabase.name
            } else {
                $databases = $server.Databases | Where-Object { $_.IsAccessible -eq $true -and ($database -contains $_.Name) }
            }
        }

        if ($exclude) {
            $databases = $databases | Where-Object Name -notin $ExcludeDatabase
        }

        if (@($databases).Count -gt 0) {

            #Database Permissions
            foreach ($db in $databases) {
                if ([string]::IsNullOrEmpty($destinationVersion)) {
                    #Get compatibility level for scripting the objects
                    $scriptVersion = $db.CompatibilityLevel
                } else {
                    $scriptVersion = $versions[$destinationVersion]
                }
                $versionNameDesc = $versionName[$scriptVersion.ToString()]

                #If not passed create new ScriptingOption. Otherwise use the one that was passed
                if ($null -eq $ScriptingOptionsObject) {
                    $ScriptingOptionsObject = New-DbaScriptingOption
                    $ScriptingOptionsObject.TargetServerVersion = [Microsoft.SqlServer.Management.Smo.SqlServerVersion]::$scriptVersion
                    $ScriptingOptionsObject.AllowSystemObjects = $false
                    $ScriptingOptionsObject.IncludeDatabaseRoleMemberships = $true
                    $ScriptingOptionsObject.ContinueScriptingOnError = $false
                    $ScriptingOptionsObject.IncludeDatabaseContext = $false
                    $ScriptingOptionsObject.IncludeIfNotExists = $true
                }

                Write-Message -Level Output -Message "Validating users on database $db"

                if ($User.Count -eq 0) {
                    $users = $db.Users | Where-Object { $_.IsSystemObject -eq $false -and $_.Name -notlike "##*" }
                } else {
                    if ($pipedatabase) {
                        $users = $pipedatabase.name
                    } else {
                        $users = $db.Users | Where-Object { $User -contains $_.Name -and $_.IsSystemObject -eq $false -and $_.Name -notlike "##*" }
                    }
                }
                # Store roles between users so if we hit the same one we don't create it again
                $roles = @()
                if ($users.Count -gt 0) {
                    foreach ($dbuser in $users) {
                        Write-Message -Level Output -Message "Generating script for user $dbuser"

                        #setting database
                        $outsql += "USE [" + $db.Name + "]"

                        try {
                            #Fixed Roles #Dependency Issue. Create Role, before add to role.
                            foreach ($rolePermission in ($db.Roles | Where-Object { $_.IsFixedRole -eq $false })) {
                                foreach ($rolePermissionScript in $rolePermission.Script($ScriptingOptionsObject)) {
                                    if ($rolePermission.ToString() -notin $roles) {
                                        $roles += , $rolePermission.ToString()
                                        $outsql += "$($rolePermissionScript.ToString())"
                                    }

                                }
                            }

                            #Database Create User(s) and add to Role(s)
                            foreach ($dbUserPermissionScript in $dbuser.Script($ScriptingOptionsObject)) {
                                if ($dbuserPermissionScript.Contains("sp_addrolemember")) {
                                    $execute = "EXEC "
                                } else {
                                    $execute = ""
                                }
                                $outsql += "$execute$($dbUserPermissionScript.ToString())"
                            }

                            #Database Permissions
                            foreach ($databasePermission in $db.EnumDatabasePermissions() | Where-Object { @("sa", "dbo", "information_schema", "sys") -notcontains $_.Grantee -and $_.Grantee -notlike "##*" -and ($dbuser.Name -contains $_.Grantee) }) {
                                if ($databasePermission.PermissionState -eq "GrantWithGrant") {
                                    $withGrant = " WITH GRANT OPTION"
                                    $grantDatabasePermission = 'GRANT'
                                } else {
                                    $withGrant = " "
                                    $grantDatabasePermission = $databasePermission.PermissionState.ToString().ToUpper()
                                }

                                $outsql += "$($grantDatabasePermission) $($databasePermission.PermissionType) TO [$($databasePermission.Grantee)]$withGrant AS [$($databasePermission.Grantor)];"
                            }

                            #Database Object Permissions
                            # NB: This is a bit of a mess for a couple of reasons
                            # 1. $db.EnumObjectPermissions() doesn't enumerate all object types
                            # 2. Some (x)Collection types can have EnumObjectPermissions() called
                            #    on them directly (e.g. AssemblyCollection); others can't (e.g.
                            #    ApplicationRoleCollection). Those that can't we iterate the
                            #    collection explicitly and add each object's permission.

                            $perms = New-Object System.Collections.ArrayList

                            $null = $perms.AddRange($db.EnumObjectPermissions($dbuser.Name))

                            foreach ($item in $db.ApplicationRoles) {
                                $null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
                            }

                            foreach ($item in $db.Assemblies) {
                                $null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
                            }

                            foreach ($item in $db.Certificates) {
                                $null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
                            }

                            foreach ($item in $db.DatabaseRoles) {
                                $null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
                            }

                            foreach ($item in $db.FullTextCatalogs) {
                                $null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
                            }

                            foreach ($item in $db.FullTextStopLists) {
                                $null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
                            }

                            foreach ($item in $db.SearchPropertyLists) {
                                $null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
                            }

                            foreach ($item in $db.ServiceBroker.MessageTypes) {
                                $null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
                            }

                            foreach ($item in $db.RemoteServiceBindings) {
                                $null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
                            }

                            foreach ($item in $db.ServiceBroker.Routes) {
                                $null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
                            }

                            foreach ($item in $db.ServiceBroker.ServiceContracts) {
                                $null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
                            }

                            foreach ($item in $db.ServiceBroker.Services) {
                                $null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
                            }

                            if ($scriptVersion -ne "Version80") {
                                foreach ($item in $db.AsymmetricKeys) {
                                    $null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
                                }
                            }

                            foreach ($item in $db.SymmetricKeys) {
                                $null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
                            }

                            foreach ($item in $db.XmlSchemaCollections) {
                                $null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
                            }

                            foreach ($objectPermission in $perms | Where-Object { @("sa", "dbo", "information_schema", "sys") -notcontains $_.Grantee -and $_.Grantee -notlike "##*" -and $_.Grantee -eq $dbuser.Name }) {
                                switch ($objectPermission.ObjectClass) {
                                    'ApplicationRole' {
                                        $object = 'APPLICATION ROLE::[{0}]' -f $objectPermission.ObjectName
                                    }
                                    'AsymmetricKey' {
                                        $object = 'ASYMMETRIC KEY::[{0}]' -f $objectPermission.ObjectName
                                    }
                                    'Certificate' {
                                        $object = 'CERTIFICATE::[{0}]' -f $objectPermission.ObjectName
                                    }
                                    'DatabaseRole' {
                                        $object = 'ROLE::[{0}]' -f $objectPermission.ObjectName
                                    }
                                    'FullTextCatalog' {
                                        $object = 'FULLTEXT CATALOG::[{0}]' -f $objectPermission.ObjectName
                                    }
                                    'FullTextStopList' {
                                        $object = 'FULLTEXT STOPLIST::[{0}]' -f $objectPermission.ObjectName
                                    }
                                    'MessageType' {
                                        $object = 'Message Type::[{0}]' -f $objectPermission.ObjectName
                                    }
                                    'ObjectOrColumn' {
                                        if ($scriptVersion -ne "Version80") {
                                            $object = 'OBJECT::[{0}].[{1}]' -f $objectPermission.ObjectSchema, $objectPermission.ObjectName
                                            if ($null -ne $objectPermission.ColumnName) {
                                                $object += '([{0}])' -f $objectPermission.ColumnName
                                            }
                                        }
                                        #At SQL Server 2000 OBJECT did not exists
                                        else {
                                            $object = '[{0}].[{1}]' -f $objectPermission.ObjectSchema, $objectPermission.ObjectName
                                        }
                                    }
                                    'RemoteServiceBinding' {
                                        $object = 'REMOTE SERVICE BINDING::[{0}]' -f $objectPermission.ObjectName
                                    }
                                    'Schema' {
                                        $object = 'SCHEMA::[{0}]' -f $objectPermission.ObjectName
                                    }
                                    'SearchPropertyList' {
                                        $object = 'SEARCH PROPERTY LIST::[{0}]' -f $objectPermission.ObjectName
                                    }
                                    'Service' {
                                        $object = 'SERVICE::[{0}]' -f $objectPermission.ObjectName
                                    }
                                    'ServiceContract' {
                                        $object = 'CONTRACT::[{0}]' -f $objectPermission.ObjectName
                                    }
                                    'ServiceRoute' {
                                        $object = 'ROUTE::[{0}]' -f $objectPermission.ObjectName
                                    }
                                    'SqlAssembly' {
                                        $object = 'ASSEMBLY::[{0}]' -f $objectPermission.ObjectName
                                    }
                                    'SymmetricKey' {
                                        $object = 'SYMMETRIC KEY::[{0}]' -f $objectPermission.ObjectName
                                    }
                                    'User' {
                                        $object = 'USER::[{0}]' -f $objectPermission.ObjectName
                                    }
                                    'UserDefinedType' {
                                        $object = 'TYPE::[{0}].[{1}]' -f $objectPermission.ObjectSchema, $objectPermission.ObjectName
                                    }
                                    'XmlNamespace' {
                                        $object = 'XML SCHEMA COLLECTION::[{0}]' -f $objectPermission.ObjectName
                                    }
                                }

                                if ($objectPermission.PermissionState -eq "GrantWithGrant") {
                                    $withGrant = " WITH GRANT OPTION"
                                    $grantObjectPermission = 'GRANT'
                                } else {
                                    $withGrant = " "
                                    $grantObjectPermission = $objectPermission.PermissionState.ToString().ToUpper()
                                }

                                $outsql += "$grantObjectPermission $($objectPermission.PermissionType) ON $object TO [$($objectPermission.Grantee)]$withGrant AS [$($objectPermission.Grantor)];"
                            }

                        } catch {
                            Stop-Function -Message "This user may be using functionality from $($versionName[$db.CompatibilityLevel.ToString()]) that does not exist on the destination version ($versionNameDesc)." -Continue -InnerErrorRecord $_ -Target $db
                        }
                    }
                } else {
                    Write-Message -Level Output -Message "No users found on database '$db'"
                }

                #reset collection
                $users = $null
            }
        } else {
            Write-Message -Level Output -Message "No users found on instance '$server'"
        }
    }

    end {
        if (Test-FunctionInterrupt) { return }

        if ($ExcludeGoBatchSeparator) {
            $sql = $outsql
        } else {
            $sql = $outsql -join "`r`nGO`r`n"
            #add the final GO
            $sql += "`r`nGO"
        }

        if ($Path) {
            $sql | Out-File -Encoding UTF8 -FilePath $Path -Append:$Append -NoClobber:$NoClobber
        } else {
            $sql
        }
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Export-SqlUser
    }
}
tools\dbatools\functions\Export-DbaXECsv.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Export-DbaXECsv {
    <#
    .SYNOPSIS
        Exports Extended Events to a CSV file.

    .DESCRIPTION
        Exports Extended Events to a CSV file.

    .PARAMETER Path
        Specifies the InputObject to the output CSV file

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER InputObject
        Allows Piping

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Gianluca Sartori (@spaghettidba)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Export-DbaXECsv

    .EXAMPLE
        PS C:\> Get-ChildItem -Path C:\temp\sample.xel | Export-DbaXECsv -Path c:\temp\sample.csv

        Writes Extended Events data to the file "C:\temp\events.csv".

    .EXAMPLE
        PS C:\> Get-DbaXESession -SqlInstance sql2014 -Session deadlocks | Export-DbaXECsv -Path c:\temp\events.csv

        Writes Extended Events data to the file "C:\temp\events.csv".

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias('FullName')]
        [object[]]$InputObject,
        [parameter(Mandatory)]
        [string]$Path,
        [switch]$EnableException
    )
    begin {
        try {
            Add-Type -Path "$script:PSModuleRoot\bin\XESmartTarget\XESmartTarget.Core.dll" -ErrorAction Stop
        } catch {
            Stop-Function -Message "Could not load XESmartTarget.Core.dll" -ErrorRecord $_ -Target "XESmartTarget"
            return
        }

        function Get-FileFromXE ($InputObject) {
            if ($InputObject.TargetFile) {
                if ($InputObject.TargetFile.Length -eq 0) {
                    Stop-Function -Message "This session does not have an associated Target File."
                    return
                }

                $instance = [dbainstance]$InputObject.ComputerName

                if ($instance.IsLocalHost) {
                    $xelpath = $InputObject.TargetFile
                } else {
                    $xelpath = $InputObject.RemoteTargetFile
                }

                if ($xelpath -notmatch ".xel") {
                    $xelpath = "$xelpath*.xel"
                }

                try {
                    Get-ChildItem -Path $xelpath -ErrorAction Stop
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_
                }
            }
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }

        $getfiles = Get-FileFromXE $InputObject

        if ($getfiles) {
            $InputObject += $getfiles
        }

        foreach ($file in $InputObject) {
            if ($file -is [System.String]) {
                $currentfile = $file
            } elseif ($file -is [System.IO.FileInfo]) {
                $currentfile = $file.FullName
            } elseif ($file -is [Microsoft.SqlServer.Management.XEvent.Session]) {
                # it was taken care of above
                continue
            } else {
                Stop-Function -Message "Unsupported file type."
                return
            }

            $accessible = Test-Path -Path $currentfile
            $whoami = whoami

            if (-not $accessible) {
                if ($file.Status -eq "Stopped") { continue }
                Stop-Function -Continue -Message "$currentfile cannot be accessed from $($env:COMPUTERNAME). Does $whoami have access?"
            }

            if (-not (Test-Path $Path)) {
                if ([String]::IsNullOrEmpty([IO.Path]::GetExtension($Path))) {
                    New-Item $Path -ItemType directory | Out-Null
                    $outDir = $Path
                    $outFile = [IO.Path]::GetFileNameWithoutExtension($currentfile) + ".csv"
                } else {
                    $outDir = [IO.Path]::GetDirectoryName($Path)
                    $outFile = [IO.Path]::GetFileName($Path)
                }
            } else {
                if ((Get-Item $Path) -is [System.IO.DirectoryInfo]) {
                    $outDir = $Path
                    $outFile = [IO.Path]::GetFileNameWithoutExtension($currentfile) + ".csv"
                } else {
                    $outDir = [IO.Path]::GetDirectoryName($Path)
                    $outFile = [IO.Path]::GetFileName($Path)
                }
            }

            $adapter = New-Object XESmartTarget.Core.Utils.XELFileCSVAdapter
            $adapter.InputFile = $currentfile
            $adapter.OutputFile = (Join-Path $outDir $outFile)

            try {
                $adapter.Convert()
                $file = Get-ChildItem -Path $adapter.OutputFile

                if ($file.Length -eq 0) {
                    Remove-Item -Path $adapter.OutputFile
                } else {
                    $file
                }
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Target "XESmartTarget" -Continue
            }
        }
    }
}
tools\dbatools\functions\Export-DbaXESessionTemplate.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Export-DbaXESessionTemplate {
    <#
    .SYNOPSIS
        Exports an XESession XML Template using XE Session(s) output by Get-DbaXESession

    .DESCRIPTION
        Exports an XESession XML Template either from the Target SQL Server or XE Session(s) output by Get-DbaXESession. Exports to "$home\Documents\SQL Server Management Studio\Templates\XEventTemplates" by default

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Session
        The Name of the session(s) to export.

    .PARAMETER Path
        The path to export the file into. Can be .xml or directory.

    .PARAMETER InputObject
        Specifies an XE Session output by Get-DbaXESession.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Export-DbaXESessionTemplate

    .EXAMPLE
        PS C:\> Export-DbaXESessionTemplate -SqlInstance sql2017 -Path C:\temp\xe

        Exports an XESession XML Template for all Extended Event Sessions on sql2017 to the C:\temp\xe folder.

    .EXAMPLE
        PS C:\> Get-DbaXESession -SqlInstance sql2017 -Session system_health | Export-DbaXESessionTemplate -Path C:\temp\xe

        Gets the system_health Extended Events Session from sql2017 and then exports as an XESession XML Template to C:\temp\xe

    #>
    [CmdletBinding()]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Session,
        [string]$Path = "$home\Documents\SQL Server Management Studio\Templates\XEventTemplates",
        [Parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.XEvent.Session[]]$InputObject,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $InputObject += Get-DbaXESession -SqlInstance $instance -SqlCredential $SqlCredential -Session $Session -EnableException
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
        }

        foreach ($xes in $InputObject) {
            $xesname = Remove-InvalidFileNameChars -Name $xes.Name

            if (-not (Test-Path -Path $Path)) {
                Stop-Function -Message "$Path does not exist." -Target $Path
            }

            if ($path.EndsWith(".xml")) {
                $filename = $path
            } else {
                $filename = "$path\$xesname.xml"
            }
            Write-Message -Level Verbose -Message "Wrote $xesname to $filename"
            [Microsoft.SqlServer.Management.XEvent.XEStore]::SaveSessionToTemplate($xes, $filename, $true)
            Get-ChildItem -Path $filename
        }
    }
}
tools\dbatools\functions\Find-DbaAgentJob.ps1
function Find-DbaAgentJob {
    <#
    .SYNOPSIS
        Find-DbaAgentJob finds agent jobs that fit certain search filters.

    .DESCRIPTION
        This command filters SQL Agent jobs giving the DBA a list of jobs that may need attention or could possibly be options for removal.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SqlCredential
        Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.

    .PARAMETER JobName
        Filter agent jobs to only the name(s) you list.
        Supports regular expression (e.g. MyJob*) being passed in.

    .PARAMETER ExcludeJobName
        Allows you to enter an array of agent job names to ignore

    .PARAMETER StepName
        Filter based on StepName.
        Supports regular expression (e.g. MyJob*) being passed in.

    .PARAMETER LastUsed
        Find all jobs that havent ran in the INT number of previous day(s)

    .PARAMETER IsDisabled
        Find all jobs that are disabled

    .PARAMETER IsFailed
        Find all jobs that have failed

    .PARAMETER IsNotScheduled
        Find all jobs with no schedule assigned

    .PARAMETER IsNoEmailNotification
        Find all jobs without email notification configured

    .PARAMETER Category
        Filter based on agent job categories

    .PARAMETER Owner
        Filter based on owner of the job/s

    .PARAMETER Since
        Datetime object used to narrow the results to a date

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Job
        Author: Stephen Bennett (https://sqlnotesfromtheunderground.wordpress.com/)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Find-DbaAgentJob

    .EXAMPLE
        PS C:\> Find-DbaAgentJob -SqlInstance Dev01 -JobName *backup*

        Returns all agent job(s) that have backup in the name

    .EXAMPLE
        PS C:\> Find-DbaAgentJob -SqlInstance Dev01, Dev02 -JobName Mybackup

        Returns all agent job(s) that are named exactly Mybackup

    .EXAMPLE
        PS C:\> Find-DbaAgentJob -SqlInstance Dev01 -LastUsed 10

        Returns all agent job(s) that have not ran in 10 days

    .EXAMPLE
        PS C:\> Find-DbaAgentJob -SqlInstance Dev01 -IsDisabled -IsNoEmailNotification -IsNotScheduled

        Returns all agent job(s) that are either disabled, have no email notification or don't have a schedule. returned with detail

    .EXAMPLE
        PS C:\> $servers | Find-DbaAgentJob -IsFailed | Start-DbaAgentJob

        Finds all failed job then starts them. Consider using a -WhatIf at the end of Start-DbaAgentJob to see what it'll do first

    .EXAMPLE
        PS C:\> Find-DbaAgentJob -SqlInstance Dev01 -LastUsed 10 -Exclude "Yearly - RollUp Workload", "SMS - Notification"

        Returns all agent jobs that have not ran in the last 10 days ignoring jobs "Yearly - RollUp Workload" and "SMS - Notification"

    .EXAMPLE
        PS C:\> Find-DbaAgentJob -SqlInstance Dev01 -Category "REPL-Distribution", "REPL-Snapshot" | Format-Table -AutoSize -Wrap

        Returns all job/s on Dev01 that are in either category "REPL-Distribution" or "REPL-Snapshot"

    .EXAMPLE
        PS C:\> Find-DbaAgentJob -SqlInstance Dev01, Dev02 -IsFailed -Since '2016-07-01 10:47:00'

        Returns all agent job(s) on Dev01 and Dev02 that have failed since July of 2016 (and still have history in msdb)

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance CMSServer -Group Production | Find-DbaAgentJob -Disabled -IsNotScheduled | Format-Table -AutoSize -Wrap

        Queries CMS server to return all SQL instances in the Production folder and then list out all agent jobs that have either been disabled or have no schedule.

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]
        $SqlCredential,
        [Alias("Name")]
        [string[]]$JobName,
        [string[]]$ExcludeJobName,
        [string[]]$StepName,
        [int]$LastUsed,
        [Alias("Disabled")]
        [switch]$IsDisabled,
        [Alias("Failed")]
        [switch]$IsFailed,
        [Alias("NoSchedule")]
        [switch]$IsNotScheduled,
        [Alias("NoEmailNotification")]
        [switch]$IsNoEmailNotification,
        [string[]]$Category,
        [string]$Owner,
        [datetime]$Since,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        if ($IsFailed, [boolean]$JobName, [boolean]$StepName, [boolean]$LastUsed.ToString(), $IsDisabled, $IsNotScheduled, $IsNoEmailNotification, [boolean]$Category, [boolean]$Owner, [boolean]$ExcludeJobName -notcontains $true) {
            Stop-Function -Message "At least one search term must be specified"
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }

        foreach ($instance in $SqlInstance) {
            Write-Message -Level Verbose -Message "Running Scan on: $instance"

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $jobs = $server.JobServer.jobs
            $output = @()

            if ($IsFailed) {
                Write-Message -Level Verbose -Message "Checking for failed jobs."
                $output += $jobs | Where-Object LastRunOutcome -eq "Failed"
            }

            if ($JobName) {
                Write-Message -Level Verbose -Message "Retrieving jobs by their name."
                $output += Get-JobList -SqlInstance $server -JobFilter $JobName
            }

            if ($StepName) {
                Write-Message -Level Verbose -Message "Retrieving jobs by their step names."
                $output += Get-JobList -SqlInstance $server -StepFilter $StepName
            }

            if ($LastUsed) {
                $DaysBack = $LastUsed * -1
                $SinceDate = (Get-date).AddDays($DaysBack)
                Write-Message -Level Verbose -Message "Finding job/s not ran in last $LastUsed days"
                $output += $jobs | Where-Object { $_.LastRunDate -le $SinceDate }
            }

            if ($IsDisabled) {
                Write-Message -Level Verbose -Message "Finding job/s that are disabled"
                $output += $jobs | Where-Object IsEnabled -eq $false
            }

            if ($IsNotScheduled) {
                Write-Message -Level Verbose -Message "Finding job/s that have no schedule defined"
                $output += $jobs | Where-Object HasSchedule -eq $false
            }
            if ($IsNoEmailNotification) {
                Write-Message -Level Verbose -Message "Finding job/s that have no email operator defined"
                $output += $jobs | Where-Object { [string]::IsNullOrEmpty($_.OperatorToEmail) -eq $true }
            }

            if ($Category) {
                Write-Message -Level Verbose -Message "Finding job/s that have the specified category defined"
                $output += $jobs | Where-Object { $Category -contains $_.Category }
            }

            if ($Owner) {
                Write-Message -Level Verbose -Message "Finding job/s with owner critera"
                if ($Owner -match "-") {
                    $OwnerMatch = $Owner -replace "-", ""
                    Write-Message -Level Verbose -Message "Checking for jobs that NOT owned by: $OwnerMatch"
                    $output += $server.JobServer.jobs | Where-Object { $OwnerMatch -notcontains $_.OwnerLoginName }
                } else {
                    Write-Message -Level Verbose -Message "Checking for jobs that are owned by: $owner"
                    $output += $server.JobServer.jobs | Where-Object { $Owner -contains $_.OwnerLoginName }
                }
            }

            if ($Exclude) {
                Write-Message -Level Verbose -Message "Excluding job/s based on Exclude"
                $output = $output | Where-Object { $Exclude -notcontains $_.Name }
            }

            if ($Since) {
                #$Since = $Since.ToString("yyyy-MM-dd HH:mm:ss")
                Write-Message -Level Verbose -Message "Getting only jobs whose LastRunDate is greater than or equal to $since"
                $output = $output | Where-Object { $_.LastRunDate -ge $since }
            }

            $jobs = $output | Select-Object -Unique

            foreach ($job in $jobs) {
                Add-Member -Force -InputObject $job -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                Add-Member -Force -InputObject $job -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                Add-Member -Force -InputObject $job -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                Add-Member -Force -InputObject $job -MemberType NoteProperty -Name JobName -value $job.Name


                Select-DefaultView -InputObject $job -Property ComputerName, InstanceName, SqlInstance, Name, Category, OwnerLoginName, CurrentRunStatus, CurrentRunRetryAttempt, 'IsEnabled as Enabled', LastRunDate, LastRunOutcome, DateCreated, HasSchedule, OperatorToEmail, 'DateCreated as CreateDate'
            }
        }
    }
}
tools\dbatools\functions\Find-DbaBackup.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Find-DbaBackup {
    <#
    .SYNOPSIS
        Finds SQL Server backups on disk.

    .DESCRIPTION
        Provides all of the same functionality for finding SQL backups to remove from disk as a standard maintenance plan would.

        As an addition you have the ability to check the Archive bit on files before deletion. This will allow you to ensure backups have been archived to your archive location before removal.

    .PARAMETER Path
        Specifies the name of the base level folder to search for backup files.

    .PARAMETER BackupFileExtension
        Specifies the filename extension of the backup files you wish to find (typically 'bak', 'trn' or 'log'). Do not include the period.

    .PARAMETER RetentionPeriod
        Specifies the retention period for backup files. Correct format is ##U.

        ## is the retention value and must be an integer value
        U signifies the units where the valid units are:
        h = hours
        d = days
        w = weeks
        m = months

        Formatting Examples:
        '48h' = 48 hours
        '7d' = 7 days
        '4w' = 4 weeks
        '1m' = 1 month

    .PARAMETER CheckArchiveBit
        If this switch is enabled, the filesystem Archive bit is checked.
        If this bit is set (which translates to "it has not been backed up to another location yet"), the file won't be included.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Backup
        Author: Chris Sommer (@cjsommer), www.cjsommer.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Find-DbaBackup

    .EXAMPLE
        PS C:\> Find-DbaBackup -Path 'C:\MSSQL\SQL Backup\' -BackupFileExtension trn -RetentionPeriod 48h

        Searches for all trn files in C:\MSSQL\SQL Backup\ and all subdirectories that are more than 48 hours old will be included.

    .EXAMPLE
        PS C:\> Find-DbaBackup -Path 'C:\MSSQL\Backup\' -BackupFileExtension bak -RetentionPeriod 7d -CheckArchiveBit

        Searches for all bak files in C:\MSSQL\Backup\ and all subdirectories that are more than 7 days old will be included, but only if the files have been backed up to another location as verified by checking the Archive bit.

    .EXAMPLE
         PS C:\> Find-DbaBackup -Path '\\SQL2014\Backup\' -BackupFileExtension bak -RetentionPeriod 24h | Remove-Item -Verbose

         Searches for all bak files in \\SQL2014\Backup\ and all subdirectories that are more than 24 hours old and deletes only those files with verbose message.
#>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, HelpMessage = "Full path to the root level backup folder (ex. 'C:\SQL\Backups'")]
        [Alias("BackupFolder")]
        [string]$Path,
        [parameter(Mandatory, HelpMessage = "Backup File extension to remove (ex. bak, trn, dif)")]
        [string]$BackupFileExtension ,
        [parameter(Mandatory, HelpMessage = "Backup retention period. (ex. 24h, 7d, 4w, 6m)")]
        [string]$RetentionPeriod ,
        [switch]$CheckArchiveBit = $false ,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        ### Local Functions
        function Convert-UserFriendlyRetentionToDatetime {
            [cmdletbinding()]
            param (
                [string]$UserFriendlyRetention
            )

            <#
            Convert a user friendly retention value into a datetime.
            The last character of the string will indicate units (validated)
            Valid units are: (h = hours, d = days, w = weeks, m = months)

            The preceeding characters are the value and must be an integer (validated)

            Examples:
                '48h' = 48 hours
                '7d' = 7 days
                '4w' = 4 weeks
                '1m' = 1 month
            #>

            [int]$Length = ($UserFriendlyRetention).Length
            $Value = ($UserFriendlyRetention).Substring(0, $Length - 1)
            $Units = ($UserFriendlyRetention).Substring($Length - 1, 1)

            # Validate that $Units is an accepted unit of measure
            if ( $Units -notin @('h', 'd', 'w', 'm') ) {
                throw "RetentionPeriod '$UserFriendlyRetention' units invalid! See Get-Help for correct formatting and examples."
            }

            # Validate that $Value is an INT
            if ( ![int]::TryParse($Value, [ref]"") ) {
                throw "RetentionPeriod '$UserFriendlyRetention' format invalid! See Get-Help for correct formatting and examples."
            }

            switch ($Units) {
                #Variable marked as unused by PSScriptAnalyzer
                'h' {<# $UnitString = 'Hours';#> [datetime]$ReturnDatetime = (Get-Date).AddHours( - $Value)  }
                'd' {<# $UnitString = 'Days';#> [datetime]$ReturnDatetime = (Get-Date).AddDays( - $Value)   }
                'w' {<# $UnitString = 'Weeks';#> [datetime]$ReturnDatetime = (Get-Date).AddDays( - $Value * 7) }
                'm' {<# $UnitString = 'Months';#> [datetime]$ReturnDatetime = (Get-Date).AddMonths( - $Value) }
            }
            $ReturnDatetime
        }

        # Validations
        # Ensure BackupFileExtension does not begin with a .
        if ($BackupFileExtension -match "^[.]") {
            Write-Message -Level Warning -Message "Parameter -BackupFileExtension begins with a period '$BackupFileExtension'. A period is automatically prepended to -BackupFileExtension and need not be passed in."
        }
        # Ensure Path is a proper path
        if (!(Test-Path $Path -PathType 'Container')) {
            Stop-Function -Message "$Path not found"
        }

    }
    process {
        if (Test-FunctionInterrupt) { return }
        # Process stuff
        Write-Message -Message "Finding backups on $Path" -Level Verbose
        # Convert Retention Value to an actual DateTime
        try {
            $RetentionDate = Convert-UserFriendlyRetentionToDatetime -UserFriendlyRetention $RetentionPeriod
            Write-Message -Message "Backup Retention Date set to $RetentionDate" -Level Verbose
        } catch {
            Stop-Function -Message "Failed to interpret retention time!" -ErrorRecord $_
        }

        # Filter out unarchived files if -CheckArchiveBit parameter is used
        if ($CheckArchiveBit) {
            Write-Message -Message "Removing only archived files." -Level Verbose
            filter DbaArchiveBitFilter {
                if ($_.Attributes -notmatch "Archive") {
                    $_
                }
            }
        } else {
            filter DbaArchiveBitFilter {
                $_
            }
        }
        # Enumeration may take a while. Without resorting to "esoteric" file listing facilities
        # and given we need to fetch at least the LastWriteTime, let's just use "streaming" processing
        # here to avoid issues like described in #970
        Get-ChildItem $Path -Filter "*.$BackupFileExtension" -File -Recurse -ErrorAction SilentlyContinue -ErrorVariable EnumErrors |
            Where-Object LastWriteTime -lt $RetentionDate | DbaArchiveBitFilter
        if ($EnumErrors) {
            Write-Message "Errors encountered enumerating files." -Level Warning -ErrorRecord $EnumErrors
        }
    }
}
tools\dbatools\functions\Find-DbaCommand.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Find-DbaCommand {
    <#
    .SYNOPSIS
        Finds dbatools commands searching through the inline help text

    .DESCRIPTION
        Finds dbatools commands searching through the inline help text, building a consolidated json index and querying it because Get-Help is too slow

    .PARAMETER Tag
        Finds all commands tagged with this auto-populated tag

    .PARAMETER Author
        Finds all commands tagged with this author

    .PARAMETER MinimumVersion
        Finds all commands tagged with this auto-populated minimum version

    .PARAMETER MaximumVersion
        Finds all commands tagged with this auto-populated maximum version

    .PARAMETER Rebuild
        Rebuilds the index

    .PARAMETER Pattern
        Searches help for all commands in dbatools for the specified pattern and displays all results

    .PARAMETER Confirm
        Confirms overwrite of index

    .PARAMETER WhatIf
        Displays what would happen if the command is run

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Find, Help, Command
        Author: Simone Bizzotto (@niphlod)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Find-DbaCommand

    .EXAMPLE
        PS C:\> Find-DbaCommand "snapshot"

        For lazy typers: finds all commands searching the entire help for "snapshot"

    .EXAMPLE
        PS C:\> Find-DbaCommand -Pattern "snapshot"

        For rigorous typers: finds all commands searching the entire help for "snapshot"

    .EXAMPLE
        PS C:\> Find-DbaCommand -Tag copy

        Finds all commands tagged with "copy"

    .EXAMPLE
        PS C:\> Find-DbaCommand -Tag copy,user

        Finds all commands tagged with BOTH "copy" and "user"

    .EXAMPLE
        PS C:\> Find-DbaCommand -Author chrissy

        Finds every command whose author contains our beloved "chrissy"

    .EXAMPLE
        PS C:\> Find-DbaCommand -Author chrissy -Tag copy

        Finds every command whose author contains our beloved "chrissy" and it tagged as "copy"

    .EXAMPLE
        PS C:\> Find-DbaCommand -Pattern snapshot -Rebuild

        Finds all commands searching the entire help for "snapshot", rebuilding the index (good for developers)

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [String]$Pattern,
        [String[]]$Tag,
        [String]$Author,
        [String]$MinimumVersion,
        [String]$MaximumVersion,
        [switch]$Rebuild,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        function Get-DbaTrimmedString($Text) {
            return $Text.Trim() -replace '(\r\n){2,}', "`n"
        }

        $tagsRex = ([regex]'(?m)^[\s]{0,15}Tags:(.*)$')
        $authorRex = ([regex]'(?m)^[\s]{0,15}Author:(.*)$')
        $minverRex = ([regex]'(?m)^[\s]{0,15}MinimumVersion:(.*)$')
        $maxverRex = ([regex]'(?m)^[\s]{0,15}MaximumVersion:(.*)$')

        function Get-DbaHelp([String]$commandName) {
            $availability = 'Windows, Linux, macOS'
            if ($commandName -in $script:noncoresmo -or $commandName -in $script:windowsonly) {
                $availability = 'Windows only'
            }
            $thishelp = Get-Help $commandName -Full
            $thebase = @{ }
            $thebase.CommandName = $commandName
            $thebase.Name = $thishelp.Name

            $thebase.Availability = $availability

            $alias = Get-Alias -Definition $commandName -ErrorAction SilentlyContinue
            $thebase.Alias = $alias.Name -Join ','

            ## fetch the description
            $thebase.Description = $thishelp.Description.Text

            ## fetch examples
            $thebase.Examples = Get-DbaTrimmedString -Text ($thishelp.Examples | Out-String -Width 200)

            ## fetch help link
            $thebase.Links = ($thishelp.relatedLinks).NavigationLink.Uri

            ## fetch the synopsis
            $thebase.Synopsis = $thishelp.Synopsis

            ## fetch the syntax
            $thebase.Syntax = Get-DbaTrimmedString -Text ($thishelp.Syntax | Out-String -Width 600)

            ## store notes
            $as = $thishelp.AlertSet | Out-String -Width 600

            ## fetch the tags
            $tags = $tagsrex.Match($as).Groups[1].Value
            if ($tags) {
                $thebase.Tags = $tags.Split(',').Trim()
            }
            ## fetch the author
            $author = $authorRex.Match($as).Groups[1].Value
            if ($author) {
                $thebase.Author = $author.Trim()
            }

            ## fetch MinimumVersion
            $MinimumVersion = $minverRex.Match($as).Groups[1].Value
            if ($MinimumVersion) {
                $thebase.MinimumVersion = $MinimumVersion.Trim()
            }

            ## fetch MaximumVersion
            $MaximumVersion = $maxverRex.Match($as).Groups[1].Value
            if ($MaximumVersion) {
                $thebase.MaximumVersion = $MaximumVersion.Trim()
            }

            ## fetch Parameters
            $parameters = $thishelp.parameters.parameter
            $command = Get-Command $commandName
            $params = @()
            foreach ($p in $parameters) {
                $paramAlias = $command.parameters[$p.Name].Aliases
                $paramDescr = Get-DbaTrimmedString -Text ($p.Description | Out-String -Width 200)
                $params += , @($p.Name, $paramDescr, ($paramAlias -Join ','), ($p.Required -eq $true), $p.PipelineInput, $p.DefaultValue)
            }

            $thebase.Params = $params

            [pscustomobject]$thebase
        }

        function Get-DbaIndex() {
            if ($Pscmdlet.ShouldProcess($dest, "Recreating index")) {
                $dbamodule = Get-Module -Name dbatools
                $allCommands = $dbamodule.ExportedCommands.Values | Where-Object CommandType -EQ 'Function'

                $helpcoll = New-Object System.Collections.Generic.List[System.Object]
                foreach ($command in $allCommands) {
                    $x = Get-DbaHelp "$command"
                    $helpcoll.Add($x)
                }
                # $dest = Get-DbatoolsConfigValue -Name 'Path.TagCache' -Fallback "$(Resolve-Path $PSScriptRoot\..)\dbatools-index.json"
                $dest = "$moduleDirectory\bin\dbatools-index.json"
                $helpcoll | ConvertTo-Json -Depth 4 | Out-File $dest -Encoding UTF8
            }
        }

        $moduleDirectory = (Get-Module -Name dbatools).ModuleBase
    }
    process {
        $Pattern = $Pattern.TrimEnd("s")
        $idxFile = "$moduleDirectory\bin\dbatools-index.json"
        if (!(Test-Path $idxFile) -or $Rebuild) {
            Write-Message -Level Verbose -Message "Rebuilding index into $idxFile"
            $swRebuild = [system.diagnostics.stopwatch]::StartNew()
            Get-DbaIndex
            Write-Message -Level Verbose -Message "Rebuild done in $($swRebuild.ElapsedMilliseconds)ms"
        }
        $consolidated = Get-Content -Raw $idxFile | ConvertFrom-Json
        $result = $consolidated
        if ($Pattern.Length -gt 0) {
            $result = $result | Where-Object { $_.PsObject.Properties.Value -like "*$Pattern*" }
        }

        if ($Tag.Length -gt 0) {
            foreach ($t in $Tag) {
                $result = $result | Where-Object Tags -Contains $t
            }
        }

        if ($Author.Length -gt 0) {
            $result = $result | Where-Object Author -Like "*$Author*"
        }

        if ($MinimumVersion.Length -gt 0) {
            $result = $result | Where-Object MinimumVersion -GE $MinimumVersion
        }

        if ($MaximumVersion.Length -gt 0) {
            $result = $result | Where-Object MaximumVersion -LE $MaximumVersion
        }

        Select-DefaultView -InputObject $result -Property CommandName, Synopsis
    }
}
tools\dbatools\functions\Find-DbaDatabase.ps1
#ValidationTags#Messaging#
function Find-DbaDatabase {
    <#
    .SYNOPSIS
        Find database/s on multiple servers that match criteria you input

    .DESCRIPTION
        Allows you to search SQL Server instances for database that have either the same name, owner or service broker guid.

        There a several reasons for the service broker guid not matching on a restored database primarily using alter database new broker. or turn off broker to return a guid of 0000-0000-0000-0000.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Credential object used to connect to the SQL Server as a different user

    .PARAMETER Property
        What you would like to search on. Either Database Name, Owner, or Service Broker GUID. Database name is the default.

    .PARAMETER Pattern
        Value that is searched for. This is a regular expression match but you can just use a plain ol string like 'dbareports'

    .PARAMETER Exact
        Search for an exact match instead of a pattern

    .PARAMETER Detailed
        Output all properties, will be depreciated in 1.0.0 release.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database
        Author: Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Find-DbaDatabase

    .EXAMPLE
        PS C:\> Find-DbaDatabase -SqlInstance "DEV01", "DEV02", "UAT01", "UAT02", "PROD01", "PROD02" -Pattern Report

        Returns all database from the SqlInstances that have a database with Report in the name

    .EXAMPLE
        PS C:\> Find-DbaDatabase -SqlInstance "DEV01", "DEV02", "UAT01", "UAT02", "PROD01", "PROD02" -Pattern TestDB -Exact | Select-Object *

        Returns all database from the SqlInstances that have a database named TestDB with a detailed output.

    .EXAMPLE
        PS C:\> Find-DbaDatabase -SqlInstance "DEV01", "DEV02", "UAT01", "UAT02", "PROD01", "PROD02" -Property ServiceBrokerGuid -Pattern '-faeb-495a-9898-f25a782835f5' | Select-Object *

        Returns all database from the SqlInstances that have the same Service Broker GUID with a detailed output

    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [ValidateSet('Name', 'ServiceBrokerGuid', 'Owner')]
        [string]$Property = 'Name',
        [parameter(Mandatory)]
        [string]$Pattern,
        [switch]$Exact,
        [switch]$Detailed,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter Detailed
    }
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($exact -eq $true) {
                $dbs = $server.Databases | Where-Object IsAccessible | Where-Object { $_.$property -eq $pattern }
            } else {
                try {
                    $dbs = $server.Databases | Where-Object IsAccessible | Where-Object { $_.$property.ToString() -match $pattern }
                } catch {
                    # they probably put asterisks thinking it's a like
                    $Pattern = $Pattern -replace '\*', ''
                    $Pattern = $Pattern -replace '\%', ''
                    $dbs = $server.Databases | Where-Object { $_.$property.ToString() -match $pattern }
                }
            }

            foreach ($db in $dbs) {

                $extendedproperties = @()
                foreach ($xp in $db.ExtendedProperties) {
                    $extendedproperties += [PSCustomObject]@{
                        Name  = $db.ExtendedProperties[$xp.Name].Name
                        Value = $db.ExtendedProperties[$xp.Name].Value
                    }
                }

                if ($extendedproperties.count -eq 0) { $extendedproperties = 0 }

                [PSCustomObject]@{
                    ComputerName       = $server.ComputerName
                    InstanceName       = $server.ServiceName
                    SqlInstance        = $server.Name
                    Name               = $db.Name
                    Size               = [dbasize]($db.Size * 1024 * 1024)
                    Owner              = $db.Owner
                    CreateDate         = $db.CreateDate
                    ServiceBrokerGuid  = $db.ServiceBrokerGuid
                    Tables             = ($db.Tables | Where-Object { $_.IsSystemObject -eq $false }).Count
                    StoredProcedures   = ($db.StoredProcedures | Where-Object { $_.IsSystemObject -eq $false }).Count
                    Views              = ($db.Views | Where-Object { $_.IsSystemObject -eq $false }).Count
                    ExtendedProperties = $extendedproperties
                }
            }
        }
    }
}
tools\dbatools\functions\Find-DbaDbGrowthEvent.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Find-DbaDbGrowthEvent {
    <#
    .SYNOPSIS
        Finds any database AutoGrow events in the Default Trace.

    .DESCRIPTION
        Finds any database AutoGrow events in the Default Trace.

        The following events are included:
        92 - Data File Auto Grow
        93 - Log File Auto Grow
        94 - Data File Auto Shrink
        95 - Log File Auto Shrink

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER EventType
        Provide a filter on growth event type to filter the results.

        Allowed values: Growth, Shrink

    .PARAMETER FileType
        Provide a filter on file type to filter the results.

        Allowed values: Data, Log

    .PARAMETER UseLocalTime
        Return the local time of the instance instead of converting to UTC.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: AutoGrow,Growth,Database
        Author: Aaron Nelson

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Query Extracted from SQL Server Management Studio (SSMS) 2016.

    .LINK
        https://dbatools.io/Find-DbaDatabaseGrowthEvent

    .EXAMPLE
        PS C:\> Find-DbaDatabaseGrowthEvent -SqlInstance localhost

        Returns any database AutoGrow events in the Default Trace with UTC time for the instance for every database on the localhost instance.

    .EXAMPLE
        PS C:\> Find-DbaDatabaseGrowthEvent -SqlInstance localhost -UseLocalTime

        Returns any database AutoGrow events in the Default Trace with the local time of the instance for every database on the localhost instance.

    .EXAMPLE
        PS C:\> Find-DbaDatabaseGrowthEvent -SqlInstance ServerA\SQL2016, ServerA\SQL2014

        Returns any database AutoGrow events in the Default Traces for every database on ServerA\sql2016 & ServerA\SQL2014.

    .EXAMPLE
        PS C:\> Find-DbaDatabaseGrowthEvent -SqlInstance ServerA\SQL2016 | Format-Table -AutoSize -Wrap

        Returns any database AutoGrow events in the Default Trace for every database on the ServerA\SQL2016 instance in a table format.

    .EXAMPLE
        PS C:\> Find-DbaDatabaseGrowthEvent -SqlInstance ServerA\SQL2016 -EventType Shrink

        Returns any database Auto Shrink events in the Default Trace for every database on the ServerA\SQL2016 instance.

    .EXAMPLE
        PS C:\> Find-DbaDatabaseGrowthEvent -SqlInstance ServerA\SQL2016 -EventType Growth -FileType Data

        Returns any database Auto Growth events on data files in the Default Trace for every database on the ServerA\SQL2016 instance.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [ValidateSet('Growth', 'Shrink')]
        [string]$EventType,
        [ValidateSet('Data', 'Log')]
        [string]$FileType,
        [switch]$UseLocalTime,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $eventClass = New-Object System.Collections.ArrayList
        92..95 | ForEach-Object { $null = $eventClass.Add($_) }

        if (Test-Bound 'EventType', 'FileType') {
            switch ($FileType) {
                'Data' {
                    <# should only contain events for data: 92 (grow), 94 (shrink) #>
                    $eventClass.Remove(93)
                    $eventClass.Remove(95)
                }
                'Log' {
                    <# should only contain events for log: 93 (grow), 95 (shrink) #>
                    $eventClass.Remove(92)
                    $eventClass.Remove(94)
                }
            }
            switch ($EventType) {
                'Growth' {
                    <# should only contain events for growth: 92 (data), 93 (log) #>
                    $eventClass.Remove(94)
                    $eventClass.Remove(95)
                }
                'Shrink' {
                    <# should only contain events for shrink: 94 (data), 95 (log) #>
                    $eventClass.Remove(92)
                    $eventClass.Remove(93)
                }
            }
        }

        $eventClassFilter = $eventClass -join ","

        $sqlTemplate = "
            BEGIN TRY
                IF (SELECT CONVERT(INT,[value_in_use]) FROM sys.configurations WHERE [name] = 'default trace enabled' ) = 1
                    BEGIN
                        DECLARE @curr_tracefilename VARCHAR(500);
                        DECLARE @base_tracefilename VARCHAR(500);
                        DECLARE @indx INT;

                        SELECT @curr_tracefilename = [path]
                        FROM sys.traces
                        WHERE is_default = 1 ;

                        SET @curr_tracefilename = REVERSE(@curr_tracefilename);
                        SELECT @indx  = PATINDEX('%\%', @curr_tracefilename);
                        SET @curr_tracefilename = REVERSE(@curr_tracefilename);
                        SET @base_tracefilename = LEFT( @curr_tracefilename,LEN(@curr_tracefilename) - @indx) + '\log.trc';

                        SELECT
                            SERVERPROPERTY('MachineName') AS ComputerName,
                            ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
                            SERVERPROPERTY('ServerName') AS SqlInstance,
                            CONVERT(INT,(DENSE_RANK() OVER (ORDER BY [StartTime] DESC))%2) AS OrderRank,
                                CONVERT(INT, [EventClass]) AS EventClass,
                            [DatabaseName],
                            [Filename],
                            CONVERT(INT,(Duration/1000)) AS Duration,
                            $(if (-not $UseLocalTime) { "
                            DATEADD (MINUTE, DATEDIFF(MINUTE, GETDATE(), GETUTCDATE()), [StartTime]) AS StartTime,  -- Convert to UTC time
                            DATEADD (MINUTE, DATEDIFF(MINUTE, GETDATE(), GETUTCDATE()), [EndTime]) AS EndTime,  -- Convert to UTC time"
                            }
                            else { "
                            [StartTime] AS StartTime,
                            [EndTime] AS EndTime,"
                            })
                            ([IntegerData]*8.0/1024) AS ChangeInSize,
                            ApplicationName,
                            HostName,
                            SessionLoginName,
                            SPID
                        FROM::fn_trace_gettable( @base_tracefilename, DEFAULT )
                        WHERE
                            [EventClass] IN ($eventClassFilter)
                            AND [ServerName] = @@SERVERNAME
                            AND [DatabaseName] IN (_DatabaseList_)
                        ORDER BY [StartTime] DESC;
                    END
                ELSE
                    SELECT
                        SERVERPROPERTY('MachineName') AS ComputerName,
                        ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
                        SERVERPROPERTY('ServerName') AS SqlInstance,
                        -100 AS [OrderRank],
                        -1 AS [OrderRank],
                        0 AS [EventClass],
                        0 [DatabaseName],
                        0 AS [Filename],
                        0 AS [Duration],
                        0 AS [StartTime],
                        0 AS [EndTime],
                        0 AS ChangeInSize,
                        0 AS [ApplicationName],
                        0 AS [HostName],
                        0 AS [SessionLoginName],
                        0 AS [SPID]
            END	TRY
            BEGIN CATCH
                SELECT
                    SERVERPROPERTY('MachineName') AS ComputerName,
                    ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
                    SERVERPROPERTY('ServerName') AS SqlInstance,
                    -100 AS [OrderRank],
                    -100 AS [OrderRank],
                    ERROR_NUMBER() AS [EventClass],
                    ERROR_SEVERITY() AS [DatabaseName],
                    ERROR_STATE() AS [Filename],
                    ERROR_MESSAGE() AS [Duration],
                    1 AS [StartTime],
                    1 AS [EndTime],
                    1 AS [ChangeInSize],
                    1 AS [ApplicationName],
                    1 AS [HostName],
                    1 AS [SessionLoginName],
                    1 AS [SPID]
            END CATCH"

        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Find-DbaDatabaseGrowthEvent
    }
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $dbs = $server.Databases

            if ($Database) {
                $dbs = $dbs | Where-Object Name -In $Database
            }

            if ($ExcludeDatabase) {
                $dbs = $dbs | Where-Object Name -NotIn $ExcludeDatabase
            }

            #Create dblist name in 'db1', 'db2' format
            $dbsList = "'$($($dbs | ForEach-Object {$_.Name}) -join "','")'"
            Write-Message -Level Verbose -Message "Executing query against $dbsList on $instance"

            $sql = $sqlTemplate -replace '_DatabaseList_', $dbsList
            Write-Message -Level Debug -Message "Executing SQL Statement:`n $sql"

            $defaults = 'ComputerName', 'InstanceName', 'SqlInstance', 'EventClass', 'DatabaseName', 'Filename', 'Duration', 'StartTime', 'EndTime', 'ChangeInSize', 'ApplicationName', 'HostName'

            try {
                Select-DefaultView -InputObject $server.Query($sql) -Property $defaults
            } catch {
                Stop-Function -Message "Issue collecting data on $server" -Target $server -ErrorRecord $_ -Exception $_.Exception.InnerException.InnerException.InnerException -Continue
            }
        }
    }
}
tools\dbatools\functions\Find-DbaDbUnusedIndex.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Find-DbaDbUnusedIndex {
    <#
    .SYNOPSIS
        Find unused indexes

    .DESCRIPTION
        This command will help you to find Unused indexes on a database or a list of databases

        For now only supported for CLUSTERED and NONCLUSTERED indexes

    .PARAMETER SqlInstance
        The SQL Server you want to check for unused indexes.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.

    .PARAMETER IgnoreUptime
        Less than 7 days uptime can mean that analysis of unused indexes is unreliable, and normally no results will be returned. By setting this option results will be returned even if the Instance has been running for less that 7 days.

    .PARAMETER InputObject
        Enables piping from Get-DbaDatabase

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Index
        Author: Aaron Nelson (@SQLvariant), SQLvariant.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Find-DbaDbUnusedIndex

    .EXAMPLE
        PS C:\> Find-DbaDbUnusedIndex -SqlInstance sql2016 -Database db1, db2

        Finds unused databases on db1 and db2 on sql2016

    .EXAMPLE
        PS C:\> Find-DbaDbUnusedIndex -SqlInstance sql2016 -SqlCredential $cred

        Finds unused databases on db1 and db2 on sql2016 using SQL Authentication to connect to the server

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sql2016 | Find-DbaDbUnusedIndex

        Finds unused databases on all databases on sql2016

       #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$IgnoreUptime,
        [Parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )
    begin {
        # Support Compression 2008+
        $sql = "SELECT  SERVERPROPERTY('MachineName') AS ComputerName,
        ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
        SERVERPROPERTY('ServerName') AS SqlInstance, DB_NAME(database_id) AS 'Database'
        ,s.name AS 'Schema'
        ,t.name AS 'Table'
        ,i.object_id AS ObjectId
        ,i.name AS 'IndexName'
        ,i.index_id as 'IndexId'
        ,i.type_desc as 'TypeDesc'
        ,user_seeks as 'UserSeeks'
        ,user_scans as 'UserScans'
        ,user_lookups  as 'UserLookups'
        ,user_updates  as 'UserUpdates'
        ,last_user_seek  as 'LastUserSeek'
        ,last_user_scan  as 'LastUserScan'
        ,last_user_lookup  as 'LastUserLookup'
        ,last_user_update  as 'LastUserUpdate'
        ,system_seeks  as 'SystemSeeks'
        ,system_scans  as 'SystemScans'
        ,system_lookups  as 'SystemLookup'
        ,system_updates  as 'SystemUpdates'
        ,last_system_seek  as 'LastSystemSeek'
        ,last_system_scan  as 'LastSystemScan'
        ,last_system_lookup  as 'LastSystemLookup'
        ,last_system_update as 'LastSystemUpdate'
        FROM sys.tables t
        JOIN sys.schemas s
            ON t.schema_id = s.schema_id
        JOIN sys.indexes i
            ON i.object_id = t.object_id LEFT OUTER
        JOIN sys.dm_db_index_usage_stats iu
            ON iu.object_id = i.object_id
                AND iu.index_id = i.index_id
        WHERE iu.database_id = DB_ID()
                AND OBJECTPROPERTY(i.[object_id], 'IsMSShipped') = 0
                AND user_seeks = 0
                AND user_scans = 0
                AND user_lookups = 0
                AND i.type_desc NOT IN ('HEAP', 'CLUSTERED COLUMNSTORE')"
    }

    process {
        if ($SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase
        }

        foreach ($db in $InputObject) {
            if ($db.Parent.Databases[$db].IsAccessible -eq $false) {
                Write-Message -Level Warning -Message "Database [$db] is not accessible."
                continue
            }

            $server = $db.Parent
            $instance = $server.Name

            if ($server.VersionMajor -lt 9) {
                Stop-Function -Message "This function does not support versions lower than SQL Server 2005 (v9)." -Continue
            }

            $lastRestart = $server.Databases['tempdb'].CreateDate
            $endDate = Get-Date -Date $lastRestart
            $diffDays = (New-TimeSpan -Start $endDate -End (Get-Date)).Days

            if ($diffDays -le 6) {
                if ($IgnoreUptime) {
                    Write-Message -Level Verbose -Message "The SQL Service was restarted on $lastRestart, which is not long enough for a solid evaluation."
                } else {
                    Stop-Function -Message "The SQL Service on $instance was restarted on $lastRestart, which is not long enough for a solid evaluation." -Continue
                }
            }

            <#
                Validate if server version is:
                    - sql 2012 and if have SP3 CU3 (Build 6537) or higher
                    - sql 2014 and if have SP2 (Build 5000) or higher
                If the major version is the same but the build is lower, throws the message
            #>

            if (($server.VersionMajor -eq 11 -and $server.BuildNumber -lt 6537) -or ($server.VersionMajor -eq 12 -and $server.BuildNumber -lt 5000)) {
                Stop-Function -Message "This SQL version has a known issue. Rebuilding an index clears any existing row entry from sys.dm_db_index_usage_stats for that index.`r`nPlease refer to connect item: https://support.microsoft.com/en-us/help/3160407/fix-sys-dm-db-index-usage-stats-missing-information-after-index-rebuil" -Continue
            }

            if ($diffDays -le 33) {
                Write-Message -Level Verbose -Message "The SQL Service on $instance was restarted on $lastRestart, which may not be long enough for a solid evaluation."
            }

            try {
                $db.Query($sql)
            } catch {
                Stop-Function -Message "Issue gathering indexes" -Category InvalidOperation -ErrorRecord $_ -Target $db
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Get-SqlUnusedIndex
    }
}
tools\dbatools\functions\Find-DbaDisabledIndex.ps1
function Find-DbaDisabledIndex {
    <#
    .SYNOPSIS
        Find Disabled indexes

    .DESCRIPTION
        This command will help you to find disabled indexes on a database or a list of databases.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.

    .PARAMETER NoClobber
        If this switch is enabled, the output file will not be overwritten.

    .PARAMETER Append
        If this switch is enabled, content will be appended to the output file.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Index
        Author: Jason Squires, sqlnotnull.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Find-DbadisabledIndex

    .EXAMPLE
        PS C:\> Find-DbaDisabledIndex -SqlInstance sql2005

        Generates the SQL statements to drop the selected disabled indexes on server "sql2005".

    .EXAMPLE
        PS C:\> Find-DbaDisabledIndex -SqlInstance sqlserver2016 -SqlCredential $cred

        Generates the SQL statements to drop the selected disabled indexes on server "sqlserver2016", using SQL Authentication to connect to the database.

    .EXAMPLE
        PS C:\> Find-DbaDisabledIndex -SqlInstance sqlserver2016 -Database db1, db2

        Generates the SQL Statement to drop selected indexes in databases db1 & db2 on server "sqlserver2016".

    .EXAMPLE
        PS C:\> Find-DbaDisabledIndex -SqlInstance sqlserver2016

        Generates the SQL statements to drop selected indexes on all user databases.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]
        $SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$NoClobber,
        [switch]$Append,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $sql = "
        SELECT DB_NAME() AS 'DatabaseName'
        ,s.name AS 'SchemaName'
        ,t.name AS 'TableName'
        ,i.object_id AS ObjectId
        ,i.name AS 'IndexName'
        ,i.index_id as 'IndexId'
        ,i.type_desc as 'TypeDesc'
        FROM sys.tables t
        JOIN sys.schemas s
            ON t.schema_id = s.schema_id
        JOIN sys.indexes i
            ON i.object_id = t.object_id
        WHERE i.is_disabled = 1"
    }
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential  -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($Database) {
                $databases = $server.Databases | Where-Object Name -in $database
            } else {
                $databases = $server.Databases | Where-Object IsAccessible -eq $true
            }

            if ($databases.Count -gt 0) {
                foreach ($db in $databases.name) {

                    if ($ExcludeDatabase -contains $db -or $null -eq $server.Databases[$db]) {
                        continue
                    }

                    try {
                        if ($PSCmdlet.ShouldProcess($db, "Getting disabled indexes")) {
                            Write-Message -Level Verbose -Message "Getting indexes from database '$db'."
                            Write-Message -Level Debug -Message "SQL Statement: $sql"
                            $disabledIndex = $server.Databases[$db].ExecuteWithResults($sql)

                            if ($disabledIndex.Tables[0].Rows.Count -gt 0) {
                                $results = $disabledIndex.Tables[0];
                                if ($results.Count -gt 0 -or !([string]::IsNullOrEmpty($results))) {
                                    foreach ($index in $results) {
                                        $index
                                    }
                                }
                            } else {
                                Write-Message -Level Verbose -Message "No Disabled indexes found!"
                            }
                        }
                    } catch {
                        Stop-Function -Message "Issue gathering indexes" -Category InvalidOperation -InnerErrorRecord $_ -Target $db
                    }
                }
            } else {
                Write-Message -Level Verbose -Message "There are no databases to analyse."
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-SqlDisabledIndex
    }
}
tools\dbatools\functions\Find-DbaDuplicateIndex.ps1
function Find-DbaDuplicateIndex {
    <#
    .SYNOPSIS
        Find duplicate and overlapping indexes.

    .DESCRIPTION
        This command will help you to find duplicate and overlapping indexes on a database or a list of databases.

        On SQL Server 2008 and higher, the IsFiltered property will also be checked

        Only supports CLUSTERED and NONCLUSTERED indexes.

        Output:
        TableName
        IndexName
        KeyColumns
        IncludedColumns
        IndexSizeMB
        IndexType
        CompressionDescription (When 2008+)
        [RowCount]
        IsDisabled
        IsFiltered (When 2008+)

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER IncludeOverlapping
        If this switch is enabled, indexes which are partially duplicated will be returned.

        Example: If the first key column is the same between two indexes, but one has included columns and the other not, this will be shown.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Index
        Author: Claudio Silva (@ClaudioESSilva)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Find-DbaDuplicateIndex

    .EXAMPLE
        PS C:\> Find-DbaDuplicateIndex -SqlInstance sql2005

        Returns duplicate indexes found on sql2005

    .EXAMPLE
        PS C:\> Find-DbaDuplicateIndex -SqlInstance sql2017 -SqlCredential sqladmin

        Finds exact duplicate indexes on all user databases present on sql2017, using SQL authentication.

    .EXAMPLE
        PS C:\> Find-DbaDuplicateIndex -SqlInstance sql2017 -Database db1, db2

        Finds exact duplicate indexes on the db1 and db2 databases.

    .EXAMPLE
        PS C:\> Find-DbaDuplicateIndex -SqlInstance sql2017 -IncludeOverlapping

        Finds both duplicate and overlapping indexes on all user databases.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [switch]$IncludeOverlapping,
        [switch]$EnableException
    )

    begin {
        $exactDuplicateQuery2005 = "
            WITH CTE_IndexCols
            AS (
                SELECT i.[object_id]
                    ,i.index_id
                    ,OBJECT_SCHEMA_NAME(i.[object_id]) AS SchemaName
                    ,OBJECT_NAME(i.[object_id]) AS TableName
                    ,NAME AS IndexName
                    ,ISNULL(STUFF((
                                SELECT ', ' + col.NAME + ' ' + CASE
                                        WHEN idxCol.is_descending_key = 1
                                            THEN 'DESC'
                                        ELSE 'ASC'
                                        END -- Include column order (ASC / DESC)
                                FROM sys.index_columns idxCol
                                INNER JOIN sys.columns col ON idxCol.[object_id] = col.[object_id]
                                    AND idxCol.column_id = col.column_id
                                WHERE i.[object_id] = idxCol.[object_id]
                                    AND i.index_id = idxCol.index_id
                                    AND idxCol.is_included_column = 0
                                ORDER BY idxCol.key_ordinal
                                FOR XML PATH('')
                                ), 1, 2, ''), '') AS KeyColumns
                    ,ISNULL(STUFF((
                                SELECT ', ' + col.NAME + ' ' + CASE
                                        WHEN idxCol.is_descending_key = 1
                                            THEN 'DESC'
                                        ELSE 'ASC'
                                        END -- Include column order (ASC / DESC)
                                FROM sys.index_columns idxCol
                                INNER JOIN sys.columns col ON idxCol.[object_id] = col.[object_id]
                                    AND idxCol.column_id = col.column_id
                                WHERE i.[object_id] = idxCol.[object_id]
                                    AND i.index_id = idxCol.index_id
                                    AND idxCol.is_included_column = 1
                                ORDER BY idxCol.key_ordinal
                                FOR XML PATH('')
                                ), 1, 2, ''), '') AS IncludedColumns
                    ,i.[type_desc] AS IndexType
                    ,i.is_disabled AS IsDisabled
                FROM sys.indexes AS i
                WHERE i.index_id > 0 -- Exclude HEAPS
                    AND i.[type_desc] IN (
                        'CLUSTERED'
                        ,'NONCLUSTERED'
                        )
                    AND OBJECT_SCHEMA_NAME(i.[object_id]) <> 'sys'
                )
                ,CTE_IndexSpace
            AS (
                SELECT s.[object_id]
                    ,s.index_id
                    ,SUM(s.[used_page_count]) * 8 / 1024.0 AS IndexSizeMB
                    ,SUM(p.[rows]) AS [RowCount]
                FROM sys.dm_db_partition_stats AS s
                INNER JOIN sys.partitions p WITH (NOLOCK) ON s.[partition_id] = p.[partition_id]
                    AND s.[object_id] = p.[object_id]
                    AND s.index_id = p.index_id
                WHERE s.index_id > 0 -- Exclude HEAPS
                    AND OBJECT_SCHEMA_NAME(s.[object_id]) <> 'sys'
                GROUP BY s.[object_id]
                    ,s.index_id
                )
            SELECT DB_NAME() AS DatabaseName
                ,CI1.SchemaName + '.' + CI1.TableName AS 'TableName'
                ,CI1.IndexName
                ,CI1.KeyColumns
                ,CI1.IncludedColumns
                ,CI1.IndexType
                ,COALESCE(CSPC.IndexSizeMB,0) AS 'IndexSizeMB'
                ,COALESCE(CSPC.[RowCount],0) AS 'RowCount'
                ,CI1.IsDisabled
            FROM CTE_IndexCols AS CI1
            LEFT JOIN CTE_IndexSpace AS CSPC ON CI1.[object_id] = CSPC.[object_id]
                AND CI1.index_id = CSPC.index_id
            WHERE EXISTS (
                    SELECT 1
                    FROM CTE_IndexCols CI2
                    WHERE CI1.SchemaName = CI2.SchemaName
                        AND CI1.TableName = CI2.TableName
                        AND CI1.KeyColumns = CI2.KeyColumns
                        AND CI1.IncludedColumns = CI2.IncludedColumns
                        AND CI1.IndexName <> CI2.IndexName
                    )"

        $overlappingQuery2005 = "
            WITH CTE_IndexCols
            AS (
                SELECT i.[object_id]
                    ,i.index_id
                    ,OBJECT_SCHEMA_NAME(i.[object_id]) AS SchemaName
                    ,OBJECT_NAME(i.[object_id]) AS TableName
                    ,NAME AS IndexName
                    ,ISNULL(STUFF((
                                SELECT ', ' + col.NAME + ' ' + CASE
                                        WHEN idxCol.is_descending_key = 1
                                            THEN 'DESC'
                                        ELSE 'ASC'
                                        END -- Include column order (ASC / DESC)
                                FROM sys.index_columns idxCol
                                INNER JOIN sys.columns col ON idxCol.[object_id] = col.[object_id]
                                    AND idxCol.column_id = col.column_id
                                WHERE i.[object_id] = idxCol.[object_id]
                                    AND i.index_id = idxCol.index_id
                                    AND idxCol.is_included_column = 0
                                ORDER BY idxCol.key_ordinal
                                FOR XML PATH('')
                                ), 1, 2, ''), '') AS KeyColumns
                    ,ISNULL(STUFF((
                                SELECT ', ' + col.NAME + ' ' + CASE
                                        WHEN idxCol.is_descending_key = 1
                                            THEN 'DESC'
                                        ELSE 'ASC'
                                        END -- Include column order (ASC / DESC)
                                FROM sys.index_columns idxCol
                                INNER JOIN sys.columns col ON idxCol.[object_id] = col.[object_id]
                                    AND idxCol.column_id = col.column_id
                                WHERE i.[object_id] = idxCol.[object_id]
                                    AND i.index_id = idxCol.index_id
                                    AND idxCol.is_included_column = 1
                                ORDER BY idxCol.key_ordinal
                                FOR XML PATH('')
                                ), 1, 2, ''), '') AS IncludedColumns
                    ,i.[type_desc] AS IndexType
                    ,i.is_disabled AS IsDisabled
                FROM sys.indexes AS i
                WHERE i.index_id > 0 -- Exclude HEAPS
                    AND i.[type_desc] IN (
                        'CLUSTERED'
                        ,'NONCLUSTERED'
                        )
                    AND OBJECT_SCHEMA_NAME(i.[object_id]) <> 'sys'
                )
                ,CTE_IndexSpace
            AS (
                SELECT s.[object_id]
                    ,s.index_id
                    ,SUM(s.[used_page_count]) * 8 / 1024.0 AS IndexSizeMB
                    ,SUM(p.[rows]) AS [RowCount]
                FROM sys.dm_db_partition_stats AS s
                INNER JOIN sys.partitions p WITH (NOLOCK) ON s.[partition_id] = p.[partition_id]
                    AND s.[object_id] = p.[object_id]
                    AND s.index_id = p.index_id
                WHERE s.index_id > 0 -- Exclude HEAPS
                    AND OBJECT_SCHEMA_NAME(s.[object_id]) <> 'sys'
                GROUP BY s.[object_id]
                    ,s.index_id
                )
            SELECT DB_NAME() AS DatabaseName
                ,CI1.SchemaName + '.' + CI1.TableName AS 'TableName'
                ,CI1.IndexName
                ,CI1.KeyColumns
                ,CI1.IncludedColumns
                ,CI1.IndexType
                ,COALESCE(CSPC.IndexSizeMB,0) AS 'IndexSizeMB'
                ,COALESCE(CSPC.[RowCount],0) AS 'RowCount'
                ,CI1.IsDisabled
            FROM CTE_IndexCols AS CI1
            LEFT JOIN CTE_IndexSpace AS CSPC ON CI1.[object_id] = CSPC.[object_id]
                AND CI1.index_id = CSPC.index_id
            WHERE EXISTS (
                    SELECT 1
                    FROM CTE_IndexCols CI2
                    WHERE CI1.SchemaName = CI2.SchemaName
                        AND CI1.TableName = CI2.TableName
                        AND (
                            (
                                CI1.KeyColumns LIKE CI2.KeyColumns + '%'
                                AND SUBSTRING(CI1.KeyColumns, LEN(CI2.KeyColumns) + 1, 1) = ' '
                                )
                            OR (
                                CI2.KeyColumns LIKE CI1.KeyColumns + '%'
                                AND SUBSTRING(CI2.KeyColumns, LEN(CI1.KeyColumns) + 1, 1) = ' '
                                )
                            )
                        AND CI1.IndexName <> CI2.IndexName
                    )"

        # Support Compression 2008+
        $exactDuplicateQuery = "
            WITH CTE_IndexCols
            AS (
                SELECT i.[object_id]
                    ,i.index_id
                    ,OBJECT_SCHEMA_NAME(i.[object_id]) AS SchemaName
                    ,OBJECT_NAME(i.[object_id]) AS TableName
                    ,NAME AS IndexName
                    ,ISNULL(STUFF((
                                SELECT ', ' + col.NAME + ' ' + CASE
                                        WHEN idxCol.is_descending_key = 1
                                            THEN 'DESC'
                                        ELSE 'ASC'
                                        END -- Include column order (ASC / DESC)
                                FROM sys.index_columns idxCol
                                INNER JOIN sys.columns col ON idxCol.[object_id] = col.[object_id]
                                    AND idxCol.column_id = col.column_id
                                WHERE i.[object_id] = idxCol.[object_id]
                                    AND i.index_id = idxCol.index_id
                                    AND idxCol.is_included_column = 0
                                ORDER BY idxCol.key_ordinal
                                FOR XML PATH('')
                                ), 1, 2, ''), '') AS KeyColumns
                    ,ISNULL(STUFF((
                                SELECT ', ' + col.NAME + ' ' + CASE
                                        WHEN idxCol.is_descending_key = 1
                                            THEN 'DESC'
                                        ELSE 'ASC'
                                        END -- Include column order (ASC / DESC)
                                FROM sys.index_columns idxCol
                                INNER JOIN sys.columns col ON idxCol.[object_id] = col.[object_id]
                                    AND idxCol.column_id = col.column_id
                                WHERE i.[object_id] = idxCol.[object_id]
                                    AND i.index_id = idxCol.index_id
                                    AND idxCol.is_included_column = 1
                                ORDER BY idxCol.key_ordinal
                                FOR XML PATH('')
                                ), 1, 2, ''), '') AS IncludedColumns
                    ,i.[type_desc] AS IndexType
                    ,i.is_disabled AS IsDisabled
                    ,i.has_filter AS IsFiltered
                FROM sys.indexes AS i
                WHERE i.index_id > 0 -- Exclude HEAPS
                    AND i.[type_desc] IN (
                        'CLUSTERED'
                        ,'NONCLUSTERED'
                        )
                    AND OBJECT_SCHEMA_NAME(i.[object_id]) <> 'sys'
                )
                ,CTE_IndexSpace
            AS (
                SELECT s.[object_id]
                    ,s.index_id
                    ,SUM(s.[used_page_count]) * 8 / 1024.0 AS IndexSizeMB
                    ,SUM(p.[rows]) AS [RowCount]
                    ,p.data_compression_desc AS CompressionDescription
                FROM sys.dm_db_partition_stats AS s
                INNER JOIN sys.partitions p WITH (NOLOCK) ON s.[partition_id] = p.[partition_id]
                    AND s.[object_id] = p.[object_id]
                    AND s.index_id = p.index_id
                WHERE s.index_id > 0 -- Exclude HEAPS
                    AND OBJECT_SCHEMA_NAME(s.[object_id]) <> 'sys'
                GROUP BY s.[object_id]
                    ,s.index_id
                    ,p.data_compression_desc
                )
            SELECT DB_NAME() AS DatabaseName
                ,CI1.SchemaName + '.' + CI1.TableName AS 'TableName'
                ,CI1.IndexName
                ,CI1.KeyColumns
                ,CI1.IncludedColumns
                ,CI1.IndexType
                ,COALESCE(CSPC.IndexSizeMB,0) AS 'IndexSizeMB'
                ,COALESCE(CSPC.CompressionDescription, 'NONE') AS 'CompressionDescription'
                ,COALESCE(CSPC.[RowCount],0) AS 'RowCount'
                ,CI1.IsDisabled
                ,CI1.IsFiltered
            FROM CTE_IndexCols AS CI1
            LEFT JOIN CTE_IndexSpace AS CSPC ON CI1.[object_id] = CSPC.[object_id]
                AND CI1.index_id = CSPC.index_id
            WHERE EXISTS (
                    SELECT 1
                    FROM CTE_IndexCols CI2
                    WHERE CI1.SchemaName = CI2.SchemaName
                        AND CI1.TableName = CI2.TableName
                        AND CI1.KeyColumns = CI2.KeyColumns
                        AND CI1.IncludedColumns = CI2.IncludedColumns
                        AND CI1.IsFiltered = CI2.IsFiltered
                        AND CI1.IndexName <> CI2.IndexName
                    )"

        $overlappingQuery = "
            WITH CTE_IndexCols AS
            (
                SELECT
                        i.[object_id]
                        ,i.index_id
                        ,OBJECT_SCHEMA_NAME(i.[object_id]) AS SchemaName
                        ,OBJECT_NAME(i.[object_id]) AS TableName
                        ,Name AS IndexName
                        ,ISNULL(STUFF((SELECT ', ' + col.NAME + ' ' + CASE
                                                                    WHEN idxCol.is_descending_key = 1 THEN 'DESC'
                                                                    ELSE 'ASC'
                                                                END -- Include column order (ASC / DESC)
                                FROM sys.index_columns idxCol
                                    INNER JOIN sys.columns col
                                    ON idxCol.[object_id] = col.[object_id]
                                    AND idxCol.column_id = col.column_id
                                WHERE i.[object_id] = idxCol.[object_id]
                                AND i.index_id = idxCol.index_id
                                AND idxCol.is_included_column = 0
                                ORDER BY idxCol.key_ordinal
                        FOR XML PATH('')), 1, 2, ''), '') AS KeyColumns
                        ,ISNULL(STUFF((SELECT ', ' + col.NAME + ' ' + CASE
                                                                    WHEN idxCol.is_descending_key = 1 THEN 'DESC'
                                                                    ELSE 'ASC'
                                                                END -- Include column order (ASC / DESC)
                                FROM sys.index_columns idxCol
                                    INNER JOIN sys.columns col
                                    ON idxCol.[object_id] = col.[object_id]
                                    AND idxCol.column_id = col.column_id
                                WHERE i.[object_id] = idxCol.[object_id]
                                AND i.index_id = idxCol.index_id
                                AND idxCol.is_included_column = 1
                                ORDER BY idxCol.key_ordinal
                        FOR XML PATH('')), 1, 2, ''), '') AS IncludedColumns
                        ,i.[type_desc] AS IndexType
                        ,i.is_disabled AS IsDisabled
                        ,i.has_filter AS IsFiltered
                FROM sys.indexes AS i
                WHERE i.index_id > 0 -- Exclude HEAPS
                AND i.[type_desc] IN ('CLUSTERED', 'NONCLUSTERED')
                AND OBJECT_SCHEMA_NAME(i.[object_id]) <> 'sys'
            ),
            CTE_IndexSpace AS
            (
            SELECT
                        s.[object_id]
                        ,s.index_id
                        ,SUM(s.[used_page_count]) * 8 / 1024.0 AS IndexSizeMB
                        ,SUM(p.[rows]) AS [RowCount]
                        ,p.data_compression_desc AS CompressionDescription
                FROM sys.dm_db_partition_stats AS s
                    INNER JOIN sys.partitions p WITH (NOLOCK)
                    ON s.[partition_id] = p.[partition_id]
                    AND s.[object_id] = p.[object_id]
                    AND s.index_id = p.index_id
                WHERE s.index_id > 0 -- Exclude HEAPS
                    AND OBJECT_SCHEMA_NAME(s.[object_id]) <> 'sys'
                GROUP BY s.[object_id], s.index_id, p.data_compression_desc
            )
            SELECT
                    DB_NAME() AS DatabaseName
                    ,CI1.SchemaName + '.' + CI1.TableName AS 'TableName'
                    ,CI1.IndexName
                    ,CI1.KeyColumns
                    ,CI1.IncludedColumns
                    ,CI1.IndexType
                    ,COALESCE(CSPC.IndexSizeMB,0) AS 'IndexSizeMB'
                    ,COALESCE(CSPC.CompressionDescription, 'NONE') AS 'CompressionDescription'
                    ,COALESCE(CSPC.[RowCount],0) AS 'RowCount'
                    ,CI1.IsDisabled
                    ,CI1.IsFiltered
            FROM CTE_IndexCols AS CI1
                LEFT JOIN CTE_IndexSpace AS CSPC
                ON CI1.[object_id] = CSPC.[object_id]
                AND CI1.index_id = CSPC.index_id
            WHERE EXISTS (SELECT 1
                            FROM CTE_IndexCols CI2
                        WHERE CI1.SchemaName = CI2.SchemaName
                            AND CI1.TableName = CI2.TableName
                            AND (
                                        (CI1.KeyColumns like CI2.KeyColumns + '%' and SUBSTRING(CI1.KeyColumns,LEN(CI2.KeyColumns)+1,1) = ' ')
                                    OR (CI2.KeyColumns like CI1.KeyColumns + '%' and SUBSTRING(CI2.KeyColumns,LEN(CI1.KeyColumns)+1,1) = ' ')
                                )
                            AND CI1.IsFiltered = CI2.IsFiltered
                            AND CI1.IndexName <> CI2.IndexName
                        )"
    }
    process {
        if (Test-FunctionInterrupt) { return }

        foreach ($instance in $sqlinstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($database) {
                $databases = $server.Databases | Where-Object Name -in $database
            } else {
                $databases = $server.Databases | Where-Object IsAccessible -eq $true
            }

            foreach ($db in $databases) {
                try {
                    Write-Message -Level Verbose -Message "Getting indexes from database '$db'."

                    $query = if ($server.versionMajor -eq 9) {
                        if ($IncludeOverlapping) { $overlappingQuery2005 }
                        else { $exactDuplicateQuery2005 }
                    } else {
                        if ($IncludeOverlapping) { $overlappingQuery }
                        else { $exactDuplicateQuery }
                    }

                    $db.Query($query)

                } catch {
                    Stop-Function -Message "Query failure" -Target $db
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-SqlDuplicateIndex
    }
}
tools\dbatools\functions\Find-DbaInstance.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Find-DbaInstance {
    <#
    .SYNOPSIS
        Search for SQL Server Instances.

    .DESCRIPTION
        This function searches for SQL Server Instances.

        It supports a variety of scans for this purpose which can be separated in two categories:
        - Discovery
        - Scan

        Discovery:
        This is where it compiles a list of computers / addresses to check.
        It supports several methods of generating such lists (including Active Directory lookup or IP Ranges), but also supports specifying a list of computers to check.
        - For details on discovery, see the documentation on the '-DiscoveryType' parameter
        - For details on explicitly providing a list, see the documentation on the '-ComputerName' parameter

        Scan:
        Once a list of computers has been provided, this command will execute a variety of actions to determine any instances present for each of them.
        This is described in more detail in the documentation on the '-ScanType' parameter.
        Additional parameters allow more granular control over individual scans (e.g. Credentials to use).

        Note on logging and auditing:
        The Discovery phase is un-problematic since it is non-intrusive, however during the scan phase, all targeted computers may be accessed repeatedly.
        This may cause issues with security teams, due to many logon events and possibly failed authentication.
        This action constitutes a network scan, which may be illegal depending on the nation you are in and whether you own the network you scan.
        If you are unsure whether you may use this command in your environment, check the detailed description on the '-ScanType' parameter and contact your IT security team for advice.

    .PARAMETER ComputerName
        The computer to scan. Can be a variety of input types, including text or the output of Get-ADComputer.
        Any extra instance information (such as connection strings or live sql server connections) beyond the computername will be discarded.

    .PARAMETER DiscoveryType
        The mechanisms to be used to discover instances.
        Supports any combination of:
        - Service Principal Name lookup ('Domain'; from Active Directory)
        - SQL Instance Enumeration ('DataSourceEnumeration'; same as SSMS uses)
        - IP Address range ('IPRange'; all IP Addresses will be scanned)

        SPN Lookup:
        The function tries to connect active directory to look up all computers with registered SQL Instances.
        Not all instances need to be registered properly, making this not 100% reliable.
        By default, your nearest Domain Controller is contacted for this scan.
        However it is possible to explicitly state the DC to contact using its DistinguishedName and the '-DomainController' parameter.
        If credentials were specified using the '-Credential' parameter, those same credentials are used to perform this lookup, allowing the scan of other domains.

        SQL Instance Enumeration:
        This uses the default UDP Broadcast based instance enumeration used by SSMS to detect instances.
        Note that the result from this is not used in the actual scan, but only to compile a list of computers to scan.
        To enable the same results for the scan, ensure that the 'Browser' scan is enabled.

        IP Address range:
        This 'Discovery' uses a range of IPAddresses and simply passes them on to be tested.
        See the 'Description' part of help on security issues of network scanning.
        By default, it will enumerate all ethernet network adapters on the local computer and scan the entire subnet they are on.
        By using the '-IpAddress' parameter, custom network ranges can be specified.

    .PARAMETER Credential
        The credentials to use on windows network connection.
        These credentials are used for:
        - Contact to domain controllers for SPN lookups (only if explicit Domain Controller is specified)
        - CIM/WMI contact to the scanned computers during the scan phase (see the '-ScanType' parameter documentation on affected scans).

    .PARAMETER SqlCredential
        The credentials used to connect to SqlInstances to during the scan phase.
        See the '-ScanType' parameter documentation on affected scans.

    .PARAMETER ScanType
    
        The scans are the individual methods used to retrieve information about the scanned computer and any potentially installed instances.
        This parameter is optional, by default all scans except for establishing an actual SQL connection are performed.
        Scans can be specified in any arbitrary combination, however at least one instance detecting scan needs to be specified in order for data to be returned.

        Scans:
         Browser
        - Tries discovering all instances via the browser service
        - This scan detects instances.
    
        SQLService
        - Tries listing all SQL Services using CIM/WMI
        - This scan uses credentials specified in the '-Credential' parameter if any.
        - This scan detects instances.
        - Success in this scan guarantees high confidence (See parameter '-MinimumConfidence' for details).
    
        SPN
        - Tries looking up the Service Principal Names for each instance
        - Will use the nearest Domain Controller by default
        - Target a specific domain controller using the '-DomainController' parameter
        - If using the '-DomainController' parameter, use the '-Credential' parameter to specify the credentials used to connect
    
        TCPPort
        - Tries connecting to the TCP Ports.
        - By default, port 1433 is connected to.
        - The parameter '-TCPPort' can be used to provide a list of port numbers to scan.
        - This scan detects possible instances. Since other services might bind to a given port, this is not the most reliable test.
        - This scan is also used to validate found SPNs if both scans are used in combination
   
        DNSResolve
        - Tries resolving the computername in DNS
    
        Ping
        - Tries pinging the computer. Failure will NOT terminate scans.
    
        SqlConnect
        - Tries to establish a SQL connection to the server
        - Uses windows credentials by default
        - Specify custom credentials using the '-SqlCredential' parameter
        - This scan is not used by default
        - Success in this scan guarantees high confidence (See parameter '-MinimumConfidence' for details).
    
        All
        - All of the above
    
    .PARAMETER IpAddress
        This parameter can be used to override the defaults for the IPRange discovery.
        This parameter accepts a list of strings supporting any combination of:
        - Plain IP Addresses (e.g.: "10.1.1.1")
        - IP Address Ranges (e.g.: "10.1.1.1-10.1.1.5")
        - IP Address & Subnet Mask (e.g.: "10.1.1.1/255.255.255.0")
        - IP Address & Subnet Length: (e.g.: "10.1.1.1/24)
        Overlapping addresses will not result in duplicate scans.

    .PARAMETER DomainController
        The domain controller to contact for SPN lookups / searches.
        Uses the credentials from the '-Credential' parameter if specified.

    .PARAMETER TCPPort
        The ports to scan in the TCP Port Scan method.
        Defaults to 1433.

    .PARAMETER MinimumConfidence
        This command tries to discover instances, which isn't always a sure thing.
        Depending on the number and type of scans completed, we have different levels of confidence in our results.
        By default, we will return anything that we have at least a low confidence of being an instance.
        These are the confidence levels we support and how they are determined:
        - High: Established SQL Connection (including rejection for bad credentials) or service scan.
        - Medium: Browser reply or a combination of TCPConnect _and_ SPN test.
        - Low: Either TCPConnect _or_ SPN
        - None: Computer existence could be verified, but no sign of an SQL Instance

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Instance, Connect, SqlServer
        Author: Scott Sutherland, 2018 NetSPI | Friedrich Weinmann (@FredWeinmann)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Outside resources used and modified:
        https://gallery.technet.microsoft.com/scriptcenter/List-the-IP-addresses-in-a-60c5bb6b

    .LINK
        https://dbatools.io/Find-DbaInstance

    .EXAMPLE
        PS C:\> Find-DbaInstance -DiscoveryType Domain, DataSourceEnumeration

        Performs a network search for SQL Instances by:
        - Looking up the Service Principal Names of computers in active directory
        - Using the UDP broadcast based auto-discovery of SSMS
        After that it will extensively scan all hosts thus discovered for instances.

    .EXAMPLE
        PS C:\> Find-DbaInstance -DiscoveryType All

        Performs a network search for SQL Instances, using all discovery protocols:
        - Active directory search for Service Principal Names
        - SQL Instance Enumeration (same as SSMS does)
        - All IPAddresses in the current computer's subnets of all connected network interfaces
        Note: This scan will take a long time, due to including the IP Scan

    .EXAMPLE
        PS C:\> Get-ADComputer -Filter "*" | Find-DbaInstance

        Scans all computers in the domain for SQL Instances, using a deep probe:
        - Tries resolving the name in DNS
        - Tries pinging the computer
        - Tries listing all SQL Services using CIM/WMI
        - Tries discovering all instances via the browser service
        - Tries connecting to the default TCP Port (1433)
        - Tries connecting to the TCP port of each discovered instance
        - Tries to establish a SQL connection to the server using default windows credentials
        - Tries looking up the Service Principal Names for each instance

    .EXAMPLE
        PS C:\> Get-Content .\servers.txt | Find-DbaInstance -SqlCredential $cred -ScanType Browser, SqlConnect

        Reads all servers from the servers.txt file (one server per line),
        then scans each of them for instances using the browser service
        and finally attempts to connect to each instance found using the specified credentials.
        then scans each of them for instances using the browser service and SqlService

    .EXAMPLE
        PS C:\> Find-DbaInstance -ComputerName localhost | Get-DbaDatabase | Format-Table -Wrap

        Scans localhost for instances using the browser service, traverses all instances for all databases and displays all information in a formatted table.

    .EXAMPLE
        PS C:\> Find-DbaInstance -ComputerName localhost | Get-DbaDatabase | Select-Object SqlInstance, Name, Status, RecoveryModel, SizeMB, Compatibility, Owner, LastFullBackup, LastDiffBackup, LastLogBackup | Format-Table -Wrap

        Scans localhost for instances using the browser service, traverses all instances for all databases and displays a subset of the important information in a formatted table.

        Using this method reguarly is not recommended. Use Get-DbaService or Get-DbaCmsRegServer instead.
    #>
    [CmdletBinding()]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseApprovedVerbs", "", Justification = "Internal functions are ignored")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseOutputTypeCorrectly", "", Justification = "PSSA Rule Ignored by BOH")]
    param (
        [Parameter(Mandatory, ParameterSetName = 'Computer', ValueFromPipeline)]
        [DbaInstance[]]$ComputerName,
        [Parameter(Mandatory, ParameterSetName = 'Discover')]
        [Sqlcollaborative.Dbatools.Discovery.DbaInstanceDiscoveryType]$DiscoveryType,
        [System.Management.Automation.PSCredential]$Credential,
        [System.Management.Automation.PSCredential]$SqlCredential,
        [ValidateSet('Default', 'SQLService', 'Browser', 'TCPPort', 'All', 'SPN', 'Ping', 'SqlConnect', 'DNSResolve')]
        [Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType[]]$ScanType = "Default",
        [Parameter(ParameterSetName = 'Discover')]
        [string[]]$IpAddress,
        [string]$DomainController,
        [int[]]$TCPPort = 1433,
        [Sqlcollaborative.Dbatools.Discovery.DbaInstanceConfidenceLevel]$MinimumConfidence = 'Low',
        [switch]$EnableException
    )

    begin {

        #region Utility Functions
        function Test-SqlInstance {
            <#
            .SYNOPSIS
                Performs the actual scanning logic

            .DESCRIPTION
                Performs the actual scanning logic
                Each potential target is accessed using the specified scan routines.

            .PARAMETER Target
                The target to scan.

            .EXAMPLE
                PS C:\> Test-SqlInstance
        #>
            [CmdletBinding()]
            param (
                [Parameter(ValueFromPipeline)][DbaInstance[]]$Target,
                [PSCredential]$Credential,
                [PSCredential]$SqlCredential,
                [Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType]$ScanType,
                [string]$DomainController,
                [int[]]$TCPPort = 1433,
                [Sqlcollaborative.Dbatools.Discovery.DbaInstanceConfidenceLevel]$MinimumConfidence,
                [switch]$EnableException
            )

            begin {
                [System.Collections.ArrayList]$computersScanned = @()
            }

            process {
                foreach ($computer in $Target) {
                    if ($computersScanned.Contains($computer.ComputerName)) {
                        continue
                    } else {
                        $null = $computersScanned.Add($computer.ComputerName)
                    }
                    Write-Message -Level Verbose -Message "Processing: $($computer)" -Target $computer -FunctionName Find-DbaInstance

                    #region Null variables to prevent scope lookup on conditional existence
                    $resolution = $null
                    $pingReply = $null
                    $sPNs = @()
                    $ports = @()
                    $browseResult = $null
                    $services = @()
                    #Variable marked as unused by PSScriptAnalyzer
                    #$serverObject = $null
                    #$browseFailed = $false
                    #endregion Null variables to prevent scope lookup on conditional existence

                    #region Gather data
                    if ($ScanType -band [Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType]::DNSResolve) {
                        try { $resolution = [System.Net.Dns]::GetHostEntry($computer.ComputerName) }
                        catch {
                            # here to avoid an empty catch
                            $null = 1
                        }
                    }

                    if ($ScanType -band [Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType]::Ping) {
                        $ping = New-Object System.Net.NetworkInformation.Ping
                        try { $pingReply = $ping.Send($computer.ComputerName) }
                        catch {
                            # here to avoid an empty catch
                            $null = 1
                        }
                    }

                    if ($ScanType -band [Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType]::SPN) {
                        $computerByName = $computer.ComputerName
                        if ($resolution.HostName) { $computerByName = $resolution.HostName }
                        if ($computerByName -notmatch "$([dbargx]::IPv4)|$([dbargx]::IPv6)") {
                            try { $sPNs = Get-DomainSPN -DomainController $DomainController -Credential $Credential -ComputerName $computerByName -GetSPN }
                            catch {
                                # here to avoid an empty catch
                                $null = 1
                            }
                        }
                    }

                    # $ports required for all scans
                    $ports = $TCPPort | Test-TcpPort -ComputerName $computer
                    
                    if ($ScanType -band [Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType]::Browser) {
                        try {
                            $browseResult = Get-SQLInstanceBrowserUDP -ComputerName $computer -EnableException
                        } catch {
                            # here to avoid an empty catch
                            $null = 1
                        }
                    }

                    if ($ScanType -band [Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType]::SqlService) {
                        if ($Credential) { $services = Get-DbaService -ComputerName $computer -Credential $Credential -EnableException -ErrorAction Ignore -WarningAction SilentlyCOntinue }
                        else { $services = Get-DbaService -ComputerName $computer -ErrorAction Ignore -WarningAction SilentlyContinue }
                    }
                    #endregion Gather data

                    #region Gather list of found instance indicators
                    $instanceNames = @()
                    if ($Services) {
                        $Services | Select-Object -ExpandProperty InstanceName -Unique | Where-Object { $_ -and ($instanceNames -notcontains $_) } | ForEach-Object {
                            $instanceNames += $_
                        }
                    }
                    if ($browseResult) {
                        $browseResult | Select-Object -ExpandProperty InstanceName -Unique | Where-Object { $_ -and ($instanceNames -notcontains $_) } | ForEach-Object {
                            $instanceNames += $_
                        }
                    }

                    $portsDetected = @()
                    foreach ($portResult in $ports) {
                        if ($portResult.IsOpen) { $portsDetected += $portResult.Port }
                    }
                    foreach ($sPN in $sPNs) {
                        try { $inst = $sPN.Split(':')[1] }
                        catch { continue }

                        try {
                            [int]$portNumber = $inst
                            if ($portNumber -and ($portsDetected -notcontains $portNumber)) {
                                $portsDetected += $portNumber
                            }
                        } catch {
                            if ($inst -and ($instanceNames -notcontains $inst)) {
                                $instanceNames += $inst
                            }
                        }
                    }
                    #endregion Gather list of found instance indicators

                    #region Case: Nothing found
                    if ((-not $instanceNames) -and (-not $portsDetected)) {
                        if ($resolution -or ($pingReply.Status -like "Success")) {
                            if ($MinimumConfidence -eq [Sqlcollaborative.Dbatools.Discovery.DbaInstanceConfidenceLevel]::None) {
                                New-Object Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport -Property @{
                                    MachineName  = $computer.ComputerName
                                    ComputerName = $computer.ComputerName
                                    Ping         = $pingReply.Status -like 'Success'
                                }
                            } else {
                                Write-Message -Level Verbose -Message "Computer $computer could be contacted, but no trace of an SQL Instance was found. Skipping..." -Target $computer -FunctionName Find-DbaInstance
                            }
                        } else {
                            Write-Message -Level Verbose -Message "Computer $computer could not be contacted, skipping." -Target $computer -FunctionName Find-DbaInstance
                        }

                        continue
                    }
                    #endregion Case: Nothing found

                    [System.Collections.ArrayList]$masterList = @()

                    #region Case: Named instance found
                    foreach ($instance in $instanceNames) {
                        $object = New-Object Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport
                        $object.MachineName = $computer.ComputerName
                        $object.ComputerName = $computer.ComputerName
                        $object.InstanceName = $instance
                        $object.DnsResolution = $resolution
                        $object.Ping = $pingReply.Status -like 'Success'
                        $object.ScanTypes = $ScanType
                        $object.Services = $services | Where-Object InstanceName -EQ $instance
                        $object.SystemServices = $services | Where-Object { -not $_.InstanceName }
                        $object.SPNs = $sPNs

                        if ($result = $browseResult | Where-Object InstanceName -EQ $instance) {
                            $object.BrowseReply = $result
                        }
                        if ($ports) {
                            $object.PortsScanned = $ports
                        }

                        if ($object.BrowseReply) {
                            $object.Confidence = 'Medium'
                            if ($object.BrowseReply.TCPPort) {
                                $object.Port = $object.BrowseReply.TCPPort

                                $object.PortsScanned | Where-Object Port -EQ $object.Port | ForEach-Object {
                                    $object.TcpConnected = $_.IsOpen
                                }
                            }
                        }
                        if ($object.Services) {
                            $object.Confidence = 'High'

                            $engine = $object.Services | Where-Object ServiceType -EQ "Engine"
                            switch ($engine.State) {
                                "Running" { $object.Availability = 'Available' }
                                "Stopped" { $object.Availability = 'Unavailable' }
                                default { $object.Availability = 'Unknown' }
                            }
                        }

                        $object.Timestamp = Get-Date

                        $masterList += $object
                    }
                    #endregion Case: Named instance found

                    #region Case: Port number found
                    foreach ($port in $portsDetected) {
                        if ($masterList.Port -contains $port) { continue }

                        $object = New-Object Sqlcollaborative.Dbatools.Discovery.DbaInstanceReport
                        $object.MachineName = $computer.ComputerName
                        $object.ComputerName = $computer.ComputerName
                        $object.Port = $port
                        $object.DnsResolution = $resolution
                        $object.Ping = $pingReply.Status -like 'Success'
                        $object.ScanTypes = $ScanType
                        $object.SystemServices = $services | Where-Object { -not $_.InstanceName }
                        $object.SPNs = $sPNs
                        $object.Confidence = 'Low'
                        if ($ports) {
                            $object.PortsScanned = $ports

                            if (($ports | Where-Object IsOpen).Port -eq 1433) {
                                $object.Confidence = 'Medium'
                            }
                        }

                        if (($ports.Port -contains $port) -and ($sPNs | Where-Object { $_ -like "*:$port" })) {
                            $object.Confidence = 'Medium'
                        }

                        $object.PortsScanned | Where-Object Port -EQ $object.Port | ForEach-Object {
                            $object.TcpConnected = $_.IsOpen
                        }
                        $object.Timestamp = Get-Date

                        if ($masterList.SqlInstance -contains $object.SqlInstance) {
                            continue
                        }

                        $masterList += $object
                    }
                    #endregion Case: Port number found
                    
                    if ($ScanType -band [Sqlcollaborative.Dbatools.Discovery.DbaInstanceScanType]::SqlConnect) {
                        $instanceHash = @{ }
                        $toDelete = @()
                        foreach ($dataSet in $masterList) {
                            try {
                                $server = Connect-SqlInstance -SqlInstance $dataSet.FullSmoName -SqlCredential $SqlCredential
                                $dataSet.SqlConnected = $true
                                $dataSet.Confidence = 'High'

                                # Remove duplicates
                                if ($instanceHash.ContainsKey($server.DomainInstanceName)) {
                                    $toDelete += $dataSet
                                } else {
                                    $instanceHash[$server.DomainInstanceName] = $dataSet

                                    try {
                                        $dataSet.MachineName = $server.ComputerNamePhysicalNetBIOS
                                    } catch {
                                        # here to avoid an empty catch
                                        $null = 1
                                    }
                                }
                            } catch {
                                # Error class definitions
                                # https://docs.microsoft.com/en-us/sql/relational-databases/errors-events/database-engine-error-severities
                                # 24 or less means an instance was found, but had some issues

                                #region Processing error (Access denied, server error, ...)
                                if ($_.Exception.InnerException.Errors.Class -lt 25) {
                                    # There IS an SQL Instance and it listened to network traffic
                                    $dataSet.SqlConnected = $true
                                    $dataSet.Confidence = 'High'
                                }
                                #endregion Processing error (Access denied, server error, ...)

                                #region Other connection errors
                                else {
                                    $dataSet.SqlConnected = $false
                                }
                                #endregion Other connection errors
                            }
                        }

                        foreach ($item in $toDelete) {
                            $masterList.Remove($item)
                        }
                    }

                    $masterList
                }
            }
        }

        function Get-DomainSPN {
            <#
            .SYNOPSIS
                Returns all computernames with registered MSSQL SPNs.

            .DESCRIPTION
                Returns all computernames with registered MSSQL SPNs.

            .PARAMETER DomainController
                The domain controller to ask.

            .PARAMETER Credential
                The credentials to use while asking.

            .PARAMETER ComputerName
                Filter by computername

            .PARAMETER GetSPN
                Returns the service SPNs instead of the hostname

            .EXAMPLE
                PS C:\> Get-DomainSPN -DomainController $DomainController -Credential $Credential

                Returns all computernames with MSQL SPNs known to $DomainController, assuming credentials are valid.
        #>
            [CmdletBinding()]
            param (
                [string]$DomainController,
                [Pscredential]$Credential,
                [string]$ComputerName = "*",
                [switch]$GetSPN
            )

            try {
                if ($DomainController) {
                    if ($Credential) {
                        $entry = New-Object -TypeName System.DirectoryServices.DirectoryEntry -ArgumentList "LDAP://$DomainController", $Credential.UserName, $Credential.GetNetworkCredential().Password
                    } else {
                        $entry = New-Object -TypeName System.DirectoryServices.DirectoryEntry -ArgumentList "LDAP://$DomainController"
                    }
                } else {
                    $entry = [ADSI]''
                }
                $objSearcher = New-Object -TypeName System.DirectoryServices.DirectorySearcher -ArgumentList $entry

                $objSearcher.PageSize = 200
                $objSearcher.Filter = "(&(objectcategory=computer)(servicePrincipalName=MSSQLsvc*)(|(name=$ComputerName)(dnshostname=$ComputerName)))"
                $objSearcher.SearchScope = 'Subtree'

                $results = $objSearcher.FindAll()
                foreach ($computer in $results) {
                    if ($GetSPN) {
                        $computer.Properties["serviceprincipalname"] | Where-Object { $_ -like "MSSQLsvc*:*" }
                    } else {
                        if ($computer.Properties["dnshostname"]) {
                            $computer.Properties["dnshostname"][0]
                        } else {
                            $computer.Properties["name"][0]
                        }
                    }
                }
            } catch {
                throw
            }
        }

        function Get-SQLInstanceBrowserUDP {
            <#
            .SYNOPSIS
                Requests a list of instances from the browser service.

            .DESCRIPTION
                Requests a list of instances from the browser service.

            .PARAMETER ComputerName
                Computer name or IP address to enumerate SQL Instance from.

            .PARAMETER UDPTimeOut
                Timeout in seconds. Longer timeout = more accurate.

            .PARAMETER EnableException
                By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
                This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
                Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

            .EXAMPLE
                PS C:\> Get-SQLInstanceBrowserUDP -ComputerName 'sql2017'

                Contacts the browsing service on sql2017 and requests its instance information.

            .NOTES
                Original Author: Eric Gruber
                Editors:
                - Scott Sutherland (Pipeline and timeout mods)
                - Friedrich Weinmann (Cleanup & dbatools Standardization)

        #>
            [CmdletBinding()]
            param (
                [Parameter(Mandatory, ValueFromPipeline)][DbaInstance[]]$ComputerName,
                [int]$UDPTimeOut = 2,
                [switch]$EnableException
            )

            process {
                foreach ($computer in $ComputerName) {
                    try {
                        #region Connect to browser service and receive response
                        $UDPClient = New-Object -TypeName System.Net.Sockets.Udpclient
                        $UDPClient.Client.ReceiveTimeout = $UDPTimeOut * 1000
                        $UDPClient.Connect($computer.ComputerName, 1434)
                        $UDPPacket = 0x03
                        $UDPEndpoint = New-Object -TypeName System.Net.IpEndPoint -ArgumentList ([System.Net.Ipaddress]::Any, 0)
                        $UDPClient.Client.Blocking = $true
                        [void]$UDPClient.Send($UDPPacket, $UDPPacket.Length)
                        $BytesRecived = $UDPClient.Receive([ref]$UDPEndpoint)
                        # Skip first three characters, since those contain trash data (SSRP metadata)
                        #$Response = [System.Text.Encoding]::ASCII.GetString($BytesRecived[3..($BytesRecived.Length - 1)])
                        $Response = [System.Text.Encoding]::ASCII.GetString($BytesRecived)
                        #endregion Connect to browser service and receive response

                        #region Parse Output
                        $Response | Select-String "(ServerName;(\w+);InstanceName;(\w+);IsClustered;(\w+);Version;(\d+\.\d+\.\d+\.\d+);(tcp;(\d+)){0,1})" -AllMatches | Select-Object -ExpandProperty Matches | ForEach-Object {
                            $obj = New-Object Sqlcollaborative.Dbatools.Discovery.DbaBrowserReply -Property @{
                                MachineName  = $computer.ComputerName
                                ComputerName = $_.Groups[2].Value
                                SqlInstance  = "$($_.Groups[2].Value)\$($_.Groups[3].Value)"
                                InstanceName = $_.Groups[3].Value
                                Version      = $_.Groups[5].Value
                                IsClustered  = "Yes" -eq $_.Groups[4].Value
                            }
                            if ($_.Groups[7].Success) {
                                $obj.TCPPort = $_.Groups[7].Value
                            }
                            $obj
                        }
                        #endregion Parse Output

                        $UDPClient.Close()
                    } catch {
                        try {
                            $UDPClient.Close()
                        } catch {
                            # here to avoid an empty catch
                            $null = 1
                        }

                        if ($EnableException) { throw }
                    }
                }
            }
        }

        function Test-TcpPort {
            <#
            .SYNOPSIS
                Tests whether a TCP Port is open or not.

            .DESCRIPTION
                Tests whether a TCP Port is open or not.

            .PARAMETER ComputerName
                The name of the computer to scan.

            .PARAMETER Port
                The port(s) to scan.

            .EXAMPLE
                PS C:\> $ports | Test-TcpPort -ComputerName "foo"

                Tests for each port in $ports whether the TCP port is open on computer "foo"
        #>
            [CmdletBinding()]
            param (
                [DbaInstance]$ComputerName,
                [Parameter(ValueFromPipeline)][int[]]$Port
            )

            begin {
                $client = New-Object Net.Sockets.TcpClient
            }
            process {
                foreach ($item in $Port) {
                    try {
                        $client.Connect($ComputerName.ComputerName, $item)
                        if ($client.Connected) {
                            $client.Close()
                            New-Object -TypeName Sqlcollaborative.Dbatools.Discovery.DbaPortReport -ArgumentList $ComputerName.ComputerName, $item, $true
                        } else {
                            New-Object -TypeName Sqlcollaborative.Dbatools.Discovery.DbaPortReport -ArgumentList $ComputerName.ComputerName, $item, $false
                        }
                    } catch {
                        New-Object -TypeName Sqlcollaborative.Dbatools.Discovery.DbaPortReport -ArgumentList $ComputerName.ComputerName, $item, $false
                    }
                }
            }
        }

        function Get-IPrange {
            <#
            .SYNOPSIS
                Get the IP addresses in a range

            .DESCRIPTION
                A detailed description of the Get-IPrange function.

            .PARAMETER Start
                A description of the Start parameter.

            .PARAMETER End
                A description of the End parameter.

            .PARAMETER IPAddress
                A description of the IPAddress parameter.

            .PARAMETER Mask
                A description of the Mask parameter.

            .PARAMETER Cidr
                A description of the Cidr parameter.

            .EXAMPLE
                Get-IPrange -Start 192.168.8.2 -End 192.168.8.20

            .EXAMPLE
                Get-IPrange -IPAddress 192.168.8.2 -Mask 255.255.255.0

            .EXAMPLE
                Get-IPrange -IPAddress 192.168.8.3 -Cidr 24

            .NOTES
                Author: BarryCWT
                Reference: https://gallery.technet.microsoft.com/scriptcenter/List-the-IP-addresses-in-a-60c5bb6b
        #>

            param
            (
                [string]$Start,
                [string]$End,
                [string]$IPAddress,
                [string]$Mask,
                [int]$Cidr
            )

            function IP-toINT64 {
                param ($ip)

                $octets = $ip.split(".")
                return [int64]([int64]$octets[0] * 16777216 + [int64]$octets[1] * 65536 + [int64]$octets[2] * 256 + [int64]$octets[3])
            }

            function INT64-toIP {
                param ([int64]$int)

                return ([System.Net.IPAddress](([math]::truncate($int / 16777216)).tostring() + "." + ([math]::truncate(($int % 16777216) / 65536)).tostring() + "." + ([math]::truncate(($int % 65536) / 256)).tostring() + "." + ([math]::truncate($int % 256)).tostring()))
            }

            if ($Cidr) {
                $maskaddr = [Net.IPAddress]::Parse((INT64-toIP -int ([convert]::ToInt64(("1" * $Cidr + "0" * (32 - $Cidr)), 2))))
            }
            if ($Mask) {
                $maskaddr = [Net.IPAddress]::Parse($Mask)
            }
            if ($IPAddress) {
                $ipaddr = [Net.IPAddress]::Parse($IPAddress)
                $networkaddr = new-object net.ipaddress ($maskaddr.address -band $ipaddr.address)
                $broadcastaddr = new-object net.ipaddress (([system.net.ipaddress]::parse("255.255.255.255").address -bxor $maskaddr.address -bor $networkaddr.address))
                $startaddr = IP-toINT64 -ip $networkaddr.ipaddresstostring
                $endaddr = IP-toINT64 -ip $broadcastaddr.ipaddresstostring
            } else {
                $startaddr = IP-toINT64 -ip $Start
                $endaddr = IP-toINT64 -ip $End
            }

            for ($i = $startaddr; $i -le $endaddr; $i++) {
                INT64-toIP -int $i
            }
        }

        function Resolve-IPRange {
            <#
            .SYNOPSIS
                Returns a number of IPAddresses based on range specified.

            .DESCRIPTION
                Returns a number of IPAddresses based on range specified.
                Warning: A too large range can lead to memory exceptions.

                Scans subnet of active computer if no address is specified.

            .PARAMETER IpAddress
                The address / range / mask / cidr to scan. Example input:
                - 10.1.1.1
                - 10.1.1.1/24
                - 10.1.1.1-10.1.1.254
                - 10.1.1.1/255.255.255.0
        #>
            [CmdletBinding()]
            param (
                [AllowEmptyString()][string]$IpAddress
            )

            #region Scan defined range
            if ($IpAddress) {
                #region Determine processing mode
                $mode = 'Unknown'
                if ($IpAddress -like "*/*") {
                    $parts = $IpAddress.Split("/")

                    $address = $parts[0]
                    if ($parts[1] -match ([dbargx]::IPv4)) {
                        $mask = $parts[1]
                        $mode = 'Mask'
                    } elseif ($parts[1] -as [int]) {
                        $cidr = [int]$parts[1]

                        if (($cidr -lt 8) -or ($cidr -gt 31)) {
                            throw "$IpAddress does not contain a valid cidr mask!"
                        }

                        $mode = 'CIDR'
                    } else {
                        throw "$IpAddress is not a valid IP Range!"
                    }
                } elseif ($IpAddress -like "*-*") {
                    $rangeStart = $IpAddress.Split("-")[0]
                    $rangeEnd = $IpAddress.Split("-")[1]

                    if ($rangeStart -notmatch ([dbargx]::IPv4)) {
                        throw "$IpAddress is not a valid IP Range!"
                    }
                    if ($rangeEnd -notmatch ([dbargx]::IPv4)) {
                        throw "$IpAddress is not a valid IP Range!"
                    }

                    $mode = 'Range'
                } else {
                    if ($IpAddress -notmatch ([dbargx]::IPv4)) {
                        throw "$IpAddress is not a valid IP Address!"
                    }
                    return $IpAddress
                }
                #endregion Determine processing mode

                switch ($mode) {
                    'CIDR' {
                        Get-IPrange -IPAddress $address -Cidr $cidr
                    }
                    'Mask' {
                        Get-IPrange -IPAddress $address -Mask $mask
                    }
                    'Range' {
                        Get-IPrange -Start $rangeStart -End $rangeEnd
                    }
                }
            }
            #endregion Scan defined range

            #region Scan own computer range
            else {
                foreach ($interface in ([System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() | Where-Object NetworkInterfaceType -Like '*Ethernet*')) {
                    foreach ($property in ($interface.GetIPProperties().UnicastAddresses | Where-Object { $_.Address.AddressFamily -like "InterNetwork" })) {
                        Get-IPrange -IPAddress $property.Address -Cidr $property.PrefixLength
                    }
                }
            }
            #endregion Scan own computer range
        }
        #endregion Utility Functions

        #region Build parameter Splat for scan
        $paramTestSqlInstance = @{
            ScanType          = $ScanType
            TCPPort           = $TCPPort
            EnableException   = $EnableException
            MinimumConfidence = $MinimumConfidence
        }

        # Only specify when passed by user to avoid credential prompts on PS3/4
        if ($SqlCredential) {
            $paramTestSqlInstance["SqlCredential"] = $SqlCredential
        }
        if ($Credential) {
            $paramTestSqlInstance["Credential"] = $Credential
        }
        if ($DomainController) {
            $paramTestSqlInstance["DomainController"] = $DomainController
        }
        #endregion Build parameter Splat for scan

        # Prepare item processing in a pipeline compliant way
        $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Test-SqlInstance', [System.Management.Automation.CommandTypes]::Function)
        $scriptCmd = {
            & $wrappedCmd @paramTestSqlInstance
        }
        $steppablePipeline = $scriptCmd.GetSteppablePipeline()
        $steppablePipeline.Begin($true)
    }

    process {
        if (Test-FunctionInterrupt) { return }
        #region Process items or discover stuff
        switch ($PSCmdlet.ParameterSetName) {
            'Computer' {
                $ComputerName | Invoke-SteppablePipeline -Pipeline $steppablePipeline
            }
            'Discover' {
                #region Discovery: DataSource Enumeration
                if ($DiscoveryType -band ([Sqlcollaborative.Dbatools.Discovery.DbaInstanceDiscoveryType]::DataSourceEnumeration)) {
                    try {
                        # Discover instances
                        foreach ($instance in ([System.Data.Sql.SqlDataSourceEnumerator]::Instance.GetDataSources())) {
                            if ($instance.InstanceName -ne [System.DBNull]::Value) {
                                $steppablePipeline.Process("$($instance.Servername)\$($instance.InstanceName)")
                            } else {
                                $steppablePipeline.Process($instance.Servername)
                            }
                        }
                    } catch {
                        Write-Message -Level Warning -Message "Datasource enumeration failed" -ErrorRecord $_ -EnableException $EnableException.ToBool()
                    }
                }
                #endregion Discovery: DataSource Enumeration

                #region Discovery: SPN Search
                if ($DiscoveryType -band ([Sqlcollaborative.Dbatools.Discovery.DbaInstanceDiscoveryType]::Domain)) {
                    try {
                        Get-DomainSPN -DomainController $DomainController -Credential $Credential -ErrorAction Stop | Invoke-SteppablePipeline -Pipeline $steppablePipeline
                    } catch {
                        Write-Message -Level Warning -Message "Failed to execute Service Principal Name discovery" -ErrorRecord $_ -EnableException $EnableException.ToBool()
                    }
                }
                #endregion Discovery: SPN Search

                #region Discovery: IP Range
                if ($DiscoveryType -band ([Sqlcollaborative.Dbatools.Discovery.DbaInstanceDiscoveryType]::IPRange)) {
                    if ($IpAddress) {
                        foreach ($address in $IpAddress) {
                            Resolve-IPRange -IpAddress $address | Invoke-SteppablePipeline -Pipeline $steppablePipeline
                        }
                    } else {
                        Resolve-IPRange | Invoke-SteppablePipeline -Pipeline $steppablePipeline
                    }
                }
                #endregion Discovery: IP Range
            }
            default {
                Stop-Function -Message "Invalid parameterset, some developer probably had a beer too much. Please file an issue so we can fix this" -EnableException $EnableException
                return
            }
        }
        #endregion Process items or discover stuff
    }

    end {
        if (Test-FunctionInterrupt) {
            return
        }
        $steppablePipeline.End()
    }
}
tools\dbatools\functions\Find-DbaLoginInGroup.ps1
#ValidationTags#Messaging#
function Find-DbaLoginInGroup {
    <#
    .SYNOPSIS
        Finds Logins in Active Directory groups that have logins on the SQL Instance.

    .DESCRIPTION
        Outputs all the active directory groups members for a server, or limits it to find a specific AD user in the groups

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input.

    .PARAMETER SqlCredential
        PSCredential object to connect under. If not specified, current Windows login will be used.

    .PARAMETER Login
        Find all AD Groups used on the instance that an individual login is a member of.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Login, Group, Security
        Author: Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/ | Simone Bizzotto (@niphlod)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Find-DbaLoginInGroup

    .EXAMPLE
        PS C:\> Find-DbaLoginInGroup -SqlInstance DEV01 -Login "MyDomain\Stephen.Bennett"

        Returns all active directory groups with logins on Sql Instance DEV01 that contain the AD user Stephen.Bennett.

    .EXAMPLE
        PS C:\> Find-DbaLoginInGroup -SqlInstance DEV01

        Returns all active directory users within all windows AD groups that have logins on the instance.

    .EXAMPLE
        PS C:\> Find-DbaLoginInGroup -SqlInstance DEV01 | Where-Object Login -like '*stephen*'

        Returns all active directory users within all windows AD groups that have logins on the instance whose login contains "stephen"

    #>
    [CmdletBinding()]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification = "Internal functions are ignored")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Login,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        try {
            Add-Type -AssemblyName System.DirectoryServices.AccountManagement
        } catch {
            Stop-Function -Message "Failed to load Assembly needed" -ErrorRecord $_
        }

        function Get-AllLogins {
            param
            (
                [string]$ADGroup,
                [string[]]$discard,
                [string]$ParentADGroup
            )
            begin {
                $output = @()
            }
            process {
                try {
                    $domain = $AdGroup.Split("\")[0]
                    $ads = New-Object System.DirectoryServices.AccountManagement.PrincipalContext('Domain', $domain)
                    [string]$groupName = $AdGroup
                    $group = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($ads, $groupName);
                    $subgroups = @()
                    foreach ($member in $group.Members) {
                        $memberDomain = $member.DistinguishedName -Split "," | Where-Object { $_ -like "DC=*" } | Select-Object -first 1 | ForEach-Object { $_.ToUpper() -replace "DC=", '' }
                        if ($member.StructuralObjectClass -eq "group") {
                            $fullName = $memberDomain + "\" + $member.SamAccountName
                            if ($fullName -in $discard) {
                                Write-Message -Level Verbose -Message "skipping $fullName, already enumerated"
                                continue
                            } else {
                                $subgroups += $fullName
                            }
                        } else {
                            $output += [PSCustomObject]@{
                                SqlInstance        = $server.Name
                                InstanceName       = $server.ServiceName
                                ComputerName       = $server.ComputerName
                                Login              = $memberDomain + "\" + $member.SamAccountName
                                DisplayName        = $member.DisplayName
                                MemberOf           = $AdGroup
                                ParentADGroupLogin = $ParentADGroup
                            }
                        }
                    }
                } catch {
                    Stop-Function -Message "Failed to connect to Group: $member." -Target $member -ErrorRecord $_
                }
                $discard += $ADGroup
                foreach ($gr in $subgroups) {
                    if ($gr -notin $discard) {
                        $discard += $gr
                        Write-Message -Level Verbose -Message "Looking at $gr, recursively."
                        Get-AllLogins -ADGroup $gr -discard $discard -ParentADGroup $ParentADGroup
                    }
                }
            }
            end {
                $output
            }
        }
    }

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $AdGroups = $server.Logins | Where-Object { $_.LoginType -eq "WindowsGroup" -and $_.Name -ne "BUILTIN\Administrators" -and $_.Name -notlike "*NT SERVICE*" }

            foreach ($AdGroup in $AdGroups) {
                Write-Message -Level Verbose -Message "Looking at Group: $AdGroup"
                $ADGroupOut += Get-AllLogins $AdGroup.Name -ParentADGroup $AdGroup.Name
            }

            if (-not $Login) {
                $res = $ADGroupOut
            } else {
                $res = $ADGroupOut | Where-Object { $Login -contains $_.Login }
                if ($res.Length -eq 0) {
                    continue
                }
            }
            Select-DefaultView -InputObject $res -Property SqlInstance, Login, DisplayName, MemberOf, ParentADGroupLogin
        }
    }
}
tools\dbatools\functions\Find-DbaOrphanedFile.ps1
#ValidationTags#FlowControl,Pipeline#
function Find-DbaOrphanedFile {
    <#
    .SYNOPSIS
        Find-DbaOrphanedFile finds orphaned database files. Orphaned database files are files not associated with any attached database.

    .DESCRIPTION
        This command searches all directories associated with SQL database files for database files that are not currently in use by the SQL Server instance.

        By default, it looks for orphaned .mdf, .ldf and .ndf files in the root\data directory, the default data path, the default log path, the system paths and any directory in use by any attached directory.

        You can specify additional filetypes using the -FileType parameter, and additional paths to search using the -Path parameter.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Path
        Specifies one or more directories to search in addition to the default data and log directories.

    .PARAMETER FileType
        Specifies file extensions other than mdf, ldf and ndf to search for. Do not include the dot (".") when specifying the extension.

    .PARAMETER LocalOnly
        If this switch is enabled, only local filenames will be returned. Using this switch with multiple servers is not recommended since it does not return the associated server name.

    .PARAMETER RemoteOnly
        If this switch is enabled, only remote filenames will be returned.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Orphan, Database, DatabaseFile
        Author: Sander Stad (@sqlstad), sqlstad.nl

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

        Thanks to Paul Randal's notes on FILESTREAM which can be found at http://www.sqlskills.com/blogs/paul/filestream-directory-structure/

    .LINK
        https://dbatools.io/Find-DbaOrphanedFile

    .EXAMPLE
        PS C:\> Find-DbaOrphanedFile -SqlInstance sqlserver2014a

        Connects to sqlserver2014a, authenticating with Windows credentials, and searches for orphaned files. Returns server name, local filename, and unc path to file.

    .EXAMPLE
        PS C:\> Find-DbaOrphanedFile -SqlInstance sqlserver2014a -SqlCredential $cred

        Connects to sqlserver2014a, authenticating with SQL Server authentication, and searches for orphaned files. Returns server name, local filename, and unc path to file.

    .EXAMPLE
        PS C:\> Find-DbaOrphanedFile -SqlInstance sql2014 -Path 'E:\Dir1', 'E:\Dir2'

        Finds the orphaned files in "E:\Dir1" and "E:Dir2" in addition to the default directories.

    .EXAMPLE
        PS C:\> Find-DbaOrphanedFile -SqlInstance sql2014 -LocalOnly

        Returns only the local file paths for orphaned files.

    .EXAMPLE
        PS C:\> Find-DbaOrphanedFile -SqlInstance sql2014 -RemoteOnly

        Returns only the remote file path for orphaned files.

    .EXAMPLE
        PS C:\> Find-DbaOrphanedFile -SqlInstance sql2014, sql2016 -FileType fsf, mld

        Finds the orphaned ending with ".fsf" and ".mld" in addition to the default filetypes ".mdf", ".ldf", ".ndf" for both the servers sql2014 and sql2016.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [pscredential]$SqlCredential,
        [string[]]$Path,
        [string[]]$FileType,
        [switch]$LocalOnly,
        [switch]$RemoteOnly,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        function Get-SQLDirTreeQuery {
            param($PathList)
            # use sysaltfiles in lower versions

            $q1 = "CREATE TABLE #enum ( id int IDENTITY, fs_filename nvarchar(512), depth int, is_file int, parent nvarchar(512) ); DECLARE @dir nvarchar(512);"
            $q2 = "SET @dir = 'dirname';

                INSERT INTO #enum( fs_filename, depth, is_file )
                EXEC xp_dirtree @dir, 1, 1;

                UPDATE #enum
                SET parent = @dir,
                fs_filename = ltrim(rtrim(fs_filename))
                WHERE parent IS NULL;"

            $query_files_sql = "SELECT e.fs_filename AS filename, e.parent
                    FROM #enum AS e
                    WHERE e.fs_filename NOT IN( 'xtp', '5', '`$FSLOG', '`$HKv2', 'filestream.hdr' )
                    AND is_file = 1;"

            # build the query string based on how many directories they want to enumerate
            $sql = $q1
            $sql += $($PathList | Where-Object { $_ -ne '' } | ForEach-Object { "$([System.Environment]::Newline)$($q2 -Replace 'dirname', $_)" })
            $sql += $query_files_sql
            Write-Message -Level Debug -Message $sql
            return $sql
        }
        function Get-SqlFileStructure {
            param
            (
                [Parameter(Mandatory, Position = 1)]
                [Microsoft.SqlServer.Management.Smo.SqlSmoObject]$smoserver
            )
            if ($smoserver.versionMajor -eq 8) {
                $sql = "select filename from sysaltfiles"
            } else {
                $sql = "select physical_name as filename from sys.master_files"
            }

            $dbfiletable = $smoserver.ConnectionContext.ExecuteWithResults($sql)
            $ftfiletable = $dbfiletable.Tables[0].Clone()
            $dbfiletable.Tables[0].TableName = "data"

            # Add support for Full Text Catalogs in Sql Server 2005 and below
            if ($server.VersionMajor -lt 10) {
                $databaselist = $smoserver.Databases | Select-Object -property  Name, IsFullTextEnabled
                foreach ($db in $databaselist) {
                    if ($db.IsFullTextEnabled -eq $false) {
                        continue
                    }
                    $database = $db.name
                    $fttable = $null = $smoserver.Databases[$database].ExecuteWithResults('sp_help_fulltext_catalogs')
                    foreach ($ftc in $fttable.Tables[0].rows) {
                        $null = $ftfiletable.Rows.add($ftc.Path)
                    }
                }
            }

            $null = $dbfiletable.Tables.Add($ftfiletable)
            return $dbfiletable.Tables.Filename
        }

        function Format-Path {
            param ($path)

            $path = $path.Trim()
            #Thank you windows 2000
            $path = $path -replace '[^A-Za-z0-9 _\.\-\\:]', '__'
            return $path
        }

        $FileType += "mdf", "ldf", "ndf"
        $systemfiles = "distmdl.ldf", "distmdl.mdf", "mssqlsystemresource.ldf", "mssqlsystemresource.mdf"

        $FileTypeComparison = $FileType | ForEach-Object {$_.ToLower()} | Where-Object { $_ } | Sort-Object | Get-Unique
    }

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            # Reset all the arrays
            $dirtreefiles = $valid = $paths = $matching = @()

            $filestructure = Get-SqlFileStructure $server

            # Get any paths associated with current data and log files
            foreach ($file in $filestructure) {
                $paths += Split-Path -Path $file -Parent
            }

            # Get the default data and log directories from the instance
            Write-Message -Level Debug -Message "Adding paths"
            $paths += $server.RootDirectory + "\DATA"
            $paths += Get-SqlDefaultPaths $server data
            $paths += Get-SqlDefaultPaths $server log
            $paths += $server.MasterDBPath
            $paths += $server.MasterDBLogPath
            $paths += $Path
            $paths = $paths | ForEach-Object { "$_".TrimEnd("\") } | Sort-Object | Get-Unique
            $sql = Get-SQLDirTreeQuery $paths
            $datatable = $server.Databases['master'].ExecuteWithResults($sql).Tables[0]

            foreach ($row in $datatable) {
                $fullpath = [IO.Path]::combine($row.parent, $row.filename)
                $dirtreefiles += [pscustomobject]@{
                    FullPath   = $fullpath
                    Comparison = [IO.Path]::GetFullPath($(Format-Path $fullpath))
                }
            }
            $dirtreefiles = $dirtreefiles | Where-Object { $_ } | Sort-Object Comparison -Unique

            foreach ($file in $filestructure) {
                $valid += [IO.Path]::GetFullPath($(Format-Path $file))
            }

            $valid = $valid | Sort-Object | Get-Unique

            foreach ($file in $dirtreefiles.Comparison) {
                foreach ($type in $FileTypeComparison) {
                    if ($file.ToLower().EndsWith($type)) {
                        $matching += $file
                        break
                    }
                }
            }

            $dirtreematcher = @{}
            foreach ($el in $dirtreefiles) {
                $dirtreematcher[$el.Comparison] = $el.Fullpath
            }

            foreach ($file in $matching) {
                if ($file -notin $valid) {
                    $fullpath = $dirtreematcher[$file]

                    $filename = Split-Path $fullpath -Leaf

                    if ($filename -in $systemfiles) { continue }

                    $result = [pscustomobject]@{
                        Server         = $server.name
                        ComputerName   = $server.ComputerName
                        InstanceName   = $server.ServiceName
                        SqlInstance    = $server.DomainInstanceName
                        Filename       = $fullpath
                        RemoteFilename = Join-AdminUnc -Servername $server.ComputerName -Filepath $fullpath
                    }

                    if ($LocalOnly -eq $true) {
                        ($result | Select-Object filename).filename
                        continue
                    }

                    if ($RemoteOnly -eq $true) {
                        ($result | Select-Object remotefilename).remotefilename
                        continue
                    }

                    $result | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, Filename, RemoteFilename

                }
            }

        }
    }
    end {
        if ($result.count -eq 0) {
            Write-Message -Level Verbose -Message "No orphaned files found"
        }
    }
}
tools\dbatools\functions\Find-DbaSimilarTable.ps1
function Find-DbaSimilarTable {
    <#
    .SYNOPSIS
        Returns all tables/views that are similar in structure by comparing the column names of matching and matched tables/views

    .DESCRIPTION
        This function can either run against specific databases or all databases searching all/specific tables and views including in system databases.
        Typically one would use this to find for example archive version(s) of a table whose structures are similar.
        This can also be used to find tables/views that are very similar to a given table/view structure to see where a table/view might be used.

        More information can be found here: https://sqljana.wordpress.com/2017/03/31/sql-server-find-tables-with-similar-table-structure/

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER SchemaName
        If you are looking in a specific schema whose table structures is to be used as reference structure, provide the name of the schema.
        If no schema is provided, looks at all schemas

    .PARAMETER TableName
        If you are looking in a specific table whose structure is to be used as reference structure, provide the name of the table.
        If no table is provided, looks at all tables
        If the table name exists in multiple schemas, all of them would qualify

    .PARAMETER ExcludeViews
        By default, views are included. You can exclude them by setting this switch to $false
        This excludes views in both matching and matched list

    .PARAMETER IncludeSystemDatabases
        By default system databases are ignored but you can include them within the search using this parameter

    .PARAMETER MatchPercentThreshold
        The minimum percentage of column names that should match between the matching and matched objects.
        Entries with no matches are eliminated

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Table
        Author: Jana Sattainathan (@SQLJana), http://sqljana.wordpress.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Find-DbaSimilarTable

    .EXAMPLE
        PS C:\> Find-DbaSimilarTable -SqlInstance DEV01

        Searches all user database tables and views for each, returns all tables or views with their matching tables/views and match percent

    .EXAMPLE
        PS C:\> Find-DbaSimilarTable -SqlInstance DEV01 -Database AdventureWorks

        Searches AdventureWorks database and lists tables/views and their corresponding matching tables/views with match percent

    .EXAMPLE
        PS C:\> Find-DbaSimilarTable -SqlInstance DEV01 -Database AdventureWorks -SchemaName HumanResource

        Searches AdventureWorks database and lists tables/views in the HumanResource schema with their corresponding matching tables/views with match percent

    .EXAMPLE
        PS C:\> Find-DbaSimilarTable -SqlInstance DEV01 -Database AdventureWorks -SchemaName HumanResource -Table Employee

        Searches AdventureWorks database and lists tables/views in the HumanResource schema and table Employee with its corresponding matching tables/views with match percent

    .EXAMPLE
        PS C:\> Find-DbaSimilarTable -SqlInstance DEV01 -Database AdventureWorks -MatchPercentThreshold 60

        Searches AdventureWorks database and lists all tables/views with its corresponding matching tables/views with match percent greater than or equal to 60

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [string]$SchemaName,
        [string]$TableName,
        [switch]$ExcludeViews,
        [switch]$IncludeSystemDatabases,
        [int]$MatchPercentThreshold,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $everyServerVwCount = 0

        $sqlSelect = "WITH ColCountsByTable
                AS
                (
                      SELECT
                            c.TABLE_CATALOG,
                            c.TABLE_SCHEMA,
                            c.TABLE_NAME,
                            COUNT(1) AS Column_Count
                      FROM INFORMATION_SCHEMA.COLUMNS c
                      GROUP BY
                            c.TABLE_CATALOG,
                            c.TABLE_SCHEMA,
                            c.TABLE_NAME
                )
                SELECT
                      100 * COUNT(c2.COLUMN_NAME) /*Matching_Column_Count*/ / MIN(ColCountsByTable.Column_Count) /*Column_Count*/ AS MatchPercent,
                      DENSE_RANK() OVER(ORDER BY c.TABLE_CATALOG, c.TABLE_SCHEMA, c.TABLE_NAME) TableNameRankInDB,
                      c.TABLE_CATALOG AS DatabaseName,
                      c.TABLE_SCHEMA AS SchemaName,
                      c.TABLE_NAME AS TableName,
                      t.TABLE_TYPE AS TableType,
                      MIN(ColCountsByTable.Column_Count) AS ColumnCount,
                      c2.TABLE_CATALOG AS MatchingDatabaseName,
                      c2.TABLE_SCHEMA AS MatchingSchemaName,
                      c2.TABLE_NAME AS MatchingTableName,
                      t2.TABLE_TYPE AS MatchingTableType,
                      COUNT(c2.COLUMN_NAME) AS MatchingColumnCount
                FROM INFORMATION_SCHEMA.TABLES t
                      INNER JOIN INFORMATION_SCHEMA.COLUMNS c
                            ON t.TABLE_CATALOG = c.TABLE_CATALOG
                                  AND t.TABLE_SCHEMA = c.TABLE_SCHEMA
                                  AND t.TABLE_NAME = c.TABLE_NAME
                      INNER JOIN ColCountsByTable
                            ON t.TABLE_CATALOG = ColCountsByTable.TABLE_CATALOG
                                  AND t.TABLE_SCHEMA = ColCountsByTable.TABLE_SCHEMA
                                  AND t.TABLE_NAME = ColCountsByTable.TABLE_NAME
                      LEFT OUTER JOIN INFORMATION_SCHEMA.COLUMNS c2
                            ON t.TABLE_NAME != c2.TABLE_NAME
                                  AND c.COLUMN_NAME = c2.COLUMN_NAME
                      LEFT JOIN INFORMATION_SCHEMA.TABLES t2
                            ON c2.TABLE_NAME = t2.TABLE_NAME"

        $sqlWhere = "
                WHERE "

        $sqlGroupBy = "
                GROUP BY
                      c.TABLE_CATALOG,
                      c.TABLE_SCHEMA,
                      c.TABLE_NAME,
                      t.TABLE_TYPE,
                      c2.TABLE_CATALOG,
                      c2.TABLE_SCHEMA,
                      c2.TABLE_NAME,
                      t2.TABLE_TYPE "

        $sqlHaving = "
                HAVING
                    /*Match_Percent should be greater than 0 at minimum!*/
                    "

        $sqlOrderBy = "
                ORDER BY
                      MatchPercent DESC"


        $sql = ''
        $wherearray = @()

        if ($ExcludeViews) {
            $wherearray += " (t.TABLE_TYPE <> 'VIEW' AND t2.TABLE_TYPE <> 'VIEW') "
        }

        if ($SchemaName) {
            $wherearray += (" (c.TABLE_SCHEMA = '{0}') " -f $SchemaName.Replace("'", "''")) #Replace single quotes with two single quotes!
        }

        if ($TableName) {
            $wherearray += (" (c.TABLE_NAME = '{0}') " -f $TableName.Replace("'", "''")) #Replace single quotes with two single quotes!

        }

        if ($wherearray.length -gt 0) {
            $sqlWhere = "$sqlWhere " + ($wherearray -join " AND ")
        } else {
            $sqlWhere = ""
        }


        $matchThreshold = 0
        if ($MatchPercentThreshold) {
            $matchThreshold = $MatchPercentThreshold
        } else {
            $matchThreshold = 0
        }

        $sqlHaving += (" (100 * COUNT(c2.COLUMN_NAME) / MIN(ColCountsByTable.Column_Count) >= {0}) " -f $matchThreshold)



        $sql = "$sqlSelect $sqlWhere $sqlGroupBy $sqlHaving $sqlOrderBy"

        Write-Message -Level Debug -Message $sql

    }

    process {
        foreach ($Instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }


            #Use IsAccessible instead of Status -eq 'normal' because databases that are on readable secondaries for AG or mirroring replicas will cause errors to be thrown
            if ($IncludeSystemDatabases) {
                $dbs = $server.Databases | Where-Object { $_.IsAccessible -eq $true }
            } else {
                $dbs = $server.Databases | Where-Object { $_.IsAccessible -eq $true -and $_.IsSystemObject -eq $false }
            }

            if ($Database) {
                $dbs = $server.Databases | Where-Object Name -In $Database
            }

            if ($ExcludeDatabase) {
                $dbs = $dbs | Where-Object Name -NotIn $ExcludeDatabase
            }


            $totalCount = 0
            $dbCount = $dbs.count
            foreach ($db in $dbs) {

                Write-Message -Level Verbose -Message "Searching on database $db"
                $rows = $db.Query($sql)

                foreach ($row in $rows) {
                    [PSCustomObject]@{
                        ComputerName              = $server.ComputerName
                        InstanceName              = $server.ServiceName
                        SqlInstance               = $server.DomainInstanceName
                        Table                     = "$($row.DatabaseName).$($row.SchemaName).$($row.TableName)"
                        MatchingTable             = "$($row.MatchingDatabaseName).$($row.MatchingSchemaName).$($row.MatchingTableName)"
                        MatchPercent              = $row.MatchPercent
                        OriginalDatabaseName      = $row.DatabaseName
                        OriginalSchemaName        = $row.SchemaName
                        OriginalTableName         = $row.TableName
                        OriginalTableNameRankInDB = $row.TableNameRankInDB
                        OriginalTableType         = $row.TableType
                        OriginalColumnCount       = $row.ColumnCount
                        MatchingDatabaseName      = $row.MatchingDatabaseName
                        MatchingSchemaName        = $row.MatchingSchemaName
                        MatchingTableName         = $row.MatchingTableName
                        MatchingTableType         = $row.MatchingTableType
                        MatchingColumnCount       = $row.MatchingColumnCount
                    }
                }

                $vwCount = $vwCount + $rows.Count
                $totalCount = $totalCount + $rows.Count
                $everyServerVwCount = $everyServerVwCount + $rows.Count

                Write-Message -Level Verbose -Message "Found $vwCount tables/views in $db"
            }

            Write-Message -Level Verbose -Message "Found $totalCount total tables/views in $dbCount databases"
        }
    }
    end {
        Write-Message -Level Verbose -Message "Found $everyServerVwCount total tables/views"
    }
}
tools\dbatools\functions\Find-DbaStoredProcedure.ps1
function Find-DbaStoredProcedure {
    <#
    .SYNOPSIS
        Returns all stored procedures that contain a specific case-insensitive string or regex pattern.

    .DESCRIPTION
        This function can either run against specific databases or all databases searching all user or user and system stored procedures.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER Pattern
        String pattern that you want to search for in the stored procedure text body

    .PARAMETER IncludeSystemObjects
        By default, system stored procedures are ignored but you can include them within the search using this parameter.

        Warning - this will likely make it super slow if you run it on all databases.

    .PARAMETER IncludeSystemDatabases
        By default system databases are ignored but you can include them within the search using this parameter

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: StoredProcedure, Proc
        Author: Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Find-DbaStoredProcedure

    .EXAMPLE
        PS C:\> Find-DbaStoredProcedure -SqlInstance DEV01 -Pattern whatever

        Searches all user databases stored procedures for "whatever" in the text body

    .EXAMPLE
        PS C:\> Find-DbaStoredProcedure -SqlInstance sql2016 -Pattern '\w+@\w+\.\w+'

        Searches all databases for all stored procedures that contain a valid email pattern in the text body

    .EXAMPLE
        PS C:\> Find-DbaStoredProcedure -SqlInstance DEV01 -Database MyDB -Pattern 'some string' -Verbose

        Searches in "mydb" database stored procedures for "some string" in the text body

    .EXAMPLE
        PS C:\> Find-DbaStoredProcedure -SqlInstance sql2016 -Database MyDB -Pattern RUNTIME -IncludeSystemObjects

        Searches in "mydb" database stored procedures for "runtime" in the text body

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [parameter(Mandatory)]
        [string]$Pattern,
        [switch]$IncludeSystemObjects,
        [switch]$IncludeSystemDatabases,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $sql = "SELECT OBJECT_SCHEMA_NAME(p.object_id) as ProcSchema, p.name, m.definition as TextBody FROM sys.sql_modules m, sys.procedures p WHERE m.object_id = p.object_id"
        if (!$IncludeSystemObjects) { $sql = "$sql AND p.is_ms_shipped = 0" }
        $everyserverspcount = 0
    }
    process {
        foreach ($Instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $Instance -SqlCredential $SqlCredential
            } catch {
                Write-Message -Level Warning -Message "Failed to connect to: $Instance"
                continue
            }

            if ($server.versionMajor -lt 9) {
                Write-Message -Level Warning -Message "This command only supports SQL Server 2005 and above."
                Continue
            }

            if ($IncludeSystemDatabases) {
                $dbs = $server.Databases | Where-Object { $_.Status -eq "normal" }
            } else {
                $dbs = $server.Databases | Where-Object { $_.Status -eq "normal" -and $_.IsSystemObject -eq $false }
            }

            if ($Database) {
                $dbs = $dbs | Where-Object Name -In $Database
            }

            if ($ExcludeDatabase) {
                $dbs = $dbs | Where-Object Name -NotIn $ExcludeDatabase
            }

            $totalcount = 0
            $dbcount = $dbs.count
            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Searching on database $db"

                # If system objects aren't needed, find stored procedure text using SQL
                # This prevents SMO from having to enumerate

                if (!$IncludeSystemObjects) {
                    Write-Message -Level Debug -Message $sql
                    $rows = $db.ExecuteWithResults($sql).Tables.Rows
                    $sproccount = 0

                    foreach ($row in $rows) {
                        $totalcount++; $sproccount++; $everyserverspcount++

                        $procSchema = $row.ProcSchema
                        $proc = $row.Name

                        Write-Message -Level Verbose -Message "Looking in stored procedure: $procSchema.$proc textBody for $pattern"
                        if ($row.TextBody -match $Pattern) {
                            $sp = $db.StoredProcedures | Where-Object {$_.Schema -eq $procSchema -and $_.Name -eq $proc}

                            $StoredProcedureText = $sp.TextBody.split("`n")
                            $spTextFound = $StoredProcedureText | Select-String -Pattern $Pattern | ForEach-Object { "(LineNumber: $($_.LineNumber)) $($_.ToString().Trim())" }

                            [PSCustomObject]@{
                                ComputerName             = $server.ComputerName
                                SqlInstance              = $server.ServiceName
                                Database                 = $db.Name
                                Schema                   = $sp.Schema
                                Name                     = $sp.Name
                                Owner                    = $sp.Owner
                                IsSystemObject           = $sp.IsSystemObject
                                CreateDate               = $sp.CreateDate
                                LastModified             = $sp.DateLastModified
                                StoredProcedureTextFound = $spTextFound -join "`n"
                                StoredProcedure          = $sp
                                StoredProcedureFullText  = $sp.TextBody
                            } | Select-DefaultView -ExcludeProperty StoredProcedure, StoredProcedureFullText
                        }
                    }
                } else {
                    $storedprocedures = $db.StoredProcedures

                    foreach ($sp in $storedprocedures) {
                        $totalcount++; $sproccount++; $everyserverspcount++

                        $procSchema = $sp.Schema
                        $proc = $sp.Name

                        Write-Message -Level Verbose -Message "Looking in stored procedure $procSchema.$proc textBody for $pattern"
                        if ($sp.TextBody -match $Pattern) {

                            $StoredProcedureText = $sp.TextBody.split("`n")
                            $spTextFound = $StoredProcedureText | Select-String -Pattern $Pattern | ForEach-Object { "(LineNumber: $($_.LineNumber)) $($_.ToString().Trim())" }

                            [PSCustomObject]@{
                                ComputerName             = $server.ComputerName
                                SqlInstance              = $server.ServiceName
                                Database                 = $db.Name
                                Schema                   = $sp.Schema
                                Name                     = $sp.Name
                                Owner                    = $sp.Owner
                                IsSystemObject           = $sp.IsSystemObject
                                CreateDate               = $sp.CreateDate
                                LastModified             = $sp.DateLastModified
                                StoredProcedureTextFound = $spTextFound -join "`n"
                                StoredProcedure          = $sp
                                StoredProcedureFullText  = $sp.TextBody
                            } | Select-DefaultView -ExcludeProperty StoredProcedure, StoredProcedureFullText
                        }
                    }
                }
                Write-Message -Level Verbose -Message "Evaluated $sproccount stored procedures in $db"
            }
            Write-Message -Level Verbose -Message "Evaluated $totalcount total stored procedures in $dbcount databases"
        }
    }
    end {
        Write-Message -Level Verbose -Message "Evaluated $everyserverspcount total stored procedures"
    }
}
tools\dbatools\functions\Find-DbaTrigger.ps1
function Find-DbaTrigger {
    <#
    .SYNOPSIS
        Returns all triggers that contain a specific case-insensitive string or regex pattern.

    .DESCRIPTION
        This function search on Instance, Database and Object level.
        If you specify one or more databases, search on Server level will not be preformed.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER Pattern
        String pattern that you want to search for in the trigger text body

    .PARAMETER TriggerLevel
        Allows specify the trigger level that you want to search. By default is All (Server, Database, Object).

    .PARAMETER IncludeSystemObjects
        By default, system triggers are ignored but you can include them within the search using this parameter.

        Warning - this will likely make it super slow if you run it on all databases.

    .PARAMETER IncludeSystemDatabases
        By default system databases are ignored but you can include them within the search using this parameter

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Trigger
        Author: Claudio Silva (@ClaudioESSilva)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Find-DbaTrigger

    .EXAMPLE
        PS C:\> Find-DbaTrigger -SqlInstance DEV01 -Pattern whatever

        Searches all user databases triggers for "whatever" in the text body

    .EXAMPLE
        PS C:\> Find-DbaTrigger -SqlInstance sql2016 -Pattern '\w+@\w+\.\w+'

        Searches all databases for all triggers that contain a valid email pattern in the text body

    .EXAMPLE
        PS C:\> Find-DbaTrigger -SqlInstance DEV01 -Database MyDB -Pattern 'some string' -Verbose

        Searches in "mydb" database triggers for "some string" in the text body

    .EXAMPLE
        PS C:\> Find-DbaTrigger -SqlInstance sql2016 -Database MyDB -Pattern RUNTIME -IncludeSystemObjects

        Searches in "mydb" database triggers for "runtime" in the text body

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [parameter(Mandatory)]
        [string]$Pattern,
        [ValidateSet('All', 'Server', 'Database', 'Object')]
        [string]$TriggerLevel = 'All',
        [switch]$IncludeSystemObjects,
        [switch]$IncludeSystemDatabases,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $sqlDatabaseTriggers = "SELECT tr.name, m.definition as TextBody FROM sys.sql_modules m, sys.triggers tr WHERE m.object_id = tr.object_id AND tr.parent_class = 0"

        $sqlTableTriggers = "SELECT OBJECT_SCHEMA_NAME(tr.parent_id) TableSchema, OBJECT_NAME(tr.parent_id) AS TableName, tr.name, m.definition as TextBody FROM sys.sql_modules m, sys.triggers tr WHERE m.object_id = tr.object_id AND tr.parent_class = 1"
        if (!$IncludeSystemObjects) { $sqlTableTriggers = "$sqlTableTriggers AND tr.is_ms_shipped = 0" }

        $everyserverstcount = 0
    }
    process {
        foreach ($Instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $Instance -SqlCredential $SqlCredential
            } catch {
                Write-Message -Level Warning -Message "Failed to connect to: $Instance"
                continue
            }

            if ($server.versionMajor -lt 9) {
                Write-Message -Level Warning -Message "This command only supports SQL Server 2005 and above."
                Continue
            }

            #search at instance level. Only if no database was specified
            if ((-Not $Database) -and ($TriggerLevel -in @('All', 'Server'))) {
                foreach ($trigger in $server.Triggers) {
                    $everyserverstcount++; $triggercount++
                    Write-Message -Level Debug -Message "Looking in Trigger: $trigger TextBody for $pattern"
                    if ($trigger.TextBody -match $Pattern) {

                        $triggerText = $trigger.TextBody.split("`n`r")
                        $trTextFound = $triggerText | Select-String -Pattern $Pattern | ForEach-Object { "(LineNumber: $($_.LineNumber)) $($_.ToString().Trim())" }

                        [PSCustomObject]@{
                            ComputerName     = $server.ComputerName
                            SqlInstance      = $server.ServiceName
                            TriggerLevel     = "Server"
                            Database         = $null
                            Object           = $null
                            Name             = $trigger.Name
                            IsSystemObject   = $trigger.IsSystemObject
                            CreateDate       = $trigger.CreateDate
                            LastModified     = $trigger.DateLastModified
                            TriggerTextFound = $trTextFound -join "`n"
                            Trigger          = $trigger
                            TriggerFullText  = $trigger.TextBody
                        } | Select-DefaultView -ExcludeProperty Trigger, TriggerFullText
                    }
                }
                Write-Message -Level Verbose -Message "Evaluated $triggercount triggers in $server"
            }

            if ($IncludeSystemDatabases) {
                $dbs = $server.Databases | Where-Object { $_.Status -eq "normal" }
            } else {
                $dbs = $server.Databases | Where-Object { $_.Status -eq "normal" -and $_.IsSystemObject -eq $false }
            }

            if ($Database) {
                $dbs = $dbs | Where-Object Name -In $Database
            }

            if ($ExcludeDatabase) {
                $dbs = $dbs | Where-Object Name -NotIn $ExcludeDatabase
            }

            $totalcount = 0
            $dbcount = $dbs.count

            if ($TriggerLevel -in @('All', 'Database', 'Object')) {
                foreach ($db in $dbs) {

                    Write-Message -Level Verbose -Message "Searching on database $db"

                    # If system objects aren't needed, find trigger text using SQL
                    # This prevents SMO from having to enumerate

                    if (!$IncludeSystemObjects) {
                        if ($TriggerLevel -in @('All', 'Database')) {
                            #Get Database Level triggers (DDL)
                            Write-Message -Level Debug -Message $sqlDatabaseTriggers
                            $rows = $db.ExecuteWithResults($sqlDatabaseTriggers).Tables.Rows
                            $triggercount = 0

                            foreach ($row in $rows) {
                                $totalcount++; $triggercount++; $everyserverstcount++

                                $trigger = $row.name

                                Write-Message -Level Verbose -Message "Looking in trigger $trigger for textBody with pattern $pattern on database $db"
                                if ($row.TextBody -match $Pattern) {
                                    $tr = $db.Triggers | Where-Object name -eq $row.name

                                    $triggerText = $tr.TextBody.split("`n`r")
                                    $trTextFound = $triggerText | Select-String -Pattern $Pattern | ForEach-Object { "(LineNumber: $($_.LineNumber)) $($_.ToString().Trim())" }

                                    [PSCustomObject]@{
                                        ComputerName     = $server.ComputerName
                                        SqlInstance      = $server.ServiceName
                                        TriggerLevel     = "Database"
                                        Database         = $db.name
                                        Object           = $tr.Parent
                                        Name             = $tr.Name
                                        IsSystemObject   = $tr.IsSystemObject
                                        CreateDate       = $tr.CreateDate
                                        LastModified     = $tr.DateLastModified
                                        TriggerTextFound = $trTextFound -join "`n"
                                        Trigger          = $tr
                                        TriggerFullText  = $tr.TextBody
                                    } | Select-DefaultView -ExcludeProperty Trigger, TriggerFullText
                                }
                            }
                        }

                        if ($TriggerLevel -in @('All', 'Object')) {
                            #Get Object Level triggers (DML)
                            Write-Message -Level Debug -Message $sqlTableTriggers
                            $rows = $db.ExecuteWithResults($sqlTableTriggers).Tables.Rows
                            $triggercount = 0

                            foreach ($row in $rows) {
                                $totalcount++; $triggercount++; $everyserverstcount++

                                $trigger = $row.name
                                $triggerParentSchema = $row.TableSchema
                                $triggerParent = $row.TableName

                                Write-Message -Level Verbose -Message "Looking in trigger $trigger for textBody with pattern $pattern in object $triggerParentSchema.$triggerParent at database $db"
                                if ($row.TextBody -match $Pattern) {

                                    $tr = ($db.Tables | Where-Object {$_.Name -eq $triggerParent -and $_.Schema -eq $triggerParentSchema}).Triggers | Where-Object name -eq $row.name

                                    $triggerText = $tr.TextBody.split("`n`r")
                                    $trTextFound = $triggerText | Select-String -Pattern $Pattern | ForEach-Object { "(LineNumber: $($_.LineNumber)) $($_.ToString().Trim())" }

                                    [PSCustomObject]@{
                                        ComputerName     = $server.ComputerName
                                        SqlInstance      = $server.ServiceName
                                        TriggerLevel     = "Object"
                                        Database         = $db.name
                                        Object           = $tr.Parent
                                        Name             = $tr.Name
                                        IsSystemObject   = $tr.IsSystemObject
                                        CreateDate       = $tr.CreateDate
                                        LastModified     = $tr.DateLastModified
                                        TriggerTextFound = $trTextFound -join "`n"
                                        Trigger          = $tr
                                        TriggerFullText  = $tr.TextBody
                                    } | Select-DefaultView -ExcludeProperty Trigger, TriggerFullText
                                }
                            }
                        }
                    } else {
                        if ($TriggerLevel -in @('All', 'Database')) {
                            #Get Database Level triggers (DDL)
                            $triggers = $db.Triggers

                            $triggercount = 0

                            foreach ($tr in $triggers) {
                                $totalcount++; $triggercount++; $everyserverstcount++
                                $trigger = $tr.Name

                                Write-Message -Level Verbose -Message "Looking in trigger $trigger for textBody with pattern $pattern on database $db"
                                if ($tr.TextBody -match $Pattern) {

                                    $triggerText = $tr.TextBody.split("`n`r")
                                    $trTextFound = $triggerText | Select-String -Pattern $Pattern | ForEach-Object { "(LineNumber: $($_.LineNumber)) $($_.ToString().Trim())" }

                                    [PSCustomObject]@{
                                        ComputerName     = $server.ComputerName
                                        SqlInstance      = $server.ServiceName
                                        TriggerLevel     = "Database"
                                        Database         = $db.name
                                        Object           = $tr.Parent
                                        Name             = $tr.Name
                                        IsSystemObject   = $tr.IsSystemObject
                                        CreateDate       = $tr.CreateDate
                                        LastModified     = $tr.DateLastModified
                                        TriggerTextFound = $trTextFound -join "`n"
                                        Trigger          = $tr
                                        TriggerFullText  = $tr.TextBody
                                    } | Select-DefaultView -ExcludeProperty Trigger, TriggerFullText
                                }
                            }
                        }

                        if ($TriggerLevel -in @('All', 'Object')) {
                            #Get Object Level triggers (DML)
                            $triggers = $db.Tables | ForEach-Object {$_.Triggers}

                            $triggercount = 0

                            foreach ($tr in $triggers) {
                                $totalcount++; $triggercount++; $everyserverstcount++
                                $trigger = $tr.Name

                                Write-Message -Level Verbose -Message "Looking in trigger $trigger for textBody with pattern $pattern in object $($tr.Parent) at database $db"
                                if ($tr.TextBody -match $Pattern) {

                                    $triggerText = $tr.TextBody.split("`n`r")
                                    $trTextFound = $triggerText | Select-String -Pattern $Pattern | ForEach-Object { "(LineNumber: $($_.LineNumber)) $($_.ToString().Trim())" }

                                    [PSCustomObject]@{
                                        ComputerName     = $server.ComputerName
                                        SqlInstance      = $server.ServiceName
                                        TriggerLevel     = "Object"
                                        Database         = $db.name
                                        Object           = $tr.Parent
                                        Name             = $tr.Name
                                        IsSystemObject   = $tr.IsSystemObject
                                        CreateDate       = $tr.CreateDate
                                        LastModified     = $tr.DateLastModified
                                        TriggerTextFound = $trTextFound -join "`n"
                                        Trigger          = $tr
                                        TriggerFullText  = $tr.TextBody
                                    } | Select-DefaultView -ExcludeProperty Trigger, TriggerFullText
                                }
                            }
                        }
                    }
                    Write-Message -Level Verbose -Message "Evaluated $triggercount triggers in $db"
                }
            }
            Write-Message -Level Verbose -Message "Evaluated $totalcount total triggers in $dbcount databases"
        }
    }
    end {
        Write-Message -Level Verbose -Message "Evaluated $everyserverstcount total triggers"
    }
}
tools\dbatools\functions\Find-DbaUserObject.ps1
#ValidationTags#Messaging#
function Find-DbaUserObject {
    <#
    .SYNOPSIS
        Searches SQL Server to find user-owned objects (i.e. not dbo or sa) or for any object owned by a specific user specified by the Pattern parameter.

    .DESCRIPTION
        Looks at the below list of objects to see if they are either owned by a user or a specific user (using the parameter -Pattern)
        Database Owner
        Agent Job Owner
        Used in Credential
        USed in Proxy
        SQL Agent Steps using a Proxy
        Endpoints
        Server Roles
        Database Schemas
        Database Roles
        Database Assembles
        Database Synonyms

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Pattern
        The regex pattern that the command will search for

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Object
        Author: Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Find-DbaUserObject

    .EXAMPLE
        PS C:\> Find-DbaUserObject -SqlInstance DEV01 -Pattern ad\stephen

        Searches user objects for owner ad\stephen

    .EXAMPLE
        PS C:\> Find-DbaUserObject -SqlInstance DEV01 -Verbose

        Shows all user owned (non-sa, non-dbo) objects and verbose output

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlInstances")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$Pattern,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        if ($Pattern -match '^[\w\d\.-]+\\[\w\d\.-]+$') {
            Write-Message -Level Verbose -Message "Too few slashes, adding extra as required by regex"
            $Pattern = $Pattern.Replace('\', '\\')
        }
    }
    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $saname = Get-SaLoginName $server

            ## Credentials
            if (-not $pattern) {
                Write-Message -Level Verbose -Message "Gathering data on instance objects"
                $creds = $server.Credentials
                $proxies = $server.JobServer.ProxyAccounts
                $endPoints = $server.Endpoints | Where-Object { $_.Owner -ne $saname }

                Write-Message -Level Verbose -Message "Gather data on Agent Jobs ownership"
                #Variable marked as unused by PSScriptAnalyzer
                #$jobs = $server.JobServer.Jobs | Where-Object { $_.OwnerLoginName -ne $saname }
            } else {
                Write-Message -Level Verbose -Message "Gathering data on instance objects"
                $creds = $server.Credentials | Where-Object { $_.Identity -match $pattern }
                $proxies = $server.JobServer.ProxyAccounts | Where-Object { $_.CredentialIdentity -match $pattern }
                $endPoints = $server.Endpoints | Where-Object { $_.Owner -match $pattern }

                Write-Message -Level Verbose -Message "Gather data on Agent Jobs ownership"
                #Variable marked as unused by PSScriptAnalyzer
                #$jobs = $server.JobServer.Jobs | Where-Object { $_.OwnerLoginName -match $pattern }
            }

            ## dbs
            if (-not $pattern) {
                foreach ($db in $server.Databases | Where-Object { $_.Owner -ne $saname }) {
                    Write-Message -Level Verbose -Message "checking if $db is owned "

                    [PSCustomObject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Type         = "Database"
                        Owner        = $db.Owner
                        Name         = $db.Name
                        Parent       = $db.Parent.Name
                    }
                }
            } else {
                foreach ($db in $server.Databases | Where-Object { $_.Owner -match $pattern }) {
                    [PSCustomObject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Type         = "Database"
                        Owner        = $db.Owner
                        Name         = $db.Name
                        Parent       = $db.Parent.Name
                    }
                }
            }

            ## agent jobs
            if (-not $pattern) {
                foreach ($job in $server.JobServer.Jobs | Where-Object { $_.OwnerLoginName -ne $saname }) {
                    [PSCustomObject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Type         = "Agent Job"
                        Owner        = $job.OwnerLoginName
                        Name         = $job.Name
                        Parent       = $job.Parent.Name
                    }
                }
            } else {
                foreach ($job in $server.JobServer.Jobs | Where-Object { $_.OwnerLoginName -match $pattern }) {
                    [PSCustomObject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Type         = "Agent Job"
                        Owner        = $job.OwnerLoginName
                        Name         = $job.Name
                        Parent       = $job.Parent.Name
                    }
                }
            }

            ## credentials
            foreach ($cred in $creds) {
                ## list credentials using the account

                [PSCustomObject]@{
                    ComputerName = $server.ComputerName
                    InstanceName = $server.ServiceName
                    SqlInstance  = $server.DomainInstanceName
                    Type         = "Credential"
                    Owner        = $cred.Identity
                    Name         = $cred.Name
                    Parent       = $cred.Parent.Name
                }
            }

            ## proxies
            foreach ($proxy in $proxies) {
                [PSCustomObject]@{
                    ComputerName = $server.ComputerName
                    InstanceName = $server.ServiceName
                    SqlInstance  = $server.DomainInstanceName
                    Type         = "Proxy"
                    Owner        = $proxy.CredentialIdentity
                    Name         = $proxy.Name
                    Parent       = $proxy.Parent.Name
                }

                ## list agent jobs steps using proxy
                foreach ($job in $server.JobServer.Jobs) {
                    foreach ($step in $job.JobSteps | Where-Object { $_.ProxyName -eq $proxy.Name }) {
                        [PSCustomObject]@{
                            ComputerName = $server.ComputerName
                            InstanceName = $server.ServiceName
                            SqlInstance  = $server.DomainInstanceName
                            Type         = "Agent Step"
                            Owner        = $step.ProxyName
                            Name         = $step.Name
                            Parent       = $step.Parent.Name #$step.Name
                        }
                    }
                }
            }


            ## endpoints
            foreach ($endPoint in $endPoints) {
                [PSCustomObject]@{
                    ComputerName = $server.ComputerName
                    InstanceName = $server.ServiceName
                    SqlInstance  = $server.DomainInstanceName
                    Type         = "Endpoint"
                    Owner        = $endpoint.Owner
                    Name         = $endPoint.Name
                    Parent       = $endPoint.Parent.Name
                }
            }

            ## Server Roles
            if (-not $pattern) {
                foreach ($role in $server.Roles | Where-Object { $_.Owner -ne $saname }) {
                    Write-Message -Level Verbose -Message "checking if $db is owned "
                    [PSCustomObject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Type         = "Server Role"
                        Owner        = $role.Owner
                        Name         = $role.Name
                        Parent       = $role.Parent.Name
                    }
                }
            } else {
                foreach ($role in $server.Roles | Where-Object { $_.Owner -match $pattern }) {
                    [PSCustomObject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Type         = "Server Role"
                        Owner        = $role.Owner
                        Name         = $role.Name
                        Parent       = $role.Parent.Name
                    }
                }
            }

            ## Loop internal database
            foreach ($db in $server.Databases | Where-Object IsAccessible) {
                Write-Message -Level Verbose -Message "Gather user owned object in database: $db"
                ##schemas
                $sysSchemas = "DatabaseMailUserRole", "db_ssisadmin", "db_ssisltduser", "db_ssisoperator", "SQLAgentOperatorRole", "SQLAgentReaderRole", "SQLAgentUserRole", "TargetServersRole", "RSExecRole"

                if (-not $pattern) {
                    $schemas = $db.Schemas | Where-Object { $_.IsSystemObject -eq 0 -and $_.Owner -ne "dbo" -and $sysSchemas -notcontains $_.Owner }
                } else {
                    $schemas = $db.Schemas | Where-Object { $_.IsSystemObject -eq 0 -and $_.Owner -match $pattern -and $sysSchemas -notcontains $_.Owner }
                }
                foreach ($schema in $schemas) {
                    [PSCustomObject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Type         = "Schema"
                        Owner        = $schema.Owner
                        Name         = $schema.Name
                        Parent       = $schema.Parent.Name
                    }
                }

                ## database roles
                if (-not $pattern) {
                    $roles = $db.Roles | Where-Object { $_.IsSystemObject -eq 0 -and $_.Owner -ne "dbo" }
                } else {
                    $roles = $db.Roles | Where-Object { $_.IsSystemObject -eq 0 -and $_.Owner -match $pattern }
                }
                foreach ($role in $roles) {
                    [PSCustomObject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Type         = "Database Role"
                        Owner        = $role.Owner
                        Name         = $role.Name
                        Parent       = $role.Parent.Name
                    }
                }

                ## assembly
                if (-not $pattern) {
                    $assemblies = $db.Assemblies | Where-Object { $_.IsSystemObject -eq 0 -and $_.Owner -ne "dbo" }
                } else {
                    $assemblies = $db.Assemblies | Where-Object { $_.IsSystemObject -eq 0 -and $_.Owner -match $pattern }
                }

                foreach ($assembly in $assemblies) {
                    [PSCustomObject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Type         = "Database Assembly"
                        Owner        = $assembly.Owner
                        Name         = $assembly.Name
                        Parent       = $assembly.Parent.Name
                    }
                }

                ## synonyms
                if (-not $pattern) {
                    $synonyms = $db.Synonyms | Where-Object { $_.IsSystemObject -eq 0 -and $_.Owner -ne "dbo" }
                } else {
                    $synonyms = $db.Synonyms | Where-Object { $_.IsSystemObject -eq 0 -and $_.Owner -match $pattern }
                }

                foreach ($synonym in $synonyms) {
                    [PSCustomObject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Type         = "Database Synonyms"
                        Owner        = $synonym.Owner
                        Name         = $synonym.Name
                        Parent       = $synonym.Parent.Name
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Find-DbaView.ps1
function Find-DbaView {
    <#
    .SYNOPSIS
        Returns all views that contain a specific case-insensitive string or regex pattern.

    .DESCRIPTION
        This function can either run against specific databases or all databases searching all user or user and system views.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER Pattern
        String pattern that you want to search for in the view text body

    .PARAMETER IncludeSystemObjects
        By default, system views are ignored but you can include them within the search using this parameter.

        Warning - this will likely make it super slow if you run it on all databases.

    .PARAMETER IncludeSystemDatabases
        By default system databases are ignored but you can include them within the search using this parameter

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: View
        Author: Claudio Silva  (@ClaudioESSilva)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Find-DbaView

    .EXAMPLE
        PS C:\> Find-DbaView -SqlInstance DEV01 -Pattern whatever

        Searches all user databases views for "whatever" in the text body

    .EXAMPLE
        PS C:\> Find-DbaView -SqlInstance sql2016 -Pattern '\w+@\w+\.\w+'

        Searches all databases for all views that contain a valid email pattern in the text body

    .EXAMPLE
        PS C:\> Find-DbaView -SqlInstance DEV01 -Database MyDB -Pattern 'some string' -Verbose

        Searches in "mydb" database views for "some string" in the text body

    .EXAMPLE
        PS C:\> Find-DbaView -SqlInstance sql2016 -Database MyDB -Pattern RUNTIME -IncludeSystemObjects

        Searches in "mydb" database views for "runtime" in the text body

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [parameter(Mandatory)]
        [string]$Pattern,
        [switch]$IncludeSystemObjects,
        [switch]$IncludeSystemDatabases,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $sql = "SELECT OBJECT_SCHEMA_NAME(vw.object_id) as ViewSchema, vw.name, m.definition as TextBody FROM sys.sql_modules m, sys.views vw WHERE m.object_id = vw.object_id"
        if (!$IncludeSystemObjects) { $sql = "$sql AND vw.is_ms_shipped = 0" }
        $everyservervwcount = 0
    }
    process {
        foreach ($Instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $Instance -SqlCredential $SqlCredential
            } catch {
                Write-Message -Level Warning -Message "Failed to connect to: $Instance"
                continue
            }

            if ($server.versionMajor -lt 9) {
                Write-Message -Level Warning -Message "This command only supports SQL Server 2005 and above."
                Continue
            }

            if ($IncludeSystemDatabases) {
                $dbs = $server.Databases | Where-Object { $_.Status -eq "normal" }
            } else {
                $dbs = $server.Databases | Where-Object { $_.Status -eq "normal" -and $_.IsSystemObject -eq $false }
            }

            if ($Database) {
                $dbs = $dbs | Where-Object Name -In $Database
            }

            if ($ExcludeDatabase) {
                $dbs = $dbs | Where-Object Name -NotIn $ExcludeDatabase
            }

            $totalcount = 0
            $dbcount = $dbs.count
            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Searching on database $db"

                # If system objects aren't needed, find view text using SQL
                # This prevents SMO from having to enumerate

                if (!$IncludeSystemObjects) {
                    Write-Message -Level Debug -Message $sql
                    $rows = $db.ExecuteWithResults($sql).Tables.Rows
                    $vwcount = 0

                    foreach ($row in $rows) {
                        $totalcount++; $vwcount++; $everyservervwcount++

                        $viewSchema = $row.ViewSchema
                        $view = $row.name

                        Write-Message -Level Verbose -Message "Looking in View: $viewSchema.$view TextBody for $pattern"
                        if ($row.TextBody -match $Pattern) {
                            $vw = $db.Views | Where-Object {$_.Schema -eq $viewSchema -and $_.Name -eq $view}

                            $viewText = $vw.TextBody.split("`n`r")
                            $vwTextFound = $viewText | Select-String -Pattern $Pattern | ForEach-Object { "(LineNumber: $($_.LineNumber)) $($_.ToString().Trim())" }

                            [PSCustomObject]@{
                                ComputerName   = $server.ComputerName
                                SqlInstance    = $server.ServiceName
                                Database       = $db.Name
                                Schema         = $vw.Schema
                                Name           = $vw.Name
                                Owner          = $vw.Owner
                                IsSystemObject = $vw.IsSystemObject
                                CreateDate     = $vw.CreateDate
                                LastModified   = $vw.DateLastModified
                                ViewTextFound  = $vwTextFound -join "`n"
                                View           = $vw
                                ViewFullText   = $vw.TextBody
                            } | Select-DefaultView -ExcludeProperty View, ViewFullText
                        }
                    }
                } else {
                    $Views = $db.Views

                    foreach ($vw in $Views) {
                        $totalcount++; $vwcount++; $everyservervwcount++

                        $viewSchema = $row.ViewSchema
                        $view = $vw.Name

                        Write-Message -Level Verbose -Message "Looking in View: $viewSchema.$view TextBody for $pattern"
                        if ($vw.TextBody -match $Pattern) {

                            $viewText = $vw.TextBody.split("`n`r")
                            $vwTextFound = $viewText | Select-String -Pattern $Pattern | ForEach-Object { "(LineNumber: $($_.LineNumber)) $($_.ToString().Trim())" }

                            [PSCustomObject]@{
                                ComputerName   = $server.ComputerName
                                SqlInstance    = $server.ServiceName
                                Database       = $db.Name
                                Schema         = $vw.Schema
                                Name           = $vw.Name
                                Owner          = $vw.Owner
                                IsSystemObject = $vw.IsSystemObject
                                CreateDate     = $vw.CreateDate
                                LastModified   = $vw.DateLastModified
                                ViewTextFound  = $vwTextFound -join "`n"
                                View           = $vw
                                ViewFullText   = $vw.TextBody
                            } | Select-DefaultView -ExcludeProperty View, ViewFullText
                        }
                    }
                }
                Write-Message -Level Verbose -Message "Evaluated $vwcount views in $db"
            }
            Write-Message -Level Verbose -Message "Evaluated $totalcount total views in $dbcount databases"
        }
    }
    end {
        Write-Message -Level Verbose -Message "Evaluated $everyservervwcount total views"
    }
}
tools\dbatools\functions\Format-DbaBackupInformation.ps1
function Format-DbaBackupInformation {
    <#
    .SYNOPSIS
        Transforms the data in a dbatools BackupHistory object for a restore

    .DESCRIPTION
        Performs various mapping on Backup History, ready restoring
        Options include changing restore paths, backup paths, database name and many others

    .PARAMETER BackupHistory
        A dbatools backupHistory object, normally this will have been created using Select-DbaBackupInformation

    .PARAMETER ReplaceDatabaseName
        If a single value is provided, this will be replaced do all occurrences a database name
        If a Hashtable is passed in, each database name mention will be replaced as specified. If a database's name does not appear it will not be replace
        DatabaseName will also be replaced where it  occurs in the file paths of data and log files.
        Please note, that this won't change the Logical Names of data files, that has to be done with a separate Alter DB call

    .PARAMETER DatabaseNamePrefix
        This string will be prefixed to all restored database's name

    .PARAMETER DataFileDirectory
        This will move ALL restored files to this location during the restore

    .PARAMETER LogFileDirectory
        This will move all log files to this location, overriding DataFileDirectory

    .PARAMETER DestinationFileStreamDirectory
        This move the FileStream folder and contents to the new location, overriding DataFileDirectory

    .PARAMETER FileNamePrefix
        This string will  be prefixed to all restored files (Data and Log)

    .PARAMETER RebaseBackupFolder
        Use this to rebase where your backups are stored.

    .PARAMETER Continue
        Indicates that this is a continuing restore

    .PARAMETER DatabaseFilePrefix
        A string that will be prefixed to every file restored

    .PARAMETER DatabaseFileSuffix
        A string that will be suffixed to every file restored

    .PARAMETER ReplaceDbNameInFile
        If set, will replace the old database name with the new name if it occurs in the file name

    .PARAMETER FileMapping
        A hashtable that can be used to move specific files to a location.
        `$FileMapping = @{'DataFile1'='c:\restoredfiles\Datafile1.mdf';'DataFile3'='d:\DataFile3.mdf'}`
        And files not specified in the mapping will be restored to their original location
        This Parameter is exclusive with DestinationDataDirectory
        If specified, this will override any other file renaming/relocation options.

    .PARAMETER PathSep
        By default is Windows's style (`\`) but you can pass also, e.g., `/` for Unix's style paths

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DisasterRecovery, Backup, Restore
        Author: Stuart Moore (@napalmgram), stuart-moore.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Format-DbaBackupInformation

    .EXAMPLE
        PS C:\> $History | Format-DbaBackupInformation -ReplaceDatabaseName NewDb

        Changes as database name references to NewDb, both in the database name and any restore paths. Note, this will fail if the BackupHistory object contains backups for more than 1 database

    .EXAMPLE
        PS C:\> $History | Format-DbaBackupInformation -ReplaceDatabaseName @{'OldB'='NewDb';'ProdHr'='DevHr'}

        Will change all occurrences of original database name in the backup history (names and restore paths) using the mapping in the hashtable.
        In this example any occurrence of OldDb will be replaced with NewDb and ProdHr with DevPR

    .EXAMPLE
        PS C:\> $History | Format-DbaBackupInformation -DataFileDirectory 'D:\DataFiles\' -LogFileDirectory 'E:\LogFiles\

        This example with change the restore path for all data files (everything that is not a log file) to d:\datafiles
        And all Transaction Log files will be restored to E:\Logfiles

    .EXAMPLE
        PS C:\> $History | Format-DbaBackupInformation -RebaseBackupFolder f:\backups

        This example changes the location that SQL Server will look for the backups. This is useful if you've moved the backups to a different location

       #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [object[]]$BackupHistory,
        [object]$ReplaceDatabaseName,
        [switch]$ReplaceDbNameInFile,
        [string]$DataFileDirectory,
        [string]$LogFileDirectory,
        [string]$DestinationFileStreamDirectory,
        [string]$DatabaseNamePrefix,
        [string]$DatabaseFilePrefix,
        [string]$DatabaseFileSuffix,
        [string]$RebaseBackupFolder,
        [switch]$Continue,
        [hashtable]$FileMapping,
        [string]$PathSep = '\',
        [switch]$EnableException
    )
    begin {

        Write-Message -Message "Starting" -Level Verbose
        if ($null -ne $ReplaceDatabaseName) {
            if ($ReplaceDatabaseName -is [string] -or $ReplaceDatabaseName.ToString() -ne 'System.Collections.Hashtable') {
                Write-Message -Message "String passed in for DB rename" -Level Verbose
                $ReplaceDatabaseNameType = 'single'
            } elseif ($ReplaceDatabaseName -is [HashTable] -or $ReplaceDatabaseName.ToString() -eq 'System.Collections.Hashtable' ) {
                Write-Message -Message "Hashtable passed in for DB rename" -Level Verbose
                $ReplaceDatabaseNameType = 'multi'
            } else {
                Write-Message -Message "ReplacemenDatabaseName is $($ReplaceDatabaseName.Gettype().ToString()) - $ReplaceDatabaseName" -level Verbose
            }
        }
        if ((Test-Bound -Parameter DataFileDirectory) -and $DataFileDirectory.EndsWith($PathSep)) {
            $DataFileDirectory = $DataFileDirectory -Replace '.$'
        }
        if ((Test-Bound -Parameter DestinationFileStreamDirectory) -and $DestinationFileStreamDirectory.EndsWith($PathSep) ) {
            $DestinationFileStreamDirectory = $DestinationFileStreamDirectory -Replace '.$'
        }
        if ((Test-Bound -Parameter LogFileDirectory) -and $LogFileDirectory.EndsWith($PathSep) ) {
            $LogFileDirectory = $LogFileDirectory -Replace '.$'
        }
        if ((Test-Bound -Parameter RebaseBackupFolder) -and $RebaseBackupFolder.EndsWith($PathSep) ) {
            $RebaseBackupFolder = $RebaseBackupFolder -Replace '.$'
        }
    }


    process {

        foreach ($History in $BackupHistory) {
            if ("OriginalDatabase" -notin $History.PSobject.Properties.name) {
                $History | Add-Member -Name 'OriginalDatabase' -Type NoteProperty -Value $History.Database
            }
            if ("OriginalFileList" -notin $History.PSobject.Properties.name) {
                $History | Add-Member -Name 'OriginalFileList' -Type NoteProperty -Value ''
                $History | ForEach-Object {$_.OriginalFileList = $_.FileList}
            }
            if ("OriginalFullName" -notin $History.PSobject.Properties.name) {
                $History | Add-Member -Name 'OriginalFullName' -Type NoteProperty -Value $History.FullName
            }
            if ("IsVerified" -notin $History.PSobject.Properties.name) {
                $History | Add-Member -Name 'IsVerified' -Type NoteProperty -Value $False
            }
            switch ($History.Type) {
                'Full' {$History.Type = 'Database'}
                'Differential' {$History.Type = 'Database Differential'}
                'Log' {$History.Type = 'Transaction Log'}
            }


            if ($ReplaceDatabaseNameType -eq 'single' -and $ReplaceDatabaseName -ne '' ) {
                $History.Database = $ReplaceDatabaseName
                Write-Message -Message "New DbName (String) = $($History.Database)" -Level Verbose
            } elseif ($ReplaceDatabaseNameType -eq 'multi') {
                if ($null -ne $ReplaceDatabaseName[$History.Database]) {
                    $History.Database = $ReplaceDatabaseName[$History.Database]
                    Write-Message -Message "New DbName (Hash) = $($History.Database)" -Level Verbose
                }
            }
            $History.Database = $DatabaseNamePrefix + $History.Database
            if ($true -ne $Continue) {
                $History.FileList | ForEach-Object {
                    if ($null -ne $FileMapping ) {
                        if ($null -ne $FileMapping[$_.LogicalName]) {
                            $_.PhysicalName = $FileMapping[$_.LogicalName]
                        }
                    } else {
                        if ($ReplaceDbNameInFile -eq $true) {
                            $_.PhysicalName = $_.PhysicalName -Replace $History.OriginalDatabase, $History.Database
                        }
                        Write-Message -Message " 1 PhysicalName = $($_.PhysicalName) " -Level Verbose
                        $Pname = [System.Io.FileInfo]$_.PhysicalName
                        $RestoreDir = $Pname.DirectoryName
                        if ($_.Type -eq 'D' -or $_.FileType -eq 'D') {
                            if ('' -ne $DataFileDirectory) {
                                $RestoreDir = $DataFileDirectory
                            }
                        } elseif ($_.Type -eq 'L' -or $_.FileType -eq 'L') {
                            if ('' -ne $LogFileDirectory) {
                                $RestoreDir = $LogFileDirectory
                            } elseif ('' -ne $DataFileDirectory) {
                                $RestoreDir = $DataFileDirectory
                            }
                        } elseif ($_.Type -eq 'S' -or $_.FileType -eq 'S') {
                            if ('' -ne $DestinationFileStreamDirectory) {
                                $RestoreDir = $DestinationFileStreamDirectory
                            } elseif ('' -ne $DataFileDirectory) {
                                $RestoreDir = $DataFileDirectory
                            }
                        }

                        $_.PhysicalName = $RestoreDir + $PathSep + $DatabaseFilePrefix + $Pname.BaseName + $DatabaseFileSuffix + $Pname.extension
                        Write-Message -Message "PhysicalName = $($_.PhysicalName) " -Level Verbose
                    }
                }
            }
            if ('' -ne $RebaseBackupFolder -and $History.FullName[0] -notmatch 'http') {
                Write-Message -Message 'Rebasing backup files' -Level Verbose

                for ($j = 0; $j -lt $History.fullname.count; $j++) {
                    $file = [System.IO.FileInfo]($History.fullname[$j])
                    $History.fullname[$j] = $RebaseBackupFolder + $PathSep + $file.BaseName + $file.Extension
                }

            }

            $History
        }
    }
}
tools\dbatools\functions\Get-DbaAgDatabase.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaAgDatabase {
    <#
    .SYNOPSIS
        Gets availability group databases from a SQL Server instance.

    .DESCRIPTION
        Gets availability group databases from a SQL Server instance.

        Default view provides most common set of properties for information on the database in an availability group.

        Information returned on the database will be specific to that replica, whether it is primary or a secondary.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.

    .PARAMETER SqlCredential
        Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER AvailabilityGroup
        Specify the availability groups to query.

    .PARAMETER Database
        Specify the database or databases to return. This list is auto-populated from the server for tab completion. Multiple databases can be specified. If none are specified all databases will be processed.

    .PARAMETER InputObject
        Enables piped input from Get-DbaAvailabilityGroup.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Hadr, HA, AG, AvailabilityGroup, Replica
        Author: Shawn Melton (@wsmelton), https://wsmelton.github.io

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaAgDatabase

    .EXAMPLE
        PS C:\> Get-DbaAgDatabase -SqlInstance sql2017a

        Returns all the databases in each availability group found on sql2017a

    .EXAMPLE
        PS C:\> Get-DbaAgDatabase -SqlInstance sql2017a -AvailabilityGroup AG101

        Returns all the databases in the availability group AG101 on sql2017a

    .EXAMPLE
        PS C:\> Get-DbaAvailabilityGroup -SqlInstance sqlcluster -AvailabilityGroup SharePoint -Database Sharepoint_Config | Get-DbaAgDatabase

        Returns the database Sharepoint_Config found in the availability group SharePoint on server sqlcluster

    #>
    [CmdletBinding()]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$AvailabilityGroup,
        [string[]]$Database,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.AvailabilityGroup[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ($SqlInstance) {
            $InputObject += Get-DbaAvailabilityGroup -SqlInstance $SqlInstance -SqlCredential $SqlCredential -AvailabilityGroup $AvailabilityGroup
        }

        foreach ($db in $InputObject.AvailabilityDatabases) {
            if ($Database) {
                if ($db.Name -notin $Database) { continue }
            }
            $server = $db.Parent.Parent
            Add-Member -Force -InputObject $db -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
            Add-Member -Force -InputObject $db -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
            Add-Member -Force -InputObject $db -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
            Add-Member -Force -InputObject $db -MemberType NoteProperty -Name Replica -value $server.ComputerName
            Add-Member -Force -InputObject $db -MemberType NoteProperty -Name DatabaseName -value $db.Name # for backwards compat
            Add-Member -Force -InputObject $db -MemberType NoteProperty -Name AvailabilityGroup -value $db.Parent.Name

            $defaults = 'ComputerName', 'InstanceName', 'SqlInstance', 'AvailabilityGroup', 'Replica', 'Name', 'SynchronizationState', 'IsFailoverReady', 'IsJoined', 'IsSuspended'
            Select-DefaultView -InputObject $db -Property $defaults
        }
    }
}
tools\dbatools\functions\Get-DbaAgentAlert.ps1
function Get-DbaAgentAlert {
    <#
    .SYNOPSIS
        Returns all SQL Agent alerts on a SQL Server Agent.

    .DESCRIPTION
        This function returns SQL Agent alerts.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, SMO
        Author: Klaas Vandenberghe (@PowerDBAKlaas)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaAgentAlert

    .EXAMPLE
        PS C:\> Get-DbaAgentAlert -SqlInstance ServerA,ServerB\instanceB

        Returns all SQL Agent alerts on serverA and serverB\instanceB

    .EXAMPLE
        PS C:\> 'serverA','serverB\instanceB' | Get-DbaAgentAlert

        Returns all SQL Agent alerts  on serverA and serverB\instanceB

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "Instance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]
        $SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            Write-Message -Level Verbose -Message "Getting Edition from $server"
            Write-Message -Level Verbose -Message "$server is a $($server.Edition)"

            if ($server.Edition -like 'Express*') {
                Stop-Function -Message "There is no SQL Agent on $server, it's a $($server.Edition)" -Continue
            }

            $defaults = "ComputerName", "SqlInstance", "InstanceName", "Name", "ID", "JobName", "AlertType", "CategoryName", "Severity", "IsEnabled", "DelayBetweenResponses", "LastRaised", "OccurrenceCount"

            $alerts = $server.Jobserver.Alerts

            foreach ($alert in $alerts) {
                $lastraised = [dbadatetime]$alert.LastOccurrenceDate

                Add-Member -Force -InputObject $alert -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                Add-Member -Force -InputObject $alert -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                Add-Member -Force -InputObject $alert -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                Add-Member -Force -InputObject $alert -MemberType NoteProperty Notifications -value $alert.EnumNotifications()
                Add-Member -Force -InputObject $alert -MemberType NoteProperty LastRaised -value $lastraised

                Select-DefaultView -InputObject $alert -Property $defaults
            }
        }
    }
}
tools\dbatools\functions\Get-DbaAgentJob.ps1
#ValidationTags#Messaging#
function Get-DbaAgentJob {
    <#
    .SYNOPSIS
        Gets SQL Agent Job information for each instance(s) of SQL Server.

    .DESCRIPTION
        The Get-DbaAgentJob returns connected SMO object for SQL Agent Job information for each instance(s) of SQL Server.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Job
        The job(s) to process - this list is auto-populated from the server. If unspecified, all jobs will be processed.

    .PARAMETER ExcludeJob
        The job(s) to exclude - this list is auto-populated from the server.

    .PARAMETER ExcludeDisabledJobs
        Switch will exclude disabled jobs from the output.

    .PARAMETER Database
        Return jobs with T-SQL job steps associated with specific databases
    
    .PARAMETER Category
        Return jobs associated with specific category
    
    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Job, Agent
        Author: Garry Bargsley (@gbargsley), http://blog.garrybargsley.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaAgentJob

    .EXAMPLE
        PS C:\> Get-DbaAgentJob -SqlInstance localhost

        Returns all SQL Agent Jobs on the local default SQL Server instance

    .EXAMPLE
        PS C:\> Get-DbaAgentJob -SqlInstance localhost, sql2016

        Returns all SQl Agent Jobs for the local and sql2016 SQL Server instances

    .EXAMPLE
        PS C:\> Get-DbaAgentJob -SqlInstance localhost -Job BackupData, BackupDiff

        Returns all SQL Agent Jobs named BackupData and BackupDiff from the local SQL Server instance.

    .EXAMPLE
        PS C:\> Get-DbaAgentJob -SqlInstance localhost -ExcludeJob BackupDiff

        Returns all SQl Agent Jobs for the local SQL Server instances, except the BackupDiff Job.

    .EXAMPLE
        PS C:\> Get-DbaAgentJob -SqlInstance localhost -ExcludeDisabledJobs

        Returns all SQl Agent Jobs for the local SQL Server instances, excluding the disabled jobs.

    .EXAMPLE
        PS C:\> $servers | Get-DbaAgentJob | Out-GridView -PassThru | Start-DbaAgentJob -WhatIf

        Find all of your Jobs from SQL Server instances in the $servers collection, select the jobs you want to start then see jobs would start if you ran Start-DbaAgentJob
    .EXAMPLE
       PS C:\> Get-DbaAgentJob -SqlInstance sqlserver2014a | Where-Object Category -eq "Report Server" | Export-DbaScript -Path "C:\temp\sqlserver2014a_SSRSJobs.sql"
        
        Exports all SSRS jobs from SQL instance sqlserver2014a to a file.
    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Job,
        [string[]]$ExcludeJob,
        [string[]]$Database,
        [string[]]$Category,
        [switch]$ExcludeDisabledJobs,
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $jobs = $server.JobServer.Jobs

            if ($Job) {
                $jobs = $jobs | Where-Object Name -In $Job
            }
            if ($ExcludeJob) {
                $jobs = $jobs | Where-Object Name -NotIn $ExcludeJob
            }
            if ($ExcludeDisabledJobs) {
                $jobs = $Jobs | Where-Object IsEnabled -eq $true
            }
            if ($Database) {
                $jobs = $jobs | Where-Object {
                    $_.JobSteps.DatabaseName -in $Database
                }
            }
            if ($Category) {
                $jobs = $jobs | Where-Object Category -in $Category
            }
            
            foreach ($agentJob in $jobs) {
                Add-Member -Force -InputObject $agentJob -MemberType NoteProperty -Name ComputerName -value $agentJob.Parent.Parent.ComputerName
                Add-Member -Force -InputObject $agentJob -MemberType NoteProperty -Name InstanceName -value $agentJob.Parent.Parent.ServiceName
                Add-Member -Force -InputObject $agentJob -MemberType NoteProperty -Name SqlInstance -value $agentJob.Parent.Parent.DomainInstanceName

                Select-DefaultView -InputObject $agentJob -Property ComputerName, InstanceName, SqlInstance, Name, Category, OwnerLoginName, CurrentRunStatus, CurrentRunRetryAttempt, 'IsEnabled as Enabled', LastRunDate, LastRunOutcome, HasSchedule, OperatorToEmail, 'DateCreated as CreateDate'
            }
        }
    }
}
tools\dbatools\functions\Get-DbaAgentJobCategory.ps1
function Get-DbaAgentJobCategory {
    <#
    .SYNOPSIS
        Get-DbaAgentJobCategory retrieves the job categories.

    .DESCRIPTION
        Get-DbaAgentJobCategory makes it possible to retrieve the job categories.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Category
        The name of the category to filter out. If no category is used all categories will be returned.

    .PARAMETER CategoryType
        The type of category. This can be "LocalJob", "MultiServerJob" or "None".
        If no category is used all categories types will be returned.

    .PARAMETER Force
        The force parameter will ignore some errors in the parameters and assume defaults.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Job, JobCategory
        Author: Sander Stad (@sqlstad), sqlstad.nl

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaAgentJobCategory

    .EXAMPLE
        PS C:\> Get-DbaAgentJobCategory -SqlInstance sql1

        Return all the job categories.

    .EXAMPLE
        PS C:\> Get-DbaAgentJobCategory -SqlInstance sql1 -Category 'Log Shipping'

        Return all the job categories that have the name 'Log Shipping'.

    .EXAMPLE
        PS C:\> Get-DbaAgentJobCategory -SqlInstance sstad-pc -CategoryType MultiServerJob

        Return all the job categories that have a type MultiServerJob.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [ValidateNotNullOrEmpty()]
        [string[]]$Category,
        [ValidateSet("LocalJob", "MultiServerJob", "None")]
        [string]$CategoryType,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            # get all the job categories
            $jobCategories = $server.JobServer.JobCategories |
                Where-Object {
                ($_.Name -in $Category -or !$Category) -and
                ($_.CategoryType -in $CategoryType -or !$CategoryType)
            }

            # Set the default output
            $defaults = 'ComputerName', 'InstanceName', 'SqlInstance', 'Name', 'ID', 'CategoryType', 'JobCount'

            # Loop through each of the categories
            try {
                foreach ($cat in $jobCategories) {

                    # Get the jobs associated with the category
                    $jobCount = ($server.JobServer.Jobs | Where-Object {$_.CategoryID -eq $cat.ID}).Count

                    # Add new properties to the category object
                    Add-Member -Force -InputObject $cat -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                    Add-Member -Force -InputObject $cat -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                    Add-Member -Force -InputObject $cat -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                    Add-Member -Force -InputObject $cat -MemberType NoteProperty -Name JobCount -Value $jobCount

                    # Show the result
                    Select-DefaultView -InputObject $cat -Property $defaults
                }
            } catch {
                Stop-Function -ErrorRecord $_ -Target $instance -Message "Failure. Collection may have been modified" -Continue
            }

        } # for each instance

    } # end process

    end {
        if (Test-FunctionInterrupt) { return }
        Write-Message -Message "Finished retrieving job category." -Level Verbose
    }

}
tools\dbatools\functions\Get-DbaAgentJobHistory.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaAgentJobHistory {
    <#
    .SYNOPSIS
        Gets execution history of SQL Agent Job on instance(s) of SQL Server.

    .DESCRIPTION
        Get-DbaAgentJobHistory returns all information on the executions still available on each instance(s) of SQL Server submitted.
        The cleanup of SQL Agent history determines how many records are kept.

        https://msdn.microsoft.com/en-us/library/ms201680.aspx
        https://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.agent.jobhistoryfilter(v=sql.120).aspx

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Job
        The name of the job from which the history is wanted. If unspecified, all jobs will be processed.

    .PARAMETER ExcludeJob
        The job(s) to exclude - this list is auto-populated from the server

    .PARAMETER StartDate
        The DateTime starting from which the history is wanted. If unspecified, all available records will be processed.

    .PARAMETER EndDate
        The DateTime before which the history is wanted. If unspecified, all available records will be processed.

    .PARAMETER ExcludeJobSteps
        Use this switch to discard all job steps, and return only the job totals

    .PARAMETER WithOutputFile
        Use this switch to retrieve the output file (only if you want step details). Bonus points, we handle the quirks
        of SQL Agent tokens to the best of our knowledge (https://technet.microsoft.com/it-it/library/ms175575(v=sql.110).aspx)

    .PARAMETER JobCollection
        An array of SMO jobs

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Job, Agent
        Author: Klaas Vandenberghe (@PowerDbaKlaas) | Simone Bizzotto (@niphold)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaAgentJobHistory

    .EXAMPLE
        PS C:\> Get-DbaAgentJobHistory -SqlInstance localhost

        Returns all SQL Agent Job execution results on the local default SQL Server instance.

    .EXAMPLE
        PS C:\> Get-DbaAgentJobHistory -SqlInstance localhost, sql2016

        Returns all SQL Agent Job execution results for the local and sql2016 SQL Server instances.

    .EXAMPLE
        PS C:\> 'sql1','sql2\Inst2K17' | Get-DbaAgentJobHistory

        Returns all SQL Agent Job execution results for sql1 and sql2\Inst2K17.

    .EXAMPLE
        PS C:\> Get-DbaAgentJobHistory -SqlInstance sql2\Inst2K17 | Select-Object *

        Returns all properties for all SQl Agent Job execution results on sql2\Inst2K17.

    .EXAMPLE
        PS C:\> Get-DbaAgentJobHistory -SqlInstance sql2\Inst2K17 -Job 'Output File Cleanup'

        Returns all properties for all SQl Agent Job execution results of the 'Output File Cleanup' job on sql2\Inst2K17.

    .EXAMPLE
        PS C:\> Get-DbaAgentJobHistory -SqlInstance sql2\Inst2K17 -Job 'Output File Cleanup' -WithOutputFile

        Returns all properties for all SQl Agent Job execution results of the 'Output File Cleanup' job on sql2\Inst2K17,
        with additional properties that show the output filename path

    .EXAMPLE
        PS C:\> Get-DbaAgentJobHistory -SqlInstance sql2\Inst2K17 -ExcludeJobSteps

        Returns the SQL Agent Job execution results for the whole jobs on sql2\Inst2K17, leaving out job step execution results.

    .EXAMPLE
        PS C:\> Get-DbaAgentJobHistory -SqlInstance sql2\Inst2K17 -StartDate '2017-05-22' -EndDate '2017-05-23 12:30:00'

        Returns the SQL Agent Job execution results between 2017/05/22 00:00:00 and 2017/05/23 12:30:00 on sql2\Inst2K17.

    .EXAMPLE
        PS C:\> Get-DbaAgentJob -SqlInstance sql2016 | Where-Object Name -Match backup | Get-DbaAgentJobHistory

        Gets all jobs with the name that match the regex pattern "backup" and then gets the job history from those. You can also use -Like *backup* in this example.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default")]
    param (
        [parameter(Mandatory, ValueFromPipeline, ParameterSetName = "Server")]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]
        $SqlCredential,
        [object[]]$Job,
        [object[]]$ExcludeJob,
        [DateTime]$StartDate = "1900-01-01",
        [DateTime]$EndDate = $(Get-Date),
        [switch]$ExcludeJobSteps,
        [switch]$WithOutputFile,
        [parameter(Mandatory, ValueFromPipeline, ParameterSetName = "Collection")]
        [Microsoft.SqlServer.Management.Smo.Agent.Job]$JobCollection,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $filter = New-Object Microsoft.SqlServer.Management.Smo.Agent.JobHistoryFilter
        $filter.StartRunDate = $StartDate
        $filter.EndRunDate = $EndDate


        if ($ExcludeJobSteps -and $WithOutputFile) {
            Stop-Function -Message "You can't use -ExcludeJobSteps and -WithOutputFile together"
        }

        function Get-JobHistory {
            [CmdletBinding()]
            param (
                $Server,
                $Job,
                [switch]$WithOutputFile
            )
            $tokenrex = [regex]'\$\((?<method>[^()]+)\((?<tok>[^)]+)\)\)|\$\((?<tok>[^)]+)\)'
            $propmap = @{
                'INST'      = $Server.ServiceName
                'MACH'      = $Server.ComputerName
                'SQLDIR'    = $Server.InstallDataDirectory
                'SQLLOGDIR' = $Server.ErrorLogPath
                #'STEPCT' loop number ?
                'SRVR'      = $Server.DomainInstanceName
                # WMI( property ) impossible
            }


            $squote_rex = [regex]"(?<!')'(?!')"
            $dquote_rex = [regex]'(?<!")"(?!")'
            $rbrack_rex = [regex]'(?<!])](?!])'

            function Resolve-TokenEscape($method, $value) {
                if (!$method) {
                    return $value
                }
                $value = switch ($method) {
                    'ESCAPE_SQUOTE' { $squote_rex.Replace($value, "''") }
                    'ESCAPE_DQUOTE' { $dquote_rex.Replace($value, '""') }
                    'ESCAPE_RBRACKET' { $rbrack_rex.Replace($value, ']]') }
                    'ESCAPE_NONE' { $value }
                    default { $value }
                }
                return $value
            }

            #'STEPID' =  stepid
            #'STRTTM' job begin time
            #'STRTDT' job begin date
            #'JOBID' = JobId
            function Resolve-JobToken($exec, $outfile, $outcome) {
                $n = $tokenrex.Matches($outfile)
                foreach ($x in $n) {
                    $tok = $x.Groups['tok'].Value
                    $EscMethod = $x.Groups['method'].Value
                    if ($propmap.containskey($tok)) {
                        $repl = Resolve-TokenEscape -method $EscMethod -value $propmap[$tok]
                        $outfile = $outfile.Replace($x.Value, $repl)
                    } elseif ($tok -eq 'STEPID') {
                        $repl = Resolve-TokenEscape -method $EscMethod -value $exec.StepID
                        $outfile = $outfile.Replace($x.Value, $repl)
                    } elseif ($tok -eq 'JOBID') {
                        # convert(binary(16), ?)
                        $repl = @('0x') + @($exec.JobID.ToByteArray() | ForEach-Object -Process { $_.ToString('X2') }) -join ''
                        $repl = Resolve-TokenEscape -method $EscMethod -value $repl
                        $outfile = $outfile.Replace($x.Value, $repl)
                    } elseif ($tok -eq 'STRTDT') {
                        $repl = Resolve-TokenEscape -method $EscMethod -value $outcome.RunDate.toString('yyyyMMdd')
                        $outfile = $outfile.Replace($x.Value, $repl)
                    } elseif ($tok -eq 'STRTTM') {
                        $repl = Resolve-TokenEscape -method $EscMethod -value ([int]$outcome.RunDate.toString('HHmmss')).toString()
                        $outfile = $outfile.Replace($x.Value, $repl)
                    } elseif ($tok -eq 'DATE') {
                        $repl = Resolve-TokenEscape -method $EscMethod -value $exec.RunDate.toString('yyyyMMdd')
                        $outfile = $outfile.Replace($x.Value, $repl)
                    } elseif ($tok -eq 'TIME') {
                        $repl = Resolve-TokenEscape -method $EscMethod -value ([int]$exec.RunDate.toString('HHmmss')).toString()
                        $outfile = $outfile.Replace($x.Value, $repl)
                    }
                }
                return $outfile
            }
            try {
                Write-Message -Message "Attempting to get job history from $instance" -Level Verbose
                if ($Job) {
                    foreach ($currentjob in $Job) {
                        $filter.JobName = $currentjob
                        $executions += $server.JobServer.EnumJobHistory($filter)
                    }
                } else {
                    $executions = $server.JobServer.EnumJobHistory($filter)
                }
                if ($ExcludeJobSteps) {
                    $executions = $executions | Where-Object { $_.StepID -eq 0 }
                }

                if ($WithOutputFile) {
                    $outmap = @{}
                    $outfiles = Get-DbaAgentJobOutputFile -SqlInstance $Server -SqlCredential $SqlCredential -Job $Job

                    foreach ($out in $outfiles) {
                        if (!$outmap.ContainsKey($out.Job)) {
                            $outmap[$out.Job] = @{}
                        }
                        $outmap[$out.Job][$out.StepId] = $out.OutputFileName
                    }
                }
                $outcome = [pscustomobject]@{}
                foreach ($execution in $executions) {
                    $status = switch ($execution.RunStatus) {
                        0 { "Failed" }
                        1 { "Succeeded" }
                        2 { "Retry" }
                        3 { "Canceled" }
                    }

                    Add-Member -Force -InputObject $execution -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                    Add-Member -Force -InputObject $execution -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                    Add-Member -Force -InputObject $execution -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                    $DurationInSeconds = ($execution.RunDuration % 100) + [int]( ($execution.RunDuration % 10000 ) / 100 ) * 60 + [int]( ($execution.RunDuration % 1000000 ) / 10000 ) * 60 * 60
                    Add-Member -Force -InputObject $execution -MemberType NoteProperty -Name StartDate -value ([dbadatetime]$execution.RunDate)
                    Add-Member -Force -InputObject $execution -MemberType NoteProperty -Name EndDate -value ([dbadatetime]$execution.RunDate.AddSeconds($DurationInSeconds))
                    Add-Member -Force -InputObject $execution -MemberType NoteProperty -Name Duration -value ([prettytimespan](New-TimeSpan -Seconds $DurationInSeconds))
                    Add-Member -Force -InputObject $execution -MemberType NoteProperty -Name Status -value $status
                    if ($WithOutputFile) {
                        if ($execution.StepID -eq 0) {
                            $outcome = $execution
                        }
                        try {
                            $outname = $outmap[$execution.JobName][$execution.StepID]
                            $outname = Resolve-JobToken -exec $execution -outcome $outcome -outfile $outname
                            $outremote = Join-AdminUNC $Server.ComputerName $outname
                        } catch {
                            $outname = ''
                            $outremote = ''
                        }
                        Add-Member -Force -InputObject $execution -MemberType NoteProperty -Name OutputFileName -value $outname
                        Add-Member -Force -InputObject $execution -MemberType NoteProperty -Name RemoteOutputFileName -value $outremote
                        # Add this in for easier ConvertTo-DbaTimeline Support
                        Add-Member -Force -InputObject $execution -MemberType NoteProperty -Name TypeName -value AgentJobHistory
                        Select-DefaultView -InputObject $execution -Property ComputerName, InstanceName, SqlInstance, 'JobName as Job', StepName, RunDate, StartDate, EndDate, Duration, Status, OperatorEmailed, Message, OutputFileName, RemoteOutputFileName -TypeName AgentJobHistory
                    } else {
                        Add-Member -Force -InputObject $execution -MemberType NoteProperty -Name TypeName -value AgentJobHistory
                        Select-DefaultView -InputObject $execution -Property ComputerName, InstanceName, SqlInstance, 'JobName as Job', StepName, RunDate, StartDate, EndDate, Duration, Status, OperatorEmailed, Message -TypeName AgentJobHistory
                    }

                }
            } catch {
                Stop-Function -Message "Could not get Agent Job History from $instance" -Target $instance -Continue
            }
        }
    }

    process {

        if (Test-FunctionInterrupt) { return }

        if ($JobCollection) {
            foreach ($currentjob in $JobCollection) {
                Get-JobHistory -Server $currentjob.Parent.Parent -Job $currentjob.Name -WithOutputFile:$WithOutputFile
            }
        }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }


            if ($ExcludeJob) {
                $jobs = $server.JobServer.Jobs.Name | Where-Object { $_ -notin $ExcludeJob }
                foreach ($currentjob in $jobs) {
                    Get-JobHistory -Server $server -Job $currentjob -WithOutputFile:$WithOutputFile
                }
            } else {
                Get-JobHistory -Server $server -Job $Job -WithOutputFile:$WithOutputFile
            }
        }
    }
}
tools\dbatools\functions\Get-DbaAgentJobOutputFile.ps1
function Get-DbaAgentJobOutputFile {
    <#
    .Synopsis
        Returns the Output File for each step of one or many agent job with the Job Names provided dynamically if
        required for one or more SQL Instances

    .DESCRIPTION
        This function returns for one or more SQL Instances the output file value for each step of one or many agent job with the Job Names
        provided dynamically. It will not return anything if there is no Output File

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SQLCredential
        Credential object used to connect to the SQL Server as a different user be it Windows or SQL Server. Windows users are determined by the existence of a backslash, so if you are intending to use an alternative Windows connection instead of a SQL login, ensure it contains a backslash.

    .PARAMETER Job
        The job(s) to process - this list is auto-populated from the server. If unspecified, all jobs will be processed.

    .PARAMETER ExcludeJob
        The job(s) to exclude - this list is auto-populated from the server

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Job
        Author: Rob Sewell (https://sqldbawithabeard.com) | Simone Bizzotto (@niphold)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaAgentJobOutputFile -SqlInstance SERVERNAME -Job 'The Agent Job'

        This will return the configured paths to the output files for each of the job step of the The Agent Job Job
        on the SERVERNAME instance

    .EXAMPLE
        PS C:\> Get-DbaAgentJobOutputFile -SqlInstance SERVERNAME

        This will return the configured paths to the output files for each of the job step of all the Agent Jobs
        on the SERVERNAME instance

    .EXAMPLE
        PS C:\> Get-DbaAgentJobOutputFile -SqlInstance SERVERNAME,SERVERNAME2 -Job 'The Agent Job'

        This will return the configured paths to the output files for each of the job step of the The Agent Job Job
        on the SERVERNAME instance and SERVERNAME2

    .EXAMPLE
        $Servers = 'SERVER','SERVER\INSTANCE1'
        Get-DbaAgentJobOutputFile -SqlInstance $Servers -Job 'The Agent Job' -OpenFile

        This will return the configured paths to the output files for each of the job step of the The Agent Job Job
        on the SERVER instance and the SERVER\INSTANCE1 and open the files if they are available

    .EXAMPLE
        PS C:\> Get-DbaAgentJobOutputFile -SqlInstance SERVERNAME  | Out-GridView

        This will return the configured paths to the output files for each of the job step of all the Agent Jobs
        on the SERVERNAME instance and Pipe them to Out-GridView

    .EXAMPLE
        PS C:\> (Get-DbaAgentJobOutputFile -SqlInstance SERVERNAME | Out-GridView -PassThru).FileName | Invoke-Item

        This will return the configured paths to the output files for each of the job step of all the Agent Jobs
        on the SERVERNAME instance and Pipe them to Out-GridView and enable you to choose the output
        file and open it

    .EXAMPLE
        PS C:\> Get-DbaAgentJobOutputFile -SqlInstance SERVERNAME -Verbose

        This will return the configured paths to the output files for each of the job step of all the Agent Jobs
        on the SERVERNAME instance and also show the job steps without an output file

    #>
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory, HelpMessage = 'The SQL Server Instance',
            ValueFromPipeline,
            ValueFromPipelineByPropertyName = $true,
            ValueFromRemainingArguments = $false,
            Position = 0)]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Parameter(HelpMessage = 'SQL Credential',
            ValueFromPipelineByPropertyName = $true,
            ValueFromRemainingArguments = $false,
            Position = 1)]
        [PSCredential]$SqlCredential,
        [object[]]$Job,
        [object[]]$ExcludeJob,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $sqlinstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $jobs = $Server.JobServer.Jobs
            if ($Job) {
                $jobs = $jobs | Where-Object Name -In $Job
            }
            if ($ExcludeJob) {
                $jobs = $jobs | Where-Object Name -NotIn $ExcludeJob
            }
            foreach ($j in $Jobs) {
                foreach ($Step in $j.JobSteps) {
                    if ($Step.OutputFileName) {
                        [pscustomobject]@{
                            ComputerName         = $server.ComputerName
                            InstanceName         = $server.ServiceName
                            SqlInstance          = $server.DomainInstanceName
                            Job                  = $j.Name
                            JobStep              = $Step.Name
                            OutputFileName       = $Step.OutputFileName
                            RemoteOutputFileName = Join-AdminUNC $Server.ComputerName $Step.OutputFileName
                            StepId               = $Step.Id
                        } | Select-DefaultView -ExcludeProperty StepId
                    } else {
                        Write-Message -Level Verbose -Message "$step for $j has no output file"
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaAgentJobStep.ps1
function Get-DbaAgentJobStep {
    <#
    .SYNOPSIS
        Gets SQL Agent Job Step information for each instance(s) of SQL Server.

    .DESCRIPTION
        The Get-DbaAgentJobStep returns connected SMO object for SQL Agent Job Step for each instance(s) of SQL Server.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Job
        The job(s) to process - this list is auto-populated from the server. If unspecified, all jobs will be processed.

    .PARAMETER ExcludeJob
        The job(s) to exclude - this list is auto-populated from the server.

    .PARAMETER ExcludeDisabledJobs
        Switch will exclude disabled jobs from the output.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Job, Agent
        Author: Klaas Vandenberghe (@PowerDbaKlaas), http://powerdba.eu

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaAgentJobStep

    .EXAMPLE
        PS C:\> Get-DbaAgentJobStep -SqlInstance localhost

        Returns all SQL Agent Job Steps on the local default SQL Server instance

    .EXAMPLE
        PS C:\> Get-DbaAgentJobStep -SqlInstance localhost, sql2016

        Returns all SQL Agent Job Steps for the local and sql2016 SQL Server instances

    .EXAMPLE
        PS C:\> Get-DbaAgentJobStep -SqlInstance localhost -Job BackupData, BackupDiff

        Returns all SQL Agent Job Steps for the jobs named BackupData and BackupDiff from the local SQL Server instance.

    .EXAMPLE
        PS C:\> Get-DbaAgentJobStep -SqlInstance localhost -ExcludeJob BackupDiff

        Returns all SQL Agent Job Steps for the local SQL Server instances, except for the BackupDiff Job.

    .EXAMPLE
        PS C:\> Get-DbaAgentJobStep -SqlInstance localhost -ExcludeDisabledJobs

        Returns all SQL Agent Job Steps for the local SQL Server instances, excluding the disabled jobs.

    .EXAMPLE
        PS C:\> $servers | Get-DbaAgentJobStep

        Find all of your Job Steps from SQL Server instances in the $servers collection

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]
        $SqlCredential,
        [object[]]$Job,
        [object[]]$ExcludeJob,
        [switch]$ExcludeDisabledJobs,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            Write-Message -Level Verbose -Message "Collecting jobs on $instance"
            $jobs = $server.JobServer.Jobs

            if ($Job) {
                $jobs = $jobs | Where-Object Name -In $Job
            }
            if ($ExcludeJob) {
                $jobs = $jobs | Where-Object Name -NotIn $ExcludeJob
            }
            if ($ExcludeDisabledJobs) {
                $jobs = $Jobs | Where-Object IsEnabled -eq $true
            }
            Write-Message -Level Verbose -Message "Collecting job steps on $instance"
            foreach ($agentJobStep in $jobs.jobsteps) {
                Add-Member -Force -InputObject $agentJobStep -MemberType NoteProperty -Name ComputerName -value $agentJobStep.Parent.Parent.Parent.ComputerName
                Add-Member -Force -InputObject $agentJobStep -MemberType NoteProperty -Name InstanceName -value $agentJobStep.Parent.Parent.Parent.ServiceName
                Add-Member -Force -InputObject $agentJobStep -MemberType NoteProperty -Name SqlInstance -value $agentJobStep.Parent.Parent.Parent.DomainInstanceName
                Add-Member -Force -InputObject $agentJobStep -MemberType NoteProperty -Name AgentJob -value $agentJobStep.Parent.Name

                Select-DefaultView -InputObject $agentJobStep -Property ComputerName, InstanceName, SqlInstance, AgentJob, Name, SubSystem, LastRunDate, LastRunOutcome, State
            }
        }
    }
}
tools\dbatools\functions\Get-DbaAgentLog.ps1
function Get-DbaAgentLog {
    <#
    .SYNOPSIS
        Gets the "SQL Agent Error Log" of an instance

    .DESCRIPTION
        Gets the "SQL Agent Error Log" of an instance. Returns all 10 error logs by default.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.

    .PARAMETER LogNumber
        An Int32 value that specifies the index number of the error log required. Error logs are listed 0 through 9 where 0 is the current error log and 9 is the oldest.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Logging
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaAgentLog

    .EXAMPLE
        PS C:\> Get-DbaAgentLog -SqlInstance sql01\sharepoint

        Returns the entire error log for the SQL Agent on sql01\sharepoint

    .EXAMPLE
        PS C:\> Get-DbaAgentLog -SqlInstance sql01\sharepoint -LogNumber 3, 6

        Returns log numbers 3 and 6 for the SQL Agent on sql01\sharepoint

    .EXAMPLE
        PS C:\> $servers = "sql2014","sql2016", "sqlcluster\sharepoint"
        PS C:\> $servers | Get-DbaAgentLog -LogNumber 0

        Returns the most recent SQL Agent error logs for "sql2014","sql2016" and "sqlcluster\sharepoint"

    #>
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]
        $SqlCredential,
        [ValidateRange(0, 9)]
        [int[]]$LogNumber,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($LogNumber) {
                foreach ($number in $lognumber) {
                    try {
                        foreach ($object in $server.JobServer.ReadErrorLog($number)) {
                            Write-Message -Level Verbose -Message "Processing $object"
                            Add-Member -Force -InputObject $object -MemberType NoteProperty ComputerName -value $server.ComputerName
                            Add-Member -Force -InputObject $object -MemberType NoteProperty InstanceName -value $server.ServiceName
                            Add-Member -Force -InputObject $object -MemberType NoteProperty SqlInstance -value $server.DomainInstanceName

                            # Select all of the columns you'd like to show
                            Select-DefaultView -InputObject $object -Property ComputerName, InstanceName, SqlInstance, LogDate, ProcessInfo, Text
                        }
                    } catch {
                        Stop-Function -Continue -Target $server -Message "Could not read from SQL Server Agent"
                    }
                }
            } else {
                try {
                    foreach ($object in $server.JobServer.ReadErrorLog()) {
                        Write-Message -Level Verbose -Message "Processing $object"
                        Add-Member -Force -InputObject $object -MemberType NoteProperty ComputerName -value $server.ComputerName
                        Add-Member -Force -InputObject $object -MemberType NoteProperty InstanceName -value $server.ServiceName
                        Add-Member -Force -InputObject $object -MemberType NoteProperty SqlInstance -value $server.DomainInstanceName

                        # Select all of the columns you'd like to show
                        Select-DefaultView -InputObject $object -Property ComputerName, InstanceName, SqlInstance, LogDate, ProcessInfo, Text
                    }
                } catch {
                    Stop-Function -Continue -Target $server -Message "Could not read from SQL Server Agent"
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaAgentOperator.ps1
function Get-DbaAgentOperator {
    <#
    .SYNOPSIS
        Returns all SQL Agent operators on a SQL Server Agent.

    .DESCRIPTION
        This function returns SQL Agent operators.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Operator
        The operator(s) to process - this list is auto-populated from the server. If unspecified, all operators will be processed.

    .PARAMETER ExcludeOperator
        The operator(s) to exclude - this list is auto-populated from the server

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Operator
        Author: Klaas Vandenberghe (@PowerDBAKlaas)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaAgentOperator

    .EXAMPLE
        PS C:\> Get-DbaAgentOperator -SqlInstance ServerA,ServerB\instanceB

        Returns any SQL Agent operators on serverA and serverB\instanceB

    .EXAMPLE
        PS C:\> 'ServerA','ServerB\instanceB' | Get-DbaAgentOperator

        Returns all SQL Agent operators  on serverA and serverB\instanceB

    .EXAMPLE
        PS C:\> Get-DbaAgentOperator -SqlInstance ServerA -Operator Dba1,Dba2

        Returns only the SQL Agent Operators Dba1 and Dba2 on ServerA.

    .EXAMPLE
        PS C:\> Get-DbaAgentOperator -SqlInstance ServerA,ServerB -ExcludeOperator Dba3

        Returns all the SQL Agent operators on ServerA and ServerB, except the Dba3 operator.

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]
        $SqlCredential,
        [object[]]$Operator,
        [object[]]$ExcludeOperator,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            Write-Message -Level Verbose -Message "Getting Edition from $server"
            Write-Message -Level Verbose -Message "$server is a $($server.Edition)"

            if ($server.Edition -like 'Express*') {
                Stop-Function -Message "There is no SQL Agent on $server, it's a $($server.Edition)" -Continue -Target $server
            }

            $defaults = "ComputerName", "SqlInstance", "InstanceName", "Name", "ID", "Enabled as IsEnabled", "EmailAddress", "LastEmail"

            if ($Operator) {
                $operators = $server.JobServer.Operators | Where-Object Name -In $Operator
            } elseif ($ExcludeOperator) {
                $operators = $server.JobServer.Operators | Where-Object Name -NotIn $ExcludeOperator
            } else {
                $operators = $server.JobServer.Operators
            }

            $alerts = $server.JobServer.alerts

            foreach ($operat in $operators) {

                $jobs = $server.JobServer.jobs | Where-Object { $_.OperatorToEmail, $_.OperatorToNetSend, $_.OperatorToPage -contains $operat.Name }
                $lastemail = [dbadatetime]$operat.LastEmailDate

                $operatAlerts = @()
                foreach ($alert in $alerts) {
                    $dtAlert = $alert.EnumNotifications($operat.Name)
                    if ($dtAlert.Rows.Count -gt 0) {
                        $operatAlerts += $alert.Name
                        $alertlastemail = [dbadatetime]$alert.LastOccurrenceDate
                    }
                }

                Add-Member -Force -InputObject $operat -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName
                Add-Member -Force -InputObject $operat -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName
                Add-Member -Force -InputObject $operat -MemberType NoteProperty -Name SqlInstance -Value $server.DomainInstanceName
                Add-Member -Force -InputObject $operat -MemberType NoteProperty -Name RelatedJobs -Value $jobs
                Add-Member -Force -InputObject $operat -MemberType NoteProperty -Name LastEmail -Value $lastemail
                Add-Member -Force -InputObject $operat -MemberType NoteProperty -Name RelatedAlerts -Value $operatAlerts
                Add-Member -Force -InputObject $operat -MemberType NoteProperty -Name AlertLastEmail -Value $alertlastemail
                Select-DefaultView -InputObject $operat -Property $defaults
            }
        }
    }
}
tools\dbatools\functions\Get-DbaAgentProxy.ps1
function Get-DbaAgentProxy {
    <#
    .SYNOPSIS
        Returns all SQL Agent proxies on a SQL Server Agent.

    .DESCRIPTION
        This function returns SQL Agent proxies.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Proxy
        The proxy to process - this list is auto-populated from the server. If unspecified, all proxies will be processed.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, SMO
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaAgentProxy

    .EXAMPLE
        PS C:\> Get-DbaAgentProxy -SqlInstance ServerA,ServerB\instanceB

        Returns all SQL Agent proxies on serverA and serverB\instanceB

    .EXAMPLE
        PS C:\> 'serverA','serverB\instanceB' | Get-DbaAgentProxy

        Returns all SQL Agent proxies  on serverA and serverB\instanceB

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "Instance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Proxy,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            Write-Message -Level Verbose -Message "Getting Edition from $server"
            Write-Message -Level Verbose -Message "$server is a $($server.Edition)"

            if ($server.Edition -like 'Express*') {
                Stop-Function -Message "There is no SQL Agent on $server, it's a $($server.Edition)" -Continue
            }

            $defaults = "ComputerName", "SqlInstance", "InstanceName", "Name", "ID", "CredentialID", "CredentialIdentity", "CredentialName", "Description", "IsEnabled"

            $proxies = $server.Jobserver.ProxyAccounts

            if ($proxy) {
                $proxies = $proxies | Where-Object Name -In $proxy
            }

            foreach ($px in $proxies) {
                Add-Member -Force -InputObject $px -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                Add-Member -Force -InputObject $px -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                Add-Member -Force -InputObject $px -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                Select-DefaultView -InputObject $px -Property $defaults
            }
        }
    }
}
tools\dbatools\functions\Get-DbaAgentSchedule.ps1
function Get-DbaAgentSchedule {
    <#
    .SYNOPSIS
        Returns all SQL Agent Shared Schedules on a SQL Server Agent.

    .DESCRIPTION
        This function returns SQL Agent Shared Schedules.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Schedule
        Parameter to filter the schedules returned

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Schedule
        Author: Chris McKeown (@devopsfu), http://www.devopsfu.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaAgentSchedule

    .EXAMPLE
        PS C:\> Get-DbaAgentSchedule -SqlInstance localhost

        Returns all SQL Agent Shared Schedules on the local default SQL Server instance

    .EXAMPLE
        PS C:\> Get-DbaAgentSchedule -SqlInstance localhost, sql2016

        Returns all SQL Agent Shared Schedules for the local and sql2016 SQL Server instances

    .EXAMPLE
        PS C:\> Get-DbaAgentSchedule -SqlInstance sql2016 -Schedule "Maintenance10min","Maintenance60min"

        Returns the "Maintenance10min" & "Maintenance60min" schedules from the sql2016 SQL Server instance
    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "Instance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Schedules")]
        [object[]]$Schedule,
        [PSCredential]$SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        function Get-ScheduleDescription {
            param (
                [Parameter(Mandatory)]
                [ValidateNotNullOrEmpty()]
                [object]$Schedule

            )

            # Get the culture to make sure the right date and time format is displayed
            $datetimeFormat = (Get-culture).DateTimeFormat

            # Set the intial description
            $description = ""

            # Get the date and time values
            $startDate = Get-Date $Schedule.ActiveStartDate -format $datetimeFormat.ShortDatePattern
            $startTime = Get-Date ($Schedule.ActiveStartTimeOfDay.ToString()) -format $datetimeFormat.LongTimePattern
            $endDate = Get-Date $Schedule.ActiveEndDate -format $datetimeFormat.ShortDatePattern
            $endTime = Get-Date ($Schedule.ActiveEndTimeOfDay.ToString()) -format $datetimeFormat.LongTimePattern

            # Start setting the description based on the frequency type
            switch ($schedule.FrequencyTypes) {
                {($_ -eq 1) -or ($_ -eq "Once")} { $description += "Occurs on $startDate at $startTime" }
                {($_ -in 4, 8, 16, 32) -or ($_ -in "Daily", "Weekly", "Monthly")} { $description += "Occurs every "}
                {($_ -eq 64) -or ($_ -eq "AutoStart")} {$description += "Start automatically when SQL Server Agent starts "}
                {($_ -eq 128) -or ($_ -eq "OnIdle")} {$description += "Start whenever the CPUs become idle"}
            }

            # Check the frequency types for daily or weekly i.e.
            switch ($schedule.FrequencyTypes) {
                # Daily
                {$_ -in 4, "Daily"} {
                    if ($Schedule.FrequencyInterval -eq 1) {
                        $description += "day "
                    } elseif ($Schedule.FrequencyInterval -gt 1) {
                        $description += "$($Schedule.FrequencyInterval) day(s) "
                    }
                }

                # Weekly
                {$_ -in 8, "Weekly"} {
                    # Check if it's for one or more weeks
                    if ($Schedule.FrequencyRecurrenceFactor -eq 1) {
                        $description += "week on "
                    } elseif ($Schedule.FrequencyRecurrenceFactor -gt 1) {
                        $description += "$($Schedule.FrequencyRecurrenceFactor) week(s) on "
                    }

                    # Save the interval for the loop
                    $frequencyInterval = $Schedule.FrequencyInterval

                    # Create the array to hold the days
                    $days = ($false, $false, $false, $false, $false, $false, $false)

                    # Loop through the days
                    while ($frequencyInterval -gt 0) {

                        switch ($FrequenctInterval) {
                            {($frequencyInterval - 64) -ge 0} {
                                $days[5] = "Saturday"
                                $frequencyInterval -= 64
                            }
                            {($frequencyInterval - 32) -ge 0} {
                                $days[4] = "Friday"
                                $frequencyInterval -= 32
                            }
                            {($frequencyInterval - 16) -ge 0} {
                                $days[3] = "Thursday"
                                $frequencyInterval -= 16
                            }
                            {($frequencyInterval - 8) -ge 0} {
                                $days[2] = "Wednesday"
                                $frequencyInterval -= 8
                            }
                            {($frequencyInterval - 4) -ge 0} {
                                $days[1] = "Tuesday"
                                $frequencyInterval -= 4
                            }
                            {($frequencyInterval - 2) -ge 0} {
                                $days[0] = "Monday"
                                $frequencyInterval -= 2
                            }
                            {($frequencyInterval - 1) -ge 0} {
                                $days[6] = "Sunday"
                                $frequencyInterval -= 1
                            }
                        }

                    }

                    # Add the days to the description by selecting the days and exploding the array
                    $description += ($days | Where-Object {$_ -ne $false}) -join ", "
                    $description += " "

                }

                # Monthly
                {$_ -in 16, "Monthly"} {
                    # Check if it's for one or more months
                    if ($Schedule.FrequencyRecurrenceFactor -eq 1) {
                        $description += "month "
                    } elseif ($Schedule.FrequencyRecurrenceFactor -gt 1) {
                        $description += "$($Schedule.FrequencyRecurrenceFactor) month(s) "
                    }

                    # Add the interval
                    $description += "on day $($Schedule.FrequencyInterval) of that month "
                }

                # Monthly relative
                {$_ -in 32, "MonthlyRelative"} {
                    # Check for the relative day
                    switch ($Schedule.FrequencyRelativeIntervals) {
                        {$_ -in 1, "First"} {$description += "first "}
                        {$_ -in 2, "Second"} {$description += "second "}
                        {$_ -in 4, "Third"} {$description += "third "}
                        {$_ -in 8, "Fourth"} {$description += "fourth "}
                        {$_ -in 16, "Last"} {$description += "last "}
                    }

                    # Get the relative day of the week
                    switch ($Schedule.FrequencyInterval) {
                        1 { $description += "Sunday "}
                        2 { $description += "Monday "}
                        3 { $description += "Tuesday "}
                        4 { $description += "Wednesday "}
                        5 { $description += "Thursday "}
                        6 { $description += "Friday "}
                        7 { $description += "Saturday "}
                        8 { $description += "Day "}
                        9 { $description += "Weekday "}
                        10 { $description += "Weekend day "}
                    }

                    $description += "of every $($Schedule.FrequencyRecurrenceFactor) month(s) "

                }
            }

            # Check the frequency type
            if ($schedule.FrequencyTypes -notin 64, 128) {

                # Check the subday types for minutes or hours i.e.
                if ($schedule.FrequencySubDayInterval -in 0, 1) {
                    $description += "at $startTime. "
                } else {

                    switch ($Schedule.FrequencySubDayTypes) {
                        {$_ -in 2, "Seconds"} { $description += "every $($schedule.FrequencySubDayInterval) second(s) "}
                        {$_ -in 4, "Minutes"} {$description += "every $($schedule.FrequencySubDayInterval) minute(s) " }
                        {$_ -in 8, "Hours"} { $description += "every $($schedule.FrequencySubDayInterval) hour(s) " }
                    }

                    $description += "between $startTime and $endTime. "
                }

                # Check if an end date has been given
                if ($Schedule.ActiveEndDate.Year -eq 9999) {
                    $description += "Schedule will be used starting on $startDate."
                } else {
                    $description += "Schedule will used between $startDate and $endDate."
                }
            }

            return $description
        }
    }

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($server.Edition -like 'Express*') {
                Stop-Function -Message "$($server.Edition) does not support SQL Server Agent. Skipping $server." -Continue
            }

            if ($Schedule) {
                $scheduleCollection = $server.JobServer.SharedSchedules | Where-Object { $_.Name -in $Schedule }
            } else {
                $scheduleCollection = $server.JobServer.SharedSchedules
            }

        }

        $defaults = "ComputerName", "InstanceName", "SqlInstance", "Name as ScheduleName", "ActiveEndDate", "ActiveEndTimeOfDay", "ActiveStartDate", "ActiveStartTimeOfDay", "DateCreated", "FrequencyInterval", "FrequencyRecurrenceFactor", "FrequencyRelativeIntervals", "FrequencySubDayInterval", "FrequencySubDayTypes", "FrequencyTypes", "IsEnabled", "JobCount", "Description"

        foreach ($schedule in $scheduleCollection) {
            $description = Get-ScheduleDescription -Schedule $schedule

            Add-Member -Force -InputObject $schedule -MemberType NoteProperty ComputerName -value $server.ComputerName
            Add-Member -Force -InputObject $schedule -MemberType NoteProperty InstanceName -value $server.ServiceName
            Add-Member -Force -InputObject $schedule -MemberType NoteProperty SqlInstance -value $server.DomainInstanceName
            Add-Member -Force -InputObject $schedule -MemberType NoteProperty Description -Value $description

            Select-DefaultView -InputObject $schedule -Property $defaults
        }

    }
}
tools\dbatools\functions\Get-DbaAgentServer.ps1
function Get-DbaAgentServer {
    <#
    .SYNOPSIS
        Gets SQL Agent Server information for each instance(s) of SQL Server.

    .DESCRIPTION
        The Get-DbaAgentServer returns connected SMO object for SQL Agent Server information for each instance(s) of SQL Server.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Job, Agent
        Author: Cláudio Silva (@claudioessilva), https://claudioessilva.eu

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaAgentServer

    .EXAMPLE
        PS C:\> Get-DbaAgentServer -SqlInstance localhost

        Returns SQL Agent Server on the local default SQL Server instance

    .EXAMPLE
        PS C:\> Get-DbaAgentServer -SqlInstance localhost, sql2016

        Returns SQL Agent Servers for the localhost and sql2016 SQL Server instances

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $jobServer = $server.JobServer

            $defaultView = 'ComputerName', 'InstanceName', 'SqlInstance', 'AgentDomainGroup', 'AgentLogLevel', 'AgentMailType', 'AgentShutdownWaitTime', 'ErrorLogFile', 'IdleCpuDuration', 'IdleCpuPercentage', 'IsCpuPollingEnabled', 'JobServerType', 'LoginTimeout', 'JobHistoryIsEnabled', 'MaximumHistoryRows', 'MaximumJobHistoryRows', 'MsxAccountCredentialName', 'MsxAccountName', 'MsxServerName', 'Name', 'NetSendRecipient', 'ServiceAccount', 'ServiceStartMode', 'SqlAgentAutoStart', 'SqlAgentMailProfile', 'SqlAgentRestart', 'SqlServerRestart', 'State', 'SysAdminOnly'

            Add-Member -Force -InputObject $jobServer -MemberType NoteProperty -Name ComputerName -Value $jobServer.Parent.ComputerName
            Add-Member -Force -InputObject $jobServer -MemberType NoteProperty -Name InstanceName -value $jobServer.Parent.ServiceName
            Add-Member -Force -InputObject $jobServer -MemberType NoteProperty -Name SqlInstance -Value $jobServer.Parent.DomainInstanceName
            Add-Member -Force -InputObject $jobServer -MemberType ScriptProperty -Name JobHistoryIsEnabled -Value { switch ( $jobServer.MaximumHistoryRows ) { -1 { $false } default { $true } } }

            Select-DefaultView -InputObject $jobServer -Property $defaultView
        }
    }
}
tools\dbatools\functions\Get-DbaAgHadr.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaAgHadr {
    <#
    .SYNOPSIS
        Gets the Hadr service setting on the specified SQL Server instance.

    .DESCRIPTION
        Gets the Hadr setting, from the service level, and returns true or false for the specified SQL Server instance.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Hadr, HA, AG, AvailabilityGroup
        Author: Shawn Melton (@wsmelton), http://wsmelton.github.io

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaAgHadr

    .EXAMPLE
        PS C:\> Get-DbaAgHadr -SqlInstance sql2016

        Returns a status of the Hadr setting for sql2016 SQL Server instance.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            Add-Member -Force -InputObject $server -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
            Add-Member -Force -InputObject $server -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
            Add-Member -Force -InputObject $server -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName

            Select-DefaultView -InputObject $server -Property 'ComputerName', 'InstanceName', 'SqlInstance', 'IsHadrEnabled'
        }
    }
}
tools\dbatools\functions\Get-DbaAgListener.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaAgListener {
    <#
    .SYNOPSIS
        Returns availability group listeners.

    .DESCRIPTION
        Returns availability group listeners.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.

    .PARAMETER SqlCredential
        Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER AvailabilityGroup
        Specify the availability groups to query.

    .PARAMETER Listener
        Return only specific listeners.

    .PARAMETER InputObject
        Enables piped input from Get-DbaAvailabilityGroup.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: AG, HA, AvailabilityGroup, Listener
        Author: Viorel Ciucu (@viorelciucu)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaAgListener

    .EXAMPLE
        PS C:\> Get-DbaAgListener -SqlInstance sql2017a

        Returns all listeners found on sql2017a

    .EXAMPLE
        PS C:\> Get-DbaAgListener -SqlInstance sql2017a -AvailabilityGroup AG-a

        Returns all listeners found on sql2017a on sql2017a for the availability group AG-a


    .EXAMPLE
        PS C:\> Get-DbaAvailabilityGroup -SqlInstance sql2017a -AvailabilityGroup OPP | Get-DbaAgListener

        Returns all listeners found on sql2017a on sql2017a for the availability group OPP

    #>
    [CmdletBinding()]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$AvailabilityGroup,
        [string[]]$Listener,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.AvailabilityGroup[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ($SqlInstance) {
            $InputObject += Get-DbaAvailabilityGroup -SqlInstance $SqlInstance -SqlCredential $SqlCredential -AvailabilityGroup $AvailabilityGroup
        }

        if (Test-Bound -ParameterName Listener) {
            $InputObject = $InputObject | Where-Object { $_.AvailabilityGroupListeners.Name -contains $Listener }
        }

        $defaults = 'ComputerName', 'InstanceName', 'SqlInstance', 'AvailabilityGroup', 'Name', 'PortNumber', 'ClusterIPConfiguration'

        foreach ($aglistener in $InputObject.AvailabilityGroupListeners) {
            $server = $aglistener.Parent.Parent
            Add-Member -Force -InputObject $aglistener -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
            Add-Member -Force -InputObject $aglistener -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
            Add-Member -Force -InputObject $aglistener -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
            Add-Member -Force -InputObject $aglistener -MemberType NoteProperty -Name AvailabilityGroup -value $aglistener.Parent.Name
            Select-DefaultView -InputObject $aglistener -Property $defaults
        }
    }
}
tools\dbatools\functions\Get-DbaAgReplica.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaAgReplica {
    <#
    .SYNOPSIS
        Returns the availability group replica object found on the server.

    .DESCRIPTION
        Returns the availability group replica object found on the server.

   .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.

    .PARAMETER SqlCredential
        Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER AvailabilityGroup
        Specify the availability groups to query.

    .PARAMETER Replica
        Return only specific replicas.

    .PARAMETER InputObject
        Enables piped input from Get-DbaAvailabilityGroup.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: AG, HA, AvailabilityGroup, Replica
        Author: Shawn Melton (@wsmelton) | Chrissy LeMaire (@cl)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaAgReplica

    .EXAMPLE
        PS C:\> Get-DbaAgReplica -SqlInstance sql2017a

        Returns basic information on all the availability group replicas found on sql2017a

    .EXAMPLE
        PS C:\> Get-DbaAgReplica -SqlInstance sql2017a -AvailabilityGroup SharePoint

        Shows basic information on the replicas found on availability group SharePoint on sql2017a

    .EXAMPLE
        PS C:\> Get-DbaAgReplica -SqlInstance sql2017a | Select-Object *

        Returns full object properties on all availability group replicas found on sql2017a

    #>
    [CmdletBinding()]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$AvailabilityGroup,
        [string[]]$Replica,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.AvailabilityGroup[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ($SqlInstance) {
            $InputObject += Get-DbaAvailabilityGroup -SqlInstance $SqlInstance -SqlCredential $SqlCredential -AvailabilityGroup $AvailabilityGroup
        }

        $availabilityReplicas = $InputObject.AvailabilityReplicas
        if ($Replica) {
            $availabilityReplicas = $InputObject.AvailabilityReplicas | Where-Object { $_.Name -in $Replica }
        }

        $defaults = 'ComputerName', 'InstanceName', 'SqlInstance', 'AvailabilityGroup', 'Name', 'Role', 'ConnectionState', 'RollupSynchronizationState', 'AvailabilityMode', 'BackupPriority', 'EndpointUrl', 'SessionTimeout', 'FailoverMode', 'ReadonlyRoutingList'

        foreach ($agreplica in $availabilityReplicas) {
            Add-Member -Force -InputObject $agreplica -MemberType NoteProperty -Name ComputerName -value $agreplica.Parent.ComputerName
            Add-Member -Force -InputObject $agreplica -MemberType NoteProperty -Name InstanceName -value $agreplica.Parent.InstanceName
            Add-Member -Force -InputObject $agreplica -MemberType NoteProperty -Name SqlInstance -value $agreplica.Parent.SqlInstance
            Add-Member -Force -InputObject $agreplica -MemberType NoteProperty -Name AvailabilityGroup -value $agreplica.Parent.Name
            Add-Member -Force -InputObject $agreplica -MemberType NoteProperty -Name Replica -value $agreplica.Name # backwards compat

            Select-DefaultView -InputObject $agreplica -Property $defaults
        }
    }
}
tools\dbatools\functions\Get-DbaAvailabilityGroup.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaAvailabilityGroup {
    <#
    .SYNOPSIS
        Returns availability group objects from a SQL Server instance.

    .DESCRIPTION
        Returns availability group objects from a SQL Server instance.

        Default view provides most common set of properties for information on the Availability Group(s).

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2012 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER AvailabilityGroup
        Return only specific availability groups.

    .PARAMETER IsPrimary
        If this switch is enabled, a boolean indicating whether SqlInstance is the Primary replica in the AG is returned.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Hadr, HA, AG, AvailabilityGroup
        Author: Shawn Melton (@wsmelton) | Chrissy LeMaire (@cl)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaAvailabilityGroup

    .EXAMPLE
        PS C:\> Get-DbaAvailabilityGroup -SqlInstance sqlserver2014a

        Returns basic information on all the Availability Group(s) found on sqlserver2014a.

    .EXAMPLE
        PS C:\> Get-DbaAvailabilityGroup -SqlInstance sqlserver2014a -AvailabilityGroup AG-a

        Shows basic information on the Availability Group AG-a on sqlserver2014a.

    .EXAMPLE
        PS C:\> Get-DbaAvailabilityGroup -SqlInstance sqlserver2014a | Select *

        Returns full object properties on all Availability Group(s) on sqlserver2014a.

    .EXAMPLE
        PS C:\> Get-DbaAvailabilityGroup -SqlInstance sqlserver2014a | Select-Object -ExpandProperty PrimaryReplicaServerName

        Returns the SQL Server instancename of the primary replica as a string

    .EXAMPLE
        PS C:\> Get-DbaAvailabilityGroup -SqlInstance sqlserver2014a -AvailabilityGroup AG-a -IsPrimary

        Returns true/false if the server, sqlserver2014a, is the primary replica for AG-a Availability Group.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$AvailabilityGroup,
        [switch]$IsPrimary,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 11
            } catch {
                Stop-Function -Message "Failure." -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if (-not $server.IsHadrEnabled) {
                Stop-Function -Message "Availability Group (HADR) is not configured for the instance: $instance." -Target $instance -Continue
            }

            $ags = $server.AvailabilityGroups

            if ($AvailabilityGroup) {
                $ags = $ags | Where-Object Name -in $AvailabilityGroup
            }

            foreach ($ag in $ags) {
                Add-Member -Force -InputObject $ag -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                Add-Member -Force -InputObject $ag -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                Add-Member -Force -InputObject $ag -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName

                if ($IsPrimary) {
                    $defaults = 'ComputerName', 'InstanceName', 'SqlInstance', 'Name as AvailabilityGroup', 'IsPrimary'
                    Add-Member -Force -InputObject $ag -MemberType NoteProperty -Name IsPrimary -Value ($ag.PrimaryReplicaServerName -eq $server.Name)
                    Select-DefaultView -InputObject $ag -Property $defaults
                } else {
                    $defaults = 'ComputerName', 'InstanceName', 'SqlInstance', 'LocalReplicaRole', 'Name as AvailabilityGroup', 'PrimaryReplicaServerName as PrimaryReplica', 'ClusterType', 'DtcSupportEnabled', 'AutomatedBackupPreference', 'AvailabilityReplicas', 'AvailabilityDatabases', 'AvailabilityGroupListeners'
                    Select-DefaultView -InputObject $ag -Property $defaults
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaAvailableCollation.ps1
function Get-DbaAvailableCollation {
    <#
    .SYNOPSIS
        Function to get available collations for a given SQL Server

    .DESCRIPTION
        The Get-DbaAvailableCollation function returns the list of collations available on each SQL Server.
        Only the connect permission is required to get this information.

    .PARAMETER SqlInstance
        TThe target SQL Server instance or instances. Only connect permission is required.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Collation, Configuration
        Author: Bryan Hamby (@galador)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaAvailableCollation

    .EXAMPLE
        PS C:\> Get-DbaAvailableCollation -SqlInstance sql2016

        Gets all the collations from server sql2016 using NT authentication

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        #Functions to get/cache the code page and language description.
        #It runs about 9x faster caching these (2 vs 18 seconds) in my test,
        #since there are so many duplicates

        #No longer supported by Windows, but still shows up in SQL Server
        #http://www.databaseteam.org/1-ms-sql-server/982faddda7a789a1.htm
        $locales = @{66577 = "Japanese_Unicode"}
        $codePages = @{}

        function Get-LocaleDescription ($LocaleId) {
            if ($locales.ContainsKey($LocaleId)) {
                $localeName = $locales.Get_Item($LocaleId)
            } else {
                try {
                    $localeName = (Get-Language $LocaleId).DisplayName
                } catch {
                    $localeName = $null
                }
                $locales.Set_Item($LocaleId, $localeName)
            }
            return $localeName
        }

        function Get-CodePageDescription ($codePageId) {
            if ($codePages.ContainsKey($codePageId)) {
                $codePageName = $codePages.Get_Item($codePageId)
            } else {
                try {
                    $codePageName = (Get-CodePage $codePageId).EncodingName
                } catch {
                    $codePageName = $null
                }
                $codePages.Set_Item($codePageId, $codePageName)
            }
            return $codePageName
        }
    }

    process {
        foreach ($Instance in $sqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $availableCollations = $server.EnumCollations()
            foreach ($collation in $availableCollations) {
                Add-Member -Force -InputObject $collation -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                Add-Member -Force -InputObject $collation -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                Add-Member -Force -InputObject $collation -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                Add-Member -Force -InputObject $collation -MemberType NoteProperty -Name CodePageName -Value (Get-CodePageDescription $collation.CodePage)
                Add-Member -Force -InputObject $collation -MemberType NoteProperty -Name LocaleName -Value (Get-LocaleDescription $collation.LocaleID)
            }

            Select-DefaultView -InputObject $availableCollations -Property ComputerName, InstanceName, SqlInstance, Name, CodePage, CodePageName, LocaleID, LocaleName, Description
        }
    }
}
tools\dbatools\functions\Get-DbaBackupDevice.ps1
#ValidationTags#Messaging#
function Get-DbaBackupDevice {
    <#
    .SYNOPSIS
        Gets SQL Backup Device information for each instance(s) of SQL Server.

    .DESCRIPTION
        The Get-DbaBackupDevice command gets SQL Backup Device information for each instance(s) of SQL Server.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function
        to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Backup
        Author: Garry Bargsley (@gbargsley), http://blog.garrybargsley.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaBackupDevice

    .EXAMPLE
        PS C:\> Get-DbaBackupDevice -SqlInstance localhost

        Returns all Backup Devices on the local default SQL Server instance

    .EXAMPLE
        PS C:\> Get-DbaBackupDevice -SqlInstance localhost, sql2016

        Returns all Backup Devices for the local and sql2016 SQL Server instances

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            foreach ($backupDevice in $server.BackupDevices) {
                Add-Member -Force -InputObject $backupDevice -MemberType NoteProperty -Name ComputerName -value $backupDevice.Parent.ComputerName
                Add-Member -Force -InputObject $backupDevice -MemberType NoteProperty -Name InstanceName -value $backupDevice.Parent.ServiceName
                Add-Member -Force -InputObject $backupDevice -MemberType NoteProperty -Name SqlInstance -value $backupDevice.Parent.DomainInstanceName

                Select-DefaultView -InputObject $backupDevice -Property ComputerName, InstanceName, SqlInstance, Name, BackupDeviceType, PhysicalLocation, SkipTapeLabel
            }
        }
    }
}
tools\dbatools\functions\Get-DbaBackupHistory.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaBackupHistory {
    <#
    .SYNOPSIS
        Returns backup history details for databases on a SQL Server.

    .DESCRIPTION
        Returns backup history details for some or all databases on a SQL Server.

        You can even get detailed information (including file path) for latest full, differential and log files.

        Backups taken with the CopyOnly option will NOT be returned, unless the IncludeCopyOnly switch is present

        Reference: http://www.sqlhub.com/2011/07/find-your-backup-history-in-sql-server.html

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Credential object used to connect to the SQL Server Instance as a different user. This can be a Windows or SQL Server account. Windows users are determined by the existence of a backslash, so if you are intending to use an alternative Windows connection instead of a SQL login, ensure it contains a backslash.

    .PARAMETER Database
        Specifies one or more database(s) to process. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies one or more database(s) to exclude from processing.

    .PARAMETER IncludeCopyOnly
        By default Get-DbaBackupHistory will ignore backups taken with the CopyOnly option. This switch will include them

    .PARAMETER Force
        If this switch is enabled, a large amount of information is returned, similar to what SQL Server itself returns.

    .PARAMETER Since
        Specifies a DateTime object to use as the starting point for the search for backups.

    .PARAMETER RecoveryFork
        Specifies the Recovery Fork you want backup history for

    .PARAMETER Last
        If this switch is enabled, the most recent full chain of full, diff and log backup sets is returned.

    .PARAMETER LastFull
        If this switch is enabled, the most recent full backup set is returned.

    .PARAMETER LastDiff
        If this switch is enabled, the most recent differential backup set is returned.

    .PARAMETER LastLog
        If this switch is enabled, the most recent log backup is returned.

    .PARAMETER DeviceType
        Specifies a filter for backup sets based on DeviceTypes. Valid options are 'Disk','Permanent Disk Device', 'Tape', 'Permanent Tape Device','Pipe','Permanent Pipe Device','Virtual Device', in addition to custom integers for your own DeviceTypes.

    .PARAMETER Raw
        If this switch is enabled, one object per backup file is returned. Otherwise, media sets (striped backups across multiple files) will be grouped into a single return object.

    .PARAMETER Type
        Specifies one or more types of backups to return. Valid options are 'Full', 'Log', 'Differential', 'File', 'Differential File', 'Partial Full', and 'Partial Differential'. Otherwise, all types of backups will be returned unless one of the -Last* switches is enabled.

    .PARAMETER LastLsn
        Specifies a minimum LSN to use in filtering backup history. Only backups with an LSN greater than this value will be returned, which helps speed the retrieval process.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DisasterRecovery, Backup
        Author: Chrissy LeMaire (@cl) | Stuart Moore (@napalmgram)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaBackupHistory

    .EXAMPLE
        PS C:\> Get-DbaBackupHistory -SqlInstance SqlInstance2014a

        Returns server name, database, username, backup type, date for all database backups still in msdb history on SqlInstance2014a. This may return many rows; consider using filters that are included in other examples.

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        Get-DbaBackupHistory -SqlInstance SqlInstance2014a -SqlCredential $cred

        Does the same as above but connect to SqlInstance2014a as SQL user "sqladmin"

    .EXAMPLE
        PS C:\> Get-DbaBackupHistory -SqlInstance SqlInstance2014a -Database db1, db2 -Since '2016-07-01 10:47:00'

        Returns backup information only for databases db1 and db2 on SqlInstance2014a since July 1, 2016 at 10:47 AM.

    .EXAMPLE
        PS C:\> Get-DbaBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014, pubs -Force | Format-Table

        Returns information only for AdventureWorks2014 and pubs and formats the results as a table.

    .EXAMPLE
        PS C:\> Get-DbaBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014 -Last

        Returns information about the most recent full, differential and log backups for AdventureWorks2014 on sql2014.

    .EXAMPLE
        PS C:\> Get-DbaBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014 -Last -DeviceType Disk

        Returns information about the most recent full, differential and log backups for AdventureWorks2014 on sql2014, but only for backups to disk.

    .EXAMPLE
        PS C:\> Get-DbaBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014 -Last -DeviceType 148,107

        Returns information about the most recent full, differential and log backups for AdventureWorks2014 on sql2014, but only for backups with device_type 148 and 107.

    .EXAMPLE
        PS C:\> Get-DbaBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014 -LastFull

        Returns information about the most recent full backup for AdventureWorks2014 on sql2014.

    .EXAMPLE
        PS C:\> Get-DbaBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014 -Type Full

        Returns information about all Full backups for AdventureWorks2014 on sql2014.

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sql2016 | Get-DbaBackupHistory

        Returns database backup information for every database on every server listed in the Central Management Server on sql2016.

    .EXAMPLE
        PS C:\> Get-DbaBackupHistory -SqlInstance SqlInstance2014a, sql2016 -Force

        Returns detailed backup history for all databases on SqlInstance2014a and sql2016.

    .EXAMPLE
        PS C:\> Get-DbaBackupHistory -SqlInstance sql2016 -Database db1 -RecoveryFork 38e5e84a-3557-4643-a5d5-eed607bef9c6 -Last

        If db1 has multiple recovery forks, specifying the RecoveryFork GUID will restrict the search to that fork.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]
        $SqlInstance,
        [Alias("Credential")]
        [PsCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$IncludeCopyOnly,
        [Parameter(ParameterSetName = "NoLast")]
        [switch]$Force,
        [DateTime]$Since = (Get-Date '01/01/1970'),
        [ValidateScript( {($_ -match '^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$') -or ('' -eq $_)})]
        [string]$RecoveryFork,
        [Parameter(ParameterSetName = "Last")]
        [switch]$Last,
        [Parameter(ParameterSetName = "Last")]
        [switch]$LastFull,
        [Parameter(ParameterSetName = "Last")]
        [switch]$LastDiff,
        [Parameter(ParameterSetName = "Last")]
        [switch]$LastLog,
        [string[]]$DeviceType,
        [switch]$Raw,
        [bigint]$LastLsn,
        [ValidateSet("Full", "Log", "Differential", "File", "Differential File", "Partial Full", "Partial Differential")]
        [string[]]$Type,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        Write-Message -Level System -Message "Active Parameter set: $($PSCmdlet.ParameterSetName)."
        Write-Message -Level System -Message "Bound parameters: $($PSBoundParameters.Keys -join ", ")"

        $deviceTypeMapping = @{
            'Disk'                  = 2
            'Permanent Disk Device' = 102
            'Tape'                  = 5
            'Permanent Tape Device' = 105
            'Pipe'                  = 6
            'Permanent Pipe Device' = 106
            'Virtual Device'        = 7
            'URL'                   = 9
        }
        $deviceTypeFilter = @()
        foreach ($devType in $DeviceType) {
            if ($devType -in $deviceTypeMapping.Keys) {
                $deviceTypeFilter += $deviceTypeMapping[$devType]
            } else {
                $deviceTypeFilter += $devType
            }
        }
        $backupTypeMapping = @{
            'Log'                  = 'L'
            'Full'                 = 'D'
            'File'                 = 'F'
            'Differential'         = 'I'
            'Differential File'    = 'G'
            'Partial Full'         = 'P'
            'Partial Differential' = 'Q'
        }
        $backupTypeFilter = @()
        foreach ($typeFilter in $Type) {
            $backupTypeFilter += $backupTypeMapping[$typeFilter]
        }

    }

    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($server.VersionMajor -ge 10) {
                $compressedFlag = $true
                # 2008 introduced compressed_backup_size
                $backupCols = "
                backupset.backup_size AS TotalSize,
                backupset.compressed_backup_size as CompressedBackupSize"
            } else {
                $compressedFlag = $false
                $backupCols = "
                backupset.backup_size AS TotalSize,
                NULL as CompressedBackupSize"
            }

            $databases = @()
            if ($null -ne $Database) {
                foreach ($db in $Database) {
                    $databases += [PSCustomObject]@{name = $db}
                }
            } else {
                $databases = $server.Databases
            }
            if ($ExcludeDatabase) {
                $databases = $databases | Where-Object Name -NotIn $ExcludeDatabase
            }
            foreach ($d in $deviceTypeFilter) {
                $deviceTypeFilterRight = "IN ('" + ($deviceTypeFilter -Join "','") + "')"
            }

            foreach ($b in $backupTypeFilter) {
                $backupTypeFilterRight = "IN ('" + ($backupTypeFilter -Join "','") + "')"
            }

            if ($last) {
                foreach ($db in $databases) {
                    if ($since) {
                        $sinceSqlFilter = "AND backupset.backup_finish_date >= '$($Since.ToString("yyyy-MM-ddTHH:mm:ss"))'"
                    }
                    if ($RecoveryFork) {
                        $recoveryForkSqlFilter = "AND backupset.last_recovery_fork_guid ='$RecoveryFork'"
                    }
                    if ($null -eq (Get-PsCallStack)[1].Command -or '{ScriptBlock}' -eq (Get-PsCallStack)[1].Command) {
                        $forkCheckSql = "
                                SELECT
                                    database_name,
                                    MIN(database_backup_lsn) as 'FirstLsn',
                                    MAX(database_backup_lsn) as 'FinalLsn',
                                    MIN(backup_start_date) as 'MinDate',
                                    MAX(backup_finish_date) as 'MaxDate',
                                    last_recovery_fork_guid 'RecFork',
                                    count(1) as 'backupcount'
                                FROM msdb.dbo.backupset
                                WHERE database_name='$($db.name)'
                                $sinceSqlFilter
                                $recoveryForkSqlFilter
                                GROUP by database_name, last_recovery_fork_guid
                                ORDER by MaxDate Asc
                                "

                        $results = $server.ConnectionContext.ExecuteWithResults($forkCheckSql).Tables.Rows
                        if ($results.count -gt 1) {
                            Write-Message -Message "Found backups from multiple recovery forks for $($db.name) on $($server.name), this may affect your results" -Level Warning
                            foreach ($result in $results) {
                                Write-Message -Message "Between $($result.MinDate)/$($result.FirstLsn) and $($result.MaxDate)/$($result.FinalLsn) $($result.name) was on Recovery Fork GUID $($result.RecFork) ($($result.backupcount) backups)"   -Level Warning
                            }
                            if ($null -eq $RecoveryFork) {
                                $RecoveryFork = $results[-1].RecFork
                                Write-Message -Message "Defaulting to last Recovery Fork, ID - $RecoveryFork"
                            }
                        }
                    }
                    #Get the full and build upwards
                    $allBackups = @()
                    $allBackups += $fullDb = Get-DbaBackupHistory -SqlInstance $server -Database $db.Name -LastFull -raw:$Raw -DeviceType $DeviceType -IncludeCopyOnly:$IncludeCopyOnly -Since:$since -RecoveryFork $RecoveryFork
                    $diffDb = Get-DbaBackupHistory -SqlInstance $server -Database $db.Name -LastDiff -raw:$Raw -DeviceType $DeviceType -IncludeCopyOnly:$IncludeCopyOnly -Since:$since -RecoveryFork $RecoveryFork
                    if ($diffDb.LastLsn -gt $fullDb.LastLsn -and $diffDb.DatabaseBackupLSN -eq $fullDb.CheckPointLSN ) {
                        Write-Message -Level Verbose -Message "Valid Differential backup "
                        $allBackups += $diffDb
                        $tlogStartDsn = ($diffDb.FirstLsn -as [bigint])
                    } else {
                        Write-Message -Level Verbose -Message "No Diff found"
                        try {
                            [bigint]$tlogStartDsn = $fullDb.FirstLsn.ToString()
                        } catch {
                            continue
                        }
                    }
                    $allBackups += Get-DbaBackupHistory -SqlInstance $server -Database $db.Name -raw:$raw -DeviceType $DeviceType -LastLsn $tlogStartDsn -IncludeCopyOnly:$IncludeCopyOnly -Since:$since -RecoveryFork $RecoveryFork | Where-Object {
                        $_.Type -eq 'Log' -and [bigint]$_.LastLsn -gt [bigint]$tlogStartDsn -and [bigint]$_.DatabaseBackupLSN -eq [bigint]$fullDb.CheckPointLSN -and $_.LastRecoveryForkGuid -eq $fullDb.LastRecoveryForkGuid
                    }
                    #This line does the output for -Last!!!
                    $allBackups |  Sort-Object -Property LastLsn, Type
                }
                continue
            }

            if ($LastFull -or $LastDiff -or $LastLog) {
                if ($LastFull) {
                    $first = 'D'; $second = 'P'
                }
                if ($LastDiff) {
                    $first = 'I'; $second = 'Q'
                }
                if ($LastLog) {
                    $first = 'L'; $second = 'L'
                }
                $databases = $databases | Select-Object -Unique -Property Name
                $sql = ""
                foreach ($db in $databases) {
                    Write-Message -Level Verbose -Message "Processing $($db.name)" -Target $db
                    if ($since) {
                        $sinceSqlFilter = "AND backupset.backup_finish_date >= '$($Since.ToString("yyyy-MM-ddTHH:mm:ss"))'"
                    }
                    if ($RecoveryFork) {
                        $recoveryForkSqlFilter = "AND backupset.last_recovery_fork_guid ='$RecoveryFork'"
                    }
                    if ((Get-PsCallStack)[1].Command -notlike 'Get-DbaBackupHistory*') {
                        $forkCheckSql = "
                            SELECT
                                database_name,
                                MIN(database_backup_lsn) as 'FirstLsn',
                                MAX(database_backup_lsn) as 'FinalLsn',
                                MIN(backup_start_date) as 'MinDate',
                                MAX(backup_finish_date) as 'MaxDate',
                                last_recovery_fork_guid 'RecFork',
                                count(1) as 'backupcount'
                            FROM msdb.dbo.backupset
                            WHERE database_name='$($db.name)'
                            $sinceSqlFilter
                            $recoveryForkSqlFilter
                            GROUP by database_name, last_recovery_fork_guid
                        "

                        $results = $server.ConnectionContext.ExecuteWithResults($forkCheckSql).Tables.Rows
                        if ($results.count -gt 1) {
                            Write-Message -Message "Found backups from multiple recovery forks for $($db.name) on $($server.name), this may affect your results" -Level Warning
                            foreach ($result in $results) {
                                Write-Message -Message "Between $($result.MinDate)/$($result.FirstLsn) and $($result.MaxDate)/$($result.FinalLsn) $($result.name) was on Recovery Fork GUID $($result.RecFork) ($($result.backupcount) backups)"   -Level Warning
                            }

                        }
                    }
                    $whereCopyOnly = $null
                    if ($true -ne $IncludeCopyOnly) {
                        $whereCopyOnly = " AND is_copy_only='0' "
                    }
                    if ($deviceTypeFilter) {
                        $devTypeFilterWhere = "AND mediafamily.device_type $deviceTypeFilterRight"
                    }
                    if ($since) {
                        $sinceSqlFilter = "AND backupset.backup_finish_date >= '$($Since.ToString("yyyy-MM-ddTHH:mm:ss"))'"
                    }
                    # recap for future editors (as this has been discussed over and over):
                    #   - original editors (from hereon referred as "we") rank over backupset.last_lsn desc, backupset.backup_finish_date desc for a good reason: DST
                    #     all times are recorded with the timezone of the server
                    #   - we thought about ranking over backupset.backup_set_id desc, backupset.last_lsn desc, backupset.backup_finish_date desc
                    #     but there is no explicit documentation about "when" a row gets inserted into backupset. Theoretically it _could_
                    #     happen that backup_set_id for the same database has not the same order of last_lsn.
                    #   - given ultimately to restore something lsn IS the source of truth, we decided to trust that and only that
                    #   - we know that sometimes it happens to drop a database without deleting the history. Assuming then to create a database with the same name,
                    #     and given the lsn are composed in the first part by the VLF SeqID, it happens seldomly that for the same database_name backupset holds
                    #     last_lsn out of order. To avoid this behaviour, we filter by database_guid choosing the guid that has MAX(backup_finish_date), as we know
                    #     last_lsn cannot be out-of-order for the same database, and the same database cannot have different database_guid
                    $sql += "
                                SELECT
                                    a.BackupSetRank,
                                    a.Server,
                                    a.[Database],
                                    a.Username,
                                    a.Start,
                                    a.[End],
                                    a.Duration,
                                    a.[Path],
                                    a.Type,
                                    a.TotalSize,
                                    a.CompressedBackupSize,
                                    a.MediaSetId,
                                    a.BackupSetID,
                                    a.Software,
                                    a.position,
                                    a.first_lsn,
                                    a.database_backup_lsn,
                                    a.checkpoint_lsn,
                                    a.last_lsn,
                                    a.first_lsn as 'FirstLSN',
                                    a.database_backup_lsn as 'DatabaseBackupLsn',
                                    a.checkpoint_lsn as 'CheckpointLsn',
                                    a.last_lsn as 'LastLsn',
                                    a.software_major_version,
                                    a.DeviceType,
                                    a.is_copy_only,
                                    a.last_recovery_fork_guid,
                                    a.recovery_model
                                FROM (SELECT
                                  RANK() OVER (ORDER BY backupset.last_lsn desc, backupset.backup_finish_date DESC) AS 'BackupSetRank',
                                  backupset.database_name AS [Database],
                                  backupset.user_name AS Username,
                                  backupset.backup_start_date AS Start,
                                  backupset.server_name as [Server],
                                  backupset.backup_finish_date AS [End],
                                  DATEDIFF(SECOND, backupset.backup_start_date, backupset.backup_finish_date) AS Duration,
                                  mediafamily.physical_device_name AS Path,
                                  $backupCols,
                                  CASE backupset.type
                                    WHEN 'L' THEN 'Log'
                                    WHEN 'D' THEN 'Full'
                                    WHEN 'F' THEN 'File'
                                    WHEN 'I' THEN 'Differential'
                                    WHEN 'G' THEN 'Differential File'
                                    WHEN 'P' THEN 'Partial Full'
                                    WHEN 'Q' THEN 'Partial Differential'
                                    ELSE NULL
                                  END AS Type,
                                  backupset.media_set_id AS MediaSetId,
                                  mediafamily.media_family_id as mediafamilyid,
                                  backupset.backup_set_id as BackupSetID,
                                  CASE mediafamily.device_type
                                    WHEN 2 THEN 'Disk'
                                    WHEN 102 THEN 'Permanent Disk Device'
                                    WHEN 5 THEN 'Tape'
                                    WHEN 105 THEN 'Permanent Tape Device'
                                    WHEN 6 THEN 'Pipe'
                                    WHEN 106 THEN 'Permanent Pipe Device'
                                    WHEN 7 THEN 'Virtual Device'
                                    WHEN 9 THEN 'URL'
                                    ELSE 'Unknown'
                                    END AS DeviceType,
                                  backupset.position,
                                  backupset.first_lsn,
                                  backupset.database_backup_lsn,
                                  backupset.checkpoint_lsn,
                                  backupset.last_lsn,
                                  backupset.software_major_version,
                                  mediaset.software_name AS Software,
                                  backupset.is_copy_only,
                                  backupset.last_recovery_fork_guid,
                                  backupset.recovery_model
                                FROM msdb..backupmediafamily AS mediafamily
                                JOIN msdb..backupmediaset AS mediaset
                                  ON mediafamily.media_set_id = mediaset.media_set_id
                                JOIN msdb..backupset AS backupset
                                  ON backupset.media_set_id = mediaset.media_set_id
                                JOIN (
                                    SELECT DISTINCT database_guid, database_name, backup_finish_date
                                    FROM msdb..backupset
                                    WHERE backupset.database_name = '$($db.Name)'
                                ) dbguid
                                  ON dbguid.database_name = backupset.database_name
                                  AND dbguid.database_guid = backupset.database_guid
                                JOIN (
                                    SELECT database_name, MAX(backup_finish_date) max_finish_date
                                    FROM msdb..backupset
                                    WHERE backupset.database_name = '$($db.Name)'
                                    GROUP BY database_name
                                ) dbguid_support
                                  ON dbguid_support.database_name = backupset.database_name
                                  AND dbguid.backup_finish_date = dbguid_support.max_finish_date
                                WHERE backupset.database_name = '$($db.Name)' $whereCopyOnly
                                AND (type = '$first' OR type = '$second')
                                $devTypeFilterWhere
                                $sinceSqlFilter
                                $recoveryForkSqlFilter
                                ) AS a
                                WHERE a.BackupSetRank = 1
                                ORDER BY a.Type;
                                "
                }
                $sql = $sql -join "; "
            } else {
                if ($Force -eq $true) {
                    $select = "SELECT * "
                } else {
                    $select = "
                            SELECT
                              backupset.database_name AS [Database],
                              backupset.user_name AS Username,
                              backupset.server_name as [server],
                              backupset.backup_start_date AS [Start],
                              backupset.backup_finish_date AS [End],
                              DATEDIFF(SECOND, backupset.backup_start_date, backupset.backup_finish_date) AS Duration,
                              mediafamily.physical_device_name AS Path,
                              $backupCols,
                              CASE backupset.type
                                WHEN 'L' THEN 'Log'
                                WHEN 'D' THEN 'Full'
                                WHEN 'F' THEN 'File'
                                WHEN 'I' THEN 'Differential'
                                WHEN 'G' THEN 'Differential File'
                                WHEN 'P' THEN 'Partial Full'
                                WHEN 'Q' THEN 'Partial Differential'
                                ELSE NULL
                              END AS Type,
                              backupset.media_set_id AS MediaSetId,
                              mediafamily.media_family_id as MediaFamilyId,
                              backupset.backup_set_id as BackupSetId,
                              CASE mediafamily.device_type
                                WHEN 2 THEN 'Disk'
                                WHEN 102 THEN 'Permanent Disk Device'
                                WHEN 5 THEN 'Tape'
                                WHEN 105 THEN 'Permanent Tape Device'
                                WHEN 6 THEN 'Pipe'
                                WHEN 106 THEN 'Permanent Pipe Device'
                                WHEN 7 THEN 'Virtual Device'
                                WHEN 9 THEN 'URL'
                                ELSE 'Unknown'
                              END AS DeviceType,
                              backupset.position,
                              backupset.first_lsn,
                              backupset.database_backup_lsn,
                              backupset.checkpoint_lsn,
                              backupset.last_lsn,
                              backupset.first_lsn as 'FirstLSN',
                              backupset.database_backup_lsn as 'DatabaseBackupLsn',
                              backupset.checkpoint_lsn as 'CheckpointLsn',
                              backupset.last_lsn as 'LastLsn',
                              backupset.software_major_version,
                              mediaset.software_name AS Software,
                              backupset.is_copy_only,
                              backupset.last_recovery_fork_guid,
                              backupset.recovery_model"
                }

                $from = " FROM msdb..backupmediafamily mediafamily
                             INNER JOIN msdb..backupmediaset mediaset ON mediafamily.media_set_id = mediaset.media_set_id
                             INNER JOIN msdb..backupset backupset ON backupset.media_set_id = mediaset.media_set_id"
                if ($Database -or $ExcludeDatabase -or $Since -or $Last -or $LastFull -or $LastLog -or $LastDiff -or $deviceTypeFilter -or $LastLsn -or $backupTypeFilter) {
                    $where = " WHERE "
                }

                $whereArray = @()

                if ($Database.length -gt 0 -or $ExcludeDatabase.length -gt 0) {
                    $dbList = $databases.Name -join "','"
                    $whereArray += "database_name IN ('$dbList')"
                }

                if ($true -ne $IncludeCopyOnly) {
                    $whereArray += "is_copy_only='0'"
                }

                if ($Last -or $LastFull -or $LastLog -or $LastDiff) {
                    $tempWhere = $whereArray -join " AND "
                    $whereArray += "type = 'Full' AND mediaset.media_set_id = (SELECT TOP 1 mediaset.media_set_id $from $tempWhere ORDER BY backupset.last_lsn DESC)"
                }

                if ($null -ne $Since) {
                    $whereArray += "backupset.backup_finish_date >= '$($Since.ToString("yyyy-MM-ddTHH:mm:ss"))'"
                }

                if ($deviceTypeFilter) {
                    $whereArray += "mediafamily.device_type $deviceTypeFilterRight"
                }
                if ($backupTypeFilter) {
                    $whereArray += "backupset.type $backupTypeFilterRight"
                }

                if ($LastLsn) {
                    $whereArray += "backupset.last_lsn > $LastLsn"
                }
                if ($where.Length -gt 0) {
                    $whereArray = $whereArray -join " AND "
                    $where = "$where $whereArray"
                }

                $sql = "$select $from $where ORDER BY backupset.last_lsn DESC"
            }

            Write-Message -Level Debug -Message "SQL Statement: `n$sql"
            Write-Message -Level SomewhatVerbose -Message "Executing sql query."
            $results = $server.ConnectionContext.ExecuteWithResults($sql).Tables.Rows | Select-Object * -ExcludeProperty BackupSetRank, RowError, RowState, Table, ItemArray, HasErrors

            if ($raw) {
                Write-Message -Level SomewhatVerbose -Message "Processing as Raw Output."
                $results | Select-Object *, @{ Name = "FullName"; Expression = { $_.Path } }
                Write-Message -Level SomewhatVerbose -Message "$($results.Count) result sets found."
            } else {
                Write-Message -Level SomewhatVerbose -Message "Processing as grouped output."
                $groupedResults = $results | Group-Object -Property BackupsetId
                Write-Message -Level SomewhatVerbose -Message "$($groupedResults.Count) result-groups found."
                $groupResults = @()
                $backupSetIds = $groupedResults.Name
                $backupSetIdsList = $backupSetIds -Join ","
                if ($groupedResults.Count -gt 0) {
                    $backupSetIdsWhere = "backup_set_id IN ($backupSetIdsList)"
                    $fileAllSql = "SELECT backup_set_id, file_type as FileType, logical_name as LogicalName, physical_name as PhysicalName
                                   FROM msdb..backupfile WHERE $backupSetIdsWhere"
                    Write-Message -Level Debug -Message "FileSQL: $fileAllSql"
                    $fileListResults = $server.Query($fileAllSql)
                } else {
                    $fileListResults = @()
                }
                $fileListHash = @{}
                foreach ($fl in $fileListResults) {
                    if (-not($fileListHash.ContainsKey($fl.backup_set_id))) {
                        $fileListHash[$fl.backup_set_id] = @()
                    }
                    $fileListHash[$fl.backup_set_id] += $fl
                }
                foreach ($group in $groupedResults) {
                    $commonFields = $group.Group[0]
                    $groupLength = $group.Group.Count
                    if ($groupLength -eq 1) {
                        $start = $commonFields.Start
                        $end = $commonFields.End
                        $duration = New-TimeSpan -Seconds $commonFields.Duration
                    } else {
                        $start = ($group.Group.Start | Measure-Object -Minimum).Minimum
                        $end = ($group.Group.End | Measure-Object -Maximum).Maximum
                        $duration = New-TimeSpan -Seconds ($group.Group.Duration | Measure-Object -Maximum).Maximum
                    }
                    $compressedBackupSize = $commonFields.CompressedBackupSize
                    if ($compressedFlag -eq $true) {
                        $ratio = [Math]::Round(($commonFields.TotalSize) / ($compressedBackupSize), 2)
                    } else {
                        $compressedBackupSize = $null
                        $ratio = 1
                    }
                    $historyObject = New-Object Sqlcollaborative.Dbatools.Database.BackupHistory
                    $historyObject.ComputerName = $server.ComputerName
                    $historyObject.InstanceName = $server.ServiceName
                    $historyObject.SqlInstance = $server.DomainInstanceName
                    $historyObject.Database = $commonFields.Database
                    $historyObject.UserName = $commonFields.UserName
                    $historyObject.Start = $start
                    $historyObject.End = $end
                    $historyObject.Duration = $duration
                    $historyObject.Path = $group.Group.Path
                    $historyObject.TotalSize = $commonFields.TotalSize
                    $historyObject.CompressedBackupSize = $compressedBackupSize
                    $historyObject.CompressionRatio = $ratio
                    $historyObject.Type = $commonFields.Type
                    $historyObject.BackupSetId = $commonFields.BackupSetId
                    $historyObject.DeviceType = $commonFields.DeviceType
                    $historyObject.Software = $commonFields.Software
                    $historyObject.FullName = $group.Group.Path
                    $historyObject.FileList = $fileListHash[$commonFields.BackupSetID] | Select-Object FileType, LogicalName, PhysicalName
                    $historyObject.Position = $commonFields.Position
                    $historyObject.FirstLsn = $commonFields.First_LSN
                    $historyObject.DatabaseBackupLsn = $commonFields.database_backup_lsn
                    $historyObject.CheckpointLsn = $commonFields.checkpoint_lsn
                    $historyObject.LastLsn = $commonFields.Last_Lsn
                    $historyObject.SoftwareVersionMajor = $commonFields.Software_Major_Version
                    $historyObject.IsCopyOnly = ($commonFields.is_copy_only -eq 1)
                    $historyObject.LastRecoveryForkGuid = $commonFields.last_recovery_fork_guid
                    $historyObject.RecoveryModel = $commonFields.recovery_model
                    $historyObject
                }
                $groupResults | Sort-Object -Property LastLsn, Type
            }
        }
    }
}
tools\dbatools\functions\Get-DbaBackupInformation.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaBackupInformation {
    <#
    .SYNOPSIS
        Scan backup files and creates a set, compatible with Restore-DbaDatabase

    .DESCRIPTION
        Upon being passed a list of potential backups files this command will scan the files, select those that contain SQL Server
        backup sets. It will then filter those files down to a set

        The function defaults to working on a remote instance. This means that all paths passed in must be relative to the remote instance.
        XpDirTree will be used to perform the file scans

        Various means can be used to pass in a list of files to be considered. The default is to non recursively scan the folder
        passed in.

    .PARAMETER Path
        Path to SQL Server backup files.

        Paths passed in as strings will be scanned using the desired method, default is a non recursive folder scan
        Accepts multiple paths separated by ','

        Or it can consist of FileInfo objects, such as the output of Get-ChildItem or Get-Item. This allows you to work with
        your own file structures as needed

    .PARAMETER SqlInstance
        The SQL Server instance to be used to read the headers of the backup files

    .PARAMETER SqlCredential
        Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.

    .PARAMETER DatabaseName
        An array of Database Names to filter by. If empty all databases are returned.

    .PARAMETER SourceInstance
        If provided only backup originating from this destination will be returned. This SQL instance will not be connected to or involved in this work

    .PARAMETER NoXpDirTree
        If this switch is set, then Files will be parsed as locally files. This can cause failures if the running user can see files that the parsing SQL Instance cannot

    .PARAMETER DirectoryRecurse
        If specified the provided path/directory will be traversed (only applies if not using XpDirTree)

    .PARAMETER Anonymise
        If specified we will output the results with ComputerName, InstanceName, Database, UserName, Paths, and Logical and Physical Names hashed out
        This options is mainly for use if we need you to submit details for fault finding to the dbatools team

    .PARAMETER ExportPath
        If specified the output will export via CliXml format to the specified file. This allows you to store the backup history object for later usage, or move it between computers

    .PARAMETER NoClobber
        If specified will stop Export from overwriting an existing file, the default is to overwrite

    .PARAMETER PassThru
        When data is exported the cmdlet will return no other output, this switch means it will also return the normal output which can be then piped into another command

    .PARAMETER MaintenanceSolution
        This switch tells the function that the folder is the root of a Ola Hallengren backup folder

    .PARAMETER IgnoreLogBackup
        This switch only works with the MaintenanceSolution switch. With an Ola Hallengren style backup we can be sure that the LOG folder contains only log backups and skip it.
        For all other scenarios we need to read the file headers to be sure.

    .PARAMETER AzureCredential
        The name of the SQL Server credential to be used if restoring from an Azure hosted backup

    .PARAMETER Import
        When specified along with a path the command will import a previously exported BackupHistory object from an xml file.

    .PARAMETER EnableException
        Replaces user friendly yellow warnings with bloody red exceptions of doom!
        Use this if you want the function to throw terminating errors you want to catch.

    .NOTES
        Tags: DisasterRecovery, Backup, Restore
        Author: Chrissy LeMaire (@cl) | Stuart Moore (@napalmgram)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaBackupInformation

    .EXAMPLE
        PS C:\> Get-DbaBackupInformation -SqlInstance Server1 -Path c:\backups\ -DirectoryRecurse

        Will use the Server1 instance to recursively read all backup files under c:\backups, and return a dbatools BackupHistory object

    .EXAMPLE
        PS C:\> Get-DbaBackupInformation -SqlInstance Server1 -Path c:\backups\ -DirectoryRecurse -ExportPath c:\store\BackupHistory.xml
        PS C:\> robocopy c:\store\ \\remoteMachine\C$\store\ BackupHistory.xml
        PS C:\> Get-DbaBackupInformation -Import -Path  c:\store\BackupHistory.xml | Restore-DbaDatabase -SqlInstance Server2 -TrustDbBackupHistory

        This example creates backup history output from server1 and copies the file to the remote machine in order to preserve backup history. It is then used to restore the databases onto server2.

    .EXAMPLE
        PS C:\> Get-DbaBackupInformation -SqlInstance Server1 -Path c:\backups\ -DirectoryRecurse -ExportPath C:\store\BackupHistory.xml -PassThru | Restore-DbaDatabase -SqlInstance Server2 -TrustDbBackupHistory

        In this example we gather backup information, export it to an xml file, and then pass it on through to Restore-DbaDatabase.
        This allows us to repeat the restore without having to scan all the backup files again

    .EXAMPLE
        PS C:\> Get-ChildItem c:\backups\ -recurse -files | Where-Object {$_.extension -in ('.bak','.trn') -and $_.LastWriteTime -gt (get-date).AddMonths(-1)} | Get-DbaBackupInformation -SqlInstance Server1 -ExportPath C:\backupHistory.xml

        This lets you keep a record of all backup history from the last month on hand to speed up refreshes

    .EXAMPLE
        PS C:\> $Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\network\backups
        PS C:\> $Backups += Get-DbaBackupInformation -SqlInstance Server2 -NoXpDirTree -Path c:\backups

        Scan the unc folder \\network\backups with Server1, and then scan the C:\backups folder on
        Server2 not using xp_dirtree, adding the results to the first set.

    .EXAMPLE
        PS C:\> $Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\network\backups -MaintenanceSolution

        When MaintenanceSolution is indicated we know we are dealing with the output from Ola Hallengren backup scripts. So we make sure that a FULL folder exists in the first level of Path, if not we shortcut scanning all the files as we have nothing to work with

    .EXAMPLE
        PS C:\> $Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\network\backups -MaintenanceSolution -IgnoreLogBackup

        As we know we are dealing with an Ola Hallengren style backup folder from the MaintenanceSolution switch, when IgnoreLogBackup is also included we can ignore the LOG folder to skip any scanning of log backups. Note this also means they WON'T be restored

    #>
    [CmdletBinding( DefaultParameterSetName = "Create")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "", Justification = "For Parameter AzureCredential")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [object[]]$Path,
        [parameter(Mandatory, ParameterSetName = "Create")]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [parameter(ParameterSetName = "Create")]
        [PSCredential]$SqlCredential,
        [string[]]$DatabaseName,
        [string[]]$SourceInstance,
        [parameter(ParameterSetName = "Create")]
        [Switch]$NoXpDirTree,
        [parameter(ParameterSetName = "Create")]
        [switch]$DirectoryRecurse,
        [switch]$EnableException,
        [switch]$MaintenanceSolution,
        [switch]$IgnoreLogBackup,
        [string]$ExportPath,
        [string]$AzureCredential,
        [parameter(ParameterSetName = "Import")]
        [switch]$Import,
        [switch][Alias('Anonymize')]$Anonymise,
        [Switch]$NoClobber,
        [Switch]$PassThru

    )
    begin {
        function Get-HashString {
            param(
                [String]$InString
            )

            $StringBuilder = New-Object System.Text.StringBuilder
            [System.Security.Cryptography.HashAlgorithm]::Create("md5").ComputeHash([System.Text.Encoding]::UTF8.GetBytes($InString))| ForEach-Object {
                [Void]$StringBuilder.Append($_.ToString("x2"))
            }
            return $StringBuilder.ToString()
        }
        Write-Message -Level InternalComment -Message "Starting"
        Write-Message -Level Debug -Message "Parameters bound: $($PSBoundParameters.Keys -join ", ")"

        if (Test-Bound -ParameterName ExportPath) {
            if ($true -eq $NoClobber) {
                if (Test-Path $ExportPath) {
                    Stop-Function -Message "$ExportPath exists and NoClobber set"
                    return
                }
            }
        }
        if ($PSCmdlet.ParameterSetName -eq "Create") {
            try {
                $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                return
            }
        }

        if ($true -eq $IgnoreLogBackup -and $true -ne $MaintenanceSolution) {
            Write-Message -Message "IgnoreLogBackup can only by used with MaintenanceSolution. Will not be used" -Level Warning
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }
        if ((Test-Bound -Parameter Import) -and ($true -eq $Import)) {
            foreach ($f in $Path) {
                if (Test-Path -Path $f) {
                    $groupResults += Import-CliXml -Path $f
                    foreach ($group in  $groupResults) {
                        $group.FirstLsn = [BigInt]$group.FirstLSN.ToString()
                        $group.CheckpointLSN = [BigInt]$group.CheckpointLSN.ToString()
                        $group.DatabaseBackupLsn = [BigInt]$group.DatabaseBackupLsn.ToString()
                        $group.LastLsn = [BigInt]$group.LastLsn.ToString()
                    }
                } else {
                    Write-Message -Message "$f does not exist or is unreadable" -Level Warning
                }
            }
        } else {
            $Files = @()
            $groupResults = @()
            if ($Path[0] -match 'http') { $NoXpDirTree = $true }
            if ($NoXpDirTree -ne $true) {
                foreach ($f in $path) {
                    if ([System.IO.Path]::GetExtension($f).Length -gt 1) {
                        if ("FullName" -notin $f.PSObject.Properties.name) {
                            $f = $f | Select-Object *, @{ Name = "FullName"; Expression = { $f } }
                        }
                        Write-Message -Message "Testing a single file $f " -Level Verbose
                        if ((Test-DbaPath -Path $f.FullName -SqlInstance $server)) {
                            $files += $f
                        } else {
                            Write-Message -Level Verbose -Message "$server cannot 'see' file $($f.FullName)"
                        }
                    } elseif ($True -eq $MaintenanceSolution) {
                        if ($true -eq $IgnoreLogBackup -and [System.IO.Path]::GetDirectoryName($f) -like '*LOG') {
                            Write-Message -Level Verbose -Message "Skipping Log Backups as requested"
                        } else {
                            Write-Message -Level Verbose -Message "OLA - Getting folder contents"
                            $Files += Get-XpDirTreeRestoreFile -Path $f -SqlInstance $server
                        }
                    } else {
                        Write-Message -Message "Testing a folder $f" -Level Verbose
                        $Files += $Check = Get-XpDirTreeRestoreFile -Path $f -SqlInstance $server
                        if ($null -eq $check) {
                            Write-Message -Message "Nothing returned from $f" -Level Verbose
                        }
                    }
                }
            } else {
                ForEach ($f in $path) {
                    Write-Message -Level VeryVerbose -Message "Not using sql for $f"
                    if ($f -is [System.IO.FileSystemInfo]) {
                        if ($f.PsIsContainer -eq $true -and $true -ne $MaintenanceSolution) {
                            Write-Message -Level VeryVerbose -Message "folder $($f.FullName)"
                            $Files += Get-ChildItem -Path $f.FullName -File -Recurse:$DirectoryRecurse
                        } elseif ($f.PsIsContainer -eq $true -and $true -eq $MaintenanceSolution) {
                            if ($IgnoreLogBackup -and $f -notlike '*LOG' ) {
                                Write-Message -Level Verbose -Message "Skipping Log backups for Maintenance backups"
                            } else {
                                $Files += Get-ChildItem -Path $f.FullName -File -Recurse:$DirectoryRecurse
                            }
                        } elseif ($true -eq $MaintenanceSolution) {
                            $Files += Get-ChildItem -Path $f.FullName -Recurse:$DirectoryRecurse
                        } else {
                            Write-Message -Level VeryVerbose -Message "File"
                            $Files += $f.FullName
                        }
                    } else {
                        if ($true -eq $MaintenanceSolution) {
                            $Files += Get-XpDirTreeRestoreFile -Path $f\FULL -SqlInstance $server -NoRecurse
                            $Files += Get-XpDirTreeRestoreFile -Path $f\DIFF -SqlInstance $server -NoRecurse
                            $Files += Get-XpDirTreeRestoreFile -Path $f\LOG -SqlInstance $server -NoRecurse
                        } else {
                            Write-Message -Level VeryVerbose -Message "File"
                            $Files += $f
                        }
                    }
                }
            }

            if ($True -eq $MaintenanceSolution -and $True -eq $IgnoreLogBackup) {
                Write-Message -Level Verbose -Message "Skipping Log Backups as requested"
                $Files = $Files | Where-Object {$_.FullName -notlike '*\LOG\*'}
            }

            if ($Files.Count -gt 0) {
                Write-Message -Level Verbose -Message "Reading backup headers of $($Files.Count) files"
                $FileDetails = Read-DbaBackupHeader -SqlInstance $server -Path $Files -AzureCredential $AzureCredential
            }

            $groupDetails = $FileDetails | Group-Object -Property BackupSetGUID

            foreach ($group in $groupDetails) {
                $dbLsn = $group.Group[0].DatabaseBackupLSN
                if (-not $dbLsn) {
                    $dbLsn = 0
                }
                $description = $group.Group[0].BackupTypeDescription
                if (-not $description) {
                    $header = Read-DbaBackupHeader -SqlInstance $server -Path $Path | Select-Object -First 1
                    $description = switch ($header.BackupType) {
                        1 { "Full" }
                        2 { "Differential" }
                        3 { "Log"}
                    }
                }
                $historyObject = New-Object Sqlcollaborative.Dbatools.Database.BackupHistory
                $historyObject.ComputerName = $group.Group[0].MachineName
                $historyObject.InstanceName = $group.Group[0].ServiceName
                $historyObject.SqlInstance = $group.Group[0].ServerName
                $historyObject.Database = $group.Group[0].DatabaseName
                $historyObject.UserName = $group.Group[0].UserName
                $historyObject.Start = [DateTime]$group.Group[0].BackupStartDate
                $historyObject.End = [DateTime]$group.Group[0].BackupFinishDate
                $historyObject.Duration = ([DateTime]$group.Group[0].BackupFinishDate - [DateTime]$group.Group[0].BackupStartDate)
                $historyObject.Path = [string[]]$group.Group.BackupPath
                $historyObject.FileList = ($group.Group.FileList | Select-Object Type, LogicalName, PhysicalName -Unique)
                $historyObject.TotalSize = ($group.Group.BackupSize.Byte | Measure-Object -Sum).Sum
                $HistoryObject.CompressedBackupSize = ($group.Group.CompressedBackupSize.Byte | Measure-Object -Sum).Sum
                $historyObject.Type = $description
                $historyObject.BackupSetId = $group.group[0].BackupSetGUID
                $historyObject.DeviceType = 'Disk'
                $historyObject.FullName = $group.Group.BackupPath
                $historyObject.Position = $group.Group[0].Position
                $historyObject.FirstLsn = $group.Group[0].FirstLSN
                $historyObject.DatabaseBackupLsn = $dbLsn
                $historyObject.CheckpointLSN = $group.Group[0].CheckpointLSN
                $historyObject.LastLsn = $group.Group[0].LastLsn
                $historyObject.SoftwareVersionMajor = $group.Group[0].SoftwareVersionMajor
                $historyObject.RecoveryModel = $group.Group.RecoveryModel
                $groupResults += $historyObject
            }
        }
        if (Test-Bound 'SourceInstance') {
            $groupResults = $groupResults | Where-Object {$_.InstanceName -in $SourceInstance}
        }

        if (Test-Bound 'DatabaseName') {
            $groupResults = $groupResults | Where-Object {$_.Database -in $DatabaseName}
        }
        if ($true -eq $Anonymise) {
            foreach ($group in $groupResults) {
                $group.ComputerName = Get-HashString -InString $group.ComputerName
                $group.InstanceName = Get-HashString -InString $group.InstanceName
                $group.SqlInstance = Get-HashString -InString $group.SqlInstance
                $group.Database = Get-HashString -InString $group.Database
                $group.UserName = Get-HashString -InString $group.UserName
                $group.Path = Get-HashString -InString  $group.Path
                $group.FullName = Get-HashString -InString $group.FullName
                $group.FileList = ($group.FileList | Select-Object Type,
                    @{Name = "LogicalName"; Expression = {Get-HashString -InString $_."LogicalName"}},
                    @{Name = "PhysicalName"; Expression = {Get-HashString -InString $_."PhysicalName"}})
            }
        }
        if ((Test-Bound -parameterName ExportPath) -and $null -ne $ExportPath) {
            $groupResults | Export-CliXml -Path $ExportPath -Depth 5 -NoClobber:$NoClobber
            if ($true -ne $PassThru) {
                return
            }
        }
        $groupResults | Sort-Object -Property End -Descending
    }
}
tools\dbatools\functions\Get-DbaBuildReference.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Get-DbaBuildReference {
    <#
    .SYNOPSIS
        Returns SQL Server Build infos on a SQL instance

    .DESCRIPTION
        Returns info about the specific build of a SQL instance, including the SP, the CU and the reference KB, wherever possible.
        It also includes End Of Support dates as specified on Microsoft Life Cycle Policy

    .PARAMETER Build
        Instead of connecting to a real instance, pass a string identifying the build to get the info back.

    .PARAMETER Kb
        Get a KB information based on its number. Supported format: KBXXXXXX, or simply XXXXXX.

    .PARAMETER MajorVersion
        Get a KB information based on SQL Server version. Can be refined further by -ServicePack and -CumulativeUpdate parameters.
        Examples: SQL2008 | 2008R2 | 2016

    .PARAMETER ServicePack
        Get a KB information based on SQL Server Service Pack version. Can be refined further by -CumulativeUpdate parameter.
        Examples: SP0 | 2 | RTM

    .PARAMETER CumulativeUpdate
        Get a KB information based on SQL Server Cumulative Update version.
         Examples: CU0 | CU13 | CU0

    .PARAMETER SqlInstance
        Target any number of instances, in order to return their build state.

    .PARAMETER SqlCredential
        When connecting to an instance, use the credentials specified.

    .PARAMETER Update
        Looks online for the most up to date reference, replacing the local one.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: SqlBuild
        Author: Simone Bizzotto (@niphold) | Friedrich Weinmann (@FredWeinmann)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaBuildReference

    .EXAMPLE
        PS C:\> Get-DbaBuildReference -Build "12.00.4502"

        Returns information about a build identified by  "12.00.4502" (which is SQL 2014 with SP1 and CU11)

    .EXAMPLE
        PS C:\> Get-DbaBuildReference -Build "12.00.4502" -Update

        Returns information about a build trying to fetch the most up to date index online. When the online version is newer, the local one gets overwritten

    .EXAMPLE
        PS C:\> Get-DbaBuildReference -Build "12.0.4502","10.50.4260"

        Returns information builds identified by these versions strings

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sqlserver2014a | Get-DbaBuildReference

        Integrate with other cmdlets to have builds checked for all your registered servers on sqlserver2014a

    #>
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding(DefaultParameterSetName = 'Build')]
    param (
        [version[]]
        $Build,

        [string[]]
        $Kb,

        [ValidateNotNullOrEmpty()]
        [string]
        $MajorVersion,

        [ValidateNotNullOrEmpty()]
        [string]
        [Alias('SP')]
        $ServicePack = 'RTM',

        [string]
        [Alias('CU')]
        $CumulativeUpdate,

        [Parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]
        $SqlInstance,

        [Alias("Credential")]
        [PsCredential]
        $SqlCredential,

        [switch]
        $Update,

        [switch]
        [Alias('Silent')]
        $EnableException
    )

    begin {

        #region Helper functions
        function Get-DbaBuildReferenceIndex {
            [CmdletBinding()]
            param (
                [string]
                $Moduledirectory,

                [bool]
                $Update,

                [bool]
                $EnableException
            )

            $orig_idxfile = "$Moduledirectory\bin\dbatools-buildref-index.json"
            $DbatoolsData = Get-DbatoolsConfigValue -Name 'Path.DbatoolsData'
            $writable_idxfile = Join-Path $DbatoolsData "dbatools-buildref-index.json"

            if (-not (Test-Path $orig_idxfile)) {
                Write-Message -Level Warning -Message "Unable to read local SQL build reference file. Check your module integrity!"
            }

            if ((-not (Test-Path $orig_idxfile)) -and (-not (Test-Path $writable_idxfile))) {
                throw "Build reference file not found, check module health!"
            }

            # If no writable copy exists, create one and return the module original
            if (-not (Test-Path $writable_idxfile)) {
                Copy-Item -Path $orig_idxfile -Destination $writable_idxfile -Force -ErrorAction Stop
                $result = Get-Content $orig_idxfile -Raw | ConvertFrom-Json
            }

            # Else, if both exist, update the writeable if necessary and return the current version
            elseif (Test-Path $orig_idxfile) {
                $module_content = Get-Content $orig_idxfile -Raw | ConvertFrom-Json
                $data_content = Get-Content $writable_idxfile -Raw | ConvertFrom-Json

                $module_time = Get-Date $module_content.LastUpdated
                $data_time = Get-Date $data_content.LastUpdated

                $offline_time = $module_time
                if ($module_time -gt $data_time) {
                    Copy-Item -Path $orig_idxfile -Destination $writable_idxfile -Force -ErrorAction Stop
                    $result = $module_content
                } else {
                    $result = $data_content
                    $offline_time = $data_time
                }
                # If Update is passed, try to fetch from online resource and store into the writeable
                if ($Update) {
                    $WebContent = Get-DbaBuildReferenceIndexOnline -EnableException $EnableException
                    if ($null -ne $WebContent) {
                        $webdata_content = $WebContent.Content | ConvertFrom-Json
                        $webdata_time = Get-Date $webdata_content.LastUpdated
                        if ($webdata_time -gt $offline_time) {
                            Write-Message -Level Output -Message "Index updated correctly, last update on: $(Get-Date -Date $webdata_time -Format s), was $(Get-Date -Date $offline_time -Format s)"
                            $WebContent.Content | Out-File $writable_idxfile -Encoding utf8 -ErrorAction Stop
                            $result = Get-Content $writable_idxfile -Raw | ConvertFrom-Json
                        }
                    }
                }
            }

            # Else if the module version of the file no longer exists, but the writable version exists, return the writable version
            else {
                $result = Get-Content $writable_idxfile -Raw | ConvertFrom-Json
            }

            $LastUpdated = Get-Date -Date $result.LastUpdated
            if ($LastUpdated -lt (Get-Date).AddDays(-45)) {
                Write-Message -Level Warning -Message "Index is stale, last update on: $(Get-Date -Date $LastUpdated -Format s), try the -Update parameter to fetch the most up to date index"
            }

            $result.Data | Select-Object @{ Name = "VersionObject"; Expression = { [version]$_.Version } }, *
        }

        function Get-DbaBuildReferenceIndexOnline {
            [CmdletBinding()]
            param (
                [bool]
                $EnableException
            )
            $url = Get-DbatoolsConfigValue -Name 'assets.sqlbuildreference'
            try {
                $WebContent = Invoke-TlsWebRequest $url -ErrorAction Stop
            } catch {
                try {
                    Write-Message -Level Verbose -Message "Probably using a proxy for internet access, trying default proxy settings"
                    (New-Object System.Net.WebClient).Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
                    $WebContent = Invoke-TlsWebRequest $url -ErrorAction Stop
                } catch {
                    Write-Message -Level Warning -Message "Couldn't download updated index from $url"
                    return
                }
            }
            return $WebContent
        }

        function Resolve-DbaBuild {
            [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
            [CmdletBinding()]
            [OutputType([System.Collections.Hashtable])]
            param (
                [Parameter(Mandatory, ParameterSetName = 'Build')]
                [version]
                $Build,

                [Parameter(Mandatory, ParameterSetName = 'KB')]
                [string]
                $Kb,

                [Parameter(Mandatory, ParameterSetName = 'HFLevel')]
                [string]
                $MajorVersion,

                [Parameter(ParameterSetName = 'HFLevel')]
                [string]
                [Alias('SP')]
                $ServicePack = 'RTM',

                [Parameter(ParameterSetName = 'HFLevel')]
                [string]
                [Alias('CU')]
                $CumulativeUpdate,

                $Data,

                [bool]
                $EnableException
            )

            if ($Build) {
                Write-Message -Level Verbose -Message "Looking for $Build"

                $IdxVersion = $Data | Where-Object Version -like "$($Build.Major).$($Build.Minor).*"
            } elseif ($Kb) {
                Write-Message -Level Verbose -Message "Looking for KB $Kb"
                if ($Kb -match '^(KB)?(\d+)$') {
                    $currentKb = $Matches[2]
                    $kbVersion = $Data | Where-Object KBList -contains $currentKb
                    $IdxVersion = $Data | Where-Object Version -like "$($kbVersion.VersionObject.Major).$($kbVersion.VersionObject.Minor).*"
                } else {
                    Stop-Function -Message "Wrong KB name $kb"
                    return
                }
            } elseif ($MajorVersion) {
                Write-Message -Level Verbose -Message "Looking for SQL $MajorVersion SP $ServicePack CU $CumulativeUpdate"
                $kbVersion = $Data | Where-Object Name -eq $MajorVersion
                $IdxVersion = $Data | Where-Object Version -like "$($kbVersion.VersionObject.Major).$($kbVersion.VersionObject.Minor).*"
            }

            $Detected = @{ }
            $Detected.MatchType = 'Approximate'
            $idxCount = $IdxVersion | Measure-Object | Select-Object -ExpandProperty Count
            Write-Message -Level Verbose -Message "We have $idxCount builds in store for this Release"
            If ($idxCount -eq 0) {
                Write-Message -Level Warning -Message "No info in store for this Release"
                $Detected.Warning = "No info in store for this Release"
            } else {
                $LastVer = $IdxVersion[0]
            }
            foreach ($el in $IdxVersion) {
                if ($null -ne $el.Name) {
                    $Detected.Name = $el.Name
                }
                if ($Build -and $el.VersionObject -gt $Build) {
                    $Detected.MatchType = 'Approximate'
                    $Detected.Warning = "$Build not found, closest build we have is $($LastVer.Version)"
                    break
                }
                $LastVer = $el
                $Detected.BuildLevel = $el.VersionObject
                if ($null -ne $el.SP) {
                    $Detected.SP = $el.SP
                    $Detected.CU = $null
                }
                if ($null -ne $el.CU) {
                    $Detected.CU = $el.CU
                }
                if ($null -ne $el.SupportedUntil) {
                    $Detected.SupportedUntil = (Get-Date -date $el.SupportedUntil)
                }
                $Detected.Build = $el.Version
                $Detected.KB = $el.KBList
                if (($Build -and $el.Version -eq $Build) -or ($Kb -and $el.KBList -eq $currentKb)) {
                    $Detected.MatchType = 'Exact'
                    break
                } elseif ($MajorVersion -and $Detected.SP -contains $ServicePack -and (!$CumulativeUpdate -or ($el.CU -and $el.CU -eq $CumulativeUpdate))) {
                    $Detected.MatchType = 'Exact'
                    break
                }
            }
            return $Detected
        }
        #endregion Helper functions

        $moduledirectory = $MyInvocation.MyCommand.Module.ModuleBase

        try {
            $IdxRef = Get-DbaBuildReferenceIndex -Moduledirectory $moduledirectory -Update $Update -EnableException $EnableException
        } catch {
            Stop-Function -Message "Error loading SQL build reference" -ErrorRecord $_
            return
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }

        #region verifying parameters
        $ComplianceSpec = @()
        $ComplianceSpecExclusiveParams = @('Build', 'Kb', @( 'MajorVersion', 'ServicePack', 'CumulativeUpdate'), 'SqlInstance')
        foreach ($exclParamGroup in $ComplianceSpecExclusiveParams) {
            foreach ($exclParam in $exclParamGroup) {
                if (Test-Bound -Parameter $exclParam) {
                    $ComplianceSpec += $exclParam
                    break
                }
            }
        }
        if ($ComplianceSpec.Length -gt 1) {
            Stop-Function -Category InvalidArgument -Message "$($ComplianceSpec -join ', ') are mutually exclusive. Please choose one or the other. Quitting."
            return
        }
        if ($ComplianceSpec.Length -eq 0) {
            Stop-Function -Category InvalidArgument -Message "You need to choose at least one parameter."
            return
        }
        if (((Test-Bound -Parameter ServicePack) -or (Test-Bound -Parameter CumulativeUpdate)) -and (Test-Bound -Not -Parameter MajorVersion)) {
            Stop-Function -Category InvalidArgument -Message "-MajorVersion is required when specifying SP or CU."
            return
        }
        if ($MajorVersion) {
            if ($MajorVersion -match '^(SQL)?(\d{4}(R2)?)$') {
                $MajorVersion = $Matches[2]
            } else {
                Stop-Function -Message "Incorrect SQL Server version format: use SQL2XXX or just 2XXXX - SQL2012, SQL2008R2"
                return
            }
            if (!$ServicePack) {
                $ServicePack = 'RTM'
            }
            if ($ServicePack -match '^(SP)?\s*(\d+)$') {
                if ($Matches[2] -eq '0') {
                    $ServicePack = 'RTM'
                } else {
                    $ServicePack = 'SP' + $Matches[2]
                }
            } elseif ($ServicePack -notmatch '^RTM$') {
                Stop-Function -Message "Incorrect SQL Server service pack format: use SPX, X or RTM, where X is a service pack number"
                return
            }
            if ($CumulativeUpdate) {
                if ($CumulativeUpdate -match '^(CU)?\s*(\d+)$') {
                    if ($Matches[2] -eq '0') {
                        $CumulativeUpdate = ''
                    } else {
                        $CumulativeUpdate = 'CU' + $Matches[2]
                    }
                } else {
                    Stop-Function -Message "Incorrect SQL Server cumulative update format: use CUX or X, where X is a cumulative update number"
                    return
                }
            }
        }
        #endregion verifying parameters


        foreach ($instance in $SqlInstance) {
            #region Ensure the connection is established
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failed to process Instance $Instance" -ErrorRecord $_ -Target $instance -Continue
            }

            try {
                $null = $server.Version.ToString()
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            #endregion Ensure the connection is established

            $Detected = Resolve-DbaBuild -Build $server.Version -Data $IdxRef -EnableException $EnableException

            [PSCustomObject]@{
                SqlInstance    = $server.DomainInstanceName
                Build          = $server.Version
                NameLevel      = $Detected.Name
                SPLevel        = $Detected.SP
                CULevel        = $Detected.CU
                KBLevel        = $Detected.KB
                BuildLevel     = $Detected.BuildLevel
                SupportedUntil = $Detected.SupportedUntil
                MatchType      = $Detected.MatchType
                Warning        = $Detected.Warning
            }
        }

        foreach ($buildstr in $Build) {
            $Detected = Resolve-DbaBuild -Build $buildstr -Data $IdxRef -EnableException $EnableException

            [PSCustomObject]@{
                SqlInstance    = $null
                Build          = $buildstr
                NameLevel      = $Detected.Name
                SPLevel        = $Detected.SP
                CULevel        = $Detected.CU
                KBLevel        = $Detected.KB
                BuildLevel     = $Detected.BuildLevel
                SupportedUntil = $Detected.SupportedUntil
                MatchType      = $Detected.MatchType
                Warning        = $Detected.Warning
            } | Select-DefaultView -ExcludeProperty SqlInstance
        }

        foreach ($kbItem in $Kb) {
            $Detected = Resolve-DbaBuild -Kb $kbItem -Data $IdxRef -EnableException $EnableException

            [PSCustomObject]@{
                SqlInstance    = $null
                Build          = $Detected.Build
                NameLevel      = $Detected.Name
                SPLevel        = $Detected.SP
                CULevel        = $Detected.CU
                KBLevel        = $Detected.KB
                BuildLevel     = $Detected.BuildLevel
                SupportedUntil = $Detected.SupportedUntil
                MatchType      = $Detected.MatchType
                Warning        = $Detected.Warning
            } | Select-DefaultView -ExcludeProperty SqlInstance
        }

        if ($MajorVersion) {
            $Detected = Resolve-DbaBuild -MajorVersion $MajorVersion -ServicePack $ServicePack -CumulativeUpdate $CumulativeUpdate -Data $IdxRef -EnableException $EnableException

            [PSCustomObject]@{
                SqlInstance    = $null
                Build          = $Detected.Build
                NameLevel      = $Detected.Name
                SPLevel        = $Detected.SP
                CULevel        = $Detected.CU
                KBLevel        = $Detected.KB
                BuildLevel     = $Detected.BuildLevel
                SupportedUntil = $Detected.SupportedUntil
                MatchType      = $Detected.MatchType
                Warning        = $Detected.Warning
            } | Select-DefaultView -ExcludeProperty SqlInstance
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaSqlBuildReference
    }
}
tools\dbatools\functions\Get-DbaClientAlias.ps1
function Get-DbaClientAlias {
    <#
    .SYNOPSIS
        Gets any SQL Server alias for the specified server(s)

    .DESCRIPTION
        Gets SQL Server alias by reading HKLM:\SOFTWARE\Microsoft\MSSQLServer\Client

    .PARAMETER ComputerName
        The target computer where the alias has been created

    .PARAMETER Credential
        Allows you to login to remote computers using alternative credentials

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Alias
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaClientAlias

    .EXAMPLE
        PS C:\> Get-DbaClientAlias

        Gets all SQL Server client aliases on the local computer

    .EXAMPLE
        PS C:\> Get-DbaClientAlias -ComputerName workstationx

        Gets all SQL Server client aliases on Workstationx

    .EXAMPLE
        PS C:\> Get-DbaClientAlias -ComputerName workstationx -Credential ad\sqldba

        Logs into workstationx as ad\sqldba then retrieves all SQL Server client aliases on Workstationx

    .EXAMPLE
        PS C:\> 'Server1', 'Server2' | Get-DbaClientAlias

        Gets all SQL Server client aliases on Server1 and Server2

    #>
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($computer in $ComputerName) {
            $scriptblock = {

                function Get-ItemPropertyValue {
                    param (
                        [parameter()]
                        [String]$Path,
                        [parameter()]
                        [String]$Name
                    )
                    (Get-ItemProperty -LiteralPath $Path -Name $Name).$Name
                }

                $basekeys = "HKLM:\SOFTWARE\WOW6432Node\Microsoft\MSSQLServer", "HKLM:\SOFTWARE\Microsoft\MSSQLServer"

                foreach ($basekey in $basekeys) {

                    if ((Test-Path $basekey) -eq $false) {
                        <# DO NOT use Write-Message as this is inside of a script block #>
                        Write-Warning "Base key ($basekey) does not exist. Quitting."
                        continue
                    }

                    $client = "$basekey\Client"

                    if ((Test-Path $client) -eq $false) {
                        continue
                    }

                    $connect = "$client\ConnectTo"

                    if ((Test-Path $connect) -eq $false) {
                        continue
                    }

                    if ($basekey -like "*WOW64*") {
                        $architecture = "32-bit"
                    } else {
                        $architecture = "64-bit"
                    }

                    # "Get SQL Server alias for $ComputerName for $architecture"
                    $all = Get-Item -Path $connect
                    foreach ($entry in $all.Property) {
                        $value = Get-ItemPropertyValue -Path $connect -Name $entry
                        $clean = $value.Replace('DBNMPNTW,', '').Replace('DBMSSOCN,', '')
                        if ($value.StartsWith('DBMSSOCN')) { $protocol = 'TCP/IP' } else { $protocol = 'Named Pipes' }

                        [pscustomobject]@{
                            ComputerName   = $env:COMPUTERNAME
                            NetworkLibrary = $protocol
                            ServerName     = $clean
                            AliasName      = $entry
                            AliasString    = $value
                            Architecture   = $architecture
                        }
                    }
                }
            }

            try {
                Invoke-Command2 -ComputerName $computer -Credential $Credential -ScriptBlock $scriptblock -ErrorAction Stop |
                    Select-DefaultView -Property ComputerName, Architecture, NetworkLibrary, ServerName, AliasName
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Target $computer -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaClientProtocol.ps1
function Get-DbaClientProtocol {
    <#
    .SYNOPSIS
        Gets the SQL Server related client protocols on a computer.

    .DESCRIPTION
        Gets the SQL Server related client protocols on one or more computers.

        Requires Local Admin rights on destination computer(s).
        The client protocols can be enabled and disabled when retrieved via WSMan.

    .PARAMETER ComputerName
        The target SQL Server instance or instances.

    .PARAMETER Credential
        Credential object used to connect to the computer as a different user.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Protocol
        Author: Klaas Vandenberghe (@PowerDBAKlaas)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaClientProtocol

    .EXAMPLE
        PS C:\> Get-DbaClientProtocol -ComputerName sqlserver2014a

        Gets the SQL Server related client protocols on computer sqlserver2014a.

    .EXAMPLE
        PS C:\> 'sql1','sql2','sql3' | Get-DbaClientProtocol

        Gets the SQL Server related client protocols on computers sql1, sql2 and sql3.

    .EXAMPLE
        PS C:\> Get-DbaClientProtocol -ComputerName sql1,sql2 | Out-GridView

        Gets the SQL Server related client protocols on computers sql1 and sql2, and shows them in a grid view.

    .EXAMPLE
        PS C:\> (Get-DbaClientProtocol -ComputerName sql2 | Where { $_.DisplayName = 'via' }).Disable()

        Disables the VIA ClientNetworkProtocol on computer sql2.
        If successful, return code 0 is shown.

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [Alias("cn", "host", "Server")]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential] $Credential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ( $computer in $ComputerName.ComputerName ) {
            $server = Resolve-DbaNetworkName -ComputerName $computer -Credential $credential
            if ( $server.FullComputerName ) {
                $computer = $server.FullComputerName
                Write-Message -Level Verbose -Message "Getting SQL Server namespace on $computer"
                $namespace = Get-DbaCmObject -ComputerName $computer -Namespace root\Microsoft\SQLServer -Query "Select * FROM __NAMESPACE WHERE Name LIke 'ComputerManagement%'" -ErrorAction SilentlyContinue |
                    Where-Object {(Get-DbaCmObject -ComputerName $computer -Namespace $("root\Microsoft\SQLServer\" + $_.Name) -ClassName ClientNetworkProtocol -ErrorAction SilentlyContinue).count -gt 0} |
                    Sort-Object Name -Descending | Select-Object -First 1

                if ( $namespace.Name ) {
                    Write-Message -Level Verbose -Message "Getting Cim class ClientNetworkProtocol in Namespace $($namespace.Name) on $computer"
                    try {
                        $prot = Get-DbaCmObject -ComputerName $computer -Namespace $("root\Microsoft\SQLServer\" + $namespace.Name) -ClassName ClientNetworkProtocol -ErrorAction SilentlyContinue

                        $prot | Add-Member -Force -MemberType ScriptProperty -Name IsEnabled -Value { switch ( $this.ProtocolOrder ) { 0 { $false } default { $true } } }
                        $prot | Add-Member -Force -MemberType ScriptMethod -Name Enable -Value {Invoke-CimMethod -MethodName SetEnable -InputObject $this }
                        $prot | Add-Member -Force -MemberType ScriptMethod -Name Disable -Value {Invoke-CimMethod -MethodName SetDisable -InputObject $this }

                        foreach ( $protocol in $prot ) {
                            Select-DefaultView -InputObject $protocol -Property 'PSComputerName as ComputerName', 'ProtocolDisplayName as DisplayName', 'ProtocolDll as DLL', 'ProtocolOrder as Order', 'IsEnabled'
                        }
                    } catch {
                        Write-Message -Level Warning -Message "No Sql ClientNetworkProtocol found on $computer"
                    }
                } #if namespace
                else {
                    Write-Message -Level Warning -Message "No ComputerManagement Namespace on $computer. Please note that this function is available from SQL 2005 up."
                } #else no namespace
            } #if computername
            else {
                Write-Message -Level Warning -Message "Failed to connect to $computer"
            }
        } #foreach computer
    }
}
tools\dbatools\functions\Get-DbaCmConnection.ps1
function Get-DbaCmConnection {
    <#
    .SYNOPSIS
        Retrieves windows management connections from the cache

    .DESCRIPTION
        Retrieves windows management connections from the cache

    .PARAMETER ComputerName
        The computername to ComputerName for.

    .PARAMETER UserName
        Username on credentials to look for. Will not find connections using the default windows credentials.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ComputerManagement, CIM
        Author: Friedrich Weinmann (@FredWeinmann)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaCmConnection

    .EXAMPLE
        PS C:\> Get-DbaCmConnection

        List all cached connections.

    .EXAMPLE
        PS C:\> Get-DbaCmConnection sql2014

        List the cached connection - if any - to the server sql2014.

    .EXAMPLE
        PS C:\> Get-DbaCmConnection -UserName "*charles*"

        List all cached connection that use a username containing "charles" as default or override credentials.

    #>
    [CmdletBinding()]
    param
    (
        [Parameter(Position = 0, ValueFromPipeline)]
        [Alias('Filter')]
        [String[]]
        $ComputerName = "*",

        [String]
        $UserName = "*",

        [switch]
        [Alias('Silent')]$EnableException
    )

    begin {
        Write-Message -Level InternalComment -Message "Starting"
        Write-Message -Level Verbose -Message "Bound parameters: $($PSBoundParameters.Keys -join ", ")"
    }
    process {
        foreach ($name in $ComputerName) {
            Write-Message -Level VeryVerbose -Message "Processing search. ComputerName: '$name' | Username: '$UserName'"
            ([Sqlcollaborative.Dbatools.Connection.ConnectionHost]::Connections.Values | Where-Object { ($_.ComputerName -like $name) -and ($_.Credentials.UserName -like $UserName) })
        }
    }
    end {
        Write-Message -Level InternalComment -Message "Ending"
    }
}
tools\dbatools\functions\Get-DbaCmObject.ps1
function Get-DbaCmObject {
    <#
    .SYNOPSIS
        Retrieves Wmi/Cim-Style information from computers.

    .DESCRIPTION
        This function centralizes all requests for information retrieved from Get-WmiObject or Get-CimInstance.
        It uses different protocols as available in this order:
        - Cim over WinRM
        - Cim over DCOM
        - Wmi
        - Wmi over PowerShell Remoting
        It remembers channels that didn't work and will henceforth avoid them. It remembers invalid credentials and will avoid reusing them.
        Much of its behavior can be configured using Test-DbaCmConnection.

    .PARAMETER ClassName
        The name of the class to retrieve.

    .PARAMETER Query
        The Wmi/Cim query tu run against the server.

    .PARAMETER ComputerName
        The computer(s) to connect to. Defaults to localhost.

    .PARAMETER Credential
        Credentials to use. Invalid credentials will be stored in a credentials cache and not be reused.

    .PARAMETER Namespace
        The namespace of the class to use.

    .PARAMETER DoNotUse
        Connection Protocols that should not be used.

    .PARAMETER Force
        Overrides some checks that might otherwise halt execution as a precaution
        - Ignores timeout on bad connections

    .PARAMETER SilentlyContinue
        Use in conjunction with the -EnableException switch.
        By default, Get-DbaCmObject will throw a terminating exception when connecting to a target is impossible in exception enabled mode.
        Setting this switch will cause it write a non-terminating exception and continue with the next computer.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ComputerManagement, CIM
        Author: Friedrich Weinmann (@FredWeinmann)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaCmObject

    .EXAMPLE
        PS C:\> Get-DbaCmObject win32_OperatingSystem

        Retrieves the common operating system information from the local computer.

    .EXAMPLE
        PS C:\> Get-DbaCmObject -Computername "sql2014" -ClassName Win32_OperatingSystem -Credential $cred -DoNotUse CimRM

        Retrieves the common operating system information from the server sql2014.
        It will use the Credentials stored in $cred to connect, unless they are known to not work, in which case they will default to windows credentials (unless another default has been set).

    #>
    [CmdletBinding(DefaultParameterSetName = "Class")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWMICmdlet", "", Justification = "Using Get-WmiObject is used as a fallback for gathering information")]
    param (
        [Parameter(Mandatory, Position = 0, ParameterSetName = "Class")]
        [Alias('Class')]
        [string]
        $ClassName,

        [Parameter(Mandatory, Position = 0, ParameterSetName = "Query")]
        [string]
        $Query,

        [Parameter(ValueFromPipeline)]
        [Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter[]]
        $ComputerName = $env:COMPUTERNAME,

        [System.Management.Automation.PSCredential]
        $Credential,

        [string]
        $Namespace = "root\cimv2",

        [Sqlcollaborative.Dbatools.Connection.ManagementConnectionType[]]
        $DoNotUse = "None",

        [switch]
        $Force,

        [switch]
        $SilentlyContinue,

        [switch]
        [Alias('Silent')]$EnableException
    )

    begin {
        #region Configuration Values
        $disable_cache = [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::DisableCache

        Write-Message -Level Verbose -Message "Configuration loaded | Cache disabled: $disable_cache"
        #endregion Configuration Values

        $ParSet = $PSCmdlet.ParameterSetName
    }
    process {
        # uses cim commands
        :main foreach ($connectionObject in $ComputerName) {
            if (-not $connectionObject.Success) { Stop-Function -Message "Failed to interpret input: $($connectionObject.Input)" -Category InvalidArgument -Target $connectionObject.Input -Continue -SilentlyContinue:$SilentlyContinue }

            # Since all connection caching runs using lower-case strings, making it lowercase here simplifies things.
            $computer = $connectionObject.Connection.ComputerName.ToLower()

            Write-Message -Message "[$computer] Retrieving Management Information" -Level VeryVerbose -Target $computer

            $connection = $connectionObject.Connection

            # Ensure using the right credentials
            try { $cred = $connection.GetCredential($Credential) }
            catch {
                $message = "Bad credentials! "
                if ($Credential) { $message += "The credentials for $($Credential.UserName) are known to not work. " }
                else { $message += "The windows credentials are known to not work. " }
                if ($connection.EnableCredentialFailover -or $connection.OverrideExplicitCredential) { $message += "The connection is configured to use credentials that are known to be good, but none have been registered yet. " }
                elseif ($connection.Credentials) { $message += "Working credentials are known for $($connection.Credentials.UserName), however the connection is not configured to automatically use them. This can be done using 'Set-DbaCmConnection -ComputerName $connection -OverrideExplicitCredential' " }
                elseif ($connection.UseWindowsCredentials) { $message += "The windows credentials are known to work, however the connection is not configured to automatically use them. This can be done using 'Set-DbaCmConnection -ComputerName $connection -OverrideExplicitCredential' " }
                $message += $_.Exception.Message
                Stop-Function -Message $message -ErrorRecord $_ -Target $connection -Continue -OverrideExceptionMessage
            }

            # Flags-Enumerations cannot be added in PowerShell 4 or older.
            # Thus we create a string and convert it afterwards.
            $enabledProtocols = "None"
            if ($connection.CimRM -notlike "Disabled") { $enabledProtocols += ", CimRM" }
            if ($connection.CimDCOM -notlike "Disabled") { $enabledProtocols += ", CimDCOM" }
            if ($connection.Wmi -notlike "Disabled") { $enabledProtocols += ", Wmi" }
            if ($connection.PowerShellRemoting -notlike "Disabled") { $enabledProtocols += ", PowerShellRemoting" }
            [Sqlcollaborative.Dbatools.Connection.ManagementConnectionType]$enabledProtocols = $enabledProtocols

            # Create list of excluded connection types (Duplicates don't matter)
            $excluded = @()
            foreach ($item in $DoNotUse) { $excluded += $item }

            :sub while ($true) {
                try { $conType = $connection.GetConnectionType(($excluded -join ","), $Force) }
                catch {
                    if (-not $disable_cache) { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::Connections[$computer] = $connection }
                    Stop-Function -Message "[$computer] Unable to find a connection to the target system. Ensure the name is typed correctly, and the server allows any of the following protocols: $enabledProtocols" -Target $computer -Category OpenError -Continue -ContinueLabel "main" -SilentlyContinue:$SilentlyContinue -ErrorRecord $_
                }

                switch ($conType.ToString()) {
                    #region CimRM
                    "CimRM" {
                        Write-Message -Level Verbose -Message "[$computer] Accessing computer using Cim over WinRM"
                        try {
                            if ($ParSet -eq "Class") { $connection.GetCimRMInstance($cred, $ClassName, $Namespace) }
                            else { $connection.QueryCimRMInstance($cred, $Query, "WQL", $Namespace) }

                            Write-Message -Level Verbose -Message "[$computer] Accessing computer using Cim over WinRM - Success"
                            $connection.ReportSuccess('CimRM')
                            $connection.AddGoodCredential($cred)
                            if (-not $disable_cache) { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::Connections[$computer] = $connection }
                            continue main
                        } catch {
                            Write-Message -Level Verbose -Message "[$computer] Accessing computer using Cim over WinRM - Failed"

                            # 1 = Generic runtime error
                            if ($_.Exception.InnerException.StatusCode -eq 1) {
                                # 0x8007052e, 0x80070005 : Authentication error, bad credential
                                if (($_.Exception.InnerException -eq 0x8007052e) -or ($_.Exception.InnerException -eq 0x80070005)) {
                                    # Ignore the global setting for bad credential cache disabling, since the connection object is aware of that state and will ignore input if it should.
                                    # This is due to the ability to locally override the global setting, thus it must be done on the object and can then be done in code
                                    $connection.AddBadCredential($cred)
                                    if (-not $disable_cache) { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::Connections[$computer] = $connection }
                                    Stop-Function -Message "[$computer] Invalid connection credentials" -Target $computer -Continue -ContinueLabel "main" -ErrorRecord $_ -SilentlyContinue:$SilentlyContinue -OverrideExceptionMessage
                                } elseif ($_.Exception.InnerException.MessageId -eq "HRESULT 0x80041013") {
                                    if ($ParSet -eq "Class") { Stop-Function -Message "[$computer] Failed to access $class in namespace $Namespace" -Target $computer -Continue -ContinueLabel "main" -ErrorRecord $_ -SilentlyContinue:$SilentlyContinue -Exception $_.Exception.InnerException }
                                    else { Stop-Function -Message "[$computer] Failed to execute $query in namespace $Namespace" -Target $computer -Continue -ContinueLabel "main" -ErrorRecord $_ -SilentlyContinue:$SilentlyContinue -Exception $_.Exception.InnerException }
                                } else {
                                    $connection.ReportFailure('CimRM')
                                    $excluded += "CimRM"
                                    continue sub
                                }
                            }

                            # 2 = Access to specific resource denied
                            elseif ($_.Exception.InnerException.StatusCode -eq 2) {
                                Stop-Function -Message "[$computer] Access to computer granted, but access to $Namespace\$ClassName denied" -Target $computer -Continue -ContinueLabel "main" -ErrorRecord $_ -SilentlyContinue:$SilentlyContinue -OverrideExceptionMessage
                            }

                            # 3 = Invalid Namespace
                            elseif ($_.Exception.InnerException.StatusCode -eq 3) {
                                Stop-Function -Message "[$computer] Invalid namespace: $Namespace" -Target $computer -Continue -ContinueLabel "main" -ErrorRecord $_ -SilentlyContinue:$SilentlyContinue -OverrideExceptionMessage
                            }
                            # 5 = Invalid Class
                            # See here for code reference: https://msdn.microsoft.com/en-us/library/cc150671(v=vs.85).aspx
                            elseif ($_.Exception.InnerException.StatusCode -eq 5) {
                                Stop-Function -Message "[$computer] Invalid class name ($ClassName), not found in current namespace ($Namespace)" -Target $computer -Continue -ContinueLabel "main" -ErrorRecord $_ -SilentlyContinue:$SilentlyContinue -OverrideExceptionMessage
                            }

                            # 0 & ExtendedStatus = Weird issue beyond the scope of the CIM standard. Often a server-side issue
                            elseif (($_.Exception.InnerException.StatusCode -eq 0) -and ($_.Exception.InnerException.ErrorData.original_error -like "__ExtendedStatus")) {
                                Stop-Function -Message "[$computer] Something went wrong when looking for $ClassName, in $Namespace. This often indicates issues with the target system." -Target $computer -Continue -ContinueLabel "main" -ErrorRecord $_ -SilentlyContinue:$SilentlyContinue
                            } else {
                                $connection.ReportFailure('CimRM')
                                $excluded += "CimRM"
                                continue sub
                            }
                        }
                    }
                    #endregion CimRM

                    #region CimDCOM
                    "CimDCOM" {
                        Write-Message -Level Verbose -Message "[$computer] Accessing computer using Cim over DCOM"
                        try {
                            if ($ParSet -eq "Class") { $connection.GetCimDCOMInstance($cred, $ClassName, $Namespace) }
                            else { $connection.QueryCimDCOMInstance($cred, $Query, "WQL", $Namespace) }

                            Write-Message -Level Verbose -Message "[$computer] Accessing computer using Cim over DCOM - Success"
                            $connection.ReportSuccess('CimDCOM')
                            $connection.AddGoodCredential($cred)
                            if (-not $disable_cache) { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::Connections[$computer] = $connection }
                            continue main
                        } catch {
                            Write-Message -Level Verbose -Message "[$computer] Accessing computer using Cim over DCOM - Failed"

                            # 1 = Generic runtime error
                            if ($_.Exception.InnerException.StatusCode -eq 1) {
                                # 0x8007052e, 0x80070005 : Authentication error, bad credential
                                if (($_.Exception.InnerException -eq 0x8007052e) -or ($_.Exception.InnerException -eq 0x80070005)) {
                                    # Ignore the global setting for bad credential cache disabling, since the connection object is aware of that state and will ignore input if it should.
                                    # This is due to the ability to locally override the global setting, thus it must be done on the object and can then be done in code
                                    $connection.AddBadCredential($cred)
                                    if (-not $disable_cache) { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::Connections[$computer] = $connection }
                                    Stop-Function -Message "[$computer] Invalid connection credentials" -Target $computer -Continue -ContinueLabel "main" -ErrorRecord $_ -SilentlyContinue:$SilentlyContinue -OverrideExceptionMessage
                                } elseif ($_.Exception.InnerException.MessageId -eq "HRESULT 0x80041013") {
                                    if ($ParSet -eq "Class") { Stop-Function -Message "[$computer] Failed to access $class in namespace $Namespace" -Target $computer -Continue -ContinueLabel "main" -ErrorRecord $_ -SilentlyContinue:$SilentlyContinue -Exception $_.Exception.InnerException }
                                    else { Stop-Function -Message "[$computer] Failed to execute $query in namespace $Namespace" -Target $computer -Continue -ContinueLabel "main" -ErrorRecord $_ -SilentlyContinue:$SilentlyContinue -Exception $_.Exception.InnerException }
                                } else {
                                    $connection.ReportFailure('CimDCOM')
                                    $excluded += "CimDCOM"
                                    continue sub
                                }
                            }

                            # 2 = Access to specific resource denied
                            elseif ($_.Exception.InnerException.StatusCode -eq 2) {
                                Stop-Function -Message "[$computer] Access to computer granted, but access to $Namespace\$ClassName denied" -Target $computer -Continue -ContinueLabel "main" -ErrorRecord $_ -SilentlyContinue:$SilentlyContinue -OverrideExceptionMessage
                            }

                            # 3 = Invalid Namespace
                            elseif ($_.Exception.InnerException.StatusCode -eq 3) {
                                Stop-Function -Message "[$computer] Invalid namespace: $Namespace" -Target $computer -Continue -ContinueLabel "main" -ErrorRecord $_ -SilentlyContinue:$SilentlyContinue -OverrideExceptionMessage
                            }

                            # 5 = Invalid Class
                            # See here for code reference: https://msdn.microsoft.com/en-us/library/cc150671(v=vs.85).aspx
                            elseif ($_.Exception.InnerException.StatusCode -eq 5) {
                                Stop-Function -Message "[$computer] Invalid class name ($ClassName), not found in current namespace ($Namespace)" -Target $computer -Continue -ContinueLabel "main" -ErrorRecord $_ -SilentlyContinue:$SilentlyContinue -OverrideExceptionMessage
                            }

                            # 0 & ExtendedStatus = Weird issue beyond the scope of the CIM standard. Often a server-side issue
                            elseif (($_.Exception.InnerException.StatusCode -eq 0) -and ($_.Exception.InnerException.ErrorData.original_error -like "__ExtendedStatus")) {
                                Stop-Function -Message "[$computer] Something went wrong when looking for $ClassName, in $Namespace. This often indicates issues with the target system." -Target $computer -Continue -ContinueLabel "main" -ErrorRecord $_ -SilentlyContinue:$SilentlyContinue
                            }

                            else {
                                $connection.ReportFailure('CimDCOM')
                                $excluded += "CimDCOM"
                                continue sub
                            }
                        }
                    }
                    #endregion CimDCOM

                    #region Wmi
                    "Wmi" {
                        Write-Message -Level Verbose -Message "[$computer] Accessing computer using WMI"
                        try {
                            switch ($ParSet) {
                                "Class" {
                                    $parameters = @{
                                        ComputerName = $computer
                                        ClassName    = $ClassName
                                        ErrorAction  = 'Stop'
                                    }
                                    if ($cred) { $parameters["Credential"] = $cred }
                                    if (Test-Bound "Namespace") { $parameters["Namespace"] = $Namespace }

                                }
                                "Query" {
                                    $parameters = @{
                                        ComputerName = $computer
                                        Query        = $Query
                                        ErrorAction  = 'Stop'
                                    }
                                    if ($cred) { $parameters["Credential"] = $cred }
                                    if (Test-Bound "Namespace") { $parameters["Namespace"] = $Namespace }
                                }
                            }

                            Get-WmiObject @parameters

                            Write-Message -Level Verbose -Message "[$computer] Accessing computer using WMI - Success"
                            $connection.ReportSuccess('Wmi')
                            $connection.AddGoodCredential($cred)
                            if (-not $disable_cache) { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::Connections[$computer] = $connection }
                            continue main
                        } catch {
                            Write-Message -Level Verbose -Message "[$computer] Accessing computer using WMI - Failed" -ErrorRecord $_

                            if ($_.CategoryInfo.Reason -eq "UnauthorizedAccessException") {
                                # Ignore the global setting for bad credential cache disabling, since the connection object is aware of that state and will ignore input if it should.
                                # This is due to the ability to locally override the global setting, thus it must be done on the object and can then be done in code
                                $connection.AddBadCredential($cred)
                                if (-not $disable_cache) { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::Connections[$computer] = $connection }
                                Stop-Function -Message "[$computer] Invalid connection credentials" -Target $computer -Continue -ContinueLabel "main" -ErrorRecord $_ -SilentlyContinue:$SilentlyContinue
                            } elseif ($_.CategoryInfo.Category -eq "InvalidType") {
                                Stop-Function -Message "[$computer] Invalid class name ($ClassName), not found in current namespace ($Namespace)" -Target $computer -Continue -ContinueLabel "main" -ErrorRecord $_ -SilentlyContinue:$SilentlyContinue
                            } elseif ($_.Exception.ErrorCode -eq "ProviderLoadFailure") {
                                Stop-Function -Message "[$computer] Failed to access: $ClassName, in namespace: $Namespace - There was a provider error. This indicates a potential issue with WMI on the server side." -Target $computer -Continue -ContinueLabel "main" -ErrorRecord $_ -SilentlyContinue:$SilentlyContinue
                            } else {
                                $connection.ReportFailure('Wmi')
                                $excluded += "Wmi"
                                continue sub
                            }
                        }
                    }
                    #endregion Wmi

                    #region PowerShell Remoting
                    "PowerShellRemoting" {
                        try {
                            Write-Message -Level Verbose -Message "[$computer] Accessing computer using PowerShell Remoting"
                            $scp_string = "Get-WmiObject -Class $ClassName -ErrorAction Stop"
                            if ($PSBoundParameters.ContainsKey("Namespace")) { $scp_string += " -Namespace $Namespace" }

                            $parameters = @{
                                ScriptBlock  = ([System.Management.Automation.ScriptBlock]::Create($scp_string))
                                ComputerName = $ComputerName
                                ErrorAction  = 'Stop'
                            }
                            if ($Credential) { $parameters["Credential"] = $Credential }
                            Invoke-Command @parameters

                            Write-Message -Level Verbose -Message "[$computer] Accessing computer using PowerShell Remoting - Success"
                            $connection.ReportSuccess('PowerShellRemoting')
                            $connection.AddGoodCredential($cred)
                            if (-not $disable_cache) { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::Connections[$computer] = $connection }
                            continue main
                        } catch {
                            # Will always consider authenticated, since any call with credentials to a server that doesn't exist will also carry invalid credentials error.
                            # There simply is no way to differentiate between actual authentication errors and server not reached
                            $connection.ReportFailure('PowerShellRemoting')
                            $excluded += "PowerShellRemoting"
                            continue sub
                        }
                    }
                    #endregion PowerShell Remoting
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaCmsRegServer.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaCmsRegServer {
    <#
    .SYNOPSIS
        Gets list of SQL Server objects stored in SQL Server Central Management Server (CMS).

    .DESCRIPTION
        Returns an array of servers found in the CMS.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Name
        Specifies one or more names to include. Name is the visible name in SSMS CMS interface (labeled Registered Server Name)

    .PARAMETER ServerName
        Specifies one or more server names to include. Server Name is the actual instance name (labeled Server Name)

    .PARAMETER Group
        Specifies one or more groups to include from SQL Server Central Management Server.

    .PARAMETER ExcludeGroup
        Specifies one or more Central Management Server groups to exclude.

    .PARAMETER ExcludeCmsServer
        Deprecated, now follows the Microsoft convention of not including it by default. If you'd like to include the CMS Server, use -IncludeSelf

    .PARAMETER Id
        Get server by Id(s)

    .PARAMETER IncludeSelf
        If this switch is enabled, the CMS server itself will be included in the results, along with all other Registered Servers.

    .PARAMETER ResolveNetworkName
        If this switch is enabled, the NetBIOS name and IP address(es) of each server will be returned.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.

        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.

        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: RegisteredServer, CMS
        Author: Bryan Hamby (@galador)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaCmsRegServer

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sqlserver2014a

        Gets a list of servers from the CMS on sqlserver2014a, using Windows Credentials.

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sqlserver2014a -IncludeSelf

        Gets a list of servers from the CMS on sqlserver2014a and includes sqlserver2014a in the output results.

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sqlserver2014a -SqlCredential $credential | Select-Object -Unique -ExpandProperty ServerName

        Returns only the server names from the CMS on sqlserver2014a, using SQL Authentication to authenticate to the server.

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sqlserver2014a -Group HR, Accounting

        Gets a list of servers in the HR and Accounting groups from the CMS on sqlserver2014a.

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sqlserver2014a -Group HR\Development

        Returns a list of servers in the HR and sub-group Development from the CMS on sqlserver2014a.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Name,
        [string[]]$ServerName,
        [Alias("Groups")]
        [object[]]$Group,
        [object[]]$ExcludeGroup,
        [int[]]$Id,
        [switch]$IncludeSelf,
        [switch]$ExcludeCmsServer,
        [switch]$ResolveNetworkName,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        if ($ResolveNetworkName) {
            $defaults = 'ComputerName', 'FQDN', 'IPAddress', 'Name', 'ServerName', 'Group', 'Description'
        }
        $defaults = 'Name', 'ServerName', 'Group', 'Description'
    }
    process {
        $servers = @()
        foreach ($instance in $SqlInstance) {
            if ($Group) {
                $groupservers = Get-DbaCmsRegServerGroup -SqlInstance $instance -SqlCredential $SqlCredential -Group $Group -ExcludeGroup $ExcludeGroup
                if ($groupservers) {
                    $servers += $groupservers.GetDescendantRegisteredServers()
                }
            } else {
                try {
                    $serverstore = Get-DbaCmsRegServerStore -SqlInstance $instance -SqlCredential $SqlCredential -EnableException
                } catch {
                    Stop-Function -Message "Cannot access Central Management Server '$instance'." -ErrorRecord $_ -Continue
                }
                $servers += ($serverstore.DatabaseEngineServerGroup.GetDescendantRegisteredServers())
                $serverstore.ServerConnection.Disconnect()
            }
        }

        if ($Name) {
            Write-Message -Level Verbose -Message "Filtering by name for $name"
            $servers = $servers | Where-Object Name -in $Name
        }

        if ($ServerName) {
            Write-Message -Level Verbose -Message "Filtering by servername for $servername"
            $servers = $servers | Where-Object ServerName -in $ServerName
        }

        if ($Id) {
            Write-Message -Level Verbose -Message "Filtering by id for $Id (1 = default/root)"
            $servers = $servers | Where-Object Id -in $Id
        }

        if ($ExcludeGroup) {
            $excluded = Get-DbaCmsRegServer $serverstore.ServerConnection.SqlConnectionObject -Group $ExcludeGroup
            Write-Message -Level Verbose -Message "Excluding $ExcludeGroup"
            $servers = $servers | Where-Object { $_.Urn.Value -notin $excluded.Urn.Value }
        }

        foreach ($server in $servers) {
            $groupname = Get-RegServerGroupReverseParse $server
            if ($groupname -eq $server.Name) {
                $groupname = $null
            } else {
                $groupname = ($groupname).Split("\")
                $groupname = $groupname[0 .. ($groupname.Count - 2)]
                $groupname = ($groupname -join "\")
            }


            Add-Member -Force -InputObject $server -MemberType NoteProperty -Name ComputerName -value $serverstore.ComputerName
            Add-Member -Force -InputObject $server -MemberType NoteProperty -Name InstanceName -value $serverstore.InstanceName
            Add-Member -Force -InputObject $server -MemberType NoteProperty -Name SqlInstance -value $serverstore.SqlInstance
            Add-Member -Force -InputObject $server -MemberType NoteProperty -Name Group -value $groupname
            Add-Member -Force -InputObject $server -MemberType NoteProperty -Name FQDN -Value $null
            Add-Member -Force -InputObject $server -MemberType NoteProperty -Name IPAddress -Value $null

            if ($ResolveNetworkName) {
                try {
                    $lookup = Resolve-DbaNetworkName $server.ServerName -Turbo
                    $server.ComputerName = $lookup.ComputerName
                    $server.FQDN = $lookup.FQDN
                    $server.IPAddress = $lookup.IPAddress
                } catch {
                    try {
                        $lookup = Resolve-DbaNetworkName $server.ServerName
                        $server.ComputerName = $lookup.ComputerName
                        $server.FQDN = $lookup.FQDN
                        $server.IPAddress = $lookup.IPAddress
                    } catch {
                        # here to avoid an empty catch
                        $null = 1
                    }
                }
            }
            Add-Member -Force -InputObject $server -MemberType ScriptMethod -Name ToString -Value { $this.ServerName }
            Select-DefaultView -InputObject $server -Property $defaults
        }

        if ($IncludeSelf -and $servers) {
            Write-Message -Level Verbose -Message "Adding CMS instance"
            $self = $servers[0].PsObject.Copy()
            $self | Add-Member -MemberType NoteProperty -Name Name -Value "CMS Instance" -Force
            $self.ServerName = $instance
            $self.Description = $null
            $self.SecureConnectionString = $null
            Select-DefaultView -InputObject $self -Property $defaults
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Parameter ExcludeCmsServer
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Get-DbaRegisteredServerName
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Get-SqlRegisteredServerName
    }
}
tools\dbatools\functions\Get-DbaCmsRegServerGroup.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaCmsRegServerGroup {
    <#
    .SYNOPSIS
        Gets list of Server Groups objects stored in SQL Server Central Management Server (CMS).

    .DESCRIPTION
        Returns an array of Server Groups found in the CMS.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Group
        Specifies one or more groups to include from SQL Server Central Management Server.

    .PARAMETER ExcludeGroup
        Specifies one or more Central Management Server groups to exclude.

    .PARAMETER Id
        Get group by Id(s). This parameter only works if the group has a registered server in it.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.

        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.

        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: RegisteredServer, CMS
        Author: Tony Wilhelm (@tonywsql)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaCmsRegServerGroup

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServerGroup -SqlInstance sqlserver2014a

        Gets the top level groups from the CMS on sqlserver2014a, using Windows Credentials.

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServerGroup -SqlInstance sqlserver2014a -SqlCredential $credential

        Gets the top level groups from the CMS on sqlserver2014a, using alternative credentials to authenticate to the server.

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServerGroup -SqlInstance sqlserver2014a -Group HR, Accounting

        Gets the HR and Accounting groups from the CMS on sqlserver2014a.

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServerGroup -SqlInstance sqlserver2014a -Group HR\Development

        Returns the sub-group Development of the HR group from the CMS on sqlserver2014a.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Group,
        [object[]]$ExcludeGroup,
        [int[]]$Id,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Get-DbaCmsRegServerStore -SqlInstance $instance -SqlCredential $SqlCredential -EnableException
            } catch {
                Stop-Function -Message "Cannot access Central Management Server '$instance'" -ErrorRecord $_ -Continue
            }

            $groups = @()

            if ($group) {
                foreach ($currentgroup in $Group) {
                    Write-Message -Level Verbose -Message "Processing $currentgroup"
                    if ($currentgroup -is [Microsoft.SqlServer.Management.RegisteredServers.ServerGroup]) {
                        $currentgroup = Get-RegServerGroupReverseParse -object $currentgroup
                    }

                    if ($currentgroup -match 'DatabaseEngineServerGroup\\') {
                        $currentgroup = $currentgroup.Replace('DatabaseEngineServerGroup\', '')
                    }

                    if ($currentgroup -match '\\') {
                        $split = $currentgroup.Split('\\')
                        $i = 0
                        $groupobject = $server.DatabaseEngineServerGroup
                        do {
                            if ($groupobject) {
                                $groupobject = $groupobject.ServerGroups[$split[$i]]
                                Write-Message -Level Verbose -Message "Parsed $($groupobject.Name)"
                            }
                        }
                        until ($i++ -eq $split.GetUpperBound(0))
                        if ($groupobject) {
                            $groups += $groupobject
                        }
                    } else {
                        try {
                            $thisgroup = $server.DatabaseEngineServerGroup.ServerGroups[$currentgroup]
                            if ($thisgroup) {
                                Write-Message -Level Verbose -Message "Added $($thisgroup.Name)"
                                $groups += $thisgroup
                            }
                        } catch {
                            # here to avoid an empty catch
                            $null = 1
                        }
                    }
                }
            } else {
                Write-Message -Level Verbose -Message "Added all root server groups"
                $groups = $server.DatabaseEngineServerGroup.ServerGroups
            }

            if ($Group -eq 'DatabaseEngineServerGroup') {
                Write-Message -Level Verbose -Message "Added root group"
                $groups = $server.DatabaseEngineServerGroup
            }

            if ($ExcludeGroup) {
                $excluded = Get-DbaCmsRegServer $server -Group $ExcludeGroup
                Write-Message -Level Verbose -Message "Excluding $ExcludeGroup"
                $groups = $groups | Where-Object { $_.Urn.Value -notin $excluded.Urn.Value }
            }

            if ($Id) {
                Write-Message -Level Verbose -Message "Filtering for id $Id. Id 1 = default."
                if ($Id -eq 1) {
                    $groups = $server.DatabaseEngineServerGroup | Where-Object Id -in $Id
                } else {
                    $groups = $server.DatabaseEngineServerGroup.GetDescendantRegisteredServers().Parent | Where-Object Id -in $Id
                }
            }
            $server.ServerConnection.Disconnect()
            foreach ($groupobject in $groups) {
                Add-Member -Force -InputObject $groupobject -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                Add-Member -Force -InputObject $groupobject -MemberType NoteProperty -Name InstanceName -value $server.InstanceName
                Add-Member -Force -InputObject $groupobject -MemberType NoteProperty -Name SqlInstance -value $server.SqlInstance

                Select-DefaultView -InputObject $groupobject -Property ComputerName, InstanceName, SqlInstance, Name, DisplayName, Description, ServerGroups, RegisteredServers
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Get-DbaRegisteredServerGroup
    }
}
tools\dbatools\functions\Get-DbaCmsRegServerStore.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaCmsRegServerStore {
    <#
    .SYNOPSIS
        Returns a SQL Server Registered Server Store Object

    .DESCRIPTION
        Returns a SQL Server Registered Server Store object - useful for working with Central Management Store

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function
        to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: RegisteredServer,CMS
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaCmsRegServerStore

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServerStore -SqlInstance sqlserver2014a

        Returns a SQL Server Registered Server Store Object from sqlserver2014a

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServerStore -SqlInstance sqlserver2014a -SqlCredential sqladmin

        Returns a SQL Server Registered Server Store Object from sqlserver2014a  by logging in with the sqladmin login

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            try {
                $store = New-Object Microsoft.SqlServer.Management.RegisteredServers.RegisteredServersStore($server.ConnectionContext.SqlConnectionObject)
            } catch {
                Stop-Function -Message "Cannot access Central Management Server on $instance" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            Add-Member -Force -InputObject $store -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
            Add-Member -Force -InputObject $store -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
            Add-Member -Force -InputObject $store -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName

            Select-DefaultView -InputObject $store -ExcludeProperty ServerConnection, DomainInstanceName, DomainName, Urn, Properties, Metadata, Parent, ConnectionContext, PropertyMetadataChanged, PropertyChanged
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Get-DbaRegisteredServerStore
    }
}
tools\dbatools\functions\Get-DbaComputerCertificate.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaComputerCertificate {
    <#
    .SYNOPSIS
        Simplifies finding computer certificates that are candidates for using with SQL Server's network encryption

    .DESCRIPTION
        Gets computer certificates on localhost that are candidates for using with SQL Server's network encryption

    .PARAMETER ComputerName
       The target SQL Server instance or instances. Defaults to localhost. If target is a cluster, you must specify the distinct nodes.

    .PARAMETER Credential
        Allows you to login to $ComputerName using alternative credentials.

    .PARAMETER Store
        Certificate store - defaults to LocalMachine

    .PARAMETER Folder
        Certificate folder - defaults to My (Personal)

    .PARAMETER Path
        The path to a certificate - basically changes the path into a certificate object

    .PARAMETER Thumbprint
        Return certificate based on thumbprint

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Certificate
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaComputerCertificate

        Gets computer certificates on localhost that are candidates for using with SQL Server's network encryption

    .EXAMPLE
        PS C:\> Get-DbaComputerCertificate -ComputerName sql2016

        Gets computer certificates on sql2016 that are candidates for using with SQL Server's network encryption

    .EXAMPLE
        PS C:\> Get-DbaComputerCertificate -ComputerName sql2016 -Thumbprint 8123472E32AB412ED4288888B83811DB8F504DED, 04BFF8B3679BB01A986E097868D8D494D70A46D6

        Gets computer certificates on sql2016 that match thumbprints 8123472E32AB412ED4288888B83811DB8F504DED or 04BFF8B3679BB01A986E097868D8D494D70A46D6

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlInstance")]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [string]$Store = "LocalMachine",
        [string]$Folder = "My",
        [string]$Path,
        [string[]]$Thumbprint,
        [switch]$EnableException
    )

    begin {
        #region Scriptblock for remoting
        $scriptblock = {
            param (
                $Thumbprint,
                $Store,
                $Folder,
                $Path
            )

            if ($Path) {
                $bytes = [System.IO.File]::ReadAllBytes($path)
                $Certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
                $Certificate.Import($bytes, $null, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::DefaultKeySet)
                return $Certificate
            }
            
            function Get-CoreCertStore {
                [CmdletBinding()]
                param (
                    [ValidateSet("CurrentUser", "LocalMachine")]
                    [string]$Store,
                    [ValidateSet("AddressBook", "AuthRoot, CertificateAuthority", "Disallowed", "My", "Root", "TrustedPeople", "TrustedPublisher")]
                    [string]$Folder,
                    [ValidateSet("ReadOnly", "ReadWrite")]
                    [string]$Flag = "ReadOnly"
                )
                
                $storename = [System.Security.Cryptography.X509Certificates.StoreLocation]::$Store
                $foldername = [System.Security.Cryptography.X509Certificates.StoreName]::$Folder
                $flags = [System.Security.Cryptography.X509Certificates.OpenFlags]::$Flag
                $certstore = [System.Security.Cryptography.X509Certificates.X509Store]::New($foldername, $storename)
                $certstore.Open($flags)
                
                $certstore
            }
            
            function Get-CoreCertificate {
                [CmdletBinding()]
                param (
                    [ValidateSet("CurrentUser", "LocalMachine")]
                    [string]$Store,
                    [ValidateSet("AddressBook", "AuthRoot, CertificateAuthority", "Disallowed", "My", "Root", "TrustedPeople", "TrustedPublisher")]
                    [string]$Folder,
                    [ValidateSet("ReadOnly", "ReadWrite")]
                    [string]$Flag = "ReadOnly",
                    [string[]]$Thumbprint,
                    [System.Security.Cryptography.X509Certificates.X509Store[]]$InputObject
                )
                
                if (-not $InputObject) {
                    $InputObject += Get-CoreCertStore -Store $Store -Folder $Folder -Flag $Flag
                }
                
                $certs = ($InputObject).Certificates
                
                if ($Thumbprint) {
                    $certs = $certs | Where-Object Thumbprint -in $Thumbprint
                }
                
                $certs
            }
            
            if ($Thumbprint) {
                try {
                    <# DO NOT use Write-Message as this is inside of a script block #>
                    Write-Verbose "Searching Cert:\$Store\$Folder"
                    Get-CoreCertificate -Store $Store -Folder $Folder -Thumbprint $Thumbprint
                } catch {
                    # don't care - there's a weird issue with remoting where an exception gets thrown for no apparent reason
                    # here to avoid an empty catch
                    $null = 1
                }
            } else {
                try {
                    <# DO NOT use Write-Message as this is inside of a script block #>
                    Write-Verbose "Searching Cert:\$Store\$Folder"
                    Get-CoreCertificate -Store $Store -Folder $Folder | Where-Object EnhancedKeyUsageList -match '1\.3\.6\.1\.5\.5\.7\.3\.1'
                } catch {
                    # still don't care
                    # here to avoid an empty catch
                    $null = 1
                }
            }
        }
        #endregion Scriptblock for remoting
    }
    
    process {
        foreach ($computer in $computername) {
            try {
                Invoke-Command2 -ComputerName $computer -Credential $Credential -ScriptBlock $scriptblock -ArgumentList $thumbprint, $Store, $Folder, $Path -ErrorAction Stop | Select-DefaultView -Property FriendlyName, DnsNameList, Thumbprint, NotBefore, NotAfter, Subject, Issuer
            } catch {
                Stop-Function -Message "Issue connecting to computer" -ErrorRecord $_ -Target $computer -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaComputerSystem.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaComputerSystem {
    <#
    .SYNOPSIS
        Gets computer system information from the server.

    .DESCRIPTION
        Gets computer system information from the server and returns as an object.

    .PARAMETER ComputerName
        Target computer(s). If no computer name is specified, the local computer is targeted

    .PARAMETER Credential
        Alternate credential object to use for accessing the target computer(s).

    .PARAMETER IncludeAws
        If computer is hosted in AWS Infrastructure as a Service (IaaS), additional information will be included.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ServerInfo
        Author: Shawn Melton (@wsmelton), https://wsmelton.github.io

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaComputerSystem

    .EXAMPLE
        PS C:\> Get-DbaComputerSystem

        Returns information about the local computer's computer system

    .EXAMPLE
        PS C:\> Get-DbaComputerSystem -ComputerName sql2016

        Returns information about the sql2016's computer system

    .EXAMPLE
        PS C:\> Get-DbaComputerSystem -ComputerName sql2016 -IncludeAws

        Returns information about the sql2016's computer system and includes additional properties around the EC2 instance.

    #>
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [Alias("cn", "host", "Server")]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [switch]$IncludeAws,
        [switch][Alias('Silent')]
        $EnableException
    )
    process {
        foreach ($computer in $ComputerName) {
            try {
                $server = Resolve-DbaNetworkName -ComputerName $computer.ComputerName -Credential $Credential

                $computerResolved = $server.FullComputerName

                if (!$computerResolved) {
                    Stop-Function -Message "Unable to resolve hostname of $computer. Skipping." -Continue
                }

                if (Test-Bound "Credential") {
                    $computerSystem = Get-DbaCmObject -ClassName Win32_ComputerSystem -ComputerName $computerResolved -Credential $Credential
                } else {
                    $computerSystem = Get-DbaCmObject -ClassName Win32_ComputerSystem -ComputerName $computerResolved
                }

                $adminPasswordStatus =
                switch ($computerSystem.AdminPasswordStatus) {
                    0 { "Disabled" }
                    1 { "Enabled" }
                    2 { "Not Implemented" }
                    3 { "Unknown" }
                    default { "Unknown" }
                }

                $domainRole =
                switch ($computerSystem.DomainRole) {
                    0 { "Standalone Workstation" }
                    1 { "Member Workstation" }
                    2 { "Standalone Server" }
                    3 { "Member Server" }
                    4 { "Backup Domain Controller" }
                    5 { "Primary Domain Controller" }
                }

                $isHyperThreading = $false
                if ($computerSystem.NumberOfLogicalProcessors -gt $computerSystem.NumberofProcessors) {
                    $isHyperThreading = $true
                }

                if ($IncludeAws) {
                    $isAws = Invoke-Command2 -ComputerName $computerResolved -Credential $Credential -ScriptBlock { ((Invoke-TlsWebRequest -TimeoutSec 15 -Uri 'http://169.254.169.254').StatusCode) -eq 200 } -Raw

                    if ($isAws) {
                        $scriptBlock = {
                            [PSCustomObject]@{
                                AmiId            = (Invoke-TlsWebRequest -Uri 'http://169.254.169.254/latest/meta-data/ami-id').Content
                                IamRoleArn       = ((Invoke-TlsWebRequest -Uri 'http://169.254.169.254/latest/meta-data/iam/info').Content | ConvertFrom-Json).InstanceProfileArn
                                InstanceId       = (Invoke-TlsWebRequest -Uri 'http://169.254.169.254/latest/meta-data/instance-id').Content
                                InstanceType     = (Invoke-TlsWebRequest -Uri 'http://169.254.169.254/latest/meta-data/instance-type').Content
                                AvailabilityZone = (Invoke-TlsWebRequest -Uri 'http://169.254.169.254/latest/meta-data/placement/availability-zone').Content
                                PublicHostname   = (Invoke-TlsWebRequest -Uri 'http://169.254.169.254/latest/meta-data/public-hostname').Content
                            }
                        }
                        $awsProps = Invoke-Command2 -ComputerName $computerResolved -Credential $Credential -ScriptBlock $scriptBlock
                    } else {
                        Write-Message -Level Warning -Message "$computerResolved was not found to be an EC2 instance. Verify http://169.254.169.254 is accessible on the computer."
                    }
                }
                $inputObject = [PSCustomObject]@{
                    ComputerName            = $computerResolved
                    Domain                  = $computerSystem.Domain
                    DomainRole              = $domainRole
                    Manufacturer            = $computerSystem.Manufacturer
                    Model                   = $computerSystem.Model
                    SystemFamily            = $computerSystem.SystemFamily
                    SystemSkuNumber         = $computerSystem.SystemSKUNumber
                    SystemType              = $computerSystem.SystemType
                    NumberLogicalProcessors = $computerSystem.NumberOfLogicalProcessors
                    NumberProcessors        = $computerSystem.NumberOfProcessors
                    IsHyperThreading        = $isHyperThreading
                    TotalPhysicalMemory     = [DbaSize]$computerSystem.TotalPhysicalMemory
                    IsDaylightSavingsTime   = $computerSystem.EnableDaylightSavingsTime
                    DaylightInEffect        = $computerSystem.DaylightInEffect
                    DnsHostName             = $computerSystem.DNSHostName
                    IsSystemManagedPageFile = $computerSystem.AutomaticManagedPagefile
                    AdminPasswordStatus     = $adminPasswordStatus
                }
                if ($IncludeAws -and $isAws) {
                    Add-Member -Force -InputObject $inputObject -MemberType NoteProperty -Name AwsAmiId -Value $awsProps.AmiId
                    Add-Member -Force -InputObject $inputObject -MemberType NoteProperty -Name AwsIamRoleArn -Value $awsProps.IamRoleArn
                    Add-Member -Force -InputObject $inputObject -MemberType NoteProperty -Name AwsEc2InstanceId -Value $awsProps.InstanceId
                    Add-Member -Force -InputObject $inputObject -MemberType NoteProperty -Name AwsEc2InstanceType -Value $awsProps.InstanceType
                    Add-Member -Force -InputObject $inputObject -MemberType NoteProperty -Name AwsAvailabilityZone -Value $awsProps.AvailabilityZone
                    Add-Member -Force -InputObject $inputObject -MemberType NoteProperty -Name AwsPublicHostName -Value $awsProps.PublicHostname
                }
                $excludes = 'SystemSkuNumber', 'IsDaylightSavingsTime', 'DaylightInEffect', 'DnsHostName', 'AdminPasswordStatus'
                Select-DefaultView -InputObject $inputObject -ExcludeProperty $excludes
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Target $computer -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaConnection.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Get-DbaConnection {
    <#
    .SYNOPSIS
        Returns a bunch of information from dm_exec_connections.

    .DESCRIPTION
        Returns a bunch of information from dm_exec_connections which, according to Microsoft:
        "Returns information about the connections established to this instance of SQL Server and the details of each connection. Returns server wide connection information for SQL Server. Returns current database connection information for SQL Database."

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server(s) must be SQL Server 2005 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Connection
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaConnection

    .EXAMPLE
        PS C:\> Get-DbaConnection -SqlInstance sql2016, sql2017

        Returns client connection information from sql2016 and sql2017

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential", "Cred")]
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )

    begin {
        $sql = "SELECT  SERVERPROPERTY('MachineName') AS ComputerName,
                            ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
                            SERVERPROPERTY('ServerName') AS SqlInstance,
                            session_id as SessionId, most_recent_session_id as MostRecentSessionId, connect_time as ConnectTime,
                            net_transport as Transport, protocol_type as ProtocolType, protocol_version as ProtocolVersion,
                            endpoint_id as EndpointId, encrypt_option as EncryptOption, auth_scheme as AuthScheme, node_affinity as NodeAffinity,
                            num_reads as Reads, num_writes as Writes, last_read as LastRead, last_write as LastWrite,
                            net_packet_size as PacketSize, client_net_address as ClientNetworkAddress, client_tcp_port as ClientTcpPort,
                            local_net_address as ServerNetworkAddress, local_tcp_port as ServerTcpPort, connection_id as ConnectionId,
                            parent_connection_id as ParentConnectionId, most_recent_sql_handle as MostRecentSqlHandle
                            FROM sys.dm_exec_connections"
    }

    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            Write-Message -Level Debug -Message "Getting results for the following query: $sql."
            try {
                $server.Query($sql)
            } catch {
                Stop-Function -Message "Failure" -Target $server -Exception $_ -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaCpuRingBuffer.ps1
function Get-DbaCpuRingBuffer {
    <#
    .SYNOPSIS
        Collects CPU data from sys.dm_os_ring_buffers.  Works on SQL Server 2005 and above.

    .DESCRIPTION
        This command is based off of Glen Berry's diagnostic query for average CPU

        The sys.dm_os_ring_buffers stores the average CPU utilization history
        by the current instance of SQL Server, plus the summed average CPU utilization
        by all other processes on your machine are captured in one minute increments
        for the past 256 minutes.

        Reference: https://www.sqlskills.com/blogs/glenn/sql-server-diagnostic-information-queries-detailed-day-16//

    .PARAMETER SqlInstance
        Allows you to specify a comma separated list of servers to query.

    .PARAMETER SqlCredential
        Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted. To use:
        $cred = Get-Credential, this pass this $cred to the param.

        Windows Authentication will be used if DestinationSqlCredential is not specified. To connect as a different Windows user, run PowerShell as that user.

    .PARAMETER CollectionMinutes
        Allows you to specify a Collection Period in Minutes. Default is 60 minutes

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: CPU
        Author: Patrick Flynn (@sqllensman)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaCpuRingBuffer

    .EXAMPLE
        PS C:\> Get-DbaCpuRingBuffer -SqlInstance sql2008, sqlserver2012

        Gets CPU Statistics from sys.dm_os_ring_buffers for servers sql2008 and sqlserver2012 for last 60 minutes.

    .EXAMPLE
        PS C:\> Get-DbaCpuRingBuffer -SqlInstance sql2008 -CollectionMinutes 240

        Gets CPU Statistics from sys.dm_os_ring_buffers for server sql2008 for last 240 minutes

    .EXAMPLE
        PS C:\> $output = Get-DbaCpuRingBuffer -SqlInstance sql2008 -CollectionMinutes 240 | Select * | ConvertTo-DbaDataTable

        Gets CPU Statistics from sys.dm_os_ring_buffers for server sql2008 for last 240 minutes into a Data Table.

    .EXAMPLE
        PS C:\> 'sql2008','sql2012' | Get-DbaCpuRingBuffer

        Gets CPU Statistics from sys.dm_os_ring_buffers for servers sql2008 and sqlserver2012

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> Get-DbaCpuRingBuffer -SqlInstance sql2008 -SqlCredential $cred

        Connects using sqladmin credential and returns CPU Statistics from sys.dm_os_ring_buffers from sql2008
    #>
    [CmdletBinding()]
    Param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [int]$CollectionMinutes = 60,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($instance in $SqlInstance) {
            Write-Message -Level Verbose -Message "Attempting to connect to $instance"

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($server.VersionMajor -gt 9) {
                $currentTimestamp = ($server.Query("SELECT cpu_ticks / CONVERT (float, ( cpu_ticks / ms_ticks )) as TimeStamp FROM sys.dm_os_sys_info"))[0]
            } else {
                $currentTimestamp = ($server.Query("SELECT cpu_ticks / CONVERT(FLOAT, cpu_ticks_in_ms) as TimeStamp FROM sys.dm_os_sys_info"))[0]
            }
            Write-Message -Level Verbose -Message "Using current timestampe of $currentTimestamp"

            $sql = "With RingBufferSchedulerMonitor as
                (
                    SELECT
                        timestamp,
                        CONVERT(xml, record) AS record
                    FROM sys.dm_os_ring_buffers
                    WHERE (ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR')
                    AND (record LIKE '%%')
                ), RingBufferSchedulerMonitorValues as
                (
                    SELECT
                        record.value('(./Record/@id)[1]', 'int') AS record_id,
                        record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') AS SystemIdle,
                        record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int') AS SQLProcessUtilization,
                        timestamp,
                        DATEADD(ss, (-1 * ($currentTimestamp - [timestamp]))/1000, GETDATE()) AS EventTime
                    FROM RingBufferSchedulerMonitor
                )
                Select
                    SERVERPROPERTY('ServerName') as ServerName,
                    record_id,
                    EventTime,
                    SQLProcessUtilization,
                    SystemIdle,
                    100 - SystemIdle - SQLProcessUtilization AS OtherProcessUtilization
                From RingBufferSchedulerMonitorValues
                WHERE EventTime> DATEADD(MINUTE, -$CollectionMinutes, GETDATE()) ;"

            Write-Message -Level Verbose -Message "Executing Sql Staement: $sql"
            foreach ($row in $server.Query($sql)) {
                [PSCustomObject]@{
                    ComputerName            = $server.NetName
                    InstanceName            = $server.ServiceName
                    SqlInstance             = $server.DomainInstanceName
                    RecordId                = $row.record_id
                    EventTime               = $row.EventTime
                    SQLProcessUtilization   = $row.SQLProcessUtilization
                    OtherProcessUtilization = $row.OtherProcessUtilization
                    SystemIdle              = $row.SystemIdle
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaCpuUsage.ps1
function Get-DbaCpuUsage {
    <#
    .SYNOPSIS
        Provides detailed CPU usage information about a SQL Server's process

    .DESCRIPTION
        "If there are a lot of processes running on your instance and the CPU is very high,
        then it's hard to find the exact process eating up your CPU using just the SQL Server
        tools. One way to correlate the data between what is running within SQL Server and at
        the Windows level is to use SPID and KPID values to get the exact process."

        This command automates that process.

        References: https://www.mssqltips.com/sqlservertip/2454/how-to-find-out-how-much-cpu-a-sql-server-process-is-really-using/

        Note: This command returns results from all SQL instances on the destination server but the process
        column is specific to -SqlInstance passed.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Allows you to login to the SQL instance using alternative credentials.

    .PARAMETER Credential
        Allows you to login to the Windows Server using alternative credentials.

    .PARAMETER Threshold
        CPU threshold.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: CPU
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaCpuUsage

    .EXAMPLE
        PS C:\> Get-DbaCpuUsage -SqlInstance sql2017

        Logs into the SQL Server instance "sql2017" and also the Computer itself (via WMI) to gather information

    .EXAMPLE
        PS C:\> $usage = Get-DbaCpuUsage -SqlInstance sql2017
        PS C:\> $usage.Process

        Explores the processes (from Get-DbaProcess) associated with the usage results

    .EXAMPLE
        PS C:\> Get-DbaCpuUsage -SqlInstance sql2017 -SqlCredential sqladmin -Credential ad\sqldba

        Logs into the SQL instance using the SQL Login 'sqladmin' and then Windows instance as 'ad\sqldba'

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [PSCredential]$Credential,
        [int]$Threshold = 0,
        [switch]$EnableException
    )
    begin {
        # This can likely be enumerated but I don't know hows
        $threadstates = [pscustomobject]@{
            0 = 'Initialized. It is recognized by the microkernel.'
            1 = 'Ready. It is prepared to run on the next available processor.'
            2 = 'Running. It is executing.'
            3 = 'Standby. It is about to run. Only one thread may be in this state at a time.'
            4 = 'Terminated. It is finished executing.'
            5 = 'Waiting. It is not ready for the processor. When ready, it will be rescheduled.'
            6 = 'Transition. The thread is waiting for resources other than the processor.'
            7 = 'Unknown. The thread state is unknown.'
        }

        $threadwaitreasons = [pscustomobject]@{
            0  = 'Executive'
            1  = 'FreePage'
            2  = 'PageIn'
            3  = 'PoolAllocation'
            4  = 'ExecutionDelay'
            5  = 'FreePage'
            6  = 'PageIn'
            7  = 'Executive'
            8  = 'FreePage'
            9  = 'PageIn'
            10 = 'PoolAllocation'
            11 = 'ExecutionDelay'
            12 = 'FreePage'
            13 = 'PageIn'
            14 = 'EventPairHigh'
            15 = 'EventPairLow'
            16 = 'LPCReceive'
            17 = 'LPCReply'
            18 = 'VirtualMemory'
            19 = 'PageOut'
            20 = 'Unknown'
        }
    }
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $processes = Get-DbaProcess -SqlInstance $server
            $threads = Get-DbaCmObject -ComputerName $instance.ComputerName -ClassName Win32_PerfFormattedData_PerfProc_Thread -Credential $Credential | Where-Object { $_.Name -like 'sql*' -and $_.PercentProcessorTime -ge $Threshold }

            if ($server.VersionMajor -eq 8) {
                $spidcollection = $server.Query("select spid, kpid from sysprocesses")
            } else {
                $spidcollection = $server.Query("select t.os_thread_id as kpid, s.session_id as spid
            from sys.dm_exec_sessions s
            join sys.dm_exec_requests er on s.session_id = er.session_id
            join sys.dm_os_workers w on er.task_address = w.task_address
            join sys.dm_os_threads t on w.thread_address = t.thread_address")
            }

            foreach ($thread in $threads) {
                $spid = ($spidcollection | Where-Object kpid -eq $thread.IDThread).spid
                $process = $processes | Where-Object spid -eq $spid
                $threadwaitreason = $thread.ThreadWaitReason
                $threadstate = $thread.ThreadState
                $ThreadStateValue = $threadstates.$threadstate
                $ThreadWaitReasonValue = $threadwaitreasons.$threadwaitreason

                Add-Member -Force -InputObject $thread -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                Add-Member -Force -InputObject $thread -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                Add-Member -Force -InputObject $thread -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                Add-Member -Force -InputObject $thread -MemberType NoteProperty -Name Processes -Value ($processes | Where-Object HostProcessID -eq $thread.IDProcess)
                Add-Member -Force -InputObject $thread -MemberType NoteProperty -Name ThreadStateValue -Value $ThreadStateValue
                Add-Member -Force -InputObject $thread -MemberType NoteProperty -Name ThreadWaitReasonValue -Value $ThreadWaitReasonValue
                Add-Member -Force -InputObject $thread -MemberType NoteProperty -Name Process -Value $process
                Add-Member -Force -InputObject $thread -MemberType NoteProperty -Name Query -Value $process.LastQuery
                Add-Member -Force -InputObject $thread -MemberType NoteProperty -Name Spid -Value $spid

                Select-DefaultView -InputObject $thread -Property ComputerName, InstanceName, SqlInstance, Name, ContextSwitchesPersec, ElapsedTime, IDProcess, Spid, PercentPrivilegedTime, PercentProcessorTime, PercentUserTime, PriorityBase, PriorityCurrent, StartAddress, ThreadStateValue, ThreadWaitReasonValue, Process, Query
            }
        }
    }
}
tools\dbatools\functions\Get-DbaCredential.ps1
#ValidationTags#Messaging,FlowControl,CodeStyle#
function Get-DbaCredential {
    <#
    .SYNOPSIS
        Gets SQL Credential information for each instance(s) of SQL Server.

    .DESCRIPTION
        The Get-DbaCredential command gets SQL Credential information for each instance(s) of SQL Server.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function
        to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Name
        Only include specific names
        Note: if spaces exist in the credential name, you will have to type "" or '' around it.

    .PARAMETER ExcludeName
        Excluded credential names

    .PARAMETER Identity
        Only include specific identities
        Note: if spaces exist in the credential identity, you will have to type "" or '' around it.

    .PARAMETER ExcludeIdentity
        Excluded identities

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Credential
        Author: Garry Bargsley (@gbargsley), http://blog.garrybargsley.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaCredential

    .EXAMPLE
        PS C:\> Get-DbaCredential -SqlInstance localhost

        Returns all SQL Credentials on the local default SQL Server instance

    .EXAMPLE
        PS C:\> Get-DbaCredential -SqlInstance localhost, sql2016 -Name 'PowerShell Proxy'

        Returns the SQL Credentials named 'PowerShell Proxy' for the local and sql2016 SQL Server instances

    .EXAMPLE
        PS C:\> Get-DbaCredential -SqlInstance localhost, sql2016 -Identity ad\powershell

        Returns the SQL Credentials for the account 'ad\powershell' on the local and sql2016 SQL Server instances

    #>
    [CmdletBinding()]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Name,
        [string[]]$ExcludeName,
        [Alias('CredentialIdentity')]
        [string[]]$Identity,
        [Alias('ExcludeCredentialIdentity')]
        [string[]]$ExcludeIdentity,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $credential = $server.Credentials

            if ($Name) {
                $credential = $credential | Where-Object { $Name -contains $_.Name }
            }

            if ($ExcludeName) {
                $credential = $credential | Where-Object { $ExcludeName -notcontains $_.Name }
            }

            if ($Identity) {
                $credential = $credential | Where-Object { $Identity -contains $_.Identity }
            }

            if ($ExcludeIdentity) {
                $credential = $credential | Where-Object { $ExcludeIdentity -notcontains $_.Identity }
            }

            foreach ($currentcredential in $credential) {
                Add-Member -Force -InputObject $currentcredential -MemberType NoteProperty -Name ComputerName -value $currentcredential.Parent.ComputerName
                Add-Member -Force -InputObject $currentcredential -MemberType NoteProperty -Name InstanceName -value $currentcredential.Parent.ServiceName
                Add-Member -Force -InputObject $currentcredential -MemberType NoteProperty -Name SqlInstance -value $currentcredential.Parent.DomainInstanceName

                Select-DefaultView -InputObject $currentcredential -Property ComputerName, InstanceName, SqlInstance, ID, Name, Identity, MappedClassType, ProviderName
            }
        }
    }
}
tools\dbatools\functions\Get-DbaCustomError.ps1
#ValidationTags#Messaging,FlowControl,CodeStyle#
function Get-DbaCustomError {
    <#
    .SYNOPSIS
        Gets SQL Custom Error Message information for each instance(s) of SQL Server.

    .DESCRIPTION
        The Get-DbaCustomError command gets SQL Custom Error Message information for each instance(s) of SQL Server.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function
        to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Error, CustomError
        Author: Garry Bargsley (@gbargsley), http://blog.garrybargsley.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaCustomError

    .EXAMPLE
        PS C:\> Get-DbaCustomError -SqlInstance localhost

        Returns all Custom Error Message(s) on the local default SQL Server instance

    .EXAMPLE
        PS C:\> Get-DbaCustomError -SqlInstance localhost, sql2016

        Returns all Custom Error Message(s) for the local and sql2016 SQL Server instances

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            foreach ($customError in $server.UserDefinedMessages) {
                Add-Member -Force -InputObject $customError -MemberType NoteProperty -Name ComputerName -value $customError.Parent.ComputerName
                Add-Member -Force -InputObject $customError -MemberType NoteProperty -Name InstanceName -value $customError.Parent.ServiceName
                Add-Member -Force -InputObject $customError -MemberType NoteProperty -Name SqlInstance -value $customError.Parent.DomainInstanceName

                Select-DefaultView -InputObject $customError -Property ComputerName, InstanceName, SqlInstance, ID, Text, LanguageID, Language
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDatabase.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Get-DbaDatabase {
    <#
    .SYNOPSIS
        Gets SQL Database information for each database that is present on the target instance(s) of SQL Server.

    .DESCRIPTION
        The Get-DbaDatabase command gets SQL database information for each database that is present on the target instance(s) of
        SQL Server. If the name of the database is provided, the command will return only the specific database information.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Defaults to localhost.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies one or more database(s) to process. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies one or more database(s) to exclude from processing.

    .PARAMETER ExcludeUser
        If this switch is enabled, only databases which are not User databases will be processed.

        This parameter cannot be used with -ExcludeSystem.

    .PARAMETER ExcludeSystem
        If this switch is enabled, only databases which are not System databases will be processed.

        This parameter cannot be used with -ExcludeUser.

    .PARAMETER Status
        Specifies one or more database statuses to filter on. Only databases in the status(es) listed will be returned. Valid options for this parameter are 'Emergency', 'Normal', 'Offline', 'Recovering', 'Restoring', 'Standby', and 'Suspect'.

    .PARAMETER Access
        Filters databases returned by their access type. Valid options for this parameter are 'ReadOnly' and 'ReadWrite'. If omitted, no filtering is performed.

    .PARAMETER Owner
        Specifies one or more database owners. Only databases owned by the listed owner(s) will be returned.

    .PARAMETER Encrypted
        If this switch is enabled, only databases which have Transparent Data Encryption (TDE) enabled will be returned.

    .PARAMETER RecoveryModel
        Filters databases returned by their recovery model. Valid options for this parameter are 'Full', 'Simple', and 'BulkLogged'.

    .PARAMETER NoFullBackup
        If this switch is enabled, only databases without a full backup recorded by SQL Server will be returned. This will also indicate which of these databases only have CopyOnly full backups.

    .PARAMETER NoFullBackupSince
        Only databases which haven't had a full backup since the specified DateTime will be returned.

    .PARAMETER NoLogBackup
        If this switch is enabled, only databases without a log backup recorded by SQL Server will be returned. This will also indicate which of these databases only have CopyOnly log backups.

    .PARAMETER NoLogBackupSince
        Only databases which haven't had a log backup since the specified DateTime will be returned.

    .PARAMETER IncludeLastUsed
        If this switch is enabled, the last used read & write times for each database will be returned. This data is retrieved from sys.dm_db_index_usage_stats which is reset when SQL Server is restarted.

    .PARAMETER OnlyAccessible
        If this switch is enabled, only accessible databases are returned (huge speedup in SMO enumeration)

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database
        Author: Garry Bargsley (@gbargsley), http://blog.garrybargsley.com | Klaas Vandenberghe (@PowerDbaKlaas) | Simone Bizzotto ( @niphlod )

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDatabase

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance localhost

        Returns all databases on the local default SQL Server instance.

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance localhost -ExcludeUser

        Returns only the system databases on the local default SQL Server instance.

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance localhost -ExcludeSystem

        Returns only the user databases on the local default SQL Server instance.

    .EXAMPLE
        PS C:\> 'localhost','sql2016' | Get-DbaDatabase

        Returns databases on multiple instances piped into the function.

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance SQL1\SQLExpress -RecoveryModel full,Simple

        Returns only the user databases in Full or Simple recovery model from SQL Server instance SQL1\SQLExpress.

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance SQL1\SQLExpress -Status Normal

        Returns only the user databases with status 'normal' from SQL Server instance SQL1\SQLExpress.

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance SQL1\SQLExpress -IncludeLastUsed

        Returns the databases from SQL Server instance SQL1\SQLExpress and includes the last used information
        from the sys.dm_db_index_usage_stats DMV.

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance SQL1\SQLExpress,SQL2 -ExcludeDatabase model,master

        Returns all databases except master and model from SQL Server instances SQL1\SQLExpress and SQL2.

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance SQL1\SQLExpress,SQL2 -Encrypted

        Returns only databases using TDE from SQL Server instances SQL1\SQLExpress and SQL2.

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance SQL1\SQLExpress,SQL2 -Access ReadOnly

        Returns only read only databases from SQL Server instances SQL1\SQLExpress and SQL2.

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance SQL2,SQL3 -Database OneDB,OtherDB

        Returns databases 'OneDb' and 'OtherDB' from SQL Server instances SQL2 and SQL3 if databases by those names exist on those instances.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification = "Internal functions are ignored")]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [Alias("SystemDbOnly", "NoUserDb", "ExcludeAllUserDb")]
        [switch]$ExcludeUser,
        [Alias("UserDbOnly", "NoSystemDb", "ExcludeAllSystemDb")]
        [switch]$ExcludeSystem,
        [string[]]$Owner,
        [switch]$Encrypted,
        [ValidateSet('EmergencyMode', 'Normal', 'Offline', 'Recovering', 'Restoring', 'Standby', 'Suspect')]
        [string[]]$Status = @('EmergencyMode', 'Normal', 'Offline', 'Recovering', 'Restoring', 'Standby', 'Suspect'),
        [ValidateSet('ReadOnly', 'ReadWrite')]
        [string]$Access,
        [ValidateSet('Full', 'Simple', 'BulkLogged')]
        [string[]]$RecoveryModel = @('Full', 'Simple', 'BulkLogged'),
        [switch]$NoFullBackup,
        [datetime]$NoFullBackupSince,
        [switch]$NoLogBackup,
        [datetime]$NoLogBackupSince,
        [Alias('Silent')]
        [switch]$EnableException,
        [switch]$IncludeLastUsed,
        [switch]$OnlyAccessible
    )

    begin {

        if ($ExcludeUser -and $ExcludeSystem) {
            Stop-Function -Message "You cannot specify both ExcludeUser and ExcludeSystem." -Continue -EnableException $EnableException
        }

    }
    process {
        if (Test-FunctionInterrupt) { return }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if (!$IncludeLastUsed) {
                $dblastused = $null
            } else {
                ## Get last used information from the DMV
                $querylastused = "WITH agg AS
                (
                  SELECT
                       max(last_user_seek) last_user_seek,
                       max(last_user_scan) last_user_scan,
                       max(last_user_lookup) last_user_lookup,
                       max(last_user_update) last_user_update,
                       sd.name dbname
                   FROM
                       sys.dm_db_index_usage_stats, master..sysdatabases sd
                   WHERE
                     database_id = sd.dbid AND database_id > 4
                      group by sd.name
                )
                SELECT
                   dbname,
                   last_read = MAX(last_read),
                   last_write = MAX(last_write)
                FROM
                (
                   SELECT dbname, last_user_seek, NULL FROM agg
                   UNION ALL
                   SELECT dbname, last_user_scan, NULL FROM agg
                   UNION ALL
                   SELECT dbname, last_user_lookup, NULL FROM agg
                   UNION ALL
                   SELECT dbname, NULL, last_user_update FROM agg
                ) AS x (dbname, last_read, last_write)
                GROUP BY
                   dbname
                ORDER BY 1;"
                # put a function around this to enable Pester Testing and also to ease any future changes
                function Invoke-QueryDBlastUsed {
                    $server.Query($querylastused)
                }
                $dblastused = Invoke-QueryDBlastUsed
            }

            if ($ExcludeUser) {
                $DBType = @($true)
            } elseif ($ExcludeSystem) {
                $DBType = @($false)
            } else {
                $DBType = @($false, $true)
            }

            $AccessibleFilter = switch ($OnlyAccessible) {
                $true { @($true) }
                default { @($true, $false) }
            }

            $Readonly = switch ($Access) {
                'Readonly' { @($true) }
                'ReadWrite' { @($false) }
                default { @($true, $false) }
            }
            $Encrypt = switch (Test-Bound $Encrypted) {
                $true { @($true) }
                default { @($true, $false, $null) }
            }
            function Invoke-QueryRawDatabases {
                try {
                    if ($server.VersionMajor -eq 8) {
                        $server.Query("SELECT *, SUSER_NAME(sid) AS [Owner] FROM master.dbo.sysdatabases")
                    } else {
                        $server.Query("SELECT *, SUSER_NAME(owner_sid) AS [Owner] FROM sys.databases")
                    }
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_
                }
            }
            $backed_info = Invoke-QueryRawDatabases
            $backed_info = $backed_info | Where-Object {
                ($_.name -in $Database -or !$Database) -and
                ($_.name -notin $ExcludeDatabase -or !$ExcludeDatabase) -and
                ($_.Owner -in $Owner -or !$Owner) -and
                ($_.state -ne 6 -or !$OnlyAccessible)
            }

            $inputObject = @()
            foreach ($dt in $backed_info) {
                $inputObject += $server.Databases | Where-Object Name -ceq $dt.name
            }
            $inputobject = $inputObject |
                Where-Object {
                ($_.Name -in $Database -or !$Database) -and
                ($_.Name -notin $ExcludeDatabase -or !$ExcludeDatabase) -and
                ($_.Owner -in $Owner -or !$Owner) -and
                $_.ReadOnly -in $Readonly -and
                $_.IsAccessible -in $AccessibleFilter -and
                $_.IsSystemObject -in $DBType -and
                ((Compare-Object @($_.Status.tostring().split(',').trim()) $Status -ExcludeDifferent -IncludeEqual).inputobject.count -ge 1 -or !$status) -and
                ($_.RecoveryModel -in $RecoveryModel -or !$_.RecoveryModel) -and
                $_.EncryptionEnabled -in $Encrypt
            }
            if ($NoFullBackup -or $NoFullBackupSince) {
                $dabs = (Get-DbaBackupHistory -SqlInstance $server -LastFull )
                if ($null -ne $NoFullBackupSince) {
                    $dabsWithinScope = ($dabs | Where-Object End -lt $NoFullBackupSince)

                    $inputobject = $inputobject | Where-Object { $_.Name -in $dabsWithinScope.Database -and $_.Name -ne 'tempdb' }
                } else {
                    $inputObject = $inputObject | Where-Object { $_.Name -notin $dabs.Database -and $_.Name -ne 'tempdb' }
                }

            }
            if ($NoLogBackup -or $NoLogBackupSince) {
                $dabs = (Get-DbaBackupHistory -SqlInstance $server -LastLog )
                if ($null -ne $NoLogBackupSince) {
                    $dabsWithinScope = ($dabs | Where-Object End -lt $NoLogBackupSince)
                    $inputobject = $inputobject |
                        Where-Object { $_.Name -in $dabsWithinScope.Database -and $_.Name -ne 'tempdb' -and $_.RecoveryModel -ne 'Simple' }
                } else {
                    $inputobject = $inputObject |
                        Where-Object { $_.Name -notin $dabs.Database -and $_.Name -ne 'tempdb' -and $_.RecoveryModel -ne 'Simple' }
                }
            }

            $defaults = 'ComputerName', 'InstanceName', 'SqlInstance', 'Name', 'Status', 'IsAccessible', 'RecoveryModel',
            'LogReuseWaitStatus', 'Size as SizeMB', 'CompatibilityLevel as Compatibility', 'Collation', 'Owner',
            'LastBackupDate as LastFullBackup', 'LastDifferentialBackupDate as LastDiffBackup',
            'LastLogBackupDate as LastLogBackup'

            if ($NoFullBackup -or $NoFullBackupSince -or $NoLogBackup -or $NoLogBackupSince) {
                $defaults += ('Notes')
            }
            if ($IncludeLastUsed) {
                # Add Last Used to the default view
                $defaults += ('LastRead as LastIndexRead', 'LastWrite as LastIndexWrite')
            }

            try {
                foreach ($db in $inputobject) {

                    $Notes = $null
                    if ($NoFullBackup -or $NoFullBackupSince) {
                        if (@($db.EnumBackupSets()).count -eq @($db.EnumBackupSets() | Where-Object { $_.IsCopyOnly }).count -and (@($db.EnumBackupSets()).count -gt 0)) {
                            $Notes = "Only CopyOnly backups"
                        }
                    }

                    $lastusedinfo = $dblastused | Where-Object { $_.dbname -eq $db.name }
                    Add-Member -Force -InputObject $db -MemberType NoteProperty BackupStatus -value $Notes
                    Add-Member -Force -InputObject $db -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                    Add-Member -Force -InputObject $db -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                    Add-Member -Force -InputObject $db -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                    Add-Member -Force -InputObject $db -MemberType NoteProperty -Name LastRead -value $lastusedinfo.last_read
                    Add-Member -Force -InputObject $db -MemberType NoteProperty -Name LastWrite -value $lastusedinfo.last_write
                    Select-DefaultView -InputObject $db -Property $defaults
                    #try { $server.Databases.Refresh() } catch {}
                }
            } catch {
                Stop-Function -ErrorRecord $_ -Target $instance -Message "Failure. Collection may have been modified. If so, please use parens (Get-DbaDatabase ....) | when working with commands that modify the collection such as Remove-DbaDatabase." -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbAssembly.ps1
#ValidationTags#Messaging,FlowControl,CodeStyle#
function Get-DbaDbAssembly {
    <#
    .SYNOPSIS
        Gets SQL Database Assembly information for each instance(s) of SQL Server.

    .DESCRIPTION
        The Get-DbaDbAssembly command gets SQL Database Assembly information for each instance(s) of SQL Server.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function
        to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Assembly, Database
        Author: Garry Bargsley (@gbargsley), http://blog.garrybargsley.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbAssembly

    .EXAMPLE
        PS C:\> Get-DbaDbAssembly -SqlInstance localhost

        Returns all Database Assembly on the local default SQL Server instance

    .EXAMPLE
        PS C:\> Get-DbaDbAssembly -SqlInstance localhost, sql2016

        Returns all Database Assembly for the local and sql2016 SQL Server instances

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            foreach ($database in ($server.Databases | Where-Object IsAccessible)) {
                try {
                    foreach ($assembly in $database.assemblies) {

                        Add-Member -Force -InputObject $assembly -MemberType NoteProperty -Name ComputerName -value $assembly.Parent.Parent.ComputerName
                        Add-Member -Force -InputObject $assembly -MemberType NoteProperty -Name InstanceName -value $assembly.Parent.Parent.ServiceName
                        Add-Member -Force -InputObject $assembly -MemberType NoteProperty -Name SqlInstance -value $assembly.Parent.Parent.DomainInstanceName

                        Select-DefaultView -InputObject $assembly -Property ComputerName, InstanceName, SqlInstance, ID, Name, Owner, 'AssemblySecurityLevel as SecurityLevel', CreateDate, IsSystemObject, Version
                    }
                } catch {
                    Stop-Function -Message "Issue pulling assembly information" -Target $assembly -ErrorRecord $_ -Continue
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaDatabaseAssembly
    }
}
tools\dbatools\functions\Get-DbaDbccHelp.ps1
function Get-DbaDbccHelp {
    <#
    .SYNOPSIS
        Execution of Database Console Command DBCC HELP

    .DESCRIPTION
        Returns the results of DBCC HELP

        Read more:
            - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-help-transact-sql

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Statement
        Is the name of the DBCC command for which to receive syntax information.
        Provide only the part of the DBCC command that follows DBCC,
            for example, CHECKDB instead of DBCC CHECKDB.

    .PARAMETER IncludeUndocumented
        Allows getting help for undocumented DBCC commands. Requires Traceflag 2588
        This only works for SQL Server 2005 or Higher

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DBCC
        Author: Patrick Flynn (@sqllensman)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbccUserOptions

    .EXAMPLE
        PS C:\> Get-DbaDbccHelp -SqlInstance SQLInstance -Statement FREESYSTEMCACHE -Verbose | Format-List

        Runs the command DBCC HELP(FREESYSTEMCACHE) WITH NO_INFOMSGS against the SQL Server instance SQLInstance

    .EXAMPLE
        PS C:\> Get-DbaDbccHelp -SqlInstance LensmanSB -Statement WritePage -IncludeUndocumented | Format-List

        Sets TraeFlag 2588 on for session and then runs the command DBCC HELP(WritePage) WITH NO_INFOMSGS against the SQL Server instance SQLInstance

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$Statement,
        [switch]$IncludeUndocumented,
        [switch]$EnableException
    )
    begin {
        if (Test-Bound -Not -ParameterName Statement) {
            Stop-Function -Message "You must specify a value for Statement"
            return
        }
        $stringBuilder = New-Object System.Text.StringBuilder

        if (Test-Bound -ParameterName IncludeUndocumented) {
            $null = $stringBuilder.Append("DBCC TRACEON (2588) WITH NO_INFOMSGS;")
        }

        Write-Message -Message "Get Help Information for $Statement" -Level Verbose
        $null = $stringBuilder.Append("DBCC HELP($Statement) WITH NO_INFOMSGS;")
    }
    process {

        foreach ($instance in $SqlInstance) {
            Write-Message -Message "Attempting Connection to $instance" -Level Verbose
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            try {
                $query = $StringBuilder.ToString()
                Write-Message -Message "Query to run: $query" -Level Verbose
                $results = $server | Invoke-DbaQuery  -Query $query -MessagesToOutput

            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Target $server -Continue
            }

            [PSCustomObject]@{
                Operation = $Statement
                Cmd       = "DBCC HELP($Statement)"
                Output    = $results
            }

        }
    }
}
tools\dbatools\functions\Get-DbaDbccMemoryStatus.ps1
function Get-DbaDbccMemoryStatus {
    <#
    .SYNOPSIS
        Gets the results of DBCC MEMORYSTATUS.  Works on SQL Server 2000-2019.

    .DESCRIPTION
        This command is used to run the DBCC MEMORYSTATUS comand and collect results in a single usable recordset

        Reference:
            - https://blogs.msdn.microsoft.com/timchapman/2012/08/16/how-to-parse-dbcc-memorystatus-via-powershell/
            - https://support.microsoft.com/en-us/help/907877/how-to-use-the-dbcc-memorystatus-command-to-monitor-memory-usage-on-sq

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DBCC, Memory
        Author: Patrick Flynn (@sqllensman)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaMemoryStatus

    .EXAMPLE
        PS C:\> Get-DbaDbccMemoryStatus -SqlInstance sqlcluster, sqlserver2012

        Get output of DBCC MEMORYSTATUS for instances "sqlcluster" and "sqlserver2012". Returns results in a single recordset.

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sqlcluster | Get-DbaDbccMemoryStatus

        Get output of DBCC MEMORYSTATUS for all servers in Server Central Management Server

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )
    begin {
        $query = 'DBCC MEMORYSTATUS'
    }
    process {
        foreach ($instance in $SqlInstance) {
            Write-Message -Message "Attempting Connection to $instance" -Level Verbose
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            Write-Message -Level Verbose -Message "Collecting $query data from server: $instance"
            try {
                $sqlconnection = New-Object System.Data.SqlClient.SqlConnection
                $sqlconnection.ConnectionString = $server.ConnectionContext.ConnectionString
                $sqlconnection.Open()

                $datatable = New-Object system.Data.DataSet
                $dataadapter = New-Object system.Data.SqlClient.SqlDataAdapter($query, $sqlconnection)
                $dataadapter.fill($datatable) | Out-Null

                $recordset = 0
                $rowId = 0
                $recordsetId = 0

                foreach ($dataset in $datatable.Tables) {
                    $dataSection = $dataset.Columns[0].ColumnName
                    $dataType = $dataset.Columns[1].ColumnName
                    $recordset = $recordset + 1
                    foreach ($row in $dataset.Rows) {
                        $rowId = $rowId + 1
                        $recordsetId = $recordsetId + 1
                        [PSCustomObject]@{
                            ComputerName = $server.ComputerName
                            InstanceName = $server.ServiceName
                            SqlInstance  = $server.DomainInstanceName
                            RecordSet    = $RecordSet
                            RowId        = $RowId
                            RecordSetId  = $RecordSetId
                            Type         = $dataSection
                            Name         = $Row[0]
                            Value        = $Row[1]
                            ValueType    = $dataType
                        }
                    }
                    $recordsetId = 0
                }
            } catch {
                Stop-Function -Message "Failure Executing $query" -ErrorRecord $_ -Target $instance -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbccProcCache.ps1
function Get-DbaDbccProcCache {
    <#
    .SYNOPSIS
        Execution of Database Console Command DBCC PROCCACHE

    .DESCRIPTION
        Returns the results of DBCC PROCCACHE

        Read more:
            - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-proccache-transact-sql

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DBCC
        Author: Patrick Flynn (@sqllensman)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbccProcCache

    .EXAMPLE
        PS C:\> Get-DbaDbccProcCache -SqlInstance Server1

        Get results of DBCC PROCCACHE for Instance Server1

    .EXAMPLE
        PS C:\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbccProcCache

        Get results of DBCC PROCCACHE for Instances Sql1 and Sql2/sqlexpress

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> Get-DbaDbccProcCache -SqlInstance Server1 -SqlCredential $cred

        Connects using sqladmin credential and gets results of DBCC PROCCACHE for Instance Server1

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )
    begin {

        $stringBuilder = New-Object System.Text.StringBuilder
        $null = $stringBuilder.Append("DBCC PROCCACHE WITH NO_INFOMSGS")
    }
    process {
        $query = $StringBuilder.ToString()
        foreach ($instance in $SqlInstance) {
            Write-Message -Message "Attempting Connection to $instance" -Level Verbose
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            try {
                Write-Message -Message "Query to run: $query" -Level Verbose
                $results = $server.Query($query)
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Target $server -Continue
            }
            foreach ($row in $results) {
                [PSCustomObject]@{
                    ComputerName = $server.ComputerName
                    InstanceName = $server.ServiceName
                    SqlInstance  = $server.DomainInstanceName
                    Count        = $row[0]
                    Used         = $row[1]
                    Active       = $row[2]
                    CacheSize    = $row[3]
                    CacheUsed    = $row[4]
                    CacheActive  = $row[5]
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbccSessionBuffer.ps1
function Get-DbaDbccSessionBuffer {
    <#
    .SYNOPSIS
        Gets result of Database Console Command DBCC INPUTBUFFER  or DBCC OUTPUTBUFFER

    .DESCRIPTION
        Returns the results of DBCC INPUTBUFFER or DBCC OUTPUTBUFFER for input sessions

        Read more:
            - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-inputbuffer-transact-sql
            - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-outputbuffer-transact-sql

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Operation
        DBCC Operation to execute - either InputBuffer or OutputBuffer

    .PARAMETER SessionId
        The Session ID(s) to use to get current input or output buffer.

    .PARAMETER RequestId
        Is the exact request (batch) to search for within the current session
        The following query returns request_id:

        SELECT request_id
        FROM sys.dm_exec_requests
        WHERE session_id = @@spid;

    .PARAMETER All
        If this switch is enabled, results for all User Sessions will be retreived
        This overides any values for SessionId or RequestId

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DBCC
        Author: Patrick Flynn (@sqllensman)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbccSessionBuffer

    .EXAMPLE
        PS C:\> Get-DbaDbccSessionBuffer -SqlInstance Server1 -Operation InputBuffer -SessionId 51

        Get results of DBCC INPUTBUFFER(51) for Instance Server1

    .EXAMPLE
        PS C:\> Get-DbaDbccSessionBuffer -SqlInstance Server1 -Operation OutputBuffer -SessionId 51, 52

        Get results of DBCC OUTPUTBUFFER for SessionId's 51 and 52 for Instance Server1

    .EXAMPLE
        PS C:\> Get-DbaDbccSessionBuffer -SqlInstance Server1 -Operation InputBuffer -SessionId 51 -RequestId 0

        Get results of DBCC INPUTBUFFER(51,0) for Instance Server1

    .EXAMPLE
        PS C:\> Get-DbaDbccSessionBuffer -SqlInstance Server1 -Operation OutputBuffer -SessionId 51 -RequestId 0

        Get results of DBCC OUTPUTBUFFER(51,0) for Instance Server1

    .EXAMPLE
        PS C:\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbccSessionBuffer -Operation InputBuffer -All

        Get results of DBCC INPUTBUFFER for all user sessions for the instances Sql1 and Sql2/sqlexpress

    .EXAMPLE
        PS C:\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbccSessionBuffer -Operation OutputBuffer -All

        Get results of DBCC OUTPUTBUFFER for all user sessions for the instances Sql1 and Sql2/sqlexpress

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> Get-DbaDbccSessionBuffer -SqlInstance Server1 -SqlCredential $cred -Operation InputBuffer -SessionId 51 -RequestId 0

        Connects using sqladmin credential and gets results of DBCC INPUTBUFFER(51,0) for Instance Server1

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> Get-DbaDbccSessionBuffer -SqlInstance Server1 -SqlCredential $cred -Operation OutputBuffer -SessionId 51 -RequestId 0

        Connects using sqladmin credential and gets results of DBCC OUTPUTBUFFER(51,0) for Instance Server1

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [ValidateSet('InputBuffer', 'OutputBuffer')]
        [string]$Operation = "InputBuffer",
        [int[]]$SessionId,
        [int]$RequestId,
        [switch]$All,
        [switch]$EnableException
    )
    begin {
        if (Test-Bound -Not -ParameterName All) {
            if (Test-Bound -Not -ParameterName SessionId) {
                Stop-Function -Message "You must specify either a SessionId or use the -All switch."
                return
            }
        }

        if (Test-Bound -ParameterName Operation) {
            $Operation = $Operation.ToUpper()
        }
        $stringBuilder = New-Object System.Text.StringBuilder
        $null = $stringBuilder.Append("DBCC $Operation(#Operation#) WITH NO_INFOMSGS")

    }
    process {

        foreach ($instance in $SqlInstance) {
            Write-Message -Message "Attempting Connection to $instance" -Level Verbose
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if (Test-Bound -Not -ParameterName All) {
                foreach ($session_id in $SessionId) {
                    $query = $StringBuilder.ToString()

                    if (Test-Bound -Not -ParameterName RequestId) {
                        Write-Message -Message "Query to run: $query" -Level Verbose
                        $query = $query.Replace('#Operation#', $session_id)
                    } else {
                        Write-Message -Message "Query to run: $query" -Level Verbose
                        $query = $query.Replace('#Operation#', "$($session_id), $($RequestId)")
                    }

                    try {
                        Write-Message -Message "Query to run: $query" -Level Verbose
                        $results = $server.Query($query)
                    } catch {
                        Stop-Function -Message "Failure" -ErrorRecord $_ -Target $server -Continue
                    }
                    if ($Operation -eq 'INPUTBUFFER') {
                        foreach ($row in $results) {
                            [PSCustomObject]@{
                                ComputerName = $server.ComputerName
                                InstanceName = $server.ServiceName
                                SqlInstance  = $server.DomainInstanceName
                                SessionId    = $session_id
                                EventType    = $row[0]
                                Parameters   = $row[1]
                                EventInfo    = $row[2]
                            }
                        }
                    } else {
                        Write-Message -Message "Output Buffer" -Level Verbose
                        $hexStringBuilder = New-Object System.Text.StringBuilder
                        $asciiStringBuilder = New-Object System.Text.StringBuilder

                        foreach ($row in $results) {
                            $str = $row[0].ToString()
                            $null = $hexStringBuilder.Append($str.Substring(11, 48))
                            $null = $asciiStringBuilder.Append($str.Substring(61, 16))
                        }
                        [PSCustomObject]@{
                            ComputerName = $server.ComputerName
                            InstanceName = $server.ServiceName
                            SqlInstance  = $server.DomainInstanceName
                            SessionId    = $session_id
                            Buffer       = $asciiStringBuilder.ToString().Replace('.', '').TrimEnd()
                            HexBuffer    = $hexStringBuilder.ToString().Replace(' ', '')
                        } | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, SessionId, Buffer
                    }
                }
            } else {
                $sessionQuery = 'Select session_id FROM sys.dm_exec_connections'
                $sessionList = $server.Query($sessionQuery )
                foreach ($session in $sessionList) {
                    $query = $StringBuilder.ToString()
                    $query = $query.Replace('#Operation#', $session.session_id)
                    try {
                        Write-Message -Message "Query to run: $query" -Level Verbose
                        $results = $server.Query($query)
                    } catch {
                        Stop-Function -Message "Failure" -ErrorRecord $_ -Target $server -Continue
                    }
                    if ($Operation -eq 'INPUTBUFFER') {
                        foreach ($row in $results) {
                            [PSCustomObject]@{
                                ComputerName = $server.ComputerName
                                InstanceName = $server.ServiceName
                                SqlInstance  = $server.DomainInstanceName
                                SessionId    = $session.session_id
                                EventType    = $row[0]
                                Parameters   = $row[1]
                                EventInfo    = $row[2]
                            }
                        }
                    } else {
                        $hexStringBuilder = New-Object System.Text.StringBuilder
                        $asciiStringBuilder = New-Object System.Text.StringBuilder

                        foreach ($row in $results) {
                            $str = $row[0].ToString()
                            $null = $hexStringBuilder.Append($str.Substring(11, 48))
                            $null = $asciiStringBuilder.Append($str.Substring(61, 16))
                        }
                        [PSCustomObject]@{
                            ComputerName = $server.ComputerName
                            InstanceName = $server.ServiceName
                            SqlInstance  = $server.DomainInstanceName
                            SessionId    = $session.session_id
                            Buffer       = $asciiStringBuilder.ToString().Replace('.', '').TrimEnd()
                            HexBuffer    = $hexStringBuilder.ToString().Replace(' ', '')
                        } | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, SessionId, Buffer
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbccStatistic.ps1
function Get-DbaDbccStatistic {
    <#
    .SYNOPSIS
        Execution of Database Console Command DBCC SHOW_STATISTICS

    .DESCRIPTION
        Executes the command DBCC SHOW_STATISTICS against defined objects and returns results

        Reclaims space from dropped variable-length columns in tables or indexed views

        Read more:
            - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-cleantable-transact-sql

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER Object
        The table or indexed view for which to display statistics information.
        Any two part object name should be formatted as 'Schema.ObjectName'

    .PARAMETER Target
        Name of the index, statistics, or column for which to display statistics information.
        Target can be enclosed in brackets, single quotes, double quotes, or no quotes

    .PARAMETER Option
        Used to limit the result sets returned by the statement to the specified option.
        Options are 'StatHeader', 'DensityVector', 'Histogram', 'StatsStream'
        Default of StatHeader

    .PARAMETER NoInformationalMessages
        Suppresses all informational messages.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DBCC, Statistics
        Author: Patrick Flynn (@sqllensman)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbccStatistic

    .EXAMPLE
        PS C:\> Get-DbaDbccStatistic -SqlInstance SQLServer2017

        Will run the statement SHOW_STATISTICS WITH STAT_HEADER against all Statistics on all User Tables or views for every accessible database on instance SQLServer2017. Connects using Windows Authentication.

    .EXAMPLE
        PS C:\> Get-DbaDbccStatistic -SqlInstance SQLServer2017 -Database MyDb -Option DensityVector

        Will run the statement SHOW_STATISTICS WITH DENSITY_VECTOR against all Statistics on all User Tables or views for database MyDb on instance SQLServer2017. Connects using Windows Authentication.

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> Get-DbaDbccStatistic -SqlInstance SQLServer2017 -SqlCredential $cred -Database MyDb -Object UserTable -Option Histogram

        Will run the statement SHOW_STATISTICS WITH HISTOGRAM against all Statistics on table UserTable for database MyDb on instance SQLServer2017. Connects using sqladmin credential.

    .EXAMPLE
        PS C:\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbccStatistic -SqlInstance SQLServer2017 -Database MyDb -Object 'dbo.UserTable' -Target MyStatistic -Option StatsStream

        Runs the statement SHOW_STATISTICS('dbo.UserTable', 'MyStatistic') WITH STATS_STREAM against database MyDb on instances Sql1 and Sql2/sqlexpress. Connects using Windows Authentication.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [string]$Object,
        [string]$Target,
        [ValidateSet('StatHeader', 'DensityVector', 'Histogram', 'StatsStream')]
        [string]$Option = "StatHeader",
        [switch]$NoInformationalMessages,
        [switch]$EnableException
    )
    begin {
        $stringBuilder = New-Object System.Text.StringBuilder
        $null = $stringBuilder.Append("DBCC SHOW_STATISTICS(#options#) WITH NO_INFOMSGS" )
        if ($Option -eq 'StatHeader') {
            $null = $stringBuilder.Append(", STAT_HEADER")
        } elseif ($Option -eq 'DensityVector') {
            $null = $stringBuilder.Append(", DENSITY_VECTOR")
        } elseif ($Option -eq 'Histogram') {
            $null = $stringBuilder.Append(", HISTOGRAM")
        } elseif ($Option -eq 'StatsStream') {
            $null = $stringBuilder.Append(", STATS_STREAM")
        }

        $statList =
        "Select Object, Target, name FROM
        (
            Select Schema_Name(o.SCHEMA_ID) + '.' + o.name as Object, st.name as Target, o.name
            FROM sys.stats st
            INNER JOIN sys.objects o
                on o.object_id = st.object_id
            WHERE o.type in ('U', 'V')
        ) a
        "
    }
    process {
        foreach ($instance in $SqlInstance) {
            Write-Message -Message "Attempting Connection to $instance" -Level Verbose
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($server.VersionMajor -eq 8) {
                if ((Test-Bound -Not -ParameterName Object) -or (Test-Bound -Not -ParameterName Target)) {
                    Write-Message -Level Warning -Message "You must specify an Object and a Target for SQL Server 2000"
                    continue
                }
            }

            $dbs = $server.Databases

            if ($Database) {
                $dbs = $dbs | Where-Object Name -In $Database
            }

            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Processing $db on $instance"
                $queryList = @()
                if ($db.IsAccessible -eq $false) {
                    Stop-Function -Message "The database $db is not accessible. Skipping." -Continue
                }

                if ((Test-Bound -ParameterName Object) -and (Test-Bound -ParameterName Target)) {
                    $query = $StringBuilder.ToString()
                    $query = $query.Replace('#options#', "'$Object', '$Target'")

                    $queryList += New-Object -TypeName PSObject -Property @{Object = $Object;
                        Target                                                     = $Target;
                        Query                                                      = $query
                    }
                } elseif (Test-Bound -ParameterName Object) {
                    $whereFilter = " WHERE (Object = '$object' or name = '$object')"
                    $statListFiltered = $statList + $whereFilter
                    Write-Message -Level Verbose -Message "Query to execute: $statListFiltered"
                    $statListData = $db.Query($statListFiltered)
                    foreach ($statisticObj in  $statListData) {
                        $query = $StringBuilder.ToString()
                        $query = $query.Replace('#options#', "'$($statisticObj.Object)', '$($statisticObj.Target)'")
                        $queryList += New-Object -TypeName PSObject -Property @{Object = $statisticObj.Object;
                            Target                                                     = $statisticObj.Target;
                            Query                                                      = $query
                        }
                    }
                } else {
                    $statListData = $db.Query($statList)
                    foreach ($statisticObj in  $statListData) {
                        $query = $StringBuilder.ToString()
                        $query = $query.Replace('#options#', "'$($statisticObj.Object)', '$($statisticObj.Target)'")
                        $queryList += New-Object -TypeName PSObject -Property @{Object = $statisticObj.Object;
                            Target                                                     = $statisticObj.Target;
                            Query                                                      = $query
                        }
                    }
                }

                try {
                    foreach ($queryObj in $queryList ) {
                        Write-Message -Message "Running statement $($queryObj.Query)" -Level Verbose
                        $results = $server | Invoke-DbaQuery  -Query $queryObj.Query -Database $db.Name -MessagesToOutput

                        if ($Option -eq 'StatHeader') {
                            foreach ($row in $results) {
                                [PSCustomObject]@{
                                    ComputerName           = $server.ComputerName
                                    InstanceName           = $server.ServiceName
                                    SqlInstance            = $server.DomainInstanceName
                                    Database               = $db.Name
                                    Object                 = $queryObj.Object
                                    Target                 = $queryObj.Target
                                    Cmd                    = $queryObj.Query
                                    Name                   = $row[0]
                                    Updated                = $row[1]
                                    Rows                   = $row[2]
                                    RowsSampled            = $row[3]
                                    Steps                  = $row[4]
                                    Density                = $row[5]
                                    AverageKeyLength       = $row[6]
                                    StringIndex            = $row[7]
                                    FilterExpression       = $row[8]
                                    UnfilteredRows         = $row[9]
                                    PersistedSamplePercent = $row[10]
                                }
                            }
                        }
                        if ($Option -eq 'DensityVector') {
                            foreach ($row in $results) {
                                [PSCustomObject]@{
                                    ComputerName  = $server.ComputerName
                                    InstanceName  = $server.ServiceName
                                    SqlInstance   = $server.DomainInstanceName
                                    Database      = $db.Name
                                    Object        = $queryObj.Object
                                    Target        = $queryObj.Target
                                    Cmd           = $queryObj.Query
                                    AllDensity    = $row[0].ToString()
                                    AverageLength = $row[1]
                                    Columns       = $row[2]
                                }
                            }
                        }
                        if ($Option -eq 'Histogram') {
                            foreach ($row in $results) {
                                [PSCustomObject]@{
                                    ComputerName      = $server.ComputerName
                                    InstanceName      = $server.ServiceName
                                    SqlInstance       = $server.DomainInstanceName
                                    Database          = $db.Name
                                    Object            = $queryObj.Object
                                    Target            = $queryObj.Target
                                    Cmd               = $queryObj.Query
                                    RangeHiKey        = $row[0]
                                    RangeRows         = $row[1]
                                    EqualRows         = $row[2]
                                    DistinctRangeRows = $row[3]
                                    AverageRangeRows  = $row[4]
                                }
                            }
                        }
                        if ($Option -eq 'StatsStream') {
                            foreach ($row in $results) {
                                [PSCustomObject]@{
                                    ComputerName = $server.ComputerName
                                    InstanceName = $server.ServiceName
                                    SqlInstance  = $server.DomainInstanceName
                                    Database     = $db.Name
                                    Object       = $queryObj.Object
                                    Target       = $queryObj.Target
                                    Cmd          = $queryObj.Query
                                    StatsStream  = $row[0]
                                    Rows         = $row[1]
                                    DataPages    = $row[2]
                                }
                            }
                        }
                    }
                } catch {
                    Stop-Function -Message "Error capturing data on $db" -Target $instance -ErrorRecord $_ -Exception $_.Exception -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbccUserOption.ps1
function Get-DbaDbccUserOption {
    <#
    .SYNOPSIS
        Execution of Database Console Command DBCC USEROPTIONS

    .DESCRIPTION
        Returns the results of DBCC USEROPTIONS

        Read more:
            - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-useroptions-transact-sql

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Option
        Return only specific options. Returns all results if not specified.
        Accepts any values in set 'ansi_null_dflt_on', 'ansi_nulls', 'ansi_padding', 'ansi_warnings', 'arithabort', 'concat_null_yields_null', 'datefirst', 'dateformat', 'isolation level', 'language', 'lock_timeout', 'quoted_identifier', 'textsize'

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DBCC
        Author: Patrick Flynn (@sqllensman)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbccUserOptions

    .EXAMPLE
        PS C:\> Get-DbaDbccUserOptions -SqlInstance Server1

        Get results of DBCC USEROPTIONS for Instance Server1

    .EXAMPLE
        PS C:\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbccUserOptions

        Get results of DBCC USEROPTIONS for Instances Sql1 and Sql2/sqlexpress

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> Get-DbaDbccUserOptions -SqlInstance Server1 -SqlCredential $cred

        Connects using sqladmin credential and gets results of DBCC USEROPTIONS for Instance Server1

    .EXAMPLE
        PS C:\> Get-DbaDbccUserOptions -SqlInstance Server1 -Option ansi_nulls, ansi_warnings, datefirst

        Gets results of DBCC USEROPTIONS for Instance Server1. Only display results for the options ansi_nulls, ansi_warnings, datefirst

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [ValidateSet('ansi_null_dflt_on', 'ansi_nulls', 'ansi_padding', 'ansi_warnings', 'arithabort', 'concat_null_yields_null', 'datefirst', 'dateformat', 'isolation level', 'language', 'lock_timeout', 'quoted_identifier', 'textsize')]
        [string[]]$Option,
        [switch]$EnableException
    )
    begin {
        $stringBuilder = New-Object System.Text.StringBuilder
        $null = $stringBuilder.Append("DBCC USEROPTIONS WITH NO_INFOMSGS")
    }
    process {
        $query = $StringBuilder.ToString()

        foreach ($instance in $SqlInstance) {
            Write-Message -Message "Attempting Connection to $instance" -Level Verbose
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Error connecting to $instance" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            try {
                Write-Message -Message "Query to run: $query" -Level Verbose
                $results = $server.Query($query)
            } catch {
                Stop-Function -Message "Failure running $query against $instance" -ErrorRecord $_ -Target $server -Continue
            }
            foreach ($row in $results) {
                if ((Test-Bound -Not -ParameterName Option) -or ($row[0] -in $Option)) {
                    [PSCustomObject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Option       = $row[0]
                        Value        = $row[1]
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbCertificate.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaDbCertificate {
    <#
    .SYNOPSIS
        Gets database certificates

    .DESCRIPTION
        Gets database certificates

    .PARAMETER SqlInstance
        The target SQL Server instance

    .PARAMETER SqlCredential
        Allows you to login to SQL Server using alternative credentials

    .PARAMETER Database
        Get certificate from specific database

    .PARAMETER ExcludeDatabase
        Database(s) to ignore when retrieving certificates

    .PARAMETER InputObject
        Enables piping from Get-DbaDatabase

    .PARAMETER Certificate
        Get specific certificate by name

    .PARAMETER Certificate
        Get specific certificate by subject

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Certificate
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaDbCertificate -SqlInstance sql2016

        Gets all certificates

    .EXAMPLE
        PS C:\> Get-DbaDbCertificate -SqlInstance Server1 -Database db1

        Gets the certificate for the db1 database

    .EXAMPLE
        PS C:\> Get-DbaDbCertificate -SqlInstance Server1 -Database db1 -Certificate cert1

        Gets the cert1 certificate within the db1 database

    .EXAMPLE
        PS C:\> Get-DbaDbCertificate -SqlInstance Server1 -Database db1 -Subject 'Availability Group Cert'

        Gets the cert1 certificate within the db1 database

    #>
    [CmdletBinding()]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [string[]]$ExcludeDatabase,
        [object[]]$Certificate, # sometimes it's text, other times cert
        [string[]]$Subject,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )
    begin {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Get-DbaDatabaseCertificate
    }
    process {
        if ($SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase
        }

        foreach ($db in $InputObject) {
            if (!$db.IsAccessible) {
                Write-Message -Level Warning -Message "$db is not accessible, skipping"
                continue
            }

            #Variable marked as unused by PSScriptAnalyzer
            #$dbName = $db.Name
            $certs = $db.Certificates

            if ($null -eq $certs) {
                Write-Message -Message "No certificate exists in the $db database on $instance" -Target $db -Level Verbose
                continue
            }

            if ($Certificate) {
                $certs = $certs | Where-Object Name -in $Certificate
            }

            if ($Subject) {
                $certs = $certs | Where-Object Subject -in $Subject
            }

            foreach ($cert in $certs) {
                Add-Member -Force -InputObject $cert -MemberType NoteProperty -Name ComputerName -value $db.ComputerName
                Add-Member -Force -InputObject $cert -MemberType NoteProperty -Name InstanceName -value $db.InstanceName
                Add-Member -Force -InputObject $cert -MemberType NoteProperty -Name SqlInstance -value $db.SqlInstance
                Add-Member -Force -InputObject $cert -MemberType NoteProperty -Name Database -value $db.Name

                Select-DefaultView -InputObject $cert -Property ComputerName, InstanceName, SqlInstance, Database, Name, Subject, StartDate, ActiveForServiceBrokerDialog, ExpirationDate, Issuer, LastBackupDate, Owner, PrivateKeyEncryptionType, Serial
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbCheckConstraint.ps1
function Get-DbaDbCheckConstraint {
    <#
    .SYNOPSIS
        Gets database Check constraints.

    .DESCRIPTION
        Gets database Checks constraints.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Allows you to login to SQL Server using alternative credentials

    .PARAMETER Database
        To get Checks from specific database(s)

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto populated from the server

    .PARAMETER ExcludeSystemTable
        This switch removes all system objects from the table collection

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database
        Author: Claudio Silva (@ClaudioESSilva), https://claudioessilva.eu

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaDbCheckConstraint -SqlInstance sql2016

        Gets all database check constraints.

    .EXAMPLE
        PS C:\> Get-DbaDbCheckConstraint -SqlInstance Server1 -Database db1

        Gets the check constraints for the db1 database.

    .EXAMPLE
        PS C:\> Get-DbaDbCheckConstraint -SqlInstance Server1 -ExcludeDatabase db1

        Gets the check constraints for all databases except db1.

    .EXAMPLE
        PS C:\> Get-DbaDbCheckConstraint -SqlInstance Server1 -ExcludeSystemTable

        Gets the check constraints for all databases that are not system objects.

    .EXAMPLE
        PS C:\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbCheckConstraint

        Gets the check constraints for the databases on Sql1 and Sql2/sqlexpress.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$ExcludeSystemTable,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $databases = $server.Databases | Where-Object IsAccessible

            if ($Database) {
                $databases = $databases | Where-Object Name -In $Database
            }
            if ($ExcludeDatabase) {
                $databases = $databases | Where-Object Name -NotIn $ExcludeDatabase
            }

            foreach ($db in $databases) {
                if (!$db.IsAccessible) {
                    Write-Message -Level Warning -Message "Database $db is not accessible. Skipping."
                    continue
                }

                foreach ($tbl in $db.Tables) {
                    if ( (Test-Bound -ParameterName ExcludeSystemTable) -and $tbl.IsSystemObject ) {
                        continue
                    }

                    if ($tbl.Checks.Count -eq 0) {
                        Write-Message -Message "No Checks exist in $tbl table on the $db database on $instance" -Target $tbl -Level Verbose
                        continue
                    }

                    foreach ($ck in $tbl.Checks) {
                        Add-Member -Force -InputObject $ck -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                        Add-Member -Force -InputObject $ck -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                        Add-Member -Force -InputObject $ck -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                        Add-Member -Force -InputObject $ck -MemberType NoteProperty -Name Database -value $db.Name

                        $defaults = 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Parent', 'ID', 'CreateDate',
                        'DateLastModified', 'Name', 'IsEnabled', 'IsChecked', 'NotForReplication', 'Text', 'State'
                        Select-DefaultView -InputObject $ck -Property $defaults
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbCompatibility.ps1
function Get-DbaDbCompatibility {
    <#
    .SYNOPSIS
        Displays the compatibility level for SQL Server databases.

    .DESCRIPTION
        Get the current database compatibility level for all databases on a server or list of databases passed in to the function.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        SqlCredential object used to connect to the SQL Server as a different user.

    .PARAMETER Database
        The database or databases to process. If unspecified, all databases will be processed.

    .PARAMETER InputObject
        A collection of databases (such as returned by Get-DbaDatabase)

    .PARAMETER WhatIf
        Shows what would happen if the command were to run

    .PARAMETER Confirm
        Prompts for confirmation of every step. For example:

        Are you sure you want to perform this action?
        Performing the operation "Update database" on target "pubs on SQL2016\VNEXT".
        [Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Compatibility, Database
        Author: Garry Bargsley, http://blog.garrybargsley.com/

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbCompatibility

    .EXAMPLE
        PS C:\> Get-DbaDbCompatibility -SqlInstance localhost\sql2017

        Displays database compatibility level for all user databases on server localhost\sql2017

    .EXAMPLE
        PS C:\> Get-DbaDbCompatibility -SqlInstance localhost\sql2017 -Database Test

        Displays database compatibility level for database Test on server localhost\sql2017

    #>
    [CmdletBinding()]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if (Test-Bound -not 'SqlInstance', 'InputObject') {
            Write-Message -Level Warning -Message "You must specify either a SQL instance or pipe a database collection"
            continue
        }

        if ($SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database
        }

        foreach ($db in $InputObject) {
            $server = $db.Parent
            $ServerVersion = $server.VersionMajor
            Write-Message -Level Verbose -Message "SQL Server is using Version: $ServerVersion"

            [PSCustomObject]@{
                ComputerName  = $server.ComputerName
                InstanceName  = $server.ServiceName
                SqlInstance   = $server.DomainInstanceName
                Database      = $db.Name
                Compatibility = $db.CompatibilityLevel
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbCompression.ps1
function Get-DbaDbCompression {
    <#
    .SYNOPSIS
        Gets tables and indexes size and current compression settings.

    .DESCRIPTION
        This function gets the current size and compression for all objects in the specified database(s), if no database is specified it will return all objects in all user databases.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto populated from the server.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Compression, Table, Database
        Author: Jess Pomfret (@jpomfret), jesspomfret.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaDbCompression -SqlInstance localhost

        Returns objects size and current compression level for all user databases.

    .EXAMPLE
        PS C:\> Get-DbaDbCompression -SqlInstance localhost -Database TestDatabase

        Returns objects size and current compression level for objects within the TestDatabase database.

    .EXAMPLE
        PS C:\> Get-DbaDbCompression -SqlInstance localhost -ExcludeDatabase TestDatabases

        Returns objects size and current compression level for objects in all databases except the TestDatabase database.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failed to process Instance $Instance" -ErrorRecord $_ -Target $instance -Continue
            }

            try {
                $dbs = $server.Databases | Where-Object { $_.IsAccessible -and $_.IsSystemObject -eq 0 }

                if ($Database) {
                    $dbs = $dbs | Where-Object { $_.Name -In $Database }
                }

                if ($ExcludeDatabase) {
                    $dbs = $dbs | Where-Object { $_.Name -NotIn $ExcludeDatabase }
                }
            } catch {
                Stop-Function -Message "Unable to gather list of databases for $instance" -Target $instance -ErrorRecord $_ -Continue
            }

            foreach ($db in $dbs) {
                try {
                    foreach ($obj in $server.Databases[$($db.name)].Tables) {
                        if ($obj.HasHeapIndex) {
                            foreach ($p in $obj.PhysicalPartitions) {
                                [pscustomobject]@{
                                    ComputerName    = $server.ComputerName
                                    InstanceName    = $server.ServiceName
                                    SqlInstance     = $server.DomainInstanceName
                                    Database        = $db.Name
                                    Schema          = $obj.Schema
                                    TableName       = $obj.Name
                                    IndexName       = $null
                                    Partition       = $p.PartitionNumber
                                    IndexID         = 0
                                    IndexType       = "Heap"
                                    DataCompression = $p.DataCompression
                                    SizeCurrent     = [dbasize]($obj.DataSpaceUsed * 1024)
                                    RowCount        = $obj.RowCount
                                }
                            }
                        }

                        foreach ($index in $obj.Indexes) {
                            foreach ($p in $index.PhysicalPartitions) {
                                [pscustomobject]@{
                                    ComputerName    = $server.ComputerName
                                    InstanceName    = $server.ServiceName
                                    SqlInstance     = $server.DomainInstanceName
                                    Database        = $db.Name
                                    Schema          = $obj.Schema
                                    TableName       = $obj.Name
                                    IndexName       = $index.Name
                                    Partition       = $p.PartitionNumber
                                    IndexID         = $index.ID
                                    IndexType       = $index.IndexType
                                    DataCompression = $p.DataCompression
                                    SizeCurrent     = if ($index.IndexType -eq "ClusteredIndex") { [dbasize]($obj.DataSpaceUsed * 1024) } else { [dbasize]($index.SpaceUsed * 1024) }
                                    RowCount        = $p.RowCount
                                }
                            }
                        }

                    }
                } catch {
                    Stop-Function -Message "Unable to query $instance - $db" -Target $db -ErrorRecord $_ -Continue
                }

            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbDbccOpenTran.ps1
function Get-DbaDbDbccOpenTran {
    <#
    .SYNOPSIS
        Execution of Database Console Command DBCC OPENTRAN

    .DESCRIPTION
        Executes the command DBCC OPENTRAN against the requested databases

        Displays information about the oldest active transaction and
        the oldest distributed and nondistributed replicated transactions, if any,
        within the transaction log of the specified database

        Read more:
            - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-opentran-transact-sql

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process. If unspecified, all databases will be processed.
        The Name or Id of a database can be specified
        Database names must comply with the rules for identifiers.


    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DBCC
        Author: Patrick Flynn (@sqllensman)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbDbccOpenTran

    .EXAMPLE
        PS C:\> Get-DbaDbDbccOpenTran -SqlInstance SQLServer2017

        Connects to instance SqlServer2017 using Windows Authentication and runs the command DBCC OPENTRAN WITH TABLERESULTS, NO_INFOMSGS against each database.

    .EXAMPLE
        PS C:\> Get-DbaDbDbccOpenTran -SqlInstance SQLServer2017 -Database CurrentDB

        Connects to instance SqlServer2017 using Windows Authentication and runs the command DBCC OPENTRAN(CurrentDB) WITH TABLERESULTS, NO_INFOMSGS against the CurrentDB database.

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbDbccOpenTran -SqlCredential $cred

        Connects to instances Sql1 and Sql2/sqlexpress using sqladmin credential and runs the command DBCC OPENTRAN WITH TABLERESULTS, NO_INFOMSGS against each database.
    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [switch]$EnableException
    )
    begin {
        $stringBuilder = New-Object System.Text.StringBuilder
        $null = $stringBuilder.Append("DBCC OPENTRAN(#options#) WITH TABLERESULTS, NO_INFOMSGS")
    }
    process {
        foreach ($instance in $SqlInstance) {
            Write-Message -Message "Attempting Connection to $instance" -Level Verbose
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $dbs = $server.Databases

            if (Test-Bound -ParameterName Database) {
                $dbs = $dbs | Where-Object {($_.Name -In $Database) -or ($_.ID -In $Database) }
            }

            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Processing $db on $instance"

                if ($db.IsAccessible -eq $false) {
                    Stop-Function -Message "The database $db is not accessible. Skipping." -Continue
                }

                try {
                    $query = $StringBuilder.ToString()
                    $query = $query.Replace('#options#', "'$($db.Name)'")

                    Write-Message -Message "Query to run: $query" -Level Verbose
                    $results = $server.Query($query)
                    Write-Message -Message "Finshed" -Level Verbose
                } catch {
                    Stop-Function -Message "Error capturing data on $db" -Target $instance -ErrorRecord $_ -Exception $_.Exception -Continue
                }

                if ($null -eq $results) {
                    [PSCustomObject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Database     = $db.Name
                        Cmd          = $query.ToString()
                        Output       = 'No active open transactions.'
                        Field        = $null
                        Data         = $null
                    }
                } else {
                    foreach ($row in $results) {
                        [PSCustomObject]@{
                            ComputerName = $server.ComputerName
                            InstanceName = $server.ServiceName
                            SqlInstance  = $server.DomainInstanceName
                            Database     = $db.Name
                            Cmd          = $query.ToString()
                            Output       = 'Oldest active transaction'
                            Field        = $row[0]
                            Data         = $row[1]
                        }
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbEncryption.ps1
function Get-DbaDbEncryption {
    <#
    .SYNOPSIS
        Returns a summary of encryption used on databases passed to it.

    .DESCRIPTION
        Shows if a database has Transparent Data Encryption (TDE), any certificates, asymmetric keys or symmetric keys with details for each.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server.

    .PARAMETER IncludeSystemDBs
        Switch parameter that when used will display system database information.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Encryption, Database
        Author: Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbEncryption

    .EXAMPLE
        PS C:\> Get-DbaDbEncryption -SqlInstance DEV01

        List all encryption found on the instance by database

    .EXAMPLE
        PS C:\> Get-DbaDbEncryption -SqlInstance DEV01 -Database MyDB

        List all encryption found for the MyDB database.

    .EXAMPLE
        PS C:\> Get-DbaDbEncryption -SqlInstance DEV01 -ExcludeDatabase MyDB

        List all encryption found for all databases except MyDB.

    .EXAMPLE
        PS C:\> Get-DbaDbEncryption -SqlInstance DEV01 -IncludeSystemDBs

        List all encryption found for all databases including the system databases.

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline, Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$IncludeSystemDBs,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            #For each SQL Server in collection, connect and get SMO object

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            #If IncludeSystemDBs is true, include systemdbs
            #only look at online databases (Status equal normal)
            try {
                if ($Database) {
                    $dbs = $server.Databases | Where-Object Name -In $Database
                } elseif ($IncludeSystemDBs) {
                    $dbs = $server.Databases | Where-Object IsAccessible
                } else {
                    $dbs = $server.Databases | Where-Object { $_.IsAccessible -and $_.IsSystemObject -eq 0 }
                }

                if ($ExcludeDatabase) {
                    $dbs = $dbs | Where-Object Name -NotIn $ExcludeDatabase
                }
            } catch {
                Stop-Function -Message "Unable to gather dbs for $instance" -Target $instance -Continue
            }

            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Processing $db"

                if ($db.EncryptionEnabled -eq $true) {
                    [PSCustomObject]@{
                        ComputerName             = $server.ComputerName
                        InstanceName             = $server.ServiceName
                        SqlInstance              = $server.DomainInstanceName
                        Database                 = $db.Name
                        Encryption               = "EncryptionEnabled (TDE)"
                        Name                     = $null
                        LastBackup               = $null
                        PrivateKeyEncryptionType = $null
                        EncryptionAlgorithm      = $null
                        KeyLength                = $null
                        Owner                    = $null
                        Object                   = $null
                        ExpirationDate           = $null
                    }

                }

                foreach ($cert in $db.Certificates) {
                    [PSCustomObject]@{
                        ComputerName             = $server.ComputerName
                        InstanceName             = $server.ServiceName
                        SqlInstance              = $server.DomainInstanceName
                        Database                 = $db.Name
                        Encryption               = "Certificate"
                        Name                     = $cert.Name
                        LastBackup               = $cert.LastBackupDate
                        PrivateKeyEncryptionType = $cert.PrivateKeyEncryptionType
                        EncryptionAlgorithm      = $null
                        KeyLength                = $null
                        Owner                    = $cert.Owner
                        Object                   = $cert
                        ExpirationDate           = $cert.ExpirationDate
                    }

                }

                foreach ($ak in $db.AsymmetricKeys) {
                    [PSCustomObject]@{
                        ComputerName             = $server.ComputerName
                        InstanceName             = $server.ServiceName
                        SqlInstance              = $server.DomainInstanceName
                        Database                 = $db.Name
                        Encryption               = "Asymmetric key"
                        Name                     = $ak.Name
                        LastBackup               = $null
                        PrivateKeyEncryptionType = $ak.PrivateKeyEncryptionType
                        EncryptionAlgorithm      = $ak.KeyEncryptionAlgorithm
                        KeyLength                = $ak.KeyLength
                        Owner                    = $ak.Owner
                        Object                   = $ak
                        ExpirationDate           = $null
                    }

                }
                foreach ($sk in $db.SymmetricKeys) {
                    [PSCustomObject]@{
                        Server                   = $server.name
                        Instance                 = $server.InstanceName
                        Database                 = $db.Name
                        Encryption               = "Symmetric key"
                        Name                     = $sk.Name
                        LastBackup               = $null
                        PrivateKeyEncryptionType = $sk.PrivateKeyEncryptionType
                        EncryptionAlgorithm      = $ak.EncryptionAlgorithm
                        KeyLength                = $sk.KeyLength
                        Owner                    = $sk.Owner
                        Object                   = $sk
                        ExpirationDate           = $null
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaDatabaseEncryption
    }
}
tools\dbatools\functions\Get-DbaDbExtentDiff.ps1
function Get-DbaDbExtentDiff {
    <#
    .SYNOPSIS
        What percentage of a database has changed since the last full backup

    .DESCRIPTION
        This is only an implementation of the script created by Paul S. Randal to find what percentage of a database has changed since the last full backup.
        https://www.sqlskills.com/blogs/paul/new-script-how-much-of-the-database-has-changed-since-the-last-full-backup/

    .PARAMETER SqlInstance
        The target SQL Server instance

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Backup, Database
        Author: Viorel Ciucu, cviorel.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: GNU GPL v3 https://opensource.org/licenses/GPL-3.0

    .LINK
        http://dbatools.io/Get-DbaDbExtentDiff

    .EXAMPLE
        PS C:\> Get-DbaDbExtentDiff -SqlInstance SQL2016 -Database DBA

        Get the changes for the DBA database.

    .EXAMPLE
        PS C:\> $Cred = Get-Credential sqladmin
        PS C:\> Get-DbaDbExtentDiff -SqlInstance SQL2017N1, SQL2017N2, SQL2016 -Database DB01 -SqlCredential $Cred

        Get the changes for the DB01 database on multiple servers.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias('ServerInstance', 'SqlServer')]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$EnableException
    )

    begin {
        $rex = [regex]':(?<extent>[\d]+)\)'
        function Get-DbaExtent ([string[]]$field) {
            $res = 0
            foreach ($f in $field) {
                $extents = $rex.Matches($f)
                if ($extents.Count -eq 1) {
                    $res += 1
                } else {
                    $pages = [int]$extents[1].Groups['extent'].Value - [int]$extents[0].Groups['extent'].Value
                    $res += $pages / 8 + 1
                }
            }
            return $res
        }
    }

    process {

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -NonPooled
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $dbs = $server.Databases

            if ($Database) {
                $dbs = $dbs | Where-Object Name -In $Database
            }

            if ($ExcludeDatabase) {
                $dbs = $dbs | Where-Object Name -NotIn $ExcludeDatabase
            }

            $sourcedbs = @()
            foreach ($db in $dbs) {
                if ($db.IsAccessible -ne $true) {
                    Write-Message -Level Verbose -Message "$db is not accessible on $instance, skipping"
                } else {
                    $sourcedbs += $db
                }
            }

            #Available from 2016 SP2
            if ($server.Version -ge [version]'13.0.5026') {
                foreach ($db in $sourcedbs) {
                    $DBCCPageQueryDMV = "
                        SELECT
                        SUM(total_page_count) / 8 as [ExtentsTotal],
                        SUM(modified_extent_page_count) / 8 as [ExtentsChanged],
                        100.0 * SUM(modified_extent_page_count)/SUM(total_page_count) as [ChangedPerc]
                        FROM sys.dm_db_file_space_usage
                    "
                    $DBCCPageResults = $server.Query($DBCCPageQueryDMV, $db.Name)
                    [pscustomobject]@{
                        ComputerName   = $server.ComputerName
                        InstanceName   = $server.ServiceName
                        SqlInstance    = $server.DomainInstanceName
                        DatabaseName   = $db.Name
                        ExtentsTotal   = $DBCCPageResults.ExtentsTotal
                        ExtentsChanged = $DBCCPageResults.ExtentsChanged
                        ChangedPerc    = [math]::Round($DBCCPageResults.ChangedPerc, 2)
                    }
                }
            } else {
                $MasterFilesQuery = "
                        SELECT [file_id], [size], database_id, db_name(database_id) as dbname FROM master.sys.master_files
                        WHERE [type_desc] = N'ROWS'
                    "
                $MasterFiles = $server.Query($MasterFilesQuery)
                $MasterFiles = $MasterFiles | Where-Object dbname -In $sourcedbs.Name
                $MasterFilesGrouped = $MasterFiles | Group-Object -Property dbname

                foreach ($db in $MasterFilesGrouped) {
                    $sizeTotal = 0
                    $dbExtents = @()
                    foreach ($results in $db.Group) {
                        $extentID = 0
                        $sizeTotal = $sizeTotal + $results.size / 8
                        while ($extentID -lt $results.size) {
                            $pageID = $extentID + 6
                            $DBCCPageQuery = "DBCC PAGE ('$($results.dbname)', $($results.file_id), $pageID, 3)  WITH TABLERESULTS, NO_INFOMSGS"
                            $DBCCPageResults = $server.Query($DBCCPageQuery)
                            $dbExtents += $DBCCPageResults | Where-Object { $_.VALUE -eq '    CHANGED' -And $_.ParentObject -like 'DIFF_MAP*'}
                            $extentID = $extentID + 511232
                        }
                    }
                    $extents = Get-DbaExtent $dbExtents.Field
                    [pscustomobject]@{
                        ComputerName   = $server.ComputerName
                        InstanceName   = $server.ServiceName
                        SqlInstance    = $server.DomainInstanceName
                        DatabaseName   = $db.Name
                        ExtentsTotal   = $sizeTotal
                        ExtentsChanged = $extents
                        ChangedPerc    = [math]::Round(($extents / $sizeTotal * 100), 2)
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbFeatureUsage.ps1
function Get-DbaDbFeatureUsage {
    <#
    .SYNOPSIS
        Shows features that are enabled in the database but not supported on all editions of SQL Server. Basically checks for Enterprise feature usage.

    .DESCRIPTION
        Shows features that are enabled in the database but not supported on all editions of SQL Server.

        Basically checks for Enterprise feature usage.

        This feature must be removed before the database can be migrated to all available editions of SQL Server.

    .PARAMETER SqlInstance
        The target SQL Server instance

    .PARAMETER SqlCredential
        Login to the target instance using alternate Windows or SQL Login Authentication. Accepts credential objects (Get-Credential).

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER InputObject
        A collection of databases (such as returned by Get-DbaDatabase), to be tested.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Deprecated
        Author: Brandon Abshire, netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbFeatureUsage

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sql2008 -Database testdb, db2 | Get-DbaDbFeatureUsage

        Shows features that are enabled in the testdb and db2 databases but
        not supported on the all the editions of SQL Server.

    #>
    [CmdletBinding()]
    param (
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [string[]]$ExcludeDatabase,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )

    begin {
        $sql = "SELECT  SERVERPROPERTY('MachineName') AS ComputerName,
            ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
            SERVERPROPERTY('ServerName') AS SqlInstance, feature_id as Id,
            feature_name as Feature,  DB_NAME() as [Database] FROM sys.dm_db_persisted_sku_features"
    }

    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $instance -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase
        }
        foreach ($db in $InputObject) {
            Write-Message -Level Verbose -Message "Processing $db on $($db.Parent.Name)"

            if ($db.IsAccessible -eq $false) {
                Stop-Function -Message "The database $db is not accessible. Skipping database." -Continue
            }

            try {
                $db.Query($sql)
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbFile.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaDbFile {
    <#
    .SYNOPSIS
        Returns detailed information about database files.

    .DESCRIPTION
        Returns detailed information about database files. Does not use SMO - SMO causes enumeration and this command avoids that.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Credentials to connect to the SQL Server instance if the calling user doesn't have permission

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER InputObject
        A piped collection of database objects

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database
        Author: Stuart Moore (@napalmgram), stuart-moore.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaDbFile -SqlInstance sql2016

        Will return an object containing all file groups and their contained files for every database on the sql2016 SQL Server instance

    .EXAMPLE
        PS C:\> Get-DbaDbFile -SqlInstance sql2016 -Database Impromptu

        Will return an object containing all file groups and their contained files for the Impromptu Database on the sql2016 SQL Server instance

    .EXAMPLE
        PS C:\> Get-DbaDbFile -SqlInstance sql2016 -Database Impromptu, Trading

        Will return an object containing all file groups and their contained files for the Impromptu and Trading databases on the sql2016 SQL Server instance

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sql2016 -Database Impromptu, Trading | Get-DbaDbFile

        Will accept piped input from Get-DbaDatabase and return an object containing all file groups and their contained files for the Impromptu and Trading databases on the sql2016 SQL Server instance
    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )
    begin {
        #region Sql Query Generation
        $sql = "select
            fg.name as FileGroupName,
            df.file_id as 'ID',
            df.Type,
            df.type_desc as TypeDescription,
            df.name as LogicalName,
            mf.physical_name as PhysicalName,
            df.state_desc as State,
            df.max_size as MaxSize,
            case mf.is_percent_growth when 1 then df.growth else df.Growth*8 end as Growth,
            fileproperty(df.name, 'spaceused') as UsedSpace,
            df.size as Size,
            vfs.size_on_disk_bytes as size_on_disk_bytes,
            case df.state_desc when 'OFFLINE' then 'True' else 'False' End as IsOffline,
            case mf.is_read_only when 1 then 'True' when 0 then 'False' End as IsReadOnly,
            case mf.is_media_read_only when 1 then 'True' when 0 then 'False' End as IsReadOnlyMedia,
            case mf.is_sparse when 1 then 'True' when 0 then 'False' End as IsSparse,
            case mf.is_percent_growth when 1 then 'Percent' when 0 then 'kb' End as GrowthType,
            case mf.is_read_only when 1 then 'True' when 0 then 'False' End as IsReadOnly,
            vfs.num_of_writes as NumberOfDiskWrites,
            vfs.num_of_reads as NumberOfDiskReads,
            vfs.num_of_bytes_read as BytesReadFromDisk,
            vfs.num_of_bytes_written as BytesWrittenToDisk,
            fg.data_space_id as FileGroupDataSpaceId,
            fg.Type as FileGroupType,
            fg.type_desc as FileGroupTypeDescription,
            case fg.is_default When 1 then 'True' when 0 then 'False' end as FileGroupDefault,
            fg.is_read_only as FileGroupReadOnly"

        $sqlfrom = "from sys.database_files df
            left outer join  sys.filegroups fg on df.data_space_id=fg.data_space_id
            inner join sys.dm_io_virtual_file_stats(db_id(),NULL) vfs on df.file_id=vfs.file_id
            inner join sys.master_files mf on df.file_id = mf.file_id
            and mf.database_id = db_id()"

        $sql2008 = ",vs.available_bytes as 'VolumeFreeSpace'"
        $sql2008from = "cross apply sys.dm_os_volume_stats(db_id(),df.file_id) vs"

        $sql2000 = "select
            fg.groupname as FileGroupName,
            df.fileid as ID,
            CONVERT(INT,df.status & 0x40) / 64 as Type,
            case CONVERT(INT,df.status & 0x40) / 64 when 1 then 'LOG' else 'ROWS' end as TypeDescription,
            df.name as LogicalName,
            df.filename as PhysicalName,
            'Existing' as State,
            df.maxsize as MaxSize,
            case CONVERT(INT,df.status & 0x100000) / 1048576 when 1 then df.growth when 0 then df.growth*8 End as Growth,
            fileproperty(df.name, 'spaceused') as UsedSpace,
            df.size as Size,
            case CONVERT(INT,df.status & 0x20000000) / 536870912 when 1 then 'True' else 'False' End as IsOffline,
            case CONVERT(INT,df.status & 0x10) / 16 when 1 then 'True' when 0 then 'False' End as IsReadOnly,
            case CONVERT(INT,df.status & 0x1000) / 4096 when 1 then 'True' when 0 then 'False' End as IsReadOnlyMedia,
            case CONVERT(INT,df.status & 0x10000000) / 268435456 when 1 then 'True' when 0 then 'False' End as IsSparse,
            case CONVERT(INT,df.status & 0x100000) / 1048576 when 1 then 'Percent' when 0 then 'kb' End as GrowthType,
            case CONVERT(INT,df.status & 0x1000) / 4096 when 1 then 'True' when 0 then 'False' End as IsReadOnly,
            fg.groupid as FileGroupDataSpaceId,
            NULL as FileGroupType,
            NULL AS FileGroupTypeDescription,
            CAST(fg.status & 0x10 as BIT) as FileGroupDefault,
            CAST(fg.status & 0x8 as BIT) as FileGroupReadOnly
            from sysfiles df
            left outer join  sysfilegroups fg on df.groupid=fg.groupid"
        #endregion Sql Query Generation
    }

    process {
        if ($SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase
        }

        foreach ($db in $InputObject) {
            $server = $db.Parent

            Write-Message -Level Verbose -Message "Querying database $db"

            try {
                $version = $server.Query("SELECT compatibility_level FROM sys.databases WHERE name = '$($db.Name)'")
                $version = [int]($version.compatibility_level / 10)
            } catch {
                $version = 8
            }

            if ($version -ge 11) {
                $query = ($sql, $sql2008, $sqlfrom, $sql2008from) -Join "`n"
            } elseif ($version -ge 9) {
                $query = ($sql, $sqlfrom) -Join "`n"
            } else {
                $query = $sql2000
            }

            Write-Message -Level Debug -Message "SQL Statement: $query"

            try {
                $results = $server.Query($query, $db.Name)
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
            }

            foreach ($result in $results) {
                $size = [dbasize]($result.Size * 8192)
                $usedspace = [dbasize]($result.UsedSpace * 8192)
                $maxsize = $result.MaxSize
                # calculation is done here because for snapshots or sparse files size is not the "virtual" size
                # (master_files.Size) but the currently allocated one (dm_io_virtual_file_stats.size_on_disk_bytes)
                $AvailableSpace = $size - $usedspace
                if ($result.size_on_disk_bytes) {
                    $size = [dbasize]($result.size_on_disk_bytes)
                }
                if ($maxsize -gt -1) {
                    $maxsize = [dbasize]($result.MaxSize * 8192)
                } else {
                    $maxsize = [dbasize]($result.MaxSize)
                }

                if ($result.VolumeFreeSpace) {
                    $VolumeFreeSpace = [dbasize]$result.VolumeFreeSpace
                } else {
                    # to get drive free space for each drive that a database has files on
                    # when database compatibility lower than 110. Lets do this with query2
                    $query2 = @'
-- to get drive free space for each drive that a database has files on
DECLARE @FixedDrives TABLE(Drive CHAR(1), MB_Free BIGINT);
INSERT @FixedDrives EXEC sys.xp_fixeddrives;

SELECT DISTINCT fd.MB_Free, LEFT(df.physical_name, 1) AS [Drive]
FROM @FixedDrives AS fd
INNER JOIN sys.database_files AS df
ON fd.Drive = LEFT(df.physical_name, 1);
'@
                    # if the server has one drive xp_fixeddrives returns one row, but we still need $disks to be an array.
                    if ($server.VersionMajor -gt 8) {
                        $disks = @($server.Query($query2, $db.Name))
                        $MbFreeColName = $disks[0].psobject.Properties.Name
                        # get the free MB value for the drive in question
                        $free = $disks | Where-Object {
                            $_.drive -eq $result.PhysicalName.Substring(0, 1)
                        } | Select-Object $MbFreeColName

                        $VolumeFreeSpace = [dbasize](($free.MB_Free) * 1024 * 1024)
                    }
                }
                if ($result.GrowthType -eq "Percent") {
                    $nextgrowtheventadd = [dbasize]($result.size * ($result.Growth * 0.01) * 1024)
                } else {
                    $nextgrowtheventadd = [dbasize]($result.Growth * 8 * 1024)
                }
                if (($nextgrowtheventadd.Byte -gt ($MaxSize.Byte - $size.Byte)) -and $maxsize -gt 0) {
                    [dbasize]$nextgrowtheventadd = 0
                }

                [PSCustomObject]@{
                    ComputerName             = $server.ComputerName
                    InstanceName             = $server.ServiceName
                    SqlInstance              = $server.DomainInstanceName
                    Database                 = $db.name
                    FileGroupName            = $result.FileGroupName
                    ID                       = $result.ID
                    Type                     = $result.Type
                    TypeDescription          = $result.TypeDescription
                    LogicalName              = $result.LogicalName.Trim()
                    PhysicalName             = $result.PhysicalName.Trim()
                    State                    = $result.State
                    MaxSize                  = $maxsize
                    Growth                   = $result.Growth
                    GrowthType               = $result.GrowthType
                    NextGrowthEventSize      = $nextgrowtheventadd
                    Size                     = $size
                    UsedSpace                = $usedspace
                    AvailableSpace           = $AvailableSpace
                    IsOffline                = $result.IsOffline
                    IsReadOnly               = $result.IsReadOnly
                    IsReadOnlyMedia          = $result.IsReadOnlyMedia
                    IsSparse                 = $result.IsSparse
                    NumberOfDiskWrites       = $result.NumberOfDiskWrites
                    NumberOfDiskReads        = $result.NumberOfDiskReads
                    ReadFromDisk             = [dbasize]$result.BytesReadFromDisk
                    WrittenToDisk            = [dbasize]$result.BytesWrittenToDisk
                    VolumeFreeSpace          = $VolumeFreeSpace
                    FileGroupDataSpaceId     = $result.FileGroupDataSpaceId
                    FileGroupType            = $result.FileGroupType
                    FileGroupTypeDescription = $result.FileGroupTypeDescription
                    FileGroupDefault         = $result.FileGroupDefault
                    FileGroupReadOnly        = $result.FileGroupReadOnly
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaDatabaseFIle
    }
}
tools\dbatools\functions\Get-DbaDbForeignKey.ps1
function Get-DbaDbForeignKey {
    <#
    .SYNOPSIS
        Gets database Foreign Keys.

    .DESCRIPTION
        Gets database Foreign Keys.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Allows you to login to SQL Server using alternative credentials

    .PARAMETER Database
        To get Foreign Keys from specific database(s)

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto populated from the server

    .PARAMETER ExcludeSystemTable
        This switch removes all system objects from the tables collection

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database,ForeignKey, Table
        Author: Claudio Silva (@ClaudioESSilva), https://claudioessilva.eu

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaDbForeignKey -SqlInstance sql2016

        Gets all database Foreign Keys.

    .EXAMPLE
        PS C:\> Get-DbaDbForeignKey -SqlInstance Server1 -Database db1

        Gets the Foreign Keys for the db1 database.

    .EXAMPLE
        PS C:\> Get-DbaDbForeignKey -SqlInstance Server1 -ExcludeDatabase db1

        Gets the Foreign Keys for all databases except db1.

    .EXAMPLE
        PS C:\> Get-DbaDbForeignKey -SqlInstance Server1 -ExcludeSystemTable

        Gets the Foreign Keys from all tables that are not system objects from all databases.

    .EXAMPLE
        PS C:\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbForeignKey

        Gets the Foreign Keys for the databases on Sql1 and Sql2/sqlexpress.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$ExcludeSystemTable,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $databases = $server.Databases | Where-Object IsAccessible

            if ($Database) {
                $databases = $databases | Where-Object Name -In $Database
            }
            if ($ExcludeDatabase) {
                $databases = $databases | Where-Object Name -NotIn $ExcludeDatabase
            }

            foreach ($db in $databases) {
                if (!$db.IsAccessible) {
                    Write-Message -Level Warning -Message "Database $db is not accessible. Skipping."
                    continue
                }

                foreach ($tbl in $db.Tables) {
                    if ( (Test-Bound -ParameterName ExcludeSystemTable) -and $tbl.IsSystemObject ) {
                        continue
                    }

                    if ($tbl.ForeignKeys.Count -eq 0) {
                        Write-Message -Message "No Foreign Keys exist in $tbl table on the $db database on $instance" -Target $tbl -Level Verbose
                        continue
                    }

                    foreach ($fk in $tbl.ForeignKeys) {
                        Add-Member -Force -InputObject $fk -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                        Add-Member -Force -InputObject $fk -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                        Add-Member -Force -InputObject $fk -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                        Add-Member -Force -InputObject $fk -MemberType NoteProperty -Name Database -value $db.Name

                        $defaults = 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Table', 'ID', 'CreateDate',
                        'DateLastModified', 'Name', 'IsEnabled', 'IsChecked', 'NotForReplication', 'ReferencedKey', 'ReferencedTable', 'ReferencedTableSchema'
                        Select-DefaultView -InputObject $fk -Property $defaults
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbIdentity.ps1
function Get-DbaDbIdentity {
    <#
    .SYNOPSIS
        Checks the current identity value via DBCC CHECKIDENT with NORESEED optuin

    .DESCRIPTION
        Use the command DBCC CHECKIDENT with NORESEED option to checks the current identity value of a table and return results

        Read more:
            - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkident-transact-sql

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER Table
        The table(s) for which to check the current identity value.

    .PARAMETER WhatIf
        Shows what would happen if the cmdlet runs. The cmdlet is not run.

    .PARAMETER Confirm
        Prompts you for confirmation before running the cmdlet.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DBCC
        Author: Patrick Flynn (@sqllensman)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbIdentity

    .EXAMPLE
        PS C:\> Get-DbaDbIdentity -SqlInstance SQLServer2017 -Database AdventureWorks2014 -Table 'Production.ScrapReason'

        Connects to AdventureWorks2014 on instance SqlServer2017 using Windows Authentication and runs the command DBCC CHECKIDENT('Production.ScrapReason', NORESEED) to return the current identity value.

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbIdentity -SqlCredential $cred -Database AdventureWorks2014 -Table 'Production.ScrapReason'

        Connects to AdventureWorks2014 on instances Sql1 and Sql2/sqlexpress using sqladmin credential and runs the command DBCC CHECKIDENT('Production.ScrapReason', NORESEED) to return the current identity value.

    .EXAMPLE
        PS C:\> $query = "Select Quotename(Schema_Name(t.schema_id)) +'.' + QuoteName(t.name) as TableName from sys.columns c INNER JOIN sys.tables t on t.object_id = c.object_id WHERE is_identity = 1 and is_memory_optimized = 0"
        PS C:\> $IdentityTables = Invoke-DbaQuery -SqlInstance SQLServer2017 -Database AdventureWorks2014 -Query $query -As SingleValue
        PS C:\> Get-DbaDbIdentity -SqlInstance SQLServer2017 -Database AdventureWorks2014 -Table $IdentityTables

        Checks the current identity value for all non memory optimized tables with an Identity in the AdventureWorks2014 database on the SQLServer2017 instance.
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [string[]]$Table,
        [switch]$EnableException
    )
    begin {
        $stringBuilder = New-Object System.Text.StringBuilder
        $null = $stringBuilder.Append("DBCC CHECKIDENT(#options#, NORESEED)")
    }
    process {
        if (Test-Bound -Not -ParameterName Table) {
            Stop-Function -Message "You must specify a table to execute against using -Table"
            return
        }
        foreach ($instance in $SqlInstance) {
            Write-Message -Message "Attempting Connection to $instance" -Level Verbose
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $dbs = $server.Databases

            if ($Database) {
                $dbs = $dbs | Where-Object Name -In $Database
            }

            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Processing $db on $instance"

                if ($db.IsAccessible -eq $false) {
                    Stop-Function -Message "The database $db is not accessible. Skipping." -Continue
                }

                foreach ($tbl in $Table) {
                    try {
                        $query = $StringBuilder.ToString()
                        $query = $query.Replace('#options#', "'$($tbl)'")

                        if ($Pscmdlet.ShouldProcess($server.Name, "Execute the command $query against $instance")) {
                            Write-Message -Message "Query to run: $query" -Level Verbose
                            $results = $server | Invoke-DbaQuery  -Query $query -Database $db.Name -MessagesToOutput
                            if ($null -ne $results) {
                                $words = $results.Split(" ")
                                $identityValue = $words[6].Replace("'", "").Replace(",", "")
                                $columnValue = $words[10].Replace("'", "").Replace(".", "")
                            } else {
                                $identityValue = $null
                                $columnValue = $null
                            }
                        }
                    } catch {
                        Stop-Function -Message "Error running  $query against $db" -Target $instance -ErrorRecord $_ -Exception $_.Exception -Continue
                    }
                    if ($Pscmdlet.ShouldProcess("console", "Outputting object")) {
                        [PSCustomObject]@{
                            ComputerName  = $server.ComputerName
                            InstanceName  = $server.ServiceName
                            SqlInstance   = $server.DomainInstanceName
                            Database      = $db.Name
                            Table         = $tbl
                            Cmd           = $query.ToString()
                            IdentityValue = $identityValue
                            ColumnValue   = $columnValue
                            Output        = $results
                        }
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbLogShipError.ps1
function Get-DbaDbLogShipError {
    <#
    .SYNOPSIS
        Get-DbaDbLogShipError returns all the log shipping errors that occurred

    .DESCRIPTION
        When your log shipping fails it's sometimes hard to see why is fails.
        Using this function you'll be able to find out what went wrong in a short amount of time.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Allows you to filter the results to only return the databases you're interested in. This can be one or more values separated by commas.
        This is not a wildcard and should be the exact database name. See examples for more info.

    .PARAMETER ExcludeDatabase
        Allows you to filter the results to only return the databases you're not interested in. This can be one or more values separated by commas.
        This is not a wildcard and should be the exact database name.

    .PARAMETER Action
        Filter to get the log shipping action that has occurred like Backup, Copy, Restore.
        By default all the actions are returned.

    .PARAMETER DateTimeFrom
        Filter the results based on the date starting from datetime X

    .PARAMETER DateTimeTo
        Filter the results based on the date ending with datetime X

    .PARAMETER Primary
        Allows to filter the results to only return values that apply to the primary instance.

    .PARAMETER Secondary
        Allows to filter the results to only return values that apply to the secondary instance.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: LogShipping
        Author: Sander Stad (@sqlstad), sqlstad.nl

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbLogShipError

    .EXAMPLE
        PS C:\> Get-DbaDbLogShipError -SqlInstance sql1

        Get all the log shipping errors that occurred

    .EXAMPLE
        PS C:\> Get-DbaDbLogShipError -SqlInstance sql1 -Action Backup

        Get the errors that have something to do with the backup of the databases

    .EXAMPLE
        PS C:\> Get-DbaDbLogShipError -SqlInstance sql1 -Secondary

        Get the errors that occurred on the secondary instance.
        This will return the copy of the restore actions because those only occur on the secondary instance

    .EXAMPLE
        PS C:\> Get-DbaDbLogShipError -SqlInstance sql1 -DateTimeFrom "01/05/2018"

        Get the errors that have occurred from "01/05/2018". This can also be of format "yyyy-MM-dd"

    .EXAMPLE
        PS C:\> Get-DbaDbLogShipError -SqlInstance sql1 -Secondary -DateTimeFrom "01/05/2018" -DateTimeTo "2018-01-07"

        Get the errors that have occurred between "01/05/2018" and "01/07/2018".
        See that is doesn't matter how the date is represented.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [string[]]$ExcludeDatabase,
        [ValidateSet("Backup", "Copy", "Restore")]
        [string[]]$Action,
        [datetime]$DateTimeFrom,
        [datetime]$DateTimeTo,
        [switch]$Primary,
        [switch]$Secondary,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($instance in $sqlinstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($server.EngineEdition -match "Express") {
                Write-Message -Level Warning -Message "$instance is Express Edition which does not support Log Shipping"
                continue
            }

            $query = "
CREATE TABLE #DatabaseID
(
    DatabaseName VARCHAR(128),
    DatabaseID UNIQUEIDENTIFIER,
    Instance VARCHAR(20)
);

INSERT INTO #DatabaseID
(
    DatabaseName,
    DatabaseID,
    Instance
)
SELECT secondary_database,
        secondary_id,
        'Secondary'
FROM msdb.dbo.log_shipping_secondary_databases;


INSERT INTO #DatabaseID
(
    DatabaseName,
    DatabaseID,
    Instance
)
SELECT primary_database,
        primary_id,
        'Primary'
FROM msdb.dbo.log_shipping_primary_databases;


SELECT di.DatabaseName,
        di.Instance,
        CASE lsmed.[agent_type]
            WHEN 0 THEN
                'Backup'
            WHEN 1 THEN
                'Copy'
            WHEN 2 THEN
                'Restore'
            ELSE
                ''
        END AS [Action],
        lsmed.[session_id] AS SessionID,
        lsmed.[sequence_number] AS SequenceNumber,
        lsmed.[log_time] AS LogTime,
        lsmed.[message] AS [Message]
FROM msdb.dbo.log_shipping_monitor_error_detail AS lsmed
    INNER JOIN #DatabaseID AS di
        ON di.DatabaseID = lsmed.agent_id
ORDER BY lsmed.[log_time],
            lsmed.[database_name],
            lsmed.[agent_type],
            lsmed.[session_id],
            lsmed.[sequence_number];

DROP TABLE #DatabaseID;"

            # Get the log shipping errors
            $results = $server.Query($query)

            if ($results.Count -ge 1) {

                # Filter the results
                if ($Database) {
                    $results = $results | Where-Object { $_.DatabaseName -in $Database }
                }

                if ($Action) {
                    $results = $results | Where-Object { $_.Action -in $Action }
                }

                if ($DateTimeFrom) {
                    $results = $results | Where-Object { $_.Logtime -ge $DateTimeFrom }
                }

                if ($DateTimeTo) {
                    $results = $results | Where-Object { $_.Logtime -le $DateTimeTo }
                }

                if ($Primary) {
                    $results = $results | Where-Object { $_.Instance -eq 'Primary' }
                }

                if ($Secondary) {
                    $results = $results | Where-Object { $_.Instance -eq 'Secondary' }
                }

                foreach ($result in $results) {
                    [PSCustomObject]@{
                        ComputerName   = $server.ComputerName
                        InstanceName   = $server.ServiceName
                        SqlInstance    = $server.DomainInstanceName
                        Database       = $result.DatabaseName
                        Instance       = $result.Instance
                        Action         = $result.Action
                        SessionID      = $result.SessionID
                        SequenceNumber = $result.SequenceNumber
                        LogTime        = $result.LogTime
                        Message        = $result.Message
                    }

                }
            } else {
                Write-Message -Message "No log shipping errors found" -Level Verbose
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Get-DbaLogShippingError
    }
}
tools\dbatools\functions\Get-DbaDbMail.ps1
function Get-DbaDbMail {
    <#
    .SYNOPSIS
        Gets the database mail from SQL Server

    .DESCRIPTION
        Gets the database mail from SQL Server

    .PARAMETER SqlInstance
        TThe target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DatabaseMail, DBMail, Mail
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbMail

    .EXAMPLE
        PS C:\> Get-DbaDbMail -SqlInstance sql01\sharepoint

        Returns the db mail server object on sql01\sharepoint

    .EXAMPLE
        PS C:\> Get-DbaDbMail -SqlInstance sql01\sharepoint | Select *

        Returns the db mail server object on sql01\sharepoint then return a bunch more columns

    .EXAMPLE
        PS C:\> $servers = "sql2014","sql2016", "sqlcluster\sharepoint"
        PS C:\> $servers | Get-DbaDbMail

        Returns the db mail server object for "sql2014","sql2016" and "sqlcluster\sharepoint"

    #>
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline, Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category Connectiondbmail -dbmailRecord $_ -Target $instance -Continue
            }

            try {
                $mailserver = $server.Mail
                Add-Member -Force -InputObject $mailserver -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                Add-Member -Force -InputObject $mailserver -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                Add-Member -Force -InputObject $mailserver -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                $mailserver | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, Profiles, Accounts, ConfigurationValues, Properties
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbMailAccount.ps1
function Get-DbaDbMailAccount {
    <#
    .SYNOPSIS
        Gets database mail accounts from SQL Server

    .DESCRIPTION
        Gets database mail accounts from SQL Server

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Account
        Specifies one or more account(s) to get. If unspecified, all accounts will be returned.

    .PARAMETER ExcludeAccount
        Specifies one or more account(s) to exclude.

    .PARAMETER InputObject
        Accepts pipeline input from Get-DbaDbMail

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DatabaseMail, DbMail, Mail
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MITIT

    .LINK
        https://dbatools.io/Get-DbaDbMailAccount

    .EXAMPLE
        PS C:\> Get-DbaDbMailAccount -SqlInstance sql01\sharepoint

        Returns Database Mail accounts on sql01\sharepoint

    .EXAMPLE
        PS C:\> Get-DbaDbMailAccount -SqlInstance sql01\sharepoint -Account 'The DBA Team'

        Returns The DBA Team Database Mail account from sql01\sharepoint

    .EXAMPLE
        PS C:\> Get-DbaDbMailAccount -SqlInstance sql01\sharepoint | Select *

        Returns the Database Mail accounts on sql01\sharepoint then return a bunch more columns

    .EXAMPLE
        PS C:\> $servers = "sql2014","sql2016", "sqlcluster\sharepoint"
        PS C:\> $servers | Get-DbaDbMail | Get-DbaDbMailAccount

        Returns the Database Mail accounts for "sql2014","sql2016" and "sqlcluster\sharepoint"

    #>
    [CmdletBinding()]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [string[]]$Account,
        [string[]]$ExcludeAccount,
        [Parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Mail.SqlMail[]]$InputObject,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaDbMail -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        }

        if (-not $InputObject) {
            Stop-Function -Message "No servers to process"
            return
        }

        foreach ($mailserver in $InputObject) {
            try {
                $accounts = $mailserver.Accounts

                if ($Account) {
                    $accounts = $accounts | Where-Object Name -in $Account
                }

                If ($ExcludeAccount) {
                    $accounts = $accounts | Where-Object Name -notin $ExcludeAccount
                }

                $accounts | Add-Member -Force -MemberType NoteProperty -Name ComputerName -value $mailserver.ComputerName
                $accounts | Add-Member -Force -MemberType NoteProperty -Name InstanceName -value $mailserver.InstanceName
                $accounts | Add-Member -Force -MemberType NoteProperty -Name SqlInstance -value $mailserver.SqlInstance
                $accounts | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, ID, Name, DisplayName, Description, EmailAddress, ReplyToAddress, IsBusyAccount, MailServers
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbMailConfig.ps1
function Get-DbaDbMailConfig {
    <#
    .SYNOPSIS
        Gets database mail configs from SQL Server

    .DESCRIPTION
        Gets database mail configs from SQL Server

    .PARAMETER SqlInstance
        TThe target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Name
        Specifies one or more config(s) to get. If unspecified, all configs will be returned.

    .PARAMETER InputObject
        Accepts pipeline input from Get-DbaDbMail

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DatabaseMail, DBMail, Mail
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbMailConfig

    .EXAMPLE
        PS C:\> Get-DbaDbMailConfig -SqlInstance sql01\sharepoint

        Returns DBMail configs on sql01\sharepoint

    .EXAMPLE
        PS C:\> Get-DbaDbMailConfig -SqlInstance sql01\sharepoint -Name ProhibitedExtensions

        Returns the ProhibitedExtensions configuration on sql01\sharepoint

    .EXAMPLE
        PS C:\> Get-DbaDbMailConfig -SqlInstance sql01\sharepoint | Select *

        Returns the DBMail configs on sql01\sharepoint then return a bunch more columns

    .EXAMPLE
        PS C:\> $servers = "sql2014","sql2016", "sqlcluster\sharepoint"
        PS C:\> $servers | Get-DbaDbMail | Get-DbaDbMailConfig

        Returns the DBMail configs for "sql2014","sql2016" and "sqlcluster\sharepoint"

    #>
    [CmdletBinding()]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Alias("Config", "ConfigName")]
        [string[]]$Name,
        [Parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Mail.SqlMail[]]$InputObject,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaDbMail -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        }

        if (-not $InputObject) {
            Stop-Function -Message "No servers to process"
            return
        }

        foreach ($mailserver in $InputObject) {
            try {
                $configs = $mailserver.ConfigurationValues

                if ($Name) {
                    $configs = $configs | Where-Object Name -in $Name
                }

                $configs | Add-Member -Force -MemberType NoteProperty -Name ComputerName -value $mailserver.ComputerName
                $configs | Add-Member -Force -MemberType NoteProperty -Name InstanceName -value $mailserver.InstanceName
                $configs | Add-Member -Force -MemberType NoteProperty -Name SqlInstance -value $mailserver.SqlInstance
                $configs | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, Name, Value, Description
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbMailHistory.ps1
function Get-DbaDbMailHistory {
    <#
    .SYNOPSIS
        Gets the history of mail sent from a SQL instance

    .DESCRIPTION
        Gets the history of mail sent from a SQL instance

    .PARAMETER SqlInstance
        TThe target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.

    .PARAMETER Since
        Datetime object used to narrow the results to the send request date

    .PARAMETER Status
        Narrow the results by status. Valid values include Unsent, Sent, Failed and Retrying

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DatabaseMail, DBMail, Mail
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbMailHistory

    .EXAMPLE
        PS C:\> Get-DbaDbMailHistory -SqlInstance sql01\sharepoint

        Returns the entire DBMail history on sql01\sharepoint

    .EXAMPLE
        PS C:\> Get-DbaDbMailHistory -SqlInstance sql01\sharepoint | Select *

        Returns the entire DBMail history on sql01\sharepoint then return a bunch more columns

    .EXAMPLE
        PS C:\> $servers = "sql2014","sql2016", "sqlcluster\sharepoint"
        PS C:\> $servers | Get-DbaDbMailHistory

        Returns the all DBMail history for "sql2014","sql2016" and "sqlcluster\sharepoint"

    #>
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]
        $SqlCredential,
        [DateTime]$Since,
        [ValidateSet('Unsent', 'Sent', 'Failed', 'Retrying')]
        [string]$Status,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category Connectiondbmail -dbmailRecord $_ -Target $instance -Continue
            }

            $sql = "SELECT SERVERPROPERTY('MachineName') AS ComputerName,
                    ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
                    SERVERPROPERTY('ServerName') AS SqlInstance,
                    mailitem_id as MailItemId,
                    a.profile_id as ProfileId,
                    p.name as Profile,
                    recipients as Recipients,
                    copy_recipients as CopyRecipients,
                    blind_copy_recipients as BlindCopyRecipients,
                    subject as Subject,
                    body as Body,
                    body_format as BodyFormat,
                    importance as Importance,
                    sensitivity as Sensitivity,
                    file_attachments as FileAttachments,
                    attachment_encoding as AttachmentEncoding,
                    query as Query,
                    execute_query_database as ExecuteQueryDatabase,
                    attach_query_result_as_file as AttachQueryResultAsFile,
                    query_result_header as QueryResultHeader,
                    query_result_width as QueryResultWidth,
                    query_result_separator as QueryResultSeparator,
                    exclude_query_output as ExcludeQueryOutput,
                    append_query_error as AppendQueryError,
                    send_request_date as SendRequestDate,
                    send_request_user as SendRequestUser,
                    sent_account_id as SentAccountId,
                    CASE sent_status
                    WHEN 'unsent' THEN 'Unsent'
                    WHEN 'sent' THEN 'Sent'
                    WHEN 'failed' THEN 'Failed'
                    WHEN 'retrying' THEN 'Retrying'
                    END AS SentStatus,
                    sent_date as SentDate,
                    last_mod_date as LastModDate,
                    a.last_mod_user as LastModUser
                    from msdb.dbo.sysmail_allitems a
                    join msdb.dbo.sysmail_profile p
                    on a.profile_id = p.profile_id"

            if ($Since -or $Status) {
                $wherearray = @()

                if ($Since) {
                    $wherearray += "send_request_date >= '$($Since.ToString("yyyy-MM-ddTHH:mm:ss"))'"
                }

                if ($Status) {
                    $Status = $Status -join "', '"
                    $wherearray += "sent_status in ('$Status')"
                }

                $wherearray = $wherearray -join ' and '
                $where = "where $wherearray"
                $sql = "$sql $where"
            }

            Write-Message -Level Debug -Message $sql

            try {
                $server.Query($sql) | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, Profile, Recipients, CopyRecipients, BlindCopyRecipients, Subject, Importance, Sensitivity, FileAttachments, AttachmentEncoding, SendRequestDate, SendRequestUser, SentStatus, SentDate
            } catch {
                Stop-Function -Message "Query failure" -ErrorRecord $_ -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbMailLog.ps1
function Get-DbaDbMailLog {
    <#
    .SYNOPSIS
        Gets the DBMail log from a SQL instance

    .DESCRIPTION
        Gets the DBMail log from a SQL instance

    .PARAMETER SqlInstance
        TThe target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.

    .PARAMETER Since
        Datetime object used to narrow the results to the send request date

    .PARAMETER Type
        Narrow the results by type. Valid values include Error, Warning, Success, Information, Internal

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DatabaseMail, DBMail, Mail
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbMailLog

    .EXAMPLE
        PS C:\> Get-DbaDbMailLog -SqlInstance sql01\sharepoint

        Returns the entire DBMail log on sql01\sharepoint

    .EXAMPLE
        PS C:\> Get-DbaDbMailLog -SqlInstance sql01\sharepoint | Select *

        Returns the entire DBMail log on sql01\sharepoint, includes all returned information.

    .EXAMPLE
        PS C:\> $servers = "sql2014","sql2016", "sqlcluster\sharepoint"
        PS C:\> $servers | Get-DbaDbMailLog -Type Error, Information

        Returns only the Error and Information DBMail log for "sql2014","sql2016" and "sqlcluster\sharepoint"

    #>
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]
        $SqlCredential,
        [DateTime]$Since,
        [ValidateSet('Error', 'Warning', 'Success', 'Information', 'Internal')]
        [string[]]$Type,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category Connectiondbmail -dbmailRecord $_ -Target $instance -Continue
            }

            $sql = "SELECT SERVERPROPERTY('MachineName') AS ComputerName,
            ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
            SERVERPROPERTY('ServerName') AS SqlInstance,
            log_id as LogId,
            CASE event_type
            WHEN 'error' THEN 'Error'
            WHEN 'warning' THEN 'Warning'
            WHEN 'information' THEN 'Information'
            WHEN 'success' THEN 'Success'
            WHEN 'internal' THEN 'Internal'
            ELSE event_type
            END as EventType,
            log_date as LogDate,
            REPLACE(description, CHAR(10)+')', '') as Description,
            process_id as ProcessId,
            mailitem_id as MailItemId,
            account_id as AccountId,
            last_mod_date as LastModDate,
            last_mod_user as LastModUser,
            last_mod_user as [Login]
            FROM msdb.dbo.sysmail_event_log"

            if ($Since -or $Type) {
                $wherearray = @()

                if ($Since) {
                    $wherearray += "log_date >= '$($Since.ToString("yyyy-MM-ddTHH:mm:ss"))'"
                }

                if ($Type) {
                    $combinedtype = $Type -join "', '"
                    $wherearray += "event_type in ('$combinedtype')"
                }

                $wherearray = $wherearray -join ' and '
                $where = "where $wherearray"
                $sql = "$sql $where"
            }

            Write-Message -Level Debug -Message $sql

            try {
                $server.Query($sql) | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, LogDate, EventType, Description, Login
            } catch {
                Stop-Function -Message "Failure" -InnerErrorRecord $_ -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbMailProfile.ps1
function Get-DbaDbMailProfile {
    <#
    .SYNOPSIS
        Gets database mail profiles from SQL Server

    .DESCRIPTION
        Gets database mail profiles from SQL Server

    .PARAMETER SqlInstance
        TThe target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Profile
        Specifies one or more profile(s) to get. If unspecified, all profiles will be returned.

    .PARAMETER ExcludeProfile
        Specifies one or more profile(s) to exclude.

    .PARAMETER InputObject
        Accepts pipeline input from Get-DbaDbMail

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DatabaseMail, DBMail, Mail
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbMailProfile

    .EXAMPLE
        PS C:\> Get-DbaDbMailProfile -SqlInstance sql01\sharepoint

        Returns DBMail profiles on sql01\sharepoint

    .EXAMPLE
        PS C:\> Get-DbaDbMailProfile -SqlInstance sql01\sharepoint -Profile 'The DBA Team'

        Returns The DBA Team DBMail profile from sql01\sharepoint

    .EXAMPLE
        PS C:\> Get-DbaDbMailProfile -SqlInstance sql01\sharepoint | Select *

        Returns the DBMail profiles on sql01\sharepoint then return a bunch more columns

    .EXAMPLE
        PS C:\> $servers = "sql2014","sql2016", "sqlcluster\sharepoint"
        PS C:\> $servers | Get-DbaDbMail | Get-DbaDbMailProfile

        Returns the DBMail profiles for "sql2014","sql2016" and "sqlcluster\sharepoint"

    #>
    [CmdletBinding()]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [string[]]$Profile,
        [string[]]$ExcludeProfile,
        [Parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Mail.SqlMail[]]$InputObject,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaDbMail -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        }

        if (-not $InputObject) {
            Stop-Function -Message "No servers to process"
            return
        }

        foreach ($mailserver in $InputObject) {
            try {
                $profiles = $mailserver.Profiles

                if ($Profile) {
                    $profiles = $profiles | Where-Object Name -in $Profile
                }

                If ($ExcludeProfile) {
                    $profiles = $profiles | Where-Object Name -notin $ExcludeProfile

                }

                $profiles | Add-Member -Force -MemberType NoteProperty -Name ComputerName -value $mailserver.ComputerName
                $profiles | Add-Member -Force -MemberType NoteProperty -Name InstanceName -value $mailserver.InstanceName
                $profiles | Add-Member -Force -MemberType NoteProperty -Name SqlInstance -value $mailserver.SqlInstance

                $profiles | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, ID, Name, Description, ForceDeleteForActiveProfiles, IsBusyProfile
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbMailServer.ps1
function Get-DbaDbMailServer {
    <#
    .SYNOPSIS
        Gets database mail servers from SQL Server

    .DESCRIPTION
        Gets database mail servers from SQL Server

    .PARAMETER SqlInstance
        TThe target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Server
        Specifies one or more server(s) to get. If unspecified, all servers will be returned.

    .PARAMETER Account
        Get only the mail server associated with specific accounts

    .PARAMETER InputObject
        Accepts pipeline input from Get-DbaDbMail

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DatabaseMail, DBMail, Mail
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbMailServer

    .EXAMPLE
        PS C:\> Get-DbaDbMailServer -SqlInstance sql01\sharepoint

        Returns all DBMail servers on sql01\sharepoint

    .EXAMPLE
        PS C:\> Get-DbaDbMailServer -SqlInstance sql01\sharepoint -Server DbaTeam

        Returns The DBA Team DBMail server from sql01\sharepoint

    .EXAMPLE
        PS C:\> Get-DbaDbMailServer -SqlInstance sql01\sharepoint | Select *

        Returns the DBMail servers on sql01\sharepoint then return a bunch more columns

    .EXAMPLE
        PS C:\> $servers = "sql2014","sql2016", "sqlcluster\sharepoint"
        PS C:\> $servers | Get-DbaDbMail | Get-DbaDbMailServer

        Returns the DBMail servers for "sql2014","sql2016" and "sqlcluster\sharepoint"

    #>
    [CmdletBinding()]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Alias("Name")]
        [string[]]$Server,
        [string[]]$Account,
        [Parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Mail.SqlMail[]]$InputObject,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaDbMail -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        }

        if (-not $InputObject) {
            Stop-Function -Message "No servers to process"
            return
        }

        foreach ($mailserver in $InputObject) {
            try {
                $accounts = $mailserver | Get-DbaDbMailAccount -Account $Account
                $servers = $accounts.MailServers

                if ($Server) {
                    $servers = $servers | Where-Object Name -in $Server
                }

                if ($servers) {
                    $servers | Add-Member -Force -MemberType NoteProperty -Name ComputerName -value $mailserver.ComputerName
                    $servers | Add-Member -Force -MemberType NoteProperty -Name InstanceName -value $mailserver.InstanceName
                    $servers | Add-Member -Force -MemberType NoteProperty -Name SqlInstance -value $mailserver.SqlInstance
                    $servers | Add-Member -Force -MemberType NoteProperty -Name Account -value $servers[0].Parent.Name
                    $servers | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, Account, Name, Port, EnableSsl, ServerType, UserName, UseDefaultCredentials, NoCredentialChange
                }
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbMasterKey.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaDbMasterKey {
    <#
    .SYNOPSIS
        Gets specified database master key

    .DESCRIPTION
        Gets specified database master key

    .PARAMETER SqlInstance
        The target SQL Server instance

    .PARAMETER SqlCredential
        Allows you to login to SQL Server using alternative credentials

    .PARAMETER Database
        Get master key from specific database

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER InputObject
        Database object piped in from Get-DbaDatabase

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Certificate, Database
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaDbMasterKey -SqlInstance sql2016

        Gets all master database keys

    .EXAMPLE
        PS C:\> Get-DbaDbMasterKey -SqlInstance Server1 -Database db1

        Gets the master key for the db1 database

    #>
    [CmdletBinding()]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [string[]]$ExcludeDatabase,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )

    process {
        if ($SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $SqlInstance -Database $Database -ExcludeDatabase $ExcludeDatabase
        }

        foreach ($db in $InputObject) {
            if (!$db.IsAccessible) {
                Write-Message -Level Warning -Message "Database $db on $($db.Parent) is not accessible. Skipping."
                continue
            }

            $masterkey = $db.MasterKey

            if (!$masterkey) {
                Write-Message -Message "No master key exists in the $db database on $instance" -Target $db -Level Verbose
                continue
            }

            Add-Member -Force -InputObject $masterkey -MemberType NoteProperty -Name ComputerName -value $db.Parent.ComputerName
            Add-Member -Force -InputObject $masterkey -MemberType NoteProperty -Name InstanceName -value $db.Parent.ServiceName
            Add-Member -Force -InputObject $masterkey -MemberType NoteProperty -Name SqlInstance -value $db.Parent.DomainInstanceName
            Add-Member -Force -InputObject $masterkey -MemberType NoteProperty -Name Database -value $db.Name

            Select-DefaultView -InputObject $masterkey -Property ComputerName, InstanceName, SqlInstance, Database, CreateDate, DateLastModified, IsEncryptedByServer
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaDatabaseMasterKey
    }
}
tools\dbatools\functions\Get-DbaDbMemoryUsage.ps1
function Get-DbaDbMemoryUsage {
    <#
    .SYNOPSIS
        Determine buffer pool usage by database.

    .DESCRIPTION
        This command can be utilized to determine which databases on a given instance are consuming buffer pool memory.

        This command is based on query provided by Aaron Bertrand.
        Reference: https://www.mssqltips.com/sqlservertip/2393/determine-sql-server-memory-use-by-database-and-object/

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential).

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude.

    .PARAMETER IncludeSystemDb
        Switch to have the output include system database memory consumption.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Memory, Database
        Author: Shawn Melton (@wsmelton), https://wsmelton.github.io

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbMemoryUsage

    .EXAMPLE
        PS C:\> Get-DbaDbMemoryUsage -SqlInstance sqlserver2014a

        Returns the buffer pool consumption for all user databases

    .EXAMPLE
        PS C:\> Get-DbaDbMemoryUsage -SqlInstance sqlserver2014a -IncludeSystemDb

        Returns the buffer pool consumption for all user databases and system databases

    .EXAMPLE
        PS C:\> Get-DbaDbMemoryUsage -SqlInstance sql1 -IncludeSystemDb -Database tempdb

        Returns the buffer pool consumption for tempdb database only

    .EXAMPLE
        PS C:\> Get-DbaDbMemoryUsage -SqlInstance sql2 -IncludeSystemDb -Exclude 'master','model','msdb','ResourceDb'

        Returns the buffer pool consumption for all user databases and tempdb database
    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(ValueFromPipelineByPropertyName = $true)]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$IncludeSystemDb,
        [switch]$EnableException
    )

    begin {
        $sql = "DECLARE @total_buffer INT;
            SELECT @total_buffer = cntr_value
            FROM sys.dm_os_performance_counters
            WHERE RTRIM([object_name]) LIKE '%Buffer Manager'
            AND counter_name = 'Database Pages';

            ;WITH src AS (
                SELECT database_id, page_type, db_buffer_pages = COUNT_BIG(*)
                FROM sys.dm_os_buffer_descriptors
                GROUP BY database_id, page_type
            )
            SELECT [DatabaseName] = CASE [database_id] WHEN 32767 THEN 'ResourceDb' ELSE DB_NAME([database_id]) END,
                page_type AS 'PageType',
                db_buffer_pages AS 'PageCount',
                (db_buffer_pages * 8)/1024 AS 'SizeMb',
                CAST(db_buffer_pages * 100.0 / @total_buffer AS FLOAT) AS 'PercentUsed'
            FROM src
            ORDER BY [DatabaseName];"
    }
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            try {
                $results = $server.Query($sql)
            } catch {
                Stop-Function -Message "Issue collecting data" -Target $instance -ErrorRecord $_
            }
            foreach ($row in $results) {
                if (Test-Bound 'Database') {
                    if ($row.DatabaseName -notin $Database) { continue }
                }
                if (Test-Bound 'ExcludeDatabase') {
                    if ($row.DatabaseName -in $ExcludeDatabase) { continue }
                }
                if (Test-Bound -Not 'IncludeSystemDb') {
                    if ($row.DatabaseName -in 'master', 'model', 'msdb', 'tempdb', 'ResourceDb') { continue }
                }

                if ($row.PercentUsed -is [System.DBNull]) {
                    $percentUsed = 0
                } else {
                    $percentUsed = [Math]::Round($row.PercentUsed)
                }

                [PSCustomObject]@{
                    ComputerName = $server.ComputerName
                    InstanceName = $server.ServiceName
                    SqlInstance  = $server.DomainInstanceName
                    Database     = $row.DatabaseName
                    PageType     = $row.PageType
                    PageCount    = [int]$row.PageCount
                    Size         = [DbaSize]$row.SizeMb * 1024
                    PercentUsed  = $percentUsed
                } | Select-DefaultView -ExcludeProperty 'PageCount'
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbMirror.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaDbMirror {
    <#
    .SYNOPSIS
        Gets properties of database mirrors and mirror witnesses.

    .DESCRIPTION
        Gets properties of database mirrors and mirror witnesses.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function
        to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Mirror, HA
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbMirror

    .EXAMPLE
        PS C:\> Get-DbaDbMirror -SqlInstance localhost

        Gets properties of database mirrors and mirror witnesses on localhost

    .EXAMPLE
        PS C:\> Get-DbaDbMirror -SqlInstance localhost, sql2016

        Gets properties of database mirrors and mirror witnesses on localhost and sql2016 SQL Server instances

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            $dbs = Get-DbaDatabase -SqlInstance $instance -SqlCredential $SqlCredential
            $partners = $dbs | Where-Object MirroringPartner
            $partners | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, Name, MirroringSafetyLevel, MirroringStatus, MirroringPartner, MirroringPartnerInstance, MirroringFailoverLogSequenceNumber, MirroringID, MirroringRedoQueueMaxSize, MirroringRoleSequence, MirroringSafetySequence, MirroringTimeout, MirroringWitness, MirroringWitnessStatus

            # The witness is kinda hidden. Go get it manually.
            try {
                $witnesses = $dbs[0].Parent.Query("select distinct database_name, principal_server_name, safety_level, safety_level_desc, partner_sync_state from master.sys.database_mirroring_witnesses")
            } catch { continue }

            foreach ($witness in $witnesses) {
                $witnessdb = $dbs | Where-Object Name -eq $witness.database_name
                $status = switch ($witness.partner_sync_state) {
                    0 { "None" }
                    1 { "Suspended" }
                    2 { "Disconnected" }
                    3 { "Synchronizing" }
                    4 { "PendingFailover" }
                    5 { "Synchronized" }
                }

                foreach ($db in $witnessdb) {
                    Add-Member -InputObject $db -Force -MemberType NoteProperty -Name MirroringPartner -Value $witness.principal_server_name
                    Add-Member -InputObject $db -Force -MemberType NoteProperty -Name MirroringSafetyLevel -Value $witness.safety_level_desc
                    Add-Member -InputObject $db -Force -MemberType NoteProperty -Name MirroringWitnessStatus -Value $status
                    Select-DefaultView -InputObject $db -Property ComputerName, InstanceName, SqlInstance, Name, MirroringSafetyLevel, MirroringStatus, MirroringPartner, MirroringPartnerInstance, MirroringFailoverLogSequenceNumber, MirroringID, MirroringRedoQueueMaxSize, MirroringRoleSequence, MirroringSafetySequence, MirroringTimeout, MirroringWitness, MirroringWitnessStatus
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbMirrorMonitor.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaDbMirrorMonitor {
    <#
    .SYNOPSIS
        Returns status rows for a monitored database from the status table in which database mirroring monitoring history is stored and allows you to choose whether the procedure obtains the latest status beforehand.

    .DESCRIPTION
        Returns status rows for a monitored database from the status table in which database mirroring monitoring history is stored and allows you to choose whether the procedure obtains the latest status beforehand.

        Basically executes sp_dbmmonitorresults.

    .PARAMETER SqlInstance
        The target SQL Server instance

    .PARAMETER SqlCredential
        Login to the target instance using alternate Windows or SQL Login Authentication. Accepts credential objects (Get-Credential).

    .PARAMETER Database
        The target database.

    .PARAMETER Database
        The target database.

    .PARAMETER Update
        Updates the status for the database by calling sp_dbmmonitorupdate before computing the results.
        However, if the status table has been updated within the previous 15 seconds, or the user is not a member of the sysadmin fixed server role, the command runs without updating the status.

    .PARAMETER LimitResults
        Limit results. Defaults to last two hours.

        Options include:
        LastRow
        LastTwoHours
        LastFourHours
        LastEightHours
        LastDay
        LastTwoDays
        Last100Rows
        Last500Rows
        Last1000Rows
        Last1000000Rows

    .PARAMETER InputObject
        Allows piping from Get-DbaDatabase.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Mirror, HA
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbMirrorMonitor

    .EXAMPLE
        PS C:\> Get-DbaDbMirrorMonitor -SqlInstance sql2008, sql2012

        Returns last two hours' worth of status rows for a monitored database from the status table on sql2008 and sql2012.

    .EXAMPLE
        PS C:\> Get-DbaDbMirrorMonitor -SqlInstance sql2005 -LimitResults LastDay -Update

        Updates monitor stats then returns the last 24 hours worth of status rows for a monitored database from the status table on sql2008 and sql2012.

    #>
    [CmdletBinding()]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$Update,
        [ValidateSet('LastRow', 'LastTwoHours', 'LastFourHours', 'LastEightHours', 'LastDay', 'LastTwoDays', 'Last100Rows', 'Last500Rows', 'Last1000Rows', 'Last1000000Rows')]
        [string]$LimitResults = 'LastTwoHours',
        [switch]$EnableException
    )
    begin {
        $rows = switch ($LimitResults) {
            'LastRow' { 0 }
            'LastTwoHours' { 1 }
            'LastFourHours' { 2 }
            'LastEightHours' { 3 }
            'LastDay' { 4 }
            'LastTwoDays' { 5 }
            'Last100Rows' { 6 }
            'Last500Rows' { 7 }
            'Last1000000Rows' { 8 }
        }
        $updatebool = switch ($Update) {
            $false { 0 }
            $true { 1 }
        }
    }
    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $instance -SqlCredential $SqlCredential -Database $Database
        }

        foreach ($db in $InputObject) {
            if (-not ($db.Parent.Databases['msdb'].Tables['dbm_monitor_data'].Name)) {
                Stop-Function -Continue -Message "msdb.dbo.dbm_monitor_data not found. Please run Add-DbaDbMirrorMonitor then you can get monitor stats."
            }
            try {
                $sql = "msdb.dbo.sp_dbmmonitorresults $db, $rows, $updatebool"
                $results = $db.Parent.Query($sql)

                foreach ($result in $results) {
                    [pscustomobject]@{
                        ComputerName          = $db.Parent.ComputerName
                        InstanceName          = $db.Parent.ServiceName
                        SqlInstance           = $db.Parent.DomainInstanceName
                        DatabaseName          = $result.database_name
                        Role                  = $result.role
                        MirroringState        = $result.mirroring_state
                        WitnessStatus         = $result.witness_status
                        LogGenerationRate     = $result.log_generation_rate
                        UnsentLog             = $result.unsent_log
                        SendRate              = $result.send_rate
                        UnrestoredLog         = $result.unrestored_log
                        RecoveryRate          = $result.recovery_rate
                        TransactionDelay      = $result.transaction_delay
                        TransactionsPerSecond = $result.transactions_per_sec
                        AverageDelay          = $result.average_delay
                        TimeRecorded          = $result.time_recorded
                        TimeBehind            = $result.time_behind
                        LocalTime             = $result.local_time
                    }
                }
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbOrphanUser.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaDbOrphanUser {
    <#
    .SYNOPSIS
        Get orphaned users.

    .DESCRIPTION
        An orphan user is defined by a user that does not have their matching login. (Login property = "").

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Orphan, Database, User, Security, Login
        Author: Claudio Silva (@ClaudioESSilva) | Garry Bargsley (@gbargsley) | Simone Bizzotto (@niphlod)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbOrphanUser

    .EXAMPLE
        PS C:\> Get-DbaDbOrphanUser -SqlInstance localhost\sql2016

        Finds all orphan users without matching Logins in all databases present on server 'localhost\sql2016'.

    .EXAMPLE
        PS C:\> Get-DbaDbOrphanUser -SqlInstance localhost\sql2016 -SqlCredential $cred

        Finds all orphan users without matching Logins in all databases present on server 'localhost\sql2016'. SQL Server authentication will be used in connecting to the server.

    .EXAMPLE
        PS C:\> Get-DbaDbOrphanUser -SqlInstance localhost\sql2016 -Database db1

        Finds orphan users without matching Logins in the db1 database present on server 'localhost\sql2016'.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Write-Message -Level Warning -Message "Failed to connect to: $instance."
                continue
            }
            $DatabaseCollection = $server.Databases | Where-Object IsAccessible

            if ($Database) {
                $DatabaseCollection = $DatabaseCollection | Where-Object Name -In $Database
            }
            if ($ExcludeDatabase) {
                $DatabaseCollection = $DatabaseCollection | Where-Object Name -NotIn $ExcludeDatabase
            }

            if ($DatabaseCollection.Count -gt 0) {
                foreach ($db in $DatabaseCollection) {
                    try {
                        #if SQL 2012 or higher only validate databases with ContainmentType = NONE
                        if ($server.versionMajor -gt 10) {
                            if ($db.ContainmentType -ne [Microsoft.SqlServer.Management.Smo.ContainmentType]::None) {
                                Write-Message -Level Warning -Message "Database '$db' is a contained database. Contained databases can't have orphaned users. Skipping validation."
                                Continue
                            }
                        }
                        Write-Message -Level Verbose -Message "Validating users on database '$db'."
                        $UsersToWork = $db.Users | Where-Object { $_.Login -eq "" -and ($_.ID -gt 4) -and (($_.Sid.Length -gt 16 -and $_.LoginType -in @([Microsoft.SqlServer.Management.Smo.LoginType]::SqlLogin, [Microsoft.SqlServer.Management.Smo.LoginType]::Certificate)) -eq $false) }

                        if ($UsersToWork.Count -gt 0) {
                            Write-Message -Level Verbose -Message "Orphan users found"
                            foreach ($user in $UsersToWork) {
                                [PSCustomObject]@{
                                    ComputerName = $server.ComputerName
                                    InstanceName = $server.ServiceName
                                    SqlInstance  = $server.DomainInstanceName
                                    DatabaseName = $db.Name
                                    User         = $user.Name
                                }
                            }
                        } else {
                            Write-Message -Level Verbose -Message "No orphan users found on database '$db'."
                        }
                        #reset collection
                        $UsersToWork = $null
                    } catch {
                        Stop-Function -Message $_ -Continue
                    }
                }
            } else {
                Write-Message -Level VeryVerbose -Message "There are no databases to analyse."
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Alias Get-DbaOrphanUser
    }
}
tools\dbatools\functions\Get-DbaDbPageInfo.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Get-DbaDbPageInfo {
    <#
    .SYNOPSIS
        Get-DbaDbPageInfo will return page information for a database

    .DESCRIPTION
        Get-DbaDbPageInfo is able to return information about the pages in a database.
        It's possible to return the information for multiple databases and filter on specific databases, schemas and tables.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Filter to only get specific databases

    .PARAMETER Schema
        Filter to only get specific schemas

    .PARAMETER Table
        Filter to only get specific tables

    .PARAMETER InputObject
        Enables piping from Get-DbaDatabase

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database, Page
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbPageInfo

    .EXAMPLE
        PS C:\> et-DbaDbPageInfo -SqlInstance sql2017

        Returns page information for all databases on sql2017

    .EXAMPLE
        PS C:\> Get-DbaDbPageInfo -SqlInstance sql2017, sql2016 -Database testdb

        Returns page information for the testdb on sql2017 and sql2016

    .EXAMPLE
        PS C:\> $servers | Get-DbaDatabase -Database testdb | Get-DbaDbPageInfo

        Returns page information for the testdb on all $servers

    #>
    [CmdLetBinding()]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [string[]]$Schema,
        [string[]]$Table,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )
    begin {
        $sql = "SELECT SERVERPROPERTY('MachineName') AS ComputerName,
        ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
        SERVERPROPERTY('ServerName') AS SqlInstance, [Database] = DB_NAME(DB_ID()),
        ss.name AS [Schema], st.name AS [Table], dbpa.page_type_desc AS PageType,
                        dbpa.page_free_space_percent AS PageFreePercent,
                        IsAllocated =
                          CASE dbpa.is_allocated
                             WHEN 0 THEN 'False'
                             WHEN 1 THEN 'True'
                          END,
                        IsMixedPage =
                          CASE dbpa.is_mixed_page_allocation
                             WHEN 0 THEN 'False'
                             WHEN 1 THEN 'True'
                          END
                        FROM sys.dm_db_database_page_allocations(DB_ID(), NULL, NULL, NULL, 'DETAILED') AS dbpa
                        INNER JOIN sys.tables AS st ON st.object_id = dbpa.object_id
                        INNER JOIN sys.schemas AS ss ON ss.schema_id = st.schema_id"

        if ($Schema) {
            $sql = "$sql WHERE ss.name IN ('$($Schema -join "','")')"
        }

        if ($Table) {
            if ($schema) {
                $sql = "$sql AND st.name IN ('$($Table -join "','")')"
            } else {
                $sql = "$sql WHERE st.name IN ('$($Table -join "','")')"
            }
        }
    }
    process {
        # Loop through all the instances
        foreach ($instance in $SqlInstance) {

            # Try connecting to the instance
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 11
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($Database) {
                $InputObject += $server.Databases | Where-Object { $_.Name -in $Database }
            } else {
                $InputObject += $server.Databases
            }
        }

        # Loop through each of databases
        foreach ($db in $InputObject) {
            # Revalidate the version of the server in case db is piped in
            try {
                if ($db.Parent.VersionMajor -ge 11) {
                    $db.Query($sql)
                } else {
                    Stop-Function -Message "Unsupported SQL Server version" -Target $db -Continue
                }
            } catch {
                Stop-Function -Message "Something went wrong executing the query" -ErrorRecord $_ -Target $instance -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbPartitionFunction.ps1
function Get-DbaDbPartitionFunction {
    <#
    .SYNOPSIS
        Gets database Partition Functions

    .DESCRIPTION
        Gets database Partition Functions

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Allows you to login to SQL Server using alternative credentials

    .PARAMETER Database
        To get users from specific database(s)

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto populated from the server

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database
        Author: Klaas Vandenberghe ( @PowerDbaKlaas )

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaDbPartitionFunction -SqlInstance sql2016

        Gets all database Partition Functions

    .EXAMPLE
        PS C:\> Get-DbaDbPartitionFunction -SqlInstance Server1 -Database db1

        Gets the Partition Functions for the db1 database

    .EXAMPLE
        PS C:\> Get-DbaDbPartitionFunction -SqlInstance Server1 -ExcludeDatabase db1

        Gets the Partition Functions for all databases except db1

    .EXAMPLE
        PS C:\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbPartitionFunction

        Gets the Partition Functions for the databases on Sql1 and Sql2/sqlexpress

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $databases = $server.Databases | Where-Object IsAccessible

            if ($Database) {
                $databases = $databases | Where-Object Name -In $Database
            }
            if ($ExcludeDatabase) {
                $databases = $databases | Where-Object Name -NotIn $ExcludeDatabase
            }

            foreach ($db in $databases) {
                if (!$db.IsAccessible) {
                    Write-Message -Level Warning -Message "Database $db is not accessible. Skipping."
                    continue
                }

                $partitionfunctions = $db.partitionfunctions

                if (!$partitionfunctions) {
                    Write-Message -Message "No Partition Functions exist in the $db database on $instance" -Target $db -Level Verbose
                    continue
                }

                $partitionfunctions | ForEach-Object {

                    Add-Member -Force -InputObject $_ -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                    Add-Member -Force -InputObject $_ -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                    Add-Member -Force -InputObject $_ -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                    Add-Member -Force -InputObject $_ -MemberType NoteProperty -Name Database -value $db.Name

                    Select-DefaultView -InputObject $_ -Property ComputerName, InstanceName, SqlInstance, Database, CreateDate, Name, NumberOfPartitions
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaDatabasePartitionFunction
    }
}
tools\dbatools\functions\Get-DbaDbPartitionScheme.ps1
function Get-DbaDbPartitionScheme {
    <#
    .SYNOPSIS
        Gets database Partition Schemes

    .DESCRIPTION
        Gets database Partition Schemes

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Allows you to login to SQL Server using alternative credentials

    .PARAMETER Database
        To get users from specific database(s)

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto populated from the server

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database
        Author: Klaas Vandenberghe (@PowerDbaKlaas)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaDbPartitionScheme -SqlInstance sql2016

        Gets all database Partition Schemes

    .EXAMPLE
        PS C:\> Get-DbaDbPartitionScheme -SqlInstance Server1 -Database db1

        Gets the Partition Schemes for the db1 database

    .EXAMPLE
        PS C:\> Get-DbaDbPartitionScheme -SqlInstance Server1 -ExcludeDatabase db1

        Gets the Partition Schemes for all databases except db1

    .EXAMPLE
        PS C:\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbPartitionScheme

        Gets the Partition Schemes for the databases on Sql1 and Sql2/sqlexpress

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $databases = $server.Databases | Where-Object IsAccessible

            if ($Database) {
                $databases = $databases | Where-Object Name -In $Database
            }
            if ($ExcludeDatabase) {
                $databases = $databases | Where-Object Name -NotIn $ExcludeDatabase
            }

            foreach ($db in $databases) {
                if (!$db.IsAccessible) {
                    Write-Message -Level Warning -Message "Database $db is not accessible. Skipping."
                    continue
                }

                $PartitionSchemes = $db.PartitionSchemes

                if (!$PartitionSchemes) {
                    Write-Message -Message "No Partition Schemes exist in the $db database on $instance" -Target $db -Level Verbose
                    continue
                }

                $PartitionSchemes | ForEach-Object {

                    Add-Member -Force -InputObject $_ -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                    Add-Member -Force -InputObject $_ -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                    Add-Member -Force -InputObject $_ -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                    Add-Member -Force -InputObject $_ -MemberType NoteProperty -Name Database -value $db.Name

                    Select-DefaultView -InputObject $_ -Property ComputerName, InstanceName, SqlInstance, Database, Name, PartitionFunction
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaDatabasePartitionScheme
    }
}
tools\dbatools\functions\Get-DbaDbQueryStoreOption.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Get-DbaDbQueryStoreOption {
    <#
    .SYNOPSIS
        Get the Query Store configuration for Query Store enabled databases.

    .DESCRIPTION
        Retrieves and returns the Query Store configuration for every database that has the Query Store feature enabled.

    .OUTPUTS
        Microsoft.SqlServer.Management.Smo.QueryStoreOptions

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        SqlCredential object used to connect to the SQL Server as a different user.

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: QueryStore
        Author: Enrico van de Laar (@evdlaar) | Klaas Vandenberghe (@PowerDBAKlaas)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaQueryStoreOptions

    .EXAMPLE
        PS C:\> Get-DbaDbQueryStoreOption -SqlInstance ServerA\sql

        Returns Query Store configuration settings for every database on the ServerA\sql instance.

    .EXAMPLE
        PS C:\> Get-DbaDbQueryStoreOption -SqlInstance ServerA\sql | Where-Object {$_.ActualState -eq "ReadWrite"}

        Returns the Query Store configuration for all databases on ServerA\sql where the Query Store feature is in Read/Write mode.

    .EXAMPLE
        PS C:\> Get-DbaDbQueryStoreOption -SqlInstance localhost | format-table -AutoSize -Wrap

        Returns Query Store configuration settings for every database on the ServerA\sql instance inside a table format.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]
        $SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        $ExcludeDatabase += 'master', 'tempdb'
    }
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 13
            } catch {
                Write-Message -Level Warning -Message "Can't connect to $instance. Moving on."
                continue
            }

            # We have to exclude all the system databases since they cannot have the Query Store feature enabled
            $dbs = Get-DbaDatabase -SqlInstance $server -ExcludeDatabase $ExcludeDatabase -Database $Database | Where-Object IsAccessible

            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Processing $($db.Name) on $instance"
                $QSO = $db.QueryStoreOptions

                Add-Member -Force -InputObject $QSO -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                Add-Member -Force -InputObject $QSO -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                Add-Member -Force -InputObject $QSO -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                Add-Member -Force -InputObject $QSO -MemberType NoteProperty Database -value $db.Name
                Select-DefaultView -InputObject $QSO -Property ComputerName, InstanceName, SqlInstance, Database, ActualState, DataFlushIntervalInSeconds, StatisticsCollectionIntervalInMinutes, MaxStorageSizeInMB, CurrentStorageSizeInMB, QueryCaptureMode, SizeBasedCleanupMode, StaleQueryThresholdInDays
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaDbQueryStoreOptions
    }
}
tools\dbatools\functions\Get-DbaDbRecoveryModel.ps1
function Get-DbaDbRecoveryModel {
    <#
    .SYNOPSIS
        Get-DbaDbRecoveryModel displays the Recovery Model.

    .DESCRIPTION
        Get-DbaDbRecoveryModel displays the Recovery Model for all databases. This is the default, you can filter using -Database, -ExcludeDatabase, -RecoveryModel

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. if unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER RecoveryModel
        Filters the output based on Recovery Model. Valid options are Simple, Full and BulkLogged

        Details about the recovery models can be found here:
        https://docs.microsoft.com/en-us/sql/relational-databases/backup-restore/recovery-models-sql-server

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Recovery, RecoveryModel, Simple, Full, Bulk, BulkLogged
        Author: Viorel Ciucu (@viorelciucu), https://www.cviorel.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbRecoveryModel

    .EXAMPLE
        PS C:\> Get-DbaDbRecoveryModel -SqlInstance sql2014 -RecoveryModel BulkLogged -Verbose

        Gets all databases on SQL Server instance sql2014 having RecoveryModel set to BulkLogged.

    .EXAMPLE
        PS C:\> Get-DbaDbRecoveryModel -SqlInstance sql2014 -Database TestDB

        Gets recovery model information for TestDB. If TestDB does not exist on the instance nothing is returned.

       #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [ValidateSet('Simple', 'Full', 'BulkLogged')]
        [string[]]$RecoveryModel,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$EnableException
    )
    begin {
        $defaults = 'ComputerName', 'InstanceName', 'SqlInstance', 'Name', 'Status', 'IsAccessible', 'RecoveryModel',
        'LastBackupDate as LastFullBackup', 'LastDifferentialBackupDate as LastDiffBackup',
        'LastLogBackupDate as LastLogBackup'
    }
    process {
        $params = @{
            SqlInstance     = $SqlInstance
            SqlCredential   = $SqlCredential
            Database        = $Database
            ExcludeDatabase = $ExcludeDatabase
            EnableException = $EnableException
        }

        if ($RecoveryModel) {
            Get-DbaDatabase @params | Where-Object RecoveryModel -in $RecoveryModel | Where-Object IsAccessible | Select-DefaultView -Property $defaults
        } else {
            Get-DbaDatabase @params | Select-DefaultView -Property $defaults
        }
    }
}
tools\dbatools\functions\Get-DbaDbRestoreHistory.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaDbRestoreHistory {
    <#
    .SYNOPSIS
        Returns restore history details for databases on a SQL Server.

    .DESCRIPTION
        By default, this command will return the server name, database, username, restore type, date, from file and to files.

        Thanks to https://www.mssqltips.com/SqlInstancetip/1724/when-was-the-last-time-your-sql-server-database-was-restored/ for the query and https://sqlstudies.com/2016/07/27/when-was-this-database-restored/ for the idea.

    .PARAMETER SqlInstance
        Specifies the SQL Server instance(s) to operate on. Requires SQL Server 2005 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.

    .PARAMETER Since
        Specifies a datetime to use as the starting point for searching backup history.

    .PARAMETER Force
        Deprecated.

    .PARAMETER Last
        If this switch is enabled, the last restore action performed on each database is returned.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DisasterRecovery, Backup, Restore
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbRestoreHistory

    .EXAMPLE
        PS C:\> Get-DbaDbRestoreHistory -SqlInstance sql2016

        Returns server name, database, username, restore type, date for all restored databases on sql2016.

    .EXAMPLE
        PS C:\> Get-DbaDbRestoreHistory -SqlInstance sql2016 -Database db1, db2 -Since '2016-07-01 10:47:00'

        Returns restore information only for databases db1 and db2 on sql2016 since July 1, 2016 at 10:47 AM.

    .EXAMPLE
        PS C:\> Get-DbaDbRestoreHistory -SqlInstance sql2014, sql2016 -Exclude db1

        Returns restore information for all databases except db1 on sql2014 and sql2016.

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> Get-DbaDbRestoreHistory -SqlInstance sql2014 -Database AdventureWorks2014, pubs -SqlCredential $cred | Format-Table

        Returns database restore information for AdventureWorks2014 and pubs database on sql2014, connects using SQL Authentication via sqladmin account. Formats the data as a table.

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sql2016 | Get-DbaDbRestoreHistory

        Returns database restore information for every database on every server listed in the Central Management Server on sql2016.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [datetime]$Since,
        [switch]$Force,
        [switch]$Last,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        Test-DbaDeprecation -DeprecatedOn "1.0.0.0" -EnableException:$false -Parameter 'Force'

        if ($Since -ne $null) {
            $Since = $Since.ToString("yyyy-MM-ddTHH:mm:ss")
        }
    }

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
                $computername = $server.ComputerName
                $instancename = $server.ServiceName
                $servername = $server.DomainInstanceName

                if ($force -eq $true) {
                    $select = "SELECT '$computername' AS [ComputerName],
                    '$instancename' AS [InstanceName],
                    '$servername' AS [SqlInstance], * "
                } else {
                    $select = "SELECT
                    '$computername' AS [ComputerName],
                    '$instancename' AS [InstanceName],
                    '$servername' AS [SqlInstance],
                     rsh.destination_database_name AS [Database],
                     --rsh.restore_history_id as RestoreHistoryID,
                     rsh.user_name AS [Username],
                     CASE
                         WHEN rsh.restore_type = 'D' THEN 'Database'
                         WHEN rsh.restore_type = 'F' THEN 'File'
                         WHEN rsh.restore_type = 'G' THEN 'Filegroup'
                         WHEN rsh.restore_type = 'I' THEN 'Differential'
                         WHEN rsh.restore_type = 'L' THEN 'Log'
                         WHEN rsh.restore_type = 'V' THEN 'Verifyonly'
                         WHEN rsh.restore_type = 'R' THEN 'Revert'
                         ELSE rsh.restore_type
                     END AS [RestoreType],
                     rsh.restore_date AS [Date],
                     ISNULL(STUFF((SELECT ', ' + bmf.physical_device_name
                                    FROM msdb.dbo.backupmediafamily bmf
                                   WHERE bmf.media_set_id = bs.media_set_id
                                 FOR XML PATH('')), 1, 2, ''), '') AS [From],
                     ISNULL(STUFF((SELECT ', ' + rf.destination_phys_name
                                    FROM msdb.dbo.restorefile rf
                                   WHERE rsh.restore_history_id = rf.restore_history_id
                                 FOR XML PATH('')), 1, 2, ''), '') AS [To],
                    bs.first_lsn,
                    bs.last_lsn,
                    bs.checkpoint_lsn,
                    bs.database_backup_lsn,
                    bs.backup_finish_date,
                    bs.backup_finish_date AS BackupFinishDate
                    "
                }

                $from = " FROM msdb.dbo.restorehistory rsh
                    INNER JOIN msdb.dbo.backupset bs ON rsh.backup_set_id = bs.backup_set_id"

                if ($ExcludeDatabase -or $Database -or $Since -or $last) {
                    $where = " WHERE "
                }

                $wherearray = @()

                if ($ExcludeDatabase) {
                    $dblist = $ExcludeDatabase -join "','"
                    $wherearray += " destination_database_name not in ('$dblist')"
                }

                if ($Database) {
                    $dblist = $Database -join "','"
                    $wherearray += "destination_database_name in ('$dblist')"
                }

                if ($null -ne $Since) {
                    $wherearray += "rsh.restore_date >= '$since'"
                }


                if ($last) {
                    $wherearray += "rsh.backup_set_id in
                        (select max(backup_set_id) from msdb.dbo.restorehistory
                        group by destination_database_name
                        )"
                }

                if ($where.length -gt 0) {
                    $wherearray = $wherearray -join " and "
                    $where = "$where $wherearray"
                }

                $sql = "$select $from $where"

                Write-Message -Level Debug -Message $sql

                $results = $server.ConnectionContext.ExecuteWithResults($sql).Tables.Rows
                if ($last) {
                    $ga = $results | Group-Object Database
                    $tmpres = @()
                    foreach ($g in $ga) {
                        $tmpres += $g.Group | Sort-Object -Property Date -Descending | Select-Object -First 1
                    }
                    $results = $tmpres
                }
                $results | Select-DefaultView -ExcludeProperty first_lsn, last_lsn, checkpoint_lsn, database_backup_lsn, backup_finish_date
            } catch {
                Stop-Function -Message "Failure" -Target $SqlInstance -Error $_ -Exception $_.Exception.InnerException -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbRoleMember.ps1
#ValidationTags#CodeStyle, Messaging, FlowControl, Pipeline#
function Get-DbaDbRoleMember {
    <#
    .SYNOPSIS
        Get members of database roles for each instance(s) of SQL Server.

    .DESCRIPTION
        The Get-DbaDbRoleMember returns connected SMO object for database roles for each instance(s) of SQL Server.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternate Windows or SQL Login Authentication. Accepts credential objects (Get-Credential).

    .PARAMETER Database
        The database(s) to process. This list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude. This list is auto-populated from the server.

    .PARAMETER Role
        The role(s) to process. If unspecified, all roles will be processed.

    .PARAMETER ExcludeRole
        The role(s) to exclude.

    .PARAMETER ExcludeFixedRole
        Excludes all members of fixed roles.

    .PARAMETER IncludeSystemUser
        Includes system users. By default system users are not included.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Role, Database, Security, Login
        Author: Klaas Vandenberghe (@PowerDBAKlaas)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbRoleMember

    .EXAMPLE
        PS C:\> Get-DbaDbRoleMember -SqlInstance localhost

        Returns all members of all database roles on the local default SQL Server instance

    .EXAMPLE
        PS C:\> Get-DbaDbRoleMember -SqlInstance localhost, sql2016

        Returns all members of all database roles on the local and sql2016 SQL Server instances

    .EXAMPLE
        PS C:\> $servers = Get-Content C:\servers.txt
        PS C:\> $servers | Get-DbaDbRoleMember

        Returns all members of all database roles for every server in C:\servers.txt

    .EXAMPLE
        PS C:\> Get-DbaDbRoleMember -SqlInstance localhost -Database msdb

        Returns non-system members of all roles in the msdb database on localhost.

    .EXAMPLE
        PS C:\> Get-DbaDbRoleMember -SqlInstance localhost -Database msdb -IncludeSystemUser -ExcludeFixedRole

        Returns all members of non-fixed roles in the msdb database on localhost.

    .EXAMPLE
        PS C:\> Get-DbaDbRoleMember -SqlInstance localhost -Database msdb -Role 'db_owner'

        Returns all members of the db_owner role in the msdb database on localhost.

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [string[]]$ExcludeDatabase,
        [string[]]$Role,
        [string[]]$ExcludeRole,
        [switch]$ExcludeFixedRole,
        [switch]$IncludeSystemUser,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            Write-Message -Level Verbose -Message "Attempting to connect to $instance"

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message 'Failure' -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $databases = $server.Databases | Where-Object { $_.IsAccessible -eq $true }

            if (Test-Bound -Parameter 'Database') {
                $databases = $databases | Where-Object { $_.Name -in $Database }
            }

            if (Test-Bound -Parameter 'ExcludeDatabase') {
                $databases = $databases | Where-Object { $_.Name -notin $ExcludeDatabase}
            }

            foreach ($db in $databases) {
                Write-Message -Level 'Verbose' -Message "Getting Database Roles for $db on $instance"

                $dbRoles = $db.roles

                if (Test-Bound -Parameter 'Role') {
                    $dbRoles = $dbRoles | Where-Object { $_.Name -in $Role }
                }

                if (Test-Bound -Parameter 'ExcludeRole') {
                    $dbRoles = $dbRoles | Where-Object { $_.Name -notin $ExcludeRole }
                }

                if (Test-Bound -Parameter 'ExcludeFixedRole') {
                    $dbRoles = $dbRoles | Where-Object { $_.IsFixedRole -eq $false }
                }

                foreach ($dbRole in $dbRoles) {
                    Write-Message -Level 'Verbose' -Message "Getting Database Role Members for $dbRole in $db on $instance"

                    $members = $dbRole.EnumMembers()
                    foreach ($member in $members) {
                        $user = $db.Users | Where-Object { $_.Name -eq $member }

                        if (Test-Bound -Not -ParameterName 'IncludeSystemUser') {
                            $user = $user | Where-Object { $_.IsSystemObject -eq $false }
                        }

                        if ($user) {
                            Add-Member -Force -InputObject $user -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName
                            Add-Member -Force -InputObject $user -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName
                            Add-Member -Force -InputObject $user -MemberType NoteProperty -Name SqlInstance -Value $server.DomainInstanceName
                            Add-Member -Force -InputObject $user -MemberType NoteProperty -Name Database -Value $db.Name
                            Add-Member -Force -InputObject $user -MemberType NoteProperty -Name Role -Value $dbRole.Name
                            Add-Member -Force -InputObject $user -MemberType NoteProperty -Name UserName -Value $user.Name

                            # Select object because Select-DefaultView causes strange behaviors when assigned to a variable (??)
                            Select-Object -InputObject $user -Property 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Role', 'UserName', 'Login', 'IsSystemObject'
                        }
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Get-DbaRoleMember
    }
}
tools\dbatools\functions\Get-DbaDbSharePoint.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaDbSharePoint {
    <#
    .SYNOPSIS
        Returns databases that are part of a SharePoint Farm.

    .DESCRIPTION
        Returns databases that are part of a SharePoint Farm, as found in the SharePoint Configuration database.

        By default, this command checks SharePoint_Config. To use an alternate database, use the ConfigDatabase parameter.

    .PARAMETER SqlInstance
        The target SQL Server instance

    .PARAMETER SqlCredential
        Login to the target instance using alternate Windows or SQL Login Authentication. Accepts credential objects (Get-Credential).

    .PARAMETER ConfigDatabase
        The name of the SharePoint Configuration database. Defaults to SharePoint_Config.

    .PARAMETER InputObject
        Allows piping from Get-DbaDatabase.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: SharePoint
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbSharePoint

    .EXAMPLE
        PS C:\> Get-DbaDbSharePoint -SqlInstance sqlcluster

        Returns databases that are part of a SharePoint Farm, as found in SharePoint_Config on sqlcluster

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sqlcluster -Database SharePoint_Config_2016 | Get-DbaDbSharePoint

        Returns databases that are part of a SharePoint Farm, as found in SharePoint_Config_2016 on sqlcluster

    #>
    [CmdletBinding()]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$ConfigDatabase = "SharePoint_Config",
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $instance -SqlCredential $SqlCredential -Database $ConfigDatabase
        }

        foreach ($db in $InputObject) {
            try {
                $guid = $db.Query("SELECT Id FROM Classes WHERE FullName LIKE 'Microsoft.SharePoint.Administration.SPDatabase,%'").Id.Guid
                $dbid = $db.Query("[dbo].[proc_getObjectsByBaseClass] @BaseClassId = '$guid', @ParentId = NULL").Id.Guid -join "', '"
                $dbname = $db.Query("SELECT [Name] FROM [SharePoint_Config].[dbo].[Objects] WHERE id in ('$dbid')").Name
                Get-DbaDatabase -SqlInstance $db.Parent -Database $dbname
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbSnapshot.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaDbSnapshot {
    <#
    .SYNOPSIS
        Get database snapshots with details

    .DESCRIPTION
        Retrieves the list of database snapshot available, along with their base (the db they are the snapshot of) and creation time

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Credential object used to connect to the SQL Server as a different user

    .PARAMETER Database
        Return information for only specific databases

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER Snapshot
        Return information for only specific snapshots

    .PARAMETER ExcludeSnapshot
        The snapshot(s) to exclude - this list is auto-populated from the server

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Snapshot
        Author: Simone Bizzotto (@niphlod)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbSnapshot

    .EXAMPLE
        PS C:\> Get-DbaDbSnapshot -SqlInstance sqlserver2014a

        Returns a custom object displaying Server, Database, DatabaseCreated, SnapshotOf, SizeMB, DatabaseCreated

    .EXAMPLE
        PS C:\> Get-DbaDbSnapshot -SqlInstance sqlserver2014a -Database HR, Accounting

        Returns information for database snapshots having HR and Accounting as base dbs

    .EXAMPLE
        PS C:\> Get-DbaDbSnapshot -SqlInstance sqlserver2014a -Snapshot HR_snapshot, Accounting_snapshot

        Returns information for database snapshots HR_snapshot and Accounting_snapshot

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [object[]]$Snapshot,
        [object[]]$ExcludeSnapshot,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            $dbs = $server.Databases | Where-Object DatabaseSnapshotBaseName
            if ($Database) {
                $dbs = $dbs | Where-Object { $Database -contains $_.DatabaseSnapshotBaseName }
            }
            if ($ExcludeDatabase) {
                $dbs = $dbs | Where-Object { $ExcludeDatabase -notcontains $_.DatabaseSnapshotBaseName }
            }
            if ($Snapshot) {
                $dbs = $dbs | Where-Object { $Snapshot -contains $_.Name }
            }
            if (!$Snapshot -and !$Database) {
                $dbs = $dbs | Where-Object IsDatabaseSnapshot -eq $true | Sort-Object DatabaseSnapshotBaseName, Name
            }
            if ($ExcludeSnapshot) {
                $dbs = $dbs | Where-Object { $ExcludeSnapshot -notcontains $_.Name }
            }
            foreach ($db in $dbs) {
                try {
                    $BytesOnDisk = $db.Query("SELECT SUM(BytesOnDisk) AS BytesOnDisk FROM fn_virtualfilestats(DB_ID(),NULL) S JOIN sys.databases D on D.database_id = S.dbid", $db.Name)
                    Add-Member -Force -InputObject $db -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                    Add-Member -Force -InputObject $db -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                    Add-Member -Force -InputObject $db -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                    Add-Member -Force -InputObject $db -MemberType NoteProperty -Name DiskUsage -value ([dbasize]($BytesOnDisk.BytesOnDisk))
                    Select-DefaultView -InputObject $db -Property ComputerName, InstanceName, SqlInstance, Name, 'DatabaseSnapshotBaseName as SnapshotOf', CreateDate, DiskUsage
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target $db -Continue
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Get-DbaDatabaseSnapshot
    }
}
tools\dbatools\functions\Get-DbaDbSpace.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Get-DbaDbSpace {
    <#
    .SYNOPSIS
        Returns database file space information for database files on a SQL instance.

    .DESCRIPTION
        This function returns database file space information for a SQL Instance or group of SQL Instances. Information is based on a query against sys.database_files and the FILEPROPERTY function to query and return information.

        File free space script borrowed and modified from Glenn Berry's DMV scripts (http://www.sqlskills.com/blogs/glenn/category/dmv-queries/)

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.

    .PARAMETER InputObject
        A piped collection of database objects from Get-DbaDatabase

    .PARAMETER IncludeSystemDBs
        If this switch is enabled, system databases will be processed. By default, only user databases are processed.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database, Space, Storage
        Author: Michael Fal (@Mike_Fal), http://mikefal.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbSpace

    .EXAMPLE
        PS C:\> Get-DbaDbSpace -SqlInstance localhost

        Returns all user database files and free space information for the localhost.

    .EXAMPLE
        PS C:\> Get-DbaDbSpace -SqlInstance localhost | Where-Object {$_.PercentUsed -gt 80}

        Returns all user database files and free space information for the local host. Filters the output object by any files that have a percent used of greater than 80%.

    .EXAMPLE
        PS C:\> 'localhost','localhost\namedinstance' | Get-DbaDbSpace

        Returns all user database files and free space information for the localhost and localhost\namedinstance SQL Server instances. Processes data via the pipeline.

    .EXAMPLE
        PS C:\> Get-DbaDbSpace -SqlInstance localhost -Database db1, db2 | Where-Object { $_.SpaceUntilMaxSize.Megabyte -lt 1 }

        Returns database files and free space information for the db1 and db2 on localhost where there is only 1MB left until the space is maxed out

    .EXAMPLE
        PS C:\> Get-DbaDbSpace -SqlInstance localhost -Database db1, db2 | Where-Object { $_.SpaceUntilMaxSize.Gigabyte -lt 1 }

        Returns database files and free space information for the db1 and db2 on localhost where there is only 1GB left until the space is maxed out

    #>
    [CmdletBinding()]
    param ([parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [string[]]$Database,
        [string[]]$ExcludeDatabase,
        [switch]$IncludeSystemDBs,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )
    begin {
        $sql = "SELECT SERVERPROPERTY('MachineName') AS ComputerName,
                                   ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
                                   SERVERPROPERTY('ServerName') AS SqlInstance,
                    DB_NAME() as DBName
                    ,f.name AS [FileName]
                    ,fg.name AS [Filegroup]
                    ,f.physical_name AS [PhysicalName]
                    ,f.type_desc AS [FileType]
                    ,CAST(CAST(FILEPROPERTY(f.name, 'SpaceUsed') AS int)/128.0 AS FLOAT) as [UsedSpaceMB]
                    ,CAST(f.size/128.0 - CAST(FILEPROPERTY(f.name, 'SpaceUsed') AS int)/128.0 AS FLOAT) AS [FreeSpaceMB]
                    ,CAST((f.size/128.0) AS FLOAT) AS [FileSizeMB]
                    ,CAST((FILEPROPERTY(f.name, 'SpaceUsed')/(f.size/1.0)) * 100 as FLOAT) as [PercentUsed]
                    ,CAST((f.growth/128.0) AS FLOAT) AS [GrowthMB]
                    ,CASE is_percent_growth WHEN 1 THEN 'pct' WHEN 0 THEN 'MB' ELSE 'Unknown' END AS [GrowthType]
                    ,CASE f.max_size WHEN -1 THEN 2147483648. ELSE CAST((f.max_size/128.0) AS FLOAT) END AS [MaxSizeMB]
                    ,CAST((f.size/128.0) AS FLOAT) - CAST(CAST(FILEPROPERTY(f.name, 'SpaceUsed') AS int)/128.0 AS FLOAT) AS [SpaceBeforeAutoGrow]
                    ,CASE f.max_size	WHEN (-1)
                                        THEN CAST(((2147483648.) - CAST(FILEPROPERTY(f.name, 'SpaceUsed') AS int))/128.0 AS FLOAT)
                                        ELSE CAST((f.max_size - CAST(FILEPROPERTY(f.name, 'SpaceUsed') AS int))/128.0 AS FLOAT)
                                        END AS [SpaceBeforeMax]
                    ,CASE f.growth	WHEN 0 THEN 0.00
                                    ELSE	CASE f.is_percent_growth	WHEN 0
                                                    THEN	CASE f.max_size
                                                            WHEN (-1)
                                                            THEN CAST(((((2147483648.)-f.Size)/f.Growth)*f.Growth)/128.0 AS FLOAT)
                                                            ELSE CAST((((f.max_size-f.Size)/f.Growth)*f.Growth)/128.0 AS FLOAT)
                                                            END
                                                    WHEN 1
                                                    THEN	CASE f.max_size
                                                            WHEN (-1)
                                                            THEN CAST(CONVERT([int],f.Size*power((1)+CONVERT([float],f.Growth)/(100),CONVERT([int],log10(CONVERT([float],(2147483648.))/CONVERT([float],f.Size))/log10((1)+CONVERT([float],f.Growth)/(100)))))/128.0 AS FLOAT)
                                                            ELSE CAST(CONVERT([int],f.Size*power((1)+CONVERT([float],f.Growth)/(100),CONVERT([int],log10(CONVERT([float],f.Max_Size)/CONVERT([float],f.Size))/log10((1)+CONVERT([float],f.Growth)/(100)))))/128.0 AS FLOAT)
                                                            END
                                                    ELSE (0)
                                                    END
                                    END AS [PossibleAutoGrowthMB]
                    , CASE f.max_size	WHEN -1 THEN 0
                                        ELSE CASE f.growth
                                                WHEN 0 THEN (f.max_size - f.size)/128
                                                ELSE	CASE f.is_percent_growth
                                                        WHEN 0
                                                        THEN CAST((f.max_size - f.size - (	CONVERT(FLOAT,FLOOR((f.max_size-f.Size)/f.Growth)*f.Growth)))/128.0 AS FLOAT)
                                                        ELSE CAST((f.max_size - f.size - (	CONVERT([int],f.Size*power((1)+CONVERT([float],f.Growth)/(100),CONVERT([int],log10(CONVERT([float],f.Max_Size)/CONVERT([float],f.Size))/log10((1)+CONVERT([float],f.Growth)/(100)))))))/128.0 AS FLOAT)
                                                        END
                                                END
                                    END AS [UnusableSpaceMB]

                FROM sys.database_files AS f WITH (NOLOCK)
                LEFT OUTER JOIN sys.filegroups AS fg WITH (NOLOCK)
                ON f.data_space_id = fg.data_space_id"
    }

    process {
        if ($IncludeSystemDBs) {
            Stop-Function -Message "IncludeSystemDBs will be removed. Please pipe in filtered results from Get-DbaDatabase instead."
            return
        }
        if ($SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase
        }

        foreach ($db in $InputObject) {
            $server = $db.Parent
            if ($server.VersionMajor -lt 9) {
                Stop-Function -Message "SQL Server 2000 not supported. $server skipped." -Continue
            }

            try {
                Write-Message -Level Verbose -Message "Querying $instance - $db."
                If ($db.status -ne 'Normal' -or $db.IsAccessible -eq $false) {
                    Write-Message -Level Warning -Message "$db is not accessible." -Target $db
                    continue
                }
                #Execute query against individual database and add to output
                foreach ($row in ($db.ExecuteWithResults($sql)).Tables.Rows) {
                    if ($row.UsedSpaceMB -is [System.DBNull]) {
                        $UsedMB = 0
                    } else {
                        $UsedMB = [Math]::Round($row.UsedSpaceMB)
                    }
                    if ($row.FreeSpaceMB -is [System.DBNull]) {
                        $FreeMB = 0
                    } else {
                        $FreeMB = [Math]::Round($row.FreeSpaceMB)
                    }
                    if ($row.PercentUsed -is [System.DBNull]) {
                        $PercentUsed = 0
                    } else {
                        $PercentUsed = [Math]::Round($row.PercentUsed)
                    }
                    if ($row.SpaceBeforeMax -is [System.DBNull]) {
                        $SpaceUntilMax = 0
                    } else {
                        $SpaceUntilMax = [Math]::Round($row.SpaceBeforeMax)
                    }
                    if ($row.UnusableSpaceMB -is [System.DBNull]) {
                        $UnusableSpace = 0
                    } else {
                        $UnusableSpace = [Math]::Round($row.UnusableSpaceMB)
                    }

                    [pscustomobject]@{
                        ComputerName       = $server.ComputerName
                        InstanceName       = $server.ServiceName
                        SqlInstance        = $server.DomainInstanceName
                        Database           = $row.DBName
                        FileName           = $row.FileName
                        FileGroup          = $row.FileGroup
                        PhysicalName       = $row.PhysicalName
                        FileType           = $row.FileType
                        UsedSpace          = [dbasize]($UsedMB * 1024 * 1024)
                        FreeSpace          = [dbasize]($FreeMB * 1024 * 1024)
                        FileSize           = [dbasize]($row.FileSizeMB * 1024 * 1024)
                        PercentUsed        = $PercentUsed
                        AutoGrowth         = [dbasize]($row.GrowthMB * 1024 * 1024)
                        AutoGrowType       = $row.GrowthType
                        SpaceUntilMaxSize  = [dbasize]($SpaceUntilMax * 1024 * 1024)
                        AutoGrowthPossible = [dbasize]($row.PossibleAutoGrowthMB * 1024 * 1024)
                        UnusableSpace      = [dbasize]($UnusableSpace * 1024 * 1024)
                    }
                }
            } catch {
                Stop-Function -Message "Unable to query $instance - $db." -Target $db -ErrorRecord $_ -Continue
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Get-DbaDatabaseFreeSpace
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Get-DbaDatabaseSpace
    }
}
tools\dbatools\functions\Get-DbaDbState.ps1
#ValidationTags#Messaging,FlowControl,Pipeline#
function Get-DbaDbState {
    <#
    .SYNOPSIS
        Gets various options for databases, hereby called "states"

    .DESCRIPTION
        Gets some common "states" on databases:
        - "RW" options : READ_ONLY or READ_WRITE
        - "Status" options : ONLINE, OFFLINE, EMERGENCY, RESTORING
        - "Access" options : SINGLE_USER, RESTRICTED_USER, MULTI_USER

        Returns an object with SqlInstance, Database, RW, Status, Access

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Credential object used to connect to the SQL Server as a different user

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database
        Author: Simone Bizzotto (@niphold)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbState

    .EXAMPLE
        PS C:\> Get-DbaDbState -SqlInstance sqlserver2014a

        Gets options for all databases of the sqlserver2014a instance

    .EXAMPLE
        PS C:\> Get-DbaDbState -SqlInstance sqlserver2014a -Database HR, Accounting

        Gets options for both HR and Accounting database of the sqlserver2014a instance

    .EXAMPLE
        PS C:\> Get-DbaDbState -SqlInstance sqlserver2014a -Exclude HR

        Gets options for all databases of the sqlserver2014a instance except HR

    .EXAMPLE
        PS C:\> 'sqlserver2014a', 'sqlserver2014b' | Get-DbaDbState

        Gets options for all databases of sqlserver2014a and sqlserver2014b instances

    #>
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseLiteralInitializerForHashtable", "")]
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]
        $SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {

        $DbStatesQuery = @'
SELECT
Name   = name,
Access = user_access_desc,
Status = state_desc,
RW     = CASE WHEN is_read_only = 0 THEN 'READ_WRITE' ELSE 'READ_ONLY' END
FROM sys.databases
'@

    }
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            $dbStates = $server.Query($DbStatesQuery)
            $dbs = $dbStates | Where-Object { @('master', 'model', 'msdb', 'tempdb', 'distribution') -notcontains $_.Name }
            if ($Database) {
                $dbs = $dbs | Where-Object Name -In $Database
            }
            if ($ExcludeDatabase) {
                $dbs = $dbs | Where-Object Name -NotIn $ExcludeDatabase
            }
            # "normal" hashtable doesn't account for case sensitivity
            $dbStatesHash = New-Object -TypeName System.Collections.Hashtable
            foreach ($db in $dbStates) {
                $dbStatesHash.Add($db.Name, [pscustomobject]@{
                        Access = $db.Access
                        Status = $db.Status
                        RW     = $db.RW
                    })
            }
            foreach ($db in $dbs) {
                $db_status = $dbStatesHash[$db.Name]
                [PSCustomObject]@{
                    SqlInstance  = $server.Name
                    InstanceName = $server.ServiceName
                    ComputerName = $server.ComputerName
                    DatabaseName = $db.Name
                    RW           = $db_status.RW
                    Status       = $db_status.Status
                    Access       = $db_status.Access
                    Database     = $server.Databases[$db.Name]
                } | Select-DefaultView -ExcludeProperty Database
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaDatabaseState
    }
}
tools\dbatools\functions\Get-DbaDbStoredProcedure.ps1
function Get-DbaDbStoredProcedure {
    <#
    .SYNOPSIS
        Gets database Stored Procedures

    .DESCRIPTION
        Gets database Stored Procedures

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Allows you to login to SQL Server using alternative credentials

    .PARAMETER Database
        To get Stored Procedures from specific database(s)

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto populated from the server

    .PARAMETER ExcludeSystemSp
        This switch removes all system objects from the Stored Procedure collection

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database, StoredProcedure, Proc
        Author: Klaas Vandenberghe (@PowerDbaKlaas)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaDbStoredProcedure -SqlInstance sql2016

        Gets all database Stored Procedures

    .EXAMPLE
        PS C:\> Get-DbaDbStoredProcedure -SqlInstance Server1 -Database db1

        Gets the Stored Procedures for the db1 database

    .EXAMPLE
        PS C:\> Get-DbaDbStoredProcedure -SqlInstance Server1 -ExcludeDatabase db1

        Gets the Stored Procedures for all databases except db1

    .EXAMPLE
        PS C:\> Get-DbaDbStoredProcedure -SqlInstance Server1 -ExcludeSystemSp

        Gets the Stored Procedures for all databases that are not system objects

    .EXAMPLE
        PS C:\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbStoredProcedure

        Gets the Stored Procedures for the databases on Sql1 and Sql2/sqlexpress

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$ExcludeSystemSp,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $databases = $server.Databases | Where-Object IsAccessible

            if ($Database) {
                $databases = $databases | Where-Object Name -In $Database
            }
            if ($ExcludeDatabase) {
                $databases = $databases | Where-Object Name -NotIn $ExcludeDatabase
            }

            foreach ($db in $databases) {
                if (!$db.IsAccessible) {
                    Write-Message -Level Warning -Message "Database $db is not accessible. Skipping."
                    continue
                }
                if ($db.StoredProcedures.Count -eq 0) {
                    Write-Message -Message "No Stored Procedures exist in the $db database on $instance" -Target $db -Level Output
                    continue
                }

                foreach ($proc in $db.StoredProcedures) {
                    if ( (Test-Bound -ParameterName ExcludeSystemSp) -and $proc.IsSystemObject ) {
                        continue
                    }

                    Add-Member -Force -InputObject $proc -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                    Add-Member -Force -InputObject $proc -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                    Add-Member -Force -InputObject $proc -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                    Add-Member -Force -InputObject $proc -MemberType NoteProperty -Name Database -value $db.Name

                    $defaults = 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Schema', 'ID as ObjectId', 'CreateDate',
                    'DateLastModified', 'Name', 'ImplementationType', 'Startup'
                    Select-DefaultView -InputObject $proc -Property $defaults
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbTable.ps1
function Get-DbaDbTable {
    <#
    .SYNOPSIS
        Returns a summary of information on the tables

    .DESCRIPTION
        Shows table information around table row and data sizes and if it has any table type information.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER IncludeSystemDBs
        Switch parameter that when used will display system database information

    .PARAMETER Table
        Define a specific table you would like to query. You can specify up to three-part name like db.sch.tbl.

        If the object has special characters please wrap them in square brackets [ ].
        Using dbo.First.Table will try to find table named 'Table' on schema 'First' and database 'dbo'.
        The correct way to find table named 'First.Table' on schema 'dbo' is by passing dbo.[First.Table]
        Any actual usage of the ] must be escaped by duplicating the ] character.
        The correct way to find a table Name] in schema Schema.Name is by passing [Schema.Name].[Name]]]

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database, Tables
        Author: Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbTable

    .EXAMPLE
        PS C:\> Get-DbaDbTable -SqlInstance DEV01 -Database Test1

        Return all tables in the Test1 database

    .EXAMPLE
        PS C:\> Get-DbaDbTable -SqlInstance DEV01 -Database MyDB -Table MyTable

        Return only information on the table MyTable from the database MyDB

    .EXAMPLE
        PS C:\> Get-DbaDbTable -SqlInstance DEV01 -Table MyTable

        Returns information on table called MyTable if it exists in any database on the server, under any schema

    .EXAMPLE
        PS C:\> Get-DbaDbTable -SqlInstance DEV01 -Table dbo.[First.Table]

        Returns information on table called First.Table on schema dbo if it exists in any database on the server

    .EXAMPLE
        PS C:\> 'localhost','localhost\namedinstance' | Get-DbaDbTable -Database DBA -Table Commandlog

        Returns information on the CommandLog table in the DBA database on both instances localhost and the named instance localhost\namedinstance

    .EXAMPLE
        PS C:\> Get-DbaDbTable -SqlInstance DEV01 -Table "[[DbName]]].[Schema.With.Dots].[`"[Process]]`"]" -Verbose

        For the instance Dev01 Returns information for a table named: "[Process]" in schema named: Schema.With.Dots in database named: [DbName]
        The Table name, Schema name and Database name must be wrapped in square brackets [ ]
        Special charcters like " must be escaped by a ` charcter.
        In addition any actual instance of the ] character must be escaped by being duplicated.
       #>
    [CmdletBinding()]
    param ([parameter(ValueFromPipeline, Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$IncludeSystemDBs,
        [string[]]$Table,
        [switch][Alias('Silent')]
        $EnableException
    )

    begin {
        if ($Table) {
            $fqtns = @()
            foreach ($t in $Table) {
                $fqtn = Get-TableNameParts -Table $t

                if (!$fqtn.Parsed) {
                    Write-Message -Level Warning -Message "Please check you are using proper three-part names. If your search value contains special characters you must use [ ] to wrap the name. The value $t could not be parsed as a valid name."
                    Continue
                }

                $fqtns += [PSCustomObject] @{
                    Database   = $fqtn.Database
                    Schema     = $fqtn.Schema
                    Table      = $fqtn.Table
                    InputValue = $fqtn.InputValue
                }
            }
            if (!$fqtns) {
                Stop-Function -Message "No Valid Table specified"  -ErrorRecord $_ -Target $instance -Continue
            }
        }
    }

    process {
        foreach ($instance in $sqlinstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            try {
                #only look at online databases (Status equal normal)
                $dbs = $server.Databases | Where-Object IsAccessible

                #If IncludeSystemDBs is false, exclude systemdbs
                if (!$IncludeSystemDBs -and !$Database) {
                    $dbs = $dbs | Where-Object { !$_.IsSystemObject }
                }

                if ($Database) {
                    $dbs = $dbs | Where-Object { $Database -contains $_.Name }
                }

                if ($ExcludeDatabase) {
                    $dbs = $dbs | Where-Object { $ExcludeDatabase -notcontains $_.Name }
                }
            } catch {
                Stop-Function -Message "Unable to gather dbs for $instance" -Target $instance -Continue -ErrorRecord $_
            }

            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Processing $db"

                if ($fqtns) {
                    $tables = @()
                    foreach ($fqtn in $fqtns) {
                        # If the user specified a database in a three-part name, and it's not the
                        # database currently being processed, skip this table.
                        if ($fqtn.Database) {
                            if ($fqtn.Database -ne $db.Name) {
                                continue
                            }
                        }

                        $tbl = $db.tables | Where-Object { $_.Name -in $fqtn.Table -and $fqtn.Schema -in ($_.Schema, $null) -and $fqtn.Database -in ($_.Parent.Name, $null) }

                        if (-not $tbl) {
                            Write-Message -Level Verbose -Message "Could not find table $($fqtn.Table) in $db on $server"
                        }
                        $tables += $tbl
                    }
                } else {
                    $tables = $db.Tables
                }

                foreach ($sqltable in $tables) {
                    $sqltable | Add-Member -Force -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName
                    $sqltable | Add-Member -Force -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName
                    $sqltable | Add-Member -Force -MemberType NoteProperty -Name SqlInstance -Value $server.DomainInstanceName
                    $sqltable | Add-Member -Force -MemberType NoteProperty -Name Database -Value $db.Name

                    $defaultprops = "ComputerName", "InstanceName", "SqlInstance", "Database", "Schema", "Name", "IndexSpaceUsed", "DataSpaceUsed", "RowCount", "HasClusteredIndex", "IsFileTable", "IsMemoryOptimized", "IsPartitioned", "FullTextIndex", "ChangeTrackingEnabled"

                    Select-DefaultView -InputObject $sqltable -Property $defaultprops
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaTable
    }
}
tools\dbatools\functions\Get-DbaDbTrigger.ps1
function Get-DbaDbTrigger {
    <#
    .SYNOPSIS
        Get all existing database triggers on one or more SQL instances.

    .DESCRIPTION
        Get all existing database triggers on one or more SQL instances.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        SqlCredential object used to connect to the SQL Server as a different user.

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER InputObject
        Allow pipedline input from Get-DbaDatabase

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/ca

    .NOTES
        Tags: Database, Trigger
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbTrigger

    .EXAMPLE
        PS C:\> Get-DbaDbTrigger -SqlInstance sql2017

        Returns all database triggers

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sql2017 -Database supa | Get-DbaDbTrigger

        Returns all triggers for database supa on sql2017

    .EXAMPLE
        PS C:\> Get-DbaDbTrigger -SqlInstance sql2017 -Database supa

        Returns all triggers for database supa on sql2017

    #>
    [CmdletBinding()]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )

    process {
        foreach ($Instance in $SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase
        }

        foreach ($db in $InputObject) {
            try {
                foreach ($trigger in ($db.Triggers)) {
                    Add-Member -Force -InputObject $trigger -MemberType NoteProperty -Name ComputerName -value $db.Parent.ComputerName
                    Add-Member -Force -InputObject $trigger -MemberType NoteProperty -Name InstanceName -value $db.Parent.ServiceName
                    Add-Member -Force -InputObject $trigger -MemberType NoteProperty -Name SqlInstance -value $db.Parent.DomainInstanceName
                    Select-DefaultView -InputObject $trigger -Property ComputerName, InstanceName, SqlInstance, Name, IsEnabled, DateLastModified
                }
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDbUdf.ps1
function Get-DbaDbUdf {
    <#
    .SYNOPSIS
        Gets database User Defined Functions

    .DESCRIPTION
        Gets database User Defined Functions

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Allows you to login to SQL Server using alternative credentials

    .PARAMETER Database
        To get User Defined Functions from specific database(s)

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto populated from the server

    .PARAMETER ExcludeSystemUdf
        This switch removes all system objects from the UDF collection

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Security, Database
        Author: Klaas Vandenberghe (@PowerDbaKlaas)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaDbUdf -SqlInstance sql2016

        Gets all database User Defined Functions

    .EXAMPLE
        PS C:\> Get-DbaDbUdf -SqlInstance Server1 -Database db1

        Gets the User Defined Functions for the db1 database

    .EXAMPLE
        PS C:\> Get-DbaDbUdf -SqlInstance Server1 -ExcludeDatabase db1

        Gets the User Defined Functions for all databases except db1

    .EXAMPLE
        PS C:\> Get-DbaDbUdf -SqlInstance Server1 -ExcludeSystemUdf

        Gets the User Defined Functions for all databases that are not system objects (there can be 100+ system User Defined Functions in each DB)

    .EXAMPLE
        PS C:\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbUdf

        Gets the User Defined Functions for the databases on Sql1 and Sql2/sqlexpress

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$ExcludeSystemUdf,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $databases = $server.Databases | Where-Object IsAccessible

            if ($Database) {
                $databases = $databases | Where-Object Name -In $Database
            }
            if ($ExcludeDatabase) {
                $databases = $databases | Where-Object Name -NotIn $ExcludeDatabase
            }

            foreach ($db in $databases) {

                $UserDefinedFunctions = $db.UserDefinedFunctions

                if (!$UserDefinedFunctions) {
                    Write-Message -Message "No User Defined Functions exist in the $db database on $instance" -Target $db -Level Verbose
                    continue
                }
                if (Test-Bound -ParameterName ExcludeSystemUdf) {
                    $UserDefinedFunctions = $UserDefinedFunctions | Where-Object { $_.IsSystemObject -eq $false }
                }

                $UserDefinedFunctions | ForEach-Object {

                    Add-Member -Force -InputObject $_ -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                    Add-Member -Force -InputObject $_ -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                    Add-Member -Force -InputObject $_ -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                    Add-Member -Force -InputObject $_ -MemberType NoteProperty -Name Database -value $db.Name

                    Select-DefaultView -InputObject $_ -Property ComputerName, InstanceName, SqlInstance, Database, Schema, CreateDate, DateLastModified, Name, DataType
                }
            }
        }
    }

    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaDatabaseUdf
    }
}
tools\dbatools\functions\Get-DbaDbUser.ps1
function Get-DbaDbUser {
    <#
    .SYNOPSIS
        Gets database users

    .DESCRIPTION
        Gets database users

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Allows you to login to SQL Server using alternative credentials

    .PARAMETER Database
        To get users from specific database(s)

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto populated from the server

    .PARAMETER ExcludeSystemUser
        This switch removes all system objects from the user collection

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Security, Database
        Author: Klaas Vandenberghe (@PowerDbaKlaas)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaDbUser -SqlInstance sql2016

        Gets all database users

    .EXAMPLE
        PS C:\> Get-DbaDbUser -SqlInstance Server1 -Database db1

        Gets the users for the db1 database

    .EXAMPLE
        PS C:\> Get-DbaDbUser -SqlInstance Server1 -ExcludeDatabase db1

        Gets the users for all databases except db1

    .EXAMPLE
        PS C:\> Get-DbaDbUser -SqlInstance Server1 -ExcludeSystemUser

        Gets the users for all databases that are not system objects, like 'dbo', 'guest' or 'INFORMATION_SCHEMA'

    .EXAMPLE
        PS C:\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbUser

        Gets the users for the databases on Sql1 and Sql2/sqlexpress

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$ExcludeSystemUser,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $databases = $server.Databases | Where-Object IsAccessible

            if ($Database) {
                $databases = $databases | Where-Object Name -In $Database
            }
            if ($ExcludeDatabase) {
                $databases = $databases | Where-Object Name -NotIn $ExcludeDatabase
            }

            foreach ($db in $databases) {

                $users = $db.users

                if (!$users) {
                    Write-Message -Message "No users exist in the $db database on $instance" -Target $db -Level Verbose
                    continue
                }
                if (Test-Bound -ParameterName ExcludeSystemUser) {
                    $users = $users | Where-Object { $_.IsSystemObject -eq $false }
                }

                $users | ForEach-Object {

                    Add-Member -Force -InputObject $_ -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                    Add-Member -Force -InputObject $_ -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                    Add-Member -Force -InputObject $_ -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                    Add-Member -Force -InputObject $_ -MemberType NoteProperty -Name Database -value $db.Name

                    Select-DefaultView -InputObject $_ -Property ComputerName, InstanceName, SqlInstance, Database, CreateDate, DateLastModified, Name, Login, LoginType, AuthenticationType, State, HasDbAccess, DefaultSchema
                }
            }
        }
    }

    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaDatabaseUser
    }
}
tools\dbatools\functions\Get-DbaDbView.ps1
function Get-DbaDbView {
    <#
    .SYNOPSIS
        Gets database views for each SqlInstance.

    .DESCRIPTION
        Gets database views for each SqlInstance.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        To get views from specific database(s) - this list is auto populated from the server.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto populated from the server.

    .PARAMETER ExcludeSystemView
        This switch removes all system objects from the view collection.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Security, Database
        Author: Klaas Vandenberghe (@PowerDbaKlaas)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaDbView -SqlInstance sql2016

        Gets all database views

    .EXAMPLE
        PS C:\> Get-DbaDbView -SqlInstance Server1 -Database db1

        Gets the views for the db1 database

    .EXAMPLE
        PS C:\> Get-DbaDbView -SqlInstance Server1 -ExcludeDatabase db1

        Gets the views for all databases except db1

    .EXAMPLE
        PS C:\> Get-DbaDbView -SqlInstance Server1 -ExcludeSystemView

        Gets the views for all databases that are not system objects (there can be 400+ system views in each DB)

    .EXAMPLE
        PS C:\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbView

        Gets the views for the databases on Sql1 and Sql2/sqlexpress

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$ExcludeSystemView,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $databases = $server.Databases | Where-Object IsAccessible

            if ($Database) {
                $databases = $databases | Where-Object Name -In $Database
            }
            if ($ExcludeDatabase) {
                $databases = $databases | Where-Object Name -NotIn $ExcludeDatabase
            }

            foreach ($db in $databases) {
                $views = $db.views

                if (!$views) {
                    Write-Message -Message "No views exist in the $db database on $instance" -Target $db -Level Verbose
                    continue
                }
                if (Test-Bound -ParameterName ExcludeSystemView) {
                    $views = $views | Where-Object { $_.IsSystemObject -eq $false }
                }

                $views | Foreach-Object {

                    Add-Member -Force -InputObject $_ -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                    Add-Member -Force -InputObject $_ -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                    Add-Member -Force -InputObject $_ -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                    Add-Member -Force -InputObject $_ -MemberType NoteProperty -Name Database -value $db.Name

                    Select-DefaultView -InputObject $_ -Property ComputerName, InstanceName, SqlInstance, Database, Schema, CreateDate, DateLastModified, Name
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaDatabaseView
    }
}
tools\dbatools\functions\Get-DbaDbVirtualLogFile.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Get-DbaDbVirtualLogFile {
    <#
    .SYNOPSIS
        Returns database virtual log file information for database files on a SQL instance.

    .DESCRIPTION
        Having a transaction log file with too many virtual log files (VLFs) can hurt database performance.

        Too many VLFs can cause transaction log backups to slow down and can also slow down database recovery and, in extreme cases, even affect insert/update/delete performance.

        References:
        http://www.sqlskills.com/blogs/kimberly/transaction-log-vlfs-too-many-or-too-few/
        http://blogs.msdn.com/b/saponsqlserver/archive/2012/02/22/too-many-virtual-log-files-vlfs-can-cause-slow-database-recovery.aspx

        If you've got a high number of VLFs, you can use Expand-SqlTLogResponsibly to reduce the number.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.

    .PARAMETER IncludeSystemDBs
        If this switch is enabled, system database information will be displayed.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: VLF, Database, LogFile
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDbVirtualLogFile

    .EXAMPLE
        PS C:\> Get-DbaDbVirtualLogFile -SqlInstance sqlcluster

        Returns all user database virtual log file details for the sqlcluster instance.

    .EXAMPLE
        PS C:\> Get-DbaDbVirtualLogFile -SqlInstance sqlserver | Group-Object -Property Database | Where-Object Count -gt 50

        Returns user databases that have 50 or more VLFs.

    .EXAMPLE
        PS C:\> 'sqlserver','sqlcluster' | Get-DbaDbVirtualLogFile

        Returns all VLF information for the sqlserver and sqlcluster SQL Server instances. Processes data via the pipeline.

    .EXAMPLE
        PS C:\> Get-DbaDbVirtualLogFile -SqlInstance sqlcluster -Database db1, db2

        Returns the VLF counts for the db1 and db2 databases on sqlcluster.

    #>
    [CmdletBinding()]
    [OutputType([System.Collections.ArrayList])]
    param ([parameter(ValueFromPipeline, Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$IncludeSystemDBs,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $dbs = $server.Databases | Where-Object IsAccessible

            if ($Database) {
                $dbs = $dbs | Where-Object Name -in $Database
            }
            if ($ExcludeDatabase) {
                $dbs = $dbs | Where-Object Name -NotIn $ExcludeDatabase
            }

            if (!$IncludeSystemDBs) {
                $dbs = $dbs | Where-Object IsSystemObject -eq $false
            }

            foreach ($db in $dbs) {
                try {
                    $data = $db.Query("DBCC LOGINFO")

                    foreach ($d in $data) {
                        [pscustomobject]@{
                            ComputerName   = $server.ComputerName
                            InstanceName   = $server.ServiceName
                            SqlInstance    = $server.DomainInstanceName
                            Database       = $db.Name
                            RecoveryUnitId = $d.RecoveryUnitId
                            FileId         = $d.FileId
                            FileSize       = $d.FileSize
                            StartOffset    = $d.StartOffset
                            FSeqNo         = $d.FSeqNo
                            Status         = $d.Status
                            Parity         = $d.Parity
                            CreateLsn      = $d.CreateLSN
                        }
                    }
                } catch {
                    Stop-Function -Message "Unable to query $($db.name) on $instance." -ErrorRecord $_ -Target $db -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDefaultPath.ps1
function Get-DbaDefaultPath {
    <#
    .SYNOPSIS
        Gets the default SQL Server paths for data, logs and backups

    .DESCRIPTION
        Gets the default SQL Server paths for data, logs and backups

    .PARAMETER SqlInstance
        TThe target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Config
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDefaultPath

    .EXAMPLE
        PS C:\> Get-DbaDefaultPath -SqlInstance sql01\sharepoint

        Returns the default file paths for sql01\sharepoint

    .EXAMPLE
        PS C:\> $servers = "sql2014","sql2016", "sqlcluster\sharepoint"
        PS C:\> $servers | Get-DbaDefaultPath

        Returns the default file paths for "sql2014","sql2016" and "sqlcluster\sharepoint"

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "Instance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]
        $SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -AzureUnsupported
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $dataPath = $server.DefaultFile
            if ($dataPath.Length -eq 0) {
                $dataPath = $server.Query("SELECT SERVERPROPERTY('InstanceDefaultdataPath') as Data").Data
            }

            if ($dataPath -eq [System.DBNull]::Value -or $dataPath.Length -eq 0) {
                $dataPath = Split-Path (Get-DbaDatabase -SqlInstance $server -Database model).FileGroups[0].Files[0].FileName
            }

            if ($dataPath.Length -eq 0) {
                $dataPath = $server.Information.MasterDbPath
            }

            $logPath = $server.DefaultLog

            if ($logPath.Length -eq 0) {
                $logPath = $server.Query("SELECT SERVERPROPERTY('InstanceDefaultLogPath') as Log").Log
            }

            if ($logPath -eq [System.DBNull]::Value -or $logPath.Length -eq 0) {
                $logPath = Split-Path (Get-DbaDatabase -SqlInstance $server -Database model).LogFiles.FileName
            }

            if ($logPath.Length -eq 0) {
                $logPath = $server.Information.MasterDbLogPath
            }

            $dataPath = $dataPath.Trim().TrimEnd("\")
            $logPath = $logPath.Trim().TrimEnd("\")

            [PSCustomObject]@{
                ComputerName = $server.ComputerName
                InstanceName = $server.ServiceName
                SqlInstance  = $server.DomainInstanceName
                Data         = $dataPath
                Log          = $logPath
                Backup       = $server.BackupDirectory
                ErrorLog     = $server.ErrorlogPath
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDependency.ps1
function Get-DbaDependency {
    <#
    .SYNOPSIS
        Finds object dependencies and their relevant creation scripts.

    .DESCRIPTION
        This function recursively finds all objects that depends on the input.
        It will then retrieve rich information from them, including their creation scripts and the order in which it should be applied.

        By using the 'Parents' switch, the function will instead retrieve all items that the input depends on (including their creation scripts).

        For more details on dependency, see:
        https://technet.microsoft.com/en-us/library/ms345449(v=sql.105).aspx

    .PARAMETER InputObject
        The SMO object to parse

    .PARAMETER AllowSystemObjects
        Normally, system objects are ignored by this function as dependencies.
        This switch overrides that behavior.

    .PARAMETER Parents
        Causes the function to retrieve all objects that the input depends on, rather than retrieving everything that depends on the input.

    .PARAMETER IncludeSelf
        Includes the object whose dependencies are retrieves itself.
        Useful when exporting an entire logic structure in order to recreate it in another database.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER IncludeScript
        Setting this switch will cause the function to also retrieve the creation script of the dependency.

    .NOTES
        Tags: Database, Dependent, Dependency, Object
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDependency

    .EXAMPLE
        PS C:\> $table = (Get-DbaDatabase -SqlInstance sql2012 -Database Northwind).tables | Where Name -eq Customers
        PS C:\> $table | Get-DbaDependency

        Returns everything that depends on the "Customers" table

    #>
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]$InputObject,
        [switch]$AllowSystemObjects,
        [switch]$Parents,
        [switch]$IncludeSelf,
        [switch]$EnableException
    )

    begin {
        #region Utility functions
        function Get-DependencyTree {
            [CmdletBinding()]
            param (
                $Object,

                $Server,

                [bool]
                $AllowSystemObjects,

                [bool]
                $EnumParents,

                [string]
                $FunctionName
            )

            $scripter = New-Object Microsoft.SqlServer.Management.Smo.Scripter
            $options = New-Object Microsoft.SqlServer.Management.Smo.ScriptingOptions
            $options.DriAll = $true
            $options.AllowSystemObjects = $AllowSystemObjects
            $options.WithDependencies = $true
            $scripter.Options = $options
            $scripter.Server = $Server

            $urnCollection = New-Object Microsoft.SqlServer.Management.Smo.UrnCollection

            Write-Message -Level 5 -Message "Adding $Object which is a $($Object.urn.Type)" -FunctionName $FunctionName
            $urnCollection.Add([Microsoft.SqlServer.Management.Sdk.Sfc.Urn]$Object.urn)

            #now we set up an event listener go get progress reports
            $progressReportEventHandler = [Microsoft.SqlServer.Management.Smo.ProgressReportEventHandler] {
                $name = $_.Current.GetAttribute('Name');
                Write-Message -Level 5 -Message "Analysed $name" -FunctionName $FunctionName
            }
            $scripter.add_DiscoveryProgress($progressReportEventHandler)

            return $scripter.DiscoverDependencies($urnCollection, $EnumParents)
        }

        function Read-DependencyTree {
            [CmdletBinding()]
            param (
                [System.Object]
                $InputObject,

                [int]
                $Tier,

                [System.Object]
                $Parent,

                [bool]
                $EnumParents
            )

            Add-Member -Force -InputObject $InputObject -Name Parent -Value $Parent -MemberType NoteProperty
            if ($EnumParents) { Add-Member -Force -InputObject $InputObject -Name Tier -Value ($Tier * -1) -MemberType NoteProperty -PassThru }
            else { Add-Member -Force -InputObject $InputObject -Name Tier -Value $Tier -MemberType NoteProperty -PassThru }

            if ($InputObject.HasChildNodes) { Read-DependencyTree -InputObject $InputObject.FirstChild -Tier ($Tier + 1) -Parent $InputObject -EnumParents $EnumParents }
            if ($InputObject.NextSibling) { Read-DependencyTree -InputObject $InputObject.NextSibling -Tier $Tier -Parent $Parent -EnumParents $EnumParents }
        }

        function Get-DependencyTreeNodeDetail {
            [CmdletBinding()]
            param (
                [Parameter(ValueFromPipeline)]
                $SmoObject,

                $Server,

                $OriginalResource,

                [bool]
                $AllowSystemObjects
            )

            begin {
                $scripter = New-Object Microsoft.SqlServer.Management.Smo.Scripter
                $options = New-Object Microsoft.SqlServer.Management.Smo.ScriptingOptions
                $options.DriAll = $true
                $options.AllowSystemObjects = $AllowSystemObjects
                $options.WithDependencies = $true
                $scripter.Options = $options
                $scripter.Server = $Server
            }

            process {
                foreach ($Item in $SmoObject) {
                    $richobject = $Server.GetSmoObject($Item.urn)
                    $parent = $Server.GetSmoObject($Item.Parent.Urn)

                    $NewObject = New-Object Sqlcollaborative.Dbatools.Database.Dependency
                    $NewObject.ComputerName = $server.ComputerName
                    $NewObject.ServiceName = $server.ServiceName
                    $NewObject.SqlInstance = $server.DomainInstanceName
                    $NewObject.Dependent = $richobject.Name
                    $NewObject.Type = $Item.Urn.Type
                    $NewObject.Owner = $richobject.Owner
                    $NewObject.IsSchemaBound = $Item.IsSchemaBound
                    $NewObject.Parent = $parent.Name
                    $NewObject.ParentType = $parent.Urn.Type
                    $NewObject.Tier = $Item.Tier
                    $NewObject.Object = $richobject
                    $NewObject.Urn = $richobject.Urn
                    $NewObject.OriginalResource = $OriginalResource

                    $SQLscript = $scripter.EnumScriptWithList($richobject)

                    # I can't remember how to remove these options and their syntax is breaking stuff
                    $SQLscript = $SQLscript -replace "SET ANSI_NULLS ON", ""
                    $SQLscript = $SQLscript -replace "SET QUOTED_IDENTIFIER ON", ""
                    $NewObject.Script = "$SQLscript `r`ngo"

                    $NewObject
                }
            }
        }

        function Select-DependencyPrecedence {
            [CmdletBinding()]
            param (
                [Parameter(ValueFromPipeline)]
                $Dependency
            )

            begin {
                $list = @()
            }
            process {
                foreach ($dep in $Dependency) {
                    # Killing the pipeline is generally a bad idea, but since we have to group and sort things, we have not really a choice
                    $list += $dep
                }
            }
            end {
                $list | Group-Object -Property Object | ForEach-Object { $_.Group | Sort-Object -Property Tier -Descending | Select-Object -First 1 } | Sort-Object Tier
            }
        }
        #endregion Utility functions
    }
    process {
        foreach ($Item in $InputObject) {
            Write-Message -Level Verbose -Message "Processing: $Item"
            if ($null -eq $Item.urn) {
                Stop-Function -Message "$Item is not a valid SMO object" -Category InvalidData -Continue -Target $Item
            }

            # Find the server object to pass on to the function
            $parent = $Item.parent

            do { $parent = $parent.parent }
            until (($parent.urn.type -eq "Server") -or (-not $parent))

            if (-not $parent) {
                Stop-Function -Message "Failed to find valid server object in input: $Item" -Category InvalidData -Continue -Target $Item
            }

            $server = $parent

            $tree = Get-DependencyTree -Object $Item -AllowSystemObjects $false -Server $server -FunctionName (Get-PSCallStack)[0].COmmand -EnumParents $Parents
            $limitCount = 2
            if ($IncludeSelf) { $limitCount = 1 }
            if ($tree.Count -lt $limitCount) {
                Write-Message -Message "No dependencies detected for $($Item)" -Level Host
                continue
            }

            if ($IncludeSelf) { $resolved = Read-DependencyTree -InputObject $tree.FirstChild -Tier 0 -Parent $tree.FirstChild -EnumParents $Parents }
            else { $resolved = Read-DependencyTree -InputObject $tree.FirstChild.FirstChild -Tier 1 -Parent $tree.FirstChild -EnumParents $Parents }
            $resolved | Get-DependencyTreeNodeDetail -Server $server -OriginalResource $Item -AllowSystemObjects $AllowSystemObjects | Select-DependencyPrecedence
        }
    }
}
tools\dbatools\functions\Get-DbaDeprecatedFeature.ps1
function Get-DbaDeprecatedFeature {
    <#
    .SYNOPSIS
        Displays information relating to deprecated features for SQL Server 2005 and above.

    .DESCRIPTION
        Displays information relating to deprecated features for SQL Server 2005 and above.

    .PARAMETER SqlInstance
        The target SQL Server instance

    .PARAMETER SqlCredential
        Login to the target instance using alternate Windows or SQL Login Authentication. Accepts credential objects (Get-Credential).

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Deprecated
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDeprecatedFeature

    .EXAMPLE
        PS C:\> Get-DbaDeprecatedFeature -SqlInstance sql2008, sqlserver2012

        Check deprecated features for all databases on the servers sql2008 and sqlserver2012.

    .EXAMPLE
        PS C:\> Get-DbaDeprecatedFeature -SqlInstance sql2008

        Check deprecated features on server sql2008.

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )

    begin {
        $sql = "SELECT  SERVERPROPERTY('MachineName') AS ComputerName,
        ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
        SERVERPROPERTY('ServerName') AS SqlInstance, object_name, instance_name as DeprecatedFeature, object_name as ObjectName, instance_name as deprecated_feature, cntr_value as UsageCount
        FROM sys.dm_os_performance_counters WHERE object_name like '%Deprecated%'
        and cntr_value > 0 ORDER BY deprecated_feature"
    }

    process {
        foreach ($instance in $SqlInstance) {
            Write-Message -Level Verbose -Message "Attempting to connect to $instance"

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            try {
                $server.Query($sql) | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, ObjectName, DeprecatedFeature, UsageCount
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Target $instance -Continue
            }

        }
    }
}
tools\dbatools\functions\Get-DbaDetachedDatabaseInfo.ps1
function Get-DbaDetachedDatabaseInfo {
    <#
    .SYNOPSIS
        Get detailed information about detached SQL Server database files.

    .DESCRIPTION
        Gathers the following information from detached database files: database name, SQL Server version (compatibility level), collation, and file structure.

        "Data files" and "Log file" report the structure of the data and log files as they were when the database was detached. "Database version" is the compatibility level.

        MDF files are most easily read by using a SQL Server to interpret them. Because of this, you must specify a SQL Server and the path must be relative to the SQL Server.

    .PARAMETER SqlInstance
        Source SQL Server. This instance must be online and is required to parse the information contained with in the detached database file.

        This function will not attach the database file, it will only use SQL Server to read its contents.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Path
        Specifies the path to the MDF file to be read. This path must be readable by the SQL Server service account. Ideally, the MDF will be located on the SQL Server itself, or on a network share to which the SQL Server service account has access.

    .NOTES
        Tags: Database, Detach
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDetachedDatabaseInfo

    .EXAMPLE
        PS C:\> Get-DbaDetachedDatabaseInfo -SqlInstance sql2016 -Path M:\Archive\mydb.mdf

        Returns information about the detached database file M:\Archive\mydb.mdf using the SQL Server instance sql2016. The M drive is relative to the SQL Server instance.

    #>

    [CmdletBinding(DefaultParameterSetName = "Default")]
    param (
        [parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [parameter(Mandatory)]
        [Alias("Mdf")]
        [string]$Path,
        [PSCredential]$SqlCredential
    )

    begin {
        function Get-MdfFileInfo {
            $datafiles = New-Object System.Collections.Specialized.StringCollection
            $logfiles = New-Object System.Collections.Specialized.StringCollection

            $servername = $server.name
            $serviceaccount = $server.ServiceAccount

            $exists = Test-DbaPath -SqlInstance $server -Path $Path

            if ($exists -eq $false) {
                throw "$servername cannot access the file $path. Does the file exist and does the service account ($serviceaccount) have access to the path?"
            }

            try {
                $detachedDatabaseInfo = $server.DetachedDatabaseInfo($path)
                $dbname = ($detachedDatabaseInfo | Where-Object { $_.Property -eq "Database name" }).Value
                $exactdbversion = ($detachedDatabaseInfo | Where-Object { $_.Property -eq "Database version" }).Value
                $collationid = ($detachedDatabaseInfo | Where-Object { $_.Property -eq "Collation" }).Value
            } catch {
                throw "$servername cannot read the file $path. Is the database detached?"
            }

            switch ($exactdbversion) {
                852 { $dbversion = "SQL Server 2016" }
                829 { $dbversion = "SQL Server 2016 Prerelease" }
                782 { $dbversion = "SQL Server 2014" }
                706 { $dbversion = "SQL Server 2012" }
                684 { $dbversion = "SQL Server 2012 CTP1" }
                661 { $dbversion = "SQL Server 2008 R2" }
                660 { $dbversion = "SQL Server 2008 R2" }
                655 { $dbversion = "SQL Server 2008 SP2+" }
                612 { $dbversion = "SQL Server 2005" }
                611 { $dbversion = "SQL Server 2005" }
                539 { $dbversion = "SQL Server 2000" }
                515 { $dbversion = "SQL Server 7.0" }
                408 { $dbversion = "SQL Server 6.5" }
                default { $dbversion = "Unknown" }
            }

            $collationsql = "SELECT name FROM fn_helpcollations() where collationproperty(name, N'COLLATIONID')  = $collationid"

            try {
                $dataset = $server.databases['master'].ExecuteWithResults($collationsql)
                $collation = "$($dataset.Tables[0].Rows[0].Item(0))"
            } catch {
                $collation = $collationid
            }

            if ($collation.length -eq 0) { $collation = $collationid }

            try {
                foreach ($file in $server.EnumDetachedDatabaseFiles($path)) {
                    $datafiles += $file
                }

                foreach ($file in $server.EnumDetachedLogFiles($path)) {
                    $logfiles += $file
                }
            } catch {
                throw "$servername unable to enumerate database or log structure information for $path"
            }

            $mdfinfo = [pscustomobject]@{
                Name         = $dbname
                Version      = $dbversion
                ExactVersion = $exactdbversion
                Collation    = $collation
                DataFiles    = $datafiles
                LogFiles     = $logfiles
            }

            return $mdfinfo
        }
    }

    process {

        $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        $mdfinfo = Get-MdfFileInfo $server $path

    }

    end {
        $server.ConnectionContext.Disconnect()
        return $mdfinfo
    }
}
tools\dbatools\functions\Get-DbaDiskSpace.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Get-DbaDiskSpace {
    <#
    .SYNOPSIS
        Displays disk information for all local disk on a server.

    .DESCRIPTION
        Returns a custom object with server name, name of disk, label of disk, total size, free size, percent free, block size and filesystem.

        By default, this function only shows drives of types 2 and 3 (removable disk and local disk).

        Requires Windows administrator access on SQL Servers

    .PARAMETER ComputerName
        The target computer. Defaults to localhost.

    .PARAMETER Credential
        Credential object used to connect to the computer as a different user.

    .PARAMETER Unit
        This parameter has been deprecated and will be removed in 1.0.0
        All properties previously generated through this command are present at the same time, but hidden by default.

    .PARAMETER CheckForSql
        If this switch is enabled, disks will be checked for SQL Server data and log files. Windows Authentication is always used for this.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER ExcludeDrive
        Filter out drives - format is C:\

    .PARAMETER Detailed
        Output all properties, will be deprecated in 1.0.0 release. Use Force Instead

    .PARAMETER CheckFragmentation
        If this switch is enabled, fragmentation of all filesystems will be checked.

        This will increase the runtime of the function by seconds or even minutes per volume.

    .PARAMETER Force
        Enabling this switch will cause the command to include ALL drives.
        By default, only local disks and removable disks are shown, and hidden volumes are excluded.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .NOTES
        Tags: Storage, Disk
        Author: Chrissy LeMaire (@cl), netnerds.net | Jakob Bindslet

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDiskSpace

    .EXAMPLE
        PS C:\> Get-DbaDiskSpace -ComputerName srv0042

        Get disk space for the server srv0042.

    .EXAMPLE
        PS C:\> Get-DbaDiskSpace -ComputerName srv0042 -Unit MB

        Get disk space for the server srv0042 and displays in megabytes (MB).

    .EXAMPLE
        PS C:\> Get-DbaDiskSpace -ComputerName srv0042, srv0007 -Unit TB

        Get disk space from two servers and displays in terabytes (TB).

    .EXAMPLE
        PS C:\> Get-DbaDiskSpace -ComputerName srv0042 -Force

        Get all disk and volume space information.

    .EXAMPLE
        PS C:\> Get-DbaDiskSpace -ComputerName srv0042 -ExcludeDrive 'C:\'

        Get all disk and volume space information.

    #>
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [Alias('ServerInstance', 'SqlInstance', 'SqlServer')]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [ValidateSet('Bytes', 'KB', 'MB', 'GB', 'TB', 'PB')]
        [string]$Unit = 'GB',
        [switch]$CheckForSql,
        [PSCredential]$SqlCredential,
        [string[]]$ExcludeDrive,
        [Alias('Detailed', 'AllDrives')]
        [switch]$CheckFragmentation,
        [switch]$Force,
        [switch][Alias('Silent')]
        $EnableException
    )

    begin {
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter Detailed
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter AllDrives
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter Unit

        $condition = " WHERE DriveType = 2 OR DriveType = 3"
        if (Test-Bound 'Force') {
            $condition = ""
        }

        # Keep track of what computer was already processed to avoid duplicates
        $processed = New-Object System.Collections.ArrayList

        <# In order to support properly identifying if a disk/volume is involved with ANY instance on a given computer #>
        $sqlDisks = New-Object System.Collections.ArrayList
    }

    process {
        foreach ($computer in $ComputerName) {
            if ($computer.ComputerName -notin $processed) {
                $null = $processed.Add($computer.ComputerName)
            } else {
                continue
            }

            try {
                $disks = Get-DbaCmObject -ComputerName $computer.ComputerName -Query "SELECT * FROM Win32_Volume$condition" -Credential $Credential -Namespace root\CIMv2 -ErrorAction Stop -WarningAction SilentlyContinue -EnableException
            } catch {
                Stop-Function -Message "Failed to connect to $computer." -EnableException $EnableException -ErrorRecord $_ -Target $computer.ComputerName -Continue
            }

            if ($CheckForSql) {
                try {
                    $sqlServices = Get-DbaService -ComputerName $computer -Type Engine
                } catch {
                    Write-Message -Level Warning -Message "Failed to connect to $computer to gather SQL Server instances, will not be reporting SQL Information." -ErrorRecord $_ -OverrideExceptionMessage -Target $computer.ComputerName
                }

                Write-Message -Level Verbose -Message "Instances found on $($computer): $($sqlServices.InstanceName.Count)"
                if ($sqlServices.InstanceName.Count -gt 0) {
                    foreach ($sqlService in $sqlServices) {
                        if ($sqlService.InstanceName -eq "MSSQLSERVER") {
                            $instanceName = $sqlService.ComputerName
                        } else {
                            $instanceName = "$($sqlService.ComputerName)\$($sqlService.InstanceName)"
                        }
                        Write-Message -Level VeryVerbose -Message "Processing instance $($instanceName)"
                        try {
                            $server = Connect-SqlInstance -SqlInstance $instanceName -SqlCredential $SqlCredential
                            if ($server.Version.Major -lt 9) {
                                $sql = "SELECT DISTINCT SUBSTRING(physical_name, 1, LEN(physical_name) - CHARINDEX('\', REVERSE(physical_name)) + 1) AS SqlDisk FROM sysaltfiles"
                            } else {
                                $sql = "SELECT DISTINCT SUBSTRING(physical_name, 1, LEN(physical_name) - CHARINDEX('\', REVERSE(physical_name)) + 1) AS SqlDisk FROM sys.master_files"
                            }
                            $results = $server.Query($sql)
                            if ($results.SqlDisk.Count -gt 0) {
                                foreach ($sqlDisk in $results.SqlDisk) {
                                    if (-not $sqlDisks.Contains($sqlDisk)) {
                                        $null = $sqlDisks.Add($sqlDisk)
                                    }
                                }
                            }
                        } catch {
                            Write-Message -Level Warning -Message "Failed to connect to $instanceName on $computer. SQL information may not be accurate or services have been stopped." -ErrorRecord $_ -OverrideExceptionMessage -Target $computer.ComputerName
                        }
                    }
                }
            }

            foreach ($disk in $disks) {
                if ($disk.Name -in $ExcludeDrive) {
                    continue
                }
                if ($disk.Name.StartsWith('\\') -and (-not $Force)) {
                    Write-Message -Level Verbose -Message "Skipping disk: $($disk.Name)" -Target $computer.ComputerName
                    continue
                }

                Write-Message -Level Verbose -Message "Processing disk: $($disk.Name)" -Target $computer.ComputerName

                $info = New-Object Sqlcollaborative.Dbatools.Computer.DiskSpace
                $info.ComputerName = $computer.ComputerName
                $info.Name = $disk.Name
                $info.Label = $disk.Label
                $info.Capacity = $disk.Capacity
                $info.Free = $disk.Freespace
                $info.BlockSize = $disk.BlockSize
                $info.FileSystem = $disk.FileSystem
                $info.Type = $disk.DriveType

                if ($CheckForSql) {
                    $drivePath = $disk.Name
                    $info.IsSqlDisk = $false
                    foreach ($sqlDisk in $sqlDisks) {
                        if ($sqlDisk -like ($drivePath + '*')) {
                            $info.IsSqlDisk = $true
                            break
                        }
                    }
                }
                $info
            }
        }
    }
}
tools\dbatools\functions\Get-DbaDump.ps1
function Get-DbaDump {
    <#
    .SYNOPSIS
        Locate a SQL Server that has generated any memory dump files.

    .DESCRIPTION
        The type of dump included in the search include minidump, all-thread dump, or a full dump.  The files have an extendion of .mdmp.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Engine, Corruption
        Author: Garry Bargsley (@gbargsley), http://blog.garrybargsley.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaDump

    .EXAMPLE
        PS C:\> Get-DbaDump -SqlInstance sql2016

        Shows the detailed information for memory dump(s) located on sql2016 instance

    .EXAMPLE
        PS C:\> Get-DbaDump -SqlInstance sql2016 -SqlCredential sqladmin

        Shows the detailed information for memory dump(s) located on sql2016 instance. Logs into the SQL Server using the SQL login 'sqladmin'

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )
    begin {
        $sql = "SELECT filename,  creation_time,  size_in_bytes FROM sys.dm_server_memory_dumps"
    }

    process {
        foreach ($instance in $SqlInstance) {
            $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential

            if ($server.versionMajor -lt 11 -and (-not ($server.versionMajor -eq 10 -and $server.versionMinor -eq 50))) {
                Stop-Function -Message "This function does not support versions lower than SQL Server 2008 R2 (v10.50). Skipping server '$instance'" -Continue
            }

            try {
                foreach ($result in $server.Query($sql)) {
                    [PSCustomObject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        FileName     = $result.filename
                        CreationTime = $result.creation_time
                        Size         = [dbasize]$result.size_in_bytes
                    }
                }
            } catch {
                Stop-Function -Message "Issue collecting data on $server" -Target $server -ErrorRecord $_ -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaEndpoint.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaEndpoint {
    <#
    .SYNOPSIS
        Returns endpoint objects from a SQL Server instance.

    .DESCRIPTION
        Returns endpoint objects from a SQL Server instance.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Endpoint
        Return only specific endpoints.

    .PARAMETER Type
        Return only specific types of endpoints. Options include: DatabaseMirroring, ServiceBroker, Soap, and TSql.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Endpoint
        Author: Garry Bargsley (@gbargsley), http://blog.garrybargsley.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaEndpoint

    .EXAMPLE
        PS C:\> Get-DbaEndpoint -SqlInstance localhost

        Returns all endpoints on the local default SQL Server instance

    .EXAMPLE
        PS C:\> Get-DbaEndpoint -SqlInstance localhost, sql2016

        Returns all endpoints for the local and sql2016 SQL Server instances

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Endpoint,
        [ValidateSet('DatabaseMirroring', 'ServiceBroker', 'Soap', 'TSql')]
        [string[]]$Type,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            # Not sure why minimumversion isnt working
            if ($server.VersionMajor -lt 9) {
                Stop-Function -Message "SQL Server version 9 required - $instance not supported." -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $endpoints = $server.Endpoints

            if ($endpoint) {
                $endpoints = $endpoints | Where-Object Name -in $endpoint
            }
            if ($Type) {
                $endpoints = $endpoints | Where-Object EndpointType -in $Type
            }

            foreach ($end in $endpoints) {
                Write-Message -Level Verbose -Message "Getting endpoint $($end.Name) on $($server.Name)"
                if ($end.Protocol.Tcp.ListenerPort) {
                    if ($instance.ComputerName -match '\.') {
                        $dns = $instance.ComputerName
                    } else {
                        try {
                            $dns = [System.Net.Dns]::GetHostEntry($instance.ComputerName).HostName
                        } catch {
                            try {
                                $dns = [System.Net.Dns]::GetHostAddresses($instance.ComputerName)
                            } catch {
                                $dns = $instance.ComputerName
                            }
                        }
                    }

                    $fqdn = "TCP://" + $dns + ":" + $end.Protocol.Tcp.ListenerPort
                } else {
                    $fqdn = $null
                }

                Add-Member -Force -InputObject $end -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName
                Add-Member -Force -InputObject $end -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName
                Add-Member -Force -InputObject $end -MemberType NoteProperty -Name SqlInstance -Value $server.DomainInstanceName
                Add-Member -Force -InputObject $end -MemberType NoteProperty -Name Fqdn -Value $fqdn
                Add-Member -Force -InputObject $end -MemberType NoteProperty -Name Port -Value $end.Protocol.Tcp.ListenerPort
                if ($end.Protocol.Tcp.ListenerPort) {
                    Select-DefaultView -InputObject $end -Property ComputerName, InstanceName, SqlInstance, ID, Name, Port, EndpointState, EndpointType, Owner, IsAdminEndpoint, Fqdn, IsSystemObject
                } else {
                    Select-DefaultView -InputObject $end -Property ComputerName, InstanceName, SqlInstance, ID, Name, EndpointState, EndpointType, Owner, IsAdminEndpoint, Fqdn, IsSystemObject
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaErrorLog.ps1
function Get-DbaErrorLog {
    <#
    .SYNOPSIS
        Gets the "SQL Error Log" of an instance

    .DESCRIPTION
        Gets the "SQL Error Log" of an instance. Returns all 10 error logs by default.

    .PARAMETER SqlInstance
        TThe target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.

    .PARAMETER LogNumber
        An Int32 value that specifies the index number of the error log required.
        Error logs are listed 0 through 99, where 0 is the current error log and 99 is potential oldest log file.

        SQL Server errorlog rollover defaults to 6, but can be increased to 99. https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/scm-services-configure-sql-server-error-logs

    .PARAMETER Source
        Filter results based on the Source of the error (e.g. Logon, Server, etc.)

    .PARAMETER Text
        Filter results based on a pattern of text (e.g. "login failed", "error: 12345").

    .PARAMETER After
        Filter the results based on datetime value.

    .PARAMETER Before
        Filter the results based on datetime value.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Instance, ErrorLog
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaErrorLog

    .EXAMPLE
        PS C:\> Get-DbaErrorLog -SqlInstance sql01\sharepoint

        Returns every log entry from sql01\sharepoint SQL Server instance.

    .EXAMPLE
        PS C:\> Get-DbaErrorLog -SqlInstance sql01\sharepoint -LogNumber 3, 6

        Returns all log entries for log number 3 and 6 on sql01\sharepoint SQL Server instance.

    .EXAMPLE
        PS C:\> Get-DbaErrorLog -SqlInstance sql01\sharepoint -Source Logon

        Returns every log entry, with a source of Logon, from sql01\sharepoint SQL Server instance.

    .EXAMPLE
        PS C:\> Get-DbaErrorLog -SqlInstance sql01\sharepoint -LogNumber 3 -Text "login failed"

        Returns every log entry for log number 3, with "login failed" in the text, from sql01\sharepoint SQL Server instance.

    .EXAMPLE
        PS C:\> $servers = "sql2014","sql2016", "sqlcluster\sharepoint"
        PS C:\> $servers | Get-DbaErrorLog -LogNumber 0

        Returns the most recent SQL Server error logs for "sql2014","sql2016" and "sqlcluster\sharepoint"

    .EXAMPLE
        PS C:\> Get-DbaErrorLog -SqlInstance sql01\sharepoint -After '2016-11-14 00:00:00'

        Returns every log entry found after the date 14 November 2016 from sql101\sharepoint SQL Server instance.

    .EXAMPLE
        PS C:\> Get-DbaErrorLog -SqlInstance sql01\sharepoint -Before '2016-08-16 00:00:00'

        Returns every log entry found before the date 16 August 2016 from sql101\sharepoint SQL Server instance.

    #>
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [ValidateRange(0, 99)]
        [int[]]$LogNumber,
        [object[]]$Source,
        [string]$Text,
        [datetime]$After,
        [datetime]$Before,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Get-DbaLog
    }
    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($LogNumber) {
                foreach ($number in $lognumber) {
                    foreach ($object in $server.ReadErrorLog($number)) {
                        if ( ($Source -and $object.ProcessInfo -ne $Source) -or ($Text -and $object.Text -notlike "*$Text*") -or ($After -and $object.LogDate -lt $After) -or ($Before -and $object.LogDate -gt $Before) ) {
                            continue
                        }
                        Write-Message -Level Verbose -Message "Processing $object"
                        Add-Member -Force -InputObject $object -MemberType NoteProperty ComputerName -value $server.ComputerName
                        Add-Member -Force -InputObject $object -MemberType NoteProperty InstanceName -value $server.ServiceName
                        Add-Member -Force -InputObject $object -MemberType NoteProperty SqlInstance -value $server.DomainInstanceName

                        # Select all of the columns you'd like to show
                        Select-DefaultView -InputObject $object -Property ComputerName, InstanceName, SqlInstance, LogDate, 'ProcessInfo as Source', Text
                    }
                }
            } else {
                foreach ($object in $server.ReadErrorLog()) {
                    if ( ($Source -and $object.ProcessInfo -ne $Source) -or ($Text -and $object.Text -notlike "*$Text*") -or ($After -and $object.LogDate -lt $After) -or ($Before -and $object.LogDate -gt $Before) ) {
                        continue
                    }
                    Write-Message -Level Verbose -Message "Processing $object"
                    Add-Member -Force -InputObject $object -MemberType NoteProperty ComputerName -value $server.ComputerName
                    Add-Member -Force -InputObject $object -MemberType NoteProperty InstanceName -value $server.ServiceName
                    Add-Member -Force -InputObject $object -MemberType NoteProperty SqlInstance -value $server.DomainInstanceName

                    # Select all of the columns you'd like to show
                    Select-DefaultView -InputObject $object -Property ComputerName, InstanceName, SqlInstance, LogDate, 'ProcessInfo as Source', Text
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaErrorLogConfig.ps1
function Get-DbaErrorLogConfig {
    <#
    .SYNOPSIS
        Pulls the configuration for the ErrorLog on a given SQL Server instance

    .DESCRIPTION
        Pulls the configuration for the ErrorLog on a given SQL Server instance.

        Includes error log path, number of log files configured and size (SQL Server 2012+ only)

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Instance, ErrorLog
        Author: Shawn Melton (@wsmelton), https://wsmelton.github.io

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaErrorLogConfig

    .EXAMPLE
        PS C:\> Get-DbaErrorLogConfig -SqlInstance server2017,server2014

        Returns error log configuration for server2017 and server2014

    #>
    [cmdletbinding()]
    param (
        [Parameter(ValueFromPipeline, Mandatory)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $numLogs = $server.NumberOfLogFiles
            $logSize =
            if ($server.VersionMajor -ge 11) {
                [dbasize]($server.ErrorLogSizeKb * 1024)
            } else {
                $null
            }

            [PSCustomObject]@{
                ComputerName = $server.ComputerName
                InstanceName = $server.ServiceName
                SqlInstance  = $server.DomainInstanceName
                LogCount     = $numLogs
                LogSize      = $logSize
                LogPath      = $server.ErrorLogPath
            }
        }
    }
}
tools\dbatools\functions\Get-DbaEstimatedCompletionTime.ps1
function Get-DbaEstimatedCompletionTime {
    <#
    .SYNOPSIS
        Gets execution and estimated completion time information for queries

    .DESCRIPTION
        Gets execution and estimated completion time information for queries

        Percent complete will show for the following commands

        ALTER INDEX REORGANIZE
        AUTO_SHRINK option with ALTER DATABASE
        BACKUP DATABASE
        DBCC CHECKDB
        DBCC CHECKFILEGROUP
        DBCC CHECKTABLE
        DBCC INDEXDEFRAG
        DBCC SHRINKDATABASE
        DBCC SHRINKFILE
        RECOVERY
        RESTORE DATABASE
        ROLLBACK
        TDE ENCRYPTION

        For additional information, check out https://blogs.sentryone.com/loriedwards/patience-dm-exec-requests/ and https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-exec-requests-transact-sql

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        SqlCredential object used to connect to the SQL Server as a different user.

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaEstimatedCompletionTime

    .EXAMPLE
        PS C:\> Get-DbaEstimatedCompletionTime -SqlInstance sql2016

        Gets estimated completion times for queries performed against the entire server

    .EXAMPLE
        PS C:\> Get-DbaEstimatedCompletionTime -SqlInstance sql2016 | Select *

        Gets estimated completion times for queries performed against the entire server PLUS the SQL query text of each command

    .EXAMPLE
        PS C:\> Get-DbaEstimatedCompletionTime -SqlInstance sql2016 | Where-Object { $_.Text -match 'somequerytext' }

        Gets results for commands whose queries only match specific text (match is like LIKE but way more powerful)

    .EXAMPLE
        PS C:\> Get-DbaEstimatedCompletionTime -SqlInstance sql2016 -Database Northwind,pubs,Adventureworks2014

        Gets estimated completion times for queries performed against the Northwind, pubs, and Adventureworks2014 databases

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $sql = "SELECT
                DB_NAME(r.database_id) as [Database],
                USER_NAME(r.user_id) as [Login],
                Command,
                start_time as StartTime,
                percent_complete as PercentComplete,

                  RIGHT('00000' + CAST(((DATEDIFF(s,start_time,GetDate()))/3600) as varchar),
                                CASE
                                    WHEN LEN(((DATEDIFF(s,start_time,GetDate()))/3600)) < 2 THEN 2
                                    ELSE LEN(((DATEDIFF(s,start_time,GetDate()))/3600))
                                 END)  + ':'
                + RIGHT('00' + CAST((DATEDIFF(s,start_time,GetDate())%3600)/60 as varchar), 2) + ':'
                + RIGHT('00' + CAST((DATEDIFF(s,start_time,GetDate())%60) as varchar), 2) as RunningTime,

                  RIGHT('00000' + CAST((estimated_completion_time/3600000) as varchar),
                        CASE
                                    WHEN LEN((estimated_completion_time/3600000)) < 2 THEN 2
                                    ELSE LEN((estimated_completion_time/3600000))
                         END)  + ':'
                + RIGHT('00' + CAST((estimated_completion_time %3600000)/60000 as varchar), 2) + ':'
                + RIGHT('00' + CAST((estimated_completion_time %60000)/1000 as varchar), 2) as EstimatedTimeToGo,
                dateadd(second,estimated_completion_time/1000, getdate()) as EstimatedCompletionTime,
                s.Text
             FROM sys.dm_exec_requests r
            CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) s"
    }

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential

            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($Database) {
                $includedatabases = $Database -join "','"
                $sql = "$sql WHERE DB_NAME(r.database_id) in ('$includedatabases')"
            }

            if ($ExcludeDatabase) {
                $excludedatabases = $ExcludeDatabase -join "','"
                $sql = "$sql WHERE DB_NAME(r.database_id) not in ('$excludedatabases')"
            }

            Write-Message -Level Debug -Message $sql
            foreach ($row in ($server.Query($sql))) {
                [pscustomobject]@{
                    ComputerName            = $server.ComputerName
                    InstanceName            = $server.ServiceName
                    SqlInstance             = $server.DomainInstanceName
                    Database                = $row.Database
                    Login                   = $row.Login
                    Command                 = $row.Command
                    PercentComplete         = $row.PercentComplete
                    StartTime               = $row.StartTime
                    RunningTime             = $row.RunningTime
                    EstimatedTimeToGo       = $row.EstimatedTimeToGo
                    EstimatedCompletionTime = $row.EstimatedCompletionTime
                    Text                    = $row.Text
                } | Select-DefaultView -ExcludeProperty Text
            }
        }
    }
}
tools\dbatools\functions\Get-DbaExecutionPlan.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaExecutionPlan {
    <#
    .SYNOPSIS
        Gets execution plans and metadata

    .DESCRIPTION
        Gets execution plans and metadata. Can pipe to Export-DbaExecutionPlan

        Thanks to following for the queries:
        https://www.simple-talk.com/sql/t-sql-programming/dmvs-for-query-plan-metadata/
        http://www.scarydba.com/2017/02/13/export-plans-cache-sqlplan-file/

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Credential object used to connect to the SQL Server as a different user

    .PARAMETER Database
        Return execution plans and metadata for only specific databases.

    .PARAMETER ExcludeDatabase
        Return execution plans and metadata for all but these specific databases

    .PARAMETER SinceCreation
        Datetime object used to narrow the results to a date

    .PARAMETER SinceLastExecution
        Datetime object used to narrow the results to a date

    .PARAMETER ExcludeEmptyQueryPlan
        Exclude results with empty query plan

    .PARAMETER Force
        Returns a ton of raw information about the execution plans

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Performance
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaExecutionPlan

    .EXAMPLE
        PS C:\> Get-DbaExecutionPlan -SqlInstance sqlserver2014a

        Gets all execution plans on  sqlserver2014a

    .EXAMPLE
        PS C:\> Get-DbaExecutionPlan -SqlInstance sqlserver2014a -Database db1, db2 -SinceLastExecution '2016-07-01 10:47:00'

        Gets all execution plans for databases db1 and db2 on sqlserver2014a since July 1, 2016 at 10:47 AM.

    .EXAMPLE
        PS C:\> Get-DbaExecutionPlan -SqlInstance sqlserver2014a, sql2016 -Exclude db1 | Format-Table

        Gets execution plan info for all databases except db1 on sqlserver2014a and sql2016 and makes the output pretty

    .EXAMPLE
        PS C:\> Get-DbaExecutionPlan -SqlInstance sql2014 -Database AdventureWorks2014, pubs -Force

        Gets super detailed information for execution plans on only for AdventureWorks2014 and pubs

    .EXAMPLE
        PS C:\> $servers = "sqlserver2014a","sql2016t"
        PS C:\> $servers | Get-DbaExecutionPlan -Force

        Gets super detailed information for execution plans on sqlserver2014a and sql2016

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [datetime]$SinceCreation,
        [datetime]$SinceLastExecution,
        [switch]$ExcludeEmptyQueryPlan,
        [switch]$Force,
        [switch]$EnableException
    )

    process {

        foreach ($instance in $sqlinstance) {
            try {
                try {
                    $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential -MinimumVersion 9
                } catch {
                    Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                }

                if ($force -eq $true) {
                    $select = "SELECT * "
                } else {
                    $select = "SELECT DB_NAME(deqp.dbid) as DatabaseName, OBJECT_NAME(deqp.objectid) as ObjectName,
                    detqp.query_plan AS SingleStatementPlan,
                    deqp.query_plan AS BatchQueryPlan,
                    ROW_NUMBER() OVER ( ORDER BY Statement_Start_offset ) AS QueryPosition,
                    sql_handle as SqlHandle,
                    plan_handle as PlanHandle,
                    creation_time as CreationTime,
                    last_execution_time as LastExecutionTime"
                }

                $from = " FROM sys.dm_exec_query_stats deqs
                        CROSS APPLY sys.dm_exec_text_query_plan(deqs.plan_handle,
                            deqs.statement_start_offset,
                            deqs.statement_end_offset) AS detqp
                        CROSS APPLY sys.dm_exec_query_plan(deqs.plan_handle) AS deqp
                        CROSS APPLY sys.dm_exec_sql_text(deqs.plan_handle) AS execText"

                if ($ExcludeDatabase -or $Database -or $SinceCreation -or $SinceLastExecution -or $ExcludeEmptyQueryPlan -eq $true) {
                    $where = " WHERE "
                }

                $wherearray = @()

                if ($Database) {
                    $dblist = $Database -join "','"
                    $wherearray += " DB_NAME(deqp.dbid) in ('$dblist') "
                }

                if ($null -ne $SinceCreation) {
                    Write-Message -Level Verbose -Message "Adding creation time"
                    $wherearray += " creation_time >= '" + $SinceCreation.ToString("yyyy-MM-dd HH:mm:ss") + "' "
                }

                if ($null -ne $SinceLastExecution) {
                    Write-Message -Level Verbose -Message "Adding last exectuion time"
                    $wherearray += " last_execution_time >= '" + $SinceLastExecution.ToString("yyyy-MM-dd HH:mm:ss") + "' "
                }

                if ($ExcludeDatabase) {
                    $dblist = $ExcludeDatabase -join "','"
                    $wherearray += " DB_NAME(deqp.dbid) not in ('$dblist') "
                }

                if ($ExcludeEmptyQueryPlan) {
                    $wherearray += " detqp.query_plan is not null"
                }

                if ($where.length -gt 0) {
                    $wherearray = $wherearray -join " and "
                    $where = "$where $wherearray"
                }

                $sql = "$select $from $where"
                Write-Message -Level Debug -Message $sql

                if ($Force -eq $true) {
                    $server.Query($sql)
                } else {
                    foreach ($row in $server.Query($sql)) {
                        $simple = ([xml]$row.SingleStatementPlan).ShowPlanXML.BatchSequence.Batch.Statements.StmtSimple
                        $sqlhandle = "0x"; $row.sqlhandle | ForEach-Object { $sqlhandle += ("{0:X}" -f $_).PadLeft(2, "0") }
                        $planhandle = "0x"; $row.planhandle | ForEach-Object { $planhandle += ("{0:X}" -f $_).PadLeft(2, "0") }
                        $planWarnings = $simple.QueryPlan.Warnings.PlanAffectingConvert;

                        [pscustomobject]@{
                            ComputerName                      = $server.ComputerName
                            InstanceName                      = $server.ServiceName
                            SqlInstance                       = $server.DomainInstanceName
                            DatabaseName                      = $row.DatabaseName
                            ObjectName                        = $row.ObjectName
                            QueryPosition                     = $row.QueryPosition
                            SqlHandle                         = $SqlHandle
                            PlanHandle                        = $PlanHandle
                            CreationTime                      = $row.CreationTime
                            LastExecutionTime                 = $row.LastExecutionTime
                            StatementCondition                = ([xml]$row.SingleStatementPlan).ShowPlanXML.BatchSequence.Batch.Statements.StmtCond
                            StatementSimple                   = $simple
                            StatementId                       = $simple.StatementId
                            StatementCompId                   = $simple.StatementCompId
                            StatementType                     = $simple.StatementType
                            RetrievedFromCache                = $simple.RetrievedFromCache
                            StatementSubTreeCost              = $simple.StatementSubTreeCost
                            StatementEstRows                  = $simple.StatementEstRows
                            SecurityPolicyApplied             = $simple.SecurityPolicyApplied
                            StatementOptmLevel                = $simple.StatementOptmLevel
                            QueryHash                         = $simple.QueryHash
                            QueryPlanHash                     = $simple.QueryPlanHash
                            StatementOptmEarlyAbortReason     = $simple.StatementOptmEarlyAbortReason
                            CardinalityEstimationModelVersion = $simple.CardinalityEstimationModelVersion

                            ParameterizedText                 = $simple.ParameterizedText
                            StatementSetOptions               = $simple.StatementSetOptions
                            QueryPlan                         = $simple.QueryPlan
                            BatchConditionXml                 = ([xml]$row.BatchQueryPlan).ShowPlanXML.BatchSequence.Batch.Statements.StmtCond
                            BatchSimpleXml                    = ([xml]$row.BatchQueryPlan).ShowPlanXML.BatchSequence.Batch.Statements.StmtSimple
                            BatchQueryPlanRaw                 = [xml]$row.BatchQueryPlan
                            SingleStatementPlanRaw            = [xml]$row.SingleStatementPlan
                            PlanWarnings                      = $planWarnings
                        } | Select-DefaultView -ExcludeProperty BatchQueryPlan, SingleStatementPlan, BatchConditionXmlRaw, BatchQueryPlanRaw, SingleStatementPlanRaw, PlanWarnings
                    }
                }
            } catch {
                Stop-Function -Message "Query Failure Failure" -ErrorRecord $_ -Target $instance -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaFeature.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Get-DbaFeature {
    <#
    .SYNOPSIS
        Runs the SQL Server feature discovery report (setup.exe /Action=RunDiscovery)

    .DESCRIPTION
        Runs the SQL Server feature discovery report (setup.exe /Action=RunDiscovery)

        Inspired by Dave Mason's (@BeginTry) post at
        https://itsalljustelectrons.blogspot.be/2018/04/SQL-Server-Discovery-Report.html

        Assumptions:
        1. The sub-folder "Microsoft SQL Server" exists in $env:ProgramFiles,
        even if SQL was installed to a non-default path. This has been
        verified on SQL 2008R2 and SQL 2012. Further verification may be needed.
        2. The discovery report displays installed components for the version of SQL
        Server associated with setup.exe, along with installed components of all
        lesser versions of SQL Server that are installed.

    .PARAMETER ComputerName
        The target computer. If the target is not localhost, it must have PowerShell remoting enabled.

        Note that this is not the SqlInstance, but rather the ComputerName

    .PARAMETER Credential
        Allows you to login to servers using alternative credentials. To use:

        $cred = Get-Credential, then pass $cred object to the -Credential parameter.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Feature, Component
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaFeature

    .EXAMPLE
        PS C:\> Get-DbaFeature -ComputerName sql2017, sql2016, sql2005

        Gets all SQL Server features for all instances on sql2017, sql2016 and sql2005.

    .EXAMPLE
        PS C:\> Get-DbaFeature -Verbose

        Gets all SQL Server features for all instances on localhost. Outputs to screen if no instances are found.

    .EXAMPLE
        PS C:\> Get-DbaFeature -ComputerName sql2017 -Credential ad\sqldba

        Gets all SQL Server features for all instances on sql2017 using the ad\sqladmin credential (which has access to the Windows Server).

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [switch]$EnableException
    )

    begin {
        $scriptblock = {
            $setup = Get-ChildItem -Recurse -Include setup.exe -Path "$env:ProgramFiles\Microsoft SQL Server" -ErrorAction SilentlyContinue |
                Where-Object { $_.FullName -match 'Setup Bootstrap\\SQL' -or $_.FullName -match 'Bootstrap\\Release\\Setup.exe' -or $_.FullName -match 'Bootstrap\\Setup.exe' } |
                Sort-Object FullName -Descending | Select-Object -First 1
            if ($setup) {
                $null = Start-Process -FilePath $setup.FullName -ArgumentList "/Action=RunDiscovery /q" -Wait
                $parent = Split-Path (Split-Path $setup.Fullname)
                $xmlfile = Get-ChildItem -Recurse -Include SqlDiscoveryReport.xml -Path $parent | Sort-Object LastWriteTime -Descending | Select-Object -First 1

                if ($xmlfile) {
                    $xml = [xml](Get-Content -Path $xmlfile)
                    $xml.ArrayOfDiscoveryInformation.DiscoveryInformation
                }
            }
        }
    }

    process {
        foreach ($computer in $ComputerName) {
            try {
                $results = Invoke-Command2 -ComputerName $Computer -ScriptBlock $scriptblock -Credential $Credential -Raw

                if (-not $results) {
                    Write-Message -Level Verbose -Message "No features found on $computer"
                }

                foreach ($result in $results) {
                    [pscustomobject]@{
                        ComputerName = $computer
                        Product      = $result.Product
                        Instance     = $result.Instance
                        InstanceID   = $result.InstanceID
                        Feature      = $result.Feature
                        Language     = $result.Language
                        Edition      = $result.Edition
                        Version      = $result.Version
                        Clustered    = $result.Clustered
                        Configured   = $result.Configured
                    }
                }
            } catch {
                Stop-Function -Continue -ErrorRecord $_ -Message "Failure"
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaSqlFeature
    }
}
tools\dbatools\functions\Get-DbaFile.ps1
function Get-DbaFile {
    <#
    .SYNOPSIS
        Get-DbaFile finds files in any directory specified on a remote SQL Server

    .DESCRIPTION
        This command searches all specified directories, allowing a DBA to see file information on a server without direct access

        You can filter by extension using the -FileType parameter. By default, the default data directory will be returned. You can provide and additional paths to search using the -Path parameter.

        Thanks to serg-52 for the query:  https://www.sqlservercentral.com/Forums/Topic1642213-391-1.aspx

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Allows you to login to servers using alternative credentials

    .PARAMETER Path
        Used to specify extra directories to search in addition to the default data directory.

    .PARAMETER FileType
        Used to specify filter by filetype. No dot required, just pass the extension.

    .PARAMETER Depth
        Used to specify recursive folder depth.  Default is 1, non-recursive.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Discovery
        Author: Brandon Abshire, netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaFile

    .EXAMPLE
        PS C:\> Get-DbaFile -SqlInstance sqlserver2014a -Path E:\Dir1

        Logs into the SQL Server "sqlserver2014a" using Windows credentials and searches E:\Dir for all files

    .EXAMPLE
        PS C:\> Get-DbaFile -SqlInstance sqlserver2014a -SqlCredential $cred -Path 'E:\sql files'

        Logs into the SQL Server "sqlserver2014a" using alternative credentials and returns all files in 'E:\sql files'

    .EXAMPLE
        PS C:\> $all = Get-DbaDefaultPath -SqlInstance sql2014
        PS C:\> Get-DbaFile -SqlInstance sql2014 -Path $all.Data, $all.Log, $all.Backup -Depth 3

        Returns the files in the default data, log and backup directories on sql2014, 3 directories deep (recursively).

    .EXAMPLE
        PS C:\> Get-DbaFile -SqlInstance sql2014 -Path 'E:\Dir1', 'E:\Dir2'

        Returns the files in "E:\Dir1" and "E:Dir2" on sql2014

    .EXAMPLE
        PS C:\> Get-DbaFile -SqlInstance sql2014, sql2016 -Path 'E:\Dir1' -FileType fsf, mld

        Finds files in E:\Dir1 ending with ".fsf" and ".mld" for both the servers sql2014 and sql2016.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Path,
        [string[]]$FileType,
        [int]$Depth = 1,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        $sql = ""

        function Get-SQLDirTreeQuery {
            param
            (
                $PathList
            )

            $q1 += "DECLARE @myPath nvarchar(4000);
                    DECLARE @depth SMALLINT = $Depth;

                    IF OBJECT_ID('tempdb..#DirectoryTree') IS NOT NULL
                    DROP TABLE #DirectoryTree;

                    CREATE TABLE #DirectoryTree (
                       id int IDENTITY(1,1)
                       ,subdirectory nvarchar(512)
                       ,depth int
                       ,isfile bit
                       , ParentDirectory int
                       ,flag tinyint default(0));"

            $q2 = "SET @myPath = 'dirname'
                    -- top level directory
                    INSERT #DirectoryTree (subdirectory,depth,isfile)
                       VALUES (@myPath,0,0);
                    -- all the rest under top level
                    INSERT #DirectoryTree (subdirectory,depth,isfile)
                       EXEC master.sys.xp_dirtree @myPath,@depth,1;


                    UPDATE #DirectoryTree
                       SET ParentDirectory = (
                          SELECT MAX(Id) FROM #DirectoryTree
                          WHERE Depth = d.Depth - 1 AND Id < d.Id   )
                    FROM #DirectoryTree d
                    WHERE ParentDirectory is NULL;"

            $query_files_sql = "-- SEE all with full paths
                    WITH dirs AS (
                        SELECT
                           Id,subdirectory,depth,isfile,ParentDirectory,flag
                           , CAST (null AS NVARCHAR(MAX)) AS container
                           , CAST([subdirectory] AS NVARCHAR(MAX)) AS dpath
                           FROM #DirectoryTree
                           WHERE ParentDirectory IS NULL
                        UNION ALL
                        SELECT
                           d.Id,d.subdirectory,d.depth,d.isfile,d.ParentDirectory,d.flag
                           , dpath as container
                           , dpath +'\'+d.[subdirectory]
                        FROM #DirectoryTree AS d
                        INNER JOIN dirs ON  d.ParentDirectory = dirs.id
                        WHERE dpath NOT LIKE '%RECYCLE.BIN%'
                    )
                    SELECT subdirectory as filename, container as filepath, isfile, dpath as fullpath FROM dirs
                    WHERE container IS NOT NULL
                    -- Dir style ordering
                    ORDER BY container, isfile, subdirectory"

            # build the query string based on how many directories they want to enumerate
            $sql = $q1
            $sql += $($PathList | Where-Object { $_ -ne '' } | ForEach-Object { "$([System.Environment]::Newline)$($q2 -Replace 'dirname', $_)" })
            $sql += $query_files_sql
            #Write-Message -Level Debug -Message $sql
            return $sql
        }

        function Format-Path {
            param ($path)
            $path = $path.Trim()
            #Thank you windows 2000
            $path = $path -replace '[^A-Za-z0-9 _\.\-\\:]', '__'
            return $path
        }

        if ($FileType) {
            $FileTypeComparison = $FileType | ForEach-Object { $_.ToLower() } | Where-Object { $_ } | Sort-Object | Get-Unique
        }
    }

    process {
        foreach ($instance in $SqlInstance) {

            #Variable marked as unused by PSScriptAnalyzer
            #$paths = @()
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            # Get the default data and log directories from the instance
            if (-not (Test-Bound -ParameterName Path)) { $Path = (Get-DbaDefaultPath -SqlInstance $server).Data }

            Write-Message -Level Verbose -Message "Adding paths"
            $sql = Get-SQLDirTreeQuery $Path
            Write-Message -Level Debug -Message $sql

            # This should remain as not .Query() to be compat with a PSProvider Chrissy is working on
            $datatable = $server.ConnectionContext.ExecuteWithResults($sql).Tables.Rows

            Write-Message -Level Verbose -Message "$($datatable.Rows.Count) files found."
            if ($FileTypeComparison) {
                foreach ($row in $datatable) {
                    foreach ($type in $FileTypeComparison) {
                        if ($row.filename.ToLower().EndsWith(".$type")) {
                            [pscustomobject]@{
                                ComputerName   = $server.ComputerName
                                InstanceName   = $server.ServiceName
                                SqlInstance    = $server.DomainInstanceName
                                Filename       = $row.fullpath
                                RemoteFilename = Join-AdminUnc -Servername $server.ComputerName -Filepath $row.fullpath
                            } | Select-DefaultView -ExcludeProperty ComputerName, InstanceName, RemoteFilename
                        }
                    }
                }
            } else {
                foreach ($row in $datatable) {
                    [pscustomobject]@{
                        ComputerName   = $server.ComputerName
                        InstanceName   = $server.ServiceName
                        SqlInstance    = $server.DomainInstanceName
                        Filename       = $row.fullpath
                        RemoteFilename = Join-AdminUnc -Servername $server.ComputerName -Filepath $row.fullpath
                    } | Select-DefaultView -ExcludeProperty ComputerName, InstanceName, RemoteFilename
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaFilestream.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Get-DbaFilestream {
    <#
    .SYNOPSIS
        Returns the status of Filestream on specified SQL Server for both the Service and Instance levels.

    .DESCRIPTION
        Returns the status of Filestream on specified SQL Server for both the Service and Instance levels.

    .PARAMETER SqlInstance
        SQL Server name or SMO object representing the SQL Server to connect to. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Defaults to localhost.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Credential
        Login to the target Windows server using alternative credentials.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Filestream
        Author: Stuart Moore ( @napalmgram ) | Chrissy LeMaire ( @cl )
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaFilestream

    .EXAMPLE
        PS C:\> Get-DbaFilestream -SqlInstance server1\instance2

        Will return the status of Filestream configuration for the service and instance server1\instance2

    .EXAMPLE
        PS C:\> Get-DbaFilestream -SqlInstance server1\instance2 -SqlCredential sqladmin

        Prompts for the password to the SQL Login "sqladmin" then returns the status of Filestream configuration for the service and instance server1\instance2
       #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [PSCredential]$Credential,
        [switch]$EnableException
    )
    begin {
        $idServiceFS = [ordered]@{
            0 = 'Disabled'
            1 = 'FileStream enabled for T-Sql access'
            2 = 'FileStream enabled for T-Sql and IO streaming access'
            3 = 'FileStream enabled for T-Sql, IO streaming, and remote clients'
        }

        $idInstanceFS = [ordered]@{
            0 = 'Disabled'
            1 = 'T-SQL access enabled'
            2 = 'Full access enabled'
        }
    }
    process {
        foreach ($instance in $SqlInstance) {
            $computer = $instance.ComputerName
            $instanceName = $instance.InstanceName

            <# Get Service-Level information #>
            if ($instance.IsLocalHost) {
                $computerName = $computer
            } else {
                $computerName = (Resolve-DbaNetworkName -ComputerName $computer -Credential $Credential).FullComputerName
            }

            Write-Message -Level Verbose -Message "Attempting to connect to $computer"
            try {
                $ognamespace = Get-DbaCmObject -EnableException -ComputerName $computerName -Namespace root\Microsoft\SQLServer -Query "SELECT NAME FROM __NAMESPACE WHERE NAME LIKE 'ComputerManagement%'"
                $namespace = $ognamespace | Where-Object {
                    (Get-DbaCmObject -EnableException -ComputerName $computerName -Namespace $("root\Microsoft\SQLServer\" + $_.Name) -ClassName FilestreamSettings).Count -gt 0
                } |
                    Sort-Object Name -Descending | Select-Object -First 1

                if (-not $namespace) {
                    $namespace = $ognamespace
                }

                if ($namespace.Name) {
                    $serviceFS = Get-DbaCmObject -EnableException -ComputerName $computerName -Namespace $("root\Microsoft\SQLServer\" + $namespace.Name) -ClassName FilestreamSettings | Where-Object InstanceName -eq $instanceName | Select-Object -First 1
                } else {
                    Write-Message -Level Warning -Message "No ComputerManagement was found on $computer. Service level information may not be collected." -Target $computer
                }
            } catch {
                Stop-Function -Message "Issue collecting service-level information on $computer for $instanceName" -Target $computer -ErrorRecord $_ -Continue
            }

            <# Get Instance-Level information #>
            try {
                Write-Message -Level Verbose -Message "Connecting to $instance."
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            try {
                $instanceFS = Get-DbaSpConfigure -SqlInstance $server -Name FilestreamAccessLevel | Select-Object ConfiguredValue, RunningValue
            } catch {
                Stop-Function -Message "Issue collection instance-level configuration on $instanceName" -Target $server -ErrorRecord $_ -Exception $_.Exception -Continue
            }

            $pendingRestart = $instanceFS.ConfiguredValue -ne $instanceFS.RunningValue

            if (($serviceFS.AccessLevel -ne 0) -and ($instanceFS.RunningValue -ne 0)) {
                if (($serviceFS.AccessLevel -eq $instanceFS.RunningValue) -and $pendingRestart) {
                    Write-Message -Level Verbose -Message "A restart of the instance is pending before Filestream is configured."
                }
            }

            $runvalue = (Get-DbaSpConfigure -SqlInstance $server -Name FilestreamAccessLevel | Select-Object RunningValue).RunningValue
            $servicelevel = [int]$serviceFS.AccessLevel

            [PsCustomObject]@{
                ComputerName        = $server.NetName
                InstanceName        = $server.ServiceName
                SqlInstance         = $server.DomainInstanceName
                InstanceAccess      = $idInstanceFS[$runvalue]
                ServiceAccess       = $idServiceFS[$servicelevel]
                ServiceShareName    = $serviceFS.ShareName
                InstanceAccessLevel = $instanceFS.RunningValue
                ServiceAccessLevel  = $serviceFS.AccessLevel
                Credential          = $Credential
                SqlCredential       = $SqlCredential
            } | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, InstanceAccess, ServiceAccess, ServiceShareName
        }
    }
}
tools\dbatools\functions\Get-DbaForceNetworkEncryption.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaForceNetworkEncryption {
    <#
    .SYNOPSIS
        Gets Force Encryption settings for a SQL Server instance

    .DESCRIPTION
        Gets Force Encryption settings for a SQL Server instance. Note that this requires access to the Windows Server - not the SQL instance itself.

        This setting is found in Configuration Manager.

    .PARAMETER SqlInstance
       The target SQL Server instance or instances. Defaults to localhost.

    .PARAMETER Credential
        Allows you to login to the computer (not sql instance) using alternative Windows credentials

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Certificate
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaForceNetworkEncryption

    .EXAMPLE
        PS C:\> Get-DbaForceNetworkEncryption

        Gets Force Encryption properties on the default (MSSQLSERVER) instance on localhost - requires (and checks for) RunAs admin.

    .EXAMPLE
        PS C:\> Get-DbaForceNetworkEncryption -SqlInstance sql01\SQL2008R2SP2

        Gets Force Network Encryption for the SQL2008R2SP2 on sql01. Uses Windows Credentials to both login and view the registry.

       #>
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "ComputerName")]
        [DbaInstanceParameter[]]$SqlInstance = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            Write-Message -Level VeryVerbose -Message "Processing $instance" -Target $instance
            $null = Test-ElevationRequirement -ComputerName $instance -Continue

            Write-Message -Level Verbose -Message "Resolving hostname"
            $resolved = $null
            $resolved = Resolve-DbaNetworkName -ComputerName $instance

            if ($null -eq $resolved) {
                Stop-Function -Message "Can't resolve $instance" -Target $instance -Continue -Category InvalidArgument
            }

            try {
                $sqlwmi = Invoke-ManagedComputerCommand -ComputerName $resolved.FullComputerName -ScriptBlock {
                    $wmi.Services
                } -Credential $Credential -ErrorAction Stop | Where-Object DisplayName -eq "SQL Server ($($instance.InstanceName))"
            } catch {
                Stop-Function -Message "Failed to access $instance" -Target $instance -Continue -ErrorRecord $_
            }

            $regroot = ($sqlwmi.AdvancedProperties | Where-Object Name -eq REGROOT).Value
            $vsname = ($sqlwmi.AdvancedProperties | Where-Object Name -eq VSNAME).Value
            try {
                $instancename = $sqlwmi.DisplayName.Replace('SQL Server (', '').Replace(')', '') # Don't clown, I don't know regex :(
            } catch {
                # Probably because the instance name has been aliased or does not exist or something
                # here to avoid an empty catch
                $null = 1
            }
            $serviceaccount = $sqlwmi.ServiceAccount

            if ([System.String]::IsNullOrEmpty($regroot)) {
                $regroot = $sqlwmi.AdvancedProperties | Where-Object {
                    $_ -match 'REGROOT'
                }
                $vsname = $sqlwmi.AdvancedProperties | Where-Object {
                    $_ -match 'VSNAME'
                }

                if (![System.String]::IsNullOrEmpty($regroot)) {
                    $regroot = ($regroot -Split 'Value\=')[1]
                    $vsname = ($vsname -Split 'Value\=')[1]
                } else {
                    Stop-Function -Message "Can't find instance $vsname on $instance" -Continue -Category ObjectNotFound -Target $instance
                }
            }

            if ([System.String]::IsNullOrEmpty($vsname)) {
                $vsname = $instance
            }

            Write-Message -Level Verbose -Message "Regroot: $regroot" -Target $instance
            Write-Message -Level Verbose -Message "ServiceAcct: $serviceaccount" -Target $instance
            Write-Message -Level Verbose -Message "InstanceName: $instancename" -Target $instance
            Write-Message -Level Verbose -Message "VSNAME: $vsname" -Target $instance

            $scriptblock = {
                $regpath = "Registry::HKEY_LOCAL_MACHINE\$($args[0])\MSSQLServer\SuperSocketNetLib"
                $cert = (Get-ItemProperty -Path $regpath -Name Certificate).Certificate
                $forceencryption = (Get-ItemProperty -Path $regpath -Name ForceEncryption).ForceEncryption

                # [pscustomobject] doesn't always work, unsure why. so return hashtable then turn it into  pscustomobject on client
                @{
                    ComputerName          = $env:COMPUTERNAME
                    InstanceName          = $args[2]
                    SqlInstance           = $args[1]
                    ForceEncryption       = ($forceencryption -eq $true)
                    CertificateThumbprint = $cert
                }
            }

            try {
                $results = Invoke-Command2 -ComputerName $resolved.FullComputerName -Credential $Credential -ArgumentList $regroot, $vsname, $instancename -ScriptBlock $scriptblock -ErrorAction Stop -Raw
                foreach ($result in $results) {
                    [pscustomobject]$result
                }
            } catch {
                Stop-Function -Message "Failed to connect to $($resolved.FullComputerName) using PowerShell remoting!" -ErrorRecord $_ -Target $instance -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaHelpIndex.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaHelpIndex {
    <#
    .SYNOPSIS
        Returns size, row and configuration information for indexes in databases.

    .DESCRIPTION
        This function will return detailed information on indexes (and optionally statistics) for all indexes in a database, or a given index should one be passed along.
        As this uses SQL Server DMVs to access the data it will only work in 2005 and up (sorry folks still running SQL Server 2000).
        For performance reasons certain statistics information will not be returned from SQL Server 2005 if an ObjectName is not provided.

        The data includes:
        - ObjectName: the table containing the index
        - IndexType: clustered/non-clustered/columnstore and whether the index is unique/primary key
        - KeyColumns: the key columns of the index
        - IncludeColumns: any include columns in the index
        - FilterDefinition: any filter that may have been used in the index
        - DataCompression: row/page/none depending upon whether or not compression has been used
        - IndexReads: the number of reads of the index since last restart or index rebuild
        - IndexUpdates: the number of writes to the index since last restart or index rebuild
        - SizeKB: the size the index in KB
        - IndexRows: the number of the rows in the index (note filtered indexes will have fewer rows than exist in the table)
        - IndexLookups: the number of lookups that have been performed (only applicable for the heap or clustered index)
        - MostRecentlyUsed: when the index was most recently queried (default to 1900 for when never read)
        - StatsSampleRows: the number of rows queried when the statistics were built/rebuilt (not included in SQL Server 2005 unless ObjectName is specified)
        - StatsRowMods: the number of changes to the statistics since the last rebuild
        - HistogramSteps: the number of steps in the statistics histogram (not included in SQL Server 2005 unless ObjectName is specified)
        - StatsLastUpdated: when the statistics were last rebuilt (not included in SQL Server 2005 unless ObjectName is specified)

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process. This list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude. This list is auto-populated from the server.

    .PARAMETER ObjectName
        The name of a table for which you want to obtain the index information. If the two part naming convention for an object is not used it will use the default schema for the executing user. If not passed it will return data on all indexes in a given database.

    .PARAMETER IncludeStats
        If this switch is enabled, statistics as well as indexes will be returned in the output (statistics information such as the StatsRowMods will always be returned for indexes).

    .PARAMETER IncludeDataTypes
        If this switch is enabled, the output will include the data type of each column that makes up a part of the index definition (key and include columns).

    .PARAMETER IncludeFragmentation
        If this switch is enabled, the output will include fragmentation information.

    .PARAMETER InputObject
        Allows piping from Get-DbaDatabase

    .PARAMETER Raw
        If this switch is enabled, results may be less user-readable but more suitable for processing by other code.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Index
        Author: Nic Cain, https://sirsql.net/

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaHelpIndex

    .EXAMPLE
        PS C:\> Get-DbaHelpIndex -SqlInstance localhost -Database MyDB

        Returns information on all indexes on the MyDB database on the localhost.

    .EXAMPLE
        PS C:\> Get-DbaHelpIndex -SqlInstance localhost -Database MyDB,MyDB2

        Returns information on all indexes on the MyDB & MyDB2 databases.

    .EXAMPLE
        PS C:\> Get-DbaHelpIndex -SqlInstance localhost -Database MyDB -ObjectName dbo.Table1

        Returns index information on the object dbo.Table1 in the database MyDB.

    .EXAMPLE
        PS C:\> Get-DbaHelpIndex -SqlInstance localhost -Database MyDB -ObjectName dbo.Table1 -IncludeStats

        Returns information on the indexes and statistics for the table dbo.Table1 in the MyDB database.

    .EXAMPLE
        PS C:\> Get-DbaHelpIndex -SqlInstance localhost -Database MyDB -ObjectName dbo.Table1 -IncludeDataTypes

        Returns the index information for the table dbo.Table1 in the MyDB database, and includes the data types for the key and include columns.

    .EXAMPLE
        PS C:\> Get-DbaHelpIndex -SqlInstance localhost -Database MyDB -ObjectName dbo.Table1 -Raw

        Returns the index information for the table dbo.Table1 in the MyDB database, and returns the numerical data without localized separators.

    .EXAMPLE
        PS C:\> Get-DbaHelpIndex -SqlInstance localhost -Database MyDB -IncludeStats -Raw

        Returns the index information for all indexes in the MyDB database as well as their statistics, and formats the numerical data without localized separators.

    .EXAMPLE
        PS C:\> Get-DbaHelpIndex -SqlInstance localhost -Database MyDB -IncludeFragmentation

        Returns the index information for all indexes in the MyDB database as well as their fragmentation

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sql2017 -Database MyDB | Get-DbaHelpIndex

        Returns the index information for all indexes in the MyDB database

    #>
    [CmdletBinding()]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [Parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [string]$ObjectName,
        [switch]$IncludeStats,
        [switch]$IncludeDataTypes,
        [switch]$Raw,
        [switch]$IncludeFragmentation,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {

        #Add the table predicate to the query
        if (!$ObjectName) {
            $TablePredicate = "DECLARE @TableName NVARCHAR(256);";
        } else {
            $TablePredicate = "DECLARE @TableName NVARCHAR(256); SET @TableName = '$ObjectName';";
        }

        #Add Fragmentation info if requested
        $FragSelectColumn = ", NULL as avg_fragmentation_in_percent"
        $FragJoin = ''
        $OutputProperties = 'Database,Object,Index,IndexType,KeyColumns,IncludeColumns,FilterDefinition,DataCompression,IndexReads,IndexUpdates,SizeKB,IndexRows,IndexLookups,MostRecentlyUsed,StatsSampleRows,StatsRowMods,HistogramSteps,StatsLastUpdated'
        if ($IncludeFragmentation) {
            $FragSelectColumn = ', pstat.avg_fragmentation_in_percent'
            $FragJoin = "LEFT JOIN sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL , 'DETAILED') pstat
             ON pstat.database_id = ustat.database_id
             AND pstat.object_id = ustat.object_id
             AND pstat.index_id = ustat.index_id"
            $OutputProperties = 'Database,Object,Index,IndexType,KeyColumns,IncludeColumns,FilterDefinition,DataCompression,IndexReads,IndexUpdates,SizeKB,IndexRows,IndexLookups,MostRecentlyUsed,StatsSampleRows,StatsRowMods,HistogramSteps,StatsLastUpdated,IndexFragInPercent'
        }
        $OutputProperties = $OutputProperties.Split(',')
        #Figure out if we are including stats in the results
        if ($IncludeStats) {
            $IncludeStatsPredicate = "";
        } else {
            $IncludeStatsPredicate = "WHERE StatisticsName IS NULL";
        }

        #Data types being returns with the results?
        if ($IncludeDataTypes) {
            $IncludeDataTypesPredicate = 'DECLARE @IncludeDataTypes BIT; SET @IncludeDataTypes = 1';
        } else {
            $IncludeDataTypesPredicate = 'DECLARE @IncludeDataTypes BIT; SET @IncludeDataTypes = 0';
        }

        #region SizesQuery
        $SizesQuery = "
            SET NOCOUNT ON;
            SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

            $TablePredicate
            $IncludeDataTypesPredicate
            ;

        DECLARE @IndexUsageStats TABLE
            (
            object_id INT ,
            index_id INT ,
            user_scans BIGINT ,
            user_seeks BIGINT ,
            user_updates BIGINT ,
            user_lookups BIGINT ,
            last_user_lookup DATETIME2(0) ,
            last_user_scan DATETIME2(0) ,
            last_user_seek DATETIME2(0) ,
            avg_fragmentation_in_percent FLOAT
            );

        DECLARE @StatsInfo TABLE
            (
            object_id INT ,
            stats_id INT ,
            stats_column_name NVARCHAR(128) ,
            stats_column_id INT ,
            stats_name NVARCHAR(128) ,
            stats_last_updated DATETIME2(0) ,
            stats_sampled_rows BIGINT ,
            rowmods BIGINT ,
            histogramsteps INT ,
            StatsRows BIGINT ,
            FullObjectName NVARCHAR(256)
            );

        INSERT  INTO @IndexUsageStats
                ( object_id ,
                index_id ,
                user_scans ,
                user_seeks ,
                user_updates ,
                user_lookups ,
                last_user_lookup ,
                last_user_scan ,
                last_user_seek ,
                avg_fragmentation_in_percent
                )
                SELECT  ustat.object_id ,
                        ustat.index_id ,
                        ustat.user_scans ,
                        ustat.user_seeks ,
                        ustat.user_updates ,
                        ustat.user_lookups ,
                        ustat.last_user_lookup ,
                        ustat.last_user_scan ,
                        ustat.last_user_seek
                        $FragSelectColumn
                FROM    sys.dm_db_index_usage_stats ustat
                $FragJoin
                WHERE   ustat.database_id = DB_ID();

        INSERT  INTO @StatsInfo
                ( object_id ,
                stats_id ,
                stats_column_name ,
                stats_column_id ,
                stats_name ,
                stats_last_updated ,
                stats_sampled_rows ,
                rowmods ,
                histogramsteps ,
                StatsRows ,
                FullObjectName
                )
                SELECT  s.object_id ,
                        s.stats_id ,
                        c.name ,
                        sc.stats_column_id ,
                        s.name ,
                        sp.last_updated ,
                        sp.rows_sampled ,
                        sp.modification_counter ,
                        sp.steps ,
                        sp.rows ,
                        QUOTENAME(sch.name) + '.' + QUOTENAME(t.name) AS FullObjectName
                FROM    [sys].[stats] AS [s]
                        INNER JOIN sys.stats_columns sc ON s.stats_id = sc.stats_id
                                                        AND s.object_id = sc.object_id
                        INNER JOIN sys.columns c ON c.object_id = sc.object_id
                                                    AND c.column_id = sc.column_id
                        INNER JOIN sys.tables t ON c.object_id = t.object_id
                        INNER JOIN sys.schemas sch ON sch.schema_id = t.schema_id
                        OUTER APPLY sys.dm_db_stats_properties([s].[object_id],
                                                            [s].[stats_id]) AS [sp]
                WHERE   s.object_id = CASE WHEN @TableName IS NULL THEN s.object_id
                                        else OBJECT_ID(@TableName)
                                    END;


        ;
        WITH    cteStatsInfo
                AS ( SELECT   object_id ,
                                si.stats_id ,
                                si.stats_name ,
                                STUFF((SELECT   N', ' + stats_column_name
                                    FROM     @StatsInfo si2
                                    WHERE    si2.object_id = si.object_id
                                                AND si2.stats_id = si.stats_id
                                    ORDER BY si2.stats_column_id
                                FOR   XML PATH(N'') ,
                                        TYPE).value(N'.[1]', N'nvarchar(1000)'), 1,
                                    2, N'') AS StatsColumns ,
                                MAX(si.stats_sampled_rows) AS SampleRows ,
                                MAX(si.rowmods) AS RowMods ,
                                MAX(si.histogramsteps) AS HistogramSteps ,
                                MAX(si.stats_last_updated) AS StatsLastUpdated ,
                                MAX(si.StatsRows) AS StatsRows,
                                FullObjectName
                    FROM     @StatsInfo si
                    GROUP BY si.object_id ,
                                si.stats_id ,
                                si.stats_name ,
                                si.FullObjectName
                    ),
                cteIndexSizes
                AS ( SELECT   object_id ,
                                index_id ,
                                CASE WHEN index_id < 2
                                    THEN ( ( SUM(in_row_data_page_count
                                                + lob_used_page_count
                                                + row_overflow_used_page_count)
                                            * 8192 ) / 1024 )
                                    else ( ( SUM(used_page_count) * 8192 ) / 1024 )
                                END AS SizeKB
                    FROM     sys.dm_db_partition_stats
                    GROUP BY object_id ,
                                index_id
                    ),
                cteRows
                AS ( SELECT   object_id ,
                                index_id ,
                                SUM(rows) AS IndexRows
                    FROM     sys.partitions
                    GROUP BY object_id ,
                                index_id
                    ),
                cteIndex
                AS ( SELECT   OBJECT_NAME(c.object_id) AS ObjectName ,
                                c.object_id ,
                                c.index_id ,
                                i.name COLLATE SQL_Latin1_General_CP1_CI_AS AS name ,
                                c.index_column_id ,
                                c.column_id ,
                                c.is_included_column ,
                                CASE WHEN @IncludeDataTypes = 0
                                        AND c.is_descending_key = 1
                                    THEN sc.name + ' DESC'
                                    WHEN @IncludeDataTypes = 0
                                        AND c.is_descending_key = 0 THEN sc.name
                                    WHEN @IncludeDataTypes = 1
                                        AND c.is_descending_key = 1
                                        AND c.is_included_column = 0
                                    THEN sc.name + ' DESC (' + t.name + ') '
                                    WHEN @IncludeDataTypes = 1
                                        AND c.is_descending_key = 0
                                        AND c.is_included_column = 0
                                    THEN sc.name + ' (' + t.name + ')'
                                    else sc.name
                                END AS ColumnName ,
                                i.filter_definition ,
                                ISNULL(dd.user_scans, 0) AS user_scans ,
                                ISNULL(dd.user_seeks, 0) AS user_seeks ,
                                ISNULL(dd.user_updates, 0) AS user_updates ,
                                ISNULL(dd.user_lookups, 0) AS user_lookups ,
                                CONVERT(DATETIME2(0), ISNULL(dd.last_user_lookup,
                                                            '1901-01-01')) AS LastLookup ,
                                CONVERT(DATETIME2(0), ISNULL(dd.last_user_scan,
                                                            '1901-01-01')) AS LastScan ,
                                CONVERT(DATETIME2(0), ISNULL(dd.last_user_seek,
                                                            '1901-01-01')) AS LastSeek ,
                                i.fill_factor ,
                                c.is_descending_key ,
                                p.data_compression_desc ,
                                i.type_desc ,
                                i.is_unique ,
                                i.is_unique_constraint ,
                                i.is_primary_key ,
                                ci.SizeKB ,
                                cr.IndexRows ,
                                QUOTENAME(sch.name) + '.' + QUOTENAME(tbl.name) AS FullObjectName ,
                                ISNULL(dd.avg_fragmentation_in_percent, 0) as avg_fragmentation_in_percent
                    FROM     sys.indexes i
                                JOIN sys.index_columns c ON i.object_id = c.object_id
                                                            AND i.index_id = c.index_id
                                JOIN sys.columns sc ON c.object_id = sc.object_id
                                                    AND c.column_id = sc.column_id
                                INNER JOIN sys.tables tbl ON c.object_id = tbl.object_id
                                INNER JOIN sys.schemas sch ON sch.schema_id = tbl.schema_id
                                LEFT JOIN sys.types t ON sc.user_type_id = t.user_type_id
                                LEFT JOIN @IndexUsageStats dd ON i.object_id = dd.object_id
                                                                AND i.index_id = dd.index_id --and dd.database_id = db_id()
                                JOIN sys.partitions p ON i.object_id = p.object_id
                                                        AND i.index_id = p.index_id
                                JOIN cteIndexSizes ci ON i.object_id = ci.object_id
                                                        AND i.index_id = ci.index_id
                                JOIN cteRows cr ON i.object_id = cr.object_id
                                                AND i.index_id = cr.index_id
                    WHERE    i.object_id = CASE WHEN @TableName IS NULL
                                                THEN i.object_id
                                                else OBJECT_ID(@TableName)
                                            END
                    ),
                cteResults
                AS ( SELECT   ci.FullObjectName ,
                                ci.object_id ,
                                MAX(index_id) AS Index_Id ,
                                ci.type_desc
                                + CASE WHEN ci.is_primary_key = 1
                                    THEN ' (PRIMARY KEY)'
                                    WHEN ci.is_unique_constraint = 1
                                    THEN ' (UNIQUE CONSTRAINT)'
                                    WHEN ci.is_unique = 1 THEN ' (UNIQUE)'
                                    else ''
                                END AS IndexType ,
                                name AS IndexName ,
                                STUFF((SELECT   N', ' + ColumnName
                                    FROM     cteIndex ci2
                                    WHERE    ci2.name = ci.name
                                                AND ci2.is_included_column = 0
                                    GROUP BY ci2.index_column_id ,
                                                ci2.ColumnName
                                    ORDER BY ci2.index_column_id
                                FOR   XML PATH(N'') ,
                                        TYPE).value(N'.[1]', N'nvarchar(1000)'), 1,
                                    2, N'') AS KeyColumns ,
                                ISNULL(STUFF((SELECT    N',  ' + ColumnName
                                            FROM      cteIndex ci3
                                            WHERE     ci3.name = ci.name
                                                        AND ci3.is_included_column = 1
                                            GROUP BY  ci3.index_column_id ,
                                                        ci3.ColumnName
                                            ORDER BY  ci3.index_column_id
                                    FOR   XML PATH(N'') ,
                                                TYPE).value(N'.[1]',
                                                            N'nvarchar(1000)'), 1, 2,
                                            N''), '') AS IncludeColumns ,
                                ISNULL(filter_definition, '') AS FilterDefinition ,
                                ci.fill_factor ,
                                CASE WHEN ci.data_compression_desc = 'NONE' THEN ''
                                    else ci.data_compression_desc
                                END AS DataCompression ,
                                MAX(ci.user_seeks) + MAX(ci.user_scans)
                                + MAX(ci.user_lookups) AS IndexReads ,
                                MAX(ci.user_lookups) AS IndexLookups ,
                                ci.user_updates AS IndexUpdates ,
                                ci.SizeKB AS SizeKB ,
                                ci.IndexRows AS IndexRows ,
                                CASE WHEN LastScan > LastSeek
                                        AND LastScan > LastLookup THEN LastScan
                                    WHEN LastSeek > LastScan
                                        AND LastSeek > LastLookup THEN LastSeek
                                    WHEN LastLookup > LastScan
                                        AND LastLookup > LastSeek THEN LastLookup
                                    else ''
                                END AS MostRecentlyUsed ,
                                AVG(ci.avg_fragmentation_in_percent) as avg_fragmentation_in_percent
                    FROM     cteIndex ci
                    GROUP BY ci.ObjectName ,
                                ci.name ,
                                ci.filter_definition ,
                                ci.object_id ,
                                ci.LastLookup ,
                                ci.LastSeek ,
                                ci.LastScan ,
                                ci.user_updates ,
                                ci.fill_factor ,
                                ci.data_compression_desc ,
                                ci.type_desc ,
                                ci.is_primary_key ,
                                ci.is_unique ,
                                ci.is_unique_constraint ,
                                ci.SizeKB ,
                                ci.IndexRows ,
                                ci.FullObjectName
                    ),
                AllResults
                AS ( SELECT   c.FullObjectName ,
                                IndexType ,
                                ISNULL(IndexName, si.stats_name) AS IndexName ,
                                NULL as StatisticsName ,
                                ISNULL(KeyColumns, si.StatsColumns) AS KeyColumns ,
                                ISNULL(IncludeColumns, '') AS IncludeColumns ,
                                FilterDefinition ,
                                fill_factor AS [FillFactor] ,
                                DataCompression ,
                                IndexReads ,
                                IndexUpdates ,
                                SizeKB ,
                                IndexRows ,
                                IndexLookups ,
                                MostRecentlyUsed ,
                                SampleRows AS StatsSampleRows ,
                                RowMods AS StatsRowMods ,
                                si.HistogramSteps ,
                                si.StatsLastUpdated ,
                                avg_fragmentation_in_percent AS IndexFragInPercent,
                                1 AS Ordering
                    FROM     cteResults c
                                INNER JOIN cteStatsInfo si ON si.object_id = c.object_id
                                                            AND si.stats_id = c.Index_Id
                    UNION
                    SELECT   QUOTENAME(sch.name) + '.' + QUOTENAME(tbl.name) AS FullObjectName ,
                                '' ,
                                '' ,
                                stats_name ,
                                StatsColumns ,
                                '' ,
                                '' AS FilterDefinition ,
                                '' AS Fill_Factor ,
                                '' AS DataCompression ,
                                '' AS IndexReads ,
                                '' AS IndexUpdates ,
                                '' AS SizeKB ,
                                StatsRows AS IndexRows ,
                                '' AS IndexLookups ,
                                '' AS MostRecentlyUsed ,
                                SampleRows AS StatsSampleRows ,
                                RowMods AS StatsRowMods ,
                                csi.HistogramSteps ,
                                csi.StatsLastUpdated ,
                                '' AS IndexFragInPercent ,
                                2
                    FROM     cteStatsInfo csi
                    INNER JOIN sys.tables tbl ON csi.object_id = tbl.object_id
                                INNER JOIN sys.schemas sch ON sch.schema_id = tbl.schema_id
                    WHERE    stats_id NOT IN (
                                SELECT  stats_id
                                FROM    cteResults c
                                        INNER JOIN cteStatsInfo si ON si.object_id = c.object_id
                                                                    AND si.stats_id = c.Index_Id )
                    )
            SELECT  FullObjectName ,
                    IndexType ,
                    IndexName ,
                    StatisticsName ,
                    KeyColumns ,
                    ISNULL(IncludeColumns, '') AS IncludeColumns ,
                    FilterDefinition ,
                    [FillFactor] AS [FillFactor] ,
                    DataCompression ,
                    IndexReads ,
                    IndexUpdates ,
                    SizeKB ,
                    IndexRows ,
                    IndexLookups ,
                    MostRecentlyUsed ,
                    StatsSampleRows ,
                    StatsRowMods ,
                    HistogramSteps ,
                    StatsLastUpdated ,
                    IndexFragInPercent
            FROM    AllResults
                    $IncludeStatsPredicate
        OPTION  ( RECOMPILE );
        "
        #endRegion SizesQuery


        #region sizesQuery2005
        $SizesQuery2005 = "
        SET NOCOUNT ON;
        SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

        $TablePredicate
        $IncludeDataTypesPredicate
        ;

        DECLARE @AllResults TABLE
            (
                RowNum INT ,
                FullObjectName	NVARCHAR(300) ,
                IndexType	NVARCHAR(256) ,
                IndexName	NVARCHAR(256) ,
                KeyColumns	NVARCHAR(2000) ,
                IncludeColumns	NVARCHAR(2000) ,
                FilterDefinition	NVARCHAR(100) ,
                [FillFactor]	TINYINT ,
                DataCompression	CHAR(4) ,
                IndexReads	BIGINT ,
                IndexUpdates	BIGINT ,
                SizeKB	BIGINT ,
                IndexRows	BIGINT ,
                IndexLookups	BIGINT ,
                MostRecentlyUsed	DATETIME ,
                StatsSampleRows	BIGINT ,
                StatsRowMods	BIGINT ,
                HistogramSteps	INT	,
                StatsLastUpdated	DATETIME ,
                object_id BIGINT ,
                index_id BIGINT
            );

        DECLARE @IndexUsageStats TABLE
            (
            object_id INT ,
            index_id INT ,
            user_scans BIGINT ,
            user_seeks BIGINT ,
            user_updates BIGINT ,
            user_lookups BIGINT ,
            last_user_lookup DATETIME ,
            last_user_scan DATETIME ,
            last_user_seek DATETIME ,
            avg_fragmentation_in_percent FLOAT
            );

        DECLARE @StatsInfo TABLE
            (
            object_id INT ,
            stats_id INT ,
            stats_column_name NVARCHAR(128) ,
            stats_column_id INT ,
            stats_name NVARCHAR(128) ,
            stats_last_updated DATETIME ,
            stats_sampled_rows BIGINT ,
            rowmods BIGINT ,
            histogramsteps INT ,
            StatsRows BIGINT ,
            FullObjectName NVARCHAR(256)
            );

        INSERT  INTO @IndexUsageStats
                ( object_id ,
                index_id ,
                user_scans ,
                user_seeks ,
                user_updates ,
                user_lookups ,
                last_user_lookup ,
                last_user_scan ,
                last_user_seek ,
                avg_fragmentation_in_percent
                )
                SELECT  ustat.object_id ,
                        ustat.index_id ,
                        ustat.user_scans ,
                        ustat.user_seeks ,
                        ustat.user_updates ,
                        ustat.user_lookups ,
                        ustat.last_user_lookup ,
                        ustat.last_user_scan ,
                        ustat.last_user_seek
                        $FragSelectColumn
                FROM    sys.dm_db_index_usage_stats ustat
                $FragJoin
                WHERE   database_id = DB_ID();


        INSERT  INTO @StatsInfo
                ( object_id ,
                stats_id ,
                stats_column_name ,
                stats_column_id ,
                stats_name ,
                stats_last_updated ,
                stats_sampled_rows ,
                rowmods ,
                histogramsteps ,
                StatsRows ,
                FullObjectName
                )
                SELECT  s.object_id ,
                        s.stats_id ,
                        c.name ,
                        sc.stats_column_id ,
                        s.name ,
                        NULL AS last_updated ,
                        NULL AS rows_sampled ,
                        NULL AS modification_counter ,
                        NULL AS steps ,
                        NULL AS rows ,
                        QUOTENAME(sch.name) + '.' + QUOTENAME(t.name) AS FullObjectName
                FROM    [sys].[stats] AS [s]
                        INNER JOIN sys.stats_columns sc ON s.stats_id = sc.stats_id
                                                        AND s.object_id = sc.object_id
                        INNER JOIN sys.columns c ON c.object_id = sc.object_id
                                                    AND c.column_id = sc.column_id
                        INNER JOIN sys.tables t ON c.object_id = t.object_id
                        INNER JOIN sys.schemas sch ON sch.schema_id = t.schema_id
                    --   OUTER APPLY sys.dm_db_stats_properties([s].[object_id],
                    --                                        [s].[stats_id]) AS [sp]
                WHERE   s.object_id = CASE WHEN @TableName IS NULL THEN s.object_id
                                        else OBJECT_ID(@TableName)
                                    END;


        ;
        WITH    cteStatsInfo
                AS ( SELECT   object_id ,
                                si.stats_id ,
                                si.stats_name ,
                                STUFF((SELECT   N', ' + stats_column_name
                                    FROM     @StatsInfo si2
                                    WHERE    si2.object_id = si.object_id
                                                AND si2.stats_id = si.stats_id
                                    ORDER BY si2.stats_column_id
                                FOR   XML PATH(N'') ,
                                        TYPE).value(N'.[1]', N'nvarchar(1000)'), 1,
                                    2, N'') AS StatsColumns ,
                                MAX(si.stats_sampled_rows) AS SampleRows ,
                                MAX(si.rowmods) AS RowMods ,
                                MAX(si.histogramsteps) AS HistogramSteps ,
                                MAX(si.stats_last_updated) AS StatsLastUpdated ,
                                MAX(si.StatsRows) AS StatsRows,
                                FullObjectName
                    FROM     @StatsInfo si
                    GROUP BY si.object_id ,
                                si.stats_id ,
                                si.stats_name ,
                                si.FullObjectName
                    ),
                cteIndexSizes
                AS ( SELECT   object_id ,
                                index_id ,
                                CASE WHEN index_id < 2
                                    THEN ( ( SUM(in_row_data_page_count
                                                + lob_used_page_count
                                                + row_overflow_used_page_count)
                                            * 8192 ) / 1024 )
                                    else ( ( SUM(used_page_count) * 8192 ) / 1024 )
                                END AS SizeKB
                    FROM     sys.dm_db_partition_stats
                    GROUP BY object_id ,
                                index_id
                    ),
                cteRows
                AS ( SELECT   object_id ,
                                index_id ,
                                SUM(rows) AS IndexRows
                    FROM     sys.partitions
                    GROUP BY object_id ,
                                index_id
                    ),
                cteIndex
                AS ( SELECT   OBJECT_NAME(c.object_id) AS ObjectName ,
                                c.object_id ,
                                c.index_id ,
                                i.name COLLATE SQL_Latin1_General_CP1_CI_AS AS name ,
                                c.index_column_id ,
                                c.column_id ,
                                c.is_included_column ,
                                CASE WHEN @IncludeDataTypes = 0
                                        AND c.is_descending_key = 1
                                    THEN sc.name + ' DESC'
                                    WHEN @IncludeDataTypes = 0
                                        AND c.is_descending_key = 0 THEN sc.name
                                    WHEN @IncludeDataTypes = 1
                                        AND c.is_descending_key = 1
                                        AND c.is_included_column = 0
                                    THEN sc.name + ' DESC (' + t.name + ') '
                                    WHEN @IncludeDataTypes = 1
                                        AND c.is_descending_key = 0
                                        AND c.is_included_column = 0
                                    THEN sc.name + ' (' + t.name + ')'
                                    else sc.name
                                END AS ColumnName ,
                                '' AS filter_definition ,
                                ISNULL(dd.user_scans, 0) AS user_scans ,
                                ISNULL(dd.user_seeks, 0) AS user_seeks ,
                                ISNULL(dd.user_updates, 0) AS user_updates ,
                                ISNULL(dd.user_lookups, 0) AS user_lookups ,
                                CONVERT(DATETIME, ISNULL(dd.last_user_lookup,
                                                            '1901-01-01')) AS LastLookup ,
                                CONVERT(DATETIME, ISNULL(dd.last_user_scan,
                                                            '1901-01-01')) AS LastScan ,
                                CONVERT(DATETIME, ISNULL(dd.last_user_seek,
                                                            '1901-01-01')) AS LastSeek ,
                                i.fill_factor ,
                                c.is_descending_key ,
                                'NONE' as data_compression_desc ,
                                i.type_desc ,
                                i.is_unique ,
                                i.is_unique_constraint ,
                                i.is_primary_key ,
                                ci.SizeKB ,
                                cr.IndexRows ,
                                QUOTENAME(sch.name) + '.' + QUOTENAME(tbl.name) AS FullObjectName ,
                                ISNULL(dd.avg_fragmentation_in_percent, 0) as avg_fragmentation_in_percent
                    FROM     sys.indexes i
                                JOIN sys.index_columns c ON i.object_id = c.object_id
                                                            AND i.index_id = c.index_id
                                JOIN sys.columns sc ON c.object_id = sc.object_id
                                                    AND c.column_id = sc.column_id
                                INNER JOIN sys.tables tbl ON c.object_id = tbl.object_id
                                INNER JOIN sys.schemas sch ON sch.schema_id = tbl.schema_id
                                LEFT JOIN sys.types t ON sc.user_type_id = t.user_type_id
                                LEFT JOIN @IndexUsageStats dd ON i.object_id = dd.object_id
                                                                AND i.index_id = dd.index_id --and dd.database_id = db_id()
                                JOIN sys.partitions p ON i.object_id = p.object_id
                                                        AND i.index_id = p.index_id
                                JOIN cteIndexSizes ci ON i.object_id = ci.object_id
                                                        AND i.index_id = ci.index_id
                                JOIN cteRows cr ON i.object_id = cr.object_id
                                                AND i.index_id = cr.index_id
                    WHERE    i.object_id = CASE WHEN @TableName IS NULL
                                                THEN i.object_id
                                                else OBJECT_ID(@TableName)
                                            END
                    ),
                cteResults
                AS ( SELECT   ci.FullObjectName ,
                                ci.object_id ,
                                MAX(index_id) AS Index_Id ,
                                ci.type_desc
                                + CASE WHEN ci.is_primary_key = 1
                                    THEN ' (PRIMARY KEY)'
                                    WHEN ci.is_unique_constraint = 1
                                    THEN ' (UNIQUE CONSTRAINT)'
                                    WHEN ci.is_unique = 1 THEN ' (UNIQUE)'
                                    else ''
                                END AS IndexType ,
                                name AS IndexName ,
                                STUFF((SELECT   N', ' + ColumnName
                                    FROM     cteIndex ci2
                                    WHERE    ci2.name = ci.name
                                                AND ci2.is_included_column = 0
                                    GROUP BY ci2.index_column_id ,
                                                ci2.ColumnName
                                    ORDER BY ci2.index_column_id
                                FOR   XML PATH(N'') ,
                                        TYPE).value(N'.[1]', N'nvarchar(1000)'), 1,
                                    2, N'') AS KeyColumns ,
                                ISNULL(STUFF((SELECT    N',  ' + ColumnName
                                            FROM      cteIndex ci3
                                            WHERE     ci3.name = ci.name
                                                        AND ci3.is_included_column = 1
                                            GROUP BY  ci3.index_column_id ,
                                                        ci3.ColumnName
                                            ORDER BY  ci3.index_column_id
                                    FOR   XML PATH(N'') ,
                                                TYPE).value(N'.[1]',
                                                            N'nvarchar(1000)'), 1, 2,
                                            N''), '') AS IncludeColumns ,
                                ISNULL(filter_definition, '') AS FilterDefinition ,
                                ci.fill_factor ,
                                CASE WHEN ci.data_compression_desc = 'NONE' THEN ''
                                    else ci.data_compression_desc
                                END AS DataCompression ,
                                MAX(ci.user_seeks) + MAX(ci.user_scans)
                                + MAX(ci.user_lookups) AS IndexReads ,
                                MAX(ci.user_lookups) AS IndexLookups ,
                                ci.user_updates AS IndexUpdates ,
                                ci.SizeKB AS SizeKB ,
                                ci.IndexRows AS IndexRows ,
                                CASE WHEN LastScan > LastSeek
                                        AND LastScan > LastLookup THEN LastScan
                                    WHEN LastSeek > LastScan
                                        AND LastSeek > LastLookup THEN LastSeek
                                    WHEN LastLookup > LastScan
                                        AND LastLookup > LastSeek THEN LastLookup
                                    else ''
                                END AS MostRecentlyUsed ,
                                AVG(ci.avg_fragmentation_in_percent) as avg_fragmentation_in_percent
                    FROM     cteIndex ci
                    GROUP BY ci.ObjectName ,
                                ci.name ,
                                ci.filter_definition ,
                                ci.object_id ,
                                ci.LastLookup ,
                                ci.LastSeek ,
                                ci.LastScan ,
                                ci.user_updates ,
                                ci.fill_factor ,
                                ci.data_compression_desc ,
                                ci.type_desc ,
                                ci.is_primary_key ,
                                ci.is_unique ,
                                ci.is_unique_constraint ,
                                ci.SizeKB ,
                                ci.IndexRows ,
                                ci.FullObjectName
                    ), AllResults AS
                        (		 SELECT   c.FullObjectName ,
                                ISNULL(IndexType, 'STATISTICS') AS IndexType ,
                                ISNULL(IndexName, '') AS IndexName ,
                                ISNULL(KeyColumns, '') AS KeyColumns ,
                                ISNULL(IncludeColumns, '') AS IncludeColumns ,
                                FilterDefinition ,
                                fill_factor AS [FillFactor] ,
                                DataCompression ,
                                IndexReads ,
                                IndexUpdates ,
                                SizeKB ,
                                IndexRows ,
                                IndexLookups ,
                                MostRecentlyUsed ,
                                NULL AS StatsSampleRows ,
                                NULL AS StatsRowMods ,
                                NULL AS HistogramSteps ,
                                NULL AS StatsLastUpdated ,
                                avg_fragmentation_in_percent as IndexFragInPercent,
                                1 AS Ordering ,
                                c.object_id ,
                                c.Index_Id
                    FROM     cteResults c
                                INNER JOIN cteStatsInfo si ON si.object_id = c.object_id
                                                            AND si.stats_id = c.Index_Id
                        UNION
                    SELECT   QUOTENAME(sch.name) + '.' + QUOTENAME(tbl.name) AS FullObjectName ,
                                'STATISTICS' ,
                                stats_name ,
                                StatsColumns ,
                                '' ,
                                '' AS FilterDefinition ,
                                '' AS Fill_Factor ,
                                '' AS DataCompression ,
                                '' AS IndexReads ,
                                '' AS IndexUpdates ,
                                '' AS SizeKB ,
                                StatsRows AS IndexRows ,
                                '' AS IndexLookups ,
                                '' AS MostRecentlyUsed ,
                                SampleRows AS StatsSampleRows ,
                                RowMods AS StatsRowMods ,
                                csi.HistogramSteps ,
                                csi.StatsLastUpdated ,
                                '' as IndexFragInPercent,
                                2 ,
                                csi.object_id ,
                                csi.stats_id
                    FROM     cteStatsInfo csi
                    INNER JOIN sys.tables tbl ON csi.object_id = tbl.object_id
                                INNER JOIN sys.schemas sch ON sch.schema_id = tbl.schema_id
                                LEFT JOIN (SELECT si.object_id, si.stats_id
                                            FROM    cteResults c
                                            INNER JOIN cteStatsInfo si ON si.object_id = c.object_id
                                                                    AND si.stats_id = c.Index_Id ) AS x on csi.object_id = x.object_id and csi.stats_id = x.stats_id
                        WHERE x.object_id is null
                    )
            INSERT INTO @AllResults
            SELECT  row_number() OVER (ORDER BY FullObjectName) AS RowNum ,
                    FullObjectName ,
                    ISNULL(IndexType, 'STATISTICS') AS IndexType ,
                    IndexName ,
                    KeyColumns ,
                    ISNULL(IncludeColumns, '') AS IncludeColumns ,
                    FilterDefinition ,
                    [FillFactor] AS [FillFactor] ,
                    DataCompression ,
                    IndexReads ,
                    IndexUpdates ,
                    SizeKB ,
                    IndexRows ,
                    IndexLookups ,
                    MostRecentlyUsed ,
                    StatsSampleRows ,
                    StatsRowMods ,
                    HistogramSteps ,
                    StatsLastUpdated ,
                    IndexFragInPercent ,
                    object_id ,
                    index_id
            FROM    AllResults
                    $IncludeStatsPredicate
        OPTION  ( RECOMPILE );

        /* Only update the stats data on 2005 for a single table, otherwise the run time for this is a potential problem for large table/index volumes */
        if @TableName IS NOT NULL
        BEGIN

            DECLARE @StatsInfo2005 TABLE (Name nvarchar(128), Updated DATETIME, Rows BIGINT, RowsSampled BIGINT, Steps INT, Density INT, AverageKeyLength INT, StringIndex NVARCHAR(20))

            DECLARE @SqlCall NVARCHAR(2000), @RowNum INT;
            SELECT @RowNum = min(RowNum) FROM @AllResults;
            WHILE @RowNum IS NOT NULL
            BEGIN
                SELECT @SqlCall = 'dbcc show_statistics('+FullObjectName+', '+IndexName+') with stat_header' FROM @AllResults WHERE RowNum = @RowNum;
                INSERT INTO @StatsInfo2005 exec (@SqlCall);
                UPDATE @AllResults
                    SET StatsSampleRows = RowsSampled,
                    HistogramSteps = Steps,
                    StatsLastUpdated = Updated
                    FROM @StatsInfo2005
                    WHERE RowNum = @RowNum;
                DELETE FROM @StatsInfo2005
                SELECT @RowNum = min(RowNum) FROM @AllResults WHERE RowNum > @RowNum;
            END;

        END;

        UPDATE a
        SET a.StatsRowMods = i.rowmodctr
        FROM @AllResults a
            JOIN sys.sysindexes i ON a.object_id = i.id AND a.index_id = i.indid;

        SELECT	FullObjectName ,
                IndexType ,
                IndexName ,
                KeyColumns ,
                IncludeColumns ,
                FilterDefinition ,
                [FillFactor] ,
                DataCompression ,
                IndexReads ,
                IndexUpdates ,
                SizeKB ,
                IndexRows ,
                IndexLookups ,
                MostRecentlyUsed ,
                StatsSampleRows ,
                StatsRowMods ,
                HistogramSteps ,
                StatsLastUpdated ,
                IndexFragInPercent
        FROM @AllResults;"

        #endregion sizesQuery2005
    }
    process {
        Write-Message -Level Debug -Message $SizesQuery
        Write-Message -Level Debug -Message $SizesQuery2005

        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $InputObject += Get-DbaDatabase -SqlInstance $server -Database $Database -ExcludeDatabase $ExcludeDatabase
        }

        foreach ($db in $InputObject) {
            $server = $db.Parent

            #Need to check the version of SQL
            if ($server.versionMajor -ge 10) {
                $indexesQuery = $SizesQuery
            } else {
                $indexesQuery = $SizesQuery2005
            }

            if (!$db.IsAccessible) {
                Stop-Function -Message "$db is not accessible. Skipping." -Continue
            }

            Write-Message -Level Debug -Message "$indexesQuery"
            try {
                $IndexDetails = $db.Query($indexesQuery)

                if (!$Raw) {
                    foreach ($detail in $IndexDetails) {
                        $recentlyused = [datetime]$detail.MostRecentlyUsed

                        if ($recentlyused.year -eq 1900) {
                            $recentlyused = $null
                        }

                        [pscustomobject]@{
                            ComputerName       = $server.ComputerName
                            InstanceName       = $server.ServiceName
                            SqlInstance        = $server.DomainInstanceName
                            Database           = $db.Name
                            Object             = $detail.FullObjectName
                            Index              = $detail.IndexName
                            IndexType          = $detail.IndexType
                            Statistics         = $detail.StatisticsName
                            KeyColumns         = $detail.KeyColumns
                            IncludeColumns     = $detail.IncludeColumns
                            FilterDefinition   = $detail.FilterDefinition
                            DataCompression    = $detail.DataCompression
                            IndexReads         = "{0:N0}" -f $detail.IndexReads
                            IndexUpdates       = "{0:N0}" -f $detail.IndexUpdates
                            Size               = "{0:N0}" -f $detail.SizeKB
                            IndexRows          = "{0:N0}" -f $detail.IndexRows
                            IndexLookups       = "{0:N0}" -f $detail.IndexLookups
                            MostRecentlyUsed   = $recentlyused
                            StatsSampleRows    = "{0:N0}" -f $detail.StatsSampleRows
                            StatsRowMods       = "{0:N0}" -f $detail.StatsRowMods
                            HistogramSteps     = $detail.HistogramSteps
                            StatsLastUpdated   = $detail.StatsLastUpdated
                            IndexFragInPercent = "{0:F2}" -f $detail.IndexFragInPercent
                        }
                    }
                }

                else {
                    foreach ($detail in $IndexDetails) {
                        $recentlyused = [datetime]$detail.MostRecentlyUsed

                        if ($recentlyused.year -eq 1900) {
                            $recentlyused = $null
                        }

                        [pscustomobject]@{
                            ComputerName       = $server.ComputerName
                            InstanceName       = $server.ServiceName
                            SqlInstance        = $server.DomainInstanceName
                            Database           = $db.Name
                            Object             = $detail.FullObjectName
                            Index              = $detail.IndexName
                            IndexType          = $detail.IndexType
                            Statistics         = $detail.StatisticsName
                            KeyColumns         = $detail.KeyColumns
                            IncludeColumns     = $detail.IncludeColumns
                            FilterDefinition   = $detail.FilterDefinition
                            DataCompression    = $detail.DataCompression
                            IndexReads         = $detail.IndexReads
                            IndexUpdates       = $detail.IndexUpdates
                            Size               = [dbasize]($detail.SizeKB * 1024)
                            IndexRows          = $detail.IndexRows
                            IndexLookups       = $detail.IndexLookups
                            MostRecentlyUsed   = $recentlyused
                            StatsSampleRows    = $detail.StatsSampleRows
                            StatsRowMods       = $detail.StatsRowMods
                            HistogramSteps     = $detail.HistogramSteps
                            StatsLastUpdated   = $detail.StatsLastUpdated
                            IndexFragInPercent = $detail.IndexFragInPercent
                        }
                    }
                }
            } catch {
                Stop-Function -Continue -ErrorRecord $_ -Message "Cannot process $db on $server"
            }
        }
    }
}
tools\dbatools\functions\Get-DbaInstanceProperty.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaInstanceProperty {
    <#
    .SYNOPSIS
        Gets SQL Server instance properties of one or more instance(s) of SQL Server.

    .DESCRIPTION
        The Get-DbaInstanceProperty command gets SQL Server instance properties from the SMO object sqlserver.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER InstanceProperty
        SQL Server instance property(ies) to include.

    .PARAMETER ExcludeInstanceProperty
        SQL Server instance property(ies) to exclude.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Instance, Configure, Configuration
        Author: Klaas Vandenberghe (@powerdbaklaas)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaInstanceProperty

    .EXAMPLE
        PS C:\> Get-DbaInstanceProperty -SqlInstance localhost

        Returns SQL Server instance properties on the local default SQL Server instance

    .EXAMPLE
        PS C:\> Get-DbaInstanceProperty -SqlInstance sql2, sql4\sqlexpress

        Returns SQL Server instance properties on default instance on sql2 and sqlexpress instance on sql4

    .EXAMPLE
        PS C:\> 'sql2','sql4' | Get-DbaInstanceProperty

        Returns SQL Server instance properties on sql2 and sql4

    .EXAMPLE
        PS C:\> Get-DbaInstanceProperty -SqlInstance sql2,sql4 -InstanceProperty DefaultFile

        Returns SQL Server instance property DefaultFile on instance sql2 and sql4

    .EXAMPLE
        PS C:\> Get-DbaInstanceProperty -SqlInstance sql2,sql4 -ExcludeInstanceProperty DefaultFile

        Returns all SQL Server instance properties except DefaultFile on instance sql2 and sql4

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> Get-DbaInstanceProperty -SqlInstance sql2 -SqlCredential $cred

        Connects using sqladmin credential and returns SQL Server instance properties from sql2

    #>
    [CmdletBinding(DefaultParameterSetName = "Default")]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$InstanceProperty,
        [object[]]$ExcludeInstanceProperty,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            try {
                $infoProperties = $server.Information.Properties

                if ($InstanceProperty) {
                    $infoProperties = $infoProperties | Where-Object Name -In $InstanceProperty
                }
                if ($ExcludeInstanceProperty) {
                    $infoProperties = $infoProperties | Where-Object Name -NotIn $ExcludeInstanceProperty
                }
                foreach ($prop in $infoProperties) {
                    Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName
                    Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName
                    Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name SqlInstance -Value $server.DomainInstanceName
                    Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name PropertyType -Value 'Information'
                    Select-DefaultView -InputObject $prop -Property ComputerName, InstanceName, SqlInstance, Name, Value, PropertyType
                }
            } catch {
                Stop-Function -Message "Issue gathering information properties for $instance." -Target $instance -ErrorRecord $_ -Continue
            }

            try {
                $userProperties = $server.UserOptions.Properties

                if ($InstanceProperty) {
                    $userProperties = $userProperties | Where-Object Name -In $InstanceProperty
                }
                if ($ExcludeInstanceProperty) {
                    $userProperties = $userProperties | Where-Object Name -NotIn $ExcludeInstanceProperty
                }
                foreach ($prop in $userProperties) {
                    Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName
                    Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName
                    Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name SqlInstance -Value $server.DomainInstanceName
                    Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name PropertyType -Value 'UserOption'
                    Select-DefaultView -InputObject $prop -Property ComputerName, InstanceName, SqlInstance, Name, Value, PropertyType
                }
            } catch {
                Stop-Function -Message "Issue gathering user options for $instance." -Target $instance -ErrorRecord $_ -Continue
            }

            try {
                $settingProperties = $server.Settings.Properties

                if ($InstanceProperty) {
                    $settingProperties = $settingProperties | Where-Object Name -In $InstanceProperty
                }
                if ($ExcludeInstanceProperty) {
                    $settingProperties = $settingProperties | Where-Object Name -NotIn $ExcludeInstanceProperty
                }
                foreach ($prop in $settingProperties) {
                    Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName
                    Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName
                    Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name SqlInstance -Value $server.DomainInstanceName
                    Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name PropertyType -Value 'Setting'
                    Select-DefaultView -InputObject $prop -Property ComputerName, InstanceName, SqlInstance, Name, Value, PropertyType
                }
            } catch {
                Stop-Function -Message "Issue gathering settings for $instance." -Target $instance -ErrorRecord $_ -Continue
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaSqlInstanceProperty
    }
}
tools\dbatools\functions\Get-DbaInstanceUserOption.ps1
function Get-DbaInstanceUserOption {
    <#
    .SYNOPSIS
        Gets SQL Instance user options of one or more instance(s) of SQL Server.

    .DESCRIPTION
        The Get-DbaInstanceUserOption command gets SQL Instance user options from the SMO object sqlserver.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.
        This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Instance, Configure, UserOption
        Author: Klaas Vandenberghe (@powerdbaklaas)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaInstanceUserOption

    .EXAMPLE
        PS C:\> Get-DbaInstanceUserOption -SqlInstance localhost

        Returns SQL Instance user options on the local default SQL Server instance

    .EXAMPLE
        PS C:\> Get-DbaInstanceUserOption -SqlInstance sql2, sql4\sqlexpress

        Returns SQL Instance user options on default instance on sql2 and sqlexpress instance on sql4

    .EXAMPLE
        PS C:\> 'sql2','sql4' | Get-DbaInstanceUserOption

        Returns SQL Instance user options on sql2 and sql4

    #>
    [CmdletBinding(DefaultParameterSetName = "Default")]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            $props = $server.useroptions.properties
            foreach ($prop in $props) {
                Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName
                Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName
                Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name SqlInstance -Value $server.DomainInstanceName
                Select-DefaultView -InputObject $prop -Property ComputerName, InstanceName, SqlInstance, Name, Value
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaSqlInstanceUserOption
    }
}
tools\dbatools\functions\Get-DbaIoLatency.ps1
function Get-DbaIoLatency {
    <#
    .SYNOPSIS
        Displays IO subsystem latency statistics from sys.dm_io_virtual_file_stats.  Works on SQL Server 2005 and above.

    .DESCRIPTION
        This command is based off of Paul Randal's post "Advanced SQL Server performance tuning"

        Returns both raw and aggregate information

        Reference:  https://www.sqlskills.com/blogs/paul/how-to-examine-io-subsystem-latencies-from-within-sql-server/
                    https://www.sqlskills.com/blogs/paul/capturing-io-latencies-period-time/

    .PARAMETER SqlInstance
        The SQL Server instance. Server version must be SQL Server version 2008 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: IOLatency
        Author: Patrick Flynn (@sqllensman)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaIoLatency

    .EXAMPLE
        PS C:\> Get-DbaIoLatency -SqlInstance sql2008, sqlserver2012

        Get IO subsystem latency statistics for servers sql2008 and sqlserver2012.

    .EXAMPLE
        PS C:\> $output = Get-DbaIoLatency -SqlInstance sql2008 | Select * | ConvertTo-DbaDataTable

        Collects all IO subsystem latency statistics on server sql2008 into a Data Table.

    .EXAMPLE
        PS C:\> 'sql2008','sqlserver2012' | Get-DbaIoLatency

        Get IO subsystem latency statistics for servers sql2008 and sqlserver2012 via pipline

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> Get-DbaIoLatency -SqlInstance sql2008 -SqlCredential $cred

        Connects using sqladmin credential and returns IO subsystem latency statistics from sql2008
    #>
    [CmdletBinding()]
    Param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    BEGIN {
        $sql = "SELECT
            [vfs].[database_id],
            DB_NAME ([vfs].[database_id]) AS [DatabaseName],
            [vfs].[file_id],
            [mf].[physical_name],
            [num_of_reads],
            [io_stall_read_ms],
            [num_of_writes],
            [io_stall_write_ms],
            [io_stall],
            [num_of_bytes_read],
            [num_of_bytes_written],
            [sample_ms],
            [size_on_disk_bytes],
            [file_handle],
            [ReadLatency] =
            CASE WHEN [num_of_reads] = 0
                THEN 0
                ELSE ([io_stall_read_ms] / [num_of_reads])
            END,
            [WriteLatency] =
                CASE WHEN [num_of_writes] = 0
                    THEN 0
                    ELSE ([io_stall_write_ms] / [num_of_writes])
                END,
            [Latency] =
                CASE WHEN ([num_of_reads] = 0 AND [num_of_writes] = 0)
                    THEN 0
                    ELSE ([io_stall] / ([num_of_reads] + [num_of_writes]))
                END,
            [AvgBPerRead] =
                CASE WHEN [num_of_reads] = 0
                    THEN 0
                    ELSE ([num_of_bytes_read] / [num_of_reads])
                END,
            [AvgBPerWrite] =
                CASE WHEN [num_of_writes] = 0
                    THEN 0
                    ELSE ([num_of_bytes_written] / [num_of_writes])
                END,
            [AvgBPerTransfer] =
                CASE WHEN ([num_of_reads] = 0 AND [num_of_writes] = 0)
                    THEN 0
                    ELSE
                        (([num_of_bytes_read] + [num_of_bytes_written]) /
                        ([num_of_reads] + [num_of_writes]))
                    END
        FROM sys.dm_io_virtual_file_stats (NULL,NULL) AS [vfs]
        INNER JOIN sys.master_files AS [mf]
            ON [vfs].[database_id] = [mf].[database_id]
            AND [vfs].[file_id] = [mf].[file_id];"

        Write-Message -Level Debug -Message $sql

        $excludeColumns = 'FileHandle', 'ReadLatency', 'WriteLatency', 'Latency', 'AvgBPerRead', 'AvgBPerWrite', 'AvgBPerTransfer'
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($instance in $SqlInstance) {
            if (Test-FunctionInterrupt) { return }

            Write-Message -Level Verbose -Message "Connecting to $instance"

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            Write-Message -Level Verbose -Message "Connected to $instance"

            foreach ($row in $server.Query($sql)) {
                [PSCustomObject]@{
                    ComputerName         = $server.NetName
                    InstanceName         = $server.ServiceName
                    SqlInstance          = $server.DomainInstanceName
                    DatabaseId           = $row.database_id
                    DatabaseName         = $row.DatabaseName
                    FileId               = $row.file_id
                    PhysicalName         = $row.physical_name
                    NumberOfReads        = $row.num_of_reads
                    IoStallRead          = $row.io_stall_read_ms
                    NumberOfwrites       = $row.num_of_writes
                    IoStallWrite         = $row.io_stall_write_ms
                    IoStall              = $row.io_stall
                    NumberOfBytesRead    = $row.num_of_bytes_read
                    NumberOfBytesWritten = $row.num_of_bytes_written
                    SampleMilliseconds   = $row.sample_ms
                    SizeOnDiskBytes      = $row.num_of_bytes_written
                    FileHandle           = $row.file_handle
                    ReadLatency          = $row.ReadLatency
                    WriteLatency         = $row.WriteLatency
                    Latency              = $row.Latency
                    AvgBPerRead          = $row.AvgBPerRead
                    AvgBPerWrite         = $row.AvgBPerWrite
                    AvgBPerTransfer      = $row.AvgBPerTransfer
                } | Select-DefaultView -ExcludeProperty $excludeColumns
            }
        }
    }
}
tools\dbatools\functions\Get-DbaLastBackup.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaLastBackup {
    <#
    .SYNOPSIS
        Get date/time for last known backups of databases.

    .DESCRIPTION
        Retrieves and compares the date/time for the last known backups, as well as the creation date/time for the database.

        Default output includes columns Server, Database, RecoveryModel, LastFullBackup, LastDiffBackup, LastLogBackup, SinceFull, SinceDiff, SinceLog, Status, DatabaseCreated, DaysSinceDbCreated.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies one or more database(s) to process. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies one or more database(s) to exclude from processing.

    .PARAMETER EnableException
        If this switch is enabled exceptions will be thrown to the caller, which will need to perform its own exception processing. Otherwise, the function will try to catch the exception, interpret it and provide a friendly error message.

    .NOTES
        Tags: DisasterRecovery, Backup
        Author: Klaas Vandenberghe (@PowerDBAKlaas)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaLastBackup

    .EXAMPLE
        PS C:\> Get-DbaLastBackup -SqlInstance ServerA\sql987

        Returns a custom object displaying Server, Database, RecoveryModel, LastFullBackup, LastDiffBackup, LastLogBackup, SinceFull, SinceDiff, SinceLog, Status, DatabaseCreated, DaysSinceDbCreated

    .EXAMPLE
        PS C:\> Get-DbaLastBackup -SqlInstance ServerA\sql987

        Returns a custom object with Server name, Database name, and the date the last time backups were performed.

    .EXAMPLE
        PS C:\> Get-DbaLastBackup -SqlInstance ServerA\sql987 | Select *

        Returns a custom object with Server name, Database name, and the date the last time backups were performed, and also recoverymodel and calculations on how long ago backups were taken and what the status is.

    .EXAMPLE
        PS C:\> Get-DbaLastBackup -SqlInstance ServerA\sql987 | Select * | Out-Gridview

        Returns a gridview displaying Server, Database, RecoveryModel, LastFullBackup, LastDiffBackup, LastLogBackup, SinceFull, SinceDiff, SinceLog, Status, DatabaseCreated, DaysSinceDbCreated.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]
        $SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        function Get-DbaDateOrNull ($TimeSpan) {
            if ($TimeSpan -eq 0) {
                return $null
            }
            return $TimeSpan
        }
        $StartOfTime = [DbaTimeSpan](New-TimeSpan -Start ([datetime]0))
    }
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $dbs = $server.Databases | Where-Object { $_.name -ne 'tempdb' }

            if ($Database) {
                $dbs = $dbs | Where-Object Name -In $Database
            }

            if ($ExcludeDatabase) {
                $dbs = $dbs | Where-Object Name -NotIn $ExcludeDatabase
            }
            # Get-DbaBackupHistory -Last would make the job in one query but SMO's (and this) report the last backup of this type irregardless of the chain
            $FullHistory = Get-DbaBackupHistory -SqlInstance $server -Database $dbs.Name -LastFull -IncludeCopyOnly -Raw
            $DiffHistory = Get-DbaBackupHistory -SqlInstance $server -Database $dbs.Name -LastDiff -IncludeCopyOnly -Raw
            $IncrHistory = Get-DbaBackupHistory -SqlInstance $server -Database $dbs.Name -LastLog -IncludeCopyOnly -Raw
            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Processing $db on $instance"

                if ($db.IsAccessible -eq $false) {
                    Write-Message -Level Warning -Message "The database $db on server $instance is not accessible. Skipping database."
                    Continue
                }
                $LastFullBackup = ($FullHistory | Where-Object Database -eq $db.Name | Sort-Object -Property End -Descending | Select-Object -First 1).End
                if ($null -ne $LastFullBackup) {
                    $SinceFull_ = [DbaTimeSpan](New-TimeSpan -Start $LastFullBackup)
                } else {
                    $SinceFull_ = $StartOfTime
                }

                $LastDiffBackup = ($DiffHistory | Where-Object Database -eq $db.Name | Sort-Object -Property End -Descending | Select-Object -First 1).End
                if ($null -ne $LastDiffBackup) {
                    $SinceDiff_ = [DbaTimeSpan](New-TimeSpan -Start $LastDiffBackup)
                } else {
                    $SinceDiff_ = $StartOfTime
                }

                $LastIncrBackup = ($IncrHistory | Where-Object Database -eq $db.Name | Sort-Object -Property End -Descending | Select-Object -First 1).End
                if ($null -ne $LastIncrBackup) {
                    $SinceLog_ = [DbaTimeSpan](New-TimeSpan -Start $LastIncrBackup)
                } else {
                    $SinceLog_ = $StartOfTime
                }

                $daysSinceDbCreated = (New-TimeSpan -Start $db.createDate).Days

                if ($daysSinceDbCreated -lt 1 -and $SinceFull_ -eq 0) {
                    $Status = 'New database, not backed up yet'
                } elseif ($SinceFull_.Days -gt 0 -and $SinceDiff_.Days -gt 0) {
                    $Status = 'No Full or Diff Back Up in the last day'
                } elseif ($db.RecoveryModel -eq "Full" -and $SinceLog_.Hours -gt 0) {
                    $Status = 'No Log Back Up in the last hour'
                } else {
                    $Status = 'OK'
                }

                $result = [PSCustomObject]@{
                    ComputerName       = $server.ComputerName
                    InstanceName       = $server.ServiceName
                    SqlInstance        = $server.DomainInstanceName
                    Database           = $db.Name
                    RecoveryModel      = $db.RecoveryModel
                    LastFullBackup     = [DbaDateTime]$LastFullBackup
                    LastDiffBackup     = [DbaDateTime]$LastDiffBackup
                    LastLogBackup      = [DbaDateTime]$LastIncrBackup
                    SinceFull          = Get-DbaDateOrNull -TimeSpan $SinceFull_
                    SinceDiff          = Get-DbaDateOrNull -TimeSpan $SinceDiff_
                    SinceLog           = Get-DbaDateOrNull -TimeSpan $SinceLog_
                    DatabaseCreated    = $db.createDate
                    DaysSinceDbCreated = $daysSinceDbCreated
                    Status             = $status
                }
                Select-DefaultView -InputObject $result -Property ComputerName, InstanceName, SqlInstance, Database, LastFullBackup, LastDiffBackup, LastLogBackup
            }
        }
    }
}
tools\dbatools\functions\Get-DbaLastGoodCheckDb.ps1
function Get-DbaLastGoodCheckDb {
    <#
    .SYNOPSIS
        Get date/time for last known good DBCC CHECKDB

    .DESCRIPTION
        Retrieves and compares the date/time for the last known good DBCC CHECKDB, as well as the creation date/time for the database.

        This function supports SQL Server 2005 and higher.

        Please note that this script uses the DBCC DBINFO() WITH TABLERESULTS. DBCC DBINFO has several known weak points, such as:
        - DBCC DBINFO is an undocumented feature/command.
        - The LastKnowGood timestamp is updated when a DBCC CHECKFILEGROUP is performed.
        - The LastKnowGood timestamp is updated when a DBCC CHECKDB WITH PHYSICAL_ONLY is performed.
        - The LastKnowGood timestamp does not get updated when a database in READ_ONLY.

        An empty ($null) LastGoodCheckDb result indicates that a good DBCC CHECKDB has never been performed.

        SQL Server 2008R2 has a "bug" that causes each databases to possess two dbi_dbccLastKnownGood fields, instead of the normal one.

        This script will only display this function to only display the newest timestamp. If -Verbose is specified, the function will announce every time more than one dbi_dbccLastKnownGood fields is encountered.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Defaults to localhost.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies one or more database(s) to process. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies one or more database(s) to exclude from processing.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: CHECKDB, Database
        Author: Jakob Bindslet ([email protected])

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Ref:
        DBCC CHECKDB:
        https://msdn.microsoft.com/en-us/library/ms176064.aspx
        http://www.sqlcopilot.com/dbcc-checkdb.html
        Data Purity:
        http://www.sqlskills.com/blogs/paul/checkdb-from-every-angle-how-to-tell-if-data-purity-checks-will-be-run/
        https://www.mssqltips.com/sqlservertip/1988/ensure-sql-server-data-purity-checks-are-performed/

    .LINK
        https://dbatools.io/Get-DbaLastGoodCheckDb

    .EXAMPLE
        PS C:\> Get-DbaLastGoodCheckDb -SqlInstance ServerA\sql987

        Returns a custom object displaying Server, Database, DatabaseCreated, LastGoodCheckDb, DaysSinceDbCreated, DaysSinceLastGoodCheckDb, Status and DataPurityEnabled

    .EXAMPLE
        PS C:\> Get-DbaLastGoodCheckDb -SqlInstance ServerA\sql987 -SqlCredential sqladmin | Format-Table -AutoSize

        Returns a formatted table displaying Server, Database, DatabaseCreated, LastGoodCheckDb, DaysSinceDbCreated, DaysSinceLastGoodCheckDb, Status and DataPurityEnabled. Authenticates using SQL Server authentication.

    .EXAMPLE
        PS C:\> Get-DbaLastGoodCheckDb -SqlInstance sql2016 -ExcludeDatabase "TempDB" | Format-Table -AutoSize

        Returns a formatted table displaying Server, Database, DatabaseCreated, LastGoodCheckDb, DaysSinceDbCreated, DaysSinceLastGoodCheckDb, Status and DataPurityEnabled. All databases except for "TempDB" will be displayed in the output.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($server.versionMajor -lt 9) {
                Stop-Function -Message "Get-DbaLastGoodCheckDb is only supported on SQL Server 2005 and above. Skipping Instance." -Continue -Target $instance
            }

            $dbs = $server.Databases

            if ($Database) {
                $dbs = $dbs | Where-Object Name -In $Database
            }

            if ($ExcludeDatabase) {
                $dbs = $dbs | Where-Object Name -NotIn $ExcludeDatabase
            }

            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Processing $db on $instances."

                if ($db.IsAccessible -eq $false) {
                    Stop-Function -Message "The database $db is not accessible. Skipping database." -Continue -Target $db
                }

                $sql = "DBCC DBINFO ([$($db.name)]) WITH TABLERESULTS"
                Write-Message -Level Debug -Message "T-SQL: $sql"

                $resultTable = $db.ExecuteWithResults($sql).Tables[0]
                [datetime[]]$lastKnownGoodArray = $resultTable | Where-Object Field -eq 'dbi_dbccLastKnownGood' | Select-Object -ExpandProperty Value

                ## look for databases with two or more occurrences of the field dbi_dbccLastKnownGood
                if ($lastKnownGoodArray.count -ge 2) {
                    Write-Message -Level Verbose -Message "The database $db has $($lastKnownGoodArray.count) dbi_dbccLastKnownGood fields. This script will only use the newest!"
                }
                [datetime]$lastKnownGood = $lastKnownGoodArray | Sort-Object -Descending | Select-Object -First 1

                [int]$createVersion = ($resultTable | Where-Object Field -eq 'dbi_createVersion').Value
                [int]$dbccFlags = ($resultTable | Where-Object Field -eq 'dbi_dbccFlags').Value

                if (($createVersion -lt 611) -and ($dbccFlags -eq 0)) {
                    $dataPurityEnabled = $false
                } else {
                    $dataPurityEnabled = $true
                }

                $daysSinceCheckDb = (New-TimeSpan -Start $lastKnownGood -End (Get-Date)).Days
                $daysSinceDbCreated = (New-TimeSpan -Start $db.createDate -End (Get-Date)).TotalDays

                if ($daysSinceCheckDb -lt 7) {
                    $Status = 'Ok'
                } elseif ($daysSinceDbCreated -lt 7) {
                    $Status = 'New database, not checked yet'
                } else {
                    $Status = 'CheckDB should be performed'
                }

                if ($lastKnownGood -eq '1/1/1900 12:00:00 AM') {
                    Remove-Variable -Name lastKnownGood, daysSinceCheckDb
                }

                [PSCustomObject]@{
                    ComputerName             = $server.ComputerName
                    InstanceName             = $server.ServiceName
                    SqlInstance              = $server.DomainInstanceName
                    Database                 = $db.name
                    DatabaseCreated          = $db.createDate
                    LastGoodCheckDb          = $lastKnownGood
                    DaysSinceDbCreated       = $daysSinceDbCreated
                    DaysSinceLastGoodCheckDb = $daysSinceCheckDb
                    Status                   = $status
                    DataPurityEnabled        = $dataPurityEnabled
                    CreateVersion            = $createVersion
                    DbccFlags                = $dbccFlags
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaLatchStatistic.ps1
function Get-DbaLatchStatistic {
    <#
    .SYNOPSIS
        Displays latch statistics from sys.dm_os_latch_stats

    .DESCRIPTION
        This command is based off of Paul Randal's post "Advanced SQL Server performance tuning"

        Returns:
                LatchClass
                WaitSeconds
                WaitCount
                Percentage
                AverageWaitSeconds
                URL

        Reference:  https://www.sqlskills.com/blogs/paul/advanced-performance-troubleshooting-waits-latches-spinlocks/
                    https://www.sqlskills.com/blogs/paul/most-common-latch-classes-and-what-they-mean/

    .PARAMETER SqlInstance
        The SQL Server instance. Server version must be SQL Server version 2005 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Threshold
        Threshold, in percentage of all latch stats on the system. Default per Paul's post is 95%.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: LatchStatistics, Waits
        Author: Patrick Flynn (@sqllensman)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaLatchStatistic

    .EXAMPLE
        PS C:\> Get-DbaLatchStatistic -SqlInstance sql2008, sqlserver2012

        Check latch statistics for servers sql2008 and sqlserver2012

    .EXAMPLE
        PS C:\> Get-DbaLatchStatistic -SqlInstance sql2008 -Threshold 98

        Check latch statistics on server sql2008 for thresholds above 98%

    .EXAMPLE
        PS C:\> $output = Get-DbaLatchStatistic -SqlInstance sql2008 -Threshold 100 | Select * | ConvertTo-DbaDataTable

        Collects all latch statistics on server sql2008 into a Data Table.

    .EXAMPLE
        PS C:\> 'sql2008','sqlserver2012' | Get-DbaLatchStatistic

        Get latch statistics for servers sql2008 and sqlserver2012 via pipline

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> Get-DbaLatchStatistic -SqlInstance sql2008 -SqlCredential $cred

        Connects using sqladmin credential and returns latch statistics from sql2008

    .EXAMPLE
        PS C:\> $output = Get-DbaLatchStatistic -SqlInstance sql2008
        PS C:\> $output
        PS C:\> foreach ($row in ($output | Sort-Object -Unique Url)) { Start-Process ($row).Url }

        Displays the output then loads the associated sqlskills website for each result. Opens one tab per unique URL.
    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [int]$Threshold = 95,
        [Alias('Silent')]
        [switch]$EnableException
    )

    BEGIN {
        $sql = "WITH [Latches] AS
               (
                   SELECT
                       [latch_class],
                       [wait_time_ms] / 1000.0 AS [WaitS],
                       [waiting_requests_count] AS [WaitCount],
                       Case WHEN SUM ([wait_time_ms]) OVER() = 0 THEN NULL ELSE 100.0 * [wait_time_ms] / SUM ([wait_time_ms]) OVER() END AS [Percentage],
                       ROW_NUMBER() OVER(ORDER BY [wait_time_ms] DESC) AS [RowNum]
                   FROM sys.dm_os_latch_stats
                   WHERE [latch_class] NOT IN (N'BUFFER')
               )
               SELECT
                   MAX ([W1].[latch_class]) AS [LatchClass],
                   CAST (MAX ([W1].[WaitS]) AS DECIMAL(14, 2)) AS [WaitSeconds],
                   MAX ([W1].[WaitCount]) AS [WaitCount],
                   CAST (MAX ([W1].[Percentage]) AS DECIMAL(14, 2)) AS [Percentage],
                   CAST ((MAX ([W1].[WaitS]) / MAX ([W1].[WaitCount])) AS DECIMAL (14, 4)) AS [AvgWaitSeconds],
                   CAST ('https://www.sqlskills.com/help/latches/' + MAX ([W1].[latch_class]) as XML) AS [URL]
               FROM [Latches] AS [W1]
               INNER JOIN [Latches] AS [W2]
                   ON [W2].[RowNum] <= [W1].[RowNum]
               GROUP BY [W1].[RowNum]
               HAVING SUM ([W2].[Percentage]) - MAX ([W1].[Percentage]) < $Threshold;"

        Write-Message -Level Debug -Message $sql
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($instance in $SqlInstance) {
            Write-Message -Level Verbose -Message "Connecting to $instance"
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                Return
            }
            Write-Message -Level Verbose -Message "Connected to $instance"

            foreach ($row in $server.Query($sql)) {
                [PSCustomObject]@{
                    ComputerName       = $server.NetName
                    InstanceName       = $server.ServiceName
                    SqlInstance        = $server.DomainInstanceName
                    WaitType           = $row.LatchClass
                    WaitSeconds        = $row.WaitSeconds
                    WaitCount          = $row.WaitCount
                    Percentage         = $row.Percentage
                    AverageWaitSeconds = $row.AvgWaitSeconds
                    URL                = $row.URL
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaLinkedServer.ps1
function Get-DbaLinkedServer {
    <#
    .SYNOPSIS
        Gets all linked servers and a summary of information from the linked servers listed.

    .DESCRIPTION
        Retrieves information about each linked server on the instance(s).

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function
        to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER LinkedServer
        The linked server(s) to process - this list is auto-populated from the server. If unspecified, all linked servers will be processed.

    .PARAMETER ExcludeLinkedServer
        The linked server(s) to exclude - this list is auto-populated from the server

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: LinkedServer, Linked
        Author: Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaLinkedServer

    .EXAMPLE
        PS C:\> Get-DbaLinkedServer -SqlInstance DEV01

        Returns all linked servers for the SQL Server instance DEV01

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance DEV01 -Group SQLDEV | Get-DbaLinkedServer | Out-GridView

        Returns all linked servers for a group of servers from SQL Server Central Management Server (CMS). Send output to GridView.
    #>
    [CmdletBinding(DefaultParameterSetName = 'Default')]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$LinkedServer,
        [object[]]$ExcludeLinkedServer,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($Instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $lservers = $server.LinkedServers

            if ($LinkedServer) {
                $lservers = $lservers | Where-Object { $_.Name -in $LinkedServer }
            }
            if ($ExcludeLinkedServer) {
                $lservers = $lservers | Where-Object { $_.Name -notin $ExcludeLinkedServer }
            }

            foreach ($ls in $lservers) {
                Add-Member -Force -InputObject $ls -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                Add-Member -Force -InputObject $ls -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                Add-Member -Force -InputObject $ls -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                Add-Member -Force -InputObject $ls -MemberType NoteProperty -Name Impersonate -value $ls.LinkedServerLogins.Impersonate
                Add-Member -Force -InputObject $ls -MemberType NoteProperty -Name RemoteUser -value $ls.LinkedServerLogins.RemoteUser

                Select-DefaultView -InputObject $ls -Property ComputerName, InstanceName, SqlInstance, Name, 'DataSource as RemoteServer', ProductName, Impersonate, RemoteUser, 'DistPublisher as Publisher', Distributor, DateLastModified
            }
        }
    }
}
tools\dbatools\functions\Get-DbaLocaleSetting.ps1
function Get-DbaLocaleSetting {
    <#
    .SYNOPSIS
        Gets the Locale settings on a computer.

    .DESCRIPTION
        Gets the Locale settings on one or more computers.

        Requires Local Admin rights on destination computer(s).

    .PARAMETER ComputerName
        The target SQL Server instance or instances.

    .PARAMETER Credential
        Credential object used to connect to the computer as a different user.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: OS
        Author: Klaas Vandenberghe (@PowerDBAKlaas)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaLocaleSetting

    .EXAMPLE
        PS C:\> Get-DbaLocaleSetting -ComputerName sqlserver2014a

        Gets the Locale settings on computer sqlserver2014a.

    .EXAMPLE
        PS C:\> 'sql1','sql2','sql3' | Get-DbaLocaleSetting

        Gets the Locale settings on computers sql1, sql2 and sql3.

    .EXAMPLE
        PS C:\> Get-DbaLocaleSetting -ComputerName sql1,sql2 -SqlCredential $credential | Out-Gridview

        Gets the Locale settings on computers sql1 and sql2 using SQL Authentication to authenticate to the servers, and shows them in a grid view.

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [Alias("cn", "host", "Server")]
        [string[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential] $Credential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $ComputerName = $ComputerName | ForEach-Object {$_.split("\")[0]} | Select-Object -Unique
        $sessionoption = New-CimSessionOption -Protocol DCom
        $keyname = "Control Panel\International"
        $NS = 'root\cimv2'
        $Reg = 'StdRegProv'
        [UInt32]$CIMHiveCU = 2147483649
    }
    process {
        # uses cim commands
        
        
        foreach ($computer in $ComputerName) {
            $props = @{ "ComputerName" = $computer }
            $Server = Resolve-DbaNetworkName -ComputerName $Computer -Credential $credential
            if ( $Server.FullComputerName ) {
                $Computer = $server.FullComputerName
                Write-Message -Level Verbose -Message "Creating CIMSession on $computer over WSMan"
                $CIMsession = New-CimSession -ComputerName $Computer -ErrorAction SilentlyContinue -Credential $Credential
                if ( -not $CIMSession ) {
                    Write-Message -Level Verbose -Message "Creating CIMSession on $computer over WSMan failed. Creating CIMSession on $computer over DCom"
                    $CIMsession = New-CimSession -ComputerName $Computer -SessionOption $sessionoption -ErrorAction SilentlyContinue -Credential $Credential
                }
                if ( $CIMSession ) {
                    Write-Message -Level Verbose -Message "Getting properties from Registry Key"
                    $PropNames = Invoke-CimMethod -CimSession $CIMsession -Namespace $NS -ClassName $Reg -MethodName enumvalues -Arguments @{hDefKey = $CIMHiveCU; sSubKeyName = $keyname} |
                        Select-Object -ExpandProperty snames

                    foreach ($Name in $PropNames) {
                        $sValue = Invoke-CimMethod -CimSession $CIMsession -Namespace $NS -ClassName $Reg -MethodName GetSTRINGvalue -Arguments @{hDefKey = $CIMHiveCU; sSubKeyName = $keyname; sValueName = $Name} |
                            Select-Object -ExpandProperty svalue
                        $props.add($Name, $sValue)
                    }
                    [PSCustomObject]$props
                } #if CIMSession
                else {
                    Write-Message -Level Warning -Message "Can't create CIMSession on $computer"
                }
            } #if computername
            else {
                Write-Message -Level Warning -Message "Can't connect to $computer"
            }
        } #foreach computer
    } #PROCESS
} #function
tools\dbatools\functions\Get-DbaLogin.ps1
function Get-DbaLogin {
    <#
    .SYNOPSIS
        Function to get an SMO login object of the logins for a given SQL Server instance. Takes a server object from the pipeline.

    .DESCRIPTION
        The Get-DbaLogin function returns an SMO Login object for the logins passed, if there are no users passed it will return all logins.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SqlCredential
        Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.

    .PARAMETER Login
        The login(s) to process - this list is auto-populated from the server. If unspecified, all logins will be processed.

    .PARAMETER ExcludeLogin
        The login(s) to exclude - this list is auto-populated from the server

    .PARAMETER IncludeFilter
        A list of logins to include - accepts wildcard patterns

    .PARAMETER ExcludeFilter
        A list of logins to exclude - accepts wildcard patterns

    .PARAMETER ExcludeSystemLogin
        A Switch to remove System Logins from the output.

    .PARAMETER Type
        Filters logins by their type. Valid options are Windows and SQL.

    .PARAMETER Locked
        A Switch to return locked Logins.

    .PARAMETER Disabled
        A Switch to return disabled Logins.

    .PARAMETER SqlLogins
        Deprecated. Please use -Type SQL

    .PARAMETER WindowsLogins
        Deprecated. Please use -Type Windows.

    .PARAMETER HasAccess
        A Switch to return Logins that have access to the instance of SQL Server.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Login, Security
        Author: Mitchell Hamann (@SirCaptainMitch) | Rob Sewell (@SQLDBaWithBeard)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaLogin

    .EXAMPLE
        PS C:\> Get-DbaLogin -SqlInstance sql2016

        Gets all the logins from server sql2016 using NT authentication and returns the SMO login objects

    .EXAMPLE
        PS C:\> Get-DbaLogin -SqlInstance sql2016 -SqlCredential $sqlcred

        Gets all the logins for a given SQL Server using a passed credential object and returns the SMO login objects

    .EXAMPLE
        PS C:\> Get-DbaLogin -SqlInstance sql2016 -SqlCredential $sqlcred -Login dbatoolsuser,TheCaptain

        Get specific logins from server sql2016 returned as SMO login objects.

    .EXAMPLE
        PS C:\> Get-DbaLogin -SqlInstance sql2016 -IncludeFilter '##*','NT *'

        Get all user objects from server sql2016 beginning with '##' or 'NT ', returned as SMO login objects.

    .EXAMPLE
        PS C:\> Get-DbaLogin -SqlInstance sql2016 -ExcludeLogin dbatoolsuser

        Get all user objects from server sql2016 except the login dbatoolsuser, returned as SMO login objects.

    .EXAMPLE
        PS C:\> Get-DbaLogin -SqlInstance sql2016 -Type Windows

        Get all user objects from server sql2016 that are Windows Logins

    .EXAMPLE
        PS C:\> Get-DbaLogin -SqlInstance sql2016 -Type Windows -IncludeFilter *Rob*

        Get all user objects from server sql2016 that are Windows Logins and have Rob in the name

    .EXAMPLE
        PS C:\> Get-DbaLogin -SqlInstance sql2016 -Type SQL

        Get all user objects from server sql2016 that are SQL Logins

    .EXAMPLE
        PS C:\> Get-DbaLogin -SqlInstance sql2016 -Type SQL -IncludeFilter *Rob*

        Get all user objects from server sql2016 that are SQL Logins and have Rob in the name

    .EXAMPLE
        PS C:\> Get-DbaLogin -SqlInstance sql2016 -ExcludeSystemLogin

        Get all user objects from server sql2016 that are not system objects

    .EXAMPLE
        PS C:\> Get-DbaLogin -SqlInstance sql2016 -ExcludeFilter '##*','NT *'

        Get all user objects from server sql2016 except any beginning with '##' or 'NT ', returned as SMO login objects.

    .EXAMPLE
        PS C:\> 'sql2016', 'sql2014' | Get-DbaLogin -SqlCredential $sqlcred

        Using Get-DbaLogin on the pipeline, you can also specify which names you would like with -Login.

    .EXAMPLE
        PS C:\> 'sql2016', 'sql2014' | Get-DbaLogin -SqlCredential $sqlcred -Locked

        Using Get-DbaLogin on the pipeline to get all locked logins on servers sql2016 and sql2014.

    .EXAMPLE
        PS C:\> 'sql2016', 'sql2014' | Get-DbaLogin -SqlCredential $sqlcred -HasAccess -Disabled

        Using Get-DbaLogin on the pipeline to get all Disabled logins that have access on servers sql2016 or sql2014.

#>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Login,
        [object[]]$IncludeFilter,
        [object[]]$ExcludeLogin,
        [object[]]$ExcludeFilter,
        [Alias('ExcludeSystemLogins')]
        [switch]$ExcludeSystemLogin,
        [ValidateSet('Windows', 'SQL')]
        [string]$Type,
        [switch]$HasAccess,
        [switch]$SqlLogins,
        [switch]$WindowsLogins,
        [switch]$Locked,
        [switch]$Disabled,
        [switch]$EnableException
    )
    begin {
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter SQLLogins
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter WindowsLogins

        if ($SQLLogins) {
            $Type = "SQL"
        }
        if ($WindowsLogins) {
            $Type = "Windows"
        }
    }
    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $serverLogins = $server.Logins

            if ($Login) {
                $serverLogins = $serverLogins | Where-Object Name -in $Login
            }

            if ($ExcludeSystemLogin) {
                $serverLogins = $serverLogins | Where-Object IsSystemObject -eq $false
            }

            if ($Type -eq 'Windows') {
                $serverLogins = $serverLogins | Where-Object LoginType -eq 'WindowsUser'
            }

            if ($Type -eq 'SQL') {
                $serverLogins = $serverLogins | Where-Object LoginType -eq 'SqlLogin'
            }

            if ($IncludeFilter) {
                $serverLogins = $serverLogins | Where-Object {
                    foreach ($filter in $IncludeFilter) {
                        if ($_.Name -like $filter) {
                            return $true;
                        }
                    }
                }
            }

            if ($ExcludeLogin) {
                $serverLogins = $serverLogins | Where-Object Name -NotIn $ExcludeLogin
            }

            if ($ExcludeFilter) {
                foreach ($filter in $ExcludeFilter) {
                    $serverLogins = $serverLogins | Where-Object Name -NotLike $filter
                }
            }

            if ($HasAccess) {
                $serverLogins = $serverLogins | Where-Object HasAccess
            }

            if ($Locked) {
                $serverLogins = $serverLogins | Where-Object IsLocked
            }

            if ($Disabled) {
                $serverLogins = $serverLogins | Where-Object IsDisabled
            }

            foreach ($serverLogin in $serverlogins) {
                Write-Message -Level Verbose -Message "Processing $serverLogin on $instance"

                if ($server.VersionMajor -gt 9) {
                    # There's no reliable method to get last login time with SQL Server 2000, so only show on 2005+
                    Write-Message -Level Verbose -Message "Getting last login time"
                    $sql = "SELECT MAX(login_time) AS [login_time] FROM sys.dm_exec_sessions WHERE login_name = '$($serverLogin.name)'"
                    Add-Member -Force -InputObject $serverLogin -MemberType NoteProperty -Name LastLogin -Value $server.ConnectionContext.ExecuteScalar($sql)
                } else {
                    Add-Member -Force -InputObject $serverLogin -MemberType NoteProperty -Name LastLogin -Value $null
                }

                Add-Member -Force -InputObject $serverLogin -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName
                Add-Member -Force -InputObject $serverLogin -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName
                Add-Member -Force -InputObject $serverLogin -MemberType NoteProperty -Name SqlInstance -Value $server.DomainInstanceName

                Select-DefaultView -InputObject $serverLogin -Property ComputerName, InstanceName, SqlInstance, Name, LoginType, CreateDate, LastLogin, HasAccess, IsLocked, IsDisabled
            }
        }
    }
}
tools\dbatools\functions\Get-DbaMaintenanceSolutionLog.ps1
function Get-DbaMaintenanceSolutionLog {
    <#
    .SYNOPSIS
        Reads the log files generated by the IndexOptimize Agent Job from Ola Hallengren's MaintenanceSolution.

    .DESCRIPTION
        Ola wrote a .sql script to get the content from the commandLog table. However, if LogToTable='N', there will be no logging in that table. This function reads the text files that are written in the SQL Instance's Log directory.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER LogType
        Accepts 'IndexOptimize', 'DatabaseBackup', 'DatabaseIntegrityCheck'. ATM only IndexOptimize parsing is available

    .PARAMETER Since
        Consider only files generated since this date

    .PARAMETER Path
        Where to search for log files. By default it's the SQL instance errorlogpath path

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Ola, Maintenance
        Author: Klaas Vandenberghe (@powerdbaklaas) | Simone Bizzotto ( @niphlod )

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaMaintenanceSolutionLog

    .EXAMPLE
        PS C:\> Get-DbaMaintenanceSolutionLog -SqlInstance sqlserver2014a

        Gets the outcome of the IndexOptimize job on sql instance sqlserver2014a.

    .EXAMPLE
        PS C:\> Get-DbaMaintenanceSolutionLog -SqlInstance sqlserver2014a -SqlCredential $credential

        Gets the outcome of the IndexOptimize job on sqlserver2014a, using SQL Authentication.

    .EXAMPLE
        PS C:\> 'sqlserver2014a', 'sqlserver2020test' | Get-DbaMaintenanceSolutionLog

        Gets the outcome of the IndexOptimize job on sqlserver2014a and sqlserver2020test.

    .EXAMPLE
        PS C:\> Get-DbaMaintenanceSolutionLog -SqlInstance sqlserver2014a -Path 'D:\logs\maintenancesolution\'

        Gets the outcome of the IndexOptimize job on sqlserver2014a, reading the log files in their custom location.

    .EXAMPLE
        PS C:\> Get-DbaMaintenanceSolutionLog -SqlInstance sqlserver2014a -Since '2017-07-18'

        Gets the outcome of the IndexOptimize job on sqlserver2014a, starting from july 18, 2017.

    .EXAMPLE
        PS C:\> Get-DbaMaintenanceSolutionLog -SqlInstance sqlserver2014a -LogType IndexOptimize

        Gets the outcome of the IndexOptimize job on sqlserver2014a, the other options are not yet available! sorry

    #>
    [CmdletBinding(DefaultParameterSetName = "Default")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseApprovedVerbs", "", Justification = "Internal functions are ignored")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [ValidateSet('IndexOptimize', 'DatabaseBackup', 'DatabaseIntegrityCheck')]
        [string[]]$LogType = 'IndexOptimize',
        [datetime]$Since,
        [string]$Path,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        function process-block ($block) {
            $fresh = @{
                'ObjectType'     = $null
                'IndexType'      = $null
                'ImageText'      = $null
                'NewLOB'         = $null
                'FileStream'     = $null
                'ColumnStore'    = $null
                'AllowPageLocks' = $null
                'PageCount'      = $null
                'Fragmentation'  = $null
                'Error'          = $null
            }
            foreach ($l in $block) {
                $splitted = $l -split ': ', 2
                if (($splitted.Length -ne 2) -or ($splitted[0].length -gt 20)) {
                    if ($null -eq $fresh['Error']) {
                        $fresh['Error'] = New-Object System.Collections.ArrayList
                    }
                    $null = $fresh['Error'].Add($l)
                    continue
                }
                $k = $splitted[0]
                $v = $splitted[1]
                if ($k -eq 'Date and Time') {
                    # this is the end date, we already parsed the start date of the block
                    if ($fresh.ContainsKey($k)) {
                        continue
                    }
                }
                $fresh[$k] = $v
            }
            if ($fresh.ContainsKey('Command')) {
                if ($fresh['Command'] -match '(SET LOCK_TIMEOUT (?<timeout>\d+); )?ALTER INDEX \[(?<index>[^\]]+)\] ON \[(?<database>[^\]]+)\]\.\[(?<schema>[^]]+)\]\.\[(?<table>[^\]]+)\] (?<action>[^\ ]+)( PARTITION = (?<partition>\d+))? WITH \((?<options>[^\)]+)') {
                    $fresh['Index'] = $Matches.index
                    $fresh['Statistics'] = $null
                    $fresh['Schema'] = $Matches.Schema
                    $fresh['Table'] = $Matches.Table
                    $fresh['Action'] = $Matches.action
                    $fresh['Options'] = $Matches.options
                    $fresh['Timeout'] = $Matches.timeout
                    $fresh['Partition'] = $Matches.partition
                } elseif ($fresh['Command'] -match '(SET LOCK_TIMEOUT (?<timeout>\d+); )?UPDATE STATISTICS \[(?<database>[^\]]+)\]\.\[(?<schema>[^]]+)\]\.\[(?<table>[^\]]+)\] \[(?<stat>[^\]]+)\]') {
                    $fresh['Index'] = $null
                    $fresh['Statistics'] = $Matches.stat
                    $fresh['Schema'] = $Matches.Schema
                    $fresh['Table'] = $Matches.Table
                    $fresh['Action'] = $null
                    $fresh['Options'] = $null
                    $fresh['Timeout'] = $Matches.timeout
                    $fresh['Partition'] = $null
                }
            }
            if ($fresh.ContainsKey('Comment')) {
                $commentparts = $fresh['Comment'] -split ', '
                foreach ($part in $commentparts) {
                    $indkey, $indvalue = $part -split ': ', 2
                    if ($fresh.ContainsKey($indkey)) {
                        $fresh[$indkey] = $indvalue
                    }
                }
            }
            if ($null -ne $fresh['Error']) {
                $fresh['Error'] = $fresh['Error'] -join "`n"
            }

            return $fresh
        }
    }
    process {
        foreach ($instance in $sqlinstance) {
            $logdir = $logfiles = $null
            $computername = $instance.ComputerName

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Can't connect to $instance" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            if ($logtype -ne 'IndexOptimize') {
                Write-Message -Level Warning -Message "Parsing $logtype is not supported at the moment"
                Continue
            }
            if ($Path) {
                $logdir = Join-AdminUnc -Servername $server.ComputerName -Filepath $Path
            } else {
                $logdir = Join-AdminUnc -Servername $server.ComputerName -Filepath $server.errorlogpath # -replace '^(.):', "\\$computername\`$1$"
            }
            if (!$logdir) {
                Write-Message -Level Warning -Message "No log directory returned from $instance"
                Continue
            }

            Write-Message -Level Verbose -Message "Log directory on $computername is $logdir"
            if (! (Test-Path $logdir)) {
                Write-Message -Level Warning -Message "Directory $logdir is not accessible"
                continue
            }
            $logfiles = [System.IO.Directory]::EnumerateFiles("$logdir", "IndexOptimize_*.txt")
            if ($Since) {
                $filteredlogs = @()
                foreach ($l in $logfiles) {
                    $base = $($l.Substring($l.Length - 15, 15))
                    try {
                        $datefile = [DateTime]::ParseExact($base, 'yyyyMMdd_HHmmss', $null)
                    } catch {
                        $datefile = Get-ItemProperty -Path $l | Select-Object -ExpandProperty CreationTime
                    }
                    if ($datefile -gt $since) {
                        $filteredlogs += $l
                    }
                }
                $logfiles = $filteredlogs
            }
            if (! $logfiles.count -ge 1) {
                Write-Message -Level Warning -Message "No log files returned from $computername"
                Continue
            }
            $instanceinfo = @{ }
            $instanceinfo['ComputerName'] = $server.ComputerName
            $instanceinfo['InstanceName'] = $server.ServiceName
            $instanceinfo['SqlInstance'] = $server.Name

            foreach ($File in $logfiles) {
                Write-Message -Level Verbose -Message "Reading $file"
                $text = New-Object System.IO.StreamReader -ArgumentList "$File"
                $block = New-Object System.Collections.ArrayList
                $remember = @{}
                while ($line = $text.ReadLine()) {

                    $real = $line.Trim()
                    if ($real.Length -eq 0) {
                        $processed = process-block $block
                        if ('Procedure' -in $processed.Keys) {
                            $block = New-Object System.Collections.ArrayList
                            continue
                        }
                        if ('Database' -in $processed.Keys) {
                            Write-Message -Level Verbose -Message "Index and Stats Optimizations on Database $($processed.Database) on $computername"
                            $processed.Remove('Is accessible')
                            $processed.Remove('User access')
                            $processed.Remove('Date and time')
                            $processed.Remove('Standby')
                            $processed.Remove('Recovery Model')
                            $processed.Remove('Updateability')
                            $processed['Database'] = $processed['Database'].Trim('[]')
                            $remember = $processed.Clone()
                        } else {
                            foreach ($k in $processed.Keys) {
                                $remember[$k] = $processed[$k]
                            }
                            $remember.Remove('Command')
                            $remember['StartTime'] = [dbadatetime]([DateTime]::ParseExact($remember['Date and time'] , "yyyy-MM-dd HH:mm:ss", $null))
                            $remember.Remove('Date and time')
                            $remember['Duration'] = ($remember['Duration'] -as [timespan])
                            [pscustomobject]$remember
                        }
                        $block = New-Object System.Collections.ArrayList
                    } else {
                        $null = $block.Add($real)
                    }
                }
                $text.close()
            }
        }
    }
}
tools\dbatools\functions\Get-DbaManagementObject.ps1
function Get-DbaManagementObject {
    <#
    .SYNOPSIS
        Gets SQL Mangaement Object versions installed on the machine.

    .DESCRIPTION
        The Get-DbaManagementObject returns an object with the Version and the
        Add-Type Load Template for each version on the server.

    .PARAMETER ComputerName
        The name of the Windows Server(s) you would like to check.

    .PARAMETER Credential
        This command uses Windows credentials. This parameter allows you to connect remotely as a different user.

    .PARAMETER VersionNumber
        This is the specific version number you are looking for. The function will look
        for that version only.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: SMO
        Author: Ben Miller (@DBAduck), http://dbaduck.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaManagementObject

    .EXAMPLE
        PS C:\> Get-DbaManagementObject

        Returns all versions of SMO on the computer

    .EXAMPLE
        PS C:\> Get-DbaManagementObject -VersionNumber 13

        Returns just the version specified. If the version does not exist then it will return nothing.

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlInstance")]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]
        $Credential,
        [int]$VersionNumber,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        if (!$VersionNumber) {
            $VersionNumber = 0
        }
        $scriptblock = {
            $VersionNumber = [int]$args[0]
            <# DO NOT use Write-Message as this is inside of a script block #>
            Write-Verbose -Message "Checking currently loaded SMO version"
            $loadedversion = [AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.Fullname -like "Microsoft.SqlServer.SMO,*" }
            if ($loadedversion) {
                $loadedversion = $loadedversion | ForEach-Object {
                    if ($_.Location -match "__") {
                        ((Split-Path (Split-Path $_.Location) -Leaf) -split "__")[0]
                    } else {
                        ((Get-ChildItem -Path $_.Location).VersionInfo.ProductVersion)
                    }
                }
            }
            <# DO NOT use Write-Message as this is inside of a script block #>
            Write-Verbose -Message "Looking for included smo library"
            $localversion = [version](Get-ChildItem -Path "$script:PSModuleRoot\bin\smo\Microsoft.SqlServer.Smo.dll").VersionInfo.ProductVersion

            foreach ($version in $localversion) {
                if ($VersionNumber -eq 0) {
                    <# DO NOT use Write-Message as this is inside of a script block #>
                    Write-Verbose -Message "Did not pass a version"
                    [PSCustomObject]@{
                        ComputerName = $env:COMPUTERNAME
                        Version      = $localversion
                        Loaded       = $loadedversion -contains $localversion
                        LoadTemplate = "Add-Type -Path $("$script:PSModuleRoot\bin\smo\Microsoft.SqlServer.Smo.dll")"
                    }
                } else {
                    <# DO NOT use Write-Message as this is inside of a script block #>
                    Write-Verbose -Message "Passed version $VersionNumber, looking for that specific version"
                    if ($localversion.ToString().StartsWith("$VersionNumber.")) {
                        <# DO NOT use Write-Message as this is inside of a script block #>
                        Write-Verbose -Message "Found the Version $VersionNumber"
                        [PSCustomObject]@{
                            ComputerName = $env:COMPUTERNAME
                            Version      = $localversion
                            Loaded       = $loadedversion -contains $localversion
                            LoadTemplate = "Add-Type -Path $("$script:PSModuleRoot\bin\smo\Microsoft.SqlServer.Smo.dll")"
                        }
                    }
                }
            }
            <# DO NOT use Write-Message as this is inside of a script block #>
            Write-Verbose -Message "Looking for SMO in the Global Assembly Cache"
            $smolist = (Get-ChildItem -Path "$env:SystemRoot\assembly\GAC_MSIL\Microsoft.SqlServer.Smo" | Sort-Object Name -Descending).Name

            foreach ($version in $smolist) {
                $array = $version.Split("__")
                if ($VersionNumber -eq 0) {
                    <# DO NOT use Write-Message as this is inside of a script block #>
                    Write-Verbose -Message "Did not pass a version, looking for all versions"
                    $currentversion = $array[0]
                    [PSCustomObject]@{
                        ComputerName = $env:COMPUTERNAME
                        Version      = $currentversion
                        Loaded       = $loadedversion -contains $currentversion
                        LoadTemplate = "Add-Type -AssemblyName `"Microsoft.SqlServer.Smo, Version=$($array[0]), Culture=neutral, PublicKeyToken=89845dcd8080cc91`""
                    }
                } else {
                    <# DO NOT use Write-Message as this is inside of a script block #>
                    Write-Verbose -Message "Passed version $VersionNumber, looking for that specific version"
                    if ($array[0].StartsWith("$VersionNumber.")) {
                        <# DO NOT use Write-Message as this is inside of a script block #>
                        Write-Verbose -Message "Found the Version $VersionNumber"
                        $currentversion = $array[0]
                        [PSCustomObject]@{
                            ComputerName = $env:COMPUTERNAME
                            Version      = $currentversion
                            Loaded       = $loadedversion -contains $currentversion
                            LoadTemplate = "Add-Type -AssemblyName `"Microsoft.SqlServer.Smo, Version=$($array[0]), Culture=neutral, PublicKeyToken=89845dcd8080cc91`""
                        }
                    }
                }
            }
        }
    }

    process {
        foreach ($computer in $ComputerName.ComputerName) {
            try {
                Write-Message -Level Verbose -Message "Executing scriptblock against $computer"
                Invoke-Command2 -ComputerName $computer -ScriptBlock $scriptblock -Credential $Credential -ArgumentList $VersionNumber -ErrorAction Stop
            } catch {
                Stop-Function -Continue -Message "Failure" -ErrorRecord $_ -Target $ComputerName
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaSqlManagementObject
    }
}
tools\dbatools\functions\Get-DbaMaxMemory.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaMaxMemory {
    <#
    .SYNOPSIS
        Gets the 'Max Server Memory' configuration setting and the memory of the server.  Works on SQL Server 2000-2014.

    .DESCRIPTION
        This command retrieves the SQL Server 'Max Server Memory' configuration setting as well as the total physical installed on the server.

        Results are turned in megabytes (MB).

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: MaxMemory, Memory
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaMaxMemory

    .EXAMPLE
        PS C:\> Get-DbaMaxMemory -SqlInstance sqlcluster, sqlserver2012

        Get memory settings for instances "sqlcluster" and "sqlserver2012". Returns results in megabytes (MB).

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sqlcluster | Get-DbaMaxMemory | Where-Object { $_.MaxValue -gt $_.Total }

        Find all servers in Server Central Management Server that have 'Max Server Memory' set to higher than the total memory of the server (think 2147483647)

    .EXAMPLE
        PS C:\> Find-DbaInstance -ComputerName localhost | Get-DbaMaxMemory | Format-Table -AutoSize

        Scans localhost for instances using the browser service, traverses all instances and displays memory settings in a formatted table.
       #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $totalMemory = $server.PhysicalMemory

            # Some servers under-report by 1.
            if (($totalMemory % 1024) -ne 0) {
                $totalMemory = $totalMemory + 1
            }

            [pscustomobject]@{
                ComputerName = $server.ComputerName
                InstanceName = $server.ServiceName
                SqlInstance  = $server.DomainInstanceName
                Total        = [int]$totalMemory
                MaxValue     = [int]$server.Configuration.MaxServerMemory.ConfigValue
                Server       = $server # This will allowing piping a non-connected object
            } | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, Total, MaxValue
        }
    }
}
tools\dbatools\functions\Get-DbaMemoryCondition.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaMemoryCondition {
    <#
    .SYNOPSIS
        Determine the memory conditions from SQL Server ring buffers.

    .DESCRIPTION
        The information from SQL Server ring buffers can be used to determine the memory conditions on the server when paging occurs.

        This command is based on a query provided by Microsoft support.
        Reference KB article: https://support.microsoft.com/en-us/help/918483/how-to-reduce-paging-of-buffer-pool-memory-in-the-64-bit-version-of-sq

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential).

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Memory
        Author: IJeb Reitsma
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaMemoryCondition

    .EXAMPLE
        PS C:\> Get-DbaMemoryCondition -SqlInstance sqlserver2014a

        Returns the memory conditions for the selected instance

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sqlserver2014a -Group GroupName | Get-DbaMemoryCondition | Out-GridView

        Returns the memory conditions for a group of servers from SQL Server Central Management Server (CMS). Send output to GridView.
       #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )

    begin {
        $sql = "SELECT CONVERT (varchar(30), GETDATE(), 121) as Runtime,
    DATEADD (ms, -1 * (sys.ms_ticks - a.[RecordTime]), GETDATE()) AS NotificationTime,
    [NotificationType],
    [MemoryUtilizationPercent],
    [TotalPhysicalMemoryKB],
    [AvailablePhysicalMemoryKB],
    [TotalPageFileKB],
    [AvailablePageFileKB],
    [TotalVirtualAddressSpaceKB],
    [AvailableVirtualAddressSpaceKB],
    [NodeId],
    [SQLReservedMemoryKB],
    [SQLCommittedMemoryKB],
    [RecordId],
    [Type],
    [Indicators],
    [RecordTime],
    sys.ms_ticks AS [CurrentTime]
    FROM
    (SELECT x.value('(//Record/ResourceMonitor/Notification)[1]', 'varchar(30)') AS [NotificationType],
    x.value('(//Record/MemoryRecord/MemoryUtilization)[1]', 'bigint') AS [MemoryUtilizationPercent],
    x.value('(//Record/MemoryRecord/TotalPhysicalMemory)[1]', 'bigint') AS [TotalPhysicalMemoryKB],
    x.value('(//Record/MemoryRecord/AvailablePhysicalMemory)[1]', 'bigint') AS [AvailablePhysicalMemoryKB],
    x.value('(//Record/MemoryRecord/TotalPageFile)[1]', 'bigint') AS [TotalPageFileKB],
    x.value('(//Record/MemoryRecord/AvailablePageFile)[1]', 'bigint') AS [AvailablePageFileKB],
    x.value('(//Record/MemoryRecord/TotalVirtualAddressSpace)[1]', 'bigint') AS [TotalVirtualAddressSpaceKB],
    x.value('(//Record/MemoryRecord/AvailableVirtualAddressSpace)[1]', 'bigint') AS [AvailableVirtualAddressSpaceKB],
    x.value('(//Record/MemoryNode/@id)[1]', 'bigint') AS [NodeId],
    x.value('(//Record/MemoryNode/ReservedMemory)[1]', 'bigint') AS [SQLReservedMemoryKB],
    x.value('(//Record/MemoryNode/CommittedMemory)[1]', 'bigint') AS [SQLCommittedMemoryKB],
    x.value('(//Record/@id)[1]', 'bigint') AS [RecordId],
    x.value('(//Record/@type)[1]', 'varchar(30)') AS [Type],
    x.value('(//Record/ResourceMonitor/Indicators)[1]', 'bigint') AS [Indicators],
    x.value('(//Record/@time)[1]', 'bigint') AS [RecordTime]
    FROM (SELECT CAST (record as xml) FROM sys.dm_os_ring_buffers
    WHERE ring_buffer_type = 'RING_BUFFER_RESOURCE_MONITOR') AS R(x)) a
CROSS JOIN sys.dm_os_sys_info sys
ORDER BY a.[RecordTime] ASC"
    }
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            try {
                $results = $server.Query($sql)
            } catch {
                Stop-Function -Message "Issue collecting data" -Target $instance -ErrorRecord $_
            }
            foreach ($row in $results) {
                [PSCustomObject]@{
                    ComputerName                 = $server.ComputerName
                    InstanceName                 = $server.ServiceName
                    SqlInstance                  = $server.DomainInstanceName
                    Runtime                      = $row.runtime
                    NotificationTime             = $row.NotificationTime
                    NotificationType             = $row.NotificationType
                    MemoryUtilizationPercent     = $row.MemoryUtilizationPercent
                    TotalPhysicalMemory          = [dbasize]$row.TotalPhysicalMemoryKB * 1024
                    AvailablePhysicalMemory      = [dbasize]$row.AvailablePhysicalMemoryKB * 1024
                    TotalPageFile                = [dbasize]$row.TotalPageFileKB * 1024
                    AvailablePageFile            = [dbasize]$row.AvailablePageFileKB * 1024
                    TotalVirtualAddressSpace     = [dbasize]$row.TotalVirtualAddressSpaceKB * 1024
                    AvailableVirtualAddressSpace = [dbasize]$row.AvailableVirtualAddressSpaceKB * 1024
                    NodeId                       = $row.NodeId
                    SQLReservedMemory            = [dbasize]$row.SQLReservedMemoryKB * 1024
                    SQLCommittedMemory           = [dbasize]$row.SQLCommittedMemoryKB * 1024
                    RecordId                     = $row.RecordId
                    Type                         = $row.Type
                    Indicators                   = $row.Indicators
                    RecordTime                   = $row.RecordTime
                    CurrentTime                  = $row.CurrentTime
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaMemoryUsage.ps1
#ValidationTags#Messaging,CodeStyle#
function Get-DbaMemoryUsage {
    <#
    .SYNOPSIS
        Get amount of memory in use by *all* SQL Server components and instances

    .DESCRIPTION
        Retrieves the amount of memory per performance counter. Default output includes columns Server, counter instance, counter, number of pages, memory in KB, memory in MB
        SSAS and SSIS are included.

        SSRS does not have memory counters, only memory shrinks and memory pressure state.

        This function requires local admin role on the targeted computers.

    .PARAMETER ComputerName
        The Windows Server that you are connecting to. Note that this will return all instances, but Out-GridView makes it easy to filter to specific instances.

    .PARAMETER Credential
        Credential object used to connect to the SQL Server as a different user

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Memory
        Author: Klaas Vandenberghe (@PowerDBAKlaas)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        SSIS Counters: https://msdn.microsoft.com/en-us/library/ms137622.aspx

    .LINK
        https://dbatools.io/Get-DbaMemoryUsage

    .EXAMPLE
        PS C:\> Get-DbaMemoryUsage -ComputerName sql2017

        Returns a custom object displaying Server, counter instance, counter, number of pages, memory

    .EXAMPLE
        PS C:\> Get-DbaMemoryUsage -ComputerName sql2017\sqlexpress -SqlCredential sqladmin | Where-Object { $_.Memory.Megabyte -gt 100 }

        Logs into the sql2017\sqlexpress as sqladmin using SQL Authentication then returns results only where memory exceeds 100 MB

    .EXAMPLE
        PS C:\> $servers | Get-DbaMemoryUsage | Out-Gridview

       Gets results from an array of $servers then diplays them in a gridview.
    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [Alias("Host", "cn", "Server")]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [switch]$EnableException
    )

    begin {
        if ($Simple) {
            $Memcounters = '(Total Server Memory |Target Server Memory |Connection Memory |Lock Memory |SQL Cache Memory |Optimizer Memory |Granted Workspace Memory |Cursor memory usage|Maximum Workspace)'
            $Plancounters = 'total\)\\cache pages'
            $BufManpagecounters = 'Total pages'
            $SSAScounters = '(\\memory usage)'
            $SSIScounters = '(memory)'
        } else {
            $Memcounters = '(Total Server Memory |Target Server Memory |Connection Memory |Lock Memory |SQL Cache Memory |Optimizer Memory |Granted Workspace Memory |Cursor memory usage|Maximum Workspace)'
            $Plancounters = '(cache pages|procedure plan|ad hoc sql plan|prepared SQL Plan)'
            $BufManpagecounters = '(Free pages|Reserved pages|Stolen pages|Total pages|Database pages|target pages|extension .* pages)'
            $SSAScounters = '(\\memory )'
            $SSIScounters = '(memory)'
        }

        $scriptblock = {
            param ($Memcounters,
                $Plancounters,
                $BufManpagecounters,
                $SSAScounters,
                $SSIScounters)
            <# DO NOT use Write-Message as this is inside of a script block #>
            Write-Verbose -Message "Searching for Memory Manager Counters on $Computer"
            try {
                $availablecounters = (Get-Counter -ListSet '*sql*:Memory Manager*' -ErrorAction SilentlyContinue).paths
                (Get-Counter -Counter $availablecounters -ErrorAction SilentlyContinue).countersamples |
                    Where-Object { $_.Path -match $Memcounters } |
                    ForEach-Object {
                    $instance = (($_.Path.split("\")[-2]).replace("mssql`$", "")).split(':')[0]
                    if ($instance -eq 'sqlserver') { $instance = 'mssqlserver' }
                    [PSCustomObject]@{
                        ComputerName    = $env:computername
                        SqlInstance     = $instance
                        CounterInstance = (($_.Path.split("\")[-2]).replace("mssql`$", "")).split(':')[1]
                        Counter         = $_.Path.split("\")[-1]
                        Pages           = $null
                        Memory          = $_.cookedvalue / 1024
                    }
                }
            } catch {
                <# DO NOT use Write-Message as this is inside of a script block #>
                Write-Verbose -Message "No Memory Manager Counters on $Computer"
            }
            <# DO NOT use Write-Message as this is inside of a script block #>
            Write-Verbose -Message "Searching for Plan Cache Counters on $Computer"
            try {
                $availablecounters = (Get-Counter -ListSet '*sql*:Plan Cache*' -ErrorAction SilentlyContinue).paths
                (Get-Counter -Counter $availablecounters -ErrorAction SilentlyContinue).countersamples |
                    Where-Object { $_.Path -match $Plancounters } |
                    ForEach-Object {
                    $instance = (($_.Path.split("\")[-2]).replace("mssql`$", "")).split(':')[0]
                    if ($instance -eq 'sqlserver') { $instance = 'mssqlserver' }
                    [PSCustomObject]@{
                        ComputerName    = $env:computername
                        SqlInstance     = $instance
                        CounterInstance = (($_.Path.split("\")[-2]).replace("mssql`$", "")).split(':')[1]
                        Counter         = $_.Path.split("\")[-1]
                        Pages           = $_.cookedvalue
                        Memory          = $_.cookedvalue * 8192 / 1048576
                    }
                }
            } catch {
                <# DO NOT use Write-Message as this is inside of a script block #>
                Write-Verbose -Message "No Plan Cache Counters on $Computer"
            }
            <# DO NOT use Write-Message as this is inside of a script block #>
            Write-Verbose -Message "Searching for Buffer Manager Counters on $Computer"
            try {
                $availablecounters = (Get-Counter -ListSet "*Buffer Manager*" -ErrorAction SilentlyContinue).paths
                (Get-Counter -Counter $availablecounters -ErrorAction SilentlyContinue).countersamples |
                    Where-Object { $_.Path -match $BufManpagecounters } |
                    ForEach-Object {
                    $instance = (($_.Path.split("\")[-2]).replace("mssql`$", "")).split(':')[0]
                    if ($instance -eq 'sqlserver') { $instance = 'mssqlserver' }
                    [PSCustomObject]@{
                        ComputerName    = $env:computername
                        SqlInstance     = $instance
                        CounterInstance = (($_.Path.split("\")[-2]).replace("mssql`$", "")).split(':')[1]
                        Counter         = $_.Path.split("\")[-1]
                        Pages           = $_.cookedvalue
                        Memory          = $_.cookedvalue * 8192 / 1048576.0
                    }
                }
            } catch {
                <# DO NOT use Write-Message as this is inside of a script block #>
                Write-Verbose -Message "No Buffer Manager Counters on $Computer"
            }
            <# DO NOT use Write-Message as this is inside of a script block #>
            Write-Verbose -Message "Searching for SSAS Counters on $Computer"
            try {
                $availablecounters = (Get-Counter -ListSet "MSAS*:Memory" -ErrorAction SilentlyContinue).paths
                (Get-Counter -Counter $availablecounters -ErrorAction SilentlyContinue).countersamples |
                    Where-Object { $_.Path -match $SSAScounters } |
                    ForEach-Object {
                    $instance = (($_.Path.split("\")[-2]).replace("mssql`$", "")).split(':')[0]
                    if ($instance -eq 'sqlserver') { $instance = 'mssqlserver' }
                    [PSCustomObject]@{
                        ComputerName    = $env:COMPUTERNAME
                        SqlInstance     = $instance
                        CounterInstance = (($_.Path.split("\")[-2]).replace("mssql`$", "")).split(':')[1]
                        Counter         = $_.Path.split("\")[-1]
                        Pages           = $null
                        Memory          = $_.cookedvalue / 1024
                    }
                }
            } catch {
                <# DO NOT use Write-Message as this is inside of a script block #>
                Write-Verbose -Message "No SSAS Counters on $Computer"
            }
            <# DO NOT use Write-Message as this is inside of a script block #>
            Write-Verbose -Message "Searching for SSIS Counters on $Computer"
            try {
                $availablecounters = (Get-Counter -ListSet "*SSIS*" -ErrorAction SilentlyContinue).paths
                (Get-Counter -Counter $availablecounters -ErrorAction SilentlyContinue).countersamples |
                    Where-Object { $_.Path -match $SSIScounters } |
                    ForEach-Object {
                    $instance = (($_.Path.split("\")[-2]).replace("mssql`$", "")).split(':')[0]
                    if ($instance -eq 'sqlserver') { $instance = 'mssqlserver' }
                    [PSCustomObject]@{
                        ComputerName    = $env:computername
                        SqlInstance     = $instance
                        CounterInstance = (($_.Path.split("\")[-2]).replace("mssql`$", "")).split(':')[1]
                        Counter         = $_.Path.split("\")[-1]
                        Pages           = $null
                        Memory          = $_.cookedvalue / 1024 / 1024
                    }
                }
            } catch {
                <# DO NOT use Write-Message as this is inside of a script block #>
                Write-Verbose -Message "No SSIS Counters on $Computer"
            }
        }
    }

    process {
        foreach ($Computer in $ComputerName.ComputerName) {
            $reply = Resolve-DbaNetworkName -ComputerName $computer -Credential $Credential -ErrorAction SilentlyContinue
            if ($reply.FullComputerName) {
                $Computer = $reply.FullComputerName
                try {
                    foreach ($result in (Invoke-Command2 -ComputerName $Computer -Credential $Credential -ScriptBlock $scriptblock -argumentlist $Memcounters, $Plancounters, $BufManpagecounters, $SSAScounters, $SSIScounters)) {
                        [PSCustomObject]@{
                            ComputerName    = $result.ComputerName
                            SqlInstance     = $result.SqlInstance
                            CounterInstance = $result.CounterInstance
                            Counter         = $result.Counter
                            Pages           = $result.Pages
                            Memory          = [dbasize]($result.Memory * 1024 * 1024)
                        }
                    }
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target $computer -Continue
                }
            } else {
                Write-Message -Level Warning -Message "Can't resolve $Computer."
                Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaModule.ps1
function Get-DbaModule {
    <#
    .SYNOPSIS
        Displays all objects in sys.sys_modules after specified modification date.  Works on SQL Server 2008 and above.

    .DESCRIPTION
        Quickly find modules (Stored Procs, Functions, Views, Constraints, Rules, Triggers, etc) that have been modified in a database, or across all databases.
        Results will exclude the module definition, but can be queried explicitly.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude.

    .PARAMETER ModifiedSince
        DateTime value to use as minimum modified date of module.

    .PARAMETER Type
        Limit by specific type of module. Valid choices include: View, TableValuedFunction, DefaultConstraint, StoredProcedure, Rule, InlineTableValuedFunction, Trigger, ScalarFunction

    .PARAMETER ExcludeSystemDatabases
        Allows you to suppress output on system databases

    .PARAMETER ExcludeSystemObjects
        Allows you to suppress output on system objects

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: StoredProcedure, Trigger
        Author: Brandon Abshire, netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaModule

    .EXAMPLE
        PS C:\> Get-DbaModule -SqlInstance sql2008, sqlserver2012

        Return all modules for servers sql2008 and sqlserver2012 sorted by Database, Modify_Date ASC.

    .EXAMPLE
        PS C:\> Get-DbaModule -SqlInstance sql2008, sqlserver2012 | Select *

        Shows hidden definition column (informative wall of text).

    .EXAMPLE
        PS C:\> Get-DbaModule -SqlInstance sql2008 -Database TestDB -ModifiedSince "2017-01-01 10:00:00"

        Return all modules on server sql2008 for only the TestDB database with a modified date after 1 January 2017 10:00:00 AM.

    .EXAMPLE
        PS C:\> Get-DbaModule -SqlInstance sql2008 -Type View, Trigger, ScalarFunction

        Return all modules on server sql2008 for all databases that are triggers, views or scalar functions.

    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [datetime]$ModifiedSince = "1900-01-01",
        [ValidateSet("View", "TableValuedFunction", "DefaultConstraint", "StoredProcedure", "Rule", "InlineTableValuedFunction", "Trigger", "ScalarFunction")]
        [string[]]$Type,
        [switch]$ExcludeSystemDatabases,
        [switch]$ExcludeSystemObjects,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {

        $types = @()

        foreach ($t in $type) {
            if ($t -eq "View") { $types += "VIEW" }
            if ($t -eq "TableValuedFunction") { $types += "SQL_TABLE_VALUED_FUNCTION" }
            if ($t -eq "DefaultConstraint") { $types += "DEFAULT_CONSTRAINT" }
            if ($t -eq "StoredProcedure") { $types += "SQL_STORED_PROCEDURE" }
            if ($t -eq "Rule") { $types += "RULE" }
            if ($t -eq "InlineTableValuedFunction") { $types += "SQL_INLINE_TABLE_VALUED_FUNCTION" }
            if ($t -eq "Trigger") { $types += "SQL_TRIGGER" }
            if ($t -eq "ScalarFunction") { $types += "SQL_SCALAR_FUNCTION" }
        }


        $sql = "SELECT  DB_NAME() AS DatabaseName,
        so.name AS ModuleName,
        so.object_id ,
        SCHEMA_NAME(so.schema_id) AS SchemaName ,
        so.parent_object_id ,
        so.type ,
        so.type_desc ,
        so.create_date ,
        so.modify_date ,
        so.is_ms_shipped ,
        sm.definition,
         OBJECTPROPERTY(so.object_id, 'ExecIsStartUp') as startup
        FROM sys.sql_modules sm
        LEFT JOIN sys.objects so ON sm.object_id = so.object_id
        WHERE so.modify_date >= '$($ModifiedSince)'"
        if ($ExcludeSystemObjects) {
            $sql += "`n AND so.is_ms_shipped = 0"
        }
        if ($Type) {
            $sqltypes = $types -join "','"
            $sql += " AND type_desc in ('$sqltypes')"
        }
        $sql += "`n ORDER BY so.modify_date"
    }

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $databases = Get-DbaDatabase -SqlInstance $server

            if ($Database) {
                $databases = $databases | Where-Object Name -In $Database
            }
            if ($ExcludeDatabase) {
                $databases = $databases | Where-Object Name -NotIn $ExcludeDatabase
            }


            foreach ($db in $databases) {

                Write-Message -Level Verbose -Message "Processing $db on $instance"

                if ($db.IsAccessible -eq $false) {
                    Stop-Function -Message "The database $db is not accessible. Skipping database." -Target $db -Continue
                }

                foreach ($row in $server.Query($sql, $db.name)) {
                    [PSCustomObject]@{
                        ComputerName  = $server.ComputerName
                        InstanceName  = $server.ServiceName
                        SqlInstance   = $server.DomainInstanceName
                        Database      = $row.DatabaseName
                        Name          = $row.ModuleName
                        ObjectID      = $row.object_id
                        SchemaName    = $row.SchemaName
                        Type          = $row.type_desc
                        CreateDate    = $row.create_date
                        ModifyDate    = $row.modify_date
                        IsMsShipped   = $row.is_ms_shipped
                        ExecIsStartUp = $row.startup
                        Definition    = $row.definition
                    } | Select-DefaultView -ExcludeProperty Definition
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaSqlModule
    }
}
tools\dbatools\functions\Get-DbaMsdtc.ps1
#ValidationTags#Messaging#
function Get-DbaMsdtc {
    <#
    .SYNOPSIS
        Displays information about the Distributed Transaction Coordinator (MSDTC) on a server

    .DESCRIPTION
        Returns a custom object with Computer name, state of the MSDTC Service, security settings of MSDTC and CID's

        Requires: Windows administrator access on Servers

    .PARAMETER ComputerName
        The target computer.

    .NOTES
        Tags: Msdtc, dtc
        Author: Klaas Vandenberghe (@powerdbaklaas)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaMsdtc

    .EXAMPLE
        PS C:\> Get-DbaMsdtc -ComputerName srv0042

        Get DTC status for the server srv0042

    .EXAMPLE
        PS C:\> $Computers = (Get-Content D:\configfiles\SQL\MySQLInstances.txt | % {$_.split('\')[0]})
        PS C:\> $Computers | Get-DbaMsdtc

        Get DTC status for all the computers in a .txt file

    .EXAMPLE
        PS C:\> Get-DbaMsdtc -Computername $Computers | where { $_.dtcservicestate -ne 'running' }

        Get DTC status for all the computers where the MSDTC Service is not running

    .EXAMPLE
        PS C:\> Get-DbaMsdtc -ComputerName srv0042 | Out-Gridview

        Get DTC status for the computer srv0042 and show in a grid view

    #>
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [Alias('cn', 'host', 'Server')]
        [string[]]$ComputerName = $env:COMPUTERNAME
    )

    begin {
        $ComputerName = $ComputerName | ForEach-Object {$_.split("\")[0]} | Select-Object -Unique
        $query = "Select * FROM Win32_Service WHERE Name = 'MSDTC'"
        $dtcSecurity = {
            Get-ItemProperty -Path HKLM:\Software\Microsoft\MSDTC\Security |
                Select-Object PSPath, PSComputerName, AccountName, networkDTCAccess,
            networkDTCAccessAdmin, networkDTCAccessClients, networkDTCAccessInbound,
            networkDTCAccessOutBound, networkDTCAccessTip, networkDTCAccessTransactions, XATransactions
        }
        $dtcCids = {
            New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT | Out-Null
            Get-ItemProperty -Path HKCR:\CID\*\Description |
                Select-Object @{ l = 'Data'; e = { $_.'(default)' } }, @{ l = 'CID'; e = { $_.PSParentPath.split('\')[-1] } }
            Remove-PSDrive -Name HKCR | Out-Null
        }
    }
    process {
        foreach ($computer in $ComputerName) {
            $reg = $cids = $null
            $cidHash = @{}
            if ( Test-PSRemoting -ComputerName $computer ) {
                $dtcservice = $null
                Write-Message -Level Verbose -Message "Getting DTC on $computer via WSMan"
                $dtcservice = Get-Ciminstance -ComputerName $computer -Query $query
                if ( $null -eq $dtcservice ) {
                    Write-Message -Level Warning -Message "Can't connect to CIM on $computer via WSMan"
                }

                Write-Message -Level Verbose -Message "Getting MSDTC Security Registry Values on $computer"
                $reg = Invoke-Command -ComputerName $computer -ScriptBlock $dtcSecurity
                if ( $null -eq $reg ) {
                    Write-Message -Level Warning -Message "Can't connect to MSDTC Security registry on $computer"
                }
                Write-Message -Level Verbose -Message "Getting MSDTC CID Registry Values on $computer"
                $cids = Invoke-Command -ComputerName $computer -ScriptBlock $dtcCids
                if ( $null -ne $cids ) {
                    foreach ($key in $cids) {
                        $cidHash.Add($key.Data, $key.CID)
                    }
                } else {
                    Write-Message -Level Warning -Message "Can't connect to MSDTC CID registry on $computer"
                }
            } else {
                Write-Message -Level Verbose -Message "PSRemoting is not enabled on $computer"
                try {
                    Write-Message -Level Verbose -Message "Failed To get DTC via WinRM. Getting DTC on $computer via DCom"
                    $SessionParams = @{ }
                    $SessionParams.ComputerName = $Computer
                    $SessionParams.SessionOption = (New-CimSessionOption -Protocol Dcom)
                    $Session = New-CimSession @SessionParams
                    $dtcservice = Get-Ciminstance -CimSession $Session -Query $query
                } catch {
                    Stop-Function -Message "Can't connect to CIM on $computer via DCom" -Target $computer -ErrorRecord $_ -Continue
                }
            }
            if ( $dtcservice ) {
                [PSCustomObject]@{
                    ComputerName                 = $dtcservice.PSComputerName
                    DTCServiceName               = $dtcservice.DisplayName
                    DTCServiceState              = $dtcservice.State
                    DTCServiceStatus             = $dtcservice.Status
                    DTCServiceStartMode          = $dtcservice.StartMode
                    DTCServiceAccount            = $dtcservice.StartName
                    DTCCID_MSDTC                 = $cidHash['MSDTC']
                    DTCCID_MSDTCUIS              = $cidHash['MSDTCUIS']
                    DTCCID_MSDTCTIPGW            = $cidHash['MSDTCTIPGW']
                    DTCCID_MSDTCXATM             = $cidHash['MSDTCXATM']
                    networkDTCAccess             = $reg.networkDTCAccess
                    networkDTCAccessAdmin        = $reg.networkDTCAccessAdmin
                    networkDTCAccessClients      = $reg.networkDTCAccessClients
                    networkDTCAccessInbound      = $reg.networkDTCAccessInbound
                    networkDTCAccessOutBound     = $reg.networkDTCAccessOutBound
                    networkDTCAccessTip          = $reg.networkDTCAccessTip
                    networkDTCAccessTransactions = $reg.networkDTCAccessTransactions
                    XATransactions               = $reg.XATransactions
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaNetworkActivity.ps1
function Get-DbaNetworkActivity {
    <#
    .SYNOPSIS
        Gets the Current traffic on every Network Interface on a computer.

    .DESCRIPTION
        Gets the Current traffic on every Network Interface on a computer.
        See https://msdn.microsoft.com/en-us/library/aa394293(v=vs.85).aspx

        Requires Local Admin rights on destination computer(s).

    .PARAMETER ComputerName
        The target SQL Server instance or instances.

    .PARAMETER Credential
        Credential object used to connect to the computer as a different user.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Network
        Author: Klaas Vandenberghe (@PowerDBAKlaas)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaNetworkActivity

    .EXAMPLE
        PS C:\> Get-DbaNetworkActivity -ComputerName sqlserver2014a

        Gets the Current traffic on every Network Interface on computer sqlserver2014a.

    .EXAMPLE
        PS C:\> 'sql1','sql2','sql3' | Get-DbaNetworkActivity

        Gets the Current traffic on every Network Interface on computers sql1, sql2 and sql3.

    .EXAMPLE
        PS C:\> Get-DbaNetworkActivity -ComputerName sql1,sql2 | Out-Gridview

        Gets the Current traffic on every Network Interface on computers sql1 and sql2, and shows them in a grid view.

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [Alias("cn", "host", "Server")]
        [string[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential] $Credential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $ComputerName = $ComputerName | ForEach-Object {$_.split("\")[0]} | Select-Object -Unique
        $sessionoption = New-CimSessionOption -Protocol DCom
    }
    process {
        foreach ($computer in $ComputerName) {
            $Server = Resolve-DbaNetworkName -ComputerName $Computer -Credential $credential
            if ( $Server.FullComputerName ) {
                $Computer = $server.FullComputerName
                Write-Message -Level Verbose -Message "Creating CIMSession on $computer over WSMan"
                $CIMsession = New-CimSession -ComputerName $Computer -ErrorAction SilentlyContinue -Credential $Credential
                if ( -not $CIMSession ) {
                    Write-Message -Level Verbose -Message "Creating CIMSession on $computer over WSMan failed. Creating CIMSession on $computer over DCom"
                    $CIMsession = New-CimSession -ComputerName $Computer -SessionOption $sessionoption -ErrorAction SilentlyContinue -Credential $Credential
                }
                if ( $CIMSession ) {
                    Write-Message -Level Verbose -Message "Getting properties for Network Interfaces on $computer"
                    $NICs = Get-CimInstance -CimSession $CIMSession -ClassName Win32_PerfFormattedData_Tcpip_NetworkInterface
                    $NICs | Add-Member -Force -MemberType ScriptProperty -Name ComputerName -Value { $computer }
                    $NICs | Add-Member -Force -MemberType ScriptProperty -Name Bandwith -Value { switch ( $this.CurrentBandWidth ) { 10000000000 { '10Gb' } 1000000000 { '1Gb' } 100000000 { '100Mb' } 10000000 { '10Mb' } 1000000 { '1Mb' } 100000 { '100Kb' } default { 'Low' } } }
                    foreach ( $NIC in $NICs ) { Select-DefaultView -InputObject $NIC -Property 'ComputerName', 'Name as NIC', 'BytesReceivedPersec', 'BytesSentPersec', 'BytesTotalPersec', 'Bandwidth'}
                } #if CIMSession
                else {
                    Write-Message -Level Warning -Message "Can't create CIMSession on $computer"
                }
            } #if computername
            else {
                Write-Message -Level Warning -Message "can't connect to $computer"
            }
        } #foreach computer
    } #PROCESS
} #function
tools\dbatools\functions\Get-DbaNetworkCertificate.ps1
function Get-DbaNetworkCertificate {
    <#
    .SYNOPSIS
        Simplifies finding computer certificates that are candidates for using with SQL Server's network encryption

    .DESCRIPTION
        Gets computer certificates on localhost that are candidates for using with SQL Server's network encryption

    .PARAMETER ComputerName
       The target SQL Server instance or instances. Defaults to localhost. If target is a cluster, you must specify the distinct nodes.

    .PARAMETER Credential
        Allows you to login to $ComputerName using alternative credentials.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Certificate
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaNetworkCertificate

        Gets computer certificates on localhost that are candidates for using with SQL Server's network encryption

    .EXAMPLE
        PS C:\> Get-DbaNetworkCertificate -ComputerName sql2016

        Gets computer certificates on sql2016 that are being used for SQL Server network encryption

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlInstance")]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [switch]$EnableException
    )
    
    process {
        # Registry access
        
        
        foreach ($computer in $computername) {

            try {
                $sqlwmis = Invoke-ManagedComputerCommand -ComputerName $computer.ComputerName -ScriptBlock { $wmi.Services } -Credential $Credential -ErrorAction Stop | Where-Object DisplayName -match "SQL Server \("
            } catch {
                Stop-Function -Message $_ -Target $sqlwmi -Continue
            }

            foreach ($sqlwmi in $sqlwmis) {

                $regroot = ($sqlwmi.AdvancedProperties | Where-Object Name -eq REGROOT).Value
                $vsname = ($sqlwmi.AdvancedProperties | Where-Object Name -eq VSNAME).Value
                $instancename = $sqlwmi.DisplayName.Replace('SQL Server (', '').Replace(')', '') # Don't clown, I don't know regex :(
                $serviceaccount = $sqlwmi.ServiceAccount

                if ([System.String]::IsNullOrEmpty($regroot)) {
                    $regroot = $sqlwmi.AdvancedProperties | Where-Object { $_ -match 'REGROOT' }
                    $vsname = $sqlwmi.AdvancedProperties | Where-Object { $_ -match 'VSNAME' }

                    if (![System.String]::IsNullOrEmpty($regroot)) {
                        $regroot = ($regroot -Split 'Value\=')[1]
                        $vsname = ($vsname -Split 'Value\=')[1]
                    } else {
                        Write-Message -Level Warning -Message "Can't find instance $vsname on $env:COMPUTERNAME"
                        return
                    }
                }

                if ([System.String]::IsNullOrEmpty($vsname)) { $vsname = $computer }

                Write-Message -Level Verbose -Message "Regroot: $regroot"
                Write-Message -Level Verbose -Message "ServiceAcct: $serviceaccount"
                Write-Message -Level Verbose -Message "InstanceName: $instancename"
                Write-Message -Level Verbose -Message "VSNAME: $vsname"

                $scriptblock = {
                    $regroot = $args[0]
                    $serviceaccount = $args[1]
                    $instancename = $args[2]
                    $vsname = $args[3]

                    $regpath = "Registry::HKEY_LOCAL_MACHINE\$regroot\MSSQLServer\SuperSocketNetLib"

                    $thumbprint = (Get-ItemProperty -Path $regpath -Name Certificate -ErrorAction SilentlyContinue).Certificate

                    try {
                        $cert = Get-ChildItem Cert:\LocalMachine -Recurse -ErrorAction Stop | Where-Object Thumbprint -eq $Thumbprint
                    } catch {
                        # Don't care - sometimes there's errors that are thrown for apparent good reason
                        # here to avoid an empty catch
                        $null = 1
                    }

                    if (!$cert) { continue }

                    [pscustomobject]@{
                        ComputerName   = $env:COMPUTERNAME
                        InstanceName   = $instancename
                        SqlInstance    = $vsname
                        ServiceAccount = $serviceaccount
                        FriendlyName   = $cert.FriendlyName
                        DnsNameList    = $cert.DnsNameList
                        Thumbprint     = $cert.Thumbprint
                        Generated      = $cert.NotBefore
                        Expires        = $cert.NotAfter
                        IssuedTo       = $cert.Subject
                        IssuedBy       = $cert.Issuer
                        Certificate    = $cert
                    }
                }

                try {
                    Invoke-Command2 -ComputerName $computer.ComputerName -Credential $Credential -ArgumentList $regroot, $serviceaccount, $instancename, $vsname -ScriptBlock $scriptblock -ErrorAction Stop |
                        Select-DefaultView -ExcludeProperty Certificate
                } catch {
                    Stop-Function -Message $_ -ErrorRecord $_ -Target $ComputerName -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaOpenTransaction.ps1
function Get-DbaOpenTransaction {
    <#
    .SYNOPSIS
        Displays all open transactions.

    .DESCRIPTION
        This command is based on open transaction script published by Paul Randal.
        Reference: https://www.sqlskills.com/blogs/paul/script-open-transactions-with-text-and-plans/

    .PARAMETER SqlInstance
        The SQL Server instance

    .PARAMETER SqlCredential
        Connect using alternative credentials

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database, Process, Session, ActivityMonitor
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaOpenTransaction

    .EXAMPLE
        PS C:\> Get-DbaOpenTransaction -SqlInstance sqlserver2014a

        Returns open transactions for sqlserver2014a

    .EXAMPLE
        PS C:\> Get-DbaOpenTransaction -SqlInstance sqlserver2014a -SqlCredential sqladmin

        Logs into sqlserver2014a using the login "sqladmin"

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )

    begin {
        $sql = "
            SELECT  SERVERPROPERTY('MachineName') AS ComputerName,
            ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
            SERVERPROPERTY('ServerName') AS SqlInstance,
            [s_tst].[session_id] as Spid,
            [s_es].[login_name] as Login,
            DB_NAME (s_tdt.database_id) AS [Database],
            [s_tdt].[database_transaction_begin_time] AS [BeginTime],
            [s_tdt].[database_transaction_log_bytes_used] AS [LogBytesUsed],
            [s_tdt].[database_transaction_log_bytes_reserved] AS [LogBytesReserved],
            [s_est].text AS [LastQuery],
            [s_eqp].[query_plan] AS [LastPlan]
            FROM
                sys.dm_tran_database_transactions [s_tdt]
            JOIN
                sys.dm_tran_session_transactions [s_tst]
            ON
                [s_tst].[transaction_id] = [s_tdt].[transaction_id]
            JOIN
                sys.[dm_exec_sessions] [s_es]
            ON
                [s_es].[session_id] = [s_tst].[session_id]
            JOIN
                sys.dm_exec_connections [s_ec]
            ON
                [s_ec].[session_id] = [s_tst].[session_id]
            LEFT OUTER JOIN
                sys.dm_exec_requests [s_er]
            ON
                [s_er].[session_id] = [s_tst].[session_id]
            CROSS APPLY
                sys.dm_exec_sql_text ([s_ec].[most_recent_sql_handle]) AS [s_est]
            OUTER APPLY
                sys.dm_exec_query_plan ([s_er].[plan_handle]) AS [s_eqp]
            ORDER BY
                [BeginTime] ASC"
    }
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $server.Query($sql)
        }
    }
}
tools\dbatools\functions\Get-DbaOperatingSystem.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaOperatingSystem {
    <#
    .SYNOPSIS
        Gets operating system information from the server.

    .DESCRIPTION
        Gets operating system information from the server and returns as an object.

    .PARAMETER ComputerName
        Target computer(s). If no computer name is specified, the local computer is targeted

    .PARAMETER Credential
        Alternate credential object to use for accessing the target computer(s).

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ServerInfo, OperatingSystem
        Author: Shawn Melton (@wsmelton), https://wsmelton.github.io

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaOperatingSystem

    .EXAMPLE
        PS C:\> Get-DbaOperatingSystem

        Returns information about the local computer's operating system

    .EXAMPLE
        PS C:\> Get-DbaOperatingSystem -ComputerName sql2016

        Returns information about the sql2016's operating system

    .EXAMPLE
        PS C:\> $wincred = Get-Credential ad\sqladmin
        PS C:\> 'sql2016', 'sql2017' | Get-DbaOperatingSystem -Credential $wincred

        Returns information about the sql2016 and sql2017 operating systems using alternative Windows credentials

    .EXAMPLE
        PS C:\> Get-Content .\servers.txt | Get-DbaOperatingSystem

        Returns information about all the servers operating system that are stored in the file. Every line in the file can only contain one hostname for a server.
    #>
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [Alias("cn", "host", "Server")]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($computer in $ComputerName) {
            Write-Message -Level Verbose -Message "Connecting to $computer"

            $server = Resolve-DbaNetworkName -ComputerName $computer.ComputerName -Credential $Credential

            $computerResolved = $server.FullComputerName
            Write-Message -Level Verbose -Message "Resolved $computerResolved"

            if (!$computerResolved) {
                Write-Message -Level Warning -Message "Unable to resolve hostname of $computer. Skipping."
                continue
            }

            try {
                $TestWS = Test-WSMan -ComputerName $computerResolved -ErrorAction SilentlyContinue
            } catch {
                Write-Message -Level Warning -Message "Remoting not availablle on $computer. Skipping checks"
                $TestWS = $null
            }

            $splatDbaCmObject = @{
                ComputerName    = $computerResolved
                EnableException = $true
            }
            if (Test-Bound "Credential") {
                $splatDbaCmObject["Credential"] = $Credential
            }
            if ($TestWS) {
                try {
                    $psVersion = Invoke-Command2 -ComputerName $computerResolved -Credential $Credential -ScriptBlock { $PSVersionTable.PSVersion }
                    $PowerShellVersion = "$($psVersion.Major).$($psVersion.Minor)"
                } catch {
                    Write-Message -Level Warning -Message "PowerShell Version information not available on $computer."
                    $PowerShellVersion = 'Unavailable'
                }
            } else {
                $PowerShellVersion = 'Unknown'
            }

            try {
                $os = Get-DbaCmObject @splatDbaCmObject -ClassName Win32_OperatingSystem
            } catch {
                Stop-Function -Message "Failure collecting OS information on $computer" -Target $computer -ErrorRecord $_
                return
            }

            try {
                $tz = Get-DbaCmObject @splatDbaCmObject -ClassName Win32_TimeZone
            } catch {
                Stop-Function -Message "Failure collecting TimeZone information on $computer" -Target $computer -ErrorRecord $_
                return
            }

            try {
                $powerPlan = Get-DbaCmObject @splatDbaCmObject -ClassName Win32_PowerPlan -Namespace "root\cimv2\power"  | Select-Object ElementName, InstanceId, IsActive
            } catch {
                Write-Message -Level Warning -Message "Power plan information not available on $computer."
                $powerPlan = $null
            }

            if ($powerPlan) {
                $activePowerPlan = ($powerPlan | Where-Object IsActive).ElementName -join ','
            } else {
                $activePowerPlan = 'Not Avaliable'
            }

            $language = Get-Language $os.OSLanguage

            try {
                $ss = Get-DbaCmObject @splatDbaCmObject -Class Win32_SystemServices
                if ($ss | Select-Object PartComponent | Where-Object {$_ -like "*ClusSvc*"}) {
                    $IsWsfc = $true
                } else {
                    $IsWsfc = $false
                }
            } catch {
                Write-Message -Level Warning -Message "Unable to determine Cluster State of $computer."
                $IsWsfc = $null
            }

            [PSCustomObject]@{
                ComputerName             = $computerResolved
                Manufacturer             = $os.Manufacturer
                Organization             = $os.Organization
                Architecture             = $os.OSArchitecture
                Version                  = $os.Version
                Build                    = $os.BuildNumber
                OSVersion                = $os.caption;
                SPVersion                = $os.servicepackmajorversion;
                InstallDate              = [DbaDateTime]$os.InstallDate
                LastBootTime             = [DbaDateTime]$os.LastBootUpTime
                LocalDateTime            = [DbaDateTime]$os.LocalDateTime
                PowerShellVersion        = $PowerShellVersion
                TimeZone                 = $tz.Caption
                TimeZoneStandard         = $tz.StandardName
                TimeZoneDaylight         = $tz.DaylightName
                BootDevice               = $os.BootDevice
                SystemDevice             = $os.SystemDevice
                SystemDrive              = $os.SystemDrive
                WindowsDirectory         = $os.WindowsDirectory
                PagingFileSize           = $os.SizeStoredInPagingFiles
                TotalVisibleMemory       = [DbaSize]($os.TotalVisibleMemorySize * 1024)
                FreePhysicalMemory       = [DbaSize]($os.FreePhysicalMemory * 1024)
                TotalVirtualMemory       = [DbaSize]($os.TotalVirtualMemorySize * 1024)
                FreeVirtualMemory        = [DbaSize]($os.FreeVirtualMemory * 1024)
                ActivePowerPlan          = $activePowerPlan
                Status                   = $os.Status
                Language                 = $language.Name
                LanguageId               = $language.LCID
                LanguageKeyboardLayoutId = $language.KeyboardLayoutId
                LanguageTwoLetter        = $language.TwoLetterISOLanguageName
                LanguageThreeLetter      = $language.ThreeLetterISOLanguageName
                LanguageAlias            = $language.DisplayName
                LanguageNative           = $language.NativeName
                CodeSet                  = $os.CodeSet
                CountryCode              = $os.CountryCode
                Locale                   = $os.Locale
                IsWsfc                   = $IsWsfc
            } | Select-DefaultView -Property ComputerName, Manufacturer, Organization, Architecture, Version, Caption, LastBootTime, LocalDateTime, PowerShellVersion, TimeZone, TotalVisibleMemory, ActivePowerPlan, LanguageNative
        }
    }
}
tools\dbatools\functions\Get-DbaPageFileSetting.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#

function Get-DbaPageFileSetting {
    <#
    .SYNOPSIS
        Returns information on the page file configuration of the target computer.

    .DESCRIPTION
        This command uses CIM (or other, related computer management tools) to detect the page file configuration of the target computer(s).

        Note that this may require local administrator privileges for the relevant computers.

    .PARAMETER ComputerName
        The target SQL Server instance or instances.
        This can be the name of a computer, a SMO object, an IP address, an AD Computer object, a connection string or a SQL Instance.

    .PARAMETER Credential
        Credential object used to connect to the Computer as a different user

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: CIM
        Author: Klaas Vandenberghe (@PowerDBAKlaas)

        dbatools PowerShell module (https://dbatools.io)
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaPageFileSetting

    .EXAMPLE
        PS C:\> Get-DbaPageFileSetting -ComputerName ServerA,ServerB

        Returns a custom object displaying ComputerName, AutoPageFile, FileName, Status, LastModified, LastAccessed, AllocatedBaseSize, InitialSize, MaximumSize, PeakUsage, CurrentUsage  for ServerA and ServerB

    .EXAMPLE
        PS C:\> 'ServerA' | Get-DbaPageFileSetting

        Returns a custom object displaying ComputerName, AutoPageFile, FileName, Status, LastModified, LastAccessed, AllocatedBaseSize, InitialSize, MaximumSize, PeakUsage, CurrentUsage  for ServerA

    #>
    [CmdletBinding()]
    param (
        [Parameter(Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName = $true)]
        [Alias("cn", "host", "ServerInstance", "Server", "SqlServer")]
        [DbaInstance[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($computer in $ComputerName) {
            $splatDbaCmObject = @{
                ComputerName    = $computer
                EnableException = $true
            }
            if ($Credential) { $splatDbaCmObject["Credential"] = $Credential }

            try {
                $compSys = Get-DbaCmObject @splatDbaCmObject -Query "SELECT * FROM win32_computersystem"
                if (-not $CompSys.automaticmanagedpagefile) {
                    $pagefiles = Get-DbaCmObject @splatDbaCmObject -Query "SELECT * FROM win32_pagefile"
                    $pagefileUsages = Get-DbaCmObject @splatDbaCmObject -Query "SELECT * FROM win32_pagefileUsage"
                    $pagefileSettings = Get-DbaCmObject @splatDbaCmObject -Query "SELECT * FROM win32_pagefileSetting"
                }
            } catch {
                Stop-Function -Message "Failed to retrieve information from $($computer.ComputerName)" -ErrorRecord $_ -Target $computer -Continue
            }

            if (-not $CompSys.automaticmanagedpagefile) {
                foreach ($file in $pagefiles) {
                    $settings = $pagefileSettings | Where-Object Name -EQ $file.Name
                    $usage = $pagefileUsages | Where-Object Name -EQ $file.Name

                    # pagefile is not automatic managed, so return settings
                    New-Object Sqlcollaborative.Dbatools.Computer.PageFileSetting -Property @{
                        ComputerName      = $computer.ComputerName
                        AutoPageFile      = $CompSys.automaticmanagedpagefile
                        FileName          = $file.name
                        Status            = $file.status
                        SystemManaged     = ($settings.InitialSize -eq 0) -and ($settings.MaximumSize -eq 0)
                        LastModified      = $file.LastModified
                        LastAccessed      = $file.LastAccessed
                        AllocatedBaseSize = $usage.AllocatedBaseSize # in MB, between Initial and Maximum Size
                        InitialSize       = $settings.InitialSize # in MB
                        MaximumSize       = $settings.MaximumSize # in MB
                        PeakUsage         = $usage.peakusage # in MB
                        CurrentUsage      = $usage.currentusage # in MB
                    }
                }
            } else {
                # pagefile is automatic managed, so there are no settings
                New-Object Sqlcollaborative.Dbatools.Computer.PageFileSetting -Property @{
                    ComputerName      = $computer
                    AutoPageFile      = $CompSys.automaticmanagedpagefile
                    FileName          = $null
                    Status            = $null
                    SystemManaged     = $null
                    LastModified      = $null
                    LastAccessed      = $null
                    AllocatedBaseSize = $null
                    InitialSize       = $null
                    MaximumSize       = $null
                    PeakUsage         = $null
                    CurrentUsage      = $null
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaPbmCategory.ps1
function Get-DbaPbmCategory {
    <#
    .SYNOPSIS
        Returns policy categories from policy based management from an instance.

    .DESCRIPTION
        Returns policy categories from policy based management from an instance.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Category
        Filters results to only show specific condition

    .PARAMETER ExcludeSystemObject
        By default system objects are include. Use this parameter to exclude them.

    .PARAMETER InputObject
        Allows piping from Get-DbaPbmStore

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Policy, PolicyBasedManagement, PBM
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaPbmCategory

    .EXAMPLE
        PS C:\> Get-DbaPbmCategory -SqlInstance sql2016

        Returns all policy categories from the sql2016 PBM server

    .EXAMPLE
        PS C:\> Get-DbaPbmCategory -SqlInstance sql2016 -SqlCredential $cred

        Uses a credential $cred to connect and return all policy categories from the sql2016 PBM server

    #>
    [CmdletBinding()]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [string[]]$Category,
        [Parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Dmf.PolicyStore[]]$InputObject,
        [switch]$ExcludeSystemObject,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaPbmStore -SqlInstance $instance -SqlCredential $SqlCredential
        }
        foreach ($store in $InputObject) {
            $all = $store.PolicyCategories

            if (-not $ExcludeSystemObject) {
                $all = $all | Where-Object IsSystemObject -ne $true
            }

            if ($Category) {
                $all = $all | Where-Object Name -in $Category
            }

            foreach ($current in $all) {
                Write-Message -Level Verbose -Message "Processing $current"
                Add-Member -Force -InputObject $current -MemberType NoteProperty ComputerName -value $store.ComputerName
                Add-Member -Force -InputObject $current -MemberType NoteProperty InstanceName -value $store.InstanceName
                Add-Member -Force -InputObject $current -MemberType NoteProperty SqlInstance -value $store.SqlInstance
                Select-DefaultView -InputObject $current -Property ComputerName, InstanceName, SqlInstance, Id, Name, MandateDatabaseSubscriptions
            }
        }
    }
}
tools\dbatools\functions\Get-DbaPbmCategorySubscription.ps1
function Get-DbaPbmCategorySubscription {
    <#
    .SYNOPSIS
        Returns policy category subscriptions from policy based management from an instance.

    .DESCRIPTION
        Returns policy category subscriptions from policy based management from an instance.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER InputObject
        Allows piping from Get-DbaPbmStore

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Policy, PolicyBasedManagement, PBM
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaPbmCategorySubscription

    .EXAMPLE
        PS C:\> Get-DbaPbmCategorySubscription -SqlInstance sql2016

        Returns all policy category subscriptions from the sql2016 PBM server

    .EXAMPLE
        PS C:\> Get-DbaPbmCategorySubscription -SqlInstance sql2016 -SqlCredential $cred

        Uses a credential $cred to connect and return all policy category subscriptions from the sql2016 PBM server

    #>
    [CmdletBinding()]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Dmf.PolicyStore[]]$InputObject,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaPbmStore -SqlInstance $instance -SqlCredential $SqlCredential
        }
        foreach ($store in $InputObject) {
            $all = $store.PolicycategorySubscriptions

            foreach ($current in $all) {
                Write-Message -Level Verbose -Message "Processing $current"
                Add-Member -Force -InputObject $current -MemberType NoteProperty ComputerName -value $store.ComputerName
                Add-Member -Force -InputObject $current -MemberType NoteProperty InstanceName -value $store.InstanceName
                Add-Member -Force -InputObject $current -MemberType NoteProperty SqlInstance -value $store.SqlInstance
                Select-DefaultView -InputObject $current -ExcludeProperty Properties, Urn, Parent
            }
        }
    }
}
tools\dbatools\functions\Get-DbaPbmCondition.ps1
function Get-DbaPbmCondition {
    <#
    .SYNOPSIS
        Returns conditions from policy based management from an instance.

    .DESCRIPTION
        Returns conditions from policy based management from an instance.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Condition
        Filters results to only show specific condition

    .PARAMETER IncludeSystemObject
        By default system objects are filtered out. Use this parameter to include them.

    .PARAMETER InputObject
        Allows piping from Get-DbaPbmStore

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Policy, PolicyBasedManagement, PBM
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaPbmCondition

    .EXAMPLE
        PS C:\> Get-DbaPbmCondition -SqlInstance sql2016

        Returns all conditions from the sql2016 PBM server

    .EXAMPLE
        PS C:\> Get-DbaPbmCondition -SqlInstance sql2016 -SqlCredential $cred

        Uses a credential $cred to connect and return all conditions from the sql2016 PBM server

    #>
    [CmdletBinding()]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [string[]]$Condition,
        [Parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Dmf.PolicyStore[]]$InputObject,
        [switch]$IncludeSystemObject,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaPbmStore -SqlInstance $instance -SqlCredential $SqlCredential
        }
        foreach ($store in $InputObject) {
            $allconditions = $store.Conditions

            if (-not $IncludeSystemObject) {
                $allconditions = $allconditions | Where-Object IsSystemObject -eq $false
            }

            if ($Condition) {
                $allconditions = $allconditions | Where-Object Name -in $Condition
            }

            foreach ($currentcondition in $allconditions) {
                Write-Message -Level Verbose -Message "Processing $currentcondition"
                Add-Member -Force -InputObject $currentcondition -MemberType NoteProperty ComputerName -value $store.ComputerName
                Add-Member -Force -InputObject $currentcondition -MemberType NoteProperty InstanceName -value $store.InstanceName
                Add-Member -Force -InputObject $currentcondition -MemberType NoteProperty SqlInstance -value $store.SqlInstance
                Select-DefaultView -InputObject $currentcondition -Property ComputerName, InstanceName, SqlInstance, Id, Name, CreateDate, CreatedBy, DateModified, Description, ExpressionNode, Facet, HasScript, IsSystemObject, ModifiedBy
            }
        }
    }
}
tools\dbatools\functions\Get-DbaPbmObjectSet.ps1
function Get-DbaPbmObjectSet {
    <#
    .SYNOPSIS
        Returns object sets from policy based management.

    .DESCRIPTION
        Returns object sets from policy based management.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER ObjectSet
        Filters results to only show specific object set

    .PARAMETER IncludeSystemObject
        By default system objects are filtered out. Use this parameter to include them.

    .PARAMETER InputObject
        Allows piping from Get-DbaPbmStore

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Policy, PolicyBasedManagement, PBM
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaPbmObjectSet

    .EXAMPLE
        PS C:\> Get-DbaPbmObjectSet -SqlInstance sql2016

        Returns all object sets from the sql2016 PBM instance

    .EXAMPLE
        PS C:\> Get-DbaPbmObjectSet -SqlInstance sql2016 -SqlCredential $cred

        Uses a credential $cred to connect and return all object sets from the sql2016 PBM instance

    #>
    [CmdletBinding()]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [string[]]$ObjectSet,
        [Parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Dmf.PolicyStore[]]$InputObject,
        [switch]$IncludeSystemObject,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaPbmStore -SqlInstance $instance -SqlCredential $SqlCredential
        }
        foreach ($store in $InputObject) {
            $all = $store.ObjectSets

            if (-not $IncludeSystemObject) {
                $all = $all | Where-Object IsSystemObject -eq $false
            }

            if ($ObjectSet) {
                $all = $all | Where-Object Name -in $ObjectSet
            }

            foreach ($currentset in $all) {
                Write-Message -Level Verbose -Message "Processing $currentset"
                Add-Member -Force -InputObject $currentset -MemberType NoteProperty ComputerName -value $store.ComputerName
                Add-Member -Force -InputObject $currentset -MemberType NoteProperty InstanceName -value $store.InstanceName
                Add-Member -Force -InputObject $currentset -MemberType NoteProperty SqlInstance -value $store.SqlInstance
                Select-DefaultView -InputObject $currentset -Property ComputerName, InstanceName, SqlInstance, Id, Name, Facet, TargetSets, IsSystemObject
            }
        }
    }
}
tools\dbatools\functions\Get-DbaPbmPolicy.ps1
function Get-DbaPbmPolicy {
    <#
    .SYNOPSIS
        Returns policies from Policy-Based Management from an instance.

    .DESCRIPTION
        Returns details of policies with the option to filter on Category and SystemObjects.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Policy
        Filters results to only show specific policy

    .PARAMETER Category
        Filters results to only show policies in the category selected

    .PARAMETER IncludeSystemObject
        By default system objects are filtered out. Use this parameter to INCLUDE them .

    .PARAMETER InputObject
        Allows piping from Get-DbaPbmStore

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Policy, PolicyBasedManagement, PBM
        Author: Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaPbmPolicy

    .EXAMPLE
        PS C:\> Get-DbaPbmPolicy -SqlInstance sql2016

        Returns all policies from sql2016 server

    .EXAMPLE
        PS C:\> Get-DbaPbmPolicy -SqlInstance sql2016 -SqlCredential $cred

        Uses a credential $cred to connect and return all policies from sql2016 instance

    .EXAMPLE
        PS C:\> Get-DbaPbmPolicy -SqlInstance sql2016 -Category MorningCheck

        Returns all policies from sql2016 server that part of the PolicyCategory MorningCheck

    #>
    [CmdletBinding()]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [string[]]$Policy,
        [string[]]$Category,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Dmf.PolicyStore[]]$InputObject,
        [switch]$IncludeSystemObject,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaPbmStore -SqlInstance $instance -SqlCredential $SqlCredential
        }
        foreach ($store in $InputObject) {
            $allpolicies = $store.Policies

            if (-not $IncludeSystemObject) {
                $allpolicies = $allpolicies | Where-Object IsSystemObject -eq $false
            }

            if ($Category) {
                $allpolicies = $allpolicies | Where-Object PolicyCategory -in $Category
            }

            if ($Policy) {
                $allpolicies = $allpolicies | Where-Object Name -in $Policy
            }

            foreach ($currentpolicy in $allpolicies) {
                Write-Message -Level Verbose -Message "Processing $currentpolicy"
                Add-Member -Force -InputObject $currentpolicy -MemberType NoteProperty ComputerName -value $store.ComputerName
                Add-Member -Force -InputObject $currentpolicy -MemberType NoteProperty InstanceName -value $store.InstanceName
                Add-Member -Force -InputObject $currentpolicy -MemberType NoteProperty SqlInstance -value $store.SqlInstance

                Select-DefaultView -InputObject $currentpolicy -ExcludeProperty HelpText, HelpLink, Urn, Properties, Metadata, Parent, IdentityKey, HasScript, PolicyEvaluationStarted, ConnectionProcessingStarted, TargetProcessed, ConnectionProcessingFinished, PolicyEvaluationFinished, PropertyMetadataChanged, PropertyChanged
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaPolicy
    }
}
tools\dbatools\functions\Get-DbaPbmStore.ps1
function Get-DbaPbmStore {
    <#
    .SYNOPSIS
        Returns the policy based management store.

    .DESCRIPTION
        Returns the policy based management store.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Policy
        Filters results to only show specific policy

    .PARAMETER Category
        Filters results to only show policies in the category selected

    .PARAMETER IncludeSystemObject
        By default system objects are filtered out. Use this parameter to include them.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Policy, PolicyBasedManagement, PBM
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaPbmStore

    .EXAMPLE
        PS C:\> Get-DbaPbmStore -SqlInstance sql2016

        Return the policy store from the sql2016 instance

    .EXAMPLE
        PS C:\> Get-DbaPbmStore -SqlInstance sql2016 -SqlCredential $cred

        Uses a credential $cred to connect and return the policy store from the sql2016 instance

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 10
                $sqlStoreConnection = New-Object Microsoft.SqlServer.Management.Sdk.Sfc.SqlStoreConnection $server.ConnectionContext.SqlConnectionObject
                # DMF is the Declarative Management Framework, Policy Based Management's old name
                $store = New-Object Microsoft.SqlServer.Management.DMF.PolicyStore $sqlStoreConnection
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            Add-Member -Force -InputObject $store -MemberType NoteProperty ComputerName -value $server.ComputerName
            Add-Member -Force -InputObject $store -MemberType NoteProperty InstanceName -value $server.ServiceName
            Add-Member -Force -InputObject $store -MemberType NoteProperty SqlInstance -value $server.DomainInstanceName

            Select-DefaultView -InputObject $store -ExcludeProperty SqlStoreConnection, ConnectionContext, Properties, Urn, Parent, DomainInstanceName, Metadata, IdentityKey, Name
        }
    }
}
tools\dbatools\functions\Get-DbaPermission.ps1
function Get-DbaPermission {
    <#
    .SYNOPSIS
        Get a list of Server and Database level permissions

    .DESCRIPTION
        Retrieves a list of permissions

        Permissions link principals to securables.
        Principals exist on Windows, Instance and Database level.
        Securables exist on Instance and Database level.
        A permission state can be GRANT, DENY or REVOKE.
        The permission type can be SELECT, CONNECT, EXECUTE and more.

        See https://msdn.microsoft.com/en-us/library/ms191291.aspx for more information

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Defaults to localhost.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies one or more database(s) to process. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies one or more database(s) to exclude from processing.

    .PARAMETER IncludeServerLevel
        If this switch is enabled, information about Server Level Permissions will be output.

    .PARAMETER ExcludeSystemObjects
        If this switch is enabled, permissions on system securables will be excluded.

    .PARAMETER EnableException
        If this switch is enabled exceptions will be thrown to the caller, which will need to perform its own exception processing. Otherwise, the function will try to catch the exception, interpret it and provide a friendly error message.

    .NOTES
        Tags: Permissions, Databases
        Author: Klaas Vandenberghe (@PowerDBAKlaas)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaPermission

    .EXAMPLE
        PS C:\> Get-DbaPermission -SqlInstance ServerA\sql987

        Returns a custom object with Server name, Database name, permission state, permission type, grantee and securable.

    .EXAMPLE
        PS C:\> Get-DbaPermission -SqlInstance ServerA\sql987 | Format-Table -AutoSize

        Returns a formatted table displaying Server, Database, permission state, permission type, grantee, granteetype, securable and securabletype.

    .EXAMPLE
        PS C:\> Get-DbaPermission -SqlInstance ServerA\sql987 -ExcludeSystemObjects -IncludeServerLevel

        Returns a custom object with Server name, Database name, permission state, permission type, grantee and securable
        in all databases and on the server level, but not on system securables.

    .EXAMPLE
        PS C:\> Get-DbaPermission -SqlInstance sql2016 -Database master

        Returns a custom object with permissions for the master database.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$IncludeServerLevel,
        [switch]$ExcludeSystemObjects,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        if ($ExcludeSystemObjects) {
            $ExcludeSystemObjectssql = "WHERE major_id > 0 "
        }

        $ServPermsql = "SELECT SERVERPROPERTY('MachineName') AS ComputerName,
                       ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
                       SERVERPROPERTY('ServerName') AS SqlInstance
                        , [Database] = ''
                        , [PermState] = state_desc
                        , [PermissionName] = permission_name
                        , [SecurableType] = COALESCE(o.type_desc,sp.class_desc)
                        , [Securable] = CASE	WHEN class = 100 THEN @@SERVERNAME
                                                WHEN class = 105 THEN OBJECT_NAME(major_id)
                                                ELSE OBJECT_NAME(major_id)
                                                END
                        , [Grantee] = SUSER_NAME(grantee_principal_id)
                        , [GranteeType] = pr.type_desc
                        , [revokeStatement] = 'REVOKE ' + permission_name + ' ' + COALESCE(OBJECT_NAME(major_id),'') + ' FROM [' + SUSER_NAME(grantee_principal_id) + ']'
                        , [grantStatement] = 'GRANT ' + permission_name + ' ' + COALESCE(OBJECT_NAME(major_id),'') + ' TO [' + SUSER_NAME(grantee_principal_id) + ']'
                    FROM sys.server_permissions sp
                        JOIN sys.server_principals pr ON pr.principal_id = sp.grantee_principal_id
                        LEFT OUTER JOIN sys.all_objects o ON o.object_id = sp.major_id

                    $ExcludeSystemObjectssql

                    UNION ALL
                    SELECT	  SERVERPROPERTY('MachineName') AS ComputerName
                            , ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName
                            , SERVERPROPERTY('ServerName') AS SqlInstance
                            , [database] = ''
                            , [PermState] = 'GRANT'
                            , [PermissionName] = pb.[permission_name]
                            , [SecurableType] = pb.class_desc
                            , [Securable] = @@SERVERNAME
                            , [Grantee] = spr.name
                            , [GranteeType] = spr.type_desc
                            , [revokestatement] = ''
                            , [grantstatement] = ''
                    FROM sys.server_principals AS spr
                    INNER JOIN sys.fn_builtin_permissions('SERVER') AS pb ON
                        spr.[name]='bulkadmin' AND pb.[permission_name]='ADMINISTER BULK OPERATIONS'
                        OR
                        spr.[name]='dbcreator' AND pb.[permission_name]='CREATE ANY DATABASE'
                        OR
                        spr.[name]='diskadmin' AND pb.[permission_name]='ALTER RESOURCES'
                        OR
                        spr.[name]='processadmin' AND pb.[permission_name] IN ('ALTER ANY CONNECTION', 'ALTER SERVER STATE')
                        OR
                        spr.[name]='sysadmin' AND pb.[permission_name]='CONTROL SERVER'
                        OR
                        spr.[name]='securityadmin' AND pb.[permission_name]='ALTER ANY LOGIN'
                        OR
                        spr.[name]='serveradmin'  AND pb.[permission_name] IN ('ALTER ANY ENDPOINT', 'ALTER RESOURCES','ALTER SERVER STATE', 'ALTER SETTINGS','SHUTDOWN', 'VIEW SERVER STATE')
                        OR
                        spr.[name]='setupadmin' AND pb.[permission_name]='ALTER ANY LINKED SERVER'
                    WHERE spr.[type]='R'
                    ;"

        $DBPermsql = "SELECT SERVERPROPERTY('MachineName') AS ComputerName,
                    ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
                    SERVERPROPERTY('ServerName') AS SqlInstance
                    , [Database] = DB_NAME()
                    , [PermState] = state_desc
                    , [PermissionName] = permission_name
                    , [SecurableType] = COALESCE(o.type_desc,dp.class_desc)
                    , [Securable] = CASE	WHEN class = 0 THEN DB_NAME()
                                            WHEN class = 1 THEN ISNULL(s.name + '.','')+OBJECT_NAME(major_id)
                                            WHEN class = 3 THEN SCHEMA_NAME(major_id)
                                            WHEN class = 6 THEN SCHEMA_NAME(t.schema_id)+'.' + t.name
                                            END
                    , [Grantee] = USER_NAME(grantee_principal_id)
                    , [GranteeType] = pr.type_desc
                    , [revokeStatement] = 'REVOKE ' + permission_name + ' ON ' + isnull(schema_name(o.object_id)+'.','')+OBJECT_NAME(major_id)+ ' FROM [' + USER_NAME(grantee_principal_id) + ']'
                    , [grantStatement] = 'GRANT ' + permission_name + ' ON ' + isnull(schema_name(o.object_id)+'.','')+OBJECT_NAME(major_id)+ ' TO [' + USER_NAME(grantee_principal_id) + ']'
                FROM sys.database_permissions dp
                    JOIN sys.database_principals pr ON pr.principal_id = dp.grantee_principal_id
                    LEFT OUTER JOIN sys.all_objects o ON o.object_id = dp.major_id
                    LEFT OUTER JOIN sys.schemas s ON s.schema_id = o.schema_id
                    LEFT OUTER JOIN sys.types t on t.user_type_id = dp.major_id

                $ExcludeSystemObjectssql

                UNION ALL
                SELECT	  SERVERPROPERTY('MachineName') AS ComputerName
                        , ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName
                        , SERVERPROPERTY('ServerName') AS SqlInstance
                        , [database] = DB_NAME()
                        , [PermState] = ''
                        , [PermissionName] = p.[permission_name]
                        , [SecurableType] = p.class_desc
                        , [Securable] = DB_NAME()
                        , [Grantee] = dp.name
                        , [GranteeType] = dp.type_desc
                        , [revokestatement] = ''
                        , [grantstatement] = ''
                FROM sys.database_principals AS dp
                INNER JOIN sys.fn_builtin_permissions('DATABASE') AS p ON
                    dp.[name]='db_accessadmin' AND p.[permission_name] IN ('ALTER ANY USER', 'CREATE SCHEMA')
                    OR
                    dp.[name]='db_backupoperator' AND p.[permission_name] IN ('BACKUP DATABASE', 'BACKUP LOG', 'CHECKPOINT')
                    OR
                    dp.[name] IN ('db_datareader', 'db_denydatareader') AND p.[permission_name]='SELECT'
                    OR
                    dp.[name] IN ('db_datawriter', 'db_denydatawriter') AND p.[permission_name] IN ('INSERT', 'DELETE', 'UPDATE')
                    OR
                    dp.[name]='db_ddladmin' AND
                    p.[permission_name] IN ('ALTER ANY ASSEMBLY', 'ALTER ANY ASYMMETRIC KEY',
                                            'ALTER ANY CERTIFICATE', 'ALTER ANY CONTRACT',
                                            'ALTER ANY DATABASE DDL TRIGGER', 'ALTER ANY DATABASE EVENT',
                                            'NOTIFICATION', 'ALTER ANY DATASPACE', 'ALTER ANY FULLTEXT CATALOG',
                                            'ALTER ANY MESSAGE TYPE', 'ALTER ANY REMOTE SERVICE BINDING',
                                            'ALTER ANY ROUTE', 'ALTER ANY SCHEMA', 'ALTER ANY SERVICE',
                                            'ALTER ANY SYMMETRIC KEY', 'CHECKPOINT', 'CREATE AGGREGATE',
                                            'CREATE DEFAULT', 'CREATE FUNCTION', 'CREATE PROCEDURE',
                                            'CREATE QUEUE', 'CREATE RULE', 'CREATE SYNONYM', 'CREATE TABLE',
                                            'CREATE TYPE', 'CREATE VIEW', 'CREATE XML SCHEMA COLLECTION',
                                            'REFERENCES')
                    OR
                    dp.[name]='db_owner' AND p.[permission_name]='CONTROL'
                    OR
                    dp.[name]='db_securityadmin' AND p.[permission_name] IN ('ALTER ANY APPLICATION ROLE', 'ALTER ANY ROLE', 'CREATE SCHEMA', 'VIEW DEFINITION')

                WHERE dp.[type]='R'
                    AND dp.is_fixed_role=1
                ;"
    }

    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($IncludeServerLevel) {
                Write-Message -Level Debug -Message "T-SQL: $ServPermsql"
                $server.Query($ServPermsql)
            }

            $dbs = $server.Databases

            if ($Database) {
                $dbs = $dbs | Where-Object Name -In $Database
            }

            if ($ExcludeDatabase) {
                $dbs = $dbs | Where-Object Name -NotIn $ExcludeDatabase
            }

            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Processing $db on $instance."

                if ($db.IsAccessible -eq $false) {
                    Write-Message -Level Warning -Message "The database $db is not accessible. Skipping database."
                    Continue
                }

                Write-Message -Level Debug -Message "T-SQL: $DBPermsql"
                $db.ExecuteWithResults($DBPermsql).Tables.Rows
            }
        }
    }
}
tools\dbatools\functions\Get-DbaPfAvailableCounter.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaPfAvailableCounter {
    <#
    .SYNOPSIS
        Gathers list of all available counters on local or remote machines.

    .DESCRIPTION
        Gathers list of all available counters on local or remote machines. Note, if you pass a credential object, it will be included in the output for easy reuse in your next piped command.

        Thanks to Daniel Streefkerk for this super fast way of counters
        https://daniel.streefkerkonline.com/2016/02/18/use-powershell-to-list-all-windows-performance-counters-and-their-numeric-ids

    .PARAMETER ComputerName
        The target computer. Defaults to localhost.

    .PARAMETER Credential
        Allows you to login to servers using alternative credentials. To use:

        $scred = Get-Credential, then pass $scred object to the -Credential parameter.

    .PARAMETER Pattern
        Specify a pattern for filtering.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Performance, DataCollector, PerfCounter
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaPfAvailableCounter

    .EXAMPLE
        PS C:\> Get-DbaPfAvailableCounter

        Gets all available counters on the local machine.

    .EXAMPLE
        PS C:\> Get-DbaPfAvailableCounter -Pattern *sql*

        Gets all counters matching sql on the local machine.

    .EXAMPLE
        PS C:\> Get-DbaPfAvailableCounter -ComputerName sql2017 -Pattern *sql*

        Gets all counters matching sql on the remote server sql2017.

    .EXAMPLE
        PS C:\> Get-DbaPfAvailableCounter -Pattern *sql*

        Gets all counters matching sql on the local machine.

    .EXAMPLE
        PS C:\> Get-DbaPfAvailableCounter -Pattern *sql* | Add-DbaPfDataCollectorCounter -CollectorSet 'Test Collector Set' -Collector DataCollector01

        Adds all counters matching "sql" to the DataCollector01 within the 'Test Collector Set' CollectorSet.

    #>
    [CmdletBinding()]
    param (
        [DbaInstance[]]$ComputerName = $env:ComputerName,
        [PSCredential]$Credential,
        [string]$Pattern,
        [switch]$EnableException
    )
    begin {
        $scriptblock = {
            $counters = Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\009' -Name 'counter' | Select-Object -ExpandProperty Counter |
                Where-Object { $_ -notmatch '[0-90000]' } | Sort-Object | Get-Unique

            foreach ($counter in $counters) {
                [pscustomobject]@{
                    ComputerName = $env:COMPUTERNAME
                    Name         = $counter
                    Credential   = $args
                }
            }
        }

        # In case people really want a "like" search, which is slower
        $Pattern = $Pattern.Replace("*", ".*").Replace("..*", ".*")
    }
    process {
        
        
        foreach ($computer in $ComputerName) {

            try {
                if ($pattern) {
                    Invoke-Command2 -ComputerName $computer -Credential $Credential -ScriptBlock $scriptblock -ArgumentList $credential -ErrorAction Stop |
                        Where-Object Name -match $pattern | Select-DefaultView -ExcludeProperty Credential
                } else {
                    Invoke-Command2 -ComputerName $computer -Credential $Credential -ScriptBlock $scriptblock -ArgumentList $credential -ErrorAction Stop |
                        Select-DefaultView -ExcludeProperty Credential
                }
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Target $computer -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaPfDataCollector.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaPfDataCollector {
    <#
    .SYNOPSIS
        Gets Performance Monitor Data Collectors.

    .DESCRIPTION
        Gets Performance Monitor Data Collectors.

    .PARAMETER ComputerName
        The target computer. Defaults to localhost.

    .PARAMETER Credential
        Allows you to login to servers using alternative credentials. To use:

        $scred = Get-Credential, then pass $scred object to the -Credential parameter.

    .PARAMETER CollectorSet
        The Collector Set name.

    .PARAMETER Collector
        The Collector name.

    .PARAMETER InputObject
        Accepts the object output by Get-DbaPfDataCollectorSet via the pipeline.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Performance, DataCollector, PerfCounter
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaPfDataCollector

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollector

        Gets all Collectors on localhost.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollector -ComputerName sql2017

        Gets all Collectors on sql2017.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollector -ComputerName sql2017, sql2016 -Credential ad\sqldba -CollectorSet 'System Correlation'

        Gets all Collectors for the 'System Correlation' CollectorSet on sql2017 and sql2016 using alternative credentials.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorSet -CollectorSet 'System Correlation' | Get-DbaPfDataCollector

        Gets all Collectors for the 'System Correlation' CollectorSet.

    #>
    [CmdletBinding()]
    param (
        [DbaInstance[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [Alias("DataCollectorSet")]
        [string[]]$CollectorSet,
        [Alias("DataCollector")]
        [string[]]$Collector,
        [parameter(ValueFromPipeline)]
        [object[]]$InputObject,
        [switch]$EnableException
    )
    begin {
        $columns = 'ComputerName', 'DataCollectorSet', 'Name', 'DataCollectorType', 'DataSourceName', 'FileName', 'FileNameFormat', 'FileNameFormatPattern', 'LatestOutputLocation', 'LogAppend', 'LogCircular', 'LogFileFormat', 'LogOverwrite', 'SampleInterval', 'SegmentMaxRecords', 'Counters'
    }
    process {
        
        
        if ($InputObject.Credential -and (Test-Bound -ParameterName Credential -Not)) {
            $Credential = $InputObject.Credential
        }

        if (-not $InputObject -or ($InputObject -and (Test-Bound -ParameterName ComputerName))) {
            foreach ($computer in $ComputerName) {
                $InputObject += Get-DbaPfDataCollectorSet -ComputerName $computer -Credential $Credential -CollectorSet $CollectorSet
            }
        }

        if ($InputObject) {
            if (-not $InputObject.DataCollectorSetObject) {
                Stop-Function -Message "InputObject is not of the right type. Please use Get-DbaPfDataCollectorSet."
                return
            }
        }

        foreach ($set in $InputObject) {
            $collectorxml = ([xml]$set.Xml).DataCollectorSet.PerformanceCounterDataCollector
            foreach ($col in $collectorxml) {
                if ($Collector -and $Collector -notcontains $col.Name) {
                    continue
                }

                $outputlocation = $col.LatestOutputLocation
                if ($outputlocation) {
                    $dir = ($outputlocation).Replace(':', '$')
                    $remote = "\\$($set.ComputerName)\$dir"
                } else {
                    $remote = $null
                }

                [pscustomobject]@{
                    ComputerName               = $set.ComputerName
                    DataCollectorSet           = $set.Name
                    Name                       = $col.Name
                    FileName                   = $col.FileName
                    DataCollectorType          = $col.DataCollectorType
                    FileNameFormat             = $col.FileNameFormat
                    FileNameFormatPattern      = $col.FileNameFormatPattern
                    LogAppend                  = $col.LogAppend
                    LogCircular                = $col.LogCircular
                    LogOverwrite               = $col.LogOverwrite
                    LatestOutputLocation       = $col.LatestOutputLocation
                    DataCollectorSetXml        = $set.Xml
                    RemoteLatestOutputLocation = $remote
                    DataSourceName             = $col.DataSourceName
                    SampleInterval             = $col.SampleInterval
                    SegmentMaxRecords          = $col.SegmentMaxRecords
                    LogFileFormat              = $col.LogFileFormat
                    Counters                   = $col.Counter
                    CounterDisplayNames        = $col.CounterDisplayName
                    CollectorXml               = $col
                    DataCollectorObject        = $true
                    Credential                 = $Credential
                } | Select-DefaultView -Property $columns
            }
        }
    }
}
tools\dbatools\functions\Get-DbaPfDataCollectorCounter.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaPfDataCollectorCounter {
    <#
    .SYNOPSIS
        Gets Performance Counters.

    .DESCRIPTION
        Gets Performance Counters.

    .PARAMETER ComputerName
        The target computer. Defaults to localhost.

    .PARAMETER Credential
        Allows you to login to servers using alternative credentials. To use:

        $scred = Get-Credential, then pass $scred object to the -Credential parameter.

    .PARAMETER CollectorSet
        The Collector Set name.

    .PARAMETER Collector
        The Collector name.

    .PARAMETER Counter
        The Counter name to capture. This must be in the form of '\Processor(_Total)\% Processor Time'.

    .PARAMETER InputObject
        Accepts the object output by Get-DbaPfDataCollectorSet via the pipeline.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Performance, DataCollector, PerfCounter
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaPfDataCollectorCounter

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorCounter

        Gets all counters for all Collector Sets on localhost.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorCounter -ComputerName sql2017

        Gets all counters for all Collector Sets on  on sql2017.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorCounter -ComputerName sql2017 -Counter '\Processor(_Total)\% Processor Time'

        Gets the '\Processor(_Total)\% Processor Time' counter on sql2017.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorCounter -ComputerName sql2017, sql2016 -Credential ad\sqldba -CollectorSet 'System Correlation'

        Gets all counters for the 'System Correlation' CollectorSet on sql2017 and sql2016 using alternative credentials.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorSet -CollectorSet 'System Correlation' | Get-DbaPfDataCollector | Get-DbaPfDataCollectorCounter

        Gets all counters for the 'System Correlation' CollectorSet.

    #>
    [CmdletBinding()]
    param (
        [DbaInstance[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [Alias("DataCollectorSet")]
        [string[]]$CollectorSet,
        [Alias("DataCollector")]
        [string[]]$Collector,
        [string[]]$Counter,
        [parameter(ValueFromPipeline)]
        [object[]]$InputObject,
        [switch]$EnableException
    )
    begin {
        #Variable marked as unused by PSScriptAnalyzer
        #$columns = 'ComputerName', 'Name', 'DataCollectorSet', 'Counters', 'DataCollectorType', 'DataSourceName', 'FileName', 'FileNameFormat', 'FileNameFormatPattern', 'LatestOutputLocation', 'LogAppend', 'LogCircular', 'LogFileFormat', 'LogOverwrite', 'SampleInterval', 'SegmentMaxRecords'
    }
    process {
        
        
        if ($InputObject.Credential -and (Test-Bound -ParameterName Credential -Not)) {
            $Credential = $InputObject.Credential
        }

        if (-not $InputObject -or ($InputObject -and (Test-Bound -ParameterName ComputerName))) {
            foreach ($computer in $ComputerName) {
                $InputObject += Get-DbaPfDataCollector -ComputerName $computer -Credential $Credential -CollectorSet $CollectorSet -Collector $Collector
            }
        }

        if ($InputObject) {
            if (-not $InputObject.DataCollectorObject) {
                Stop-Function -Message "InputObject is not of the right type. Please use Get-DbaPfDataCollector."
                return
            }
        }

        foreach ($counterobject in $InputObject) {
            foreach ($countername in $counterobject.Counters) {
                if ($Counter -and $Counter -notcontains $countername) { continue }
                [pscustomobject]@{
                    ComputerName        = $counterobject.ComputerName
                    DataCollectorSet    = $counterobject.DataCollectorSet
                    DataCollector       = $counterobject.Name
                    DataCollectorSetXml = $counterobject.DataCollectorSetXml
                    Name                = $countername
                    FileName            = $counterobject.FileName
                    CounterObject       = $true
                    Credential          = $Credential
                } | Select-DefaultView -ExcludeProperty DataCollectorObject, Credential, CounterObject, DataCollectorSetXml
            }
        }
    }
}
tools\dbatools\functions\Get-DbaPfDataCollectorCounterSample.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaPfDataCollectorCounterSample {
    <#
    .SYNOPSIS
        Gets Performance Counter Samples.

    .DESCRIPTION
        Gets Performance Counter Samples.

    .PARAMETER ComputerName
        The target computer. Defaults to localhost.

    .PARAMETER Credential
        Allows you to login to servers using alternative credentials. To use:

        $scred = Get-Credential, then pass $scred object to the -Credential parameter.

    .PARAMETER CollectorSet
        The Collector Set name.

    .PARAMETER Collector
        The Collector name.

    .PARAMETER Counter
        The Counter name. This must be in the form of '\Processor(_Total)\% Processor Time'.

    .PARAMETER Continuous
        If this switch is enabled, samples will be retrieved continuously until you press CTRL+C. By default, this command gets only one counter sample. You can use the SampleInterval parameter to set the interval for continuous sampling.

    .PARAMETER ListSet
        Gets the specified performance counter sets on the computers. Enter the names of the counter sets. Wildcards are permitted.

    .PARAMETER MaxSamples
        Specifies the number of samples to get from each counter. The default is 1 sample. To get samples continuously (no maximum sample size), use the Continuous parameter.

        To collect a very large data set, consider running a Get-DbaPfDataCollectorCounterSample command as a Windows PowerShell background job.

    .PARAMETER SampleInterval
        Specifies the time between samples in seconds. The minimum value and the default value are 1 second.

    .PARAMETER InputObject
        Accepts the object output by Get-DbaPfDataCollectorCounter via the pipeline.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Performance, DataCollector, PerfCounter
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaPfDataCollectorCounterSample

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorCounterSample

        Gets a single sample for all counters for all Collector Sets on localhost.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorCounterSample -Counter '\Processor(_Total)\% Processor Time'

        Gets a single sample for all counters for all Collector Sets on localhost.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorCounter -ComputerName sql2017, sql2016 | Out-GridView -PassThru | Get-DbaPfDataCollectorCounterSample -MaxSamples 10

        Gets 10 samples for all counters for all Collector Sets for servers sql2016 and sql2017.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorCounterSample -ComputerName sql2017

        Gets a single sample for all counters for all Collector Sets on sql2017.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorCounterSample -ComputerName sql2017, sql2016 -Credential ad\sqldba -CollectorSet 'System Correlation'

        Gets a single sample for all counters for the 'System Correlation' CollectorSet on sql2017 and sql2016 using alternative credentials.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorCounterSample -CollectorSet 'System Correlation'

        Gets a single sample for all counters for the 'System Correlation' CollectorSet.

    #>
    [CmdletBinding()]
    param (
        [DbaInstance[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [Alias("DataCollectorSet")]
        [string[]]$CollectorSet,
        [Alias("DataCollector")]
        [string[]]$Collector,
        [string[]]$Counter,
        [switch]$Continuous,
        [switch[]]$ListSet,
        [int]$MaxSamples,
        [int]$SampleInterval,
        [parameter(ValueFromPipeline)]
        [object[]]$InputObject,
        [switch]$EnableException
    )
    process {
        
        
        if ($InputObject.Credential -and (Test-Bound -ParameterName Credential -Not)) {
            $Credential = $InputObject.Credential
        }

        if ($InputObject.Counter -and (Test-Bound -ParameterName Counter -Not)) {
            $Counter = $InputObject.Counter
        }

        if (-not $InputObject -or ($InputObject -and (Test-Bound -ParameterName ComputerName))) {
            foreach ($computer in $ComputerName) {
                $InputObject += Get-DbaPfDataCollectorCounter -ComputerName $computer -Credential $Credential -CollectorSet $CollectorSet -Collector $Collector
            }
        }

        if ($InputObject) {
            if (-not $InputObject.CounterObject) {
                Stop-Function -Message "InputObject is not of the right type. Please use Get-DbaPfDataCollectorCounter."
                return
            }
        }

        foreach ($counterobject in $InputObject) {
            if ((Test-Bound -ParameterName Counter) -and ($Counter -notcontains $counterobject.Name)) { continue }
            $params = @{
                Counter = $counterobject.Name
            }

            if (-not ([dbainstance]$counterobject.ComputerName).IsLocalHost) {
                $params.Add("ComputerName", $counterobject.ComputerName)
            }

            if ($Credential) {
                $params.Add("Credential", $Credential)
            }

            if ($Continuous) {
                $params.Add("Continuous", $Continuous)
            }

            if ($ListSet) {
                $params.Add("ListSet", $ListSet)
            }

            if ($MaxSamples) {
                $params.Add("MaxSamples", $MaxSamples)
            }

            if ($SampleInterval) {
                $params.Add("SampleInterval", $SampleInterval)
            }

            if ($Continuous) {
                Get-Counter @params
            } else {
                try {
                    $pscounters = Get-Counter @params -ErrorAction Stop
                } catch {
                    Stop-Function -Message "Failure for $($counterobject.Name) on $($counterobject.ComputerName)." -ErrorRecord $_ -Continue
                }

                foreach ($pscounter in $pscounters) {
                    foreach ($sample in $pscounter.CounterSamples) {
                        [pscustomobject]@{
                            ComputerName           = $counterobject.ComputerName
                            DataCollectorSet       = $counterobject.DataCollectorSet
                            DataCollector          = $counterobject.DataCollector
                            Name                   = $counterobject.Name
                            Timestamp              = $pscounter.Timestamp
                            Path                   = $sample.Path
                            InstanceName           = $sample.InstanceName
                            CookedValue            = $sample.CookedValue
                            RawValue               = $sample.RawValue
                            SecondValue            = $sample.SecondValue
                            MultipleCount          = $sample.MultipleCount
                            CounterType            = $sample.CounterType
                            SampleTimestamp        = $sample.Timestamp
                            SampleTimestamp100NSec = $sample.Timestamp100NSec
                            Status                 = $sample.Status
                            DefaultScale           = $sample.DefaultScale
                            TimeBase               = $sample.TimeBase
                            Sample                 = $pscounter.CounterSamples
                            CounterSampleObject    = $true
                        } | Select-DefaultView -ExcludeProperty Sample, CounterSampleObject
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaPfDataCollectorSet.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaPfDataCollectorSet {
    <#
    .SYNOPSIS
        Gets Performance Monitor Data Collector Set.

    .DESCRIPTION
        Gets Performance Monitor Data Collector Set.

    .PARAMETER ComputerName
        The target computer. Defaults to localhost.

    .PARAMETER Credential
        Allows you to login to servers using alternative credentials. To use:

        $scred = Get-Credential, then pass $scred object to the -Credential parameter.

    .PARAMETER CollectorSet
        The Collector set name.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Performance, DataCollector, PerfCounter
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaPfDataCollectorSet

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorSet

        Gets all Collector Sets on localhost.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorSet -ComputerName sql2017

        Gets all Collector Sets on sql2017.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorSet -ComputerName sql2017 -Credential ad\sqldba -CollectorSet 'System Correlation'

        Gets the 'System Correlation' CollectorSet on sql2017 using alternative credentials.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorSet | Select-Object *

        Displays extra columns and also exposes the original COM object in DataCollectorSetObject.

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstance[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [Alias("DataCollectorSet")]
        [string[]]$CollectorSet,
        [switch]$EnableException
    )

    begin {
        $setscript = {
            # Get names / status info
            $schedule = New-Object -ComObject "Schedule.Service"
            $schedule.Connect()
            $folder = $schedule.GetFolder("Microsoft\Windows\PLA")
            $tasks = @()
            $tasknumber = 0
            $done = $false
            do {
                try {
                    $task = $folder.GetTasks($tasknumber)
                    $tasknumber++
                    if ($task) {
                        $tasks += $task
                    }
                } catch {
                    $done = $true
                }
            }
            while ($done -eq $false)
            $null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($schedule)

            if ($args[0]) {
                $tasks = $tasks | Where-Object Name -in $args[0]
            }

            $sets = New-Object -ComObject Pla.DataCollectorSet
            foreach ($task in $tasks) {
                $setname = $task.Name
                switch ($task.State) {
                    0 { $state = "Unknown" }
                    1 { $state = "Disabled" }
                    2 { $state = "Queued" }
                    3 { $state = "Ready" }
                    4 { $state = "Running" }
                }

                try {
                    # Query changes $sets so work from there
                    $sets.Query($setname, $null)
                    $set = $sets.PSObject.Copy()

                    $outputlocation = $set.OutputLocation
                    $latestoutputlocation = $set.LatestOutputLocation

                    if ($outputlocation) {
                        $dir = (Split-Path $outputlocation).Replace(':', '$')
                        $remote = "\\$env:COMPUTERNAME\$dir"
                    } else {
                        $remote = $null
                    }

                    if ($latestoutputlocation) {
                        $dir = ($latestoutputlocation).Replace(':', '$')
                        $remotelatest = "\\$env:COMPUTERNAME\$dir"
                    } else {
                        $remote = $null
                    }

                    [pscustomobject]@{
                        ComputerName               = $env:COMPUTERNAME
                        Name                       = $setname
                        LatestOutputLocation       = $set.LatestOutputLocation
                        OutputLocation             = $set.OutputLocation
                        RemoteOutputLocation       = $remote
                        RemoteLatestOutputLocation = $remotelatest
                        RootPath                   = $set.RootPath
                        Duration                   = $set.Duration
                        Description                = $set.Description
                        DescriptionUnresolved      = $set.DescriptionUnresolved
                        DisplayName                = $set.DisplayName
                        DisplayNameUnresolved      = $set.DisplayNameUnresolved
                        Keywords                   = $set.Keywords
                        Segment                    = $set.Segment
                        SegmentMaxDuration         = $set.SegmentMaxDuration
                        SegmentMaxSize             = $set.SegmentMaxSize
                        SerialNumber               = $set.SerialNumber
                        Server                     = $set.Server
                        Status                     = $set.Status
                        Subdirectory               = $set.Subdirectory
                        SubdirectoryFormat         = $set.SubdirectoryFormat
                        SubdirectoryFormatPattern  = $set.SubdirectoryFormatPattern
                        Task                       = $set.Task
                        TaskRunAsSelf              = $set.TaskRunAsSelf
                        TaskArguments              = $set.TaskArguments
                        TaskUserTextArguments      = $set.TaskUserTextArguments
                        Schedules                  = $set.Schedules
                        SchedulesEnabled           = $set.SchedulesEnabled
                        UserAccount                = $set.UserAccount
                        Xml                        = $set.Xml
                        Security                   = $set.Security
                        StopOnCompletion           = $set.StopOnCompletion
                        State                      = $state.Trim()
                        DataCollectorSetObject     = $true
                        TaskObject                 = $task
                        Credential                 = $args[1]
                    }
                } catch {
                    <# DO NOT use Write-Message as this is inside of a script block #>
                    Write-Warning -Message "Issue with getting Collector Set $setname on $env:Computername : $_."
                    continue
                }
            }
        }

        $columns = 'ComputerName', 'Name', 'DisplayName', 'Description', 'State', 'Duration', 'OutputLocation', 'LatestOutputLocation',
        'RootPath', 'SchedulesEnabled', 'Segment', 'SegmentMaxDuration', 'SegmentMaxSize',
        'SerialNumber', 'Server', 'StopOnCompletion', 'Subdirectory', 'SubdirectoryFormat',
        'SubdirectoryFormatPattern', 'Task', 'TaskArguments', 'TaskRunAsSelf', 'TaskUserTextArguments', 'UserAccount'
    }
    process {
        
        
        foreach ($computer in $ComputerName.ComputerName) {
            try {
                Invoke-Command2 -ComputerName $computer -Credential $Credential -ScriptBlock $setscript -ArgumentList $CollectorSet, $Credential -ErrorAction Stop | Select-DefaultView -Property $columns
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Target $computer -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaPfDataCollectorSetTemplate.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaPfDataCollectorSetTemplate {
    <#
    .SYNOPSIS
        Parses Perf Monitor templates. Defaults to parsing templates in the dbatools template repository (\bin\perfmontemplates\).

    .DESCRIPTION
        Parses Perf Monitor XML templates. Defaults to parsing templates in the dbatools template repository (\bin\perfmontemplates\).

    .PARAMETER Path
        The path to the template directory. Defaults to the dbatools template repository (\bin\perfmontemplates\).

    .PARAMETER Pattern
        Specify a pattern for filtering. Alternatively, you can use Out-GridView -Passthru to select objects and pipe them to Import-DbaPfDataCollectorSetTemplate.

    .PARAMETER Template
        Specifies one or more of the templates provided by dbatools. Press tab to cycle through the list to the options.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Performance, DataCollector, PerfCounter
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaPfDataCollectorSetTemplate

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorSetTemplate

        Returns information about all the templates in the local dbatools repository.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorSetTemplate | Out-GridView -PassThru | Import-DbaPfDataCollectorSetTemplate -ComputerName sql2017 | Start-DbaPfDataCollectorSet

        Allows you to select a template, then deploys it to sql2017 and immediately starts the DataCollectorSet.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorSetTemplate | Select-Object *

        Returns more information about the template, including the full path/filename.

    #>
    [CmdletBinding()]
    param (
        [string[]]$Path = "$script:PSModuleRoot\bin\perfmontemplates\collectorsets",
        [string]$Pattern,
        [string[]]$Template,
        [switch]$EnableException
    )
    begin {
        $metadata = Import-Clixml "$script:PSModuleRoot\bin\perfmontemplates\collectorsets.xml"
        # In case people really want a "like" search, which is slower
        $Pattern = $Pattern.Replace("*", ".*").Replace("..*", ".*")
    }
    process {
        
        
        foreach ($directory in $Path) {
            $files = Get-ChildItem "$directory\*.xml"

            if ($Template) {
                $files = $files | Where-Object BaseName -in $Template
            }

            foreach ($file in $files) {
                try {
                    $xml = [xml](Get-Content $file)
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target $file -Continue
                }

                foreach ($dataset in $xml.DataCollectorSet) {
                    $meta = $metadata | Where-Object Name -eq $dataset.name
                    if ($Pattern) {
                        if (
                            ($dataset.Name -match $Pattern) -or
                            ($dataset.Description -match $Pattern)
                        ) {
                            [pscustomobject]@{
                                Name        = $dataset.name
                                Source      = $meta.Source
                                UserAccount = $dataset.useraccount
                                Description = $dataset.Description
                                Path        = $file
                                File        = $file.Name
                            } | Select-DefaultView -ExcludeProperty File, Path
                        }
                    } else {
                        [pscustomobject]@{
                            Name        = $dataset.name
                            Source      = $meta.Source
                            UserAccount = $dataset.useraccount
                            Description = $dataset.Description
                            Path        = $file
                            File        = $file.Name
                        } | Select-DefaultView -ExcludeProperty File, Path
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaPlanCache.ps1
function Get-DbaPlanCache {
    <#
    .SYNOPSIS
        Provides information about adhoc and prepared plan cache usage

    .DESCRIPTION
        Checks adhoc and prepared plan cache for each database, if over 100 MB you should consider using Remove-DbaQueryPlan to clear the plan caches or turning on "optimize for adhoc workloads" configuration if running 2008 or later.

        References: https://www.sqlskills.com/blogs/kimberly/plan-cache-adhoc-workloads-and-clearing-the-single-use-plan-cache-bloat/

        Note: This command returns results from all SQL server instances on the destination server but the process column is specific to -SqlInstance passed.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Memory
        Author: Tracy Boggiano, databasesuperhero.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaPlanCache

    .EXAMPLE
        PS C:\> Get-DbaPlanCache -SqlInstance sql2017

        Returns the single use plan cache usage information for SQL Server instance 2017

    .EXAMPLE
        PS C:\> Get-DbaPlanCache -SqlInstance sql2017 -SqlCredential sqladmin

        Returns the single use plan cache usage information for SQL Server instance 2017 using login 'sqladmin'

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )
    begin {
        $Sql = "SELECT SERVERPROPERTY('MachineName') AS ComputerName,
    ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
    SERVERPROPERTY('ServerName') AS SqlInstance, MB = SUM(CAST((CASE WHEN usecounts = 1 AND objtype IN ('Adhoc', 'Prepared') THEN size_in_bytes ELSE 0 END) AS DECIMAL(12, 2))) / 1024 / 1024,
    UseCount = SUM(CASE WHEN usecounts = 1 AND objtype IN ('Adhoc', 'Prepared') THEN 1 ELSE 0 END)
    FROM sys.dm_exec_cached_plans;"
    }

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $results = $server.Query($sql)
            $size = [dbasize]($results.MB * 1024 * 1024)
            Add-Member -Force -InputObject $results -MemberType NoteProperty -Name Size -Value $size

            Select-DefaultView -InputObject $results -Property ComputerName, InstanceName, SqlInstance, Size, UseCount
        }
    }
}
tools\dbatools\functions\Get-DbaPowerPlan.ps1
function Get-DbaPowerPlan {
    <#
    .SYNOPSIS
        Gets the Power Plan settings for compliance with best practices, which recommend High Performance for SQL Server.

    .DESCRIPTION
        Gets the Power Plan settings on a computer against best practices recommendations.

    .PARAMETER ComputerName
        The server(s) to check Power Plan settings on.

    .PARAMETER Credential
        Specifies a PSCredential object to use in authenticating to the server(s), instead of the current user account.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: PowerPlan
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaPowerPlan

    .EXAMPLE
        PS C:\> Get-DbaPowerPlan -ComputerName sql2017

        Gets the Power Plan settings for sql2017

    .EXAMPLE
        PS C:\> Get-DbaPowerPlan -ComputerName sql2017 -Credential ad\admin

        Gets the Power Plan settings for sql2017 using an alternative credential

       #>
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlInstance")]
        [DbaInstance[]]$ComputerName,
        [PSCredential]$Credential,
        [switch]$EnableException
    )

    process {
        foreach ($computer in $ComputerName) {
            $null = Test-ElevationRequirement -ComputerName $computer -Continue

            $server = Resolve-DbaNetworkName -ComputerName $computer -Credential $Credential

            $computerResolved = $server.FullComputerName

            if (-not $computerResolved) {
                Stop-Function -Message "Couldn't resolve hostname. Skipping." -Continue
            }

            $splatDbaCmObject = @{
                ComputerName    = $computerResolved
                EnableException = $true
            }

            if (Test-Bound "Credential") {
                $splatDbaCmObject["Credential"] = $Credential
            }

            Write-Message -Level Verbose -Message "Getting Power Plan information from $computer."

            try {
                $powerPlans = Get-DbaCmObject @splatDbaCmObject -ClassName Win32_PowerPlan -Namespace "root\cimv2\power" | Select-Object ElementName, InstanceId, IsActive
            } catch {
                if ($_.Exception -match "namespace") {
                    Stop-Function -Message "Can't get Power Plan Info for $computer. Unsupported operating system." -Continue -ErrorRecord $_ -Target $computer
                } else {
                    Stop-Function -Message "Can't get Power Plan Info for $computer. Check logs for more details." -Continue -ErrorRecord $_ -Target $computer
                }
            }

            $powerPlan = $powerPlans | Where-Object IsActive -eq 'True' | Select-Object ElementName, InstanceID
            $powerPlan.InstanceID = $powerPlan.InstanceID.Split('{')[1].Split('}')[0]

            if ($null -eq $powerPlan.InstanceID) {
                $powerPlan.ElementName = "Unknown"
            }

            [PSCustomObject]@{
                ComputerName = $computer
                InstanceId   = $powerPlan.InstanceID
                PowerPlan    = $powerPlan.ElementName
                Credential   = $Credential
            } | Select-DefaultView -ExcludeProperty Credential, InstanceId
        }
    }
}
tools\dbatools\functions\Get-DbaPrivilege.ps1
function Get-DbaPrivilege {
    <#
    .SYNOPSIS
        Gets the users with local privileges on one or more computers.

    .DESCRIPTION
        Gets the users with local privileges 'Lock Pages in Memory', 'Instant File Initialization', 'Logon as Batch' on one or more computers.

        Requires Local Admin rights on destination computer(s).

    .PARAMETER ComputerName
        The target SQL Server instance or instances.

    .PARAMETER Credential
        Credential object used to connect to the computer as a different user.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Privilege
        Author: Klaas Vandenberghe (@PowerDBAKlaas)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaPrivilege

    .EXAMPLE
        PS C:\> Get-DbaPrivilege -ComputerName sqlserver2014a

        Gets the local privileges on computer sqlserver2014a.

    .EXAMPLE
        PS C:\> 'sql1','sql2','sql3' | Get-DbaPrivilege

        Gets the local privileges on computers sql1, sql2 and sql3.

    .EXAMPLE
        PS C:\> Get-DbaPrivilege -ComputerName sql1,sql2 | Out-GridView

        Gets the local privileges on computers sql1 and sql2, and shows them in a grid view.

             #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [Alias("cn", "host", "Server")]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [switch][Alias('Silent')]
        $EnableException
    )

    begin {
        $ResolveSID = @"
    function Convert-SIDToUserName ([string] `$SID ) {
      `$objSID = New-Object System.Security.Principal.SecurityIdentifier (`"`$SID`")
      `$objUser = `$objSID.Translate( [System.Security.Principal.NTAccount])
      `$objUser.Value
    }
"@
        $ComputerName = $ComputerName.ComputerName | Select-Object -Unique
    }
    process {
        foreach ($computer in $ComputerName) {
            try {
                $null = Test-PSRemoting -ComputerName $Computer -EnableException
            } catch {
                Stop-Function -Message "Failure on $computer" -ErrorRecord $_ -Continue
            }

            try {
                Write-Message -Level Verbose -Message "Getting Privileges on $Computer"
                $Priv = $null
                $Priv = Invoke-Command2 -Raw -ComputerName $computer -Credential $Credential -ScriptBlock {
                    $temp = ([System.IO.Path]::GetTempPath()).TrimEnd(""); secedit /export /cfg $temp\secpolByDbatools.cfg > $NULL;
                    Get-Content $temp\secpolByDbatools.cfg | Where-Object {
                        $_ -match "SeBatchLogonRight" -or $_ -match 'SeManageVolumePrivilege' -or $_ -match 'SeLockMemoryPrivilege'
                    }
                }
                if ($Priv.count -eq 0) {
                    Write-Message -Level Verbose -Message "No users with Batch Logon, Instant File Initialization, or Lock Pages in Memory Rights on $computer"
                }

                Write-Message -Level Verbose -Message "Getting Batch Logon Privileges on $Computer"
                $BL = Invoke-Command2 -Raw -ComputerName $computer -Credential $Credential -ArgumentList $ResolveSID -ScriptBlock {
                    param ($ResolveSID)
                    . ([ScriptBlock]::Create($ResolveSID))
                    $temp = ([System.IO.Path]::GetTempPath()).TrimEnd("");
                    $blEntries = (Get-Content $temp\secpolByDbatools.cfg | Where-Object {
                            $_ -like "SeBatchLogonRight*"
                        })

                    if ($null -ne $blEntries) {
                        $blEntries.substring(20).split(",").replace("`*", "") | ForEach-Object {
                            Convert-SIDToUserName -SID $_
                        }
                    }

                } -ErrorAction SilentlyContinue
                if ($BL.count -eq 0) {
                    Write-Message -Level Verbose -Message "No users with Batch Logon Rights on $computer"
                }

                Write-Message -Level Verbose -Message "Getting Instant File Initialization Privileges on $Computer"
                $ifi = Invoke-Command2 -Raw -ComputerName $computer -Credential $Credential -ArgumentList $ResolveSID -ScriptBlock {
                    param ($ResolveSID)
                    . ([ScriptBlock]::Create($ResolveSID))
                    $temp = ([System.IO.Path]::GetTempPath()).TrimEnd("");
                    $ifiEntries = (Get-Content $temp\secpolByDbatools.cfg | Where-Object {
                            $_ -like 'SeManageVolumePrivilege*'
                        })

                    if ($null -ne $ifiEntries) {
                        $ifiEntries.substring(26).split(",").replace("`*", "") | ForEach-Object {
                            Convert-SIDToUserName -SID $_
                        }
                    }

                } -ErrorAction SilentlyContinue
                if ($ifi.count -eq 0) {
                    Write-Message -Level Verbose -Message "No users with Instant File Initialization Rights on $computer"
                }

                Write-Message -Level Verbose -Message "Getting Lock Pages in Memory Privileges on $Computer"
                $lpim = Invoke-Command2 -Raw -ComputerName $computer -Credential $Credential -ArgumentList $ResolveSID -ScriptBlock {
                    param ($ResolveSID)
                    . ([ScriptBlock]::Create($ResolveSID))
                    $temp = ([System.IO.Path]::GetTempPath()).TrimEnd("");
                    $lpimEntries = (Get-Content $temp\secpolByDbatools.cfg | Where-Object {
                            $_ -like 'SeLockMemoryPrivilege*'
                        })

                    if ($null -ne $lpimEntries) {
                        $lpimEntries.substring(24).split(",").replace("`*", "") | ForEach-Object {
                            Convert-SIDToUserName -SID $_
                        }
                    }
                } -ErrorAction SilentlyContinue

                if ($lpim.count -eq 0) {
                    Write-Message -Level Verbose -Message "No users with Lock Pages in Memory Rights on $computer"
                }
                $users = @() + $BL + $ifi + $lpim | Select-Object -Unique
                $users | ForEach-Object {
                    [PSCustomObject]@{
                        ComputerName              = $computer
                        User                      = $_
                        LogonAsBatch              = $BL -contains $_
                        InstantFileInitialization = $ifi -contains $_
                        LockPagesInMemory         = $lpim -contains $_
                    }
                }
                Write-Message -Level Verbose -Message "Removing secpol file on $computer"
                Invoke-Command2 -Raw -ComputerName $computer -Credential $Credential -ScriptBlock {
                    $temp = ([System.IO.Path]::GetTempPath()).TrimEnd(""); Remove-Item $temp\secpolByDbatools.cfg -Force > $NULL
                }
            } catch {
                Stop-Function -Continue -Message "Failure" -ErrorRecord $_ -Target $computer
            }
        }
    }
}
tools\dbatools\functions\Get-DbaProcess.ps1
function Get-DbaProcess {
    <#
    .SYNOPSIS
        This command displays SQL Server processes.

    .DESCRIPTION
        This command displays processes associated with a spid, login, host, program or database.

        Thanks to Michael J Swart at https://sqlperformance.com/2017/07/sql-performance/find-database-connection-leaks for the query to get the last executed SQL statement, minutesasleep and host process ID.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Spid
        Specifies one or more process IDs (Spid) to be displayed. Options for this parameter are auto-populated from the server.

    .PARAMETER Login
        Specifies one or more Login names with active processes to look for. Options for this parameter are auto-populated from the server.

    .PARAMETER Hostname
        Specifies one or more hostnames with active processes to look for. Options for this parameter are auto-populated from the server.

    .PARAMETER Program
        Specifies one or more program names with active processes to look for. Options for this parameter are auto-populated from the server.

    .PARAMETER Database
        Specifies one or more databases with active processes to look for. Options for this parameter are auto-populated from the server.

    .PARAMETER ExcludeSpid
        Specifies one ore more process IDs to exclude from display. Options for this parameter are auto-populated from the server.

        This is the last filter to run, so even if a Spid matches another filter, it will be excluded by this filter.

    .PARAMETER ExcludeSystemSpids
        If this switch is enabled, system Spids will be ignored.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Process, Session, ActivityMonitor
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaProcess

    .EXAMPLE
        PS C:\> Get-DbaProcess -SqlInstance sqlserver2014a -Login base\ctrlb, sa

        Shows information about the processes for base\ctrlb and sa on sqlserver2014a. Windows Authentication is used in connecting to sqlserver2014a.

    .EXAMPLE
        PS C:\> Get-DbaProcess -SqlInstance sqlserver2014a -SqlCredential $credential -Spid 56, 77

        Shows information about the processes for spid 56 and 57. Uses alternative (SQL or Windows) credentials to authenticate to sqlserver2014a.

    .EXAMPLE
        PS C:\> Get-DbaProcess -SqlInstance sqlserver2014a -Program 'Microsoft SQL Server Management Studio'

        Shows information about the processes that were created in Microsoft SQL Server Management Studio.

    .EXAMPLE
        PS C:\> Get-DbaProcess -SqlInstance sqlserver2014a -Host workstationx, server100

        Shows information about the processes that were initiated by hosts (computers/clients) workstationx and server 1000.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [int[]]$Spid,
        [int[]]$ExcludeSpid,
        [string[]]$Database,
        [string[]]$Login,
        [string[]]$Hostname,
        [string[]]$Program,
        [switch]$ExcludeSystemSpids,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $sqlinstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Could not connect to Sql Server instance $instance : $_" -Target $instance -ErrorRecord $_ -Continue
            }

            $sql = "SELECT DATEDIFF(MINUTE, s.last_request_end_time, GETDATE()) AS MinutesAsleep,
                s.session_id AS spid,
                s.host_process_id AS HostProcessId,
                t.text AS Query,
                s.login_time AS LoginTime,
                s.client_version AS ClientVersion,
                s.last_request_start_time AS LastRequestStartTime,
                s.last_request_end_time AS LastRequestEndTime,
                c.net_transport AS NetTransport,
                c.encrypt_option AS EncryptOption,
                c.auth_scheme AS AuthScheme,
                c.net_packet_size AS NetPacketSize,
                c.client_net_address AS ClientNetAddress
            FROM sys.dm_exec_connections c
            JOIN sys.dm_exec_sessions s
                on c.session_id = s.session_id
            CROSS APPLY sys.dm_exec_sql_text(c.most_recent_sql_handle) t"

            if ($server.VersionMajor -gt 8) {
                $results = $server.Query($sql)
            } else {
                $results = $null
            }

            $allsessions = @()

            $processes = $server.EnumProcesses()

            if ($Login) {
                $allsessions += $processes | Where-Object { $_.Login -in $Login -and $_.Spid -notin $allsessions.Spid }
            }

            if ($Spid) {
                $allsessions += $processes | Where-Object { ($_.Spid -in $Spid -or $_.BlockingSpid -in $Spid) -and $_.Spid -notin $allsessions.Spid }
            }

            if ($Hostname) {
                $allsessions += $processes | Where-Object { $_.Host -in $Hostname -and $_.Spid -notin $allsessions.Spid }
            }

            if ($Program) {
                $allsessions += $processes | Where-Object { $_.Program -in $Program -and $_.Spid -notin $allsessions.Spid }
            }

            if ($Database) {
                $allsessions += $processes | Where-Object { $Database -contains $_.Database -and $_.Spid -notin $allsessions.Spid }
            }

            if (Test-Bound -not 'Login', 'Spid', 'ExcludeSpid', 'Hostname', 'Program', 'Database') {
                $allsessions = $processes
            }

            if ($ExcludeSystemSpids -eq $true) {
                $allsessions = $allsessions | Where-Object { $_.Spid -gt 50 }
            }

            if ($Exclude) {
                $allsessions = $allsessions | Where-Object { $Exclude -notcontains $_.SPID -and $_.Spid -notin $allsessions.Spid }
            }

            foreach ($session in $allsessions) {

                if ($session.Status -eq "") {
                    $status = "sleeping"
                } else {
                    $status = $session.Status
                }

                if ($session.Command -eq "") {
                    $command = "AWAITING COMMAND"
                } else {
                    $command = $session.Command
                }

                $row = $results | Where-Object { $_.Spid -eq $session.Spid }

                Add-Member -Force -InputObject $session -MemberType NoteProperty -Name Parent -value $server
                Add-Member -Force -InputObject $session -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                Add-Member -Force -InputObject $session -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                Add-Member -Force -InputObject $session -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                Add-Member -Force -InputObject $session -MemberType NoteProperty -Name Status -value $status
                Add-Member -Force -InputObject $session -MemberType NoteProperty -Name Command -value $command
                Add-Member -Force -InputObject $session -MemberType NoteProperty -Name HostProcessId -value $row.HostProcessId
                Add-Member -Force -InputObject $session -MemberType NoteProperty -Name MinutesAsleep -value $row.MinutesAsleep
                Add-Member -Force -InputObject $session -MemberType NoteProperty -Name LoginTime -value $row.LoginTime
                Add-Member -Force -InputObject $session -MemberType NoteProperty -Name ClientVersion -value $row.ClientVersion
                Add-Member -Force -InputObject $session -MemberType NoteProperty -Name LastRequestStartTime -value $row.LastRequestStartTime
                Add-Member -Force -InputObject $session -MemberType NoteProperty -Name LastRequestEndTime -value $row.LastRequestEndTime
                Add-Member -Force -InputObject $session -MemberType NoteProperty -Name NetTransport -value $row.NetTransport
                Add-Member -Force -InputObject $session -MemberType NoteProperty -Name EncryptOption -value $row.EncryptOption
                Add-Member -Force -InputObject $session -MemberType NoteProperty -Name AuthScheme -value $row.AuthScheme
                Add-Member -Force -InputObject $session -MemberType NoteProperty -Name NetPacketSize -value $row.NetPacketSize
                Add-Member -Force -InputObject $session -MemberType NoteProperty -Name ClientNetAddress -value $row.ClientNetAddress
                Add-Member -Force -InputObject $session -MemberType NoteProperty -Name LastQuery -value $row.Query

                Select-DefaultView -InputObject $session -Property ComputerName, InstanceName, SqlInstance, Spid, Login, LoginTime, Host, Database, BlockingSpid, Program, Status, Command, Cpu, MemUsage, LastRequestStartTime, LastRequestEndTime, MinutesAsleep, ClientNetAddress, NetTransport, EncryptOption, AuthScheme, NetPacketSize, ClientVersion, HostProcessId, IsSystem, LastQuery
            }
        }
    }
}
tools\dbatools\functions\Get-DbaProductKey.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Get-DbaProductKey {
    <#
    .SYNOPSIS
        Gets SQL Server Product Keys from local or destination SQL Servers. Works with SQL Server 2005-2017

    .DESCRIPTION
        This command find the product key for all installed instances. Clustered instances are supported as well.

        Uses key decoder by Jakob Bindslet (http://goo.gl/1jiwcB)

    .PARAMETER ComputerName
        The target SQL Server instance or instances.

    .PARAMETER Credential
        Login to the target Windows instance using alternative credentials. Windows Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER SqlCredential
        This command logs into the SQL instance to gather additional information.

        Use this parameter to connect to the discovered SQL instances using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ProductKey
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaProductKey

    .EXAMPLE
        PS C:\> Get-DbaProductKey -ComputerName winxp, sqlservera, sqlserver2014a, win2k8

        Gets SQL Server versions, editions and product keys for all instances within each server or workstation.

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline, Mandatory)]
        [Alias("SqlInstance")]
        [DbaInstanceParameter[]]$ComputerName,
        [PSCredential]$SqlCredential,
        [PSCredential]$Credential,
        [switch]$EnableException
    )

    begin {
        $scriptblock = {
            $versionMajor = $args[0]
            $instanceReg = $args[1]
            $edition = $args[2]

            Function Unlock-SqlInstanceKey {
                [CmdletBinding()]
                param (
                    [Parameter(Mandatory)]
                    [byte[]]$data,
                    [int]$version
                )
                try {
                    if ($version -ge 11) {
                        $binArray = ($data)[0 .. 66]
                    } else {
                        $binArray = ($data)[52 .. 66]
                    }
                    $charsArray = "B", "C", "D", "F", "G", "H", "J", "K", "M", "P", "Q", "R", "T", "V", "W", "X", "Y", "2", "3", "4", "6", "7", "8", "9"
                    for ($i = 24; $i -ge 0; $i--) {
                        $k = 0
                        for ($j = 14; $j -ge 0; $j--) {
                            $k = $k * 256 -bxor $binArray[$j]
                            $binArray[$j] = [math]::truncate($k / 24)
                            $k = $k % 24
                        }
                        $productKey = $charsArray[$k] + $productKey
                        if (($i % 5 -eq 0) -and ($i -ne 0)) {
                            $productKey = "-" + $productKey
                        }
                    }
                } catch {
                    $productkey = "Cannot decode product key."
                }
                return $productKey
            }
            $localmachine = [Microsoft.Win32.RegistryHive]::LocalMachine
            $defaultview = [Microsoft.Win32.RegistryView]::Default
            $reg = [Microsoft.Win32.RegistryKey]::OpenBaseKey($localmachine, $defaultview)

            switch ($versionMajor) {
                9 {
                    $sqlversion = "SQL Server 2005 $servicePack"
                    $findkeys = $reg.OpenSubKey("$($instanceReg.Path)\ProductID", $false)
                    foreach ($findkey in $findkeys.GetValueNames()) {
                        if ($findkey -like "DigitalProductID*") {
                            $key = @("$($instanceReg.Path)\ProductID\$findkey")
                        }
                    }
                }
                10 {
                    $sqlversion = "SQL Server 2008 $servicePack"
                    if ($server.VersionMinor -eq 50) {
                        $sqlversion = "SQL Server 2008 R2 $servicePack"
                    }
                    $key = @("$($instanceReg.Path)\Setup\DigitalProductID")
                }
                11 {
                    $key = @("$($instanceReg.Path)\Setup\DigitalProductID", "$($instanceReg.Path)\ClientSetup\DigitalProductID")
                    $sqlversion = "SQL Server 2012 $servicePack"
                }
                12 {
                    $key = @("$($instanceReg.Path)\Setup\DigitalProductID", "$($instanceReg.Path)\ClientSetup\DigitalProductID")
                    $sqlversion = "SQL Server 2014 $servicePack"
                }
                13 {
                    $key = @("$($instanceReg.Path)\Setup\DigitalProductID", "$($instanceReg.Path)\ClientSetup\DigitalProductID")
                    $sqlversion = "SQL Server 2016 $servicePack"
                }
                14 {
                    $key = @("$($instanceReg.Path)\Setup\DigitalProductID", "$($instanceReg.Path)\ClientSetup\DigitalProductID")
                    $sqlversion = "SQL Server 2017 $servicePack"
                }
                default {
                    Stop-Function -Message "SQL version not currently supported." -Continue
                }
            }
            if ($edition -notlike "*Express*") {
                $sqlkey = ''
                foreach ($k in $key) {
                    $subkey = Split-Path $k
                    $binaryvalue = Split-Path $k -Leaf
                    try {
                        $binarykey = $($reg.OpenSubKey($subkey)).GetValue($binaryvalue)
                        break
                    } catch {
                        $binarykey = $null
                    }
                }

                if ($null -eq $binarykey) {
                    $sqlkey = "Could not read Product Key from registry on $env:COMPUTERNAME"
                } else {
                    try {
                        $sqlkey = Unlock-SqlInstanceKey $binarykey $versionMajor
                    } catch {
                        $sqlkey = "Unable to unlock key"
                    }
                }
            } else {
                $sqlkey = "SQL Server Express Edition"
            }

            [pscustomobject]@{
                Version = $sqlversion
                Key     = $sqlkey
            }
            $reg.Close()
        }
    }

    process {
        foreach ($computer in $ComputerName) {
            try {
                $registryroot = Get-DbaRegistryRoot -ComputerName $computer.ComputerName -EnableException
            } catch {
                Stop-Function -Message "Can't access registry for $($computer.ComputerName). Is the Remote Registry service started?" -Continue
            }

            if (-not $registryroot) {
                Stop-Function -Message "No instances found on $($computer.ComputerName)" -Continue
            }

            # Get Product Keys for all instances on the server.
            foreach ($instanceReg in $registryroot) {
                try {
                    $server = Connect-SqlInstance -SqlInstance $instanceReg.SqlInstance -SqlCredential $SqlCredential -MinimumVersion 10
                } catch {
                    Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instanceReg.SqlInstance -Continue
                }

                $servicePack = $server.ProductLevel
                $versionMajor = $server.VersionMajor
                Write-Message -Level Debug -Message "$instance $instanceName version is $($server.VersionMajor)"

                try {
                    $results = Invoke-Command2 -ComputerName $computer.ComputerName -Credential $Credential -ScriptBlock $scriptblock -ArgumentList $server.VersionMajor, $instanceReg, $server.Edition
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_
                }

                [pscustomobject]@{
                    ComputerName = $server.ComputerName
                    InstanceName = $server.ServiceName
                    SqlInstance  = $server.DomainInstanceName
                    Version      = $results.Version
                    Edition      = $server.Edition
                    Key          = $results.Key
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-SqlServerKey
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaSqlProductKey
    }
}
tools\dbatools\functions\Get-DbaQueryExecutionTime.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaQueryExecutionTime {
    <#
    .SYNOPSIS
        Displays Stored Procedures and Ad hoc queries with the highest execution times.  Works on SQL Server 2008 and above.

    .DESCRIPTION
        Quickly find slow query executions within a database.  Results will include stored procedures and individual SQL statements.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER MaxResultsPerDb
        Allows you to limit the number of results returned, as many systems can have very large amounts of query plans.  Default value is 100 results.

    .PARAMETER MinExecs
        Allows you to limit the scope to queries that have been executed a minimum number of time. Default value is 100 executions.

    .PARAMETER MinExecMs
        Allows you to limit the scope to queries with a specified average execution time.  Default value is 500 (ms).

    .PARAMETER ExcludeSystem
        Allows you to suppress output on system databases

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Query, Performance
        Author: Brandon Abshire, netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaQueryExecutionTime

    .EXAMPLE
        PS C:\> Get-DbaQueryExecutionTime -SqlInstance sql2008, sqlserver2012

        Return the top 100 slowest stored procedures or statements for servers sql2008 and sqlserver2012.

    .EXAMPLE
        PS C:\> Get-DbaQueryExecutionTime -SqlInstance sql2008 -Database TestDB

        Return the top 100 slowest stored procedures or statements on server sql2008 for only the TestDB database.

    .EXAMPLE
        PS C:\> Get-DbaQueryExecutionTime -SqlInstance sql2008 -Database TestDB -MaxResultsPerDb 100 -MinExecs 200 -MinExecMs 1000

        Return the top 100 slowest stored procedures or statements on server sql2008 for only the TestDB database, limiting results to queries with more than 200 total executions and an execution time over 1000ms or higher.

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]
        $SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [parameter(Position = 1)]
        [int]$MaxResultsPerDb = 100,
        [parameter(Position = 2)]
        [int]$MinExecs = 100,
        [parameter(Position = 3)]
        [int]$MinExecMs = 500,
        [parameter(Position = 4)]
        [Alias("ExcludeSystemDatabases")]
        [switch]$ExcludeSystem,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $sql = ";With StatsCTE AS
            (
                SELECT
                    DB_NAME() as DatabaseName,
                    (total_worker_time / execution_count) / 1000 AS AvgExec_ms ,
                    execution_count ,
                    max_worker_time / 1000 AS MaxExec_ms ,
                    OBJECT_NAME(object_id) as ProcName,
                    object_id,
                    type_desc,
                    cached_time,
                    last_execution_time,
                    total_worker_time / 1000 as total_worker_time_ms,
                    total_elapsed_time / 1000 as total_elapsed_time_ms,
                    OBJECT_NAME(object_id) as SQLText,
                    OBJECT_NAME(object_id) as full_statement_text
                FROM    sys.dm_exec_procedure_stats
                WHERE   database_id = DB_ID()"

        if ($MinExecs) { $sql += "`n AND execution_count >= " + $MinExecs }
        if ($MinExecMs) { $sql += "`n AND (total_worker_time / execution_count) / 1000 >= " + $MinExecMs }

        $sql += "`n UNION
            SELECT
                DB_NAME() as DatabaseName,
                ( qs.total_worker_time / qs.execution_count ) / 1000 AS AvgExec_ms ,
                qs.execution_count ,
                qs.max_worker_time / 1000 AS MaxExec_ms ,
                OBJECT_NAME(st.objectid) as ProcName,
                   st.objectid as [object_id],
                   'STATEMENT' as type_desc,
                   '1901-01-01 00:00:00' as cached_time,
                    qs.last_execution_time,
                    qs.total_worker_time / 1000 as total_worker_time_ms,
                    qs.total_elapsed_time / 1000 as total_elapsed_time_ms,
                    SUBSTRING(st.text, (qs.statement_start_offset/2)+1, 50) + '...' AS SQLText,
                    SUBSTRING(st.text, (qs.statement_start_offset/2)+1,
                        ((CASE qs.statement_end_offset
                          WHEN -1 THEN DATALENGTH(st.text)
                         ELSE qs.statement_end_offset
                         END - qs.statement_start_offset)/2) + 1) AS full_statement_text
            FROM    sys.dm_exec_query_stats qs
            CROSS APPLY sys.dm_exec_plan_attributes(qs.plan_handle) as pa
            CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) as st
            WHERE st.dbid = DB_ID() OR (pa.attribute = 'dbid' and pa.value = DB_ID())"

        if ($MinExecs) { $sql += "`n AND execution_count >= " + $MinExecs }
        if ($MinExecMs) { $sql += "`n AND (total_worker_time / execution_count) / 1000 >= " + $MinExecMs }

        if ($MaxResultsPerDb) { $sql += ")`n SELECT TOP " + $MaxResultsPerDb }
        else {
            $sql += ")
                        SELECT "
        }

        $sql += "`n     DatabaseName,
                        AvgExec_ms,
                        execution_count,
                        MaxExec_ms,
                        ProcName,
                        object_id,
                        type_desc,
                        cached_time,
                        last_execution_time,
                        total_worker_time_ms,
                        total_elapsed_time_ms,
                        SQLText,
                        full_statement_text
                    FROM StatsCTE "

        if ($MinExecs -or $MinExecMs) {
            $sql += "`n WHERE `n"

            if ($MinExecs) {
                $sql += " execution_count >= " + $MinExecs
            }

            if ($MinExecMs -gt 0 -and $MinExecs) {
                $sql += "`n AND AvgExec_ms >= " + $MinExecMs
            } elseif ($MinExecMs) {
                $sql += "`n AvgExecs_ms >= " + $MinExecMs
            }
        }

        $sql += "`n ORDER BY AvgExec_ms DESC"
    }
    process {
        if (!$MaxResultsPerDb -and !$MinExecs -and !$MinExecMs) {
            Write-Message -Level Warning -Message "Results may take time, depending on system resources and size of buffer cache."
            Write-Message -Level Warning -Message "Consider limiting results using -MaxResultsPerDb, -MinExecs and -MinExecMs parameters."
        }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $dbs = $server.Databases
            if ($Database) {
                $dbs = $dbs | Where-Object Name -In $Database
            }

            if ($ExcludeSystem) {
                $dbs = $dbs | Where-Object { $_.IsSystemObject -eq $false }
            }

            if ($ExcludeDatabase) {
                $dbs = $dbs | Where-Object Name -NotIn $ExcludeDatabase
            }

            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Processing $db on $instance"

                if ($db.IsAccessible -eq $false) {
                    Write-Message -Level Warning -Message "The database $db is not accessible. Skipping database."
                    continue
                }

                try {
                    foreach ($row in $db.ExecuteWithResults($sql).Tables.Rows) {
                        [PSCustomObject]@{
                            ComputerName       = $server.ComputerName
                            InstanceName       = $server.ServiceName
                            SqlInstance        = $server.DomainInstanceName
                            Database           = $row.DatabaseName
                            ProcName           = $row.ProcName
                            ObjectID           = $row.object_id
                            TypeDesc           = $row.type_desc
                            Executions         = $row.Execution_Count
                            AvgExecMs          = $row.AvgExec_ms
                            MaxExecMs          = $row.MaxExec_ms
                            CachedTime         = $row.cached_time
                            LastExecTime       = $row.last_execution_time
                            TotalWorkerTimeMs  = $row.total_worker_time_ms
                            TotalElapsedTimeMs = $row.total_elapsed_time_ms
                            SQLText            = $row.SQLText
                            FullStatementText  = $row.full_statement_text
                        } | Select-DefaultView -ExcludeProperty FullStatementText
                    }
                } catch {
                    Stop-Function -Message "Could not process $db on $instance" -Target $db -ErrorRecord $_ -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaRegistryRoot.ps1
function Get-DbaRegistryRoot {
    <#
    .SYNOPSIS
        Uses SQL WMI to find the Registry Root of each SQL Server instance on a computer

    .DESCRIPTION
        Uses SQL WMI to find the Registry Root of each SQL Server instance on a computer

    .PARAMETER ComputerName
        The target computer. This is not a SQL Server service, though if you pass a named SQL instance, it'll parse properly down to the computer name

    .PARAMETER Credential
        Allows you to login to $ComputerName using alternative Windows credentials

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Configuration, Registry
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaRegistryRoot

        Gets the registry root for all instances on localhost

    .EXAMPLE
        PS C:\> Get-DbaRegistryRoot -ComputerName server1

        Gets the registry root for all instances on server1

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($computer in $computername) {
            try {
                $sqlwmis = Invoke-ManagedComputerCommand -ComputerName $computer.ComputerName -ScriptBlock { $wmi.Services } -Credential $Credential -ErrorAction Stop | Where-Object DisplayName -match "SQL Server \("
            } catch {
                Stop-Function -Message $_ -Target $sqlwmi -Continue
            }

            foreach ($sqlwmi in $sqlwmis) {

                $regroot = ($sqlwmi.AdvancedProperties | Where-Object Name -eq REGROOT).Value
                $vsname = ($sqlwmi.AdvancedProperties | Where-Object Name -eq VSNAME).Value
                $instancename = $sqlwmi.DisplayName.Replace('SQL Server (', '').Replace(')', '') # Don't clown, I don't know regex :(

                if ([System.String]::IsNullOrEmpty($regroot)) {
                    $regroot = $sqlwmi.AdvancedProperties | Where-Object { $_ -match 'REGROOT' }
                    $vsname = $sqlwmi.AdvancedProperties | Where-Object { $_ -match 'VSNAME' }

                    if (![System.String]::IsNullOrEmpty($regroot)) {
                        $regroot = ($regroot -Split 'Value\=')[1]
                        $vsname = ($vsname -Split 'Value\=')[1]
                    } else {
                        Write-Message -Level Warning -Message "Can't find instance $vsname on $env:COMPUTERNAME"
                        return
                    }
                }

                # vsname takes care of clusters
                if ([System.String]::IsNullOrEmpty($vsname)) {
                    $vsname = $computer
                    if ($instancename -ne "MSSQLSERVER") {
                        $vsname = "$($computer.ComputerName)\$instancename"
                    }
                }

                Write-Message -Level Verbose -Message "Regroot: $regroot"
                Write-Message -Level Verbose -Message "InstanceName: $instancename"
                Write-Message -Level Verbose -Message "VSNAME: $vsname"

                [PSCustomObject]@{
                    ComputerName = $computer.ComputerName
                    InstanceName = $instancename
                    SqlInstance  = $vsname
                    Hive         = "HKLM"
                    Path         = $regroot
                    RegistryRoot = "HKLM:\$regroot"
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaSqlRegistryRoot
    }
}
tools\dbatools\functions\Get-DbaRepDistributor.ps1
function Get-DbaRepDistributor {
    <#
    .SYNOPSIS
        Gets the information about a replication distributor for a given SQL Server instance.

    .DESCRIPTION
        This function locates and enumerates distributor information for a given SQL Server instance.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Replication
        Author: William Durkin (@sql_williamd)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaRepDistributor

    .EXAMPLE
        PS C:\> Get-DbaRepDistributor -SqlInstance sql2008, sqlserver2012

        Retrieve distributor information for servers sql2008 and sqlserver2012.

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstanceParameter[]]$SqlInstance,
        [parameter(Position = 1)]
        [PSCredential]$SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        if ($null -eq [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.RMO")) {
            Stop-Function -Message "Replication management objects not available. Please install SQL Server Management Studio."
        }
    }

    process {
        if (Test-FunctionInterrupt) { return }

        foreach ($instance in $SqlInstance) {

            # connect to the instance
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            Write-Message -Level Verbose -Message "Attempting to retrieve distributor information from $instance"

            # Connect to the distributor of the instance
            try {
                $sourceSqlConn = $server.ConnectionContext.SqlConnectionObject
                $distributor = New-Object Microsoft.SqlServer.Replication.ReplicationServer $sourceSqlConn
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            Add-Member -Force -InputObject $distributor -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName
            Add-Member -Force -InputObject $distributor -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName
            Add-Member -Force -InputObject $distributor -MemberType NoteProperty -Name SqlInstance -Value $server.DomainInstanceName

            Select-DefaultView -InputObject $distributor -Property ComputerName, InstanceName, SqlInstance, IsPublisher, IsDistributor, DistributionServer, DistributionDatabase, DistributorInstalled, DistributorAvailable, HasRemotePublisher
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaDistributor
    }
}
tools\dbatools\functions\Get-DbaRepPublication.ps1
function Get-DbaRepPublication {
    <#
    .SYNOPSIS
        Displays all publications for a server or database.

    .DESCRIPTION
        Quickly find all transactional, merge, and snapshot publications on a specific server or database.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER Database
        The database(s) to process. If unspecified, all databases will be processed.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER PublicationType
        Limit by specific type of publication. Valid choices include: Transactional, Merge, Snapshot

    .PARAMETER EnableException
        byng this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Replication
        Author: Colin Douglas

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaRepPublication

    .EXAMPLE
        PS C:\> Get-DbaRepPublication -SqlInstance sql2008, sqlserver2012

        Return all publications for servers sql2008 and sqlserver2012.

    .EXAMPLE
        PS C:\> Get-DbaRepPublication -SqlInstance sql2008 -Database TestDB

        Return all publications on server sql2008 for only the TestDB database

    .EXAMPLE
        PS C:\> Get-DbaRepPublication -SqlInstance sql2008 -PublicationType Transactional

        Return all publications on server sql2008 for all databases that have Transactional publications

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [object[]]$Database,
        [PSCredential]$SqlCredential,
        [ValidateSet("Transactional", "Merge", "Snapshot")]
        [object[]]$PublicationType,
        [switch]$EnableException
    )

    process {

        foreach ($instance in $SqlInstance) {

            # Connect to Publisher
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $dbList = $server.Databases

            if ($Database) {
                $dbList = $dbList | Where-Object name -in $Database
            }

            $dbList = $dbList | Where-Object { ($_.ID -gt 4) -and ($_.status -ne "Offline") }


            foreach ($db in $dbList) {

                if (($db.ReplicationOptions -ne "Published") -and ($db.ReplicationOptions -ne "MergePublished")) {
                    Write-Message -Level Verbose -Message "Skipping $($db.name). Database is not published."
                }

                $repDB = Connect-ReplicationDB -Server $server -Database $db

                $pubTypes = $repDB.TransPublications + $repDB.MergePublications

                if ($PublicationType) {
                    $pubTypes = $pubTypes | Where-Object Type -in $PublicationType
                }

                foreach ($pub in $pubTypes) {

                    [PSCustomObject]@{
                        ComputerName    = $server.ComputerName
                        InstanceName    = $server.InstanceName
                        SqlInstance     = $server.SqlInstance
                        Server          = $server.name
                        Database        = $db.name
                        PublicationName = $pub.Name
                        PublicationType = $pub.Type
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaRepServer.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaRepServer {
    <#
    .SYNOPSIS
        Gets a replication server object

    .DESCRIPTION
        Gets a replication server object

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Replication
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaRepServer -SqlInstance sql2016

        Gets the replication server object for sql2016 using Windows authentication

    .EXAMPLE
        PS C:\> Get-DbaRepServer -SqlInstance sql2016 -SqlCredential repadmin

        Gets the replication server object for sql2016 using SQL authentication

    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
                New-Object Microsoft.SqlServer.Replication.ReplicationServer $server.ConnectionContext.SqlConnectionObject
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
        }
    }
}
tools\dbatools\functions\Get-DbaResourceGovernor.ps1
function Get-DbaResourceGovernor {
    <#
    .SYNOPSIS
        Gets the Resource Governor object

    .DESCRIPTION
        Gets the Resource Governor object

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Allows you to login to SQL Server using alternative credentials

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ResourceGovernor
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaResourceGovernor

    .EXAMPLE
        PS C:\> Get-DbaResourceGovernor -SqlInstance sql2016

        Gets the resource governor object of the SqlInstance sql2016

    .EXAMPLE
        PS C:\> 'Sql1','Sql2/sqlexpress' | Get-DbaResourceGovernor

        Gets the resource governor object on Sql1 and Sql2/sqlexpress instances

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $resourcegov = $server.ResourceGovernor

            if ($resourcegov) {
                Add-Member -Force -InputObject $resourcegov -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                Add-Member -Force -InputObject $resourcegov -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                Add-Member -Force -InputObject $resourcegov -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
            }

            Select-DefaultView -InputObject $resourcegov -Property ComputerName, InstanceName, SqlInstance, ClassifierFunction, Enabled, MaxOutstandingIOPerVolume, ReconfigurePending, ResourcePools, ExternalResourcePools
        }
    }
}
tools\dbatools\functions\Get-DbaRgClassifierFunction.ps1
function Get-DbaRgClassifierFunction {
    <#
    .SYNOPSIS
        Gets the Resource Governor custom classifier Function

    .DESCRIPTION
        Gets the Resource Governor custom classifier Function which is used for customize the workload groups usage

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Allows you to login to SQL Server using alternative credentials

    .PARAMETER InputObject
        Allows input to be piped from Get-DbaResourceGovernor

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration, ResourceGovernor
        Author: Alessandro Alpi (@suxstellino), alessandroalpi.blog

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaRgClassifierFunction

    .EXAMPLE
        PS C:\> Get-DbaRgClassifierFunction -SqlInstance sql2016

        Gets the classifier function from sql2016

    .EXAMPLE
        PS C:\> 'Sql1','Sql2/sqlexpress' | Get-DbaResourceGovernor | Get-DbaRgClassifierFunction

        Gets the classifier function object on Sql1 and Sql2/sqlexpress instances

    #>
    [CmdletBinding()]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.ResourceGovernor[]]$InputObject,
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaResourceGovernor -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        }

        foreach ($resourcegov in $InputObject) {
            $server = $resourcegov.Parent
            $classifierFunction = $null

            foreach ($currentFunction in $server.Databases["master"].UserDefinedFunctions) {
                $fullyQualifiedFunctionName = [string]::Format("[{0}].[{1}]", $currentFunction.Schema, $currentFunction.Name)
                if ($fullyQualifiedFunctionName -eq $InputObject.ClassifierFunction) {
                    $classifierFunction = $currentFunction
                }
            }

            if ($classifierFunction) {
                Add-Member -Force -InputObject $classifierFunction -MemberType NoteProperty -Name ComputerName -value $resourcegov.ComputerName
                Add-Member -Force -InputObject $classifierFunction -MemberType NoteProperty -Name InstanceName -value $resourcegov.InstanceName
                Add-Member -Force -InputObject $classifierFunction -MemberType NoteProperty -Name SqlInstance -value $resourcegov.SqlInstance
                Add-Member -Force -InputObject $classifierFunction -MemberType NoteProperty -Name Database -value 'master'
            }

            Select-DefaultView -InputObject $classifierFunction -Property ComputerName, InstanceName, SqlInstance, Database, Schema, CreateDate, DateLastModified, Name, DataType
        }
    }
}
tools\dbatools\functions\Get-DbaRgResourcePool.ps1
function Get-DbaRgResourcePool {
    <#
    .SYNOPSIS
        Gets Resource Governor Pool objects, including internal or external

    .DESCRIPTION
        Gets Resource Governor Pool objects, including internal or external

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Allows you to login to SQL Server using alternative credentials

    .PARAMETER InputObject
        Allows input to be piped from Get-DbaResourceGovernor

    .PARAMETER Type
        Internal or External

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ResourceGovernor
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaRgResourcePool

    .EXAMPLE
        PS C:\> Get-DbaRgResourcePool -SqlInstance sql2016

        Gets the internal resource pools on sql2016

    .EXAMPLE
        PS C:\> 'Sql1','Sql2/sqlexpress' | Get-DbaResourceGovernor | Get-DbaRgResourcePool

        Gets the internal resource pools on Sql1 and Sql2/sqlexpress instances

    .EXAMPLE
        PS C:\> 'Sql1','Sql2/sqlexpress' | Get-DbaResourceGovernor | Get-DbaRgResourcePool -Type External

        Gets the external resource pools on Sql1 and Sql2/sqlexpress instances


    #>
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [ValidateSet("Internal", "External")]
        [string]$Type = "Internal",
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.ResourceGovernor[]]$InputObject,
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaResourceGovernor -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        }

        foreach ($resourcegov in $InputObject) {
            if ($Type -eq "External") {
                $respool = $resourcegov.ExternalResourcePools
                if ($respool) {
                    $respool | Add-Member -Force -MemberType NoteProperty -Name ComputerName -value $resourcegov.ComputerName
                    $respool | Add-Member -Force -MemberType NoteProperty -Name InstanceName -value $resourcegov.InstanceName
                    $respool | Add-Member -Force -MemberType NoteProperty -Name SqlInstance -value $resourcegov.SqlInstance
                    $respool | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, Id, Name, CapCpuPercentage, IsSystemObject, MaximumCpuPercentage, MaximumIopsPerVolume, MaximumMemoryPercentage, MinimumCpuPercentage, MinimumIopsPerVolume, MinimumMemoryPercentage, WorkloadGroups
                }
            } else {
                $respool = $resourcegov.ResourcePools
                if ($respool) {
                    $respool | Add-Member -Force -MemberType NoteProperty -Name ComputerName -value $resourcegov.ComputerName
                    $respool | Add-Member -Force -MemberType NoteProperty -Name InstanceName -value $resourcegov.InstanceName
                    $respool | Add-Member -Force -MemberType NoteProperty -Name SqlInstance -value $resourcegov.SqlInstance
                    $respool | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, Id, Name, CapCpuPercentage, IsSystemObject, MaximumCpuPercentage, MaximumIopsPerVolume, MaximumMemoryPercentage, MinimumCpuPercentage, MinimumIopsPerVolume, MinimumMemoryPercentage, WorkloadGroups
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaRgWorkloadGroup.ps1
function Get-DbaRgWorkloadGroup {
    <#
    .SYNOPSIS
        Gets all Resource Governor Pool objects, including both internal and external

    .DESCRIPTION
        Gets all Resource Governor Pool objects, including both internal and external

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Allows you to login to SQL Server using alternative credentials

    .PARAMETER InputObject
        Allows input to be piped from Get-DbaRgResourcePool

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ResourceGovernor
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaRgWorkloadGroup

    .EXAMPLE
        PS C:\> Get-DbaRgWorkloadGroup -SqlInstance sql2017

        Gets the workload groups on sql2017

    .EXAMPLE
        PS C:\> Get-DbaResourceGovernor -SqlInstance sql2017 | Get-DbaRgResourcePool | Get-DbaRgWorkloadGroup

        Gets the workload groups on sql2017

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.ResourcePool[]]$InputObject,
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaRgResourcePool -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        }

        foreach ($pool in $InputObject) {
            $group = $pool.WorkloadGroups
            if ($group) {
                $group | Add-Member -Force -MemberType NoteProperty -Name ComputerName -value $pool.ComputerName
                $group | Add-Member -Force -MemberType NoteProperty -Name InstanceName -value $pool.InstanceName
                $group | Add-Member -Force -MemberType NoteProperty -Name SqlInstance -value $pool.SqlInstance
                $group | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, Id, Name, ExternalResourcePoolName, GroupMaximumRequests, Importance, IsSystemObject, MaximumDegreeOfParallelism, RequestMaximumCpuTimeInSeconds, RequestMaximumMemoryGrantPercentage, RequestMemoryGrantTimeoutInSeconds
            }
        }
    }
}
tools\dbatools\functions\Get-DbaRunningJob.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Get-DbaRunningJob {
    <#
    .SYNOPSIS
        Returns all non-idle Agent jobs running on the server

    .DESCRIPTION
        This function returns agent jobs that active on the SQL Server instance when calling the command

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER InputObject
        Enables piped input from Get-DbaAgentJob

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Job
        Author: Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaRunningJob

    .EXAMPLE
        PS C:\> Get-DbaRunningJob -SqlInstance sql2017

        Returns any active jobs on sql2017

    .EXAMPLE
        PS C:\> Get-DbaAgentJob -SqlInstance sql2017, sql2019 | Get-DbaRunningJob

        Returns all active jobs on multiple instances piped into the function.

    .EXAMPLE
        PS C:\> $servers | Get-DbaRunningJob

        Returns all active jobs on multiple instances piped into the function.

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Agent.Job[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ($SqlInstance) {
            Get-DbaAgentJob -SqlInstance $SqlInstance -SqlCredential $SqlCredential | Where-Object CurrentRunStatus -ne 'Idle'
        }

        $InputObject | Where-Object CurrentRunStatus -ne 'Idle'
    }
}
tools\dbatools\functions\Get-DbaSchemaChangeHistory.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaSchemaChangeHistory {
    <#
    .SYNOPSIS
        Gets DDL changes logged in the system trace.

    .DESCRIPTION
        Queries the default system trace for any DDL changes in the specified time frame
        Only works with SQL 2005 and later, as the system trace didn't exist before then

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER Since
        A date from which DDL changes should be returned. Default is to start at the beginning of the current trace file

    .PARAMETER Object
        The name of a SQL Server object you want to look for changes on

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration, Backup, Database
        Author: Stuart Moore (@napalmgram - http://stuart-moore.com)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaSchemaChangeHistory

    .EXAMPLE
        PS C:\> Get-DbaSchemaChangeHistory -SqlInstance localhost

        Returns all DDL changes made in all databases on the SQL Server instance localhost since the system trace began

    .EXAMPLE
        PS C:\> Get-DbaSchemaChangeHistory -SqlInstance localhost -Since (Get-Date).AddDays(-7)

        Returns all DDL changes made in all databases on the SQL Server instance localhost in the last 7 days

    .EXAMPLE
        PS C:\> Get-DbaSchemaChangeHistory -SqlInstance localhost -Database Finance, Prod -Since (Get-Date).AddDays(-7)

        Returns all DDL changes made in the Prod and Finance databases on the SQL Server instance localhost in the last 7 days

    .EXAMPLE
        PS C:\> Get-DbaSchemaChangeHistory -SqlInstance localhost -Database Finance -Object AccountsTable -Since (Get-Date).AddDays(-7)

        Returns all DDL changes made  to the AccountsTable object in the Finance database on the SQL Server instance localhost in the last 7 days

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]
        $SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [DbaDateTime]$Since,
        [string[]]$Object,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            if ($Server.Version.Major -le 8) {
                Stop-Function -Message "This command doesn't support SQL Server 2000, sorry about that"
                return
            }
            $TraceFileQuery = "select path from sys.traces where is_default = 1"

            $TraceFile = $server.Query($TraceFileQuery) | Select-Object Path

            $Databases = $server.Databases

            if ($Database) { $Databases = $Databases | Where-Object Name -in $database }

            if ($ExcludeDatabase) { $Databases = $Databases | Where-Object Name -notin $ExcludeDatabase }

            foreach ($db in $Databases) {
                if ($db.IsAccessible -eq $false) {
                    Write-Message -Level Verbose -Message "$($db.name) is not accessible, skipping"
                }

                $sql = "select SERVERPROPERTY('MachineName') AS ComputerName,
                        ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
                        SERVERPROPERTY('ServerName') AS SqlInstance,
                        tt.databasename as 'DatabaseName',
                        starttime as 'DateModified',
                        Sessionloginname as 'LoginName',
                        NTusername as 'UserName',
                        applicationname as 'ApplicationName',
                        case eventclass
                            When '46' Then 'Create'
                            when '47' Then 'Drop'
                            when '164' then 'Alter'
                        end as 'DDLOperation',
                        s.name+'.'+o.name as 'Object',
                        o.type_desc as 'ObjectType'
                        from
                        sys.objects o  inner join
                        sys.schemas s on s.schema_id=o.schema_id
                        cross apply (select * from ::fn_trace_gettable('$($TraceFile.path)',default) where ObjectID=o.object_id ) tt
                        where tt.objecttype not in (21587)
                        and tt.DatabaseID=db_id()
                        and tt.EventSubClass=0"

                if ($null -ne $since) {
                    $sql = $sql + " and tt.StartTime>'$Since' "
                }
                if ($null -ne $object) {
                    $sql = $sql + " and o.name in ('$($object -join ''',''')') "
                }

                $sql = $sql + " order by tt.StartTime asc"
                Write-Message -Level Verbose -Message "Querying Database $db on $instance"
                Write-Message -Level Debug -Message "SQL: $sql"

                $db.Query($sql) | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, DatabaseName, DateModified, LoginName, UserName, ApplicationName, DDLOperation, Object, ObjectType
            }
        }
    }
}
tools\dbatools\functions\Get-DbaServerAudit.ps1
function Get-DbaServerAudit {
    <#
    .SYNOPSIS
        Gets SQL Security Audit information for each instance(s) of SQL Server.

    .DESCRIPTION
        The Get-DbaServerAudit command gets SQL Security Audit information for each instance(s) of SQL Server.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function
        to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Audit
        Return only specific audits

    .PARAMETER ExcludeAudit
        Exclude specific audits

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Audit, Security, SqlAudit
        Author: Garry Bargsley (@gbargsley), http://blog.garrybargsley.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaServerAudit

    .EXAMPLE
        PS C:\> Get-DbaServerAudit -SqlInstance localhost

        Returns all Security Audits on the local default SQL Server instance

    .EXAMPLE
        PS C:\> Get-DbaServerAudit -SqlInstance localhost, sql2016

        Returns all Security Audits for the local and sql2016 SQL Server instances

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [string[]]$Audit,
        [string[]]$ExcludeAudit,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $audits = $server.Audits

            if (Test-Bound -ParameterName Audit) {
                $audits = $audits | Where-Object Name -in $Audit
            }
            if (Test-Bound -ParameterName ExcludeAudit) {
                $audits = $audits | Where-Object Name -notin $ExcludeAudit
            }

            foreach ($currentaudit in $audits) {
                $directory = $currentaudit.FilePath.TrimEnd("\")
                $filename = $currentaudit.FileName
                $fullname = "$directory\$filename"
                $remote = $fullname.Replace(":", "$")
                $remote = "\\$($currentaudit.Parent.ComputerName)\$remote"

                Add-Member -Force -InputObject $currentaudit -MemberType NoteProperty -Name ComputerName -value $currentaudit.Parent.ComputerName
                Add-Member -Force -InputObject $currentaudit -MemberType NoteProperty -Name InstanceName -value $currentaudit.Parent.ServiceName
                Add-Member -Force -InputObject $currentaudit -MemberType NoteProperty -Name SqlInstance -value $currentaudit.Parent.DomainInstanceName
                Add-Member -Force -InputObject $currentaudit -MemberType NoteProperty -Name FullName -value $fullname
                Add-Member -Force -InputObject $currentaudit -MemberType NoteProperty -Name RemoteFullName -value $remote

                Select-DefaultView -InputObject $currentaudit -Property ComputerName, InstanceName, SqlInstance, Name, 'Enabled as IsEnabled', FullName
            }
        }
    }
}
tools\dbatools\functions\Get-DbaServerAuditSpecification.ps1
function Get-DbaServerAuditSpecification {
    <#
    .SYNOPSIS
        Gets SQL Security Audit Specification information for each instance(s) of SQL Server.

    .DESCRIPTION
        The Get-DbaServerAuditSpecification command gets SQL Security Audit Specification information for each instance(s) of SQL Server.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function
        to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Audit, Security, SqlAudit
        Author: Garry Bargsley (@gbargsley), http://blog.garrybargsley.com

        dbatools PowerShell module (https://dbatools.io, [email protected])
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaServerAuditSpecification

    .EXAMPLE
        PS C:\> Get-DbaServerAuditSpecification -SqlInstance localhost

        Returns all Security Audit Specifications on the local default SQL Server instance

    .EXAMPLE
        PS C:\> Get-DbaServerAuditSpecification -SqlInstance localhost, sql2016

        Returns all Security Audit Specifications for the local and sql2016 SQL Server instances

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            foreach ($auditSpecification in $server.ServerAuditSpecifications) {
                Add-Member -Force -InputObject $auditSpecification -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                Add-Member -Force -InputObject $auditSpecification -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                Add-Member -Force -InputObject $auditSpecification -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName

                Select-DefaultView -InputObject $auditSpecification -Property ComputerName, InstanceName, SqlInstance, ID, Name, AuditName, Enabled, CreateDate, DateLastModified, Guid
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-SqlServerAuditSpecification
    }
}
tools\dbatools\functions\Get-DbaServerInstallDate.ps1
function Get-DbaServerInstallDate {
    <#
    .SYNOPSIS
        Returns the install date of a SQL Instance and Windows Server.

    .DESCRIPTION
        This command returns:
        SqlInstallDate
        WindowsInstallDate (use -IncludeWindows)

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Credential object used to connect to the SQL Server using SQL Authentication as a different user

    .PARAMETER Credential
        Credential object used to connect to the SQL Server as a different Windows user

    .PARAMETER IncludeWindows
        Includes the Windows Server Install date information

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Install
        Author: Mitchell Hamann (@SirCaptainMitch), mitchellhamann.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaServerInstallDate

    .EXAMPLE
        PS C:\> Get-DbaServerInstallDate -SqlInstance SqlBox1\Instance2

        Returns an object with SQL Instance Install date as a string.

    .EXAMPLE
        PS C:\> Get-DbaServerInstallDate -SqlInstance winserver\sqlexpress, sql2016

        Returns an object with SQL Instance Install date as a string for both SQLInstances that are passed to the cmdlet.

    .EXAMPLE
        PS C:\> 'sqlserver2014a', 'sql2016' | Get-DbaServerInstallDate

        Returns an object with SQL Instance Install date as a string for both SQLInstances that are passed to the cmdlet via the pipeline.

    .EXAMPLE
        PS C:\> Get-DbaServerInstallDate -SqlInstance sqlserver2014a, sql2016 -IncludeWindows

        Returns an object with the Windows Install date and the SQL install date as a string.

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sql2014 | Get-DbaServerInstallDate

        Returns an object with SQL Instance install date as a string for every server listed in the Central Management Server on sql2014

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "ComputerName")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]
        $SqlCredential,
        [PSCredential]
        $Credential,
        [Switch]$IncludeWindows,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failed to process Instance $Instance" -ErrorRecord $_ -Target $instance -Continue
            }

            if ($server.VersionMajor -ge 9) {
                Write-Message -Level Verbose -Message "Getting Install Date for: $instance"
                $sql = "SELECT create_date FROM sys.server_principals WHERE sid = 0x010100000000000512000000"
                [DbaDateTime]$sqlInstallDate = $server.Query($sql, 'master', $true).create_date

            } else {
                Write-Message -Level Verbose -Message "Getting Install Date for: $instance"
                $sql = "SELECT schemadate FROM sysservers"
                [DbaDateTime]$sqlInstallDate = $server.Query($sql, 'master', $true).create_date
            }

            $WindowsServerName = $server.ComputerNamePhysicalNetBIOS

            if ($IncludeWindows) {
                try {
                    [DbaDateTime]$windowsInstallDate = (Get-DbaCmObject -ClassName win32_OperatingSystem -ComputerName $WindowsServerName -Credential $Credential -EnableException).InstallDate
                } catch {
                    Stop-Function -Message "Failed to connect to: $WindowsServerName" -Continue -Target $instance -ErrorRecord $_
                }
            }

            $object = [PSCustomObject]@{
                ComputerName       = $server.ComputerName
                InstanceName       = $server.ServiceName
                SqlInstance        = $server.DomainInstanceName
                SqlInstallDate     = $sqlInstallDate
                WindowsInstallDate = $windowsInstallDate
            }

            if ($IncludeWindows) {
                Select-DefaultView -InputObject $object -Property ComputerName, InstanceName, SqlInstance, SqlInstallDate, WindowsInstallDate
            } else {
                Select-DefaultView -InputObject $object -Property ComputerName, InstanceName, SqlInstance, SqlInstallDate
            }

        }
    }
}
tools\dbatools\functions\Get-DbaServerProtocol.ps1
function Get-DbaServerProtocol {
    <#
    .SYNOPSIS
        Gets the SQL Server related server protocols on a computer.

    .DESCRIPTION
        Gets the SQL Server related server protocols on one or more computers.

        Requires Local Admin rights on destination computer(s).
        The server protocols can be enabled and disabled when retrieved via WSMan.

    .PARAMETER ComputerName
        The target SQL Server instance or instances.

    .PARAMETER Credential
        Credential object used to connect to the computer as a different user.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Protocol
        Author: Klaas Vandenberghe ( @PowerDBAKlaas )

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaServerProtocol

    .EXAMPLE
        PS C:\> Get-DbaServerProtocol -ComputerName sqlserver2014a

        Gets the SQL Server related server protocols on computer sqlserver2014a.

    .EXAMPLE
        PS C:\> 'sql1','sql2','sql3' | Get-DbaServerProtocol

        Gets the SQL Server related server protocols on computers sql1, sql2 and sql3.

    .EXAMPLE
        PS C:\> Get-DbaServerProtocol -ComputerName sql1,sql2 | Out-GridView

        Gets the SQL Server related server protocols on computers sql1 and sql2, and shows them in a grid view.

    .EXAMPLE
        PS C:\> (Get-DbaServerProtocol -ComputerName sql1 | Where { $_.DisplayName = 'via' }).Disable()

        Disables the VIA ServerNetworkProtocol on computer sql1.
        If successful, return code 0 is shown.

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [Alias("cn", "host", "Server")]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($Computer in $ComputerName.ComputerName) {
            $Server = Resolve-DbaNetworkName -ComputerName $Computer -Credential $credential
            if ($Server.FullComputerName) {
                $Computer = $server.FullComputerName
                Write-Message -Level Verbose -Message "Getting SQL Server namespace on $computer"
                $namespace = Get-DbaCmObject -ComputerName $Computer -NameSpace root\Microsoft\SQLServer -Query "Select * FROM __NAMESPACE WHERE Name Like 'ComputerManagement%'" -ErrorAction SilentlyContinue |
                    Where-Object { (Get-DbaCmObject -ComputerName $Computer -Namespace $("root\Microsoft\SQLServer\" + $_.Name) -ClassName ServerNetworkProtocol -ErrorAction SilentlyContinue).count -gt 0 } |
                    Sort-Object Name -Descending | Select-Object -First 1
                if ($namespace.Name) {
                    Write-Message -Level Verbose -Message "Getting Cim class ServerNetworkProtocol in Namespace $($namespace.Name) on $Computer"
                    try {
                        $prot = Get-DbaCmObject -ComputerName $Computer -Namespace $("root\Microsoft\SQLServer\" + $namespace.Name) -ClassName ServerNetworkProtocol -ErrorAction SilentlyContinue
                        $prot | Add-Member -Force -MemberType ScriptMethod -Name Enable -Value { Invoke-CimMethod -MethodName SetEnable -InputObject $this }
                        $prot | Add-Member -Force -MemberType ScriptMethod -Name Disable -Value { Invoke-CimMethod -MethodName SetDisable -InputObject $this }
                        foreach ($protocol in $prot) { Select-DefaultView -InputObject $protocol -Property 'PSComputerName as ComputerName', 'InstanceName', 'ProtocolDisplayName as DisplayName', 'ProtocolName as Name', 'MultiIpconfigurationSupport as MultiIP', 'Enabled as IsEnabled' }
                    } catch {
                        Write-Message -Level Warning -Message "No Sql ServerNetworkProtocol found on $Computer"
                    }
                } else {
                    Write-Message -Level Warning -Message "No ComputerManagement Namespace on $Computer. Please note that this function is available from SQL 2005 up."
                }
            } else {
                Write-Message -Level Warning -Message "Failed to connect to $Computer"
            }
        }
    }
}
tools\dbatools\functions\Get-DbaServerRole.ps1
function Get-DbaServerRole {
    <#
    .SYNOPSIS
        Gets the list of server-level roles.

    .DESCRIPTION
        Gets the list of server-level roles for SQL Server instance.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server version must be SQL Server version 2005 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER ServerRole
        Server-Level role to filter results to that role only.

    .PARAMETER ExcludeServerRole
        Server-Level role to exclude from results.

    .PARAMETER ExcludeFixedRole
        Filter the fixed server-level roles. Only applies to SQL Server 2017 that supports creation of server-level roles.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ServerRole, Security
        Author: Shawn Melton (@wsmelton)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaServerRole

    .EXAMPLE
        PS C:\> Get-DbaServerRole -SqlInstance sql2016a

        Outputs list of server-level roles for sql2016a instance.

    .EXAMPLE
        PS C:\> Get-DbaServerRole -SqlInstance sql2017a -ExcludeFixedRole

        Outputs the server-level role(s) that are not fixed roles on sql2017a instance.

    #>
    [CmdletBinding()]
    param (
        [Parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$ServerRole,
        [string[]]$ExcludeServerRole,
        [switch]$ExcludeFixedRole,
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $serverroles = $server.Roles

            if ($ServerRole) {
                $serverroles = $serverroles | Where-Object Name -In $ServerRole
            }
            if ($ExcludeServerRole) {
                $serverroles = $serverroles | Where-Object Name -NotIn $ExcludeServerRole
            }
            if ($ExcludeFixedRole) {
                $serverroles = $serverroles | Where-Object IsFixedRole -eq $false
            }

            foreach ($role in $serverroles) {
                $members = $role.EnumMemberNames()

                Add-Member -Force -InputObject $role -MemberType NoteProperty -Name Login -Value $members
                Add-Member -Force -InputObject $role -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                Add-Member -Force -InputObject $role -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                Add-Member -Force -InputObject $role -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName

                $default = 'ComputerName', 'InstanceName', 'SqlInstance', 'Name as Role', 'IsFixedRole', 'DateCreated', 'DateModified'
                Select-DefaultView -InputObject $role -Property $default
            }
        }
    }
}
tools\dbatools\functions\Get-DbaServerRoleMember.ps1
function Get-DbaServerRoleMember {
    <#
    .SYNOPSIS
        Get members of server roles for each instance(s) of SQL Server.

    .DESCRIPTION
        The Get-DbaServerRoleMember returns connected SMO object for server roles for each instance(s) of SQL Server.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternate Windows or SQL Login Authentication. Accepts credential objects (Get-Credential).

    .PARAMETER ServerRole
        The role(s) to process. If unspecified, all roles will be processed.

    .PARAMETER ExcludeServerRole
        The role(s) to exclude.

    .PARAMETER Login
        The login(s) to process. If unspecified, all logins will be processed.

    .PARAMETER ExcludeFixedRole
        Filter the fixed server-level roles. Only applies to SQL Server 2017 that supports creation of server-level roles.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ServerRole, Security, Login
        Author: Klaas Vandenberghe (@PowerDBAKlaas)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaServerRoleMember

    .EXAMPLE
        PS C:\> Get-DbaServerRoleMember -SqlInstance localhost

        Returns all members of all server roles on the local default SQL Server instance

    .EXAMPLE
        PS C:\> Get-DbaServerRoleMember -SqlInstance localhost, sql2016

        Returns all members of all server roles on the local and sql2016 SQL Server instances

    .EXAMPLE
        PS C:\> $servers = Get-Content C:\servers.txt
        PS C:\> $servers | Get-DbaServerRoleMember

        Returns all members of all server roles for every server in C:\servers.txt

    .EXAMPLE
        PS C:\> Get-DbaServerRoleMember -SqlInstance localhost -ServerRole 'sysadmin', 'dbcreator'

        Returns all members of the sysadmin or dbcreator roles on localhost.

    .EXAMPLE
        PS C:\> Get-DbaServerRoleMember -SqlInstance localhost -ExcludeServerRole 'sysadmin'

        Returns all members of server-level roles other than sysadmin.

    .EXAMPLE
        PS C:\> Get-DbaServerRoleMember -SqlInstance sql2017a -ExcludeFixedRole

        Returns all members of server-level role(s) that are not fixed roles on sql2017a instance.

    .EXAMPLE
        PS C:\> Get-DbaServerRoleMember -SqlInstance localhost -Login 'MyFriendlyDeveloper'

        Returns all server-level role(s) for the MyFriendlyDeveloper login on localhost.

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias('ServerInstance', 'SqlServer')]
        [DbaInstance[]]$SqlInstance,
        [Alias('Credential')]
        [PSCredential]$SqlCredential,
        [string[]]$ServerRole,
        [string[]]$ExcludeServerRole,
        [object[]]$Login,
        [switch]$ExcludeFixedRole,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            Write-Message -Level Verbose -Message "Attempting to connect to $instance"

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message 'Failure' -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $roles = $server.Roles

            if (Test-Bound -ParameterName 'Login') {
                $logins = Get-DbaLogin -SqlInstance $instance -Login $Login
                Write-Message -Level 'Verbose' -Message "Filtering by logins: $($logins -join ', ')"

                foreach ($l in $logins) {
                    $loginRoles += $l.ListMembers()
                }

                $loginRoles = $loginRoles | Select-Object -Unique
                Write-Message -Level 'Verbose' -Message "Filtering by roles: $($loginRoles -join ', ')"

                $roles = $roles | Where-Object { $_.Name -in $loginRoles }
            }

            if (Test-Bound -ParameterName 'ServerRole') {
                $roles = $roles | Where-Object { $_.Name -in $ServerRole }
            }

            if (Test-Bound -ParameterName 'ExcludeServerRole') {
                $roles = $roles | Where-Object { $_.Name -notin $ExcludeServerRole }
            }

            if (Test-Bound -ParameterName 'ExcludeFixedRole') {
                $roles = $roles | Where-Object { $_.IsFixedRole -eq $false }
            }

            foreach ($role in $roles) {
                Write-Message -Level 'Verbose' -Message "Getting Server Role Members for $role on $instance"

                $members = $role.EnumMemberNames()
                Write-Message -Level 'Verbose' -Message "$role members: $($members -join ', ')"

                if (Test-Bound -ParameterName 'Login') {
                    Write-Message -Level 'Verbose' -Message "Only returning results for $($logins.Name -join ', ')"
                    $members = $members | Where-Object { $_ -in $logins.Name }
                }

                foreach ($member in $members) {
                    $l = $server.Logins | Where-Object { $_.Name -eq $member }

                    if ($l) {
                        Add-Member -Force -InputObject $l -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName
                        Add-Member -Force -InputObject $l -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName
                        Add-Member -Force -InputObject $l -MemberType NoteProperty -Name SqlInstance -Value $server.DomainInstanceName
                        Add-Member -Force -InputObject $l -MemberType NoteProperty -Name Role -Value $role.Name

                        # Select object because Select-DefaultView causes strange behaviors when assigned to a variable (??)
                        Select-Object -InputObject $l -Property 'ComputerName', 'InstanceName', 'SqlInstance', 'Role', 'Name'
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaServerTrigger.ps1
function Get-DbaServerTrigger {
    <#
    .SYNOPSIS
        Get all existing server triggers on one or more SQL instances.

    .DESCRIPTION
        Get all existing server triggers on one or more SQL instances.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        SqlCredential object used to connect to the SQL Server as a different user.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database, Trigger
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaServerTrigger

    .EXAMPLE
        PS C:\> Get-DbaServerTrigger -SqlInstance sql2017

        Returns all server triggers on sql2017

    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )

    process {
        foreach ($Instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            foreach ($trigger in $server.Triggers) {
                try {
                    Add-Member -Force -InputObject $trigger -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                    Add-Member -Force -InputObject $trigger -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                    Add-Member -Force -InputObject $trigger -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                    Select-DefaultView -InputObject $trigger -Property ComputerName, InstanceName, SqlInstance, ID, Name, AnsiNullsStatus, AssemblyName, BodyStartIndex, ClassName, CreateDate, DateLastModified, DdlTriggerEvents, ExecutionContext, ExecutionContextLogin, ImplementationType, IsDesignMode, IsEnabled, IsEncrypted, IsSystemObject, MethodName, QuotedIdentifierStatus, State, TextHeader, TextMode
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaService.ps1
function Get-DbaService {
    <#
    .SYNOPSIS
        Gets the SQL Server related services on a computer.

    .DESCRIPTION
        Gets the SQL Server related services on one or more computers.

        Requires Local Admin rights on destination computer(s).

    .PARAMETER ComputerName
        The target SQL Server instance or instances.

    .PARAMETER InstanceName
        Only returns services that belong to the specific instances.

    .PARAMETER Credential
        Credential object used to connect to the computer as a different user.

    .PARAMETER Type
        Use -Type to collect only services of the desired SqlServiceType.
        Can be one of the following: "Agent","Browser","Engine","FullText","SSAS","SSIS","SSRS", "PolyBase"

    .PARAMETER ServiceName
        Can be used to specify service names explicitly, without looking for service types/instances.

    .PARAMETER AdvancedProperties
        Collect additional properties from the SqlServiceAdvancedProperty Namespace
        This collects information about Version, Service Pack Level", SkuName, Clustered status and the Cluster Service Name
        This adds additional overhead to the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Service, SqlServer, Instance, Connect
        Author: Klaas Vandenberghe ( @PowerDBAKlaas )

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaService

    .EXAMPLE
        PS C:\> Get-DbaService -ComputerName sqlserver2014a

        Gets the SQL Server related services on computer sqlserver2014a.

    .EXAMPLE
        PS C:\> 'sql1','sql2','sql3' | Get-DbaService -AdvancedProperties

        Gets the SQL Server related services on computers sql1, sql2 and sql3. Includes Advanced Properties from the SqlServiceAdvancedProperty Namespace

    .EXAMPLE
        PS C:\> $cred = Get-Credential WindowsUser
        PS C:\> Get-DbaService -ComputerName sql1,sql2 -Credential $cred  | Out-GridView

        Gets the SQL Server related services on computers sql1 and sql2 via the user WindowsUser, and shows them in a grid view.

    .EXAMPLE
        PS C:\> Get-DbaService -ComputerName sql1,sql2 -InstanceName MSSQLSERVER

        Gets the SQL Server related services related to the default instance MSSQLSERVER on computers sql1 and sql2.

    .EXAMPLE
        PS C:\> Get-DbaService -ComputerName $MyServers -Type SSRS

        Gets the SQL Server related services of type "SSRS" (Reporting Services) on computers in the variable MyServers.

    .EXAMPLE
        PS C:\> $MyServers =  Get-Content .\servers.txt
        PS C:\> Get-DbaService -ComputerName $MyServers -ServiceName MSSQLSERVER,SQLSERVERAGENT

        Gets the SQL Server related services with ServiceName MSSQLSERVER or SQLSERVERAGENT  for all the servers that are stored in the file. Every line in the file can only contain one hostname for a server.

    .EXAMPLE
        PS C:\> $services = Get-DbaService -ComputerName sql1 -Type Agent,Engine
        PS C:\> $services.ChangeStartMode('Manual')

        Gets the SQL Server related services of types Sql Agent and DB Engine on computer sql1 and changes their startup mode to 'Manual'.

    .EXAMPLE
        PS C:\> (Get-DbaService -ComputerName sql1 -Type Engine).Restart($true)

        Calls a Restart method for each Engine service on computer sql1.

    #>
    [CmdletBinding(DefaultParameterSetName = "Search")]
    param (
        [parameter(ValueFromPipeline, Position = 1)]
        [Alias("cn", "host", "Server")]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [Parameter(ParameterSetName = "Search")]
        [Alias("Instance")]
        [string[]]$InstanceName,
        [PSCredential]$Credential,
        [Parameter(ParameterSetName = "Search")]
        [ValidateSet("Agent", "Browser", "Engine", "FullText", "SSAS", "SSIS", "SSRS", "PolyBase")]
        [string[]]$Type,
        [Parameter(ParameterSetName = "ServiceName")]
        [string[]]$ServiceName,
        [switch]$AdvancedProperties,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        #Dictionary to transform service type IDs into the names from Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer.Services.Type
        $ServiceIdMap = @(
            @{ Name = "Engine"; Id = 1 },
            @{ Name = "Agent"; Id = 2 },
            @{ Name = "FullText"; Id = 3, 9 },
            @{ Name = "SSIS"; Id = 4 },
            @{ Name = "SSAS"; Id = 5 },
            @{ Name = "SSRS"; Id = 6 },
            @{ Name = "Browser"; Id = 7 },
            @{ Name = "PolyBase"; Id = 10, 11 },
            @{ Name = "Unknown"; Id = 8 }
        )
        if ($PsCmdlet.ParameterSetName -match 'Search') {
            if ($Type) {
                $searchClause = ""
                foreach ($itemType in $Type) {
                    foreach ($id in ($ServiceIdMap | Where-Object { $_.Name -eq $itemType }).Id) {
                        if ($searchClause) { $searchClause += ' OR ' }
                        $searchClause += "SQLServiceType = $id"
                    }
                }
            } else {
                $searchClause = "SQLServiceType > 0"
            }
        } elseif ($PsCmdlet.ParameterSetName -match 'ServiceName') {
            if ($ServiceName) {
                $searchClause = ""
                foreach ($sn in $ServiceName) {
                    if ($searchClause) { $searchClause += ' OR ' }
                    $searchClause += "ServiceName = '$sn'"
                }
            } else {
                $searchClause = "SQLServiceType > 0"
            }
        }
    }
    process {
        foreach ($Computer in $ComputerName.ComputerName) {
            $Server = Resolve-DbaNetworkName -ComputerName $Computer -Credential $credential
            if ($Server.FullComputerName) {
                $Computer = $server.FullComputerName
                $outputServices = @()
                if (!$Type -or 'SSRS' -in $Type) {
                    Write-Message -Level Verbose -Message "Getting SQL Reporting Server services on $Computer" -Target $Computer
                    $reportingServices = Get-DbaReportingService -ComputerName $Computer -InstanceName $InstanceName -Credential $Credential -ServiceName $ServiceName
                    $outputServices += $reportingServices
                }
                Write-Message -Level Verbose -Message "Getting SQL Server namespace on $Computer" -Target $Computer
                try { $namespaces = Get-DbaCmObject -ComputerName $Computer -NameSpace root\Microsoft\SQLServer -Query "Select Name FROM __NAMESPACE WHERE Name Like 'ComputerManagement%'" -EnableException -Credential $credential | Sort-Object Name -Descending }
                catch {
                    # here to avoid an empty catch
                    $null = 1
                }
                if ($namespaces) {
                    $servicesTemp = @()

                    ForEach ($namespace in $namespaces) {
                        try {
                            Write-Message -Level Verbose -Message "Getting Cim class SqlService in Namespace $($namespace.Name) on $Computer." -Target $Computer
                            foreach ($service in (Get-DbaCmObject -ComputerName $Computer -Namespace "root\Microsoft\SQLServer\$($namespace.Name)" -Query "SELECT * FROM SqlService WHERE $searchClause" -EnableException -Credential $credential)) {
                                $servicesTemp += New-Object PSObject -Property @{
                                    Name      = $service.ServiceName
                                    Namespace = $namespace.Name
                                    Service   = $service
                                }
                            }
                        } catch {
                            Write-Message -Level Verbose -Message "Failed to acquire services from namespace $($namespace.Name)." -Target $Computer -ErrorRecord $_
                        }
                    }
                }
                #use highest namespace available
                $services = ($servicesTemp | Group-Object Name | ForEach-Object { $_.Group | Sort-Object Namespace -Descending | Select-Object -First 1 }).Service
                #remove services returned by the SSRS namespace
                $services = $services | Where-Object ServiceName -notin $reportingServices.ServiceName
                #Add custom properties and methods to the service objects
                ForEach ($service in $services) {
                    Add-Member -Force -InputObject $service -MemberType NoteProperty -Name ComputerName -Value $service.HostName
                    Add-Member -Force -InputObject $service -MemberType NoteProperty -Name ServiceType -Value ($ServiceIdMap | Where-Object { $_.Id -contains $service.SQLServiceType }).Name
                    Add-Member -Force -InputObject $service -MemberType NoteProperty -Name State -Value $(switch ($service.State) { 1 { 'Stopped' } 2 { 'Start Pending' }  3 { 'Stop Pending' } 4 { 'Running' } })
                    Add-Member -Force -InputObject $service -MemberType NoteProperty -Name StartMode -Value $(switch ($service.StartMode) { 1 { 'Unknown' } 2 { 'Automatic' }  3 { 'Manual' } 4 { 'Disabled' } })

                    if ($service.ServiceName -in ("MSSQLSERVER", "SQLSERVERAGENT", "ReportServer", "MSSQLServerOLAPService")) {
                        $instance = "MSSQLSERVER"
                    } else {
                        if ($service.ServiceType -in @("Agent", "Engine", "SSRS", "SSAS")) {
                            if ($service.ServiceName.indexof('$') -ge 0) {
                                $instance = $service.ServiceName.split('$')[1]
                            } else {
                                $instance = "Unknown"
                            }
                        } else {
                            $instance = ""
                        }
                    }
                    $priority = switch ($service.ServiceType) {
                        "Engine" { 200 }
                        default { 100 }
                    }
                    #If only specific instances are selected
                    if (!$InstanceName -or $instance -in $InstanceName) {
                        #Add other properties and methods
                        Add-Member -Force -InputObject $service -NotePropertyName InstanceName -NotePropertyValue $instance
                        Add-Member -Force -InputObject $service -NotePropertyName ServicePriority -NotePropertyValue $priority
                        Add-Member -Force -InputObject $service -MemberType ScriptMethod -Name "Stop" -Value {
                            param ([bool]$Force = $false)
                            Stop-DbaService -InputObject $this -Force:$Force
                        }
                        Add-Member -Force -InputObject $service -MemberType ScriptMethod -Name "Start" -Value { Start-DbaService -InputObject $this }
                        Add-Member -Force -InputObject $service -MemberType ScriptMethod -Name "Restart" -Value {
                            param ([bool]$Force = $false)
                            Restart-DbaService -InputObject $this -Force:$Force
                        }
                        Add-Member -Force -InputObject $service -MemberType ScriptMethod -Name "ChangeStartMode" -Value {
                            param (
                                [parameter(Mandatory)]
                                [string]$Mode
                            )
                            $supportedModes = @("Automatic", "Manual", "Disabled")
                            if ($Mode -notin $supportedModes) {
                                Stop-Function -Message ("Incorrect mode '$Mode'. Use one of the following values: {0}" -f ($supportedModes -join ' | ')) -EnableException $false -FunctionName 'Get-DbaService'
                                Return
                            }
                            Set-ServiceStartMode -InputObject $this -Mode $Mode -ErrorAction Stop
                            $this.StartMode = $Mode
                        }

                        if ($AdvancedProperties) {
                            $namespaceValue = $service.CimClass.ToString().ToUpper().Replace(":SQLSERVICE", "").Replace("ROOT/MICROSOFT/SQLSERVER/", "")
                            $serviceAdvancedProperties = Get-DbaCmObject -ComputerName $Computer -Namespace "root\Microsoft\SQLServer\$($namespaceValue)" -Query "SELECT * FROM SqlServiceAdvancedProperty WHERE ServiceName = '$($service.ServiceName)'"

                            Add-Member -Force -InputObject $service -MemberType NoteProperty -Name Version -Value ($serviceAdvancedProperties | Where-Object PropertyName -eq 'VERSION' ).PropertyStrValue
                            Add-Member -Force -InputObject $service -MemberType NoteProperty -Name SPLevel -Value ($serviceAdvancedProperties | Where-Object PropertyName -eq 'SPLEVEL' ).PropertyNumValue
                            Add-Member -Force -InputObject $service -MemberType NoteProperty -Name SkuName -Value ($serviceAdvancedProperties | Where-Object PropertyName -eq 'SKUNAME' ).PropertyStrValue

                            $ClusterServiceTypeList = @(1, 2, 5, 7)
                            if ($ClusterServiceTypeList -contains $service.SQLServiceType) {
                                Add-Member -Force -InputObject $service -MemberType NoteProperty -Name Clustered -Value ($serviceAdvancedProperties | Where-Object PropertyName -eq 'CLUSTERED' ).PropertyNumValue
                                Add-Member -Force -InputObject $service -MemberType NoteProperty -Name VSName -Value ($serviceAdvancedProperties | Where-Object PropertyName -eq 'VSNAME' ).PropertyStrValue
                            } else {
                                Add-Member -Force -InputObject $service -MemberType NoteProperty -Name Clustered -Value ''
                                Add-Member -Force -InputObject $service -MemberType NoteProperty -Name VSName -Value ''
                            }
                        }
                        $outputServices += $service
                    }
                }
                if ($AdvancedProperties) {
                    $defaults = "ComputerName", "ServiceName", "ServiceType", "InstanceName", "DisplayName", "StartName", "State", "StartMode", "Version", "SPLevel", "SkuName", "Clustered", "VSName"
                } else {
                    $defaults = "ComputerName", "ServiceName", "ServiceType", "InstanceName", "DisplayName", "StartName", "State", "StartMode"
                }
                if ($outputServices) {
                    $outputServices | Select-DefaultView -Property $defaults -TypeName DbaSqlService
                } else {
                    Stop-Function -Message "No services found in relevant namespaces on $Computer. Please note that this function is available from SQL 2005 up."
                }
            } else {
                Stop-Function -EnableException $EnableException -Message "Failed to connect to $Computer" -Continue
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaSqlService
    }
}
tools\dbatools\functions\Get-DbaSpConfigure.ps1
function Get-DbaSpConfigure {
    <#
    .SYNOPSIS
        Returns all server level system configuration (sys.configuration/sp_configure) information

    .DESCRIPTION
        This function returns server level system configuration (sys.configuration/sp_configure) information. The information is gathered through SMO Configuration.Properties.
        The data includes the default value for each configuration, for quick identification of values that may have been changed.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Name
        Return only specific configurations. Name can be either values from (sys.configuration/sp_configure) or from SMO object

    .PARAMETER ExcludeName
        Exclude specific configurations. Name can be either values from (sys.configuration/sp_configure) or from SMO object

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: SpConfig, Configure, Configuration
        Author: Nic Cain, https://sirsql.net/

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaSpConfigure

    .INPUTS
        A DbaInstanceParameter representing an array of SQL Server instances.

    .OUTPUTS
        Returns PSCustomObject with properties ServerName, ComputerName, InstanceName, SqlInstance, Name, DisplayName, Description, IsAdvanced, IsDynamic, MinValue, MaxValue, ConfiguredValue, RunningValue, DefaultValue, IsRunningDefaultValue

    .EXAMPLE
        PS C:\> Get-DbaSpConfigure -SqlInstance localhost

        Returns all system configuration information on the localhost.

    .EXAMPLE
        PS C:\> 'localhost','localhost\namedinstance' | Get-DbaSpConfigure

        Returns system configuration information on multiple instances piped into the function

    .EXAMPLE
        PS C:\> Get-DbaSpConfigure -SqlInstance sql2012 -Name 'max server memory (MB)'

        Returns only the system configuration for MaxServerMemory on sql2012.

    .EXAMPLE
        PS C:\> Get-DbaSpConfigure -SqlInstance sql2012 -ExcludeName 'max server memory (MB)', RemoteAccess | Out-GridView

        Returns system configuration information on sql2012 but excludes for max server memory (MB) and remote access. Values returned in grid view

    .EXAMPLE
        PS C:\> $cred = Get-Credential SqlCredential
        PS C:\> 'sql2012' | Get-DbaSpConfigure -SqlCredential $cred -Name RemoteAccess, 'max server memory (MB)' -ExcludeName 'remote access' | Out-GridView

        Returns system configuration information on sql2012 using SQL Server Authentication. Only MaxServerMemory is returned as RemoteAccess was also excluded.

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Config", "ConfigName")]
        [string[]]$Name,
        [string[]]$ExcludeName,
        [switch]$EnableException
    )
    begin {
        $smoName = [pscustomobject]@{
            "Ad Hoc Distributed Queries"         = "AdHocDistributedQueriesEnabled"
            "affinity I/O mask"                  = "AffinityIOMask"
            "affinity mask"                      = "AffinityMask"
            "affinity64 I/O mask"                = "Affinity64IOMask"
            "affinity64 mask"                    = "Affinity64Mask"
            "Agent XPs"                          = "AgentXPsEnabled"
            "allow updates"                      = "AllowUpdates"
            "awe enabled"                        = "AweEnabled"
            "backup compression default"         = "DefaultBackupCompression"
            "blocked process threshold"          = "BlockedProcessThreshold"
            "blocked process threshold (s)"      = "BlockedProcessThreshold"
            "c2 audit mode"                      = "C2AuditMode"
            "clr enabled"                        = "IsSqlClrEnabled"
            "common criteria compliance enabled" = "CommonCriteriaComplianceEnabled"
            "contained database authentication"  = "ContainmentEnabled"
            "cost threshold for parallelism"     = "CostThresholdForParallelism"
            "cross db ownership chaining"        = "CrossDBOwnershipChaining"
            "cursor threshold"                   = "CursorThreshold"
            "Database Mail XPs"                  = "DatabaseMailEnabled"
            "default full-text language"         = "DefaultFullTextLanguage"
            "default language"                   = "DefaultLanguage"
            "default trace enabled"              = "DefaultTraceEnabled"
            "disallow results from triggers"     = "DisallowResultsFromTriggers"
            "EKM provider enabled"               = "ExtensibleKeyManagementEnabled"
            "filestream access level"            = "FilestreamAccessLevel"
            "fill factor (%)"                    = "FillFactor"
            "ft crawl bandwidth (max)"           = "FullTextCrawlBandwidthMax"
            "ft crawl bandwidth (min)"           = "FullTextCrawlBandwidthMin"
            "ft notify bandwidth (max)"          = "FullTextNotifyBandwidthMax"
            "ft notify bandwidth (min)"          = "FullTextNotifyBandwidthMin"
            "index create memory (KB)"           = "IndexCreateMemory"
            "in-doubt xact resolution"           = "InDoubtTransactionResolution"
            "lightweight pooling"                = "LightweightPooling"
            "locks"                              = "Locks"
            "max degree of parallelism"          = "MaxDegreeOfParallelism"
            "max full-text crawl range"          = "FullTextCrawlRangeMax"
            "max server memory (MB)"             = "MaxServerMemory"
            "max text repl size (B)"             = "ReplicationMaxTextSize"
            "max worker threads"                 = "MaxWorkerThreads"
            "media retention"                    = "MediaRetention"
            "min memory per query (KB)"          = "MinMemoryPerQuery"
            "min server memory (MB)"             = "MinServerMemory"
            "nested triggers"                    = "NestedTriggers"
            "network packet size (B)"            = "NetworkPacketSize"
            "Ole Automation Procedures"          = "OleAutomationProceduresEnabled"
            "open objects"                       = "OpenObjects"
            "optimize for ad hoc workloads"      = "OptimizeAdhocWorkloads"
            "PH timeout (s)"                     = "ProtocolHandlerTimeout"
            "precompute rank"                    = "PrecomputeRank"
            "priority boost"                     = "PriorityBoost"
            "query governor cost limit"          = "QueryGovernorCostLimit"
            "query wait (s)"                     = "QueryWait"
            "recovery interval (min)"            = "RecoveryInterval"
            "remote access"                      = "RemoteAccess"
            "remote admin connections"           = "RemoteDacConnectionsEnabled"
            "remote data archive"                = "RemoteDataArchiveEnabled"
            "remote login timeout (s)"           = "RemoteLoginTimeout"
            "remote proc trans"                  = "RemoteProcTrans"
            "remote query timeout (s)"           = "RemoteQueryTimeout"
            "Replication XPs"                    = "ReplicationXPsEnabled"
            "scan for startup procs"             = "ScanForStartupProcedures"
            "server trigger recursion"           = "ServerTriggerRecursionEnabled"
            "set working set size"               = "SetWorkingSetSize"
            "show advanced options"              = "ShowAdvancedOptions"
            "SMO and DMO XPs"                    = "SmoAndDmoXPsEnabled"
            "SQL Mail XPs"                       = "SqlMailXPsEnabled"
            "transform noise words"              = "TransformNoiseWords"
            "two digit year cutoff"              = "TwoDigitYearCutoff"
            "user connections"                   = "UserConnections"
            "user options"                       = "UserOptions"
            "Web Assistant Procedures"           = "WebXPsEnabled"
            "xp_cmdshell"                        = "XPCmdShellEnabled"
            # Configurations without defined names - Created dummy entries
            "access check cache bucket count"    = "AccessCheckCacheBucketCount"
            "access check cache quota"           = "AccessCheckCacheQuota"
            "allow polybase export"              = "AllowPolybaseExport"
            "automatic soft-NUMA disabled"       = "AutomaticSoftnumaDisabled"
            "backup checksum default"            = "BackupChecksumDefault"
            "clr strict security"                = "ClrStrictSecurity"
            "external scripts enabled"           = "ExternalScriptsEnabled"
            "hadoop connectivity"                = "HadoopConnectivity"
            "polybase network encryption"        = "PolybaseNetworkEncryption"
            "User Instance Timeout"              = "UserInstanceTimeout"
            "user instances enabled"             = "UserInstancesEnabled"
        }
    }
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failed to process Instance $Instance" -ErrorRecord $_ -Target $instance -Continue
            }

            #Get a list of the configuration Properties. This collection matches entries in sys.configurations
            try {
                $proplist = $server.Configuration.Properties
            } catch {
                Stop-Function -Message "Unable to gather configuration properties $instance" -Target $instance -ErrorRecord $_ -Continue
            }

            if ($Name) {
                $proplist = $proplist | Where-Object { ($_.DisplayName -in $Name -or ($smoName).$($_.DisplayName) -in $Name) }
            }

            if (Test-Bound "ExcludeName") {
                $proplist = $proplist | Where-Object { ($_.DisplayName -NotIn $ExcludeName -and ($smoName).$($_.DisplayName) -NotIn $ExcludeName) }
            }

            #Grab the default sp_configure property values from the external function
            $defaultConfigs = (Get-SqlDefaultSpConfigure -SqlVersion $server.VersionMajor).psobject.properties;

            #Iterate through the properties to get the configuration settings
            foreach ($prop in $proplist) {
                $defaultConfig = $defaultConfigs | Where-Object { $_.Name -eq $prop.DisplayName };

                if ($defaultConfig.Value -eq $prop.RunValue) { $isDefault = $true }
                else { $isDefault = $false }

                #Ignores properties that are not valid on this version of SQL
                if (!([string]::IsNullOrEmpty($prop.RunValue))) {

                    $DisplayName = $prop.DisplayName
                    [pscustomobject]@{
                        ServerName            = $server.Name
                        ComputerName          = $server.ComputerName
                        InstanceName          = $server.ServiceName
                        SqlInstance           = $server.DomainInstanceName
                        Name                  = ($smoName).$DisplayName
                        DisplayName           = $DisplayName
                        Description           = $prop.Description
                        IsAdvanced            = $prop.IsAdvanced
                        IsDynamic             = $prop.IsDynamic
                        MinValue              = $prop.Minimum
                        MaxValue              = $prop.Maximum
                        ConfiguredValue       = $prop.ConfigValue
                        RunningValue          = $prop.RunValue
                        DefaultValue          = $defaultConfig.Value
                        IsRunningDefaultValue = $isDefault
                        Parent                = $server
                        ConfigName            = ($smoName).$DisplayName
                    } | Select-DefaultView -ExcludeProperty ServerName, Parent, ConfigName
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaSpinLockStatistic.ps1
function Get-DbaSpinLockStatistic {
    <#
    .SYNOPSIS
        Displays information from sys.dm_os_spinlock_stats.  Works on SQL Server 2008 and above.

    .DESCRIPTION
            This command is based off of Paul Randal's post "Advanced SQL Server performance tuning"

            Returns:
                    SpinLockName
                    Collisions
                    Spins
                    SpinsPerCollision
                    SleepTime
                    Backoffs

            Reference:  https://www.sqlskills.com/blogs/paul/advanced-performance-troubleshooting-waits-latches-spinlocks/

    .PARAMETER SqlInstance
        The SQL Server instance. Server version must be SQL Server version 2008 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: SpinLockStatistics, Waits
        Author: Patrick Flynn (@sqllensman)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaSpinLockStatistic

    .EXAMPLE
        PS C:\> Get-DbaSpinLockStatistic -SqlInstance sql2008, sqlserver2012

        Get SpinLock Statistics for servers sql2008 and sqlserver2012.

    .EXAMPLE
        PS C:\> $output = Get-DbaSpinLockStatistic -SqlInstance sql2008 | Select * | ConvertTo-DbaDataTable

        Collects all SpinLock Statistics on server sql2008 into a Data Table.

    .EXAMPLE
        PS C:\> 'sql2008','sqlserver2012' | Get-DbaSpinLockStatistic

        Get SpinLock Statistics for servers sql2008 and sqlserver2012 via pipline

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> Get-DbaSpinLockStatistic -SqlInstance sql2008 -SqlCredential $cred

        Connects using sqladmin credential and returns SpinLock Statistics from sql2008
    #>
    [CmdletBinding()]
    Param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    BEGIN {

        $sql = "SELECT
                	name,
                	collisions,
                	spins,
                	spins_per_collision,
                	sleep_time,
                	backoffs
                FROM sys.dm_os_spinlock_stats;"

        Write-Message -Level Debug -Message $sql
    }

    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($instance in $SqlInstance) {
            Write-Message -Level Verbose -Message "Connecting to $instance"
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            Write-Message -Level Verbose -Message "Connected to $instance"

            foreach ($row in $server.Query($sql)) {
                [PSCustomObject]@{
                    ComputerName      = $server.NetName
                    InstanceName      = $server.ServiceName
                    SqlInstance       = $server.DomainInstanceName
                    SpinLockName      = $row.name
                    Collisions        = $row.collisions
                    Spins             = $row.spins
                    SpinsPerCollision = $row.spins_per_collision
                    SleepTime         = $row.sleep_time
                    Backoffs          = $row.backoffs
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaSpn.ps1
#ValidationTags#FlowControl,Pipeline#
function Get-DbaSpn {
    <#
    .SYNOPSIS
        Returns a list of set service principal names for a given computer/AD account

    .DESCRIPTION
        Get a list of set SPNs. SPNs are set at the AD account level. You can either retrieve set SPNs for a computer, or any SPNs set for
        a given active directory account. You can query one, or both. You'll get a list of every SPN found for either search term.

    .PARAMETER ComputerName
        The servers you want to return set SPNs for. This is defaulted automatically to localhost.

    .PARAMETER AccountName
        The accounts you want to retrieve set SPNs for.

    .PARAMETER Credential
        User credential to connect to the remote servers or active directory.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: SPN
        Author: Drew Furgiuele (@pittfurg), http://www.port1433.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaSpn

    .EXAMPLE
        PS C:\> Get-DbaSpn -ComputerName SQLSERVERA -Credential ad\sqldba

        Returns a custom object with SearchTerm (ServerName) and the SPNs that were found

    .EXAMPLE
        PS C:\> Get-DbaSpn -AccountName domain\account -Credential ad\sqldba

        Returns a custom object with SearchTerm (domain account) and the SPNs that were found

    .EXAMPLE
        PS C:\> Get-DbaSpn -ComputerName SQLSERVERA,SQLSERVERB -Credential ad\sqldba

        Returns a custom object with SearchTerm (ServerName) and the SPNs that were found for multiple computers

    #>
    [cmdletbinding()]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseApprovedVerbs", "", Justification = "Internal functions are ignored")]
    param (
        [Parameter(ValueFromPipeline)]
        [string[]]$ComputerName,
        [string[]]$AccountName,
        [PSCredential]$Credential,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        Function Process-Account ($AccountName) {

            ForEach ($account in $AccountName) {
                Write-Message -Message "Looking for account $account..." -Level Verbose
                $searchfor = 'User'
                if ($account.EndsWith('$')) {
                    $searchfor = 'Computer'
                }
                try {
                    $Result = Get-DbaADObject -ADObject $account -Type $searchfor -Credential $Credential -EnableException
                } catch {
                    Write-Message -Message "AD lookup failure. This may be because the domain cannot be resolved for the SQL Server service account ($Account)." -Level Warning
                    continue
                }
                if ($Result.Count -gt 0) {
                    try {
                        $results = $Result.GetUnderlyingObject()
                        $spns = $results.Properties.servicePrincipalName
                    } catch {
                        Write-Message -Message "The SQL Service account ($Account) has been found, but you don't have enough permission to inspect its SPNs" -Level Warning
                        continue
                    }
                } else {
                    Write-Message -Message "The SQL Service account ($Account) has not been found" -Level Warning
                    continue
                }

                foreach ($spn in $spns) {
                    if ($spn -match "\:") {
                        try {
                            $port = [int]($spn -Split "\:")[1]
                        } catch {
                            $port = $null
                        }
                        #Variable marked as unused by PSScriptAnalyzer
                        # if ($spn -match "\/") {
                        #     $serviceclass = ($spn -Split "\/")[0]
                        # }
                    }
                    [pscustomobject] @{
                        Input        = $Account
                        AccountName  = $Account
                        ServiceClass = "MSSQLSvc" # $serviceclass
                        Port         = $port
                        SPN          = $spn
                    }
                }
            }
        }
        if ($ComputerName.Count -eq 0 -and $AccountName.Count -eq 0) {
            $ComputerName = @($env:COMPUTERNAME)
        }
    }

    process {

        foreach ($computer in $ComputerName) {
            if ($computer) {
                if ($computer.EndsWith('$')) {
                    Write-Message -Message "$computer is an account name. Processing as account." -Level Verbose
                    Process-Account -AccountName $computer
                    continue
                }
            }

            Write-Message -Message "Getting SQL Server SPN for $computer" -Level Verbose
            $spns = Test-DbaSpn -ComputerName $computer -Credential $Credential

            $sqlspns = 0
            $spncount = $spns.count
            Write-Message -Message "Calculated $spncount SQL SPN entries that should exist for $computer" -Level Verbose
            foreach ($spn in $spns | Where-Object { $_.IsSet -eq $true }) {
                $sqlspns++

                if ($accountName) {
                    if ($accountName -eq $spn.InstanceServiceAccount) {
                        [pscustomobject] @{
                            Input        = $computer
                            AccountName  = $spn.InstanceServiceAccount
                            ServiceClass = "MSSQLSvc"
                            Port         = $spn.Port
                            SPN          = $spn.RequiredSPN
                        }
                    }
                } else {
                    [pscustomobject] @{
                        Input        = $computer
                        AccountName  = $spn.InstanceServiceAccount
                        ServiceClass = "MSSQLSvc"
                        Port         = $spn.Port
                        SPN          = $spn.RequiredSPN
                    }
                }
            }
            Write-Message -Message "Found $sqlspns set SQL SPN entries for $computer" -Level Verbose
        }

        if ($AccountName) {
            foreach ($account in $AccountName) {
                Process-Account -AccountName $account
            }
        }
    }
}
tools\dbatools\functions\Get-DbaSsisEnvironmentVariable.ps1
function Get-DbaSsisEnvironmentVariable {
    <#
    .SYNOPSIS
        This command gets specified SSIS Environment and all its variables

    .DESCRIPTION
        This command gets all variables from specified environment from SSIS Catalog. All sensitive values are decrypted.
        The function communicates directly with SSISDB database, "SQL Server Integration Services" service isn't queried there.
        Each parameter (besides SqlInstance and SqlCredential) acts as the filter to only include or exclude particular element

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.
        This can be a collection and receive pipeline input to allow the function
        to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Environment
        The SSIS Environments names that we want to get variables from

    .PARAMETER EnvironmentExclude
        The SSIS Environments to exclude. Acts as a filter for environments, best used without 'Environment' parameter
        to get variables for all environments but excluded ones

    .PARAMETER Folder
        The Folders names that contain the environments

    .PARAMETER FolderExclude
        The Folders names to exclude. Acts as a filter for folders containing environments, best user without 'Folder' parameter
        to get variables for all folders but excluded ones

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: SSIS, SSISDB, Variable
        Author: Bartosz Ratajczyk (@b_ratajczyk)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaSsisEnvironmentVariable

    .EXAMPLE
        PS C:\> Get-DbaSsisEnvironmentVariable -SqlInstance localhost -Environment DEV -Folder DWH_ETL

        Gets variables of 'DEV' environment located in 'DWH_ETL' folder on 'localhost' Server

    .EXAMPLE
        PS C:\> Get-DbaSsisEnvironmentVariable -SqlInstance localhost -Environment DEV -Folder DWH_ETL, DEV2, QA

        Gets variables of 'DEV' environment(s) located in folders 'DWH_ETL', 'DEV2' and 'QA' on 'localhost' server

    .EXAMPLE
        PS C:\> Get-DbaSsisEnvironmentVariable -SqlInstance localhost -Environment DEV -FolderExclude DWH_ETL, DEV2, QA

        Gets variables of 'DEV' environments located in folders other than 'DWH_ETL', 'DEV2' and 'QA' on 'localhost' server

    .EXAMPLE
        PS C:\> Get-DbaSsisEnvironmentVariable -SqlInstance localhost -Environment DEV, PROD -Folder DWH_ETL, DEV2, QA

        Gets variables of 'DEV' and 'PROD' environment(s) located in folders 'DWH_ETL', 'DEV2' and 'QA' on 'localhost' server

    .EXAMPLE
        PS C:\> Get-DbaSsisEnvironmentVariable -SqlInstance localhost -EnvironmentExclude DEV, PROD -Folder DWH_ETL, DEV2, QA

        Gets variables of environments other than 'DEV' and 'PROD' located in folders 'DWH_ETL', 'DEV2' and 'QA' on 'localhost' server

    .EXAMPLE
        PS C:\> Get-DbaSsisEnvironmentVariable -SqlInstance localhost -EnvironmentExclude DEV, PROD -FolderExclude DWH_ETL, DEV2, QA

        Gets variables of environments other than 'DEV' and 'PROD' located in folders other than 'DWH_ETL', 'DEV2' and 'QA' on 'localhost' server

    .EXAMPLE
        PS C:\> 'localhost' | Get-DbaSsisEnvironmentVariable -EnvironmentExclude DEV, PROD

        Gets all SSIS environments except 'DEV' and 'PROD' from 'localhost' server. The server name comes from pipeline

    .EXAMPLE
        PS C:\> 'SRV1', 'SRV3' | Get-DbaSsisEnvironmentVariable

        Gets all SSIS environments from 'SRV1' and 'SRV3' servers. The server's names come from pipeline

    .EXAMPLE
        PS C:\> 'SRV1', 'SRV2' | Get-DbaSsisEnvironmentVariable DEV | Out-GridView

        Gets all variables from 'DEV' Environment(s) on servers 'SRV1' and 'SRV2' and outputs it as the GridView.
        The server names come from the pipeline.

    .EXAMPLE
        PS C:\> 'localhost' | Get-DbaSsisEnvironmentVariable -EnvironmentExclude DEV, PROD | Select-Object -Property Name, Value | Where-Object {$_.Name -match '^a'} | Out-GridView

        Gets all variables from Environments other than 'DEV' and 'PROD' on 'localhost' server,
        selects Name and Value properties for variables that names start with letter 'a' and outputs it as the GridView

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias('SqlServer', 'ServerInstance')]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Environment,
        [object[]]$EnvironmentExclude,
        [object[]]$Folder,
        [object[]]$FolderExclude,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -MinimumVersion 11
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            try {
                $ISNamespace = "Microsoft.SqlServer.Management.IntegrationServices"

                $SSIS = New-Object "$ISNamespace.IntegrationServices" $server
            } catch {
                Stop-Function -Message "Could not connect to SSIS Catalog on $instance or current SMO library does not support SSIS catalog"
                return
            }

            Write-Message -Message "Fetching SSIS Catalog and its folders" -Level Verbose
            $catalog = $SSIS.Catalogs | Where-Object { $_.Name -eq "SSISDB" }

            # get all folders names if none provided
            if ($null -eq $Folder) {
                $searchFolders = $catalog.Folders.Name
            } else {
                $searchFolders = $Folder
            }

            # filter unwanted folders
            if ($FolderExclude) {
                $searchFolders = $searchFolders | Where-Object { $_ -notin $FolderExclude }
            }

            if ($null -eq $searchFolders) {
                Write-Message -Message "Instance: $instance > -Folder and -FolderExclude filters return an empty collection. Skipping" -Level Warning
            } else {
                foreach ($f in $searchFolders) {
                    # get all environments names if none provided
                    if ($null -eq $Environment) {
                        $searchEnvironments = $catalog.Folders.Environments.Name
                    } else {
                        $searchEnvironments = $Environment
                    }

                    #filter unwanted environments
                    if ($EnvironmentExclude) {
                        $searchEnvironments = $searchEnvironments | Where-Object { $_ -notin $EnvironmentExclude }
                    }

                    if ($null -eq $searchEnvironments) {
                        Write-Message -Message "Instance: $instance / Folder: $f > -Environment and -EnvironmentExclude filters return an empty collection. Skipping." -Level Warning
                    } else {
                        $Environments = $catalog.Folders[$f].Environments | Where-Object { $_.Name -in $searchEnvironments }

                        foreach ($e in $Environments) {
                            #encryption handling
                            $encKey = 'MS_Enckey_Env_' + $e.EnvironmentId
                            $encCert = 'MS_Cert_Env_' + $e.EnvironmentId

                            <#
                            SMO does not return sensitive values (gets data from catalog.environment_variables)
                            We have to manually query internal.environment_variables instead and use symmetric keys
                            within T-SQL code
                            #>

                            $sql = @"
                            OPEN SYMMETRIC KEY $encKey DECRYPTION BY CERTIFICATE $encCert;

                            SELECT
                                ev.variable_id,
                                ev.name,
                                ev.description,
                                ev.type,
                                ev.sensitive,
                                value = ev.value,
                                ev.sensitive_value,
                                ev.base_data_type,
                                decrypted = decrypted.value
                            FROM internal.environment_variables ev

                                CROSS APPLY (
                                    SELECT
                                        value   = CASE base_data_type
                                                    WHEN 'nvarchar' THEN CONVERT(NVARCHAR(MAX), DECRYPTBYKEY(sensitive_value))
                                                    WHEN 'bit' THEN CONVERT(NVARCHAR(MAX), CONVERT(bit, DECRYPTBYKEY(sensitive_value)))
                                                    WHEN 'datetime' THEN CONVERT(NVARCHAR(MAX), CONVERT(datetime2(0), DECRYPTBYKEY(sensitive_value)))
                                                    WHEN 'single' THEN CONVERT(NVARCHAR(MAX), CONVERT(DECIMAL(38, 18), DECRYPTBYKEY(sensitive_value)))
                                                    WHEN 'float' THEN CONVERT(NVARCHAR(MAX), CONVERT(DECIMAL(38, 18), DECRYPTBYKEY(sensitive_value)))
                                                    WHEN 'decimal' THEN CONVERT(NVARCHAR(MAX), CONVERT(DECIMAL(38, 18), DECRYPTBYKEY(sensitive_value)))
                                                    WHEN 'tinyint' THEN CONVERT(NVARCHAR(MAX), CONVERT(tinyint, DECRYPTBYKEY(sensitive_value)))
                                                    WHEN 'smallint' THEN CONVERT(NVARCHAR(MAX), CONVERT(smallint, DECRYPTBYKEY(sensitive_value)))
                                                    WHEN 'int' THEN CONVERT(NVARCHAR(MAX), CONVERT(INT, DECRYPTBYKEY(sensitive_value)))
                                                    WHEN 'bigint' THEN CONVERT(NVARCHAR(MAX), CONVERT(bigint, DECRYPTBYKEY(sensitive_value)))
                                                END
                                ) decrypted
                            WHERE environment_id = $($e.EnvironmentId);
                            CLOSE SYMMETRIC KEY $encKey;
"@

                            $ssisVariables = $server.Query($sql, "SSISDB")

                            foreach ($variable in $ssisVariables) {
                                if ($variable.sensitive -eq $true) {
                                    $value = $variable.decrypted
                                } else {
                                    $value = $variable.value
                                }

                                [PSCustomObject]@{
                                    ComputerName = $server.ComputerName
                                    InstanceName = $server.ServiceName
                                    SqlInstance  = $server.DomainInstanceName
                                    Folder       = $f
                                    Environment  = $e.Name
                                    Id           = $variable.variable_id
                                    Name         = $variable.Name
                                    Description  = $variable.description
                                    Type         = $variable.type
                                    IsSensitive  = $variable.sensitive
                                    BaseDataType = $variable.base_data_type
                                    Value        = $value
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaSsisExecutionHistory.ps1
#ValidationTags#Messaging#
function Get-DbaSsisExecutionHistory {
    <#
    .SYNOPSIS
        Get-DbaSsisHistory Retreives SSIS project and package execution History, and environments from one SQL Server to another.

    .DESCRIPTION
        This command gets execution history for SSIS executison given one or more instances and can be filtered by Project, Environment,Folder or Status.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.
        This can be a collection and receive pipeline input to allow the function
        to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Project
        Specifies a filter by project

    .PARAMETER Folder
        Specifies a filter by folder

    .PARAMETER Environment
        Specifies a filter by environment

    .PARAMETER Status
        Specifies a filter by status (created,running,cancelled,failed,pending,halted,succeeded,stopping,completed)

    .PARAMETER Since
        Datetime object used to narrow the results to a date

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration, SSIS
        Author: Chris Tucker (@ChrisTuc47368095)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaSsisExecutionHistory

    .EXAMPLE
        PS C:\> Get-DbaSsisExecutionHistory -SqlInstance SMTQ01 -Folder SMTQ_PRC

        Get all history items for SMTQ01 in folder SMTQ_PRC.

    .EXAMPLE
        PS C:\> Get-DbaSsisExecutionHistory -SqlInstance SMTQ01 -Status Failed,Cancelled

        Gets all failed or canceled executions for SMTQ01.

    .EXAMPLE
        PS C:\> Get-DbaSsisExecutionHistory -SqlInstance SMTQ01,SMTQ02 -Status Failed,Cancelled -Whatif

        Shows what would happen if the command were executed and would return the SQL statement that would be executed per instance.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [datetime]$Since,
        [ValidateSet("Created", "Running", "Cancelled", "Failed", "Pending", "Halted", "Succeeded", "Stopping", "Completed")]
        [String[]]$Status,
        [String[]]$Project,
        [String[]]$Folder,
        [String[]]$Environment,
        [switch]$EnableException
    )
    begin {
        $params = @{}

        #build status parameter
        $statuses = @{
            'Created'   = 1
            'Running'   = 2
            'Cancelled' = 3
            'Failed'    = 4
            'Pending'   = 5
            'Halted'    = 6
            'Succeeded' = 7
            'Stopping'  = 8
            'Completed' = 9
        }
        if ($Status) {
            $csv = ($statuses[$Status] -join ',')
            $statusq = "`n`t`tAND e.[Status] in ($csv)"
        } else {
            $statusq = ''
        }

        #construct parameterized collection predicate for project array
        if ($Project) {
            $projectq = "`n`t`tAND ( 1=0 "
            $i = 0
            foreach ($p in $Project) {
                $i ++
                $projectq += "`n`t`t`tOR e.[project_name] = @project$i"
                $params.Add("project$i", $p)
            }
            $projectq += "`n`t`t)"
        } else {
            $projectq = ''
        }

        #construct parameterized collection predicate for folder array
        if ($Folder) {
            $folderq = "`n`t`tAND ( 1=0 "
            $i = 0
            foreach ($f in $Folder) {
                $i ++
                $folderq += "`n`t`t`tOR e.[folder_name] = @folder$i"
                $params.Add("folder$i" , $f)
            }
            $folderq += "`n`t`t)"
        } else {
            $folderq = ''
        }

        #construct parameterized collection predicate for environment array
        if ($Environment) {
            $environmentq = "`n`t`tAND ( 1=0 "
            $i = 0
            foreach ($e in $Environment) {
                $i ++
                $environmentq += "`n`t`t`tOR e.[environment_name] = @environment$i"
                $params.Add("environment$i" , $e)
            }
            $environmentq += "`n`t`t)"
        } else {
            $environmentq = ''
        }

        #construct date filter for since
        if ($Since) {
            $sinceq = "`n`t`tAND e.[start_time] >= @since"
            $params.Add('since', $Since )
        }

        $sql = "
        WITH
            cteLoglevel as (
                SELECT
                    execution_id as ExecutionID,
                    cast(parameter_value AS INT) AS LoggingLevel
                FROM
                    [catalog].[execution_parameter_values]
                WHERE
                    parameter_name = 'LOGGING_LEVEL'
            )
            , cteStatus AS (
                SELECT
                     [key]
                    ,[code]
                FROM (
                    VALUES
                          ( 1,'Created'  )
                        , ( 2,'Running'  )
                        , ( 3,'Cancelled')
                        , ( 4,'Failed'   )
                        , ( 5,'Pending'  )
                        , ( 6,'Halted'   )
                        , ( 7,'Succeeded')
                        , ( 8,'Stopping' )
                        , ( 9,'Completed')
                ) codes([key],[code])
            )
            SELECT
                      e.execution_id as ExecutionID
                    , e.folder_name as FolderName
                    , e.project_name as ProjectName
                    , e.package_name as PackageName
                    , e.project_lsn as ProjectLsn
                    , Environment = isnull(e.environment_folder_name, '') + isnull('\' + e.environment_name,  '')
                    , s.code AS StatusCode
                    , start_time as StartTime
                    , end_time as EndTime
                    , ElapsedMinutes = DATEDIFF(ss, e.start_time, e.end_time)
                    , l.LoggingLevel
            FROM
                [catalog].executions e
                LEFT OUTER JOIN cteLoglevel l
                    ON e.execution_id = l.ExecutionID
                LEFT OUTER JOIN cteStatus s
                    ON s.[key] = e.status
            WHERE 1=1$statusq$projectq$folderq$environmentq$sinceq
            OPTION  ( RECOMPILE );
        "

        #debug verbose output
        Write-Message -Level Debug -Message "`nSQL statement: $sql"
        $paramout = ($params | Out-String)
        Write-Message -Level Debug -Message "`nParameters:$paramout"
    }


    process {
        foreach ($instance in $SqlInstance) {
            $results = Invoke-DbaQuery -SqlInstance $instance -Database SSISDB -Query $sql -as PSObject -SqlParameters $params -SqlCredential $SqlCredential
            foreach ($row in $results) {
                $row.StartTime = [dbadatetime]$row.StartTime.DateTime
                $row.EndTime = [dbadatetime]$row.EndTime.DateTime
                $row
            }
        }
    }
}
tools\dbatools\functions\Get-DbaStartupParameter.ps1
function Get-DbaStartupParameter {
    <#
    .SYNOPSIS
        Displays values for a detailed list of SQL Server Startup Parameters.

    .DESCRIPTION
        Displays values for a detailed list of SQL Server Startup Parameters including Master Data Path, Master Log path, Error Log, Trace Flags, Parameter String and much more.

        This command relies on remote Windows Server (SQL WMI/WinRm) access. You can pass alternative Windows credentials by using the -Credential parameter.

        See https://msdn.microsoft.com/en-us/library/ms190737.aspx for more information.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER Credential
        Allows you to login to servers using alternate Windows credentials.

        $scred = Get-Credential, then pass $scred object to the -Credential parameter.

    .PARAMETER Simple
        If this switch is enabled, simplified output will be produced including only Server, Master Data Path, Master Log path, ErrorLog, TraceFlags and ParameterString.

    .PARAMETER EnableException
        If this switch is enabled, exceptions will be thrown to the caller, which will need to perform its own exception processing. Otherwise, the function will try to catch the exception, interpret it and provide a friendly error message.

    .NOTES
        Tags: WSMan, SQLWMI, Memory
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaStartupParameter

    .EXAMPLE
        PS C:\> Get-DbaStartupParameter -SqlInstance sql2014

        Logs into SQL WMI as the current user then displays the values for numerous startup parameters.

    .EXAMPLE
        PS C:\> $wincred = Get-Credential ad\sqladmin
        PS C:\> Get-DbaStartupParameter -SqlInstance sql2014 -Credential $wincred -Simple

        Logs in to WMI using the ad\sqladmin credential and gathers simplified information about the SQL Server Startup Parameters.

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline, Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("SqlCredential")]
        [PSCredential]$Credential,
        [switch]$Simple,
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $computerName = $instance.ComputerName
                $instanceName = $instance.InstanceName
                $ogInstance = $instance.FullSmoName

                $computerName = (Resolve-DbaNetworkName -ComputerName $computerName).FullComputerName


                if ($instanceName.Length -eq 0) { $instanceName = "MSSQLSERVER" }

                $displayname = "SQL Server ($instanceName)"

                $Scriptblock = {
                    $computerName = $args[0]
                    $displayname = $args[1]

                    $wmisvc = $wmi.Services | Where-Object DisplayName -eq $displayname

                    $params = $wmisvc.StartupParameters -split ';'

                    $masterdata = $params | Where-Object { $_.StartsWith('-d') }
                    $masterlog = $params | Where-Object { $_.StartsWith('-l') }
                    $errorlog = $params | Where-Object { $_.StartsWith('-e') }
                    $traceflags = $params | Where-Object { $_.StartsWith('-T') }

                    $debugflag = $params | Where-Object { $_.StartsWith('-t') }

                    if ($debugflag.length -ne 0) {
                        Write-Message -Level Warning "$instance is using the lowercase -t trace flag. This is for internal debugging only. Please ensure this was intentional."
                    }
                    #>

                    if ($traceflags.length -eq 0) {
                        $traceflags = "None"
                    } else {
                        $traceflags = $traceflags.substring(2)
                    }

                    if ($Simple -eq $true) {
                        [PSCustomObject]@{
                            ComputerName    = $computerName
                            InstanceName    = $instanceName
                            SqlInstance     = $ogInstance
                            MasterData      = $masterdata.TrimStart('-d')
                            MasterLog       = $masterlog.TrimStart('-l')
                            ErrorLog        = $errorlog.TrimStart('-e')
                            TraceFlags      = $traceflags -join ','
                            ParameterString = $wmisvc.StartupParameters
                        }
                    } else {
                        # From https://msdn.microsoft.com/en-us/library/ms190737.aspx

                        $commandpromptparm = $params | Where-Object { $_ -eq '-c' }
                        $minimalstartparm = $params | Where-Object { $_ -eq '-f' }
                        $memorytoreserve = $params | Where-Object { $_.StartsWith('-g') }
                        $noeventlogsparm = $params | Where-Object { $_ -eq '-n' }
                        $instancestartparm = $params | Where-Object { $_ -eq '-s' }
                        $disablemonitoringparm = $params | Where-Object { $_ -eq '-x' }
                        $increasedextentsparm = $params | Where-Object { $_ -ceq '-E' }

                        $minimalstart = $noeventlogs = $instancestart = $disablemonitoring = $false
                        $increasedextents = $commandprompt = $singleuser = $false

                        if ($null -ne $commandpromptparm) {
                            $commandprompt = $true
                        }
                        if ($null -ne $minimalstartparm) {
                            $minimalstart = $true
                        }
                        if ($null -eq $memorytoreserve) {
                            $memorytoreserve = 0
                        }
                        if ($null -ne $noeventlogsparm) {
                            $noeventlogs = $true
                        }
                        if ($null -ne $instancestartparm) {
                            $instancestart = $true
                        }
                        if ($null -ne $disablemonitoringparm) {
                            $disablemonitoring = $true
                        }
                        if ($null -ne $increasedextentsparm) {
                            $increasedextents = $true
                        }

                        $singleuserparm = $params | Where-Object { $_.StartsWith('-m') }

                        if ($singleuserparm.length -ne 0) {
                            $singleuser = $true
                            $singleuserdetails = $singleuserparm.TrimStart('-m')
                        }

                        [PSCustomObject]@{
                            ComputerName         = $computerName
                            InstanceName         = $instanceName
                            SqlInstance          = $ogInstance
                            MasterData           = $masterdata -replace '^-[dD]', ''
                            MasterLog            = $masterlog -replace '^-[lL]', ''
                            ErrorLog             = $errorlog -replace '^-[eE]', ''
                            TraceFlags           = $traceflags -join ','
                            CommandPromptStart   = $commandprompt
                            MinimalStart         = $minimalstart
                            MemoryToReserve      = $memorytoreserve
                            SingleUser           = $singleuser
                            SingleUserName       = $singleuserdetails
                            NoLoggingToWinEvents = $noeventlogs
                            StartAsNamedInstance = $instancestart
                            DisableMonitoring    = $disablemonitoring
                            IncreasedExtents     = $increasedextents
                            ParameterString      = $wmisvc.StartupParameters
                        }
                    }
                }

                # This command is in the internal function
                # It's sorta like Invoke-Command.
                if ($credential) {
                    Invoke-ManagedComputerCommand -Server $computerName -Credential $credential -ScriptBlock $Scriptblock -ArgumentList $computerName, $displayname
                } else {
                    Invoke-ManagedComputerCommand -Server $computerName -ScriptBlock $Scriptblock -ArgumentList $computerName, $displayname
                }
            } catch {
                Stop-Function -Message "$instance failed." -ErrorRecord $_ -Continue -Target $instance
            }
        }
    }
}
tools\dbatools\functions\Get-DbaSuspectPage.ps1
function Get-DbaSuspectPage {
    <#
    .SYNOPSIS
        Returns data that is stored in SQL for Suspect Pages on the specified SQL Server Instance

    .DESCRIPTION
        This function returns any records that were stored due to suspect pages in databases on a SQL Server Instance.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        A credential to use to connect to the SQL Instance rather than using Windows Authentication

    .PARAMETER Database
        The database to return. If unspecified, all records will be returned.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Pages, DBCC
        Author: Garry Bargsley (@gbargsley), http://blog.garrybargsley.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaSuspectPage -SqlInstance sql2016

        Retrieve any records stored for Suspect Pages on the sql2016 SQL Server.

    .EXAMPLE
        PS C:\> Get-DbaSuspectPage -SqlInstance sql2016 -Database Test

        Retrieve any records stored for Suspect Pages on the sql2016 SQL Server and the Test database only.

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [object]$Database,
        [PSCredential]$SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $sqlinstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                return
            }

            $sql = "Select
            DB_NAME(database_id) as DBName,
            file_id,
            page_id,
            CASE event_type
            WHEN 1 THEN '823 or 824 or Torn Page'
            WHEN 2 THEN 'Bad Checksum'
            WHEN 3 THEN 'Torn Page'
            WHEN 4 THEN 'Restored'
            WHEN 5 THEN 'Repaired (DBCC)'
            WHEN 7 THEN 'Deallocated (DBCC)'
            END as EventType,
            error_count,
            last_update_date
            from msdb.dbo.suspect_pages"

            try {
                $results = $server.Query($sql)
            } catch {
                Stop-Function -Message "Issue collecting data on $server" -Target $server -ErrorRecord $_ -Continue
            }

            if ($Database) {
                $results = $results | Where-Object DBName -EQ $Database
            }

        }
        foreach ($row in $results) {
            [PSCustomObject]@{
                ComputerName   = $server.ComputerName
                InstanceName   = $server.ServiceName
                SqlInstance    = $server.DomainInstanceName
                Database       = $row.DBName
                FileId         = $row.file_id
                PageId         = $row.page_id
                EventType      = $row.EventType
                ErrorCount     = $row.error_count
                LastUpdateDate = $row.last_update_date
            }
        }
    }
}
tools\dbatools\functions\Get-DbaTcpPort.ps1
function Get-DbaTcpPort {
    <#
    .SYNOPSIS
        Returns the TCP port used by the specified SQL Server.

    .DESCRIPTION
        By default, this function returns just the TCP port used by the specified SQL Server.

        If -All is specified, the server name, IPAddress (ipv4 and ipv6), port number and an indicator of whether or not the port assignment is static are returned.

        Remote sqlwmi is used by default. If this doesn't work, then remoting is used. If neither work, it defaults to T-SQL which can provide only the port.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Allows you to connect to servers using alternate Windows credentials

        $scred = Get-Credential, then pass $scred object to the -SqlCredential parameter.

    .PARAMETER All
        If this switch is enabled, an object with server name, IPAddress (ipv4 and ipv6), port and static ($true/$false) for one or more SQL Servers is returned.

    .PARAMETER Detailed
        Output all properties, will be deprecated in 1.0.0 release. Use All instead.

    .PARAMETER ExcludeIpv6
        If this switch is enabled, IPv6 information is excluded from All output.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: SQLWMI, tcp
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaTcpPort

    .EXAMPLE
        PS C:\> Get-DbaTcpPort -SqlInstance sqlserver2014a

        Returns just the port number for the default instance on sqlserver2014a.

    .EXAMPLE
        PS C:\> Get-DbaTcpPort -SqlInstance winserver\sqlexpress, sql2016

        Returns an object with server name and port number for the sqlexpress on winserver and the default instance on sql2016.

    .EXAMPLE
        PS C:\> Get-DbaTcpPort -SqlInstance sqlserver2014a, sql2016 -All

        Returns an object with server name, IPAddress (ipv4 and ipv6), port and static ($true/$false) for sqlserver2014a and sql2016.

        Remote sqlwmi is used by default. If this doesn't work, then remoting is used. If neither work, it defaults to T-SQL which can provide only the port.

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sql2014 | Get-DbaTcpPort -ExcludeIpv6 -All

        Returns an object with server name, IPAddress (just ipv4), port and static ($true/$false) for every server listed in the Central Management Server on sql2014.

       #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [switch]$Detailed,
        [switch]$All,
        [Alias("Ipv4")]
        [switch]$ExcludeIpv6,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter Detailed
    }
    process {
        foreach ($instance in $SqlInstance) {
            if ($All) {
                try {
                    $scriptblock = {
                        $instance = $args[0]

                        Add-Type -AssemblyName Microsoft.VisualBasic

                        foreach ($servername in $wmi.ServerInstances) {
                            $instanceName = $servername.Name
                            $wmiinstance = $wmi.Services | Where-Object { $_.DisplayName -eq "SQL Server ($instanceName)" }
                            $vsname = ($wmiinstance.AdvancedProperties | Where-Object { $_ -match 'VSNAME' }).Value

                            if ($vsname.length -eq 0) {
                                $vsname = "$instance\$instanceName"
                            }

                            $vsname = $vsname.Replace("\MSSQLSERVER", "")

                            try {
                                $regroot = ($wmiinstance.AdvancedProperties | Where-Object { $_ -match 'REGROOT' }).Value
                                $dacport = (Get-ItemProperty "HKLM:\$regroot\MSSQLServer\SuperSocketNetLib\AdminConnection\Tcp").TcpDynamicPorts

                                [PsCustomObject]@{
                                    ComputerName = $instance
                                    InstanceName = $instanceName
                                    SqlInstance  = $vsname
                                    IPAddress    = "0.0.0.0"
                                    Port         = $dacport
                                    Static       = $false
                                    Type         = "DAC"
                                }
                            } catch {
                                # Shouldn't have an empty catch block
                                # Use write-verbose becaues it's remote and write-message may note exist
                                Write-Verbose -Message "it's just not our day"
                            }

                            $tcp = $servername.ServerProtocols | Where-Object Name -eq Tcp
                            $ips = $tcp.IPAddresses

                            # This is a remote command so do not use Write-message
                            Write-Verbose "Parsing information for $($ips.count) IP addresses."
                            foreach ($ip in $ips) {
                                $props = $ip.IPAddressProperties | Where-Object { $_.Name -eq "TcpPort" -or $_.Name -eq "TcpDynamicPorts" }

                                foreach ($prop in $props) {
                                    if ([Microsoft.VisualBasic.Information]::IsNumeric($prop.value)) {
                                        $port = $prop.value
                                        if ($prop.name -eq 'TcpPort') {
                                            $static = $true
                                        } else {
                                            $static = $false
                                        }
                                    }
                                }
                                [PsCustomObject]@{
                                    ComputerName = $instance
                                    InstanceName = $instanceName
                                    SqlInstance  = $vsname
                                    IPAddress    = $ip.IPAddress.IPAddressToString
                                    Port         = $port
                                    Static       = $static
                                    Type         = "Normal"
                                }
                            }
                        }
                    }

                    $computer = $instance.ComputerName
                    $resolved = Resolve-DbaNetworkName -ComputerName $instance
                    $computername = $resolved.FullComputerName
                    $fqdn = $resolved.Fqdn

                    try {
                        Write-Message -Level Verbose -Message "Trying with ComputerName ($computer)."
                        $someIps = Invoke-ManagedComputerCommand -ComputerName $computer -Credential $Credential -ArgumentList $computer -ScriptBlock $scriptblock
                    } catch {
                        Write-Message -Level Verbose -Message "Trying with FullComputerName because ComputerName failed."
                        $someIps = Invoke-ManagedComputerCommand -ComputerName $computername -Credential $Credential -ArgumentList $fqdn -ScriptBlock $scriptblock
                    }
                } catch {
                    Stop-Function -Message "Could not get all information." -Target $instance -ErrorRecord $_
                }

                $results = $someIps | Sort-Object IPAddress

                if ($ExcludeIpv6) {
                    $octet = '(?:0?0?[0-9]|0?[1-9][0-9]|1[0-9]{2}|2[0-5][0-5]|2[0-4][0-9])'
                    [regex]$ipv4 = "^(?:$octet\.){3}$octet$"
                    $results = $results | Where-Object { $_.IPAddress -match $ipv4 }
                }

                $results
            }
            #Default Execution of Get-DbaTcpPort
            if (-not $All -or ($All -and ($null -eq $someIps))) {
                try {
                    $server = Connect-SqlInstance -SqlInstance "TCP:$instance" -SqlCredential $SqlCredential -MinimumVersion 9
                } catch {
                    Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target "TCP:$instance" -Continue
                }

                # WmiComputer can be unreliable :( Use T-SQL
                $sql = "SELECT local_net_address,local_tcp_port FROM sys.dm_exec_connections WHERE session_id = @@SPID"
                $port = $server.Query($sql)

                [PsCustomObject]@{
                    ComputerName = $server.ComputerName
                    InstanceName = $server.ServiceName
                    SqlInstance  = $server.DomainInstanceName
                    IPAddress    = $port.local_net_address
                    Port         = $port.local_tcp_port
                    Static       = $true
                    Type         = "Normal"
                } | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, IPAddress, Port
            }
        }
    }
}
tools\dbatools\functions\Get-DbaTempdbUsage.ps1
function Get-DbaTempdbUsage {
    <#
    .SYNOPSIS
        Gets Tempdb usage for running queries.

    .DESCRIPTION
        This function queries DMVs for running sessions using tempdb and returns results if those sessions have user or internal space allocated or deallocated against them.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        If you want to use alternative credentials to connect to the server.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Tempdb, Space
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaTempdbUsage

    .EXAMPLE
        PS C:\> Get-DbaTempdbUsage -SqlInstance localhost\SQLDEV2K14

        Gets tempdb usage for localhost\SQLDEV2K14

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($server.VersionMajor -le 9) {
                Stop-Function -Message "This function is only supported in SQL Server 2008 or higher." -Continue
            }

            $sql = "SELECT  SERVERPROPERTY('MachineName') AS ComputerName,
        ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
        SERVERPROPERTY('ServerName') AS SqlInstance,
        t.session_id AS Spid,
        r.command AS StatementCommand,
        SUBSTRING(   est.[text],
                     (r.statement_start_offset / 2) + 1,
                     ((CASE r.statement_end_offset
                            WHEN-1
                            THEN DATALENGTH(est.[text])
                            ELSE
                            r.statement_end_offset
                       END - r.statement_start_offset
                      ) / 2
                     ) + 1
                 ) AS QueryText,
        QUOTENAME(DB_NAME(r.database_id)) + N'.' + QUOTENAME(OBJECT_SCHEMA_NAME(est.objectid, est.dbid)) + N'.'
        + QUOTENAME(OBJECT_NAME(est.objectid, est.dbid)) AS ProcedureName,
        r.start_time AS StartTime,
        tdb.UserObjectAllocated * 8 AS CurrentUserAllocatedKB,
        (t.user_objects_alloc_page_count + tdb.UserObjectAllocated) * 8 AS TotalUserAllocatedKB,
        tdb.UserObjectDeallocated * 8 AS UserDeallocatedKB,
        (t.user_objects_dealloc_page_count + tdb.UserObjectDeallocated) * 8 AS TotalUserDeallocatedKB,
        tdb.InternalObjectAllocated * 8 AS InternalAllocatedKB,
        (t.internal_objects_alloc_page_count + tdb.InternalObjectAllocated) * 8 AS TotalInternalAllocatedKB,
        tdb.InternalObjectDeallocated * 8 AS InternalDeallocatedKB,
        (t.internal_objects_dealloc_page_count + tdb.InternalObjectDeallocated) * 8 AS TotalInternalDeallocatedKB,
        r.reads AS RequestedReads,
        r.writes AS RequestedWrites,
        r.logical_reads AS RequestedLogicalReads,
        r.cpu_time AS RequestedCPUTime,
        s.is_user_process AS IsUserProcess,
        s.[status] AS [Status],
        DB_NAME(r.database_id) AS [Database],
        s.login_name AS LoginName,
        s.original_login_name AS OriginalLoginName,
        s.nt_domain AS NTDomain,
        s.nt_user_name AS NTUserName,
        s.[host_name] AS HostName,
        s.[program_name] AS ProgramName,
        s.login_time AS LoginTime,
        s.last_request_start_time AS LastRequestedStartTime,
        s.last_request_end_time AS LastRequestedEndTime
FROM    sys.dm_db_session_space_usage AS t
INNER JOIN sys.dm_exec_sessions AS s
    ON s.session_id = t.session_id
LEFT JOIN sys.dm_exec_requests AS r
    ON r.session_id = s.session_id
LEFT JOIN
          (   SELECT    _tsu.session_id,
                        _tsu.request_id,
                        SUM(_tsu.user_objects_alloc_page_count)       AS UserObjectAllocated,
                        SUM(_tsu.user_objects_dealloc_page_count)     AS UserObjectDeallocated,
                        SUM(_tsu.internal_objects_alloc_page_count)   AS InternalObjectAllocated,
                        SUM(_tsu.internal_objects_dealloc_page_count) AS InternalObjectDeallocated
              FROM      tempdb.sys.dm_db_task_space_usage AS _tsu
              GROUP BY  _tsu.session_id,
                        _tsu.request_id
          ) AS tdb
    ON  tdb.session_id = r.session_id
   AND  tdb.request_id = r.request_id
OUTER APPLY sys.dm_exec_sql_text(r.[sql_handle]) AS est
WHERE   t.session_id != @@SPID
  AND   (tdb.UserObjectAllocated - tdb.UserObjectDeallocated + tdb.InternalObjectAllocated - tdb.InternalObjectDeallocated) != 0
OPTION (RECOMPILE);"

            $server.Query($sql)
        }
    }
}
tools\dbatools\functions\Get-DbatoolsLog.ps1
function Get-DbatoolsLog {
    <#
    .SYNOPSIS
        Returns log entries for dbatools

    .DESCRIPTION
        Returns log entries for dbatools. Handy when debugging or developing a script using it.

    .PARAMETER FunctionName
        Default: "*"
        Only messages written by similar functions will be returned.

    .PARAMETER ModuleName
        Default: "*"
        Only messages written by commands from similar modules will be returned.

    .PARAMETER Target
        Only messags handling the specified target will be returned.

    .PARAMETER Tag
        Only messages containing one of these tags will be returned.

    .PARAMETER Last
        Only messages written by the last X executions will be returned.
        Uses Get-History to determine execution. Ignores Get-message commands.
        By default, this will also include messages from other runspaces. If your command executes in parallel, that's useful.
        If it doesn't and you were offloading executions to other runspaces, consider also filtering by runspace using '-Runspace'

    .PARAMETER Skip
        How many executions to skip when specifying '-Last'.
        Has no effect without the '-Last' parameter.

    .PARAMETER Raw
        By default, messages such as SQL statements are flattened. Use raw to see the output without flattened formatting.

    .PARAMETER Runspace
        The guid of the runspace to return messages from.
        By default, messages from all runspaces are returned.
        Run the following line to see the list of guids:

        Get-Runspace | ft Id, Name, InstanceId -Autosize

    .PARAMETER Level
        Limit the message selection by level.
        Message levels have a numeric value, making it easier to select a range:

        -Level (1..6)

        Will select the first 6 levels (Critical - SomewhatVerbose).

    .PARAMETER Errors
        Instead of log entries, the error entries will be retrieved

    .NOTES
        Tags: Debug
        Author: Friedrich Weinmann (@FredWeinmann)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbatoolsLog

    .EXAMPLE
        PS C:\> Get-DbatoolsLog

        Returns all log entries currently in memory.

    .EXAMPLE
        PS C:\> Get-DbatoolsLog -Target "a" -Last 1 -Skip 1

        Returns all log entries that targeted the object "a" in the second last execution sent.

    .EXAMPLE
        PS C:\> Get-DbatoolsLog -Tag "fail" -Last 5

        Returns all log entries within the last 5 executions that contained the tag "fail"

    #>
    [CmdletBinding()]
    param (
        [string]$FunctionName = "*",
        [string]$ModuleName = "*",
        [AllowNull()]
        [object]$Target,
        [string[]]$Tag,
        [int]$Last,
        [int]$Skip = 0,
        [guid]$Runspace,
        [Sqlcollaborative.Dbatools.Message.MessageLevel[]]$Level,
        [switch]$Raw,
        [switch]$Errors
    )
    process {
        if ($Errors) {
            $messages = [Sqlcollaborative.Dbatools.Message.LogHost]::GetErrors() | Where-Object {
                ($_.FunctionName -like $FunctionName) -and ($_.ModuleName -like $ModuleName)
            }
        } else {
            $messages = [Sqlcollaborative.Dbatools.Message.LogHost]::GetLog() | Where-Object {
                ($_.FunctionName -like $FunctionName) -and ($_.ModuleName -like $ModuleName)
            }
        }

        if (Test-Bound -ParameterName Target) {
            $messages = $messages | Where-Object TargetObject -eq $Target
        }

        if (Test-Bound -ParameterName Tag) {
            $messages = $messages | Where-Object {
                $_.Tags | Where-Object {
                    $_ -in $Tag
                }
            }
        }

        if (Test-Bound -ParameterName Runspace) {
            $messages = $messages | Where-Object Runspace -eq $Runspace
        }

        if (Test-Bound -ParameterName Last) {
            $history = Get-History | Where-Object CommandLine -NotLike "Get-DbatoolsLog*" | Select-Object -Last $Last -Skip $Skip
            $start = $history[0].StartExecutionTime
            $end = $history[-1].EndExecutionTime

            $messages = $messages | Where-Object {
                ($_.Timestamp -gt $start) -and ($_.Timestamp -lt $end) -and ($_.Runspace -eq ([System.Management.Automation.Runspaces.Runspace]::DefaultRunspace.InstanceId))
            }
        }

        if (Test-Bound -ParameterName Level) {
            $messages = $messages | Where-Object Level -In $Level
        }

        if ($Raw) {
            return $messages
        } else {
            $messages | Select-Object -Property CallStack, ComputerName, File, FunctionName, Level, Line, @{
                Name       = "Message"
                Expression = {
                    $msg = ($_.Message.Split("`n") -join " ")
                    do {
                        $msg = $msg.Replace('  ', ' ')
                    } until ($msg -notmatch '  ')
                    $msg
                }
            }, ModuleName, Runspace, Tags, TargetObject, Timestamp, Type, Username
        }
    }
}
tools\dbatools\functions\Get-DbaTopResourceUsage.ps1
function Get-DbaTopResourceUsage {
    <#
    .SYNOPSIS
        Returns the top 20 resource consumers for cached queries based on four different metrics: duration, frequency, IO, and CPU.

    .DESCRIPTION
        Returns the top 20 resource consumers for cached queries based on four different metrics: duration, frequency, IO, and CPU.

        This command is based off of queries provided by Michael J. Swart at http://michaeljswart.com/go/Top20

        Per Michael: "I've posted queries like this before, and others have written many other versions of this query. All these queries are based on sys.dm_exec_query_stats."

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER ExcludeSystem
        This will exclude system objects like replication procedures from being returned.

    .PARAMETER Type
        By default, all Types run but you can specify one or more of the following: Duration, Frequency, IO, or CPU

    .PARAMETER Limit
        By default, these query the Top 20 worst offenders (though more than 20 results can be returned if each of the top 20 have more than 1 subsequent result)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Query, Performance
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaTopResourceUsage

    .EXAMPLE
        PS C:\> Get-DbaTopResourceUsage -SqlInstance sql2008, sql2012

        Return the 80 (20 x 4 types) top usage results by duration, frequency, IO, and CPU servers for servers sql2008 and sql2012

    .EXAMPLE
        PS C:\> Get-DbaTopResourceUsage -SqlInstance sql2008 -Type Duration, Frequency -Database TestDB

        Return the highest usage by duration (top 20) and frequency (top 20) for the TestDB on sql2008

    .EXAMPLE
        PS C:\> Get-DbaTopResourceUsage -SqlInstance sql2016 -Limit 30

        Return the highest usage by duration (top 30) and frequency (top 30) for the TestDB on sql2016

    .EXAMPLE
        PS C:\> Get-DbaTopResourceUsage -SqlInstance sql2008, sql2012 -ExcludeSystem

        Return the 80 (20 x 4 types) top usage results by duration, frequency, IO, and CPU servers for servers sql2008 and sql2012 without any System Objects

    .EXAMPLE
        PS C:\> Get-DbaTopResourceUsage -SqlInstance sql2016| Select-Object *

        Return all the columns plus the QueryPlan column

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [ValidateSet("All", "Duration", "Frequency", "IO", "CPU")]
        [string[]]$Type = "All",
        [int]$Limit = 20,
        [Alias('Silent')]
        [switch]$EnableException,
        [switch]$ExcludeSystem
    )

    begin {

        $instancecolumns = " SERVERPROPERTY('MachineName') AS ComputerName,
        ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
        SERVERPROPERTY('ServerName') AS SqlInstance, "

        if ($database) {
            $wheredb = " and coalesce(db_name(st.dbid), db_name(cast(pa.value AS INT)), 'Resource') in ('$($database -join '', '')')"
        }

        if ($ExcludeDatabase) {
            $wherenotdb = " and coalesce(db_name(st.dbid), db_name(cast(pa.value AS INT)), 'Resource') notin '$($excludedatabase -join '', '')'"
        }

        if ($ExcludeSystem) {
            $whereexcludesystem = " AND coalesce(object_name(st.objectid, st.dbid), '<none>') NOT LIKE 'sp_MS%' "
        }
        $duration = ";with long_queries as
                        (
                            select top $Limit
                                query_hash,
                                sum(total_elapsed_time) elapsed_time
                            from sys.dm_exec_query_stats
                            where query_hash <> 0x0
                            group by query_hash
                            order by sum(total_elapsed_time) desc
                        )
                        select $instancecolumns
                            coalesce(db_name(st.dbid), db_name(cast(pa.value AS INT)), 'Resource') AS [Database],
                            coalesce(object_name(st.objectid, st.dbid), '<none>') as ObjectName,
                            qs.query_hash as QueryHash,
                            qs.total_elapsed_time / 1000 as TotalElapsedTimeMs,
                            qs.execution_count as ExecutionCount,
                            cast((total_elapsed_time / 1000) / (execution_count + 0.0) as money) as AverageDurationMs,
                            lq.elapsed_time / 1000 as QueryTotalElapsedTimeMs,
                            SUBSTRING(st.TEXT,(qs.statement_start_offset + 2) / 2,
                                (CASE
                                    WHEN qs.statement_end_offset = -1  THEN LEN(CONVERT(NVARCHAR(MAX),st.text)) * 2
                                    ELSE qs.statement_end_offset
                                    END - qs.statement_start_offset) / 2) as QueryText,
                            qp.query_plan as QueryPlan
                        from sys.dm_exec_query_stats qs
                        join long_queries lq
                            on lq.query_hash = qs.query_hash
                        cross apply sys.dm_exec_sql_text(qs.sql_handle) st
                        cross apply sys.dm_exec_query_plan (qs.plan_handle) qp
                        outer apply sys.dm_exec_plan_attributes(qs.plan_handle) pa
                        where pa.attribute = 'dbid' $wheredb $wherenotdb $whereexcludesystem
                        order by lq.elapsed_time desc,
                            lq.query_hash,
                            qs.total_elapsed_time desc
                        option (recompile)"

        $frequency = ";with frequent_queries as
                        (
                            select top $Limit
                                query_hash,
                                sum(execution_count) executions
                            from sys.dm_exec_query_stats
                            where query_hash <> 0x0
                            group by query_hash
                            order by sum(execution_count) desc
                        )
                        select $instancecolumns
                            coalesce(db_name(st.dbid), db_name(cast(pa.value AS INT)), 'Resource') AS [Database],
                            coalesce(object_name(st.objectid, st.dbid), '<none>') as ObjectName,
                            qs.query_hash as QueryHash,
                            qs.execution_count as ExecutionCount,
                            executions as QueryTotalExecutions,
                            SUBSTRING(st.TEXT,(qs.statement_start_offset + 2) / 2,
                                (CASE
                                    WHEN qs.statement_end_offset = -1  THEN LEN(CONVERT(NVARCHAR(MAX),st.text)) * 2
                                    ELSE qs.statement_end_offset
                                    END - qs.statement_start_offset) / 2) as QueryText,
                            qp.query_plan as QueryPlan
                        from sys.dm_exec_query_stats qs
                        join frequent_queries fq
                            on fq.query_hash = qs.query_hash
                        cross apply sys.dm_exec_sql_text(qs.sql_handle) st
                        cross apply sys.dm_exec_query_plan (qs.plan_handle) qp
                        outer apply sys.dm_exec_plan_attributes(qs.plan_handle) pa
                        where pa.attribute = 'dbid'  $wheredb $wherenotdb $whereexcludesystem
                        order by fq.executions desc,
                            fq.query_hash,
                            qs.execution_count desc
                        option (recompile)"

        $io = ";with high_io_queries as
                (
                    select top $Limit
                        query_hash,
                        sum(total_logical_reads + total_logical_writes) io
                    from sys.dm_exec_query_stats
                    where query_hash <> 0x0
                    group by query_hash
                    order by sum(total_logical_reads + total_logical_writes) desc
                )
                select $instancecolumns
                    coalesce(db_name(st.dbid), db_name(cast(pa.value AS INT)), 'Resource') AS [Database],
                    coalesce(object_name(st.objectid, st.dbid), '<none>') as ObjectName,
                    qs.query_hash as QueryHash,
                    qs.total_logical_reads + total_logical_writes as TotalIO,
                    qs.execution_count as ExecutionCount,
                    cast((total_logical_reads + total_logical_writes) / (execution_count + 0.0) as money) as AverageIO,
                    io as QueryTotalIO,
                    SUBSTRING(st.TEXT,(qs.statement_start_offset + 2) / 2,
                        (CASE
                            WHEN qs.statement_end_offset = -1  THEN LEN(CONVERT(NVARCHAR(MAX),st.text)) * 2
                            ELSE qs.statement_end_offset
                            END - qs.statement_start_offset) / 2) as QueryText,
                    qp.query_plan as QueryPlan
                from sys.dm_exec_query_stats qs
                join high_io_queries fq
                    on fq.query_hash = qs.query_hash
                cross apply sys.dm_exec_sql_text(qs.sql_handle) st
                cross apply sys.dm_exec_query_plan (qs.plan_handle) qp
                outer apply sys.dm_exec_plan_attributes(qs.plan_handle) pa
                where pa.attribute = 'dbid' $wheredb $wherenotdb $whereexcludesystem
                order by fq.io desc,
                    fq.query_hash,
                    qs.total_logical_reads + total_logical_writes desc
                option (recompile)"

        $cpu = ";with high_cpu_queries as
                (
                    select top $Limit
                        query_hash,
                        sum(total_worker_time) cpuTime
                    from sys.dm_exec_query_stats
                    where query_hash <> 0x0
                    group by query_hash
                    order by sum(total_worker_time) desc
                )
                select $instancecolumns
                    coalesce(db_name(st.dbid), db_name(cast(pa.value AS INT)), 'Resource') AS [Database],
                    coalesce(object_name(st.objectid, st.dbid), '<none>') as ObjectName,
                    qs.query_hash as QueryHash,
                    qs.total_worker_time as CpuTime,
                    qs.execution_count as ExecutionCount,
                    cast(total_worker_time / (execution_count + 0.0) as money) as AverageCpuMs,
                    cpuTime as QueryTotalCpu,
                    SUBSTRING(st.TEXT,(qs.statement_start_offset + 2) / 2,
                        (CASE
                            WHEN qs.statement_end_offset = -1  THEN LEN(CONVERT(NVARCHAR(MAX),st.text)) * 2
                            ELSE qs.statement_end_offset
                            END - qs.statement_start_offset) / 2) as QueryText,
                    qp.query_plan as QueryPlan
                from sys.dm_exec_query_stats qs
                join high_cpu_queries hcq
                    on hcq.query_hash = qs.query_hash
                cross apply sys.dm_exec_sql_text(qs.sql_handle) st
                cross apply sys.dm_exec_query_plan (qs.plan_handle) qp
                outer apply sys.dm_exec_plan_attributes(qs.plan_handle) pa
                where pa.attribute = 'dbid' $wheredb $wherenotdb $whereexcludesystem
                order by hcq.cpuTime desc,
                    hcq.query_hash,
                    qs.total_worker_time desc
                option (recompile)"
    }

    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            if ($server.ConnectionContext.StatementTimeout -ne 0) {
                $server.ConnectionContext.StatementTimeout = 0
            }

            if ($Type -in "All", "Duration") {
                try {
                    Write-Message -Level Debug -Message "Executing SQL: $duration"
                    $server.Query($duration) | Select-DefaultView -ExcludeProperty QueryPlan
                } catch {
                    Stop-Function -Message "Failure executing query for duration." -ErrorRecord $_ -Target $server -Continue
                }
            }

            if ($Type -in "All", "Frequency") {
                try {
                    Write-Message -Level Debug -Message "Executing SQL: $frequency"
                    $server.Query($frequency) | Select-DefaultView -ExcludeProperty QueryPlan
                } catch {
                    Stop-Function -Message "Failure executing query for frequency." -ErrorRecord $_ -Target $server -Continue
                }
            }

            if ($Type -in "All", "IO") {
                try {
                    Write-Message -Level Debug -Message "Executing SQL: $io"
                    $server.Query($io) | Select-DefaultView -ExcludeProperty QueryPlan
                } catch {
                    Stop-Function -Message "Failure executing query for IO." -ErrorRecord $_ -Target $server -Continue
                }
            }

            if ($Type -in "All", "CPU") {
                try {
                    Write-Message -Level Debug -Message "Executing SQL: $cpu"
                    $server.Query($cpu) | Select-DefaultView -ExcludeProperty QueryPlan
                } catch {
                    Stop-Function -Message "Failure executing query for CPU." -ErrorRecord $_ -Target $server -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaTrace.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaTrace {
    <#
    .SYNOPSIS
        Gets a list of trace(s) from specified SQL Server Instance

    .DESCRIPTION
        This function returns a list of traces on a SQL Server instance and identifies the default trace file

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        A credential to use to connect to the SQL Instance rather than using Windows Authentication

    .PARAMETER Id
        The id(s) of the Trace

    .PARAMETER Default
        Switch that will only return the information for the default system trace

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Security, Trace
        Author: Garry Bargsley (@gbargsley), http://blog.garrybargsley.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaTrace -SqlInstance sql2016

        Lists all the trace files on the sql2016 SQL Server.

    .EXAMPLE
        PS C:\> Get-DbaTrace -SqlInstance sql2016 -Default

        Lists the default trace information on the sql2016 SQL Server.

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [int[]]$Id,
        [switch]$Default,
        [switch][Alias('Silent')]
        $EnableException
    )
    begin {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Get-DbaTraceFile

        # A Microsoft.SqlServer.Management.Trace.TraceServer class exists but is buggy
        # and requires x86 PowerShell. So we'll go with T-SQL.
        $sql = "SELECT id, status, path, max_size, stop_time, max_files, is_rowset, is_rollover, is_shutdown, is_default, buffer_count, buffer_size, file_position, reader_spid, start_time, last_event_time, event_count, dropped_event_count FROM sys.traces"

        if ($Id) {
            $idstring = $Id -join ","
            $sql = "$sql WHERE id in ($idstring)"
        }
    }
    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                return
            }

            try {
                $results = $server.Query($sql)
            } catch {
                Stop-Function -Message "Issue collecting trace data on $server" -Target $server -ErrorRecord $_
            }

            if ($Default) {
                $results = $results | Where-Object { $_.is_default }
            }

            foreach ($row in $results) {
                if ($row.Path.ToString().Length -gt 0) {
                    $remotefile = Join-AdminUnc -servername $server.ComputerName -filepath $row.path
                } else {
                    $remotefile = $null
                }

                [PSCustomObject]@{
                    ComputerName      = $server.ComputerName
                    InstanceName      = $server.ServiceName
                    SqlInstance       = $server.DomainInstanceName
                    Id                = $row.id
                    Status            = $row.status
                    IsRunning         = ($row.status -eq 1)
                    Path              = $row.path
                    RemotePath        = $remotefile
                    MaxSize           = $row.max_size
                    StopTime          = $row.stop_time
                    MaxFiles          = $row.max_files
                    IsRowset          = $row.is_rowset
                    IsRollover        = $row.is_rollover
                    IsShutdown        = $row.is_shutdown
                    IsDefault         = $row.is_default
                    BufferCount       = $row.buffer_count
                    BufferSize        = $row.buffer_size
                    FilePosition      = $row.file_position
                    ReaderSpid        = $row.reader_spid
                    StartTime         = $row.start_time
                    LastEventTime     = $row.last_event_time
                    EventCount        = $row.event_count
                    DroppedEventCount = $row.dropped_event_count
                    Parent            = $server
                    SqlCredential     = $SqlCredential
                } | Select-DefaultView -ExcludeProperty Parent, RemotePath, RemoStatus, SqlCredential
            }
        }
    }
}
tools\dbatools\functions\Get-DbaTraceFlag.ps1
function Get-DbaTraceFlag {
    <#
    .SYNOPSIS
        Get global Trace Flag(s) information for each instance(s) of SQL Server.

    .DESCRIPTION
        Returns Trace Flags that are enabled globally on each instance(s) of SQL Server as an object.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER TraceFlag
        Use this switch to filter to a specific Trace Flag.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: TraceFlag, DBCC
        Author: Kevin Bullen (@sqlpadawan)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        References:  https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-traceon-trace-flags-transact-sql

    .LINK
        https://dbatools.io/Get-DbaTraceFlag

    .EXAMPLE
        PS C:\> Get-DbaTraceFlag -SqlInstance localhost

        Returns all Trace Flag information on the local default SQL Server instance

    .EXAMPLE
        PS C:\> Get-DbaTraceFlag -SqlInstance localhost, sql2016

        Returns all Trace Flag(s) for the local and sql2016 SQL Server instances

    .EXAMPLE
        PS C:\> Get-DbaTraceFlag -SqlInstance localhost -TraceFlag 4199,3205

        Returns Trace Flag status for TF 4199 and 3205 for the local SQL Server instance if they are enabled.

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]
        $SqlCredential,
        [int[]]$TraceFlag,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $tflags = $server.EnumActiveGlobalTraceFlags()

            if ($tFlags.Rows.Count -eq 0) {
                Write-Message -Level Output -Message "No global trace flags enabled"
                return
            }

            if ($TraceFlag) {
                $tflags = $tflags | Where-Object TraceFlag -In $TraceFlag
            }

            foreach ($tflag in $tflags) {
                [pscustomobject]@{
                    ComputerName = $server.ComputerName
                    InstanceName = $server.ServiceName
                    SqlInstance  = $server.DomainInstanceName
                    TraceFlag    = $tflag.TraceFlag
                    Global       = $tflag.Global
                    Session      = $tflag.Session
                    Status       = $tflag.Status
                } | Select-DefaultView -ExcludeProperty 'Session'
            }
        }
    }
}
tools\dbatools\functions\Get-DbaUptime.ps1
function Get-DbaUptime {
    <#
    .SYNOPSIS
        Returns the uptime of the SQL Server instance, and if required the hosting windows server

    .DESCRIPTION
        By default, this command returns for each SQL Server instance passed in:
        SQL Instance last startup time, Uptime as a PS TimeSpan, Uptime as a formatted string
        Hosting Windows server last startup time, Uptime as a PS TimeSpan, Uptime as a formatted string

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Allows you to login to servers using SQL Logins instead of Windows Authentication (AKA Integrated or Trusted). To use:

        $scred = Get-Credential, then pass $scred object to the -SqlCredential parameter.

        Windows Authentication will be used if SqlCredential is not specified. SQL Server does not accept Windows credentials being passed as credentials.

        To connect to SQL Server as a different Windows user, run PowerShell as that user.

    .PARAMETER Credential
        Allows you to login to the computer (not SQL Server instance) using alternative Windows credentials.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: CIM
        Author: Stuart Moore (@napalmgram), stuart-moore.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaUptime

    .EXAMPLE
        PS C:\> Get-DbaUptime -SqlInstance SqlBox1\Instance2

        Returns an object with SQL Server start time, uptime as TimeSpan object, uptime as a string, and Windows host boot time, host uptime as TimeSpan objects and host uptime as a string for the sqlexpress instance on winserver

    .EXAMPLE
        PS C:\> Get-DbaUptime -SqlInstance winserver\sqlexpress, sql2016

        Returns an object with SQL Server start time, uptime as TimeSpan object, uptime as a string, and Windows host boot time, host uptime as TimeSpan objects and host uptime as a string for the sqlexpress instance on host winserver  and the default instance on host sql2016

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sql2014 | Get-DbaUptime

        Returns an object with SQL Server start time, uptime as TimeSpan object, uptime as a string, and Windows host boot time, host uptime as TimeSpan objects and host uptime as a string for every server listed in the Central Management Server on sql2014

    #>
    [CmdletBinding(DefaultParameterSetName = "Default")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "ComputerName")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [PSCredential]$Credential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $nowutc = (Get-Date).ToUniversalTime()
    }
    process {
        # uses cim commands
        
        
        foreach ($instance in $SqlInstance) {
            if ($instance.Gettype().FullName -eq [System.Management.Automation.PSCustomObject] ) {
                $servername = $instance.SqlInstance
            } elseif ($instance.Gettype().FullName -eq [Microsoft.SqlServer.Management.Smo.Server]) {
                $servername = $instance.ComputerName
            } else {
                $servername = $instance.ComputerName;
            }

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            Write-Message -Level Verbose -Message "Getting start times for $servername"
            #Get tempdb creation date
            [dbadatetime]$SQLStartTime = $server.Databases["tempdb"].CreateDate
            $SQLUptime = New-TimeSpan -Start $SQLStartTime.ToUniversalTime() -End $nowutc
            $SQLUptimeString = "{0} days {1} hours {2} minutes {3} seconds" -f $($SQLUptime.Days), $($SQLUptime.Hours), $($SQLUptime.Minutes), $($SQLUptime.Seconds)

            $WindowsServerName = (Resolve-DbaNetworkName $servername -Credential $Credential).FullComputerName

            try {
                Write-Message -Level Verbose -Message "Getting WinBootTime via CimInstance for $servername"
                $WinBootTime = (Get-DbaOperatingSystem -ComputerName $windowsServerName -Credential $Credential -ErrorAction SilentlyContinue).LastBootTime
                $WindowsUptime = New-TimeSpan -start $WinBootTime.ToUniversalTime() -end $nowutc
                $WindowsUptimeString = "{0} days {1} hours {2} minutes {3} seconds" -f $($WindowsUptime.Days), $($WindowsUptime.Hours), $($WindowsUptime.Minutes), $($WindowsUptime.Seconds)
            } catch {
                try {
                    Write-Message -Level Verbose -Message "Getting WinBootTime via CimInstance DCOM"
                    $CimOption = New-CimSessionOption -Protocol DCOM
                    $CimSession = New-CimSession -Credential:$Credential -ComputerName $WindowsServerName -SessionOption $CimOption
                    [dbadatetime]$WinBootTime = ($CimSession | Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime
                    $WindowsUptime = New-TimeSpan -start $WinBootTime.ToUniversalTime() -end $nowutc
                    $WindowsUptimeString = "{0} days {1} hours {2} minutes {3} seconds" -f $($WindowsUptime.Days), $($WindowsUptime.Hours), $($WindowsUptime.Minutes), $($WindowsUptime.Seconds)
                } catch {
                    Stop-Function -Message "Failure getting WinBootTime" -ErrorRecord $_ -Target $instance -Continue
                }
            }

            [PSCustomObject]@{
                ComputerName     = $WindowsServerName
                InstanceName     = $server.ServiceName
                SqlServer        = $server.Name
                SqlUptime        = $SQLUptime
                WindowsUptime    = $WindowsUptime
                SqlStartTime     = $SQLStartTime
                WindowsBootTime  = $WinBootTime
                SinceSqlStart    = $SQLUptimeString
                SinceWindowsBoot = $WindowsUptimeString
            }
        }
    }
}
tools\dbatools\functions\Get-DbaUserPermission.ps1
function Get-DbaUserPermission {
    <#
    .SYNOPSIS
        Displays detailed permissions information for the server and database roles and securables.

    .DESCRIPTION
        This command will display all server logins, server level securable, database logins and database securables.

        DISA STIG implementators will find this command useful as it uses Permissions.sql provided by DISA.

        Note that if you Ctrl-C out of this command and end it prematurely, it will leave behind a STIG schema in tempdb.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER ExcludeSystemDatabase
        Allows you to suppress output on system databases

    .PARAMETER IncludePublicGuest
        Allows you to include output for public and guest grants.

    .PARAMETER IncludeSystemObjects
        Allows you to include output on sys schema objects.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Discovery, Permissions, Security
        Author: Brandon Abshire, netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaUserPermission

    .EXAMPLE
        PS C:\> Get-DbaUserPermission -SqlInstance sql2008, sqlserver2012

        Check server and database permissions for servers sql2008 and sqlserver2012.

    .EXAMPLE
        PS C:\> Get-DbaUserPermission -SqlInstance sql2008 -Database TestDB

        Check server and database permissions on server sql2008 for only the TestDB database

    .EXAMPLE
        PS C:\> Get-DbaUserPermission -SqlInstance sql2008 -Database TestDB -IncludePublicGuest -IncludeSystemObjects

        Check server and database permissions on server sql2008 for only the TestDB database,
        including public and guest grants, and sys schema objects.

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [parameter(Position = 1)]
        [switch]$ExcludeSystemDatabase,
        [switch]$IncludePublicGuest,
        [switch]$IncludeSystemObjects,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {

        $sql = [System.IO.File]::ReadAllText("$script:PSModuleRoot\bin\stig.sql")

        $endSQL = "	   BEGIN TRY DROP FUNCTION STIG.server_effective_permissions END TRY BEGIN CATCH END CATCH;
                       GO
                       BEGIN TRY DROP VIEW STIG.server_permissions END TRY BEGIN CATCH END CATCH;
                       GO
                       BEGIN TRY DROP FUNCTION STIG.members_of_server_role END TRY BEGIN CATCH END CATCH;
                       GO
                       BEGIN TRY DROP FUNCTION STIG.server_roles_of END TRY BEGIN CATCH END CATCH;
                       GO
                       BEGIN TRY DROP VIEW STIG.server_role_members END TRY BEGIN CATCH END CATCH;
                       GO
                       BEGIN TRY DROP FUNCTION STIG.database_effective_permissions END TRY BEGIN CATCH END CATCH;
                       GO
                       BEGIN TRY DROP VIEW STIG.database_permissions END TRY BEGIN CATCH END CATCH;
                       GO
                       BEGIN TRY DROP FUNCTION STIG.members_of_db_role END TRY BEGIN CATCH END CATCH;
                       GO
                       BEGIN TRY DROP FUNCTION STIG.database_roles_of END TRY BEGIN CATCH END CATCH;
                       GO
                       BEGIN TRY DROP VIEW STIG.database_role_members END TRY BEGIN CATCH END CATCH;
                       GO
                       BEGIN TRY DROP SCHEMA STIG END TRY BEGIN CATCH END CATCH;
                       GO"


        $serverSQL = "SELECT  'SERVER LOGINS' AS Type ,
                                    sl.name AS Member ,
                                    ISNULL(srm.role, 'None') AS [Role/Securable/Class] ,
                                    ' ' AS [Schema/Owner] ,
                                    ' ' AS [Securable] ,
                                    ' ' AS [Grantee Type] ,
                                    ' ' AS [Grantee] ,
                                    ' ' AS [Permission] ,
                                    ' ' AS [State] ,
                                    ' ' AS [Grantor] ,
                                    ' ' AS [Grantor Type] ,
                                    ' ' AS [Source View]
                            FROM    master.sys.syslogins sl
                                    LEFT JOIN tempdb.[STIG].[server_role_members] srm ON sl.name = srm.member
                            WHERE   sl.name NOT LIKE 'NT %'
                                    AND sl.name NOT LIKE '##%'
                            UNION
                            SELECT  'SERVER SECURABLES' AS Type ,
                                    sl.name ,
                                    sp.[Securable Class] COLLATE SQL_Latin1_General_CP1_CI_AS ,
                                    ' ' ,
                                    sp.[Securable] ,
                                    sp.[Grantee Type] COLLATE SQL_Latin1_General_CP1_CI_AS ,
                                    sp.Grantee ,
                                    sp.Permission COLLATE SQL_Latin1_General_CP1_CI_AS ,
                                    sp.State COLLATE SQL_Latin1_General_CP1_CI_AS ,
                                    sp.Grantor ,
                                    sp.[Grantor Type] COLLATE SQL_Latin1_General_CP1_CI_AS ,
                                    sp.[Source View]
                            FROM    master.sys.syslogins sl
                                    LEFT JOIN tempdb.[STIG].[server_permissions] sp ON sl.name = sp.Grantee
                            WHERE   sl.name NOT LIKE 'NT %'
                                    AND sl.name NOT LIKE '##%';"

        $dbSQL = "SELECT  'DB ROLE MEMBERS' AS type ,
                                Member ,
                                Role ,
                                ' ' AS [Schema/Owner] ,
                                ' ' AS [Securable] ,
                                ' ' AS [Grantee Type] ,
                                ' ' AS [Grantee] ,
                                ' ' AS [Permission] ,
                                ' ' AS [State] ,
                                ' ' AS [Grantor] ,
                                ' ' AS [Grantor Type] ,
                                ' ' AS [Source View]
                        FROM    tempdb.[STIG].[database_role_members]
                        UNION
                        SELECT DISTINCT
                                'DB SECURABLES' AS Type ,
                                drm.member ,
                                dp.[Securable Type or Class] COLLATE SQL_Latin1_General_CP1_CI_AS ,
                                dp.[Schema/Owner] ,
                                dp.Securable ,
                                dp.[Grantee Type] COLLATE SQL_Latin1_General_CP1_CI_AS ,
                                dp.Grantee ,
                                dp.Permission COLLATE SQL_Latin1_General_CP1_CI_AS ,
                                dp.State COLLATE SQL_Latin1_General_CP1_CI_AS ,
                                dp.Grantor ,
                                dp.[Grantor Type] COLLATE SQL_Latin1_General_CP1_CI_AS ,
                                dp.[Source View]
                        FROM    tempdb.[STIG].[database_role_members] drm
                                LEFT JOIN tempdb.[STIG].[database_permissions] dp ON ( drm.member = dp.grantee
                                                                                      OR drm.role = dp.grantee
                                                                                     )
                        WHERE	dp.Grantor IS NOT NULL
                                AND [Schema/Owner] <> 'sys'"

        if ($IncludePublicGuest) { $dbSQL = $dbSQL.Replace("LEFT JOIN", "FULL JOIN") }
        if ($IncludeSystemObjects) { $dbSQL = $dbSQL.Replace("AND [Schema/Owner] <> 'sys'", "") }

    }

    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $dbs = $server.Databases

            if ($Database) {
                $dbs = $dbs | Where-Object { $Database -contains $_.Name }
            }

            if ($ExcludeDatabase) {
                $dbs = $dbs | Where-Object Name -NotIn $ExcludeDatabase
            }

            if ($ExcludeSystemDatabase) {
                $dbs = $dbs | Where-Object IsSystemObject -eq $false
            }

            #reset $serverDT
            $serverDT = $null

            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Processing $db on $instance"

                if ($db.IsAccessible -eq $false) {
                    Stop-Function -Message "The database $db is not accessible" -Continue
                }

                $sql = $sql.Replace("<TARGETDB>", $db.Name)

                #Create objects in active database
                Write-Message -Level Verbose -Message "Creating objects"
                try {
                    $db.ExecuteNonQuery($sql)
                } catch {
                    # here to avoid an empty catch
                    $null = 1
                } # sometimes it complains about not being able to drop the stig schema if the person Ctrl-C'd before.

                #Grab permissions data
                if (-not $serverDT) {
                    Write-Message -Level Verbose -Message "Building data table for server objects"

                    try {
                        $serverDT = $db.Query($serverSQL)
                    } catch {
                        # here to avoid an empty catch
                        $null = 1
                    }

                    foreach ($row in $serverDT) {
                        [PSCustomObject]@{
                            ComputerName       = $server.ComputerName
                            InstanceName       = $server.ServiceName
                            SqlInstance        = $server.DomainInstanceName
                            Object             = 'SERVER'
                            Type               = $row.Type
                            Member             = $row.Member
                            RoleSecurableClass = $row.'Role/Securable/Class'
                            SchemaOwner        = $row.'Schema/Owner'
                            Securable          = $row.Securable
                            GranteeType        = $row.'Grantee Type'
                            Grantee            = $row.Grantee
                            Permission         = $row.Permission
                            State              = $row.State
                            Grantor            = $row.Grantor
                            GrantorType        = $row.'Grantor Type'
                            SourceView         = $row.'Source View'
                        }
                    }
                }

                Write-Message -Level Verbose -Message "Building data table for $db objects"
                try {
                    $dbDT = $db.Query($dbSQL)
                } catch {
                    # here to avoid an empty catch
                    $null = 1
                }

                foreach ($row in $dbDT) {
                    [PSCustomObject]@{
                        ComputerName       = $server.ComputerName
                        InstanceName       = $server.ServiceName
                        SqlInstance        = $server.DomainInstanceName
                        Object             = $db.Name
                        Type               = $row.Type
                        Member             = $row.Member
                        RoleSecurableClass = $row.'Role/Securable/Class'
                        SchemaOwner        = $row.'Schema/Owner'
                        Securable          = $row.Securable
                        GranteeType        = $row.'Grantee Type'
                        Grantee            = $row.Grantee
                        Permission         = $row.Permission
                        State              = $row.State
                        Grantor            = $row.Grantor
                        GrantorType        = $row.'Grantor Type'
                        SourceView         = $row.'Source View'
                    }
                }

                #Delete objects
                Write-Message -Level Verbose -Message "Deleting objects"
                try {
                    $db.ExecuteNonQuery($endSQL)
                } catch {
                    # here to avoid an empty catch
                    $null = 1
                }
                $sql = $sql.Replace($db.Name, "<TARGETDB>")

                #Sashay Away
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaUserLevelPermission
    }
}
tools\dbatools\functions\Get-DbaWaitingTask.ps1
function Get-DbaWaitingTask {
    <#
    .SYNOPSIS
        Displays waiting task.

    .DESCRIPTION
        This command is based on waiting task T-SQL script published by Paul Randal.
        Reference: https://www.sqlskills.com/blogs/paul/updated-sys-dm_os_waiting_tasks-script-2/

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server version must be SQL Server version XXXX or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Spid
        Find the waiting task of one or more specific process ids

    .PARAMETER IncludeSystemSpid
        If this switch is enabled, the output will include the system sessions.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Waits,Task,WaitTask
        Author: Shawn Melton (@wsmelton), https://wsmelton.github.io

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaWaitingTask

    .EXAMPLE
        PS C:\> Get-DbaWaitingTask -SqlInstance sqlserver2014a

        Returns the waiting task for all sessions on sqlserver2014a

    .EXAMPLE
        PS C:\> Get-DbaWaitingTask -SqlInstance sqlserver2014a -IncludeSystemSpid

        Returns the waiting task for all sessions (user and system) on sqlserver2014a

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(ValueFromPipelineByPropertyName = $true)]
        [object[]]$Spid,
        [switch]$IncludeSystemSpid,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $sql = "
            SELECT
                [owt].[session_id] AS [Spid],
                [owt].[exec_context_id] AS [Thread],
                [ot].[scheduler_id] AS [Scheduler],
                [owt].[wait_duration_ms] AS [WaitMs],
                [owt].[wait_type] AS [WaitType],
                [owt].[blocking_session_id] AS [BlockingSpid],
                [owt].[resource_description] AS [ResourceDesc],
                CASE [owt].[wait_type]
                    WHEN N'CXPACKET' THEN
                        RIGHT ([owt].[resource_description],
                            CHARINDEX (N'=', REVERSE ([owt].[resource_description])) - 1)
                    ELSE NULL
                END AS [NodeId],
                [eqmg].[dop] AS [Dop],
                [er].[database_id] AS [DbId],
                [est].text AS [SqlText],
                [eqp].[query_plan] AS [QueryPlan],
                CAST ('https://www.sqlskills.com/help/waits/' + [owt].[wait_type] as XML) AS [URL]
            FROM sys.dm_os_waiting_tasks [owt]
            INNER JOIN sys.dm_os_tasks [ot] ON
                [owt].[waiting_task_address] = [ot].[task_address]
            INNER JOIN sys.dm_exec_sessions [es] ON
                [owt].[session_id] = [es].[session_id]
            INNER JOIN sys.dm_exec_requests [er] ON
                [es].[session_id] = [er].[session_id]
            FULL JOIN sys.dm_exec_query_memory_grants [eqmg] ON
                [owt].[session_id] = [eqmg].[session_id]
            OUTER APPLY sys.dm_exec_sql_text ([er].[sql_handle]) [est]
            OUTER APPLY sys.dm_exec_query_plan ([er].[plan_handle]) [eqp]
            WHERE
                [es].[is_user_process] = $(if (Test-Bound 'IncludeSystemSpid') {0} else {1})
            ORDER BY
                [owt].[session_id],
                [owt].[exec_context_id]
            OPTION(RECOMPILE);"
    }
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $results = $server.Query($sql)
            foreach ($row in $results) {
                if (Test-Bound 'Spid') {
                    if ($row.Spid -notin $Spid) { continue }
                }

                [PSCustomObject]@{
                    ComputerName = $server.ComputerName
                    InstanceName = $server.ServiceName
                    SqlInstance  = $server.DomainInstanceName
                    Spid         = $row.Spid
                    Thread       = $row.Thread
                    Scheduler    = $row.Scheduler
                    WaitMs       = $row.WaitMs
                    WaitType     = $row.WaitType
                    BlockingSpid = $row.BlockingSpid
                    ResourceDesc = $row.ResourceDesc
                    NodeId       = $row.NodeId
                    Dop          = $row.Dop
                    DbId         = $row.DbId
                    SqlText      = $row.SqlText
                    QueryPlan    = $row.QueryPlan
                    InfoUrl      = $row.InfoUrl
                } | Select-DefaultView -ExcludeProperty 'SqlText', 'QueryPlan', 'InfoUrl'
            }
        }
    }
}
tools\dbatools\functions\Get-DbaWaitResource.ps1
function Get-DbaWaitResource {
    <#
    .SYNOPSIS
        Returns the resource being waited upon

    .DESCRIPTION
        Given a wait resource in the form of 'PAGE: 10:1:9180084' returns the database, data file and the system object which is being waited up.

        Given a wait resource in the form of 'KEY: 7:35457594073541168 (de21f92a1572)', returns the database, object and index that is being waited on, With the -row switch the row data will also be returned.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.

    .PARAMETER WaitResource
        The wait resource value as supplied in sys.dm_exec_requests

    .PARAMETER Row
        If this switch provided also returns the value of the row being waited on with KEY wait resources

    .PARAMETER EnableException
        Replaces user friendly yellow warnings with bloody red exceptions of doom!
        Use this if you want the function to throw terminating errors you want to catch.

    .NOTES
        Tags: Pages, DBCC
        Author: Stuart Moore (@napalmgram), stuart-moore.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaWaitResource

    .EXAMPLE
        PS C:\> Get-DbaWaitResource -SqlInstance server1 -WaitResource 'PAGE: 10:1:9180084'

        Will return an object containing; database name, data file name, schema name and the object which owns the resource

    .EXAMPLE
        PS C:\> Get-DbaWaitResource -SqlInstance server2 -WaitResource 'KEY: 7:35457594073541168 (de21f92a1572)'

        Will return an object containing; database name, schema name and index name which is being waited on.

    .EXAMPLE
        PS C:\> Get-DbaWaitResource -SqlInstance server2 -WaitResource 'KEY: 7:35457594073541168 (de21f92a1572)' -row

        Will return an object containing; database name, schema name and index name which is being waited on, and in addition the contents of the locked row at the time the command is run.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance]$SqlInstance,
        [PsCredential]$SqlCredential,
        [parameter(Mandatory, ValueFromPipeline)]
        [string]$WaitResource,
        [switch]$Row,
        [switch]$EnableException
    )

    process {
        if ($WaitResource -notmatch '^PAGE: [0-9]*:[0-9]*:[0-9]*$' -and $WaitResource -notmatch '^KEY: [0-9]*:[0-9]* \([a-f0-9]*\)$') {
            Stop-Function -Message "Row input - $WaitResource - Improperly formatted"
            return
        }

        try {
            $server = Connect-SqlInstance -SqlInstance $sqlinstance -SqlCredential $SqlCredential
        } catch {
            Write-Message -Level Warning -Message "Cannot connect to $SqlInstance"
        }

        $null = $WaitResource -match '^(?<Type>[A-Z]*): (?<dbid>[0-9]*):*'
        $ResourceType = $matches.Type
        $DbId = $matches.DbId
        $DbName = ($server.Databases | Where-Object ID -eq $dbid).Name
        if ($null -eq $DbName) {
            stop-function -Message "Database with id $dbid does not exist on $server"
            return
        }
        if ($ResourceType -eq 'PAGE') {
            $null = $WaitResource -match '^(?<Type>[A-Z]*): (?<dbid>[0-9]*):(?<FileID>[0-9]*):(?<PageID>[0-9]*)$'
            $DataFileSql = "select name, physical_name from sys.master_files where database_id=$DbID and file_ID=$($matches.FileID);"
            $DataFile = $server.query($DataFileSql)
            if ($null -eq $DataFile) {
                Write-Message -Level Warning -Message "Datafile with id $($matches.FileID) for $dbname not found"
                return
            }
            $ObjectIdSQL = "dbcc traceon (3604); dbcc page ($dbid,$($matches.fileID),$($matches.PageID),2) with tableresults;"
            try {
                $ObjectID = ($server.databases[$dbname].Query($ObjectIdSQL) | Where-Object Field -eq 'Metadata: ObjectId').Value
            } catch {
                Stop-Function -Message "You've requested a page beyond the end of the database, exiting"
                return
            }
            if ($null -eq $ObjectID) {
                Write-Message -Level Warning -Message "Object not found, could have been delete, or a transcription error when copying the Wait_resource to PowerShell"
                return
            }
            $ObjectSql = "select SCHEMA_NAME(schema_id) as SchemaName, name, type_desc from sys.all_objects where object_id=$objectID;"
            $Object = $server.databases[$dbname].query($ObjectSql)
            if ($null -eq $Object) {
                Write-Message -Warning "Object could not be found. Could have been removed, or could be a transcription error copying the Wait_resource to sowerShell"
            }
            [PsCustomObject]@{
                DatabaseID   = $DbId
                DatabaseName = $DbName
                DataFileName = $Datafile.name
                DataFilePath = $DataFile.physical_name
                ObjectID     = $ObjectID
                ObjectName   = $Object.Name
                ObjectSchema = $Object.SchemaName
                ObjectType   = $Object.type_desc
            }
        }
        if ($ResourceType -eq 'KEY') {
            $null = $WaitResource -match '^(?<Type>[A-Z]*): (?<dbid>[0-9]*):(?<frodo>[0-9]*) (?<physloc>\(.*\))$'
            $IndexSql = "select
                            sp.object_id as ObjectID,
                            OBJECT_SCHEMA_NAME(sp.object_id) as SchemaName,
                            sao.name as ObjectName,
                            si.name as IndexName
                        from
                            sys.partitions sp inner join sys.indexes si on sp.index_id=si.index_id and sp.object_id=si.object_id
                                inner join sys.all_objects sao on sp.object_id=sao.object_id
                        where
                            hobt_id = $($matches.frodo);
                "
            $Index = $server.databases[$dbname].Query($IndexSql)
            if ($null -eq $Index) {
                Write-Message -Level Warning -Message "Heap or B-Tree with ID $($matches.frodo) can not be found in $dbname on $server"
                return
            }
            $output = [PsCustomObject]@{
                DatabaseID   = $DbId
                DatabaseName = $DbName
                SchemaName   = $Index.SchemaName
                IndexName    = $Index.IndexName
                ObjectID     = $index.ObjectID
                Objectname   = $index.ObjectName
                HobtID       = $matches.frodo
            }
            if ($row -eq $True) {
                $DataSql = "select * from $($Index.SchemaName).$($Index.ObjectName) with (NOLOCK) where %%lockres%% ='$($matches.physloc)'"
                $Data = $server.databases[$dbname].query($DataSql)
                if ($null -eq $data) {
                    Write-Message -Level warning -Message "Could not retrieve the data. It may have been deleted or moved since the wait resource value was generated"
                } else {
                    $output | Add-Member -Type NoteProperty -Name ObjectData -Value $Data
                    $output | Select-Object * -ExpandProperty ObjectData
                }
            } else {
                $output
            }
        }
    }
}
tools\dbatools\functions\Get-DbaWaitStatistic.ps1
function Get-DbaWaitStatistic {
    <#
    .SYNOPSIS
        Displays wait statistics

    .DESCRIPTION
        This command is based off of Paul Randal's post "Wait statistics, or please tell me where it hurts"

        Returns:
        WaitType
        Category
        WaitSeconds
        ResourceSeconds
        SignalSeconds
        WaitCount
        Percentage
        AverageWaitSeconds
        AverageResourceSeconds
        AverageSignalSeconds
        URL

        Reference: https://www.sqlskills.com/blogs/paul/wait-statistics-or-please-tell-me-where-it-hurts/

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server version must be SQL Server version 2005 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Threshold
        Threshold, in percentage of all waits on the system. Default per Paul's post is 95%.

    .PARAMETER IncludeIgnorable
        Some waits are no big deal and can be safely ignored in most circumstances. If you've got weird issues with mirroring or AGs.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: WaitStatistic
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaWaitStatistic

    .EXAMPLE
        PS C:\> Get-DbaWaitStatistic -SqlInstance sql2008, sqlserver2012

        Check wait statistics for servers sql2008 and sqlserver2012

    .EXAMPLE
        PS C:\> Get-DbaWaitStatistic -SqlInstance sql2008 -Threshold 98 -IncludeIgnorable

        Check wait statistics on server sql2008 for thresholds above 98% and include wait stats that are most often, but not always, ignorable

    .EXAMPLE
        PS C:\> Get-DbaWaitStatistic -SqlInstance sql2008 | Select *

        Shows detailed notes, if available, from Paul's post

    .EXAMPLE
        PS C:\> $output = Get-DbaWaitStatistic -SqlInstance sql2008 -Threshold 100 -IncludeIgnorable | Select-Object * | ConvertTo-DbaDataTable

        Collects all Wait Statistics (including ignorable waits) on server sql2008 into a Data Table.

    .EXAMPLE
        PS C:\> $output = Get-DbaWaitStatistic -SqlInstance sql2008
        PS C:\> foreach ($row in ($output | Sort-Object -Unique Url)) { Start-Process ($row).Url }

        Displays the output then loads the associated sqlskills website for each result. Opens one tab per unique URL.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [int]$Threshold = 95,
        [switch]$IncludeIgnorable,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {

        $details = [pscustomobject]@{
            CXPACKET                         = "This indicates parallelism, not necessarily that there's a problem. The coordinator thread in a parallel query always accumulates these waits. If the parallel threads are not given equal amounts of work to do, or one thread blocks, the waiting threads will also accumulate CXPACKET waits, which will make them aggregate a lot faster - this is a problem. One thread may have a lot more to do than the others, and so the whole query is blocked while the long-running thread completes. If this is combined with a high number of PAGEIOLATCH_XX waits, it could be large parallel table scans going on because of incorrect non-clustered indexes, or a bad query plan. If neither of these are the issue, you might want to try setting MAXDOP to 4, 2, or 1 for the offending queries (or possibly the whole instance). Make sure that if you have a NUMA system that you try setting MAXDOP to the number of cores in a single NUMA node first to see if that helps the problem. You also need to consider the MAXDOP effect on a mixed-load system. Play with the cost threshold for parallelism setting (bump it up to, say, 25) before reducing the MAXDOP of the whole instance. And don't forget Resource Governor in Enterprise Edition of  SQL Server 2008 onward that allows DOP governing for a particular group of connections to the server."
            PAGEIOLATCH_XX                   = "This is where SQL Server is waiting for a data page to be read from disk into memory. It may indicate a bottleneck at the IO subsystem level (which is a common knee-jerk response to seeing these), but why is the I/O subsystem having to service so many reads? It could be buffer pool/memory pressure (i.e. not enough memory for the workload), a sudden change in query plans causing a large parallel scan instead of a seek, plan cache bloat, or a number of other things. Don't assume the root cause is the I/O subsystem."
            ASYNC_NETWORK_IO                 = "This is usually where SQL Server is waiting for a client to finish consuming data. It could be that the client has asked for a very large amount of data or just that it's consuming it reeeeeally slowly because of poor programming - I rarely see this being a network issue. Clients often process one row at a time - called RBAR or Row-By-Agonizing-Row - instead of caching the data on the client and acknowledging to SQL Server immediately."
            WRITELOG                         = "This is the log management system waiting for a log flush to disk. It commonly indicates that the I/O subsystem can't keep up with the log flush volume, but on very high-volume systems it could also be caused by internal log flush limits, that may mean you have to split your workload over multiple databases or even make your transactions a little longer to reduce log flushes. To be sure it is the I/O subsystem, use the DMV sys.dm_io_virtual_file_stats to examine the I/O latency for the log file and see if it correlates to the average WRITELOG time. If WRITELOG is longer, you've got internal contention and need to shard. If not, investigate why you're creating so much transaction log."
            BROKER_RECEIVE_WAITFOR           = "This is just Service Broker waiting around for new messages to receive. I would add this to the list of waits to filter out and re-run the wait stats query."
            MSQL_XP                          = "This is SQL Server waiting for an extended stored-proc to finish. This could indicate a problem in your XP code."
            OLEDB                            = "As its name suggests, this is a wait for something communicating using OLEDB - e.g. a linked server. However, OLEDB is also used by all DMVs and by DBCC CHECKDB, so don't assume linked servers are the problem - it could be a third-party monitoring tool making excessive DMV calls. If it *is* a linked server (wait times in the 10s or 100s of milliseconds), go to the linked server and do wait stats analysis there to figure out what the performance issue is there."
            BACKUPIO                         = "This can show up when you're backing up to a slow I/O subsystem, like directly to tape, which is slooooow, or over a network."
            LCK_M_XX                         = "This is simply the thread waiting for a lock to be granted and indicates blocking problems. These could be caused by unwanted lock escalation or bad programming, but could also be from I/Os taking a long time causing locks to be held for longer than usual. Look at the resource associated with the lock using the DMV sys.dm_os_waiting_tasks. Don't assume that locking is the root cause."
            ONDEMAND_TASK_QUEUE              = "This is normal and is part of the background task system (e.g. deferred drop, ghost cleanup).  I would add this to the list of waits to filter out and re-run the wait stats query."
            BACKUPBUFFER                     = "This commonly show up with BACKUPIO and is a backup thread waiting for a buffer to write backup data into."
            IO_COMPLETION                    = "This is SQL Server waiting for non-data page I/Os to complete and could be an indication that the I/O subsystem is overloaded if the latencies look high (see Are I/O latencies killing your performance?)"
            SOS_SCHEDULER_YIELD              = "This is code running that doesn't hit any resource waits."
            DBMIRROR_EVENTS_QUEUE            = "These two are database mirroring just sitting around waiting for something to do. I would add these to the list of waits to filter out and re-run the wait stats query."
            DBMIRRORING_CMD                  = "These two are database mirroring just sitting around waiting for something to do. I would add these to the list of waits to filter out and re-run the wait stats query."
            PAGELATCH_XX                     = "This is contention for access to in-memory copies of pages. The most well-known cases of these are the PFS and SGAM contention that can occur in tempdb under certain workloads. To find out what page the contention is on, you'll need to use the DMV sys.dm_os_waiting_tasks to figure out what page the latch is for. For tempdb issues, Robert Davis (blog | twitter) has a good post showing how to do this. Another common cause I've seen is an index hot-spot with concurrent inserts into an index with an identity value key."
            LATCH_XX                         = "This is contention for some non-page structure inside SQL Server - so not related to I/O or data at all. These can be hard to figure out and you're going to be using the DMV sys.dm_os_latch_stats. More on this in my Latches category."
            PREEMPTIVE_OS_PIPEOPS            = "This is SQL Server switching to preemptive scheduling mode to call out to Windows for something, and this particular wait is usually from using xp_cmdshell. These were added for 2008 and aren't documented anywhere except through the links to my waits library."
            THREADPOOL                       = "This says that there aren't enough worker threads on the system to satisfy demand. Commonly this is large numbers of high-DOP queries trying to execute and taking all the threads from the thread pool."
            BROKER_TRANSMITTER               = "This is just Service Broker waiting around for new messages to send. I would add this to the list of waits to filter out and re-run the wait stats query."
            SQLTRACE_WAIT_ENTRIES            = "Part of SQL Trace. I would add this to the list of waits to filter out and re-run the wait stats query."
            DBMIRROR_DBM_MUTEX               = "This one is undocumented and is contention for the send buffer that database mirroring shares between all the mirroring sessions on a server. It could indicate that you've got too many mirroring sessions."
            RESOURCE_SEMAPHORE               = "This is queries waiting for execution memory (the memory used to process the query operators - like a sort). This could be memory pressure or a very high concurrent workload."
            PREEMPTIVE_OS_AUTHENTICATIONOPS  = "These are SQL Server switching to preemptive scheduling mode to call out to Windows for something. These were added for 2008 and aren't documented anywhere except through the links to my waits library."
            PREEMPTIVE_OS_GENERICOPS         = "These are SQL Server switching to preemptive scheduling mode to call out to Windows for something. These were added for 2008 and aren't documented anywhere except through the links to my waits library."
            SLEEP_BPOOL_FLUSH                = "This is normal to see and indicates that checkpoint is throttling itself to avoid overloading the IO subsystem. I would add this to the list of waits to filter out and re-run the wait stats query."
            MSQL_DQ                          = "This is SQL Server waiting for a distributed query to finish. This could indicate a problem with the distributed query, or it could just be normal."
            RESOURCE_SEMAPHORE_QUERY_COMPILE = "When there are too many concurrent query compilations going on, SQL Server will throttle them. I don't remember the threshold, but this can indicate excessive recompilation, or maybe single-use plans."
            DAC_INIT                         = "This is the Dedicated Admin Connection initializing."
            MSSEARCH                         = "This is normal to see for full-text operations.  If this is the highest wait, it could mean your system is spending most of its time doing full-text queries. You might want to consider adding this to the filter list."
            PREEMPTIVE_OS_FILEOPS            = "These are SQL Server switching to preemptive scheduling mode to call out to Windows for something. These were added for 2008 and aren't documented anywhere except through the links to my waits library."
            PREEMPTIVE_OS_LIBRARYOPS         = "These are SQL Server switching to preemptive scheduling mode to call out to Windows for something. These were added for 2008 and aren't documented anywhere except through the links to my waits library."
            PREEMPTIVE_OS_LOOKUPACCOUNTSID   = "These are SQL Server switching to preemptive scheduling mode to call out to Windows for something. These were added for 2008 and aren't documented anywhere except through the links to my waits library."
            PREEMPTIVE_OS_QUERYREGISTRY      = "These are SQL Server switching to preemptive scheduling mode to call out to Windows for something. These were added for 2008 and aren't documented anywhere except through the links to my waits library."
            SQLTRACE_LOCK                    = "Part of SQL Trace. I would add this to the list of waits to filter out and re-run the wait stats query."
        }

        # Thanks Brent Ozar via https://gist.github.com/BrentOzar/42e82ee0603a1917c17d74c3fca26d34
        # Thanks Marcin Gminski via https://www.dropbox.com/s/x3zr7u18tc1ojey/WaitStats.sql?dl=0

        $category = [pscustomobject]@{
            ASYNC_IO_COMPLETION                             = 'Other Disk IO'
            ASYNC_NETWORK_IO                                = 'Network IO'
            BACKUPIO                                        = 'Other Disk IO'
            BROKER_CONNECTION_RECEIVE_TASK                  = 'Service Broker'
            BROKER_DISPATCHER                               = 'Service Broker'
            BROKER_ENDPOINT_STATE_MUTEX                     = 'Service Broker'
            BROKER_EVENTHANDLER                             = 'Service Broker'
            BROKER_FORWARDER                                = 'Service Broker'
            BROKER_INIT                                     = 'Service Broker'
            BROKER_MASTERSTART                              = 'Service Broker'
            BROKER_RECEIVE_WAITFOR                          = 'User Wait'
            BROKER_REGISTERALLENDPOINTS                     = 'Service Broker'
            BROKER_SERVICE                                  = 'Service Broker'
            BROKER_SHUTDOWN                                 = 'Service Broker'
            BROKER_START                                    = 'Service Broker'
            BROKER_TASK_SHUTDOWN                            = 'Service Broker'
            BROKER_TASK_STOP                                = 'Service Broker'
            BROKER_TASK_SUBMIT                              = 'Service Broker'
            BROKER_TO_FLUSH                                 = 'Service Broker'
            BROKER_TRANSMISSION_OBJECT                      = 'Service Broker'
            BROKER_TRANSMISSION_TABLE                       = 'Service Broker'
            BROKER_TRANSMISSION_WORK                        = 'Service Broker'
            BROKER_TRANSMITTER                              = 'Service Broker'
            CHECKPOINT_QUEUE                                = 'Idle'
            CHKPT                                           = 'Tran Log IO'
            CLR_AUTO_EVENT                                  = 'SQL CLR'
            CLR_CRST                                        = 'SQL CLR'
            CLR_JOIN                                        = 'SQL CLR'
            CLR_MANUAL_EVENT                                = 'SQL CLR'
            CLR_MEMORY_SPY                                  = 'SQL CLR'
            CLR_MONITOR                                     = 'SQL CLR'
            CLR_RWLOCK_READER                               = 'SQL CLR'
            CLR_RWLOCK_WRITER                               = 'SQL CLR'
            CLR_SEMAPHORE                                   = 'SQL CLR'
            CLR_TASK_START                                  = 'SQL CLR'
            CLRHOST_STATE_ACCESS                            = 'SQL CLR'
            CMEMPARTITIONED                                 = 'Memory'
            CMEMTHREAD                                      = 'Memory'
            CXPACKET                                        = 'Parallelism'
            DBMIRROR_DBM_EVENT                              = 'Mirroring'
            DBMIRROR_DBM_MUTEX                              = 'Mirroring'
            DBMIRROR_EVENTS_QUEUE                           = 'Mirroring'
            DBMIRROR_SEND                                   = 'Mirroring'
            DBMIRROR_WORKER_QUEUE                           = 'Mirroring'
            DBMIRRORING_CMD                                 = 'Mirroring'
            DTC                                             = 'Transaction'
            DTC_ABORT_REQUEST                               = 'Transaction'
            DTC_RESOLVE                                     = 'Transaction'
            DTC_STATE                                       = 'Transaction'
            DTC_TMDOWN_REQUEST                              = 'Transaction'
            DTC_WAITFOR_OUTCOME                             = 'Transaction'
            DTCNEW_ENLIST                                   = 'Transaction'
            DTCNEW_PREPARE                                  = 'Transaction'
            DTCNEW_RECOVERY                                 = 'Transaction'
            DTCNEW_TM                                       = 'Transaction'
            DTCNEW_TRANSACTION_ENLISTMENT                   = 'Transaction'
            DTCPNTSYNC                                      = 'Transaction'
            EE_PMOLOCK                                      = 'Memory'
            EXCHANGE                                        = 'Parallelism'
            EXTERNAL_SCRIPT_NETWORK_IOF                     = 'Network IO'
            FCB_REPLICA_READ                                = 'Replication'
            FCB_REPLICA_WRITE                               = 'Replication'
            FT_COMPROWSET_RWLOCK                            = 'Full Text Search'
            FT_IFTS_RWLOCK                                  = 'Full Text Search'
            FT_IFTS_SCHEDULER_IDLE_WAIT                     = 'Idle'
            FT_IFTSHC_MUTEX                                 = 'Full Text Search'
            FT_IFTSISM_MUTEX                                = 'Full Text Search'
            FT_MASTER_MERGE                                 = 'Full Text Search'
            FT_MASTER_MERGE_COORDINATOR                     = 'Full Text Search'
            FT_METADATA_MUTEX                               = 'Full Text Search'
            FT_PROPERTYLIST_CACHE                           = 'Full Text Search'
            FT_RESTART_CRAWL                                = 'Full Text Search'
            'FULLTEXT GATHERER'                             = 'Full Text Search'
            HADR_AG_MUTEX                                   = 'Replication'
            HADR_AR_CRITICAL_SECTION_ENTRY                  = 'Replication'
            HADR_AR_MANAGER_MUTEX                           = 'Replication'
            HADR_AR_UNLOAD_COMPLETED                        = 'Replication'
            HADR_ARCONTROLLER_NOTIFICATIONS_SUBSCRIBER_LIST = 'Replication'
            HADR_BACKUP_BULK_LOCK                           = 'Replication'
            HADR_BACKUP_QUEUE                               = 'Replication'
            HADR_CLUSAPI_CALL                               = 'Replication'
            HADR_COMPRESSED_CACHE_SYNC                      = 'Replication'
            HADR_CONNECTIVITY_INFO                          = 'Replication'
            HADR_DATABASE_FLOW_CONTROL                      = 'Replication'
            HADR_DATABASE_VERSIONING_STATE                  = 'Replication'
            HADR_DATABASE_WAIT_FOR_RECOVERY                 = 'Replication'
            HADR_DATABASE_WAIT_FOR_RESTART                  = 'Replication'
            HADR_DATABASE_WAIT_FOR_TRANSITION_TO_VERSIONING = 'Replication'
            HADR_DB_COMMAND                                 = 'Replication'
            HADR_DB_OP_COMPLETION_SYNC                      = 'Replication'
            HADR_DB_OP_START_SYNC                           = 'Replication'
            HADR_DBR_SUBSCRIBER                             = 'Replication'
            HADR_DBR_SUBSCRIBER_FILTER_LIST                 = 'Replication'
            HADR_DBSEEDING                                  = 'Replication'
            HADR_DBSEEDING_LIST                             = 'Replication'
            HADR_DBSTATECHANGE_SYNC                         = 'Replication'
            HADR_FABRIC_CALLBACK                            = 'Replication'
            HADR_FILESTREAM_BLOCK_FLUSH                     = 'Replication'
            HADR_FILESTREAM_FILE_CLOSE                      = 'Replication'
            HADR_FILESTREAM_FILE_REQUEST                    = 'Replication'
            HADR_FILESTREAM_IOMGR                           = 'Replication'
            HADR_FILESTREAM_IOMGR_IOCOMPLETION              = 'Replication'
            HADR_FILESTREAM_MANAGER                         = 'Replication'
            HADR_FILESTREAM_PREPROC                         = 'Replication'
            HADR_GROUP_COMMIT                               = 'Replication'
            HADR_LOGCAPTURE_SYNC                            = 'Replication'
            HADR_LOGCAPTURE_WAIT                            = 'Replication'
            HADR_LOGPROGRESS_SYNC                           = 'Replication'
            HADR_NOTIFICATION_DEQUEUE                       = 'Replication'
            HADR_NOTIFICATION_WORKER_EXCLUSIVE_ACCESS       = 'Replication'
            HADR_NOTIFICATION_WORKER_STARTUP_SYNC           = 'Replication'
            HADR_NOTIFICATION_WORKER_TERMINATION_SYNC       = 'Replication'
            HADR_PARTNER_SYNC                               = 'Replication'
            HADR_READ_ALL_NETWORKS                          = 'Replication'
            HADR_RECOVERY_WAIT_FOR_CONNECTION               = 'Replication'
            HADR_RECOVERY_WAIT_FOR_UNDO                     = 'Replication'
            HADR_REPLICAINFO_SYNC                           = 'Replication'
            HADR_SEEDING_CANCELLATION                       = 'Replication'
            HADR_SEEDING_FILE_LIST                          = 'Replication'
            HADR_SEEDING_LIMIT_BACKUPS                      = 'Replication'
            HADR_SEEDING_SYNC_COMPLETION                    = 'Replication'
            HADR_SEEDING_TIMEOUT_TASK                       = 'Replication'
            HADR_SEEDING_WAIT_FOR_COMPLETION                = 'Replication'
            HADR_SYNC_COMMIT                                = 'Replication'
            HADR_SYNCHRONIZING_THROTTLE                     = 'Replication'
            HADR_TDS_LISTENER_SYNC                          = 'Replication'
            HADR_TDS_LISTENER_SYNC_PROCESSING               = 'Replication'
            HADR_THROTTLE_LOG_RATE_GOVERNOR                 = 'Log Rate Governor'
            HADR_TIMER_TASK                                 = 'Replication'
            HADR_TRANSPORT_DBRLIST                          = 'Replication'
            HADR_TRANSPORT_FLOW_CONTROL                     = 'Replication'
            HADR_TRANSPORT_SESSION                          = 'Replication'
            HADR_WORK_POOL                                  = 'Replication'
            HADR_WORK_QUEUE                                 = 'Replication'
            HADR_XRF_STACK_ACCESS                           = 'Replication'
            INSTANCE_LOG_RATE_GOVERNOR                      = 'Log Rate Governor'
            IO_COMPLETION                                   = 'Other Disk IO'
            IO_QUEUE_LIMIT                                  = 'Other Disk IO'
            IO_RETRY                                        = 'Other Disk IO'
            LATCH_DT                                        = 'Latch'
            LATCH_EX                                        = 'Latch'
            LATCH_KP                                        = 'Latch'
            LATCH_NL                                        = 'Latch'
            LATCH_SH                                        = 'Latch'
            LATCH_UP                                        = 'Latch'
            LAZYWRITER_SLEEP                                = 'Idle'
            LCK_M_BU                                        = 'Lock'
            LCK_M_BU_ABORT_BLOCKERS                         = 'Lock'
            LCK_M_BU_LOW_PRIORITY                           = 'Lock'
            LCK_M_IS                                        = 'Lock'
            LCK_M_IS_ABORT_BLOCKERS                         = 'Lock'
            LCK_M_IS_LOW_PRIORITY                           = 'Lock'
            LCK_M_IU                                        = 'Lock'
            LCK_M_IU_ABORT_BLOCKERS                         = 'Lock'
            LCK_M_IU_LOW_PRIORITY                           = 'Lock'
            LCK_M_IX                                        = 'Lock'
            LCK_M_IX_ABORT_BLOCKERS                         = 'Lock'
            LCK_M_IX_LOW_PRIORITY                           = 'Lock'
            LCK_M_RIn_NL                                    = 'Lock'
            LCK_M_RIn_NL_ABORT_BLOCKERS                     = 'Lock'
            LCK_M_RIn_NL_LOW_PRIORITY                       = 'Lock'
            LCK_M_RIn_S                                     = 'Lock'
            LCK_M_RIn_S_ABORT_BLOCKERS                      = 'Lock'
            LCK_M_RIn_S_LOW_PRIORITY                        = 'Lock'
            LCK_M_RIn_U                                     = 'Lock'
            LCK_M_RIn_U_ABORT_BLOCKERS                      = 'Lock'
            LCK_M_RIn_U_LOW_PRIORITY                        = 'Lock'
            LCK_M_RIn_X                                     = 'Lock'
            LCK_M_RIn_X_ABORT_BLOCKERS                      = 'Lock'
            LCK_M_RIn_X_LOW_PRIORITY                        = 'Lock'
            LCK_M_RS_S                                      = 'Lock'
            LCK_M_RS_S_ABORT_BLOCKERS                       = 'Lock'
            LCK_M_RS_S_LOW_PRIORITY                         = 'Lock'
            LCK_M_RS_U                                      = 'Lock'
            LCK_M_RS_U_ABORT_BLOCKERS                       = 'Lock'
            LCK_M_RS_U_LOW_PRIORITY                         = 'Lock'
            LCK_M_RX_S                                      = 'Lock'
            LCK_M_RX_S_ABORT_BLOCKERS                       = 'Lock'
            LCK_M_RX_S_LOW_PRIORITY                         = 'Lock'
            LCK_M_RX_U                                      = 'Lock'
            LCK_M_RX_U_ABORT_BLOCKERS                       = 'Lock'
            LCK_M_RX_U_LOW_PRIORITY                         = 'Lock'
            LCK_M_RX_X                                      = 'Lock'
            LCK_M_RX_X_ABORT_BLOCKERS                       = 'Lock'
            LCK_M_RX_X_LOW_PRIORITY                         = 'Lock'
            LCK_M_S                                         = 'Lock'
            LCK_M_S_ABORT_BLOCKERS                          = 'Lock'
            LCK_M_S_LOW_PRIORITY                            = 'Lock'
            LCK_M_SCH_M                                     = 'Lock'
            LCK_M_SCH_M_ABORT_BLOCKERS                      = 'Lock'
            LCK_M_SCH_M_LOW_PRIORITY                        = 'Lock'
            LCK_M_SCH_S                                     = 'Lock'
            LCK_M_SCH_S_ABORT_BLOCKERS                      = 'Lock'
            LCK_M_SCH_S_LOW_PRIORITY                        = 'Lock'
            LCK_M_SIU                                       = 'Lock'
            LCK_M_SIU_ABORT_BLOCKERS                        = 'Lock'
            LCK_M_SIU_LOW_PRIORITY                          = 'Lock'
            LCK_M_SIX                                       = 'Lock'
            LCK_M_SIX_ABORT_BLOCKERS                        = 'Lock'
            LCK_M_SIX_LOW_PRIORITY                          = 'Lock'
            LCK_M_U                                         = 'Lock'
            LCK_M_U_ABORT_BLOCKERS                          = 'Lock'
            LCK_M_U_LOW_PRIORITY                            = 'Lock'
            LCK_M_UIX                                       = 'Lock'
            LCK_M_UIX_ABORT_BLOCKERS                        = 'Lock'
            LCK_M_UIX_LOW_PRIORITY                          = 'Lock'
            LCK_M_X                                         = 'Lock'
            LCK_M_X_ABORT_BLOCKERS                          = 'Lock'
            LCK_M_X_LOW_PRIORITY                            = 'Lock'
            LOGBUFFER                                       = 'Tran Log IO'
            LOGMGR                                          = 'Tran Log IO'
            LOGMGR_FLUSH                                    = 'Tran Log IO'
            LOGMGR_PMM_LOG                                  = 'Tran Log IO'
            LOGMGR_QUEUE                                    = 'Idle'
            LOGMGR_RESERVE_APPEND                           = 'Tran Log IO'
            MEMORY_ALLOCATION_EXT                           = 'Memory'
            MEMORY_GRANT_UPDATE                             = 'Memory'
            MSQL_XACT_MGR_MUTEX                             = 'Transaction'
            MSQL_XACT_MUTEX                                 = 'Transaction'
            MSSEARCH                                        = 'Full Text Search'
            NET_WAITFOR_PACKET                              = 'Network IO'
            ONDEMAND_TASK_QUEUE                             = 'Idle'
            PAGEIOLATCH_DT                                  = 'Buffer IO'
            PAGEIOLATCH_EX                                  = 'Buffer IO'
            PAGEIOLATCH_KP                                  = 'Buffer IO'
            PAGEIOLATCH_NL                                  = 'Buffer IO'
            PAGEIOLATCH_SH                                  = 'Buffer IO'
            PAGEIOLATCH_UP                                  = 'Buffer IO'
            PAGELATCH_DT                                    = 'Buffer Latch'
            PAGELATCH_EX                                    = 'Buffer Latch'
            PAGELATCH_KP                                    = 'Buffer Latch'
            PAGELATCH_NL                                    = 'Buffer Latch'
            PAGELATCH_SH                                    = 'Buffer Latch'
            PAGELATCH_UP                                    = 'Buffer Latch'
            POOL_LOG_RATE_GOVERNOR                          = 'Log Rate Governor'
            PREEMPTIVE_ABR                                  = 'Preemptive'
            PREEMPTIVE_CLOSEBACKUPMEDIA                     = 'Preemptive'
            PREEMPTIVE_CLOSEBACKUPTAPE                      = 'Preemptive'
            PREEMPTIVE_CLOSEBACKUPVDIDEVICE                 = 'Preemptive'
            PREEMPTIVE_CLUSAPI_CLUSTERRESOURCECONTROL       = 'Preemptive'
            PREEMPTIVE_COM_COCREATEINSTANCE                 = 'Preemptive'
            PREEMPTIVE_COM_COGETCLASSOBJECT                 = 'Preemptive'
            PREEMPTIVE_COM_CREATEACCESSOR                   = 'Preemptive'
            PREEMPTIVE_COM_DELETEROWS                       = 'Preemptive'
            PREEMPTIVE_COM_GETCOMMANDTEXT                   = 'Preemptive'
            PREEMPTIVE_COM_GETDATA                          = 'Preemptive'
            PREEMPTIVE_COM_GETNEXTROWS                      = 'Preemptive'
            PREEMPTIVE_COM_GETRESULT                        = 'Preemptive'
            PREEMPTIVE_COM_GETROWSBYBOOKMARK                = 'Preemptive'
            PREEMPTIVE_COM_LBFLUSH                          = 'Preemptive'
            PREEMPTIVE_COM_LBLOCKREGION                     = 'Preemptive'
            PREEMPTIVE_COM_LBREADAT                         = 'Preemptive'
            PREEMPTIVE_COM_LBSETSIZE                        = 'Preemptive'
            PREEMPTIVE_COM_LBSTAT                           = 'Preemptive'
            PREEMPTIVE_COM_LBUNLOCKREGION                   = 'Preemptive'
            PREEMPTIVE_COM_LBWRITEAT                        = 'Preemptive'
            PREEMPTIVE_COM_QUERYINTERFACE                   = 'Preemptive'
            PREEMPTIVE_COM_RELEASE                          = 'Preemptive'
            PREEMPTIVE_COM_RELEASEACCESSOR                  = 'Preemptive'
            PREEMPTIVE_COM_RELEASEROWS                      = 'Preemptive'
            PREEMPTIVE_COM_RELEASESESSION                   = 'Preemptive'
            PREEMPTIVE_COM_RESTARTPOSITION                  = 'Preemptive'
            PREEMPTIVE_COM_SEQSTRMREAD                      = 'Preemptive'
            PREEMPTIVE_COM_SEQSTRMREADANDWRITE              = 'Preemptive'
            PREEMPTIVE_COM_SETDATAFAILURE                   = 'Preemptive'
            PREEMPTIVE_COM_SETPARAMETERINFO                 = 'Preemptive'
            PREEMPTIVE_COM_SETPARAMETERPROPERTIES           = 'Preemptive'
            PREEMPTIVE_COM_STRMLOCKREGION                   = 'Preemptive'
            PREEMPTIVE_COM_STRMSEEKANDREAD                  = 'Preemptive'
            PREEMPTIVE_COM_STRMSEEKANDWRITE                 = 'Preemptive'
            PREEMPTIVE_COM_STRMSETSIZE                      = 'Preemptive'
            PREEMPTIVE_COM_STRMSTAT                         = 'Preemptive'
            PREEMPTIVE_COM_STRMUNLOCKREGION                 = 'Preemptive'
            PREEMPTIVE_CONSOLEWRITE                         = 'Preemptive'
            PREEMPTIVE_CREATEPARAM                          = 'Preemptive'
            PREEMPTIVE_DEBUG                                = 'Preemptive'
            PREEMPTIVE_DFSADDLINK                           = 'Preemptive'
            PREEMPTIVE_DFSLINKEXISTCHECK                    = 'Preemptive'
            PREEMPTIVE_DFSLINKHEALTHCHECK                   = 'Preemptive'
            PREEMPTIVE_DFSREMOVELINK                        = 'Preemptive'
            PREEMPTIVE_DFSREMOVEROOT                        = 'Preemptive'
            PREEMPTIVE_DFSROOTFOLDERCHECK                   = 'Preemptive'
            PREEMPTIVE_DFSROOTINIT                          = 'Preemptive'
            PREEMPTIVE_DFSROOTSHARECHECK                    = 'Preemptive'
            PREEMPTIVE_DTC_ABORT                            = 'Preemptive'
            PREEMPTIVE_DTC_ABORTREQUESTDONE                 = 'Preemptive'
            PREEMPTIVE_DTC_BEGINTRANSACTION                 = 'Preemptive'
            PREEMPTIVE_DTC_COMMITREQUESTDONE                = 'Preemptive'
            PREEMPTIVE_DTC_ENLIST                           = 'Preemptive'
            PREEMPTIVE_DTC_PREPAREREQUESTDONE               = 'Preemptive'
            PREEMPTIVE_FILESIZEGET                          = 'Preemptive'
            PREEMPTIVE_FSAOLEDB_ABORTTRANSACTION            = 'Preemptive'
            PREEMPTIVE_FSAOLEDB_COMMITTRANSACTION           = 'Preemptive'
            PREEMPTIVE_FSAOLEDB_STARTTRANSACTION            = 'Preemptive'
            PREEMPTIVE_FSRECOVER_UNCONDITIONALUNDO          = 'Preemptive'
            PREEMPTIVE_GETRMINFO                            = 'Preemptive'
            PREEMPTIVE_HADR_LEASE_MECHANISM                 = 'Preemptive'
            PREEMPTIVE_HTTP_EVENT_WAIT                      = 'Preemptive'
            PREEMPTIVE_HTTP_REQUEST                         = 'Preemptive'
            PREEMPTIVE_LOCKMONITOR                          = 'Preemptive'
            PREEMPTIVE_MSS_RELEASE                          = 'Preemptive'
            PREEMPTIVE_ODBCOPS                              = 'Preemptive'
            PREEMPTIVE_OLE_UNINIT                           = 'Preemptive'
            PREEMPTIVE_OLEDB_ABORTORCOMMITTRAN              = 'Preemptive'
            PREEMPTIVE_OLEDB_ABORTTRAN                      = 'Preemptive'
            PREEMPTIVE_OLEDB_GETDATASOURCE                  = 'Preemptive'
            PREEMPTIVE_OLEDB_GETLITERALINFO                 = 'Preemptive'
            PREEMPTIVE_OLEDB_GETPROPERTIES                  = 'Preemptive'
            PREEMPTIVE_OLEDB_GETPROPERTYINFO                = 'Preemptive'
            PREEMPTIVE_OLEDB_GETSCHEMALOCK                  = 'Preemptive'
            PREEMPTIVE_OLEDB_JOINTRANSACTION                = 'Preemptive'
            PREEMPTIVE_OLEDB_RELEASE                        = 'Preemptive'
            PREEMPTIVE_OLEDB_SETPROPERTIES                  = 'Preemptive'
            PREEMPTIVE_OLEDBOPS                             = 'Preemptive'
            PREEMPTIVE_OS_ACCEPTSECURITYCONTEXT             = 'Preemptive'
            PREEMPTIVE_OS_ACQUIRECREDENTIALSHANDLE          = 'Preemptive'
            PREEMPTIVE_OS_AUTHENTICATIONOPS                 = 'Preemptive'
            PREEMPTIVE_OS_AUTHORIZATIONOPS                  = 'Preemptive'
            PREEMPTIVE_OS_AUTHZGETINFORMATIONFROMCONTEXT    = 'Preemptive'
            PREEMPTIVE_OS_AUTHZINITIALIZECONTEXTFROMSID     = 'Preemptive'
            PREEMPTIVE_OS_AUTHZINITIALIZERESOURCEMANAGER    = 'Preemptive'
            PREEMPTIVE_OS_BACKUPREAD                        = 'Preemptive'
            PREEMPTIVE_OS_CLOSEHANDLE                       = 'Preemptive'
            PREEMPTIVE_OS_CLUSTEROPS                        = 'Preemptive'
            PREEMPTIVE_OS_COMOPS                            = 'Preemptive'
            PREEMPTIVE_OS_COMPLETEAUTHTOKEN                 = 'Preemptive'
            PREEMPTIVE_OS_COPYFILE                          = 'Preemptive'
            PREEMPTIVE_OS_CREATEDIRECTORY                   = 'Preemptive'
            PREEMPTIVE_OS_CREATEFILE                        = 'Preemptive'
            PREEMPTIVE_OS_CRYPTACQUIRECONTEXT               = 'Preemptive'
            PREEMPTIVE_OS_CRYPTIMPORTKEY                    = 'Preemptive'
            PREEMPTIVE_OS_CRYPTOPS                          = 'Preemptive'
            PREEMPTIVE_OS_DECRYPTMESSAGE                    = 'Preemptive'
            PREEMPTIVE_OS_DELETEFILE                        = 'Preemptive'
            PREEMPTIVE_OS_DELETESECURITYCONTEXT             = 'Preemptive'
            PREEMPTIVE_OS_DEVICEIOCONTROL                   = 'Preemptive'
            PREEMPTIVE_OS_DEVICEOPS                         = 'Preemptive'
            PREEMPTIVE_OS_DIRSVC_NETWORKOPS                 = 'Preemptive'
            PREEMPTIVE_OS_DISCONNECTNAMEDPIPE               = 'Preemptive'
            PREEMPTIVE_OS_DOMAINSERVICESOPS                 = 'Preemptive'
            PREEMPTIVE_OS_DSGETDCNAME                       = 'Preemptive'
            PREEMPTIVE_OS_DTCOPS                            = 'Preemptive'
            PREEMPTIVE_OS_ENCRYPTMESSAGE                    = 'Preemptive'
            PREEMPTIVE_OS_FILEOPS                           = 'Preemptive'
            PREEMPTIVE_OS_FINDFILE                          = 'Preemptive'
            PREEMPTIVE_OS_FLUSHFILEBUFFERS                  = 'Preemptive'
            PREEMPTIVE_OS_FORMATMESSAGE                     = 'Preemptive'
            PREEMPTIVE_OS_FREECREDENTIALSHANDLE             = 'Preemptive'
            PREEMPTIVE_OS_FREELIBRARY                       = 'Preemptive'
            PREEMPTIVE_OS_GENERICOPS                        = 'Preemptive'
            PREEMPTIVE_OS_GETADDRINFO                       = 'Preemptive'
            PREEMPTIVE_OS_GETCOMPRESSEDFILESIZE             = 'Preemptive'
            PREEMPTIVE_OS_GETDISKFREESPACE                  = 'Preemptive'
            PREEMPTIVE_OS_GETFILEATTRIBUTES                 = 'Preemptive'
            PREEMPTIVE_OS_GETFILESIZE                       = 'Preemptive'
            PREEMPTIVE_OS_GETFINALFILEPATHBYHANDLE          = 'Preemptive'
            PREEMPTIVE_OS_GETLONGPATHNAME                   = 'Preemptive'
            PREEMPTIVE_OS_GETPROCADDRESS                    = 'Preemptive'
            PREEMPTIVE_OS_GETVOLUMENAMEFORVOLUMEMOUNTPOINT  = 'Preemptive'
            PREEMPTIVE_OS_GETVOLUMEPATHNAME                 = 'Preemptive'
            PREEMPTIVE_OS_INITIALIZESECURITYCONTEXT         = 'Preemptive'
            PREEMPTIVE_OS_LIBRARYOPS                        = 'Preemptive'
            PREEMPTIVE_OS_LOADLIBRARY                       = 'Preemptive'
            PREEMPTIVE_OS_LOGONUSER                         = 'Preemptive'
            PREEMPTIVE_OS_LOOKUPACCOUNTSID                  = 'Preemptive'
            PREEMPTIVE_OS_MESSAGEQUEUEOPS                   = 'Preemptive'
            PREEMPTIVE_OS_MOVEFILE                          = 'Preemptive'
            PREEMPTIVE_OS_NETGROUPGETUSERS                  = 'Preemptive'
            PREEMPTIVE_OS_NETLOCALGROUPGETMEMBERS           = 'Preemptive'
            PREEMPTIVE_OS_NETUSERGETGROUPS                  = 'Preemptive'
            PREEMPTIVE_OS_NETUSERGETLOCALGROUPS             = 'Preemptive'
            PREEMPTIVE_OS_NETUSERMODALSGET                  = 'Preemptive'
            PREEMPTIVE_OS_NETVALIDATEPASSWORDPOLICY         = 'Preemptive'
            PREEMPTIVE_OS_NETVALIDATEPASSWORDPOLICYFREE     = 'Preemptive'
            PREEMPTIVE_OS_OPENDIRECTORY                     = 'Preemptive'
            PREEMPTIVE_OS_PDH_WMI_INIT                      = 'Preemptive'
            PREEMPTIVE_OS_PIPEOPS                           = 'Preemptive'
            PREEMPTIVE_OS_PROCESSOPS                        = 'Preemptive'
            PREEMPTIVE_OS_QUERYCONTEXTATTRIBUTES            = 'Preemptive'
            PREEMPTIVE_OS_QUERYREGISTRY                     = 'Preemptive'
            PREEMPTIVE_OS_QUERYSECURITYCONTEXTTOKEN         = 'Preemptive'
            PREEMPTIVE_OS_REMOVEDIRECTORY                   = 'Preemptive'
            PREEMPTIVE_OS_REPORTEVENT                       = 'Preemptive'
            PREEMPTIVE_OS_REVERTTOSELF                      = 'Preemptive'
            PREEMPTIVE_OS_RSFXDEVICEOPS                     = 'Preemptive'
            PREEMPTIVE_OS_SECURITYOPS                       = 'Preemptive'
            PREEMPTIVE_OS_SERVICEOPS                        = 'Preemptive'
            PREEMPTIVE_OS_SETENDOFFILE                      = 'Preemptive'
            PREEMPTIVE_OS_SETFILEPOINTER                    = 'Preemptive'
            PREEMPTIVE_OS_SETFILEVALIDDATA                  = 'Preemptive'
            PREEMPTIVE_OS_SETNAMEDSECURITYINFO              = 'Preemptive'
            PREEMPTIVE_OS_SQLCLROPS                         = 'Preemptive'
            PREEMPTIVE_OS_SQMLAUNCH                         = 'Preemptive'
            PREEMPTIVE_OS_VERIFYSIGNATURE                   = 'Preemptive'
            PREEMPTIVE_OS_VERIFYTRUST                       = 'Preemptive'
            PREEMPTIVE_OS_VSSOPS                            = 'Preemptive'
            PREEMPTIVE_OS_WAITFORSINGLEOBJECT               = 'Preemptive'
            PREEMPTIVE_OS_WINSOCKOPS                        = 'Preemptive'
            PREEMPTIVE_OS_WRITEFILE                         = 'Preemptive'
            PREEMPTIVE_OS_WRITEFILEGATHER                   = 'Preemptive'
            PREEMPTIVE_OS_WSASETLASTERROR                   = 'Preemptive'
            PREEMPTIVE_REENLIST                             = 'Preemptive'
            PREEMPTIVE_RESIZELOG                            = 'Preemptive'
            PREEMPTIVE_ROLLFORWARDREDO                      = 'Preemptive'
            PREEMPTIVE_ROLLFORWARDUNDO                      = 'Preemptive'
            PREEMPTIVE_SB_STOPENDPOINT                      = 'Preemptive'
            PREEMPTIVE_SERVER_STARTUP                       = 'Preemptive'
            PREEMPTIVE_SETRMINFO                            = 'Preemptive'
            PREEMPTIVE_SHAREDMEM_GETDATA                    = 'Preemptive'
            PREEMPTIVE_SNIOPEN                              = 'Preemptive'
            PREEMPTIVE_SOSHOST                              = 'Preemptive'
            PREEMPTIVE_SOSTESTING                           = 'Preemptive'
            PREEMPTIVE_SP_SERVER_DIAGNOSTICS                = 'Preemptive'
            PREEMPTIVE_STARTRM                              = 'Preemptive'
            PREEMPTIVE_STREAMFCB_CHECKPOINT                 = 'Preemptive'
            PREEMPTIVE_STREAMFCB_RECOVER                    = 'Preemptive'
            PREEMPTIVE_STRESSDRIVER                         = 'Preemptive'
            PREEMPTIVE_TESTING                              = 'Preemptive'
            PREEMPTIVE_TRANSIMPORT                          = 'Preemptive'
            PREEMPTIVE_UNMARSHALPROPAGATIONTOKEN            = 'Preemptive'
            PREEMPTIVE_VSS_CREATESNAPSHOT                   = 'Preemptive'
            PREEMPTIVE_VSS_CREATEVOLUMESNAPSHOT             = 'Preemptive'
            PREEMPTIVE_XE_CALLBACKEXECUTE                   = 'Preemptive'
            PREEMPTIVE_XE_CX_FILE_OPEN                      = 'Preemptive'
            PREEMPTIVE_XE_CX_HTTP_CALL                      = 'Preemptive'
            PREEMPTIVE_XE_DISPATCHER                        = 'Preemptive'
            PREEMPTIVE_XE_ENGINEINIT                        = 'Preemptive'
            PREEMPTIVE_XE_GETTARGETSTATE                    = 'Preemptive'
            PREEMPTIVE_XE_SESSIONCOMMIT                     = 'Preemptive'
            PREEMPTIVE_XE_TARGETFINALIZE                    = 'Preemptive'
            PREEMPTIVE_XE_TARGETINIT                        = 'Preemptive'
            PREEMPTIVE_XE_TIMERRUN                          = 'Preemptive'
            PREEMPTIVE_XETESTING                            = 'Preemptive'
            PWAIT_HADR_ACTION_COMPLETED                     = 'Replication'
            PWAIT_HADR_CHANGE_NOTIFIER_TERMINATION_SYNC     = 'Replication'
            PWAIT_HADR_CLUSTER_INTEGRATION                  = 'Replication'
            PWAIT_HADR_FAILOVER_COMPLETED                   = 'Replication'
            PWAIT_HADR_JOIN                                 = 'Replication'
            PWAIT_HADR_OFFLINE_COMPLETED                    = 'Replication'
            PWAIT_HADR_ONLINE_COMPLETED                     = 'Replication'
            PWAIT_HADR_POST_ONLINE_COMPLETED                = 'Replication'
            PWAIT_HADR_SERVER_READY_CONNECTIONS             = 'Replication'
            PWAIT_HADR_WORKITEM_COMPLETED                   = 'Replication'
            PWAIT_HADRSIM                                   = 'Replication'
            PWAIT_RESOURCE_SEMAPHORE_FT_PARALLEL_QUERY_SYNC = 'Full Text Search'
            QUERY_TRACEOUT                                  = 'Tracing'
            REPL_CACHE_ACCESS                               = 'Replication'
            REPL_HISTORYCACHE_ACCESS                        = 'Replication'
            REPL_SCHEMA_ACCESS                              = 'Replication'
            REPL_TRANFSINFO_ACCESS                          = 'Replication'
            REPL_TRANHASHTABLE_ACCESS                       = 'Replication'
            REPL_TRANTEXTINFO_ACCESS                        = 'Replication'
            REPLICA_WRITES                                  = 'Replication'
            REQUEST_FOR_DEADLOCK_SEARCH                     = 'Idle'
            RESERVED_MEMORY_ALLOCATION_EXT                  = 'Memory'
            RESOURCE_SEMAPHORE                              = 'Memory'
            RESOURCE_SEMAPHORE_QUERY_COMPILE                = 'Compilation'
            SLEEP_BPOOL_FLUSH                               = 'Idle'
            SLEEP_BUFFERPOOL_HELPLW                         = 'Idle'
            SLEEP_DBSTARTUP                                 = 'Idle'
            SLEEP_DCOMSTARTUP                               = 'Idle'
            SLEEP_MASTERDBREADY                             = 'Idle'
            SLEEP_MASTERMDREADY                             = 'Idle'
            SLEEP_MASTERUPGRADED                            = 'Idle'
            SLEEP_MEMORYPOOL_ALLOCATEPAGES                  = 'Idle'
            SLEEP_MSDBSTARTUP                               = 'Idle'
            SLEEP_RETRY_VIRTUALALLOC                        = 'Idle'
            SLEEP_SYSTEMTASK                                = 'Idle'
            SLEEP_TASK                                      = 'Idle'
            SLEEP_TEMPDBSTARTUP                             = 'Idle'
            SLEEP_WORKSPACE_ALLOCATEPAGE                    = 'Idle'
            SOS_SCHEDULER_YIELD                             = 'CPU'
            SQLCLR_APPDOMAIN                                = 'SQL CLR'
            SQLCLR_ASSEMBLY                                 = 'SQL CLR'
            SQLCLR_DEADLOCK_DETECTION                       = 'SQL CLR'
            SQLCLR_QUANTUM_PUNISHMENT                       = 'SQL CLR'
            SQLTRACE_BUFFER_FLUSH                           = 'Idle'
            SQLTRACE_FILE_BUFFER                            = 'Tracing'
            SQLTRACE_FILE_READ_IO_COMPLETION                = 'Tracing'
            SQLTRACE_FILE_WRITE_IO_COMPLETION               = 'Tracing'
            SQLTRACE_INCREMENTAL_FLUSH_SLEEP                = 'Idle'
            SQLTRACE_PENDING_BUFFER_WRITERS                 = 'Tracing'
            SQLTRACE_SHUTDOWN                               = 'Tracing'
            SQLTRACE_WAIT_ENTRIES                           = 'Idle'
            THREADPOOL                                      = 'Worker Thread'
            TRACE_EVTNOTIF                                  = 'Tracing'
            TRACEWRITE                                      = 'Tracing'
            TRAN_MARKLATCH_DT                               = 'Transaction'
            TRAN_MARKLATCH_EX                               = 'Transaction'
            TRAN_MARKLATCH_KP                               = 'Transaction'
            TRAN_MARKLATCH_NL                               = 'Transaction'
            TRAN_MARKLATCH_SH                               = 'Transaction'
            TRAN_MARKLATCH_UP                               = 'Transaction'
            TRANSACTION_MUTEX                               = 'Transaction'
            WAIT_FOR_RESULTS                                = 'User Wait'
            WAITFOR                                         = 'User Wait'
            WRITE_COMPLETION                                = 'Other Disk IO'
            WRITELOG                                        = 'Tran Log IO'
            XACT_OWN_TRANSACTION                            = 'Transaction'
            XACT_RECLAIM_SESSION                            = 'Transaction'
            XACTLOCKINFO                                    = 'Transaction'
            XACTWORKSPACE_MUTEX                             = 'Transaction'
            XE_DISPATCHER_WAIT                              = 'Idle'
            XE_TIMER_EVENT                                  = 'Idle'
            ABR                                             = 'Other'
            ASSEMBLY_LOAD                                   = 'SQLCLR'
            ASYNC_DISKPOOL_LOCK                             = 'Buffer I/O'
            BACKUP                                          = 'Backup'
            BACKUP_CLIENTLOCK                               = 'Backup'
            BACKUP_OPERATOR                                 = 'Backup'
            BACKUPBUFFER                                    = 'Backup'
            BACKUPTHREAD                                    = 'Backup'
            BAD_PAGE_PROCESS                                = 'Other'
            BUILTIN_HASHKEY_MUTEX                           = 'Other'
            CHECK_PRINT_RECORD                              = 'Other'
            CPU                                             = 'CPU'
            CURSOR                                          = 'Other'
            CURSOR_ASYNC                                    = 'Other'
            DAC_INIT                                        = 'Other'
            DBCC_COLUMN_TRANSLATION_CACHE                   = 'Other'
            DBTABLE                                         = 'Other'
            DEADLOCK_ENUM_MUTEX                             = 'Latch'
            DEADLOCK_TASK_SEARCH                            = 'Other'
            DEBUG                                           = 'Other'
            DISABLE_VERSIONING                              = 'Other'
            DISKIO_SUSPEND                                  = 'Backup'
            DLL_LOADING_MUTEX                               = 'Other'
            DROPTEMP                                        = 'Other'
            DUMP_LOG_COORDINATOR                            = 'Other'
            DUMP_LOG_COORDINATOR_QUEUE                      = 'Other'
            DUMPTRIGGER                                     = 'Other'
            EC                                              = 'Other'
            EE_SPECPROC_MAP_INIT                            = 'Other'
            ENABLE_VERSIONING                               = 'Other'
            ERROR_REPORTING_MANAGER                         = 'Other'
            EXECSYNC                                        = 'Parallelism'
            EXECUTION_PIPE_EVENT_INTERNAL                   = 'Other'
            FAILPOINT                                       = 'Other'
            FS_GARBAGE_COLLECTOR_SHUTDOWN                   = 'SQLCLR'
            FSAGENT                                         = 'Idle'
            FT_RESUME_CRAWL                                 = 'Other'
            GUARDIAN                                        = 'Other'
            HTTP_ENDPOINT_COLLCREATE                        = 'Other'
            HTTP_ENUMERATION                                = 'Other'
            HTTP_START                                      = 'Other'
            IMP_IMPORT_MUTEX                                = 'Other'
            IMPPROV_IOWAIT                                  = 'Other'
            INDEX_USAGE_STATS_MUTEX                         = 'Latch'
            INTERNAL_TESTING                                = 'Other'
            IO_AUDIT_MUTEX                                  = 'Other'
            KSOURCE_WAKEUP                                  = 'Idle'
            KTM_ENLISTMENT                                  = 'Other'
            KTM_RECOVERY_MANAGER                            = 'Other'
            KTM_RECOVERY_RESOLUTION                         = 'Other'
            LOWFAIL_MEMMGR_QUEUE                            = 'Memory'
            MIRROR_SEND_MESSAGE                             = 'Other'
            MISCELLANEOUS                                   = 'Other'
            MSQL_DQ                                         = 'Network I/O'
            MSQL_SYNC_PIPE                                  = 'Other'
            MSQL_XP                                         = 'Other'
            OLEDB                                           = 'Network I/O'
            PARALLEL_BACKUP_QUEUE                           = 'Other'
            PRINT_ROLLBACK_PROGRESS                         = 'Other'
            QNMANAGER_ACQUIRE                               = 'Other'
            QPJOB_KILL                                      = 'Other'
            QPJOB_WAITFOR_ABORT                             = 'Other'
            QRY_MEM_GRANT_INFO_MUTEX                        = 'Other'
            QUERY_ERRHDL_SERVICE_DONE                       = 'Other'
            QUERY_EXECUTION_INDEX_SORT_EVENT_OPEN           = 'Other'
            QUERY_NOTIFICATION_MGR_MUTEX                    = 'Other'
            QUERY_NOTIFICATION_SUBSCRIPTION_MUTEX           = 'Other'
            QUERY_NOTIFICATION_TABLE_MGR_MUTEX              = 'Other'
            QUERY_NOTIFICATION_UNITTEST_MUTEX               = 'Other'
            QUERY_OPTIMIZER_PRINT_MUTEX                     = 'Other'
            QUERY_REMOTE_BRICKS_DONE                        = 'Other'
            RECOVER_CHANGEDB                                = 'Other'
            REQUEST_DISPENSER_PAUSE                         = 'Other'
            RESOURCE_QUEUE                                  = 'Idle'
            RESOURCE_SEMAPHORE_MUTEX                        = 'Compilation'
            RESOURCE_SEMAPHORE_SMALL_QUERY                  = 'Compilation'
            SEC_DROP_TEMP_KEY                               = 'Other'
            SEQUENTIAL_GUID                                 = 'Other'
            SERVER_IDLE_CHECK                               = 'Idle'
            SHUTDOWN                                        = 'Other'
            SNI_CRITICAL_SECTION                            = 'Other'
            SNI_HTTP_ACCEPT                                 = 'Idle'
            SNI_HTTP_WAITFOR_0_DISCON                       = 'Other'
            SNI_LISTENER_ACCESS                             = 'Other'
            SNI_TASK_COMPLETION                             = 'Other'
            SOAP_READ                                       = 'Full Text Search'
            SOAP_WRITE                                      = 'Full Text Search'
            SOS_CALLBACK_REMOVAL                            = 'Other'
            SOS_DISPATCHER_MUTEX                            = 'Other'
            SOS_LOCALALLOCATORLIST                          = 'Other'
            SOS_OBJECT_STORE_DESTROY_MUTEX                  = 'Other'
            SOS_PROCESS_AFFINITY_MUTEX                      = 'Other'
            SOS_RESERVEDMEMBLOCKLIST                        = 'Memory'
            SOS_STACKSTORE_INIT_MUTEX                       = 'Other'
            SOS_SYNC_TASK_ENQUEUE_EVENT                     = 'Other'
            SOS_VIRTUALMEMORY_LOW                           = 'Memory'
            SOSHOST_EVENT                                   = 'Other'
            SOSHOST_INTERNAL                                = 'Other'
            SOSHOST_MUTEX                                   = 'Other'
            SOSHOST_RWLOCK                                  = 'Other'
            SOSHOST_SEMAPHORE                               = 'Other'
            SOSHOST_SLEEP                                   = 'Other'
            SOSHOST_TRACELOCK                               = 'Other'
            SOSHOST_WAITFORDONE                             = 'Other'
            SQLSORT_NORMMUTEX                               = 'Other'
            SQLSORT_SORTMUTEX                               = 'Other'
            SQLTRACE_LOCK                                   = 'Other'
            SRVPROC_SHUTDOWN                                = 'Other'
            TEMPOBJ                                         = 'Other'
            TIMEPRIV_TIMEPERIOD                             = 'Other'
            UTIL_PAGE_ALLOC                                 = 'Memory'
            VIA_ACCEPT                                      = 'Other'
            VIEW_DEFINITION_MUTEX                           = 'Latch'
            WAITFOR_TASKSHUTDOWN                            = 'Idle'
            WAITSTAT_MUTEX                                  = 'Other'
            WCC                                             = 'Other'
            WORKTBL_DROP                                    = 'Other'
            XE_BUFFERMGR_ALLPROCECESSED_EVENT               = 'Other'
            XE_BUFFERMGR_FREEBUF_EVENT                      = 'Other'
            XE_DISPATCHER_JOIN                              = 'Other'
            XE_MODULEMGR_SYNC                               = 'Other'
            XE_OLS_LOCK                                     = 'Other'
            XE_SERVICES_MUTEX                               = 'Other'
            XE_SESSION_CREATE_SYNC                          = 'Other'
            XE_SESSION_SYNC                                 = 'Other'
            XE_STM_CREATE                                   = 'Other'
            XE_TIMER_MUTEX                                  = 'Other'
            XE_TIMER_TASK_DONE                              = 'Other'
        }

        $ignorable = 'BROKER_EVENTHANDLER', 'BROKER_RECEIVE_WAITFOR', 'BROKER_TASK_STOP',
        'BROKER_TO_FLUSH', 'BROKER_TRANSMITTER', 'CHECKPOINT_QUEUE',
        'CHKPT', 'CLR_AUTO_EVENT', 'CLR_MANUAL_EVENT', 'CLR_SEMAPHORE', 'CXCONSUMER',
        'DBMIRROR_DBM_EVENT', 'DBMIRROR_EVENTS_QUEUE', 'DBMIRROR_WORKER_QUEUE',
        'DBMIRRORING_CMD', 'DIRTY_PAGE_POLL', 'DISPATCHER_QUEUE_SEMAPHORE',
        'EXECSYNC', 'FSAGENT', 'FT_IFTS_SCHEDULER_IDLE_WAIT', 'FT_IFTSHC_MUTEX',
        'HADR_CLUSAPI_CALL', 'HADR_FILESTREAM_IOMGR_IOCOMPLETION', 'HADR_LOGCAPTURE_WAIT',
        'HADR_NOTIFICATION_DEQUEUE', 'HADR_TIMER_TASK', 'HADR_WORK_QUEUE',
        'KSOURCE_WAKEUP', 'LAZYWRITER_SLEEP', 'LOGMGR_QUEUE',
        'MEMORY_ALLOCATION_EXT', 'ONDEMAND_TASK_QUEUE',
        'PARALLEL_REDO_DRAIN_WORKER', 'PARALLEL_REDO_LOG_CACHE', 'PARALLEL_REDO_TRAN_LIST', 'PARALLEL_REDO_WORKER_SYNC',
        'PREEMPTIVE_SP_SERVER_DIAGNOSTICS',
        'PARALLEL_REDO_WORKER_WAIT_WORK', 'PREEMPTIVE_HADR_LEASE_MECHANISM',
        'PREEMPTIVE_OS_LIBRARYOPS', 'PREEMPTIVE_OS_COMOPS', 'PREEMPTIVE_OS_CRYPTOPS',
        'PREEMPTIVE_OS_PIPEOPS', 'PREEMPTIVE_OS_AUTHENTICATIONOPS',
        'PREEMPTIVE_OS_GENERICOPS', 'PREEMPTIVE_OS_VERIFYTRUST',
        'PREEMPTIVE_OS_FILEOPS', 'PREEMPTIVE_OS_DEVICEOPS', 'PREEMPTIVE_OS_QUERYREGISTRY',
        'PREEMPTIVE_OS_WRITEFILE', 'PREEMPTIVE_XE_CALLBACKEXECUTE', 'PREEMPTIVE_XE_DISPATCHER',
        'PREEMPTIVE_XE_GETTARGETSTATE', 'PREEMPTIVE_XE_SESSIONCOMMIT',
        'PREEMPTIVE_XE_TARGETINIT', 'PREEMPTIVE_XE_TARGETFINALIZE',
        'PWAIT_ALL_COMPONENTS_INITIALIZED', 'PWAIT_DIRECTLOGCONSUMER_GETNEXT',
        'QDS_PERSIST_TASK_MAIN_LOOP_SLEEP', 'QDS_ASYNC_QUEUE',
        'QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP', 'REDO_THREAD_PENDING_WORK',
        'QDS_SHUTDOWN_QUEUE', 'REQUEST_FOR_DEADLOCK_SEARCH',
        'RESOURCE_QUEUE', 'SERVER_IDLE_CHECK', 'SLEEP_BPOOL_FLUSH', 'SLEEP_DBSTARTUP',
        'SLEEP_DCOMSTARTUP', 'SLEEP_MASTERDBREADY', 'SLEEP_MASTERMDREADY',
        'SLEEP_MASTERUPGRADED', 'SLEEP_MSDBSTARTUP', 'SLEEP_SYSTEMTASK', 'SLEEP_TASK',
        'SLEEP_TEMPDBSTARTUP', 'SNI_HTTP_ACCEPT', 'SP_SERVER_DIAGNOSTICS_SLEEP',
        'SQLTRACE_BUFFER_FLUSH', 'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', 'SQLTRACE_WAIT_ENTRIES',
        'WAIT_FOR_RESULTS', 'WAITFOR', 'WAITFOR_TASKSHUTDOWN', 'WAIT_XTP_HOST_WAIT',
        'WAIT_XTP_OFFLINE_CKPT_NEW_LOG', 'WAIT_XTP_CKPT_CLOSE', 'WAIT_XTP_RECOVERY',
        'XE_BUFFERMGR_ALLPROCESSED_EVENT', 'XE_DISPATCHER_JOIN',
        'XE_DISPATCHER_WAIT', 'XE_LIVE_TARGET_TVF', 'XE_TIMER_EVENT'

        if ($IncludeIgnorable) {
            $sql = "WITH [Waits] AS
                (SELECT
                    [wait_type],
                    [wait_time_ms] / 1000.0 AS [WaitS],
                    ([wait_time_ms] - [signal_wait_time_ms]) / 1000.0 AS [ResourceS],
                    [signal_wait_time_ms] / 1000.0 AS [SignalS],
                    [waiting_tasks_count] AS [WaitCount],
                    Case WHEN SUM ([wait_time_ms]) OVER() = 0 THEN NULL ELSE 100.0 * [wait_time_ms] / SUM ([wait_time_ms]) OVER() END AS [Percentage],
                    ROW_NUMBER() OVER(ORDER BY [wait_time_ms] DESC) AS [RowNum]
                FROM sys.dm_os_wait_stats
                WHERE [waiting_tasks_count] > 0
                )
                SELECT
                    MAX ([W1].[wait_type]) AS [WaitType],
                    CAST (MAX ([W1].[WaitS]) AS DECIMAL (16,2)) AS [WaitSeconds],
                    CAST (MAX ([W1].[ResourceS]) AS DECIMAL (16,2)) AS [ResourceSeconds],
                    CAST (MAX ([W1].[SignalS]) AS DECIMAL (16,2)) AS [SignalSeconds],
                    MAX ([W1].[WaitCount]) AS [WaitCount],
                    CAST (MAX ([W1].[Percentage]) AS DECIMAL (5,2)) AS [Percentage],
                    CAST ((MAX ([W1].[WaitS]) / MAX ([W1].[WaitCount])) AS DECIMAL (16,4)) AS [AvgWaitSeconds],
                    CAST ((MAX ([W1].[ResourceS]) / MAX ([W1].[WaitCount])) AS DECIMAL (16,4)) AS [AvgResSeconds],
                    CAST ((MAX ([W1].[SignalS]) / MAX ([W1].[WaitCount])) AS DECIMAL (16,4)) AS [AvgSigSeconds],
                    CAST ('https://www.sqlskills.com/help/waits/' + MAX ([W1].[wait_type]) as XML) AS [URL]
                FROM [Waits] AS [W1]
                INNER JOIN [Waits] AS [W2]
                    ON [W2].[RowNum] <= [W1].[RowNum]
                GROUP BY [W1].[RowNum] HAVING SUM ([W2].[Percentage]) - MAX([W1].[Percentage]) < $Threshold"
        } else {
            $IgnorableList = "'$($ignorable -join "','")'"
            $sql = "WITH [Waits] AS
                (SELECT
                    [wait_type],
                    [wait_time_ms] / 1000.0 AS [WaitS],
                    ([wait_time_ms] - [signal_wait_time_ms]) / 1000.0 AS [ResourceS],
                    [signal_wait_time_ms] / 1000.0 AS [SignalS],
                    [waiting_tasks_count] AS [WaitCount],
                    Case WHEN SUM ([wait_time_ms]) OVER() = 0 THEN NULL ELSE 100.0 * [wait_time_ms] / SUM ([wait_time_ms]) OVER() END AS [Percentage],
                    ROW_NUMBER() OVER(ORDER BY [wait_time_ms] DESC) AS [RowNum]
                FROM sys.dm_os_wait_stats
                WHERE [waiting_tasks_count] > 0
                AND Cast([wait_type] as VARCHAR(60)) NOT IN ($IgnorableList)
                )
                SELECT
                    MAX ([W1].[wait_type]) AS [WaitType],
                    CAST (MAX ([W1].[WaitS]) AS DECIMAL (16,2)) AS [WaitSeconds],
                    CAST (MAX ([W1].[ResourceS]) AS DECIMAL (16,2)) AS [ResourceSeconds],
                    CAST (MAX ([W1].[SignalS]) AS DECIMAL (16,2)) AS [SignalSeconds],
                    MAX ([W1].[WaitCount]) AS [WaitCount],
                    CAST (MAX ([W1].[Percentage]) AS DECIMAL (5,2)) AS [Percentage],
                    CAST ((MAX ([W1].[WaitS]) / MAX ([W1].[WaitCount])) AS DECIMAL (16,4)) AS [AvgWaitSeconds],
                    CAST ((MAX ([W1].[ResourceS]) / MAX ([W1].[WaitCount])) AS DECIMAL (16,4)) AS [AvgResSeconds],
                    CAST ((MAX ([W1].[SignalS]) / MAX ([W1].[WaitCount])) AS DECIMAL (16,4)) AS [AvgSigSeconds],
                    CAST ('https://www.sqlskills.com/help/waits/' + MAX ([W1].[wait_type]) as XML) AS [URL]
                FROM [Waits] AS [W1]
                INNER JOIN [Waits] AS [W2]
                    ON [W2].[RowNum] <= [W1].[RowNum]
                GROUP BY [W1].[RowNum] HAVING SUM ([W2].[Percentage]) - MAX([W1].[Percentage]) < $Threshold"

        }
        Write-Message -Level Debug -Message $sql
    }
    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            Write-Message -Level Verbose -Message "Connected to $instance"
            if ($IncludeIgnorable) {
                $excludeColumns = 'Notes'
            } else {
                $excludeColumns = 'Notes', 'Ignorable'
            }

            foreach ($row in $server.Query($sql)) {
                $waitType = $row.WaitType
                if (-not $IncludeIgnorable) {
                    if ($ignorable -contains $waitType) { continue }
                }

                [PSCustomObject]@{
                    ComputerName           = $server.ComputerName
                    InstanceName           = $server.ServiceName
                    SqlInstance            = $server.DomainInstanceName
                    WaitType               = $waitType
                    Category               = ($category).$waitType
                    WaitSeconds            = $row.WaitSeconds
                    ResourceSeconds        = $row.ResourceSeconds
                    SignalSeconds          = $row.SignalSeconds
                    WaitCount              = $row.WaitCount
                    Percentage             = $row.Percentage
                    AverageWaitSeconds     = $row.AvgWaitSeconds
                    AverageResourceSeconds = $row.AvgResSeconds
                    AverageSignalSeconds   = $row.AvgSigSeconds
                    Ignorable              = ($ignorable -contains $waitType)
                    URL                    = $row.URL
                    Notes                  = ($details).$waitType
                } | Select-DefaultView -ExcludeProperty $excludeColumns
            }
        }
    }
}
tools\dbatools\functions\Get-DbaWindowsLog.ps1
function Get-DbaWindowsLog {
    <#
    .SYNOPSIS
        Gets Windows Application events associated with an instance

    .DESCRIPTION
        Gets Windows Application events associated with an instance

    .PARAMETER SqlInstance
        The instance(s) to retrieve the event logs from

    .PARAMETER Start
        Default: 1970
        Retrieve all events starting from this timestamp.

    .PARAMETER End
        Default: Now
        Retrieve all events that happened before this timestamp

    .PARAMETER Credential
        Credential to be used to connect to the Server. Note this is a Windows credential, as this command requires we communicate with the computer and not with the SQL instance.

    .PARAMETER MaxThreads
        Default: Unlimited
        The maximum number of parallel threads used on the local computer.
        Given that those will mostly be waiting for the remote system, there is usually no need to limit this.

    .PARAMETER MaxRemoteThreads
        Default: 2
        The maximum number of parallel threads that are executed on the target sql server.
        These processes will cause considerable CPU load, so a low limit is advisable in most scenarios.
        Any value lower than 1 disables the limit

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Logging
        Author: Drew Furgiuele | Friedrich Weinmann (@FredWeinmann)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaWindowsLog

    .EXAMPLE
        PS C:\> $ErrorLogs = Get-DbaWindowsLog -SqlInstance sql01\sharepoint
        PS C:\> $ErrorLogs | Where-Object ErrorNumber -eq 18456

        Returns all lines in the errorlogs that have event number 18456 in them

    #>
    #This exists to ignore the Script Analyzer rule for Start-Runspace
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]
        $SqlInstance = $env:COMPUTERNAME,

        [DateTime]
        $Start = "1/1/1970 00:00:00",

        [DateTime]
        $End = (Get-Date),


        [System.Management.Automation.PSCredential]
        $Credential,

        [int]
        $MaxThreads = 0,

        [int]
        $MaxRemoteThreads = 2,

        [switch]
        [Alias('Silent')]$EnableException
    )

    begin {
        Write-Message -Level Debug -Message "Bound parameters: $($PSBoundParameters.Keys -join ", ")"

        #region Helper Functions
        function Start-Runspace {
            $Powershell = [PowerShell]::Create().AddScript($scriptBlock_ParallelRemoting).AddParameter("SqlInstance", $instance).AddParameter("Start", $Start).AddParameter("End", $End).AddParameter("Credential", $Credential).AddParameter("MaxRemoteThreads", $MaxRemoteThreads).AddParameter("ScriptBlock", $scriptBlock_RemoteExecution)
            $Powershell.RunspacePool = $RunspacePool
            Write-Message -Level Verbose -Message "Launching remote runspace against <c='green'>$instance</c>" -Target $instance
            $null = $RunspaceCollection.Add((New-Object -TypeName PSObject -Property @{ Runspace = $PowerShell.BeginInvoke(); PowerShell = $PowerShell; Instance = $instance.FullSmoName }))
        }

        function Receive-Runspace {
            [Parameter()]
            param (
                [switch]
                $Wait
            )

            do {
                foreach ($Run in $RunspaceCollection.ToArray()) {
                    if ($Run.Runspace.IsCompleted) {
                        Write-Message -Level Verbose -Message "Receiving results from <c='green'>$($Run.Instance)</c>" -Target $Run.Instance
                        $Run.PowerShell.EndInvoke($Run.Runspace)
                        $Run.PowerShell.Dispose()
                        $RunspaceCollection.Remove($Run)
                    }
                }

                if ($Wait -and ($RunspaceCollection.Count -gt 0)) { Start-Sleep -Milliseconds 250 }
            }
            while ($Wait -and ($RunspaceCollection.Count -gt 0))
        }
        #endregion Helper Functions

        #region Scriptblocks
        $scriptBlock_RemoteExecution = {
            param (
                [System.DateTime]
                $Start,

                [System.DateTime]
                $End,

                [string]
                $InstanceName,

                [int]
                $Throttle
            )

            #region Helper function
            function Convert-ErrorRecord {
                param (
                    $Line
                )

                if (Get-Variable -Name codesAndStuff -Scope 1) {
                    $line2 = (Get-Variable -Name codesAndStuff -Scope 1).Value
                    Remove-Variable -Name codesAndStuff -Scope 1

                    $groups = [regex]::Matches($line2, '^([\d- :]+.\d\d) (\w+)[ ]+Error: (\d+), Severity: (\d+), State: (\d+)').Groups
                    $groups2 = [regex]::Matches($line, '^[\d- :]+.\d\d \w+[ ]+(.*)$').Groups

                    New-Object PSObject -Property @{
                        Timestamp   = [DateTime]::ParseExact($groups[1].Value, "yyyy-MM-dd HH:mm:ss.ff", $null)
                        Spid        = $groups[2].Value
                        Message     = $groups2[1].Value
                        ErrorNumber = [int]($groups[3].Value)
                        Severity    = [int]($groups[4].Value)
                        State       = [int]($groups[5].Value)
                    }
                }

                if ($Line -match '^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d\d[\w ]+((\w+): (\d+)[,\.]\s?){3}') {
                    Set-Variable -Name codesAndStuff -Value $Line -Scope 1
                }
            }
            #endregion Helper function

            #region Script that processes an individual file
            $scriptBlock = {
                param (
                    [System.IO.FileInfo]
                    $File
                )

                try {
                    $stream = New-Object System.IO.FileStream($File.FullName, "Open", "Read", "ReadWrite, Delete")
                    $reader = New-Object System.IO.StreamReader($stream)

                    while (-not $reader.EndOfStream) {
                        Convert-ErrorRecord -Line $reader.ReadLine()
                    }
                } catch {
                    # here to avoid an empty catch
                    $null = 1
                }
            }
            #endregion Script that processes an individual file

            #region Gather list of files to process
            $eventSource = "MSSQLSERVER"
            if ($InstanceName -notmatch "^DEFAULT$|^MSSQLSERVER$") {
                $eventSource = 'MSSQL$' + $InstanceName
            }

            $event = Get-WinEvent -FilterHashtable @{
                LogName      = "Application"
                ID           = 17111
                ProviderName = $eventSource
            } -MaxEvents 1 -ErrorAction SilentlyContinue

            if (-not $event) { return }

            $path = $event.Properties[0].Value
            $errorLogPath = Split-Path -Path $path
            $errorLogFileName = Split-Path -Path $path -Leaf
            $errorLogFiles = Get-ChildItem -Path $errorLogPath | Where-Object { ($_.Name -like "$errorLogFileName*") -and ($_.LastWriteTime -gt $Start) -and ($_.CreationTime -lt $End) }
            #endregion Gather list of files to process

            #region Prepare Runspaces
            [Collections.Arraylist]$RunspaceCollection = @()

            $InitialSessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
            $Command = Get-Item function:Convert-ErrorRecord
            $InitialSessionState.Commands.Add((New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry($command.Name, $command.Definition)))

            $RunspacePool = [RunspaceFactory]::CreateRunspacePool($InitialSessionState)
            $null = $RunspacePool.SetMinRunspaces(1)
            if ($Throttle -gt 0) { $null = $RunspacePool.SetMaxRunspaces($Throttle) }
            $RunspacePool.Open()
            #endregion Prepare Runspaces

            #region Process Error files
            $countDone = 0
            $countStarted = 0
            $countTotal = ($errorLogFiles | Measure-Object).Count

            while ($countDone -lt $countTotal) {
                while (($RunspacePool.GetAvailableRunspaces() -gt 0) -and ($countStarted -lt $countTotal)) {
                    $Powershell = [PowerShell]::Create().AddScript($scriptBlock).AddParameter("File", $errorLogFiles[$countStarted])
                    $Powershell.RunspacePool = $RunspacePool
                    $null = $RunspaceCollection.Add((New-Object -TypeName PSObject -Property @{ Runspace = $PowerShell.BeginInvoke(); PowerShell = $PowerShell }))
                    $countStarted++
                }

                foreach ($Run in $RunspaceCollection.ToArray()) {
                    if ($Run.Runspace.IsCompleted) {
                        $Run.PowerShell.EndInvoke($Run.Runspace) | Where-Object { ($_.Timestamp -gt $Start) -and ($_.Timestamp -lt $End) }
                        $Run.PowerShell.Dispose()
                        $RunspaceCollection.Remove($Run)
                        $countDone++
                    }
                }

                Start-Sleep -Milliseconds 250
            }
            $RunspacePool.Close()
            $RunspacePool.Dispose()
            #endregion Process Error files
        }

        $scriptBlock_ParallelRemoting = {
            param (
                [DbaInstanceParameter]
                $SqlInstance,

                [DateTime]
                $Start,

                [DateTime]
                $End,

                [PSCredential]
                $Credential,

                [int]
                $MaxRemoteThreads,

                [System.Management.Automation.ScriptBlock]
                $ScriptBlock
            )

            $params = @{
                ArgumentList = $Start, $End, $SqlInstance.InstanceName, $MaxRemoteThreads
                ScriptBlock  = $ScriptBlock
            }
            if (-not $SqlInstance.IsLocalhost) { $params["ComputerName"] = $SqlInstance.ComputerName }
            if ($Credential) { $params["Credential"] = $Credential }

            Invoke-Command @params | Select-Object @{ n = "InstanceName"; e = { $SqlInstance.FullSmoName } }, Timestamp, Spid, Severity, ErrorNumber, State, Message
        }
        #endregion Scriptblocks

        #region Setup Runspace
        [Collections.Arraylist]$RunspaceCollection = @()
        $InitialSessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
        $defaultrunspace = [System.Management.Automation.Runspaces.Runspace]::DefaultRunspace
        $RunspacePool = [RunspaceFactory]::CreateRunspacePool($InitialSessionState)
        $RunspacePool.SetMinRunspaces(1) | Out-Null
        if ($MaxThreads -gt 0) { $null = $RunspacePool.SetMaxRunspaces($MaxThreads) }
        $RunspacePool.Open()

        $countStarted = 0
        #Variable marked as unused by PSScriptAnalyzer
        #$countReceived = 0
        #endregion Setup Runspace
    }

    process {
        foreach ($instance in $SqlInstance) {
            Write-Message -Level VeryVerbose -Message "Processing <c='green'>$instance</c>" -Target $instance
            Start-Runspace
            Receive-Runspace
        }
    }

    end {
        Receive-Runspace -Wait
        $RunspacePool.Close()
        $RunspacePool.Dispose()
        [System.Management.Automation.Runspaces.Runspace]::DefaultRunspace = $defaultrunspace
    }
}
tools\dbatools\functions\Get-DbaWsfcAvailableDisk.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaWsfcAvailableDisk {
    <#
    .SYNOPSIS
        Gets information about the disks that can support Failover Clustering and are visible to all nodes, but are not yet part of the set of clustered disks.

    .DESCRIPTION
        Gets information about the disks that can support Failover Clustering and are visible to all nodes, but are not yet part of the set of clustered disks.

        All Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.

    .PARAMETER ComputerName
        The target cluster name. Can be a node or the cluster name itself.

    .PARAMETER Credential
        Allows you to login to the cluster using alternative credentials.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Cluster, WSFC, FCI, HA
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaWsfcAvailableDisk

    .EXAMPLE
        PS C:\> Get-DbaWsfcAvailableDisk -ComputerName cluster01

        Gets available disks from the failover cluster cluster01

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [switch]$EnableException
    )
    process {
        foreach ($computer in $computername) {
            $cluster = Get-DbaWsfcCluster -ComputerName $computer -Credential $Credential
            $disk = Get-DbaCmObject -Computername $computer -Credential $Credential -Namespace root\MSCluster -ClassName MSCluster_AvailableDisk

            # I don't have an available disk, so I can't see how to clean this up: Passthru
            $disk | Add-Member -Force -NotePropertyName State -NotePropertyValue (Get-ResourceState $resource.State)
            $disk | Add-Member -Force -NotePropertyName ClusterName -NotePropertyValue $cluster.Name
            $disk | Add-Member -Force -NotePropertyName ClusterFqdn -NotePropertyValue $cluster.Fqdn -PassThru
        }
    }
}
tools\dbatools\functions\Get-DbaWsfcCluster.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaWsfcCluster {
    <#
    .SYNOPSIS
        Gets information about one or more failover clusters in a given domain.

    .DESCRIPTION
        Gets information about one or more failover clusters in a given domain.

        All Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.

    .PARAMETER ComputerName
        The target cluster name. Can be a node or the cluster name itself.

    .PARAMETER Credential
        Allows you to login to the cluster using alternative credentials.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Cluster, WSFC, FCI, HA
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaWsfcCluster

    .EXAMPLE
        PS C:\> Get-DbaWsfcCluster -ComputerName cluster01

        Gets failover cluster information about cluster01

    .EXAMPLE
        PS C:\> Get-DbaWsfcCluster -ComputerName cluster01 | Select *

        Shows all cluster values, including the ones not shown in the default view

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [switch]$EnableException
    )
    process {
        foreach ($computer in $computername) {
            $cluster = Get-DbaCmObject -Computername $computer -Credential $Credential -Namespace root\MSCluster -ClassName MSCluster_Cluster
            $cluster | Add-Member -Force -NotePropertyName State -NotePropertyValue (Get-ResourceState $resource.State)
            $cluster | Select-DefaultView -Property Name, Fqdn, State, DrainOnShutdown, DynamicQuorumEnabled, EnableSharedVolumes, SharedVolumesRoot, QuorumPath, QuorumType, QuorumTypeValue, RequestReplyTimeout
        }
    }
}
tools\dbatools\functions\Get-DbaWsfcDisk.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaWsfcDisk {
    <#
    .SYNOPSIS
        Gets information about the clustered disks on one or more failover clusters in a given domain.

    .DESCRIPTION
        Gets information about the clustered disks on one or more failover clusters in a given domain.

        All Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.

    .PARAMETER ComputerName
        The target cluster name. Can be a node or the cluster name itself.

    .PARAMETER Credential
        Allows you to login to the cluster using alternative credentials.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Cluster, WSFC, FCI, HA
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaWsfcDisk

    .EXAMPLE
        PS C:\> Get-DbaWsfcDisk -ComputerName cluster01

        Gets disk information from the failover cluster cluster01

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [switch]$EnableException
    )
    process {
        foreach ($computer in $computername) {
            $resources = Get-DbaWsfcResource -ComputerName $computer -Credential $Credential | Where-Object Type -eq 'Physical Disk'
            foreach ($resource in $resources) {
                $disks = $resource | Get-CimAssociatedInstance -ResultClassName MSCluster_Disk
                foreach ($disk in $disks) {
                    $diskpart = $disk | Get-CimAssociatedInstance -ResultClassName MSCluster_DiskPartition
                    [pscustomobject]@{
                        ClusterName     = $resource.ClusterName
                        ClusterFqdn     = $resource.ClusterFqdn
                        ResourceGroup   = $resource.OwnerGroup
                        Disk            = $resource.Name
                        State           = $resource.State
                        FileSystem      = $diskpart.FileSystem
                        Path            = $diskpart.Path
                        Label           = $diskpart.VolumeLabel
                        Size            = [dbasize]($diskpart.TotalSize * 1MB)
                        Free            = [dbasize]($diskpart.FreeSpace * 1MB)
                        MountPoints     = $diskpart.MountPoints
                        SerialNumber    = $diskpart.SerialNumber
                        ClusterDisk     = $disk
                        ClusterDiskPart = $diskpart
                        ClusterResource = $resource
                    } | Select-DefaultView -ExcludeProperty ClusterDisk, ClusterDiskPart, ClusterResource
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaWsfcNetwork.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaWsfcNetwork {
    <#
    .SYNOPSIS
        Gets information about one or more networks in a failover cluster.

    .DESCRIPTION
        Gets information about one or more networks in a failover cluster.

        All Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.

    .PARAMETER ComputerName
        The target cluster name. Can be a Network or the cluster name itself.

    .PARAMETER Credential
        Allows you to login to the cluster using alternative credentials.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Cluster, WSFC, FCI, HA
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaWsfcNetwork

    .EXAMPLE
        PS C:\> Get-DbaWsfcNetwork -ComputerName cluster01

        Gets network information from the failover cluster cluster01

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [switch]$EnableException
    )
    process {
        foreach ($computer in $computername) {
            $cluster = Get-DbaWsfcCluster -ComputerName $computer -Credential $Credential

            $network = Get-DbaCmObject -Computername $computer -Credential $Credential -Namespace root\MSCluster -ClassName MSCluster_Network
            $network | Add-Member -Force -NotePropertyName ClusterName -NotePropertyValue $cluster.Name
            $network | Add-Member -Force -NotePropertyName ClusterFqdn -NotePropertyValue $cluster.Fqdn

            $network | Select-DefaultView -Property ClusterName, ClusterFqdn, Name, Address, AddressMask, IPv4Addresses, IPv4PrefixLengths, IPv6Addresses, IPv6PrefixLengths, QuorumType, QuorumTypeValue, RequestReplyTimeout, Role
        }
    }
}
tools\dbatools\functions\Get-DbaWsfcNetworkInterface.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaWsfcNetworkInterface {
    <#
    .SYNOPSIS
        Gets information about one or more network adapters in a failover cluster.

    .DESCRIPTION
        Gets information about one or more network adapters in a failover cluster.

        All Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.

    .PARAMETER ComputerName
        The target cluster name. Can be a Network or the cluster name itself.

    .PARAMETER Credential
        Allows you to login to the cluster using alternative credentials.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Cluster, WSFC, FCI, HA
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaWsfcNetworkInterface

    .EXAMPLE
        PS C:\> Get-DbaWsfcNetworkInterface -ComputerName cluster01

        Gets network interface information from the failover cluster cluster01

    .EXAMPLE
        PS C:\> Get-DbaWsfcNetworkInterface -ComputerName cluster01 | Select *

        Shows all network interface  values, including the ones not shown in the default view

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [switch]$EnableException
    )
    process {
        foreach ($computer in $computername) {
            $cluster = Get-DbaWsfcCluster -ComputerName $computer -Credential $Credential
            $network = Get-DbaCmObject -Computername $computer -Credential $Credential -Namespace root\MSCluster -ClassName MSCluster_NetworkInterface
            $network | Add-Member -Force -NotePropertyName ClusterName -NotePropertyValue $cluster.Name
            $network | Add-Member -Force -NotePropertyName ClusterFqdn -NotePropertyValue $cluster.Fqdn
            $network | Select-DefaultView -Property ClusterName, ClusterFqdn, Name, Network, Node, Adapter, Address, DhcpEnabled, IPv4Addresses, IPv6Addresses, IPv6Addresses
        }
    }
}
tools\dbatools\functions\Get-DbaWsfcNode.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaWsfcNode {
    <#
    .SYNOPSIS
        Gets information about one or more nodes, or servers, in a failover cluster.

    .DESCRIPTION
        Gets information about one or more nodes, or servers, in a failover cluster.

        All Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.

    .PARAMETER ComputerName
        The target cluster name. Can be a node or the cluster name itself.

    .PARAMETER Credential
        Allows you to login to the cluster using alternative credentials.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Cluster, WSFC, FCI, HA
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaWsfcNode

    .EXAMPLE
        PS C:\> Get-DbaWsfcNode -ComputerName cluster01

        Gets node information from the failover cluster cluster01

    .EXAMPLE
        PS C:\> Get-DbaWsfcNode -ComputerName cluster01 | Select-Object *

        Shows all node values, including the ones not shown in the default view

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [switch]$EnableException
    )
    process {
        foreach ($computer in $computername) {
            $cluster = Get-DbaWsfcCluster -ComputerName $computer -Credential $Credential
            $node = Get-DbaCmObject -Computername $computer -Credential $Credential -Namespace root\MSCluster -ClassName MSCluster_Node
            $node | Add-Member -Force -NotePropertyName ClusterName -NotePropertyValue $cluster.Name
            $node | Add-Member -Force -NotePropertyName ClusterFqdn -NotePropertyValue $cluster.Fqdn
            $node | Select-DefaultView -Property ClusterName, ClusterFqdn, Name, PrimaryOwnerName, PrimaryOwnerContact, Dedicated, NodeHighestVersion, NodeLowestVersion
        }
    }
}
tools\dbatools\functions\Get-DbaWsfcResource.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaWsfcResource {
    <#
    .SYNOPSIS
        Gets information about one or more resources in a failover cluster.

    .DESCRIPTION
        Gets information about one or more resources in a failover cluster.

        All Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.

    .PARAMETER ComputerName
        The target cluster name. Can be a node or the cluster name itself.

    .PARAMETER Credential
        Allows you to login to the cluster using alternative credentials.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Cluster, WSFC, FCI, HA
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaWsfcResource

    .EXAMPLE
        PS C:\> Get-DbaWsfcResource -ComputerName cluster01

        Gets resource information from the failover cluster cluster01

    .EXAMPLE
        PS C:\> Get-DbaWsfcResource -ComputerName cluster01 | Select *

        Shows all resource values, including the ones not shown in the default view

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [switch]$EnableException
    )
    process {
        foreach ($computer in $computername) {
            $cluster = Get-DbaWsfcCluster -ComputerName $computer -Credential $Credential
            $resources = Get-DbaCmObject -Computername $computer -Credential $Credential -Namespace root\MSCluster -ClassName MSCluster_Resource
            foreach ($resource in $resources) {
                $resource | Add-Member -Force -NotePropertyName State -NotePropertyValue (Get-ResourceState $resource.State)
                $resource | Add-Member -Force -NotePropertyName ClusterName -NotePropertyValue $cluster.Name
                $resource | Add-Member -Force -NotePropertyName ClusterFqdn -NotePropertyValue $cluster.Fqdn
                $resource | Select-DefaultView -Property ClusterName, ClusterFqdn, Name, State, Type, OwnerGroup, OwnerNode, PendingTimeout, PersistentState, QuorumCapable, RequiredDependencyClasses, RequiredDependencyTypes, RestartAction, RestartDelay, RestartPeriod, RestartThreshold, RetryPeriodOnFailure, SeparateMonitor
            }
        }
    }
}
tools\dbatools\functions\Get-DbaWsfcResourceType.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaWsfcResourceType {
    <#
    .SYNOPSIS
        Gets information about one or more resource types in a failover cluster.

    .DESCRIPTION
        Gets information about one or more resource types in a failover cluster.

        All Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.

    .PARAMETER ComputerName
        The target cluster name. Can be a node or the cluster name itself.

    .PARAMETER Credential
        Allows you to login to the cluster using alternative credentials.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Cluster, WSFC, FCI, HA
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaWsfcResourceType

    .EXAMPLE
        PS C:\> Get-DbaWsfcResourceType -ComputerName cluster01

        Gets resource type information from the failover cluster cluster01

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [switch]$EnableException
    )
    process {
        foreach ($computer in $computername) {
            $cluster = Get-DbaWsfcCluster -ComputerName $computer -Credential $Credential
            $resource = Get-DbaCmObject -Computername $computer -Credential $Credential -Namespace root\MSCluster -ClassName MSCluster_ResourceType
            $resource | Add-Member -Force -NotePropertyName ClusterName -NotePropertyValue $cluster.Name
            $resource | Add-Member -Force -NotePropertyName ClusterFqdn -NotePropertyValue $cluster.Fqdn
            $resource | Select-DefaultView -Property ClusterName, ClusterFqdn, Name, DisplayName, DllName, RequiredDependencyTypes
        }
    }
}
tools\dbatools\functions\Get-DbaWsfcRole.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaWsfcRole {
    <#
    .SYNOPSIS
        Gets information about one or more clustered roles (resource groups) in a failover cluster.

    .DESCRIPTION
        Gets information about one or more clustered roles (resource groups) in a failover cluster.

        All Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.

    .PARAMETER ComputerName
        The target cluster name. Can be a Role or the cluster name itself.

    .PARAMETER Credential
        Allows you to login to the cluster using alternative credentials.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Cluster, WSFC, FCI, HA
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaWsfcRole

    .EXAMPLE
        PS C:\> Get-DbaWsfcRole -ComputerName cluster01

        Gets role information from the failover cluster cluster01

    .EXAMPLE
        PS C:\> Get-DbaWsfcRole -ComputerName cluster01 | Select *

        Shows all role values, including the ones not shown in the default view

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [switch]$EnableException
    )
    process {
        foreach ($computer in $computername) {
            $cluster = Get-DbaWsfcCluster -ComputerName $computer -Credential $Credential
            $role = Get-DbaCmObject -Computername $computer -Credential $Credential -Namespace root\MSCluster -ClassName MSCluster_ResourceGroup
            $role | Add-Member -Force -NotePropertyName State -NotePropertyValue (Get-ResourceState $resource.State)
            $role | Add-Member -Force -NotePropertyName ClusterName -NotePropertyValue $cluster.Name
            $role | Add-Member -Force -NotePropertyName ClusterFqdn -NotePropertyValue $cluster.Fqdn
            $role | Select-DefaultView -Property ClusterName, ClusterFqdn, Name, OwnerNode, State
        }
    }
}
tools\dbatools\functions\Get-DbaWsfcSharedVolume.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaWsfcSharedVolume {
    <#
    .SYNOPSIS
        Gets information about Cluster Shared Volumes in a failover cluster.

    .DESCRIPTION
        Gets information about Cluster Shared Volumes in a failover cluster.

        All Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.

    .PARAMETER ComputerName
        The target cluster name. Can be a node or the cluster name itself.

    .PARAMETER Credential
        Allows you to login to the cluster using alternative credentials.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Cluster, WSFC, FCI, HA
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaWsfcSharedVolume

    .EXAMPLE
        PS C:\> Get-DbaWsfcSharedVolume -ComputerName cluster01

        Gets shared volume (CSV) information from the failover cluster cluster01

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [switch]$EnableException
    )
    process {
        foreach ($computer in $computername) {
            $cluster = Get-DbaWsfcCluster -ComputerName $computer -Credential $Credential
            $volume = Get-DbaCmObject -Computername $computer -Credential $Credential -Namespace root\MSCluster -ClassName ClusterSharedVolume
            # I don't have a shared volume, so I can't see how to clean this up: Passthru
            $volume | Add-Member -Force -NotePropertyName ClusterName -NotePropertyValue $cluster.Name
            $volume | Add-Member -Force -NotePropertyName ClusterFqdn -NotePropertyValue $cluster.Fqdn
            $volume | Add-Member -Force -NotePropertyName State -NotePropertyValue (Get-ResourceState $resource.State) -PassThru
        }
    }
}
tools\dbatools\functions\Get-DbaXEObject.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaXEObject {
    <#
    .SYNOPSIS
        Gets a list of extended events objects exposed by event packages from specified SQL Server instance(s).

    .DESCRIPTION
        This function returns a list of extended events objects exposed by event packages from specified SQL Server instance(s).

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Type
        Used to specify the type. Valid types include:

        Action
        Event
        Map
        Message
        PredicateComparator
        PredicateSource
        Target
        Type

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaXEObject -SqlInstance sql2016

        Lists all the XE Objects on the sql2016 SQL Server.

    .EXAMPLE
        PS C:\> Get-DbaXEObject -SqlInstance sql2017 -Type Action, Event

        Lists all the XE Objects of type Action and Event on the sql2017 SQL Server.

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [ValidateSet("Type", "Event", "Target", "Action", "Map", "Message", "PredicateComparator", "PredicateSource")]
        [string[]]$Type,
        [switch]$EnableException
    )
    begin {
        if ($Type) {
            $join = $Type -join "','"
            $where = "AND o.object_type in ('$join')"
            $where.Replace("PredicateComparator", "pred_compare")
            $where.Replace("PredicateSource", "pred_source")
        }
        $sql = "SELECT  SERVERPROPERTY('MachineName') AS ComputerName,
                ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
                SERVERPROPERTY('ServerName') AS SqlInstance,
                p.name AS PackageName,
                ObjectType =
                      CASE o.object_type
                         WHEN 'type' THEN 'Type'
                         WHEN 'event' THEN 'Event'
                         WHEN 'target' THEN 'Target'
                         WHEN 'pred_compare' THEN 'PredicateComparator'
                         WHEN 'pred_source' THEN 'PredicateSource'
                         WHEN 'action' THEN 'Action'
                         WHEN 'map' THEN 'Map'
                         WHEN 'message' THEN 'Message'
                         ELSE o.object_type
                      END,
                o.object_type as ObjectTypeRaw,
                o.name AS TargetName,
                o.description as Description
                FROM sys.dm_xe_packages AS p
                JOIN sys.dm_xe_objects AS o ON p.guid = o.package_guid
                WHERE (p.capabilities IS NULL OR p.capabilities & 1 = 0)
                $where
                AND (o.capabilities IS NULL OR o.capabilities & 1 = 0)
                ORDER BY o.object_type
                "
    }
    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                return
            }

            try {
                $server.Query($sql) | Select-DefaultView -ExcludeProperty ComputerName, InstanceName, ObjectTypeRaw
            } catch {
                Stop-Function -Message "Issue collecting trace data on $server." -Target $server -ErrorRecord $_
            }
        }
    }
}
tools\dbatools\functions\Get-DbaXESession.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaXESession {
    <#
    .SYNOPSIS
        Gets a list of Extended Events Sessions from the specified SQL Server instance(s).

    .DESCRIPTION
        Retrieves a list of Extended Events Sessions present on the specified SQL Server instance(s).

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Session
        Only return specific sessions. Options for this parameter are auto-populated from the server.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Klaas Vandenberghe (@PowerDBAKlaas)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaXESession

    .EXAMPLE
        PS C:\> Get-DbaXESession -SqlInstance ServerA\sql987

        Returns a custom object with ComputerName, SQLInstance, Session, StartTime, Status and other properties.

    .EXAMPLE
        PS C:\> Get-DbaXESession -SqlInstance ServerA\sql987 | Format-Table ComputerName, SqlInstance, Session, Status -AutoSize

        Returns a formatted table displaying ComputerName, SqlInstance, Session, and Status.

    .EXAMPLE
        PS C:\> 'ServerA\sql987','ServerB' | Get-DbaXESession

        Returns a custom object with ComputerName, SqlInstance, Session, StartTime, Status and other properties, from multiple SQL instances.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Sessions")]
        [object[]]$Session,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaXEsSession
    }

    process {

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 11 -AzureUnsupported
                $SqlConn = $server.ConnectionContext.SqlConnectionObject
                $SqlStoreConnection = New-Object Microsoft.SqlServer.Management.Sdk.Sfc.SqlStoreConnection $SqlConn
                $XEStore = New-Object  Microsoft.SqlServer.Management.XEvent.XEStore $SqlStoreConnection
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            Write-Message -Level Verbose -Message "Getting XEvents Sessions on $instance."
            $xesessions = $XEStore.sessions

            if ($Session) {
                $xesessions = $xesessions | Where-Object { $_.Name -in $Session }
            }

            foreach ($x in $xesessions) {
                $status = switch ($x.IsRunning) { $true { "Running" } $false { "Stopped" } }
                $files = $x.Targets.TargetFields | Where-Object Name -eq Filename | Select-Object -ExpandProperty Value

                $filecollection = $remotefile = @()

                if ($files) {
                    foreach ($file in $files) {
                        if ($file -notmatch ':\\' -and $file -notmatch '\\\\') {
                            $directory = $server.ErrorLogPath.TrimEnd("\")
                            $file = "$directory\$file"
                        }
                        $filecollection += $file
                        $remotefile += Join-AdminUnc -servername $server.ComputerName -filepath $file
                    }
                }

                Add-Member -Force -InputObject $x -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName
                Add-Member -Force -InputObject $x -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName
                Add-Member -Force -InputObject $x -MemberType NoteProperty -Name SqlInstance -Value $server.DomainInstanceName
                Add-Member -Force -InputObject $x -MemberType NoteProperty -Name Status -Value $status
                Add-Member -Force -InputObject $x -MemberType NoteProperty -Name Session -Value $x.Name
                Add-Member -Force -InputObject $x -MemberType NoteProperty -Name TargetFile -Value $filecollection
                Add-Member -Force -InputObject $x -MemberType NoteProperty -Name RemoteTargetFile -Value $remotefile
                Add-Member -Force -InputObject $x -MemberType NoteProperty -Name Parent -Value $server
                Add-Member -Force -InputObject $x -MemberType NoteProperty -Name Store -Value $XEStore
                Select-DefaultView -InputObject $x -Property ComputerName, InstanceName, SqlInstance, Name, Status, StartTime, AutoStart, State, Targets, TargetFile, Events, MaxMemory, MaxEventSize
            }
        }
    }
}
tools\dbatools\functions\Get-DbaXESessionTarget.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaXESessionTarget {
    <#
    .SYNOPSIS
        Get a list of Extended Events Session Targets from the specified SQL Server instance(s).

    .DESCRIPTION
        Retrieves a list of Extended Events Session Targets from the specified SQL Server instance(s).

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Session
        Only return a specific session. Options for this parameter are auto-populated from the server.

    .PARAMETER Target
        Only return a specific target.

    .PARAMETER InputObject
        Specifies an XE session returned by Get-DbaXESession to search.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaXESessionTarget

    .EXAMPLE
        PS C:\> Get-DbaXESessionTarget -SqlInstance ServerA\sql987 -Session system_health

        Shows targets for the system_health session on ServerA\sql987.

    .EXAMPLE
        PS C:\> Get-DbaXESession -SqlInstance sql2016 -Session system_health | Get-DbaXESessionTarget

        Returns the targets for the system_health session on sql2016.

    .EXAMPLE
        PS C:\> Get-DbaXESession -SqlInstance sql2016 -Session system_health | Get-DbaXESessionTarget -Target package0.event_file

        Return only the package0.event_file target for the system_health session on sql2016.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default")]
    param (
        [parameter(ValueFromPipeline, ParameterSetName = "instance", Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Session,
        [string[]]$Target,
        [parameter(ValueFromPipeline, ParameterSetName = "piped", Mandatory)]
        [Microsoft.SqlServer.Management.XEvent.Session[]]$InputObject,
        [switch][Alias('Silent')]
        $EnableException
    )

    begin {
        function Get-Target {
            [CmdletBinding()]
            param (
                $Sessions,
                $Session,
                $Server,
                $Target
            )

            foreach ($xsession in $Sessions) {

                if ($null -eq $server) {
                    $server = $xsession.Parent
                }

                if ($Session -and $xsession.Name -notin $Session) { continue }
                $status = switch ($xsession.IsRunning) { $true { "Running" } $false { "Stopped" } }
                $sessionname = $xsession.Name

                foreach ($xtarget in $xsession.Targets) {
                    if ($Target -and $xtarget.Name -notin $Target) { continue }

                    $files = $xtarget.TargetFields | Where-Object Name -eq Filename | Select-Object -ExpandProperty Value

                    $filecollection = $remotefile = @()

                    if ($files) {
                        foreach ($file in $files) {
                            if ($file -notmatch ':\\' -and $file -notmatch '\\\\') {
                                $directory = $server.ErrorLogPath.TrimEnd("\")
                                $file = "$directory\$file"
                            }
                            $filecollection += $file
                            $remotefile += Join-AdminUnc -servername $server.ComputerName -filepath $file
                        }
                    }

                    Add-Member -Force -InputObject $xtarget -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName
                    Add-Member -Force -InputObject $xtarget -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName
                    Add-Member -Force -InputObject $xtarget -MemberType NoteProperty -Name SqlInstance -Value $server.DomainInstanceName
                    Add-Member -Force -InputObject $xtarget -MemberType NoteProperty -Name Session -Value $sessionname
                    Add-Member -Force -InputObject $xtarget -MemberType NoteProperty -Name SessionStatus -Value $status
                    Add-Member -Force -InputObject $xtarget -MemberType NoteProperty -Name TargetFile -Value $filecollection
                    Add-Member -Force -InputObject $xtarget -MemberType NoteProperty -Name RemoteTargetFile -Value $remotefile

                    Select-DefaultView -InputObject $xtarget -Property ComputerName, InstanceName, SqlInstance, Session, SessionStatus, Name, ID, 'TargetFields as Field', PackageName, 'TargetFile as File', Description, ScriptName
                }
            }
        }
    }

    process {
        if (Test-FunctionInterrupt) { return }

        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaXESession -SqlInstance $instance -SqlCredential $SqlCredential -Session $Session
        }
        Get-Target -Sessions $InputObject -Session $Session -Target $Target
    }
}
tools\dbatools\functions\Get-DbaXESessionTargetFile.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaXESessionTargetFile {
    <#
    .SYNOPSIS
        Get a file system object from the Extended Events Session Target Files.

    .DESCRIPTION
        Get a file system object from the Extended Events Session Target Files.

        Note: this performs a Get-ChildItem on remote servers if the specified target SQL Server is remote.

    .PARAMETER SqlInstance
        The target SQL Server

    .PARAMETER SqlCredential
        Login to SQL instnace with alternative credentials

    .PARAMETER Session
        Only return files from a specific session. Options for this parameter are auto-populated from the server.

    .PARAMETER Target
        Only return files from a specific target.

    .PARAMETER InputObject
        Allows results from piping in Get-DbaXESessionTarget.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaXESessionTargetFile

    .EXAMPLE
        PS C:\> Get-DbaXESessionTargetFile -SqlInstance sql2017 -Session 'Long Running Queries'

        Shows Target Files for the 'Long Running Queries' session on sql2017.

    .EXAMPLE
        PS C:\> Get-DbaXESession -SqlInstance sql2016 -Session 'Long Running Queries' | Get-DbaXESessionTarget | Get-DbaXESessionTargetFile

        Returns the Target Files for the system_health session on sql2016.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default")]
    param (
        [parameter(ValueFromPipeline, ParameterSetName = "instance", Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Session,
        [string[]]$Target,
        [parameter(ValueFromPipeline, ParameterSetName = "piped", Mandatory)]
        [Microsoft.SqlServer.Management.XEvent.Target[]]$InputObject,
        [switch]$EnableException
    )

    process {
        if (Test-FunctionInterrupt) { return }

        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaXESessionTarget -SqlInstance $instance -SqlCredential $SqlCredential -Session $Session -Target $Target | Where-Object File -ne $null
        }

        foreach ($object in $InputObject) {
            $computer = [dbainstance]$object.ComputerName
            try {
                if ($computer.IsLocal) {
                    $file = $object.TargetFile
                    Write-Message -Level Verbose -Message "Getting $file"
                    Get-ChildItem "$file*" -ErrorAction Stop
                } else {
                    $file = $object.RemoteTargetFile
                    Write-Message -Level Verbose -Message "Getting $file"
                    Get-ChildItem -Recurse "$file*" -ErrorAction Stop
                }
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_
            }
        }
    }
}
tools\dbatools\functions\Get-DbaXESessionTemplate.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaXESessionTemplate {
    <#
    .SYNOPSIS
        Parses Extended Event XML templates. Defaults to parsing templates in the dbatools template repository (\bin\xetemplates\).

    .DESCRIPTION
        Parses Extended Event XML templates. Defaults to parsing templates in the dbatools template repository (\bin\xetemplates\).

        The default repository contains templates from:
        Microsoft's Templates that come with SSMS
        Jes Borland's "Everyday Extended Events" presentation and GitHub repository (https://github.com/grrlgeek/extended-events)
        Christian Grafe (@ChrGraefe) XE Repo: https://github.com/chrgraefe/sqlscripts/blob/master/XE-Events/
        Erin Stellato's Blog: https://www.sqlskills.com/blogs/erin/

        Some profile templates converted using:
        sp_SQLskills_ConvertTraceToExtendedEvents.sql
        Jonathan M. Kehayias, SQLskills.com
        http://sqlskills.com/blogs/jonathan

    .PARAMETER Path
        The path to the template directory. Defaults to the dbatools template repository (\bin\xetemplates\).

    .PARAMETER Pattern
        Specify a pattern for filtering. Alternatively, you can use Out-GridView -Passthru to select objects and pipe them to Import-DbaXESessionTemplate

    .PARAMETER Template
        Specifies one or more of the templates provided by dbatools. Press tab to cycle through the list of options.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaXESessionTemplate

    .EXAMPLE
        PS C:\> Get-DbaXESessionTemplate

        Returns information about all the templates in the local dbatools repository.

    .EXAMPLE
        PS C:\> Get-DbaXESessionTemplate | Out-GridView -PassThru | Import-DbaXESessionTemplate -SqlInstance sql2017 | Start-DbaXESession

        Allows you to select a Session template, then import it to the specified instance and start the session.

    .EXAMPLE
        PS C:\> Get-DbaXESessionTemplate -Path "$home\Documents\SQL Server Management Studio\Templates\XEventTemplates"

        Returns information about all the templates in your local XEventTemplates repository.

    .EXAMPLE
        PS C:\> Get-DbaXESessionTemplate -Pattern duration

        Returns information about all the templates that match the word "duration" in the title, category or body.

    .EXAMPLE
        PS C:\> Get-DbaXESessionTemplate | Select-Object *

        Returns more information about the template, including the full path/filename.

    #>

    [CmdletBinding()]
    param (
        [string[]]$Path = "$script:PSModuleRoot\bin\xetemplates",
        [string]$Pattern,
        [string[]]$Template,
        [switch]$EnableException
    )
    begin {
        $metadata = Import-Clixml "$script:PSModuleRoot\bin\xetemplates-metadata.xml"
        # In case people really want a "like" search, which is slower
        $Pattern = $Pattern.Replace("*", ".*").Replace("..*", ".*")
    }
    process {
        foreach ($directory in $Path) {
            $files = Get-ChildItem "$directory\*.xml"

            if ($Template) {
                $files = $files | Where-Object BaseName -in $Template
            }

            foreach ($file in $files) {
                try {
                    $xml = [xml](Get-Content $file)
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target $file -Continue
                }

                foreach ($session in $xml.event_sessions) {
                    $meta = $metadata | Where-Object Name -eq $session.event_session.name
                    if ($Pattern) {
                        if (
                            # There's probably a better way to do this
                            ($session.event_session.name -match $Pattern) -or
                            ($session.event_session.TemplateCategory.'#text' -match $Pattern) -or
                            ($session.event_session.TemplateSource -match $Pattern) -or
                            ($session.event_session.TemplateDescription.'#text' -match $Pattern) -or
                            ($session.event_session.TemplateName.'#text' -match $Pattern) -or
                            ($meta.Source -match $Pattern)
                        ) {
                            [pscustomobject]@{
                                Name          = $session.event_session.name
                                Category      = $session.event_session.TemplateCategory.'#text'
                                Source        = $meta.Source
                                Compatibility = ("$($meta.Compatibility)").ToString().Replace(",", "")
                                Description   = $session.event_session.TemplateDescription.'#text'
                                TemplateName  = $session.event_session.TemplateName.'#text'
                                Path          = $file
                                File          = $file.Name
                            } | Select-DefaultView -ExcludeProperty File, TemplateName, Path
                        }
                    } else {
                        [pscustomobject]@{
                            Name          = $session.event_session.name
                            Category      = $session.event_session.TemplateCategory.'#text'
                            Source        = $meta.Source
                            Compatibility = $meta.Compatibility.ToString().Replace(",", "")
                            Description   = $session.event_session.TemplateDescription.'#text'
                            TemplateName  = $session.event_session.TemplateName.'#text'
                            Path          = $file
                            File          = $file.Name
                        } | Select-DefaultView -ExcludeProperty File, TemplateName, Path
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Get-DbaXESmartTarget.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaXESmartTarget {
    <#
    .SYNOPSIS
        Gets an XESmartTarget PowerShell job created by Start-DbaXESmartTarget.

    .DESCRIPTION
        Gets an XESmartTarget PowerShell job created by Start-DbaXESmartTarget.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl) | SmartTarget by Gianluca Sartori (@spaghettidba)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaXESmartTarget

    .EXAMPLE
        PS C:\> Get-DbaXESmartTarget

        Gets an XESmartTarget PowerShell Job created by Start-DbaXESmartTarget.

    #>
    [CmdletBinding()]
    param (
        [switch]$EnableException
    )
    process {
        try {
            Get-Job | Where-Object Name -Match SmartTarget | Select-Object -Property ID, Name, State
        } catch {
            Stop-Function -Message "Failure" -ErrorRecord $_
        }
    }
}
tools\dbatools\functions\Get-DbaXEStore.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DbaXEStore {
    <#
    .SYNOPSIS
        Get a Extended Events store

    .DESCRIPTION
        Get a Extended Events store

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaXEStore

    .EXAMPLE
        PS C:\> Get-DbaXEStore -SqlInstance ServerA\sql987

        Returns an XEvent Store.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 11
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $SqlConn = $server.ConnectionContext.SqlConnectionObject
            $SqlStoreConnection = New-Object Microsoft.SqlServer.Management.Sdk.Sfc.SqlStoreConnection $SqlConn
            $store = New-Object  Microsoft.SqlServer.Management.XEvent.XEStore $SqlStoreConnection

            Add-Member -Force -InputObject $store -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName
            Add-Member -Force -InputObject $store -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName
            Add-Member -Force -InputObject $store -MemberType NoteProperty -Name SqlInstance -Value $server.DomainInstanceName
            Select-DefaultView -InputObject $store -Property ComputerName, InstanceName, SqlInstance, ServerName, Sessions, Packages, RunningSessionCount
        }
    }
}
tools\dbatools\functions\Grant-DbaAgPermission.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Grant-DbaAgPermission {
    <#
    .SYNOPSIS
        Grants endpoint and availability group permissions to a login.

    .DESCRIPTION
        Grants endpoint and availability group permissions to a login. If the account is a Windows login and does not exist, it will be automatically added.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Login
        The login or logins to modify.

    .PARAMETER AvailabilityGroup
        Only modify specific availability groups.

    .PARAMETER Type
        Specify type: Endpoint or AvailabilityGroup. Endpoint will modify the DatabaseMirror endpoint type.

    .PARAMETER Permission
        Grants one or more permissions:
            Alter
            Connect
            Control
            CreateSequence
            CreateAnyDatabase
            Delete
            Execute
            Impersonate
            Insert
            Receive
            References
            Select
            Send
            TakeOwnership
            Update
            ViewChangeTracking
            ViewDefinition

            CreateAnyDatabase

        Connect is default.

    .PARAMETER InputObject
        Enables piping from Get-DbaLogin.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: AvailabilityGroup, HA, AG
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Grant-DbaAgPermission

    .EXAMPLE
        PS C:\> Grant-DbaAgPermission -SqlInstance sql2017a -Type AvailabilityGroup -AvailabilityGroup SharePoint -Login ad\spservice -Permission CreateAnyDatabase

        Adds CreateAnyDatabase permissions to ad\spservice on the SharePoint availability group on sql2017a. Does not prompt for confirmation.

    .EXAMPLE
        PS C:\> Grant-DbaAgPermission -SqlInstance sql2017a -Type AvailabilityGroup -AvailabilityGroup ag1, ag2 -Login ad\spservice -Permission CreateAnyDatabase -Confirm

        Adds CreateAnyDatabase permissions to ad\spservice on the ag1 and ag2 availability groups on sql2017a. Prompts for confirmation.

    .EXAMPLE
        PS C:\> Get-DbaLogin -SqlInstance sql2017a | Out-GridView -Passthru | Grant-DbaAgPermission -Type EndPoint

        Grants the selected logins Connect permissions on the DatabaseMirroring endpoint for sql2017a
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Login,
        [string[]]$AvailabilityGroup,
        [parameter(Mandatory)]
        [ValidateSet('Endpoint', 'AvailabilityGroup')]
        [string[]]$Type,
        [ValidateSet('Alter', 'Connect', 'Control', 'CreateAnyDatabase', 'CreateSequence', 'Delete', 'Execute', 'Impersonate', 'Insert', 'Receive', 'References', 'Select', 'Send', 'TakeOwnership', 'Update', 'ViewChangeTracking', 'ViewDefinition')]
        [string[]]$Permission = "Connect",
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Login[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ($SqlInstance -and -not $Login -and -not $AvailabilityGroup) {
            Stop-Function -Message "You must specify one or more logins when using the SqlInstance parameter."
            return
        }

        if ($Type -contains "AvailabilityGroup" -and -not $AvailabilityGroup) {
            Stop-Function -Message "You must specify at least one availability group when using the AvailabilityGroup type."
            return
        }

        foreach ($instance in $SqlInstance) {
            if ($perm -contains "CreateAnyDatabase") {
                try {
                    $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
                } catch {
                    Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                }

                foreach ($ag in $AvailabilityGroup) {
                    try {
                        $server.Query("ALTER AVAILABILITY GROUP $ag GRANT CREATE ANY DATABASE")
                    } catch {
                        Stop-Function -Message "Failure" -ErrorRecord $_ -Target $instance
                        return
                    }
                }
            } elseif ($Login) {
                $InputObject += Get-DbaLogin -SqlInstance $instance -SqlCredential $SqlCredential -Login $Login
                foreach ($account in $Login) {
                    if ($account -notin $InputObject.Name) {
                        try {
                            $InputObject += New-DbaLogin -SqlInstance $server -Login $account -EnableException
                        } catch {
                            Stop-Function -Message "Failure" -ErrorRecord $_ -Target $instance
                            return
                        }
                    }
                }
            }
        }

        foreach ($account in $InputObject) {
            $server = $account.Parent
            if ($Type -contains "Endpoint") {
                $server.Endpoints.Refresh()
                $endpoint = $server.Endpoints | Where-Object EndpointType -eq DatabaseMirroring

                if (-not $endpoint) {
                    Stop-Function -Message "DatabaseMirroring endpoint does not exist on $server" -Target $server -Continue
                }

                foreach ($perm in $Permission) {
                    if ($Pscmdlet.ShouldProcess($server.Name, "Granting $perm on $endpoint")) {
                        if ($perm -in 'CreateAnyDatabase') {
                            Stop-Function -Message "$perm not supported by endpoints" -Continue
                        }
                        try {
                            $bigperms = New-Object Microsoft.SqlServer.Management.Smo.ObjectPermissionSet([Microsoft.SqlServer.Management.Smo.ObjectPermission]::$perm)
                            $endpoint.Grant($bigperms, $account.Name)
                            [pscustomobject]@{
                                ComputerName = $account.ComputerName
                                InstanceName = $account.InstanceName
                                SqlInstance  = $account.SqlInstance
                                Name         = $account.Name
                                Permission   = $perm
                                Type         = "Grant"
                                Status       = "Success"
                            }
                        } catch {
                            Stop-Function -Message "Failure" -ErrorRecord $_ -Target $ag -Continue
                        }
                    }
                }
            }

            if ($Type -contains "AvailabilityGroup") {
                $ags = Get-DbaAvailabilityGroup -SqlInstance $account.Parent -AvailabilityGroup $AvailabilityGroup
                foreach ($ag in $ags) {
                    foreach ($perm in $Permission) {
                        if ($perm -notin 'Alter', 'Control', 'TakeOwnership', 'ViewDefinition') {
                            Stop-Function -Message "$perm not supported by availability groups" -Continue
                        }
                        if ($Pscmdlet.ShouldProcess($server.Name, "Granting $perm on $ags")) {
                            try {
                                $bigperms = New-Object Microsoft.SqlServer.Management.Smo.ObjectPermissionSet([Microsoft.SqlServer.Management.Smo.ObjectPermission]::$perm)
                                $ag.Grant($bigperms, $account.Name)
                                [pscustomobject]@{
                                    ComputerName = $account.ComputerName
                                    InstanceName = $account.InstanceName
                                    SqlInstance  = $account.SqlInstance
                                    Name         = $account.Name
                                    Permission   = $perm
                                    Type         = "Grant"
                                    Status       = "Success"
                                }
                            } catch {
                                Stop-Function -Message "Failure" -ErrorRecord $_ -Target $ag -Continue
                            }
                        }
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Import-DbaCmsRegServer.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Import-DbaCmsRegServer {
    <#
    .SYNOPSIS
        Imports registered servers and registered server groups to SQL Server Central Management Server (CMS)

    .DESCRIPTION
        Imports registered servers and registered server groups to SQL Server Central Management Server (CMS)

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Group
        Imports to specific group

    .PARAMETER Path
        Optional path to exported reg server XML

    .PARAMETER InputObject
        Enables piping from Get-DbaCmsRegServer, Get-DbaCmsRegServerGroup, CSVs and other objects.

        If importing from CSV or other object, a column named ServerName is required. Optional columns include Name, Description and Group.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.

        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.

        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: RegisteredServer, CMS
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Import-DbaCmsRegServer

    .EXAMPLE
        PS C:\> Import-DbaCmsRegServer -SqlInstance sql2012 -Path C:\temp\corp-regservers.xml

        Imports C:\temp\corp-regservers.xml to the CMS on sql2012

    .EXAMPLE
        PS C:\> Import-DbaCmsRegServer -SqlInstance sql2008 -Group hr\Seattle -Path C:\temp\Seattle.xml

        Imports C:\temp\Seattle.xml to Seattle subgroup within the hr group on sql2008

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sql2008, sql2012 | Import-DbaCmsRegServer -SqlInstance sql2017

        Imports all registered servers from sql2008 and sql2012 to sql2017

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServerGroup -SqlInstance sql2008 -Group hr\Seattle | Import-DbaCmsRegServer -SqlInstance sql2017 -Group Seattle

        Imports all registered servers from the hr\Seattle group on sql2008 to the Seattle group on sql2017

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("FullName")]
        [string[]]$Path,
        [parameter(ValueFromPipeline)]
        [object[]]$InputObject,
        [object]$Group,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            # Prep to import from file
            if ((Test-Bound -ParameterName Path)) {
                $InputObject += Get-ChildItem -Path $Path
            }
            if ((Test-Bound -ParameterName Group) -and (Test-Bound -Not -ParameterName Path)) {
                if ($Group -is [Microsoft.SqlServer.Management.RegisteredServers.ServerGroup]) {
                    $groupobject = $Group
                } else {
                    $groupobject = Get-DbaCmsRegServerGroup -SqlInstance $instance -SqlCredential $SqlCredential -Group $Group
                }
                if (-not $groupobject) {
                    Stop-Function -Message "Group $Group cannot be found on $instance" -Target $instance -Continue
                }
            }

            foreach ($object in $InputObject) {
                if ($object -is [Microsoft.SqlServer.Management.RegisteredServers.RegisteredServer]) {

                    $groupexists = Get-DbaCmsRegServerGroup -SqlInstance $instance -SqlCredential $SqlCredential -Group $object.Parent.Name
                    if (-not $groupexists) {
                        $groupexists = Add-DbaCmsRegServerGroup -SqlInstance $instance -SqlCredential $SqlCredential -Name $object.Parent.Name
                    }
                    Add-DbaCmsRegServer -SqlInstance $instance -SqlCredential $SqlCredential -Name $object.Name -ServerName $object.ServerName -Description $object.Description -Group $groupexists
                } elseif ($object -is [Microsoft.SqlServer.Management.RegisteredServers.ServerGroup]) {
                    foreach ($regserver in $object.RegisteredServers) {
                        $groupexists = Get-DbaCmsRegServerGroup -SqlInstance $instance -SqlCredential $SqlCredential -Group $regserver.Parent.Name
                        if (-not $groupexists) {
                            $groupexists = Add-DbaCmsRegServerGroup -SqlInstance $instance -SqlCredential $SqlCredential -Name $regserver.Parent.Name
                        }
                        Add-DbaCmsRegServer -SqlInstance $instance -SqlCredential $SqlCredential -Name $regserver.Name -ServerName $regserver.ServerName -Description $regserver.Description -Group $groupexists
                    }
                } elseif ($object -is [System.IO.FileInfo]) {
                    if ((Test-Bound -ParameterName Group)) {
                        if ($Group -is [Microsoft.SqlServer.Management.RegisteredServers.ServerGroup]) {
                            $reggroups = $Group
                        } else {
                            $reggroups = Get-DbaCmsRegServerGroup -SqlInstance $instance -SqlCredential $SqlCredential -Group $Group
                        }
                    } else {
                        $reggroups = Get-DbaCmsRegServerGroup -SqlInstance $instance -SqlCredential $SqlCredential -Id 1
                    }

                    foreach ($file in $object) {
                        if (-not (Test-Path -Path $file)) {
                            Stop-Function -Message "$file cannot be found" -Target $file -Continue
                        }

                        foreach ($reggroup in $reggroups) {
                            try {
                                Write-Message -Level Verbose -Message "Importing $file to $($reggroup.Name) on $instance"
                                $urnlist = $reggroup.RegisteredServers.Urn.Value
                                $reggroup.Import($file.FullName)
                                Get-DbaCmsRegServer -SqlInstance $instance -SqlCredential $SqlCredential | Where-Object { $_.Urn.Value -notin $urnlist }
                            } catch {
                                Stop-Function -Message "Failure attempting to import $file to $instance" -ErrorRecord $_ -Continue
                            }
                        }
                    }
                } else {
                    if (-not $object.ServerName) {
                        Stop-Function -Message "Property 'ServerName' not found in InputObject. No servers added." -Continue
                    }
                    Add-DbaCmsRegServer -SqlInstance $instance -SqlCredential $SqlCredential -Name $object.Name -ServerName $object.ServerName -Description $object.Description -Group $groupobject
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Import-DbaRegisteredServer
    }
}
tools\dbatools\functions\Import-DbaCsv.ps1
function Import-DbaCsv {
    <#
    .SYNOPSIS
        Efficiently imports very large (and small) CSV files into SQL Server.

    .DESCRIPTION
        Import-DbaCsv takes advantage of .NET's super fast SqlBulkCopy class to import CSV files into SQL Server.

        The entire import is performed within a transaction, so if a failure occurs or the script is aborted, no changes will persist.

        If the table or view specified does not exist and -AutoCreateTable, it will be automatically created using slow and efficient but accomodating data types.

        This importer supports fields spanning multiple lines. The only restriction is that they must be quoted, otherwise it would not be possible to distinguish between malformed data and multi-line values.

    .PARAMETER Path
        Specifies path to the CSV file(s) to be imported. Multiple files may be imported at once.

    .PARAMETER NoHeaderRow
        By default, the first row is used to determine column names for the data being imported.

        Use this switch if the first row contains data and not column names.

    .PARAMETER Delimiter
        Specifies the delimiter used in the imported file(s). If no delimiter is specified, comma is assumed.

        Valid delimiters are '`t`, '|', ';',' ' and ',' (tab, pipe, semicolon, space, and comma).

    .PARAMETER SingleColumn
        Specifies that the file contains a single column of data. Otherwise, the delimiter check bombs.

    .PARAMETER SqlInstance
        The SQL Server Instance to import data into.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies the name of the database the CSV will be imported into. Options for this this parameter are  auto-populated from the server.

    .PARAMETER Schema
        Specifies the schema in which the SQL table or view where CSV will be imported into resides. Default is dbo

        If a schema name is not specified, and a CSV name with multiple dots is specified (ie; something.data.csv) then this will be interpreted as a request to import into a table [data] in the schema [something].

        If a schema does not currently exist, it will be created, after a prompt to confirm this. Authorization will be set to dbo by default

    .PARAMETER Table
        Specifies the SQL table or view where CSV will be imported into.

        If a table name is not specified, the table name will be automatically determined from the filename.

        If the table specified does not exist and -AutoCreateTable, it will be automatically created using slow and efficient but accomodating data types.

        If the automatically generated table datatypes do not work for you, please create the table prior to import.

        If you want to import specific columns from a CSV, create a view with corresponding columns.

    .PARAMETER Column
        Import only specific columns. To remap column names, use the ColumnMap.

    .PARAMETER ColumnMap
        By default, the bulk copy tries to automap columns. When it doesn't work as desired, this parameter will help. Check out the examples for more information.

    .PARAMETER AutoCreateTable
        Creates a table if it does not already exist. The table will be created with sub-optimal data types such as nvarchar(max)

    .PARAMETER Truncate
        If this switch is enabled, the destination table will be truncated prior to import.

    .PARAMETER NotifyAfter
        Specifies the import row count interval for reporting progress. A notification will be shown after each group of this many rows has been imported.

    .PARAMETER BatchSize
        Specifies the batch size for the import. Defaults to 50000.

    .PARAMETER TableLock
        If this switch is enabled, the SqlBulkCopy option to acquire a table lock will be used. This is automatically used if -Turbo is enabled.

        Per Microsoft "Obtain a bulk update lock for the duration of the bulk copy operation. When not
        specified, row locks are used."

    .PARAMETER CheckConstraints
        If this switch is enabled, the SqlBulkCopy option to check constraints will be used.

        Per Microsoft "Check constraints while data is being inserted. By default, constraints are not checked."

    .PARAMETER FireTriggers
        If this switch is enabled, the SqlBulkCopy option to allow insert triggers to be executed will be used.

        Per Microsoft "When specified, cause the server to fire the insert triggers for the rows being inserted into the database."

    .PARAMETER KeepIdentity
        If this switch is enabled, the SqlBulkCopy option to keep identity values from the source will be used.

        Per Microsoft "Preserve source identity values. When not specified, identity values are assigned by the destination."

    .PARAMETER KeepNulls
        If this switch is enabled, the SqlBulkCopy option to keep NULL values in the table will be used.

        Per Microsoft "Preserve null values in the destination table regardless of the settings for default values. When not specified, null values are replaced by default values where applicable."

    .PARAMETER NoProgress
        The progress bar is pretty but can slow down imports. Use this parameter to quietly import.

    .PARAMETER Quote
        Defines the default quote character wrapping every field.

    .PARAMETER Escape
        Defines the default escape character letting insert quotation characters inside a quoted field.

        The escape character can be the same as the quote character.

    .PARAMETER Comment
        Defines the default comment character indicating that a line is commented out. Default is #.

    .PARAMETER TrimmingOption
        Determines which values should be trimmed. Default is "None". Options are All, None, UnquotedOnly and QuotedOnly.

    .PARAMETER BufferSize
        Defines the default buffer size. The default BufferSize is 4096.

    .PARAMETER ParseErrorAction
        By default, the parse error action throws an exception and ends the import.

        You can also choose AdvanceToNextLine which basically ignores parse errors.

    .PARAMETER Encoding
        The encoding of the file.

    .PARAMETER NullValue
        The value which denotes a DbNull-value.

    .PARAMETER Threshold
        Defines the default value for Threshold indicating when the CsvReader should replace/remove consecutive null bytes.

    .PARAMETER MaxQuotedFieldLength
        The axmimum length (in bytes) for any quoted field.

    .PARAMETER SkipEmptyLine
        Skip empty lines.

    .PARAMETER SupportsMultiline
        Indicates if the importer should support multiline fields.

    .PARAMETER UseColumnDefault
        Use the column default values if the field is not in the record.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration, Import
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Import-DbaCsv

    .EXAMPLE
        PS C:\> Import-DbaCsv -Path C:\temp\housing.csv -SqlInstance sql001 -Database markets

        Imports the entire comma-delimited housing.csv to the SQL "markets" database on a SQL Server named sql001, using the first row as column names.

        Since a table name was not specified, the table name is automatically determined from filename as "housing".

    .EXAMPLE
        PS C:\> Import-DbaCsv -Path .\housing.csv -SqlInstance sql001 -Database markets -Table housing -Delimiter "`t" -NoHeaderRow

        Imports the entire comma-delimited housing.csv, including the first row which is not used for colum names, to the SQL markets database, into the housing table, on a SQL Server named sql001.

    .EXAMPLE
        PS C:\> Import-DbaCsv -Path C:\temp\huge.txt -SqlInstance sqlcluster -Database locations -Table latitudes -Delimiter "|"

        Imports the entire pipe-delimited huge.txt to the locations database, into the latitudes table on a SQL Server named sqlcluster.

    .EXAMPLE
        PS C:\> Import-DbaCsv -Path c:\temp\SingleColumn.csv -SqlInstance sql001 -Database markets -Table TempTable -SingleColumn

        Imports the single column CSV into TempTable

    .EXAMPLE
        PS C:\> Get-ChildItem -Path \\FileServer\csvs | Import-DbaCsv -SqlInstance sql001, sql002 -Database tempdb -AutoCreateTable

        Imports every CSV in the \\FileServer\csvs path into both sql001 and sql002's tempdb database. Each CSV will be imported into an automatically determined table name.

    .EXAMPLE
        PS C:\> Get-ChildItem -Path \\FileServer\csvs | Import-DbaCsv -SqlInstance sql001, sql002 -Database tempdb -AutoCreateTable -WhatIf

        Shows what would happen if the command were to be executed

    .EXAMPLE
        PS C:\> Import-DbaCsv -Path c:\temp\dataset.csv -SqlInstance sql2016 -Database tempdb -Column Name, Address, Mobile

        Import only Name, Address and Mobile even if other columns exist. All other columns are ignored and therefore null or default values.

    .EXAMPLE
        PS C:\> $columns = @{
        >> Text = 'FirstName'
        >> Number = 'PhoneNumber'
        >> }
        PS C:\> Import-DbaCsv -Path c:\temp\supersmall.csv -SqlInstance sql2016 -Database tempdb -ColumnMap $columns

        The CSV column 'Text' is inserted into SQL column 'FirstName' and CSV column Number is inserted into the SQL Column 'PhoneNumber'. All other columns are ignored and therefore null or default values.
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseDeclaredVarsMoreThanAssignments", "line", Justification = "Variable line is used, False Positive on line 330")]
    param (
        [parameter(ValueFromPipeline)]
        [ValidateNotNullOrEmpty()]
        [Alias("Csv", "FullPath")]
        [object[]]$Path,
        [Parameter(Mandatory)]
        [DbaInstanceParameter[]]$SqlInstance,
        [pscredential]$SqlCredential,
        [Parameter(Mandatory)]
        [string]$Database,
        [string]$Table,
        [string]$Schema = "dbo",
        [switch]$Truncate,
        [char]$Delimiter = ",",
        [switch]$SingleColumn,
        [int]$BatchSize = 50000,
        [int]$NotifyAfter = 50000,
        [switch]$TableLock,
        [switch]$CheckConstraints,
        [switch]$FireTriggers,
        [switch]$KeepIdentity,
        [switch]$KeepNulls,
        [string[]]$Column,
        [hashtable[]]$ColumnMap,
        [switch]$AutoCreateTable,
        [switch]$NoProgress,
        [switch]$NoHeaderRow,
        [char]$Quote = '"',
        [char]$Escape = '"',
        [char]$Comment = '#',
        [ValidateSet('All', 'None', 'UnquotedOnly', 'QuotedOnly')]
        [string]$TrimmingOption = "None",
        [int]$BufferSize = 4096,
        [ValidateSet('AdvanceToNextLine', 'ThrowException')]
        [string]$ParseErrorAction = 'ThrowException',
        [System.Text.Encoding]$Encoding,
        [string]$NullValue,
        [int]$Threshold = 60,
        [int]$MaxQuotedFieldLength,
        [switch]$SkipEmptyLine,
        [switch]$SupportsMultiline,
        [switch]$UseColumnDefault,
        [switch]$EnableException
    )
    begin {
        $FirstRowHeader = $NoHeaderRow -eq $false
        $scriptelapsed = [System.Diagnostics.Stopwatch]::StartNew()

        try {
            # SilentContinue isn't enough
            Add-Type -Path "$script:PSModuleRoot\bin\csv\LumenWorks.Framework.IO.dll" -ErrorAction Stop
        } catch {
            $null = 1
        }

        function New-SqlTable {
            <#
                .SYNOPSIS
                    Creates new Table using existing SqlCommand.

                    SQL datatypes based on best guess of column data within the -ColumnText parameter.
                    Columns parameter determine column names.

                .EXAMPLE
                    New-SqlTable -Path $Path -Delimiter $Delimiter -Columns $columns -ColumnText $columntext -SqlConn $sqlconn -Transaction $transaction

                .OUTPUTS
                    Creates new table
            #>
            [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
            param (
                [Parameter(Mandatory)]
                [string]$Path,
                [Parameter(Mandatory)]
                [string]$Delimiter,
                [Parameter(Mandatory)]
                [bool]$FirstRowHeader,
                [System.Data.SqlClient.SqlConnection]$sqlconn,
                [System.Data.SqlClient.SqlTransaction]$transaction
            )
            $reader = New-Object LumenWorks.Framework.IO.Csv.CsvReader(
                (New-Object System.IO.StreamReader($Path)),
                $FirstRowHeader,
                $Delimiter,
                $Quote,
                $Escape,
                $Comment,
                [LumenWorks.Framework.IO.Csv.ValueTrimmingOptions]::$TrimmingOption,
                $BufferSize,
                $NullValue
            )
            $columns = $reader.GetFieldHeaders()
            $reader.Close()
            $reader.Dispose()

            # Get SQL datatypes by best guess on first data row
            $sqldatatypes = @(); $index = 0

            foreach ($column in $Columns) {
                $sqldatatypes += "[$column] varchar(MAX)"
            }

            $sql = "BEGIN CREATE TABLE [$schema].[$table] ($($sqldatatypes -join ' NULL,')) END"
            $sqlcmd = New-Object System.Data.SqlClient.SqlCommand($sql, $sqlconn, $transaction)

            try {
                $null = $sqlcmd.ExecuteNonQuery()
            } catch {
                $errormessage = $_.Exception.Message.ToString()
                Stop-Function -Continue -Message "Failed to execute $sql. `nDid you specify the proper delimiter? `n$errormessage"
            }

            Write-Message -Level Verbose -Message "Successfully created table $schema.$table with the following column definitions:`n $($sqldatatypes -join "`n ")"
            # Write-Message -Level Warning -Message "All columns are created using a best guess, and use their maximum datatype."
            Write-Message -Level Verbose -Message "This is inefficient but allows the script to import without issues."
            Write-Message -Level Verbose -Message "Consider creating the table first using best practices if the data will be used in production."
        }

        Write-Message -Level Verbose -Message "Started at $(Get-Date)"

        # Getting the total rows copied is a challenge. Use SqlBulkCopyExtension.
        # http://stackoverflow.com/questions/1188384/sqlbulkcopy-row-count-when-complete

        $sourcecode = 'namespace System.Data.SqlClient
        {
            using Reflection;

            public static class SqlBulkCopyExtension
            {
                const String _rowsCopiedFieldName = "_rowsCopied";
                static FieldInfo _rowsCopiedField = null;

                public static int RowsCopiedCount(this SqlBulkCopy bulkCopy)
                {
                    if (_rowsCopiedField == null) _rowsCopiedField = typeof(SqlBulkCopy).GetField(_rowsCopiedFieldName, BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
                    return (int)_rowsCopiedField.GetValue(bulkCopy);
                }
            }
        }
    '
        if (-not $script:core) {
            try {
                Add-Type -ReferencedAssemblies System.Data.dll -TypeDefinition $sourcecode -ErrorAction Stop
            } catch {
                $null = 1
            }
        }
    }
    process {
        foreach ($filename in $Path) {

            if ($filename.FullName) {
                $filename = $filename.FullName
            }

            if (-not (Test-Path -Path $filename)) {
                Stop-Function -Continue -Message "$filename cannot be found"
            }

            $file = (Resolve-Path -Path $filename).ProviderPath

            # Does the second line contain the specified delimiter?
            try {
                $firstline = Get-Content -Path $file -TotalCount 2 -ErrorAction Stop
            } catch {
                Stop-Function -Continue -Message "Failure reading $file" -ErrorRecord $_
            }
            if (-not $SingleColumn) {
                if ($firstline -notmatch $Delimiter) {
                    Stop-Function -Message "Delimiter ($Delimiter) not found in first few rows of $file. If this is a single column import, please specify -SingleColumn"
                    return
                }
            }

            # Automatically generate Table name if not specified, then prompt user to confirm
            if (-not (Test-Bound -ParameterName Table)) {
                $table = [IO.Path]::GetFileNameWithoutExtension($file)
                Write-Message -Level Verbose -Message "Table name not specified, using $table"
            }

            foreach ($instance in $SqlInstance) {
                $elapsed = [System.Diagnostics.Stopwatch]::StartNew()
                # Open Connection to SQL Server
                try {
                    $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential -StatementTimeout 0 -MinimumVersion 9
                    $sqlconn = $server.ConnectionContext.SqlConnectionObject
                    $sqlconn.Open()
                } catch {
                    Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                }

                if ($PSCmdlet.ShouldProcess($instance, "Starting transaction in $Database")) {
                    # Everything will be contained within 1 transaction, even creating a new table if required
                    # and truncating the table, if specified.
                    $transaction = $sqlconn.BeginTransaction()
                }

                # Ensure database exists
                $sql = "select count(*) from master.dbo.sysdatabases where name = '$Database'"
                $sqlcmd = New-Object System.Data.SqlClient.SqlCommand($sql, $sqlconn, $transaction)
                if (($sqlcmd.ExecuteScalar()) -eq 0) {
                    Stop-Function -Continue -Message "Database does not exist on $instance"
                }
                Write-Message -Level Verbose -Message "Database exists"
                $sqlconn.ChangeDatabase($Database)

                # Ensure Schema exists
                $sql = "select count(*) from $Database.sys.schemas where name='$schema'"
                $sqlcmd = New-Object System.Data.SqlClient.SqlCommand($sql, $sqlconn, $transaction)

                # If Schema doesn't exist create it
                # Defaulting to dbo.
                if (($sqlcmd.ExecuteScalar()) -eq 0) {
                    if (-not $AutoCreateTable) {
                        Stop-Function -Continue -Message "Schema $Schema does not exist and AutoCreateTable was not specified"
                    }
                    $sql = "CREATE SCHEMA [$schema] AUTHORIZATION dbo"
                    if ($PSCmdlet.ShouldProcess($instance, "Creating schema $schema")) {
                        $sqlcmd = New-Object System.Data.SqlClient.SqlCommand($sql, $sqlconn, $transaction)
                        try {
                            $null = $sqlcmd.ExecuteNonQuery()
                        } catch {
                            Stop-Function -Continue -Message "Could not create $schema" -ErrorRecord $_
                        }
                    }
                }

                # Ensure table or view exists
                $sql = "select count(*) from $Database.sys.tables where name = '$table' and schema_id=schema_id('$schema')"
                $sqlcmd = New-Object System.Data.SqlClient.SqlCommand($sql, $sqlconn, $transaction)

                $sql2 = "select count(*) from $Database.sys.views where name = '$table' and schema_id=schema_id('$schema')"
                $sqlcmd2 = New-Object System.Data.SqlClient.SqlCommand($sql2, $sqlconn, $transaction)

                # Create the table if required. Remember, this will occur within a transaction, so if the script fails, the
                # new table will no longer exist.
                if (($sqlcmd.ExecuteScalar()) -eq 0 -and ($sqlcmd2.ExecuteScalar()) -eq 0) {
                    if (-not $AutoCreateTable) {
                        Stop-Function -Continue -Message "Table or view $table does not exist and AutoCreateTable was not specified"
                    }
                    Write-Message -Level Verbose -Message "Table does not exist"
                    if ($PSCmdlet.ShouldProcess($instance, "Creating table $table")) {
                        try {
                            New-SqlTable -Path $file -Delimiter $Delimiter -FirstRowHeader $FirstRowHeader -SqlConn $sqlconn -Transaction $transaction
                        } catch {
                            Stop-Function -Continue -Message "Failure" -ErrorRecord $_
                        }
                    }
                } else {
                    Write-Message -Level Verbose -Message "Table exists"
                }

                # Truncate if specified. Remember, this will occur within a transaction, so if the script fails, the
                # truncate will not be committed.
                if ($Truncate) {
                    $sql = "TRUNCATE TABLE [$schema].[$table]"
                    if ($PSCmdlet.ShouldProcess($instance, "Performing TRUNCATE TABLE [$schema].[$table] on $Database")) {
                        $sqlcmd = New-Object System.Data.SqlClient.SqlCommand($sql, $sqlconn, $transaction)
                        try {
                            $null = $sqlcmd.ExecuteNonQuery()
                        } catch {
                            Stop-Function -Continue -Message "Could not truncate $schema.$table" -ErrorRecord $_
                        }
                    }
                }

                # Setup bulk copy
                Write-Message -Level Verbose -Message "Starting bulk copy for $(Split-Path $file -Leaf)"

                # Setup bulk copy options
                $bulkCopyOptions = @()
                $options = "TableLock", "CheckConstraints", "FireTriggers", "KeepIdentity", "KeepNulls", "Default"
                foreach ($option in $options) {
                    $optionValue = Get-Variable $option -ValueOnly -ErrorAction SilentlyContinue
                    if ($optionValue -eq $true) {
                        $bulkCopyOptions += "$option"
                    }
                }
                $bulkCopyOptions = $bulkCopyOptions -join " & "

                if ($PSCmdlet.ShouldProcess($instance, "Performing import from $file")) {
                    try {
                        # Create SqlBulkCopy using default options, or options specified in command line.
                        if ($bulkCopyOptions) {
                            $bulkcopy = New-Object Data.SqlClient.SqlBulkCopy($oleconnstring, $bulkCopyOptions, $transaction)
                        } else {
                            $bulkcopy = New-Object Data.SqlClient.SqlBulkCopy($sqlconn, "Default", $transaction)
                        }

                        $bulkcopy.DestinationTableName = "[$schema].[$table]"
                        $bulkcopy.BulkCopyTimeout = 0
                        $bulkCopy.BatchSize = $BatchSize
                        $bulkCopy.NotifyAfter = $NotifyAfter
                        $bulkCopy.EnableStreaming = $true

                        if ($ColumnMap) {
                            foreach ($columnname in $ColumnMap) {
                                foreach ($key in $columnname.Keys) {
                                    $null = $bulkcopy.ColumnMappings.Add($key, $columnname[$key])
                                }
                            }
                        }

                        if ($Column) {
                            foreach ($columnname in $Column) {
                                $null = $bulkcopy.ColumnMappings.Add($columnname, $columnname)
                            }
                        }
                    } catch {
                        Stop-Function -Continue -Message "Failure" -ErrorRecord $_
                    }

                    # Write to server :D
                    try {
                        $reader = New-Object LumenWorks.Framework.IO.Csv.CsvReader(
                            (New-Object System.IO.StreamReader($file)),
                            $FirstRowHeader,
                            $Delimiter,
                            $Quote,
                            $Escape,
                            $Comment,
                            [LumenWorks.Framework.IO.Csv.ValueTrimmingOptions]::$TrimmingOption,
                            $BufferSize,
                            $NullValue
                        )

                        if (Test-Bound -ParameterName Encoding) {
                            $reader.Encoding = $Encoding
                        }
                        if (Test-Bound -ParameterName Threshold) {
                            $reader.Threshold = $Threshold
                        }
                        if (Test-Bound -ParameterName MaxQuotedFieldLength) {
                            $reader.MaxQuotedFieldLength = $MaxQuotedFieldLength
                        }
                        if (Test-Bound -ParameterName SkipEmptyLine) {
                            $reader.SkipEmptyLines = $SkipEmptyLine
                        }
                        if (Test-Bound -ParameterName SupportsMultiline) {
                            $reader.SupportsMultiline = $SupportsMultiline
                        }
                        if (Test-Bound -ParameterName UseColumnDefault) {
                            $reader.UseColumnDefaults = $UseColumnDefault
                        }
                        if (Test-Bound -ParameterName ParseErrorAction) {
                            $reader.DefaultParseErrorAction = $ParseErrorAction
                        }

                        # Add rowcount output
                        $bulkCopy.Add_SqlRowsCopied( {
                                $script:totalrows = $args[1].RowsCopied
                                if (-not $NoProgress) {
                                    $timetaken = [math]::Round($elapsed.Elapsed.TotalSeconds, 2)
                                    Write-ProgressHelper -StepNumber 1 -TotalSteps 2 -Activity "Importing from $file" -Message ([System.String]::Format("Progress: {0} rows in {2} seconds", $script:totalrows, $percent, $timetaken)) -ExcludePercent
                                }
                            })

                        $bulkCopy.WriteToServer($reader)

                        if ($resultcount -is [int]) {
                            Write-Progress -id 1 -activity "Inserting $resultcount rows" -status "Complete" -Completed
                        }

                        $reader.Close()
                        $reader.Dispose()
                        $completed = $true
                    } catch {
                        $completed = $false

                        if ($resultcount -is [int]) {
                            Write-Progress -id 1 -activity "Inserting $resultcount rows" -status "Failed" -Completed
                        }
                        Stop-Function -Continue -Message "Failure" -ErrorRecord $_
                    }
                }
                if ($PSCmdlet.ShouldProcess($instance, "Committing transaction")) {
                    if ($completed) {
                        # "Note: This count does not take into consideration the number of rows actually inserted when Ignore Duplicates is set to ON."
                        $null = $transaction.Commit()
                        if ($script:core) {
                            $rowscopied = "Unsupported in Core"
                        } else {
                            $rowscopied = [System.Data.SqlClient.SqlBulkCopyExtension]::RowsCopiedCount($bulkcopy)
                        }

                        Write-Message -Level Verbose -Message "$rowscopied total rows copied"

                        [pscustomobject]@{
                            ComputerName  = $server.ComputerName
                            InstanceName  = $server.ServiceName
                            SqlInstance   = $server.DomainInstanceName
                            Database      = $Database
                            Table         = $table
                            Schema        = $schema
                            RowsCopied    = $rowscopied
                            Elapsed       = [prettytimespan]$elapsed.Elapsed
                            RowsPerSecond = [int]($rowscopied / $elapsed.Elapsed.TotalSeconds)
                            Path          = $file
                        }
                    } else {
                        Stop-Function -Message "Transaction rolled back. Was the proper delimiter specified? Is the first row the column name?" -ErrorRecord $_
                        return
                    }
                }

                # Close everything just in case & ignore errors
                try {
                    $null = $sqlconn.close(); $null = $sqlconn.Dispose();
                    $null = $bulkCopy.close(); $bulkcopy.dispose();
                    $null = $reader.close(); $null = $reader.dispose()
                } catch {
                    #here to avoid an empty catch
                    $null = 1
                }
            }
        }
    }
    end {
        # Close everything just in case & ignore errors
        try {
            $null = $sqlconn.close(); $null = $sqlconn.Dispose();
            $null = $bulkCopy.close(); $bulkcopy.dispose();
            $null = $reader.close(); $null = $reader.dispose()
        } catch {
            #here to avoid an empty catch
            $null = 1
        }

        # Script is finished. Show elapsed time.
        $totaltime = [math]::Round($scriptelapsed.Elapsed.TotalSeconds, 2)
        Write-Message -Level Verbose -Message "Total Elapsed Time for everything: $totaltime seconds"

        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Import-DbaCsvtoSql
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Import-CsvToSql
    }
}
tools\dbatools\functions\Import-DbaPfDataCollectorSetTemplate.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Import-DbaPfDataCollectorSetTemplate {
    <#
    .SYNOPSIS
        Imports a new Performance Monitor Data Collector Set Template either from the dbatools repository or a file you specify.

    .DESCRIPTION
        Imports a new Performance Monitor Data Collector Set Template either from the dbatools repository or a file you specify.
        When importing data collector sets from the local instance, Run As Admin is required.

        Note: The included counters will be added for all SQL instances on the machine by default.
        For specific instances in addition to the default, use -Instance.

        See https://msdn.microsoft.com/en-us/library/windows/desktop/aa371952 for more information

    .PARAMETER ComputerName
        The target computer. Defaults to localhost.

    .PARAMETER Credential
        Allows you to login to servers using alternative credentials. To use:

        $scred = Get-Credential, then pass $scred object to the -Credential parameter.

    .PARAMETER Path
        The path to the xml file or files.

    .PARAMETER Template
        From one or more of the templates from the dbatools repository. Press Tab to cycle through the available options.

    .PARAMETER RootPath
        Sets the base path where the subdirectories are created.

    .PARAMETER DisplayName
        Sets the display name of the data collector set.

    .PARAMETER SchedulesEnabled
        If this switch is enabled, sets a value that indicates whether the schedules are enabled.

    .PARAMETER Segment
        Sets a value that indicates whether PLA creates new logs if the maximum size or segment duration is reached before the data collector set is stopped.

    .PARAMETER SegmentMaxDuration
        Sets the duration that the data collector set can run before it begins writing to new log files.

    .PARAMETER SegmentMaxSize
        Sets the maximum size of any log file in the data collector set.

    .PARAMETER Subdirectory
        Sets a base subdirectory of the root path where the next instance of the data collector set will write its logs.

    .PARAMETER SubdirectoryFormat
        Sets flags that describe how to decorate the subdirectory name. PLA appends the decoration to the folder name. For example, if you specify plaMonthDayHour, PLA appends the current month, day, and hour values to the folder name. If the folder name is MyFile, the result could be MyFile110816.

    .PARAMETER SubdirectoryFormatPattern
        Sets a format pattern to use when decorating the folder name. Default is 'yyyyMMdd\-NNNNNN'.

    .PARAMETER Task
        Sets the name of a Task Scheduler job to start each time the data collector set stops, including between segments.

    .PARAMETER TaskRunAsSelf
        If this switch is enabled, sets a value that determines whether the task runs as the data collector set user or as the user specified in the task.

    .PARAMETER TaskArguments
        Sets the command-line arguments to pass to the Task Scheduler job specified in the IDataCollectorSet::Task property.
        See https://msdn.microsoft.com/en-us/library/windows/desktop/aa371992 for more information.

    .PARAMETER TaskUserTextArguments
        Sets the command-line arguments that are substituted for the {usertext} substitution variable in the IDataCollectorSet::TaskArguments property.
        See https://msdn.microsoft.com/en-us/library/windows/desktop/aa371993 for more information.

    .PARAMETER StopOnCompletion
        If this switch is enabled, sets a value that determines whether the data collector set stops when all the data collectors in the set are in a completed state.

    .PARAMETER Instance
        By default, the template will be applied to all instances. If you want to set specific ones in addition to the default, supply just the instance name.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Performance, DataCollector, PerfCounter
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Import-DbaPfDataCollectorSetTemplate

    .EXAMPLE
        PS C:\> Import-DbaPfDataCollectorSetTemplate -ComputerName sql2017 -Template 'Long Running Query'

        Creates a new data collector set named 'Long Running Query' from the dbatools repository on the SQL Server sql2017.

    .EXAMPLE
        PS C:\> Import-DbaPfDataCollectorSetTemplate -ComputerName sql2017 -Template 'Long Running Query' -DisplayName 'New Long running query' -Confirm

        Creates a new data collector set named "New Long Running Query" using the 'Long Running Query' template. Forces a confirmation if the template exists.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorSet -ComputerName sql2017 -Session db_ola_health | Remove-DbaPfDataCollectorSet
        Import-DbaPfDataCollectorSetTemplate -ComputerName sql2017 -Template db_ola_health | Start-DbaPfDataCollectorSet

        Imports a session if it exists, then recreates it using a template.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorSetTemplate | Out-GridView -PassThru | Import-DbaPfDataCollectorSetTemplate -ComputerName sql2017

        Allows you to select a Session template then import to an instance named sql2017.

    .EXAMPLE
        PS C:\> Import-DbaPfDataCollectorSetTemplate -ComputerName sql2017 -Template 'Long Running Query' -Instance SHAREPOINT

        Creates a new data collector set named 'Long Running Query' from the dbatools repository on the SQL Server sql2017 for both the default and the SHAREPOINT instance.

        If you'd like to remove counters for the default instance, use Remove-DbaPfDataCollectorCounter.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [string]$DisplayName,
        [switch]$SchedulesEnabled,
        [string]$RootPath,
        [switch]$Segment,
        [int]$SegmentMaxDuration,
        [int]$SegmentMaxSize,
        [string]$Subdirectory,
        [int]$SubdirectoryFormat = 3,
        [string]$SubdirectoryFormatPattern = 'yyyyMMdd\-NNNNNN',
        [string]$Task,
        [switch]$TaskRunAsSelf,
        [string]$TaskArguments,
        [string]$TaskUserTextArguments,
        [switch]$StopOnCompletion,
        [parameter(ValueFromPipelineByPropertyName)]
        [Alias("FullName")]
        [string[]]$Path,
        [string[]]$Template,
        [string[]]$Instance,
        [switch]$EnableException
    )
    begin {
        #Variable marked as unused by PSScriptAnalyzer
        #$metadata = Import-Clixml "$script:PSModuleRoot\bin\perfmontemplates\collectorsets.xml"

        $setscript = {
            $setname = $args[0]; $templatexml = $args[1]
            $collectorset = New-Object -ComObject Pla.DataCollectorSet
            $collectorset.SetXml($templatexml)
            $null = $collectorset.Commit($setname, $null, 0x0003) #add or modify.
            $null = $collectorset.Query($setname, $Null)
        }

        $instancescript = {
            $services = Get-Service -DisplayName *sql* | Select-Object -ExpandProperty DisplayName
            [regex]::matches($services, '(?<=\().+?(?=\))').Value | Where-Object { $PSItem -ne 'MSSQLSERVER' } | Select-Object -Unique
        }
    }
    process {
        
        
        if ((Test-Bound -ParameterName Path -Not) -and (Test-Bound -ParameterName Template -Not)) {
            Stop-Function -Message "You must specify Path or Template"
        }

        if (($Path.Count -gt 1 -or $Template.Count -gt 1) -and (Test-Bound -ParameterName Template)) {
            Stop-Function -Message "Name cannot be specified with multiple files or templates because the Session will already exist"
        }

        foreach ($computer in $ComputerName) {
            $null = Test-ElevationRequirement -ComputerName $computer -Continue

            foreach ($file in $template) {
                $templatepath = "$script:PSModuleRoot\bin\perfmontemplates\collectorsets\$file.xml"
                if ((Test-Path $templatepath)) {
                    $Path += $templatepath
                } else {
                    Stop-Function -Message "Invalid template ($templatepath does not exist)" -Continue
                }
            }

            foreach ($file in $Path) {

                if ((Test-Bound -ParameterName DisplayName -Not)) {
                    Set-Variable -Name DisplayName -Value (Get-ChildItem -Path $file).BaseName
                }

                $Name = $DisplayName

                Write-Message -Level Verbose -Message "Processing $file for $computer"

                if ((Test-Bound -ParameterName RootPath -Not)) {
                    Set-Variable -Name RootName -Value "%systemdrive%\PerfLogs\Admin\$Name"
                }

                # Perform replace
                $temp = ([System.IO.Path]::GetTempPath()).TrimEnd("").TrimEnd("\")
                $tempfile = "$temp\import-dbatools-perftemplate.xml"

                try {
                    # Get content
                    $contents = Get-Content $file -ErrorAction Stop

                    # Replace content
                    $replacements = 'RootPath', 'DisplayName', 'SchedulesEnabled', 'Segment', 'SegmentMaxDuration', 'SegmentMaxSize', 'SubdirectoryFormat', 'SubdirectoryFormatPattern', 'Task', 'TaskRunAsSelf', 'TaskArguments', 'TaskUserTextArguments', 'StopOnCompletion', 'DisplayNameUnresolved'

                    foreach ($replacement in $replacements) {
                        $phrase = "<$replacement></$replacement>"
                        $value = (Get-Variable -Name $replacement -ErrorAction SilentlyContinue).Value
                        if ($value -eq $false) {
                            $value = "0"
                        }
                        if ($value -eq $true) {
                            $value = "1"
                        }
                        $replacephrase = "<$replacement>$value</$replacement>"
                        $contents = $contents.Replace($phrase, $replacephrase)
                    }

                    # Set content
                    $null = Set-Content -Path $tempfile -Value $contents -Encoding Unicode
                    $xml = [xml](Get-Content $tempfile -ErrorAction Stop)
                    $plainxml = Get-Content $tempfile -ErrorAction Stop -Raw
                    $file = $tempfile
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target $file -Continue
                }
                if (-not $xml.DataCollectorSet) {
                    Stop-Function -Message "$file is not a valid Performance Monitor template document" -Continue
                }

                try {
                    Write-Message -Level Verbose -Message "Importing $file as $name "

                    if ($instance) {
                        $instances = $instance
                    } else {
                        $instances = Invoke-Command2 -ComputerName $computer -Credential $Credential -ScriptBlock $instancescript -ErrorAction Stop -Raw
                    }

                    $scriptblock = {
                        try {
                            $results = Invoke-Command2 -ComputerName $computer -Credential $Credential -ScriptBlock $setscript -ArgumentList $Name, $plainxml -ErrorAction Stop
                            Write-Message -Level Verbose -Message " $results"
                        } catch {
                            Stop-Function -Message "Failure starting $setname on $computer" -ErrorRecord $_ -Target $computer -Continue
                        }
                    }

                    if ((Get-DbaPfDataCollectorSet -ComputerName $computer -CollectorSet $Name)) {
                        if ($Pscmdlet.ShouldProcess($computer, "CollectorSet $Name already exists. Modify?")) {
                            Invoke-Command -Scriptblock $scriptblock
                            $output = Get-DbaPfDataCollectorSet -ComputerName $computer -CollectorSet $Name
                        }
                    } else {
                        if ($Pscmdlet.ShouldProcess($computer, "Importing collector set $Name")) {
                            Invoke-Command -Scriptblock $scriptblock
                            $output = Get-DbaPfDataCollectorSet -ComputerName $computer -CollectorSet $Name
                        }
                    }

                    $newcollection = @()
                    foreach ($instance in $instances) {
                        $datacollector = Get-DbaPfDataCollectorSet -ComputerName $computer -CollectorSet $Name | Get-DbaPfDataCollector
                        $sqlcounters = $datacollector | Get-DbaPfDataCollectorCounter | Where-Object { $_.Name -match 'sql.*\:' -and $_.Name -notmatch 'sqlclient' } | Select-Object -ExpandProperty Name

                        foreach ($counter in $sqlcounters) {
                            $split = $counter.Split(":")
                            $firstpart = switch ($split[0]) {
                                'SQLServer' { 'MSSQL' }
                                '\SQLServer' { '\MSSQL' }
                                default { $split[0] }
                            }
                            $secondpart = $split[-1]
                            $finalcounter = "$firstpart`$$instance`:$secondpart"
                            $newcollection += $finalcounter
                        }
                    }

                    if ($newcollection.Count) {
                        if ($Pscmdlet.ShouldProcess($computer, "Adding $($newcollection.Count) additional counters")) {
                            $null = Add-DbaPfDataCollectorCounter -InputObject $datacollector -Counter $newcollection
                        }
                    }

                    Remove-Item $tempfile -ErrorAction SilentlyContinue
                    $output
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target $store -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Import-DbaSpConfigure.ps1
function Import-DbaSpConfigure {
    <#
    .SYNOPSIS
        Updates sp_configure settings on destination server.

    .DESCRIPTION
        Updates sp_configure settings on destination server.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER SqlInstance
        Specifies a SQL Server instance to set up sp_configure values on using a SQL file.

    .PARAMETER SqlCredential
        Use this SQL credential if you are setting up sp_configure values from a SQL file.

        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Path
        Specifies the path to a SQL script file holding sp_configure queries for each of the settings to be changed. Export-DbaSPConfigure creates a suitable file as its output.

    .PARAMETER Force
        If this switch is enabled, no version check between Source and Destination is performed. By default, the major and minor versions of Source and Destination must match when copying sp_configure settings.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .NOTES
        Tags: SpConfig, Configure, Configuration
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Import-DbaSpConfigure

    .INPUTS
        None You cannot pipe objects to Import-DbaSpConfigure

    .OUTPUTS
        $true if success
        $false if failure

    .EXAMPLE
        PS C:\> Import-DbaSpConfigure -Source sqlserver -Destination sqlcluster

        Imports the sp_configure settings from the source server sqlserver and sets them on the sqlcluster server using Windows Authentication

    .EXAMPLE
        PS C:\> Import-DbaSpConfigure -Source sqlserver -Destination sqlcluster -Force

        Imports the sp_configure settings from the source server sqlserver and sets them on the sqlcluster server using Windows Authentication. Will not do a version check between Source and Destination

    .EXAMPLE
        PS C:\> Import-DbaSpConfigure -Source sqlserver -Destination sqlcluster -SourceSqlCredential $SourceSqlCredential -DestinationSqlCredential $DestinationSqlCredential

        Imports the sp_configure settings from the source server sqlserver and sets them on the sqlcluster server using the SQL credentials stored in the variables $SourceSqlCredential and $DestinationSqlCredential

    .EXAMPLE
        PS C:\> Import-DbaSpConfigure -SqlInstance sqlserver -Path .\spconfig.sql -SqlCredential $SqlCredential

        Imports the sp_configure settings from the file .\spconfig.sql and sets them on the sqlserver server using the SQL credential stored in the variable $SqlCredential

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [Parameter(ParameterSetName = "ServerCopy")]
        [DbaInstanceParameter]$Source,
        [Parameter(ParameterSetName = "ServerCopy")]
        [DbaInstanceParameter]$Destination,
        [Parameter(ParameterSetName = "ServerCopy")]
        [PSCredential]$SourceSqlCredential,
        [Parameter(ParameterSetName = "ServerCopy")]
        [PSCredential]$DestinationSqlCredential,
        [Parameter(ParameterSetName = "FromFile")]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [Parameter(ParameterSetName = "FromFile")]
        [string]$Path,
        [Parameter(ParameterSetName = "FromFile")]
        [PSCredential]$SqlCredential,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {

        if ($Path.length -eq 0) {
            try {
                $sourceserver = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential
            } catch {
                Stop-Function -Message "Failed to process Instance $Source" -ErrorRecord $_ -Target $Source
                return
            }

            if (!(Test-SqlSa -SqlInstance $sourceserver -SqlCredential $SourceSqlCredential)) {
                Stop-Function -Message "Not a sysadmin on $sourceserver. Quitting." -Category PermissionDenied -ErrorRecord $_ -Target $server -Continue
            }

            try {
                $destserver = Connect-SqlInstance -SqlInstance $Destination -SqlCredential $DestinationSqlCredential
            } catch {
                Stop-Function -Message "Failed to process Instance $Destination" -ErrorRecord $_ -Target $Destination
                return
            }

            if (!(Test-SqlSa -SqlInstance $destserver -SqlCredential $DestinationSqlCredential)) {
                Stop-Function -Message "Not a sysadmin on $destserver. Quitting." -Category PermissionDenied -ErrorRecord $_ -Target $server -Continue
            }

            $source = $sourceserver.DomainInstanceName
            $destination = $destserver.DomainInstanceName
        } else {
            try {
                $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failed to process Instance $SqlInstance" -ErrorRecord $_ -Target $SqlInstance -Continue
            }

            if (!(Test-SqlSa -SqlInstance $server -SqlCredential $SqlCredential)) {
                Stop-Function -Message "Not a sysadmin on $server. Quitting." -Category PermissionDenied -ErrorRecord $_ -Target $server -Continue
            }

            if ((Test-Path $Path) -eq $false) {
                Stop-Function -Message "File $Path Not Found" -Category InvalidArgument -Target $Path -Continue
            }
        }

    }
    process {
        if ($Path.length -eq 0) {
            if ($Pscmdlet.ShouldProcess($destination, "Export sp_configure")) {
                $sqlfilename = Export-DbaSpConfigure $sourceserver
            }

            if ($sourceserver.versionMajor -ne $destserver.versionMajor -and $force -eq $false) {
                Write-Message -Level Warning -Message "Source SQL Server major version and Destination SQL Server major version must match for sp_configure migration. Use -Force to override this precaution or check the exported sql file, $sqlfilename, and run manually."
                return
            }

            If ($Pscmdlet.ShouldProcess($destination, "Execute sp_configure")) {
                $sourceserver.Configuration.ShowAdvancedOptions.ConfigValue = $true
                $sourceserver.Configuration.Alter($true)
                $destserver.Configuration.ShowAdvancedOptions.ConfigValue = $true
                $sourceserver.Configuration.Alter($true)

                $destprops = $destserver.Configuration.Properties

                foreach ($sourceprop in $sourceserver.Configuration.Properties) {
                    $displayname = $sourceprop.DisplayName

                    $destprop = $destprops | where-object { $_.Displayname -eq $displayname }
                    if ($null -ne $destprop) {
                        try {
                            $destprop.configvalue = $sourceprop.configvalue
                            $null = $destserver.Query("RECONFIGURE WITH OVERRIDE")
                            Write-Message -Level Output -Message "updated $($destprop.displayname) to $($sourceprop.configvalue)."
                        } catch {
                            Stop-Function -Message "Could not set $($destprop.displayname) to $($sourceprop.configvalue). Feature may not be supported." -ErrorRecord $_ -Continue
                        }
                    }
                }
                try {
                    $destserver.Configuration.Alter()
                } catch {
                    $needsrestart = $true
                }

                $sourceserver.Configuration.ShowAdvancedOptions.ConfigValue = $false
                $sourceserver.Configuration.Alter($true)
                $destserver.Configuration.ShowAdvancedOptions.ConfigValue = $false
                $destserver.Configuration.Alter($true)

                if ($needsrestart -eq $true) {
                    Write-Message -Level Warning -Message "Some configuration options will be updated once SQL Server is restarted."
                } else {
                    Write-Message -Level Output -Message "Configuration option has been updated."
                }
            }

            if ($Pscmdlet.ShouldProcess($destination, "Removing temp file")) {
                Remove-Item $sqlfilename -ErrorAction SilentlyContinue
            }

        } else {
            if ($Pscmdlet.ShouldProcess($destination, "Importing sp_configure from $Path")) {
                $server.Configuration.ShowAdvancedOptions.ConfigValue = $true
                $sql = Get-Content $Path
                foreach ($line in $sql) {
                    try {
                        $null = $server.Query($line)
                        Write-Message -Level Output -Message "Successfully executed $line."
                    } catch {
                        Stop-Function -Message "$line failed. Feature may not be supported." -ErrorRecord $_ -Continue
                    }
                }
                $server.Configuration.ShowAdvancedOptions.ConfigValue = $false
                Write-Message -Level Warning -Message "Some configuration options will be updated once SQL Server is restarted."
            }
        }
    }
    end {
        if ($Path.length -gt 0) {
            $server.ConnectionContext.Disconnect()
        } else {
            $sourceserver.ConnectionContext.Disconnect()
            $destserver.ConnectionContext.Disconnect()
        }

        If ($Pscmdlet.ShouldProcess("console", "Showing finished message")) {
            Write-Message -Level Output -Message "SQL Server configuration options migration finished."
        }

        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Import-SqlSpConfigure
    }
}
tools\dbatools\functions\Import-DbaXESessionTemplate.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Import-DbaXESessionTemplate {
    <#
    .SYNOPSIS
        Imports a new XESession XML Template

    .DESCRIPTION
        Imports a new XESession XML Template either from the dbatools repository or a file you specify.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Name
        The Name of the session to create.

    .PARAMETER Path
        The path to the xml file or files for the session(s).

    .PARAMETER Template
        Specifies the name of one of the templates from the dbatools repository. Press tab to cycle through the provided templates.

    .PARAMETER TargetFilePath
        By default, files will be created in the default xel directory. Use TargetFilePath to change all instances of
        filename = "file.xel" to filename = "$TargetFilePath\file.xel". Only specify the directory, not the file itself.

        This path is relative to the destination directory

    .PARAMETER TargetFileMetadataPath
        By default, files will be created in the default xem directory. Use TargetFileMetadataPath to change all instances of
        filename = "file.xem" to filename = "$TargetFilePath\file.xem". Only specify the directory, not the file itself.

        This path is relative to the destination directory

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Import-DbaXESessionTemplate

    .EXAMPLE
        PS C:\> Import-DbaXESessionTemplate -SqlInstance sql2017 -Template db_query_wait_stats

        Creates a new XESession named db_query_wait_stats from the dbatools repository to the SQL Server sql2017.

    .EXAMPLE
        PS C:\> Import-DbaXESessionTemplate -SqlInstance sql2017 -Template db_query_wait_stats -Name "Query Wait Stats"

        Creates a new XESession named "Query Wait Stats" using the db_query_wait_stats template.

    .EXAMPLE
        PS C:\> Get-DbaXESession -SqlInstance sql2017 -Session 'Database Health 2014' | Remove-DbaXESession
        PS C:\> Import-DbaXESessionTemplate -SqlInstance sql2017 -Template 'Database Health 2014' | Start-DbaXESession

        Removes a session if it exists, then recreates it using a template.

    .EXAMPLE
        PS C:\> Get-DbaXESessionTemplate | Out-GridView -PassThru | Import-DbaXESessionTemplate -SqlInstance sql2017

        Allows you to select a Session template then import to an instance named sql2017.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$Name,
        [parameter(ValueFromPipelineByPropertyName)]
        [Alias("FullName")]
        [string[]]$Path,
        [string[]]$Template,
        [string]$TargetFilePath,
        [string]$TargetFileMetadataPath,
        [switch]$EnableException
    )
    begin {
        $metadata = Import-Clixml "$script:PSModuleRoot\bin\xetemplates-metadata.xml"
    }
    process {
        if ((Test-Bound -ParameterName Path -Not) -and (Test-Bound -ParameterName Template -Not)) {
            Stop-Function -Message "You must specify Path or Template."
        }

        if (($Path.Count -gt 1 -or $Template.Count -gt 1) -and (Test-Bound -ParameterName Template)) {
            Stop-Function -Message "Name cannot be specified with multiple files or templates because the Session will already exist."
        }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 11
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $SqlConn = $server.ConnectionContext.SqlConnectionObject
            $SqlStoreConnection = New-Object Microsoft.SqlServer.Management.Sdk.Sfc.SqlStoreConnection $SqlConn
            $store = New-Object  Microsoft.SqlServer.Management.XEvent.XEStore $SqlStoreConnection

            foreach ($file in $template) {
                $templatepath = "$script:PSModuleRoot\bin\xetemplates\$file.xml"
                if ((Test-Path $templatepath)) {
                    $Path += $templatepath
                } else {
                    Stop-Function -Message "Invalid template ($templatepath does not exist)." -Continue
                }
            }

            foreach ($file in $Path) {

                if ((Test-Bound -Not -ParameterName TargetFilePath)) {
                    Write-Message -Level Verbose -Message "Importing $file to $instance"
                    try {
                        $xml = [xml](Get-Content $file -ErrorAction Stop)
                    } catch {
                        Stop-Function -Message "Failure" -ErrorRecord $_ -Target $file -Continue
                    }
                } else {
                    Write-Message -Level Verbose -Message "TargetFilePath specified, changing all file locations in $file for $instance."
                    Write-Message -Level Verbose -Message "TargetFileMetadataPath specified, changing all metadata file locations in $file for $instance."

                    # Handle whatever people specify
                    $TargetFilePath = $TargetFilePath.TrimEnd("\")
                    $TargetFileMetadataPath = $TargetFileMetadataPath.TrimEnd("\")
                    $TargetFilePath = "$TargetFilePath\"
                    $TargetFileMetadataPath = "$TargetFileMetadataPath\"

                    # Perform replace
                    $xelphrase = 'name="filename" value="'
                    $xemphrase = 'name="metadatafile" value="'

                    try {
                        $basename = (Get-ChildItem $file).Basename
                        $contents = Get-Content $file -ErrorAction Stop
                        $contents = $contents.Replace($xelphrase, "$xelphrase$TargetFilePath")
                        $contents = $contents.Replace($xemphrase, "$xemphrase$TargetFileMetadataPath")
                        $temp = ([System.IO.Path]::GetTempPath()).TrimEnd("").TrimEnd("\")
                        $tempfile = "$temp\$basename"
                        $null = Set-Content -Path $tempfile -Value $contents -Encoding UTF8
                        $xml = [xml](Get-Content $tempfile -ErrorAction Stop)
                        $file = $tempfile
                    } catch {
                        Stop-Function -Message "Failure" -ErrorRecord $_ -Target $file -Continue
                    }

                    Write-Message -Level Verbose -Message "$TargetFilePath does not exist on $server, creating now."
                    try {
                        if (-not (Test-DbaPath -SqlInstance $server -Path $TargetFilePath)) {
                            $null = New-DbaDirectory -SqlInstance $server -Path $TargetFilePath
                        }
                    } catch {
                        Stop-Function -Message "Failure" -ErrorRecord $_ -Target $file -Continue
                    }
                }

                if (-not $xml.event_sessions) {
                    Stop-Function -Message "$file is not a valid XESession template document." -Continue
                }

                if ((Test-Bound -ParameterName Name -not)) {
                    $Name = (Get-ChildItem $file).BaseName
                }

                # This could be done better but not today
                $no2012 = ($metadata | Where-Object Compatibility -gt 2012).Name
                $no2014 = ($metadata | Where-Object Compatibility -gt 2014).Name

                if ($Name -in $no2012 -and $server.VersionMajor -eq 11) {
                    Stop-Function -Message "$Name is not supported in SQL Server 2012 ($server)" -Continue
                }

                if ($Name -in $no2014 -and $server.VersionMajor -eq 12) {
                    Stop-Function -Message "$Name is not supported in SQL Server 2014 ($server)" -Continue
                }

                if ((Get-DbaXESession -SqlInstance $server -Session $Name)) {
                    Stop-Function -Message "$Name already exists on $instance" -Continue
                }

                try {
                    Write-Message -Level Verbose -Message "Importing $file as $name "
                    $session = $store.CreateSessionFromTemplate($Name, $file)
                    $session.Create()
                    if ($file -eq $tempfile) {
                        Remove-Item $tempfile -ErrorAction SilentlyContinue
                    }
                    Get-DbaXESession -SqlInstance $server -Session $session.Name
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target $store -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Install-DbaFirstResponderKit.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Install-DbaFirstResponderKit {
    <#
    .SYNOPSIS
        Installs or updates the First Responder Kit stored procedures.

    .DESCRIPTION
        Downloads, extracts and installs the First Responder Kit stored procedures:
        sp_Blitz, sp_BlitzWho, sp_BlitzFirst, sp_BlitzIndex, sp_BlitzCache and sp_BlitzTrace, etc.

        First Responder Kit links:
        http://FirstResponderKit.org
        https://github.com/BrentOzarULTD/SQL-Server-First-Responder-Kit

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies the database to instal the First Responder Kit stored procedures into

    .PARAMETER Branch
        Specifies an alternate branch of the First Responder Kit to install. (master or dev)

    .PARAMETER LocalFile
        Specifies the path to a local file to install FRK from. This *should* be the zipfile as distributed by the maintainers.
        If this parameter is not specified, the latest version will be downloaded and installed from https://github.com/BrentOzarULTD/SQL-Server-First-Responder-Kit

    .PARAMETER Force
        If this switch is enabled, the FRK will be downloaded from the internet even if previously cached.

    .PARAMETER Confirm
        Prompts to confirm actions

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: BrentOzar, FRK, FirstResponderKit
        Author: Tara Kizer, Brent Ozar Unlimited (https://www.brentozar.com/)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Install-DbaFirstResponderKit

    .EXAMPLE
        PS C:\> Install-DbaFirstResponderKit -SqlInstance server1 -Database master

        Logs into server1 with Windows authentication and then installs the FRK in the master database.

    .EXAMPLE
        PS C:\> Install-DbaFirstResponderKit -SqlInstance server1\instance1 -Database DBA

        Logs into server1\instance1 with Windows authentication and then installs the FRK in the DBA database.

    .EXAMPLE
        PS C:\> Install-DbaFirstResponderKit -SqlInstance server1\instance1 -Database master -SqlCredential $cred

        Logs into server1\instance1 with SQL authentication and then installs the FRK in the master database.

    .EXAMPLE
        PS C:\> Install-DbaFirstResponderKit -SqlInstance sql2016\standardrtm, sql2016\sqlexpress, sql2014

        Logs into sql2016\standardrtm, sql2016\sqlexpress and sql2014 with Windows authentication and then installs the FRK in the master database.

    .EXAMPLE
        PS C:\> $servers = "sql2016\standardrtm", "sql2016\sqlexpress", "sql2014"
        PS C:\> $servers | Install-DbaFirstResponderKit

        Logs into sql2016\standardrtm, sql2016\sqlexpress and sql2014 with Windows authentication and then installs the FRK in the master database.

    .EXAMPLE
        PS C:\> Install-DbaFirstResponderKit -SqlInstance sql2016 -Branch dev

        Installs the dev branch version of the FRK in the master database on sql2016 instance.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [ValidateSet('master', 'dev')]
        [string]$Branch = "master",
        [object]$Database = "master",
        [string]$LocalFile,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $DbatoolsData = Get-DbatoolsConfigValue -FullName "Path.DbatoolsData"

        if (-not $DbatoolsData) {
            $DbatoolsData = ([System.IO.Path]::GetTempPath()).TrimEnd("\")
        }

        $url = "https://github.com/BrentOzarULTD/SQL-Server-First-Responder-Kit/archive/$Branch.zip"

        $temp = ([System.IO.Path]::GetTempPath()).TrimEnd("\")
        $zipfile = "$temp\SQL-Server-First-Responder-Kit-$Branch.zip"
        $zipfolder = "$temp\SQL-Server-First-Responder-Kit-$Branch\"
        $FRKLocation = "FRK_$Branch"
        $LocalCachedCopy = Join-Path -Path $DbatoolsData -ChildPath $FRKLocation
        if ($LocalFile) {
            if (-not(Test-Path $LocalFile)) {
                Stop-Function -Message "$LocalFile doesn't exist"
                return
            }
            if (-not($LocalFile.EndsWith('.zip'))) {
                Stop-Function -Message "$LocalFile should be a zip file"
                return
            }
        }

        if ($Force -or -not(Test-Path -Path $LocalCachedCopy -PathType Container) -or $LocalFile) {
            # Force was passed, or we don't have a local copy, or $LocalFile was passed
            if ($zipfile | Test-Path) {
                Remove-Item -Path $zipfile -ErrorAction SilentlyContinue
            }
            if ($zipfolder | Test-Path) {
                Remove-Item -Path $zipfolder -Recurse -ErrorAction SilentlyContinue
            }

            $null = New-Item -ItemType Directory -Path $zipfolder -ErrorAction SilentlyContinue
            if ($LocalFile) {
                Unblock-File $LocalFile -ErrorAction SilentlyContinue
                Expand-Archive -Path $LocalFile -DestinationPath $zipfolder -Force
            } else {
                Write-Message -Level Verbose -Message "Downloading and unzipping the First Responder Kit zip file."

                try {

                    try {
                        Invoke-TlsWebRequest $url -OutFile $zipfile -ErrorAction Stop -UseBasicParsing
                    } catch {
                        # Try with default proxy and usersettings
                        (New-Object System.Net.WebClient).Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
                        Invoke-TlsWebRequest $url -OutFile $zipfile -ErrorAction Stop -UseBasicParsing
                    }


                    # Unblock if there's a block
                    Unblock-File $zipfile -ErrorAction SilentlyContinue

                    Expand-Archive -Path $zipfile -DestinationPath $zipfolder -Force

                    Remove-Item -Path $zipfile
                } catch {
                    Stop-Function -Message "Couldn't download the First Responder Kit. Download and install manually from https://github.com/BrentOzarULTD/SQL-Server-First-Responder-Kit/archive/$Branch.zip." -ErrorRecord $_
                    return
                }
            }

            ## Copy it into local area
            if (Test-Path -Path $LocalCachedCopy -PathType Container) {
                Remove-Item -Path (Join-Path $LocalCachedCopy '*') -Recurse -ErrorAction SilentlyContinue
            } else {
                $null = New-Item -Path $LocalCachedCopy -ItemType Container
            }
            Copy-Item -Path $zipfolder -Destination $LocalCachedCopy -Recurse
        }
    }


    process {
        if (Test-FunctionInterrupt) {
            return
        }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure." -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            Write-Message -Level Verbose -Message "Starting installing/updating the First Responder Kit stored procedures in $database on $instance."
            $allprocedures_query = "select name from sys.procedures where is_ms_shipped = 0"
            $allprocedures = ($server.Query($allprocedures_query, $Database)).Name
            # Install/Update each FRK stored procedure
            foreach ($script in (Get-ChildItem $LocalCachedCopy -Recurse -Filter "sp_*.sql")) {
                $scriptname = $script.Name
                $scriptError = $false
                if ($scriptname -ne "sp_BlitzRS.sql") {

                    if ($scriptname -eq "sp_BlitzQueryStore.sql") {
                        if ($server.VersionMajor -lt 13) { continue }
                    }
                    if ($Pscmdlet.ShouldProcess($instance, "installing/updating $scriptname in $database.")) {
                        try {
                            Invoke-DbaQuery -SqlInstance $server -Database $Database -File $script.FullName -EnableException -Verbose:$false
                        } catch {
                            Write-Message -Level Warning -Message "Could not execute at least one portion of $scriptname in $Database on $instance." -ErrorRecord $_
                            $scriptError = $true
                        }
                        $baseres = @{
                            ComputerName = $server.ComputerName
                            InstanceName = $server.ServiceName
                            SqlInstance  = $server.DomainInstanceName
                            Database     = $Database
                            Name         = $script.BaseName
                        }
                        if ($scriptError) {
                            $baseres['Status'] = 'Error'
                        } elseif ($script.BaseName -in $allprocedures) {
                            $baseres['Status'] = 'Updated'
                        } else {
                            $baseres['Status'] = 'Installed'
                        }
                        [PSCustomObject]$baseres
                    }
                }
            }
            Write-Message -Level Verbose -Message "Finished installing/updating the First Responder Kit stored procedures in $database on $instance."
        }
    }
}
tools\dbatools\functions\Install-DbaMaintenanceSolution.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Install-DbaMaintenanceSolution {
    <#
    .SYNOPSIS
        Download and Install SQL Server Maintenance Solution created by Ola Hallengren (https://ola.hallengren.com)

    .DESCRIPTION
        This script will download and install the latest version of SQL Server Maintenance Solution created by Ola Hallengren

    .PARAMETER SqlInstance
        The target SQL Server instance onto which the Maintenance Solution will be installed.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database where Ola Hallengren's solution will be installed. Defaults to master.

    .PARAMETER BackupLocation
        Location of the backup root directory. If this is not supplied, the default backup directory will be used.

    .PARAMETER CleanupTime
        Time in hours, after which backup files are deleted.

    .PARAMETER OutputFileDirectory
        Specify the output file directory where the Maintenance Solution will write to.

    .PARAMETER ReplaceExisting
        If this switch is enabled, objects already present in the target database will be dropped and recreated.

    .PARAMETER LogToTable
        If this switch is enabled, the Maintenance Solution will be configured to log commands to a table.

    .PARAMETER Solution
        Specifies which portion of the Maintenance solution to install. Valid values are All (full solution), Backup, IntegrityCheck and IndexOptimize.

    .PARAMETER InstallJobs
        If this switch is enabled, the corresponding SQL Agent Jobs will be created.

    .PARAMETER LocalFile
        Specifies the path to a local file to install Ola's solution from. This *should* be the zipfile as distributed by the maintainers.
        If this parameter is not specified, the latest version will be downloaded and installed from https://github.com/olahallengren/sql-server-maintenance-solution

    .PARAMETER Force
        If this switch is enabled, the Ola's solution will be downloaded from the internet even if previously cached.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Ola, Maintenance
        Author: Viorel Ciucu, cviorel.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        http://dbatools.io/Install-DbaMaintenanceSolution

    .EXAMPLE
        PS C:\> Install-DbaMaintenanceSolution -SqlInstance RES14224 -Database DBA -CleanupTime 72

        Installs Ola Hallengren's Solution objects on RES14224 in the DBA database.
        Backups will default to the default Backup Directory.
        If the Maintenance Solution already exists, the script will be halted.

    .EXAMPLE
        PS C:\> Install-DbaMaintenanceSolution -SqlInstance RES14224 -Database DBA -BackupLocation "Z:\SQLBackup" -CleanupTime 72

        This will create the Ola Hallengren's Solution objects. Existing objects are not affected in any way.

    .EXAMPLE
        PS C:\> Install-DbaMaintenanceSolution -SqlInstance RES14224 -Database DBA -BackupLocation "Z:\SQLBackup" -CleanupTime 72 -ReplaceExisting

        This will drop and then recreate the Ola Hallengren's Solution objects
        The cleanup script will drop and recreate:
        - TABLE [dbo].[CommandLog]
        - STORED PROCEDURE [dbo].[CommandExecute]
        - STORED PROCEDURE [dbo].[DatabaseBackup]
        - STORED PROCEDURE [dbo].[DatabaseIntegrityCheck]
        - STORED PROCEDURE [dbo].[IndexOptimize]

        The following SQL Agent jobs will be deleted:
        - 'Output File Cleanup'
        - 'IndexOptimize - USER_DATABASES'
        - 'sp_delete_backuphistory'
        - 'DatabaseBackup - USER_DATABASES - LOG'
        - 'DatabaseBackup - SYSTEM_DATABASES - FULL'
        - 'DatabaseBackup - USER_DATABASES - FULL'
        - 'sp_purge_jobhistory'
        - 'DatabaseIntegrityCheck - SYSTEM_DATABASES'
        - 'CommandLog Cleanup'
        - 'DatabaseIntegrityCheck - USER_DATABASES'
        - 'DatabaseBackup - USER_DATABASES - DIFF'

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Medium")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification = "Internal functions are ignored")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object]$Database = "master",
        [string]$BackupLocation,
        [int]$CleanupTime,
        [string]$OutputFileDirectory,
        [switch]$ReplaceExisting,
        [switch]$LogToTable,
        [ValidateSet('All', 'Backup', 'IntegrityCheck', 'IndexOptimize')]
        [string]$Solution = 'All',
        [switch]$InstallJobs,
        [string]$LocalFile,
        [switch]$Force,
        [switch]$EnableException
    )

    begin {
        if ($InstallJobs -and $Solution -ne 'All') {
            Stop-Function -Message "Jobs can only be created for all solutions. To create SQL Agent jobs you need to use '-Solution All' (or not specify the Solution and let it default to All) and '-InstallJobs'."
            return
        }

        if ((Test-Bound -ParameterName CleanupTime) -and -not $InstallJobs) {
            Stop-Function -Message "CleanupTime is only useful when installing jobs. To install jobs, please use '-InstallJobs' in addition to CleanupTime."
            return
        }

        if ($ReplaceExisting -eq $true) {
            Write-Message -Level Verbose -Message "If Ola Hallengren's scripts are found, we will drop and recreate them!"
        }

        $DbatoolsData = Get-DbatoolsConfigValue -FullName "Path.DbatoolsData"

        $url = "https://github.com/olahallengren/sql-server-maintenance-solution/archive/master.zip"

        $temp = ([System.IO.Path]::GetTempPath()).TrimEnd("\")
        $zipfile = "$temp\ola-sql-server-maintenance-solution.zip"
        $zipfolder = "$temp\ola-sql-server-maintenance-solution\"
        $OLALocation = "OLA_SQL_MAINT_master"
        $LocalCachedCopy = Join-Path -Path $DbatoolsData -ChildPath $OLALocation
        if ($LocalFile) {
            if (-not (Test-Path $LocalFile)) {
                Stop-Function -Message "$LocalFile doesn't exist"
                return
            }
            if (-not ($LocalFile.EndsWith('.zip'))) {
                Stop-Function -Message "$LocalFile should be a zip file"
                return
            }
        }

        if ($Force -or -not (Test-Path -Path $LocalCachedCopy -PathType Container) -or $LocalFile) {
            # Force was passed, or we don't have a local copy, or $LocalFile was passed
            if ($zipfile | Test-Path) {
                Remove-Item -Path $zipfile -ErrorAction SilentlyContinue
            }
            if ($zipfolder | Test-Path) {
                Remove-Item -Path $zipfolder -Recurse -ErrorAction SilentlyContinue
            }

            $null = New-Item -ItemType Directory -Path $zipfolder -ErrorAction SilentlyContinue
            if ($LocalFile) {
                Unblock-File $LocalFile -ErrorAction SilentlyContinue
                Expand-Archive -Path $LocalFile -DestinationPath $zipfolder -Force
            } else {
                Write-Message -Level Verbose -Message "Downloading and unzipping Ola's maintenance solution zip file."

                try {
                    try {
                        Invoke-TlsWebRequest $url -OutFile $zipfile -ErrorAction Stop -UseBasicParsing
                    } catch {
                        # Try with default proxy and usersettings
                        (New-Object System.Net.WebClient).Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
                        Invoke-TlsWebRequest $url -OutFile $zipfile -ErrorAction Stop -UseBasicParsing
                    }

                    # Unblock if there's a block
                    Unblock-File $zipfile -ErrorAction SilentlyContinue

                    Expand-Archive -Path $zipfile -DestinationPath $zipfolder -Force

                    Remove-Item -Path $zipfile
                } catch {
                    Stop-Function -Message "Couldn't download Ola's maintenance solution. Download and install manually from https://github.com/olahallengren/sql-server-maintenance-solution/archive/master.zip." -ErrorRecord $_
                    return
                }
            }

            ## Copy it into local area
            if (Test-Path -Path $LocalCachedCopy -PathType Container) {
                Remove-Item -Path (Join-Path $LocalCachedCopy '*') -Recurse -ErrorAction SilentlyContinue
            } else {
                $null = New-Item -Path $LocalCachedCopy -ItemType Container
            }
            Copy-Item -Path $zipfolder -Destination $LocalCachedCopy -Recurse
        }

        function Get-DbaOlaWithParameters($listOfFiles) {

            $fileContents = @{ }
            foreach ($file in $listOfFiles) {
                $fileContents[$file] = Get-Content -Path $file -Raw
            }

            foreach ($file in $($fileContents.Keys)) {
                # In which database we install
                if ($Database -ne 'master') {
                    $findDB = 'USE [master]'
                    $replaceDB = 'USE [' + $Database + ']'
                    $fileContents[$file] = $fileContents[$file].Replace($findDB, $replaceDB)
                }

                # Backup location
                if ($BackupLocation) {
                    $findBKP = 'SET @BackupDirectory     = NULL'
                    $replaceBKP = 'SET @BackupDirectory     = N''' + $BackupLocation + ''''
                    $fileContents[$file] = $fileContents[$file].Replace($findBKP, $replaceBKP)
                }

                # CleanupTime
                if ($CleanupTime -ne 0) {
                    $findCleanupTime = 'SET @CleanupTime         = NULL'
                    $replaceCleanupTime = 'SET @CleanupTime         = ' + $CleanupTime
                    $fileContents[$file] = $fileContents[$file].Replace($findCleanupTime, $replaceCleanupTime)
                }

                # OutputFileDirectory
                if (-not $OutputFileDirectory) {
                    $findOutputFileDirectory = 'SET @OutputFileDirectory = NULL'
                    $replaceOutputFileDirectory = 'SET @OutputFileDirectory = N''' + $OutputFileDirectory + ''''
                    $fileContents[$file] = $fileContents[$file].Replace($findOutputFileDirectory, $replaceOutputFileDirectory)
                }

                # LogToTable
                if (!$LogToTable) {
                    $findLogToTable = "SET @LogToTable          = 'Y'"
                    $replaceLogToTable = "SET @LogToTable          = 'N'"
                    $fileContents[$file] = $fileContents[$file].Replace($findLogToTable, $replaceLogToTable)
                }

                # Create Jobs
                if (-not $InstallJobs) {
                    $findCreateJobs = "SET @CreateJobs          = 'Y'"
                    $replaceCreateJobs = "SET @CreateJobs          = 'N'"
                    $fileContents[$file] = $fileContents[$file].Replace($findCreateJobs, $replaceCreateJobs)
                }
            }
            return $fileContents
        }
    }

    process {
        if (Test-FunctionInterrupt) {
            return
        }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -NonPooled
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ((Test-Bound -ParameterName ReplaceExisting -Not)) {
                $procs = Get-DbaModule -SqlInstance $server -Database $Database | Where-Object Name -in 'CommandExecute', 'DatabaseBackup', 'DatabaseIntegrityCheck', 'IndexOptimize'
                $table = Get-DbaDbTable -SqlInstance $server -Database $Database -Table CommandLog -IncludeSystemDBs | Where-Object Database -eq $Database

                if ($null -ne $procs -or $null -ne $table) {
                    Stop-Function -Message "The Maintenance Solution already exists in $Database on $instance. Use -ReplaceExisting to automatically drop and recreate."
                    return
                }
            }

            if ((Test-Bound -ParameterName BackupLocation -Not)) {
                $BackupLocation = (Get-DbaDefaultPath -SqlInstance $server).Backup
            }

            Write-Message -Level Output -Message "Ola Hallengren's solution will be installed on database $Database."

            $db = $server.Databases[$Database]

            # Required
            $required = @('CommandExecute.sql')

            if ($LogToTable) {
                $required += 'CommandLog.sql'
            }

            if ($Solution -match 'Backup') {
                $required += 'DatabaseBackup.sql'
            }

            if ($Solution -match 'IntegrityCheck') {
                $required += 'DatabaseIntegrityCheck.sql'
            }

            if ($Solution -match 'IndexOptimize') {
                $required += 'IndexOptimize.sql'
            }

            if ($Solution -match 'All') {
                $required += 'MaintenanceSolution.sql'
            }

            $temp = ([System.IO.Path]::GetTempPath()).TrimEnd("\")
            $zipfile = "$temp\ola.zip"


            $listOfFiles = Get-ChildItem -Filter "*.sql" -Path $LocalCachedCopy -Recurse | Select-Object -ExpandProperty FullName

            $fileContents = Get-DbaOlaWithParameters -listOfFiles $listOfFiles

            $CleanupQuery = $null
            if ($ReplaceExisting) {
                [string]$CleanupQuery = $("
                            IF OBJECT_ID('[dbo].[CommandLog]', 'U') IS NOT NULL
                                DROP TABLE [dbo].[CommandLog];
                            IF OBJECT_ID('[dbo].[CommandExecute]', 'P') IS NOT NULL
                                DROP PROCEDURE [dbo].[CommandExecute];
                            IF OBJECT_ID('[dbo].[DatabaseBackup]', 'P') IS NOT NULL
                                DROP PROCEDURE [dbo].[DatabaseBackup];
                            IF OBJECT_ID('[dbo].[DatabaseIntegrityCheck]', 'P') IS NOT NULL
                                DROP PROCEDURE [dbo].[DatabaseIntegrityCheck];
                            IF OBJECT_ID('[dbo].[IndexOptimize]', 'P') IS NOT NULL
                                DROP PROCEDURE [dbo].[IndexOptimize];
                            ")

                Write-Message -Level Output -Message "Dropping objects created by Ola's Maintenance Solution"
                $null = $db.Query($CleanupQuery)

                # Remove Ola's Jobs
                if ($InstallJobs -and $ReplaceExisting) {
                    Write-Message -Level Output -Message "Removing existing SQL Agent Jobs created by Ola's Maintenance Solution."
                    $jobs = Get-DbaAgentJob -SqlInstance $server | Where-Object Description -match "hallengren"
                    if ($jobs) {
                        $jobs | ForEach-Object { Remove-DbaAgentJob -SqlInstance $instance -Job $_.name }
                    }
                }
            }

            try {
                Write-Message -Level Output -Message "Installing on server $instance, database $Database."

                foreach ($file in $fileContents.Keys) {
                    $shortFileName = Split-Path $file -Leaf
                    if ($required.Contains($shortFileName)) {
                        Write-Message -Level Output -Message "Installing $shortFileName."
                        $sql = $fileContents[$file]
                        try {
                            foreach ($query in ($sql -Split "\nGO\b")) {
                                $null = $db.Query($query)
                            }
                        } catch {
                            Stop-Function -Message "Could not execute $shortFileName in $Database on $instance." -ErrorRecord $_ -Target $db -Continue
                        }
                    }
                }
            } catch {
                Stop-Function -Message "Could not execute $shortFileName in $Database on $instance." -ErrorRecord $_ -Target $db -Continue
            }
        }
        # Only here due to need for non-pooled connection in this command
        try {
            $server.ConnectionContext.Disconnect()
        } catch {
            # here to avoid an empty catch
            $null = 1
        }

        Write-Message -Level Output -Message "Installation complete."
    }
}
tools\dbatools\functions\Install-DbaSqlWatch.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Install-DbaSqlWatch {
    <#
    .SYNOPSIS
        Installs or updates SqlWatch.

    .DESCRIPTION
        Downloads, extracts and installs or updates SqlWatch.
        https://sqlwatch.io/

    .PARAMETER SqlInstance
        SQL Server name or SMO object representing the SQL Server to connect to.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies the database to install SqlWatch into. Defaults to SQLWATCH.

    .PARAMETER LocalFile
        Specifies the path to a local file to install SqlWatch from. This *should* be the zipfile as distributed by the maintainers.
        If this parameter is not specified, the latest version will be downloaded and installed from https://github.com/marcingminski/sqlwatch

    .PARAMETER Force
        If this switch is enabled, SqlWatch will be downloaded from the internet even if previously cached.

    .PARAMETER Confirm
        Prompts to confirm actions

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: SqlWatch
        Author: Ken K (github.com/koglerk)
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Install-DbaSqlWatch

    .EXAMPLE
        Install-DbaSqlWatch -SqlInstance server1

        Logs into server1 with Windows authentication and then installs SqlWatch in the SQLWATCH database.

    .EXAMPLE
        Install-DbaSqlWatch -SqlInstance server1\instance1 -Database DBA

        Logs into server1\instance1 with Windows authentication and then installs SqlWatch in the DBA database.

    .EXAMPLE
        Install-DbaSqlWatch -SqlInstance server1\instance1 -Database DBA -SqlCredential $cred

        Logs into server1\instance1 with SQL authentication and then installs SqlWatch in the DBA database.

    .EXAMPLE
        Install-DbaSqlWatch -SqlInstance sql2016\standardrtm, sql2016\sqlexpress, sql2014

        Logs into sql2016\standardrtm, sql2016\sqlexpress and sql2014 with Windows authentication and then installs SqlWatch in the SQLWATCH database.

    .EXAMPLE
        $servers = "sql2016\standardrtm", "sql2016\sqlexpress", "sql2014"
        $servers | Install-DbaSqlWatch

        Logs into sql2016\standardrtm, sql2016\sqlexpress and sql2014 with Windows authentication and then installs SqlWatch in the SQLWATCH database.
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$Database = "SQLWATCH",
        [string]$LocalFile,
        [switch]$Force,
        [switch]$EnableException
    )
    begin {
        $stepCounter = 0

        $DbatoolsData = Get-DbatoolsConfigValue -FullName "Path.DbatoolsData"
        $tempFolder = ([System.IO.Path]::GetTempPath()).TrimEnd("\")
        $zipfile = "$tempFolder\SqlWatch.zip"

        if (-not $LocalFile) {
            if ($PSCmdlet.ShouldProcess($env:computername, "Downloading latest release from GitHub")) {
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Downloading latest release from GitHub"
                # query the releases to find the latest, check and see if its cached
                $ReleasesUrl = "https://api.github.com/repos/marcingminski/sqlwatch/releases"
                $DownloadBase = "https://github.com/marcingminski/sqlwatch/releases/download/"

                Write-Message -Level Verbose -Message "Checking GitHub for the latest release."
                $LatestReleaseUrl = (Invoke-TlsWebRequest -UseBasicParsing -Uri $ReleasesUrl | ConvertFrom-Json)[0].assets[0].browser_download_url

                Write-Message -Level VeryVerbose -Message "Latest release is available at $LatestReleaseUrl"
                $LocallyCachedZip = Join-Path -Path $DbatoolsData -ChildPath $($LatestReleaseUrl -replace $DownloadBase, '');

                # if local cached copy exists, use it, otherwise download a new one
                if (-not $Force) {

                    # download from github
                    Write-Message -Level Verbose "Downloading $LatestReleaseUrl"
                    try {
                        Invoke-TlsWebRequest $LatestReleaseUrl -OutFile $zipfile -ErrorAction Stop -UseBasicParsing
                    } catch {
                        #try with default proxy and usersettings
                        (New-Object System.Net.WebClient).Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
                        Invoke-TlsWebRequest $LatestReleaseUrl -OutFile $zipfile -ErrorAction Stop -UseBasicParsing
                    }

                    # copy the file from temp to local cache
                    Write-Message -Level Verbose "Copying $zipfile to $LocallyCachedZip"
                    try {
                        New-Item -Path $LocallyCachedZip -ItemType File -Force | Out-Null
                        Copy-Item -Path $zipfile -Destination $LocallyCachedZip -Force
                    } catch {
                        # should we stop the function if the file copy fails?
                        # here to avoid an empty catch
                        $null = 1
                    }
                }
            }
        } else {

            # $LocalFile was passed, so use it
            if ($PSCmdlet.ShouldProcess($env:computername, "Copying local file to temp directory")) {

                if ($LocalFile.EndsWith("zip")) {
                    $LocallyCachedZip = $zipfile
                    Copy-Item -Path $LocalFile -Destination $LocallyCachedZip -Force
                } else {
                    $LocallyCachedZip = (Join-Path -path $tempFolder -childpath "SqlWatch.zip")
                    Copy-Item -Path $LocalFile -Destination $LocallyCachedZip -Force
                }
            }
        }

        # expand the zip file
        if ($PSCmdlet.ShouldProcess($env:computername, "Unpacking zipfile")) {
            Write-Message -Level VeryVerbose "Unblocking $LocallyCachedZip"
            Unblock-File $LocallyCachedZip -ErrorAction SilentlyContinue
            $LocalCacheFolder = Split-Path $LocallyCachedZip -Parent

            Write-Message -Level Verbose "Extracting $LocallyCachedZip to $LocalCacheFolder"
            if (Get-Command -ErrorAction SilentlyContinue -Name "Expand-Archive") {
                try {
                    Expand-Archive -Path $LocallyCachedZip -DestinationPath $LocalCacheFolder -Force
                } catch {
                    Stop-Function -Message "Unable to extract $LocallyCachedZip. Archive may not be valid." -ErrorRecord $_
                    return
                }
            } else {
                # Keep it backwards compatible
                $shell = New-Object -ComObject Shell.Application
                $zipPackage = $shell.NameSpace($LocallyCachedZip)
                $destinationFolder = $shell.NameSpace($LocalCacheFolder)
                Get-ChildItem "$LocalCacheFolder\SqlWatch.zip" | Remove-Item
                $destinationFolder.CopyHere($zipPackage.Items())
            }

            Write-Message -Level VeryVerbose "Deleting $LocallyCachedZip"
            Remove-Item -Path $LocallyCachedZip
        }
    }
    process {
        if (Test-FunctionInterrupt) {
            return
        }

        foreach ($instance in $SqlInstance) {
            if ($PSCmdlet.ShouldProcess($instance, "Installing SqlWatch on $Database")) {
                try {
                    $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
                } catch {
                    Stop-Function -Message "Failure." -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                }

                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Starting installing/updating SqlWatch in $database on $instance"


                try {
                    # create a publish profile and publish DACPAC
                    $DacPacPath = Get-ChildItem -Filter "SqlWatch.dacpac" -Path $LocalCacheFolder -Recurse | Select-Object -ExpandProperty FullName
                    $PublishOptions = @{
                        RegisterDataTierApplication = $true
                    }

                    Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Publishing SqlWatch dacpac to $database on $instance"
                    $DacProfile = New-DbaDacProfile -SqlInstance $server -Database $Database -Path $LocalCacheFolder -PublishOptions $PublishOptions | Select-Object -ExpandProperty FileName
                    $PublishResults = Publish-DbaDacPackage -SqlInstance $server -Database $Database -Path $DacPacPath -PublishXml $DacProfile

                    # parse results
                    $parens = Select-String -InputObject $PublishResults.Result -Pattern "\(([^\)]+)\)" -AllMatches
                    if ($parens.matches) {
                        $ExtractedResult = $parens.matches | Select-Object -Last 1
                    }

                    [PSCustomObject]@{
                        ComputerName = $PublishResults.ComputerName
                        InstanceName = $PublishResults.InstanceName
                        SqlInstance  = $PublishResults.SqlInstance
                        Database     = $PublishResults.Database
                        Status       = $ExtractedResult
                    }
                } catch {
                    Stop-Function -Message "DACPAC failed to publish to $database on $instance." -ErrorRecord $_ -Target $instance -Continue
                }

                Write-Message -Level Verbose -Message "Finished installing/updating SqlWatch in $database on $instance."
            }
        }
    }
}
tools\dbatools\functions\Install-DbaWatchUpdate.ps1
function Install-DbaWatchUpdate {
    <#
    .SYNOPSIS
        Adds the scheduled task to support Watch-DbaUpdate.

    .DESCRIPTION
        Adds the scheduled task to support Watch-DbaUpdate.

    .PARAMETER TaskName
        Provide custom name for the Scheduled Task

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Module
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Install-DbaWatchUpdate

    .EXAMPLE
        PS C:\> Install-DbaWatchUpdate

        Adds the scheduled task needed by Watch-DbaUpdate

    .EXAMPLE
        PS C:\> Install-DbaWatchUpdate -TaskName MyScheduledTask

        Will create the scheduled task as the name MyScheduledTask

    #>
    [cmdletbinding(SupportsShouldProcess)]
    param(
        [string]$TaskName = 'dbatools version check',
        [switch]$EnableException
    )
    process {
        if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME, "Validate Version of OS") ) {
            if (([Environment]::OSVersion).Version.Major -lt 10) {
                Stop-Function -Message "This command only supports Windows 10 and above"
            }
        }
        $script = {
            try {
                # create a task, check every 3 hours
                $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -NoLogo -NonInteractive -WindowStyle Hidden Watch-DbaUpdate'
                $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RepetitionInterval (New-TimeSpan -Hours 1)
                $principal = New-ScheduledTaskPrincipal -LogonType S4U -UserId (whoami)
                $settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit ([timespan]::Zero) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RunOnlyIfNetworkAvailable -DontStopOnIdleEnd
                #Variable $Task marked as unused by PSScriptAnalyzer replaced with $null for catching output
                $null = Register-ScheduledTask -Principal $principal -TaskName 'dbatools version check' -Action $action -Trigger $trigger -Settings $settings -ErrorAction Stop
            } catch {
                # keep moving
                # here to avoid an empty catch
                $null = 1
            }
        }

        if ($null -eq (Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue)) {
            # Needs admin creds to setup the kind of PowerShell window that doesn't appear for a millisecond
            # which is a millisecond too long
            if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME, "Validate running in RunAs mode")) {
                if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
                    Write-Message -Level Warning -Message "This command has to run using RunAs mode (privileged) to create the Scheduled Task. This will only happen once."
                    if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME, "Starting process in RunAs mode") ) {
                        Start-Process powershell -Verb runAs -ArgumentList Install-DbaWatchUpdate -Wait
                    }
                }

            }
            if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME, "Creating scheduled task $TaskName")) {
                try {
                    Invoke-Command -ScriptBlock $script -ErrorAction Stop

                    if ((Get-Location).Path -ne "$env:WINDIR\system32") {
                        Write-Message -Level Output -Message "Scheduled Task [$TaskName] created! A notification should appear momentarily. Here's something cute to look at in the interim."
                        Show-Notification -Title "dbatools wants you" -Text "come hang out at dbatools.io/slack"
                    }
                } catch {
                    Stop-Function -Message "Could not create scheduled task $TaskName" -Target $env:COMPUTERNAME -ErrorRecord $_
                }
            }
            if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME, "Checking scheduled task was created")) {
                # double check
                if ($null -eq (Get-ScheduledTask -TaskName "dbatools version check" -ErrorAction SilentlyContinue)) {
                    Write-Message -Level Warning -Message "Scheduled Task was not created."
                }
            }
        } else {
            Write-Message -Level Output -Message "Scheduled Task $TaskName is already installed on this machine."
        }
    }
}
tools\dbatools\functions\Install-DbaWhoIsActive.ps1
function Install-DbaWhoIsActive {
    <#
    .SYNOPSIS
        Automatically installs or updates sp_WhoisActive by Adam Machanic.

    .DESCRIPTION
        This command downloads, extracts and installs sp_WhoisActive with Adam's permission. To read more about sp_WhoisActive, please visit http://whoisactive.com and http://sqlblog.com/blogs/adam_machanic/archive/tags/who+is+active/default.aspx

        Please consider donating to Adam if you find this stored procedure helpful: http://tinyurl.com/WhoIsActiveDonate

        Note that you will be prompted a bunch of times to confirm an action.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server version must be SQL Server version 2005 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database to install sp_WhoisActive into. This parameter is mandatory when executing this command unattended.

    .PARAMETER LocalFile
        Specifies the path to a local file to install sp_WhoisActive from. This can be either the zipfile as distributed by the website or the expanded SQL script. If this parameter is not specified, the latest version will be downloaded and installed from https://whoisactive.com/

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER Force
        If this switch is enabled, the sp_WhoisActive will be downloaded from the internet even if previously cached.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: AdamMechanic, WhoIsActive, SpWhoIsActive
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Install-DbaWhoIsActive

    .EXAMPLE
        PS C:\> Install-DbaWhoIsActive -SqlInstance sqlserver2014a -Database master

        Downloads sp_WhoisActive from the internet and installs to sqlserver2014a's master database. Connects to SQL Server using Windows Authentication.

    .EXAMPLE
        PS C:\> Install-DbaWhoIsActive -SqlInstance sqlserver2014a -SqlCredential $cred

        Pops up a dialog box asking which database on sqlserver2014a you want to install the procedure into. Connects to SQL Server using SQL Authentication.

    .EXAMPLE
        PS C:\> Install-DbaWhoIsActive -SqlInstance sqlserver2014a -Database master -LocalFile c:\SQLAdmin\whoisactive_install.sql

        Installs sp_WhoisActive to sqlserver2014a's master database from the local file whoisactive_install.sql

    .EXAMPLE
        PS C:\> $instances = Get-DbaCmsRegServer sqlserver
        PS C:\> Install-DbaWhoIsActive -SqlInstance $instances -Database master

        Installs sp_WhoisActive to all servers within CMS
    #>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [parameter(Mandatory, ValueFromPipeline, Position = 0)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PsCredential]$SqlCredential,
        [ValidateScript( { Test-Path -Path $_ -PathType Leaf })]
        [string]$LocalFile,
        [object]$Database,
        [switch][Alias('Silent')]
        $EnableException,
        [switch]$Force
    )

    begin {
        $DbatoolsData = Get-DbatoolsConfigValue -FullName "Path.DbatoolsData"
        $temp = ([System.IO.Path]::GetTempPath()).TrimEnd("\")
        $zipfile = "$temp\spwhoisactive.zip"

        if ($LocalFile -eq $null -or $LocalFile.Length -eq 0) {
            $baseUrl = "http://whoisactive.com/downloads"
            $latest = ((Invoke-TlsWebRequest -UseBasicParsing -uri http://whoisactive.com/downloads).Links | where-object { $PSItem.href -match "who_is_active" } | Select-Object href -First 1).href
            $LocalCachedCopy = Join-Path -Path $DbatoolsData -ChildPath $latest;

            if ((Test-Path -Path $LocalCachedCopy -PathType Leaf) -and (-not $Force)) {
                Write-Message -Level Verbose -Message "Locally-cached copy exists, skipping download."
                if ($PSCmdlet.ShouldProcess($env:computername, "Copying sp_WhoisActive from local cache for installation")) {
                    Copy-Item -Path $LocalCachedCopy -Destination $zipfile;
                }
            } else {
                if ($PSCmdlet.ShouldProcess($env:computername, "Downloading sp_WhoisActive")) {
                    try {
                        Write-Message -Level Verbose -Message "Downloading sp_WhoisActive zip file, unzipping and installing."
                        $url = $baseUrl + "/" + $latest
                        try {
                            Invoke-TlsWebRequest $url -OutFile $zipfile -ErrorAction Stop -UseBasicParsing
                            Copy-Item -Path $zipfile -Destination $LocalCachedCopy
                        } catch {
                            #try with default proxy and usersettings
                            (New-Object System.Net.WebClient).Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
                            Invoke-TlsWebRequest $url -OutFile $zipfile -ErrorAction Stop -UseBasicParsing
                        }
                    } catch {
                        Stop-Function -Message "Couldn't download sp_WhoisActive. Please download and install manually from $url." -ErrorRecord $_
                        return
                    }
                }
            }
        } else {
            # Look local
            if ($PSCmdlet.ShouldProcess($env:computername, "Copying local file to temp directory")) {

                if ($LocalFile.EndsWith("zip")) {
                    Copy-Item -Path $LocalFile -Destination $zipfile -Force
                } else {
                    Copy-Item -Path $LocalFile -Destination (Join-Path -path $temp -childpath "whoisactivelocal.sql")
                }
            }
        }
        if ($LocalFile -eq $null -or $LocalFile.Length -eq 0 -or $LocalFile.EndsWith("zip")) {
            # Unpack
            # Unblock if there's a block
            if ($PSCmdlet.ShouldProcess($env:computername, "Unpacking zipfile")) {

                Unblock-File $zipfile -ErrorAction SilentlyContinue

                if (Get-Command -ErrorAction SilentlyContinue -Name "Expand-Archive") {
                    try {
                        Expand-Archive -Path $zipfile -DestinationPath $temp -Force
                    } catch {
                        Stop-Function -Message "Unable to extract $zipfile. Archive may not be valid." -ErrorRecord $_
                        return
                    }
                } else {
                    # Keep it backwards compatible
                    $shell = New-Object -ComObject Shell.Application
                    $zipPackage = $shell.NameSpace($zipfile)
                    $destinationFolder = $shell.NameSpace($temp)
                    Get-ChildItem "$temp\who*active*.sql" | Remove-Item
                    $destinationFolder.CopyHere($zipPackage.Items())
                }
                Remove-Item -Path $zipfile
            }
            $sqlfile = (Get-ChildItem "$temp\who*active*.sql" -ErrorAction SilentlyContinue | Select-Object -First 1).FullName
        } else {
            $sqlfile = $LocalFile
        }

        if ($PSCmdlet.ShouldProcess($env:computername, "Reading SQL file into memory")) {
            Write-Message -Level Verbose -Message "Using $sqlfile."

            $sql = [IO.File]::ReadAllText($sqlfile)
            $sql = $sql -replace 'USE master', ''
            $batches = $sql -split "GO\r\n"

            $matchString = 'Who Is Active? v'

            If ($sql -like "*$matchString*") {
                $posStart = $sql.IndexOf("$matchString")
                $PosEnd = $sql.IndexOf(")", $PosStart)
                $versionWhoIsActive = $sql.Substring($posStart + $matchString.Length, $posEnd - ($posStart + $matchString.Length) + 1).TrimEnd()
            } Else {
                $versionWhoIsActive = ''
            }
        }
    }

    process {
        if (Test-FunctionInterrupt) { return }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if (-not $Database) {
                if ($PSCmdlet.ShouldProcess($instance, "Prompting with GUI list of databases")) {
                    $Database = Show-DbaDbList -SqlInstance $server -Title "Install sp_WhoisActive" -Header "To deploy sp_WhoisActive, select a database or hit cancel to quit." -DefaultDb "master"

                    if (-not $Database) {
                        Stop-Function -Message "You must select a database to install the procedure." -Target $Database
                        return
                    }

                    if ($Database -ne 'master') {
                        Write-Message -Level Warning -Message "You have selected a database other than master. When you run Invoke-DbaWhoIsActive in the future, you must specify -Database $Database."
                    }
                }
            }
            if ($PSCmdlet.ShouldProcess($instance, "Installing sp_WhoisActive")) {
                try {
                    $ProcedureExists_Query = "select COUNT(*) [proc_count] from sys.procedures where is_ms_shipped = 0 and name like '%sp_WhoisActive%'"

                    if ($server.Databases[$Database]) {
                        $ProcedureExists = ($server.Query($ProcedureExists_Query, $Database)).proc_count
                        foreach ($batch in $batches) {
                            try {
                                $null = $server.databases[$Database].ExecuteNonQuery($batch)
                            } catch {
                                Stop-Function -Message "Failed to install stored procedure." -ErrorRecord $_ -Continue -Target $instance
                            }
                        }

                        if ($ProcedureExists -gt 0) {
                            $status = 'Updated'
                        } else {
                            $status = 'Installed'
                        }


                        [PSCustomObject]@{
                            ComputerName = $server.ComputerName
                            InstanceName = $server.ServiceName
                            SqlInstance  = $server.DomainInstanceName
                            Database     = $Database
                            Name         = 'sp_WhoisActive'
                            Version      = $versionWhoIsActive
                            Status       = $status
                        }
                    } else {
                        Stop-Function -Message "Failed to find database $Database on $instance or $Database is not writeable." -ErrorRecord $_ -Continue -Target $instance
                    }

                } catch {
                    Stop-Function -Message "Failed to install stored procedure." -ErrorRecord $_ -Continue -Target $instance
                }

            }
        }
    }
    end {
        if ($PSCmdlet.ShouldProcess($env:computername, "Post-install cleanup")) {
            Get-Item $sqlfile | Remove-Item
        }
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Install-SqlWhoIsActive
    }
}
tools\dbatools\functions\Invoke-DbaAdvancedRestore.ps1
function Invoke-DbaAdvancedRestore {
    <#
    .SYNOPSIS
        Allows the restore of modified BackupHistory Objects
        For 90% of users Restore-DbaDatabase should be your point of access to this function. The other 10% use it at their own risk

    .DESCRIPTION
        This is the final piece in the Restore-DbaDatabase Stack. Usually a BackupHistory object will arrive here from `Restore-Dbadatabase` via the following pipeline:
        `Get-DbaBackupInformation  | Select-DbaBackupInformation | Format-DbaBackupInformation | Test-DbaBackupInformation | Invoke-DbaAdvancedRestore`

        We have exposed these functions publicly to allow advanced users to perform operations that we don't support, or won't add as they would make things too complex for the majority of our users

        For example if you wanted to do some very complex redirection during a migration, then doing the rewrite of destinations may be better done with your own custom scripts rather than via `Format-DbaBackupInformation`

        We would recommend ALWAYS pushing your input through `Test-DbaBackupInformation` just to make sure that it makes sense to us.

    .PARAMETER BackupHistory
        The BackupHistory object to be restored.
        Can be passed in on the pipeline

    .PARAMETER SqlInstance
        The SqlInstance to which the backups should be restored

    .PARAMETER SqlCredential
        SqlCredential to be used to connect to the target SqlInstance

    .PARAMETER OutputScriptOnly
        If set, the restore will not be performed, but the T-SQL scripts to perform it will be returned

    .PARAMETER VerifyOnly
        If set, performs a Verify of the backups rather than a full restore

    .PARAMETER RestoreTime
        Point in Time to which the database should be restored.

        This should be the same value or earlier, as used in the previous pipeline stages

    .PARAMETER StandbyDirectory
        A folder path where a standby file should be created to put the recovered databases in a standby mode

    .PARAMETER NoRecovery
        Leave the database in a restoring state so that further restore may be made

    .PARAMETER MaxTransferSize
        Parameter to set the unit of transfer. Values must be a multiple by 64kb

    .PARAMETER Blocksize
        Specifies the block size to use. Must be one of 0.5kb,1kb,2kb,4kb,8kb,16kb,32kb or 64kb
        Can be specified in bytes
        Refer to https://msdn.microsoft.com/en-us/library/ms178615.aspx for more detail

    .PARAMETER BufferCount
        Number of I/O buffers to use to perform the operation.
        Refer to https://msdn.microsoft.com/en-us/library/ms178615.aspx for more detail

    .PARAMETER Continue
        Indicates that the restore is continuing a restore, so target database must be in Recovering or Standby states

    .PARAMETER AzureCredential
        AzureCredential required to connect to blob storage holding the backups

    .PARAMETER WithReplace
        Indicated that if the database already exists it should be replaced

    .PARAMETER KeepCDC
        Indicates whether CDC information should be restored as part of the database

    .PARAMETER PageRestore
        The output from Get-DbaSuspect page containing the suspect pages to be restored.

    .PARAMETER WhatIf
        Shows what would happen if the cmdlet runs. The cmdlet is not run.

    .PARAMETER Confirm
        Prompts you for confirmation before running the cmdlet.

    .PARAMETER EnableException
        Replaces user friendly yellow warnings with bloody red exceptions of doom!
        Use this if you want the function to throw terminating errors you want to catch.

    .NOTES
        Tags: Restore, Backup
        Author: Stuart Moore (@napalmgram - http://stuart-moore.com)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaAdvancedRestore

    .EXAMPLE
        PS C:\> $BackupHistory | Invoke-DbaAdvancedRestore -SqlInstance MyInstance

        Will restore all the backups in the BackupHistory object according to the transformations it contains

    .EXAMPLE
        PS C:\> $BackupHistory | Invoke-DbaAdvancedRestore -SqlInstance MyInstance -OutputScriptOnly
        PS C:\> $BackupHistory | Invoke-DbaAdvancedRestore -SqlInstance MyInstance

        First generates just the T-SQL restore scripts so they can be sanity checked, and then if they are good perform the full restore.
        By reusing the BackupHistory object there is no need to rescan all the backup files again

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "AzureCredential", Justification = "For Parameter AzureCredential")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseOutputTypeCorrectly", "", Justification = "PSSA Rule Ignored by BOH")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Object[]]$BackupHistory,
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$OutputScriptOnly,
        [switch]$VerifyOnly,
        [datetime]$RestoreTime = (Get-Date).AddDays(2),
        [string]$StandbyDirectory,
        [switch]$NoRecovery,
        [int]$MaxTransferSize,
        [int]$BlockSize,
        [int]$BufferCount,
        [switch]$Continue,
        [string]$AzureCredential,
        [switch]$WithReplace,
        [switch]$KeepCDC,
        [object[]]$PageRestore,
        [switch]$EnableException
    )
    begin {
        try {
            $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            return
        }
        if ($KeepCDC -and ($NoRecovery -or ('' -ne $StandbyDirectory))) {
            Stop-Function -Category InvalidArgument -Message "KeepCDC cannot be specified with Norecovery or Standby as it needs recovery to work"
            return
        }

        if ($null -ne $PageRestore) {
            Write-Message -Message "Doing Page Recovery" -Level Verbose
            $tmpPages = @()
            foreach ($Page in $PageRestore) {
                $tmppages += "$($Page.FileId):$($Page.PageID)"
            }
            $NoRecovery = $True
            $Pages = $tmpPages -join ','
        }
        $InternalHistory = @()
    }
    process {
        foreach ($bh in $BackupHistory) {
            $InternalHistory += $bh
        }
    }
    end {
        if (Test-FunctionInterrupt) { return }
        $Databases = $InternalHistory.Database | Select-Object -Unique
        foreach ($Database in $Databases) {
            $DatabaseRestoreStartTime = Get-Date
            if ($Database -in $Server.Databases.Name) {
                if (-not $OutputScriptOnly -and -not $VerifyOnly) {
                    if ($Pscmdlet.ShouldProcess("Killing processes in $Database on $SqlInstance as it exists and WithReplace specified  `n", "Cannot proceed if processes exist, ", "Database Exists and WithReplace specified, need to kill processes to restore")) {
                        try {
                            Write-Message -Level Verbose -Message "Killing processes on $Database"
                            $null = Stop-DbaProcess -SqlInstance $Server -Database $Database -WarningAction Silentlycontinue
                            $null = $server.Query("Alter database $Database set offline with rollback immediate; alter database $Database set restricted_user; Alter database $Database set online with rollback immediate", 'master')
                            $server.ConnectionContext.Connect()
                        } catch {
                            Write-Message -Level Verbose -Message "No processes to kill in $Database"
                        }
                    }
                } elseif (-not $WithReplace -and (-not $VerifyOnly)) {
                    Stop-Function -Message "$Database exists and WithReplace not specified, stopping" -EnableException $EnableException
                    return
                }
            }
            Write-Message -Message "WithReplace  = $WithReplace" -Level Debug
            $backups = @($InternalHistory | Where-Object {$_.Database -eq $Database} | Sort-Object -Property Type, FirstLsn)
            $BackupCnt = 1
            foreach ($backup in $backups) {
                $FileRestoreStartTime = Get-Date
                $Restore = New-Object Microsoft.SqlServer.Management.Smo.Restore
                if (($backup -ne $backups[-1]) -or $true -eq $NoRecovery) {
                    $Restore.NoRecovery = $True
                } elseif ($backup -eq $backups[-1] -and '' -ne $StandbyDirectory) {
                    $Restore.StandbyFile = $StandByDirectory + "\" + $Database + (get-date -Format yyyMMddHHmmss) + ".bak"
                    Write-Message -Level Verbose -Message "Setting standby on last file $($Restore.StandbyFile)"
                } else {
                    $Restore.NoRecovery = $False
                }
                if ($restoretime -gt (Get-Date) -or $Restore.RestoreTime -gt (Get-Date) -or $backup.RecoveryModel -eq 'Simple') {
                    $Restore.ToPointInTime = $null
                } else {
                    if ($RestoreTime -ne $Restore.RestoreTime) {
                        $Restore.ToPointInTime = $backup.RestoreTime
                    } else {
                        $Restore.ToPointInTime = $RestoreTime
                    }
                }
                $Restore.Database = $database
                $Restore.ReplaceDatabase = $WithReplace
                if ($MaxTransferSize) {
                    $Restore.MaxTransferSize = $MaxTransferSize
                }
                if ($BufferCount) {
                    $Restore.BufferCount = $BufferCount
                }
                if ($BlockSize) {
                    $Restore.Blocksize = $BlockSize
                }
                if ($true -ne $Continue -and ($null -eq $Pages)) {
                    foreach ($file in $backup.FileList) {
                        $MoveFile = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile
                        $MoveFile.LogicalFileName = $File.LogicalName
                        $MoveFile.PhysicalFileName = $File.PhysicalName
                        $null = $Restore.RelocateFiles.Add($MoveFile)
                    }
                }
                $Action = switch ($backup.Type) {
                    '1' {'Database'}
                    '2' {'Log'}
                    '5' {'Database'}
                    'Transaction Log' {'Log'}
                    Default {'Database'}
                }

                Write-Message -Level Debug -Message "restore action = $Action"
                $Restore.Action = $Action
                foreach ($File in $backup.FullName) {
                    Write-Message -Message "Adding device $file" -Level Debug
                    $Device = New-Object -TypeName Microsoft.SqlServer.Management.Smo.BackupDeviceItem
                    $Device.Name = $file
                    if ($file.StartsWith("http")) {
                        $Device.devicetype = "URL"
                    } else {
                        $Device.devicetype = "File"
                    }

                    if ($AzureCredential) {
                        $Restore.CredentialName = $AzureCredential
                    }

                    $Restore.FileNumber = $backup.Position
                    $Restore.Devices.Add($Device)
                }
                Write-Message -Level Verbose -Message "Performing restore action"
                $ConfirmMessage = "`n Restore Database $Database on $SqlInstance `n from files: $RestoreFileNames `n with these file moves: `n $LogicalFileMovesString `n $ConfirmPointInTime `n"
                if ($Pscmdlet.ShouldProcess("$Database on $SqlInstance `n `n", $ConfirmMessage)) {
                    try {
                        $RestoreComplete = $true
                        if ($KeepCDC -and $Restore.NoRecovery -eq $false) {
                            $script = $Restore.Script($server)
                            if ($script -like '*WITH*') {
                                $script = $script.TrimEnd() + ' , KEEP_CDC'
                            } else {
                                $script = $script.TrimEnd() + ' WITH KEEP_CDC'
                            }
                            if ($true -ne $OutputScriptOnly) {
                                Write-Progress -id 1 -activity "Restoring $Database to $sqlinstance - Backup $BackupCnt of $($Backups.count)" -percentcomplete 0 -status ([System.String]::Format("Progress: {0} %", 0))
                                $null = $server.ConnectionContext.ExecuteNonQuery($script)
                                Write-Progress -id 1 -activity "Restoring $Database to $sqlinstance - Backup $BackupCnt of $($Backups.count)" -status "Complete" -Completed
                            }
                        } elseif ($null -ne $Pages -and $Action -eq 'Database') {
                            $script = $Restore.Script($server)
                            $script = $script -replace "] FROM", "] PAGE='$pages' FROM"
                            if ($true -ne $OutputScriptOnly) {
                                Write-Progress -id 1 -activity "Restoring $Database to $sqlinstance - Backup $BackupCnt of $($Backups.count)" -percentcomplete 0 -status ([System.String]::Format("Progress: {0} %", 0))
                                $null = $server.ConnectionContext.ExecuteNonQuery($script)
                                Write-Progress -id 1 -activity "Restoring $Database to $sqlinstance - Backup $BackupCnt of $($Backups.count)" -status "Complete" -Completed
                            }
                        } elseif ($OutputScriptOnly) {
                            $script = $Restore.Script($server)
                        } elseif ($VerifyOnly) {
                            Write-Message -Message "VerifyOnly restore" -Level Verbose
                            Write-Progress -id 1 -activity "Verifying $Database backup file on $sqlinstance - Backup $BackupCnt of $($Backups.count)" -percentcomplete 0 -status ([System.String]::Format("Progress: {0} %", 0))
                            $Verify = $Restore.SqlVerify($server)
                            Write-Progress -id 1 -activity "Verifying $Database backup file on $sqlinstance - Backup $BackupCnt of $($Backups.count)" -status "Complete" -Completed
                            if ($verify -eq $true) {
                                Write-Message -Message "VerifyOnly restore Succeeded" -Level Verbose
                                return "Verify successful"
                            } else {
                                Write-Message -Message "VerifyOnly restore Failed" -Level Verbose
                                return "Verify failed"
                            }
                        } else {
                            $outerProgress = $BackupCnt / $Backups.Count * 100
                            if ($BackupCnt -eq 1) {
                                Write-Progress -id 1 -Activity "Restoring $Database to $sqlinstance - Backup $BackupCnt of $($Backups.count)" -percentcomplete 0
                            }
                            Write-Progress -id 2 -ParentId 1 -Activity "Restore $($backup.FullName -Join ',')" -percentcomplete 0
                            $script = $Restore.Script($Server)
                            $percentcomplete = [Microsoft.SqlServer.Management.Smo.PercentCompleteEventHandler] {
                                Write-Progress -id 2 -ParentId 1 -Activity "Restore $($backup.FullName -Join ',')" -percentcomplete $_.Percent -status ([System.String]::Format("Progress: {0} %", $_.Percent))
                            }
                            $Restore.add_PercentComplete($percentcomplete)
                            $Restore.PercentCompleteNotification = 1
                            $Restore.SqlRestore($Server)
                            Write-Progress -id 2 -ParentId 1 -Activity "Restore $($backup.FullName -Join ',')" -Completed
                            Write-Progress -id 1 -Activity "Restoring $Database to $sqlinstance - Backup $BackupCnt of $($Backups.count)" -percentcomplete $outerProgress -status ([System.String]::Format("Progress: {0:N2} %", $outerProgress))
                        }
                    } catch {
                        Write-Message -Level Verbose -Message "Failed, Closing Server connection"
                        $RestoreComplete = $False
                        $ExitError = $_.Exception.InnerException
                        Stop-Function -Message "Failed to restore db $Database, stopping" -ErrorRecord $_
                        return
                    } finally {
                        if ($OutputScriptOnly -eq $false) {
                            $pathSep = Get-DbaPathSep -Server $server
                            $RestoreDirectory = ((Split-Path $backup.FileList.PhysicalName -Parent) | Sort-Object -Unique).Replace('\', $pathSep) -Join ','
                            [PSCustomObject]@{
                                ComputerName           = $server.ComputerName
                                InstanceName           = $server.ServiceName
                                SqlInstance            = $server.DomainInstanceName
                                Database               = $backup.Database
                                DatabaseName           = $backup.Database
                                DatabaseOwner          = $server.ConnectionContext.TrueLogin
                                Owner                  = $server.ConnectionContext.TrueLogin
                                NoRecovery             = $Restore.NoRecovery
                                WithReplace            = $WithReplace
                                RestoreComplete        = $RestoreComplete
                                BackupFilesCount       = $backup.FullName.Count
                                RestoredFilesCount     = $backup.Filelist.PhysicalName.count
                                BackupSizeMB           = if ([bool]($backup.psobject.Properties.Name -contains 'TotalSize')) { [Math]::Round(($backup | Measure-Object -Property TotalSize -Sum).Sum / 1mb, 2) } else { $null }
                                CompressedBackupSizeMB = if ([bool]($backup.psobject.Properties.Name -contains 'CompressedBackupSize')) { [Math]::Round(($backup | Measure-Object -Property CompressedBackupSize -Sum).Sum / 1mb, 2) } else { $null }
                                BackupFile             = $backup.FullName -Join ','
                                RestoredFile           = $((Split-Path $backup.FileList.PhysicalName -Leaf) | Sort-Object -Unique) -Join ','
                                RestoredFileFull       = ($backup.Filelist.PhysicalName -Join ',')
                                RestoreDirectory       = $RestoreDirectory
                                BackupSize             = if ([bool]($backup.psobject.Properties.Name -contains 'TotalSize')) { [dbasize](($backup | Measure-Object -Property TotalSize -Sum).Sum) } else { $null }
                                CompressedBackupSize   = if ([bool]($backup.psobject.Properties.Name -contains 'CompressedBackupSize')) { [dbasize](($backup | Measure-Object -Property CompressedBackupSize -Sum).Sum) } else { $null }
                                Script                 = $script
                                BackupFileRaw          = ($backups.Fullname)
                                FileRestoreTime        = New-TimeSpan -Seconds ((Get-Date) - $FileRestoreStartTime).TotalSeconds
                                DatabaseRestoreTime    = New-TimeSpan -Seconds ((Get-Date) - $DatabaseRestoreStartTime).TotalSeconds
                                ExitError              = $ExitError
                            } | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, BackupFile, BackupFilesCount, BackupSize, CompressedBackupSize, Database, Owner, DatabaseRestoreTime, FileRestoreTime, NoRecovery, RestoreComplete, RestoredFile, RestoredFilesCount, Script, RestoreDirectory, WithReplace
                        } else {
                            $script
                        }
                        if ($Restore.Devices.Count -gt 0) {
                            $Restore.Devices.Clear()
                        }
                        Write-Message -Level Verbose -Message "Succeeded, Closing Server connection"
                        $server.ConnectionContext.Disconnect()
                    }
                }
                $BackupCnt++
            }
            Write-Progress -id 2 -Activity "Finished" -Completed
            if ($server.ConnsectionContext.exists) {
                $server.ConnectionContext.Disconnect()
            }
            Write-Progress -id 1 -Activity "Finished" -Completed
        }
    }
}
tools\dbatools\functions\Invoke-DbaAgFailover.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Invoke-DbaAgFailover {
    <#
    .SYNOPSIS
        Failover an availability group.

    .DESCRIPTION
       Failover an availability group.

    .PARAMETER SqlInstance
        The SQL Server instance. Server version must be SQL Server version 2012 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential).

    .PARAMETER AvailabilityGroup
        Only failover specific availability groups.

    .PARAMETER InputObject
        Enables piping from Get-DbaAvailabilityGroup

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER Force
        Force Failover and allow data loss

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: AG, AvailabilityGroup, HA
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaAgFailover

    .EXAMPLE
        PS C:\> Invoke-DbaAgFailover -SqlInstance sql2017 -AvailabilityGroup SharePoint

        Safely (no potential data loss) fails over the SharePoint AG to sql2017. Prompts for confirmation.

    .EXAMPLE
        PS C:\> Get-DbaAvailabilityGroup -SqlInstance sql2017 | Out-GridView -Passthru | Invoke-DbaAgFailover -Confirm:$false

        Safely (no potential data loss) fails over the selected availability groups to sql2017. Does not prompt for confirmation.

    .EXAMPLE
        PS C:\> Invoke-DbaAgFailover -SqlInstance sql2017 -AvailabilityGroup SharePoint -Force

        Forcefully (with potential data loss) fails over the SharePoint AG to sql2017. Prompts for confirmation.
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$AvailabilityGroup,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.AvailabilityGroup[]]$InputObject,
        [switch]$Force,
        [switch]$EnableException
    )
    process {
        if ($SqlInstance -and -not $AvailabilityGroup) {
            Stop-Function -Message "You must specify at least one availability group when using SqlInstance."
            return
        }

        if ($SqlInstance) {
            $InputObject += Get-DbaAvailabilityGroup -SqlInstance $SqlInstance -SqlCredential $SqlCredential -AvailabilityGroup $AvailabilityGroup
        }

        foreach ($ag in $InputObject) {
            try {
                $server = $ag.Parent
                if ($Force) {
                    if ($Pscmdlet.ShouldProcess($server.Name, "Forcefully failing over $($ag.Name), allowing potential data loss")) {
                        $ag.FailoverWithPotentialDataLoss()
                        $ag.Refresh()
                        $ag
                    }
                } else {
                    if ($Pscmdlet.ShouldProcess($server.Name, "Gracefully failing over $($ag.Name)")) {
                        $ag.Failover()
                        $ag.Refresh()
                        $ag
                    }
                }
            } catch {
                Stop-Function -Continue -Message "Failure" -ErrorRecord $_
            }
        }
    }
}
tools\dbatools\functions\Invoke-DbaBalanceDataFiles.ps1
function Invoke-DbaBalanceDataFiles {
    <#
    .SYNOPSIS
        Re-balance data between data files

    .DESCRIPTION
        When you have a large database with a single data file and add another file, SQL Server will only use the new file until it's about the same size.
        You may want to balance the data between all the data files.

        The function will check the server version and edition to see if the it allows for online index rebuilds.
        If the server does support it, it will try to rebuild the index online.
        If the server doesn't support it, it will rebuild the index offline. Be carefull though, this can cause downtime

        The tables must have a clustered index to be able to balance out the data.
        The function does NOT yet support heaps.

        The function will also check if the file groups are subject to balance out.
        A file group whould have at least have 2 data files and should be writable.
        If a table is within such a file group it will be subject for processing. If not the table will be skipped.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process.

    .PARAMETER Table
        The tables(s) of the database to process. If unspecified, all tables will be processed.

    .PARAMETER RebuildOffline
        Will set all the indexes to rebuild offline.
        This option is also needed when the server version is below 2005.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run

    .PARAMETER Confirm
        Prompts for confirmation of every step. For example:

        The server does not support online rebuilds of indexes.
        Do you want to rebuild the indexes offline?
        [Y] Yes  [N] No   [?] Help (default is "Y"):

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER Force
        This will disable the check for enough disk space for the action to be successful.
        Use this with caution!!

    .NOTES
        Tags: Database, FileManagement, File, Space
        Author: Sander Stad (@sqlstad), sqlstad.nl

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Invoke-DbaBalanceDataFiles -SqlInstance sql1 -Database db1

        This command will distribute the data in database db1 on instance sql1

    .EXAMPLE
        PS C:\> Invoke-DbaBalanceDataFiles -SqlInstance sql1 -Database db1 | Select-Object -ExpandProperty DataFilesEnd

        This command will distribute the data in database db1 on instance sql1

    .EXAMPLE
        PS C:\> Invoke-DbaBalanceDataFiles -SqlInstance sql1 -Database db1 -Table table1,table2,table5

        This command will distribute the data for only the tables table1,table2 and table5

    .EXAMPLE
        PS C:\> Invoke-DbaBalanceDataFiles -SqlInstance sql1 -Database db1 -RebuildOffline

        This command will consider the fact that there might be a SQL Server edition that does not support online rebuilds of indexes.
        By supplying this parameter you give permission to do the rebuilds offline if the edition does not support it.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification = "Singular Noun doesn't make sense")]
    param (
        [parameter(ParameterSetName = "Pipe", Mandatory)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [Alias("Tables")]
        [object[]]$Table,
        [switch]$RebuildOffline,
        [switch]$EnableException,
        [switch]$Force
    )

    process {

        Write-Message -Message "Starting balancing out data files" -Level Verbose

        # Set the initial success flag
        [bool]$success = $true

        foreach ($instance in $sqlinstance) {
            # Try connecting to the instance
            try {
                $Server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            # Check the database parameter
            if ($Database) {
                if ($Database -notin $server.Databases.Name) {
                    Stop-Function -Message "One or more databases cannot be found on instance on instance $instance" -Target $instance -Continue
                }

                $DatabaseCollection = $server.Databases | Where-Object { $_.Name -in $Database }
            } else {
                Stop-Function -Message "Please supply a database to balance out" -Target $instance -Continue
            }

            # Get the server version
            $serverVersion = $server.Version.Major

            # Check edition of the sql instance
            if ($RebuildOffline) {
                Write-Message -Message "Continuing with offline rebuild." -Level Verbose
            } elseif (-not $RebuildOffline -and ($serverVersion -lt 9 -or (([string]$Server.Edition -notmatch "Developer") -and ($Server.Edition -notmatch "Enterprise")))) {
                # Set up the confirm part
                $message = "The server does not support online rebuilds of indexes. `nDo you want to rebuild the indexes offline?"
                $choiceYes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Answer Yes."
                $choiceNo = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Answer No."
                $options = [System.Management.Automation.Host.ChoiceDescription[]]($choiceYes, $choiceNo)
                $result = $host.ui.PromptForChoice($title, $message, $options, 0)

                # Check the result from the confirm
                switch ($result) {
                    # If yes
                    0 {
                        # Set the option to generate a full backup
                        Write-Message -Message "Continuing with offline rebuild." -Level Verbose

                        [bool]$supportOnlineRebuild = $false
                    }
                    1 {
                        Stop-Function -Message "You chose to not allow offline rebuilds of indexes. Use -RebuildOffline" -Target $instance
                        return
                    }
                } # switch
            } elseif ($serverVersion -ge 9 -and (([string]$Server.Edition -like "Developer*") -or ($Server.Edition -like "Enterprise*"))) {
                [bool]$supportOnlineRebuild = $true
            }

            # Loop through each of the databases
            foreach ($db in $DatabaseCollection) {
                $dataFilesStarting = Get-DbaDbFile -SqlInstance $server -Database $db.Name | Where-Object { $_.TypeDescription -eq 'ROWS' } | Select-Object ID, LogicalName, PhysicalName, Size, UsedSpace, AvailableSpace | Sort-Object ID

                if (-not $Force) {
                    # Check the amount of disk space available
                    $query = "SELECT SUBSTRING(physical_name, 0, 4) AS 'Drive' ,
                                        SUM(( size * 8 ) / 1024) AS 'SizeMB'
                                FROM	sys.master_files
                                WHERE	DB_NAME(database_id) = '$($db.Name)'
                                GROUP BY SUBSTRING(physical_name, 0, 4)"
                    # Execute the query
                    $dbDiskUsage = $Server.Query($query)

                    # Get the free space for each drive
                    $result = $Server.Query("xp_fixeddrives")
                    $MbFreeColName = $result[0].psobject.Properties.Name[1]
                    $diskFreeSpace = $result | Select-Object Drive, @{ Name = 'FreeMB'; Expression = { $_.$MbFreeColName } }

                    # Loop through each of the drives to see if the size of files on that
                    # particular disk do not exceed the free space of that disk
                    foreach ($d in $dbDiskUsage) {
                        $freeSpace = $diskFreeSpace | Where-Object { $_.Drive -eq $d.Drive.Trim(':\') } | Select-Object FreeMB
                        if ($d.SizeMB -gt $freeSpace.FreeMB) {
                            # Set the success flag
                            $success = $false

                            Stop-Function -Message "The available space may not be sufficient to continue the process. Please use -Force to try anyway." -Target $instance -Continue
                            return
                        }
                    }
                }

                # Create the start time
                $start = Get-Date

                # Check if the function needs to continue
                if ($success) {

                    # Get the database files before all the alterations
                    Write-Message -Message "Retrieving data files before data move" -Level Verbose
                    Write-Message -Message "Processing database $db" -Level Verbose

                    # Check the datafiles of the database
                    $dataFiles = Get-DbaDbFile -SqlInstance $instance -Database $db | Where-Object { $_.TypeDescription -eq 'ROWS' }
                    if ($dataFiles.Count -eq 1) {
                        # Set the success flag
                        $success = $false

                        Stop-Function -Message "Database $db only has one data file. Please add a data file to balance out the data" -Target $instance -Continue
                    }

                    # Check the tables parameter
                    if ($Table) {
                        if ($Table -notin $db.Table) {
                            # Set the success flag
                            $success = $false

                            Stop-Function -Message "One or more tables cannot be found in database $db on instance $instance" -Target $instance -Continue
                        }

                        $TableCollection = $db.Tables | Where-Object { $_.Name -in $Table }
                    } else {
                        $TableCollection = $db.Tables
                    }

                    # Get the database file groups and check the aount of data files
                    Write-Message -Message "Retrieving file groups" -Level Verbose
                    $fileGroups = $Server.Databases[$db.Name].FileGroups

                    # ARray to hold the file groups with properties
                    $balanceableTables = @()

                    # Loop through each of the file groups

                    foreach ($fg in $fileGroups) {

                        # If there is less than 2 files balancing out data is not possible
                        if (($fg.Files.Count -ge 2) -and ($fg.Readonly -eq $false)) {
                            $balanceableTables += $fg.EnumObjects() | Where-Object { $_.GetType().Name -eq 'Table' }
                        }
                    }

                    $unsuccessfulTables = @()

                    # Loop through each of the tables
                    foreach ($tbl in $TableCollection) {

                        # Chck if the table balanceable
                        if ($tbl.Name -in $balanceableTables.Name) {

                            Write-Message -Message "Processing table $tbl" -Level Verbose

                            # Chck the tables and get the clustered indexes
                            if ($TableCollection.Indexes.Count -lt 1) {
                                # Set the success flag
                                $success = $false

                                Stop-Function -Message "Table $tbl does not contain any indexes" -Target $instance -Continue
                            } else {

                                # Get all the clustered indexes for the table
                                $clusteredIndexes = $TableCollection.Indexes | Where-Object { $_.IndexType -eq 'ClusteredIndex' }

                                if ($clusteredIndexes.Count -lt 1) {
                                    # Set the success flag
                                    $success = $false

                                    Stop-Function -Message "No clustered indexes found in table $tbl" -Target $instance -Continue
                                }
                            }

                            # Loop through each of the clustered indexes and rebuild them
                            Write-Message -Message "$($clusteredIndexes.Count) clustered index(es) found for table $tbl" -Level Verbose
                            if ($PSCmdlet.ShouldProcess("Rebuilding indexes to balance data")) {
                                foreach ($ci in $clusteredIndexes) {

                                    Write-Message -Message "Rebuilding index $($ci.Name)" -Level Verbose

                                    # Get the original index operation
                                    [bool]$originalIndexOperation = $ci.OnlineIndexOperation

                                    # Set the rebuild option to be either offline or online
                                    if ($RebuildOffline) {
                                        $ci.OnlineIndexOperation = $false
                                    } elseif ($serverVersion -ge 9 -and $supportOnlineRebuild -and -not $RebuildOffline) {
                                        Write-Message -Message "Setting the index operation for index $($ci.Name) to online" -Level Verbose
                                        $ci.OnlineIndexOperation = $true
                                    }

                                    # Rebuild the index
                                    try {
                                        Write-Message -Message "Rebuilding index $($ci.Name)" -Level Verbose
                                        $ci.Rebuild()

                                        # Set the success flag
                                        $success = $true
                                    } catch {
                                        # Set the original index operation back for the index
                                        $ci.OnlineIndexOperation = $originalIndexOperation

                                        # Set the success flag
                                        $success = $false

                                        Stop-Function -Message "Something went wrong rebuilding index $($ci.Name). `n$($_.Exception.Message)" -ErrorRecord $_ -Target $instance -Continue
                                    }

                                    # Set the original index operation back for the index
                                    Write-Message -Message "Setting the index operation for index $($ci.Name) back to the original value" -Level Verbose
                                    $ci.OnlineIndexOperation = $originalIndexOperation

                                } # foreach index

                            } # if process

                        } # if table is balanceable
                        else {
                            # Add the table to the unsuccessful array
                            $unsuccessfulTables += $tbl.Name

                            # Set the success flag
                            $success = $false

                            Write-Message -Message "Table $tbl cannot be balanced out" -Level Verbose
                        }

                    } #foreach table
                }

                # Create the end time
                $end = Get-Date

                # Create the time span
                $timespan = New-TimeSpan -Start $start -End $end
                $ts = [timespan]::fromseconds($timespan.TotalSeconds)
                $elapsed = "{0:HH:mm:ss}" -f ([datetime]$ts.Ticks)

                # Get the database files after all the alterations
                Write-Message -Message "Retrieving data files after data move" -Level Verbose
                $dataFilesEnding = Get-DbaDbFile -SqlInstance $server -Database $db.Name | Where-Object { $_.TypeDescription -eq 'ROWS' } | Select-Object ID, LogicalName, PhysicalName, Size, UsedSpace, AvailableSpace | Sort-Object ID

                [pscustomobject]@{
                    ComputerName   = $server.ComputerName
                    InstanceName   = $server.ServiceName
                    SqlInstance    = $server.DomainInstanceName
                    Database       = $db.Name
                    Start          = $start
                    End            = $end
                    Elapsed        = $elapsed
                    Success        = $success
                    Unsuccessful   = $unsuccessfulTables -join ","
                    DataFilesStart = $dataFilesStarting
                    DataFilesEnd   = $dataFilesEnding
                }

            } # foreach database

        } # end process
    }
}
tools\dbatools\functions\Invoke-DbaCycleErrorLog.ps1
function Invoke-DbaCycleErrorLog {
    <#
    .SYNOPSIS
        Cycles the current instance or agent log.

    .DESCRIPTION
        Cycles the current error log for the instance (SQL Server) and/or SQL Server Agent.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Type
        The log to cycle.
        Accepts: instance or agent.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Log, Cycle
        Author: Shawn Melton (@wsmelton), https://wsmelton.github.io

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaCycleLog

    .EXAMPLE
        PS C:\> Invoke-DbaCycleLog -SqlInstance sql2016 -Type agent

        Cycles the current error log for the SQL Server Agent on SQL Server instance sql2016

    .EXAMPLE
        PS C:\> Invoke-DbaCycleLog -SqlInstance sql2016 -Type instance

        Cycles the current error log for the SQL Server instance on SQL Server instance sql2016

    .EXAMPLE
        PS C:\> Invoke-DbaCycleLog -SqlInstance sql2016

        Cycles the current error log for both SQL Server instance and SQL Server Agent on SQL Server instance sql2016

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [ValidateSet('instance', 'agent')]
        [string]$Type,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        if (Test-Bound 'Type') {
            if ($Type -notin 'instance', 'agent') {
                Stop-Function -Message "The type provided [$Type] for $SqlInstance is not an accepted value. Please use 'Instance' or 'Agent'"
                return
            }
        }
        $logToCycle = @()
        switch ($Type) {
            'agent' {
                $sql = "EXEC msdb.dbo.sp_cycle_agent_errorlog;"
                $logToCycle = $Type
            }
            'instance' {
                $sql = "EXEC master.dbo.sp_cycle_errorlog;"
                $logToCycle = $Type
            }
            default {
                $sql = "
                    EXEC master.dbo.sp_cycle_errorlog;
                    EXEC msdb.dbo.sp_cycle_agent_errorlog;"
                $logToCycle = 'instance', 'agent'
            }
        }

    }
    process {
        if (Test-FunctionInterrupt) { return }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            try {
                $logs = $logToCycle -join ','
                if ($Pscmdlet.ShouldProcess($server, "Cycle the log(s): $logs")) {
                    $null = $server.Query($sql)
                    [pscustomobject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        LogType      = $logToCycle
                        IsSuccessful = $true
                        Notes        = $null
                    }
                }
            } catch {
                [pscustomobject]@{
                    ComputerName = $server.ComputerName
                    InstanceName = $server.ServiceName
                    SqlInstance  = $server.DomainInstanceName
                    LogType      = $logToCycle
                    IsSuccessful = $false
                    Notes        = $_.Exception
                }
                Stop-Function -Message "Issue cycling $logs on $server" -Target $server -ErrorRecord $_ -Exception $_.Exception -Continue
            }
        }
    }
}
tools\dbatools\functions\Invoke-DbaDbccDropCleanBuffer.ps1
function Invoke-DbaDbccDropCleanBuffer {
    <#
    .SYNOPSIS
        Execution of Database Console Command DBCC DROPCLEANBUFFERS

    .DESCRIPTION
        Allows execution of Database Console Command DBCC DROPCLEANBUFFERS

        Removes all clean buffers from the buffer pool, and columnstore objects from the columnstore object pool.

        Read more:
            - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-dropcleanbuffers-transact-sql

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER NoInformationalMessages
        Suppresses all informational messages.

    .PARAMETER WhatIf
        Shows what would happen if the cmdlet runs. The cmdlet is not run.

    .PARAMETER Confirm
        Prompts you for confirmation before running the cmdlet.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DBCC
        Author: Patrick Flynn (@sqllensman)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaDbccDropCleanBuffer

    .EXAMPLE
        PS C:\> Invoke-DbaDbccDropCleanBuffer -SqlInstance SqlServer2017

        Runs the command DBCC DROPCLEANBUFFERS against the instance SqlServer2017 using Windows Authentication

    .EXAMPLE
        PS C:\> Invoke-DbaDbccDropCleanBuffer -SqlInstance SqlServer2017 -NoInformationalMessages

        Runs the command DBCC DROPCLEANBUFFERS WITH NO_INFOMSGS against the instance SqlServer2017 using Windows Authentication

    .EXAMPLE
        PS C:\> 'Sql1','Sql2/sqlexpress' | Invoke-DbaDbccDropCleanBuffer -WhatIf

        Displays what will happen if command DBCC DROPCLEANBUFFERS is called against Sql1 and Sql2/sqlexpress

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> Invoke-DbaDbccDropCleanBuffer -SqlInstance Server1 -SqlCredential $cred

        Connects using sqladmin credential and executes command DBCC DROPCLEANBUFFERS for instance Server1

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$NoInformationalMessages,
        [switch]$EnableException
    )
    begin {

        $stringBuilder = New-Object System.Text.StringBuilder
        $null = $stringBuilder.Append("DBCC DROPCLEANBUFFERS")
        if (Test-Bound -ParameterName NoInformationalMessages) {
            $null = $stringBuilder.Append(" WITH NO_INFOMSGS")
        }
    }
    process {
        $query = $StringBuilder.ToString()

        foreach ($instance in $SqlInstance) {
            Write-Message -Message "Attempting Connection to $instance" -Level Verbose
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            try {
                if ($Pscmdlet.ShouldProcess($server.Name, "Execute the command $query against $instance")) {
                    Write-Message -Message "Query to run: $query" -Level Verbose
                    $results = $server | Invoke-DbaQuery  -Query $query -MessagesToOutput
                }
            } catch {
                Stop-Function -Message "Failure running DBCC DROPCLEANBUFFERS" -ErrorRecord $_ -Target $server -Continue
            }
            If ($Pscmdlet.ShouldProcess("console", "Outputting object")) {
                [PSCustomObject]@{
                    ComputerName = $server.ComputerName
                    InstanceName = $server.ServiceName
                    SqlInstance  = $server.DomainInstanceName
                    Cmd          = $query.ToString()
                    Output       = $results
                }
            }
        }
    }
}
tools\dbatools\functions\Invoke-DbaDbccFreeCache.ps1
function Invoke-DbaDbccFreeCache {
    <#
    .SYNOPSIS
        Execution of Database Console Commands that clear Server level Memory caches

    .DESCRIPTION
        Allows execution of Database Console Commands that act at Server Level to clear Memory caches

        Allows execution of the following commands
            DBCC FREEPROCCACHE
            DBCC FREESESSIONCACHE
            DBCC FREESYSTEMCACHE

        Read more:
            - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-freeproccache-transact-sql
            - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-freesessioncache-transact-sql
            - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-freesystemcache-transact-sql

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Operation
        DBCC Operation to Perform - Supports specific set of operations

    .PARAMETER InputValue
        Value used for Operation - meaning depends on Operation
        DBCC FREEPROCCACHE accepts
            a plan_handle of type varbinary(64)
            a sql_handle of type varbinary(64)
            or the name of a Resource Governor resource pool of type sysname
            If blank then clears all elements from the plan cache
        DBCC FREESYSTEMCACHE accepts
            'ALL' for ALL specifies all supported caches
            or name of a Resource Governor pool cache
        Not required for other values

    .PARAMETER NoInformationalMessages
        Suppresses all informational messages.

    .PARAMETER MarkInUseForRemoval
        Used when Operation = DBCC FREESYSTEMCACHE
        Asynchronously frees currently used entries from their respective caches after they become unused

    .PARAMETER WhatIf
        Shows what would happen if the cmdlet runs. The cmdlet is not run.

    .PARAMETER Confirm
        Prompts you for confirmation before running the cmdlet.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DBCC
        Author: Patrick Flynn (@sqllensman)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaDbccFreeCache

    .EXAMPLE
        PS C:\> Invoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREEPROCCACHE

        Runs the command DBCC FREEPROCCACHE against the instance SqlServer2017 using Windows Authentication

    .EXAMPLE
        PS C:\> Invoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREESESSIONCACHE -NoInformationalMessages

        Runs the command DBCC FREESESSIONCACHE WITH NO_INFOMSGS against the instance SqlServer2017 using Windows Authentication

    .EXAMPLE
        PS C:\> Invoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREESYSTEMCACHE -NoInformationalMessages

        Runs the command DBCC FREESYSTEMCACHE WITH NO_INFOMSGS against the instance SqlServer2017 using Windows Authentication

    .EXAMPLE
        PS C:\> Invoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREEPROCCACHE -InputValue 0x060006001ECA270EC0215D05000000000000000000000000

        Remove a specific plan with plan_handle 0x060006001ECA270EC0215D05000000000000000000000000 from the cache via the command DBCC FREEPROCCACHE(0x060006001ECA270EC0215D05000000000000000000000000) against the instance SqlServer2017 using Windows Authentication

    .EXAMPLE
        PS C:\> Invoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREEPROCCACHE -InputValue default

        Runs the command DBCC FREEPROCCACHE('default') against the instance SqlServer2017 using Windows Authentication. This clears all cache entries associated with a resource pool 'default'.

    .EXAMPLE
        PS C:\> Invoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREESYSTEMCACHE -InputValue default

        Runs the command DBCC FREESYSTEMCACHE ('ALL', default) against the instance SqlServer2017 using Windows Authentication. This will clean all the caches with entries specific to the resource pool named "default".

    .EXAMPLE
        PS C:\> Invoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREESYSTEMCACHE -InputValue default -MarkInUseForRemoval

        Runs the command DBCC FREESYSTEMCACHE ('ALL', default) WITH MARK_IN_USE_FOR_REMOVAL against the instance SqlServer2017 using Windows Authentication. This will to release entries once the entries become unused for all the caches with entries specific to the resource pool named "default".

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [ValidateSet('FreeProcCache', 'FreeSessionCache', 'FreeSystemCache')]
        [string]$Operation = "FreeProcCache",
        [string]$InputValue,
        [switch]$NoInformationalMessages,
        [switch]$MarkInUseForRemoval,
        [switch]$EnableException
    )
    begin {

        if (Test-Bound -ParameterName Operation) {
            $Operation = $Operation.ToUpper()
        } else {
            Write-Message -Level Warning -Message "You must specify an operation "
            continue
        }

        $stringBuilder = New-Object System.Text.StringBuilder
        if ($Operation -eq 'FREESESSIONCACHE') {
            $null = $stringBuilder.Append("DBCC $Operation")
            if (Test-Bound -ParameterName NoInformationalMessages) {
                $null = $stringBuilder.Append(" WITH NO_INFOMSGS")
            }
        }
        if ($Operation -eq 'FREEPROCCACHE') {
            if (Test-Bound -ParameterName InputValue) {
                if ($InputValue.StartsWith('0x')) {
                    $null = $stringBuilder.Append("DBCC $Operation($InputValue)")
                } else {
                    $null = $stringBuilder.Append("DBCC $Operation('$InputValue')")
                }
                if (Test-Bound -ParameterName NoInformationalMessages) {
                    $null = $stringBuilder.Append(" WITH NO_INFOMSGS")
                }
            } else {
                $null = $stringBuilder.Append("DBCC $Operation")
                if (Test-Bound -ParameterName NoInformationalMessages) {
                    $null = $stringBuilder.Append(" WITH NO_INFOMSGS")
                }
            }
        }
        if ($Operation -eq 'FREESYSTEMCACHE') {
            if (Test-Bound -ParameterName InputValue) {
                $null = $stringBuilder.Append("DBCC FREESYSTEMCACHE('ALL', $InputValue)")
            } else {
                $null = $stringBuilder.Append("DBCC FREESYSTEMCACHE('ALL')")
            }
            if (Test-Bound -ParameterName NoInformationalMessages) {
                if (Test-Bound -ParameterName MarkInUseForRemoval) {
                    $null = $stringBuilder.Append(" WITH NO_INFOMSGS, MARK_IN_USE_FOR_REMOVAL")
                } else {
                    $null = $stringBuilder.Append(" WITH NO_INFOMSGS")
                }
            } elseif (Test-Bound -ParameterName MarkInUseForRemoval) {
                $null = $stringBuilder.Append(" WITH MARK_IN_USE_FOR_REMOVAL")
            }
        }
    }
    process {
        $query = $StringBuilder.ToString()

        foreach ($instance in $SqlInstance) {
            Write-Message -Message "Attempting Connection to $instance" -Level Verbose
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            try {
                if ($Pscmdlet.ShouldProcess($server.Name, "Execute the command $query against $instance")) {
                    Write-Message -Message "Query to run: $query" -Level Verbose
                    $results = $server | Invoke-DbaQuery  -Query $query -MessagesToOutput
                }
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Target $server -Continue
            }
            if ($Pscmdlet.ShouldProcess("console", "Outputting object")) {
                [PSCustomObject]@{
                    ComputerName = $server.ComputerName
                    InstanceName = $server.ServiceName
                    SqlInstance  = $server.DomainInstanceName
                    Operation    = $Operation
                    Cmd          = $query.ToString()
                    Output       = $results
                }
            }
        }
    }
}
tools\dbatools\functions\Invoke-DbaDbClone.ps1
function Invoke-DbaDbClone {
    <#
    .SYNOPSIS
        Clones a database schema and statistics

    .DESCRIPTION
        Clones a database schema and statistics.

        This can be useful for testing query performance without requiring all the space needed for the data in the database.

        Read more:
            - https://sqlperformance.com/2016/08/sql-statistics/expanding-dbcc-clonedatabase
            - https://support.microsoft.com/en-us/help/3177838/how-to-use-dbcc-clonedatabase-to-generate-a-schema-and-statistics-only

        Thanks to Microsoft Tiger Team for the code and idea https://github.com/Microsoft/tigertoolbox/

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database to clone - this list is auto-populated from the server.

    .PARAMETER InputObject
        Enables piping from Get-DbaDatabase

    .PARAMETER CloneDatabase
        The name(s) to clone to.

    .PARAMETER ExcludeStatistics
        Exclude the statistics in the cloned database

    .PARAMETER ExcludeQueryStore
        Exclude the QueryStore data in the cloned database

    .PARAMETER UpdateStatistics
        Update the statistics prior to cloning (per Microsoft Tiger Team formula)

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.
    
    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Statistics, Performance, Clone
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaDbClone

    .EXAMPLE
        PS C:\> Invoke-DbaDbClone -SqlInstance sql2016 -Database mydb -CloneDatabase myclone

        Clones mydb to myclone on sql2016

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sql2016 -Database mydb | Invoke-DbaDbClone -CloneDatabase myclone, myclone2 -UpdateStatistics

        Updates the statistics of mydb then clones to myclone and myclone2
        
#>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [string[]]$CloneDatabase,
        [switch]$ExcludeStatistics,
        [switch]$ExcludeQueryStore,
        [switch]$UpdateStatistics,
        [switch]$EnableException
    )

    begin {
        if (-not $Database -and $SqlInstance) {
            Stop-Function -Message "You must specify a database name if you did not pipe a database"
        }

        $sqlStats = "DECLARE @out TABLE(id INT IDENTITY(1,1), s SYSNAME, o SYSNAME, i SYSNAME, stats_stream VARBINARY(MAX), rows BIGINT, pages BIGINT)
            DECLARE @dbcc TABLE(stats_stream VARBINARY(MAX), rows BIGINT, pages BIGINT)
            DECLARE c CURSOR FOR
                    SELECT OBJECT_SCHEMA_NAME(object_id) s, OBJECT_NAME(object_id) o, name i
                    FROM sys.indexes
                    WHERE type_desc IN ('CLUSTERED COLUMNSTORE', 'NONCLUSTERED COLUMNSTORE')
            DECLARE @s SYSNAME, @o SYSNAME, @i SYSNAME
            OPEN c
            FETCH NEXT FROM c INTO @s, @o, @i
            WHILE @@FETCH_STATUS = 0
            BEGIN
                DECLARE @showStats NVARCHAR(MAX) = N'DBCC SHOW_STATISTICS(""' + QUOTENAME(@s) + '.' + QUOTENAME(@o) + '"", ' + QUOTENAME(@i) + ') WITH stats_stream'
                INSERT @dbcc EXEC sp_executesql @showStats
                INSERT @out SELECT @s, @o, @i, stats_stream, rows, pages FROM @dbcc
                DELETE @dbcc
                FETCH NEXT FROM c INTO @s, @o, @i
            END
            CLOSE c
            DEALLOCATE c

            DECLARE @sql NVARCHAR(MAX);
            DECLARE @id INT;
            SELECT TOP 1 @id=id,@sql=
            'UPDATE STATISTICS ' + QUOTENAME(s) + '.' + QUOTENAME(o)  + '(' + QUOTENAME(i)
            + ') WITH stats_stream = ' + CONVERT(NVARCHAR(MAX), stats_stream, 1)
            + ', rowcount = ' + CONVERT(NVARCHAR(MAX), rows) + ', pagecount = '  + CONVERT(NVARCHAR(MAX), pages)
            FROM @out

            WHILE (@@ROWCOUNT <> 0)
            BEGIN
                EXEC sp_executesql @sql
                DELETE @out WHERE id = @id
                SELECT TOP 1 @id=id,@sql=
                'UPDATE STATISTICS ' + QUOTENAME(s) + '.' + QUOTENAME(o)  + '(' + QUOTENAME(i)
                + ') WITH stats_stream = ' + CONVERT(NVARCHAR(MAX), stats_stream, 1)
                + ', rowcount = ' + CONVERT(NVARCHAR(MAX), rows) + ', pagecount = '  + CONVERT(NVARCHAR(MAX), pages)
                FROM @out
            END
        "

        $noStats = "NO_STATISTICS"
        $noQueryStore = "NO_QUERYSTORE"
        if ( (Test-Bound -ParameterName 'ExcludeStatistics') -or (Test-Bound -ParameterName 'ExcludeQueryStore') ) {
            $sqlWith = ""
            if ($ExcludeStatistics) {
                $sqlWith = "WITH $noStats"
            }
            if ($ExcludeQueryStore) {
                $sqlWith = "WITH $noQueryStore"
            }
            if ($ExcludeStatistics -and $ExcludeQueryStore) {
                $sqlWith = "WITH $noStats,$noQueryStore"
            }
        }
        
        $sql2012min = [version]"11.0.7001.0" # SQL 2012 SP4
        $sql2014min = [version]"12.0.5000.0" # SQL 2014 SP2
        $sql2014CuMin = [version]"12.0.5538" # SQL 2014 SP2 + CU3
        $sql2016min = [version]"13.0.4001.0" # SQL 2016 SP1
    }
    process {
        if (Test-FunctionInterrupt) { return }
        
        if ($SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        }
        
        foreach ($db in $InputObject) {
            $server = $db.Parent

            if ($server.VersionMajor -eq 11 -and $server.Version -lt $sql2012min) {
                Stop-Function -Message "Unsupported version for $instance. SQL Server 2012 SP4 and above required." -Target $server -Continue
            }

            if ($server.VersionMajor -eq 12 -and $server.Version -lt $sql2014min) {
                Stop-Function -Message "Unsupported version for $instance. SQL Server 2014 SP2 and above required." -Target $server -Continue
            }

            if ($server.VersionMajor -eq 13 -and $server.Version -lt $sql2016min) {
                Stop-Function -Message "Unsupported version for $instance. SQL Server 2016 SP1 and above required." -Target $server -Continue
            }

            if (Test-Bound -ParameterName 'ExcludeStatistics') {
                if ($server.VersionMajor -eq 12 -and $server.Version -lt $sql2014CuMin) {
                    Stop-Function -Message "Unsupported version for $instance. SQL Server 2014 SP1 + CU3 and above required." -Target $server -Continue
                }
                if ($server.VersionMajor -eq 13 -and $server.Version -lt $sql2016min) {
                    Stop-Function -Message "Unsupported version for $instance. SQL Server 2016 SP1 and above required." -Target $server -Continue
                }
            }

            if (Test-Bound -ParameterName 'ExcludeQueryStore') {
                if ($server.VersionMajor -lt 13 - ($server.VersionMajor -eq 13 -and $server.Version -lt $sql2016min)) {
                    Stop-Function -Message "Unsupported version for $instance. SQL Server 2016 SP1 and above required." -Target $server -Continue
                }
            }

            if ($db.IsSystemObject) {
                Stop-Function -Message "Only user databases are supported" -Target $instance -Continue
            }

            if ( (Test-Bound -ParameterName 'UpdateStatistics') -and (Test-Bound -ParameterName 'ExcludeStatistics' -Not) ) {
                if ($Pscmdlet.ShouldProcess($instance, "Update statistics in $($db.Name)")) {
                    try {
                        Write-Message -Level Verbose -Message "Updating statistics"
                        $null = $db.Query($sqlStats)
                    } catch {
                        Stop-Function -Message "Failure" -ErrorRecord $_ -Target $server -Continue
                    }
                }
            }

            $dbName = $db.Name

            foreach ($clonedb in $CloneDatabase) {
                Write-Message -Level Verbose -Message "Cloning $clonedb from $db"
                if ($server.Databases[$clonedb]) {
                    Stop-Function -Message "Destination clone database $clonedb already exists" -Target $instance -Continue
                } else {
                    if ($Pscmdlet.ShouldProcess($instance, "Execute DBCC CloneDatabase($dbName, $clonedb)")) {
                        try {
                            $sql = "DBCC CLONEDATABASE('$dbName','$clonedb') $sqlWith"
                            Write-Message -Level Debug -Message "Sql Statement: $sql"
                            $null = $db.Query($sql)
                            Get-DbaDatabase -SqlInstance $server -Database $clonedb
                        } catch {
                            Stop-Function -Message "Failure" -ErrorRecord $_ -Target $server -Continue
                        }
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Invoke-DbaDatabaseClone
    }
}
tools\dbatools\functions\Invoke-DbaDbDataMasking.ps1
function Invoke-DbaDbDataMasking {
    <#
    .SYNOPSIS
        Masks data by using randomized values determined by a configuration file and a randomizer framework

    .DESCRIPTION
        TMasks data by using randomized values determined by a configuration file and a randomizer framework

        It will use a configuration file that can be made manually or generated using New-DbaDbMaskingConfig

        Note that the following column and data types are not currently supported:
        Identity
        ForeignKey
        Computed
        Hierarchyid
        Geography
        Geometry
        Xml

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Databases to process through

    .PARAMETER Table
        Tables to process. By default all the tables will be processed

    .PARAMETER Column
        Columns to process. By default all the columns will be processed

    .PARAMETER FilePath
        Configuration file that contains the which tables and columns need to be masked

    .PARAMETER Query
        If you would like to mask only a subset of a table, use the Query parameter, otherwise all data will be masked.

    .PARAMETER Locale
        Set the local to enable certain settings in the masking

    .PARAMETER CharacterString
        The characters to use in string data. 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' by default

    .PARAMETER ExcludeTable
        Exclude specific tables even if it's listed in the config file.

    .PARAMETER ExcludeColumn
        Exclude specific columns even if it's listed in the config file.

    .PARAMETER MaxValue
        Force a max length of strings instead of relying on datatype maxes. Note if a string datatype has a lower MaxValue, that will be used instead.

        Useful for adhoc updates and testing, otherwise, the config file should be used.

    .PARAMETER ModulusFactor
        Calculating the next nullable by using the remainder from the modulus. Default is every 10.

    .PARAMETER ExactLength
        Mask string values to the same length. So 'Tate' will be replaced with 4 random characters.

    .PARAMETER Force
        Forcefully execute commands when needed

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DataMasking, Database
        Author: Sander Stad (@sqlstad, sqlstad.nl) | Chrissy LeMaire (@cl, netnerds.net)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaDbDataMasking

    .EXAMPLE
        Invoke-DbaDbDataMasking -SqlInstance SQLDB2 -Database DB1 -FilePath C:\Temp\sqldb1.db1.tables.json

        Apply the data masking configuration from the file "sqldb1.db1.tables.json" to the db1 database on sqldb2. Prompt for confirmation for each table.

    .EXAMPLE
        Get-ChildItem -Path C:\Temp\sqldb1.db1.tables.json | Invoke-DbaDbDataMasking -SqlInstance SQLDB2 -Database DB1 -Confirm:$false

        Apply the data masking configuration from the file "sqldb1.db1.tables.json" to the db1 database on sqldb2. Do not prompt for confirmation.

    .EXAMPLE
        New-DbaDbMaskingConfig -SqlInstance SQLDB1 -Database DB1 -Path C:\Temp\clone -OutVariable file
        $file | Invoke-DbaDbDataMasking -SqlInstance SQLDB2 -Database DB1 -Confirm:$false

        Create the data masking configuration file "sqldb1.db1.tables.json", then use it to mask the db1 database on sqldb2. Do not prompt for confirmation.

    .EXAMPLE
        Get-ChildItem -Path C:\Temp\sqldb1.db1.tables.json | Invoke-DbaDbDataMasking -SqlInstance SQLDB2, sqldb3 -Database DB1 -Confirm:$false

        See what would happen if you the data masking configuration from the file "sqldb1.db1.tables.json" to the db1 database on sqldb2 and sqldb3. Do not prompt for confirmation.

    #>
    [CmdLetBinding(SupportsShouldProcess, ConfirmImpact = "High")]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias('Path', 'FullName')]
        [object]$FilePath,
        [string]$Locale = 'en',
        [string]$CharacterString = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
        [string[]]$Table,
        [string[]]$Column,
        [string[]]$ExcludeTable,
        [string[]]$ExcludeColumn,
        [string]$Query,
        [int]$MaxValue,
        [int]$ModulusFactor = 10,
        [switch]$ExactLength,
        [switch]$EnableException
    )
    begin {
        # Create the faker objects
        Add-Type -Path (Resolve-Path -Path "$script:PSModuleRoot\bin\datamasking\Bogus.dll")
        $faker = New-Object Bogus.Faker($Locale)
    }

    process {
        if (Test-FunctionInterrupt) {
            return
        }

        if ($FilePath.ToString().StartsWith('http')) {
            $tables = Invoke-RestMethod -Uri $FilePath
        } else {
            # Check if the destination is accessible
            if (-not (Test-Path -Path $FilePath)) {
                Stop-Function -Message "Could not find masking config file $FilePath" -Target $FilePath
                return
            }

            # Get all the items that should be processed
            try {
                $tables = Get-Content -Path $FilePath -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
            } catch {
                Stop-Function -Message "Could not parse masking config file" -ErrorRecord $_ -Target $FilePath
                return
            }
        }

        foreach ($tabletest in $tables.Tables) {
            if ($Table -and $tabletest.Name -notin $Table) {
                continue
            }
            foreach ($columntest in $tabletest.Columns) {
                if ($columntest.ColumnType -in 'hierarchyid', 'geography', 'xml', 'geometry' -and $columntest.Name -notin $Column) {
                    Stop-Function -Message "$($columntest.ColumnType) is not supported, please remove the column $($columntest.Name) from the $($tabletest.Name) table" -Target $tables
                }
            }
        }

        if (Test-FunctionInterrupt) {
            return
        }

        $dictionary = @{}

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($Database) {
                $dbs = Get-DbaDatabase -SqlInstance $server -Database $Database
            } else {
                $dbs = Get-DbaDatabase -SqlInstance $server -Database $tables.Name
            }

            $sqlconn = $server.ConnectionContext.SqlConnectionObject.PsObject.Copy()
            $sqlconn.Open()

            foreach ($db in $dbs) {
                $stepcounter = $nullmod = 0
                foreach ($tableobject in $tables.Tables) {
                    if ($tableobject.Name -in $ExcludeTable -or ($Table -and $tableobject.Name -notin $Table)) {
                        Write-Message -Level Verbose -Message "Skipping $($tableobject.Name) because it is explicitly excluded"
                        continue
                    }

                    if ($tableobject.Name -notin $db.Tables.Name) {
                        Stop-Function -Message "Table $($tableobject.Name) is not present in $db" -Target $db -Continue
                    }
                    try {
                        if (-not (Test-Bound -ParameterName Query)) {
                            $query = "SELECT * FROM [$($tableobject.Schema)].[$($tableobject.Name)]"
                        }
                        $data = $server.Databases[$($db.Name)].Query($query) | ConvertTo-DbaDataTable
                    } catch {
                        Stop-Function -Message "Failure retrieving the data from table $($tableobject.Name)" -Target $Database -ErrorRecord $_ -Continue
                    }

                    $sqlconn.ChangeDatabase($db.Name)
                    
                    $deterministicColumns = $tables.Tables.Columns | Where-Object Deterministic -eq $true
                    $tablecolumns = $tableobject.Columns

                    if ($Column) {
                        $tablecolumns = $tablecolumns | Where-Object Name -in $Column
                    }

                    if ($ExcludeColumn) {
                        $tablecolumns = $tablecolumns | Where-Object Name -notin $ExcludeColumn
                    }

                    if (-not $tablecolumns) {
                        Write-Message -Level Verbose "No columns to process in $($db.Name).$($tableobject.Schema).$($tableobject.Name), moving on"
                        continue
                    }

                    if ($Pscmdlet.ShouldProcess($instance, "Masking $($tablecolumns.Name -join ', ') in $($data.Rows.Count) rows in $($db.Name).$($tableobject.Schema).$($tableobject.Name)")) {
                        $transaction = $sqlconn.BeginTransaction()
                        $elapsed = [System.Diagnostics.Stopwatch]::StartNew()
                        Write-ProgressHelper -StepNumber ($stepcounter++) -TotalSteps $tables.Tables.Count -Activity "Masking data" -Message "Updating $($data.Rows.Count) rows in $($tableobject.Schema).$($tableobject.Name) in $($db.Name) on $instance"

                        # Loop through each of the rows and change them
                        foreach ($row in $data.Rows) {
                            $updates = $wheres = @()

                            foreach ($columnobject in $tablecolumns) {
                                if ($columnobject.Nullable -and (($nullmod++) % $ModulusFactor -eq 0)) {
                                    $newValue = $null
                                } else {
                                    # make sure max is good
                                    if ($MaxValue) {
                                        if ($columnobject.MaxValue -le $MaxValue) {
                                            $max = $columnobject.MaxValue
                                        } else {
                                            $max = $MaxValue
                                        }
                                    } else {
                                        $max = $columnobject.MaxValue
                                    }

                                    if (-not $columnobject.MaxValue -and -not (Test-Bound -ParameterName MaxValue)) {
                                        $max = 10
                                    }

                                    if ($columnobject.CharacterString) {
                                        $charstring = $columnobject.CharacterString
                                    } else {
                                        $charstring = $CharacterString
                                    }

                                    # make sure min is good
                                    if ($columnobject.MinValue) {
                                        $min = $columnobject.MinValue
                                    } else {
                                        if ($columnobject.CharacterString) {
                                            $min = 1
                                        } else {
                                            $min = 0
                                        }
                                    }

                                    if (($columnobject.MinValue -or $columnobject.MaxValue) -and ($columnobject.ColumnType -match 'date')) {
                                        $nowmin = $columnobject.MinValue
                                        $nowmax = $columnobject.MaxValue
                                        if (-not $nowmin) {
                                            $nowmin = (Get-Date -Date $nowmax).AddDays(-365)
                                        }
                                        if (-not $nowmax) {
                                            $nowmax = (Get-Date -Date $nowmin).AddDays(365)
                                        }
                                    }

                                    try {
                                        $newValue = $null

                                        if ($columnobject.Deterministic -and ($row.$($columnobject.Name) -in $dictionary.Keys)) {
                                            $newValue = $dictionary.$($row.$($columnobject.Name))
                                        }

                                        if (-not $newValue) {
                                            $newValue = switch ($columnobject.ColumnType) {
                                                {
                                                    $psitem -in 'bit', 'bool'
                                                } {
                                                    $faker.System.Random.Bool()
                                                }
                                                {
                                                    $psitem -match 'date'
                                                } {
                                                    if ($columnobject.MinValue -or $columnobject.MaxValue) {
                                                        ($faker.Date.Between($nowmin, $nowmax)).ToString("yyyyMMdd")
                                                    } else {
                                                        ($faker.Date.Past()).ToString("yyyyMMdd")
                                                    }
                                                }
                                                {
                                                    $psitem -match 'int'
                                                } {
                                                    if ($columnobject.MinValue -or $columnobject.MaxValue) {
                                                        $faker.System.Random.Int($columnobject.MinValue, $columnobject.MaxValue)
                                                    } else {
                                                        $faker.System.Random.Int(0, $max)
                                                    }
                                                }
                                                'money' {
                                                    if ($columnobject.MinValue -or $columnobject.MaxValue) {
                                                        $faker.Finance.Amount($columnobject.MinValue, $columnobject.MaxValue)
                                                    } else {
                                                        $faker.Finance.Amount(0, $max)
                                                    }
                                                }
                                                'time' {
                                                    ($faker.Date.Past()).ToString("h:mm tt zzz")
                                                }
                                                'uniqueidentifier' {
                                                    $faker.System.Random.Guid().Guid
                                                }
                                                'userdefineddatatype' {
                                                    if ($columnobject.MaxValue -eq 1) {
                                                        $faker.System.Random.Bool()
                                                    } else {
                                                        $null
                                                    }
                                                }
                                                default {
                                                    $null
                                                }
                                            }
                                        }

                                        if (-not $newValue) {
                                            $newValue = switch ($columnobject.SubType.ToLower()) {
                                                'number' {
                                                    $faker.$($columnobject.MaskingType).$($columnobject.SubType)($columnobject.MaxValue)
                                                }
                                                {
                                                    $psitem -in 'bit', 'bool'
                                                } {
                                                    $faker.System.Random.Bool()
                                                }
                                                {
                                                    $psitem -in 'date', 'datetime', 'datetime2', 'smalldatetime'
                                                } {
                                                    if ($columnobject.MinValue -or $columnobject.MaxValue) {
                                                        ($faker.Date.Between($nowmin, $nowmax)).ToString("yyyyMMdd")
                                                    } else {
                                                        ($faker.Date.Past()).ToString("yyyyMMdd")
                                                    }
                                                }
                                                'shuffle' {
                                                    ($row.($columnobject.Name) -split '' | Sort-Object {
                                                            Get-Random
                                                        }) -join ''
                                                }
                                                'string' {
                                                    if ($max -eq -1) {
                                                        $max = 1024
                                                    }

                                                    if ($columnobject.SubType -eq "String" -and (Test-Bound -ParameterName ExactLength)) {
                                                        $max = ($row.$($columnobject.Name)).Length
                                                    }

                                                    if ($columnobject.ColumnType -eq 'xml') {
                                                        $null
                                                    } else {
                                                        $faker.$($columnobject.MaskingType).String2($max, $charstring)
                                                    }
                                                }
                                                default {
                                                    $null
                                                }
                                            }
                                        }

                                        if (-not $newValue) {
                                            $newValue = switch ($columnobject.MaskingType.ToLower()) {
                                                {
                                                    $psitem -in 'bit', 'bool'
                                                } {
                                                    $faker.System.Random.Bool()
                                                }
                                                {
                                                    $psitem -in 'name', 'address', 'finance'
                                                } {
                                                    $faker.$($columnobject.MaskingType).$($columnobject.SubType)()
                                                }
                                                default {
                                                    if ($max -eq -1) {
                                                        $max = 1024
                                                    }
                                                    if ((Test-Bound -ParameterName ExactLength)) {
                                                        $max = ($row.$($columnobject.Name)).ToString().Length
                                                    }
                                                    if ($max -eq 1) {
                                                        $faker.System.Random.Bool()
                                                    } else {
                                                        try {
                                                            $faker.$($columnobject.MaskingType).$($columnobject.SubType)()
                                                        } catch {
                                                            $faker.Random.String2($max, $charstring)
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    } catch {
                                        Stop-Function -Message "Failure" -Target $faker -Continue -ErrorRecord $_
                                    }
                                }

                                if ($columnobject.ColumnType -eq 'xml') {
                                    # nothing, unsure how i'll handle this
                                } elseif ($columnobject.ColumnType -in 'uniqueidentifier') {
                                    if ($null -eq $newValue -and $columnobject.Nullable) {
                                        $updates += "[$($columnobject.Name)] = NULL"
                                    } else {
                                        $updates += "[$($columnobject.Name)] = '$newValue'"
                                    }

                                } elseif ($columnobject.ColumnType -match 'int') {
                                    if ($null -eq $newValue -and $columnobject.Nullable) {
                                        $updates += "[$($columnobject.Name)] = NULL"
                                    } else {
                                        $updates += "[$($columnobject.Name)] = $newValue"
                                    }
                                } else {
                                    if ($null -eq $newValue -and $columnobject.Nullable) {
                                        $updates += "[$($columnobject.Name)] = NULL"
                                    } else {
                                        $newValue = ($newValue).Tostring().Replace("'", "''")
                                        $updates += "[$($columnobject.Name)] = '$newValue'"
                                    }
                                }

                                if ($columnobject.ColumnType -notin 'xml', 'geography', 'geometry') {
                                    if (($row.$($columnobject.Name)).GetType().Name -match 'DBNull') {
                                        $wheres += "[$($columnobject.Name)] IS NULL"
                                    } else {
                                        $oldValue = ($row.$($columnobject.Name)).Tostring().Replace("'", "''")
                                        $wheres += "[$($columnobject.Name)] = '$oldValue'"
                                    }
                                }

                                if ($columnobject.Deterministic -and ($row.$($columnobject.Name) -notin $dictionary.Keys)) {
                                    $dictionary.Add($row.$($columnobject.Name), $newValue)
                                }
                            }

                            $updatequery = "UPDATE [$($tableobject.Schema)].[$($tableobject.Name)] SET $($updates -join ', ') WHERE $($wheres -join ' AND ')"

                            try {
                                $sqlcmd = New-Object System.Data.SqlClient.SqlCommand($updatequery, $sqlconn, $transaction)
                                $null = $sqlcmd.ExecuteNonQuery()
                            } catch {
                                Write-Message -Level VeryVerbose -Message "$updatequery"
                                $errormessage = $_.Exception.Message.ToString()
                                Stop-Function -Message "Error updating $($tableobject.Schema).$($tableobject.Name): $errormessage" -Target $updatequery -Continue -ErrorRecord $_
                            }
                        }
                        try {
                            $null = $transaction.Commit()
                            [pscustomobject]@{
                                ComputerName = $db.Parent.ComputerName
                                InstanceName = $db.Parent.ServiceName
                                SqlInstance  = $db.Parent.DomainInstanceName
                                Database     = $db.Name
                                Schema       = $tableobject.Schema
                                Table        = $tableobject.Name
                                Columns      = $tableobject.Columns.Name
                                Rows         = $($data.Rows.Count)
                                Elapsed      = [prettytimespan]$elapsed.Elapsed
                                Status       = "Masked"
                            }
                        } catch {
                            Stop-Function -Message "Error updating $($tableobject.Schema).$($tableobject.Name)" -Target $updatequery -Continue -ErrorRecord $_
                        }
                    }
                }
            }
            try {
                $sqlconn.Close()
            } catch {
                Stop-Function -Message "Failure" -Continue -ErrorRecord $_
            }
        }
    }
}
tools\dbatools\functions\Invoke-DbaDbDbccCheckConstraint.ps1
function Invoke-DbaDbDbccCheckConstraint {
    <#
    .SYNOPSIS
        Execution of Database Console Command DBCC CHECKCONSTRAINTS

    .DESCRIPTION
        Executes the command DBCC CHECKCONSTRAINTS and returns results

        Reports and corrects pages and row count inaccuracies in the catalog views.
        These inaccuracies may cause incorrect space usage reports returned by the sp_spaceused system stored procedure.

        Read more:
            - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkconstraints-transact-sql

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER Object
        The table or constraint to be checked.
        When table_name or table_id is specified, all enabled constraints on that table are checked.
        When constraint_name or constraint_id is specified, only that constraint is checked.
        If neither a table identifier nor a constraint identifier is specified, all enabled constraints on all tables in the current database are checked.

    .PARAMETER AllConstraints
        Checks all enabled and disabled constraints on the table if the table name is specified or if all tables are checked;
        Otherwise, checks only the enabled constraint.
        Has no effect when a constraint is specified

    .PARAMETER AllErrorMessages
        Returns all rows that violate constraints in the table that is checked.
        The default is the first 200 rows.

    .PARAMETER NoInformationalMessages
        Suppresses all informational messages.

    .PARAMETER WhatIf
        Shows what would happen if the cmdlet runs. The cmdlet is not run.

    .PARAMETER Confirm
        Prompts you for confirmation before running the cmdlet.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DBCC
        Author: Patrick Flynn (@sqllensman)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaDbDbccCheckConstraint

    .EXAMPLE
        PS C:\> Invoke-DbaDbDbccCheckConstraint -SqlInstance SqlServer2017

        Runs the command DBCC CHECKCONSTRAINTS to check all enabled constraints on all tables for all databases for the instance SqlServer2017. Connect using Windows Authentication

    .EXAMPLE
        PS C:\> Invoke-DbaDbDbccCheckConstraint -SqlInstance SqlServer2017 -Database CurrentDB

        Connect to instance SqlServer2017 using Windows Authentication and run the command DBCC CHECKCONSTRAINTS to check all enabled constraints on all tables in the CurrentDB database.

    .EXAMPLE
        PS C:\> Invoke-DbaDbDbccCheckConstraint -SqlInstance SqlServer2017 -Database CurrentDB -Object Sometable

        Connects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC CHECKCONSTRAINTS(SometableId) to check all enabled constraints in the table.

    .EXAMPLE
        PS C:\> Invoke-DbaDbDbccCheckConstraint -SqlInstance SqlServer2017 -Database CurrentDB -Object ConstraintId

        Connects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC CHECKCONSTRAINTS(ConstraintId) to check the constraint with constraint_id = ConstraintId.

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> Invoke-DbaDbDbccCheckConstraint -SqlInstance SqlServer2017 -SqlCredential $cred -Database CurrentDB -Object TableId -AllConstraints -AllErrorMessages -NoInformationalMessages

        Connects to CurrentDB on instance SqlServer2017 using sqladmin credential and runs the command DBCC CHECKCONSTRAINTS(TableId) WITH ALL_CONSTRAINTS, ALL_ERRORMSGS, NO_INFOMSGS to check all enabled and disabled constraints on the table with able_id = TableId. Returns all rows that violate constraints.

    .EXAMPLE
        PS C:\> 'Sql1','Sql2/sqlexpress' | Invoke-DbaDbDbccCheckConstraint -WhatIf

        Displays what will happen if command DBCC CHECKCONSTRAINTS is called against all databses on Sql1 and Sql2/sqlexpress

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [string]$Object,
        [switch]$AllConstraints,
        [switch]$AllErrorMessages,
        [switch]$NoInformationalMessages,
        [switch]$EnableException
    )
    begin {
        $withCount = 0
        $stringBuilder = New-Object System.Text.StringBuilder
        $null = $stringBuilder.Append("DBCC CHECKCONSTRAINTS(#options#)")
        if (Test-Bound -ParameterName AllConstraints) {
            $null = $stringBuilder.Append(" WITH ALL_CONSTRAINTS")
            $withCount++
        }
        if (Test-Bound -ParameterName AllErrorMessages) {
            if ($withCount -eq 0) {
                $null = $stringBuilder.Append(" WITH ALL_ERRORMSGS")
            } else {
                $null = $stringBuilder.Append(", ALL_ERRORMSGS")
            }
            $withCount++
        }
        if (Test-Bound -ParameterName NoInformationalMessages) {
            if ($withCount -eq 0) {
                $null = $stringBuilder.Append(" WITH NO_INFOMSGS")
            } else {
                $null = $stringBuilder.Append(", NO_INFOMSGS")
            }
        }

    }
    process {
        foreach ($instance in $SqlInstance) {
            Write-Message -Message "Attempting Connection to $instance" -Level Verbose
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $dbs = $server.Databases

            if ($Database) {
                $dbs = $dbs | Where-Object Name -In $Database
            }

            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Processing $db on $instance"

                if ($db.IsAccessible -eq $false) {
                    Stop-Function -Message "The database $db is not accessible. Skipping." -Continue
                }

                try {
                    $query = $StringBuilder.ToString()
                    if (Test-Bound -ParameterName Object) {
                        if ($object -match '^\d+$') {
                            $query = $query.Replace('#options#', "$Object")
                        } else {
                            $query = $query.Replace('#options#', "'$Object'")
                        }
                    } else {
                        $query = $query.Replace('(#options#)', "")
                    }

                    if ($Pscmdlet.ShouldProcess($server.Name, "Execute the command $query against $instance")) {
                        Write-Message -Message "Query to run: $query" -Level Verbose
                        $results = $server | Invoke-DbaQuery  -Query $query -Database $db.Name -MessagesToOutput
                    }
                } catch {
                    Stop-Function -Message "Error capturing data on $db" -Target $instance -ErrorRecord $_ -Exception $_.Exception -Continue
                }

                if ($Pscmdlet.ShouldProcess("console", "Outputting object")) {
                    $output = $null
                    if (($null -eq $results) -or ($results.GetType().Name -eq 'String') ) {
                        [PSCustomObject]@{
                            ComputerName = $server.ComputerName
                            InstanceName = $server.ServiceName
                            SqlInstance  = $server.DomainInstanceName
                            Database     = $db.Name
                            Cmd          = $query.ToString()
                            Output       = $results
                            Table        = $null
                            Constraint   = $null
                            Where        = $null
                        }
                    } elseif (($results.GetType().Name -eq 'Object[]') -or ($results.GetType().Name -eq 'DataRow')) {
                        foreach ($row in $results) {
                            if ($row.GetType().Name -eq 'String') {
                                $output = $row.ToString()
                            } else {
                                [PSCustomObject]@{
                                    ComputerName = $server.ComputerName
                                    InstanceName = $server.ServiceName
                                    SqlInstance  = $server.DomainInstanceName
                                    Database     = $db.Name
                                    Cmd          = $query.ToString()
                                    Output       = $output
                                    Table        = $row[0]
                                    Constraint   = $row[1]
                                    Where        = $row[2]

                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Invoke-DbaDbDbccCleanTable.ps1
function Invoke-DbaDbDbccCleanTable {
    <#
    .SYNOPSIS
        Execution of Database Console Command DBCC CLEANTABLE

    .DESCRIPTION
        Executes the command DBCC CLEANTABLE against defined objects and returns results

        Reclaims space from dropped variable-length columns in tables or indexed views

        Read more:
            - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-cleantable-transact-sql

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process. If unspecified, all databases will be processed.

    .PARAMETER Object
        The table(s) or indexed view(s) to be cleaned.

    .PARAMETER BatchSize
        Is the number of rows processed per transaction.
        If not specified, or if 0 is specified, the statement processes the whole table in one transaction.

    .PARAMETER NoInformationalMessages
        Suppresses all informational messages.

    .PARAMETER WhatIf
        Shows what would happen if the cmdlet runs. The cmdlet is not run.

    .PARAMETER Confirm
        Prompts you for confirmation before running the cmdlet.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DBCC
        Author: Patrick Flynn (@sqllensman)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaDbDbccCleanTable

    .EXAMPLE
        PS C:\> Invoke-DbaDbDbccCleanTable -SqlInstance SqlServer2017 -Database CurrentDB -Object 'dbo.SomeTable'

        Connects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC CLEANTABLE('CurrentDB', 'dbo.SomeTable') to reclaim space after variable-length columns have been dropped.

    .EXAMPLE
        PS C:\> Invoke-DbaDbDbccCleanTable -SqlInstance SqlServer2017 -Database CurrentDB -Object 34636372 -BatchSize 5000

        Connects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC CLEANTABLE('CurrentDB', 34636372, 5000) to reclaim space from table with Table_Id = 34636372 after variable-length columns have been dropped.

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> Invoke-DbaDbDbccCleanTable -SqlInstance SqlServer2017 -SqlCredential $cred -Database CurrentDB -Object 'dbo.SomeTable'  -NoInformationalMessages

        Connects to CurrentDB on instance SqlServer2017 using sqladmin credential and runs the command DBCC CLEANTABLE('CurrentDB', 'dbo.SomeTable') WITH NO_INFOMSGS to reclaim space after variable-length columns have been dropped.

    .EXAMPLE
        PS C:\> 'Sql1','Sql2/sqlexpress' | Invoke-DbaDbDbccCleanTable -Object 'dbo.SomeTable' -BatchSize 5000

        Runs the command DBCC CLEANTABLE('DatabaseName', 'dbo.SomeTable', 5000) against all databses on Sql1 and Sql2/sqlexpress

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [string[]]$Object,
        [int]$BatchSize,
        [switch]$NoInformationalMessages,
        [switch]$EnableException
    )
    begin {
        $stringBuilder = New-Object System.Text.StringBuilder
        $null = $stringBuilder.Append("DBCC CLEANTABLE(#options#)")
        if (Test-Bound -ParameterName NoInformationalMessages) {
            $null = $stringBuilder.Append(" WITH NO_INFOMSGS")
        }
    }
    process {
        if (Test-Bound -Not -ParameterName Object) {
            Stop-Function -Message "You must specify a table or indexed view to execute against using -Object"
            return
        }
        foreach ($instance in $SqlInstance) {
            Write-Message -Message "Attempting Connection to $instance" -Level Verbose
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $dbs = $server.Databases

            if ($Database) {
                $dbs = $dbs | Where-Object Name -In $Database
            }

            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Processing $db on $instance"

                if ($db.IsAccessible -eq $false) {
                    Stop-Function -Message "The database $db is not accessible. Skipping." -Continue
                }

                foreach ($obj in $Object) {
                    try {
                        $query = $StringBuilder.ToString()
                        $options = New-Object System.Text.StringBuilder
                        if ($obj -match '^\d+$') {
                            $null = $options.Append("'$($db.Name)', $($obj)")
                        } else {
                            $null = $options.Append("'$($db.Name)', '$($obj)'")
                        }
                        if (Test-Bound -ParameterName BatchSize) {
                            $null = $options.Append(", $($BatchSize)")
                        }

                        $query = $query.Replace('#options#', "$($options.ToString())")
                        Write-Message -Message "Query to run: $query" -Level Verbose

                        if ($Pscmdlet.ShouldProcess($server.Name, "Execute the command $query against $instance")) {
                            Write-Message -Message "Query to run: $query" -Level Verbose
                            $results = $server | Invoke-DbaQuery  -Query $query -Database $db.Name -MessagesToOutput
                        }
                    } catch {
                        Stop-Function -Message "Error running  $query against $db" -Target $instance -ErrorRecord $_ -Exception $_.Exception -Continue
                    }
                    if ($Pscmdlet.ShouldProcess("console", "Outputting object")) {
                        if (($null -eq $results) -or ($results.GetType().Name -eq 'String') ) {
                            [PSCustomObject]@{
                                ComputerName = $server.ComputerName
                                InstanceName = $server.ServiceName
                                SqlInstance  = $server.DomainInstanceName
                                Database     = $db.Name
                                Object       = $obj
                                Cmd          = $query.ToString()
                                Output       = $results
                            }
                        }
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Invoke-DbaDbDbccUpdateUsage.ps1
function Invoke-DbaDbDbccUpdateUsage {
    <#
    .SYNOPSIS
        Execution of Database Console Command DBCC UPDATEUSAGE

    .DESCRIPTION
        Executes the command DBCC UPDATEUSAGE and returns results

        Reports and corrects pages and row count inaccuracies in the catalog views.
        These inaccuracies may cause incorrect space usage reports returned by the sp_spaceused system stored procedure.

        Read more:
            - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-updateusage-transact-sql

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process. If unspecified, all databases will be processed.
        The Name or Id of a database can be specified
        Database names must comply with the rules for identifiers.

    .PARAMETER Table
        The table or indexed view to process.
        Table and view names must comply with the rules for identifiers
        The Id of Table or View can be specified
        If not specified, all tables or indexed views will be processed

    .PARAMETER Index
        The Index to process.
        The Id of Index can be specified
        If not specified, all indexes for the specified table or view will be processed.

    .PARAMETER NoInformationalMessages
        Suppresses all informational messages.

    .PARAMETER CountRows
        Specifies that the row count column is updated with the current count of the number of rows in the table or view.

    .PARAMETER WhatIf
        Shows what would happen if the cmdlet runs. The cmdlet is not run.

    .PARAMETER Confirm
        Prompts you for confirmation before running the cmdlet.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DBCC
        Author: Patrick Flynn (@sqllensman)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaDbDbccUpdateUsage

    .EXAMPLE
        PS C:\> Invoke-DbaDbDbccUpdateUsage -SqlInstance SqlServer2017

        Runs the command DBCC UPDATEUSAGE to update the page or row counts or both for all objects in all databases for the instance SqlServer2017. Connect using Windows Authentication

    .EXAMPLE
        PS C:\> Invoke-DbaDbDbccUpdateUsage -SqlInstance SqlServer2017 -Database CurrentDB

        Runs the command DBCC UPDATEUSAGE to update the page or row counts or both for all objects in the CurrentDB database for the instance SqlServer2017. Connect using Windows Authentication

    .EXAMPLE
        PS C:\> Invoke-DbaDbDbccUpdateUsage -SqlInstance SqlServer2017 -Database CurrentDB -Table Sometable

        Connects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC UPDATEUSAGE(SometableId) to update the page or row counts for all indexes in the table.

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> Invoke-DbaDbDbccUpdateUsage -SqlInstance SqlServer2017 -SqlCredential $cred -Database CurrentDB -Table 'SometableId -Index IndexName -NoInformationalMessages -CountRows

        Connects to CurrentDB on instance SqlServer2017 using sqladmin credential and runs the command DBCC UPDATEUSAGE(SometableId, IndexName) WITH NO_INFOMSGS, COUNT_ROWS to update the page or row counts.

    .EXAMPLE
        PS C:\> 'Sql1','Sql2/sqlexpress' | Invoke-DbaDbDbccUpdateUsage -WhatIf

        Displays what will happen if command DBCC UPDATEUSAGE is called against all databses on Sql1 and Sql2/sqlexpress

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [string]$Table,
        [string]$Index,
        [switch]$NoInformationalMessages,
        [switch]$CountRows,
        [switch]$EnableException
    )
    begin {

        $stringBuilder = New-Object System.Text.StringBuilder
        $null = $stringBuilder.Append("DBCC UPDATEUSAGE(#options#)")
        if (Test-Bound -ParameterName NoInformationalMessages) {
            $null = $stringBuilder.Append(" WITH NO_INFOMSGS")
            if (Test-Bound -ParameterName CountRows) {
                $null = $stringBuilder.Append(", COUNT_ROWS")
            }
        } else {
            if (Test-Bound -ParameterName CountRows) {
                $null = $stringBuilder.Append(" WITH COUNT_ROWS")
            }
        }
        Write-Message -Message "$($StringBuilder.ToString())" -Level Verbose

    }
    process {
        foreach ($instance in $SqlInstance) {
            Write-Message -Message "Attempting Connection to $instance" -Level Verbose
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $dbs = $server.Databases

            if (Test-Bound -ParameterName Database) {
                $dbs = $dbs | Where-Object {($_.Name -In $Database) -or ($_.ID -In $Database) }
            }

            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Processing $db on $instance"

                if ($db.IsAccessible -eq $false) {
                    Stop-Function -Message "The database $db is not accessible. Skipping." -Continue
                }

                try {
                    $query = $StringBuilder.ToString()
                    if (Test-Bound -ParameterName Table) {
                        if (Test-Bound -ParameterName Index) {
                            if ($Table -match '^\d+$') {
                                if ($Index -match '^\d+$') {
                                    $query = $query.Replace('#options#', "'$($db.name)', $Table, $Index")
                                } else {
                                    $query = $query.Replace('#options#', "'$($db.name)', $Table, '$Index'")
                                }
                            } else {
                                if ($Index -match '^\d+$') {
                                    $query = $query.Replace('#options#', "'$($db.name)', '$Table', $Index")
                                } else {
                                    $query = $query.Replace('#options#', "'$($db.name)', '$Table', '$Index'")
                                }
                            }
                        } else {
                            if ($Table -match '^\d+$') {
                                $query = $query.Replace('#options#', "'$($db.name)', $Table")
                            } else {
                                $query = $query.Replace('#options#', "'$($db.name)', '$Table'")
                            }
                        }
                    } else {
                        $query = $query.Replace('#options#', "'$($db.name)'")
                    }

                    if ($Pscmdlet.ShouldProcess($server.Name, "Execute the command $query against $instance")) {
                        Write-Message -Message "Query to run: $query" -Level Verbose
                        $results = $server | Invoke-DbaQuery  -Query $query -MessagesToOutput
                        Write-Message -Message "$($results.Count)" -Level Verbose
                    }
                } catch {
                    Stop-Function -Message "Error capturing data on $db" -Target $instance -ErrorRecord $_ -Exception $_.Exception -Continue
                }

                foreach ($row in $results) {
                    if ($Pscmdlet.ShouldProcess("console", "Outputting object")) {
                        [PSCustomObject]@{
                            ComputerName = $server.ComputerName
                            InstanceName = $server.ServiceName
                            SqlInstance  = $server.DomainInstanceName
                            Database     = $db.name
                            Cmd          = $query.ToString()
                            Output       = $results
                        }
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Invoke-DbaDbDecryptObject.ps1
function Invoke-DbaDbDecryptObject {
    <#
    .SYNOPSIS
        Invoke-DbaDbDecryptObject returns the decrypted version of an object

    .DESCRIPTION
        When a procedure or a function is created with encryption and you lost the code you're in trouble.
        You cannot alter the object or view the definition.
        With this command you can search for the object and decrypt the it.

        The command will output the results to the console.
        There is an option to export all the results to a folder creating .sql files.

        Make sure the instance allowed dedicated administrator connections (DAC).
        The binary versions of the objects can only be retrieved using a DAC connection.
        You can check the DAC connection with:
        'Get-DbaSpConfigure -SqlInstance [yourinstance] -ConfigName RemoteDacConnectionsEnabled'
        It should say 1 in the ConfiguredValue.

        To change the configurations you can use the Set-DbaSpConfigure command:
        'Set-DbaSpConfigure -SqlInstance [yourinstance] -ConfigName RemoteDacConnectionsEnabled -Value 1'
        In some cases you may need to reboot the instance.

    .PARAMETER SqlInstance
        The target SQL Server instance

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Database to look through for the object.

    .PARAMETER ObjectName
        The name of the object to search for in the database.

    .PARAMETER EncodingType
        The encoding that's used to decrypt and encrypt values.

    .PARAMETER ExportDestination
        Used for exporting the results to.
        The destiation will use the instance name, database name and object type i.e.: C:\temp\decrypt\SQLDB1\DB1\StoredProcedure

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Encryption, Decrypt, Database
        Author: Sander Stad (@sqlstad), sqlstad.nl

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaDbDecryptObject

    .EXAMPLE
        PS C:\> Invoke-DbaDbDecryptObject -SqlInstance SQLDB1 -Database DB1 -ObjectName Function1

        Decrypt object "Function1" in DB1 of instance SQLDB1 and output the data to the user.

    .EXAMPLE
        PS C:\> Invoke-DbaDbDecryptObject -SqlInstance SQLDB1 -Database DB1 -ObjectName Function1 -ExportDestination C:\temp\decrypt

        Decrypt object "Function1" in DB1 of instance SQLDB1 and output the data to the folder "C:\temp\decrypt".

    .EXAMPLE
        PS C:\> Invoke-DbaDbDecryptObject -SqlInstance SQLDB1 -Database DB1 -ExportDestination C:\temp\decrypt

        Decrypt all objects in DB1 of instance SQLDB1 and output the data to the folder "C:\temp\decrypt"

    .EXAMPLE
        PS C:\> Invoke-DbaDbDecryptObject -SqlInstance SQLDB1 -Database DB1 -ObjectName Function1, Function2

        Decrypt objects "Function1" and "Function2" and output the data to the user.

    .EXAMPLE
        PS C:\> "SQLDB1" | Invoke-DbaDbDecryptObject -Database DB1 -ObjectName Function1, Function2

        Decrypt objects "Function1" and "Function2" and output the data to the user using a pipeline for the instance.

    #>
    [CmdletBinding()]
    param(
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(Mandatory)]
        [object[]]$Database,
        [string[]]$ObjectName,
        [ValidateSet('ASCII', 'UTF8')]
        [string]$EncodingType = 'ASCII',
        [string]$ExportDestination,
        [switch]$EnableException
    )

    begin {

        function Invoke-DecryptData() {
            param(
                [parameter(Mandatory)]
                [byte[]]$Secret,
                [parameter(Mandatory)]
                [byte[]]$KnownPlain,
                [parameter(Mandatory)]
                [byte[]]$KnownSecret
            )

            # Declare pointers
            [int]$i = 0

            # Loop through each of the characters and apply an XOR to decrypt the data
            $result = $(

                # Loop through the byte string
                while ($i -lt $Secret.Length) {

                    # Compare the byte string character to the key character using XOR
                    if ($i -lt $Secret.Length) {
                        $Secret[$i] -bxor $KnownPlain[$i] -bxor $KnownSecret[$i]
                    }

                    # Increment the byte string indicator
                    $i += 2

                } # end while loop

            ) # end data value

            # Get the string value from the data
            $decryptedData = $Encoding.GetString($result)

            # Return the decrypted data
            return $decryptedData
        }

        # Create array list to hold the results
        $objectCollection = New-Object System.Collections.ArrayList

        # Set the encoding
        if ($EncodingType -eq 'ASCII') {
            $encoding = [System.Text.Encoding]::ASCII
        } elseif ($EncodingType -eq 'UTF8') {
            $encoding = [System.Text.Encoding]::UTF8
        }

        # Check the export parameter
        if ($ExportDestination -and -not (Test-Path $ExportDestination)) {
            try {
                # Create the new destination
                New-Item -Path $ExportDestination -ItemType Directory -Force | Out-Null
            } catch {
                Stop-Function -Message "Couldn't create destination folder $ExportDestination" -ErrorRecord $_ -Target $instance -Continue
            }
        }

    }

    process {

        if (Test-FunctionInterrupt) { return }

        # Loop through all the instances
        foreach ($instance in $SqlInstance) {

            # Check the configuration of the intance to see if the DAC is enabled
            $config = Get-DbaSpConfigure -SqlInstance $instance -ConfigName RemoteDacConnectionsEnabled
            if ($config.ConfiguredValue -ne 1) {
                Stop-Function -Message "DAC is not enabled for instance $instance.`nPlease use 'Set-DbaSpConfigure -SqlInstance $instance -ConfigName RemoteDacConnectionsEnabled -Value 1' to configure the instance to allow DAC connections" -Target $instance -Continue
            }

            # Try to connect to instance
            try {
                $server = New-Object Microsoft.SqlServer.Management.Smo.Server "ADMIN:$instance"
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            # Get all the databases that compare to the database parameter
            $databaseCollection = $server.Databases | Where-Object {$_.Name -in $Database}

            # Loop through each of databases
            foreach ($db in $databaseCollection) {
                # Get the objects
                if ($ObjectName) {
                    $storedProcedures = @($db.StoredProcedures | Where-Object {$_.Name -in $ObjectName -and $_.IsEncrypted -eq $true} | Select-Object Name, Schema, @{N = "ObjectType"; E = {'StoredProcedure'}}, @{N = "SubType"; E = {''}})
                    $functions = @($db.UserDefinedFunctions | Where-Object {$_.Name -in $ObjectName -and $_.IsEncrypted -eq $true} | Select-Object Name, Schema, @{N = "ObjectType"; E = {"UserDefinedFunction"}}, @{N = "SubType"; E = {$_.FunctionType.ToString().Trim()}})
                    $views = @($db.Views | Where-Object {$_.Name -in $ObjectName -and $_.IsEncrypted -eq $true} | Select-Object Name, Schema, @{N = "ObjectType"; E = {'View'}}, @{N = "SubType"; E = {''}})
                } else {
                    # Get all encrypted objects
                    $storedProcedures = @($db.StoredProcedures | Where-Object {$_.IsEncrypted -eq $true} | Select-Object Name, Schema, @{N = "ObjectType"; E = {'StoredProcedure'}}, @{N = "SubType"; E = {''}})
                    $functions = @($db.UserDefinedFunctions | Where-Object {$_.IsEncrypted -eq $true} | Select-Object Name, Schema, @{N = "ObjectType"; E = {"UserDefinedFunction"}}, @{N = "SubType"; E = {$_.FunctionType.ToString().Trim()}})
                    $views = @($db.Views | Where-Object {$_.IsEncrypted -eq $true} | Select-Object Name, Schema, @{N = "ObjectType"; E = {'View'}}, @{N = "SubType"; E = {''}})
                }

                <# Get all the objects
                $storedProcedures = @($db.StoredProcedures | Where-Object {$_.Name -in $ObjectName -and $_.IsEncrypted -eq $true} | Select-Object Name, Schema, @{N = "ObjectType"; E = {'StoredProcedure'}}, @{N = "SubType"; E = {''}})
                $functions = @($db.UserDefinedFunctions | Where-Object {$_.Name -in $ObjectName -and $_.IsEncrypted -eq $true} | Select-Object Name, Schema, @{N = "ObjectType"; E = {"UserDefinedFunction"}}, @{N = "SubType"; E = {$_.FunctionType.ToString().Trim()}})
                $views = @($db.Views | Where-Object {$_.Name -in $ObjectName -and $_.IsEncrypted -eq $true} | Select-Object Name, Schema, @{N = "ObjectType"; E = {'View'}}, @{N = "SubType"; E = {''}})
                #>

                # Check if there are any objects
                if ($storedProcedures.Count -ge 1) {
                    $objectCollection += $storedProcedures
                }
                if ($functions.Count -ge 1) {
                    $objectCollection += $functions
                }
                if ($views.Count -ge 1) {
                    $objectCollection += $views
                }

                # Loop through all the objects
                foreach ($object in $objectCollection) {

                    # Setup the query to get the secret
                    $querySecret = "SELECT imageval AS Value FROM sys.sysobjvalues WHERE objid = OBJECT_ID('$($object.Name)')"

                    # Get the result of the secret query
                    try {
                        $secret = $server.Databases[$db.Name].Query($querySecret)
                    } catch {
                        Stop-Function -Message "Couldn't retrieve secret from $instance" -ErrorRecord $_ -Target $instance -Continue
                    }

                    # Check if at least a value came back
                    if ($secret) {

                        # Setup a known plain command and get the binary version of it
                        switch ($object.ObjectType) {

                            'StoredProcedure' {
                                $queryKnownPlain = (" " * $secret.Value.Length) + "ALTER PROCEDURE $($object.Schema).$($object.Name) WITH ENCRYPTION AS RETURN 0;"
                            }
                            'UserDefinedFunction' {

                                switch ($object.SubType) {
                                    'Inline' {
                                        $queryKnownPlain = (" " * $secret.value.length) + "ALTER FUNCTION $($object.Schema).$($object.Name)() RETURNS TABLE WITH ENCRYPTION AS BEGIN RETURN SELECT 0 i END;"
                                    }
                                    'Scalar' {
                                        $queryKnownPlain = (" " * $secret.value.length) + "ALTER FUNCTION $($object.Schema).$($object.Name)() RETURNS INT WITH ENCRYPTION AS BEGIN RETURN 0 END;"
                                    }
                                    'Table' {
                                        $queryKnownPlain = (" " * $secret.value.length) + "ALTER FUNCTION $($object.Schema).$($object.Name)() RETURNS @r TABLE(i INT) WITH ENCRYPTION AS BEGIN RETURN END;"
                                    }
                                }
                            }
                            'View' {
                                $queryKnownPlain = (" " * $secret.Value.Length) + "ALTER VIEW $($object.Schema).$($object.Name) WITH ENCRYPTION AS SELECT NULL AS [Value];"
                            }
                        }

                        # Convert the known plain into binary
                        if ($queryKnownPlain) {
                            try {
                                $knownPlain = $encoding.GetBytes(($queryKnownPlain))
                            } catch {
                                Stop-Function -Message "Couldn't convert the known plain to binary" -ErrorRecord $_ -Target $instance -Continue
                            }
                        } else {
                            Stop-Function -Message "Something went wrong setting up the known plain" -ErrorRecord $_ -Target $instance -Continue
                        }

                        # Setup the query to change the object in SQL Server and roll it back getting the encrypted version
                        $queryKnownSecret = "
                            BEGIN TRANSACTION;
                                EXEC ('$queryKnownPlain');
                                SELECT imageval AS Value
                                FROM sys.sysobjvalues
                                WHERE objid = OBJECT_ID('$($object.Name)');
                            ROLLBACK;
                        "

                        # Get the result for the known encrypted
                        try {
                            $knownSecret = $server.Databases[$db.Name].Query($queryKnownSecret)
                        } catch {
                            Stop-Function -Message "Couldn't retrieve known secret from $instance" -ErrorRecord $_ -Target $instance -Continue
                        }

                        # Get the result
                        $result = Invoke-DecryptData -Secret $secret.value -KnownPlain $knownPlain -KnownSecret $knownSecret.value

                        # Check if the results need to be exported
                        if ($ExportDestination) {
                            # make up the file name
                            $filename = "$($object.Schema).$($object.Name).sql"

                            # Check the export destination
                            if ($ExportDestination.EndsWith("\")) {
                                $destinationFolder = "$ExportDestination$instance\$($db.Name)\$($object.ObjectType)\"
                            } else {
                                $destinationFolder = "$ExportDestination\$instance\$($db.Name)\$($object.ObjectType)\"
                            }

                            # Check if the destination folder exists
                            if (-not (Test-Path $destinationFolder)) {
                                try {
                                    # Create the new destination
                                    New-Item -Path $destinationFolder -ItemType Directory -Force:$Force | Out-Null
                                } catch {
                                    Stop-Function -Message "Couldn't create destination folder $destinationFolder" -ErrorRecord $_ -Target $instance -Continue
                                }
                            }

                            # Combine the destination folder and the file name to get the path
                            $filePath = $destinationFolder + $filename

                            # Export the result
                            try {
                                $result | Out-File -FilePath $filePath -Force
                            } catch {
                                Stop-Function -Message "Couldn't export the results of $($object.Name) to $filePath" -ErrorRecord $_ -Target $instance -Continue
                            }

                        }

                        # Add the results to the custom object
                        [PSCustomObject]@{
                            ComputerName = $server.ComputerName
                            InstanceName = $server.ServiceName
                            SqlInstance  = $server.DomainInstanceName
                            Database     = $db.Name
                            Type         = $object.ObjectType
                            Schema       = $object.Schema
                            Name         = $object.Name
                            FullName     = "$($object.Schema).$($object.Name)"
                            Script       = $result
                        }

                    } # end if secret

                } # end for each object

            } # end for each database

        } # end for each instance

    } # process

    end {
        if (Test-FunctionInterrupt) { return }

        Write-Message -Message "Finished decrypting data" -Level Verbose
    }
}
tools\dbatools\functions\Invoke-DbaDbLogShipping.ps1
function Invoke-DbaDbLogShipping {
    <#
    .SYNOPSIS
        Invoke-DbaDbLogShipping sets up log shipping for one or more databases

    .DESCRIPTION
        Invoke-DbaDbLogShipping helps to easily set up log shipping for one or more databases.

        This function will make a lot of decisions for you assuming you want default values like a daily interval for the schedules with a 15 minute interval on the day.
        There are some settings that cannot be made by the function and they need to be prepared before the function is executed.

        The following settings need to be made before log shipping can be initiated:
        - Backup destination (the folder and the privileges)
        - Copy destination (the folder and the privileges)

        * Privileges
        Make sure your agent service on both the primary and the secondary instance is an Active Directory account.
        Also have the credentials ready to set the folder permissions

        ** Network share
        The backup destination needs to be shared and have the share privileges of FULL CONTROL to Everyone.

        ** NTFS permissions
        The backup destination must have at least read/write permissions for the primary instance agent account.
        The backup destination must have at least read permissions for the secondary instance agent account.
        The copy destination must have at least read/write permission for the secondary instance agent acount.

    .PARAMETER SourceSqlInstance
        Source SQL Server instance which contains the databases to be log shipped.
        You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER DestinationSqlInstance
        Destination SQL Server instance which contains the databases to be log shipped.
        You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER SourceCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER DestinationCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Database to set up log shipping for.

    .PARAMETER BackupNetworkPath
        The backup unc path to place the backup files. This is the root directory.
        A directory with the name of the database will be created in this path.

    .PARAMETER BackupLocalPath
        If the backup path is locally for the source server you can also set this value.

    .PARAMETER BackupJob
        Name of the backup that will be created in the SQL Server agent.
        The parameter works as a prefix where the name of the database will be added to the backup job name.
        The default is "LSBackup_[databasename]"

    .PARAMETER BackupRetention
        The backup retention period in minutes. Default is 4320 / 72 hours

    .PARAMETER BackupSchedule
        Name of the backup schedule created for the backup job.
        The parameter works as a prefix where the name of the database will be added to the backup job schedule name.
        Default is "LSBackupSchedule_[databasename]"

    .PARAMETER BackupScheduleDisabled
        Parameter to set the backup schedule to disabled upon creation.
        By default the schedule is enabled.

    .PARAMETER BackupScheduleFrequencyType
        A value indicating when a job is to be executed.
        Allowed values are "Daily", "AgentStart", "IdleComputer"

    .PARAMETER BackupScheduleFrequencyInterval
        The number of type periods to occur between each execution of the backup job.

    .PARAMETER BackupScheduleFrequencySubdayType
        Specifies the units for the sub-day FrequencyInterval.
        Allowed values are "Time", "Seconds", "Minutes", "Hours"

    .PARAMETER BackupScheduleFrequencySubdayInterval
        The number of sub-day type periods to occur between each execution of the backup job.

    .PARAMETER BackupScheduleFrequencyRelativeInterval
        A job's occurrence of FrequencyInterval in each month, if FrequencyInterval is 32 (monthlyrelative).

    .PARAMETER BackupScheduleFrequencyRecurrenceFactor
        The number of weeks or months between the scheduled execution of a job. FrequencyRecurrenceFactor is used only if FrequencyType is 8, "Weekly", 16, "Monthly", 32 or "MonthlyRelative".

    .PARAMETER BackupScheduleStartDate
        The date on which execution of a job can begin.

    .PARAMETER BackupScheduleEndDate
        The date on which execution of a job can stop.

    .PARAMETER BackupScheduleStartTime
        The time on any day to begin execution of a job. Format HHMMSS / 24 hour clock.
        Example: '010000' for 01:00:00 AM.
        Example: '140000' for 02:00:00 PM.

    .PARAMETER BackupScheduleEndTime
        The time on any day to end execution of a job. Format HHMMSS / 24 hour clock.
        Example: '010000' for 01:00:00 AM.
        Example: '140000' for 02:00:00 PM.

    .PARAMETER BackupThreshold
        Is the length of time, in minutes, after the last backup before a threshold alert error is raised.
        The default is 60.

    .PARAMETER CompressBackup
        Do the backups need to be compressed. By default the backups are not compressed.

    .PARAMETER CopyDestinationFolder
        The path to copy the transaction log backup files to. This is the root directory.
        A directory with the name of the database will be created in this path.

    .PARAMETER CopyJob
        Name of the copy job that will be created in the SQL Server agent.
        The parameter works as a prefix where the name of the database will be added to the copy job name.
        The default is "LSBackup_[databasename]"

    .PARAMETER CopyRetention
        The copy retention period in minutes. Default is 4320 / 72 hours

    .PARAMETER CopySchedule
        Name of the backup schedule created for the copy job.
        The parameter works as a prefix where the name of the database will be added to the copy job schedule name.
        Default is "LSCopy_[DestinationServerName]_[DatabaseName]"

    .PARAMETER CopyScheduleDisabled
        Parameter to set the copy schedule to disabled upon creation.
        By default the schedule is enabled.

    .PARAMETER CopyScheduleFrequencyType
        A value indicating when a job is to be executed.
        Allowed values are "Daily", "AgentStart", "IdleComputer"

    .PARAMETER CopyScheduleFrequencyInterval
        The number of type periods to occur between each execution of the copy job.

    .PARAMETER CopyScheduleFrequencySubdayType
        Specifies the units for the subday FrequencyInterval.
        Allowed values are "Time", "Seconds", "Minutes", "Hours"

    .PARAMETER CopyScheduleFrequencySubdayInterval
        The number of subday type periods to occur between each execution of the copy job.

    .PARAMETER CopyScheduleFrequencyRelativeInterval
        A job's occurrence of FrequencyInterval in each month, if FrequencyInterval is 32 (monthlyrelative).

    .PARAMETER CopyScheduleFrequencyRecurrenceFactor
        The number of weeks or months between the scheduled execution of a job. FrequencyRecurrenceFactor is used only if FrequencyType is 8, "Weekly", 16, "Monthly", 32 or "MonthlyRelative".

    .PARAMETER CopyScheduleStartDate
        The date on which execution of a job can begin.

    .PARAMETER CopyScheduleEndDate
        The date on which execution of a job can stop.

    .PARAMETER CopyScheduleStartTime
        The time on any day to begin execution of a job. Format HHMMSS / 24 hour clock.
        Example: '010000' for 01:00:00 AM.
        Example: '140000' for 02:00:00 PM.

    .PARAMETER CopyScheduleEndTime
        The time on any day to end execution of a job. Format HHMMSS / 24 hour clock.
        Example: '010000' for 01:00:00 AM.
        Example: '140000' for 02:00:00 PM.

    .PARAMETER DisconnectUsers
        If this parameter is set in combinations of standby the users will be disconnected during restore.

    .PARAMETER FullBackupPath
        Path to an existing full backup. Use this when an existing backup needs to used to initialize the database on the secondary instance.

    .PARAMETER GenerateFullBackup
        If the database is not initialized on the secondary instance it can be done by creating a new full backup and
        restore it for you.

    .PARAMETER HistoryRetention
        Is the length of time in minutes in which the history is retained.
        The default value is 14420

    .PARAMETER NoRecovery
        If this parameter is set the database will be in recovery mode. The database will not be readable.
        This setting is default.

    .PARAMETER NoInitialization
        If this parameter is set the secondary database will not be initialized.
        The database needs to be on the secondary instance in recovery mode.

    .PARAMETER PrimaryMonitorServer
        Is the name of the monitor server for the primary server.
        The default is the name of the primary sql server.

    .PARAMETER PrimaryMonitorCredential
        Allows you to login to enter a secure credential. Only needs to be used when the PrimaryMonitorServerSecurityMode is 0 or "sqlserver"
        To use: $scred = Get-Credential, then pass $scred object to the -PrimaryMonitorCredential parameter.

    .PARAMETER PrimaryMonitorServerSecurityMode
        The security mode used to connect to the monitor server for the primary server. Allowed values are 0, "sqlserver", 1, "windows"
        The default is 1 or Windows.

    .PARAMETER PrimaryThresholdAlertEnabled
        Enables the Threshold alert for the primary database

    .PARAMETER RestoreDataFolder
        Folder to be used to restore the database data files. Only used when parameter GenerateFullBackup or UseExistingFullBackup are set.
        If the parameter is not set the default data folder of the secondary instance will be used including the name of the database.
        If the folder is set but doesn't exist the default data folder of the secondary instance will be used including the name of the database.

    .PARAMETER RestoreLogFolder
        Folder to be used to restore the database log files. Only used when parameter GenerateFullBackup or UseExistingFullBackup are set.
        If the parameter is not set the default transaction log folder of the secondary instance will be used.
        If the folder is set but doesn't exist the default transaction log folder of the secondary instance will be used.

    .PARAMETER RestoreDelay
        In case a delay needs to be set for the restore.
        The default is 0.

    .PARAMETER RestoreAlertThreshold
        The amount of minutes after which an alert will be raised is no restore has taken place.
        The default is 45 minutes.

    .PARAMETER RestoreJob
        Name of the restore job that will be created in the SQL Server agent.
        The parameter works as a prefix where the name of the database will be added to the restore job name.
        The default is "LSRestore_[databasename]"

    .PARAMETER RestoreRetention
        The backup retention period in minutes. Default is 4320 / 72 hours

    .PARAMETER RestoreSchedule
        Name of the backup schedule created for the restore job.
        The parameter works as a prefix where the name of the database will be added to the restore job schedule name.
        Default is "LSRestore_[DestinationServerName]_[DatabaseName]"

    .PARAMETER RestoreScheduleDisabled
        Parameter to set the restore schedule to disabled upon creation.
        By default the schedule is enabled.

    .PARAMETER RestoreScheduleFrequencyType
        A value indicating when a job is to be executed.
        Allowed values are "Daily", "AgentStart", "IdleComputer"

    .PARAMETER RestoreScheduleFrequencyInterval
        The number of type periods to occur between each execution of the restore job.

    .PARAMETER RestoreScheduleFrequencySubdayType
        Specifies the units for the subday FrequencyInterval.
        Allowed values are "Time", "Seconds", "Minutes", "Hours"

    .PARAMETER RestoreScheduleFrequencySubdayInterval
        The number of subday type periods to occur between each execution of the restore job.

    .PARAMETER RestoreScheduleFrequencyRelativeInterval
        A job's occurrence of FrequencyInterval in each month, if FrequencyInterval is 32 (monthlyrelative).

    .PARAMETER RestoreScheduleFrequencyRecurrenceFactor
        The number of weeks or months between the scheduled execution of a job. FrequencyRecurrenceFactor is used only if FrequencyType is 8, "Weekly", 16, "Monthly", 32 or "MonthlyRelative".

    .PARAMETER RestoreScheduleStartDate
        The date on which execution of a job can begin.

    .PARAMETER RestoreScheduleEndDate
        The date on which execution of a job can stop.

    .PARAMETER RestoreScheduleStartTime
        The time on any day to begin execution of a job. Format HHMMSS / 24 hour clock.
        Example: '010000' for 01:00:00 AM.
        Example: '140000' for 02:00:00 PM.

    .PARAMETER RestoreScheduleEndTime
        The time on any day to end execution of a job. Format HHMMSS / 24 hour clock.
        Example: '010000' for 01:00:00 AM.
        Example: '140000' for 02:00:00 PM.

    .PARAMETER RestoreThreshold
        The number of minutes allowed to elapse between restore operations before an alert is generated.
        The default value = 0

    .PARAMETER SecondaryDatabasePrefix
        The secondary database can be renamed to include a prefix.

    .PARAMETER SecondaryDatabaseSuffix
        The secondary database can be renamed to include a suffix.

    .PARAMETER SecondaryMonitorServer
        Is the name of the monitor server for the secondary server.
        The default is the name of the secondary sql server.

    .PARAMETER SecondaryMonitorCredential
        Allows you to login to enter a secure credential. Only needs to be used when the SecondaryMonitorServerSecurityMode is 0 or "sqlserver"
        To use: $scred = Get-Credential, then pass $scred object to the -SecondaryMonitorCredential parameter.

    .PARAMETER SecondaryMonitorServerSecurityMode
        The security mode used to connect to the monitor server for the secondary server. Allowed values are 0, "sqlserver", 1, "windows"
        The default is 1 or Windows.

    .PARAMETER SecondaryThresholdAlertEnabled
        Enables the Threshold alert for the secondary database

    .PARAMETER Standby
        If this parameter is set the database will be set to standby mode making the database readable.
        If not set the database will be in recovery mode.

    .PARAMETER StandbyDirectory
        Directory to place the standby file(s) in

    .PARAMETER UseExistingFullBackup
        If the database is not initialized on the secondary instance it can be done by selecting an existing full backup
        and restore it for you.

    .PARAMETER UseBackupFolder
        This enables the user to specify a specific backup folder containing one or more backup files to initialize the database on the secondary instance.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        Use this switch to disable any kind of verbose messages

    .PARAMETER Force
        The force parameter will ignore some errors in the parameters and assume defaults.
        It will also remove the any present schedules with the same name for the specific job.

    .NOTES
        Tags: LogShipping
        Author: Sander Stad (@sqlstad), sqlstad.nl

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaDbLogShipping

    .EXAMPLE
        PS C:\> $params = @{
        >> SourceSqlInstance = 'sql1'
        >> DestinationSqlInstance = 'sql2'
        >> Database = 'db1'
        >> BackupNetworkPath= '\\sql1\logshipping'
        >> BackupLocalPath= 'D:\Data\logshipping'
        >> BackupScheduleFrequencyType = 'daily'
        >> BackupScheduleFrequencyInterval = 1
        >> CompressBackup = $true
        >> CopyScheduleFrequencyType = 'daily'
        >> CopyScheduleFrequencyInterval = 1
        >> GenerateFullBackup = $true
        >> RestoreScheduleFrequencyType = 'daily'
        >> RestoreScheduleFrequencyInterval = 1
        >> SecondaryDatabaseSuffix = 'DR'
        >> CopyDestinationFolder = '\\sql2\logshippingdest'
        >> Force = $true
        >> }
        >>
        PS C:\> Invoke-DbaDbLogShipping @params

        Sets up log shipping for database "db1" with the backup path to a network share allowing local backups.
        It creates daily schedules for the backup, copy and restore job with all the defaults to be executed every 15 minutes daily.
        The secondary database will be called "db1_LS".

    .EXAMPLE
        PS C:\> $params = @{
        >> SourceSqlInstance = 'sql1'
        >> DestinationSqlInstance = 'sql2'
        >> Database = 'db1'
        >> BackupNetworkPath= '\\sql1\logshipping'
        >> GenerateFullBackup = $true
        >> Force = $true
        >> }
        >>
        PS C:\> Invoke-DbaDbLogShipping @params

        Sets up log shipping with all defaults except that a backup file is generated.
        The script will show a message that the copy destination has not been supplied and asks if you want to use the default which would be the backup directory of the secondary server with the folder "logshipping" i.e. "D:\SQLBackup\Logshiping".

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]

    param(
        [parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [Alias("SourceServerInstance", "SourceSqlServerSqlServer", "Source")]
        [object]$SourceSqlInstance,

        [parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [Alias("DestinationServerInstance", "DestinationSqlServer", "Destination")]
        [object[]]$DestinationSqlInstance,

        [System.Management.Automation.PSCredential]
        $SourceSqlCredential,

        [System.Management.Automation.PSCredential]
        $SourceCredential,

        [System.Management.Automation.PSCredential]
        $DestinationSqlCredential,

        [System.Management.Automation.PSCredential]
        $DestinationCredential,

        [Parameter(Mandatory, ValueFromPipeline)]
        [object[]]$Database,

        [parameter(Mandatory)]
        [string]$BackupNetworkPath,

        [string]$BackupLocalPath,

        [string]$BackupJob,

        [int]$BackupRetention,

        [string]$BackupSchedule,

        [switch]$BackupScheduleDisabled,

        [ValidateSet("Daily", "Weekly", "AgentStart", "IdleComputer")]
        [object]$BackupScheduleFrequencyType,

        [object[]]$BackupScheduleFrequencyInterval,

        [ValidateSet('Time', 'Seconds', 'Minutes', 'Hours')]
        [object]$BackupScheduleFrequencySubdayType,

        [int]$BackupScheduleFrequencySubdayInterval,

        [ValidateSet('Unused', 'First', 'Second', 'Third', 'Fourth', 'Last')]
        [object]$BackupScheduleFrequencyRelativeInterval,

        [int]$BackupScheduleFrequencyRecurrenceFactor,

        [string]$BackupScheduleStartDate,

        [string]$BackupScheduleEndDate,

        [string]$BackupScheduleStartTime,

        [string]$BackupScheduleEndTime,

        [int]$BackupThreshold,

        [switch]$CompressBackup,

        [string]$CopyDestinationFolder,

        [string]$CopyJob,

        [int]$CopyRetention,

        [string]$CopySchedule,

        [switch]$CopyScheduleDisabled,

        [ValidateSet("Daily", "Weekly", "AgentStart", "IdleComputer")]
        [object]$CopyScheduleFrequencyType,

        [object[]]$CopyScheduleFrequencyInterval,

        [ValidateSet('Time', 'Seconds', 'Minutes', 'Hours')]
        [object]$CopyScheduleFrequencySubdayType,

        [int]$CopyScheduleFrequencySubdayInterval,

        [ValidateSet('Unused', 'First', 'Second', 'Third', 'Fourth', 'Last')]
        [object]$CopyScheduleFrequencyRelativeInterval,

        [int]$CopyScheduleFrequencyRecurrenceFactor,

        [string]$CopyScheduleStartDate,

        [string]$CopyScheduleEndDate,

        [string]$CopyScheduleStartTime,

        [string]$CopyScheduleEndTime,

        [switch]$DisconnectUsers,

        [string]$FullBackupPath,

        [switch]$GenerateFullBackup,

        [int]$HistoryRetention,

        [switch]$NoRecovery,

        [switch]$NoInitialization,

        [string]$PrimaryMonitorServer,

        [System.Management.Automation.PSCredential]
        $PrimaryMonitorCredential,

        [ValidateSet(0, "sqlserver", 1, "windows")]
        [object]$PrimaryMonitorServerSecurityMode,

        [switch]$PrimaryThresholdAlertEnabled,

        [string]$RestoreDataFolder,

        [string]$RestoreLogFolder,

        [int]$RestoreDelay,

        [int]$RestoreAlertThreshold,

        [string]$RestoreJob,

        [int]$RestoreRetention,

        [string]$RestoreSchedule,

        [switch]$RestoreScheduleDisabled,

        [ValidateSet("Daily", "Weekly", "AgentStart", "IdleComputer")]
        [object]$RestoreScheduleFrequencyType,

        [object[]]$RestoreScheduleFrequencyInterval,

        [ValidateSet('Time', 'Seconds', 'Minutes', 'Hours')]
        [object]$RestoreScheduleFrequencySubdayType,

        [int]$RestoreScheduleFrequencySubdayInterval,

        [ValidateSet('Unused', 'First', 'Second', 'Third', 'Fourth', 'Last')]
        [object]$RestoreScheduleFrequencyRelativeInterval,

        [int]$RestoreScheduleFrequencyRecurrenceFactor,

        [string]$RestoreScheduleStartDate,

        [string]$RestoreScheduleEndDate,

        [string]$RestoreScheduleStartTime,

        [string]$RestoreScheduleEndTime,

        [int]$RestoreThreshold,

        [string]$SecondaryDatabasePrefix,

        [string]$SecondaryDatabaseSuffix,

        [string]$SecondaryMonitorServer,

        [System.Management.Automation.PSCredential]
        $SecondaryMonitorCredential,

        [ValidateSet(0, "sqlserver", 1, "windows")]
        [object]$SecondaryMonitorServerSecurityMode,

        [switch]$SecondaryThresholdAlertEnabled,

        [switch]$Standby,

        [string]$StandbyDirectory,

        [switch]$UseExistingFullBackup,

        [string]$UseBackupFolder,

        [switch]$Force,

        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        Write-Message -Message "Started log shipping for $SourceSqlInstance to $DestinationSqlInstance" -Level Verbose

        # Try connecting to the instance
        try {
            $SourceServer = Connect-SqlInstance -SqlInstance $SourceSqlInstance -SqlCredential $SourceSqlCredential
        } catch {
            Stop-Function -Message "Could not connect to Sql Server instance $SourceSqlInstance" -ErrorRecord $_ -Target $SourceSqlInstance
            return
        }


        # Check the instance if it is a named instance
        $SourceServerName, $SourceInstanceName = $SourceSqlInstance.Split("\")

        if ($null -eq $SourceInstanceName) {
            $SourceInstanceName = "MSSQLSERVER"
        }

        # Set up regex strings for several checks
        $RegexDate = '(?<!\d)(?:(?:(?:1[6-9]|[2-9]\d)?\d{2})(?:(?:(?:0[13578]|1[02])31)|(?:(?:0[1,3-9]|1[0-2])(?:29|30)))|(?:(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))0229)|(?:(?:1[6-9]|[2-9]\d)?\d{2})(?:(?:0?[1-9])|(?:1[0-2]))(?:0?[1-9]|1\d|2[0-8]))(?!\d)'
        $RegexTime = '^(?:(?:([01]?\d|2[0-3]))?([0-5]?\d))?([0-5]?\d)$'
        $RegexUnc = '^\\(?:\\[^<>:`"/\\|?*]+)+$'


        # Check the connection timeout
        if ($SourceServer.ConnectionContext.StatementTimeout -ne 0) {
            $SourceServer.ConnectionContext.StatementTimeout = 0
            Write-Message -Message "Connection timeout of $SourceServer is set to 0" -Level Verbose
        }

        # Check the backup network path
        Write-Message -Message "Testing backup network path $BackupNetworkPath" -Level Verbose
        if ((Test-DbaPath -Path $BackupNetworkPath -SqlInstance $SourceSqlInstance -SqlCredential $SourceCredential) -ne $true) {
            Stop-Function -Message "Backup network path $BackupNetworkPath is not valid or can't be reached." -Target $SourceSqlInstance
            return
        } elseif ($BackupNetworkPath -notmatch $RegexUnc) {
            Stop-Function -Message "Backup network path $BackupNetworkPath has to be in the form of \\server\share." -Target $SourceSqlInstance
            return
        }

        # Check the backup compression
        if ($SourceServer.Version.Major -gt 9) {
            if ($CompressBackup) {
                Write-Message -Message "Setting backup compression to 1." -Level Verbose
                [bool]$BackupCompression = 1
            } else {
                $backupServerSetting = (Get-DbaSpConfigure -SqlInstance $SourceSqlInstance -ConfigName DefaultBackupCompression).ConfiguredValue
                Write-Message -Message "Setting backup compression to default server setting $backupServerSetting." -Level Verbose
                [bool]$BackupCompression = $backupServerSetting
            }
        } else {
            Write-Message -Message "Source server $SourceServer does not support backup compression" -Level Verbose
        }

        # Check the database parameter
        if ($Database) {
            foreach ($db in $Database) {
                if ($db -notin $SourceServer.Databases.Name) {
                    Stop-Function -Message "Database $db cannot be found on instance $SourceSqlInstance" -Target $SourceSqlInstance
                }

                $DatabaseCollection = $SourceServer.Databases | Where-Object { $_.Name -in $Database }
            }
        } else {
            Stop-Function -Message "Please supply a database to set up log shipping for" -Target $SourceSqlInstance -Continue
        }

        # Set the database mode
        if ($Standby) {
            $DatabaseStatus = 1
            Write-Message -Message "Destination database status set to STANDBY" -Level Verbose
        } else {
            $DatabaseStatus = 0
            Write-Message -Message "Destination database status set to NO RECOVERY" -Level Verbose
        }

        # Setting defaults
        if (-not $BackupRetention) {
            $BackupRetention = 4320
            Write-Message -Message "Backup retention set to $BackupRetention" -Level Verbose
        }
        if (-not $BackupThreshold) {
            $BackupThreshold = 60
            Write-Message -Message "Backup Threshold set to $BackupThreshold" -Level Verbose
        }
        if (-not $CopyRetention) {
            $CopyRetention = 4320
            Write-Message -Message "Copy retention set to $CopyRetention" -Level Verbose
        }
        if (-not $HistoryRetention) {
            $HistoryRetention = 14420
            Write-Message -Message "History retention set to $HistoryRetention" -Level Verbose
        }
        if (-not $RestoreAlertThreshold) {
            $RestoreAlertThreshold = 45
            Write-Message -Message "Restore alert Threshold set to $RestoreAlertThreshold" -Level Verbose
        }
        if (-not $RestoreDelay) {
            $RestoreDelay = 0
            Write-Message -Message "Restore delay set to $RestoreDelay" -Level Verbose
        }
        if (-not $RestoreRetention) {
            $RestoreRetention = 4320
            Write-Message -Message "Restore retention set to $RestoreRetention" -Level Verbose
        }
        if (-not $RestoreThreshold) {
            $RestoreThreshold = 0
            Write-Message -Message "Restore Threshold set to $RestoreThreshold" -Level Verbose
        }
        if (-not $PrimaryMonitorServerSecurityMode) {
            $PrimaryMonitorServerSecurityMode = 1
            Write-Message -Message "Primary monitor server security mode set to $PrimaryMonitorServerSecurityMode" -Level Verbose
        }
        if (-not $SecondaryMonitorServerSecurityMode) {
            $SecondaryMonitorServerSecurityMode = 1
            Write-Message -Message "Secondary monitor server security mode set to $SecondaryMonitorServerSecurityMode" -Level Verbose
        }
        if (-not $BackupScheduleFrequencyType) {
            $BackupScheduleFrequencyType = "Daily"
            Write-Message -Message "Backup frequency type set to $BackupScheduleFrequencyType" -Level Verbose
        }
        if (-not $BackupScheduleFrequencyInterval) {
            $BackupScheduleFrequencyInterval = "EveryDay"
            Write-Message -Message "Backup frequency interval set to $BackupScheduleFrequencyInterval" -Level Verbose
        }
        if (-not $BackupScheduleFrequencySubdayType) {
            $BackupScheduleFrequencySubdayType = "Minutes"
            Write-Message -Message "Backup frequency subday type set to $BackupScheduleFrequencySubdayType" -Level Verbose
        }
        if (-not $BackupScheduleFrequencySubdayInterval) {
            $BackupScheduleFrequencySubdayInterval = 15
            Write-Message -Message "Backup frequency subday interval set to $BackupScheduleFrequencySubdayInterval" -Level Verbose
        }
        if (-not $BackupScheduleFrequencyRelativeInterval) {
            $BackupScheduleFrequencyRelativeInterval = "Unused"
            Write-Message -Message "Backup frequency relative interval set to $BackupScheduleFrequencyRelativeInterval" -Level Verbose
        }
        if (-not $BackupScheduleFrequencyRecurrenceFactor) {
            $BackupScheduleFrequencyRecurrenceFactor = 0
            Write-Message -Message "Backup frequency recurrence factor set to $BackupScheduleFrequencyRecurrenceFactor" -Level Verbose
        }
        if (-not $CopyScheduleFrequencyType) {
            $CopyScheduleFrequencyType = "Daily"
            Write-Message -Message "Copy frequency type set to $CopyScheduleFrequencyType" -Level Verbose
        }
        if (-not $CopyScheduleFrequencyInterval) {
            $CopyScheduleFrequencyInterval = "EveryDay"
            Write-Message -Message "Copy frequency interval set to $CopyScheduleFrequencyInterval" -Level Verbose
        }
        if (-not $CopyScheduleFrequencySubdayType) {
            $CopyScheduleFrequencySubdayType = "Minutes"
            Write-Message -Message "Copy frequency subday type set to $CopyScheduleFrequencySubdayType" -Level Verbose
        }
        if (-not $CopyScheduleFrequencySubdayInterval) {
            $CopyScheduleFrequencySubdayInterval = 15
            Write-Message -Message "Copy frequency subday interval set to $CopyScheduleFrequencySubdayInterval" -Level Verbose
        }
        if (-not $CopyScheduleFrequencyRelativeInterval) {
            $CopyScheduleFrequencyRelativeInterval = "Unused"
            Write-Message -Message "Copy frequency relative interval set to $CopyScheduleFrequencyRelativeInterval" -Level Verbose
        }
        if (-not $CopyScheduleFrequencyRecurrenceFactor) {
            $CopyScheduleFrequencyRecurrenceFactor = 0
            Write-Message -Message "Copy frequency recurrence factor set to $CopyScheduleFrequencyRecurrenceFactor" -Level Verbose
        }
        if (-not $RestoreScheduleFrequencyType) {
            $RestoreScheduleFrequencyType = "Daily"
            Write-Message -Message "Restore frequency type set to $RestoreScheduleFrequencyType" -Level Verbose
        }
        if (-not $RestoreScheduleFrequencyInterval) {
            $RestoreScheduleFrequencyInterval = "EveryDay"
            Write-Message -Message "Restore frequency interval set to $RestoreScheduleFrequencyInterval" -Level Verbose
        }
        if (-not $RestoreScheduleFrequencySubdayType) {
            $RestoreScheduleFrequencySubdayType = "Minutes"
            Write-Message -Message "Restore frequency subday type set to $RestoreScheduleFrequencySubdayType" -Level Verbose
        }
        if (-not $RestoreScheduleFrequencySubdayInterval) {
            $RestoreScheduleFrequencySubdayInterval = 15
            Write-Message -Message "Restore frequency subday interval set to $RestoreScheduleFrequencySubdayInterval" -Level Verbose
        }
        if (-not $RestoreScheduleFrequencyRelativeInterval) {
            $RestoreScheduleFrequencyRelativeInterval = "Unused"
            Write-Message -Message "Restore frequency relative interval set to $RestoreScheduleFrequencyRelativeInterval" -Level Verbose
        }
        if (-not $RestoreScheduleFrequencyRecurrenceFactor) {
            $RestoreScheduleFrequencyRecurrenceFactor = 0
            Write-Message -Message "Restore frequency recurrence factor set to $RestoreScheduleFrequencyRecurrenceFactor" -Level Verbose
        }

        # Checking for contradicting variables
        if ($NoInitialization -and ($GenerateFullBackup -or $UseExistingFullBackup)) {
            Stop-Function -Message "Cannot use -NoInitialization with -GenerateFullBackup or -UseExistingFullBackup" -Target $DestinationSqlInstance
            return
        }

        if ($UseBackupFolder -and ($GenerateFullBackup -or $NoInitialization -or $UseExistingFullBackup)) {
            Stop-Function -Message "Cannot use -UseBackupFolder with -GenerateFullBackup, -NoInitialization or -UseExistingFullBackup" -Target $DestinationSqlInstance
            return
        }

        # Check the subday interval
        if (($BackupScheduleFrequencySubdayType -in 2, "Seconds", 4, "Minutes") -and (-not ($BackupScheduleFrequencySubdayInterval -ge 1 -or $BackupScheduleFrequencySubdayInterval -le 59))) {
            Stop-Function -Message "Backup subday interval $BackupScheduleFrequencySubdayInterval must be between 1 and 59 when subday type is 2, 'Seconds', 4 or 'Minutes'" -Target $SourceSqlInstance
            return
        } elseif (($BackupScheduleFrequencySubdayType -in 8, "Hours") -and (-not ($BackupScheduleFrequencySubdayInterval -ge 1 -and $BackupScheduleFrequencySubdayInterval -le 23))) {
            Stop-Function -Message "Backup Subday interval $BackupScheduleFrequencySubdayInterval must be between 1 and 23 when subday type is 8 or 'Hours" -Target $SourceSqlInstance
            return
        }

        # Check the subday interval
        if (($CopyScheduleFrequencySubdayType -in 2, "Seconds", 4, "Minutes") -and (-not ($CopyScheduleFrequencySubdayInterval -ge 1 -or $CopyScheduleFrequencySubdayInterval -le 59))) {
            Stop-Function -Message "Copy subday interval $CopyScheduleFrequencySubdayInterval must be between 1 and 59 when subday type is 2, 'Seconds', 4 or 'Minutes'" -Target $DestinationSqlInstance
            return
        } elseif (($CopyScheduleFrequencySubdayType -in 8, "Hours") -and (-not ($CopyScheduleFrequencySubdayInterval -ge 1 -and $CopyScheduleFrequencySubdayInterval -le 23))) {
            Stop-Function -Message "Copy subday interval $CopyScheduleFrequencySubdayInterval must be between 1 and 23 when subday type is 8 or 'Hours'" -Target $DestinationSqlInstance
            return
        }

        # Check the subday interval
        if (($RestoreScheduleFrequencySubdayType -in 2, "Seconds", 4, "Minutes") -and (-not ($RestoreScheduleFrequencySubdayInterval -ge 1 -or $RestoreScheduleFrequencySubdayInterval -le 59))) {
            Stop-Function -Message "Restore subday interval $RestoreScheduleFrequencySubdayInterval must be between 1 and 59 when subday type is 2, 'Seconds', 4 or 'Minutes'" -Target $DestinationSqlInstance
            return
        } elseif (($RestoreScheduleFrequencySubdayType -in 8, "Hours") -and (-not ($RestoreScheduleFrequencySubdayInterval -ge 1 -and $RestoreScheduleFrequencySubdayInterval -le 23))) {
            Stop-Function -Message "Restore subday interval $RestoreScheduleFrequencySubdayInterval must be between 1 and 23 when subday type is 8 or 'Hours" -Target $DestinationSqlInstance
            return
        }

        # Check the backup start date
        if (-not $BackupScheduleStartDate) {
            $BackupScheduleStartDate = (Get-Date -format "yyyyMMdd")
            Write-Message -Message "Backup start date set to $BackupScheduleStartDate" -Level Verbose
        } else {
            if ($BackupScheduleStartDate -notmatch $RegexDate) {
                Stop-Function -Message "Backup start date $BackupScheduleStartDate needs to be a valid date with format yyyyMMdd" -Target $SourceSqlInstance
                return
            }
        }

        # Check the back start time
        if (-not $BackupScheduleStartTime) {
            $BackupScheduleStartTime = '000000'
            Write-Message -Message "Backup start time set to $BackupScheduleStartTime" -Level Verbose
        } elseif ($BackupScheduleStartTime -notmatch $RegexTime) {
            Stop-Function -Message  "Backup start time $BackupScheduleStartTime needs to match between '000000' and '235959'" -Target $SourceSqlInstance
            return
        }

        # Check the back end time
        if (-not $BackupScheduleEndTime) {
            $BackupScheduleEndTime = '235959'
            Write-Message -Message "Backup end time set to $BackupScheduleEndTime" -Level Verbose
        } elseif ($BackupScheduleStartTime -notmatch $RegexTime) {
            Stop-Function -Message  "Backup end time $BackupScheduleStartTime needs to match between '000000' and '235959'" -Target $SourceSqlInstance
            return
        }

        # Check the backup end date
        if (-not $BackupScheduleEndDate) {
            $BackupScheduleEndDate = '99991231'
        } elseif ($BackupScheduleEndDate -notmatch $RegexDate) {
            Stop-Function -Message "Backup end date $BackupScheduleEndDate needs to be a valid date with format yyyyMMdd" -Target $SourceSqlInstance
            return
        }

        # Check the copy start date
        if (-not $CopyScheduleStartDate) {
            $CopyScheduleStartDate = (Get-Date -format "yyyyMMdd")
            Write-Message -Message "Copy start date set to $CopyScheduleStartDate" -Level Verbose
        } else {
            if ($CopyScheduleStartDate -notmatch $RegexDate) {
                Stop-Function -Message "Copy start date $CopyScheduleStartDate needs to be a valid date with format yyyyMMdd" -Target $SourceSqlInstance
                return
            }
        }

        # Check the copy end date
        if (-not $CopyScheduleEndDate) {
            $CopyScheduleEndDate = '99991231'
        } elseif ($CopyScheduleEndDate -notmatch $RegexDate) {
            Stop-Function -Message "Copy end date $CopyScheduleEndDate needs to be a valid date with format yyyyMMdd" -Target $SourceSqlInstance
            return
        }

        # Check the copy start time
        if (-not $CopyScheduleStartTime) {
            $CopyScheduleStartTime = '000000'
            Write-Message -Message "Copy start time set to $CopyScheduleStartTime" -Level Verbose
        } elseif ($CopyScheduleStartTime -notmatch $RegexTime) {
            Stop-Function -Message  "Copy start time $CopyScheduleStartTime needs to match between '000000' and '235959'" -Target $SourceSqlInstance
            return
        }

        # Check the copy end time
        if (-not $CopyScheduleEndTime) {
            $CopyScheduleEndTime = '235959'
            Write-Message -Message "Copy end time set to $CopyScheduleEndTime" -Level Verbose
        } elseif ($CopyScheduleEndTime -notmatch $RegexTime) {
            Stop-Function -Message  "Copy end time $CopyScheduleEndTime needs to match between '000000' and '235959'" -Target $SourceSqlInstance
            return
        }

        # Check the restore start date
        if (-not $RestoreScheduleStartDate) {
            $RestoreScheduleStartDate = (Get-Date -format "yyyyMMdd")
            Write-Message -Message "Restore start date set to $RestoreScheduleStartDate" -Level Verbose
        } else {
            if ($RestoreScheduleStartDate -notmatch $RegexDate) {
                Stop-Function -Message "Restore start date $RestoreScheduleStartDate needs to be a valid date with format yyyyMMdd" -Target $SourceSqlInstance
                return
            }
        }

        # Check the restore end date
        if (-not $RestoreScheduleEndDate) {
            $RestoreScheduleEndDate = '99991231'
        } elseif ($RestoreScheduleEndDate -notmatch $RegexDate) {
            Stop-Function -Message "Restore end date $RestoreScheduleEndDate needs to be a valid date with format yyyyMMdd" -Target $SourceSqlInstance
            return
        }

        # Check the restore start time
        if (-not $RestoreScheduleStartTime) {
            $RestoreScheduleStartTime = '000000'
            Write-Message -Message "Restore start time set to $RestoreScheduleStartTime" -Level Verbose
        } elseif ($RestoreScheduleStartTime -notmatch $RegexTime) {
            Stop-Function -Message  "Restore start time $RestoreScheduleStartTime needs to match between '000000' and '235959'" -Target $SourceSqlInstance
            return
        }

        # Check the restore end time
        if (-not $RestoreScheduleEndTime) {
            $RestoreScheduleEndTime = '235959'
            Write-Message -Message "Restore end time set to $RestoreScheduleEndTime" -Level Verbose
        } elseif ($RestoreScheduleEndTime -notmatch $RegexTime) {
            Stop-Function -Message  "Restore end time $RestoreScheduleEndTime needs to match between '000000' and '235959'" -Target $SourceSqlInstance
            return
        }
    }

    process {

        if (Test-FunctionInterrupt) { return }

        foreach ($destInstance in $DestinationSqlInstance) {

            $setupResult = "Success"
            $comment = ""

            # Try connecting to the instance
            try {
                $DestinationServer = Connect-SqlInstance -SqlInstance $destInstance -SqlCredential $DestinationSqlCredential
            } catch {
                Stop-Function -Message "Could not connect to Sql Server instance $destInstance" -ErrorRecord $_ -Target $destInstance
                return
            }

            $DestinationServerName, $DestinationInstanceName = $destInstance.Split("\")

            if ($null -eq $DestinationInstanceName) {
                $DestinationInstanceName = "MSSQLSERVER"
            }

            $IsDestinationLocal = $false

            # Check if it's local or remote
            if ($DestinationServerName -in ".", "localhost", $env:ServerName, "127.0.0.1") {
                $IsDestinationLocal = $true
            }

            # Check the instance names and the database settings
            if (($SourceSqlInstance -eq $destInstance) -and (-not $SecondaryDatabasePrefix -or $SecondaryDatabaseSuffix)) {
                $setupResult = "Failed"
                $comment = "The destination database is the same as the source"
                Stop-Function -Message "The destination database is the same as the source`nPlease enter a prefix or suffix using -SecondaryDatabasePrefix or -SecondaryDatabaseSuffix." -Target $SourceSqlInstance
                return
            }

            if ($DestinationServer.ConnectionContext.StatementTimeout -ne 0) {
                $DestinationServer.ConnectionContext.StatementTimeout = 0
                Write-Message -Message "Connection timeout of $DestinationServer is set to 0" -Level Verbose
            }

            # Check the copy destination
            if (-not $CopyDestinationFolder) {
                # Make a default copy destination by retrieving the backup folder and adding a directory
                $CopyDestinationFolder = "$($DestinationServer.Settings.BackupDirectory)\Logshipping"

                # Check to see if the path already exists
                Write-Message -Message "Testing copy destination path $CopyDestinationFolder" -Level Verbose
                if (Test-DbaPath -Path $CopyDestinationFolder -SqlInstance $destInstance -SqlCredential $DestinationCredential) {
                    Write-Message -Message "Copy destination $CopyDestinationFolder already exists" -Level Verbose
                } else {
                    # Check if force is being used
                    if (-not $Force) {
                        # Set up the confirm part
                        $message = "The copy destination is missing. Do you want to use the default $($CopyDestinationFolder)?"
                        $choiceYes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Answer Yes."
                        $choiceNo = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Answer No."
                        $options = [System.Management.Automation.Host.ChoiceDescription[]]($choiceYes, $choiceNo)
                        $result = $host.ui.PromptForChoice($title, $message, $options, 0)

                        # Check the result from the confirm
                        switch ($result) {
                            # If yes
                            0 {
                                # Try to create the new directory
                                try {
                                    # If the destination server is remote and the credential is set
                                    if (-not $IsDestinationLocal -and $DestinationCredential) {
                                        Invoke-Command2 -ComputerName $DestinationServerName -Credential $DestinationCredential -ScriptBlock {
                                            Write-Message -Message "Creating copy destination folder $CopyDestinationFolder" -Level Verbose
                                            New-Item -Path $CopyDestinationFolder -ItemType Directory -Credential $DestinationCredential -Force:$Force | Out-Null
                                        }
                                    }
                                    # If the server is local and the credential is set
                                    elseif ($DestinationCredential) {
                                        Invoke-Command2 -Credential $DestinationCredential -ScriptBlock {
                                            Write-Message -Message "Creating copy destination folder $CopyDestinationFolder" -Level Verbose
                                            New-Item -Path $CopyDestinationFolder -ItemType Directory -Credential $DestinationCredential -Force:$Force | Out-Null
                                        }
                                    }
                                    # If the server is local and the credential is not set
                                    else {
                                        Write-Message -Message "Creating copy destination folder $CopyDestinationFolder" -Level Verbose
                                        New-Item -Path $CopyDestinationFolder -Force:$Force -ItemType Directory | Out-Null
                                    }
                                    Write-Message -Message "Copy destination $CopyDestinationFolder created." -Level Verbose
                                } catch {
                                    $setupResult = "Failed"
                                    $comment = "Something went wrong creating the copy destination folder"
                                    Stop-Function -Message "Something went wrong creating the copy destination folder $CopyDestinationFolder. `n$_" -Target $destInstance -ErrorRecord $_
                                    return
                                }
                            }
                            1 {
                                $setupResult = "Failed"
                                $comment = "Copy destination is a mandatory parameter"
                                Stop-Function -Message "Copy destination is a mandatory parameter. Please make sure the value is entered." -Target $destInstance
                                return
                            }
                        } # switch
                    } # if not force
                    else {
                        # Try to create the copy destination on the local server
                        try {
                            Write-Message -Message "Creating copy destination folder $CopyDestinationFolder" -Level Verbose
                            New-Item $CopyDestinationFolder -ItemType Directory -Credential $DestinationCredential -Force:$Force | Out-Null
                            Write-Message -Message "Copy destination $CopyDestinationFolder created." -Level Verbose
                        } catch {
                            $setupResult = "Failed"
                            $comment = "Something went wrong creating the copy destination folder"
                            Stop-Function -Message "Something went wrong creating the copy destination folder $CopyDestinationFolder. `n$_" -Target $destInstance -ErrorRecord $_
                            return
                        }
                    } # else not force
                } # if test path copy destination
            } # if not copy destination

            Write-Message -Message "Testing copy destination path $CopyDestinationFolder" -Level Verbose
            if ((Test-DbaPath -Path $CopyDestinationFolder -SqlInstance $destInstance -SqlCredential $DestinationCredential) -ne $true) {
                $setupResult = "Failed"
                $comment = "Copy destination folder $CopyDestinationFolder is not valid or can't be reached"
                Stop-Function -Message "Copy destination folder $CopyDestinationFolder is not valid or can't be reached." -Target $destInstance
                return
            } elseif ($CopyDestinationFolder.StartsWith("\\") -and $CopyDestinationFolder -notmatch $RegexUnc) {
                $setupResult = "Failed"
                $comment = "Copy destination folder $CopyDestinationFolder has to be in the form of \\server\share"
                Stop-Function -Message "Copy destination folder $CopyDestinationFolder has to be in the form of \\server\share." -Target $destInstance
                return
            }

            if (-not ($SecondaryDatabasePrefix -or $SecondaryDatabaseSuffix) -and ($SourceServer.Name -eq $DestinationServer.Name) -and ($SourceServer.InstanceName -eq $DestinationServer.InstanceName)) {
                if ($Force) {
                    $SecondaryDatabaseSuffix = "_LS"
                } else {
                    $setupResult = "Failed"
                    $comment = "Destination database is the same as source database"
                    Stop-Function -Message "Destination database is the same as source database.`nPlease check the secondary server, database prefix or suffix or use -Force to set the secondary database using a suffix." -Target $SourceSqlInstance
                    return
                }
            }

            # Check if standby is being used
            if ($Standby) {
                # Check the stand-by directory
                if ($StandbyDirectory) {
                    # Check if the path is reachable for the destination server
                    if ((Test-DbaPath -Path $StandbyDirectory -SqlInstance $destInstance -SqlCredential $DestinationCredential) -ne $true) {
                        $setupResult = "Failed"
                        $comment = "The directory $StandbyDirectory cannot be reached by the destination instance"
                        Stop-Function -Message "The directory $StandbyDirectory cannot be reached by the destination instance. Please check the permission and credentials." -Target $destInstance
                        return
                    }
                } elseif (-not $StandbyDirectory -and $Force) {
                    $StandbyDirectory = $destInstance.BackupDirectory
                    Write-Message -Message "Stand-by directory was not set. Setting it to $StandbyDirectory" -Level Verbose
                } else {
                    $setupResult = "Failed"
                    $comment = "Please set the parameter -StandbyDirectory when using -Standby"
                    Stop-Function -Message "Please set the parameter -StandbyDirectory when using -Standby" -Target $SourceSqlInstance
                    return
                }
            }

            # Loop through each of the databases
            foreach ($db in $DatabaseCollection) {

                # Check the status of the database
                if ($db.RecoveryModel -ne 'Full') {
                    $setupResult = "Failed"
                    $comment = "Database $db is not in FULL recovery mode"

                    Stop-Function -Message  "Database $db is not in FULL recovery mode" -Target $SourceSqlInstance -Continue
                }

                # Set the intital destination database
                $SecondaryDatabase = $db.Name

                # Set the database prefix
                if ($SecondaryDatabasePrefix) {
                    $SecondaryDatabase = "$SecondaryDatabasePrefix$($db.Name)"
                }

                # Set the database suffix
                if ($SecondaryDatabaseSuffix) {
                    $SecondaryDatabase += $SecondaryDatabaseSuffix
                }

                # Check is the database is already initialized a check if the database exists on the secondary instance
                if ($NoInitialization -and ($DestinationServer.Databases.Name -notcontains $SecondaryDatabase)) {
                    $setupResult = "Failed"
                    $comment = "Database $SecondaryDatabase needs to be initialized before log shipping setting can continue"

                    Stop-Function -Message "Database $SecondaryDatabase needs to be initialized before log shipping setting can continue." -Target $SourceSqlInstance -Continue
                }

                # Check the local backup path
                if ($BackupLocalPath) {
                    if ($BackupLocalPath.EndsWith("\")) {
                        $DatabaseBackupLocalPath = "$BackupLocalPath$($db.Name)"
                    } else {
                        $DatabaseBackupLocalPath = "$BackupLocalPath\$($db.Name)"
                    }
                } else {
                    $BackupLocalPath = $BackupNetworkPath

                    if ($BackupLocalPath.EndsWith("\")) {
                        $DatabaseBackupLocalPath = "$BackupLocalPath$($db.Name)"
                    } else {
                        $DatabaseBackupLocalPath = "$BackupLocalPath\$($db.Name)"
                    }
                }
                Write-Message -Message "Backup local path set to $DatabaseBackupLocalPath." -Level Verbose

                # Setting the backup network path for the database
                if ($BackupNetworkPath.EndsWith("\")) {
                    $DatabaseBackupNetworkPath = "$BackupNetworkPath$($db.Name)"
                } else {
                    $DatabaseBackupNetworkPath = "$BackupNetworkPath\$($db.Name)"
                }
                Write-Message -Message "Backup network path set to $DatabaseBackupNetworkPath." -Level Verbose


                # Checking if the database network path exists
                if ($setupResult -ne 'Failed') {
                    Write-Message -Message "Testing database backup network path $DatabaseBackupNetworkPath" -Level Verbose
                    if ((Test-DbaPath -Path $DatabaseBackupNetworkPath -SqlInstance $SourceSqlInstance -SqlCredential $SourceCredential) -ne $true) {
                        # To to create the backup directory for the database
                        try {
                            Write-Message -Message "Database backup network path $DatabaseBackupNetworkPath not found. Trying to create it.." -Level Verbose

                            Invoke-Command2 -Credential $SourceCredential -ScriptBlock {
                                Write-Message -Message "Creating backup folder $DatabaseBackupNetworkPath" -Level Verbose
                                $null = New-Item -Path $DatabaseBackupNetworkPath -ItemType Directory -Credential $SourceCredential -Force:$Force
                            }
                        } catch {
                            $setupResult = "Failed"
                            $comment = "Something went wrong creating the backup directory"

                            Stop-Function -Message "Something went wrong creating the backup directory" -ErrorRecord $_ -Target $SourceSqlInstance -Continue
                        }
                    }
                }

                # Check if the backup job name is set
                if ($BackupJob) {
                    $DatabaseBackupJob = "$BackupJob_$($db.Name)"
                } else {
                    $DatabaseBackupJob = "LSBackup_$($db.Name)"
                }
                Write-Message -Message "Backup job name set to $DatabaseBackupJob" -Level Verbose

                # Check if the backup job schedule name is set
                if ($BackupSchedule) {
                    $DatabaseBackupSchedule = "$BackupSchedule_$($db.Name)"
                } else {
                    $DatabaseBackupSchedule = "LSBackupSchedule_$($db.Name)"
                }
                Write-Message -Message "Backup job schedule name set to $DatabaseBackupSchedule" -Level Verbose

                # Check if secondary database is present on secondary instance
                if (-not $Force -and -not $NoInitialization -and ($DestinationServer.Databases[$SecondaryDatabase].Status -ne 'Restoring') -and ($DestinationServer.Databases.Name -contains $SecondaryDatabase)) {
                    $setupResult = "Failed"
                    $comment = "Secondary database already exists on instance"

                    Stop-Function -Message "Secondary database already exists on instance $destInstance." -ErrorRecord $_ -Target $destInstance -Continue
                }

                # Check if the secondary database needs to be initialized
                if ($setupResult -ne 'Failed') {
                    if (-not $NoInitialization) {
                        # Check if the secondary database exists on the secondary instance
                        if ($DestinationServer.Databases.Name -notcontains $SecondaryDatabase) {
                            # Check if force is being used and no option to generate the full backup is set
                            if ($Force -and -not ($GenerateFullBackup -or $UseExistingFullBackup)) {
                                # Set the option to generate a full backup
                                Write-Message -Message "Set option to initialize secondary database with full backup" -Level Verbose
                                $GenerateFullBackup = $true
                            } elseif (-not $Force -and -not $GenerateFullBackup -and -not $UseExistingFullBackup -and -not $UseBackupFolder) {
                                # Set up the confirm part
                                $message = "The database $SecondaryDatabase does not exist on instance $destInstance. `nDo you want to initialize it by generating a full backup?"
                                $choiceYes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Answer Yes."
                                $choiceNo = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Answer No."
                                $options = [System.Management.Automation.Host.ChoiceDescription[]]($choiceYes, $choiceNo)
                                $result = $host.ui.PromptForChoice($title, $message, $options, 0)

                                # Check the result from the confirm
                                switch ($result) {
                                    # If yes
                                    0 {
                                        # Set the option to generate a full backup
                                        Write-Message -Message "Set option to initialize secondary database with full backup." -Level Verbose
                                        $GenerateFullBackup = $true
                                    }
                                    1 {
                                        $setupResult = "Failed"
                                        $comment = "The database is not initialized on the secondary instance"

                                        Stop-Function -Message "The database is not initialized on the secondary instance. `nPlease initialize the database on the secondary instance, use -GenerateFullbackup or use -Force." -Target $destInstance
                                        return
                                    }
                                } # switch
                            }
                        }
                    }
                }


                # Check the parameters for initialization of the secondary database
                if (-not $NoInitialization -and ($GenerateFullBackup -or $UseExistingFullBackup -or $UseBackupFolder)) {
                    # Check if the restore data and log folder are set
                    if ($setupResult -ne 'Failed') {
                        if (-not $RestoreDataFolder -or -not $RestoreLogFolder) {
                            Write-Message -Message "Restore data folder or restore log folder are not set. Using server defaults" -Level Verbose

                            # Get the default data folder
                            if (-not $RestoreDataFolder) {
                                $DatabaseRestoreDataFolder = $DestinationServer.DefaultFile
                            } else {
                                # Set the restore data folder
                                if ($RestoreDataFolder.EndsWith("\")) {
                                    $DatabaseRestoreDataFolder = "$RestoreDataFolder$($db.Name)"
                                } else {
                                    $DatabaseRestoreDataFolder = "$RestoreDataFolder\$($db.Name)"
                                }
                            }

                            Write-Message -Message "Restore data folder set to $DatabaseRestoreDataFolder" -Level Verbose

                            # Get the default log folder
                            if (-not $RestoreLogFolder) {
                                $DatabaseRestoreLogFolder = $DestinationServer.DefaultLog
                            }

                            Write-Message -Message "Restore log folder set to $DatabaseRestoreLogFolder" -Level Verbose

                            # Check if the restore data folder exists
                            Write-Message -Message "Testing database restore data path $DatabaseRestoreDataFolder" -Level Verbose
                            if ((Test-DbaPath  -Path $DatabaseRestoreDataFolder -SqlInstance $destInstance -SqlCredential $DestinationCredential) -ne $true) {
                                if ($PSCmdlet.ShouldProcess($DestinationServerName, "Creating database restore data folder $DatabaseRestoreDataFolder on $DestinationServerName")) {
                                    # Try creating the data folder
                                    try {
                                        Invoke-Command2 -Credential $DestinationCredential -ScriptBlock {
                                            Write-Message -Message "Creating data folder $DatabaseRestoreDataFolder" -Level Verbose
                                            $null = New-Item -Path $DatabaseRestoreDataFolder -ItemType Directory -Credential $DestinationCredential -Force:$Force
                                        }
                                    } catch {
                                        $setupResult = "Failed"
                                        $comment = "Something went wrong creating the restore data directory"
                                        Stop-Function -Message "Something went wrong creating the restore data directory" -ErrorRecord $_ -Target $SourceSqlInstance -Continue
                                    }
                                }
                            }

                            # Check if the restore log folder exists
                            Write-Message -Message "Testing database restore log path $DatabaseRestoreLogFolder" -Level Verbose
                            if ((Test-DbaPath  -Path $DatabaseRestoreLogFolder -SqlInstance $destInstance -SqlCredential $DestinationCredential) -ne $true) {
                                if ($PSCmdlet.ShouldProcess($DestinationServerName, "Creating database restore log folder $DatabaseRestoreLogFolder on $DestinationServerName")) {
                                    # Try creating the log folder
                                    try {
                                        Write-Message -Message "Restore log folder $DatabaseRestoreLogFolder not found. Trying to create it.." -Level Verbose

                                        Invoke-Command2 -Credential $DestinationCredential -ScriptBlock {
                                            Write-Message -Message "Restore log folder $DatabaseRestoreLogFolder not found. Trying to create it.." -Level Verbose
                                            $null = New-Item -Path $DatabaseRestoreLogFolder -ItemType Directory -Credential $DestinationCredential -Force:$Force
                                        }
                                    } catch {
                                        $setupResult = "Failed"
                                        $comment = "Something went wrong creating the restore log directory"
                                        Stop-Function -Message "Something went wrong creating the restore log directory" -ErrorRecord $_ -Target $SourceSqlInstance -Continue
                                    }
                                }
                            }
                        }
                    }

                    # Check if the full backup path can be reached
                    if ($setupResult -ne 'Failed') {
                        if ($FullBackupPath) {
                            Write-Message -Message "Testing full backup path $FullBackupPath" -Level Verbose
                            if ((Test-DbaPath -Path $FullBackupPath -SqlInstance $destInstance -SqlCredential $DestinationCredential) -ne $true) {
                                $setupResult = "Failed"
                                $comment = "The path to the full backup could not be reached"
                                Stop-Function -Message ("The path to the full backup could not be reached. Check the path and/or the crdential") -ErrorRecord $_ -Target $destInstance -Continue
                            }
                        } elseif ($UseBackupFolder.Length -ge 1) {
                            Write-Message -Message "Testing backup folder $UseBackupFolder" -Level Verbose
                            if ((Test-DbaPath -Path $UseBackupFolder -SqlInstance $destInstance -SqlCredential $DestinationCredential) -ne $true) {
                                $setupResult = "Failed"
                                $comment = "The path to the backup folder could not be reached"
                                Stop-Function -Message ("The path to the backup folder could not be reached. Check the path and/or the crdential") -ErrorRecord $_ -Target $destInstance -Continue
                            }

                            $BackupPath = $UseBackupFolder
                        } elseif ($UseExistingFullBackup) {
                            Write-Message -Message "No path to the full backup is set. Trying to retrieve the last full backup for $db from $SourceSqlInstance" -Level Verbose

                            # Get the last full backup
                            $LastBackup = Get-DbaBackupHistory -SqlInstance $SourceSqlInstance -Databases $($db.Name) -LastFull -Credential $SourceSqlCredential

                            # Check if there was a last backup
                            if ($null -eq $LastBackup) {
                                # Test the path to the backup
                                Write-Message -Message "Testing last backup path $(($LastBackup[-1]).Path[-1])" -Level Verbose
                                if ((Test-DbaPath -Path ($LastBackup[-1]).Path[-1] -SqlInstance $SourceSqlInstance -SqlCredential $SourceCredential) -ne $true) {
                                    $setupResult = "Failed"
                                    $comment = "The full backup could not be found"
                                    Stop-Function -Message "The full backup could not be found on $($LastBackup.Path). Check path and/or credentials" -ErrorRecord $_ -Target $destInstance -Continue
                                }
                                # Check if the source for the last full backup is remote and the backup is on a shared location
                                elseif (($LastBackup.Computername -ne $SourceServerName) -and (($LastBackup[-1]).Path[-1].StartsWith('\\') -eq $false)) {
                                    $setupResult = "Failed"
                                    $comment = "The last full backup is not located on shared location"
                                    Stop-Function -Message "The last full backup is not located on shared location. `n$($_.Exception.Message)" -ErrorRecord $_ -Target $destInstance -Continue
                                } else {
                                    #$FullBackupPath = $LastBackup.Path
                                    $BackupPath = $LastBackup.Path
                                    Write-Message -Message "Full backup found for $db. Path $BackupPath" -Level Verbose
                                }
                            } else {
                                Write-Message -Message "No Full backup found for $db." -Level Verbose
                            }
                        }
                    }
                }

                # Set the copy destination folder to include the database name
                if ($CopyDestinationFolder.EndsWith("\")) {
                    $DatabaseCopyDestinationFolder = "$CopyDestinationFolder$($db.Name)"
                } else {
                    $DatabaseCopyDestinationFolder = "$CopyDestinationFolder\$($db.Name)"
                }
                Write-Message -Message "Copy destination folder set to $DatabaseCopyDestinationFolder." -Level Verbose

                # Check if the copy job name is set
                if ($CopyJob) {
                    $DatabaseCopyJob = "$CopyJob_$SourceServerName_$($db.Name)"
                } else {
                    $DatabaseCopyJob = "LSCopy_$SourceServerName_$($db.Name)"
                }
                Write-Message -Message "Copy job name set to $DatabaseCopyJob" -Level Verbose

                # Check if the copy job schedule name is set
                if ($CopySchedule) {
                    $DatabaseCopySchedule = "$CopySchedule_$($db.Name)"
                } else {
                    $DatabaseCopySchedule = "LSCopySchedule_$($db.Name)"
                    Write-Message -Message "Copy job schedule name set to $DatabaseCopySchedule" -Level Verbose
                }

                # Check if the copy destination folder exists
                if ($setupResult -ne 'Failed') {
                    Write-Message -Message "Testing database copy destination path $DatabaseCopyDestinationFolder" -Level Verbose
                    if ((Test-DbaPath -Path $DatabaseCopyDestinationFolder -SqlInstance $destInstance -SqlCredential $DestinationCredential) -ne $true) {
                        if ($PSCmdlet.ShouldProcess($DestinationServerName, "Creating copy destination folder on $DestinationServerName")) {
                            try {
                                Invoke-Command2 -Credential $DestinationCredential -ScriptBlock {
                                    Write-Message -Message "Copy destination folder $DatabaseCopyDestinationFolder not found. Trying to create it.. ." -Level Verbose
                                    $null = New-Item -Path $DatabaseCopyDestinationFolder -ItemType Directory -Credential $DestinationCredential -Force:$Force
                                }
                            } catch {
                                $setupResult = "Failed"
                                $comment = "Something went wrong creating the database copy destination folder"
                                Stop-Function -Message "Something went wrong creating the database copy destination folder. `n$($_.Exception.Message)" -ErrorRecord $_ -Target $DestinationServerName -Continue
                            }
                        }
                    }
                }

                # Check if the restore job name is set
                if ($RestoreJob) {
                    $DatabaseRestoreJob = "$RestoreJob_$SourceServerName_$($db.Name)"
                } else {
                    $DatabaseRestoreJob = "LSRestore_$DestinationServerName_$($db.Name)"
                }
                Write-Message -Message "Restore job name set to $DatabaseRestoreJob" -Level Verbose

                # Check if the restore job schedule name is set
                if ($RestoreSchedule) {
                    $DatabaseRestoreSchedule = "$RestoreSchedule_$($db.Name)"
                } else {
                    $DatabaseRestoreSchedule = "LSRestoreSchedule_$($db.Name)"
                }
                Write-Message -Message "Restore job schedule name set to $DatabaseRestoreSchedule" -Level Verbose

                # If the database needs to be backed up first
                if ($setupResult -ne 'Failed') {
                    if ($GenerateFullBackup) {
                        if ($PSCmdlet.ShouldProcess($SourceSqlInstance, "Backing up database $db")) {

                            Write-Message -Message "Generating full backup." -Level Verbose
                            Write-Message -Message "Backing up database $db to $DatabaseBackupNetworkPath" -Level Verbose

                            try {
                                $Timestamp = Get-Date -format "yyyyMMddHHmmss"

                                $LastBackup = Backup-DbaDatabase -SqlInstance $SourceSqlInstance `
                                    -SqlCredential $SourceSqlCredential `
                                    -BackupDirectory $DatabaseBackupNetworkPath `
                                    -BackupFileName "FullBackup_$($db.Name)_PreLogShipping_$Timestamp.bak" `
                                    -Databases $($db.Name) `
                                    -Type Full

                                Write-Message -Message "Backup completed." -Level Verbose

                                # Get the last full backup path
                                #$FullBackupPath = $LastBackup.BackupPath
                                $BackupPath = $LastBackup.BackupPath

                                Write-Message -Message "Backup is located at $BackupPath" -Level Verbose
                            } catch {
                                $setupResult = "Failed"
                                $comment = "Something went wrong generating the full backup"
                                Stop-Function -Message "Something went wrong generating the full backup" -ErrorRecord $_ -Target $DestinationServerName -Continue
                            }
                        }
                    }
                }

                # Check of the MonitorServerSecurityMode value is of type string and set the integer value
                if ($PrimaryMonitorServerSecurityMode -notin 0, 1) {
                    $PrimaryMonitorServerSecurityMode = switch ($PrimaryMonitorServerSecurityMode) {
                        "SQLSERVER" { 0 } "WINDOWS" { 1 } default { 1 }
                    }
                }

                # Check the primary monitor server
                if ($Force -and (-not$PrimaryMonitorServer -or [string]$PrimaryMonitorServer -eq '' -or $null -eq $PrimaryMonitorServer)) {
                    Write-Message -Message "Setting monitor server for primary server to $SourceSqlInstance." -Level Verbose
                    $PrimaryMonitorServer = $SourceSqlInstance
                }

                # Check the PrimaryMonitorServerSecurityMode if it's SQL Server authentication
                if ($PrimaryMonitorServerSecurityMode -eq 0) {
                    if ($PrimaryMonitorServerLogin) {
                        $setupResult = "Failed"
                        $comment = "The PrimaryMonitorServerLogin cannot be empty"
                        Stop-Function -Message "The PrimaryMonitorServerLogin cannot be empty when using SQL Server authentication." -Target $SourceSqlInstance -Continue
                    }

                    if ($PrimaryMonitorServerPassword) {
                        $setupResult = "Failed"
                        $comment = "The PrimaryMonitorServerPassword cannot be empty"
                        Stop-Function -Message "The PrimaryMonitorServerPassword cannot be empty when using SQL Server authentication." -Target $ -Continue
                    }
                }

                # Check of the SecondaryMonitorServerSecurityMode value is of type string and set the integer value
                if ($SecondaryMonitorServerSecurityMode -notin 0, 1) {
                    $SecondaryMonitorServerSecurityMode = switch ($SecondaryMonitorServerSecurityMode) {
                        "SQLSERVER" { 0 } "WINDOWS" { 1 } default { 1 }
                    }
                }

                # Check the secondary monitor server
                if ($Force -and (-not $SecondaryMonitorServer -or [string]$SecondaryMonitorServer -eq '' -or $null -eq $SecondaryMonitorServer)) {
                    Write-Message -Message "Setting secondary monitor server for $destInstance to $SourceSqlInstance." -Level Verbose
                    $SecondaryMonitorServer = $SourceSqlInstance
                }

                # Check the MonitorServerSecurityMode if it's SQL Server authentication
                if ($SecondaryMonitorServerSecurityMode -eq 0) {
                    if ($SecondaryMonitorServerLogin) {
                        $setupResult = "Failed"
                        $comment = "The SecondaryMonitorServerLogin cannot be empty"
                        Stop-Function -Message "The SecondaryMonitorServerLogin cannot be empty when using SQL Server authentication." -Target $SourceSqlInstance -Continue
                    }

                    if ($SecondaryMonitorServerPassword) {
                        $setupResult = "Failed"
                        $comment = "The SecondaryMonitorServerPassword cannot be empty"
                        Stop-Function -Message "The SecondaryMonitorServerPassword cannot be empty when using SQL Server authentication." -Target $SourceSqlInstance -Continue
                    }
                }

                # Now that all the checks have been done we can start with the fun stuff !

                # Restore the full backup
                if ($setupResult -ne 'Failed') {
                    if ($PSCmdlet.ShouldProcess($destInstance, "Restoring database $db to $SecondaryDatabase on $destInstance")) {
                        if ($GenerateFullBackup -or $UseExistingFullBackup -or $UseBackupFolder) {
                            try {
                                Write-Message -Message "Start database restore" -Level Verbose
                                if ($NoRecovery -or (-not $Standby)) {
                                    if ($Force) {
                                        $null = Restore-DbaDatabase -SqlInstance $destInstance `
                                            -SqlCredential $DestinationSqlCredential `
                                            -Path $BackupPath `
                                            -DestinationFilePrefix $SecondaryDatabasePrefix `
                                            -DestinationFileSuffix $SecondaryDatabaseSuffix `
                                            -DestinationDataDirectory $DatabaseRestoreDataFolder `
                                            -DestinationLogDirectory $DatabaseRestoreLogFolder `
                                            -DatabaseName $SecondaryDatabase `
                                            -DirectoryRecurse `
                                            -NoRecovery `
                                            -WithReplace
                                    } else {
                                        $null = Restore-DbaDatabase -SqlInstance $destInstance `
                                            -SqlCredential $DestinationSqlCredential `
                                            -Path $BackupPath `
                                            -DestinationFilePrefix $SecondaryDatabasePrefix `
                                            -DestinationFileSuffix $SecondaryDatabaseSuffix `
                                            -DestinationDataDirectory $DatabaseRestoreDataFolder `
                                            -DestinationLogDirectory $DatabaseRestoreLogFolder `
                                            -DatabaseName $SecondaryDatabase `
                                            -DirectoryRecurse `
                                            -NoRecovery
                                    }
                                }

                                # If the database needs to be in standby
                                if ($Standby) {
                                    # Setup the path to the standby file
                                    $StandbyDirectory = "$DatabaseCopyDestinationFolder"

                                    # Check if credentials need to be used
                                    if ($DestinationSqlCredential) {
                                        $null = Restore-DbaDatabase -SqlInstance $destInstance `
                                            -SqlCredential $DestinationSqlCredential `
                                            -Path $BackupPath `
                                            -DestinationFilePrefix $SecondaryDatabasePrefix `
                                            -DestinationFileSuffix $SecondaryDatabaseSuffix `
                                            -DestinationDataDirectory $DatabaseRestoreDataFolder `
                                            -DestinationLogDirectory $DatabaseRestoreLogFolder `
                                            -DatabaseName $SecondaryDatabase `
                                            -DirectoryRecurse `
                                            -StandbyDirectory $StandbyDirectory
                                    } else {
                                        $null = Restore-DbaDatabase -SqlInstance $destInstance `
                                            -Path $BackupPath `
                                            -DestinationFilePrefix $SecondaryDatabasePrefix `
                                            -DestinationFileSuffix $SecondaryDatabaseSuffix `
                                            -DestinationDataDirectory $DatabaseRestoreDataFolder `
                                            -DestinationLogDirectory $DatabaseRestoreLogFolder `
                                            -DatabaseName $SecondaryDatabase `
                                            -DirectoryRecurse `
                                            -StandbyDirectory $StandbyDirectory
                                    }
                                }
                            } catch {
                                $setupResult = "Failed"
                                $comment = "Something went wrong restoring the secondary database"
                                Stop-Function -Message "Something went wrong restoring the secondary database" -ErrorRecord $_ -Target $SourceSqlInstance -Continue
                            }

                            Write-Message -Message "Restore completed." -Level Verbose
                        }
                    }
                }

                #region Set up log shipping on the primary instance
                # Set up log shipping on the primary instance
                if ($setupResult -ne 'Failed') {
                    if ($PSCmdlet.ShouldProcess($SourceSqlInstance, "Configuring logshipping for primary database $db on $SourceSqlInstance")) {
                        try {

                            Write-Message -Message "Configuring logshipping for primary database" -Level Verbose

                            New-DbaLogShippingPrimaryDatabase -SqlInstance $SourceSqlInstance `
                                -SqlCredential $SourceSqlCredential `
                                -Database $($db.Name) `
                                -BackupDirectory $DatabaseBackupLocalPath `
                                -BackupJob $DatabaseBackupJob `
                                -BackupRetention $BackupRetention `
                                -BackupShare $DatabaseBackupNetworkPath `
                                -BackupThreshold $BackupThreshold `
                                -CompressBackup:$BackupCompression `
                                -HistoryRetention $HistoryRetention `
                                -MonitorServer $PrimaryMonitorServer `
                                -MonitorServerSecurityMode $PrimaryMonitorServerSecurityMode `
                                -MonitorCredential $PrimaryMonitorCredential `
                                -ThresholdAlertEnabled:$PrimaryThresholdAlertEnabled `
                                -Force:$Force

                            # Check if the backup job needs to be enabled or disabled
                            if ($BackupScheduleDisabled) {
                                $null = Set-DbaAgentJob -SqlInstance $SourceSqlInstance -SqlCredential $SourceSqlCredential -Job $DatabaseBackupJob -Disabled
                                Write-Message -Message "Disabling backup job $DatabaseBackupJob" -Level Verbose
                            } else {
                                $null = Set-DbaAgentJob -SqlInstance $SourceSqlInstance -SqlCredential $SourceSqlCredential -Job $DatabaseBackupJob -Enabled
                                Write-Message -Message "Enabling backup job $DatabaseBackupJob" -Level Verbose
                            }

                            Write-Message -Message "Create backup job schedule $DatabaseBackupSchedule" -Level Verbose

                            #Variable $BackupJobSchedule marked as unused by PSScriptAnalyzer replaced with $null for catching output
                            $null = New-DbaAgentSchedule -SqlInstance $SourceSqlInstance `
                                -SqlCredential $SourceSqlCredential `
                                -Job $DatabaseBackupJob `
                                -Schedule $DatabaseBackupSchedule `
                                -FrequencyType $BackupScheduleFrequencyType `
                                -FrequencyInterval $BackupScheduleFrequencyInterval `
                                -FrequencySubdayType $BackupScheduleFrequencySubdayType `
                                -FrequencySubdayInterval $BackupScheduleFrequencySubdayInterval `
                                -FrequencyRelativeInterval $BackupScheduleFrequencyRelativeInterval `
                                -FrequencyRecurrenceFactor $BackupScheduleFrequencyRecurrenceFactor `
                                -StartDate $BackupScheduleStartDate `
                                -EndDate $BackupScheduleEndDate `
                                -StartTime $BackupScheduleStartTime `
                                -EndTime $BackupScheduleEndTime `
                                -Force:$Force

                            Write-Message -Message "Configuring logshipping from primary to secondary database." -Level Verbose

                            New-DbaLogShippingPrimarySecondary -SqlInstance $SourceSqlInstance `
                                -SqlCredential $SourceSqlCredential `
                                -PrimaryDatabase $($db.Name) `
                                -SecondaryDatabase $SecondaryDatabase `
                                -SecondaryServer $destInstance `
                                -SecondarySqlCredential $DestinationSqlCredential
                        } catch {
                            $setupResult = "Failed"
                            $comment = "Something went wrong setting up log shipping for primary instance"
                            Stop-Function -Message "Something went wrong setting up log shipping for primary instance" -ErrorRecord $_ -Target $SourceSqlInstance -Continue
                        }
                    }
                }
                #endregion Set up log shipping on the primary instance

                #region Set up log shipping on the secondary instance
                # Set up log shipping on the secondary instance
                if ($setupResult -ne 'Failed') {
                    if ($PSCmdlet.ShouldProcess($destInstance, "Configuring logshipping for secondary database $SecondaryDatabase on $destInstance")) {
                        try {

                            Write-Message -Message "Configuring logshipping from secondary database $SecondaryDatabase to primary database $db." -Level Verbose

                            New-DbaLogShippingSecondaryPrimary -SqlInstance $destInstance `
                                -SqlCredential $DestinationSqlCredential `
                                -BackupSourceDirectory $DatabaseBackupNetworkPath `
                                -BackupDestinationDirectory $DatabaseCopyDestinationFolder `
                                -CopyJob $DatabaseCopyJob `
                                -FileRetentionPeriod $BackupRetention `
                                -MonitorServer $SecondaryMonitorServer `
                                -MonitorServerSecurityMode $SecondaryMonitorServerSecurityMode `
                                -MonitorCredential $SecondaryMonitorCredential `
                                -PrimaryServer $SourceSqlInstance `
                                -PrimaryDatabase $($db.Name) `
                                -RestoreJob $DatabaseRestoreJob `
                                -Force:$Force

                            Write-Message -Message "Create copy job schedule $DatabaseCopySchedule" -Level Verbose
                            #Variable $CopyJobSchedule marked as unused by PSScriptAnalyzer replaced with $null for catching output
                            $null = New-DbaAgentSchedule -SqlInstance $destInstance `
                                -SqlCredential $DestinationSqlCredential `
                                -Job $DatabaseCopyJob `
                                -Schedule $DatabaseCopySchedule `
                                -FrequencyType $CopyScheduleFrequencyType `
                                -FrequencyInterval $CopyScheduleFrequencyInterval `
                                -FrequencySubdayType $CopyScheduleFrequencySubdayType `
                                -FrequencySubdayInterval $CopyScheduleFrequencySubdayInterval `
                                -FrequencyRelativeInterval $CopyScheduleFrequencyRelativeInterval `
                                -FrequencyRecurrenceFactor $CopyScheduleFrequencyRecurrenceFactor `
                                -StartDate $CopyScheduleStartDate `
                                -EndDate $CopyScheduleEndDate `
                                -StartTime $CopyScheduleStartTime `
                                -EndTime $CopyScheduleEndTime `
                                -Force:$Force

                            Write-Message -Message "Create restore job schedule $DatabaseRestoreSchedule" -Level Verbose

                            #Variable $RestoreJobSchedule marked as unused by PSScriptAnalyzer replaced with $null for catching output
                            $null = New-DbaAgentSchedule -SqlInstance $destInstance `
                                -SqlCredential $DestinationSqlCredential `
                                -Job $DatabaseRestoreJob `
                                -Schedule $DatabaseRestoreSchedule `
                                -FrequencyType $RestoreScheduleFrequencyType `
                                -FrequencyInterval $RestoreScheduleFrequencyInterval `
                                -FrequencySubdayType $RestoreScheduleFrequencySubdayType `
                                -FrequencySubdayInterval $RestoreScheduleFrequencySubdayInterval `
                                -FrequencyRelativeInterval $RestoreScheduleFrequencyRelativeInterval `
                                -FrequencyRecurrenceFactor $RestoreScheduleFrequencyRecurrenceFactor `
                                -StartDate $RestoreScheduleStartDate `
                                -EndDate $RestoreScheduleEndDate `
                                -StartTime $RestoreScheduleStartTime `
                                -EndTime $RestoreScheduleEndTime `
                                -Force:$Force

                            Write-Message -Message "Configuring logshipping for secondary database." -Level Verbose

                            New-DbaLogShippingSecondaryDatabase -SqlInstance $destInstance `
                                -SqlCredential $DestinationSqlCredential `
                                -SecondaryDatabase $SecondaryDatabase `
                                -PrimaryServer $SourceSqlInstance `
                                -PrimaryDatabase $($db.Name) `
                                -RestoreDelay $RestoreDelay `
                                -RestoreMode $DatabaseStatus `
                                -DisconnectUsers:$DisconnectUsers `
                                -RestoreThreshold $RestoreThreshold `
                                -ThresholdAlertEnabled:$SecondaryThresholdAlertEnabled `
                                -HistoryRetention $HistoryRetention `
                                -MonitorServer $PrimaryMonitorServer `
                                -MonitorServerSecurityMode $PrimaryMonitorServerSecurityMode `
                                -MonitorCredential $PrimaryMonitorCredential

                            # Check if the copy job needs to be enabled or disabled
                            if ($CopyScheduleDisabled) {
                                $null = Set-DbaAgentJob -SqlInstance $destInstance -SqlCredential $DestinationSqlCredential -Job $DatabaseCopyJob -Disabled
                            } else {
                                $null = Set-DbaAgentJob -SqlInstance $destInstance -SqlCredential $DestinationSqlCredential -Job $DatabaseCopyJob -Enabled
                            }

                            # Check if the restore job needs to be enabled or disabled
                            if ($RestoreScheduleDisabled) {
                                $null = Set-DbaAgentJob -SqlInstance $destInstance -SqlCredential $DestinationSqlCredential -Job $DatabaseRestoreJob -Disabled
                            } else {
                                $null = Set-DbaAgentJob -SqlInstance $destInstance -SqlCredential $DestinationSqlCredential -Job $DatabaseRestoreJob -Enabled
                            }

                        } catch {
                            $setupResult = "Failed"
                            $comment = "Something went wrong setting up log shipping for secondary instance"
                            Stop-Function -Message "Something went wrong setting up log shipping for secondary instance.`n$($_.Exception.Message)" -ErrorRecord $_ -Target $destInstance -Continue
                        }
                    }
                }
                #endregion Set up log shipping on the secondary instance

                Write-Message -Message "Completed configuring log shipping for database $db" -Level Verbose

                [PSCustomObject]@{
                    PrimaryInstance   = $SourceServer.DomainInstanceName
                    SecondaryInstance = $DestinationServer.DomainInstanceName
                    PrimaryDatabase   = $($db.Name)
                    SecondaryDatabase = $SecondaryDatabase
                    Result            = $setupResult
                    Comment           = $comment
                }

            } # for each database
        } # end for each destination server
    } # end process
    end {
        Write-Message -Message "Finished setting up log shipping." -Level Verbose
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Invoke-DbaLogShipping
    }
}
tools\dbatools\functions\Invoke-DbaDbLogShipRecovery.ps1
function Invoke-DbaDbLogShipRecovery {
    <#
    .SYNOPSIS
        Invoke-DbaDbLogShipRecovery recovers log shipped databases to a normal state to act upon a migration or disaster.

    .DESCRIPTION
        By default all the databases for a particular instance are recovered.
        If the database is in the right state, either standby or recovering, the process will try to recover the database.

        At first the function will check if the backup source directory can still be reached.
        If so it will look up the last transaction log backup for the database. If that backup file is not the last copied file the log shipping copy job will be started.
        If the directory cannot be reached for the function will continue to the restoring process.
        After the copy job check is performed the job is disabled to prevent the job to run.

        For the restore the log shipping status is checked in the msdb database.
        If the last restored file is not the same as the last file name found, the log shipping restore job will be executed.
        After the restore job check is performed the job is disabled to prevent the job to run

        The last part is to set the database online by restoring the databases with recovery

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER Database
        Database to perform the restore for. This value can also be piped enabling multiple databases to be recovered.
        If this value is not supplied all databases will be recovered.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER NoRecovery
        Allows you to choose to not restore the database to a functional state (Normal) in the final steps of the process.
        By default the database is restored to a functional state (Normal).

    .PARAMETER InputObject
        Allows piped input from Get-DbaDatabase

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER Force
        Use this parameter to force the function to continue and perform any adjusting actions to successfully execute

    .PARAMETER Delay
        Set the delay in seconds to wait for the copy and/or restore jobs.
        By default the delay is 5 seconds

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .NOTES
        Tags: LogShipping
        Author: Sander Stad (@sqlstad), sqlstad.nl

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaDbLogShipRecovery

    .EXAMPLE
        PS C:\> Invoke-DbaDbLogShipRecovery -SqlInstance server1

        Recovers all the databases on the instance that are enabled for log shipping

    .EXAMPLE
        PS C:\> Invoke-DbaDbLogShipRecovery -SqlInstance server1 -SqlCredential $cred -Verbose

        Recovers all the databases on the instance that are enabled for log shipping using a credential

    .EXAMPLE
        PS C:\> Invoke-DbaDbLogShipRecovery -SqlInstance server1 -database db_logship -Verbose

        Recovers the database "db_logship" to a normal status

    .EXAMPLE
        PS C:\> db1, db2, db3, db4 | Invoke-DbaDbLogShipRecovery -SqlInstance server1 -Verbose

        Recovers the database db1, db2, db3, db4 to a normal status

    .EXAMPLE
        PS C:\> Invoke-DbaDbLogShipRecovery -SqlInstance server1 -WhatIf

        Shows what would happen if the command were executed.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param
    (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [string[]]$Database,
        [PSCredential]$SqlCredential,
        [switch]$NoRecovery,
        [Alias('Silent')]
        [switch]$EnableException,
        [switch]$Force,
        [Parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [int]$Delay = 5
    )
    begin {
        $stepCounter = 0
    }
    process {
        foreach ($instance in $SqlInstance) {
            if (-not $Force -and -not $Database) {
                Stop-Function -Message "You must specify a -Database or -Force for all databases" -Target $server.name
                return
            }
            $InputObject += Get-DbaDatabase -SqlInstance $instance -SqlCredential $SqlCredential -Database $Database
        }

        # Loop through all the databases
        foreach ($db in $InputObject) {
            $stepCounter = 0
            $server = $db.Parent
            $instance = $server.Name
            $activity = "Performing log shipping recovery for $($db.Name) on $($server.Name)"
            # Try to get the agent service details
            try {
                # Get the service details
                $agentStatus = $server.Query("SELECT COUNT(*) as AgentCount FROM master.dbo.sysprocesses WITH (nolock) WHERE Program_Name LIKE 'SQLAgent%'")

                if ($agentStatus.AgentCount -lt 1) {
                    Stop-Function -Message "The agent service is not in a running state. Please start the service." -ErrorRecord $_ -Target $server.name
                    return
                }
            } catch {
                Stop-Function -Message "Unable to get SQL Server Agent Service status" -ErrorRecord $_ -Target $server.name
                return
            }
            # Query for retrieving the log shipping information
            $query = "SELECT lss.primary_server, lss.primary_database, lsd.secondary_database, lss.backup_source_directory,
                    lss.backup_destination_directory, lss.last_copied_file, lss.last_copied_date,
                    lsd.last_restored_file, sj1.name AS 'copyjob', sj2.name AS 'restorejob'
                FROM msdb.dbo.log_shipping_secondary AS lss
                    INNER JOIN msdb.dbo.log_shipping_secondary_databases AS lsd ON lsd.secondary_id = lss.secondary_id
                    INNER JOIN msdb.dbo.sysjobs AS sj1 ON sj1.job_id = lss.copy_job_id
                    INNER JOIN msdb.dbo.sysjobs AS sj2 ON sj2.job_id = lss.restore_job_id
                WHERE lsd.secondary_database = '$($db.Name)'"

            # Retrieve the log shipping information from the secondary instance
            try {
                Write-Message -Message "Retrieving log shipping information from the secondary instance" -Level Verbose
                Write-ProgressHelper -Activity $activity -StepNumber ($stepCounter++) -Message "Retrieving log shipping information from the secondary instance"
                $logshipping_details = $server.Query($query)
            } catch {
                Stop-Function -Message "Error retrieving the log shipping details: $($_.Exception.Message)" -ErrorRecord $_ -Target $server.name
                return
            }

            # Check if there are any databases to recover
            if ($null -eq $logshipping_details) {
                Stop-Function -Message "The database $db is not configured as a secondary database for log shipping." -Continue
            } else {
                # Loop through each of the log shipped databases
                foreach ($ls in $logshipping_details) {
                    $secondarydb = $ls.secondary_database

                    $recoverResult = "Success"
                    $comment = ""
                    $jobOutputs = @()

                    # Check if the database is in the right state
                    if ($server.Databases[$secondarydb].Status -notin ('Normal, Standby', 'Standby', 'Restoring')) {
                        Stop-Function -Message "The database $db doesn't have the right status to be recovered" -Continue
                    } else {
                        Write-Message -Message "Started Recovery for $secondarydb" -Level Verbose

                        # Start the job to get the latest files
                        if ($PSCmdlet.ShouldProcess($server.name, ("Starting copy job $($ls.copyjob)"))) {
                            Write-Message -Message "Starting copy job $($ls.copyjob)" -Level Verbose

                            Write-ProgressHelper -Activity $activity -StepNumber ($stepCounter++) -Message "Starting copy job"
                            try {
                                $null = Start-DbaAgentJob -SqlInstance $instance -SqlCredential $sqlcredential -Job $ls.copyjob
                            } catch {
                                $recoverResult = "Failed"
                                $comment = "Something went wrong starting the copy job $($ls.copyjob)"
                                Stop-Function -Message "Something went wrong starting the copy job.`n$($_)" -ErrorRecord $_ -Target $server.name
                            }

                            if ($recoverResult -ne 'Failed') {
                                Write-Message -Message "Copying files to $($ls.backup_destination_directory)" -Level Verbose

                                Write-Message -Message "Waiting for the copy action to complete.." -Level Verbose

                                # Get the job status
                                $jobStatus = Get-DbaAgentJob -SqlInstance $instance -SqlCredential $sqlcredential -Job $ls.copyjob

                                while ($jobStatus.CurrentRunStatus -ne 'Idle') {
                                    # Sleep for while to let the files be copied
                                    Start-Sleep -Seconds $Delay

                                    # Get the job status
                                    $jobStatus = Get-DbaAgentJob -SqlInstance $instance -SqlCredential $sqlcredential -Job $ls.copyjob
                                }

                                # Check the lat outcome of the job
                                if ($jobStatus.LastRunOutcome -eq 'Failed') {
                                    $recoverResult = "Failed"
                                    $comment = "The copy job for database $db failed. Please check the error log."
                                    Stop-Function -Message "The copy job for database $db failed. Please check the error log."
                                }

                                $jobOutputs += $jobStatus

                                Write-Message -Message "Copying of backup files finished" -Level Verbose
                            }
                        } # if should process

                        # Disable the log shipping copy job on the secondary instance
                        if ($recoverResult -ne 'Failed') {
                            Write-ProgressHelper -Activity $activity -StepNumber ($stepCounter++) -Message "Disabling copy job"

                            if ($PSCmdlet.ShouldProcess($server.name, "Disabling copy job $($ls.copyjob)")) {
                                try {
                                    Write-Message -Message "Disabling copy job $($ls.copyjob)" -Level Verbose
                                    $null = Set-DbaAgentJob -SqlInstance $instance -SqlCredential $sqlcredential -Job $ls.copyjob -Disabled
                                } catch {
                                    $recoverResult = "Failed"
                                    $comment = "Something went wrong disabling the copy job."
                                    Stop-Function -Message "Something went wrong disabling the copy job.`n$($_)" -ErrorRecord $_ -Target $server.name
                                }
                            }
                        }

                        if ($recoverResult -ne 'Failed') {
                            # Start the restore job
                            Write-ProgressHelper -Activity $activity -StepNumber ($stepCounter++) -Message "Starting restore job"

                            if ($PSCmdlet.ShouldProcess($server.name, ("Starting restore job " + $ls.restorejob))) {
                                Write-Message -Message "Starting restore job $($ls.restorejob)" -Level Verbose
                                try {
                                    $null = Start-DbaAgentJob -SqlInstance $instance -SqlCredential $sqlcredential -Job $ls.restorejob
                                } catch {
                                    $comment = "Something went wrong starting the restore job."
                                    Stop-Function -Message "Something went wrong starting the restore job.`n$($_)" -ErrorRecord $_ -Target $server.name
                                }

                                Write-Message -Message "Waiting for the restore action to complete.." -Level Verbose

                                # Get the job status
                                $jobStatus = Get-DbaAgentJob -SqlInstance $instance -SqlCredential $sqlcredential -Job $ls.restorejob

                                while ($jobStatus.CurrentRunStatus -ne 'Idle') {
                                    # Sleep for while to let the files be copied
                                    Start-Sleep -Seconds $Delay

                                    # Get the job status
                                    $jobStatus = Get-DbaAgentJob -SqlInstance $instance -SqlCredential $sqlcredential -Job $ls.restorejob
                                }

                                # Check the lat outcome of the job
                                if ($jobStatus.LastRunOutcome -eq 'Failed') {
                                    $recoverResult = "Failed"
                                    $comment = "The restore job for database $db failed. Please check the error log."
                                    Stop-Function -Message "The restore job for database $db failed. Please check the error log."
                                }

                                $jobOutputs += $jobStatus
                            }
                        }

                        if ($recoverResult -ne 'Failed') {
                            # Disable the log shipping restore job on the secondary instance
                            if ($PSCmdlet.ShouldProcess($server.name, "Disabling restore job $($ls.restorejob)")) {
                                try {
                                    Write-Message -Message ("Disabling restore job " + $ls.restorejob) -Level Verbose
                                    $null = Set-DbaAgentJob -SqlInstance $instance -SqlCredential $sqlcredential -Job $ls.restorejob -Disabled
                                } catch {
                                    $recoverResult = "Failed"
                                    $comment = "Something went wrong disabling the restore job."
                                    Stop-Function -Message "Something went wrong disabling the restore job.`n$($_)" -ErrorRecord $_ -Target $server.name
                                }
                            }
                        }

                        if ($recoverResult -ne 'Failed') {
                            # Check if the database needs to recovered to its normal state
                            if ($NoRecovery -eq $false) {
                                if ($PSCmdlet.ShouldProcess($secondarydb, "Restoring database with recovery")) {
                                    Write-Message -Message "Restoring the database to it's normal state" -Level Verbose
                                    try {
                                        $query = "RESTORE DATABASE [$secondarydb] WITH RECOVERY"
                                        $server.Query($query)

                                    } catch {
                                        $recoverResult = "Failed"
                                        $comment = "Something went wrong restoring the database to a normal state."
                                        Stop-Function -Message "Something went wrong restoring the database to a normal state.`n$($_)" -ErrorRecord $_ -Target $secondarydb
                                    }
                                }
                            } else {
                                $comment = "Skipping restore with recovery."
                                Write-Message -Message "Skipping restore with recovery" -Level Verbose
                            }

                            Write-Message -Message ("Finished Recovery for $secondarydb") -Level Verbose
                        }

                        # Reset the log ship details
                        $logshipping_details = $null

                        [PSCustomObject]@{
                            ComputerName  = $server.ComputerName
                            InstanceName  = $server.InstanceName
                            SqlInstance   = $server.DomainInstanceName
                            Database      = $secondarydb
                            RecoverResult = $recoverResult
                            Comment       = $comment
                        }

                    }
                }
            }
            Write-Progress -Activity $activity -Completed
            $stepCounter = 0
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Invoke-DbaLogShippingRecovery
    }
}
tools\dbatools\functions\Invoke-DbaDbMirrorFailover.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Invoke-DbaDbMirrorFailover {
    <#
    .SYNOPSIS
        Failover a mirrored database

    .DESCRIPTION
        Failover a mirrored database

    .PARAMETER SqlInstance
        SQL Server name or SMO object representing the primary SQL Server.

    .PARAMETER SqlCredential
        Login to the primary instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database or databases to mirror

    .PARAMETER InputObject
        Allows piping from Get-DbaDatabase

    .PARAMETER Force
        Force Failover and allow data loss

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Mirror, HA
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        TODO: add service accounts

    .LINK
        https://dbatools.io/Invoke-DbaDbMirrorFailover

    .EXAMPLE
        PS C:\> Invoke-DbaDbMirrorFailover -SqlInstance sql2016 -Database pubs

        Fails over the pubs database on sql2016. Prompts for confirmation.

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sql2016 -Database pubs | Invoke-DbaDbMirrorFailover -Force -Confirm:$false

        Forces the failover of the pubs database on sql2016 and allows data loss.
        Does not prompt for confirmation.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$Force,
        [switch]$EnableException
    )
    process {
        if ((Test-Bound -ParameterName SqlInstance) -and (Test-Bound -Not -ParameterName Database)) {
            Stop-Function -Message "Database is required when SqlInstance is specified"
            return
        }

        $InputObject += Get-DbaDatabase -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database

        foreach ($db in $InputObject) {
            # if it's async, you have to break the mirroring and allow data loss
            # alter database set partner force_service_allow_data_loss
            # if it's sync mirroring you know it's all in sync, so you can just do alter database [dbname] set partner failover
            if ($Force) {
                if ($Pscmdlet.ShouldProcess($db.Parent.Name, "Forcing failover of $db and allowing data loss")) {
                    $db | Set-DbaDbMirror -State ForceFailoverAndAllowDataLoss
                }
            } else {
                if ($Pscmdlet.ShouldProcess($db.Parent.Name, "Setting safety level to full and failing over $db to partner server")) {
                    $db | Set-DbaDbMirror -SafetyLevel Full
                    $db | Set-DbaDbMirror -State Failover
                }
            }
        }
    }
}
tools\dbatools\functions\Invoke-DbaDbMirroring.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Invoke-DbaDbMirroring {
    <#
    .SYNOPSIS
        Automates the creation of database mirrors.

    .DESCRIPTION
        Automates the creation of database mirrors.

        * Verifies that a mirror is possible
        * Sets the recovery model to Full if needed
        * If the database does not exist on mirror or witness, a backup/restore is performed
        * Sets up endpoints if necessary
        * Creates a login and grants permissions to service accounts if needed
        * Starts endpoints if needed
        * Sets up partner for mirror
        * Sets up partner for primary
        * Sets up witness if one is specified

        NOTE: If a backup / restore is performed, the backups will be left in tact on the network share.

    .PARAMETER Primary
        SQL Server name or SMO object representing the primary SQL Server.

    .PARAMETER PrimarySqlCredential
        Login to the primary instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Mirror
        SQL Server name or SMO object representing the mirror SQL Server.

    .PARAMETER MirrorSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Witness
        SQL Server name or SMO object representing the witness SQL Server.

    .PARAMETER WitnessSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database or databases to mirror.

    .PARAMETER SharedPath
        The network share where the backups will be backed up and restored from.

        Each SQL Server service account must have access to this share.

        NOTE: If a backup / restore is performed, the backups will be left in tact on the network share.

    .PARAMETER InputObject
        Enables piping from Get-DbaDatabase.

    .PARAMETER UseLastBackup
        Use the last full backup of database.

    .PARAMETER Force
        Drop and recreate the database on remote servers using fresh backup.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Mirror, HA
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaDbMirroring

    .EXAMPLE
        PS C:\> $params = @{
        >> Primary = 'sql2017a'
        >> Mirror = 'sql2017b'
        >> MirrorSqlCredential = 'sqladmin'
        >> Witness = 'sql2019'
        >> Database = 'pubs'
        >> SharedPath = '\\nas\sql\share'
        >> }
        >>
        PS C:\> Invoke-DbaDbMirroring @params

        Performs a bunch of checks to ensure the pubs database on sql2017a
        can be mirrored from sql2017a to sql2017b. Logs in to sql2019 and sql2017a
        using Windows credentials and sql2017b using a SQL credential.

        Prompts for confirmation for most changes. To avoid confirmation, use -Confirm:$false or
        use the syntax in the second example.

    .EXAMPLE
        PS C:\> $params = @{
        >> Primary = 'sql2017a'
        >> Mirror = 'sql2017b'
        >> MirrorSqlCredential = 'sqladmin'
        >> Witness = 'sql2019'
        >> Database = 'pubs'
        >> SharedPath = '\\nas\sql\share'
        >> Force = $true
        >> Confirm = $false
        >> }
        >>
        PS C:\> Invoke-DbaDbMirroring @params

        Performs a bunch of checks to ensure the pubs database on sql2017a
        can be mirrored from sql2017a to sql2017b. Logs in to sql2019 and sql2017a
        using Windows credentials and sql2017b using a SQL credential.

        Drops existing pubs database on Mirror and Witness and restores them with
        a fresh backup.

        Does all the things in the decription, does not prompt for confirmation.

    .EXAMPLE
        PS C:\> $map = @{ 'database_data' = 'M:\Data\database_data.mdf' 'database_log' = 'L:\Log\database_log.ldf' }
        PS C:\> Get-ChildItem \\nas\seed | Restore-DbaDatabase -SqlInstance sql2017b -FileMapping $map -NoRecovery
        PS C:\> Get-DbaDatabase -SqlInstance sql2017a -Database pubs | Invoke-DbaDbMirroring -Mirror sql2017b -Confirm:$false

        Restores backups from sql2017a to a specific file struture on sql2017b then creates mirror with no prompts for confirmation.

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sql2017a -Database pubs |
        >> Invoke-DbaDbMirroring -Mirror sql2017b -UseLastBackup -Confirm:$false

        Mirrors pubs on sql2017a to sql2017b and uses the last full and logs from sql2017a to seed. Doesn't prompt for confirmation.

       #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [DbaInstanceParameter]$Primary,
        [PSCredential]$PrimarySqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Mirror,
        [PSCredential]$MirrorSqlCredential,
        [DbaInstanceParameter]$Witness,
        [PSCredential]$WitnessSqlCredential,
        [string[]]$Database,
        [Alias("NetworkShare")]
        [string]$SharedPath,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$UseLastBackup,
        [switch]$Force,
        [switch]$EnableException
    )
    begin {
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter NetworkShare -CustomMessage "Using the parameter NetworkShare is deprecated. This parameter will be removed in version 1.0.0 or before. Use SharedPath instead."
        
        $params = $PSBoundParameters
        $null = $params.Remove('UseLastBackup')
        $null = $params.Remove('Force')
        $null = $params.Remove('Confirm')
        $null = $params.Remove('Whatif')
    }
    process {
        if ((Test-Bound -ParameterName Primary) -and (Test-Bound -Not -ParameterName Database)) {
            Stop-Function -Message "Database is required when Primary is specified"
            return
        }

        if ($Force -and (-not $SharedPath -and -not $UseLastBackup)) {
            Stop-Function -Message "SharedPath or UseLastBackup is required when Force is used"
            return
        }

        if ($Primary) {
            $InputObject += Get-DbaDatabase -SqlInstance $Primary -SqlCredential $PrimarySqlCredential -Database $Database
        }

        foreach ($primarydb in $InputObject) {
            $stepCounter = 0
            $Primary = $source = $primarydb.Parent

            try {
                $dest = Connect-SqlInstance -SqlInstance $Mirror -SqlCredential $MirrorSqlCredential

                if ($Witness) {
                    $witserver = Connect-SqlInstance -SqlInstance $Witness -SqlCredential $WitnessSqlCredential
                }
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $dbName = $primarydb.Name

            Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Validating mirror setup"
            # Thanks to https://github.com/mmessano/PowerShell/blob/master/SQL-ConfigureDatabaseMirroring.ps1 for the tips

            $validation = Invoke-DbMirrorValidation @params

            if ((Test-Bound -ParameterName SharedPath) -and -not $validation.AccessibleShare) {
                Stop-Function -Continue -Message "Cannot access $SharedPath from $($dest.Name)"
            }

            if (-not $validation.EditionMatch) {
                Stop-Function -Continue -Message "This mirroring configuration is not supported. Because the principal server instance, $source, is $($source.EngineEdition) Edition, the mirror server instance must also be $($source.EngineEdition) Edition."
            }

            if ($validation.MirroringStatus -ne "None") {
                Stop-Function -Continue -Message "Cannot setup mirroring on database ($dbname) due to its current mirroring state: $($primarydb.MirroringStatus)"
            }

            if ($primarydb.Status -ne "Normal") {
                Stop-Function -Continue -Message "Cannot setup mirroring on database ($dbname) due to its current state: $($primarydb.Status)"
            }

            Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Setting recovery model for $dbName on $($source.Name) to Full"

            if ($primarydb.RecoveryModel -ne "Full") {
                if ((Test-Bound -ParameterName UseLastBackup)) {
                    Stop-Function -Continue -Message "$dbName not set to full recovery. UseLastBackup cannot be used."
                } else {
                    Set-DbaDbRecoveryModel -SqlInstance $source -Database $primarydb.Name -RecoveryModel Full
                }
            }

            Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Copying $dbName from primary to mirror"
            if (-not $validation.DatabaseExistsOnMirror -or $Force) {
                if ($UseLastBackup) {
                    $allbackups = Get-DbaBackupHistory -SqlInstance $primarydb.Parent -Database $primarydb.Name -IncludeCopyOnly -Last
                } else {
                    if ($Force -or $Pscmdlet.ShouldProcess("$Primary", "Creating full and log backups of $primarydb on $SharedPath")) {
                        $fullbackup = $primarydb | Backup-DbaDatabase -BackupDirectory $SharedPath -Type Full
                        $logbackup = $primarydb | Backup-DbaDatabase -BackupDirectory $SharedPath -Type Log
                        $allbackups = $fullbackup, $logbackup
                    }
                }
                if ($Pscmdlet.ShouldProcess("$Mirror", "Restoring full and log backups of $primarydb from $Primary")) {
                    foreach ($mirrorinstance in $Mirror) {
                        try {
                            $null = $allbackups | Restore-DbaDatabase -SqlInstance $mirrorinstance -SqlCredential $MirrorSqlCredential -WithReplace -NoRecovery -TrustDbBackupHistory -EnableException
                        } catch {
                            Stop-Function -Message "Failure" -ErrorRecord $_ -Target $dest -Continue
                        }
                    }
                }

                if ($SharedPath) {
                    Write-Message -Level Verbose -Message "Backups still exist on $SharedPath"
                }
            }

            $mirrordb = Get-DbaDatabase -SqlInstance $dest -Database $dbName

            Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Copying $dbName from primary to witness"

            if ($Witness -and (-not $validation.DatabaseExistsOnWitness -or $Force)) {
                if (-not $allbackups) {
                    if ($UseLastBackup) {
                        $allbackups = Get-DbaBackupHistory -SqlInstance $primarydb.Parent -Database $primarydb.Name -IncludeCopyOnly -Last
                    } else {
                        if ($Force -or $Pscmdlet.ShouldProcess("$Primary", "Creating full and log backups of $primarydb on $SharedPath")) {
                            $fullbackup = $primarydb | Backup-DbaDatabase -BackupDirectory $SharedPath -Type Full
                            $logbackup = $primarydb | Backup-DbaDatabase -BackupDirectory $SharedPath -Type Log
                            $allbackups = $fullbackup, $logbackup
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess("$Witness", "Restoring full and log backups of $primarydb from $Primary")) {
                    try {
                        $null = $allbackups | Restore-DbaDatabase -SqlInstance $Witness -SqlCredential $WitnessSqlCredential -WithReplace -NoRecovery -TrustDbBackupHistory -EnableException
                    } catch {
                        Stop-Function -Message "Failure" -ErrorRecord $_ -Target $witserver -Continue
                    }
                }
            }

            $primaryendpoint = Get-DbaEndpoint -SqlInstance $source | Where-Object EndpointType -eq DatabaseMirroring
            $mirrorendpoint = Get-DbaEndpoint -SqlInstance $dest | Where-Object EndpointType -eq DatabaseMirroring

            if (-not $primaryendpoint) {
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Setting up endpoint for primary"
                $primaryendpoint = New-DbaEndpoint -SqlInstance $source -Type DatabaseMirroring -Role Partner -Name Mirroring -EncryptionAlgorithm RC4
                $null = $primaryendpoint | Stop-DbaEndpoint
                $null = $primaryendpoint | Start-DbaEndpoint
            }

            if (-not $mirrorendpoint) {
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Setting up endpoint for mirror"
                $mirrorendpoint = New-DbaEndpoint -SqlInstance $dest -Type DatabaseMirroring -Role Partner -Name Mirroring -EncryptionAlgorithm RC4
                $null = $mirrorendpoint | Stop-DbaEndpoint
                $null = $mirrorendpoint | Start-DbaEndpoint
            }

            if ($witserver) {
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Setting up endpoint for witness"
                $witnessendpoint = Get-DbaEndpoint -SqlInstance $witserver | Where-Object EndpointType -eq DatabaseMirroring
                if (-not $witnessendpoint) {
                    $witnessendpoint = New-DbaEndpoint -SqlInstance $witserver -Type DatabaseMirroring -Role Witness -Name Mirroring -EncryptionAlgorithm RC4
                    $null = $witnessendpoint | Stop-DbaEndpoint
                    $null = $witnessendpoint | Start-DbaEndpoint
                }
            }

            Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Granting permissions to service account"

            $serviceaccounts = $source.ServiceAccount, $dest.ServiceAccount, $witserver.ServiceAccount | Select-Object -Unique

            foreach ($account in $serviceaccounts) {
                if ($Pscmdlet.ShouldProcess("primary, mirror and witness (if specified)", "Creating login $account and granting CONNECT ON ENDPOINT")) {
                    $null = New-DbaLogin -SqlInstance $source -Login $account -WarningAction SilentlyContinue
                    $null = New-DbaLogin -SqlInstance $dest -Login $account -WarningAction SilentlyContinue
                    try {
                        $null = $source.Query("GRANT CONNECT ON ENDPOINT::$primaryendpoint TO [$account]")
                        $null = $dest.Query("GRANT CONNECT ON ENDPOINT::$mirrorendpoint TO [$account]")
                        if ($witserver) {
                            $null = New-DbaLogin -SqlInstance $witserver -Login $account -WarningAction SilentlyContinue
                            $witserver.Query("GRANT CONNECT ON ENDPOINT::$witnessendpoint TO [$account]")
                        }
                    } catch {
                        Stop-Function -Continue -Message "Failure" -ErrorRecord $_
                    }
                }
            }

            Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Starting endpoints if necessary"
            try {
                $null = $primaryendpoint, $mirrorendpoint, $witnessendpoint | Start-DbaEndpoint -EnableException
            } catch {
                Stop-Function -Continue -Message "Failure" -ErrorRecord $_
            }

            try {
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Setting up partner for mirror"
                $null = $mirrordb | Set-DbaDbMirror -Partner $primaryendpoint.Fqdn -EnableException
            } catch {
                Stop-Function -Continue -Message "Failure on mirror" -ErrorRecord $_
            }

            try {
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Setting up partner for primary"
                $null = $primarydb | Set-DbaDbMirror -Partner $mirrorendpoint.Fqdn -EnableException
            } catch {
                Stop-Function -Continue -Message "Failure on primary" -ErrorRecord $_
            }

            try {
                if ($witnessendpoint) {
                    $null = $primarydb | Set-DbaDbMirror -Witness $witnessendpoint.Fqdn -EnableException
                }
            } catch {
                Stop-Function -Continue -Message "Failure with the new last part" -ErrorRecord $_
            }

            if ($Pscmdlet.ShouldProcess("console", "Showing results")) {
                $results = [pscustomobject]@{
                    Primary  = $Primary
                    Mirror   = $Mirror -join ", "
                    Witness  = $Witness
                    Database = $primarydb.Name
                    Status   = "Success"
                }
                if ($Witness) {
                    $results | Select-DefaultView -Property Primary, Mirror, Witness, Database, Status
                } else {
                    $results | Select-DefaultView -Property Primary, Mirror, Database, Status
                }
            }
        }
    }
}
tools\dbatools\functions\Invoke-DbaDbShrink.ps1
function Invoke-DbaDbShrink {
    <#
    .SYNOPSIS
        Shrinks all files in a database. This is a command that should rarely be used.

        - Shrinks can cause severe index fragmentation (to the tune of 99%)
        - Shrinks can cause massive growth in the database's transaction log
        - Shrinks can require a lot of time and system resources to perform data movement

    .DESCRIPTION
        Shrinks all files in a database. Databases should be shrunk only when completely necessary.

        Many awesome SQL people have written about why you should not shrink your data files. Paul Randal and Kalen Delaney wrote great posts about this topic:

        http://www.sqlskills.com/blogs/paul/why-you-should-not-shrink-your-data-files
        http://sqlmag.com/sql-server/shrinking-data-files

        However, there are some cases where a database will need to be shrunk. In the event that you must shrink your database:

        1. Ensure you have plenty of space for your T-Log to grow
        2. Understand that shrinks require a lot of CPU and disk resources
        3. Consider running DBCC INDEXDEFRAG or ALTER INDEX ... REORGANIZE after the shrink is complete.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Defaults to the default instance on localhost.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential).

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server.

    .PARAMETER AllUserDatabases
        Run command against all user databases.

    .PARAMETER PercentFreeSpace
        Specifies how much free space to leave, defaults to 0.

    .PARAMETER ShrinkMethod
        Specifies the method that is used to shrink the database
        Default
        Data in pages located at the end of a file is moved to pages earlier in the file. Files are truncated to reflect allocated space.
        EmptyFile
        Migrates all of the data from the referenced file to other files in the same filegroup. (DataFile and LogFile objects only).
        NoTruncate
        Data in pages located at the end of a file is moved to pages earlier in the file.
        TruncateOnly
        Data distribution is not affected. Files are truncated to reflect allocated space, recovering free space at the end of any file.

    .PARAMETER StatementTimeout
        Timeout in minutes. Defaults to infinity (shrinks can take a while).

    .PARAMETER LogsOnly
        Deprecated. Use FileType instead.

    .PARAMETER FileType
        Specifies the files types that will be shrunk
        All - All Data and Log files are shrunk, using database shrink (Default)
        Data - Just the Data files are shrunk using file shrink
        Log - Just the Log files are shrunk using file shrink

    .PARAMETER StepSize
        Measured in bits - but no worries! PowerShell has a very cool way of formatting bits. Just specify something like: 1MB or 10GB. See the examples for more information.

        If specified, this will chunk a larger shrink operation into multiple smaller shrinks.
        If shrinking a file by a large amount there are benefits of doing multiple smaller chunks.

    .PARAMETER ExcludeIndexStats
        Exclude statistics about fragmentation.

    .PARAMETER ExcludeUpdateUsage
        Exclude DBCC UPDATE USAGE for database.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run.

    .PARAMETER Confirm
        Prompts for confirmation of every step. For example:

        Are you sure you want to perform this action?
        Performing the operation "Shrink database" on target "pubs on SQL2016\VNEXT".
        [Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Shrink, Database
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaDbShrink

    .EXAMPLE
        PS C:\> Invoke-DbaDbShrink -SqlInstance sql2016 -Database Northwind,pubs,Adventureworks2014

        Shrinks Northwind, pubs and Adventureworks2014 to have as little free space as possible.

    .EXAMPLE
        PS C:\> Invoke-DbaDbShrink -SqlInstance sql2014 -Database AdventureWorks2014 -PercentFreeSpace 50

        Shrinks AdventureWorks2014 to have 50% free space. So let's say AdventureWorks2014 was 1GB and it's using 100MB space. The database free space would be reduced to 50MB.

    .EXAMPLE
        PS C:\> Invoke-DbaDbShrink -SqlInstance sql2014 -Database AdventureWorks2014 -PercentFreeSpace 50 -FileType Data -StepSize 25MB

        Shrinks AdventureWorks2014 to have 50% free space, runs shrinks in 25MB chunks for improved performance.

    .EXAMPLE
        PS C:\> Invoke-DbaDbShrink -SqlInstance sql2012 -AllUserDatabases

        Shrinks all databases on SQL2012 (not ideal for production)

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$AllUserDatabases,
        [ValidateRange(0, 99)]
        [int]$PercentFreeSpace = 0,
        [ValidateSet('Default', 'EmptyFile', 'NoTruncate', 'TruncateOnly')]
        [string]$ShrinkMethod = "Default",
        [ValidateSet('All', 'Data', 'Log')]
        [string]$FileType = "All",
        [int]$StepSize,
        [int]$StatementTimeout = 0,
        [switch]$LogsOnly,
        [switch]$ExcludeIndexStats,
        [switch]$ExcludeUpdateUsage,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        if ($LogsOnly) {
            Test-DbaDeprecation -DeprecatedOn "1.0.0" -Parameter "LogsOnly"
            $FileType = 'Log'
        }
        if (-not $Database -and -not $ExcludeDatabase -and -not $AllUserDatabases) {
            Stop-Function -Message "You must specify databases to execute against using either -Database, -Exclude or -AllUserDatabases"
            return
        }

        if ((Test-Bound -ParameterName StepSize) -and $stepsize -lt 1024) {
            Stop-Function -Message "StepSize is measured in bits. Did you mean $StepSize bits? If so, please use 1024 or above. If not, then use the PowerShell bit notation like $($StepSize)MB or $($StepSize)GB"
            return
        }

        if ($stepsize) {
            $StepSizeKB = ([dbasize]($StepSize)).Kilobyte
        }
        $StatementTimeoutSeconds = $StatementTimeout * 60

        $sql = "SELECT
                  avg(avg_fragmentation_in_percent) as [avg_fragmentation_in_percent]
                , max(avg_fragmentation_in_percent) as [max_fragmentation_in_percent]
                FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
                WHERE indexstats.avg_fragmentation_in_percent > 0 AND indexstats.page_count > 100
                GROUP BY indexstats.database_id"
    }

    process {
        if (Test-FunctionInterrupt) { return }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $server.ConnectionContext.StatementTimeout = $StatementTimeoutSeconds
            Write-Message -Level Verbose -Message "Connection timeout set to $StatementTimeout"

            $dbs = $server.Databases | Where-Object {$_.IsAccessible}

            if ($Database) {
                $dbs = $dbs | Where-Object Name -In $Database
            }

            if ($ExcludeDatabase) {
                $dbs = $dbs | Where-Object Name -NotIn $ExcludeDatabase
            }

            foreach ($db in $dbs) {

                Write-Message -Level Verbose -Message "Processing $db on $instance"

                if ($db.IsDatabaseSnapshot) {
                    Write-Message -Level Warning -Message "The database $db on server $instance is a snapshot and cannot be shrunk. Skipping database."
                    continue
                }

                $files = @()
                if ($FileType -in ('Log', 'All')) {
                    $files += $db.LogFiles
                }
                if ($FileType -in ('Data', 'All')) {
                    $files += $db.FileGroups.Files
                }

                foreach ($file in $files) {
                    $startingSize = $file.Size
                    $spaceUsed = $file.UsedSpace
                    $spaceAvailable = ($file.Size - $file.UsedSpace)
                    $desiredSpaceAvailable = [math]::ceiling((($PercentFreeSpace / 100)) * $spaceUsed)
                    $desiredFileSize = $spaceUsed + $desiredSpaceAvailable

                    Write-Message -Level Verbose -Message "File: $($file.Name)"
                    Write-Message -Level Verbose -Message "Initial Size (KB): $([int]$startingSize)"
                    Write-Message -Level Verbose -Message "Space Used (KB): $([int]$spaceUsed)"
                    Write-Message -Level Verbose -Message "Initial Freespace (KB): $([int]$spaceAvailable)"
                    Write-Message -Level Verbose -Message "Target Freespace (KB): $([int]$desiredSpaceAvailable)"
                    Write-Message -Level Verbose -Message "Target FileSize (KB): $([int]$desiredFileSize)"

                    if ($spaceAvailable -le $desiredSpaceAvailable) {
                        Write-Message -Level Warning -Message "File size of ($startingSize) is less than or equal to the desired outcome ($desiredFileSize) for $($file.Name)"
                    } else {
                        if ($Pscmdlet.ShouldProcess("$db on $instance", "Shrinking from $([int]$startingSize)KB to $([int]$desiredFileSize)KB")) {
                            if ($server.VersionMajor -gt 8 -and $ExcludeIndexStats -eq $false) {
                                Write-Message -Level Verbose -Message "Getting starting average fragmentation"
                                $dataRow = $server.Query($sql, $db.name)
                                $startingFrag = $dataRow.avg_fragmentation_in_percent
                                $startingTopFrag = $dataRow.max_fragmentation_in_percent
                            } else {
                                $startingTopFrag = $startingFrag = $null
                            }

                            $start = Get-Date
                            try {
                                Write-Message -Level Verbose -Message "Beginning shrink of files"

                                $shrinkGap = ($startingSize - $desiredFileSize)
                                Write-Message -Level Verbose -Message "ShrinkGap: $([int]$shrinkGap) KB"
                                Write-Message -Level Verbose -Message "Step Size: $(([dbasize]$StepSize).Megabyte) MB"

                                if ($StepSizeKB -and ($shrinkGap -gt $stepSizeKB)) {
                                    for ($i = 1; $i -le [int](($shrinkGap) / $stepSizeKB); $i++) {
                                        Write-Message -Level Verbose -Message "Step: $i"
                                        $shrinkSize = $startingSize - (($StepSizeKB * 1024 * 1024) * $i)
                                        if ($shrinkSize -lt $desiredFileSize) {
                                            $shrinkSize = $desiredFileSize
                                        }
                                        Write-Message -Level Verbose -Message ("Shrinking {0} to {1}" -f $file.Name, $shrinkSize)
                                        $file.Shrink(($shrinkSize / 1024), $ShrinkMethod)
                                        $file.Refresh()

                                        if ($startingSize -eq $file.Size) {
                                            Write-Message -Level Verbose -Message ("Unable to shrink further")
                                            break
                                        }
                                    }
                                } else {
                                    $file.Shrink(($desiredFileSize / 1024), $ShrinkMethod)
                                    $file.Refresh()
                                }
                                $success = $true
                            } catch {
                                $success = $false
                                Stop-Function -message "Failure" -EnableException $EnableException -ErrorRecord $_ -Continue
                                continue
                            }
                            $end = Get-Date
                            $finalFileSize = $file.Size
                            $finalSpaceAvailable = ($file.Size - $file.UsedSpace)
                            Write-Message -Level Verbose -Message "Final file size: $([int]$finalFileSize) KB"
                            Write-Message -Level Verbose -Message "Final file space available: $($finalSpaceAvailable) KB"

                            if ($server.VersionMajor -gt 8 -and $ExcludeIndexStats -eq $false -and $success -and $FileType -ne 'Log') {
                                Write-Message -Level Verbose -Message "Getting ending average fragmentation"
                                $dataRow = $server.Query($sql, $db.name)
                                $endingDefrag = $dataRow.avg_fragmentation_in_percent
                                $endingTopDefrag = $dataRow.max_fragmentation_in_percent
                            } else {
                                $endingTopDefrag = $endingDefrag = $null
                            }

                            $timSpan = New-TimeSpan -Start $start -End $end
                            $ts = [TimeSpan]::fromseconds($timSpan.TotalSeconds)
                            $elapsed = "{0:HH:mm:ss}" -f ([datetime]$ts.Ticks)

                            $object = [PSCustomObject]@{
                                ComputerName                = $server.ComputerName
                                InstanceName                = $server.ServiceName
                                SqlInstance                 = $server.DomainInstanceName
                                Database                    = $db.name
                                File                        = $file.name
                                Start                       = $start
                                End                         = $end
                                Elapsed                     = $elapsed
                                Success                     = $success
                                InitialSize                 = [dbasize]($startingSize * 1024)
                                InitialUsed                 = [dbasize]($spaceUsed * 1024)
                                InitialAvailable            = [dbasize]($spaceAvailable * 1024)
                                TargetAvailable             = [dbasize]($desiredSpaceAvailable * 1024)
                                FinalAvailable              = [dbasize]($finalSpaceAvailable * 1024)
                                FinalSize                   = [dbasize]($finalFileSize * 1024)
                                InitialAverageFragmentation = [math]::Round($startingFrag, 1)
                                FinalAverageFragmentation   = [math]::Round($endingDefrag, 1)
                                InitialTopFragmentation     = [math]::Round($startingTopFrag, 1)
                                FinalTopFragmentation       = [math]::Round($endingTopDefrag, 1)
                                Notes                       = "Database shrinks can cause massive index fragmentation and negatively impact performance. You should now run DBCC INDEXDEFRAG or ALTER INDEX ... REORGANIZE"
                            }
                            if ($ExcludeIndexStats) {
                                Select-DefaultView -InputObject $object -ExcludeProperty InitialAverageFragmentation, FinalAverageFragmentation, InitialTopFragmentation, FinalTopFragmentation
                            } else {
                                $object
                            }
                        }
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Invoke-DbaDatabaseShrink
    }
}
tools\dbatools\functions\Invoke-DbaDbUpgrade.ps1
function Invoke-DbaDbUpgrade {
    <#
    .SYNOPSIS
        Take a database and upgrades it to compatibility of the SQL Instance its hosted on. Based on https://thomaslarock.com/2014/06/upgrading-to-sql-server-2014-a-dozen-things-to-check/

    .DESCRIPTION
        Updates compatibility level, then runs CHECKDB with data_purity, DBCC updateusage, sp_updatestats and finally sp_refreshview against all user views.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        SqlCredential object used to connect to the SQL Server as a different user.

    .PARAMETER Database
        The database(s) to process - this list is autopopulated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is autopopulated from the server

    .PARAMETER AllUserDatabases
        Run command against all user databases

    .PARAMETER Force
        Don't skip over databases that are already at the same level the instance is

    .PARAMETER NoCheckDb
        Skip checkdb

    .PARAMETER NoUpdateUsage
        Skip usage update

    .PARAMETER NoUpdateStats
        Skip stats update

    .PARAMETER NoRefreshView
        Skip view update

    .PARAMETER InputObject
        A collection of databases (such as returned by Get-DbaDatabase)

    .PARAMETER WhatIf
        Shows what would happen if the command were to run

    .PARAMETER Confirm
        Prompts for confirmation of every step. For example:

        Are you sure you want to perform this action?
        Performing the operation "Update database" on target "pubs on SQL2016\VNEXT".
        [Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Shrink, Database
        Author: Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaDbUpgrade

    .EXAMPLE
        PS C:\> Invoke-DbaDbUpgrade -SqlInstance PRD-SQL-MSD01 -Database Test

        Runs the below processes against the databases
        -- Puts compatibility of database to level of SQL Instance
        -- Runs CHECKDB DATA_PURITY
        -- Runs DBCC UPDATESUSAGE
        -- Updates all users statistics
        -- Runs sp_refreshview against every view in the database

    .EXAMPLE
        PS C:\> Invoke-DbaDbUpgrade -SqlInstance PRD-SQL-INT01 -Database Test -NoRefreshView

        Runs the upgrade command skipping the sp_refreshview update on all views

    .EXAMPLE
        PS C:\> Invoke-DbaDbUpgrade -SqlInstance PRD-SQL-INT01 -Database Test -Force

        If database Test is already at the correct compatibility, runs every necessary step

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sql2016 | Out-GridView -Passthru | Invoke-DbaDbUpgrade

        Get only specific databases using GridView and pass those to Invoke-DbaDbUpgrade

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Position = 0)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [System.Management.Automation.PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$NoCheckDb,
        [switch]$NoUpdateUsage,
        [switch]$NoUpdateStats,
        [switch]$NoRefreshView,
        [switch]$AllUserDatabases,
        [switch]$Force,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {

        if (Test-Bound -not 'SqlInstance', 'InputObject') {
            Write-Message -Level Warning -Message "You must specify either a SQL instance or pipe a database collection"
            continue
        }

        if (Test-Bound -not 'Database', 'InputObject', 'ExcludeDatabase', 'AllUserDatabases') {
            Write-Message -Level Warning -Message "You must explicitly specify a database. Use -Database, -ExcludeDatabase, -AllUserDatabases or pipe a database collection"
            continue
        }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
                $server.ConnectionContext.StatementTimeout = [Int32]::MaxValue
            } catch {
                Stop-Function -Message "Failed to process Instance $Instance" -ErrorRecord $_ -Target $instance -Continue
            }
            $InputObject += $server.Databases | Where-Object IsAccessible
        }

        $InputObject = $InputObject | Where-Object { $_.IsSystemObject -eq $false }
        if ($Database) {
            $InputObject = $InputObject | Where-Object { $_.Name -contains $Database }
        }
        if ($ExcludeDatabase) {
            $InputObject = $InputObject | Where-Object { $_.Name -notcontains $ExcludeDatabase }
        }

        foreach ($db in $InputObject) {
            # create objects to use in updates
            $server = $db.Parent
            $ServerVersion = $server.VersionMajor
            Write-Message -Level Verbose -Message "SQL Server is using Version: $ServerVersion"

            $ogcompat = $db.CompatibilityLevel
            $dbname = $db.Name
            $dbversion = switch ($db.CompatibilityLevel) {
                "Version100" { 10 } # SQL Server 2008
                "Version110" { 11 } # SQL Server 2012
                "Version120" { 12 } # SQL Server 2014
                "Version130" { 13 } # SQL Server 2016
                "Version140" { 14 } # SQL Server 2017
                default { 9 } # SQL Server 2005
            }
            if (-not $Force) {
                # skip over databases at the correct level, unless -Force
                if ($dbversion -ge $ServerVersion) {
                    Write-Message -Level VeryVerbose -Message "Skipping $db because compatibility is at the correct level. Use -Force if you want to run all the additional steps"
                    continue
                }
            }
            Write-Message -Level Verbose -Message "Updating $db compatibility to SQL Instance level"
            if ($dbversion -lt $ServerVersion) {
                If ($Pscmdlet.ShouldProcess($server, "Updating $db version on $server from $dbversion to $ServerVersion")) {
                    $Comp = $ServerVersion * 10
                    $tsqlComp = "ALTER DATABASE $db SET COMPATIBILITY_LEVEL = $Comp"
                    try {
                        $db.ExecuteNonQuery($tsqlComp)
                        $comResult = $Comp
                    } catch {
                        Write-Message -Level Warning -Message "Failed run Compatibility Upgrade" -ErrorRecord $_ -Target $instance
                        $comResult = "Fail"
                    }
                }
            } else {
                $comResult = "No change"
            }

            if (!($NoCheckDb)) {
                Write-Message -Level Verbose -Message "Updating $db with DBCC CHECKDB DATA_PURITY"
                If ($Pscmdlet.ShouldProcess($server, "Updating $db with DBCC CHECKDB DATA_PURITY")) {
                    $tsqlCheckDB = "DBCC CHECKDB ('$dbname') WITH DATA_PURITY, NO_INFOMSGS"
                    try {
                        $db.ExecuteNonQuery($tsqlCheckDB)
                        $DataPurityResult = "Success"
                    } catch {
                        Write-Message -Level Warning -Message "Failed run DBCC CHECKDB with DATA_PURITY on $db" -ErrorRecord $_ -Target $instance
                        $DataPurityResult = "Fail"
                    }
                }
            } else {
                Write-Message -Level Verbose -Message "Ignoring CHECKDB DATA_PURITY"
            }

            if (!($NoUpdateUsage)) {
                Write-Message -Level Verbose -Message "Updating $db with DBCC UPDATEUSAGE"
                If ($Pscmdlet.ShouldProcess($server, "Updating $db with DBCC UPDATEUSAGE")) {
                    $tsqlUpdateUsage = "DBCC UPDATEUSAGE ($db) WITH NO_INFOMSGS;"
                    try {
                        $db.ExecuteNonQuery($tsqlUpdateUsage)
                        $UpdateUsageResult = "Success"
                    } catch {
                        Write-Message -Level Warning -Message "Failed to run DBCC UPDATEUSAGE on $db" -ErrorRecord $_ -Target $instance
                        $UpdateUsageResult = "Fail"
                    }
                }
            } else {
                Write-Message -Level Verbose -Message "Ignore DBCC UPDATEUSAGE"
                $UpdateUsageResult = "Skipped"
            }

            if (!($NoUpdatestats)) {
                Write-Message -Level Verbose -Message "Updating $db statistics"
                If ($Pscmdlet.ShouldProcess($server, "Updating $db statistics")) {
                    $tsqlStats = "EXEC sp_updatestats;"
                    try {
                        $db.ExecuteNonQuery($tsqlStats)
                        $UpdateStatsResult = "Success"
                    } catch {
                        Write-Message -Level Warning -Message "Failed to run sp_updatestats on $db" -ErrorRecord $_ -Target $instance
                        $UpdateStatsResult = "Fail"
                    }
                }
            } else {
                Write-Message -Level Verbose -Message "Ignoring sp_updatestats"
                $UpdateStatsResult = "Skipped"
            }

            if (!($NoRefreshView)) {
                Write-Message -Level Verbose -Message "Refreshing $db Views"
                $dbViews = $db.Views | Where-Object IsSystemObject -eq $false
                $RefreshViewResult = "Success"
                foreach ($dbview in $dbviews) {
                    $viewName = $dbView.Name
                    $viewSchema = $dbView.Schema
                    $fullName = $viewSchema + "." + $viewName

                    $tsqlupdateView = "EXECUTE sp_refreshview N'$fullName';  "

                    If ($Pscmdlet.ShouldProcess($server, "Refreshing view $fullName on $db")) {
                        try {
                            $db.ExecuteNonQuery($tsqlupdateView)
                        } catch {
                            Write-Message -Level Warning -Message "Failed update view $fullName on $db" -ErrorRecord $_ -Target $instance
                            $RefreshViewResult = "Fail"
                        }
                    }
                }
            } else {
                Write-Message -Level Verbose -Message "Ignore View Refreshes"
                $RefreshViewResult = "Skipped"
            }

            If ($Pscmdlet.ShouldProcess("console", "Outputting object")) {
                $db.Refresh()

                [PSCustomObject]@{
                    ComputerName          = $server.ComputerName
                    InstanceName          = $server.ServiceName
                    SqlInstance           = $server.DomainInstanceName
                    Database              = $db.name
                    OriginalCompatibility = $ogcompat.ToString().Replace('Version', '')
                    CurrentCompatibility  = $db.CompatibilityLevel.ToString().Replace('Version', '')
                    Compatibility         = $comResult
                    DataPurity            = $DataPurityResult
                    UpdateUsage           = $UpdateUsageResult
                    UpdateStats           = $UpdateStatsResult
                    RefreshViews          = $RefreshViewResult
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Invoke-DbaDatabaseUpgrade
    }
}
tools\dbatools\functions\Invoke-DbaDiagnosticQuery.ps1
function Invoke-DbaDiagnosticQuery {
    <#
    .SYNOPSIS
        Invoke-DbaDiagnosticQuery runs the scripts provided by Glenn Berry's DMV scripts on specified servers

    .DESCRIPTION
        This is the main function of the Sql Server Diagnostic Queries related functions in dbatools.
        The diagnostic queries are developed and maintained by Glenn Berry and they can be found here along with a lot of documentation:
        http://www.sqlskills.com/blogs/glenn/category/dmv-queries/

        The most recent version of the diagnostic queries are included in the dbatools module.
        But it is possible to download a newer set or a specific version to an alternative location and parse and run those scripts.
        It will run all or a selection of those scripts on one or multiple servers and return the result as a PowerShell Object

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Can be either a string or SMO server

    .PARAMETER SqlCredential
        Allows alternative Windows or SQL login credentials to be used

    .PARAMETER Path
        Alternate path for the diagnostic scripts

    .PARAMETER Database
        The database(s) to process. If unspecified, all databases will be processed

    .PARAMETER ExcludeDatabase
        The database(s) to exclude

    .PARAMETER ExcludeQuery
        The Queries to exclude

    .PARAMETER UseSelectionHelper
        Provides a gridview with all the queries to choose from and will run the selection made by the user on the Sql Server instance specified.

    .PARAMETER QueryName
        Only run specific query

    .PARAMETER InstanceOnly
        Run only instance level queries

    .PARAMETER DatabaseSpecific
        Run only database level queries

    .PARAMETER ExcludeQueryTextColumn
        Use this switch to exclude the [Complete Query Text] column from relevant queries

    .PARAMETER ExcludePlanColumn
        Use this switch to exclude the [Query Plan] column from relevant queries

    .PARAMETER NoColumnParsing
        Does not parse the [Complete Query Text] and [Query Plan] columns and disregards the ExcludeQueryTextColumn and NoColumnParsing switches

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER Confirm
        Prompts to confirm certain actions

    .PARAMETER WhatIf
        Shows what would happen if the command would execute, but does not actually perform the command

    .PARAMETER OutputPath
        Directory to parsed diagnostict queries to. This will split them based on server, databasename, and query.

    .PARAMETER ExportQueries
        Use this switch to export the diagnostic queries to sql files. I
        nstead of running the queries, the server will be evaluated to find the appropriate queries to run based on SQL Version.
        These sql files will then be created in the OutputDirectory

    .NOTES
        Tags: Database, DMV
        Author: Andre Kamman (@AndreKamman), http://clouddba.io

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaDiagnosticQuery

    .EXAMPLE
        PS C:\>Invoke-DbaDiagnosticQuery -SqlInstance sql2016

        Run the selection made by the user on the Sql Server instance specified.

    .EXAMPLE
        PS C:\>Invoke-DbaDiagnosticQuery -SqlInstance sql2016 -UseSelectionHelper | Export-DbaDiagnosticQuery -Path C:\temp\gboutput

        Provides a gridview with all the queries to choose from and will run the selection made by the user on the SQL Server instance specified.
        Then it will export the results to Export-DbaDiagnosticQuery.

    .EXAMPLE
        PS C:\> Invoke-DbaDiagnosticQuery -sqlinstance localhost -ExportQueries -outputpath "C:\temp\DiagnosticQueries"

        Export All Queries to Disk

    .EXAMPLE
        PS C:\> Invoke-DbaDiagnosticQuery -sqlinstance localhost -DatabaseSpecific -DatabaseName 'tempdb' -ExportQueries -outputpath "C:\temp\DiagnosticQueries"

        Export Database Specific Queries for all User Dbs

    .EXAMPLE
        PS C:\> Invoke-DbaDiagnosticQuery -sqlinstance localhost -DatabaseSpecific -DatabaseName 'tempdb' -ExportQueries -outputpath "C:\temp\DiagnosticQueries"

        Export Database Specific Queries For One Target Database

    .EXAMPLE
        PS C:\> Invoke-DbaDiagnosticQuery -sqlinstance localhost -DatabaseSpecific -DatabaseName 'tempdb' -ExportQueries -outputpath "C:\temp\DiagnosticQueries" -queryname 'Database-scoped Configurations'

        Export Database Specific Queries For One Target Database and One Specific Query

    .EXAMPLE
        PS C:\> Invoke-DbaDiagnosticQuery -sqlinstance localhost -UseSelectionHelper

        Choose Queries To Export

    .EXAMPLE
        PS C:\> [PSObject[]]$results = Invoke-DbaDiagnosticQuery -SqlInstance localhost -whatif

        Parse the appropriate diagnostic queries by connecting to server, and instead of running them, return as [PSCustomObject[]] to work with further

    .EXAMPLE
        PS C:\> $results = Invoke-DbaDiagnosticQuery -SqlInstance Sql2017 -DatabaseSpecific -queryname 'Database-scoped Configurations' -databasename TestStuff

        Run diagnostic queries targeted at specific database, and only run database level queries against this database.

    #>

    [CmdletBinding(SupportsShouldProcess)]
    [outputtype([pscustomobject[]])]
    param (
        [parameter(Mandatory, ValueFromPipeline, Position = 0)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,

        [Alias('DatabaseName')]
        [object[]]$Database,

        [object[]]$ExcludeDatabase,

        [object[]]$ExcludeQuery,

        [Alias('Credential')]
        [PSCredential]$SqlCredential,
        [System.IO.FileInfo]$Path,
        [string[]]$QueryName,
        [switch]$UseSelectionHelper,
        [switch]$InstanceOnly,
        [switch]$DatabaseSpecific,
        [Switch]$ExcludeQueryTextColumn,
        [Switch]$ExcludePlanColumn,
        [Switch]$NoColumnParsing,

        [string]$OutputPath,
        [switch]$ExportQueries,

        [switch][Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $ProgressId = Get-Random

        function Invoke-DiagnosticQuerySelectionHelper {
            [CmdletBinding()]
            param (
                [parameter(Mandatory)]
                $ParsedScript
            )

            $ParsedScript | Select-Object QueryNr, QueryName, DBSpecific, Description | Out-GridView -Title "Diagnostic Query Overview" -OutputMode Multiple | Sort-Object QueryNr | Select-Object -ExpandProperty QueryName

        }

        Write-Message -Level Verbose -Message "Interpreting DMV Script Collections"

        $module = Get-Module -Name dbatools
        $base = $module.ModuleBase

        if (!$Path) {
            $Path = "$base\bin\diagnosticquery"
        }

        $scriptversions = @()
        $scriptfiles = Get-ChildItem "$Path\SQLServerDiagnosticQueries_*_*.sql"

        if (!$scriptfiles) {
            Write-Message -Level Warning -Message "Diagnostic scripts not found in $Path. Using the ones within the module."

            $Path = "$base\bin\diagnosticquery"

            $scriptfiles = Get-ChildItem "$base\bin\diagnosticquery\SQLServerDiagnosticQueries_*_*.sql"
            if (!$scriptfiles) {
                Stop-Function -Message "Unable to download scripts, do you have an internet connection? $_" -ErrorRecord $_
                return
            }
        }

        [int[]]$filesort = $null

        foreach ($file in $scriptfiles) {
            $filesort += $file.BaseName.Split("_")[2]
        }

        $currentdate = $filesort | Sort-Object -Descending | Select-Object -First 1

        foreach ($file in $scriptfiles) {
            if ($file.BaseName.Split("_")[2] -eq $currentdate) {
                $parsedscript = Invoke-DbaDiagnosticQueryScriptParser -filename $file.fullname -ExcludeQueryTextColumn:$ExcludeQueryTextColumn -ExcludePlanColumn:$ExcludePlanColumn -NoColumnParsing:$NoColumnParsing

                $newscript = [pscustomobject]@{
                    Version = $file.Basename.Split("_")[1]
                    Script  = $parsedscript
                }
                $scriptversions += $newscript
            }
        }
    }

    process {
        if (Test-FunctionInterrupt) { return }

        foreach ($instance in $SqlInstance) {
            $counter = 0
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            Write-Message -Level Verbose -Message "Collecting diagnostic query data from server: $instance"

            if ($server.VersionMinor -eq 50) {
                $version = "2008R2"
            } else {
                $version = switch ($server.VersionMajor) {
                    9 { "2005" }
                    10 { "2008" }
                    11 { "2012" }
                    12 { "2014" }
                    13 { "2016" }
                    14 { "2017" }
                }
            }

            if ($version -eq "2016" -and $server.VersionMinor -gt 5026 ) {
                $version = "2016SP2"
            }

            if ($server.DatabaseEngineType -eq "SqlAzureDatabase") {
                $version = "AzureSQLDatabase"
            }

            if (!$instanceOnly) {
                if (-not $Database) {
                    $databases = (Get-DbaDatabase -SqlInstance $server -ExcludeSystem -ExcludeDatabase $ExcludeDatabase).Name
                } else {
                    $databases = (Get-DbaDatabase -SqlInstance $server -ExcludeSystem -Database $Database -ExcludeDatabase $ExcludeDatabase).Name
                }
            }

            $parsedscript = $scriptversions | Where-Object -Property Version -eq $version | Select-Object -ExpandProperty Script

            if ($null -eq $first) { $first = $true }
            if ($UseSelectionHelper -and $first) {
                $QueryName = Invoke-DiagnosticQuerySelectionHelper $parsedscript
                $first = $false
                if ($QueryName.Count -eq 0) {
                    Write-Message -Level Output -Message "No query selected through SelectionHelper, halting script execution"
                    return
                }
            }

            if ($QueryName.Count -eq 0) {
                $QueryName = $parsedscript | Select-Object -ExpandProperty QueryName
            }

            if ($ExcludeQuery) {
                $QueryName = Compare-Object -ReferenceObject $QueryName -DifferenceObject $ExcludeQuery | Where-Object SideIndicator -eq "<=" | Select-Object -ExpandProperty InputObject
            }

            #since some database level queries can take longer (such as fragmentation) calculate progress with database specific queries * count of databases to run against into context
            $CountOfDatabases = ($databases).Count

            if ($QueryName.Count -ne 0) {
                #if running all queries, then calculate total to run by instance queries count + (db specific count * databases to run each against)
                $countDBSpecific = @($parsedscript | Where-Object {$_.QueryName -in $QueryName -and $_.DBSpecific -eq $true}).Count
                $countInstanceSpecific = @($parsedscript | Where-Object {$_.QueryName -in $QueryName -and $_.DBSpecific -eq $false}).Count
            } else {
                #if narrowing queries to database specific, calculate total to process based on instance queries count + (db specific count * databases to run each against)
                $countDBSpecific = @($parsedscript | Where-Object DBSpecific).Count
                $countInstanceSpecific = @($parsedscript | Where-Object DBSpecific -eq $false).Count

            }
            if (!$instanceonly -and !$DatabaseSpecific -and !$QueryName) {
                $scriptcount = $countInstanceSpecific + ($countDBSpecific * $CountOfDatabases )
            } elseif ($instanceOnly) {
                $scriptcount = $countInstanceSpecific
            } elseif ($DatabaseSpecific) {
                $scriptcount = $countDBSpecific * $CountOfDatabases
            } elseif ($QueryName.Count -ne 0) {
                $scriptcount = $countInstanceSpecific + ($countDBSpecific * $CountOfDatabases )


            }
            
            foreach ($scriptpart in $parsedscript) {
                # ensure results are null with each part, otherwise duplicated information may be returned
                $result = $null
                if (($QueryName.Count -ne 0) -and ($QueryName -notcontains $scriptpart.QueryName)) { continue }
                if (!$scriptpart.DBSpecific -and !$DatabaseSpecific) {
                    if ($ExportQueries) {
                        $null = New-Item -Path $OutputPath -ItemType Directory -Force
                        $FileName = Remove-InvalidFileNameChars ('{0}.sql' -f $Scriptpart.QueryName)
                        $FullName = Join-Path $OutputPath $FileName
                        Write-Message -Level Verbose -Message  "Creating file: $FullName"
                        $scriptPart.Text | out-file -FilePath $FullName -Encoding UTF8 -force
                        continue
                    }

                    if ($PSCmdlet.ShouldProcess($instance, $scriptpart.QueryName)) {

                        if (-not $EnableException) {
                            $Counter++
                            Write-Progress -Id $ProgressId -ParentId 0 -Activity "Collecting diagnostic query data from $instance" -Status "Processing $counter of $scriptcount" -CurrentOperation $scriptpart.QueryName -PercentComplete (($counter / $scriptcount) * 100)
                        }

                        try {
                            $result = $server.Query($scriptpart.Text)
                            Write-Message -Level Verbose -Message "Processed $($scriptpart.QueryName) on $instance"
                            if (-not $result) {
                                [pscustomobject]@{
                                    ComputerName     = $server.ComputerName
                                    InstanceName     = $server.ServiceName
                                    SqlInstance      = $server.DomainInstanceName
                                    Number           = $scriptpart.QueryNr
                                    Name             = $scriptpart.QueryName
                                    Description      = $scriptpart.Description
                                    DatabaseSpecific = $scriptpart.DBSpecific
                                    Database         = $null
                                    Notes            = "Empty Result for this Query"
                                    Result           = $null
                                }
                                Write-Message -Level Verbose -Message ("Empty result for Query {0} - {1} - {2}" -f $scriptpart.QueryNr, $scriptpart.QueryName, $scriptpart.Description)
                            }
                        } catch {
                            Write-Message -Level Verbose -Message ('Some error has occured on Server: {0} - Script: {1}, result unavailable' -f $instance, $scriptpart.QueryName) -Target $instance -ErrorRecord $_
                        }
                        if ($result) {
                            [pscustomobject]@{
                                ComputerName     = $server.ComputerName
                                InstanceName     = $server.ServiceName
                                SqlInstance      = $server.DomainInstanceName
                                Number           = $scriptpart.QueryNr
                                Name             = $scriptpart.QueryName
                                Description      = $scriptpart.Description
                                DatabaseSpecific = $scriptpart.DBSpecific
                                Database         = $null
                                Notes            = $null
                                #Result           = Select-DefaultView -InputObject $result -Property *
                                #Not using Select-DefaultView because excluding the fields below doesn't seem to work
                                Result           = $result | Select-Object * -ExcludeProperty 'Item', 'RowError', 'RowState', 'Table', 'ItemArray', 'HasErrors'
                            }

                        }
                    } else {
                        # if running WhatIf, then return the queries that would be run as an object, not just whatif output

                        [pscustomobject]@{
                            ComputerName     = $server.ComputerName
                            InstanceName     = $server.ServiceName
                            SqlInstance      = $server.DomainInstanceName
                            Number           = $scriptpart.QueryNr
                            Name             = $scriptpart.QueryName
                            Description      = $scriptpart.Description
                            DatabaseSpecific = $scriptpart.DBSpecific
                            Database         = $null
                            Notes            = "WhatIf - Bypassed Execution"
                            Result           = $null
                        }
                    }

                } elseif ($scriptpart.DBSpecific -and !$instanceOnly) {

                    foreach ($currentdb in $databases) {
                        if ($ExportQueries) {
                            $null = New-Item -Path $OutputPath -ItemType Directory -Force
                            $FileName = Remove-InvalidFileNameChars ('{0}-{1}-{2}.sql' -f $server.DomainInstanceName, $currentDb, $Scriptpart.QueryName)
                            $FullName = Join-Path $OutputPath $FileName
                            Write-Message -Level Verbose -Message  "Creating file: $FullName"
                            $scriptPart.Text | out-file -FilePath $FullName -encoding UTF8 -force
                            continue
                        }


                        if ($PSCmdlet.ShouldProcess(('{0} ({1})' -f $instance, $currentDb), $scriptpart.QueryName)) {

                            if (-not $EnableException) {
                                $Counter++
                                Write-Progress -Id $ProgressId -ParentId 0 -Activity "Collecting diagnostic query data from $($currentDb) on $instance" -Status ('Processing {0} of {1}' -f $counter, $scriptcount) -CurrentOperation $scriptpart.QueryName -PercentComplete (($Counter / $scriptcount) * 100)
                            }

                            Write-Message -Level Verbose -Message "Collecting diagnostic query data from $($currentDb) for $($scriptpart.QueryName) on $instance"
                            try {
                                $result = $server.Query($scriptpart.Text, $currentDb)
                                if (-not $result) {
                                    [pscustomobject]@{
                                        ComputerName     = $server.ComputerName
                                        InstanceName     = $server.ServiceName
                                        SqlInstance      = $server.DomainInstanceName
                                        Number           = $scriptpart.QueryNr
                                        Name             = $scriptpart.QueryName
                                        Description      = $scriptpart.Description
                                        DatabaseSpecific = $scriptpart.DBSpecific
                                        Database         = $currentdb
                                        Notes            = "Empty Result for this Query"
                                        Result           = $null
                                    }
                                    Write-Message -Level Verbose -Message ("Empty result for Query {0} - {1} - {2}" -f $scriptpart.QueryNr, $scriptpart.QueryName, $scriptpart.Description) -Target $scriptpart -ErrorRecord $_
                                }
                            } catch {
                                Write-Message -Level Verbose -Message ('Some error has occured on Server: {0} - Script: {1} - Database: {2}, result will not be saved' -f $instance, $scriptpart.QueryName, $currentDb) -Target $currentdb -ErrorRecord $_
                            }

                            if ($result) {
                                [pscustomobject]@{
                                    ComputerName     = $server.ComputerName
                                    InstanceName     = $server.ServiceName
                                    SqlInstance      = $server.DomainInstanceName
                                    Number           = $scriptpart.QueryNr
                                    Name             = $scriptpart.QueryName
                                    Description      = $scriptpart.Description
                                    DatabaseSpecific = $scriptpart.DBSpecific
                                    Database         = $currentDb
                                    Notes            = $null
                                    #Result           = Select-DefaultView -InputObject $result -Property *
                                    #Not using Select-DefaultView because excluding the fields below doesn't seem to work
                                    Result           = $result | Select-Object * -ExcludeProperty 'Item', 'RowError', 'RowState', 'Table', 'ItemArray', 'HasErrors'
                                }
                            }
                        } else {
                            # if running WhatIf, then return the queries that would be run as an object, not just whatif output

                            [pscustomobject]@{
                                ComputerName     = $server.ComputerName
                                InstanceName     = $server.ServiceName
                                SqlInstance      = $server.DomainInstanceName
                                Number           = $scriptpart.QueryNr
                                Name             = $scriptpart.QueryName
                                Description      = $scriptpart.Description
                                DatabaseSpecific = $scriptpart.DBSpecific
                                Database         = $null
                                Notes            = "WhatIf - Bypassed Execution"
                                Result           = $null
                            }
                        }
                    }
                }
            }
        }
    }
    end {
        Write-Progress -Id $ProgressId -Activity 'Invoke-DbaDiagnosticQuery' -Completed
    }
}
tools\dbatools\functions\Invoke-DbaPfRelog.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Invoke-DbaPfRelog {
    <#
    .SYNOPSIS
        Pipeline-compatible wrapper for the relog command which is available on modern Windows platforms.

    .DESCRIPTION
        Pipeline-compatible wrapper for the relog command. Relog is useful for converting Windows Perfmon.

        Extracts performance counters from performance counter logs into other formats,
        such as text-TSV (for tab-delimited text), text-CSV (for comma-delimited text), binary-BIN, or SQL.

        `relog "C:\PerfLogs\Admin\System Correlation\WORKSTATIONX_20180112-000001\DataCollector01.blg" -o C:\temp\foo.csv -f tsv`

        If you find any input hangs, please send us the output so we can accommodate for it then use -Raw for an immediate solution.

    .PARAMETER Path
        Specifies the pathname of an existing performance counter log or performance counter path. You can specify multiple input files.

    .PARAMETER Destination
        Specifies the pathname of the output file or SQL database where the counters will be written. Defaults to the same directory as the source.

    .PARAMETER Type
        The output format. Defaults to tsv. Options include tsv, csv, bin, and sql.

        For a SQL database, the output file specifies the DSN!counter_log. You can specify the database location by using the ODBC manager to configure the DSN (Database System Name).

        For more information, read here: https://technet.microsoft.com/en-us/library/bb490958.aspx

    .PARAMETER Append
        If this switch is enabled, output will be appended to the specified file instead of overwriting. This option does not apply to SQL format where the default is always to append.

    .PARAMETER AllowClobber
        If this switch is enabled, the destination file will be overwritten if it exists.

    .PARAMETER PerformanceCounter
        Specifies the performance counter path to log.

    .PARAMETER PerformanceCounterPath
        Specifies the pathname of the text file that lists the performance counters to be included in a relog file. Use this option to list counter paths in an input file, one per line. Default setting is all counters in the original log file are relogged.

    .PARAMETER Interval
        Specifies sample intervals in "n" records. Includes every nth data point in the relog file. Default is every data point.

    .PARAMETER BeginTime
        This is is Get-Date object and we format it for you.

    .PARAMETER EndTime
        Specifies end time for copying last record from the input file. This is is Get-Date object and we format it for you.

    .PARAMETER ConfigPath
        Specifies the pathname of the settings file that contains command-line parameters.

    .PARAMETER Summary
        If this switch is enabled, the performance counters and time ranges of log files specified in the input file will be displayed.

    .PARAMETER Multithread
        If this switch is enabled, processing will be done in parallel. This may speed up large batches or large files.

    .PARAMETER AllTime
        If this switch is enabled and a datacollector or datacollectorset is passed in via the pipeline, collects all logs, not just the latest.

    .PARAMETER Raw
        If this switch is enabled, the results of the DOS command instead of Get-ChildItem will be displayed. This does not run in parallel.

    .PARAMETER InputObject
        Accepts the output of Get-DbaPfDataCollector and Get-DbaPfDataCollectorSet as input via the pipeline.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Performance, DataCollector, PerfCounter, Relog
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaPfRelog

    .EXAMPLE
        PS C:\> Invoke-DbaPfRelog -Path C:\temp\perfmon.blg

        Creates C:\temp\perfmon.tsv from C:\temp\perfmon.blg.

    .EXAMPLE
        PS C:\> Invoke-DbaPfRelog -Path C:\temp\perfmon.blg -Destination C:\temp\a\b\c

        Creates the temp, a, and b directories if needed, then generates c.tsv (tab separated) from C:\temp\perfmon.blg.

        Returns the newly created file as a file object.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorSet -ComputerName sql2016 | Get-DbaPfDataCollector | Invoke-DbaPfRelog -Destination C:\temp\perf

        Creates C:\temp\perf if needed, then generates computername-datacollectorname.tsv (tab separated) from the latest logs of all data collector sets on sql2016. This destination format was chosen to avoid naming conflicts with piped input.

    .EXAMPLE
        PS C:\> Invoke-DbaPfRelog -Path C:\temp\perfmon.blg -Destination C:\temp\a\b\c -Raw
        ```
        [Invoke-DbaPfRelog][21:21:35] relog "C:\temp\perfmon.blg" -f csv -o C:\temp\a\b\c

        Input
        ----------------
        File(s):
        C:\temp\perfmon.blg (Binary)

        Begin:    1/13/2018 5:13:23
        End:      1/13/2018 14:29:55
        Samples:  2227

        100.00%

        Output
        ----------------
        File:     C:\temp\a\b\c.csv

        Begin:    1/13/2018 5:13:23
        End:      1/13/2018 14:29:55
        Samples:  2227

        The command completed successfully.
        ```

        Creates the temp, a, and b directories if needed, then generates c.tsv (tab separated) from C:\temp\perfmon.blg then outputs the raw results of the relog command.

    .EXAMPLE
        PS C:\> Invoke-DbaPfRelog -Path 'C:\temp\perflog with spaces.blg' -Destination C:\temp\a\b\c -Type csv -BeginTime ((Get-Date).AddDays(-30)) -EndTime ((Get-Date).AddDays(-1))

        Creates the temp, a, and b directories if needed, then generates c.csv (comma separated) from C:\temp\perflog with spaces.blg', starts 30 days ago and ends one day ago.

    .EXAMPLE
        PS C:\> $servers | Get-DbaPfDataCollectorSet | Get-DbaPfDataCollector | Invoke-DbaPfRelog -Multithread -AllowClobber

        Relogs latest data files from all collectors within the servers listed in $servers.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollector -Collector DataCollector01 | Invoke-DbaPfRelog -AllowClobber -AllTime

        Relogs all the log files from the DataCollector01 on the local computer and allows overwrite.

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipelineByPropertyName)]
        [Alias("FullName")]
        [string[]]$Path,
        [string]$Destination,
        [ValidateSet("tsv", "csv", "bin", "sql")]
        [string]$Type = "tsv",
        [switch]$Append,
        [switch]$AllowClobber,
        [string[]]$PerformanceCounter,
        [string]$PerformanceCounterPath,
        [int]$Interval,
        [datetime]$BeginTime,
        [datetime]$EndTime,
        [string]$ConfigPath,
        [switch]$Summary,
        [parameter(ValueFromPipeline)]
        [object[]]$InputObject,
        [switch]$Multithread,
        [switch]$AllTime,
        [switch]$Raw,
        [switch]$EnableException
    )
    begin {
        
        
        if (Test-Bound -ParameterName BeginTime) {
            $script:beginstring = ($BeginTime -f 'M/d/yyyy hh:mm:ss' | Out-String).Trim()
        }
        if (Test-Bound -ParameterName EndTime) {
            $script:endstring = ($EndTime -f 'M/d/yyyy hh:mm:ss' | Out-String).Trim()
        }

        $allpaths = @()
        $allpaths += $Path

        # to support multithreading
        if (Test-Bound -ParameterName Destination) {
            $script:destinationset = $true
            $originaldestination = $Destination
        } else {
            $script:destinationset = $false
        }
    }
    process {
        if ($Append -and $Type -ne "bin") {
            Stop-Function -Message "Append can only be used with -Type bin." -Target $Path
            return
        }

        if ($InputObject) {
            foreach ($object in $InputObject) {
                # DataCollectorSet
                if ($object.OutputLocation -and $object.RemoteOutputLocation) {
                    $instance = [dbainstance]$object.ComputerName

                    if (-not $AllTime) {
                        if ($instance.IsLocalHost) {
                            $allpaths += (Get-ChildItem -Recurse -Path $object.LatestOutputLocation -Include *.blg -ErrorAction SilentlyContinue).FullName
                        } else {
                            $allpaths += (Get-ChildItem -Recurse -Path $object.RemoteLatestOutputLocation -Include *.blg -ErrorAction SilentlyContinue).FullName
                        }
                    } else {
                        if ($instance.IsLocalHost) {
                            $allpaths += (Get-ChildItem -Recurse -Path $object.OutputLocation -Include *.blg -ErrorAction SilentlyContinue).FullName
                        } else {
                            $allpaths += (Get-ChildItem -Recurse -Path $object.RemoteOutputLocation -Include *.blg -ErrorAction SilentlyContinue).FullName
                        }
                    }


                    $script:perfmonobject = $true
                }
                # DataCollector
                if ($object.LatestOutputLocation -and $object.RemoteLatestOutputLocation) {
                    $instance = [dbainstance]$object.ComputerName

                    if (-not $AllTime) {
                        if ($instance.IsLocalHost) {
                            $allpaths += (Get-ChildItem -Recurse -Path $object.LatestOutputLocation -Include *.blg -ErrorAction SilentlyContinue).FullName
                        } else {
                            $allpaths += (Get-ChildItem -Recurse -Path $object.RemoteLatestOutputLocation -Include *.blg -ErrorAction SilentlyContinue).FullName
                        }
                    } else {
                        if ($instance.IsLocalHost) {
                            $allpaths += (Get-ChildItem -Recurse -Path (Split-Path $object.LatestOutputLocation) -Include *.blg -ErrorAction SilentlyContinue).FullName
                        } else {
                            $allpaths += (Get-ChildItem -Recurse -Path (Split-Path $object.RemoteLatestOutputLocation) -Include *.blg -ErrorAction SilentlyContinue).FullName
                        }
                    }
                    $script:perfmonobject = $true
                }
            }
        }
    }

    # Gotta collect all the paths first then process them otherwise there may be duplicates
    end {
        $allpaths = $allpaths | Where-Object { $_ -match '.blg' } | Select-Object -Unique

        if (-not $allpaths) {
            Stop-Function -Message "Could not find matching .blg files" -Target $file -Continue
            return
        }

        $scriptblock = {
            if ($args) {
                $file = $args
            } else {
                $file = $psitem
            }
            $item = Get-ChildItem -Path $file -ErrorAction SilentlyContinue

            if ($null -eq $item) {
                Stop-Function -Message "$file does not exist." -Target $file -Continue
                return
            }

            if (-not $script:destinationset -and $file -match "C\:\\.*Admin.*") {
                $null = Test-ElevationRequirement -ComputerName $env:COMPUTERNAME -Continue
            }

            if ($script:destinationset -eq $false -and -not $Append) {
                $Destination = Join-Path (Split-Path $file) $item.BaseName
            }

            if ($Destination -and $Destination -notmatch "\." -and -not $Append -and $script:perfmonobject) {
                # if destination is set, then it needs a different name
                if ($script:destinationset -eq $true) {
                    if ($file -match "\:") {
                        $computer = $env:COMPUTERNAME
                    } else {
                        $computer = $file.Split("\")[2]
                    }
                    # Avoid naming conflicts
                    $timestamp = Get-Date -format yyyyMMddHHmmfff
                    $Destination = Join-Path $originaldestination "$computer - $($item.BaseName) - $timestamp"
                }
            }

            $params = @("`"$file`"")

            if ($Append) {
                $params += "-a"
            }

            if ($PerformanceCounter) {
                $parsedcounters = $PerformanceCounter -join " "
                $params += "-c `"$parsedcounters`""
            }

            if ($PerformanceCounterPath) {
                $params += "-cf `"$PerformanceCounterPath`""
            }

            $params += "-f $Type"

            if ($Interval) {
                $params += "-t $Interval"
            }

            if ($Destination) {
                $params += "-o `"$Destination`""
            }

            if ($script:beginstring) {
                $params += "-b $script:beginstring"
            }

            if ($script:endstring) {
                $params += "-e $script:endstring"
            }

            if ($ConfigPath) {
                $params += "-config $ConfigPath"
            }

            if ($Summary) {
                $params += "-q"
            }


            if (-not ($Destination.StartsWith("DSN"))) {
                $outputisfile = $true
            } else {
                $outputisfile = $false
            }

            if ($outputisfile) {
                if ($Destination) {
                    $dir = Split-Path $Destination
                    if (-not (Test-Path -Path $dir)) {
                        try {
                            $null = New-Item -ItemType Directory -Path $dir -ErrorAction Stop
                        } catch {
                            Stop-Function -Message "Failure" -ErrorRecord $_ -Target $Destination -Continue
                        }
                    }

                    if ((Test-Path $Destination) -and -not $Append -and ((Get-Item $Destination) -isnot [System.IO.DirectoryInfo])) {
                        if ($AllowClobber) {
                            try {
                                Remove-Item -Path "$Destination" -ErrorAction Stop
                            } catch {
                                Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
                            }
                        } else {
                            if ($Type -eq "bin") {
                                Stop-Function -Message "$Destination exists. Use -AllowClobber to overwrite or -Append to append." -Continue
                            } else {
                                Stop-Function -Message "$Destination exists. Use -AllowClobber to overwrite." -Continue
                            }
                        }
                    }

                    if ((Test-Path "$Destination.$type") -and -not $Append) {
                        if ($AllowClobber) {
                            try {
                                Remove-Item -Path "$Destination.$type" -ErrorAction Stop
                            } catch {
                                Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
                            }
                        } else {
                            if ($Type -eq "bin") {
                                Stop-Function -Message "$("$Destination.$type") exists. Use -AllowClobber to overwrite or -Append to append." -Continue
                            } else {
                                Stop-Function -Message "$("$Destination.$type") exists. Use -AllowClobber to overwrite." -Continue
                            }
                        }
                    }
                }
            }

            $arguments = ($params -join " ")

            try {
                if ($Raw) {
                    Write-Message -Level Output -Message "relog $arguments"
                    cmd /c "relog $arguments"
                } else {
                    Write-Message -Level Verbose -Message "relog $arguments"
                    $scriptblock = {
                        $output = (cmd /c "relog $arguments" | Out-String).Trim()

                        if ($output -notmatch "Success") {
                            Stop-Function -Continue -Message $output.Trim("Input")
                        } else {
                            Write-Message -Level Verbose -Message "$output"
                            $array = $output -Split [environment]::NewLine
                            $files = $array | Select-String "File:"

                            foreach ($rawfile in $files) {
                                $rawfile = $rawfile.ToString().Replace("File:", "").Trim()
                                $gcierror = $null
                                Get-ChildItem $rawfile -ErrorAction SilentlyContinue -ErrorVariable gcierror | Add-Member -MemberType NoteProperty -Name RelogFile -Value $true -PassThru -ErrorAction Ignore
                                if ($gcierror) {
                                    Write-Message -Level Verbose -Message "$gcierror"
                                }
                            }
                        }
                    }
                    Invoke-Command -ScriptBlock $scriptblock
                }
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Target $path
            }
        }

        if ($Multithread) {
            $allpaths | Invoke-Parallel -ImportVariables -ImportModules -ScriptBlock $scriptblock -ErrorAction SilentlyContinue -ErrorVariable parallelerror
            if ($parallelerror) {
                Write-Message -Level Verbose -Message "$parallelerror"
            }
        } else {
            foreach ($file in $allpaths) { Invoke-Command -ScriptBlock $scriptblock -ArgumentList $file }
        }
    }
}
tools\dbatools\functions\Invoke-DbaQuery.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Invoke-DbaQuery {
    <#
    .SYNOPSIS
        A command to run explicit T-SQL commands or files.

    .DESCRIPTION
        This function is a wrapper command around Invoke-DbaAsync, which in turn is based on Invoke-SqlCmd2.
        It was designed to be more convenient to use in a pipeline and to behave in a way consistent with the rest of our functions.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Credential object used to connect to the SQL Server Instance as a different user. This can be a Windows or SQL Server account. Windows users are determined by the existence of a backslash, so if you are intending to use an alternative Windows connection instead of a SQL login, ensure it contains a backslash.

    .PARAMETER Database
        The database to select before running the query. This list is auto-populated from the server.

    .PARAMETER Query
        Specifies one or more queries to be run. The queries can be Transact-SQL, XQuery statements, or sqlcmd commands. Multiple queries in a single batch may be separated by a semicolon or a GO

        Escape any double quotation marks included in the string.

        Consider using bracketed identifiers such as [MyTable] instead of quoted identifiers such as "MyTable".

    .PARAMETER QueryTimeout
        Specifies the number of seconds before the queries time out.

    .PARAMETER File
        Specifies the path to one or several files to be used as the query input.

    .PARAMETER SqlObject
        Specify on or multiple SQL objects. Those will be converted to script and their scripts run on the target system(s).

    .PARAMETER As
        Specifies output type. Valid options for this parameter are 'DataSet', 'DataTable', 'DataRow', 'PSObject', and 'SingleValue'

        PSObject output introduces overhead but adds flexibility for working with results: http://powershell.org/wp/forums/topic/dealing-with-dbnull/

    .PARAMETER SqlParameters
        Specifies a hashtable of parameters for parameterized SQL queries.  http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/

    .PARAMETER AppendServerInstance
        If this switch is enabled, the SQL Server instance will be appended to PSObject and DataRow output.

    .PARAMETER MessagesToOutput
        Use this switch to have on the output stream messages too (e.g. PRINT statements). Output will hold the resultset too. See examples for detail

    .PARAMETER InputObject
        A collection of databases (such as returned by Get-DbaDatabase)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER ReadOnly
        Execute the query with ReadOnly application intent.

    .NOTES
        Tags: Database, Query
        Author: Friedrich Weinmann (@FredWeinmann)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaQuery

    .EXAMPLE
        PS C:\> Invoke-DbaQuery -SqlInstance server\instance -Query 'SELECT foo FROM bar'

        Runs the sql query 'SELECT foo FROM bar' against the instance 'server\instance'

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance [SERVERNAME] -Group [GROUPNAME] | Invoke-DbaQuery -Query 'SELECT foo FROM bar'

        Runs the sql query 'SELECT foo FROM bar' against all instances in the group [GROUPNAME] on the CMS [SERVERNAME]

    .EXAMPLE
        PS C:\> "server1", "server1\nordwind", "server2" | Invoke-DbaQuery -File "C:\scripts\sql\rebuild.sql"

        Runs the sql commands stored in rebuild.sql against the instances "server1", "server1\nordwind" and "server2"

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance "server1", "server1\nordwind", "server2" | Invoke-DbaQuery -File "C:\scripts\sql\rebuild.sql"

        Runs the sql commands stored in rebuild.sql against all accessible databases of the instances "server1", "server1\nordwind" and "server2"

    .EXAMPLE
        PS C:\> Invoke-DbaQuery -SqlInstance . -Query 'SELECT * FROM users WHERE Givenname = @name' -SqlParameters @{ Name = "Maria" }

        Executes a simple query against the users table using SQL Parameters.
        This avoids accidental SQL Injection and is the safest way to execute queries with dynamic content.
        Keep in mind the limitations inherent in parameters - it is quite impossible to use them for content references.
        While it is possible to parameterize a where condition, it is impossible to use this to select which columns to select.
        The inserted text will always be treated as string content, and not as a reference to any SQL entity (such as columns, tables or databases).
    .EXAMPLE
        PS C:\> Invoke-DbaQuery -SqlInstance aglistener1 -ReadOnly -Query "select something from readonlydb.dbo.atable"

        Executes a query with ReadOnly application intent on aglistener1.
    #>
    [CmdletBinding(DefaultParameterSetName = "Query")]
    param (
        [parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance[]]$SqlInstance,
        [Alias("Credential")]
        [PsCredential]$SqlCredential,
        [string]$Database,
        [Parameter(Mandatory, Position = 0, ParameterSetName = "Query")]
        [string]$Query,
        [Int32]$QueryTimeout = 600,
        [Parameter(Mandatory, ParameterSetName = "File")]
        [Alias("InputFile")]
        [object[]]$File,
        [Parameter(Mandatory, ParameterSetName = "SMO")]
        [Microsoft.SqlServer.Management.Smo.SqlSmoObject[]]$SqlObject,
        [ValidateSet("DataSet", "DataTable", "DataRow", "PSObject", "SingleValue")]
        [string]$As = "DataRow",
        [System.Collections.IDictionary]$SqlParameters,
        [switch]$AppendServerInstance,
        [switch]$MessagesToOutput,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$ReadOnly,
        [switch]$EnableException
    )

    begin {
        Write-Message -Level Debug -Message "Bound parameters: $($PSBoundParameters.Keys -join ", ")"

        $splatInvokeDbaSqlAsync = @{
            As = $As
        }

        if (Test-Bound -ParameterName "SqlParameters") {
            $splatInvokeDbaSqlAsync["SqlParameters"] = $SqlParameters
        }
        if (Test-Bound -ParameterName "AppendServerInstance") {
            $splatInvokeDbaSqlAsync["AppendServerInstance"] = $AppendServerInstance
        }
        if (Test-Bound -ParameterName "Query") {
            $splatInvokeDbaSqlAsync["Query"] = $Query
        }
        if (Test-Bound -ParameterName "QueryTimeout") {
            $splatInvokeDbaSqlAsync["QueryTimeout"] = $QueryTimeout
        }
        if (Test-Bound -ParameterName "MessagesToOutput") {
            $splatInvokeDbaSqlAsync["MessagesToOutput"] = $MessagesToOutput
        }
        if (Test-Bound -ParameterName "Verbose") {
            $splatInvokeDbaSqlAsync["Verbose"] = $Verbose
        }


        if (Test-Bound -ParameterName "File") {
            $files = @()
            $temporaryFiles = @()
            $temporaryFilesCount = 0
            $temporaryFilesPrefix = (97 .. 122 | Get-Random -Count 10 | ForEach-Object { [char]$_ }) -join ''

            foreach ($item in $File) {
                if ($null -eq $item) { continue }

                $type = $item.GetType().FullName

                switch ($type) {
                    "System.IO.DirectoryInfo" {
                        if (-not $item.Exists) {
                            Stop-Function -Message "Directory not found!" -Category ObjectNotFound
                            return
                        }
                        $files += ($item.GetFiles() | Where-Object Extension -EQ ".sql").FullName

                    }
                    "System.IO.FileInfo" {
                        if (-not $item.Exists) {
                            Stop-Function -Message "Directory not found!" -Category ObjectNotFound
                            return
                        }

                        $files += $item.FullName
                    }
                    "System.String" {
                        $uri = [uri]$item

                        switch -regex ($uri.Scheme) {
                            "http" {
                                $tempfile = "$env:TEMP\$temporaryFilesPrefix-$temporaryFilesCount.sql"
                                try {
                                    try {
                                        Invoke-TlsWebRequest -Uri $item -OutFile $tempfile -ErrorAction Stop
                                    } catch {
                                        (New-Object System.Net.WebClient).Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
                                        Invoke-TlsWebRequest -Uri $item -OutFile $tempfile -ErrorAction Stop
                                    }
                                    $files += $tempfile
                                    $temporaryFilesCount++
                                    $temporaryFiles += $tempfile
                                } catch {
                                    Stop-Function -Message "Failed to download file $item" -ErrorRecord $_
                                    return
                                }
                            }
                            default {
                                try {
                                    $paths = Resolve-Path $item | Select-Object -ExpandProperty Path | Get-Item -ErrorAction Stop
                                } catch {
                                    Stop-Function -Message "Failed to resolve path: $item" -ErrorRecord $_
                                    return
                                }

                                foreach ($path in $paths) {
                                    if (-not $path.PSIsContainer) {
                                        if (([uri]$path.FullName).Scheme -ne 'file') {
                                            Stop-Function -Message "Could not resolve path $path as filesystem object"
                                            return
                                        }
                                        $files += $path.FullName
                                    }
                                }
                            }
                        }
                    }
                    default {
                        Stop-Function -Message "Unkown input type: $type" -Category InvalidArgument
                        return
                    }
                }
            }
        }

        if (Test-Bound -ParameterName "SqlObject") {
            $files = @()
            $temporaryFiles = @()
            $temporaryFilesCount = 0
            $temporaryFilesPrefix = (97 .. 122 | Get-Random -Count 10 | ForEach-Object { [char]$_ }) -join ''

            foreach ($object in $SqlObject) {
                try { $code = Export-DbaScript -InputObject $object -Passthru -EnableException }
                catch {
                    Stop-Function -Message "Failed to generate script for object $object" -ErrorRecord $_
                    return
                }

                try {
                    $newfile = "$env:TEMP\$temporaryFilesPrefix-$temporaryFilesCount.sql"
                    Set-Content -Value $code -Path $newfile -Force -ErrorAction Stop -Encoding UTF8
                    $files += $newfile
                    $temporaryFilesCount++
                    $temporaryFiles += $newfile
                } catch {
                    Stop-Function -Message "Failed to write sql script to temp" -ErrorRecord $_
                    return
                }
            }
        }
    }

    process {
        if (Test-FunctionInterrupt) { return }
        if (Test-Bound -ParameterName "Database", "InputObject" -And) {
            Stop-Function -Category InvalidArgument -Message "You can't use -Database with piped databases"
            return
        }
        if (Test-Bound -ParameterName "SqlInstance", "InputObject" -And) {
            Stop-Function -Category InvalidArgument -Message "You can't use -SqlInstance with piped databases"
            return
        }

        foreach ($db in $InputObject) {
            if (!$db.IsAccessible) {
                Write-Message -Level Warning -Message "Database $db is not accessible. Skipping."
                continue
            }
            $server = $db.Parent
            $conncontext = $server.ConnectionContext
            if ($conncontext.DatabaseName -ne $db.Name) {
                $conncontext = $server.ConnectionContext.Copy()
                $conncontext.DatabaseName = $db.Name
            }
            try {
                if ($File -or $SqlObject) {
                    foreach ($item in $files) {
                        if ($null -eq $item) {continue}
                        $filePath = $(Resolve-Path -LiteralPath $item).ProviderPath
                        $QueryfromFile = [System.IO.File]::ReadAllText("$filePath")
                        Invoke-DbaAsync -SQLConnection $conncontext @splatInvokeDbaSqlAsync -Query $QueryfromFile
                    }
                } else { Invoke-DbaAsync -SQLConnection $conncontext @splatInvokeDbaSqlAsync }
            } catch {
                Stop-Function -Message "[$db] Failed during execution" -ErrorRecord $_ -Target $server -Continue
            }
        }
        foreach ($instance in $SqlInstance) {
            try {
                $intent = if ($ReadOnly) { "ReadOnly" } else { "ReadWrite" }
                $server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential -ApplicationIntent $intent
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Target $instance -Continue
            }
            $conncontext = $server.ConnectionContext
            try {
                if ($Database -and $conncontext.DatabaseName -ne $Database) {
                    $conncontext = $server.ConnectionContext.Copy()
                    $conncontext.DatabaseName = $Database
                }
                if ($File -or $SqlObject) {
                    foreach ($item in $files) {
                        if ($null -eq $item) {continue}
                        $filePath = $(Resolve-Path -LiteralPath $item).ProviderPath
                        $QueryfromFile = [System.IO.File]::ReadAllText("$filePath")
                        Invoke-DbaAsync -SQLConnection $conncontext @splatInvokeDbaSqlAsync -Query $QueryfromFile
                    }
                } else {
                    Invoke-DbaAsync -SQLConnection $conncontext @splatInvokeDbaSqlAsync
                }
            } catch {
                Stop-Function -Message "[$instance] Failed during execution" -ErrorRecord $_ -Target $instance -Continue
            }
        }
    }

    end {
        # Execute end even when interrupting, as only used for cleanup

        if ($temporaryFiles) {
            # Clean up temporary files that were downloaded
            foreach ($item in $temporaryFiles) {
                Remove-Item -Path $item -ErrorAction Ignore
            }
        }
        Test-DbaDeprecation -DeprecatedOn '1.0.0' -Alias Invoke-DbaCmd
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Invoke-DbaSqlQuery
    }
}
tools\dbatools\functions\Invoke-DbatoolsFormatter.ps1
function Invoke-DbatoolsFormatter {
    <#
    .SYNOPSIS
        Helps formatting function files to dbatools' standards

    .DESCRIPTION
        Uses PSSA's Invoke-Formatter to format the target files and saves it without the BOM.

    .PARAMETER Path
        The path to the ps1 file that needs to be formatted

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Formatting
        Author: Simone Bizzotto

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbatoolsFormatter

    .EXAMPLE
        PS C:\> Invoke-DbatoolsFormatter -Path C:\dbatools\functions\Get-DbaDatabase.ps1

        Reformats C:\dbatools\functions\Get-DbaDatabase.ps1 to dbatools' standards

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [object[]]$Path,
        [switch]$EnableException
    )
    begin {
        $HasInvokeFormatter = $null -ne (Get-Command Invoke-Formatter -ErrorAction SilentlyContinue).Version
        if (!($HasInvokeFormatter)) {
            Stop-Function -Message "You need a recent version of PSScriptAnalyzer installed"
        }
        $CBHRex = [regex]'(?smi)\s+<#[^#]*#>'
        $CBHStartRex = [regex]'(?<spaces>[ ]+)<#'
        $CBHEndRex = [regex]'(?<spaces>[ ]*)#>'
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($p in $Path) {
            try {
                $realPath = (Resolve-Path -Path $p -ErrorAction Stop).Path
            } catch {
                Stop-Function -Message "Cannot find or resolve $p" -Continue
            }

            $content = Get-Content -Path $realPath -Raw -Encoding UTF8
            #strip ending empty lines
            $content = $content -replace "(?s)`r`n\s*$"
            try {
                $content = Invoke-Formatter -ScriptDefinition $content -Settings CodeFormattingOTBS -ErrorAction Stop
            } catch {
                Write-Message -Level Warning "Unable to format $p"
            }
            #match the ending indentation of CBH with the starting one, see #4373
            $CBH = $CBHRex.Match($content).Value
            if ($CBH) {
                #get starting spaces
                $startSpaces = $CBHStartRex.Match($CBH).Groups['spaces']
                if ($startSpaces) {
                    #get end
                    $newCBH = $CBHEndRex.Replace($CBH, "$startSpaces#>")
                    if ($newCBH) {
                        #replace the CBH
                        $content = $content.Replace($CBH, $newCBH)
                    }
                }
            }
            $Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False
            $realContent = @()
            #trim whitespace lines
            foreach ($line in $content.Split("`n")) {
                $realContent += $line.TrimEnd()
            }
            [System.IO.File]::WriteAllText($realPath, ($realContent -Join "`r`n"), $Utf8NoBomEncoding)
        }
    }
}
tools\dbatools\functions\Invoke-DbatoolsRenameHelper.ps1
function Invoke-DbatoolsRenameHelper {
    <#
    .SYNOPSIS
        Older dbatools command names have been changed. This script helps keep up.

    .DESCRIPTION
        Older dbatools command names have been changed. This script helps keep up.

    .PARAMETER InputObject
        A piped in object from Get-ChildItem

    .PARAMETER Encoding
        Specifies the file encoding. The default is UTF8.

        Valid values are:
        -- ASCII: Uses the encoding for the ASCII (7-bit) character set.
        -- BigEndianUnicode: Encodes in UTF-16 format using the big-endian byte order.
        -- Byte: Encodes a set of characters into a sequence of bytes.
        -- String: Uses the encoding type for a string.
        -- Unicode: Encodes in UTF-16 format using the little-endian byte order.
        -- UTF7: Encodes in UTF-7 format.
        -- UTF8: Encodes in UTF-8 format.
        -- Unknown: The encoding type is unknown or invalid. The data can be treated as binary.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command

    .NOTES
        Tags: Module
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbatoolsRenameHelper

    .EXAMPLE
        PS C:\> Get-ChildItem C:\temp\ps\*.ps1 -Recurse | Invoke-DbatoolsRenameHelper

        Checks to see if any ps1 file in C:\temp\ps matches an old command name.
        If so, then the command name within the text is updated and the resulting changes are written to disk in UTF-8.

    .EXAMPLE
        PS C:\> Get-ChildItem C:\temp\ps\*.ps1 -Recurse | Invoke-DbatoolsRenameHelper -Encoding Ascii -WhatIf

        Shows what would happen if the command would run. If the command would run and there were matches,
        the resulting changes would be written to disk as Ascii encoded.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [System.IO.FileInfo[]]$InputObject,
        [ValidateSet('ASCII', 'BigEndianUnicode', 'Byte', 'String', 'Unicode', 'UTF7', 'UTF8', 'Unknown')]
        [string]$Encoding = 'UTF8',
        [switch]$EnableException
    )
    begin {
        $morerenames = @(
            @{
                "AliasName"  = "Invoke-Sqlcmd2"
                "Definition" = "Invoke-DbaQuery"
            },
            @{
                "AliasName"  = "UseLastBackups"
                "Definition" = "UseLastBackup"
            },
            @{
                "AliasName"  = "NetworkShare"
                "Definition" = "SharedPath"
            },
            @{
                "AliasName"  = "NoSystemLogins"
                "Definition" = "ExcludeSystemLogins"
            },
            @{
                "AliasName"  = "NoJobSteps"
                "Definition" = "ExcludeJobSteps"
            },
            @{
                "AliasName"  = "NoSystemObjects"
                "Definition" = "ExcludeSystemObjects"
            },
            @{
                "AliasName"  = "NoJobs"
                "Definition" = "ExcludeJobs"
            },
            @{
                "AliasName"  = "NoDatabases"
                "Definition" = "ExcludeDatabases"
            },
            @{
                "AliasName"  = "NoDisabledJobs"
                "Definition" = "ExcludeDisabledJobs"
            },
            @{
                "AliasName"  = "NoJobSteps"
                "Definition" = "ExcludeJobSteps"
            },
            @{
                "AliasName"  = "NoSystem"
                "Definition" = "ExcludeSystemLogins"
            },
            @{
                "AliasName"  = "NoSystemDb"
                "Definition" = "ExcludeSystem"
            },
            @{
                "AliasName"  = "NoSystemObjects"
                "Definition" = "ExcludeSystemObjects"
            },
            @{
                "AliasName"  = "NoSystemSpid"
                "Definition" = "ExcludeSystemSpids"
            },
            @{
                "AliasName"  = "NoQueryTextColumn"
                "Definition" = "ExcludeQueryTextColumn"
            },
            @{
                "AliasName"  = "ExcludeAllSystemDb"
                "Definition" = "ExcludeSystem"
            },
            @{
                "AliasName"  = "ExcludeAllUserDb"
                "Definition" = "ExcludeUser"
            }
        )

        $allrenames = $script:renames + $morerenames
    }
    process {
        foreach ($fileobject in $InputObject) {
            $file = $fileobject.FullName

            foreach ($name in $allrenames) {
                if ((Select-String -Pattern $name.AliasName -Path $file)) {
                    if ($Pscmdlet.ShouldProcess($file, "Replacing $($name.AliasName) with $($name.Definition)")) {
                        $content = (Get-Content -Path $file -Raw).Replace($name.AliasName, $name.Definition).Trim()
                        Set-Content -Path $file -Encoding $Encoding -Value $content
                        [pscustomobject]@{
                            Path         = $file
                            Pattern      = $name.AliasName
                            ReplacedWith = $name.Definition
                        }
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Invoke-DbaWhoisActive.ps1
function Invoke-DbaWhoIsActive {
    <#
    .SYNOPSIS
        Outputs results of Adam Machanic's sp_WhoIsActive DataTable

    .DESCRIPTION
        Output results of Adam Machanic's sp_WhoIsActive

        This command was built with Adam's permission. To read more about sp_WhoIsActive, please visit:

        Updates: http://sqlblog.com/blogs/adam_machanic/archive/tags/who+is+active/default.aspx

        Also, consider donating to Adam if you find this stored procedure helpful: http://tinyurl.com/WhoIsActiveDonate

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER Database
        The database where sp_WhoIsActive is installed. Defaults to master. If the sp_WhoIsActive is not installed, the command will warn and exit.

    .PARAMETER Filter
        FiltersBoth inclusive and exclusive
        Set either filter to '' to disable
        Session is a session ID, and either 0 or '' can be used to indicate "all" sessions
        All other filter types support % or _ as wildcards

    .PARAMETER FilterType
        Valid filter types are: session, program, database, login, and host

    .PARAMETER NotFilter
        FiltersBoth inclusive and exclusive
        Set either filter to '' to disable
        Session is a session ID, and either 0 or '' can be used to indicate "all" sessions
        All other filter types support % or _ as wildcards

    .PARAMETER NotFilterType
        Valid filter types are: session, program, database, login, and host

    .PARAMETER ShowOwnSpid
        Retrieve data about the calling session?

    .PARAMETER ShowSystemSpids
        Retrieve data about system sessions?

    .PARAMETER ShowSleepingSpids
        Controls how sleeping SPIDs are handled, based on the idea of levels of interest
        0 does not pull any sleeping SPIDs
        1 pulls only those sleeping SPIDs that also have an open transaction
        2 pulls all sleeping SPIDs

    .PARAMETER GetFullInnerText
        If 1, gets the full stored procedure or running batch, when available
        If 0, gets only the actual statement that is currently running in the batch or procedure

    .PARAMETER GetPlans
        Get associated query plans for running tasks, if available
        If 1, gets the plan based on the request's statement offset
        If 2, gets the entire plan based on the request's plan_handle

    .PARAMETER GetOuterCommand
        Get the associated outer ad hoc query or stored procedure call, if available

    .PARAMETER GetTransactionInfo
        Enables pulling transaction log write info and transaction duration

    .PARAMETER GetTaskInfo
        Get information on active tasks, based on three interest levels
        Level 0 does not pull any task-related information
        Level 1 is a lightweight mode that pulls the top non-CXPACKET wait, giving preference to blockers
        Level 2 pulls all available task-based metrics, including:
        number of active tasks, current wait stats, physical I/O, context switches, and blocker information

    .PARAMETER GetLocks
        Gets associated locks for each request, aggregated in an XML format

    .PARAMETER GetAverageTime
        Get average time for past runs of an active query
        (based on the combination of plan handle, sql handle, and offset)

    .PARAMETER GetAdditonalInfo
        Get additional non-performance-related information about the session or request
        text_size, language, date_format, date_first, quoted_identifier, arithabort, ansi_null_dflt_on,
        ansi_defaults, ansi_warnings, ansi_padding, ansi_nulls, concat_null_yields_null,
        transaction_isolation_level, lock_timeout, deadlock_priority, row_count, command_type

        If a SQL Agent job is running, an subnode called agent_info will be populated with some or all of
        the following: job_id, job_name, step_id, step_name, msdb_query_error (in the event of an error)

        If @get_task_info is set to 2 and a lock wait is detected, a subnode called block_info will be
        populated with some or all of the following: lock_type, database_name, object_id, file_id, hobt_id,
        applock_hash, metadata_resource, metadata_class_id, object_name, schema_name

    .PARAMETER FindBlockLeaders
        Walk the blocking chain and count the number of
        total SPIDs blocked all the way down by a given session
        Also enables task_info Level 1, if @get_task_info is set to 0

    .PARAMETER DeltaInterval
        Pull deltas on various metrics
        Interval in seconds to wait before doing the second data pull

    .PARAMETER OutputColumnList
        List of desired output columns, in desired order
        Note that the final output will be the intersection of all enabled features and all
        columns in the list. Therefore, only columns associated with enabled features will
        actually appear in the output. Likewise, removing columns from this list may effectively
        disable features, even if they are turned on

        Each element in this list must be one of the valid output column names. Names must be
        delimited by square brackets. White space, formatting, and additional characters are
        allowed, as long as the list contains exact matches of delimited valid column names.

    .PARAMETER SortOrder
        Column(s) by which to sort output, optionally with sort directions.
        Valid column choices:
        session_id, physical_io, reads, physical_reads, writes, tempdb_allocations,
        tempdb_current, CPU, context_switches, used_memory, physical_io_delta,
        reads_delta, physical_reads_delta, writes_delta, tempdb_allocations_delta,
        tempdb_current_delta, CPU_delta, context_switches_delta, used_memory_delta,
        tasks, tran_start_time, open_tran_count, blocking_session_id, blocked_session_count,
        percent_complete, host_name, login_name, database_name, start_time, login_time

        Note that column names in the list must be bracket-delimited. Commas and/or white
        space are not required.

    .PARAMETER FormatOutput
        Formats some of the output columns in a more "human readable" form
        0 disables output format
        1 formats the output for variable-width fonts
        2 formats the output for fixed-width fonts

    .PARAMETER DestinationTable
        If set to a non-blank value, the script will attempt to insert into the specified destination table. Please note that the script will not verify that the table exists, or that it has the correct schema, before doing the insert. Table can be specified in one, two, or three-part format

    .PARAMETER ReturnSchema
        If set to 1, no data collection will happen and no result set will be returned; instead,
        a CREATE TABLE statement will be returned via the @schema parameter, which will match
        the schema of the result set that would be returned by using the same collection of the
        rest of the parameters. The CREATE TABLE statement will have a placeholder token of
        <table_name> in place of an actual table name.

    .PARAMETER Schema
        If set to 1, no data collection will happen and no result set will be returned; instead,
        a CREATE TABLE statement will be returned via the @schema parameter, which will match
        the schema of the result set that would be returned by using the same collection of the
        rest of the parameters. The CREATE TABLE statement will have a placeholder token of
        <table_name> in place of an actual table name.

    .PARAMETER Help
        Help! What do I do?

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: AdamMechanic, WhoIsActive, SpWhoIsActive
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaWhoIsActive

    .EXAMPLE
        PS C:\> Invoke-DbaWhoIsActive -SqlInstance sqlserver2014a

        Execute sp_whoisactive on sqlserver2014a. This command expects sp_WhoIsActive to be in the master database. Logs into the SQL Server with Windows credentials.

    .EXAMPLE
        PS C:\> Invoke-DbaWhoIsActive -SqlInstance sqlserver2014a -SqlCredential $credential -Database dbatools

        Execute sp_whoisactive on sqlserver2014a. This command expects sp_WhoIsActive to be in the dbatools database. Logs into the SQL Server with SQL Authentication.

    .EXAMPLE
        PS C:\> Invoke-DbaWhoIsActive -SqlInstance sqlserver2014a -GetAverageTime

        Similar to running sp_WhoIsActive @get_avg_time

    .EXAMPLE
        PS C:\> Invoke-DbaWhoIsActive -SqlInstance sqlserver2014a -GetOuterCommand -FindBlockLeaders

        Similar to running sp_WhoIsActive @get_outer_command = 1, @find_block_leaders = 1

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias('ServerInstance', 'SqlServer')]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]
        $SqlCredential,
        [object]$Database,
        [Alias('As')]
        [ValidateLength(0, 128)]
        [string]$Filter,
        [ValidateSet('Session', 'Program', 'Database', 'Login', 'Host')]
        [string]$FilterType = 'Session',
        [ValidateLength(0, 128)]
        [string]$NotFilter,
        [ValidateSet('Session', 'Program', 'Database', 'Login', 'Host')]
        [string]$NotFilterType = 'Session',
        [switch]$ShowOwnSpid,
        [switch]$ShowSystemSpids,
        [ValidateRange(0, 255)]
        [int]$ShowSleepingSpids,
        [switch]$GetFullInnerText,
        [ValidateRange(0, 255)]
        [int]$GetPlans,
        [switch]$GetOuterCommand,
        [switch]$GetTransactionInfo,
        [ValidateRange(0, 2)]
        [int]$GetTaskInfo,
        [switch]$GetLocks,
        [switch]$GetAverageTime,
        [switch]$GetAdditonalInfo,
        [switch]$FindBlockLeaders,
        [ValidateRange(0, 255)]
        [int]$DeltaInterval,
        [ValidateLength(0, 8000)]
        [string]$OutputColumnList = '[dd%][session_id][sql_text][sql_command][login_name][wait_info][tasks][tran_log%][cpu%][temp%][block%][reads%][writes%][context%][physical%][query_plan][locks][%]',
        [ValidateLength(0, 500)]
        [string]$SortOrder = '[start_time] ASC',
        [ValidateRange(0, 255)]
        [int]$FormatOutput = 1,
        [ValidateLength(0, 4000)]
        [string]$DestinationTable = '',
        [switch]$ReturnSchema,
        [string]$Schema,
        [switch]$Help,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $passedparams = $psboundparameters.Keys | Where-Object { 'Silent', 'SqlServer', 'SqlCredential', 'OutputAs', 'ServerInstance', 'SqlInstance', 'Database' -notcontains $_ }
        $localparams = $psboundparameters
    }

    process {

        foreach ($instance in $sqlinstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($server.VersionMajor -lt 9) {
                throw "sp_WhoIsActive is only supported in SQL Server 2005 and above"
            }

            $paramdictionary = @{
                Filter             = '@filter'
                FilterType         = '@filter_type'
                NotFilter          = 'not_filter'
                NotFilterType      = '@not_filter_type'
                ShowOwnSpid        = '@show_own_spid'
                ShowSystemSpids    = '@show_system_spids'
                ShowSleepingSpids  = '@show_sleeping_spids'
                GetFullInnerText   = '@get_full_inner_text'
                GetPlans           = '@get_plans'
                GetOuterCommand    = '@get_outer_command'
                GetTransactionInfo = '@get_transaction_info'
                GetTaskInfo        = '@get_task_info'
                GetLocks           = '@get_locks '
                GetAverageTime     = '@get_avg_time'
                GetAdditonalInfo   = '@get_additional_info'
                FindBlockLeaders   = '@find_block_leaders'
                DeltaInterval      = '@delta_interval'
                OutputColumnList   = '@output_column_list'
                SortOrder          = '@sort_order'
                FormatOutput       = '@format_output '
                DestinationTable   = '@destination_table '
                ReturnSchema       = '@return_schema'
                Schema             = '@schema'
                Help               = '@help'
            }

            Write-Message -Level Verbose -Message "Collecting sp_whoisactive data from server: $instance"
            try {
                $sqlconnection = New-Object System.Data.SqlClient.SqlConnection
                $sqlconnection.ConnectionString = $server.ConnectionContext.ConnectionString
                $sqlconnection.Open()

                if ($Database) {
                    # database is being returned as something weird. change it to string without using a method then trim.
                    $Database = "$Database"
                    $Database = $Database.Trim()
                    $sqlconnection.ChangeDatabase($Database)
                }

                $sqlcommand = New-Object System.Data.SqlClient.SqlCommand
                $sqlcommand.CommandType = "StoredProcedure"
                $sqlcommand.CommandText = "dbo.sp_WhoIsActive"
                $sqlcommand.Connection = $sqlconnection

                foreach ($param in $passedparams) {
                    Write-Message -Level Verbose -Message "Check parameter '$param'"

                    $sqlparam = $paramdictionary[$param]

                    if ($sqlparam) {

                        $value = $localparams[$param]

                        switch ($value) {
                            $true { $value = 1 }
                            $false { $value = 0 }
                        }
                        Write-Message -Level Verbose -Message "Adding parameter '$sqlparam' with value '$value'"
                        [Void]$sqlcommand.Parameters.AddWithValue($sqlparam, $value)
                    }
                }

                $datatable = New-Object system.Data.DataSet
                $dataadapter = New-Object system.Data.SqlClient.SqlDataAdapter($sqlcommand)
                $dataadapter.fill($datatable) | Out-Null
                $datatable.Tables.Rows
            } catch {
                if ($_.Exception.InnerException -Like "*Could not find*") {
                    Stop-Function -Message "sp_whoisactive not found, please install using Install-DbaWhoIsActive." -Continue
                } else {
                    Stop-Function -Message "Invalid query." -Continue
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Show-SqlWhoIsActive -CustomMessage "Show-SqlWhoIsActive is no longer supported. Use Invoke-DbaWhoIsActive | Out-GridView for similar results."
    }
}
tools\dbatools\functions\Invoke-DbaXEReplay.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Invoke-DbaXeReplay {
    <#
    .SYNOPSIS
        This command replays events from Read-DbaXEFile on one or more target servers

    .DESCRIPTION
        This command replays events from Read-DbaXEFile. It is simplistic in its approach.

        - Writes all queries to a temp sql file
        - Executes temp file using . $sqlcmd so that batches are executed properly
        - Deletes temp file

    .PARAMETER SqlInstance
        Target SQL Server(s)

    .PARAMETER SqlCredential
        Used to provide alternative credentials.

    .PARAMETER Database
        The initial starting database.

    .PARAMETER Event
        Each Response can be limited to processing specific events, while ignoring all the other ones. When this attribute is omitted, all events are processed.

    .PARAMETER Raw
        By dafault, the results of . $sqlcmd are collected, cleaned up and displayed. If you'd like to see all results immeidately, use Raw.

    .PARAMETER InputObject
        Accepts the object output of Read-DbaXESession.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaXEReplay

    .EXAMPLE
        PS C:\> Read-DbaXEFile -Path C:\temp\sample.xel | Invoke-DbaXeReplay -SqlInstance sql2017

        Runs all batch_text for sql_batch_completed against tempdb on sql2017.

    .EXAMPLE
        PS C:\> Read-DbaXEFile -Path C:\temp\sample.xel | Invoke-DbaXeReplay -SqlInstance sql2017 -Database planning -Event sql_batch_completed

        Sets the *initial* database to planning then runs only sql_batch_completed against sql2017.

    .EXAMPLE
        PS C:\> Read-DbaXEFile -Path C:\temp\sample.xel | Invoke-DbaXeReplay -SqlInstance sql2017, sql2016

        Runs all batch_text for sql_batch_completed against tempdb on sql2017 and sql2016.


    #>
    [Cmdletbinding()]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseOutputTypeCorrectly", "", Justification = "PSSA Rule Ignored by BOH")]
    param (
        [Parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance[]]$SqlInstance,
        [Alias("Credential")]
        [PsCredential]$SqlCredential,
        [string[]]$Database,
        [string[]]$Event = @('sql_batch_completed', 'rcp_completed'),
        [Parameter(Mandatory, ValueFromPipeline)]
        [object]$InputObject,
        [switch]$Raw,
        [switch]$EnableException
    )

    begin {
        #Variable marked as unused by PSScriptAnalyzer
        #$querycolumns = 'statement', 'batch_text'
        $timestamp = (Get-Date -Format yyyyMMddHHmm)
        $temp = ([System.IO.Path]::GetTempPath()).TrimEnd("\")
        $filename = "$temp\dbatools-replay-$timestamp.sql"
        Set-Content $filename -Value $null

        $sqlcmd = "$script:PSModuleRoot\bin\sqlcmd\sqlcmd.exe"
    }
    process {
        if (Test-FunctionInterrupt) { return }
        if ($InputObject.Name -notin $Event) {
            continue
        }

        if ($InputObject.statement) {
            if ($InputObject.statement -notmatch "ALTER EVENT SESSION") {
                Add-Content -Path $filename -Value $InputObject.statement
                Add-Content -Path $filename -Value "GO"
            }
        } else {
            if ($InputObject.batch_text -notmatch "ALTER EVENT SESSION") {
                Add-Content -Path $filename -Value $InputObject.batch_text
                Add-Content -Path $filename -Value "GO"
            }
        }
    }
    end {
        if (Test-FunctionInterrupt) { return }
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Target $instance -Continue
            }


            if ($Raw) {
                Write-Message -Message "Invoking XEReplay against $instance running on $($server.name) with raw output" -Level Verbose
                if (Test-Bound -ParameterName SqlCredential) {
                    . $sqlcmd -S $instance -i $filename -U $SqlCredential.Username -P $SqlCredential.GetNetworkCredential().Password
                    continue
                } else {
                    . $sqlcmd -S $instance -i $filename
                    continue
                }
            }

            Write-Message -Message "Invoking XEReplay against $instance running on $($server.name)" -Level Verbose
            if (Test-Bound -ParameterName SqlCredential) {
                $output = . $sqlcmd -S $instance -i $filename -U $SqlCredential.Username -P $SqlCredential.GetNetworkCredential().Password
            } else {
                $output = . $sqlcmd -S $instance -i $filename
            }

            foreach ($line in $output) {
                $newline = $line.Trim()
                if ($newline -and $newline -notmatch "------------------------------------------------------------------------------------") {
                    "$newline"
                }
            }
        }
        Remove-Item -Path $filename -ErrorAction Ignore
    }
}
tools\dbatools\functions\Join-DbaAvailabilityGroup.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Join-DbaAvailabilityGroup {
    <#
    .SYNOPSIS
        Joins a secondary replica to an availability group on a SQL Server instance.

    .DESCRIPTION
        Joins a secondary replica to an availability group on a SQL Server instance.

   .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.

    .PARAMETER SqlCredential
        Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER AvailabilityGroup
        The availability group to join.

    .PARAMETER ClusterType
        Cluster type of the Availability Group. Only supported in SQL Server 2017 and above.
        Options include: External, Wsfc or None.

    .PARAMETER InputObject
        Enables piped input from Get-DbaAvailabilityGroup.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: AvailabilityGroup, HA, AG
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Join-DbaAvailabilityGroup

    .EXAMPLE
        PS C:\> Get-DbaAvailabilityGroup -SqlInstance sql01 -AvailabilityGroup SharePoint | Join-DbaAvailabilityGroup -SqlInstance sql02

        Joins sql02 to the SharePoint availability group on sql01

    .EXAMPLE
        PS C:\> $ag = Get-DbaAvailabilityGroup -SqlInstance sql01 -AvailabilityGroup SharePoint
        PS C:\> Join-DbaAvailabilityGroup -SqlInstance sql02 -InputObject $ag

        Joins sql02 to the SharePoint availability group on sql01

    .EXAMPLE
        PS C:\> Get-DbaAvailabilityGroup -SqlInstance sql01 -AvailabilityGroup SharePoint | Join-DbaAvailabilityGroup -SqlInstance sql02 -WhatIf

        Shows what would happen if the command were to run. No actions are actually performed.

    .EXAMPLE
        PS C:\> Get-DbaAvailabilityGroup -SqlInstance sql01 -AvailabilityGroup SharePoint | Join-DbaAvailabilityGroup -SqlInstance sql02 -Confirm

        Prompts for confirmation then joins sql02 to the SharePoint availability group on sql01.
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$AvailabilityGroup,
        [ValidateSet('External', 'Wsfc', 'None')]
        [string]$ClusterType,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.AvailabilityGroup[]]$InputObject,
        [switch]$EnableException
    )
    process {

        if ($InputObject) {
            $AvailabilityGroup += $InputObject.Name
            if (-not $ClusterType) {
                $tempclustertype = ($InputObject | Select-Object -First 1).ClusterType
                if ($tempclustertype) {
                    $ClusterType = $tempclustertype
                }
            }
        }

        if (-not $AvailabilityGroup) {
            Stop-Function -Message "No availability group to add"
            return
        }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            foreach ($ag in $AvailabilityGroup) {
                if ($Pscmdlet.ShouldProcess($server.Name, "Joining $ag")) {
                    try {
                        if ($ClusterType -and $server.VersionMajor -ge 14) {
                            $server.Query("ALTER AVAILABILITY GROUP [$ag] JOIN WITH (CLUSTER_TYPE = $ClusterType)")
                        } else {
                            $server.JoinAvailabilityGroup($ag)
                        }
                    } catch {
                        Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Measure-DbaBackupThroughput.ps1
function Measure-DbaBackupThroughput {
    <#
    .SYNOPSIS
        Determines how quickly SQL Server is backing up databases to media.

    .DESCRIPTION
        Returns backup history details for one or more databases on a SQL Server.

        Output looks like this:
        SqlInstance     : sql2016
        Database        : SharePoint_Config
        AvgThroughput   : 1.07 MB
        AvgSize         : 24.17
        AvgDuration     : 00:00:01.1000000
        MinThroughput   : 0.02 MB
        MaxThroughput   : 2.26 MB
        MinBackupDate   : 8/6/2015 10:22:01 PM
        MaxBackupDate   : 6/19/2016 12:57:45 PM
        BackupCount     : 10

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude. Options for this list are auto-populated from the server.

    .PARAMETER Type
        By default, this command measures the speed of Full backups. Valid options are "Full", "Log" and "Differential".

    .PARAMETER Since
        All backups taken on or after the point in time represented by this datetime object will be processed.

    .PARAMETER Last
        If this switch is enabled, only the last backup will be measured.

    .PARAMETER DeviceType
        Specifies one or more DeviceTypes to use in filtering backup sets. Valid values are "Disk", "Permanent Disk Device", "Tape", "Permanent Tape Device", "Pipe", "Permanent Pipe Device" and "Virtual Device", as well as custom integers for your own DeviceTypes.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Backup, Database
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Measure-DbaBackupThroughput

    .EXAMPLE
        PS C:\> Measure-DbaBackupThroughput -SqlInstance sql2016

        Parses every backup in msdb's backuphistory for stats on all databases.

    .EXAMPLE
        PS C:\> Measure-DbaBackupThroughput -SqlInstance sql2016 -Database AdventureWorks2014

        Parses every backup in msdb's backuphistory for stats on AdventureWorks2014.

    .EXAMPLE
        PS C:\> Measure-DbaBackupThroughput -SqlInstance sql2005 -Last

        Processes the last full, diff and log backups every backup for all databases on sql2005.

    .EXAMPLE
        PS C:\> Measure-DbaBackupThroughput -SqlInstance sql2005 -Last -Type Log

        Processes the last log backups every backup for all databases on sql2005.

    .EXAMPLE
        PS C:\> Measure-DbaBackupThroughput -SqlInstance sql2016 -Since (Get-Date).AddDays(-7) | Where-Object { $_.MinThroughput.Gigabyte -gt 1 }

        Gets backup calculations for the last week and filters results that have a minimum of 1GB throughput

    .EXAMPLE
        PS C:\> Measure-DbaBackupThroughput -SqlInstance sql2016 -Since (Get-Date).AddDays(-365) -Database bigoldb

        Gets backup calculations, limited to the last year and only the bigoldb database

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "Instance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [datetime]$Since,
        [switch]$Last,
        [ValidateSet("Full", "Log", "Differential", "File", "Differential File", "Partial Full", "Partial Differential")]
        [string]$Type = "Full",
        [string[]]$DeviceType,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($Database) {
                $DatabaseCollection = $server.Databases | Where-Object Name -in $Database
            } else {
                $DatabaseCollection = $server.Databases
            }

            if ($ExcludeDatabase) {
                $DatabaseCollection = $DatabaseCollection | Where-Object Name -NotIn $ExcludeDatabase
            }

            foreach ($db in $DatabaseCollection) {
                Write-Message -Level VeryVerbose -Message "Retrieving history for $db."
                $allhistory = @()

                # Splatting didn't work
                if ($since) {
                    $histories = Get-DbaBackupHistory -SqlInstance $server -Database $db.name -Since $since -DeviceType $DeviceType -Type $Type
                } else {
                    $histories = Get-DbaBackupHistory -SqlInstance $server -Database $db.name -Last:$last -DeviceType $DeviceType -Type $Type
                }

                foreach ($history in $histories) {
                    $timetaken = New-TimeSpan -Start $history.Start -End $history.End

                    if ($timetaken.TotalMilliseconds -eq 0) {
                        $throughput = $history.TotalSize.Megabyte
                    } else {
                        $throughput = $history.TotalSize.Megabyte / $timetaken.TotalSeconds
                    }

                    Add-Member -Force -InputObject $history -MemberType Noteproperty -Name MBps -value $throughput

                    $allhistory += $history | Select-Object ComputerName, InstanceName, SqlInstance, Database, MBps, TotalSize, Start, End
                }

                Write-Message -Level VeryVerbose -Message "Calculating averages for $db."
                foreach ($db in ($allhistory | Sort-Object Database | Group-Object Database)) {

                    $measuremb = $db.Group.MBps | Measure-Object -Average -Minimum -Maximum
                    $measurestart = $db.Group.Start | Measure-Object -Minimum
                    $measureend = $db.Group.End | Measure-Object -Maximum
                    $measuresize = $db.Group.TotalSize.Megabyte | Measure-Object -Average
                    $avgduration = $db.Group | ForEach-Object { New-TimeSpan -Start $_.Start -End $_.End } | Measure-Object -Average TotalSeconds

                    [pscustomobject]@{
                        ComputerName  = $db.Group.ComputerName | Select-Object -First 1
                        InstanceName  = $db.Group.InstanceName | Select-Object -First 1
                        SqlInstance   = $db.Group.SqlInstance | Select-Object -First 1
                        Database      = $db.Name
                        AvgThroughput = [dbasize]([System.Math]::Round($measuremb.Average, 2) * 1024 * 1024)
                        AvgSize       = [dbasize]([System.Math]::Round($measuresize.Average, 2) * 1024 * 1024)
                        AvgDuration   = [dbatimespan](New-TimeSpan -Seconds $avgduration.Average)
                        MinThroughput = [dbasize]([System.Math]::Round($measuremb.Minimum, 2) * 1024 * 1024)
                        MaxThroughput = [dbasize]([System.Math]::Round($measuremb.Maximum, 2) * 1024 * 1024)
                        MinBackupDate = [dbadatetime]$measurestart.Minimum
                        MaxBackupDate = [dbadatetime]$measureend.Maximum
                        BackupCount   = $db.Count
                    } | Select-DefaultView -ExcludeProperty ComputerName, InstanceName
                }
            }
        }
    }
}
tools\dbatools\functions\Measure-DbaDiskSpaceRequirement.ps1
function Measure-DbaDiskSpaceRequirement {
    <#
    .SYNOPSIS
        Calculate the space needed to copy and possibly replace a database from one SQL server to another.

    .DESCRIPTION
        Returns a file list from source and destination where source file may overwrite destination. Complex scenarios where a new file may exist is taken into account.
        This command will accept a hash object in pipeline with the following keys: Source, SourceDatabase, Destination. Using this command will provide a way to prepare before a complex migration with multiple databases from different sources and destinations.

    .PARAMETER Source
        Source SQL Server.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database to copy. It MUST exist.

    .PARAMETER Destination
        Destination SQL Server instance.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER DestinationDatabase
        The database name at destination.
        May or may not be present, if unspecified it will default to the database name provided in SourceDatabase.

    .PARAMETER Credential
        The credentials to use to connect via CIM/WMI/PowerShell remoting.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database, DiskSpace, Migration
        Author: Pollus Brodeur (@pollusb)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Measure-DbaDiskSpaceRequirement

    .EXAMPLE
        PS C:\> Measure-DbaDiskSpaceRequirement -Source INSTANCE1 -Database DB1 -Destination INSTANCE2

        Calculate space needed for a simple migration with one database with the same name at destination.

    .EXAMPLE
        PS C:\> @(
        >> [PSCustomObject]@{Source='SQL1';Destination='SQL2';Database='DB1'},
        >> [PSCustomObject]@{Source='SQL1';Destination='SQL2';Database='DB2'}
        >> ) | Measure-DbaDiskSpaceRequirement

        Using a PSCustomObject with 2 databases to migrate on SQL2.

    .EXAMPLE
        PS C:\> Import-Csv -Path .\migration.csv -Delimiter "`t" | Measure-DbaDiskSpaceRequirement | Format-Table -AutoSize

        Using a CSV file. You will need to use this header line "Source<tab>Destination<tab>Database<tab>DestinationDatabase".

    .EXAMPLE
        PS C:\> $qry = "SELECT Source, Destination, Database FROM dbo.Migrations"
        PS C:\> Invoke-DbaCmd -SqlInstance DBA -Database Migrations -Query $qry | Measure-DbaDiskSpaceRequirement

        Using a SQL table. We are DBA after all!

    #>
    [CmdletBinding()]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseOutputTypeCorrectly", "", Justification = "PSSA Rule Ignored by BOH")]
    param(
        [Parameter(Mandatory, ValueFromPipelineByPropertyName = $true)]
        [DbaInstanceParameter]$Source,
        [Parameter(Mandatory, ValueFromPipelineByPropertyName = $true)]
        [string]$Database,
        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [PSCredential]$SourceSqlCredential,
        [Parameter(Mandatory, ValueFromPipelineByPropertyName = $true)]
        [DbaInstanceParameter]$Destination,
        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [string]$DestinationDatabase,
        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [PSCredential]$DestinationSqlCredential,
        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [PSCredential]$Credential,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        $local:cacheMP = @{}
        $local:cacheDP = @{}
        function Get-MountPoint {
            [CmdletBinding()]
            param(
                [Parameter(Mandatory)]
                $computerName,
                [PSCredential]$credential
            )
            Get-DbaCmObject -Class Win32_MountPoint -ComputerName $computerName -Credential $credential |
                Select-Object @{n = 'Mountpoint'; e = {$_.Directory.split('=')[1].Replace('"', '').Replace('\\', '\')}}
        }
        function Get-MountPointFromPath {
            [CmdletBinding()]
            param(
                [Parameter(Mandatory)]
                $path,
                [Parameter(Mandatory)]
                $computerName,
                [PSCredential]$credential
            )
            if (!$cacheMP[$computerName]) {
                try {
                    $cacheMP.Add($computerName, (Get-MountPoint -computerName $computerName -credential $credential))
                    Write-Message -Level Verbose -Message "cacheMP[$computerName] is now cached"
                } catch {
                    # This way, I won't be asking again for this computer.
                    $cacheMP.Add($computerName, '?')
                    Stop-Function -Message "Can't connect to $computerName. cacheMP[$computerName] = ?" -ErrorRecord $_ -Target $computerName -Continue
                }
            }
            if ($cacheMP[$computerName] -eq '?') {
                return '?'
            }
            foreach ($m in ($cacheMP[$computerName] | Sort-Object -Property Mountpoint -Descending)) {
                if ($path -like "$($m.Mountpoint)*") {
                    return $m.Mountpoint
                }
            }
            Write-Message -Level Warning -Message "Path $path can't be found in any MountPoints of $computerName"
        }
        function Get-MountPointFromDefaultPath {
            [CmdletBinding()]
            param(
                [Parameter(Mandatory)]
                [ValidateSet('Log', 'Data')]
                $DefaultPathType,
                [Parameter(Mandatory)]
                $SqlInstance,
                [PSCredential]$SqlCredential,
                # Could probably use the computer defined in SqlInstance but info was already available from the caller
                $computerName,
                [PSCredential]$Credential
            )
            if (!$cacheDP[$SqlInstance]) {
                try {
                    $cacheDP.Add($SqlInstance, (Get-DbaDefaultPath -SqlInstance $SqlInstance -SqlCredential $SqlCredential -EnableException))
                    Write-Message -Level Verbose -Message "cacheDP[$SqlInstance] is now cached"
                } catch {
                    Stop-Function -Message "Can't connect to $SqlInstance" -Continue
                    $cacheDP.Add($SqlInstance, '?')
                    return '?'
                }
            }
            if ($cacheDP[$SqlInstance] -eq '?') {
                return '?'
            }
            if (!$computerName) {
                $computerName = $cacheDP[$SqlInstance].ComputerName
            }
            if (!$cacheMP[$computerName]) {
                try {
                    $cacheMP.Add($computerName, (Get-MountPoint -computerName $computerName -Credential $Credential))
                } catch {
                    Stop-Function -Message "Can't connect to $computerName." -Continue
                    $cacheMP.Add($computerName, '?')
                    return '?'
                }
            }
            if ($DefaultPathType -eq 'Log') {
                $path = $cacheDP[$SqlInstance].Log
            } else {
                $path = $cacheDP[$SqlInstance].Data
            }
            foreach ($m in ($cacheMP[$computerName] | Sort-Object -Property Mountpoint -Descending)) {
                if ($path -like "$($m.Mountpoint)*") {
                    return $m.Mountpoint
                }
            }
        }
    }
    process {
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
        }

        try {
            $destServer = Connect-SqlInstance -SqlInstance $Destination -SqlCredential $DestinationSqlCredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Destination
        }

        if (Test-Bound 'DestinationDatabase' -not) {
            $DestinationDatabase = $Database
        }
        Write-Message -Level Verbose -Message "$Source.[$Database] -> $Destination.[$DestinationDatabase]"

        $sourceDb = Get-DbaDatabase -SqlInstance $sourceServer -Database $Database -SqlCredential $SourceSqlCredential
        if (Test-Bound 'Database' -not) {
            Stop-Function -Message "Database [$Database] MUST exist on Source Instance $Source." -ErrorRecord $_
        }
        $sourceFiles = @($sourceDb.FileGroups.Files | Select-Object Name, FileName, Size, @{n = 'Type'; e = {'Data'}})
        $sourceFiles += @($sourceDb.LogFiles        | Select-Object Name, FileName, Size, @{n = 'Type'; e = {'Log'}})

        if ($destDb = Get-DbaDatabase -SqlInstance $destServer -Database $DestinationDatabase -SqlCredential $DestinationSqlCredential) {
            $destFiles = @($destDb.FileGroups.Files | Select-Object Name, FileName, Size, @{n = 'Type'; e = {'Data'}})
            $destFiles += @($destDb.LogFiles        | Select-Object Name, FileName, Size, @{n = 'Type'; e = {'Log'}})
            $computerName = $destDb.ComputerName
        } else {
            Write-Message -Level Verbose -Message "Database [$DestinationDatabase] does not exist on Destination Instance $Destination."
            $computerName = $destServer.ComputerName
        }

        foreach ($sourceFile in $sourceFiles) {
            foreach ($destFile in $destFiles) {
                if (($found = ($sourceFile.Name -eq $destFile.Name))) {
                    # Files found on both sides
                    [PSCustomObject]@{
                        SourceComputerName      = $sourceServer.ComputerName
                        SourceInstance          = $sourceServer.ServiceName
                        SourceSqlInstance       = $sourceServer.DomainInstanceName
                        DestinationComputerName = $destServer.ComputerName
                        DestinationInstance     = $destServer.ServiceName
                        DestinationSqlInstance  = $destServer.DomainInstanceName
                        SourceDatabase          = $sourceDb.Name
                        SourceLogicalName       = $sourceFile.Name
                        SourceFileName          = $sourceFile.FileName
                        SourceFileSize          = [DbaSize]($sourceFile.Size * 1000)
                        DestinationDatabase     = $destDb.Name
                        DestinationLogicalName  = $destFile.Name
                        DestinationFileName     = $destFile.FileName
                        DestinationFileSize     = [DbaSize]($destFile.Size * 1000) * -1
                        DifferenceSize          = [DbaSize]( ($sourceFile.Size * 1000) - ($destFile.Size * 1000) )
                        MountPoint              = Get-MountPointFromPath -Path $destFile.Filename -ComputerName $computerName -Credential $Credential
                        FileLocation            = 'Source and Destination'
                    } | Select-DefaultView -ExcludeProperty SourceComputerName, SourceInstance, DestinationInstance, DestinationLogicalName
                    break
                }
            }
            if (!$found) {
                # Files on source but not on destination
                [PSCustomObject]@{
                    SourceComputerName      = $sourceServer.ComputerName
                    SourceInstance          = $sourceServer.ServiceName
                    SourceSqlInstance       = $sourceServer.DomainInstanceName
                    DestinationComputerName = $destServer.ComputerName
                    DestinationInstance     = $destServer.ServiceName
                    DestinationSqlInstance  = $destServer.DomainInstanceName
                    SourceDatabase          = $sourceDb.Name
                    SourceLogicalName       = $sourceFile.Name
                    SourceFileName          = $sourceFile.FileName
                    SourceFileSize          = [DbaSize]($sourceFile.Size * 1000)
                    DestinationDatabase     = $DestinationDatabase
                    DestinationLogicalName  = $null
                    DestinationFileName     = $null
                    DestinationFileSize     = [DbaSize]0
                    DifferenceSize          = [DbaSize]($sourceFile.Size * 1000)
                    MountPoint              = Get-MountPointFromDefaultPath -DefaultPathType $sourceFile.Type -SqlInstance $Destination `
                        -SqlCredential $DestinationSqlCredential -computerName $computerName -credential $Credential
                    FileLocation            = 'Only on Source'
                } | Select-DefaultView -ExcludeProperty SourceComputerName, SourceInstance, DestinationInstance, DestinationLogicalName
            }
        }
        if ($destDb) {
            # Files on destination but not on source (strange scenario but possible)
            $destFilesNotSource = Compare-Object -ReferenceObject $destFiles -DifferenceObject $sourceFiles -Property Name -PassThru
            foreach ($destFileNotSource in $destFilesNotSource) {
                [PSCustomObject]@{
                    SourceComputerName      = $sourceServer.ComputerName
                    SourceInstance          = $sourceServer.ServiceName
                    SourceSqlInstance       = $sourceServer.DomainInstanceName
                    DestinationComputerName = $destServer.ComputerName
                    DestinationInstance     = $destServer.ServiceName
                    DestinationSqlInstance  = $destServer.DomainInstanceName
                    SourceDatabaseName      = $Database
                    SourceLogicalName       = $null
                    SourceFileName          = $null
                    SourceFileSize          = [DbaSize]0
                    DestinationDatabaseName = $destDb.Name
                    DestinationLogicalName  = $destFileNotSource.Name
                    DestinationFileName     = $destFile.FileName
                    DestinationFileSize     = [DbaSize]($destFileNotSource.Size * 1000) * -1
                    DifferenceSize          = [DbaSize]($destFileNotSource.Size * 1000) * -1
                    MountPoint              = Get-MountPointFromPath -Path $destFileNotSource.Filename -ComputerName $computerName -Credential $Credential
                    FileLocation            = 'Only on Destination'
                } | Select-DefaultView -ExcludeProperty SourceComputerName, SourceInstance, DestinationInstance, DestinationLogicalName
            }
        }
        $DestinationDatabase = $null
    }
}
tools\dbatools\functions\Measure-DbatoolsImport.ps1
function Measure-DbatoolsImport {
    <#
    .SYNOPSIS
        Displays the import load times of the dbatools PowerShell module

    .DESCRIPTION
        Displays the import load times of the dbatools PowerShell module

    .NOTES
        Tags: Debug
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Measure-DbatoolsImport

    .EXAMPLE
        PS C:\> Measure-DbatoolsImport
        Displays the import load times of the dbatools PowerShell module

    .EXAMPLE
        PS C:\> Import-Module dbatools
        PS C:\> Measure-DbatoolsImport

        Displays the import load times of the dbatools PowerShell module

    #>
    [Sqlcollaborative.Dbatools.dbaSystem.DebugHost]::ImportTime
}
tools\dbatools\functions\Mount-DbaDatabase.ps1
function Mount-DbaDatabase {
    <#
    .SYNOPSIS
        Attach a SQL Server Database - aliased to Attach-DbaDatabase

    .DESCRIPTION
        This command will attach a SQL Server database.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to attach.

    .PARAMETER FileStructure
        A StringCollection object value that contains a list database files. If FileStructure is not specified, BackupHistory will be used to guess the structure.

    .PARAMETER DatabaseOwner
        Sets the database owner for the database. The sa account (or equivalent) will be used if DatabaseOwner is not specified.

    .PARAMETER AttachOption
        An AttachOptions object value that contains the attachment options. Valid options are "None", "RebuildLog", "EnableBroker", "NewBroker" and "ErrorBrokerConversations".

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Mount-DbaDatabase

    .EXAMPLE
        PS C:\> $fileStructure = New-Object System.Collections.Specialized.StringCollection
        PS C:\> $fileStructure.Add("E:\archive\example.mdf")
        PS C:\> $filestructure.Add("E:\archive\example.ldf")
        PS C:\> $filestructure.Add("E:\archive\example.ndf")
        PS C:\> Mount-DbaDatabase -SqlInstance sql2016 -Database example -FileStructure $fileStructure

        Attaches a database named "example" to sql2016 with the files "E:\archive\example.mdf", "E:\archive\example.ldf" and "E:\archive\example.ndf". The database owner will be set to sa and the attach option is None.

    .EXAMPLE
        PS C:\> Mount-DbaDatabase -SqlInstance sql2016 -Database example

        Since the FileStructure was not provided, this command will attempt to determine it based on backup history. If found, a database named example will be attached to sql2016.

    .EXAMPLE
        PS C:\> Mount-DbaDatabase -SqlInstance sql2016 -Database example -WhatIf

        Shows what would happen if the command were executed (without actually performing the command)

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]
        $SqlCredential,
        [parameter(Mandatory)]
        [string[]]$Database,
        [System.Collections.Specialized.StringCollection]$FileStructure,
        [string]$DatabaseOwner,
        [ValidateSet('None', 'RebuildLog', 'EnableBroker', 'NewBroker', 'ErrorBrokerConversations')]
        [string]$AttachOption = "None",
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if (-not $server.Logins.Item($DatabaseOwner)) {
                try {
                    $DatabaseOwner = ($server.Logins | Where-Object { $_.id -eq 1 }).Name
                } catch {
                    $DatabaseOwner = "sa"
                }
            }

            foreach ($db in $database) {

                if ($server.Databases[$db]) {
                    Stop-Function -Message "$db is already attached to $server." -Target $db -Continue
                }

                if ($server.Databases[$db].IsSystemObject) {
                    Stop-Function -Message "$db is a system database and cannot be attached using this method." -Target $db -Continue
                }

                if (-Not (Test-Bound -Parameter FileStructure)) {
                    $backuphistory = Get-DbaBackupHistory -SqlInstance $server -Database $db -Type Full | Sort-Object End -Descending | Select-Object -First 1

                    if (-not $backuphistory) {
                        $message = "Could not enumerate backup history to automatically build FileStructure. Rerun the command and provide the filestructure parameter."
                        Stop-Function -Message $message -Target $db -Continue
                    }

                    $backupfile = $backuphistory.Path[0]
                    $filepaths = (Read-DbaBackupHeader -SqlInstance $server -FileList -Path $backupfile).PhysicalName

                    $FileStructure = New-Object System.Collections.Specialized.StringCollection
                    foreach ($file in $filepaths) {
                        $exists = Test-Dbapath -SqlInstance $server -Path $file
                        if (-not $exists) {
                            $message = "Could not find the files to build the FileStructure. Rerun the command and provide the FileStructure parameter."
                            Stop-Function -Message $message -Target $file -Continue
                        }

                        $null = $FileStructure.Add($file)
                    }
                }

                If ($Pscmdlet.ShouldProcess($server, "Attaching $Database with $DatabaseOwner as database owner and $AttachOption as attachoption")) {
                    try {
                        $server.AttachDatabase($db, $FileStructure, $DatabaseOwner, [Microsoft.SqlServer.Management.Smo.AttachOptions]::$AttachOption)

                        [pscustomobject]@{
                            ComputerName  = $server.ComputerName
                            InstanceName  = $server.ServiceName
                            SqlInstance   = $server.DomainInstanceName
                            Database      = $db
                            AttachResult  = "Success"
                            AttachOption  = $AttachOption
                            FileStructure = $FileStructure
                        }
                    } catch {
                        Stop-Function -Message "Failure" -ErrorRecord $_ -Target $server
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Move-DbaCmsRegServer.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Move-DbaCmsRegServer {
    <#
    .SYNOPSIS
        Moves registered servers around SQL Server Central Management Server (CMS)

    .DESCRIPTION
        Moves registered servers around SQL Server Central Management Server (CMS)

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Name
        Specifies one or more reg servers to move. Name is the visible name in SSMS CMS interface (labeled Registered Server Name)

    .PARAMETER ServerName
        Specifies one or more reg servers to move. Server Name is the actual instance name (labeled Server Name)

    .PARAMETER NewGroup
        The new group. If no new group is specified, the default root will used

    .PARAMETER InputObject
        Allows results from Get-DbaCmsRegServer to be piped in

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.

        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.

        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: RegisteredServer, CMS
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Move-DbaCmsRegServer

    .EXAMPLE
        PS C:\> Move-DbaCmsRegServer -SqlInstance sql2012 -Name 'Web SQL Cluster' -NewGroup HR\Prod

        Moves the registered server on sql2012 titled 'Web SQL Cluster' to the Prod group within the HR group

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sql2017 -Name 'Web SQL Cluster' | Move-DbaCmsRegServer -NewGroup Web

        Moves the registered server 'Web SQL Cluster' on sql2017 to the Web group, also on sql2017

    #>

    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Name,
        [string[]]$ServerName,
        [string]$NewGroup,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.RegisteredServers.RegisteredServer[]]$InputObject,
        [switch]$EnableException
    )

    begin {
        if ((Test-Bound -ParameterName SqlInstance) -and (Test-Bound -Not -ParameterName Name) -and (Test-Bound -Not -ParameterName ServerName)) {
            Stop-Function -Message "Name or ServerName must be specified when using -SqlInstance"
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }

        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaCmsRegServer -SqlInstance $instance -SqlCredential $SqlCredential -Name $Name -ServerName $ServerName

        }

        foreach ($regserver in $InputObject) {
            $parentserver = Get-RegServerParent -InputObject $regserver

            if ($null -eq $parentserver) {
                Stop-Function -Message "Something went wrong and it's hard to explain, sorry. This basically shouldn't happen." -Continue
            }

            $server = $parentserver.ServerConnection.SqlConnectionObject

            if ((Test-Bound -ParameterName NewGroup)) {
                $group = Get-DbaCmsRegServerGroup -SqlInstance $server -Group $NewGroup

                if (-not $group) {
                    Stop-Function -Message "$NewGroup not found on $server" -Continue
                }
            } else {
                $group = Get-DbaCmsRegServerGroup -SqlInstance $server -Id 1
            }

            if ($Pscmdlet.ShouldProcess($regserver.SqlInstance, "Moving $($regserver.Name) to $group")) {
                try {
                    $null = $parentserver.ServerConnection.ExecuteNonQuery($regserver.ScriptMove($group).GetScript())
                    Get-DbaCmsRegServer -SqlInstance $server -Name $regserver.Name -ServerName $regserver.ServerName
                    $parentserver.ServerConnection.Disconnect()
                } catch {
                    Stop-Function -Message "Failed to move $($regserver.Name) to $NewGroup on $($regserver.SqlInstance)" -ErrorRecord $_ -Continue
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Move-DbaRegisteredServer
    }
}
tools\dbatools\functions\Move-DbaCmsRegServerGroup.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Move-DbaCmsRegServerGroup {
    <#
    .SYNOPSIS
        Moves registered server groups around SQL Server Central Management Server (CMS).

    .DESCRIPTION
        Moves registered server groups around SQL Server Central Management Server (CMS).

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Group
        Specifies one or more groups to include from SQL Server Central Management Server.

    .PARAMETER NewGroup
        The new location.

    .PARAMETER InputObject
        Allows results from Get-DbaCmsRegServerGroup to be piped in

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.

        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.

        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: RegisteredServer, CMS
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Move-DbaCmsRegServerGroup

    .EXAMPLE
        PS C:\> Move-DbaCmsRegServerGroup -SqlInstance sql2012 -Group HR\Development -NewGroup AD\Prod

        Moves the Development group within HR to the Prod group within AD

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServerGroup -SqlInstance sql2017 -Group HR\Development| Move-DbaCmsRegServer -NewGroup Web

        Moves the Development group within HR to the Web group

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Group,
        [parameter(Mandatory)]
        [string]$NewGroup,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.RegisteredServers.ServerGroup[]]$InputObject,
        [switch]$EnableException
    )
    begin {
        if ((Test-Bound -ParameterName SqlInstance) -and (Test-Bound -Not -ParameterName Group)) {
            Stop-Function -Message "Group must be specified when using -SqlInstance"
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }

        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaCmsRegServerGroup -SqlInstance $instance -SqlCredential $SqlCredential -Group $Group
        }

        foreach ($regservergroup in $InputObject) {
            $parentserver = Get-RegServerParent -InputObject $regservergroup

            if ($null -eq $parentserver) {
                Stop-Function -Message "Something went wrong and it's hard to explain, sorry. This basically shouldn't happen." -Continue
            }

            $server = $parentserver.ServerConnection.SqlConnectionObject

            if ($NewGroup -eq 'Default') {
                $groupobject = Get-DbaCmsRegServerGroup -SqlInstance $server -Id 1
            } else {
                $groupobject = Get-DbaCmsRegServerGroup -SqlInstance $server -Group $NewGroup
            }

            Write-Message -Level Verbose -Message "Found $($groupobject.Name) on $($parentserver.ServerConnection.ServerName)"

            if (-not $groupobject) {
                Stop-Function -Message "Group '$NewGroup' not found on $server" -Continue
            }

            if ($Pscmdlet.ShouldProcess($regservergroup.SqlInstance, "Moving $($regservergroup.Name) to $($groupobject.Name)")) {
                try {
                    Write-Message -Level Verbose -Message "Parsing $groupobject"
                    $newname = Get-RegServerGroupReverseParse $groupobject
                    $newname = "$newname\$($regservergroup.Name)"
                    Write-Message -Level Verbose -Message "Executing $($regservergroup.ScriptMove($groupobject).GetScript())"
                    $null = $parentserver.ServerConnection.ExecuteNonQuery($regservergroup.ScriptMove($groupobject).GetScript())
                    Get-DbaCmsRegServerGroup -SqlInstance $server -Group $newname
                    $parentserver.ServerConnection.Disconnect()
                } catch {
                    Stop-Function -Message "Failed to move $($regserver.Name) to $NewGroup on $($regserver.SqlInstance)" -ErrorRecord $_ -Continue
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Move-DbaRegisteredServerGroup
    }
}
tools\dbatools\functions\New-DbaAgentJob.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function New-DbaAgentJob {
    <#
    .SYNOPSIS
        New-DbaAgentJob creates a new job

    .DESCRIPTION
        New-DbaAgentJob makes is possible to create a job in the SQL Server Agent.
        It returns an array of the job(s) created

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Job
        The name of the job. The name must be unique and cannot contain the percent (%) character.

    .PARAMETER Schedule
        Schedule to attach to job. This can be more than one schedule.

    .PARAMETER ScheduleId
        Schedule ID to attach to job. This can be more than one schedule ID.

    .PARAMETER Disabled
        Sets the status of the job to disabled. By default a job is enabled.

    .PARAMETER Description
        The description of the job.

    .PARAMETER StartStepId
        The identification number of the first step to execute for the job.

    .PARAMETER Category
        The category of the job.

    .PARAMETER OwnerLogin
        The name of the login that owns the job.

    .PARAMETER EventLogLevel
        Specifies when to place an entry in the Microsoft Windows application log for this job.
        Allowed values 0, "Never", 1, "OnSuccess", 2, "OnFailure", 3, "Always"
        The text value can either be lowercase, uppercase or something in between as long as the text is correct.

    .PARAMETER EmailLevel
        Specifies when to send an e-mail upon the completion of this job.
        Allowed values 0, "Never", 1, "OnSuccess", 2, "OnFailure", 3, "Always"
        The text value can either be lowercase, uppercase or something in between as long as the text is correct.

    .PARAMETER NetsendLevel
        Specifies when to send a network message upon the completion of this job.
        Allowed values 0, "Never", 1, "OnSuccess", 2, "OnFailure", 3, "Always"
        The text value can either be lowercase, uppercase or something in between as long as the text is correct.

    .PARAMETER PageLevel
        Specifies when to send a page upon the completion of this job.
        Allowed values 0, "Never", 1, "OnSuccess", 2, "OnFailure", 3, "Always"
        The text value can either be lowercase, uppercase or something in between as long as the text is correct.

    .PARAMETER EmailOperator
        The e-mail name of the operator to whom the e-mail is sent when EmailLevel is reached.

    .PARAMETER NetsendOperator
        The name of the operator to whom the network message is sent.

    .PARAMETER PageOperator
        The name of the operator to whom a page is sent.

    .PARAMETER DeleteLevel
        Specifies when to delete the job.
        Allowed values 0, "Never", 1, "OnSuccess", 2, "OnFailure", 3, "Always"
        The text value can either be lowercase, uppercase or something in between as long as the text is correct.

    .PARAMETER Force
        The force parameter will ignore some errors in the parameters and assume defaults.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Job, JobStep
        Author: Sander Stad (@sqlstad), sqlstad.nl

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaAgentJob

    .EXAMPLE
        PS C:\> New-DbaAgentJob -SqlInstance sql1 -Job 'Job One' -Description 'Just another job'

        Creates a job with the name "Job1" and a small description

    .EXAMPLE
        PS C:\> New-DbaAgentJob -SqlInstance sql1 -Job 'Job One' -Disabled

        Creates the job but sets it to disabled

    .EXAMPLE
        PS C:\> New-DbaAgentJob -SqlInstance sql1 -Job 'Job One' -EventLogLevel OnSuccess

        Creates the job and sets the notification to write to the Windows Application event log on success

    .EXAMPLE
        PS C:\> New-DbaAgentJob -SqlInstance SSTAD-PC -Job 'Job One' -EmailLevel OnFailure -EmailOperator dba

        Creates the job and sets the notification to send an e-mail to the e-mail operator

    .EXAMPLE
        PS C:\> New-DbaAgentJob -SqlInstance sql1 -Job 'Job One' -Description 'Just another job' -Whatif

        Doesn't create the job but shows what would happen.

    .EXAMPLE
        PS C:\> New-DbaAgentJob -SqlInstance sql1, sql2, sql3 -Job 'Job One'

        Creates a job with the name "Job One" on multiple servers

    .EXAMPLE
        PS C:\> "sql1", "sql2", "sql3" | New-DbaAgentJob -Job 'Job One'

        Creates a job with the name "Job One" on multiple servers using the pipe line

    #>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Job,
        [object[]]$Schedule,
        [int[]]$ScheduleId,
        [switch]$Disabled,
        [string]$Description,
        [int]$StartStepId,
        [string]$Category,
        [string]$OwnerLogin,
        [ValidateSet(0, "Never", 1, "OnSuccess", 2, "OnFailure", 3, "Always")]
        [object]$EventLogLevel,
        [ValidateSet(0, "Never", 1, "OnSuccess", 2, "OnFailure", 3, "Always")]
        [object]$EmailLevel,
        [ValidateSet(0, "Never", 1, "OnSuccess", 2, "OnFailure", 3, "Always")]
        [Parameter()]
        [ValidateSet(0, "Never", 1, "OnSuccess", 2, "OnFailure", 3, "Always")]
        [object]$PageLevel,
        [string]$EmailOperator,
        [string]$NetsendOperator,
        [string]$PageOperator,
        [ValidateSet(0, "Never", 1, "OnSuccess", 2, "OnFailure", 3, "Always")]
        [object]$DeleteLevel,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {

        # Check of the event log level is of type string and set the integer value
        if ($EventLogLevel -notin 1, 2, 3) {
            $EventLogLevel = switch ($EventLogLevel) {
                "Never" { 0 } "OnSuccess" { 1 } "OnFailure" { 2 } "Always" { 3 }
                default { 0 }
            }
        }

        # Check of the email level is of type string and set the integer value
        if ($EmailLevel -notin 1, 2, 3) {
            $EmailLevel = switch ($EmailLevel) {
                "Never" { 0 } "OnSuccess" { 1 } "OnFailure" { 2 } "Always" { 3 }
                default { 0 }
            }
        }

        # Check of the net send level is of type string and set the integer value
        if ($NetsendLevel -notin 1, 2, 3) {
            $NetsendLevel = switch ($NetsendLevel) {
                "Never" { 0 } "OnSuccess" { 1 } "OnFailure" { 2 } "Always" { 3 }
                default { 0 }
            }
        }

        # Check of the page level is of type string and set the integer value
        if ($PageLevel -notin 1, 2, 3) {
            $PageLevel = switch ($PageLevel) {
                "Never" { 0 } "OnSuccess" { 1 } "OnFailure" { 2 } "Always" { 3 }
                default { 0 }
            }
        }

        # Check of the delete level is of type string and set the integer value
        if ($DeleteLevel -notin 1, 2, 3) {
            $DeleteLevel = switch ($DeleteLevel) {
                "Never" { 0 } "OnSuccess" { 1 } "OnFailure" { 2 } "Always" { 3 }
                default { 0 }
            }
        }

        # Check the e-mail operator name
        if (($EmailLevel -ge 1) -and (-not $EmailOperator)) {
            Stop-Function -Message "Please set the e-mail operator when the e-mail level parameter is set." -Target $sqlinstance
            return
        }

        # Check the e-mail operator name
        if (($NetsendLevel -ge 1) -and (-not $NetsendOperator)) {
            Stop-Function -Message "Please set the netsend operator when the netsend level parameter is set." -Target $sqlinstance
            return
        }

        # Check the e-mail operator name
        if (($PageLevel -ge 1) -and (-not $PageOperator)) {
            Stop-Function -Message "Please set the page operator when the page level parameter is set." -Target $sqlinstance
            return
        }
    }

    process {

        if (Test-FunctionInterrupt) { return }

        foreach ($instance in $sqlinstance) {
            # Try connecting to the instance
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            # Check if the job already exists
            if (-not $Force -and ($server.JobServer.Jobs.Name -contains $Job)) {
                Stop-Function -Message "Job $Job already exists on $instance" -Target $instance -Continue
            } elseif ($Force -and ($server.JobServer.Jobs.Name -contains $Job)) {
                Write-Message -Message "Job $Job already exists on $instance. Removing.." -Level Verbose

                if ($PSCmdlet.ShouldProcess($instance, "Removing the job $Job on $instance")) {
                    try {
                        Remove-DbaAgentJob -SqlInstance $instance -Job $Job -EnableException
                    } catch {
                        Stop-Function -Message "Couldn't remove job $Job from $instance" -Target $instance -Continue -ErrorRecord $_
                    }
                }

            }

            if ($PSCmdlet.ShouldProcess($instance, "Creating the job on $instance")) {
                # Create the job object
                try {
                    $currentjob = New-Object Microsoft.SqlServer.Management.Smo.Agent.Job($server.JobServer, $Job)
                } catch {
                    Stop-Function -Message "Something went wrong creating the job. `n" -Target $Job -Continue -ErrorRecord $_
                }

                #region job options
                # Settings the options for the job
                if ($Disabled) {
                    Write-Message -Message "Setting job to disabled" -Level Verbose
                    $currentjob.IsEnabled = $false
                } else {
                    Write-Message -Message "Setting job to enabled" -Level Verbose
                    $currentjob.IsEnabled = $true
                }

                if ($Description.Length -ge 1) {
                    Write-Message -Message "Setting job description" -Level Verbose
                    $currentjob.Description = $Description
                }

                if ($StartStepId -ge 1) {
                    Write-Message -Message "Setting job start step id" -Level Verbose
                    $currentjob.StartStepID = $StartStepId
                }

                if ($Category.Length -ge 1) {
                    # Check if the job category exists
                    if ($Category -notin $server.JobServer.JobCategories.Name) {
                        if ($Force) {
                            if ($PSCmdlet.ShouldProcess($instance, "Creating job category on $instance")) {
                                try {
                                    # Create the category
                                    New-DbaAgentJobCategory -SqlInstance $instance -Category $Category
                                } catch {
                                    Stop-Function -Message "Couldn't create job category $Category from $instance" -Target $instance -Continue -ErrorRecord $_
                                }
                            }
                        } else {
                            Stop-Function -Message "Job category $Category doesn't exist on $instance. Use -Force to create it." -Target $instance
                            return
                        }
                    } else {
                        Write-Message -Message "Setting job category" -Level Verbose
                        $currentjob.Category = $Category
                    }
                }

                if ($OwnerLogin.Length -ge 1) {
                    # Check if the login name is present on the instance
                    if ($server.Logins.Name -contains $OwnerLogin) {
                        Write-Message -Message "Setting job owner login name to $OwnerLogin" -Level Verbose
                        $currentjob.OwnerLoginName = $OwnerLogin
                    } else {
                        Stop-Function -Message "The owner $OwnerLogin does not exist on instance $instance" -Target $Job -Continue
                    }
                }

                if ($EventLogLevel -ge 0) {
                    Write-Message -Message "Setting job event log level" -Level Verbose
                    $currentjob.EventLogLevel = $EventLogLevel
                }

                if ($EmailOperator) {
                    if ($EmailLevel -ge 1) {
                        # Check if the operator name is present
                        if ($server.JobServer.Operators.Name -contains $EmailOperator) {
                            Write-Message -Message "Setting job e-mail level" -Level Verbose
                            $currentjob.EmailLevel = $EmailLevel

                            Write-Message -Message "Setting job e-mail operator" -Level Verbose
                            $currentjob.OperatorToEmail = $EmailOperator
                        } else {
                            Stop-Function -Message "The e-mail operator name $EmailOperator does not exist on instance $instance. Exiting.." -Target $Job -Continue
                        }
                    } else {
                        Stop-Function -Message "Invalid combination of e-mail operator name $EmailOperator and email level $EmailLevel. Not setting the notification." -Target $Job -Continue
                    }
                }

                if ($NetsendOperator) {
                    if ($NetsendLevel -ge 1) {
                        # Check if the operator name is present
                        if ($server.JobServer.Operators.Name -contains $NetsendOperator) {
                            Write-Message -Message "Setting job netsend level" -Level Verbose
                            $currentjob.NetSendLevel = $NetsendLevel

                            Write-Message -Message "Setting job netsend operator" -Level Verbose
                            $currentjob.OperatorToNetSend = $NetsendOperator
                        } else {
                            Stop-Function -Message "The netsend operator name $NetsendOperator does not exist on instance $instance. Exiting.." -Target $Job -Continue
                        }
                    } else {
                        Write-Message -Message "Invalid combination of netsend operator name $NetsendOperator and netsend level $NetsendLevel. Not setting the notification."
                    }
                }

                if ($PageOperator) {
                    if ($PageLevel -ge 1) {
                        # Check if the operator name is present
                        if ($server.JobServer.Operators.Name -contains $PageOperator) {
                            Write-Message -Message "Setting job pager level" -Level Verbose
                            $currentjob.PageLevel = $PageLevel

                            Write-Message -Message "Setting job pager operator" -Level Verbose
                            $currentjob.OperatorToPage = $PageOperator
                        } else {
                            Stop-Function -Message "The page operator name $PageOperator does not exist on instance $instance. Exiting.." -Target $Job -Continue
                        }
                    } else {
                        Write-Message -Message "Invalid combination of page operator name $PageOperator and page level $PageLevel. Not setting the notification." -Level Warning
                    }
                }

                if ($DeleteLevel -ge 0) {
                    Write-Message -Message "Setting job delete level" -Level Verbose
                    $currentjob.DeleteLevel = $DeleteLevel
                }
                #endregion job options

                try {
                    Write-Message -Message "Creating the job" -Level Verbose

                    # Create the job
                    $currentjob.Create()

                    Write-Message -Message "Job created with UID $($currentjob.JobID)" -Level Verbose

                    # Make sure the target is set for the job
                    Write-Message -Message "Applying the target (local) to job $Job" -Level Verbose
                    $currentjob.ApplyToTargetServer("(local)")

                    # If a schedule needs to be attached
                    if ($Schedule) {
                        Set-DbaAgentJob -SqlInstance $instance -Job $currentjob -Schedule $Schedule -SqlCredential $SqlCredential
                    }

                    if ($ScheduleId) {
                        Set-DbaAgentJob -SqlInstance $instance -Job $currentjob -ScheduleId $ScheduleId -SqlCredential $SqlCredential
                    }
                } catch {
                    Stop-Function -Message "Something went wrong creating the job" -Target $currentjob -ErrorRecord $_ -Continue
                }
            }

            # Return the job
            return $currentjob
        }
    }

    end {
        if (Test-FunctionInterrupt) { return }
        Write-Message -Message "Finished creating job(s)." -Level Verbose
    }

}
tools\dbatools\functions\New-DbaAgentJobCategory.ps1
function New-DbaAgentJobCategory {
    <#
    .SYNOPSIS
        New-DbaAgentJobCategory creates a new job category.

    .DESCRIPTION
        New-DbaAgentJobCategory makes it possible to create a job category that can be used with jobs.
        It returns an array of the job(s) created .

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Category
        The name of the category

    .PARAMETER CategoryType
        The type of category. This can be "LocalJob", "MultiServerJob" or "None".
        The default is "LocalJob" and will automatically be set when no option is chosen.

    .PARAMETER Force
        The force parameter will ignore some errors in the parameters and assume defaults.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Job, JobCategory
        Author: Sander Stad (@sqlstad), sqlstad.nl

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaAgentJobCategory

    .EXAMPLE
        PS C:\> New-DbaAgentJobCategory -SqlInstance sql1 -Category 'Category 1'

        Creates a new job category with the name 'Category 1'.

    .EXAMPLE
        PS C:\> New-DbaAgentJobCategory -SqlInstance sql1 -Category 'Category 2' -CategoryType MultiServerJob

        Creates a new job category with the name 'Category 2' and assign the category type for a multi server job.

    #>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string[]]$Category,
        [ValidateSet("LocalJob", "MultiServerJob", "None")]
        [string]$CategoryType,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        # Check the category type
        if (-not $CategoryType) {
            # Setting category type to default
            Write-Message -Message "Setting the category type to 'LocalJob'" -Level Verbose
            $CategoryType = "LocalJob"
        }
    }

    process {

        foreach ($instance in $sqlinstance) {
            # Try connecting to the instance
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            foreach ($cat in $Category) {
                # Check if the category already exists
                if ($cat -in $server.JobServer.JobCategories.Name) {
                    Stop-Function -Message "Job category $cat already exists on $instance" -Target $instance -Continue
                } else {
                    if ($PSCmdlet.ShouldProcess($instance, "Adding the job category $cat")) {
                        try {
                            $jobcategory = New-Object Microsoft.SqlServer.Management.Smo.Agent.JobCategory($server.JobServer, $cat)
                            $jobcategory.CategoryType = $CategoryType

                            $jobcategory.Create()

                            $server.JobServer.Refresh()
                        } catch {
                            Stop-Function -Message "Something went wrong creating the job category $cat on $instance" -Target $cat -Continue -ErrorRecord $_
                        }

                    } # if should process

                } # end else category exists

                # Return the job category
                Get-DbaAgentJobCategory -SqlInstance $instance -Category $cat

            } # for each category

        } # for each instance
    }

    end {
        if (Test-FunctionInterrupt) { return }
        Write-Message -Message "Finished creating job category." -Level Verbose
    }

}
tools\dbatools\functions\New-DbaAgentJobStep.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function New-DbaAgentJobStep {
    <#
    .SYNOPSIS
        New-DbaAgentJobStep creates a new job step for a job

    .DESCRIPTION
        New-DbaAgentJobStep creates a new job in the SQL Server Agent for a specific job

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Job
        The name of the job to which to add the step.

    .PARAMETER StepId
        The sequence identification number for the job step. Step identification numbers start at 1 and increment without gaps.

    .PARAMETER StepName
        The name of the step.

    .PARAMETER SubSystem
        The subsystem used by the SQL Server Agent service to execute command.
        Allowed values 'ActiveScripting','AnalysisCommand','AnalysisQuery','CmdExec','Distribution','LogReader','Merge','PowerShell','QueueReader','Snapshot','Ssis','TransactSql'
        The default is 'TransactSql'

    .PARAMETER SubSystemServer
        The subsystems AnalysisScripting, AnalysisCommand, AnalysisQuery ned the server property to be able to apply

    .PARAMETER Command
        The commands to be executed by SQLServerAgent service through subsystem.

    .PARAMETER CmdExecSuccessCode
        The value returned by a CmdExec subsystem command to indicate that command executed successfully.

    .PARAMETER OnSuccessAction
        The action to perform if the step succeeds.
        Allowed values  "QuitWithSuccess" (default), "QuitWithFailure", "GoToNextStep", "GoToStep".
        The text value van either be lowercase, uppercase or something in between as long as the text is correct.

    .PARAMETER OnSuccessStepId
        The ID of the step in this job to execute if the step succeeds and OnSuccessAction is "GoToStep".

    .PARAMETER OnFailAction
        The action to perform if the step fails.
        Allowed values  "QuitWithSuccess" (default), "QuitWithFailure", "GoToNextStep", "GoToStep".
        The text value van either be lowercase, uppercase or something in between as long as the text is correct.

    .PARAMETER OnFailStepId
        The ID of the step in this job to execute if the step fails and OnFailAction is "GoToStep".

    .PARAMETER Database
        The name of the database in which to execute a Transact-SQL step. The default is 'master'.

    .PARAMETER DatabaseUser
        The name of the user account to use when executing a Transact-SQL step.

    .PARAMETER RetryAttempts
        The number of retry attempts to use if this step fails. The default is 0.

    .PARAMETER RetryInterval
        The amount of time in minutes between retry attempts. The default is 0.

    .PARAMETER OutputFileName
        The name of the file in which the output of this step is saved.

    .PARAMETER Flag
        Sets the flag(s) for the job step.

        Flag                                    Description
        ----------------------------------------------------------------------------
        AppendAllCmdExecOutputToJobHistory      Job history, including command output, is appended to the job history file.
        AppendToJobHistory                      Job history is appended to the job history file.
        AppendToLogFile                         Job history is appended to the SQL Server log file.
        AppendToTableLog                        Job history is appended to a log table.
        LogToTableWithOverwrite                 Job history is written to a log table, overwriting previous contents.
        None                                    Job history is not appended to a file.
        ProvideStopProcessEvent                 Job processing is stopped.

    .PARAMETER ProxyName
        The name of the proxy that the job step runs as.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER Force
        The force parameter will ignore some errors in the parameters and assume defaults.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Job, JobStep
        Author: Sander Stad (@sqlstad), sqlstad.nl

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaAgentJobStep

    .EXAMPLE
        PS C:\> New-DbaAgentJobStep -SqlInstance sql1 -Job Job1 -StepName Step1

        Create a step in "Job1" with the name Step1 with the default subsystem TransactSql.

    .EXAMPLE
        PS C:\> New-DbaAgentJobStep -SqlInstance sql1 -Job Job1 -StepName Step1 -Database msdb

        Create a step in "Job1" with the name Step1 where the database will the msdb

    .EXAMPLE
        PS C:\> New-DbaAgentJobStep -SqlInstance sql1, sql2, sql3 -Job Job1 -StepName Step1 -Database msdb

        Create a step in "Job1" with the name Step1 where the database will the "msdb" for multiple servers

    .EXAMPLE
        PS C:\> New-DbaAgentJobStep -SqlInstance sql1, sql2, sql3 -Job Job1, Job2, 'Job Three' -StepName Step1 -Database msdb

        Create a step in "Job1" with the name Step1 where the database will the "msdb" for multiple servers for multiple jobs

    .EXAMPLE
        PS C:\> sql1, sql2, sql3 | New-DbaAgentJobStep -Job Job1 -StepName Step1 -Database msdb

        Create a step in "Job1" with the name Step1 where the database will the "msdb" for multiple servers using pipeline

    #>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [object[]]$Job,
        [int]$StepId,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$StepName,
        [ValidateSet('ActiveScripting', 'AnalysisCommand', 'AnalysisQuery', 'CmdExec', 'Distribution', 'LogReader', 'Merge', 'PowerShell', 'QueueReader', 'Snapshot', 'Ssis', 'TransactSql')]
        [string]$Subsystem = 'TransactSql',
        [string]$SubsystemServer,
        [string]$Command,
        [int]$CmdExecSuccessCode,
        [ValidateSet('QuitWithSuccess', 'QuitWithFailure', 'GoToNextStep', 'GoToStep')]
        [string]$OnSuccessAction = 'QuitWithSuccess',
        [int]$OnSuccessStepId = 0,
        [ValidateSet('QuitWithSuccess', 'QuitWithFailure', 'GoToNextStep', 'GoToStep')]
        [string]$OnFailAction = 'QuitWithFailure',
        [int]$OnFailStepId = 0,
        [object]$Database,
        [string]$DatabaseUser,
        [int]$RetryAttempts,
        [int]$RetryInterval,
        [string]$OutputFileName,
        [ValidateSet('AppendAllCmdExecOutputToJobHistory', 'AppendToJobHistory', 'AppendToLogFile', 'LogToTableWithOverwrite', 'None', 'ProvideStopProcessEvent')]
        [string[]]$Flag,
        [string]$ProxyName,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        # Check the parameter on success step id
        if (($OnSuccessAction -ne 'GoToStep') -and ($OnSuccessStepId -ge 1)) {
            Stop-Function -Message "Parameter OnSuccessStepId can only be used with OnSuccessAction 'GoToStep'." -Target $SqlInstance
            return
        }

        # Check the parameter on fail step id
        if (($OnFailAction -ne 'GoToStep') -and ($OnFailStepId -ge 1)) {
            Stop-Function -Message "Parameter OnFailStepId can only be used with OnFailAction 'GoToStep'." -Target $SqlInstance
            return
        }

        if ($Subsystem -in 'AnalysisScripting', 'AnalysisCommand', 'AnalysisQuery') {
            if (-not $SubsystemServer) {
                Stop-Function -Message "Please enter the server value using -SubSystemServer for subsystem $Subsystem." -Target $Subsystem
                return
            }
        }
    }

    process {

        if (Test-FunctionInterrupt) { return }

        foreach ($instance in $sqlinstance) {
            # Try connecting to the instance
            try {
                $Server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            foreach ($j in $Job) {

                # Check if the job exists
                if ($Server.JobServer.Jobs.Name -notcontains $j) {
                    Write-Message -Message "Job $j doesn't exists on $instance" -Level Warning
                } else {
                    # Create the job step object
                    try {
                        # Get the job
                        $currentjob = $Server.JobServer.Jobs[$j]

                        # Create the job step
                        $JobStep = New-Object Microsoft.SqlServer.Management.Smo.Agent.JobStep

                        # Set the job where the job steps belongs to
                        $JobStep.Parent = $currentjob
                    } catch {
                        Stop-Function -Message "Something went wrong creating the job step" -Target $instance -ErrorRecord $_ -Continue
                    }

                    #region job step options
                    # Setting the options for the job step
                    if ($StepName) {
                        # Check if the step already exists
                        if ($Server.JobServer.Jobs[$j].JobSteps.Name -notcontains $StepName) {
                            $JobStep.Name = $StepName
                        } elseif (($Server.JobServer.Jobs[$j].JobSteps.Name -contains $StepName) -and $Force) {
                            Write-Message -Message "Step $StepName already exists for job. Force is used. Removing existing step" -Level Verbose

                            # Remove the job step based on the name
                            Remove-DbaAgentJobStep -SqlInstance $instance -Job $currentjob -StepName $StepName -SqlCredential $SqlCredential

                            # Set the name job step object
                            $JobStep.Name = $StepName
                        } else {
                            Stop-Function -Message "The step name $StepName already exists for job $j" -Target $instance -Continue
                        }
                    }

                    # If the step id need to be set
                    if ($StepId) {
                        # Check if the used step id is already in place
                        if ($Job.JobSteps.ID -notcontains $StepId) {
                            Write-Message -Message "Setting job step step id to $StepId" -Level Verbose
                            $JobStep.ID = $StepId
                        } elseif (($Job.JobSteps.ID -contains $StepId) -and $Force) {
                            Write-Message -Message "Step ID $StepId already exists for job. Force is used. Removing existing step" -Level Verbose

                            # Remove the existing job step
                            $StepName = ($Server.JobServer.Jobs[$j].JobSteps | Where-Object {$_.ID -eq 1}).Name
                            Remove-DbaAgentJobStep -SqlInstance $instance -Job $currentjob -StepName $StepName -SqlCredential $SqlCredential

                            # Set the ID job step object
                            $JobStep.ID = $StepId
                        } else {
                            Stop-Function -Message "The step id $StepId already exists for job $j" -Target $instance -Continue
                        }
                    } else {
                        # Get the job step count
                        $JobStep.ID = $Job.JobSteps.Count + 1
                    }

                    if ($Subsystem) {
                        Write-Message -Message "Setting job step subsystem to $Subsystem" -Level Verbose
                        $JobStep.Subsystem = $Subsystem
                    }

                    if ($SubsystemServer) {
                        Write-Message -Message "Setting job step subsystem server to $SubsystemServer" -Level Verbose
                        $JobStep.Server = $SubsystemServer
                    }

                    if ($Command) {
                        Write-Message -Message "Setting job step command to $Command" -Level Verbose
                        $JobStep.Command = $Command
                    }

                    if ($CmdExecSuccessCode) {
                        Write-Message -Message "Setting job step command exec success code to $CmdExecSuccessCode" -Level Verbose
                        $JobStep.CommandExecutionSuccessCode = $CmdExecSuccessCode
                    }

                    if ($OnSuccessAction) {
                        Write-Message -Message "Setting job step success action to $OnSuccessAction" -Level Verbose
                        $JobStep.OnSuccessAction = $OnSuccessAction
                    }

                    if ($OnSuccessStepId) {
                        Write-Message -Message "Setting job step success step id to $OnSuccessStepId" -Level Verbose
                        $JobStep.OnSuccessStep = $OnSuccessStepId
                    }

                    if ($OnFailAction) {
                        Write-Message -Message "Setting job step fail action to $OnFailAction" -Level Verbose
                        $JobStep.OnFailAction = $OnFailAction
                    }

                    if ($OnFailStepId) {
                        Write-Message -Message "Setting job step fail step id to $OnFailStepId" -Level Verbose
                        $JobStep.OnFailStep = $OnFailStepId
                    }

                    if ($Database) {
                        # Check if the database is present on the server
                        if ($Server.Databases.Name -contains $Database) {
                            Write-Message -Message "Setting job step database name to $Database" -Level Verbose
                            $JobStep.DatabaseName = $Database
                        } else {
                            Stop-Function -Message "The database is not present on instance $instance." -Target $instance -Continue
                        }
                    }

                    if ($DatabaseUser -and $DatabaseName) {
                        # Check if the username is present in the database
                        if ($Server.Databases[$DatabaseName].Users.Name -contains $DatabaseUser) {

                            Write-Message -Message "Setting job step database username to $DatabaseUser" -Level Verbose
                            $JobStep.DatabaseUserName = $DatabaseUser
                        } else {
                            Stop-Function -Message "The database user is not present in the database $DatabaseName on instance $instance." -Target $instance -Continue
                        }
                    }

                    if ($RetryAttempts) {
                        Write-Message -Message "Setting job step retry attempts to $RetryAttempts" -Level Verbose
                        $JobStep.RetryAttempts = $RetryAttempts
                    }

                    if ($RetryInterval) {
                        Write-Message -Message "Setting job step retry interval to $RetryInterval" -Level Verbose
                        $JobStep.RetryInterval = $RetryInterval
                    }

                    if ($OutputFileName) {
                        Write-Message -Message "Setting job step output file name to $OutputFileName" -Level Verbose
                        $JobStep.OutputFileName = $OutputFileName
                    }

                    if ($ProxyName) {
                        # Check if the proxy exists
                        if ($Server.JobServer.ProxyAccounts.Name -contains $ProxyName) {
                            Write-Message -Message "Setting job step proxy name to $ProxyName" -Level Verbose
                            $JobStep.ProxyName = $ProxyName
                        } else {
                            Stop-Function -Message "The proxy name $ProxyName doesn't exist on instance $instance." -Target $instance -Continue
                        }
                    }

                    if ($Flag.Count -ge 1) {
                        Write-Message -Message "Setting job step flag(s) to $($Flags -join ',')" -Level Verbose
                        $JobStep.JobStepFlags = $Flag
                    }
                    #endregion job step options

                    # Execute
                    if ($PSCmdlet.ShouldProcess($instance, "Creating the job step $StepName")) {
                        try {
                            Write-Message -Message "Creating the job step" -Level Verbose

                            # Create the job step
                            $JobStep.Create()
                            $currentjob.Alter()
                        } catch {
                            Stop-Function -Message "Something went wrong creating the job step" -Target $instance -ErrorRecord $_ -Continue
                        }
                    }

                    # Return the job step
                    $JobStep
                }
            } # foreach object job
        } # foreach object instance
    } # process

    end {
        if (Test-FunctionInterrupt) { return }
        Write-Message -Message "Finished creating job step(s)" -Level Verbose
    }
}
tools\dbatools\functions\New-DbaAgentProxy.ps1
function New-DbaAgentProxy {
    <#
    .SYNOPSIS
        Adds one or more proxies to SQL Server Agent

    .DESCRIPTION
        Adds one or more proxies to SQL Server Agent

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Name
        The name of the proxy or proxies you want to create

    .PARAMETER ProxyCredential
        The associated SQL Server Credential. The credential must be created prior to creating the Proxy.

    .PARAMETER SubSystem
        The associated subsystem or subsystems. Defaults to CmdExec.

        Valid options include:
        ActiveScripting
        AnalysisCommand
        AnalysisQuery
        CmdExec
        Distribution
        LogReader
        Merge
        PowerShell
        QueueReader
        Snapshot
        Ssis
        TransactSql

    .PARAMETER Description
        A description of the proxy

    .PARAMETER Login
        The SQL Server login or logins (known as proxy principals) to assign to the proxy

    .PARAMETER ServerRole
        The SQL Server role or roles (known as proxy principals) to assign to the proxy

    .PARAMETER MsdbRole
        The msdb role or roles (known as proxy principals) to assign to the proxy

    .PARAMETER Disabled
        Create the proxy as disabled

    .PARAMETER Force
        Drop and recreate the proxy if it already exists

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Proxy
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaAgentProxy

    .EXAMPLE
        PS C:\> New-DbaAgentProxy -SqlInstance sql2016 -Name STIG -ProxyCredential 'PowerShell Proxy'

        Creates an Agent Proxy on sql2016 with the name STIG with the 'PowerShell Proxy' credential.
        The proxy is automatically added to the CmdExec subsystem.

    .EXAMPLE
        PS C:\> New-DbaAgentProxy -SqlInstance localhost\sql2016 -Name STIG -ProxyCredential 'PowerShell Proxy' -Description "Used for auditing purposes" -Login ad\sqlstig -SubSystem CmdExec, PowerShell -ServerRole securtyadmin -MsdbRole ServerGroupAdministratorRole

        Creates an Agent Proxy on sql2016 with the name STIG with the 'PowerShell Proxy' credential and the following principals:

        Login: ad\sqlstig
        ServerRole: securtyadmin
        MsdbRole: ServerGroupAdministratorRole

        By default, only sysadmins have access to create job steps with proxies. This will allow 3 additional principals access:
        The proxy is then added to the CmdExec and PowerShell subsystems

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "", Justification = "For Parameter ProxyCredential")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(Mandatory)]
        [string[]]$Name,
        [parameter(Mandatory)]
        [string[]]$ProxyCredential,
        [ValidateSet("ActiveScripting", "AnalysisCommand", "AnalysisQuery", "CmdExec", "Distribution", "LogReader", "Merge", "PowerShell", "QueueReader", "Snapshot", "Ssis", "TransactSql")]
        [string[]]$SubSystem = "CmdExec",
        [string]$Description,
        [string[]]$Login,
        [string[]]$ServerRole,
        [string[]]$MsdbRole,
        [switch]$Disabled,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            try {
                $jobServer = $server.JobServer
            } catch {
                Stop-Function -Message "Failure. Is SQL Agent started?" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            foreach ($proxyname in $name) {

                if ($jobServer.ProxyAccounts[$proxyName]) {
                    if ($force) {
                        if ($Pscmdlet.ShouldProcess($instance, "Dropping $proxyname")) {
                            $jobServer.ProxyAccounts[$proxyName].Drop()
                            $jobServer.ProxyAccounts.Refresh()
                        }
                    } else {
                        Write-Message -Level Warning -Message "Proxy account $proxy already exists on $instance. Use -Force to drop and recreate."
                        continue
                    }
                }

                if (-not $server.Credentials[$ProxyCredential]) {
                    Write-Message -Level Warning -Message "Credential '$ProxyCredential' does not exist on $instance"
                    continue
                }

                if ($Pscmdlet.ShouldProcess($instance, "Adding $proxyname with the $ProxyCredential credential")) {
                    # the new-object is stubborn and $true/$false has to be forced in
                    switch (Test-Bound -ParameterName Disabled) {
                        $false {
                            $proxy = New-Object Microsoft.SqlServer.Management.Smo.Agent.ProxyAccount -ArgumentList $jobServer, $ProxyName, $ProxyCredential, $true, $Description
                        }
                        $true {
                            $proxy = New-Object Microsoft.SqlServer.Management.Smo.Agent.ProxyAccount -ArgumentList $jobServer, $ProxyName, $ProxyCredential, $false, $Description
                        }
                    }

                    try {
                        $proxy.Create()
                    } catch {
                        Stop-Function -Message "Could not create proxy account" -ErrorRecord $_ -Target $instance -Continue
                    }
                }

                foreach ($loginname in $login) {
                    if ($server.Logins[$loginname]) {
                        if ($Pscmdlet.ShouldProcess($instance, "Adding login $loginname to proxy")) {
                            $proxy.AddLogin($loginname)
                        }
                    } else {
                        Write-Message -Level Warning -Message "Login '$loginname' does not exist on $instance"
                    }
                }

                foreach ($role in $ServerRole) {
                    if ($server.Roles[$role]) {
                        if ($Pscmdlet.ShouldProcess($instance, "Adding server role $role to proxy")) {
                            $proxy.AddServerRole($role)
                        }
                    } else {
                        Write-Message -Level Warning -Message "Server Role '$role' does not exist on $instance"
                    }
                }

                foreach ($role in $MsdbRole) {
                    if ($server.Databases['msdb'].Roles[$role]) {
                        if ($Pscmdlet.ShouldProcess($instance, "Adding msdb role $role to proxy")) {
                            $proxy.AddMsdbRole($role)
                        }
                    } else {
                        Write-Message -Level Warning -Message "msdb role '$role' does not exist on $instance"
                    }
                }

                foreach ($system in $SubSystem) {
                    if ($Pscmdlet.ShouldProcess($instance, "Adding subsystem $system to proxy")) {
                        $proxy.AddSubSystem($system)
                    }
                }

                if ($Pscmdlet.ShouldProcess("console", "Outputting Proxy object")) {
                    $proxy.Alter()
                    $proxy.Refresh()
                    Add-Member -Force -InputObject $proxy -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                    Add-Member -Force -InputObject $proxy -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                    Add-Member -Force -InputObject $proxy -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                    Add-Member -Force -InputObject $proxy -MemberType NoteProperty -Name Logins -value $proxy.EnumLogins()
                    Add-Member -Force -InputObject $proxy -MemberType NoteProperty -Name ServerRoles -value $proxy.EnumServerRoles()
                    Add-Member -Force -InputObject $proxy -MemberType NoteProperty -Name MsdbRoles -value $proxy.EnumMsdbRoles()
                    Add-Member -Force -InputObject $proxy -MemberType NoteProperty -Name Subsystems -value $proxy.EnumSubSystems()

                    Select-DefaultView -InputObject $proxy -Property ComputerName, InstanceName, SqlInstance, ID, Name, CredentialName, CredentialIdentity, Description, Logins, ServerRoles, MsdbRoles, SubSystems, IsEnabled
                }
            }
        }
    }
}
tools\dbatools\functions\New-DbaAgentSchedule.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function New-DbaAgentSchedule {
    <#
    .SYNOPSIS
        New-DbaAgentSchedule creates a new schedule in the msdb database.

    .DESCRIPTION
        New-DbaAgentSchedule will help create a new schedule for a job.
        If the job parameter is not supplied the schedule will not be attached to a job.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Job
        The name of the job that has the schedule.

    .PARAMETER Schedule
        The name of the schedule.

    .PARAMETER Disabled
        Set the schedule to disabled. Default is enabled

    .PARAMETER FrequencyType
        A value indicating when a job is to be executed.

        Allowed values: Once, Daily, Weekly, Monthly, MonthlyRelative, AgentStart or IdleComputer

        If force is used the default will be "Once".

    .PARAMETER FrequencyInterval
        The days that a job is executed

        Allowed values: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Weekdays, Weekend or EveryDay.
        The other allowed values are the numbers 1 to 31 for each day of the month.

        If "Weekdays", "Weekend" or "EveryDay" is used it over writes any other value that has been passed before.

        If force is used the default will be 1.

    .PARAMETER FrequencySubdayType
        Specifies the units for the subday FrequencyInterval.

        Allowed values: Time, Seconds, Minutes, or Hours

    .PARAMETER FrequencySubdayInterval
        The number of subday type periods to occur between each execution of a job.

    .PARAMETER FrequencyRelativeInterval
        A job's occurrence of FrequencyInterval in each month, if FrequencyInterval is 32 (monthlyrelative).

        Allowed values: First, Second, Third, Fourth or Last

    .PARAMETER FrequencyRecurrenceFactor
        The number of weeks or months between the scheduled execution of a job.

        FrequencyRecurrenceFactor is used only if FrequencyType is "Weekly", "Monthly" or "MonthlyRelative".

    .PARAMETER StartDate
        The date on which execution of a job can begin.

        If force is used the start date will be the current day

    .PARAMETER EndDate
        The date on which execution of a job can stop.

        If force is used the end date will be '9999-12-31'

    .PARAMETER StartTime
        The time on any day to begin execution of a job. Format HHMMSS / 24 hour clock.
        Example: '010000' for 01:00:00 AM.
        Example: '140000' for 02:00:00 PM.

        If force is used the start time will be '00:00:00'

    .PARAMETER EndTime
        The time on any day to end execution of a job. Format HHMMSS / 24 hour clock.
        Example: '010000' for 01:00:00 AM.
        Example: '140000' for 02:00:00 PM.

        If force is used the start time will be '23:59:59'

    .PARAMETER Owner
        The name of the server principal that owns the schedule. If no value is given the schedule is owned by the creator.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER Force
        The force parameter will ignore some errors in the parameters and assume defaults.
        It will also remove the any present schedules with the same name for the specific job.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Job, JobStep
        Author: Sander Stad (@sqlstad), sqlstad.nl

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaAgentSchedule

    .EXAMPLE
        PS C:\> New-DbaAgentSchedule -SqlInstance localhost\SQL2016 -Schedule daily -FrequencyType Daily -FrequencyInterval Everyday -Force

        Creates a schedule with a daily frequency every day. It assumes default values for the start date, start time, end date and end time due to -Force.

    .EXAMPLE
        PS C:\> New-DbaAgentSchedule -SqlInstance sstad-pc -Schedule MonthlyTest -FrequencyType Monthly -FrequencyInterval 10 -FrequencyRecurrenceFactor 1 -Force

        Create a schedule with a monhtly frequency occuring every 10th of the month. It assumes default values for the start date, start time, end date and end time due to -Force.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseOutputTypeCorrectly", "", Justification = "PSSA Rule Ignored by BOH")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [System.Management.Automation.PSCredential]
        $SqlCredential,
        [object[]]$Job,
        [object]$Schedule,
        [switch]$Disabled,
        [ValidateSet('Once', 'Daily', 'Weekly', 'Monthly', 'MonthlyRelative', 'AgentStart', 'IdleComputer')]
        [object]$FrequencyType,
        [ValidateSet('EveryDay', 'Weekdays', 'Weekend', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 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)]
        [object[]]$FrequencyInterval,
        [ValidateSet('Time', 'Seconds', 'Minutes', 'Hours')]
        [object]$FrequencySubdayType,
        [int]$FrequencySubdayInterval,
        [ValidateSet('Unused', 'First', 'Second', 'Third', 'Fourth', 'Last')]
        [object]$FrequencyRelativeInterval,
        [int]$FrequencyRecurrenceFactor,
        [string]$StartDate,
        [string]$EndDate,
        [string]$StartTime,
        [string]$EndTime,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        # if a Schedule is not provided there is no much point
        if (!$Schedule) {
            Stop-Function -Message "A schedule was not provided! Please provide a schedule name."
            return
        }

        [int]$Interval = 0

        # Translate FrequencyType value from string to the integer value
        if (!$FrequencyType -or $FrequencyType) {
            [int]$FrequencyType =
            switch ($FrequencyType) {
                "Once" { 1 }
                "Daily" { 4 }
                "Weekly" { 8 }
                "Monthly" { 16 }
                "MonthlyRelative" { 32 }
                "AgentStart" { 64 }
                "IdleComputer" { 128 }
                default { 1 }
            }
        }

        # Translate FrequencySubdayType value from string to the integer value
        if (!$FrequencySubdayType -or $FrequencySubdayType) {
            [int]$FrequencySubdayType =
            switch ($FrequencySubdayType) {
                "Time" { 1 }
                "Seconds" { 2 }
                "Minutes" { 4 }
                "Hours" { 8 }
                default { 1 }
            }
        }

        # Check of the relative FrequencyInterval value is of type string and set the integer value
        [int]$FrequencyRelativeInterval =
        switch ($FrequencyRelativeInterval) {
            "First" { 1 }
            "Second" { 2 }
            "Third" { 4 }
            "Fourth" { 8 }
            "Last" { 16 }
            "Unused" { 0 }
            default {0}
        }

        # Check if the interval is valid
        if (($FrequencyType -in 4, "Daily") -and (($FrequencyInterval -lt 1 -or $FrequencyInterval -ge 365) -and -not $FrequencyInterval -eq "EveryDay")) {
            Stop-Function -Message "The frequency interval $FrequencyInterval requires a frequency interval to be between 1 and 365." -Target $SqlInstance
            return
        }

        # Check if the recurrence factor is set for weekly or monthly interval
        if (($FrequencyType -in (16, 8)) -and $FrequencyRecurrenceFactor -lt 1) {
            if ($Force) {
                $FrequencyRecurrenceFactor = 1
                Write-Message -Message "Recurrence factor not set for weekly or monthly interval. Setting it to $FrequencyRecurrenceFactor." -Level Verbose
            } else {
                Stop-Function -Message "The recurrence factor $FrequencyRecurrenceFactor (parameter FrequencyRecurrenceFactor) needs to be at least one when using a weekly or monthly interval." -Target $SqlInstance
                return
            }
        }

        # Check the subday interval
        if (($FrequencySubdayType -in 2, "Seconds", 4, "Minutes") -and (-not ($FrequencySubdayInterval -ge 1 -or $FrequencySubdayInterval -le 59))) {
            Stop-Function -Message "Subday interval $FrequencySubdayInterval must be between 1 and 59 when subday type is 'Seconds' or 'Minutes'" -Target $SqlInstance
            return
        } elseif (($FrequencySubdayType -eq 8, "Hours") -and (-not ($FrequencySubdayInterval -ge 1 -and $FrequencySubdayInterval -le 23))) {
            Stop-Function -Message "Subday interval $FrequencySubdayInterval must be between 1 and 23 when subday type is 'Hours'" -Target $SqlInstance
            return
        }

        # If the FrequencyInterval is set for the daily FrequencyType
        if ($FrequencyType -in 4, 'Daily') {
            # Create the interval to hold the value(s)
            [int]$Interval = 0

            # Create the interval to hold the value(s)
            switch ($FrequencyInterval) {
                "EveryDay" { $Interval = 1}
                default {$Interval = 1 }
            }

        }

        # If the FrequencyInterval is set for the weekly FrequencyType
        if ($FrequencyType -in 8, 'Weekly') {
            # Create the interval to hold the value(s)
            [int]$Interval = 0

            # Loop through the array
            foreach ($Item in $FrequencyInterval) {

                switch ($Item) {
                    "Sunday" { $Interval += 1 }
                    "Monday" { $Interval += 2 }
                    "Tuesday" { $Interval += 4 }
                    "Wednesday" { $Interval += 8 }
                    "Thursday" { $Interval += 16 }
                    "Friday" { $Interval += 32 }
                    "Saturday" { $Interval += 64 }
                    "Weekdays" { $Interval = 62 }
                    "Weekend" { $Interval = 65 }
                    "EveryDay" {$Interval = 127 }
                    1 { $Interval += 1 }
                    2 { $Interval += 2 }
                    4 { $Interval += 4 }
                    8 { $Interval += 8 }
                    16 { $Interval += 16 }
                    32 { $Interval += 32 }
                    64 { $Interval += 64 }
                    62 { $Interval = 62 }
                    65 { $Interval = 65 }
                    127 {$Interval = 127 }
                    default { $Interval = 0 }
                }
            }
        }

        # If the FrequencyInterval is set for the monthly FrequencyInterval
        if ($FrequencyType -in 16, 'Monthly') {
            # Create the interval to hold the value(s)
            [int]$Interval = 0

            # Loop through the array
            foreach ($Item in $FrequencyInterval) {
                $FrequencyInterval
                switch ($Item) {
                    {[int]$_ -ge 1 -and [int]$_ -le 31} { $Interval = [int]$Item }
                }
            }


        }

        # If the FrequencyInterval is set for the relative monthly FrequencyInterval
        if ($FrequencyType -eq 32) {
            # Create the interval to hold the value(s)
            [int]$Interval = 0

            # Loop through the array
            foreach ($Item in $FrequencyInterval) {
                switch ($Item) {
                    "Sunday" { $Interval += 1 }
                    "Monday" { $Interval += 2 }
                    "Tuesday" { $Interval += 3 }
                    "Wednesday" { $Interval += 4 }
                    "Thursday" { $Interval += 5 }
                    "Friday" { $Interval += 6 }
                    "Saturday" { $Interval += 7 }
                    "Day" { $Interval += 8 }
                    "Weekday" { $Interval += 9 }
                    "WeekendDay" { $Interval += 10 }
                    1 { $Interval += 1 }
                    2 { $Interval += 2 }
                    3 { $Interval += 3 }
                    4 { $Interval += 4 }
                    5 { $Interval += 5 }
                    6 { $Interval += 6 }
                    7 { $Interval += 7 }
                    8 { $Interval += 8 }
                    9 { $Interval += 9 }
                    10 { $Interval += 10 }
                }
            }
        }

        # Check if the interval is valid for the frequency
        if ($FrequencyType -eq 0) {
            if ($Force) {
                Write-Message -Message "Parameter FrequencyType must be set to at least [Once]. Setting it to 'Once'." -Level Warning
                $FrequencyType = 1
            } else {
                Stop-Function -Message "Parameter FrequencyType must be set to at least [Once]" -Target $SqlInstance
                return
            }
        }

        # Check if the interval is valid for the frequency
        if (($FrequencyType -in 4, 8, 32) -and ($Interval -lt 1)) {
            if ($Force) {
                Write-Message -Message "Parameter FrequencyInterval must be provided for a recurring schedule. Setting it to first day of the week." -Level Warning
                $Interval = 1
            } else {
                Stop-Function -Message "Parameter FrequencyInterval must be provided for a recurring schedule." -Target $SqlInstance
                return
            }
        }

        # Setup the regex
        $RegexDate = '(?<!\d)(?:(?:(?:1[6-9]|[2-9]\d)?\d{2})(?:(?:(?:0[13578]|1[02])31)|(?:(?:0[1,3-9]|1[0-2])(?:29|30)))|(?:(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))0229)|(?:(?:1[6-9]|[2-9]\d)?\d{2})(?:(?:0?[1-9])|(?:1[0-2]))(?:0?[1-9]|1\d|2[0-8]))(?!\d)'
        $RegexTime = '^(?:(?:([01]?\d|2[0-3]))?([0-5]?\d))?([0-5]?\d)$'

        # Check the start date
        if (-not $StartDate -and $Force) {
            $StartDate = Get-Date -Format 'yyyyMMdd'
            Write-Message -Message "Start date was not set. Force is being used. Setting it to $StartDate" -Level Verbose
        } elseif (-not $StartDate) {
            Stop-Function -Message "Please enter a start date or use -Force to use defaults." -Target $SqlInstance
            return
        } elseif ($StartDate -notmatch $RegexDate) {
            Stop-Function -Message "Start date $StartDate needs to be a valid date with format yyyyMMdd" -Target $SqlInstance
            return
        }

        # Check the end date
        if (-not $EndDate -and $Force) {
            $EndDate = '99991231'
            Write-Message -Message "End date was not set. Force is being used. Setting it to $EndDate" -Level Verbose
        } elseif (-not $EndDate) {
            Stop-Function -Message "Please enter an end date or use -Force to use defaults." -Target $SqlInstance
            return
        }

        elseif ($EndDate -notmatch $RegexDate) {
            Stop-Function -Message "End date $EndDate needs to be a valid date with format yyyyMMdd" -Target $SqlInstance
            return
        } elseif ($EndDate -lt $StartDate) {
            Stop-Function -Message "End date $EndDate cannot be before start date $StartDate" -Target $SqlInstance
            return
        }

        # Check the start time
        if (-not $StartTime -and $Force) {
            $StartTime = '000000'
            Write-Message -Message "Start time was not set. Force is being used. Setting it to $StartTime" -Level Verbose
        } elseif (-not $StartTime) {
            Stop-Function -Message "Please enter a start time or use -Force to use defaults." -Target $SqlInstance
            return
        } elseif ($StartTime -notmatch $RegexTime) {
            Stop-Function -Message "Start time $StartTime needs to match between '000000' and '235959'" -Target $SqlInstance
            return
        }

        # Check the end time
        if (-not $EndTime -and $Force) {
            $EndTime = '235959'
            Write-Message -Message "End time was not set. Force is being used. Setting it to $EndTime" -Level Verbose
        } elseif (-not $EndTime) {
            Stop-Function -Message "Please enter an end time or use -Force to use defaults." -Target $SqlInstance
            return
        } elseif ($EndTime -notmatch $RegexTime) {
            Stop-Function -Message "End time $EndTime needs to match between '000000' and '235959'" -Target $SqlInstance
            return
        }

        #Format dates and times
        if ($StartDate) {
            $StartDate = $StartDate.Insert(6, '-').Insert(4, '-')
        }
        if ($EndDate) {
            $EndDate = $EndDate.Insert(6, '-').Insert(4, '-')
        }
        if ($StartTime) {
            $StartTime = $StartTime.Insert(4, ':').Insert(2, ':')
        }
        if ($EndTime) {
            $EndTime = $EndTime.Insert(4, ':').Insert(2, ':')
        }
    }

    process {
        if (Test-FunctionInterrupt) { return }

        foreach ($instance in $sqlinstance) {
            # Try connecting to the instance
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            # Check if the jobs parameter is set
            if ($Job) {
                # Loop through each of the jobs
                foreach ($j in $Job) {

                    # Check if the job exists
                    if ($Server.JobServer.Jobs.Name -notcontains $j) {
                        Write-Message -Message "Job $j doesn't exists on $instance" -Level Warning
                    } else {
                        # Create the job schedule object
                        try {
                            # Get the job
                            $smoJob = $Server.JobServer.Jobs[$j]

                            # Check if schedule already exists with the same name
                            if ($Server.JobServer.JobSchedules.Name -contains $Schedule) {
                                # Check if force is set which will remove the other schedule
                                if ($Force) {
                                    if ($PSCmdlet.ShouldProcess($instance, "Removing the schedule $Schedule on $instance")) {
                                        # Removing schedule
                                        Remove-DbaAgentSchedule -SqlInstance $instance -SqlCredential $SqlCredential -Schedule $Schedule -Force:$Force
                                    }
                                } else {
                                    Stop-Function -Message "Schedule $Schedule already exists for job $j on instance $instance" -Target $instance -ErrorRecord $_ -Continue
                                }
                            }

                            # Create the job schedule
                            $JobSchedule = New-Object Microsoft.SqlServer.Management.Smo.Agent.JobSchedule($smoJob, $Schedule)

                        } catch {
                            Stop-Function -Message "Something went wrong creating the job schedule $Schedule for job $j." -Target $instance -ErrorRecord $_ -Continue
                        }

                        #region job schedule options
                        if ($Disabled) {
                            Write-Message -Message "Setting job schedule to disabled" -Level Verbose
                            $JobSchedule.IsEnabled = $false
                        } else {
                            Write-Message -Message "Setting job schedule to enabled" -Level Verbose
                            $JobSchedule.IsEnabled = $true
                        }

                        if ($Interval -ge 0) {
                            Write-Message -Message "Setting job schedule frequency interval to $Interval" -Level Verbose
                            $JobSchedule.FrequencyInterval = $Interval
                        }

                        if ($FrequencyType -ge 1) {
                            Write-Message -Message "Setting job schedule frequency to $FrequencyType" -Level Verbose
                            $JobSchedule.FrequencyTypes = $FrequencyType
                        }

                        if ($FrequencySubdayType -ge 1) {
                            Write-Message -Message "Setting job schedule frequency subday type to $FrequencySubdayType" -Level Verbose
                            $JobSchedule.FrequencySubDayTypes = $FrequencySubdayType
                        }

                        if ($FrequencySubdayInterval -ge 1) {
                            Write-Message -Message "Setting job schedule frequency subday interval to $FrequencySubdayInterval" -Level Verbose
                            $JobSchedule.FrequencySubDayInterval = $FrequencySubdayInterval
                        }

                        if (($FrequencyRelativeInterval -ge 1) -and ($FrequencyType -eq 32)) {
                            Write-Message -Message "Setting job schedule frequency relative interval to $FrequencyRelativeInterval" -Level Verbose
                            $JobSchedule.FrequencyRelativeIntervals = $FrequencyRelativeInterval
                        }

                        if (($FrequencyRecurrenceFactor -ge 1) -and ($FrequencyType -in 8, 16, 32)) {
                            Write-Message -Message "Setting job schedule frequency recurrence factor to $FrequencyRecurrenceFactor" -Level Verbose
                            $JobSchedule.FrequencyRecurrenceFactor = $FrequencyRecurrenceFactor
                        }

                        if ($StartDate) {
                            Write-Message -Message "Setting job schedule start date to $StartDate" -Level Verbose
                            $JobSchedule.ActiveStartDate = $StartDate
                        }

                        if ($EndDate) {
                            Write-Message -Message "Setting job schedule end date to $EndDate" -Level Verbose
                            $JobSchedule.ActiveEndDate = $EndDate
                        }

                        if ($StartTime) {
                            Write-Message -Message "Setting job schedule start time to $StartTime" -Level Verbose
                            $JobSchedule.ActiveStartTimeOfDay = $StartTime
                        }

                        if ($EndTime) {
                            Write-Message -Message "Setting job schedule end time to $EndTime" -Level Verbose
                            $JobSchedule.ActiveEndTimeOfDay = $EndTime
                        }
                        #endregion job schedule options

                        # Create the schedule
                        if ($PSCmdlet.ShouldProcess($SqlInstance, "Adding the schedule $Schedule to job $j on $instance")) {
                            try {
                                Write-Message -Message "Adding the schedule $Schedule to job $j" -Level Verbose
                                #$JobSchedule
                                $JobSchedule.Create()

                                Write-Message -Message "Job schedule created with UID $($JobSchedule.ScheduleUid)" -Level Verbose
                            } catch {
                                Stop-Function -Message "Something went wrong adding the schedule" -Target $instance -ErrorRecord $_ -Continue

                            }

                            # Output the job schedule
                            return $JobSchedule
                        }
                    }
                } # foreach object job
            } # end if job
            else {
                # Create the schedule
                $JobSchedule = New-Object Microsoft.SqlServer.Management.Smo.Agent.JobSchedule($Server.JobServer, $Schedule)

                #region job schedule options
                if ($Disabled) {
                    Write-Message -Message "Setting job schedule to disabled" -Level Verbose
                    $JobSchedule.IsEnabled = $false
                } else {
                    Write-Message -Message "Setting job schedule to enabled" -Level Verbose
                    $JobSchedule.IsEnabled = $true
                }

                if ($Interval -ge 1) {
                    Write-Message -Message "Setting job schedule frequency interval to $Interval" -Level Verbose
                    $JobSchedule.FrequencyInterval = $Interval
                }

                if ($FrequencyType -ge 1) {
                    Write-Message -Message "Setting job schedule frequency to $FrequencyType" -Level Verbose
                    $JobSchedule.FrequencyTypes = $FrequencyType
                }

                if ($FrequencySubdayType -ge 1) {
                    Write-Message -Message "Setting job schedule frequency subday type to $FrequencySubdayType" -Level Verbose
                    $JobSchedule.FrequencySubDayTypes = $FrequencySubdayType
                }

                if ($FrequencySubdayInterval -ge 1) {
                    Write-Message -Message "Setting job schedule frequency subday interval to $FrequencySubdayInterval" -Level Verbose
                    $JobSchedule.FrequencySubDayInterval = $FrequencySubdayInterval
                }

                if (($FrequencyRelativeInterval -ge 1) -and ($FrequencyType -eq 32)) {
                    Write-Message -Message "Setting job schedule frequency relative interval to $FrequencyRelativeInterval" -Level Verbose
                    $JobSchedule.FrequencyRelativeIntervals = $FrequencyRelativeInterval
                }

                if (($FrequencyRecurrenceFactor -ge 1) -and ($FrequencyType -in 8, 16, 32)) {
                    Write-Message -Message "Setting job schedule frequency recurrence factor to $FrequencyRecurrenceFactor" -Level Verbose
                    $JobSchedule.FrequencyRecurrenceFactor = $FrequencyRecurrenceFactor
                }

                if ($StartDate) {
                    Write-Message -Message "Setting job schedule start date to $StartDate" -Level Verbose
                    $JobSchedule.ActiveStartDate = $StartDate
                }

                if ($EndDate) {
                    Write-Message -Message "Setting job schedule end date to $EndDate" -Level Verbose
                    $JobSchedule.ActiveEndDate = $EndDate
                }

                if ($StartTime) {
                    Write-Message -Message "Setting job schedule start time to $StartTime" -Level Verbose
                    $JobSchedule.ActiveStartTimeOfDay = $StartTime
                }

                if ($EndTime) {
                    Write-Message -Message "Setting job schedule end time to $EndTime" -Level Verbose
                    $JobSchedule.ActiveEndTimeOfDay = $EndTime
                }

                # Create the schedule
                if ($PSCmdlet.ShouldProcess($SqlInstance, "Adding the schedule $schedule on $instance")) {
                    try {
                        Write-Message -Message "Adding the schedule $JobSchedule on instance $instance" -Level Verbose

                        $JobSchedule.Create()

                        Write-Message -Message "Job schedule created with UID $($JobSchedule.ScheduleUid)" -Level Verbose
                    } catch {
                        Stop-Function -Message "Something went wrong adding the schedule." -Target $instance -ErrorRecord $_ -Continue
                    }

                    # Output the job schedule
                    return $JobSchedule
                }
            }
        } # foreach object instance
    } #process

    end {
        if (Test-FunctionInterrupt) { return }
        Write-Message -Message "Finished creating job schedule(s)." -Level Verbose
    }
}
tools\dbatools\functions\New-DbaAvailabilityGroup.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function New-DbaAvailabilityGroup {
    <#
    .SYNOPSIS
        Automates the creation of availability groups.

    .DESCRIPTION
        Automates the creation of availability groups.

    	* Checks prerequisites
    	* Creates Availability Group and adds primary replica
    	* Grants cluster permissions if necessary
    	* Adds secondary replica if supplied
    	* Adds databases if supplied
    		* Performs backup/restore if seeding mode is manual
    		* Performs backup to NUL if seeding mode is automatic
    	* Adds listener to primary if supplied
    	* Joins secondaries to availability group
    	* Grants endpoint connect permissions to service accounts
    	* Grants CreateAnyDatabase permissions if seeding mode is automatic
    	* Returns Availability Group object from primary

        NOTE: If a backup / restore is performed, the backups will be left intact on the network share.

        Thanks for this, Thomas Stringer! https://blogs.technet.microsoft.com/heyscriptingguy/2013/04/29/set-up-an-alwayson-availability-group-with-powershell/

    .PARAMETER Primary
        The primary SQL Server instance. Server version must be SQL Server version 2012 or higher.

    .PARAMETER PrimarySqlCredential
        Login to the primary instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Secondary
        The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.

    .PARAMETER SecondarySqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Name
        The name of the Availability Group.

    .PARAMETER DtcSupport
        Indicates whether the DtcSupport is enabled

    .PARAMETER ClusterType
        Cluster type of the Availability Group. Only supported in SQL Server 2017 and above.
        Options include: External, Wsfc or None. None by default.

    .PARAMETER AutomatedBackupPreference
        Specifies how replicas in the primary role are treated in the evaluation to pick the desired replica to perform a backup.

    .PARAMETER FailureConditionLevel
        Specifies the different conditions that can trigger an automatic failover in Availability Group.

    .PARAMETER HealthCheckTimeout
        This setting used to specify the length of time, in milliseconds, that the SQL Server resource DLL should wait for information returned by the sp_server_diagnostics stored procedure before reporting the Always On Failover Cluster Instance (FCI) as unresponsive.

        Changes that are made to the timeout settings are effective immediately and do not require a restart of the SQL Server resource.

        Defaults to 30000 (30 seconds).

    .PARAMETER Basic
        Indicates whether the availability group is basic. Basic availability groups like pumpkin spice and uggs.

        https://docs.microsoft.com/en-us/sql/database-engine/availability-groups/windows/basic-availability-groups-always-on-availability-groups

    .PARAMETER DatabaseHealthTrigger
        Indicates whether the availability group triggers the database health.

    .PARAMETER Passthru
        Don't create the availability group, just pass thru an object that can be further customized before creation.

    .PARAMETER Database
        The database or databases to add.

    .PARAMETER SharedPath
        The network share where the backups will be backed up and restored from.

        Each SQL Server service account must have access to this share.

        NOTE: If a backup / restore is performed, the backups will be left in tact on the network share.

    .PARAMETER UseLastBackup
        Use the last full backup of database.

    .PARAMETER Force
        Drop and recreate the database on remote servers using fresh backup.

    .PARAMETER AvailabilityMode
        Sets the availability mode of the availability group replica. Options are: AsynchronousCommit and SynchronousCommit. SynchronousCommit is default.

    .PARAMETER FailoverMode
        Sets the failover mode of the availability group replica. Options are Automatic, Manual and External. Automatic is default.

    .PARAMETER BackupPriority
        Sets the backup priority availability group replica. Default is 50.

    .PARAMETER Endpoint
        By default, this command will attempt to find a DatabaseMirror endpoint. If one does not exist, it will create it.

        If an endpoint must be created, the name "hadr_endpoint" will be used. If an alternative is preferred, use Endpoint.

    .PARAMETER ConnectionModeInPrimaryRole
        Specifies the connection intent modes of an Availability Replica in primary role. AllowAllConnections by default.

    .PARAMETER ConnectionModeInSecondaryRole
        Specifies the connection modes of an Availability Replica in secondary role. AllowAllConnections by default.

    .PARAMETER ReadonlyRoutingConnectionUrl
        Sets the read only routing connection url for the availability replica.

    .PARAMETER SeedingMode
        Specifies how the secondary replica will be initially seeded.

        Automatic enables direct seeding. This method will seed the secondary replica over the network. This method does not require you to backup and restore a copy of the primary database on the replica.

        Manual requires you to create a backup of the database on the primary replica and manually restore that backup on the secondary replica.

    .PARAMETER Certificate
        Specifies that the endpoint is to authenticate the connection using the certificate specified by certificate_name to establish identity for authorization.

        The far endpoint must have a certificate with the public key matching the private key of the specified certificate.

    .PARAMETER IPAddress
        Sets the IP address of the availability group listener.

    .PARAMETER SubnetMask
        Sets the subnet IP mask of the availability group listener.

    .PARAMETER Port
        Sets the number of the port used to communicate with the availability group.

    .PARAMETER Dhcp
        Indicates whether the object is DHCP.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: HA
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaAvailabilityGroup

    .EXAMPLE
        PS C:\> New-DbaAvailabilityGroup -Primary sql2016a -Name SharePoint

        Creates a new availability group on sql2016a named SharePoint

    .EXAMPLE
        PS C:\> New-DbaAvailabilityGroup -Primary sql2016a -Name SharePoint -Secondary sql2016b

        Creates a new availability group on sql2016a named SharePoint with a secondary replica, sql2016b

    .EXAMPLE
        PS C:\> New-DbaAvailabilityGroup -Primary sql2016std -Name BAG1 -Basic -Confirm:$false

        Creates a basic availability group named BAG1 on sql2016std and does not confirm when setting up

    .EXAMPLE
        PS C:\> New-DbaAvailabilityGroup -Primary sql2016b -Name AG1 -ClusterType Wsfc -Dhcp -Database db1 -UseLastBackup

        Creates an availability group on sql2016b with the name ag1. Uses the last backups available to add the database db1 to the AG.

    .EXAMPLE
        PS C:\> New-DbaAvailabilityGroup -Primary sql2017 -Name SharePoint -ClusterType None -FailoverMode Manual

        Creates a new availability group on sql2017 named SharePoint with a cluster type of none and a failover mode of manual

    .EXAMPLE
        PS C:\> New-DbaAvailabilityGroup -Primary sql1 -Secondary sql2 -Name ag1 -Database pubs -ClusterType None -SeedingMode Automatic -FailoverMode Manual

        Creates a new availability group with a primary replica on sql1 and a secondary on sql2. Automatically adds the database pubs.

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> $params = @{
        >> Primary = "sql1"
        >> PrimarySqlCredential = $cred
        >> Secondary = "sql2"
        >> SecondarySqlCredential = $cred
        >> Name = "test-ag"
        >> Database = "pubs"
        >> ClusterType = "None"
        >> SeedingMode = "Automatic"
        >> FailoverMode = "Manual"
        >> Confirm = $false
        >> }
        PS C:\> New-DbaAvailabilityGroup @params

        This exact command was used to create an availability group on docker!
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstanceParameter]$Primary,
        [PSCredential]$PrimarySqlCredential,
        [DbaInstanceParameter[]]$Secondary,
        [PSCredential]$SecondarySqlCredential,
        # AG

        [parameter(Mandatory)]
        [string]$Name,
        [switch]$DtcSupport,
        [ValidateSet('External', 'Wsfc', 'None')]
        [string]$ClusterType = 'External',
        [ValidateSet('None', 'Primary', 'Secondary', 'SecondaryOnly')]
        [string]$AutomatedBackupPreference = 'Secondary',
        [ValidateSet('OnAnyQualifiedFailureCondition', 'OnCriticalServerErrors', 'OnModerateServerErrors', 'OnServerDown', 'OnServerUnresponsive')]
        [string]$FailureConditionLevel = "OnServerDown",
        [int]$HealthCheckTimeout = 30000,
        [switch]$Basic,
        [switch]$DatabaseHealthTrigger,
        [switch]$Passthru,
        # database

        [string[]]$Database,
        [Alias("NetworkShare")]
        [string]$SharedPath,
        [switch]$UseLastBackup,
        [switch]$Force,
        # replica

        [ValidateSet('AsynchronousCommit', 'SynchronousCommit')]
        [string]$AvailabilityMode = "SynchronousCommit",
        [ValidateSet('Automatic', 'Manual', 'External')]
        [string]$FailoverMode = "Automatic",
        [int]$BackupPriority = 50,
        [ValidateSet('AllowAllConnections', 'AllowReadWriteConnections')]
        [string]$ConnectionModeInPrimaryRole = 'AllowAllConnections',
        [ValidateSet('AllowAllConnections', 'AllowNoConnections', 'AllowReadIntentConnectionsOnly')]
        [string]$ConnectionModeInSecondaryRole = 'AllowAllConnections',
        [ValidateSet('Automatic', 'Manual')]
        [string]$SeedingMode = 'Manual',
        [string]$Endpoint,
        [string]$ReadonlyRoutingConnectionUrl,
        [string]$Certificate,
        # network

        [ipaddress[]]$IPAddress,
        [ipaddress]$SubnetMask = "255.255.255.0",
        [int]$Port = 1433,
        [switch]$Dhcp,
        [switch]$EnableException
    )
    begin {
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter NetworkShare -CustomMessage "Using the parameter NetworkShare is deprecated. This parameter will be removed in version 1.0.0 or before. Use SharedPath instead."
    }
    process {
        $stepCounter = $wait = 0

        if ($Force -and $Secondary -and (-not $SharedPath -and -not $UseLastBackup) -and ($SeedingMode -ne 'Automatic')) {
            Stop-Function -Message "SharedPath or UseLastBackup is required when Force is used"
            return
        }

        try {
            $server = Connect-SqlInstance -SqlInstance $Primary -SqlCredential $PrimarySqlCredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Primary
            return
        }

        if ($SeedingMode -eq 'Automatic' -and $server.VersionMajor -lt 13) {
            Stop-Function -Message "Automatic seeding mode only supported in SQL Server 2016 and above" -Target $Primary
            return
        }

        if ($Basic -and $server.VersionMajor -lt 13) {
            Stop-Function -Message "Basic availability groups are only supported in SQL Server 2016 and above" -Target $Primary
            return
        }

        Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Checking perquisites"

        # Don't reuse $server here, it fails
        if (Get-DbaAvailabilityGroup -SqlInstance $Primary -SqlCredential $PrimarySqlCredential -AvailabilityGroup $Name) {
            Stop-Function -Message "Availability group named $Name already exists on $Primary"
            return
        }

        if ($Certificate) {
            $cert = Get-DbaDbCertificate -SqlInstance $Primary -SqlCredential $PrimarySqlCredential -Certificate $Certificate
            if (-not $cert) {
                Stop-Function -Message "Certificate $Certificate does not exist on $Primary" -ErrorRecord $_ -Target $Primary
                return
            }
        }

        if (($SharedPath)) {
            if (-not (Test-DbaPath -SqlInstance $Primary -SqlCredential $PrimarySqlCredential -Path $SharedPath)) {
                Stop-Function -Continue -Message "Cannot access $SharedPath from $Primary"
                return
            }
        }

        if ($Database -and -not $UseLastBackup -and -not $SharedPath -and $Secondary -and $SeedingMode -ne 'Automatic') {
            Stop-Function -Continue -Message "You must specify a SharedPath when adding databases to a manually seeded availability group"
            return
        }

        if ($server.HostPlatform -eq "Linux") {
            # New to SQL Server 2017 (14.x) is the introduction of a cluster type for AGs. For Linux, there are two valid values: External and None.
            if ($ClusterType -notin "External", "None") {
                Stop-Function -Continue -Message "Linux only supports ClusterType of External or None"
                return
            }
            # Microsoft Distributed Transaction Coordinator (DTC) is not supported under Linux in SQL Server 2017
            if ($DtcSupport) {
                Stop-Function -Continue -Message "Microsoft Distributed Transaction Coordinator (DTC) is not supported under Linux"
                return
            }
        }

        if ($ClusterType -eq "None" -and $server.VersionMajor -lt 14) {
            Stop-Function -Message "ClusterType of None only supported in SQL Server 2017 and above"
            return
        }

        if ($Secondary) {
            $secondaries = @()
            foreach ($computer in $Secondary) {
                try {
                    $secondaries += Connect-SqlInstance -SqlInstance $computer -SqlCredential $SecondarySqlCredential
                } catch {
                    Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Primary
                    return
                }
            }

            if ($SeedingMode -eq "Automatic") {
                $primarypath = Get-DbaDefaultPath -SqlInstance $server
                foreach ($second in $secondaries) {
                    $secondarypath = Get-DbaDefaultPath -SqlInstance $second
                    if ($primarypath.Data -ne $secondarypath.Data) {
                        Write-Message -Level Warning -Message "Primary and secondary ($second) default data paths do not match. Trying anyway."
                    }
                    if ($primarypath.Log -ne $secondarypath.Log) {
                        Write-Message -Level Warning -Message "Primary and secondary ($second) default log paths do not match. Trying anyway."
                    }
                }
            }
        }

        # database checks
        if ($Database) {
            $dbs += Get-DbaDatabase -SqlInstance $Primary -SqlCredential $PrimarySqlCredential -Database $Database
        }

        foreach ($primarydb in $dbs) {
            if ($primarydb.MirroringStatus -ne "None") {
                Stop-Function -Message "Cannot setup mirroring on database ($dbname) due to its current mirroring state: $($primarydb.MirroringStatus)"
                return
            }

            if ($primarydb.Status -ne "Normal") {
                Stop-Function -Message "Cannot setup mirroring on database ($dbname) due to its current state: $($primarydb.Status)"
                return
            }

            if ($primarydb.RecoveryModel -ne "Full") {
                if ((Test-Bound -ParameterName UseLastBackup)) {
                    Stop-Function -Message "$dbName not set to full recovery. UseLastBackup cannot be used."
                    return
                } else {
                    Set-DbaDbRecoveryModel -SqlInstance $Primary -SqlCredential $PrimarySqlCredential -Database $primarydb.Name -RecoveryModel Full
                }
            }
        }

        Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Creating availability group named $Name on $Primary"

        # Start work
        if ($Pscmdlet.ShouldProcess($Primary, "Setting up availability group named $Name and adding primary replica")) {
            try {
                $ag = New-Object Microsoft.SqlServer.Management.Smo.AvailabilityGroup -ArgumentList $server, $Name
                $ag.AutomatedBackupPreference = [Microsoft.SqlServer.Management.Smo.AvailabilityGroupAutomatedBackupPreference]::$AutomatedBackupPreference
                $ag.FailureConditionLevel = [Microsoft.SqlServer.Management.Smo.AvailabilityGroupFailureConditionLevel]::$FailureConditionLevel
                $ag.HealthCheckTimeout = $HealthCheckTimeout

                if ($server.VersionMajor -ge 13) {
                    $ag.BasicAvailabilityGroup = $Basic
                    $ag.DatabaseHealthTrigger = $DatabaseHealthTrigger
                }

                if ($server.VersionMajor -ge 14) {
                    $ag.ClusterType = $ClusterType
                }

                if ($PassThru) {
                    $defaults = 'LocalReplicaRole', 'Name as AvailabilityGroup', 'PrimaryReplicaServerName as PrimaryReplica', 'AutomatedBackupPreference', 'AvailabilityReplicas', 'AvailabilityDatabases', 'AvailabilityGroupListeners'
                    return (Select-DefaultView -InputObject $ag -Property $defaults)
                }

                $replicaparams = @{
                    InputObject                   = $ag
                    AvailabilityMode              = $AvailabilityMode
                    FailoverMode                  = $FailoverMode
                    BackupPriority                = $BackupPriority
                    ConnectionModeInPrimaryRole   = $ConnectionModeInPrimaryRole
                    ConnectionModeInSecondaryRole = $ConnectionModeInSecondaryRole
                    Endpoint                      = $Endpoint
                    ReadonlyRoutingConnectionUrl  = $ReadonlyRoutingConnectionUrl
                    Certificate                   = $Certificate
                }

                if ($server.VersionMajor -ge 13) {
                    $replicaparams += @{SeedingMode = $SeedingMode}
                }

                $null = Add-DbaAgReplica @replicaparams -EnableException -SqlInstance $server
            } catch {
                $msg = $_.Exception.InnerException.InnerException.Message
                if (-not $msg) {
                    $msg = $_
                }
                Stop-Function -Message $msg -ErrorRecord $_ -Target $Primary
                return
            }
        }

        # Add cluster permissions
        if ($ClusterType -eq 'Wsfc') {
            Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Adding endpoint connect permissions"

            foreach ($second in $secondaries) {
                if ($Pscmdlet.ShouldProcess($Primary, "Adding cluster permissions for availability group named $Name")) {
                    Write-Message -Level Verbose -Message "WSFC Cluster requires granting [NT AUTHORITY\SYSTEM] a few things. Setting now."
                    $sql = "GRANT ALTER ANY AVAILABILITY GROUP TO [NT AUTHORITY\SYSTEM]
                        GRANT CONNECT SQL TO [NT AUTHORITY\SYSTEM]
                        GRANT VIEW SERVER STATE TO [NT AUTHORITY\SYSTEM]"
                    try {
                        $null = $server.Query($sql)
                        foreach ($second in $secondaries) {
                            $null = $second.Query($sql)
                        }
                    } catch {
                        Stop-Function -Message "Failure adding cluster service account permissions" -ErrorRecord $_
                    }
                }
            }
        }

        # Add replicas
        Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Adding secondary replicas"

        foreach ($second in $secondaries) {
            if ($Pscmdlet.ShouldProcess($second.Name, "Adding replica to availability group named $Name")) {
                try {
                    # Add replicas
                    $null = Add-DbaAgReplica @replicaparams -EnableException -SqlInstance $second
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target $second -Continue
                }
            }
        }

        try {
            # something is up with .net create(), force a stop
            Invoke-Create -Object $ag
        } catch {
            $msg = $_.Exception.InnerException.InnerException.Message
            if (-not $msg) {
                $msg = $_
            }
            Stop-Function -Message $msg -ErrorRecord $_ -Target $Primary
            return
        }

        # Add listener
        if ($IPAddress -or $Dhcp) {
            $progressmsg = "Adding listener"
        } else {
            $progressmsg = "Joining availability group"
        }
        Write-ProgressHelper -StepNumber ($stepCounter++) -Message $progressmsg

        if ($IPAddress) {
            if ($Pscmdlet.ShouldProcess($Primary, "Adding static IP listener for $Name to the Primary replica")) {
                $null = Add-DbaAgListener -InputObject $ag -IPAddress $IPAddress[0] -SubnetMask $SubnetMask -Port $Port -Dhcp:$Dhcp
            }
        } elseif ($Dhcp) {
            if ($Pscmdlet.ShouldProcess($Primary, "Adding DHCP listener for $Name to all replicas")) {
                $null = Add-DbaAgListener -InputObject $ag -Port $Port -Dhcp:$Dhcp
                foreach ($second in $secondaries) {
                    $secag = Get-DbaAvailabilityGroup -SqlInstance $second -AvailabilityGroup $Name
                    $null = Add-DbaAgListener -InputObject $secag -Port $Port -Dhcp:$Dhcp
                }
            }
        }

        Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Joining availability group"

        foreach ($second in $secondaries) {
            if ($Pscmdlet.ShouldProcess("Joining $($second.Name) to $Name")) {
                try {
                    # join replicas to ag
                    Join-DbaAvailabilityGroup -SqlInstance $second -InputObject $ag -EnableException
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target $second -Continue
                }
            }
        }

        Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Granting permissions on availability group, this may take a moment"

        # Grant permissions, but first, get all necessary service accounts
        $primaryserviceaccount = $server.ServiceAccount.Trim()
        $saname = ([DbaInstanceParameter]($server.DomainInstanceName)).ComputerName

        if ($primaryserviceaccount) {
            if ($primaryserviceaccount.StartsWith("NT ")) {
                $primaryserviceaccount = "$saname`$"
            }
            if ($primaryserviceaccount.StartsWith("$saname")) {
                $primaryserviceaccount = "$saname`$"
            }
            if ($primaryserviceaccount.StartsWith(".")) {
                $primaryserviceaccount = "$saname`$"
            }
        }

        if (-not $primaryserviceaccount) {
            $primaryserviceaccount = "$saname`$"
        }

        $serviceaccounts = @($primaryserviceaccount)

        foreach ($second in $secondaries) {
            # If service account is empty, add the computer account instead
            $secondaryserviceaccount = $second.ServiceAccount.Trim()
            $saname = ([DbaInstanceParameter]($second.DomainInstanceName)).ComputerName

            if ($secondaryserviceaccount) {
                if ($secondaryserviceaccount.StartsWith("NT ")) {
                    $secondaryserviceaccount = "$saname`$"
                }
                if ($secondaryserviceaccount.StartsWith("$saname")) {
                    $secondaryserviceaccount = "$saname`$"
                }
                if ($secondaryserviceaccount.StartsWith(".")) {
                    $secondaryserviceaccount = "$saname`$"
                }
            }

            if (-not $secondaryserviceaccount) {
                $secondaryserviceaccount = "$saname`$"
            }

            $serviceaccounts += $secondaryserviceaccount
        }

        $serviceaccounts = $serviceaccounts | Select-Object -Unique

        if ($SeedingMode -eq 'Automatic') {
            try {
                if ($Pscmdlet.ShouldProcess($server.Name, "Seeding mode is automatic. Adding CreateAnyDatabase permissions to availability group.")) {
                    $null = $server.Query("ALTER AVAILABILITY GROUP [$Name] GRANT CREATE ANY DATABASE")
                }
            } catch {
                # Log the exception but keep going
                Stop-Function -Message "Failure" -ErrorRecord $_
            }
        }

        # Add databases
        Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Adding databases"

        $null = Add-DbaAgDatabase -SqlInstance $Primary -SqlCredential $PrimarySqlCredential -AvailabilityGroup $Name -Database $Database -SeedingMode $SeedingMode -SharedPath $SharedPath -Secondary $Secondary -SecondarySqlCredential $SecondarySqlCredential

        foreach ($second in $secondaries) {
            if ($server.HostPlatform -ne "Linux" -and $second.HostPlatform -ne "Linux") {
                if ($Pscmdlet.ShouldProcess($second.Name, "Granting Connect permissions to service accounts: $serviceaccounts")) {
                    $null = Grant-DbaAgPermission -SqlInstance $server, $second -Login $serviceaccounts -Type Endpoint -Permission Connect
                }
            }
            if ($SeedingMode -eq 'Automatic') {
                $done = $false
                try {
                    if ($Pscmdlet.ShouldProcess($second.Name, "Seeding mode is automatic. Adding CreateAnyDatabase permissions to availability group.")) {
                        do {
                            $second.Refresh()
                            $second.AvailabilityGroups.Refresh()
                            if (Get-DbaAvailabilityGroup -SqlInstance $second -AvailabilityGroup $Name) {
                                $null = $second.Query("ALTER AVAILABILITY GROUP [$Name] GRANT CREATE ANY DATABASE")
                                $done = $true
                            } else {
                                $wait++
                                Start-Sleep -Seconds 1
                            }
                        } while ($wait -lt 20 -and $done -eq $false)
                    }
                } catch {
                    # Log the exception but keep going
                    Stop-Function -Message "Failure" -ErrorRecord $_
                }
            }
        }

        # Get results
        Get-DbaAvailabilityGroup -SqlInstance $Primary -SqlCredential $PrimarySqlCredential -AvailabilityGroup $Name
    }
}
tools\dbatools\functions\New-DbaClientAlias.ps1
function New-DbaClientAlias {
    <#
    .SYNOPSIS
        Creates/updates a sql alias for the specified server - mimics cliconfg.exe

    .DESCRIPTION
        Creates/updates a SQL Server alias by altering HKLM:\SOFTWARE\Microsoft\MSSQLServer\Client

    .PARAMETER ComputerName
        The target computer where the alias will be created

    .PARAMETER Credential
        Allows you to login to remote computers using alternative credentials

    .PARAMETER ServerName
        The target SQL Server

    .PARAMETER Alias
        The alias to be created

    .PARAMETER Protocol
        The protocol for the connection, either TCPIP or NetBIOS. Defaults to TCPIP.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Alias
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaClientAlias

    .EXAMPLE
        PS C:\> New-DbaClientAlias -ServerName sqlcluster\sharepoint -Alias sp

        Creates a new TCP alias on the local workstation called sp, which points sqlcluster\sharepoint


    .EXAMPLE
        PS C:\> New-DbaClientAlias -ServerName 'sqlcluster,14443' -Alias spinstance

        Creates a new TCP alias on the local workstation called spinstance, which points to sqlcluster, port 14443.

    .EXAMPLE
        PS C:\> New-DbaClientAlias -ServerName sqlcluster\sharepoint -Alias sp -Protocol NamedPipes

        Creates a new NamedPipes alias on the local workstation called sp, which points sqlcluster\sharepoint

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$ServerName,
        [parameter(Mandatory)]
        [string]$Alias,
        [ValidateSet("TCPIP", "NamedPipes")]
        [string]$Protocol = "TCPIP",
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        # This is a script block so cannot use messaging system
        $scriptblock = {
            $basekeys = "HKLM:\SOFTWARE\WOW6432Node\Microsoft\MSSQLServer", "HKLM:\SOFTWARE\Microsoft\MSSQLServer"
            #Variable marked as unused by PSScriptAnalyzer
            #$ServerName = $args[0]
            $Alias = $args[1]
            $serverstring = $args[2]

            if ($env:PROCESSOR_ARCHITECTURE -like "*64*") { $64bit = $true }

            foreach ($basekey in $basekeys) {
                if ($64bit -ne $true -and $basekey -like "*WOW64*") { continue }

                if ((Test-Path $basekey) -eq $false) {
                    throw "Base key ($basekey) does not exist. Quitting."
                }

                $client = "$basekey\Client"

                if ((Test-Path $client) -eq $false) {
                    # "Creating $client key"
                    $null = New-Item -Path $client -Force
                }

                $connect = "$client\ConnectTo"

                if ((Test-Path $connect) -eq $false) {
                    # "Creating $connect key"
                    $null = New-Item -Path $connect -Force
                }

                <#
                #Variable marked as unused by PSScriptAnalyzer
                #Looks like it was once used for a Verbose Message
                if ($basekey -like "*WOW64*") {
                    $architecture = "32-bit"
                } else {
                    $architecture = "64-bit"
                }
                #>
                <# DO NOT use Write-Message as this is inside of a script block #>
                # Write-Verbose "Creating/updating alias for $ComputerName for $architecture"
                $null = New-ItemProperty -Path $connect -Name $Alias -Value $serverstring -PropertyType String -Force
            }
        }
    }

    process {
        if ($protocol -eq "TCPIP") {
            $serverstring = "DBMSSOCN,$ServerName"
        } else {
            $serverstring = "DBNMPNTW,\\$ServerName\pipe\sql\query"
        }

        foreach ($computer in $ComputerName.ComputerName) {

            $null = Test-ElevationRequirement -ComputerName $computer -Continue

            if ($PScmdlet.ShouldProcess($computer, "Adding $alias")) {
                try {
                    Invoke-Command2 -ComputerName $computer -Credential $Credential -ScriptBlock $scriptblock -ErrorAction Stop -ArgumentList $ServerName, $Alias, $serverstring
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target $computer -Continue
                }
            }
        }

        Get-DbaClientAlias -ComputerName $computer -Credential $Credential | Where-Object AliasName -eq $Alias
    }
}
tools\dbatools\functions\New-DbaCmConnection.ps1
function New-DbaCmConnection {
    <#
    .SYNOPSIS
        Generates a connection object for use in remote computer management.

    .DESCRIPTION
        Generates a connection object for use in remote computer management.
        Those objects are used for the purpose of cim/wmi queries, caching which protocol worked, optimizing performance and minimizing authentication errors.

        New-DbaCmConnection will create a NEW object and overwrite any existing ones for the specified computer.
        Furthermore, information stored in the input beyond the computername will be discarded in favor of the new settings.

        Unless the connection cache has been disabled, all connections will automatically be registered in the cache, so no further action is necessary.
        The output is primarily for information purposes, however it may be used to pass objects and circumvent the cache with those.

        NOTE: Generally, this function need not be used, as a first connection to a computer using any connecting function such as "Get-DbaCmObject" will automatically register a new default connection for it.

        This function exists to be able to preconfigure connections.

    .PARAMETER ComputerName
        The computer to build the connection object for.

    .PARAMETER Credential
        The credential to register.

    .PARAMETER UseWindowsCredentials
        Whether using the default windows credentials is legit.
        Not setting this will not exclude using windows credentials, but only not pre-confirm them as working.

    .PARAMETER OverrideExplicitCredential
        Setting this will enable the credential override.
        The override will cause the system to ignore explicitly specified credentials, so long as known, good credentials are available.

    .PARAMETER DisabledConnectionTypes
        Exlicitly disable connection types.
        These types will then not be used for connecting to the computer.

    .PARAMETER DisableBadCredentialCache
        Will prevent the caching of credentials if set to true.

    .PARAMETER DisableCimPersistence
        Will prevent Cim-Sessions to be reused.

    .PARAMETER DisableCredentialAutoRegister
        Will prevent working credentials from being automatically cached

    .PARAMETER EnableCredentialFailover
        Will enable automatic failing over to known to work credentials, when using bad credentials.
        By default, passing bad credentials will cause the Computer Management functions to interrupt with a warning (Or exception if in silent mode).

    .PARAMETER WindowsCredentialsAreBad
        Will prevent the windows credentials of the currently logged on user from being used for the remote connection.

    .PARAMETER CimWinRMOptions
        Specify a set of options to use when connecting to the target computer using CIM over WinRM.
        Use 'New-CimSessionOption' to create such an object.

    .PARAMETER CimDCOMOptions
        Specify a set of options to use when connecting to the target computer using CIM over DCOM.
        Use 'New-CimSessionOption' to create such an object.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ComputerManagement, CIM
        Friedrich Weinmann (@FredWeinmann)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaCmConnection

    .EXAMPLE
        PS C:\> New-DbaCmConnection -ComputerName sql2014 -UseWindowsCredentials -OverrideExplicitCredential -DisabledConnectionTypes CimRM

        Returns a new configuration object for connecting to the computer sql2014.
        - The current user credentials are set as valid
        - The connection is configured to ignore explicit credentials (so all connections use the windows credentials)
        - The connections will not try using CIM over WinRM

        Unless caching is globally disabled, this is automatically stored in the connection cache and will be applied automatically.
        In that (the default) case, the output is for information purposes only and need not be used.

    .EXAMPLE
        PS C:\> Get-Content computers.txt | New-DbaCmConnection -Credential $cred -CimWinRMOptions $options -DisableBadCredentialCache -OverrideExplicitCredential

        Gathers a list of computers from a text file, then creates and registers connections for each of them, setting them to ...
        - use the credentials stored in $cred
        - use the options stored in $options when connecting using CIM over WinRM
        - not store credentials that are known to not work
        - to ignore explicitly specified credentials

        Essentially, this configures all connections to those computers to prefer failure with the specified credentials over using alternative credentials.

    #>
    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'Credential')]
    param (
        [Parameter(ValueFromPipeline)]
        [Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter[]]
        $ComputerName = $env:COMPUTERNAME,
        [Parameter(ParameterSetName = "Credential")]
        [PSCredential]
        $Credential,
        [Parameter(ParameterSetName = "Windows")]
        [switch]
        $UseWindowsCredentials,
        [switch]
        $OverrideExplicitCredential,
        [Sqlcollaborative.Dbatools.Connection.ManagementConnectionType]
        $DisabledConnectionTypes = 'None',
        [switch]
        $DisableBadCredentialCache,
        [switch]
        $DisableCimPersistence,
        [switch]
        $DisableCredentialAutoRegister,
        [switch]
        $EnableCredentialFailover,
        [Parameter(ParameterSetName = "Credential")]
        [switch]
        $WindowsCredentialsAreBad,
        [Microsoft.Management.Infrastructure.Options.WSManSessionOptions]
        $CimWinRMOptions,
        [Microsoft.Management.Infrastructure.Options.DComSessionOptions]
        $CimDCOMOptions,
        [switch]
        [Alias('Silent')]$EnableException
    )

    begin {
        Write-Message -Level InternalComment -Message "Starting execution"
        Write-Message -Level Verbose -Message "Bound parameters: $($PSBoundParameters.Keys -join ", ")"

        $disable_cache = Get-DbatoolsConfigValue -Name 'ComputerManagement.Cache.Disable.All' -Fallback $false
    }
    process {
        foreach ($connectionObject in $ComputerName) {
            if ($Pscmdlet.ShouldProcess($($connectionObject.connection.computername), "Creating connection object")) {
                if (-not $connectionObject.Success) { Stop-Function -Message "Failed to interpret computername input: $($connectionObject.InputObject)" -Category InvalidArgument -Target $connectionObject.InputObject -Continue }
                Write-Message -Level VeryVerbose -Message "Processing computer: $($connectionObject.Connection.ComputerName)" -Target $connectionObject.Connection

                $connection = New-Object -TypeName Sqlcollaborative.Dbatools.Connection.ManagementConnection -ArgumentList $connectionObject.Connection.ComputerName
                if (Test-Bound "Credential") { $connection.Credentials = $Credential }
                if (Test-Bound "UseWindowsCredentials") {
                    $connection.Credentials = $null
                    $connection.UseWindowsCredentials = $UseWindowsCredentials
                }
                if (Test-Bound "OverrideExplicitCredential") { $connection.OverrideExplicitCredential = $OverrideExplicitCredential }
                if (Test-Bound "DisabledConnectionTypes") { $connection.DisabledConnectionTypes = $DisabledConnectionTypes }
                if (Test-Bound "DisableBadCredentialCache") { $connection.DisableBadCredentialCache = $DisableBadCredentialCache }
                if (Test-Bound "DisableCimPersistence") { $connection.DisableCimPersistence = $DisableCimPersistence }
                if (Test-Bound "DisableCredentialAutoRegister") { $connection.DisableCredentialAutoRegister = $DisableCredentialAutoRegister }
                if (Test-Bound "EnableCredentialFailover") { $connection.DisableCredentialAutoRegister = $EnableCredentialFailover }
                if (Test-Bound "WindowsCredentialsAreBad") { $connection.WindowsCredentialsAreBad = $WindowsCredentialsAreBad }
                if (Test-Bound "CimWinRMOptions") { $connection.CimWinRMOptions = $CimWinRMOptions }
                if (Test-Bound "CimDCOMOptions") { $connection.CimDCOMOptions = $CimDCOMOptions }

                if (-not $disable_cache) {
                    Write-Message -Level Verbose -Message "Writing connection to cache"
                    [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::Connections[$connectionObject.Connection.ComputerName] = $connection
                } else { Write-Message -Level Verbose -Message "Skipping writing to cache, since the cache has been disabled!" }
                $connection
            }
        }
    }
    end {
        Write-Message -Level InternalComment -Message "Stopping execution"
    }
}
tools\dbatools\functions\New-DbaComputerCertificate.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function New-DbaComputerCertificate {
    <#
    .SYNOPSIS
        Creates a new computer certificate useful for Forcing Encryption

    .DESCRIPTION
        Creates a new computer certificate - self-signed or signed by an Active Directory CA, using the Web Server certificate.

        By default, a key with a length of 1024 and a friendly name of the machines FQDN is generated.

        This command was originally intended to help automate the process so that SSL certificates can be available for enforcing encryption on connections.

        It makes a lot of assumptions - namely, that your account is allowed to auto-enroll and that you have permission to do everything it needs to do ;)

        References:
        http://sqlmag.com/sql-server/7-steps-ssl-encryption
        https://azurebi.jppp.org/2016/01/23/using-lets-encrypt-certificates-for-secure-sql-server-connections/
        https://blogs.msdn.microsoft.com/sqlserverfaq/2016/09/26/creating-and-registering-ssl-certificates/

        The certificate is generated using AD's webserver SSL template on the client machine and pushed to the remote machine.

    .PARAMETER ComputerName
       The target SQL Server instance or instances. Defaults to localhost. If target is a cluster, you must also specify ClusterInstanceName (see below)

    .PARAMETER Credential
        Allows you to login to $ComputerName using alternative credentials.

    .PARAMETER CaServer
        Optional - the CA Server where the request will be sent to

    .PARAMETER CaName
        The properly formatted CA name of the corresponding CaServer

    .PARAMETER ClusterInstanceName
        When creating certs for a cluster, use this parameter to create the certificate for the cluster node name. Use ComputerName for each of the nodes.

    .PARAMETER SecurePassword
        Password to encrypt/decrypt private key for export to remote machine

    .PARAMETER FriendlyName
        The FriendlyName listed in the certificate. This defaults to the FQDN of the $ComputerName

    .PARAMETER CertificateTemplate
        The domain's Certificate Template - WebServer by default.

    .PARAMETER KeyLength
        The length of the key - defaults to 1024

    .PARAMETER Store
        Certificate store - defaults to LocalMachine

    .PARAMETER Folder
        Certificate folder - defaults to My (Personal)

    .PARAMETER Dns
        Specify the Dns entries listed in SAN. By default, it will be ComputerName + FQDN, or in the case of clusters, clustername + cluster FQDN.

    .PARAMETER SelfSigned
        Creates a self-signed certificate. All other parameters can still apply except CaServer and CaName because the command does not go and get the certificate signed.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .NOTES
        Tags: Certificate
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> New-DbaComputerCertificate

        Creates a computer certificate signed by the local domain CA for the local machine with the keylength of 1024.

    .EXAMPLE
        PS C:\> New-DbaComputerCertificate -ComputerName Server1

        Creates a computer certificate signed by the local domain CA _on the local machine_ for server1 with the keylength of 1024.

        The certificate is then copied to the new machine over WinRM and imported.

    .EXAMPLE
        PS C:\> New-DbaComputerCertificate -ComputerName sqla, sqlb -ClusterInstanceName sqlcluster -KeyLength 4096

        Creates a computer certificate for sqlcluster, signed by the local domain CA, with the keylength of 4096.

        The certificate is then copied to sqla _and_ sqlb over WinRM and imported.

    .EXAMPLE
        PS C:\> New-DbaComputerCertificate -ComputerName Server1 -WhatIf

        Shows what would happen if the command were run

    .EXAMPLE
        PS C:\> New-DbaComputerCertificate -SelfSigned

        Creates a self-signed certificate

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseOutputTypeCorrectly", "", Justification = "PSSA Rule Ignored by BOH")]
    param (
        [parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlInstance")]
        [DbaInstance[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [string]$CaServer,
        [string]$CaName,
        [string]$ClusterInstanceName,
        [Alias("Password")]
        [securestring]$SecurePassword,
        [string]$FriendlyName = "SQL Server",
        [string]$CertificateTemplate = "WebServer",
        [int]$KeyLength = 1024,
        [string]$Store = "LocalMachine",
        [string]$Folder = "My",
        [string[]]$Dns,
        [switch]$SelfSigned,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        $englishCodes = 9, 1033, 2057, 3081, 4105, 5129, 6153, 7177, 8201, 9225
        if ($englishCodes -notcontains (Get-DbaCmObject Win32_OperatingSystem).OSLanguage) {
            Stop-Function -Message "Currently, this command is only supported in English OS locales. OS Locale detected: $([System.Globalization.CultureInfo]::GetCultureInfo([int](Get-DbaCmObject Win32_OperatingSystem).OSLanguage).DisplayName)`nWe apologize for the inconvenience and look into providing universal language support in future releases."
            return
        }

        if (-not (Test-ElevationRequirement -ComputerName $env:COMPUTERNAME)) {
            return
        }

        function GetHexLength {
            [cmdletbinding()]
            param(
                [int]$strLen
            )
            $hex = [String]::Format("{0:X2}", $strLen)

            if ($strLen -gt 127) { [String]::Format("{0:X2}", 128 + ($hex.Length / 2)) + $hex }
            else { $hex }
        }

        function Get-SanExt {
            [cmdletbinding()]
            param(
                [string[]]$hostName
            )
            # thanks to Lincoln of
            # https://social.technet.microsoft.com/Forums/windows/en-US/f568edfa-7f93-46a4-aab9-a06151592dd9/converting-ascii-to-asn1-der

            $temp = ''
            foreach ($fqdn in $hostName) {
                # convert each character of fqdn to hex
                $hexString = ($fqdn.ToCharArray() | ForEach-Object { [String]::Format("{0:X2}", [int]$_) }) -join ''

                # length of hex fqdn, in hex
                $hexLength = GetHexLength ($hexString.Length / 2)

                # concatenate special code 82, hex length, hex string
                $temp += "82${hexLength}${hexString}"
            }
            # calculate total length of concatenated string, in hex
            $totalHexLength = GetHexLength ($temp.Length / 2)
            # concatenate special code 30, hex length, hex string
            $temp = "30${totalHexLength}${temp}"
            # convert to binary
            $bytes = $(
                for ($i = 0; $i -lt $temp.Length; $i += 2) {
                    [byte]"0x$($temp.SubString($i, 2))"
                }
            )
            # convert to base 64
            $base64 = [Convert]::ToBase64String($bytes)
            # output in proper format
            for ($i = 0; $i -lt $base64.Length; $i += 64) {
                $line = $base64.SubString($i, [Math]::Min(64, $base64.Length - $i))
                if ($i -eq 0) { "2.5.29.17=$line" }
                else { "_continue_=$line" }
            }
        }

        if ((!$CaServer -or !$CaName) -and !$SelfSigned) {
            try {
                Write-Message -Level Verbose -Message "No CaServer or CaName specified. Performing lookup."
                # hat tip Vadims Podans
                $domain = ([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).Name
                $domain = "DC=" + $domain -replace '\.', ", DC="
                $pks = [ADSI]"LDAP://CN=Enrollment Services, CN=Public Key Services, CN=Services, CN=Configuration, $domain"
                $cas = $pks.psBase.Children

                $allCas = @()
                foreach ($ca in $cas) {
                    $allCas += [pscustomobject]@{
                        CA       = $ca | ForEach-Object { $_.Name }
                        Computer = $ca | ForEach-Object { $_.DNSHostName }
                    }
                }
            } catch {
                Stop-Function -Message "Cannot access Active Directory or find the Certificate Authority" -ErrorRecord $_
                return
            }

            if (!$CaServer) {
                $CaServer = ($allCas | Select-Object -First 1).Computer
                Write-Message -Level Verbose -Message "Root Server: $CaServer"
            }

            if (!$CaName) {
                $CaName = ($allCas | Select-Object -First 1).CA
                Write-Message -Level Verbose -Message "Root CA name: $CaName"
            }
        }

        $tempDir = ([System.IO.Path]::GetTempPath()).TrimEnd("\")
        $certTemplate = "CertificateTemplate:$CertificateTemplate"
    }

    process {
        if (Test-FunctionInterrupt) { return }

        # uses dos command locally
        

        foreach ($computer in $ComputerName) {

            if (!$secondaryNode) {

                if ($ClusterInstanceName) {
                    if ($ClusterInstanceName -notmatch "\.") {
                        $fqdn = "$ClusterInstanceName.$env:USERDNSDOMAIN"
                    } else {
                        $fqdn = $ClusterInstanceName
                    }
                } else {
                    $resolved = Resolve-DbaNetworkName -ComputerName $computer.ComputerName -WarningAction SilentlyContinue

                    if (!$resolved) {
                        $fqdn = "$ComputerName.$env:USERDNSDOMAIN"
                        Write-Message -Level Warning -Message "Server name cannot be resolved. Guessing it's $fqdn"
                    } else {
                        $fqdn = $resolved.fqdn
                    }
                }

                $certDir = "$tempDir\$fqdn"
                $certCfg = "$certDir\request.inf"
                $certCsr = "$certDir\$fqdn.csr"
                $certCrt = "$certDir\$fqdn.crt"
                $certPfx = "$certDir\$fqdn.pfx"
                $tempPfx = "$certDir\temp-$fqdn.pfx"

                if (Test-Path($certDir)) {
                    Write-Message -Level Output -Message "Deleting files from $certDir"
                    $null = Remove-Item "$certDir\*.*"
                } else {
                    Write-Message -Level Output -Message "Creating $certDir"
                    $null = New-Item -Path $certDir -ItemType Directory -Force
                }

                # Make sure output is compat with clusters
                $shortName = $fqdn.Split(".")[0]

                if (!$dns) {
                    $dns = $shortName, $fqdn
                }

                $san = Get-SanExt $dns
                # Write config file
                Set-Content $certCfg "[Version]"
                Add-Content $certCfg 'Signature="$Windows NT$"'
                Add-Content $certCfg "[NewRequest]"
                Add-Content $certCfg "Subject = ""CN=$fqdn"""
                Add-Content $certCfg "KeySpec = 1"
                Add-Content $certCfg "KeyLength = $KeyLength"
                Add-Content $certCfg "Exportable = TRUE"
                Add-Content $certCfg "MachineKeySet = TRUE"
                Add-Content $certCfg "FriendlyName=""$FriendlyName"""
                Add-Content $certCfg "SMIME = False"
                Add-Content $certCfg "PrivateKeyArchive = FALSE"
                Add-Content $certCfg "UserProtected = FALSE"
                Add-Content $certCfg "UseExistingKeySet = FALSE"
                Add-Content $certCfg "ProviderName = ""Microsoft RSA SChannel Cryptographic Provider"""
                Add-Content $certCfg "ProviderType = 12"
                if ($SelfSigned) {
                    Add-Content $certCfg "RequestType = Cert"
                } else {
                    Add-Content $certCfg "RequestType = PKCS10"
                }
                Add-Content $certCfg "KeyUsage = 0xa0"
                Add-Content $certCfg "[EnhancedKeyUsageExtension]"
                Add-Content $certCfg "OID=1.3.6.1.5.5.7.3.1"
                Add-Content $certCfg "[Extensions]"
                Add-Content $certCfg $san
                Add-Content $certCfg "Critical=2.5.29.17"


                if ($PScmdlet.ShouldProcess("local", "Creating certificate for $computer")) {
                    Write-Message -Level Output -Message "Running: certreq -new $certCfg $certCsr"
                    $create = certreq -new $certCfg $certCsr
                }

                if ($SelfSigned) {
                    $serial = (($create -Split "Serial Number:" -Split "Subject")[2]).Trim() # D:
                    $storedCert = Get-ChildItem Cert:\LocalMachine\My -Recurse | Where-Object SerialNumber -eq $serial

                    if ($computer.IsLocalHost) {
                        $storedCert | Select-Object * | Select-DefaultView -Property FriendlyName, DnsNameList, Thumbprint, NotBefore, NotAfter, Subject, Issuer
                    }
                } else {
                    if ($PScmdlet.ShouldProcess("local", "Submitting certificate request for $computer to $CaServer\$CaName")) {
                        Write-Message -Level Output -Message "certreq -submit -config `"$CaServer\$CaName`" -attrib $certTemplate $certCsr $certCrt $certPfx"
                        $submit = certreq -submit -config ""$CaServer\$CaName"" -attrib $certTemplate $certCsr $certCrt $certPfx
                    }

                    if ($submit -match "ssued") {
                        Write-Message -Level Output -Message "certreq -accept -machine $certCrt"
                        $null = certreq -accept -machine $certCrt
                        $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
                        $cert.Import($certCrt, $null, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::DefaultKeySet)
                        $storedCert = Get-ChildItem "Cert:\$store\$folder" -Recurse | Where-Object { $_.Thumbprint -eq $cert.Thumbprint }
                    } elseif ($submit) {
                        Write-Message -Level Warning -Message "Something went wrong"
                        Write-Message -Level Warning -Message "$create"
                        Write-Message -Level Warning -Message "$submit"
                        Stop-Function -Message "Failure when attempting to create the cert on $computer. Exception: $_" -ErrorRecord $_ -Target $computer -Continue
                    }

                    if ($Computer.IsLocalHost) {
                        $storedCert | Select-Object * | Select-DefaultView -Property FriendlyName, DnsNameList, Thumbprint, NotBefore, NotAfter, Subject, Issuer
                    }
                }
            }

            if (!$Computer.IsLocalHost) {

                if (!$secondaryNode) {
                    if ($PScmdlet.ShouldProcess("local", "Generating pfx and reading from disk")) {
                        Write-Message -Level Output -Message "Exporting PFX with password to $tempPfx"
                        $certdata = $storedCert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::PFX, $SecurePassword)
                    }

                    if ($PScmdlet.ShouldProcess("local", "Removing cert from disk but keeping it in memory")) {
                        $storedCert | Remove-Item
                    }

                    if ($ClusterInstanceName) { $secondaryNode = $true }
                }

                $scriptblock = {
                    $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
                    $cert.Import($args[0], $args[1], "Exportable,PersistKeySet")

                    $certstore = New-Object System.Security.Cryptography.X509Certificates.X509Store($args[3], $args[2])
                    $certstore.Open('ReadWrite')
                    $certstore.Add($cert)
                    $certstore.Close()
                    Get-ChildItem "Cert:\$($args[2])\$($args[3])" -Recurse | Where-Object { $_.Thumbprint -eq $cert.Thumbprint }
                }

                if ($PScmdlet.ShouldProcess("local", "Connecting to $computer to import new cert")) {
                    try {
                        Invoke-Command2 -ComputerName $computer -Credential $Credential -ArgumentList $certdata, $SecurePassword, $Store, $Folder -ScriptBlock $scriptblock -ErrorAction Stop |
                            Select-DefaultView -Property DnsNameList, Thumbprint, NotBefore, NotAfter, Subject, Issuer
                    } catch {
                        Stop-Function -Message "Issue importing new cert on $computer" -ErrorRecord $_ -Target $computer -Continue
                    }
                }
            }
            if ($PScmdlet.ShouldProcess("local", "Removing all files from $certDir")) {
                try {
                    Remove-Item -Force -Recurse $certDir -ErrorAction SilentlyContinue
                } catch {
                    Stop-Function "Isue removing files from $certDir" -Target $certDir -ErrorRecord $_
                }
            }
        }
    }
}
tools\dbatools\functions\New-DbaConnectionString.ps1
function New-DbaConnectionString {
    <#
    .SYNOPSIS
        Builds or extracts a SQL Server Connection String

    .DESCRIPTION
        Builds or extracts a SQL Server Connection String

        See https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx
        and https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.aspx
        and https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER Credential
        Credential object used to connect to the SQL Server as a different user be it Windows or SQL Server. Windows users are determined by the existence of a backslash, so if you are intending to use an alternative Windows connection instead of a SQL login, ensure it contains a backslash.

    .PARAMETER AccessToken
        Gets or sets the access token for the connection.

    .PARAMETER AppendConnectionString
        Appends to the current connection string. Note that you cannot pass authentication information using this method. Use -SqlInstance and, optionally, -SqlCredential to set authentication information.

    .PARAMETER ApplicationIntent
        Declares the application workload type when connecting to a server. Possible values are ReadOnly and ReadWrite.

    .PARAMETER BatchSeparator
        By default, this is "GO"

    .PARAMETER ClientName
        By default, this command sets the client to "dbatools PowerShell module - dbatools.io - custom connection" if you're doing anything that requires profiling, you can look for this client name. Using -ClientName allows you to set your own custom client.

    .PARAMETER ConnectTimeout
        The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error.

        Valid values are greater than or equal to 0 and less than or equal to 2147483647.

        When opening a connection to a Azure SQL Database, set the connection timeout to 30 seconds.

    .PARAMETER EncryptConnection
        When true, SQL Server uses SSL encryption for all data sent between the client and server if the server has a certificate installed. Recognized values are true, false, yes, and no. For more information, see Connection String Syntax.

        Beginning in .NET Framework 4.5, when TrustServerCertificate is false and Encrypt is true, the server name (or IP address) in a SQL Server SSL certificate must exactly match the server name (or IP address) specified in the connection string. Otherwise, the connection attempt will fail. For information about support for certificates whose subject starts with a wildcard character (*), see Accepted wildcards used by server certificates for server authentication.

    .PARAMETER FailoverPartner
        The name of the failover partner server where database mirroring is configured.

        If the value of this key is "", then Initial Catalog must be present, and its value must not be "".

        The server name can be 128 characters or less.

        If you specify a failover partner but the failover partner server is not configured for database mirroring and the primary server (specified with the Server keyword) is not available, then the connection will fail.

        If you specify a failover partner and the primary server is not configured for database mirroring, the connection to the primary server (specified with the Server keyword) will succeed if the primary server is available.

    .PARAMETER IsActiveDirectoryUniversalAuth
        Azure related

    .PARAMETER LockTimeout
        Sets the time in seconds required for the connection to time out when the current transaction is locked.

    .PARAMETER MaxPoolSize
        Sets the maximum number of connections allowed in the connection pool for this specific connection string.

    .PARAMETER MinPoolSize
        Sets the minimum number of connections allowed in the connection pool for this specific connection string.

    .PARAMETER MultipleActiveResultSets
        When used, an application can maintain multiple active result sets (MARS). When false, an application must process or cancel all result sets from one batch before it can execute any other batch on that connection.

    .PARAMETER MultiSubnetFailover
        If your application is connecting to an AlwaysOn availability group (AG) on different subnets, setting MultiSubnetFailover provides faster detection of and connection to the (currently) active server. For more information about SqlClient support for Always On Availability Groups

    .PARAMETER NetworkProtocol
        Connect explicitly using 'TcpIp','NamedPipes','Multiprotocol','AppleTalk','BanyanVines','Via','SharedMemory' and 'NWLinkIpxSpx'

    .PARAMETER NonPooledConnection
        Request a non-pooled connection

    .PARAMETER PacketSize
        Sets the size in bytes of the network packets used to communicate with an instance of SQL Server. Must match at server.

    .PARAMETER PooledConnectionLifetime
        When a connection is returned to the pool, its creation time is compared with the current time, and the connection is destroyed if that time span (in seconds) exceeds the value specified by Connection Lifetime. This is useful in clustered configurations to force load balancing between a running server and a server just brought online.

        A value of zero (0) causes pooled connections to have the maximum connection timeout.

    .PARAMETER SqlExecutionModes
        The SqlExecutionModes enumeration contains values that are used to specify whether the commands sent to the referenced connection to the server are executed immediately or saved in a buffer.

        Valid values include CaptureSql, ExecuteAndCaptureSql and ExecuteSql.

    .PARAMETER StatementTimeout
        Sets the number of seconds a statement is given to run before failing with a time-out error.

    .PARAMETER TrustServerCertificate
        Sets a value that indicates whether the channel will be encrypted while bypassing walking the certificate chain to validate trust.

    .PARAMETER WorkstationId
        Sets the name of the workstation connecting to SQL Server.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .NOTES
        Tags: Connection, Connect, ConnectionString
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaConnectionString

    .EXAMPLE
        PS C:\> New-DbaConnectionString -SqlInstance sql2014

        Creates a connection string that connects using Windows Authentication

    .EXAMPLE
        PS C:\> Connect-DbaInstance -SqlInstance sql2016 | New-DbaConnectionString

        Builds a connected SMO object using Connect-DbaInstance then extracts and displays the connection string

    .EXAMPLE
        PS C:\> $wincred = Get-Credential ad\sqladmin
        PS C:\> New-DbaConnectionString -SqlInstance sql2014 -Credential $wincred

        Creates a connection string that connects using alternative Windows credentials

    .EXAMPLE
        PS C:\> $sqlcred = Get-Credential sqladmin
        PS C:\> $server = New-DbaConnectionString -SqlInstance sql2014 -Credential $sqlcred

        Login to sql2014 as SQL login sqladmin.

    .EXAMPLE
        PS C:\> $server = New-DbaConnectionString -SqlInstance sql2014 -ClientName "mah connection"

        Creates a connection string that connects using Windows Authentication and uses the client name "mah connection". So when you open up profiler or use extended events, you can search for "mah connection".

    .EXAMPLE
        PS C:\> $server = New-DbaConnectionString -SqlInstance sql2014 -AppendConnectionString "Packet Size=4096;AttachDbFilename=C:\MyFolder\MyDataFile.mdf;User Instance=true;"

        Creates a connection string that connects to sql2014 using Windows Authentication, then it sets the packet size (this can also be done via -PacketSize) and other connection attributes.

    .EXAMPLE
        PS C:\> $server = New-DbaConnectionString -SqlInstance sql2014 -NetworkProtocol TcpIp -MultiSubnetFailover

        Creates a connection string with Windows Authentication that uses TCPIP and has MultiSubnetFailover enabled.

    .EXAMPLE
        PS C:\> $connstring = New-DbaConnectionString sql2016 -ApplicationIntent ReadOnly

        Creates a connection string with ReadOnly ApplicationIntent.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("SqlCredential")]
        [PSCredential]$Credential,
        [string]$AccessToken,
        [ValidateSet('ReadOnly', 'ReadWrite')]
        [string]$ApplicationIntent,
        [string]$BatchSeparator,
        [string]$ClientName = "custom connection",
        [int]$ConnectTimeout,
        [switch]$EncryptConnection,
        [string]$FailoverPartner,
        [switch]$IsActiveDirectoryUniversalAuth,
        [int]$LockTimeout,
        [int]$MaxPoolSize,
        [int]$MinPoolSize,
        [switch]$MultipleActiveResultSets,
        [switch]$MultiSubnetFailover,
        [ValidateSet('TcpIp', 'NamedPipes', 'Multiprotocol', 'AppleTalk', 'BanyanVines', 'Via', 'SharedMemory', 'NWLinkIpxSpx')]
        [string]$NetworkProtocol,
        [switch]$NonPooledConnection,
        [int]$PacketSize,
        [int]$PooledConnectionLifetime,
        [ValidateSet('CaptureSql', 'ExecuteAndCaptureSql', 'ExecuteSql')]
        [string]$SqlExecutionModes,
        [int]$StatementTimeout,
        [switch]$TrustServerCertificate,
        [string]$WorkstationId,
        [string]$AppendConnectionString
    )

    process {
        foreach ($instance in $sqlinstance) {
            if ($Pscmdlet.ShouldProcess($instance, "Making a new Connection String")) {
                if ($instance.GetType() -eq [Microsoft.SqlServer.Management.Smo.Server]) {
                    return $instance.ConnectionContext.ConnectionString
                } else {
                    $guid = [System.Guid]::NewGuid()
                    $server = New-Object Microsoft.SqlServer.Management.Smo.Server $guid

                    if ($AppendConnectionString) {
                        $connstring = $server.ConnectionContext.ConnectionString
                        $server.ConnectionContext.ConnectionString = "$connstring;$appendconnectionstring"
                        $server.ConnectionContext.ConnectionString
                    } else {

                        $server.ConnectionContext.ApplicationName = $clientname

                        if ($AccessToken) { $server.ConnectionContext.AccessToken = $AccessToken }
                        if ($BatchSeparator) { $server.ConnectionContext.BatchSeparator = $BatchSeparator }
                        if ($ConnectTimeout) { $server.ConnectionContext.ConnectTimeout = $ConnectTimeout }
                        if ($Database) { $server.ConnectionContext.DatabaseName = $Database }
                        if ($EncryptConnection) { $server.ConnectionContext.EncryptConnection = $true }
                        if ($IsActiveDirectoryUniversalAuth) { $server.ConnectionContext.IsActiveDirectoryUniversalAuth = $true }
                        if ($LockTimeout) { $server.ConnectionContext.LockTimeout = $LockTimeout }
                        if ($MaxPoolSize) { $server.ConnectionContext.MaxPoolSize = $MaxPoolSize }
                        if ($MinPoolSize) { $server.ConnectionContext.MinPoolSize = $MinPoolSize }
                        if ($MultipleActiveResultSets) { $server.ConnectionContext.MultipleActiveResultSets = $true }
                        if ($NetworkProtocol) { $server.ConnectionContext.NetworkProtocol = $NetworkProtocol }
                        if ($NonPooledConnection) { $server.ConnectionContext.NonPooledConnection = $true }
                        if ($PacketSize) { $server.ConnectionContext.PacketSize = $PacketSize }
                        if ($PooledConnectionLifetime) { $server.ConnectionContext.PooledConnectionLifetime = $PooledConnectionLifetime }
                        if ($StatementTimeout) { $server.ConnectionContext.StatementTimeout = $StatementTimeout }
                        if ($SqlExecutionModes) { $server.ConnectionContext.SqlExecutionModes = $SqlExecutionModes }
                        if ($TrustServerCertificate) { $server.ConnectionContext.TrustServerCertificate = $true }
                        if ($WorkstationId) { $server.ConnectionContext.WorkstationId = $WorkstationId }

                        $connstring = $server.ConnectionContext.ConnectionString
                        if ($MultiSubnetFailover) { $connstring = "$connstring;MultiSubnetFailover=True" }
                        if ($FailoverPartner) { $connstring = "$connstring;Failover Partner=$FailoverPartner" }
                        if ($ApplicationIntent) { $connstring = "$connstring;ApplicationIntent=$ApplicationIntent;" }

                        if ($connstring -ne $server.ConnectionContext.ConnectionString) {
                            $server.ConnectionContext.ConnectionString = $connstring
                        }
                        if ($null -ne $Credential.username) {
                            $username = ($Credential.username).TrimStart("\")

                            if ($username -like "*\*") {
                                $username = $username.Split("\")[1]
                                #Variable marked as unused by PSScriptAnalyzer
                                #$authtype = "Windows Authentication with Credential"
                                $server.ConnectionContext.LoginSecure = $true
                                $server.ConnectionContext.ConnectAsUser = $true
                                $server.ConnectionContext.ConnectAsUserName = $username
                                $server.ConnectionContext.ConnectAsUserPassword = ($Credential).GetNetworkCredential().Password
                            } else {
                                #Variable marked as unused by PSScriptAnalyzer
                                #$authtype = "SQL Authentication"
                                $server.ConnectionContext.LoginSecure = $false
                                $server.ConnectionContext.set_Login($username)
                                $server.ConnectionContext.set_SecurePassword($Credential.Password)
                            }
                        }

                        ($server.ConnectionContext.ConnectionString).Replace($guid, $SqlInstance)
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias New-DbaSqlConnectionString
    }
}
tools\dbatools\functions\New-DbaConnectionStringBuilder.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function New-DbaConnectionStringBuilder {
    <#
    .SYNOPSIS
        Returns a System.Data.SqlClient.SqlConnectionStringBuilder with the string specified

    .DESCRIPTION
        Creates a System.Data.SqlClient.SqlConnectionStringBuilder from a connection string.

    .PARAMETER ConnectionString
        A Connection String

    .PARAMETER ApplicationName
        The application name to tell SQL Server the connection is associated with.

    .PARAMETER DataSource
        The Sql Server to connect to.

    .PARAMETER InitialCatalog
        The initial database on the server to connect to.

    .PARAMETER IntegratedSecurity
        Set to true to use windows authentication.

    .PARAMETER UserName
        Sql User Name to connect with.

    .PARAMETER Password
        Password to use to connect with.

    .PARAMETER MultipleActiveResultSets
        Enable Multiple Active Result Sets.

    .PARAMETER ColumnEncryptionSetting
        Enable Always Encrypted.

    .PARAMETER WorkstationID
        Set the Workstation Id that is associated with the connection.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .NOTES
        Tags: SqlBuild, ConnectionString, Connection
        Author: zippy1981 | Chrissy LeMaire (@cl)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaConnectionStringBuilder

    .EXAMPLE
        PS C:\> New-DbaConnectionStringBuilder

        Returns an empty ConnectionStringBuilder

    .EXAMPLE
        PS C:\> "Data Source=localhost,1433;Initial Catalog=AlwaysEncryptedSample;UID=sa;PWD=alwaysB3Encrypt1ng;Application Name=Always Encrypted Sample MVC App;Column Encryption Setting=enabled" | New-DbaConnectionStringBuilder

        Returns a connection string builder that can be used to connect to the local sql server instance on the default port.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "")]
    param (
        [Parameter(ValueFromPipeline)]
        [string[]]$ConnectionString = "",
        [string]$ApplicationName = "dbatools Powershell Module",
        [string]$DataSource = $null,
        [string]$InitialCatalog = $null,
        [Nullable[bool]]$IntegratedSecurity = $null,
        [string]$UserName = $null,
        # No point in securestring here, the memory is never stored securely in memory.
        [string]$Password = $null,
        [Alias('MARS')]
        [switch]$MultipleActiveResultSets,
        [Alias('AlwaysEncrypted')]
        [Data.SqlClient.SqlConnectionColumnEncryptionSetting]$ColumnEncryptionSetting =
        [Data.SqlClient.SqlConnectionColumnEncryptionSetting]::Enabled,
        [string]$WorkstationId = $env:COMPUTERNAME
    )
    process {
        foreach ($cs in $ConnectionString) {
            if ($Pscmdlet.ShouldProcess($cs, "Creating new connection string")) {
                $builder = New-Object Data.SqlClient.SqlConnectionStringBuilder $cs
                if ($builder.ApplicationName -eq ".Net SqlClient Data Provider") {
                    $builder['Application Name'] = $ApplicationName
                }
                if (![string]::IsNullOrWhiteSpace($DataSource)) {
                    $builder['Data Source'] = $DataSource
                }
                if (![string]::IsNullOrWhiteSpace($InitialCatalog)) {
                    $builder['Initial Catalog'] = $InitialCatalog
                }
                if (![string]::IsNullOrWhiteSpace($IntegratedSecurity)) {
                    $builder['Integrated Security'] = $IntegratedSecurity
                }
                if (![string]::IsNullOrWhiteSpace($UserName)) {
                    $builder["User ID"] = $UserName
                }
                if (![string]::IsNullOrWhiteSpace($Password)) {
                    $builder['Password'] = $Password
                }
                if (![string]::IsNullOrWhiteSpace($WorkstationId)) {
                    $builder['Workstation ID'] = $WorkstationId
                }
                if ($MultipleActiveResultSets -eq $true) {
                    $builder['MultipleActiveResultSets'] = $true
                }
                if ($ColumnEncryptionSetting -eq [Data.SqlClient.SqlConnectionColumnEncryptionSetting]::Enabled) {
                    $builder['Column Encryption Setting'] = [Data.SqlClient.SqlConnectionColumnEncryptionSetting]::Enabled
                }
                $builder
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias New-DbaSqlConnectionStringBuilder
    }
}
tools\dbatools\functions\New-DbaCredential.ps1
function New-DbaCredential {
    <#
    .SYNOPSIS
        Creates a new SQL Server credential

    .DESCRIPTION
        Creates a new credential

    .PARAMETER SqlInstance
        The target SQL Server(s)

    .PARAMETER SqlCredential
        Allows you to login to SQL Server using alternative credentials

    .PARAMETER Name
        The Credential name

    .PARAMETER Identity
        The Credential Identity

    .PARAMETER SecurePassword
        Secure string used to authenticate the Credential Identity

    .PARAMETER MappedClassType
        Sets the class associated with the credential.

    .PARAMETER ProviderName
        Sets the name of the provider

    .PARAMETER Force
        If credential exists, drop and recreate

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Certificate
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> New-DbaCredential -SqlInstance Server1

        You will be prompted to securely enter your password, then a credential will be created in the master database on server1 if it does not exist.

    .EXAMPLE
        PS C:\> New-DbaCredential -SqlInstance Server1 -Confirm:$false

        Suppresses all prompts to install but prompts to securely enter your password and creates a credential on Server1.

    .EXAMPLE
        PS C:\> New-DbaCredential -SqlInstance Server1 -Name AzureBackupBlobStore -Identity '<Azure Storage Account Name>' -SecurePassword (ConvertTo-SecureString '<Azure Storage Account Access Key>' -AsPlainText -Force)

        Create credential on SQL Server 2012 CU2, SQL Server 2014 for use with BACKUP TO URL.
        CredentialIdentity needs to be supplied with the Azure Storage Account Name.
        Password needs to be one of the Access Keys for the account.

    .EXAMPLE
        PS C:\> New-DbaCredential -SqlInstance Server1 -Name 'https://<Azure Storage Account Name>.blob.core.windows.net/<Blob Store Container Name>' -Identity 'SHARED ACCESS SIGNATURE' -SecurePassword (ConvertTo-SecureString '<Shared Access Token>' -AsPlainText -Force)

        Create Credential on SQL Server 2016 or higher for use with BACKUP TO URL.
        Name has to be the full URL for the blob store container that will be the backup target.
        Password needs to be passed the Shared Access Token (SAS Key).

    #>
    [CmdletBinding(SupportsShouldProcess)] #, ConfirmImpact = "High"
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Name = $Identity,
        [parameter(Mandatory)]
        [Alias("CredentialIdentity")]
        [string[]]$Identity,
        [Alias("Password")]
        [Security.SecureString]$SecurePassword,
        [ValidateSet('CryptographicProvider', 'None')]
        [string]$MappedClassType = "None",
        [string]$ProviderName,
        [switch]$Force,
        [switch]$EnableException
    )

    begin {
        $mappedclass = switch ($MappedClassType) {
            "CryptographicProvider" { 1 }
            "None" { 0 }
        }
    }

    process {
        if (!$SecurePassword) {
            Read-Host -AsSecureString -Prompt "Enter the credential password"
        }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            foreach ($cred in $Identity) {
                $currentcred = $server.Credentials[$name]

                if ($currentcred) {
                    if ($force) {
                        Write-Message -Level Verbose -Message "Dropping credential $name"
                        $currentcred.Drop()
                    } else {
                        Stop-Function -Message "Credential exists and Force was not specified" -Target $name -Continue
                    }
                }


                if ($Pscmdlet.ShouldProcess($SqlInstance, "Creating credential for database '$cred' on $instance")) {
                    try {
                        $credential = New-Object Microsoft.SqlServer.Management.Smo.Credential -ArgumentList $server, $name
                        $credential.MappedClassType = $mappedclass
                        $credential.ProviderName = $ProviderName
                        $credential.Create($Identity, $SecurePassword)

                        Add-Member -Force -InputObject $credential -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
                        Add-Member -Force -InputObject $credential -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                        Add-Member -Force -InputObject $credential -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName

                        Select-DefaultView -InputObject $credential -Property ComputerName, InstanceName, SqlInstance, Name, Identity, CreateDate, MappedClassType, ProviderName
                    } catch {
                        Stop-Function -Message "Failed to create credential in $cred on $instance. Exception: $($_.Exception.InnerException)" -Target $credential -InnerErrorRecord $_ -Continue
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\New-DbaDacOption.ps1
function New-DbaDacOption {
    <#
    .SYNOPSIS
        Creates a new Microsoft.SqlServer.Dac.DacExtractOptions/DacExportOptions object depending on the chosen Type

    .DESCRIPTION
        Creates a new Microsoft.SqlServer.Dac.DacExtractOptions/DacExportOptions object that can be used during DacPackage extract. Basically saves you the time from remembering the SMO assembly name ;)

        See:
        https://msdn.microsoft.com/en-us/library/microsoft.sqlserver.dac.dacexportoptions.aspx
        https://msdn.microsoft.com/en-us/library/microsoft.sqlserver.dac.dacextractoptions.aspx
        for more information

    .PARAMETER Type
        Selecting the type of the export: Dacpac (default) or Bacpac.

    .PARAMETER Action
        Choosing an intended action: Publish or Export.

    .PARAMETER PublishXml
        Specifies the publish profile which will include options and sqlCmdVariables.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration, Database, Dacpac
        Author: Kirill Kravtsov (@nvarscar), nvarscar.wordpress.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaDacOption

    .EXAMPLE
        PS C:\> $options = New-DbaDacOption -Type Dacpac -Action Export
        PS C:\> $options.ExtractAllTableData = $true
        PS C:\> $options.CommandTimeout = 0
        PS C:\> Export-DbaDacPackage -SqlInstance sql2016 -Database DB1 -Options $options

        Uses DacOption object to set the CommandTimeout to 0 then extracts the dacpac for SharePoint_Config on sql2016 to C:\temp\SharePoint_Config.dacpac including all table data.

    .EXAMPLE
        PS C:\> $options = New-DbaDacOption -Type Dacpac -Action Publish
        PS C:\> $options.DeployOptions.DropObjectsNotInSource = $true
        PS C:\> Publish-DbaDacPackage -SqlInstance sql2016 -Database DB1 -Options $options -Path c:\temp\db.dacpac

        Uses DacOption object to set Deployment Options and publish the db.dacpac dacpac file as DB1 on sql2016

    #>
    [CmdletBinding(SupportsShouldProcess)]
    Param (
        [ValidateSet('Dacpac', 'Bacpac')]
        [string]$Type = 'Dacpac',
        [Parameter(Mandatory)]
        [ValidateSet('Publish', 'Export')]
        [string]$Action,
        [string]$PublishXml,
        [switch]$EnableException
    )
    if ($PScmdlet.ShouldProcess("$type", "Creating New DacOptions of $action")) {
        if (-not $script:core) {
            $dacfxPath = "$script:PSModuleRoot\bin\smo\Microsoft.SqlServer.Dac.dll"
            if ((Test-Path $dacfxPath) -eq $false) {
                Stop-Function -Message 'Dac Fx library not found.' -EnableException $EnableException
                return
            } else {
                try {
                    Add-Type -Path $dacfxPath
                    Write-Message -Level Verbose -Message "Dac Fx loaded."
                } catch {
                    Stop-Function -Message 'No usable version of Dac Fx found.' -ErrorRecord $_
                    return
                }
            }
        }
        
        # Pick proper option object depending on type and action
        if ($Action -eq 'Export') {
            if ($Type -eq 'Dacpac') {
                New-Object -TypeName Microsoft.SqlServer.Dac.DacExtractOptions
            } elseif ($Type -eq 'Bacpac') {
                New-Object -TypeName Microsoft.SqlServer.Dac.DacExportOptions
            }
        } elseif ($Action -eq 'Publish') {
            if ($Type -eq 'Dacpac') {
                $output = New-Object -TypeName Microsoft.SqlServer.Dac.PublishOptions
                if ($PublishXml) {
                    try {
                        $dacProfile = [Microsoft.SqlServer.Dac.DacProfile]::Load($PublishXml)
                        $output.DeployOptions = $dacProfile.DeployOptions
                    } catch {
                        Stop-Function -Message "Could not load profile." -ErrorRecord $_
                        return
                    }
                } else {
                    $output.DeployOptions = New-Object -TypeName Microsoft.SqlServer.Dac.DacDeployOptions
                }
                $output.GenerateDeploymentScript = $false
                $output
            } elseif ($Type -eq 'Bacpac') {
                New-Object -TypeName Microsoft.SqlServer.Dac.DacImportOptions
            }
        }
    }
}
tools\dbatools\functions\New-DbaDacProfile.ps1
function New-DbaDacProfile {
    <#
    .SYNOPSIS
        Creates a new Publish Profile.

    .DESCRIPTION
        The New-DbaDacProfile command generates a standard publish profile xml file that can be used by the DacFx (this and everything else) to control the deployment of your dacpac
        This generates a standard template XML which is enough to dpeloy a dacpac but it is highly recommended that you add additional options to the publish profile.
        If you use Visual Studio you can open a publish.xml file and use the ui to edit the file -
        To create a new file, right click on an SSDT project, choose "Publish" then "Load Profile" and load your profile or create a new one.
        Once you have loaded it in Visual Studio, clicking advanced shows you the list of options available to you.
        For a full list of options that you can add to the profile, google "sqlpackage.exe command line switches" or (https://msdn.microsoft.com/en-us/library/hh550080(v=vs.103).aspx)

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Alternatively, you can provide a ConnectionString.

    .PARAMETER SqlCredential
        Allows you to login to servers using alternative logins instead Integrated, accepts Credential object created by Get-Credential

    .PARAMETER Database
        The database name you are targeting

    .PARAMETER ConnectionString
        The connection string to the database you are upgrading.

        Alternatively, you can provide a SqlInstance (and optionally SqlCredential) and the script will connect and generate the connectionstring.

    .PARAMETER Path
        The directory where you would like to save the profile xml file(s).

    .PARAMETER PublishOptions
        Optional hashtable to set publish options. Key/value pairs in the hashtable get converted to strings of "<key>value</key>".

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Dacpac
        Author: Richie lee (@richiebzzzt)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaDacProfile

    .EXAMPLE
        PS C:\> New-DbaDacProfile -SqlInstance sql2017 -SqlCredential ad\sqldba -Database WorldWideImporters -Path C:\temp

        In this example, a prompt will appear for alternative credentials, then a connection will be made to sql2017. Using that connection,
        the ConnectionString will be extracted and used within the Publish Profile XML file which will be created at C:\temp\sql2017-WorldWideImporters-publish.xml

    .EXAMPLE
        PS C:\> New-DbaDacProfile -Database WorldWideImporters -Path C:\temp -ConnectionString "SERVER=(localdb)\MSSQLLocalDB;Integrated Security=True;Database=master"

        In this example, no connections are made, and a Publish Profile XML would be created at C:\temp\localdb-MSSQLLocalDB-WorldWideImporters-publish.xml

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Parameter(Mandatory)]
        [string[]]$Database,
        [string]$Path = "$home\Documents",
        [string[]]$ConnectionString,
        [hashtable]$PublishOptions,
        [switch]$EnableException
    )
    begin {
        if ((Test-Bound -Not -ParameterName SqlInstance) -and (Test-Bound -Not -ParameterName ConnectionString)) {
            Stop-Function -Message "You must specify either SqlInstance or ConnectionString"
        }

        if (-not (Test-Path $Path)) {
            Stop-Function -Message "$Path doesn't exist or access denied"
        }

        if ((Get-Item $path) -isnot [System.IO.DirectoryInfo]) {
            Stop-Function -Message "Path must be a directory"
        }

        function Convert-HashtableToXMLString($PublishOptions) {
            $return = @()
            if ($PublishOptions) {
                $PublishOptions.GetEnumerator() | ForEach-Object {
                    $key = $PSItem.Key.ToString()
                    $value = $PSItem.Value.ToString()
                    $return += "<$key>$value</$key>"
                }
            }
            $return | Out-String
        }

        function Get-Template ($db, $connstring) {
            "<?xml version=""1.0"" ?>
            <Project ToolsVersion=""14.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
              <PropertyGroup>
                <TargetDatabaseName>{0}</TargetDatabaseName>
                <TargetConnectionString>{1}</TargetConnectionString>
                <ProfileVersionNumber>1</ProfileVersionNumber>
                {2}
              </PropertyGroup>
            </Project>" -f $db[0], $connstring, $(Convert-HashtableToXMLString($PublishOptions))
        }

        function Get-ServerName ($connstring) {
            $builder = New-Object System.Data.Common.DbConnectionStringBuilder
            $builder.set_ConnectionString($connstring)
            $instance = $builder['data source']

            if (-not $instance) {
                $instance = $builder['server']
            }

            return $instance.ToString().Replace('\', '--')
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }

        foreach ($instance in $sqlinstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $ConnectionString += $server.ConnectionContext.ConnectionString.Replace(';Application Name="dbatools PowerShell module - dbatools.io"', '')

        }

        foreach ($connstring in $ConnectionString) {
            foreach ($db in $Database) {
                if ($Pscmdlet.ShouldProcess($db, "Creating new DAC Profile")) {
                    $profileTemplate = Get-Template $db, $connstring
                    $instancename = Get-ServerName $connstring

                    try {
                        $server = [DbaInstance]($instancename.ToString().Replace('--', '\'))
                        $PublishProfile = Join-Path $Path "$($instancename.Replace('--','-'))-$db-publish.xml" -ErrorAction Stop
                        Write-Message -Level Verbose -Message "Writing to $PublishProfile"
                        $profileTemplate | Out-File $PublishProfile -ErrorAction Stop
                        [pscustomobject]@{
                            ComputerName     = $server.ComputerName
                            InstanceName     = $server.InstanceName
                            SqlInstance      = $server.FullName
                            Database         = $db
                            FileName         = $PublishProfile
                            ConnectionString = $connstring
                            ProfileTemplate  = $profileTemplate
                        } | Select-DefaultView -ExcludeProperty ComputerName, InstanceName, ProfileTemplate
                    } catch {
                        Stop-Function -ErrorRecord $_ -Message "Failure" -Target $instancename -Continue
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias New-DbaPublishProfile
    }
}
tools\dbatools\functions\New-DbaDatabase.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function New-DbaDatabase {
    <#
    .SYNOPSIS
        Creates a new database

    .DESCRIPTION
        This command creates a new database.

        It allows creation with multiple files, and sets all growth settings to be fixed size rather than percentage growth.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Name
        The name of the new database or databases to be created.

    .PARAMETER DataFilePath
        The location that data files will be placed, otherwise the default SQL Server data path will be used.

    .PARAMETER LogFilePath
        The location the log file will be placed, otherwise the default SQL Server log path will be used.

    .PARAMETER Collation
        The database collation, if not supplied the default server collation will be used.

    .PARAMETER Recoverymodel
        The recovery model for the database, if not supplied the recovery model from the model database will be used.

    .PARAMETER Owner
        The login that will be used as the database owner.

    .PARAMETER PrimaryFilesize
        The size in MB for the Primary file. If this is less than the primary file size for the model database, then the model size will be used instead.

    .PARAMETER PrimaryFileGrowth
        The size in MB that the Primary file will autogrow by.

    .PARAMETER PrimaryFileMaxSize
        The maximum permitted size in MB for the Primary File. If this is less the primary file size for the model database, then the model size will be used instead.

    .PARAMETER LogSize
        The size in MB that the Transaction log will be created.

    .PARAMETER LogGrowth
        The amount in MB that the log file will be set to autogrow by.

    .PARAMETER SecondaryFileCount
        The number of files to create in the Secondary filegroup for the database.

    .PARAMETER SecondaryFilesize
        The size in MB of the files to be added to the Secondary filegroup. Each file added will be created with this size setting.

    .PARAMETER SecondaryFileMaxSize
        The maximum permitted size in MB for the Secondary data files to grow to. Each file added will be created with this max size setting.

    .PARAMETER SecondaryFileGrowth
        The amount in MB that the Secondary files will be set to autogrow by. Use 0 for no growth allowed. Each file added will be created with this growth setting.

    .PARAMETER DefaultFileGroup
        Sets the default file group. Either primary or secondary.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database
        Author: Matthew Darwin (@evoDBA, naturalselectiondba.wordpress.com)  | Chrissy LeMaire (@cl)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaDatabase

    .EXAMPLE
        New-DbaDatabase -SqlInstance sql1

        Creates a randomly named database (random-N) on instance sql1

    .EXAMPLE
        New-DbaDatabase -SqlInstance sql1 -Name dbatools, dbachecks

        Creates a database named dbatools and a database named dbachecks on sql1

    .EXAMPLE
        New-DbaDatabase -SqlInstance sql1, sql2, sql3 -Name multidb, multidb2 -SecondaryFilesize 20 -SecondaryFileGrowth 20 -LogSize 20 -LogGrowth 20

        Creates two databases, multidb and multidb2, on 3 instances (sql1, sql2 and sql3) and sets the secondary data file size to 20MB, the file growth to 20MB and the log growth to 20MB for each

    .EXAMPLE
        New-DbaDatabase -SqlInstance sql1 -Name nondefault -DataFilePath M:\Data -LogFilePath 'L:\Logs with spaces' -SecondaryFileCount 2

        Creates a database named nondefault and places data files in in the M:\data directory and log files in "L:\Logs with spaces".

        Creates a secondary group with 2 files in the Secondary filegroup.

          #>
    [Cmdletbinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param
    (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Name,
        [string]$Collation,
        [string]$Recoverymodel,
        [string]$Owner,
        [string]$DataFilePath,
        [string]$LogFilePath,
        [int32]$PrimaryFilesize,
        [int32]$PrimaryFileGrowth,
        [int32]$PrimaryFileMaxSize,
        [int32]$LogSize,
        [int32]$LogGrowth,
        [int32]$SecondaryFilesize,
        [int32]$SecondaryFileGrowth,
        [int32]$SecondaryFileMaxSize,
        [int32]$SecondaryFileCount,
        [ValidateSet('Primary', 'Secondary')]
        [string]$DefaultFileGroup,
        [switch]$EnableException
    )

    begin {
        # do some checks to see if the advanced config settings will be invoked
        if (Test-Bound -ParameterName DataFilePath, LogFilePath, DefaultFileGroup) {
            $advancedconfig = $true
        }

        if (Test-Bound -ParameterName PrimaryFilesize, PrimaryFileGrowth, PrimaryFileMaxSize) {
            $advancedconfig = $true
        }

        if (Test-Bound -ParameterName LogSize, LogGrowth) {
            $advancedconfig = $true
        }

        if (Test-Bound -ParameterName SecondaryFilesize, SecondaryFileMaxSize, SecondaryFileGrowth, SecondaryFileCount) {
            $advancedconfig = $true
        }

        if ($advancedconfig) {
            Write-Message -Message "Advanced data file configuration will be invoked" -Level Verbose
        }
    }

    process {
        if (Test-FunctionInterrupt) {
            return
        }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($advancedconfig -and $server.VersionMajor -eq 8) {
                Stop-Function -Message "Advanced configuration options are not available to SQL Server 2000. Aborting creation of database on $instance" -Target $instance -Continue
            }

            if (-not (Test-Bound -ParameterName Name)) {
                $Name = "random-$(Get-Random)"
            }

            if (-not (Test-Bound -ParameterName DataFilePath)) {
                $DataFilePath = (Get-DbaDefaultPath -SqlInstance $server).Data
            }

            if (-not (Test-Bound -ParameterName LogFilePath)) {
                $LogFilePath = (Get-DbaDefaultPath -SqlInstance $server).Log
            }

            if (-not (Test-DbaPath -SqlInstance $server -Path $LogFilePath)) {
                try {
                    Write-Message -Message "Creating directory $LogFilePath" -Level Verbose
                    $null = New-DbaDirectory -SqlInstance $server -Path $LogFilePath -EnableException
                } catch {
                    Stop-Function -Message "Error creating log file directory $LogFilePath" -Target $instance -Continue
                }
            }

            if (-not (Test-DbaPath -SqlInstance $server -Path $DataFilePath)) {
                try {
                    Write-Message -Message "Creating directory $DataFilePath" -Level Verbose
                    $null = New-DbaDirectory -SqlInstance $server -Path $DataFilePath -EnableException
                } catch {
                    Stop-Function -Message "Error creating secondary file directory $DataFilePath on $instance" -Target $instance -Continue
                }
            }

            Write-Message -Message "Set local data path to $DataFilePath and local log path to $LogFilePath" -Level Verbose

            foreach ($dbname in $Name) {
                if ($server.Databases[$dbname].Name) {
                    Stop-Function -Message "Database $dbname already exists on $instance" -Target $instance -Continue
                }

                try {
                    Write-Message -Message "Creating smo object for new database $dbname" -Level Verbose
                    $newdb = New-Object Microsoft.SqlServer.Management.Smo.Database($server, $dbname)
                } catch {
                    Stop-Function -Message "Error creating database object for $dbname on server $server" -ErrorRecord $_ -Target $instance -Continue
                }

                if ($Collation) {
                    Write-Message -Message "Setting collation to $Collation" -Level Verbose
                    $newdb.Collation = $Collation
                }

                if ($Recoverymodel) {
                    Write-Message -Message "Setting recovery model to $Recoverymodel" -Level Verbose
                    $newdb.Recoverymodel = $Recoverymodel
                }

                if ($advancedconfig) {
                    try {
                        Write-Message -Message "Creating PRIMARY filegroup" -Level Verbose
                        $primaryfg = New-Object Microsoft.SqlServer.Management.Smo.Filegroup($newdb, "PRIMARY")
                        $newdb.Filegroups.Add($primaryfg)
                    } catch {
                        Stop-Function -Message "Error creating Primary filegroup object" -ErrorRecord $_ -Target $instance -Continue
                    }

                    #add the primary file
                    try {
                        $primaryfilename = $dbname + "_PRIMARY"
                        Write-Message -Message "Creating file name $primaryfilename in filegroup PRIMARY" -Level Verbose

                        #check the size of the modeldev file; if larger than our $PrimaryFilesize setting use that instead
                        if ($server.Databases["model"].FileGroups["PRIMARY"].Files["modeldev"].Size -gt ($PrimaryFilesize * 1024)) {
                            Write-Message -Message "model database modeldev larger than our the PrimaryFilesize so using modeldev size for Primary file" -Level Verbose
                            $PrimaryFilesize = ($server.Databases["model"].FileGroups["PRIMARY"].Files["modeldev"].Size / 1024)
                            if ($PrimaryFilesize -gt $PrimaryFileMaxSize) {
                                Write-Message -Message "Resetting Primary File Max size to be the new Primary File Size setting" -Level Verbose
                                $PrimaryFileMaxSize = $PrimaryFilesize
                            }
                        }

                        #create the filegroup object
                        $primaryfile = New-Object Microsoft.SqlServer.Management.Smo.DataFile($primaryfg, $primaryfilename)
                        $primaryfile.FileName = $DataFilePath + "\" + $primaryfilename + ".mdf"
                        $primaryfile.IsPrimaryFile = $true

                        if (Test-Bound -ParameterName PrimaryFilesize) {
                            $primaryfile.Size = ($PrimaryFilesize * 1024)
                        }
                        if (Test-Bound -ParameterName PrimaryFileGrowth) {
                            $primaryfile.Growth = ($PrimaryFileGrowth * 1024)
                            $primaryfile.GrowthType = "KB"
                        }
                        if (Test-Bound -ParameterName PrimaryFileMaxSize) {
                            $primaryfile.MaxSize = ($PrimaryFileMaxSize * 1024)
                        }

                        #add the file to the filegroup
                        $primaryfg.Files.Add($primaryfile)
                    } catch {
                        Stop-Function -Message "Error adding file to Primary filegroup" -ErrorRecord $_ -Target $instance -Continue
                    }

                    try {
                        $logname = $dbname + "_Log"
                        Write-Message -Message "Creating log $logname" -Level Verbose

                        #check the size of the modellog file; if larger than our $LogSize setting use that instead
                        if ($server.Databases["model"].LogFiles["modellog"].Size -gt ($LogSize * 1024)) {
                            Write-Message -Message "model database modellog larger than our the LogSize so using modellog size for Log file size" -Level Verbose
                            $LogSize = ($server.Databases["model"].LogFiles["modellog"].Size / 1024)
                        }

                        $tlog = New-Object Microsoft.SqlServer.Management.Smo.LogFile($newdb, $logname)
                        $tlog.FileName = $LogFilePath + "\" + $logname + ".ldf"

                        if (Test-Bound -ParameterName LogSize) {
                            $tlog.Size = ($LogSize * 1024)
                        }
                        if (Test-Bound -ParameterName LogGrowth) {
                            $tlog.Growth = ($LogGrowth * 1024)
                            $tlog.GrowthType = "KB"
                        }

                        #add the log to the db
                        $newdb.LogFiles.Add($tlog)
                    } catch {
                        Stop-Function -Message "Error adding log file to database." -ErrorRecord $_ -Target $instance -Continue
                    }

                    if (Test-Bound -ParameterName SecondaryFileMaxSize, SecondaryFileGrowth, SecondaryFilesize) {
                        #add the Secondary data file group
                        try {
                            $secondaryfilegroupname = $dbname + "_MainData"
                            Write-Message -Message "Creating Secondary filegroup $secondaryfilegroupname" -Level Verbose

                            $secondaryfg = New-Object Microsoft.SqlServer.Management.Smo.Filegroup($newdb, $secondaryfilegroupname)
                            $newdb.Filegroups.Add($secondaryfg)
                        } catch {
                            Stop-Function -Message "Error creating Secondary filegroup" -ErrorRecord $_ -Target $instance -Continue
                        }

                        # add the required number of files to the filegroup in a loop
                        $secondaryfgcount = $bail = 0

                        # open a loop while the filecounter is less than the required number of files
                        do {
                            $secondaryfgcount++
                            try {
                                $secondaryfilename = "$($secondaryfilegroupname)_$($secondaryfgcount)"
                                Write-Message -Message "Creating file name $secondaryfilename in filegroup $secondaryfilegroupname" -Level Verbose
                                $secondaryfile = New-Object Microsoft.SQLServer.Management.Smo.Datafile($secondaryfg, $secondaryfilename)
                                $secondaryfile.FileName = $DataFilePath + "\" + $secondaryfilename + ".ndf"

                                if (Test-Bound -ParameterName SecondaryFilesize) {
                                    $secondaryfile.Size = ($SecondaryFilesize * 1024)
                                }
                                if (Test-Bound -ParameterName SecondaryFileGrowth) {
                                    $secondaryfile.Growth = ($SecondaryFileGrowth * 1024)
                                    $secondaryfile.GrowthType = "KB"
                                }
                                if (Test-Bound -ParameterName SecondaryFileMaxSize) {
                                    $secondaryfile.MaxSize = ($SecondaryFileMaxSize * 1024)
                                }

                                $secondaryfg.Files.Add($secondaryfile)
                            } catch {
                                $bail = $true
                                Stop-Function -Message "Error adding file $secondaryfg to $secondaryfilegroupname" -ErrorRecord $_ -Target $instance
                                return
                            }
                        } while ($secondaryfgcount -le $SecondaryFileCount -or $bail)
                    }
                }

                Write-Message -Message "Creating Database $dbname" -Level Verbose
                if ($PSCmdlet.ShouldProcess($instance, "Creating the database $dbname on instance $instance")) {
                    try {
                        $newdb.Create()
                    } catch {
                        Stop-Function -Message "Error creating Database $dbname on server $instance" -ErrorRecord $_ -Target $instance -Continue
                    }

                    if ($Owner) {
                        Write-Message -Message "Setting database owner to $Owner" -Level Verbose
                        try {
                            $newdb.SetOwner($Owner)
                        } catch {
                            Stop-Function -Message "Error setting Database Owner to $Owner" -ErrorRecord $_ -Target $instance -Continue
                        }
                    }

                    if ($DefaultFileGroup -eq "Secondary") {
                        Write-Message -Message "Setting default filegroup to $secondaryfilegroupname" -Level Verbose
                        try {
                            $newdb.SetDefaultFileGroup($secondaryfilegroupname)
                        } catch {
                            Stop-Function -Message "Error setting default filegorup to $secondaryfilegroupname" -ErrorRecord $_ -Target $instance -Continue
                        }
                    }

                    Get-DbaDatabase -SqlInstance $server -Database $dbname
                }
            }
        }
    }
}
tools\dbatools\functions\New-DbaDbCertificate.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function New-DbaDbCertificate {
    <#
    .SYNOPSIS
        Creates a new database certificate

    .DESCRIPTION
        Creates a new database certificate. If no database is specified, the certificate will be created in master.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Allows you to login to SQL Server using alternative credentials.

    .PARAMETER Database
        The database where the certificate will be created. Defaults to master.

    .PARAMETER Name
        Optional name to create the certificate. Defaults to database name.

    .PARAMETER Subject
        Optional subject to create the certificate.

    .PARAMETER StartDate
        Optional secure string used to create the certificate.

    .PARAMETER ExpirationDate
        Optional secure string used to create the certificate.

    .PARAMETER ActiveForServiceBrokerDialog
        Optional secure string used to create the certificate.

    .PARAMETER SecurePassword
        Optional password - if no password is supplied, the password will be protected by the master key

    .PARAMETER InputObject
        Enables piping from Get-DbaDatabase

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Certificate
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> New-DbaDbCertificate -SqlInstance Server1

        You will be prompted to securely enter your password, then a certificate will be created in the master database on server1 if it does not exist.

    .EXAMPLE
        PS C:\> New-DbaDbCertificate -SqlInstance Server1 -Database db1 -Confirm:$false

        Suppresses all prompts to install but prompts to securely enter your password and creates a certificate in the 'db1' database

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Name,
        [string[]]$Database = "master",
        [string[]]$Subject,
        [datetime]$StartDate = (Get-Date),
        [datetime]$ExpirationDate = $StartDate.AddYears(5),
        [switch]$ActiveForServiceBrokerDialog,
        [Alias("Password")]
        [Security.SecureString]$SecurePassword,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )
    begin {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias New-DbaDatabaseCertificate
    }
    process {
        if ($SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database
        }

        foreach ($db in $InputObject) {
            if ((Test-Bound -Not -ParameterName Name)) {
                Write-Message -Level Verbose -Message "Name of certificate not specified, setting it to '$db'"
                $Name = $db.Name
            }

            if ((Test-Bound -Not -ParameterName Subject)) {
                Write-Message -Level Verbose -Message "Subject not specified, setting it to '$Name Database Certificate'"
                $subject = "$Name Database Certificate"
            }

            foreach ($cert in $Name) {
                if ($null -ne $db.Certificates[$cert]) {
                    Stop-Function -Message "Certificate '$cert' already exists in $($db.Name) on $($db.Parent.Name)" -Target $db -Continue
                }

                if ($Pscmdlet.ShouldProcess($db.Parent.Name, "Creating certificate for database '$($db.Name)'")) {

                    # something is up with .net, force a stop
                    $eap = $ErrorActionPreference
                    $ErrorActionPreference = 'Stop'
                    try {
                        $smocert = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Certificate $db, $cert
                        $smocert.StartDate = $StartDate
                        $smocert.Subject = $Subject
                        $smocert.ExpirationDate = $ExpirationDate
                        $smocert.ActiveForServiceBrokerDialog = $ActiveForServiceBrokerDialog

                        if ($SecurePassword) {
                            $smocert.Create(([System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($SecurePassword))))
                        } else {
                            $smocert.Create()
                        }

                        Add-Member -Force -InputObject $smocert -MemberType NoteProperty -Name ComputerName -value $db.Parent.ComputerName
                        Add-Member -Force -InputObject $smocert -MemberType NoteProperty -Name InstanceName -value $db.Parent.ServiceName
                        Add-Member -Force -InputObject $smocert -MemberType NoteProperty -Name SqlInstance -value $db.Parent.DomainInstanceName
                        Add-Member -Force -InputObject $smocert -MemberType NoteProperty -Name Database -value $db.Name

                        Select-DefaultView -InputObject $smocert -Property ComputerName, InstanceName, SqlInstance, Database, Name, Subject, StartDate, ActiveForServiceBrokerDialog, ExpirationDate, Issuer, LastBackupDate, Owner, PrivateKeyEncryptionType, Serial
                    } catch {
                        $ErrorActionPreference = $eap
                        Stop-Function -Message "Failed to create certificate in $($db.Name) on $($db.Parent.Name)" -Target $smocert -ErrorRecord $_ -Continue
                    }
                    $ErrorActionPreference = $eap
                }
            }
        }
    }
}
tools\dbatools\functions\New-DbaDbMaskingConfig.ps1
function New-DbaDbMaskingConfig {
    <#
    .SYNOPSIS
        Generates a new data masking configuration file to be used with Invoke-DbaDbDataMasking

    .DESCRIPTION
        Generates a new data masking configuration file. This file is important to apply any data masking to the data in a database.

        Note that the following column and data types are not currently supported:
        Identity
        ForeignKey
        Computed
        Hierarchyid
        Geography
        Geometry
        Xml

        Read more here:
        https://sachabarbs.wordpress.com/2018/06/11/bogus-simple-fake-data-tool/
        https://github.com/bchavez/Bogus

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Databases to process through

    .PARAMETER Table
        Tables to process. By default all the tables will be processed

    .PARAMETER Column
        Columns to process. By default all the columns will be processed

    .PARAMETER Path
        Path where to save the generated JSON files.
        Th naming convention will be "servername.databasename.tables.json"

    .PARAMETER Locale
        Set the local to enable certain settings in the masking

    .PARAMETER Force
        Forcefully execute commands when needed

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DataMasking, Database
        Author: Sander Stad (@sqlstad, sqlstad.nl) | Chrissy LeMaire (@cl, netnerds.net)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaDbMaskingConfig

    .EXAMPLE
        New-DbaDbMaskingConfig -SqlInstance SQLDB1 -Database DB1 -Path C:\Temp\clone

        Process all tables and columns for database DB1 on instance SQLDB1

    .EXAMPLE
        New-DbaDbMaskingConfig -SqlInstance SQLDB1 -Database DB1 -Table Customer -Path C:\Temp\clone

        Process only table Customer with all the columns

    .EXAMPLE
        New-DbaDbMaskingConfig -SqlInstance SQLDB1 -Database DB1 -Table Customer -Column City -Path C:\Temp\clone

        Process only table Customer and only the column named "City"

    #>
    [CmdLetBinding()]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [string[]]$Table,
        [string[]]$Column,
        [parameter(Mandatory)]
        [string]$Path,
        [string]$Locale = 'en',
        [switch]$Force,
        [switch]$EnableException
    )
    begin {

        # Get all the different column types
        try {
            $columnTypes = Get-Content -Path "$script:PSModuleRoot\bin\datamasking\columntypes.json" | ConvertFrom-Json
        } catch {
            Stop-Function -Message "Something went wrong importing the column types" -Continue
        }
        # Check if the Path is accessible
        if (-not (Test-Path -Path $Path)) {
            try {
                $null = New-Item -Path $Path -ItemType Directory -Force:$Force
            } catch {
                Stop-Function -Message "Could not create Path directory" -ErrorRecord $_ -Target $Path
            }
        } else {
            if ((Get-Item $path) -isnot [System.IO.DirectoryInfo]) {
                Stop-Function -Message "$Path is not a directory"
            }
        }
    }

    process {
        if (Test-FunctionInterrupt) {
            return
        }

        if ($SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database
        }

        $results = @()
        foreach ($db in $InputObject) {
            $server = $db.Parent
            $tables = @()

            # Get the tables
            if ($Table) {
                $tablecollection = $db.Tables | Where-Object Name -in $Table
            } else {
                $tablecollection = $db.Tables
            }

            if ($tablecollection.Count -lt 1) {
                Stop-Function -Message "The database does not contain any tables" -Target $db -Continue
            }

            # Loop through the tables
            foreach ($tableobject in $tablecollection) {
                Write-Message -Message "Processing table $($tableobject.Name)" -Level Verbose

                $columns = @()

                # Get the columns
                if ($Column) {
                    [array]$columncollection = $tableobject.Columns | Where-Object Name -in $Column
                } else {
                    [array]$columncollection = $tableobject.Columns
                }

                foreach ($columnobject in $columncollection) {
                    # Skip incompatible columns
                    if ($columnobject.Identity) {
                        Write-Message -Level Verbose -Message "Skipping $columnobject because it is an identity column"
                        continue
                    }
                    if ($columnobject.IsForeignKey) {
                        Write-Message -Level Verbose -Message "Skipping $columnobject because it is a foreign key"
                        continue
                    }
                    if ($columnobject.Computed) {
                        Write-Message -Level Verbose -Message "Skipping $columnobject because it is a computed column"
                        continue
                    }
                    if ($columnobject.DataType.Name -eq 'hierarchyid') {
                        Write-Message -Level Verbose -Message "Skipping $columnobject because it is a hierarchyid column"
                        continue
                    }
                    if ($columnobject.DataType.Name -eq 'geography') {
                        Write-Message -Level Verbose -Message "Skipping $columnobject because it is a geography column"
                        continue
                    }
                    if ($columnobject.DataType.Name -eq 'geometry') {
                        Write-Message -Level Verbose -Message "Skipping $columnobject because it is a geometry column"
                        continue
                    }
                    if ($columnobject.DataType.SqlDataType.ToString().ToLower() -eq 'xml') {
                        Write-Message -Level Verbose -Message "Skipping $columnobject because it is a xml column"
                        continue
                    }

                    $maskingType = $min = $null
                    $columnLength = $columnobject.Datatype.MaximumLength
                    $columnType = $columnobject.DataType.SqlDataType.ToString().ToLower()

                    if ($columnobject.InPrimaryKey -and $columnobject.DataType.SqlDataType.ToString().ToLower() -notmatch 'date') {
                        $min = 2
                    }
                    if (-not $columnType) {
                        $columnType = $columnobject.DataType.Name.ToLower()
                    }

                    # Get the masking type with the synonym
                    $maskingType = $columnTypes | Where-Object {
                        $columnobject.Name -in $_.Synonym
                    }

                    if ($maskingType) {
                        # Make it easier to get the type name
                        $maskingType = $maskingType | Select-Object TypeName -ExpandProperty TypeName

                        switch ($maskingType.ToLower()) {
                            "firstname" {
                                $columns += [PSCustomObject]@{
                                    Name            = $columnobject.Name
                                    ColumnType      = $columnType
                                    CharacterString = $null
                                    MinValue        = $min
                                    MaxValue        = $columnLength
                                    MaskingType     = "Name"
                                    SubType         = "Firstname"
                                    Deterministic   = $false
                                    Nullable        = $columnobject.Nullable
                                }
                            }
                            "lastname" {
                                $columns += [PSCustomObject]@{
                                    Name            = $columnobject.Name
                                    ColumnType      = $columnType
                                    CharacterString = $null
                                    MinValue        = $min
                                    MaxValue        = $columnLength
                                    MaskingType     = "Name"
                                    SubType         = "Lastname"
                                    Deterministic   = $false
                                    Nullable        = $columnobject.Nullable
                                }
                            }
                            "creditcard" {
                                $columns += [PSCustomObject]@{
                                    Name            = $columnobject.Name
                                    ColumnType      = $columnType
                                    CharacterString = $null
                                    MinValue        = $min
                                    MaxValue        = $columnLength
                                    MaskingType     = "Finance"
                                    SubType         = "CreditcardNumber"
                                    Deterministic   = $false
                                    Nullable        = $columnobject.Nullable
                                }
                            }
                            "address" {
                                $columns += [PSCustomObject]@{
                                    Name            = $columnobject.Name
                                    ColumnType      = $columnType
                                    CharacterString = $null
                                    MinValue        = $min
                                    MaxValue        = $columnLength
                                    MaskingType     = "Address"
                                    SubType         = "StreetAddress"
                                    Deterministic   = $false
                                    Nullable        = $columnobject.Nullable
                                }
                            }
                            "city" {
                                $columns += [PSCustomObject]@{
                                    Name            = $columnobject.Name
                                    ColumnType      = $columnType
                                    CharacterString = $null
                                    MinValue        = $min
                                    MaxValue        = $columnLength
                                    MaskingType     = "Address"
                                    SubType         = "City"
                                    Deterministic   = $false
                                    Nullable        = $columnobject.Nullable
                                }
                            }
                            "zipcode" {
                                $columns += [PSCustomObject]@{
                                    Name            = $columnobject.Name
                                    ColumnType      = $columnType
                                    CharacterString = $null
                                    MinValue        = $min
                                    MaxValue        = $columnLength
                                    MaskingType     = "Address"
                                    SubType         = "Zipcode"
                                    Deterministic   = $false
                                    Nullable        = $columnobject.Nullable
                                }
                            }
                            "company" {
                                $columns += [PSCustomObject]@{
                                    Name            = $columnobject.Name
                                    ColumnType      = $columnType
                                    CharacterString = $null
                                    MinValue        = $min
                                    MaxValue        = $columnLength
                                    MaskingType     = "Company"
                                    SubType         = "CompanyName"
                                    Deterministic   = $false
                                    Nullable        = $columnobject.Nullable
                                }
                            }
                            "username" {
                                $columns += [PSCustomObject]@{
                                    Name            = $columnobject.Name
                                    ColumnType      = $columnType
                                    CharacterString = $null
                                    MinValue        = $min
                                    MaxValue        = $columnLength
                                    MaskingType     = "Internet"
                                    SubType         = "UserName"
                                    Deterministic   = $false
                                    Nullable        = $columnobject.Nullable
                                }
                            }
                        }
                    } else {
                        $type = "Random"

                        switch ($columnType) {
                            {
                                $_ -in "bit", "bool"
                            } {
                                $subType = "Bool"
                                $MaxValue = $null
                            }
                            "bigint" {
                                $subType = "Number"
                                $MaxValue = 9223372036854775807
                            }
                            "int" {
                                $subType = "Number"
                                $MaxValue = 2147483647
                            }
                            "date" {
                                $subType = "Date"
                                $MaxValue = $null
                            }
                            "datetime" {
                                $subType = "Date"
                                $MaxValue = $null
                            }
                            "datetime2" {
                                $subType = "Date"
                                $MaxValue = $null
                            }
                            "float" {
                                $subType = "Float"
                                $MaxValue = $null
                            }
                            "smallint" {
                                $subType = "Number"
                                $MaxValue = 32767
                            }
                            "smalldatetime" {
                                $subType = "Date"
                                $MaxValue = $null
                            }
                            "tinyint" {
                                $subType = "Number"
                                $MaxValue = 255
                            }
                            "varbinary" {
                                $subType = "Byte"
                                $MaxValue = $columnLength
                            }
                            "userdefineddatatype" {
                                if ($columnLength -eq 1) {
                                    $subType = "Bool"
                                    $MaxValue = $columnLength
                                } else {
                                    $subType = "String"
                                    $MaxValue = $columnLength
                                }
                            }
                            default {
                                $subType = "String"
                                $MaxValue = $columnLength
                            }
                        }

                        $columns += [PSCustomObject]@{
                            Name            = $columnobject.Name
                            ColumnType      = $columnType
                            CharacterString = $null
                            MinValue        = $min
                            MaxValue        = $MaxValue
                            MaskingType     = $type
                            SubType         = $subType
                            Deterministic   = $false
                            Nullable        = $columnobject.Nullable
                        }
                    }
                }


                # Check if something needs to be generated
                if ($columns) {
                    $tables += [PSCustomObject]@{
                        Name    = $tableobject.Name
                        Schema  = $tableobject.Schema
                        Columns = $columns
                    }
                } else {
                    Write-Message -Message "No columns match for masking in table $($tableobject.Name)" -Level Verbose
                }
            }

            # Check if something needs to be generated
            if ($tables) {
                $results += [PSCustomObject]@{
                    Name   = $db.Name
                    Tables = $tables
                }
            } else {
                Write-Message -Message "No columns match for masking in table $($tableobject.Name)" -Level Verbose
            }
        }

        # Write the data to the Path
        if ($results) {
            try {
                $temppath = "$Path\$($server.Name.Replace('\', '$')).$($db.Name).tables.json"
                if (-not $script:isWindows) {
                    $temppath = $temppath.Replace("\", "/")
                }
                Set-Content -Path $temppath -Value ($results | ConvertTo-Json -Depth 5)
                Get-ChildItem -Path $temppath
            } catch {
                Stop-Function -Message "Something went wrong writing the results to the Path" -Target $Path -Continue -ErrorRecord $_
            }
        } else {
            Write-Message -Message "No tables to save for database $($db.Name) on $($server.Name)" -Level Verbose
        }
    }
}
tools\dbatools\functions\New-DbaDbMasterKey.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function New-DbaDbMasterKey {
    <#
    .SYNOPSIS
        Creates a new database master key

    .DESCRIPTION
        Creates a new database master key. If no database is specified, the master key will be created in master.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Allows you to login to SQL Server using alternative credentials.

    .PARAMETER Credential
        Enables easy creation of a secure password.

    .PARAMETER Database
        The database where the master key will be created. Defaults to master.

    .PARAMETER SecurePassword
        Secure string used to create the key.

    .PARAMETER InputObject
        Database object piped in from Get-DbaDatabase.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Certificate
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> New-DbaDbMasterKey -SqlInstance Server1

        You will be prompted to securely enter your password, then a master key will be created in the master database on server1 if it does not exist.


    .EXAMPLE
        PS C:\> New-DbaDbMasterKey -SqlInstance Server1 -Credential usernamedoesntmatter

        You will be prompted by a credential interface to securely enter your password, then a master key will be created in the master database on server1 if it does not exist.

    .EXAMPLE
        PS C:\> New-DbaDbMasterKey -SqlInstance Server1 -Database db1 -Confirm:$false

        Suppresses all prompts to install but prompts in th console to securely enter your password and creates a master key in the 'db1' database

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [PSCredential]$Credential,
        [string[]]$Database = "master",
        [Alias("Password")]
        [Security.SecureString]$SecurePassword,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )
    begin {
        if ($Credential) {
            $SecurePassword = $Credential.Password
        } else {
            if (-not $SecurePassword) {
                $SecurePassword = Read-Host "Password" -AsSecureString
            }
        }
    }
    process {
        if ($SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $SqlInstance -Database $Database -ExcludeDatabase $ExcludeDatabase
        }

        foreach ($db in $InputObject) {
            if ($null -ne $db.MasterKey) {
                Stop-Function -Message "Master key already exists in the $db database on $($db.Parent.Name)" -Target $db -Continue
            }

            if ($Pscmdlet.ShouldProcess($db.Parent.Name, "Creating master key for database '$($db.Name)'")) {
                try {
                    $masterkey = New-Object Microsoft.SqlServer.Management.Smo.MasterKey $db
                    $masterkey.Create(([System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($SecurePassword))))

                    Add-Member -Force -InputObject $masterkey -MemberType NoteProperty -Name ComputerName -value $db.Parent.ComputerName
                    Add-Member -Force -InputObject $masterkey -MemberType NoteProperty -Name InstanceName -value $db.Parent.ServiceName
                    Add-Member -Force -InputObject $masterkey -MemberType NoteProperty -Name SqlInstance -value $db.Parent.DomainInstanceName
                    Add-Member -Force -InputObject $masterkey -MemberType NoteProperty -Name Database -value $db.Name

                    Select-DefaultView -InputObject $masterkey -Property ComputerName, InstanceName, SqlInstance, Database, CreateDate, DateLastModified, IsEncryptedByServer
                } catch {
                    Stop-Function -Message "Failed to create master key in $db on $instance. Exception: $($_.Exception.InnerException)" -Target $masterkey -ErrorRecord $_ -Continue
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias New-DbaDatabaseMasterKey
    }
}
tools\dbatools\functions\New-DbaDbSnapshot.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function New-DbaDbSnapshot {
    <#
    .SYNOPSIS
        Creates database snapshots

    .DESCRIPTION
        Creates database snapshots without hassles

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Credential object used to connect to the SQL Server as a different user

    .PARAMETER AllDatabases
        Creates snapshot for all eligible databases

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER WhatIf
        Shows what would happen if the command were to run

    .PARAMETER Confirm
        Prompts for confirmation of every step.

    .PARAMETER Name
        The specific snapshot name you want to create. Works only if you target a single database. If you need to create multiple snapshot,
        you must use the NameSuffix parameter

    .PARAMETER NameSuffix
        When you pass a simple string, it'll be appended to use it to build the name of the snapshot. By default snapshots are created with yyyyMMdd_HHmmss suffix
        You can also pass a standard placeholder, in which case it'll be interpolated (e.g. '{0}' gets replaced with the database name)

    .PARAMETER Path
        Snapshot files will be created here (by default the filestructure will be created in the same folder as the base db)

    .PARAMETER InputObject
        Allows Piping from Get-DbaDatabase

    .PARAMETER Force
        Databases with Filestream FG can be snapshotted, but the Filestream FG is marked offline
        in the snapshot. To create a "partial" snapshot, you need to pass -Force explicitely

        NB: You can't then restore the Database from the newly-created snapshot.
        For details, check https://msdn.microsoft.com/en-us/library/bb895334.aspx

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Snapshot, Restore, Database
        Author: Simone Bizzotto (@niphold)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaDbSnapshot

    .EXAMPLE
        PS C:\> New-DbaDbSnapshot -SqlInstance sqlserver2014a -Database HR, Accounting

        Creates snapshot for HR and Accounting, returning a custom object displaying Server, Database, DatabaseCreated, SnapshotOf, SizeMB, DatabaseCreated, PrimaryFilePath, Status, Notes

    .EXAMPLE
        PS C:\> New-DbaDbSnapshot -SqlInstance sqlserver2014a -Database HR -Name HR_snap

        Creates snapshot named "HR_snap" for HR

    .EXAMPLE
        PS C:\> New-DbaDbSnapshot -SqlInstance sqlserver2014a -Database HR -NameSuffix 'fool_{0}_snap'

        Creates snapshot named "fool_HR_snap" for HR

    .EXAMPLE
        PS C:\> New-DbaDbSnapshot -SqlInstance sqlserver2014a -Database HR, Accounting -Path F:\snapshotpath

        Creates snapshots for HR and Accounting databases, storing files under the F:\snapshotpath\ dir

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sql2016 -Database df | New-DbaDbSnapshot

        Creates a snapshot for the database df on sql2016

    #>

    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$AllDatabases,
        [string]$Name,
        [string]$NameSuffix,
        [string]$Path,
        [switch]$Force,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {

        $NoSupportForSnap = @('model', 'master', 'tempdb')
        # Evaluate the default suffix here for naming consistency
        $DefaultSuffix = (Get-Date -Format "yyyyMMdd_HHmmss")
        if ($NameSuffix.Length -gt 0) {
            #Validate if Name can be interpolated
            try {
                $null = $NameSuffix -f 'some_string'
            } catch {
                Stop-Function -Message "NameSuffix parameter must be a template only containing one parameter {0}" -ErrorRecord $_
            }
        }

        function Resolve-SnapshotError($server) {
            $errhelp = ''
            $CurrentEdition = $server.Edition.toLower()
            $CurrentVersion = $server.Version.Major * 1000000 + $server.Version.Minor * 10000 + $server.Version.Build
            if ($server.Version.Major -lt 9) {
                $errhelp = 'Not supported before 2005'
            }
            if ($CurrentVersion -lt 12002000 -and $errhelp.Length -eq 0) {
                if ($CurrentEdition -notmatch '.*enterprise.*|.*developer.*|.*datacenter.*') {
                    $errhelp = 'Supported only for Enterprise, Developer or Datacenter editions'
                }
            }
            $message = ""
            if ($errhelp.Length -gt 0) {
                $message += "Please make sure your version supports snapshots : ($errhelp)"
            } else {
                $message += "This module can't tell you why the snapshot creation failed. Feel free to report back to dbatools what happened"
            }
            Write-Message -Level Warning -Message $message
        }
    }
    process {
        if (-not $InputObject -and -not $Database -and $AllDatabases -eq $false) {
            Stop-Function -Message "You must specify a -AllDatabases or -Database to continue" -EnableException $EnableException
            return
        }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            #Checks for path existence, left the length test because test-bound wasn't working for some reason
            if ($Path.Length -gt 0) {
                if (!(Test-DbaPath -SqlInstance $instance -Path $Path)) {
                    Stop-Function -Message "$instance cannot access the directory $Path" -ErrorRecord $_ -Target $instance -Continue -EnableException $EnableException
                }
            }

            if ($AllDatabases) {
                $dbs = $server.Databases
            }

            if ($Database) {
                $dbs = $server.Databases | Where-Object { $Database -contains $_.Name }
            }

            if ($ExcludeDatabase) {
                $dbs = $server.Databases | Where-Object { $ExcludeDatabase -notcontains $_.Name }
            }

            ## double check for gotchas
            foreach ($db in $dbs) {
                if ($db.IsDatabaseSnapshot) {
                    Write-Message -Level Warning -Message "$($db.name) is a snapshot, skipping"
                } elseif ($db.name -in $NoSupportForSnap) {
                    Write-Message -Level Warning -Message "$($db.name) snapshots are prohibited"
                } elseif ($db.IsAccessible -ne $true) {
                    Write-Message -Level Verbose -Message "$($db.name) is not accessible, skipping"
                } else {
                    $InputObject += $db
                }
            }

            if ($InputObject.Length -gt 1 -and $Name) {
                Stop-Function -Message "You passed the Name parameter that is fixed but selected multiple databases to snapshot: use the NameSuffix parameter" -Continue -EnableException $EnableException
            }
        }

        foreach ($db in $InputObject) {
            $server = $db.Parent

            # In case stuff is piped in
            if ($server.VersionMajor -lt 9) {
                Stop-Function -Message "SQL Server version 9 required - $server not supported" -Continue
            }

            if ($NameSuffix.Length -gt 0) {
                $SnapName = $NameSuffix -f $db.Name
                if ($SnapName -eq $NameSuffix) {
                    #no interpolation, just append
                    $SnapName = '{0}{1}' -f $db.Name, $NameSuffix
                }
            } elseif ($Name.Length -gt 0) {
                $SnapName = $Name
            } else {
                $SnapName = "{0}_{1}" -f $db.Name, $DefaultSuffix
            }
            if ($SnapName -in $server.Databases.Name) {
                Write-Message -Level Warning -Message "A database named $Snapname already exists, skipping"
                continue
            }
            $all_FSD = $db.FileGroups | Where-Object FileGroupType -eq 'FileStreamDataFileGroup'
            $all_MMO = $db.FileGroups | Where-Object FileGroupType -eq 'MemoryOptimizedDataFileGroup'
            $has_FSD = $all_FSD.Count -gt 0
            $has_MMO = $all_MMO.Count -gt 0
            if ($has_MMO) {
                Write-Message -Level Warning -Message "MEMORY_OPTIMIZED_DATA detected, snapshots are not possible"
                continue
            }
            if ($has_FSD -and $Force -eq $false) {
                Write-Message -Level Warning -Message "Filestream detected, skipping. You need to specify -Force. See Get-Help for details"
                continue
            }
            $snaptype = "db snapshot"
            if ($has_FSD) {
                $snaptype = "partial db snapshot"
            }
            If ($Pscmdlet.ShouldProcess($server, "Create $snaptype $SnapName of $($db.Name)")) {
                $CustomFileStructure = @{ }
                $counter = 0
                foreach ($fg in $db.FileGroups) {
                    $CustomFileStructure[$fg.Name] = @()
                    if ($fg.FileGroupType -eq 'FileStreamDataFileGroup') {
                        Continue
                    }
                    foreach ($file in $fg.Files) {
                        $counter += 1
                        $basename = [IO.Path]::GetFileNameWithoutExtension($file.FileName)
                        $basepath = Split-Path $file.FileName -Parent
                        # change path if specified
                        if ($Path.Length -gt 0) {
                            $basepath = $Path
                        }
                        # we need to avoid cases where basename is the same for multiple FG
                        $fname = [IO.Path]::Combine($basepath, ("{0}_{1}_{2:0000}_{3:000}" -f $basename, $DefaultSuffix, (Get-Date).MilliSecond, $counter))
                        # fixed extension is hardcoded as "ss", which seems a "de-facto" standard
                        $fname = [IO.Path]::ChangeExtension($fname, "ss")
                        $CustomFileStructure[$fg.Name] += @{ 'name' = $file.name; 'filename' = $fname }
                    }
                }

                $SnapDB = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Database -ArgumentList $server, $Snapname
                $SnapDB.DatabaseSnapshotBaseName = $db.Name

                foreach ($fg in $CustomFileStructure.Keys) {
                    $SnapFG = New-Object -TypeName Microsoft.SqlServer.Management.Smo.FileGroup $SnapDB, $fg
                    $SnapDB.FileGroups.Add($SnapFG)
                    foreach ($file in $CustomFileStructure[$fg]) {
                        $SnapFile = New-Object -TypeName Microsoft.SqlServer.Management.Smo.DataFile $SnapFG, $file['name'], $file['filename']
                        $SnapDB.FileGroups[$fg].Files.Add($SnapFile)
                    }
                }

                # we're ready to issue a Create, but SMO is a little uncooperative here
                # there are cases we can manage and others we can't, and we need all the
                # info we can get both from testers and from users

                $sql = $SnapDB.Script()

                try {
                    $SnapDB.Create()
                    $server.Databases.Refresh()
                    Get-DbaDbSnapshot -SqlInstance $server -Snapshot $Snapname
                } catch {
                    try {
                        $server.Databases.Refresh()
                        if ($SnapName -notin $server.Databases.Name) {
                            # previous creation failed completely, snapshot is not there already
                            $null = $server.Query($sql[0])
                            $server.Databases.Refresh()
                            $SnapDB = Get-DbaDbSnapshot -SqlInstance $server -Snapshot $Snapname
                        } else {
                            $SnapDB = Get-DbaDbSnapshot -SqlInstance $server -Snapshot $Snapname
                        }

                        $Notes = @()
                        if ($db.ReadOnly -eq $true) {
                            $Notes += 'SMO is probably trying to set a property on a read-only snapshot, run with -Debug to find out and report back'
                        }
                        if ($has_FSD) {
                            #Variable marked as unused by PSScriptAnalyzer
                            #$Status = 'Partial'
                            $Notes += 'Filestream groups are not viable for snapshot'
                        }
                        $Notes = $Notes -Join ';'

                        $hints = @("Executing these commands led to a partial failure")
                        foreach ($stmt in $sql) {
                            $hints += $stmt
                        }

                        Write-Message -Level Debug -Message ($hints -Join "`n")

                        $SnapDB
                    } catch {
                        # Resolve-SnapshotError $server
                        $hints = @("Executing these commands led to a failure")
                        foreach ($stmt in $sql) {
                            $hints += $stmt
                        }
                        Write-Message -Level Debug -Message ($hints -Join "`n")

                        Stop-Function -Message "Failure" -ErrorRecord $_ -Target $SnapDB -Continue
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias New-DbaDatabaseSnapshot
    }
}
tools\dbatools\functions\New-DbaDbUser.ps1
function New-DbaDbUser {
    <#
    .SYNOPSIS
        Creates a new user for the specified database.

    .DESCRIPTION
        Creates a new user for a specified database with provided specifications.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Defaults to the default instance on localhost.

    .PARAMETER SqlCredential
        Allows you to login to servers using SQL Logins instead of Windows Authentication (AKA Integrated or Trusted). To use:

        $scred = Get-Credential, then pass $scred object to the -SqlCredential parameter.

        Windows Authentication will be used if SqlCredential is not specified. SQL Server does not accept Windows credentials being passed as credentials.

        To connect to SQL Server as a different Windows user, run PowerShell as that user.

    .PARAMETER Database
        Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server. By default, system databases are excluded.

    .PARAMETER IncludeSystem
        If this switch is enabled, the user will be added to system databases.

    .PARAMETER Login
        When specified, the user will be associated to this SQL login and have the same name as the Login.

    .PARAMETER Username
        When specified, the user will have this name.

    .PARAMETER Force
        If user exists, drop and recreate.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database, User
        Author: Frank Henninger (@osiris687)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaDbUser

    .EXAMPLE
        PS C:\> New-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -Login user1

        Creates a new sql user with login named user1 in the specified database.

    .EXAMPLE
        PS C:\> New-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -Username user1

        Creates a new sql user without login named user1 in the specified database.

    .EXAMPLE
        PS C:\> New-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -Login Login1 -Username user1

        Creates a new sql user named user1 mapped to Login1 in the specified database.

    .EXAMPLE
        PS C:\> Get-DbaDbUser -SqlInstance sqlserver1 -Database DB1 | New-DbaDbUser -SqlInstance sqlserver2 -Database DB1

        Copies users from sqlserver1.DB1 to sqlserver2.DB1. Does not copy permissions!

    #>
    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = "NoLogin")]
    param(
        [parameter(Mandatory, Position = 1)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$IncludeSystem,
        [parameter(ParameterSetName = "Login")]
        [string[]]$Login,
        [parameter(ParameterSetName = "NoLogin")]
        [parameter(ParameterSetName = "Login")]
        [string[]]$Username,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        function Test-SqlLoginInDatabase {
            param(
                [Microsoft.SqlServer.Management.Smo.Login]$Login,
                [Microsoft.SqlServer.Management.Smo.Database]$Database
            )

            # Does user exist with same login?
            if ( $existingUser = ( $Database.Users | Where-Object Login -eq $smoLogin ) ) {
                if (Test-Bound 'Force') {
                    if ($Pscmdlet.ShouldProcess($existingUser, "Dropping existing user $($existingUser.Name) because -Force was used")) {
                        try {
                            $existingUser.Drop()
                        } catch {
                            Stop-Function -Message "Could not remove existing user $($existingUser.Name), skipping." -Target $existingUser -ErrorRecord $_ -Exception $_.Exception.InnerException.InnerException.InnerException -Continue
                        }
                    }
                } else {
                    Stop-Function -Message "User $($existingUser.Name) already exists and -Force was not specified" -Target $existingUser -Continue
                }
            }
        }

        function Test-SqlUserInDatabase {
            param(
                [string[]]$Username,
                [Microsoft.SqlServer.Management.Smo.Database]$Database
            )

            # Does user exist with same login?
            if ( $existingUser = ( $Database.Users | Where-Object Name -eq $Username ) ) {
                if (Test-Bound 'Force') {
                    if ($Pscmdlet.ShouldProcess($existingUser, "Dropping existing user $($existingUser.Name) because -Force was used")) {
                        try {
                            $existingUser.Drop()
                        } catch {
                            Stop-Function -Message "Could not remove existing user $($existingUser.Name), skipping." -Target $existingUser -ErrorRecord $_ -Exception $_.Exception.InnerException.InnerException.InnerException -Continue
                        }
                    }
                } else {
                    Stop-Function -Message "User $($existingUser.Name) already exists and -Force was not specified" -Target $existingUser -Continue
                }
            }
        }
    }

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $databases = $server.Databases | Where-Object IsAccessible -eq $true

            if ($Database) {
                $databases = $databases | Where-Object Name -In $Database
            }
            if ($ExcludeDatabase) {
                $databases = $databases | Where-Object Name -NotIn $ExcludeDatabase
            }
            if (Test-Bound 'IncludeSystem' -Not) {
                $databases = $databases | Where-Object IsSystemObject -NE $true
            }

            foreach ($db in $databases) {
                Write-Message -Level Verbose -Message "Add users to Database $db on target $server"

                switch -Wildcard ($PSCmdlet.ParameterSetName) {
                    "Login*" {
                        # Creates a user with Login
                        Write-Message -Level VeryVerbose -Message "Using UserType: SqlLogin"

                        if ($PSBoundParameters.Keys -notcontains 'Login') {
                            Stop-Function -Message "Parameter -Login is required " -Target $instance
                        }
                        if ($Login.GetType().Name -eq 'Login') {
                            $smoLogin = $Login
                        } else {
                            #get the login associated with the given name.
                            $smoLogin = $server.Logins | Where-Object Name -eq $Login
                            if ($null -eq $smoLogin) {
                                Stop-Function -Message "Invalid Login: $Login is not found on $Server" -Target $instance;
                                return
                            }
                        }

                        Test-SqlLoginInDatabase -Database $db -Login $smoLogin

                        if ( $PSCmdlet.ParameterSetName -eq "LoginWithNewUsername" ) {
                            $Name = $Username
                            Write-Message -Level Verbose -Message "Using UserName: $Username"
                        } else {
                            $Name = $smoLogin.Name
                            Write-Message -Level Verbose -Message "Using LoginName: $Name"
                        }

                        $Login = $smoLogin
                        $UserType = [Microsoft.SqlServer.Management.Smo.UserType]::SqlLogin
                    }

                    "NoLogin" {
                        # Creates a user without login
                        Write-Message -Level Verbose -Message "Using UserType: NoLogin"
                        $UserType = [Microsoft.SqlServer.Management.Smo.UserType]::NoLogin
                        $Name = $Username
                    }
                } #switch

                # Does user exist with same name?
                Test-SqlUserInDatabase -Database $db -Username $Name

                if ($Pscmdlet.ShouldProcess($db, "Creating user $Name")) {
                    try {
                        $smoUser = New-Object Microsoft.SqlServer.Management.Smo.User
                        $smoUser.Parent = $db
                        $smoUser.Name = $Name

                        if ( $PSBoundParameters.Keys -contains 'Login' -and $Login.GetType().Name -eq 'Login' ) {
                            $smoUser.Login = Login
                        }
                        $smoUser.UserType = $UserType

                        $smoUser.Create()
                    } catch {
                        Stop-Function -Message "Failed to add user $Name in $db to $instance"  -Category InvalidOperation -ErrorRecord $_ -Target $instance -Continue
                    }
                    $smoUser.Refresh()

                    if ( $PSBoundParameters.Keys -contains 'Username' -and $smoUser.Name -ne $Username ) {
                        $smoUser.Rename($Username)
                    }

                    Write-Message -Level Verbose -Message "Successfully added $smoUser in $db to $instance."
                }

                #Display Results
                Get-DbaDbUser -SqlInstance $instance -SqlCredential $sqlcredential -Database $db.Name | Where-Object name -eq $smoUser.Name
            }
        }
    }
}
tools\dbatools\functions\New-DbaDirectory.ps1
function New-DbaDirectory {
    <#
    .SYNOPSIS
        Creates new path as specified by the path variable

    .DESCRIPTION
        Uses master.dbo.xp_create_subdir to create the path
        Returns $true if the path can be created, $false otherwise

    .PARAMETER SqlInstance
        The SQL Server you want to run the test on.

    .PARAMETER Path
        The Path to tests. Can be a file or directory.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Path, Directory, Folder
        Author: Stuart Moore

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: Admin access to server (not SQL Services),
        Remoting must be enabled and accessible if $SqlInstance is not local

    .LINK
        https://dbatools.io/New-DbaDirectory

    .EXAMPLE
        PS C:\> New-DbaDirectory -SqlInstance sqlcluster -Path L:\MSAS12.MSSQLSERVER\OLAP

        If the SQL Server instance sqlcluster can create the path L:\MSAS12.MSSQLSERVER\OLAP it will do and return $true, if not it will return $false.

    .EXAMPLE
        PS C:\> $credential = Get-Credential
        PS C:\> New-DbaDirectory -SqlInstance sqlcluster -SqlCredential $credential -Path L:\MSAS12.MSSQLSERVER\OLAP

        If the SQL Server instance sqlcluster can create the path L:\MSAS12.MSSQLSERVER\OLAP it will do and return $true, if not it will return $false. Uses a SqlCredential to connect

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Parameter(Mandatory)]
        [string]$Path,
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )

    Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias New-DbaSqlDirectory

    foreach ($instance in $SqlInstance) {
        try {
            $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
        }

        $Path = $Path.Replace("'", "''")

        $exists = Test-DbaPath -SqlInstance $sqlinstance -SqlCredential $SqlCredential -Path $Path

        if ($exists) {
            Stop-Function -Message "$Path already exists" -Target $server -Continue
        }

        $sql = "EXEC master.dbo.xp_create_subdir'$path'"
        Write-Message -Level Debug -Message $sql
        if ($Pscmdlet.ShouldProcess($path, "Creating a new path on $($server.name)")) {
            try {
                $null = $server.Query($sql)
                $Created = $true
            } catch {
                $Created = $false
                Stop-Function -Message "Failure" -ErrorRecord $_
            }

            [pscustomobject]@{
                Server  = $SqlInstance
                Path    = $Path
                Created = $Created
            }
        }
    }
}
tools\dbatools\functions\New-DbaEndpoint.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function New-DbaEndpoint {
    <#
    .SYNOPSIS
        Creates endpoints on a SQL Server instance.

    .DESCRIPTION
        Creates endpoints on a SQL Server instance.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Name
        The name of the endpoint. If a name is not specified, one will be auto-generated.

    .PARAMETER Type
        The type of endpoint. Defaults to DatabaseMirroring. Options: DatabaseMirroring, ServiceBroker, Soap, TSql

    .PARAMETER Protocol
        The type of protocol. Defaults to tcp. Options: Tcp, NamedPipes, Http, Via, SharedMemory

    .PARAMETER Role
        The type of role. Defaults to All. Options: All, None, Partner, Witness

    .PARAMETER Port
        Port for TCP. If one is not provided, it will be autogenerated.

    .PARAMETER SslPort
        Port for SSL

    .PARAMETER Certificate
        Database certificate used for authentication.

    .PARAMETER EndpointEncryption
        Used to specify the state of encryption on the endpoint. Defaults to required.
        Disabled
        Required
        Supported

    .PARAMETER EncryptionAlgorithm
        Specifies an encryption algorithm used on an endpoint. Defaults to Aes.

        Options are:
        AesRC4
        Aes
        None
        RC4
        RC4Aes

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Owner
        Owner of the endpoint. Defaults to sa.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Endpoint
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaEndpoint

    .EXAMPLE
        PS C:\> New-DbaEndpoint -SqlInstance localhost

        Creates all Endpoint(s) on the local default SQL Server instance

    .EXAMPLE
        PS C:\> New-DbaEndpoint -SqlInstance localhost, sql2016

        Returns all Endpoint(s) for the local and sql2016 SQL Server instances

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$Name,
        [ValidateSet('DatabaseMirroring', 'ServiceBroker', 'Soap', 'TSql')]
        [string]$Type = 'DatabaseMirroring',
        [ValidateSet('Tcp', 'NamedPipes', 'Http', 'Via', 'SharedMemory')]
        [string]$Protocol = 'Tcp',
        [ValidateSet('All', 'None', 'Partner', 'Witness')]
        [string]$Role = 'All',
        [ValidateSet('Disabled', 'Required', 'Supported')]
        [string]$EndpointEncryption = 'Required',
        [ValidateSet('Aes', 'AesRC4', 'None', 'RC4', 'RC4Aes')]
        [string]$EncryptionAlgorithm = 'Aes',
        [string]$Certificate,
        [int]$Port,
        [int]$SslPort,
        [string]$Owner,
        [switch]$EnableException
    )
    process {
        if ((Test-Bound -ParameterName Name -Not)) {
            $name = "endpoint-" + [DateTime]::Now.ToString('s').Replace(":", "-")
        }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if (-not (Test-Bound -ParameterName Owner)) {
                $Owner = Get-SaLoginName -SqlInstance $server
            }

            if ($Certificate) {
                $cert = Get-DbaDbCertificate -SqlInstance $server -Certificate $Certificate
                if (-not $cert) {
                    Stop-Function -Message "Certificate $Certificate does not exist on $instance" -ErrorRecord $_ -Target $Certificate -Continue
                }
            }

            # Thanks to https://github.com/mmessano/PowerShell/blob/master/SQL-ConfigureDatabaseMirroring.ps1
            if ($Port) {
                $tcpPort = $port
            } else {
                $thisport = (Get-DbaEndPoint -SqlInstance $server).Protocol.Tcp
                $measure = $thisport | Measure-Object ListenerPort -Maximum

                if ($thisport.ListenerPort -eq 0) {
                    $tcpPort = 5022
                } elseif ($measure.Maximum) {
                    $maxPort = $measure.Maximum
                    #choose a random port that is greater than the current max port
                    $tcpPort = $maxPort + (New-Object Random).Next(1, 500)
                } else {
                    $maxPort = 5000
                    #choose a random port that is greater than the current max port
                    $tcpPort = $maxPort + (New-Object Random).Next(1, 500)
                }
            }

            if ($Pscmdlet.ShouldProcess($server.Name, "Creating endpoint $Name of type $Type using protocol $Protocol and if TCP then using Port $tcpPort")) {
                try {
                    $endpoint = New-Object Microsoft.SqlServer.Management.Smo.EndPoint $server, $Name
                    $endpoint.ProtocolType = [Microsoft.SqlServer.Management.Smo.ProtocolType]::$Protocol
                    $endpoint.EndpointType = [Microsoft.SqlServer.Management.Smo.EndpointType]::$Type
                    $endpoint.Owner = $Owner
                    if ($Protocol -eq "TCP") {
                        $endpoint.Protocol.Tcp.ListenerPort = $tcpPort
                        $endpoint.Payload.DatabaseMirroring.ServerMirroringRole = [Microsoft.SqlServer.Management.Smo.ServerMirroringRole]::$Role
                        if (Test-Bound -ParameterName SslPort) {
                            $endpoint.Protocol.Tcp.SslPort = $SslPort
                        }

                        $endpoint.Payload.DatabaseMirroring.EndpointEncryption = [Microsoft.SqlServer.Management.Smo.EndpointEncryption]::$EndpointEncryption
                        $endpoint.Payload.DatabaseMirroring.EndpointEncryptionAlgorithm = [Microsoft.SqlServer.Management.Smo.EndpointEncryptionAlgorithm]::$EncryptionAlgorithm

                    }
                    if ($Certificate) {
                        $outscript = $endpoint.Script()
                        $outscript = $outscript.Replace("ROLE = ALL,", "ROLE = ALL, AUTHENTICATION = CERTIFICATE $cert,")
                        $server.Query($outscript)
                    } else {
                        $null = $endpoint.Create()
                    }

                    $server.Endpoints.Refresh()
                    Get-DbaEndpoint -SqlInstance $server -Endpoint $name
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\New-DbaLogin.ps1
function New-DbaLogin {
    <#
    .SYNOPSIS
        Creates a new SQL Server login

    .DESCRIPTION
        Creates a new SQL Server login with provided specifications

    .PARAMETER SqlInstance
        The target SQL Server(s)

    .PARAMETER SqlCredential
        Allows you to login to SQL Server using alternative credentials

    .PARAMETER Login
        The Login name(s)

    .PARAMETER SecurePassword
        Secure string used to authenticate the Login

    .PARAMETER HashedPassword
        Hashed password string used to authenticate the Login

    .PARAMETER InputObject
        Takes the parameters required from a Login object that has been piped into the command

    .PARAMETER LoginRenameHashtable
        Pass a hash table into this parameter to change login names when piping objects into the procedure

    .PARAMETER MapToCertificate
        Map the login to a certificate

    .PARAMETER MapToAsymmetricKey
        Map the login to an asymmetric key

    .PARAMETER MapToCredential
        Map the login to a credential

    .PARAMETER Sid
        Provide an explicit Sid that should be used when creating the account. Can be [byte[]] or hex [string] ('0xFFFF...')

    .PARAMETER DefaultDatabase
        Default database for the login

    .PARAMETER Language
        Login's default language

    .PARAMETER PasswordExpiration
        Enforces password expiration policy. Requires PasswordPolicy to be enabled. Can be $true or $false(default)

    .PARAMETER PasswordPolicy
        Enforces password complexity policy. Can be $true or $false(default)

    .PARAMETER Disabled
        Create the login in a disabled state

    .PARAMETER NewSid
        Ignore sids from the piped login object to generate new sids on the server. Useful when copying login onto the same server

    .PARAMETER Force
        If login exists, drop and recreate

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Login, Security
        Author: Kirill Kravtsov (@nvarscar)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaLogin

    .EXAMPLE
        PS C:\> New-DbaLogin -SqlInstance Server1,Server2 -Login Newlogin

        You will be prompted to securely enter the password for a login [Newlogin]. The login would be created on servers Server1 and Server2 with default parameters.

    .EXAMPLE
        PS C:\> $securePassword = Read-Host "Input password" -AsSecureString
        PS C:\> New-DbaLogin -SqlInstance Server1\sql1 -Login Newlogin -Password $securePassword -PasswordPolicy -PasswordExpiration

        Creates a login on Server1\sql1 with a predefined password. The login will have password and expiration policies enforced onto it.

    .EXAMPLE
        PS C:\> Get-DbaLogin -SqlInstance sql1 -Login Oldlogin | New-DbaLogin -SqlInstance sql1 -LoginRenameHashtable @{Oldlogin = 'Newlogin'} -Force -NewSid -Disabled:$false

        Copies a login [Oldlogin] to the same instance sql1 with the same parameters (including password). New login will have a new sid, a new name [Newlogin] and will not be disabled. Existing login [Newlogin] will be removed prior to creation.

    .EXAMPLE
        PS C:\> Get-DbaLogin -SqlInstance sql1 -Login Login1,Login2 | New-DbaLogin -SqlInstance sql2 -PasswordPolicy -PasswordExpiration -DefaultDatabase tempdb -Disabled

        Copies logins [Login1] and [Login2] from instance sql1 to instance sql2, but enforces password and expiration policies for the new logins. New logins will also have a default database set to [tempdb] and will be created in a disabled state.

    .EXAMPLE
        PS C:\> New-DbaLogin -SqlInstance sql1 -Login domain\user

        Creates a new Windows Authentication backed login on sql1. The login will be part of the public server role.

    #>
    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = "Password", ConfirmImpact = "Low")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "", Justification = "For Parameters Password and MapToCredential")]
    param (
        [parameter(Mandatory, Position = 1)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Name", "LoginName")]
        [parameter(ParameterSetName = "Password", Position = 2)]
        [parameter(ParameterSetName = "PasswordHash")]
        [parameter(ParameterSetName = "MapToCertificate")]
        [parameter(ParameterSetName = "MapToAsymmetricKey")]
        [string[]]$Login,
        [parameter(ValueFromPipeline)]
        [parameter(ParameterSetName = "Password")]
        [parameter(ParameterSetName = "PasswordHash")]
        [parameter(ParameterSetName = "MapToCertificate")]
        [parameter(ParameterSetName = "MapToAsymmetricKey")]
        [object[]]$InputObject,
        [Alias("Rename")]
        [hashtable]$LoginRenameHashtable,
        [parameter(ParameterSetName = "Password", Position = 3)]
        [Alias("Password")]
        [Security.SecureString]$SecurePassword,
        [Alias("Hash", "PasswordHash")]
        [parameter(ParameterSetName = "PasswordHash")]
        [string]$HashedPassword,
        [parameter(ParameterSetName = "MapToCertificate")]
        [string]$MapToCertificate,
        [parameter(ParameterSetName = "MapToAsymmetricKey")]
        [string]$MapToAsymmetricKey,
        [string]$MapToCredential,
        [object]$Sid,
        [Alias("DefaulDB")]
        [parameter(ParameterSetName = "Password")]
        [parameter(ParameterSetName = "PasswordHash")]
        [string]$DefaultDatabase,
        [parameter(ParameterSetName = "Password")]
        [parameter(ParameterSetName = "PasswordHash")]
        [string]$Language,
        [Alias("Expiration", "CheckExpiration")]
        [parameter(ParameterSetName = "Password")]
        [parameter(ParameterSetName = "PasswordHash")]
        [switch]$PasswordExpiration,
        [Alias("Policy", "CheckPolicy")]
        [parameter(ParameterSetName = "Password")]
        [parameter(ParameterSetName = "PasswordHash")]
        [switch]$PasswordPolicy,
        [Alias("Disable")]
        [switch]$Disabled,
        [switch]$NewSid,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        if ($Sid) {
            if ($Sid.GetType().Name -ne 'Byte[]') {
                foreach ($symbol in $Sid.TrimStart("0x").ToCharArray()) {
                    if ($symbol -notin "0123456789ABCDEF".ToCharArray()) {
                        Stop-Function -Message "Sid has invalid character '$symbol', cannot proceed." -Category InvalidArgument -EnableException $EnableException
                        return
                    }
                }
                $Sid = Convert-HexStringToByte $Sid
            }
        }

        if ($HashedPassword) {
            if ($HashedPassword.GetType().Name -eq 'Byte[]') {
                $HashedPassword = Convert-ByteToHexString $HashedPassword
            }
        }
    }

    process {
        #At least one of those should be specified
        if (!($Login -or $InputObject)) {
            Stop-Function -Message "No logins have been specified." -Category InvalidArgument -EnableException $EnableException
            Return
        }

        $loginCollection = @()
        if ($InputObject) {
            $loginCollection += $InputObject
            if ($Login) {
                Stop-Function -Message "Parameter -Login is not supported when processing objects from -InputObject. If you need to rename the logins, please use -LoginRenameHashtable." -Category InvalidArgument -EnableException $EnableException
                Return
            }
        } else {
            $loginCollection += $Login
        }
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            foreach ($loginItem in $loginCollection) {
                #check if $loginItem is an SMO Login object
                if ($loginItem.GetType().Name -eq 'Login') {
                    #Get all the necessary fields
                    $loginName = $loginItem.Name
                    $loginType = $loginItem.LoginType
                    $currentSid = $loginItem.Sid
                    $currentDefaultDatabase = $loginItem.DefaultDatabase
                    $currentLanguage = $loginItem.Language
                    $currentPasswordExpiration = $loginItem.PasswordExpiration
                    $currentPasswordPolicyEnforced = $loginItem.PasswordPolicyEnforced
                    $currentDisabled = $loginItem.IsDisabled

                    #Get previous password
                    if ($loginType -eq 'SqlLogin' -and !($SecurePassword -or $HashedPassword)) {
                        $sourceServer = $loginItem.Parent
                        switch ($sourceServer.versionMajor) {
                            0 { $sql = "SELECT CONVERT(VARBINARY(256),password) as hashedpass FROM master.dbo.syslogins WHERE loginname='$loginName'" }
                            8 { $sql = "SELECT CONVERT(VARBINARY(256),password) as hashedpass FROM dbo.syslogins WHERE name='$loginName'" }
                            9 { $sql = "SELECT CONVERT(VARBINARY(256),password_hash) as hashedpass FROM sys.sql_logins where name='$loginName'" }
                            default {
                                $sql = "SELECT CAST(CONVERT(VARCHAR(256), CAST(LOGINPROPERTY(name,'PasswordHash')
                                    AS VARBINARY(256)), 1) AS NVARCHAR(max)) AS hashedpass
                                    FROM sys.server_principals
                                    WHERE principal_id = $($loginItem.id)"
                            }
                        }

                        try {
                            $hashedPass = $sourceServer.ConnectionContext.ExecuteScalar($sql)
                        } catch {
                            $hashedPassDt = $sourceServer.Databases['master'].ExecuteWithResults($sql)
                            $hashedPass = $hashedPassDt.Tables[0].Rows[0].Item(0)
                        }

                        if ($hashedPass.GetType().Name -ne "String") {
                            $hashedPass = Convert-ByteToHexString $hashedPass
                        }
                        $currentHashedPassword = $hashedPass
                    }

                    #Get cryptography and attached credentials
                    if ($loginType -eq 'AsymmetricKey') {
                        $currentAsymmetricKey = $loginItem.AsymmetricKey
                    }
                    if ($loginType -eq 'Certificate') {
                        $currentCertificate = $loginItem.Certificate
                    }
                    #This method or property is accessible only while working with SQL Server 2008 or later.
                    if ($sourceServer.versionMajor -gt 9) {
                        if ($loginItem.EnumCredentials()) {
                            $currentCredential = $loginItem.EnumCredentials()
                        }
                    }
                } else {
                    $loginName = $loginItem
                    $currentSid = $currentDefaultDatabase = $currentLanguage = $currentPasswordExpiration = $currentAsymmetricKey = $currentCertificate = $currentCredential = $currentDisabled = $currentPasswordPolicyEnforced = $null

                    if ($PsCmdlet.ParameterSetName -eq "MapToCertificate") { $loginType = 'Certificate' }
                    elseif ($PsCmdlet.ParameterSetName -eq "MapToAsymmetricKey") { $loginType = 'AsymmetricKey' }
                    elseif ($loginItem.IndexOf('\') -eq -1) {    $loginType = 'SqlLogin' }
                    else { $loginType = 'WindowsUser' }
                }

                if (($server.LoginMode -ne [Microsoft.SqlServer.Management.Smo.ServerLoginMode]::Mixed) -and ($loginType -eq 'SqlLogin')) {
                    Write-Message -Level Warning -Message "$instance does not have Mixed Mode enabled. [$loginName] is an SQL Login. Enable mixed mode authentication after the migration completes to use this type of login."
                }

                if ($Sid) {
                    $currentSid = $Sid
                }
                if ($DefaultDatabase) {
                    $currentDefaultDatabase = $DefaultDatabase
                }
                if ($Language) {
                    $currentLanguage = $Language
                }
                if ($PSBoundParameters.Keys -contains 'PasswordExpiration') {
                    $currentPasswordExpiration = $PasswordExpiration
                }
                if ($PSBoundParameters.Keys -contains 'PasswordPolicy') {
                    $currentPasswordPolicyEnforced = $PasswordPolicy
                }
                if ($PSBoundParameters.Keys -contains 'MapToAsymmetricKey') {
                    $currentAsymmetricKey = $MapToAsymmetricKey
                }
                if ($PSBoundParameters.Keys -contains 'MapToCertificate') {
                    $currentCertificate = $MapToCertificate
                }
                if ($PSBoundParameters.Keys -contains 'MapToCredential') {
                    $currentCredential = $MapToCredential
                }
                if ($PSBoundParameters.Keys -contains 'Disabled') {
                    $currentDisabled = $Disabled
                }

                #Apply renaming if necessary
                if ($LoginRenameHashtable.Keys -contains $loginName) {
                    $loginName = $LoginRenameHashtable[$loginName]
                }

                #Requesting password if required
                if ($loginItem.GetType().Name -ne 'Login' -and $loginType -eq 'SqlLogin' -and !($SecurePassword -or $HashedPassword)) {
                    $SecurePassword = Read-Host -AsSecureString -Prompt "Enter a new password for the SQL Server login(s)"
                }

                #verify if login exists on the server
                if (($existingLogin = $server.Logins[$loginName])) {
                    if ($force) {
                        if ($Pscmdlet.ShouldProcess($existingLogin, "Dropping existing login $loginName on $instance because -Force was used")) {
                            try {
                                $existingLogin.Drop()
                            } catch {
                                Stop-Function -Message "Could not remove existing login $loginName on $instance, skipping." -Target $loginName -Continue
                            }
                        }
                    } else {
                        Stop-Function -Message "Login $loginName already exists on $instance and -Force was not specified" -Target $loginName -Continue
                    }
                }


                if ($Pscmdlet.ShouldProcess($SqlInstance, "Creating login $loginName on $instance")) {
                    try {
                        $newLogin = New-Object Microsoft.SqlServer.Management.Smo.Login($server, $loginName)
                        $newLogin.LoginType = $loginType

                        $withParams = ""

                        if ($loginType -eq 'SqlLogin' -and $currentSid -and !$NewSid) {
                            Write-Message -Level Verbose -Message "Setting $loginName SID"
                            $withParams += ", SID = " + (Convert-ByteToHexString $currentSid)
                            $newLogin.Set_Sid($currentSid)
                        }

                        if ($loginType -in ("WindowsUser", "WindowsGroup", "SqlLogin")) {
                            if ($currentDefaultDatabase) {
                                Write-Message -Level Verbose -Message "Setting $loginName default database to $currentDefaultDatabase"
                                $withParams += ", DEFAULT_DATABASE = [$currentDefaultDatabase]"
                                $newLogin.DefaultDatabase = $currentDefaultDatabase
                            }

                            if ($currentLanguage) {
                                Write-Message -Level Verbose -Message "Setting $loginName language to $currentLanguage"
                                $withParams += ", DEFAULT_LANGUAGE = [$currentLanguage]"
                                $newLogin.Language = $currentLanguage
                            }

                            #CHECK_EXPIRATION: default - OFF
                            if ($currentPasswordExpiration) {
                                $withParams += ", CHECK_EXPIRATION = ON"
                                $newLogin.PasswordExpirationEnabled = $true
                            } else {
                                $withParams += ", CHECK_EXPIRATION = OFF"
                                $newLogin.PasswordExpirationEnabled = $false
                            }

                            #CHECK_POLICY: default - ON
                            if ($currentPasswordPolicyEnforced) {
                                $withParams += ", CHECK_POLICY = ON"
                                $newLogin.PasswordPolicyEnforced = $true
                            } else {
                                $withParams += ", CHECK_POLICY = OFF"
                                $newLogin.PasswordPolicyEnforced = $false
                            }

                            #Generate hashed password if necessary
                            if ($SecurePassword) {
                                $currentHashedPassword = Get-PasswordHash $SecurePassword $server.versionMajor
                            } elseif ($HashedPassword) {
                                $currentHashedPassword = $HashedPassword
                            }
                        } elseif ($loginType -eq 'AsymmetricKey') {
                            $newLogin.AsymmetricKey = $currentAsymmetricKey
                        } elseif ($loginType -eq 'Certificate') {
                            $newLogin.Certificate = $currentCertificate
                        }

                        #Add credential
                        if ($currentCredential) {
                            $withParams += ", CREDENTIAL = [$currentCredential]"
                        }

                        Write-Message -Level Verbose -Message "Adding as login type $loginType"

                        # Attempt to add login using SMO, then T-SQL
                        try {
                            if ($loginType -in ("WindowsUser", "WindowsGroup", "AsymmetricKey", "Certificate")) {
                                if ($withParams) { $withParams = " WITH " + $withParams.TrimStart(',') }
                                $newLogin.Create()
                            } elseif ($loginType -eq "SqlLogin") {
                                $newLogin.Create($currentHashedPassword, [Microsoft.SqlServer.Management.Smo.LoginCreateOptions]::IsHashed)
                            }
                            $newLogin.Refresh()

                            #Adding credential
                            if ($currentCredential) {
                                try {
                                    $newLogin.AddCredential($currentCredential)
                                } catch {
                                    $newLogin.Drop()
                                    Stop-Function -Message "Failed to add $loginName to $instance." -Category InvalidOperation -ErrorRecord $_ -Target $instance -Continue
                                }
                            }
                            Write-Message -Level Verbose -Message "Successfully added $loginName to $instance."
                        } catch {
                            Write-Message -Level Verbose -Message "Failed to create $loginName on $instance using SMO, trying T-SQL."
                            try {
                                if ($loginType -eq 'AsymmetricKey') { $sql = "CREATE LOGIN [$loginName] FROM ASYMMETRIC KEY [$currentAsymmetricKey]" }
                                elseif ($loginType -eq 'Certificate') { $sql = "CREATE LOGIN [$loginName] FROM CERTIFICATE [$currentCertificate]" }
                                elseif ($loginType -eq "SqlLogin") { $sql = "CREATE LOGIN [$loginName] WITH PASSWORD = $currentHashedPassword HASHED" + $withParams }
                                else { $sql = "CREATE LOGIN [$loginName] FROM WINDOWS" + $withParams }

                                $null = $server.Query($sql)
                                $newLogin = $server.logins[$loginName]
                                Write-Message -Level Verbose -Message "Successfully added $loginName to $instance."
                            } catch {
                                Stop-Function -Message "Failed to add $loginName to $instance." -Category InvalidOperation -ErrorRecord $_ -Target $instance -Continue
                            }
                        }

                        #Process the Disabled property
                        if ($currentDisabled) {
                            try {
                                $newLogin.Disable()
                                Write-Message -Level Verbose -Message "Login $loginName has been disabled on $instance."
                            } catch {
                                Write-Message -Level Verbose -Message "Failed to disable $loginName on $instance using SMO, trying T-SQL."
                                try {
                                    $sql = "ALTER LOGIN [$loginName] DISABLE"
                                    $null = $server.Query($sql)
                                    Write-Message -Level Verbose -Message "Login $loginName has been disabled on $instance."
                                } catch {
                                    Stop-Function -Message "Failed to disable $loginName on $instance." -Category InvalidOperation -ErrorRecord $_ -Target $instance -Continue
                                }
                            }
                        }
                        #Display results
                        Get-DbaLogin -SqlInstance $server -Login $loginName
                    } catch {
                        Stop-Function -Message "Failed to create login $loginName on $instance." -Target $credential -InnerErrorRecord $_ -Continue
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\New-DbaScriptingOption.ps1
function New-DbaScriptingOption {
    <#
    .SYNOPSIS
        Creates a new Microsoft.SqlServer.Management.Smo.ScriptingOptions object

    .DESCRIPTION
        Creates a new Microsoft.SqlServer.Management.Smo.ScriptingOptions object. Basically saves you the time from remembering the SMO assembly name ;)

        See https://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.scriptingoptions.aspx for more information

    .NOTES
        Tags: Migration, Backup, DR
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaScriptingOption

    .EXAMPLE
        PS C:\> $options = New-DbaScriptingOption
        PS C:\> $options.ScriptDrops = $false
        PS C:\> $options.WithDependencies = $true
        PS C:\> Get-DbaAgentJob -SqlInstance sql2016 | Export-DbaScript -ScriptingOptionObject $options

        Exports Agent Jobs with the Scripting Options ScriptDrops set to $false and WithDependencies set to true

    #>
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    param()
    New-Object Microsoft.SqlServer.Management.Smo.ScriptingOptions
}
tools\dbatools\functions\New-DbaServiceMasterKey.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function New-DbaServiceMasterKey {
    <#
    .SYNOPSIS
        Creates a new service master key.

    .DESCRIPTION
        Creates a new service master key in the master database.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Allows you to login to SQL Server using alternative credentials.

    .PARAMETER SecurePassword
        Secure string used to create the key.

    .PARAMETER Credential
        Enables easy creation of a secure password.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Certificate
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> New-DbaServiceMasterKey -SqlInstance Server1

        You will be prompted to securely enter your Service Key password, then a master key will be created in the master database on server1 if it does not exist.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [PSCredential]$Credential,
        [Alias("Password")]
        [Security.SecureString]$SecurePassword,
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            if ($PSCmdlet.ShouldProcess("$instance", "Creating New MasterKey")) {
                New-DbaDbMasterKey -SqlInstance $instance -Database master -SecurePassword $SecurePassword -Credential $Credential
            }
        }
    }
}
tools\dbatools\functions\New-DbaSsisCatalog.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function New-DbaSsisCatalog {
    <#
    .SYNOPSIS
        Enables the SSIS Catalog on a SQL Server 2012+

    .DESCRIPTION
        After installing the SQL Server Engine and SSIS you still have to enable the SSIS Catalog. This function will enable the catalog and gives the option of supplying the password.

    .PARAMETER SqlInstance
        SQL Server you wish to run the function on.

    .PARAMETER SqlCredential
        Credentials used to connect to the SQL Server

    .PARAMETER SecurePassword
        Required password that will be used for the security key in SSISDB.

    .PARAMETER Credential
        Use a credential object instead of a securepassword

    .PARAMETER SsisCatalog
        SSIS catalog name. By default, this is SSISDB.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: SSIS, SSISDB, Catalog
        Author: Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaSsisCatalog

    .EXAMPLE
        PS C:\> $SecurePassword = Read-Host -AsSecureString -Prompt "Enter password"
        PS C:\> New-DbaSsisCatalog -SqlInstance DEV01 -SecurePassword $SecurePassword

        Creates the SSIS Catalog on server DEV01 with the specified password.

    .EXAMPLE
        PS C:\> New-DbaSsisCatalog -SqlInstance sql2016 -Credential usernamedoesntmatter

        Creates the SSIS Catalog on server DEV01 with the specified password in the credential prompt. As the example username suggets the username does not matter.
        This is simply an easier way to get a secure password.
    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [PSCredential]$Credential,
        [Alias("Password")]
        [Security.SecureString]$SecurePassword,
        [string]$SsisCatalog = "SSISDB",
        [switch]$EnableException
    )
    begin {
        if (-not $SecurePassword -and -not $Credential) {
            Stop-Function -Message "You must specify either -SecurePassword or -Credential"
            return
        }
        if (-not $SecurePassword -and $Credential) {
            $SecurePassword = $Credential.Password
        }
    }
    process {
        if (Test-FunctionInterrupt) {
            return
        }
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            ## check if SSIS and Engine running on box
            $services = Get-DbaService -ComputerName $server.ComputerName

            $ssisservice = $Services | Where-Object {
                $_.ServiceType -eq "SSIS" -and $_.State -eq "Running"
            }

            if (-not $ssisservice) {
                Stop-Function -Message "SSIS is not running on $instance" -Continue -Target $instance
            }

            #if SQL 2012 or higher only validate databases with ContainmentType = NONE
            $clrenabled = Get-DbaSpConfigure -SqlInstance $server -Name IsSqlClrEnabled

            if (-not $clrenabled.RunningValue) {
                Stop-Function -Message 'CLR Integration must be enabled.  You can enable it by running Set-DbaSpConfigure -SqlInstance sql2012 -Config IsSqlClrEnabled -Value $true' -Continue -Target $instance
            }

            try {
                $ssis = New-Object Microsoft.SqlServer.Management.IntegrationServices.IntegrationServices $server
            } catch {
                Stop-Function -Message "Can't load server" -Target $instance -ErrorRecord $_
                return
            }

            if ($ssis.Catalogs.Count -gt 0) {
                Stop-Function -Message "SSIS Catalog already exists" -Continue -Target $ssis.Catalogs
            } else {
                if ($Pscmdlet.ShouldProcess($server, "Creating SSIS catalog: $SsisCatalog")) {
                    try {
                        $ssisdb = New-Object Microsoft.SqlServer.Management.IntegrationServices.Catalog ($ssis, $SsisCatalog, $(([System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($SecurePassword)))))
                    } catch {
                        Stop-Function -Message "Failed to create SSIS Catalog: $_" -Target $_ -Continue
                    }
                    try {
                        $ssisdb.Create()
                        [pscustomobject]@{
                            ComputerName = $server.ComputerName
                            InstanceName = $server.ServiceName
                            SqlInstance  = $server.DomainInstanceName
                            SsisCatalog  = $SsisCatalog
                            Created      = $true
                        }
                    } catch {
                        $msg = $_.Exception.InnerException.InnerException.Message
                        if (-not $msg) {
                            $msg = $_
                        }
                        Stop-Function -Message "$msg" -Target $_ -Continue
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\New-DbatoolsSupportPackage.ps1
function New-DbatoolsSupportPackage {
    <#
    .SYNOPSIS
        Creates a package of troubleshooting information that can be used by dbatools to help debug issues.

    .DESCRIPTION
        This function creates an extensive debugging package that can help with reproducing and fixing issues.

        The file will be created on the desktop by default and will contain quite a bit of information:
        - OS Information
        - Hardware Information (CPU, Ram, things like that)
        - .NET Information
        - PowerShell Information
        - Your input history
        - The In-Memory message log
        - The In-Memory error log
        - Screenshot of the console buffer (Basically, everything written in your current console, even if you have to scroll upwards to see it.

    .PARAMETER Path
        The folder where to place the output xml in.

    .PARAMETER Variables
        Name of additional variables to attach.
        This allows you to add the content of variables to the support package, if you believe them to be relevant to the case.

    .PARAMETER PassThru
        Returns file object that was created during execution.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Debug
        Author: Friedrich Weinmann (@FredWeinmann)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbatoolsSupportPackage

    .EXAMPLE
        PS C:\> New-DbatoolsSupportPackage

        Creates a large support pack in order to help us troubleshoot stuff.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [string]
        $Path = "$($env:USERPROFILE)\Desktop",

        [string[]]
        $Variables,

        [switch]
        $PassThru,

        [switch]
        [Alias('Silent')]$EnableException
    )

    begin {
        Write-Message -Level InternalComment -Message "Starting"
        Write-Message -Level Verbose -Message "Bound parameters: $($PSBoundParameters.Keys -join ", ")"

        #region Helper functions
        function Get-ShellBuffer {
            [CmdletBinding()]
            param ()

            try {
                # Define limits
                $rec = New-Object System.Management.Automation.Host.Rectangle
                $rec.Left = 0
                $rec.Right = $host.ui.rawui.BufferSize.Width - 1
                $rec.Top = 0
                $rec.Bottom = $host.ui.rawui.BufferSize.Height - 1

                # Load buffer
                $buffer = $host.ui.rawui.GetBufferContents($rec)

                # Convert Buffer to list of strings
                $int = 0
                $lines = @()
                while ($int -le $rec.Bottom) {
                    $n = 0
                    $line = ""
                    while ($n -le $rec.Right) {
                        $line += $buffer[$int, $n].Character
                        $n++
                    }
                    $line = $line.TrimEnd()
                    $lines += $line
                    $int++
                }

                # Measure empty lines at the beginning
                $int = 0
                $temp = $lines[$int]
                while ($temp -eq "") { $int++; $temp = $lines[$int] }

                # Measure empty lines at the end
                $z = $rec.Bottom
                $temp = $lines[$z]
                while ($temp -eq "") { $z--; $temp = $lines[$z] }

                # Skip the line launching this very function
                $z--

                # Measure empty lines at the end (continued)
                $temp = $lines[$z]
                while ($temp -eq "") { $z--; $temp = $lines[$z] }

                # Cut results to the limit and return them
                return $lines[$int .. $z]
            } catch {
                # here to avoid an empty catch
                $null = 1
            }
        }
        #endregion Helper functions
    }
    process {
        if ($Pscmdlet.ShouldProcess("Creating a Support Package for diagnosing Dbatools")) {

            $filePathXml = "$($Path.Trim('\'))\dbatools_support_pack_$(Get-Date -Format "yyyy_MM_dd-HH_mm_ss").xml"
            $filePathZip = $filePathXml -replace "\.xml$", ".zip"

            Write-Message -Level Critical -Message @"
Gathering information...
Will write the final output to: $filePathZip

Please submit this file to the team, to help with troubleshooting whatever issue you encountered.
Be aware that this package contains a lot of information including your input history in the console.
Please make sure no sensitive data (such as passwords) can be caught this way.

Ideally start a new console, perform the minimal steps required to reproduce the issue, then run this command.
This will make it easier for us to troubleshoot and you won't be sending us the keys to your castle.
"@

            $hash = @{ }
            Write-Message -Level Output -Message "Collecting dbatools logged messages (Get-DbatoolsLog)"
            $hash["Messages"] = Get-DbatoolsLog
            Write-Message -Level Output -Message "Collecting dbatools logged errors (Get-DbatoolsLog -Errors)"
            $hash["Errors"] = Get-DbatoolsLog -Errors
            Write-Message -Level Output -Message "Collecting copy of console buffer (what you can see on your console)"
            $hash["ConsoleBuffer"] = Get-ShellBuffer
            Write-Message -Level Output -Message "Collecting Operating System information (Win32_OperatingSystem)"
            $hash["OperatingSystem"] = Get-DbaCmObject -ClassName Win32_OperatingSystem
            Write-Message -Level Output -Message "Collecting CPU information (Win32_Processor)"
            $hash["CPU"] = Get-DbaCmObject -ClassName Win32_Processor
            Write-Message -Level Output -Message "Collecting Ram information (Win32_PhysicalMemory)"
            $hash["Ram"] = Get-DbaCmObject -ClassName Win32_PhysicalMemory
            Write-Message -Level Output -Message "Collecting PowerShell & .NET Version (`$PSVersionTable)"
            $hash["PSVersion"] = $PSVersionTable
            Write-Message -Level Output -Message "Collecting Input history (Get-History)"
            $hash["History"] = Get-History
            Write-Message -Level Output -Message "Collecting list of loaded modules (Get-Module)"
            $hash["Modules"] = Get-Module
            # Snapins not supported in Core: https://github.com/PowerShell/PowerShell/issues/6135
            if ($PSVersionTable.PSEdition -ne 'Core') {
                Write-Message -Level Output -Message "Collecting list of loaded snapins (Get-PSSnapin)"
                $hash["SnapIns"] = Get-PSSnapin
            }
            Write-Message -Level Output -Message "Collecting list of loaded assemblies (Name, Version, and Location)"
            $hash["Assemblies"] = [appdomain]::CurrentDomain.GetAssemblies() | Select-Object CodeBase, FullName, Location, ImageRuntimeVersion, GlobalAssemblyCache, IsDynamic

            if (Test-Bound "Variables") {
                Write-Message -Level Output -Message "Adding variables specified for export: $($Variables -join ", ")"
                $hash["Variables"] = $Variables | Get-Variable -ErrorAction Ignore
            }

            $data = [pscustomobject]$hash

            try { $data | Export-Clixml -Path $filePathXml -ErrorAction Stop }
            catch {
                Stop-Function -Message "Failed to export dump to file!" -ErrorRecord $_ -Target $filePathXml
                return
            }

            try { Compress-Archive -Path $filePathXml -DestinationPath $filePathZip -ErrorAction Stop }
            catch {
                Stop-Function -Message "Failed to pack dump-file into a zip archive. Please do so manually before submitting the results as the unpacked xml file will be rather large." -ErrorRecord $_ -Target $filePathZip
                return
            }

            Remove-Item -Path $filePathXml -ErrorAction Ignore
            if ($PassThru) {
                Get-Item $filePathZip
            }
        }
    }
    end {
        Write-Message -Level InternalComment -Message "Ending"
    }
}
tools\dbatools\functions\New-DbaXESession.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function New-DbaXESession {
    <#
    .SYNOPSIS
        Creates a new XESession object - for the dogged.

    .DESCRIPTION
        Creates a new XESession object - for the dogged (very manual, Import-DbaXESessionTemplate is recommended). See the following for more info:

        https://docs.microsoft.com/en-us/sql/relational-databases/extended-events/use-the-powershell-provider-for-extended-events

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Name
        The Name of the session to be created.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaXESession

    .EXAMPLE
        PS C:\> $session = New-DbaXESession -SqlInstance sql2017 -Name XeSession_Test
        PS C:\> $event = $session.AddEvent("sqlserver.file_written")
        PS C:\> $event.AddAction("package0.callstack")
        PS C:\> $session.Create()

        Returns a new XE Session object from sql2017 then adds an event, an action then creates it.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(Mandatory)]
        [string]$Name,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 11
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($Pscmdlet.ShouldProcess($instance, "Creating new XESession")) {
                $SqlConn = $server.ConnectionContext.SqlConnectionObject
                $SqlStoreConnection = New-Object Microsoft.SqlServer.Management.Sdk.Sfc.SqlStoreConnection $SqlConn
                $store = New-Object  Microsoft.SqlServer.Management.XEvent.XEStore $SqlStoreConnection

                $store.CreateSession($Name)
            }
        }
    }
}
tools\dbatools\functions\New-DbaXESmartCsvWriter.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function New-DbaXESmartCsvWriter {
    <#
    .SYNOPSIS
        This response type is used to write Extended Events to a CSV file.

    .DESCRIPTION
        This response type is used to write Extended Events to a CSV file.

    .PARAMETER OutputFile
        Specifies the path to the output CSV file.

    .PARAMETER Overwrite
        Specifies whether any existiting file should be overwritten or not.

    .PARAMETER OutputColumn
        Specifies the list of columns to output from the events. XESmartTarget will capture in memory and write to the target table only the columns (fields or targets) that are present in this list.

        Fields and actions are matched in a case-sensitive manner.

        Expression columns are supported. Specify a column with ColumnName AS Expression to add an expression column (Example: Total AS Reads + Writes)

    .PARAMETER Event
        Specifies a list of events to be processed (with others being ignored. By default, all events are processed.

    .PARAMETER Filter
        Specifies a filter expression in the same form as you would use in the WHERE clause of a SQL query.

        Example: duration > 10000 AND cpu_time > 10000

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl) | SmartTarget by Gianluca Sartori (@spaghettidba)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaXESmartCsvWriter

    .EXAMPLE
        PS C:\> $columns = "cpu_time", "duration", "physical_reads", "logical_reads", "writes", "row_count"
        PS C:\> $response = New-DbaXESmartCsvWriter -OutputFile c:\temp\workload.csv -OutputColumn $columns -OverWrite -Event "sql_batch_completed"
        PS C:\> Start-DbaXESmartTarget -SqlInstance localhost\sql2017 -Session "Profiler Standard" -Responder $response

        Writes Extended Events to the file "C:\temp\workload.csv".

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [string]$OutputFile,
        [switch]$Overwrite,
        [string[]]$Event,
        [string[]]$OutputColumn,
        [string]$Filter,
        [switch]$EnableException
    )

    begin {
        try {
            Add-Type -Path "$script:PSModuleRoot\bin\XESmartTarget\XESmartTarget.Core.dll" -ErrorAction Stop
        } catch {
            Stop-Function -Message "Could not load XESmartTarget.Core.dll" -ErrorRecord $_ -Target "XESmartTarget"
            return
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }

        if ($Pscmdlet.ShouldProcess("Creating new XESmartCsvWriter Object")) {
            try {
                $writer = New-Object -TypeName XESmartTarget.Core.Responses.CsvAppenderResponse
                $writer.OutputFile = $OutputFile
                $writer.OverWrite = $Overwrite
                if (Test-Bound -ParameterName "Event") {
                    $writer.Events = $Event
                }
                if (Test-Bound -ParameterName "OutputColumn") {
                    $writer.OutputColumns = $OutputColumn
                }
                if (Test-Bound -ParameterName "Filter") {
                    $writer.Filter = $Filter
                }
                $writer
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Target "XESmartTarget" -Continue
            }
        }
    }
}
tools\dbatools\functions\New-DbaXESmartEmail.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function New-DbaXESmartEmail {
    <#
    .SYNOPSIS
        This response type can be used to send an email each time an event is captured.

    .DESCRIPTION
        This response type can be used to send an email each time an event is captured.

    .PARAMETER SmtpServer
        Address of the SMTP server for outgoing mail.

    .PARAMETER Sender
        Sender's email address.

    .PARAMETER To
        Address of the To recipient(s).

    .PARAMETER Cc
        Address of the Cc recipient(s).

    .PARAMETER Bcc
        Address of the Bcc recipient(s).

    .PARAMETER Credential
        Credential object containing username and password used to authenticate on the SMTP server. When blank, no authentication is performed.

    .PARAMETER Subject
        Subject of the mail message. Accepts placeholders in the text.

        Placeholders are in the form {PropertyName}, where PropertyName is one of the fields or actions available in the Event object.

        For instance, a valid Subject in a configuration file looks like this: "An event of name {Name} occurred at {collection_time}"

    .PARAMETER Body
        Body of the mail message. The body can be static text or any property taken from the underlying event. See Subject for a description of how placeholders work.

    .PARAMETER Attachment
        Data to attach to the email message. At this time, it can be any of the fields/actions of the underlying event. The data from the field/action is attached to the message as an ASCII stream. A single attachment is supported.

    .PARAMETER AttachmentFileName
        File name to assign to the attachment.

    .PARAMETER PlainText
        If this switch is enabled, the email will be sent in plain text. By default, HTML formatting is used.

    .PARAMETER Event
        Each Response can be limited to processing specific events, while ignoring all the other ones. When this attribute is omitted, all events are processed.

    .PARAMETER Filter
        You can specify a filter expression by using this attribute. The filter expression is in the same form that you would use in a SQL query. For example, a valid example looks like this: duration > 10000 AND cpu_time > 10000

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl) | SmartTarget by Gianluca Sartori (@spaghettidba)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaXESmartEmail

    .EXAMPLE
        PS C:\> $params = @{
        >> SmtpServer = "smtp.ad.local"
        >> To = "[email protected]"
        >> Sender = "[email protected]"
        >> Subject = "Query executed"
        >> Body = "Query executed at {collection_time}"
        >> Attachment = "batch_text"
        >> AttachmentFileName = "query.sql"
        >> }
        >>
        PS C:\> $emailresponse = New-DbaXESmartEmail @params
        PS C:\> Start-DbaXESmartTarget -SqlInstance sql2017 -Session querytracker -Responder $emailresponse

        Sends an email each time a querytracker event is captured.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [string]$SmtpServer,
        [parameter(Mandatory)]
        [string]$Sender,
        [parameter(Mandatory)]
        [string[]]$To,
        [string[]]$Cc,
        [string[]]$Bcc,
        [pscredential]$Credential,
        [parameter(Mandatory)]
        [string]$Subject,
        [parameter(Mandatory)]
        [string]$Body,
        [string]$Attachment,
        [string]$AttachmentFileName,
        [string]$PlainText,
        [string[]]$Event,
        [string]$Filter,
        [switch]$EnableException
    )
    begin {
        try {
            Add-Type -Path "$script:PSModuleRoot\bin\XESmartTarget\XESmartTarget.Core.dll" -ErrorAction Stop
        } catch {
            Stop-Function -Message "Could not load XESmartTarget.Core.dll." -ErrorRecord $_ -Target "XESmartTarget"
            return
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }

        if ($Pscmdlet.ShouldProcess("Creating new XESmartEmail Object")) {
            try {
                $email = New-Object -TypeName XESmartTarget.Core.Responses.EmailResponse
                $email.SmtpServer = $SmtpServer
                $email.Sender = $Sender
                $email.To = $To
                $email.Cc = $Cc
                $email.Bcc = $Bcc
                $email.Subject = $Subject
                $email.Body = $Body
                $email.Attachment = $Attachment
                $email.AttachmentFileName = $AttachmentFileName
                $email.HTMLFormat = ($PlainText -eq $false)
                if (Test-Bound -ParameterName "Event") {
                    $email.Events = $Event
                }
                if (Test-Bound -ParameterName "Filter") {
                    $email.Filter = $Filter
                }

                if ($Credential) {
                    $email.UserName = $Credential.UserName
                    $email.Password = $Credential.GetNetworkCredential().Password
                }

                $email
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Target "XESmartTarget" -Continue
            }
        }
    }
}
tools\dbatools\functions\New-DbaXESmartQueryExec.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function New-DbaXESmartQueryExec {
    <#
    .SYNOPSIS
        This response type executes a T-SQL command against a target database whenever an event is recorded.

    .DESCRIPTION
        This response type executes a T-SQL command against a target database whenever an event is recorded.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies the name of the database that contains the target table.

    .PARAMETER Query
        The T-SQL command to execute. This string can contain placeholders for properties taken from the events.

        Placeholders are in the form {PropertyName}, where PropertyName is one of the fields or actions available in the Event object.

    .PARAMETER Event
        Each Response can be limited to processing specific events, while ignoring all the other ones. When this attribute is omitted, all events are processed.

    .PARAMETER Filter
        You can specify a filter expression by using this attribute. The filter expression is in the same form that you would use in a SQL query. For example, a valid example looks like this: duration > 10000 AND cpu_time > 10000

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl) | SmartTarget by Gianluca Sartori (@spaghettidba)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaXESmartQueryExec

    .EXAMPLE
        PS C:\> $response = New-DbaXESmartQueryExec -SqlInstance sql2017 -Database dbadb -Query "update table set whatever = 1"
        PS C:\> Start-DbaXESmartTarget -SqlInstance sql2017 -Session deadlock_tracker -Responder $response

        Executes a T-SQL command against dbadb on sql2017 whenever a deadlock event is recorded.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$Database,
        [string]$Query,
        [switch]$EnableException,
        [string[]]$Event,
        [string]$Filter
    )
    begin {
        try {
            Add-Type -Path "$script:PSModuleRoot\XESmartTarget\XESmartTarget.Core.dll" -ErrorAction Stop
        } catch {
            Stop-Function -Message "Could not load XESmartTarget.Core.dll" -ErrorRecord $_ -Target "XESmartTarget"
            return
        }
    }
    process {
        if (Test-FunctionInterrupt) {
            return
        }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 11
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($Pscmdlet.ShouldProcess($instance, "Creating new XESmartQueryExec")) {
                $execute = New-Object -TypeName XESmartTarget.Core.Responses.ExecuteTSQLResponse
                $execute.ServerName = $server.Name
                $execute.DatabaseName = $Database
                $execute.TSQL = $Query

                if ($SqlCredential) {
                    $execute.UserName = $SqlCredential.UserName
                    $execute.Password = $SqlCredential.GetNetworkCredential().Password
                }

                if (Test-Bound -ParameterName "Event") {
                    $execute.Events = $Event
                }
                if (Test-Bound -ParameterName "Filter") {
                    $execute.Filter = $Filter
                }

                $execute
            }
        }
    }
}
tools\dbatools\functions\New-DbaXESmartReplay.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function New-DbaXESmartReplay {
    <#
    .SYNOPSIS
        This response type can be used to replay execution related events to a target SQL Server instance.

    .DESCRIPTION
        This response type can be used to replay execution related events to a target SQL Server instance. The events that you can replay are of the type sql_batch_completed and rpc_completed: all other events are ignored.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Name of the initial catalog to connect to. Statements will be replayed by changing database to the same database where the event was originally captured, so this property only controls the initial database to connect to.

    .PARAMETER Event
        Each Response can be limited to processing specific events, while ignoring all the other ones. When this attribute is omitted, all events are processed.

    .PARAMETER Filter
        Specifies a filter expression in the same form as you would use in the WHERE clause of a SQL query.

        Example: duration > 10000 AND cpu_time > 10000

    .PARAMETER DelaySeconds
        Specifies the duration of the delay in seconds.

    .PARAMETER ReplayIntervalSeconds
        Specifies the duration of the replay interval in seconds.

    .PARAMETER StopOnError
        If this switch is enabled, the replay will be stopped when the first error is encountered. By default, error messages are piped to the log and console output, and replay proceeds.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl) | SmartTarget by Gianluca Sartori (@spaghettidba)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/New-DbaXESmartReplay

    .EXAMPLE
        PS C:\> $response = New-DbaXESmartReplay -SqlInstance sql2017 -Database planning
        PS C:\> Start-DbaXESmartTarget -SqlInstance sql2016 -Session loadrelay -Responder $response

        Replays events from sql2016 on sql2017 in the planning database. Returns a PowerShell job object.

        To see a list of all SmartTarget job objects, use Get-DbaXESmartTarget.

    .EXAMPLE
        PS C:\> $response = New-DbaXESmartReplay -SqlInstance sql2017 -Database planning
        PS C:\> Start-DbaXESmartTarget -SqlInstance sql2017 -Session 'Profiler Standard' -Responder $response -NotAsJob

        Replays events from the 'Profiler Standard' session on sql2016 to sql2017's planning database. Does not run as a job so you can see the raw output.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$Database,
        [string[]]$Event = "sql_batch_completed",
        [string]$Filter,
        [int]$DelaySeconds,
        [switch]$StopOnError,
        [int]$ReplayIntervalSeconds,
        [switch]$EnableException
    )
    begin {
        try {
            Add-Type -Path "$script:PSModuleRoot\bin\XESmartTarget\XESmartTarget.Core.dll" -ErrorAction Stop
        } catch {
            Stop-Function -Message "Could not load XESmartTarget.Core.dll" -ErrorRecord $_ -Target "XESmartTarget"
            return
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 11
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            if ($Pscmdlet.ShouldProcess($instance, "Creating new XESmartReply")) {
                Write-Message -Message "Making a New XE SmartReplay for $Event against $instance running on $($server.name)" -Level Verbose
                try {
                    $replay = New-Object -TypeName XESmartTarget.Core.Responses.ReplayResponse
                    $replay.ServerName = $instance
                    $replay.DatabaseName = $Database
                    $replay.Events = $Event
                    $replay.StopOnError = $StopOnError
                    $replay.Filter = $Filter
                    $replay.DelaySeconds = $DelaySeconds
                    $replay.ReplayIntervalSeconds = $ReplayIntervalSeconds

                    if ($SqlCredential) {
                        $replay.UserName = $SqlCredential.UserName
                        $replay.Password = $SqlCredential.GetNetworkCredential().Password
                    }

                    $replay
                } catch {
                    $message = $_.Exception.InnerException.InnerException | Out-String
                    Stop-Function -Message $message -Target "XESmartTarget" -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\New-DbaXESmartTableWriter.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function New-DbaXESmartTableWriter {
    <#
    .SYNOPSIS
        This response type is used to write Extended Events to a database table.

    .DESCRIPTION
        This response type is used to write Extended Events to a database table. The events are temporarily stored in memory before being written to the database at regular intervals.

        The target table can be created manually upfront or you can let the TableAppenderResponse create a target table based on the fields and actions available in the events captured.

        The columns of the target table and the fields/actions of the events are mapped by name (case-sensitive).

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies the name of the database that contains the target table.

    .PARAMETER Table
        Specifies the name of the target table.

    .PARAMETER AutoCreateTargetTable
        If this switch is enabled, XESmartTarget will infer the definition of the target table from the columns captured in the Extended Events session.

        If the target table already exists, it will not be recreated.

    .PARAMETER UploadIntervalSeconds
        Specifies the number of seconds XESmartTarget will keep the events in memory before dumping them to the target table. The default is 10 seconds.

    .PARAMETER OutputColumn
        Specifies the list of columns to output from the events. XESmartTarget will capture in memory and write to the target table only the columns (fields or targets) that are present in this list.

        Fields and actions are matched in a case-sensitive manner.

        Expression columns are supported. Specify a column with ColumnName AS Expression to add an expression column (Example: Total AS Reads + Writes)

    .PARAMETER Event
        Specifies a list of events to be processed (with others being ignored. By default, all events are processed.

    .PARAMETER Filter
        Specifies a filter expression in the same form as you would use in the WHERE clause of a SQL query.

        Example: duration > 10000 AND cpu_time > 10000

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl) | SmartTarget by Gianluca Sartori (@spaghettidba)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT
        SmartTarget: by Gianluca Sartori (@spaghettidba)

    .LINK
        https://dbatools.io/New-DbaXESmartTableWriter

    .EXAMPLE
        PS C:\> $columns = "cpu_time", "duration", "physical_reads", "logical_reads", "writes", "row_count", "batch_text"
        PS C:\> $response = New-DbaXESmartTableWriter -SqlInstance sql2017 -Database dbadb -Table deadlocktracker -OutputColumn $columns -Filter "duration > 10000"
        PS C:\> Start-DbaXESmartTarget -SqlInstance sql2017 -Session deadlock_tracker -Responder $response

        Writes Extended Events to the deadlocktracker table in dbadb on sql2017.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(Mandatory)]
        [string]$Database,
        [parameter(Mandatory)]
        [string]$Table,
        [switch]$AutoCreateTargetTable,
        [int]$UploadIntervalSeconds = 10,
        [string[]]$Event,
        [string[]]$OutputColumn,
        [string]$Filter,
        [switch]$EnableException
    )
    begin {
        try {
            Add-Type -Path "$script:PSModuleRoot\bin\XESmartTarget\XESmartTarget.Core.dll" -ErrorAction Stop
        } catch {
            Stop-Function -Message "Could not load XESmartTarget.Core.dll" -ErrorRecord $_ -Target "XESmartTarget"
            return
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 11
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            if ($Pscmdlet.ShouldProcess($instance, "Creating new XESmartTableWriter")) {
                try {
                    $writer = New-Object -TypeName XESmartTarget.Core.Responses.TableAppenderResponse
                    $writer.ServerName = $server.Name
                    $writer.DatabaseName = $Database
                    $writer.TableName = $Table
                    $writer.AutoCreateTargetTable = $AutoCreateTargetTable
                    $writer.UploadIntervalSeconds = $UploadIntervalSeconds
                    if (Test-Bound -ParameterName "Event") {
                        $writer.Events = $Event
                    }
                    if (Test-Bound -ParameterName "OutputColumn") {
                        $writer.OutputColumns = $OutputColumn
                    }
                    if (Test-Bound -ParameterName "Filter") {
                        $writer.Filter = $Filter
                    }
                    $writer
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target "XESmartTarget" -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Publish-DbaDacPackage.ps1
function Publish-DbaDacPackage {
    <#
    .SYNOPSIS
        The Publish-DbaDacPackage command takes a dacpac which is the output from an SSDT project and publishes it to a database. Changing the schema to match the dacpac and also to run any scripts in the dacpac (pre/post deploy scripts).

    .DESCRIPTION
        Deploying a dacpac uses the DacFx which historically needed to be installed on a machine prior to use. In 2016 the DacFx was supplied by Microsoft as a nuget package (Microsoft.Data.Tools.MSBuild) and this uses that nuget package.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Path
        Specifies the filesystem path to the DACPAC

    .PARAMETER PublishXml
        Specifies the publish profile which will include options and sqlCmdVariables.

    .PARAMETER Database
        Specifies the name of the database being published.

    .PARAMETER ConnectionString
        Specifies the connection string to the database you are upgrading. This is not required if SqlInstance is specified.

    .PARAMETER GenerateDeploymentScript
        If this switch is enabled, the publish script will be generated.

    .PARAMETER GenerateDeploymentReport
        If this switch is enabled, the publish XML report  will be generated.

    .PARAMETER Type
        Selecting the type of the export: Dacpac (default) or Bacpac.

    .PARAMETER DacOption
        Export options for a corresponding export type. Can be created by New-DbaDacOption -Type Dacpac | Bacpac

    .PARAMETER OutputPath
        Specifies the filesystem path (directory) where output files will be generated.

    .PARAMETER ScriptOnly
        If this switch is enabled, only the change scripts will be generated.

    .PARAMETER IncludeSqlCmdVars
        If this switch is enabled, SqlCmdVars in publish.xml will have their values overwritten.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER DacFxPath
        Path to the dac dll. If this is ommited, then the version of dac dll which is packaged with dbatools is used.

    .NOTES
        Tags: Migration, Database, Dacpac
        Author: Richie lee (@richiebzzzt)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Publish-DbaDacPackage

    .EXAMPLE
        PS C:\> $options = New-DbaDacOption -Type Dacpac -Action Publish
        PS C:\> $options.DeployOptions.DropObjectsNotInSource = $true
        PS C:\> Publish-DbaDacPackage -SqlInstance sql2016 -Database DB1 -DacOption $options -Path c:\temp\db.dacpac

        Uses DacOption object to set Deployment Options and updates DB1 database on sql2016 from the db.dacpac dacpac file, dropping objects that are missing from source.

    .EXAMPLE
        PS C:\> Publish-DbaDacPackage -SqlInstance sql2017 -Database WideWorldImporters -Path C:\temp\sql2016-WideWorldImporters.dacpac -PublishXml C:\temp\sql2016-WideWorldImporters-publish.xml -Confirm

        Updates WideWorldImporters on sql2017 from the sql2016-WideWorldImporters.dacpac using the sql2016-WideWorldImporters-publish.xml publish profile. Prompts for confirmation.

    .EXAMPLE
        PS C:\> New-DbaDacProfile -SqlInstance sql2016 -Database db2 -Path C:\temp
        PS C:\> Export-DbaDacPackage -SqlInstance sql2016 -Database db2 | Publish-DbaDacPackage -PublishXml C:\temp\sql2016-db2-publish.xml -Database db1, db2 -SqlInstance sql2017

        Creates a publish profile at C:\temp\sql2016-db2-publish.xml, exports the .dacpac to $home\Documents\sql2016-db2.dacpac. Does not prompt for confirmation.
        then publishes it to the sql2017 server database db2

    .EXAMPLE
        PS C:\> $loc = "C:\Users\bob\source\repos\Microsoft.Data.Tools.Msbuild\lib\net46\Microsoft.SqlServer.Dac.dll"
        PS C:\> Publish-DbaDacPackage -SqlInstance "local" -Database WideWorldImporters -Path C:\temp\WideWorldImporters.dacpac -PublishXml C:\temp\WideWorldImporters.publish.xml -DacFxPath $loc -Confirm
    
        Publishes the dacpac using a specific dacfx library. Prompts for confirmation.

    .EXAMPLE
        PS C:\> Publish-DbaDacPackage -SqlInstance sql2017 -Database WideWorldImporters -Path C:\temp\sql2016-WideWorldImporters.dacpac -PublishXml C:\temp\sql2016-WideWorldImporters-publish.xml -GenerateDeploymentScript -ScriptOnly

        Does not deploy the changes, but will generate the deployment script that would be executed against WideWorldImporters.

    .EXAMPLE
        PS C:\> Publish-DbaDacPackage -SqlInstance sql2017 -Database WideWorldImporters -Path C:\temp\sql2016-WideWorldImporters.dacpac -PublishXml C:\temp\sql2016-WideWorldImporters-publish.xml -GenerateDeploymentReport -ScriptOnly

        Does not deploy the changes, but will generate the deployment report that would be executed against WideWorldImporters.
    #>
    [CmdletBinding(DefaultParameterSetName = 'Obj', SupportsShouldProcess, ConfirmImpact = 'Medium')]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [string]$Path,
        [Parameter(Mandatory, ParameterSetName = 'Xml')]
        [string]$PublishXml,
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [string[]]$Database,
        [string[]]$ConnectionString,
        [parameter(ParameterSetName = 'Xml')]
        [switch]$GenerateDeploymentScript,
        [parameter(ParameterSetName = 'Xml')]
        [switch]$GenerateDeploymentReport,
        [Switch]$ScriptOnly,
        [ValidateSet('Dacpac', 'Bacpac')]
        [string]$Type = 'Dacpac',
        [string]$OutputPath = "$home\Documents",
        [switch]$IncludeSqlCmdVars,
        [Parameter(ParameterSetName = 'Obj')]
        [Alias("Option")]
        [object]$DacOption,
        [switch]$EnableException,
        [String]$DacFxPath
    )

    begin {
        if ((Test-Bound -Not -ParameterName SqlInstance) -and (Test-Bound -Not -ParameterName ConnectionString)) {
            Stop-Function -Message "You must specify either SqlInstance or ConnectionString."
            return
        }
        if ($Type -eq 'Dacpac') {
            if ((Test-Bound -ParameterName GenerateDeploymentScript) -or (Test-Bound -ParameterName GenerateDeploymentReport)) {
                $defaultcolumns = 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Dacpac', 'PublishXml', 'Result', 'DatabaseScriptPath', 'MasterDbScriptPath', 'DeploymentReport', 'DeployOptions', 'SqlCmdVariableValues'
            } else {
                $defaultcolumns = 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Dacpac', 'PublishXml', 'Result', 'DeployOptions', 'SqlCmdVariableValues'
            }
        } elseif ($Type -eq 'Bacpac') {
            if ($ScriptOnly -or $GenerateDeploymentReport -or $GenerateDeploymentScript) {
                Stop-Function -Message "ScriptOnly, GenerateDeploymentScript, and GenerateDeploymentReport cannot be used in a Bacpac scenario." -ErrorRecord $_
                return
            }
            $defaultcolumns = 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Bacpac', 'Result', 'DeployOptions'
        }

        if ((Test-Bound -ParameterName ScriptOnly) -and (Test-Bound -Not -ParameterName GenerateDeploymentScript) -and (Test-Bound -Not -ParameterName GenerateDeploymentScript)) {
            Stop-Function -Message "You must at least one of GenerateDeploymentScript or GenerateDeploymentReport when using ScriptOnly"
            return
        }

        function Get-ServerName ($connstring) {
            $builder = New-Object System.Data.Common.DbConnectionStringBuilder
            $builder.set_ConnectionString($connstring)
            $instance = $builder['data source']

            if (-not $instance) {
                $instance = $builder['server']
            }

            return $instance.ToString().Replace('\', '-').Replace('(', '').Replace(')', '')
        }

        if ((Test-Bound -Not -ParameterName 'DacfxPath') -and (-not $script:core)) {
            $dacfxPath = "$script:PSModuleRoot\bin\smo\Microsoft.SqlServer.Dac.dll"

            if ((Test-Path $dacfxPath) -eq $false) {
                Stop-Function -Message 'No usable version of Dac Fx found.' -EnableException $EnableException
                return
            } else {
                try {
                    Add-Type -Path $dacfxPath
                    Write-Message -Level Verbose -Message "Dac Fx loaded."
                } catch {
                    Stop-Function -Message 'No usable version of Dac Fx found.' -EnableException $EnableException -ErrorRecord $_
                }
            }
        }

        #Check Option object types - should have a specific type
        if ($Type -eq 'Dacpac') {
            if ($DacOption -and $DacOption -isnot [Microsoft.SqlServer.Dac.PublishOptions]) {
                Stop-Function -Message "Microsoft.SqlServer.Dac.PublishOptions object type is expected - got $($DacOption.GetType())."
                return
            }
        } elseif ($Type -eq 'Bacpac') {
            if ($DacOption -and $DacOption -isnot [Microsoft.SqlServer.Dac.DacImportOptions]) {
                Stop-Function -Message "Microsoft.SqlServer.Dac.DacImportOptions object type is expected - got $($DacOption.GetType())."
                return
            }
        }
    }

    process {
        if (Test-FunctionInterrupt) {
            return
        }

        if (-not (Test-Path -Path $Path)) {
            Stop-Function -Message "$Path not found!"
            return
        }

        if ($PsCmdlet.ParameterSetName -eq 'Xml') {
            if (-not (Test-Path -Path $PublishXml)) {
                Stop-Function -Message "$PublishXml not found!"
                return
            }
        }

        foreach ($instance in $sqlinstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure." -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            $ConnectionString += $server.ConnectionContext.ConnectionString.Replace('"', "'")
        }

        #Use proper class to load the object
        if ($Type -eq 'Dacpac') {
            try {
                $dacPackage = [Microsoft.SqlServer.Dac.DacPackage]::Load($Path)
            } catch {
                Stop-Function -Message "Could not load Dacpac." -ErrorRecord $_
                return
            }
        } elseif ($Type -eq 'Bacpac') {
            try {
                $bacPackage = [Microsoft.SqlServer.Dac.BacPackage]::Load($Path)
            } catch {
                Stop-Function -Message "Could not load Bacpac." -ErrorRecord $_
                return
            }
        }
        #Load XML profile when used
        if ($PsCmdlet.ParameterSetName -eq 'Xml') {
            try {
                $options = New-DbaDacOption -Type $Type -Action Publish -PublishXml $PublishXml -EnableException
            } catch {
                Stop-Function -Message "Could not load profile." -ErrorRecord $_
                return
            }
        }
        #Create/re-use deployment options object
        elseif ($PsCmdlet.ParameterSetName -eq 'Obj') {
            if (!$DacOption) {
                $options = New-DbaDacOption -Type $Type -Action Publish
            } else {
                $options = $DacOption
            }
        }
        #Replace variables if defined
        if ($IncludeSqlCmdVars) {
            Get-SqlCmdVars -SqlCommandVariableValues $options.DeployOptions.SqlCommandVariableValues
        }

        foreach ($connstring in $ConnectionString) {
            $cleaninstance = Get-ServerName $connstring
            $instance = $cleaninstance.ToString().Replace('--', '\')

            foreach ($dbname in $database) {
                #Set deployment properties when specified
                if (Test-Bound -ParameterName GenerateDeploymentScript) {
                    $options.GenerateDeploymentScript = $GenerateDeploymentScript
                }
                if (Test-Bound -ParameterName GenerateDeploymentReport) {
                    $options.GenerateDeploymentReport = $GenerateDeploymentReport
                }
                #Set output file paths when needed
                $timeStamp = (Get-Date).ToString("yyMMdd_HHmmss_f")
                if ($GenerateDeploymentScript) {
                    $options.DatabaseScriptPath = Join-Path $OutputPath "$cleaninstance-$dbname`_DeployScript_$timeStamp.sql"
                    $options.MasterDbScriptPath = Join-Path $OutputPath "$cleaninstance-$dbname`_Master.DeployScript_$timeStamp.sql"
                }
                if ($connstring -notmatch 'Database=') {
                    $connstring = "$connstring;Database=$dbname"
                }

                #Create services object
                try {
                    $dacServices = New-Object Microsoft.SqlServer.Dac.DacServices $connstring
                } catch {
                    Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $server -Continue
                }

                try {
                    $null = $output = Register-ObjectEvent -InputObject $dacServices -EventName "Message" -SourceIdentifier "msg" -ErrorAction SilentlyContinue -Action {
                        $EventArgs.Message.Message
                    }
                    #Perform proper action depending on the Type
                    if ($Type -eq 'Dacpac') {
                        if ($ScriptOnly) {
                            if (!$options.GenerateDeploymentScript) {
                                Stop-Function -Message "GenerateDeploymentScript option should be specified when running with -ScriptOnly" -EnableException $true
                            }
                            if (!$options.DatabaseScriptPath) {
                                Stop-Function -Message "DatabaseScriptPath option should be specified when running with -ScriptOnly" -EnableException $true
                            }
                            if ($Pscmdlet.ShouldProcess($instance, "Generating script")) {
                                $result = $dacServices.Script($dacPackage, $dbname, $options)
                            }
                        } else {
                            if ($Pscmdlet.ShouldProcess($instance, "Executing Dacpac publish")) {
                                $result = $dacServices.Publish($dacPackage, $dbname, $options)
                            }
                        }
                    } elseif ($Type -eq 'Bacpac') {
                        if ($Pscmdlet.ShouldProcess($instance, "Executing Bacpac import")) {
                            $dacServices.ImportBacpac($bacPackage, $dbname, $options, $null)
                        }
                    }
                } catch [Microsoft.SqlServer.Dac.DacServicesException] {
                    Stop-Function -Message "Deployment failed" -ErrorRecord $_ -Continue
                } finally {
                    Unregister-Event -SourceIdentifier "msg"
                    if ($Pscmdlet.ShouldProcess($instance, "Generating deployment report and output")) {
                        if ($options.GenerateDeploymentReport) {
                            $deploymentReport = Join-Path $OutputPath "$cleaninstance-$dbname`_Result.DeploymentReport_$timeStamp.xml"
                            $result.DeploymentReport | Out-File $deploymentReport
                            Write-Message -Level Verbose -Message "Deployment Report - $deploymentReport."
                        }
                        if ($options.GenerateDeploymentScript) {
                            Write-Message -Level Verbose -Message "Database change script - $($options.DatabaseScriptPath)."
                            if ((Test-Path $options.MasterDbScriptPath)) {
                                Write-Message -Level Verbose -Message "Master database change script - $($result.MasterDbScript)."
                            }
                        }
                        $resultoutput = ($output.output -join "`r`n" | Out-String).Trim()
                        if ($resultoutput -match "Failed" -and ($options.GenerateDeploymentReport -or $options.GenerateDeploymentScript)) {
                            Write-Message -Level Warning -Message "Seems like the attempt to publish/script may have failed. If scripts have not generated load dacpac into Visual Studio to check SQL is valid."
                        }
                        $server = [dbainstance]$instance
                        if ($Type -eq 'Dacpac') {
                            $output = [pscustomobject]@{
                                ComputerName         = $server.ComputerName
                                InstanceName         = $server.InstanceName
                                SqlInstance          = $server.FullName
                                Database             = $dbname
                                Result               = $resultoutput
                                Dacpac               = $Path
                                PublishXml           = $PublishXml
                                ConnectionString     = $connstring
                                DatabaseScriptPath   = $options.DatabaseScriptPath
                                MasterDbScriptPath   = $options.MasterDbScriptPath
                                DeploymentReport     = $DeploymentReport
                                DeployOptions        = $options.DeployOptions | Select-Object -Property * -ExcludeProperty "SqlCommandVariableValues"
                                SqlCmdVariableValues = $options.DeployOptions.SqlCommandVariableValues.Keys
                            }
                        } elseif ($Type -eq 'Bacpac') {
                            $output = [pscustomobject]@{
                                ComputerName     = $server.ComputerName
                                InstanceName     = $server.InstanceName
                                SqlInstance      = $server.FullName
                                Database         = $dbname
                                Result           = $resultoutput
                                Bacpac           = $Path
                                ConnectionString = $connstring
                                DeployOptions    = $options
                            }
                        }
                        $output | Select-DefaultView -Property $defaultcolumns
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Publish-DbaDacpac
    }
}
tools\dbatools\functions\Read-DbaAuditFile.ps1
function Read-DbaAuditFile {
    <#
    .SYNOPSIS
        Read Audit details from *.sqlaudit files.

    .DESCRIPTION
        Read Audit details from *.sqlaudit files.

    .PARAMETER Path
        The path to the *.sqlaudit file. This is relative to the computer executing the command. UNC paths are supported.

    .PARAMETER Exact
        If this switch is enabled, only an exact search will be used for the Path. By default, this command will add a wildcard to the Path because Eventing uses the file name as a template and adds characters.

    .PARAMETER Raw
        If this switch is enabled, the Microsoft.SqlServer.XEvent.Linq.PublishedEvent enumeration object will be returned.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, Audit
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Read-DbaAuditFile

    .EXAMPLE
        PS C:\> Read-DbaAuditFile -Path C:\temp\logins.sqlaudit

        Returns events from C:\temp\logins.sqlaudit.

    .EXAMPLE
        PS C:\> Get-ChildItem C:\temp\audit\*.sqlaudit | Read-DbaAuditFile

        Returns events from all .sqlaudit files in C:\temp\audit.

    .EXAMPLE
        PS C:\> Get-DbaServerAudit -SqlInstance sql2014 -Audit LoginTracker | Read-DbaAuditFile

        Reads remote Audit details by accessing the file over the admin UNC share.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias('FullName')]
        [object[]]$Path,
        [switch]$Exact,
        [switch]$Raw,
        [switch]$EnableException
    )
    process {
        foreach ($file in $path) {
            # in order to ensure CSV gets all fields, all columns will be
            # collected and output in the first (all all subsequent) object
            $columns = @("name", "timestamp")

            if ($file -is [System.String]) {
                $currentfile = $file
                #Variable marked as unused by PSScriptAnalyzer
                #$manualadd = $true
            } elseif ($file -is [System.IO.FileInfo]) {
                $currentfile = $file.FullName
                #Variable marked as unused by PSScriptAnalyzer
                #$manualadd = $true
            } else {
                if ($file -isnot [Microsoft.SqlServer.Management.Smo.Audit]) {
                    Stop-Function -Message "Unsupported file type."
                    return
                }

                if ($file.FullName.Length -eq 0) {
                    Stop-Function -Message "This Audit does not have an associated file."
                    return
                }

                $instance = [dbainstance]$file.ComputerName

                if ($instance.IsLocalHost) {
                    $currentfile = $file.FullName
                } else {
                    $currentfile = $file.RemoteFullName
                }
            }

            if (-not $Exact) {
                $currentfile = $currentfile.Replace('.sqlaudit', '*.sqlaudit')

                if ($currentfile -notmatch "sqlaudit") {
                    $currentfile = "$currentfile*.sqlaudit"
                }
            }

            $accessible = Test-Path -Path $currentfile
            $whoami = whoami

            if (-not $accessible) {
                if ($file.Status -eq "Stopped") { continue }
                Stop-Function -Continue -Message "$currentfile cannot be accessed from $($env:COMPUTERNAME). Does $whoami have access?"
            }

            if ($raw) {
                return New-Object Microsoft.SqlServer.XEvent.Linq.QueryableXEventData($currentfile)
            }

            $enum = New-Object Microsoft.SqlServer.XEvent.Linq.QueryableXEventData($currentfile)
            $newcolumns = ($enum.Fields.Name | Select-Object -Unique)

            $actions = ($enum.Actions.Name | Select-Object -Unique)
            foreach ($action in $actions) {
                $newcolumns += ($action -Split '\.')[-1]
            }

            $newcolumns = $newcolumns | Sort-Object
            $columns = ($columns += $newcolumns) | Select-Object -Unique

            # Make it selectable, otherwise it's a weird enumeration
            foreach ($event in (New-Object Microsoft.SqlServer.XEvent.Linq.QueryableXEventData($currentfile))) {
                $hash = [ordered]@{ }

                foreach ($column in $columns) {
                    $null = $hash.Add($column, $event.$column)
                }

                foreach ($action in $event.Actions) {
                    $hash[$action.Name] = $action.Value
                }

                foreach ($field in $event.Fields) {
                    $hash[$field.Name] = $field.Value
                }

                [pscustomobject]$hash
            }
        }
    }
}
tools\dbatools\functions\Read-DbaBackupHeader.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Read-DbaBackupHeader {
    <#
    .SYNOPSIS
        Reads and displays detailed information about a SQL Server backup.

    .DESCRIPTION
        Reads full, differential and transaction log backups. An online SQL Server is required to parse the backup files and the path specified must be relative to that SQL Server.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Path
        Path to SQL Server backup file. This can be a full, differential or log backup file. Accepts valid filesystem paths and URLs.

    .PARAMETER Simple
        If this switch is enabled, fewer columns are returned, giving an easy overview.

    .PARAMETER FileList
        If this switch is enabled, detailed information about the files within the backup is returned.

    .PARAMETER AzureCredential
        Name of the SQL Server credential that should be used for Azure storage access.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DisasterRecovery, Backup, Restore
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Read-DbaBackupHeader

    .EXAMPLE
        PS C:\> Read-DbaBackupHeader -SqlInstance sql2016 -Path S:\backups\mydb\mydb.bak

        Logs into sql2016 using Windows authentication and reads the local file on sql2016, S:\backups\mydb\mydb.bak.

        If you are running this command on a workstation and connecting remotely, remember that sql2016 cannot access files on your own workstation.

    .EXAMPLE
        PS C:\> Read-DbaBackupHeader -SqlInstance sql2016 -Path \\nas\sql\backups\mydb\mydb.bak, \\nas\sql\backups\otherdb\otherdb.bak

        Logs into sql2016 and reads two backup files - mydb.bak and otherdb.bak. The SQL Server service account must have rights to read this file.

    .EXAMPLE
        PS C:\> Read-DbaBackupHeader -SqlInstance . -Path C:\temp\myfile.bak -Simple

        Logs into the local workstation (or computer) and shows simplified output about C:\temp\myfile.bak. The SQL Server service account must have rights to read this file.

    .EXAMPLE
        PS C:\> $backupinfo = Read-DbaBackupHeader -SqlInstance . -Path C:\temp\myfile.bak
        PS C:\> $backupinfo.FileList

        Displays detailed information about each of the datafiles contained in the backupset.

    .EXAMPLE
        PS C:\> Read-DbaBackupHeader -SqlInstance . -Path C:\temp\myfile.bak -FileList

        Also returns detailed information about each of the datafiles contained in the backupset.

    .EXAMPLE
        PS C:\> "C:\temp\myfile.bak", "\backupserver\backups\myotherfile.bak" | Read-DbaBackupHeader -SqlInstance sql2016  | Where-Object { $_.BackupSize.Megabyte -gt 100 }

        Reads the two files and returns only backups larger than 100 MB

    .EXAMPLE
        PS C:\> Get-ChildItem \\nas\sql\*.bak | Read-DbaBackupHeader -SqlInstance sql2016

        Gets a list of all .bak files on the \\nas\sql share and reads the headers using the server named "sql2016". This means that the server, sql2016, must have read access to the \\nas\sql share.

    .EXAMPLE
        PS C:\> Read-DbaBackupHeader -Path https://dbatoolsaz.blob.core.windows.net/azbackups/restoretime/restoretime_201705131850.bak -AzureCredential AzureBackupUser

        Gets the backup header information from the SQL Server backup file stored at https://dbatoolsaz.blob.core.windows.net/azbackups/restoretime/restoretime_201705131850.bak on Azure

    #>
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", 'AzureCredential', Justification = "For Parameter AzureCredential")]
    [CmdletBinding()]
    param (
        [parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance]$SqlInstance,
        [PsCredential]$SqlCredential,
        [parameter(Mandatory, ValueFromPipeline)]
        [object[]]$Path,
        [switch]$Simple,
        [switch]$FileList,
        [string]$AzureCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        foreach ($p in $path) {
            if ([System.IO.Path]::GetExtension($p).Length -eq 0) {
                Stop-Function -Message "Path ($p) should be a file, not a folder" -Category InvalidArgument
                return
            }
        }
        Write-Message -Level InternalComment -Message "Starting reading headers"
        try {
            $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            return
        }
        $getHeaderScript = {
            param (
                $SqlInstance,
                $Path,
                $DeviceType,
                $AzureCredential
            )
            #Copy existing connection to create an independent TSQL session
            $server = New-Object Microsoft.SqlServer.Management.Smo.Server $SqlInstance.ConnectionContext.Copy()
            $restore = New-Object Microsoft.SqlServer.Management.Smo.Restore

            if ($DeviceType -eq 'URL') {
                $restore.CredentialName = $AzureCredential
            }

            $device = New-Object Microsoft.SqlServer.Management.Smo.BackupDeviceItem $Path, $DeviceType
            $restore.Devices.Add($device)
            $dataTable = $restore.ReadBackupHeader($server)
            $null = $dataTable.Columns.Add("FileList", [object])
            $null = $dataTable.Columns.Add("SqlVersion")
            $null = $dataTable.Columns.Add("BackupPath")

            foreach ($row in $dataTable) {
                $row.BackupPath = $Path
                
                $backupsize = $row.BackupSize
                $null = $dataTable.Columns.Remove("BackupSize")
                $null = $dataTable.Columns.Add("BackupSize", [dbasize])
                if ($backupsize -isnot [dbnull]) {
                    $row.BackupSize = [dbasize]$backupsize
                }
                
                $cbackupsize = $row.CompressedBackupSize
                $null = $dataTable.Columns.Remove("CompressedBackupSize")
                $null = $dataTable.Columns.Add("CompressedBackupSize", [dbasize])
                if ($cbackupsize -isnot [dbnull]) {
                    $row.CompressedBackupSize = [dbasize]$cbackupsize
                }
                
                $restore.FileNumber = $row.Position
                <# Select-Object does a quick and dirty conversion from datatable to PS object #>
                $row.FileList = $restore.ReadFileList($server) | Select-Object *
            }
            $dataTable
        }
    }

    process {
        if (Test-FunctionInterrupt) { return }

        #Extract fullnames from the file system objects
        $pathStrings = @()
        foreach ($pathItem in $Path) {
            if ($null -ne $pathItem.FullName) {
                $pathStrings += $pathItem.FullName
            } else {
                $pathStrings += $pathItem
            }
        }
        #Group by filename
        $pathGroup = $pathStrings | Group-Object -NoElement | Select-Object -ExpandProperty Name

        $pathCount = ($pathGroup | Measure-Object).Count
        Write-Message -Level Verbose -Message "$pathCount unique files to scan."
        Write-Message -Level Verbose -Message "Checking accessibility for all the files."

        $testPath = Test-DbaPath -SqlInstance $server -Path $pathGroup

        #Setup initial session state
        $InitialSessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
        $defaultrunspace = [System.Management.Automation.Runspaces.Runspace]::DefaultRunspace
        #Create Runspace pool, min - 1, max - 10 sessions: there is internal SQL Server queue for the restore operations. 10 threads seem to perform best
        $runspacePool = [runspacefactory]::CreateRunspacePool(1, 10, $InitialSessionState, $Host)
        $runspacePool.Open()

        $threads = @()

        foreach ($file in $pathGroup) {
            if ($file -like 'http*') {
                $deviceType = 'URL'
            } else {
                $deviceType = 'FILE'
            }
            if ($pathCount -eq 1) {
                $fileExists = $testPath
            } else {
                $fileExists = ($testPath | Where-Object FilePath -eq $file).FileExists
            }
            if ($fileExists -or $deviceType -eq 'URL') {
                #Create parameters hashtable
                $argsRunPool = @{
                    SqlInstance     = $server
                    Path            = $file
                    AzureCredential = $AzureCredential
                    DeviceType      = $deviceType
                }
                Write-Message -Level Verbose -Message "Scanning file $file."
                #Create new runspace thread
                $thread = [powershell]::Create()
                $thread.RunspacePool = $runspacePool
                $thread.AddScript($getHeaderScript) | Out-Null
                $thread.AddParameters($argsRunPool) | Out-Null
                #Start the thread
                $handle = $thread.BeginInvoke()
                $threads += [pscustomobject]@{
                    handle      = $handle
                    thread      = $thread
                    file        = $file
                    deviceType  = $deviceType
                    isRetrieved = $false
                    started     = Get-Date
                }
            } else {
                Write-Message -Level Warning -Message "File $file does not exist or access denied. The SQL Server service account may not have access to the source directory."
            }
        }
        #receive runspaces
        while ($threads | Where-Object { $_.isRetrieved -eq $false }) {
            $totalThreads = ($threads | Measure-Object).Count
            $totalRetrievedThreads = ($threads | Where-Object { $_.isRetrieved -eq $true } | Measure-Object).Count
            Write-Progress -Id 1 -Activity Updating -Status 'Progress' -CurrentOperation "Scanning Restore headers: $totalRetrievedThreads/$totalThreads" -PercentComplete ($totalRetrievedThreads / $totalThreads * 100)
            foreach ($thread in ($threads | Where-Object { $_.isRetrieved -eq $false })) {
                if ($thread.Handle.IsCompleted) {
                    $dataTable = $thread.thread.EndInvoke($thread.handle)
                    $thread.isRetrieved = $true
                    #Check if thread had any errors
                    if ($thread.thread.HadErrors) {
                        if ($thread.deviceType -eq 'FILE') {
                            Stop-Function -Message "Problem found with $($thread.file)." -Target $thread.file -ErrorRecord $thread.thread.Streams.Error -Continue
                        } else {
                            Stop-Function -Message "Unable to read $($thread.file), check credential $AzureCredential and network connectivity." -Target $thread.file -ErrorRecord $thread.thread.Streams.Error -Continue
                        }
                    }
                    #Process the result of this thread

                    $dbVersion = $dataTable[0].DatabaseVersion
                    $SqlVersion = (Convert-DbVersionToSqlVersion $dbVersion)
                    foreach ($row in $dataTable) {
                        $row.SqlVersion = $SqlVersion
                        if ($row.BackupName -eq "*** INCOMPLETE ***") {
                            Stop-Function -Message "$($thread.file) appears to be from a new version of SQL Server than $SqlInstance, skipping" -Target $thread.file -Continue
                        }
                    }
                    if ($Simple) {
                        $dataTable | Select-Object DatabaseName, BackupFinishDate, RecoveryModel, BackupSize, CompressedBackupSize, DatabaseCreationDate, UserName, ServerName, SqlVersion, BackupPath
                    } elseif ($FileList) {
                        $dataTable.filelist
                    } else {
                        $dataTable
                    }

                    $thread.thread.Dispose()
                }
            }
            Start-Sleep -Milliseconds 500
        }
        #Close the runspace pool
        $runspacePool.Close()
        [System.Management.Automation.Runspaces.Runspace]::DefaultRunspace = $defaultrunspace
    }
}
tools\dbatools\functions\Read-DbaTraceFile.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Read-DbaTraceFile {
    <#
    .SYNOPSIS
        Reads SQL Server trace files

    .DESCRIPTION
        Using the fn_trace_gettable function, a trace file is read and returned as a PowerShell object

        This function returns the whole of the trace file. The information is presented in the format that the trace subsystem uses.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Path
        Path to the trace file. This path is relative to the SQL Server instance.

    .PARAMETER Database
        Search for results only with specific DatabaseName. Uses IN for comparisons.

    .PARAMETER Login
        Search for results only with specific Logins. Uses IN for comparisons.

    .PARAMETER Spid
        Search for results only with specific Spids. Uses IN for comparisons.

    .PARAMETER EventClass
        Search for results only with specific EventClasses. Uses IN for comparisons.

    .PARAMETER ObjectType
        Search for results only with specific ObjectTypes. Uses IN for comparisons.

    .PARAMETER ErrorId
        Search for results only with specific Errors. Filters 'Error in ($ErrorId)'  Uses IN for comparisons.

    .PARAMETER EventSequence
        Search for results only with specific EventSequences. Uses IN for comparisons.

    .PARAMETER TextData
        Search for results only with specific TextData. Uses LIKE for comparisons.

    .PARAMETER ApplicationName
        Search for results only with specific ApplicationNames. Uses LIKE for comparisons.

    .PARAMETER ObjectName
        Search for results only with specific ObjectNames. Uses LIKE for comparisons.

    .PARAMETER Where
        Custom where clause - use without the word "WHERE". Here are the available columns:

        TextData
        BinaryData
        DatabaseID
        TransactionID
        LineNumber
        NTUserName
        NTDomainName
        HostName
        ClientProcessID
        ApplicationName
        LoginName
        SPID
        Duration
        StartTime
        EndTime
        Reads
        Writes
        CPU
        Permissions
        Severity
        EventSubClass
        ObjectID
        Success
        IndexID
        IntegerData
        ServerName
        EventClass
        ObjectType
        NestLevel
        State
        Error
        Mode
        Handle
        ObjectName
        DatabaseName
        FileName
        OwnerName
        RoleName
        TargetUserName
        DBUserName
        LoginSid
        TargetLoginName
        TargetLoginSid
        ColumnPermissions
        LinkedServerName
        ProviderName
        MethodName
        RowCounts
        RequestID
        XactSequence
        EventSequence
        BigintData1
        BigintData2
        GUID
        IntegerData2
        ObjectID2
        Type
        OwnerID
        ParentName
        IsSystem
        Offset
        SourceDatabaseID
        SqlHandle
        SessionLoginName
        PlanHandle
        GroupID

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Security, Trace
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Read-DbaTraceFile -SqlInstance sql2016 -Database master, tempdb -Path C:\traces\big.trc

        Reads the tracefile C:\traces\big.trc, stored on the sql2016 sql server. Filters only results that have master or tempdb as the DatabaseName.

    .EXAMPLE
        PS C:\> Read-DbaTraceFile -SqlInstance sql2016 -Database master, tempdb -Path C:\traces\big.trc -TextData 'EXEC SP_PROCOPTION'

        Reads the tracefile C:\traces\big.trc, stored on the sql2016 sql server.
        Filters only results that have master or tempdb as the DatabaseName and that have 'EXEC SP_PROCOPTION' somewhere in the text.

    .EXAMPLE
        PS C:\> Read-DbaTraceFile -SqlInstance sql2016 -Path C:\traces\big.trc -Where "LinkedServerName = 'myls' and StartTime > '5/30/2017 4:27:52 PM'"

        Reads the tracefile C:\traces\big.trc, stored on the sql2016 sql server.
        Filters only results where LinkServerName = myls and StartTime is greater than '5/30/2017 4:27:52 PM'.

    .EXAMPLE
        PS C:\> Get-DbaTrace -SqlInstance sql2014 | Read-DbaTraceFile

        Reads every trace file on sql2014

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipelineByPropertyName)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [parameter(ValueFromPipelineByPropertyName)]
        [PSCredential]$SqlCredential,
        [parameter(ValueFromPipelineByPropertyName)]
        [string[]]$Path,
        [string[]]$Database,
        [string[]]$Login,
        [int[]]$Spid,
        [string[]]$EventClass,
        [string[]]$ObjectType,
        [int[]]$ErrorId,
        [int[]]$EventSequence,
        [string[]]$TextData,
        [string[]]$ApplicationName,
        [string[]]$ObjectName,
        [string]$Where,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        if ($where) {
            $Where = "where $where"
        } elseif ($Database -or $Login -or $Spid -or $ApplicationName -or $EventClass -or $ObjectName -or $ObjectType -or $EventSequence -or $ErrorId) {

            $tempwhere = @()

            if ($Database) {
                $where = $database -join "','"
                $tempwhere += "databasename in ('$where')"
            }

            if ($Login) {
                $where = $Login -join "','"
                $tempwhere += "LoginName in ('$where')"
            }

            if ($Spid) {
                $where = $Spid -join ","
                $tempwhere += "Spid in ($where)"
            }

            if ($EventClass) {
                $where = $EventClass -join ","
                $tempwhere += "EventClass in ($where)"
            }

            if ($ObjectType) {
                $where = $ObjectType -join ","
                $tempwhere += "ObjectType in ($where)"
            }

            if ($ErrorId) {
                $where = $ErrorId -join ","
                $tempwhere += "Error in ($where)"
            }

            if ($EventSequence) {
                $where = $EventSequence -join ","
                $tempwhere += "EventSequence in ($where)"
            }

            if ($TextData) {
                $where = $TextData -join "%','%"
                $tempwhere += "TextData like ('%$where%')"
            }

            if ($ApplicationName) {
                $where = $ApplicationName -join "%','%"
                $tempwhere += "ApplicationName like ('%$where%')"
            }

            if ($ObjectName) {
                $where = $ObjectName -join "%','%"
                $tempwhere += "ObjectName like ('%$where%')"
            }

            $tempwhere = $tempwhere -join " and "
            $Where = "where $tempwhere"
        }
    }
    process {
        foreach ($instance in $sqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                return
            }

            if (Test-Bound -Parameter Path) {
                $currentpath = $path
            } else {
                $currentpath = $server.ConnectionContext.ExecuteScalar("Select path from sys.traces where is_default = 1")
            }

            foreach ($file in $currentpath) {
                Write-Message -Level Verbose -Message "Parsing $file"

                $exists = Test-DbaPath -SqlInstance $server -Path $file

                if (!$exists) {
                    Write-Message -Level Warning -Message "Path does not exist" -Target $file
                    Continue
                }

                $sql = "select SERVERPROPERTY('MachineName') AS ComputerName,
                ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
                SERVERPROPERTY('ServerName') AS SqlInstance,
                 * FROM [fn_trace_gettable]('$file', DEFAULT) $Where"

                try {
                    $server.Query($sql)
                } catch {
                    Stop-Function -Message "Error returned from SQL Server: $_" -Target $server -InnerErrorRecord $_
                }
            }
        }
    }
}
tools\dbatools\functions\Read-DbaTransactionLog.ps1
function Read-DbaTransactionLog {
    <#
    .SYNOPSIS
        Reads the live Transaction log from specified SQL Server Database

    .DESCRIPTION
        Using the fn_dblog function, the live transaction log is read and returned as a PowerShell object

        This function returns the whole of the log. The information is presented in the format that the logging subsystem uses.

        A soft limit of 0.5GB of log as been implemented. This is based on testing. This limit can be overridden
        at the users request, but please be aware that this may have an impact on your target databases and on the
        system running this function

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        A credential to use to connect to the SQL Instance rather than using Windows Authentication

    .PARAMETER Database
        Database to read the transaction log of

    .PARAMETER IgnoreLimit
        Switch to indicate that you wish to bypass the recommended limits of the function

    .PARAMETER RowLimit
        Will limit the number of rows returned from the transaction log

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database, Log, LogFile
        Author: Stuart Moore (@napalmgram), stuart-moore.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> $Log = Read-DbaTransactionLog -SqlInstance sql2016 -Database MyDatabase

        Will read the contents of the transaction log of MyDatabase on SQL Server Instance sql2016 into the local PowerShell object $Log

    .EXAMPLE
        PS C:\> $Log = Read-DbaTransactionLog -SqlInstance sql2016 -Database MyDatabase -IgnoreLimit

        Will read the contents of the transaction log of MyDatabase on SQL Server Instance sql2016 into the local PowerShell object $Log, ignoring the recommendation of not returning more that 0.5GB of log

    #>
    [CmdletBinding(DefaultParameterSetName = "Default")]
    param (
        [parameter(Position = 0, Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(Mandatory)]
        [object]$Database,
        [Switch]$IgnoreLimit,
        [int]$RowLimit = 0,
        [Alias('Silent')]
        [switch]$EnableException
    )

    try {
        $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
    } catch {
        Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
        return
    }

    if (-not $server.databases[$Database]) {
        Stop-Function -Message "$Database does not exist"
        return
    }

    if ('Normal' -notin ($server.databases[$Database].Status -split ',')) {
        Stop-Function -Message "$Database is not in a normal State, command will not run."
        return
    }

    if ($RowLimit -gt 0) {
        Write-Message -Message "Limiting results to $RowLimit rows" -Level Verbose
        $RowLimitSql = " TOP $RowLimit "
        $IgnoreLimit = $true
    } else {
        $RowLimitSql = ""
    }


    if ($IgnoreLimit) {
        Write-Message -Level Verbose -Message "Please be aware that ignoring the recommended limits may impact on the performance of the SQL Server database and the calling system"
    } else {
        #Warn if more than 0.5GB of live log. Dodgy conversion as SMO returns the value in an unhelpful format :(
        $SqlSizeCheck = "select
                                sum(FileProperty(sf.name,'spaceused')*8/1024) as 'SizeMb'
                                from sys.sysfiles sf
                                where CONVERT(INT,sf.status & 0x40) / 64=1"
        $TransLogSize = $server.Query($SqlSizeCheck, $Database)
        if ($TransLogSize.SizeMb -ge 500) {
            Stop-Function -Message "$Database has more than 0.5 Gb of live log data, returning this may have an impact on the database and the calling system. If you wish to proceed please rerun with the -IgnoreLimit switch"
            return
        }
    }

    $sql = "select $RowLimitSql * from fn_dblog(NULL,NULL)"
    Write-Message -Level Debug -Message $sql
    Write-Message -Level Verbose -Message "Starting Log retrieval"
    $server.Query($sql, $Database)

}
tools\dbatools\functions\Read-DbaXEFile.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Read-DbaXEFile {
    <#
    .SYNOPSIS
        Read XEvents from a *.xel or *.xem file.

    .DESCRIPTION
        Read XEvents from a *.xel or *.xem file.

    .PARAMETER Path
        The path to the *.xem or *.xem file. This is relative to the computer executing the command. UNC paths are supported.

    .PARAMETER Exact
        If this switch is enabled, only an exact search will be used for the Path. By default, this command will add a wildcard to the Path because Eventing uses the file name as a template and adds characters.

    .PARAMETER Raw
        If this switch is enabled, the Microsoft.SqlServer.XEvent.Linq.PublishedEvent enumeration object will be returned.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Read-DbaXEFile

    .EXAMPLE
        PS C:\> Read-DbaXEFile -Path C:\temp\deadocks.xel

        Returns events from C:\temp\deadocks.xel.

    .EXAMPLE
        PS C:\> Get-ChildItem C:\temp\xe\*.xel | Read-DbaXEFile

        Returns events from all .xel files in C:\temp\xe.

    .EXAMPLE
        PS C:\> Get-DbaXESession -SqlInstance sql2014 -Session deadlocks | Read-DbaXEFile

        Reads remote XEvents by accessing the file over the admin UNC share.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias('FullName')]
        [object[]]$Path,
        [switch]$Exact,
        [switch]$Raw,
        [switch][Alias('Silent')]
        $EnableException
    )
    process {
        foreach ($file in $path) {
            # in order to ensure CSV gets all fields, all columns will be
            # collected and output in the first (all all subsequent) object
            $columns = @("name", "timestamp")

            if ($file -is [System.String]) {
                $currentfile = $file
                #Variable marked as unused by PSScriptAnalyzer
                #$manualadd = $true
            } elseif ($file -is [System.IO.FileInfo]) {
                $currentfile = $file.FullName
                #Variable marked as unused by PSScriptAnalyzer
                #$manualadd = $true
            } else {
                if ($file -isnot [Microsoft.SqlServer.Management.XEvent.Session]) {
                    Stop-Function -Message "Unsupported file type."
                    return
                }

                if ($file.TargetFile.Length -eq 0) {
                    Stop-Function -Message "This session does not have an associated Target File."
                    return
                }

                $instance = [dbainstance]$file.ComputerName

                if ($instance.IsLocalHost) {
                    $currentfile = $file.TargetFile
                } else {
                    $currentfile = $file.RemoteTargetFile
                }
            }

            if (-not $Exact) {
                $currentfile = $currentfile.Replace('.xel', '*.xel')
                $currentfile = $currentfile.Replace('.xem', '*.xem')

                if ($currentfile -notmatch "xel" -and $currentfile -notmatch "xem") {
                    $currentfile = "$currentfile*.xel"
                }
            }

            $accessible = Test-Path -Path $currentfile
            $whoami = whoami

            if (-not $accessible) {
                if ($file.Status -eq "Stopped") { continue }
                Stop-Function -Continue -Message "$currentfile cannot be accessed from $($env:COMPUTERNAME). Does $whoami have access?"
            }

            if ($raw) {
                return New-Object Microsoft.SqlServer.XEvent.Linq.QueryableXEventData($currentfile)
            }

            $enum = New-Object Microsoft.SqlServer.XEvent.Linq.QueryableXEventData($currentfile)
            $newcolumns = ($enum.Fields.Name | Select-Object -Unique)

            $actions = ($enum.Actions.Name | Select-Object -Unique)
            foreach ($action in $actions) {
                $newcolumns += ($action -Split '\.')[-1]
            }

            $newcolumns = $newcolumns | Sort-Object
            $columns = ($columns += $newcolumns) | Select-Object -Unique

            # Make it selectable, otherwise it's a weird enumeration
            foreach ($event in $enum) {
                $hash = [ordered]@{ }

                foreach ($column in $columns) {
                    $null = $hash.Add($column, $event.$column)
                }

                foreach ($action in $event.Actions) {
                    $hash[$action.Name] = $action.Value
                }

                foreach ($field in $event.Fields) {
                    $hash[$field.Name] = $field.Value
                }

                [pscustomobject]$hash
            }
            $enum.Dispose()
        }
    }
}
tools\dbatools\functions\Remove-DbaAgDatabase.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaAgDatabase {
    <#
    .SYNOPSIS
        Removes a database from an availability group on a SQL Server instance.

    .DESCRIPTION
        Removes a database from an availability group on a SQL Server instance.

   .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.

    .PARAMETER SqlCredential
        Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database or databases to remove.

    .PARAMETER AvailabilityGroup
        Only remove databases from specific availability groups.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER InputObject
        Enables piping from Get-DbaDatabase

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: AvailabilityGroup, HA, AG
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaAgDatabase

    .EXAMPLE
        PS C:\> Remove-DbaAgDatabase -SqlInstance sqlserver2012 -AvailabilityGroup ag1, ag2 -Confirm:$false

        Removes the ag1 and ag2 availability groups on sqlserver2012.  Does not prompt for confirmation.

    .EXAMPLE
        PS C:\> Get-DbaAvailabilityGroup -SqlInstance sqlserver2012 -AvailabilityGroup availabilitygroup1 | Remove-DbaAgDatabase

        Removes the availability groups returned from the Get-DbaAvailabilityGroup function. Prompts for confirmation.
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [string[]]$AvailabilityGroup,
        # needs to accept db or agdb so generic object

        [parameter(ValueFromPipeline)]
        [object[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ((Test-Bound -ParameterName SqlInstance)) {
            if ((Test-Bound -Not -ParameterName Database)) {
                Stop-Function -Message "You must specify one or more databases and one or more Availability Groups when using the SqlInstance parameter."
                return
            }
        }

        if ($InputObject) {
            if ($InputObject[0].GetType().Name -eq 'Database') {
                $Database += $InputObject.Name
            }
        }

        if ($SqlInstance) {
            $InputObject += Get-DbaAgDatabase -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database
        }

        foreach ($db in $InputObject) {
            if ($Pscmdlet.ShouldProcess($db.Parent.Parent.Name, "Removing availability group database $db")) {
                try {
                    $ag = $db.Parent.Name
                    $db.Parent.AvailabilityDatabases[$db.Name].Drop()
                    [pscustomobject]@{
                        ComputerName      = $db.ComputerName
                        InstanceName      = $db.InstanceName
                        SqlInstance       = $db.SqlInstance
                        AvailabilityGroup = $ag
                        Database          = $db.Name
                        Status            = "Removed"
                    }
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Remove-DbaAgentJob.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaAgentJob {
    <#
    .SYNOPSIS
        Remove-DbaAgentJob removes a job.

    .DESCRIPTION
        Remove-DbaAgentJob removes a job in the SQL Server Agent.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Job
        The name of the job. Can be null if the the job id is being used.

    .PARAMETER KeepHistory
        Specifies to keep the history for the job. By default history is deleted.

    .PARAMETER KeepUnusedSchedule
        Specifies to keep the schedules attached to this job if they are not attached to any other job.
        By default the unused schedule is deleted.

    .PARAMETER Mode
        Default: Strict
        How strict does the command take lesser issues?
        Strict: Interrupt if the job specified doesn't exist.
        Lazy:   Silently skip over jobs that don't exist.

    .PARAMETER InputObject
        Accepts piped input from Get-DbaAgentJob

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Job
        Author: Sander Stad (@sqlstad, sqlstad.nl)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaAgentJob

    .EXAMPLE
        PS C:\> Remove-DbaAgentJob -SqlInstance sql1 -Job Job1

        Removes the job from the instance with the name Job1

    .EXAMPLE
        PS C:\> GetDbaAgentJob -SqlInstance sql1 -Job Job1 | Remove-DbaAgentJob -KeepHistory

        Removes teh job but keeps the history

    .EXAMPLE
        PS C:\> Remove-DbaAgentJob -SqlInstance sql1 -Job Job1 -KeepUnusedSchedule

        Removes the job but keeps the unused schedules

    .EXAMPLE
        PS C:\> Remove-DbaAgentJob -SqlInstance sql1, sql2, sql3 -Job Job1

        Removes the job from multiple servers

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Job,
        [switch]$KeepHistory,
        [switch]$KeepUnusedSchedule,
        [DbaMode]$Mode = (Get-DbatoolsConfigValue -FullName 'message.mode.default' -Fallback "Strict"),
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Agent.Job[]]$InputObject,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            foreach ($j in $Job) {
                if ($Server.JobServer.Jobs.Name -notcontains $j) {
                    switch ($Mode) {
                        'Lazy' {
                            Write-Message -Level Verbose -Message "Job $j doesn't exists on $instance." -Target $instance
                        }
                        'Strict' {
                            Stop-Function -Message "Job $j doesn't exist on $instance." -Continue -ContinueLabel main -Target $instance -Category InvalidData
                        }
                    }
                }
                $InputObject += ($Server.JobServer.Jobs | Where-Object Name -eq $j)
            }
        }
        foreach ($currentJob in $InputObject) {
            $j = $currentJob.Name
            $server = $currentJob.Parent.Parent

            if ($PSCmdlet.ShouldProcess($instance, "Removing the job $j from $server")) {
                try {
                    $dropHistory = $dropSchedule = 1

                    if (Test-Bound -ParameterName KeepHistory) {
                        Write-Message -Level SomewhatVerbose -Message "Job history will be kept"
                        $dropHistory = 0
                    }
                    if (Test-Bound -ParameterName KeepUnusedSchedule) {
                        Write-Message -Level SomewhatVerbose -Message "Unused job schedules will be kept"
                        $dropSchedule = 0
                    }
                    Write-Message -Level SomewhatVerbose -Message "Removing job"
                    $dropJobQuery = ("EXEC dbo.sp_delete_job @job_name = '{0}', @delete_history = {1}, @delete_unused_schedule = {2}" -f $currentJob.Name.Replace("'", "''"), $dropHistory, $dropSchedule)
                    $server.Databases['msdb'].ExecuteNonQuery($dropJobQuery)
                    [pscustomobject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Name         = $currentJob.Name
                        Status       = 'Dropped'
                    }
                } catch {
                    Write-Message -Level Verbose -Message "Could not drop job $job on $server"

                    [pscustomobject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Name         = $currentJob.Name
                        Status       = "Failed. $(Get-ErrorMessage -Record $_)"
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Remove-DbaAgentJobCategory.ps1
function Remove-DbaAgentJobCategory {
    <#
    .SYNOPSIS
        Remove-DbaAgentJobCategory removes a job category.

    .DESCRIPTION
        Remove-DbaAgentJobCategory makes it possible to remove a job category.
        Be assured that the category you want to remove is not used with other jobs. If another job uses this category it will be get the category [Uncategorized (Local)].

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Category
        The name of the category

    .PARAMETER Force
        The force parameter will ignore some errors in the parameters and assume defaults.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Job, JobCategory
        Author: Sander Stad (@sqlstad, sqlstad.nl)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaAgentJobCategory

    .EXAMPLE
        PS C:\> Remove-DbaAgentJobCategory -SqlInstance sql1 -Category 'Category 1'

        Remove the job category Category 1 from the instance.

    .EXAMPLE
        PS C:\> Remove-DbaAgentJobCategory -SqlInstance sql1 -Category Category1, Category2, Category3

        Remove multiple job categories from the instance.

    .EXAMPLE
        PS C:\> Remove-DbaAgentJobCategory -SqlInstance sql1, sql2, sql3 -Category Category1, Category2, Category3

        Remove multiple job categories from the multiple instances.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [ValidateNotNullOrEmpty()]
        [string[]]$Category,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {

        foreach ($instance in $sqlinstance) {
            # Try connecting to the instance
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            # Loop through each of the categories
            foreach ($cat in $Category) {

                # Check if the job category exists
                if ($cat -notin $server.JobServer.JobCategories.Name) {
                    Stop-Function -Message "Job category $cat doesn't exist on $instance" -Target $instance -Continue
                }

                # Remove the category
                if ($PSCmdlet.ShouldProcess($instance, "Changing the job category $Category")) {
                    try {
                        # Get the category
                        $currentCategory = $server.JobServer.JobCategories[$cat]

                        Write-Message -Message "Removing job category $cat" -Level Verbose

                        $currentCategory.Drop()
                    } catch {
                        Stop-Function -Message "Something went wrong removing the job category $cat on $instance" -Target $cat -Continue -ErrorRecord $_
                    }

                } #if should process

            } # for each category

        } # for each instance

    } # end process

    end {
        if (Test-FunctionInterrupt) { return }
        Write-Message -Message "Finished removing job category." -Level Verbose
    }

}
tools\dbatools\functions\Remove-DbaAgentJobStep.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaAgentJobStep {
    <#
    .SYNOPSIS
        Removes a step from the specified SQL Agent job.

    .DESCRIPTION
        Removes a job step from a SQL Server Agent job.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Job
        The name of the job.

    .PARAMETER StepName
        The name of the job step.

    .PARAMETER Mode
        Default: Strict
        How strict does the command take lesser issues?
        Strict: Interrupt if the configuration already has the same value as the one specified.
        Lazy:   Silently skip over instances that already have this configuration at the specified value.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Job, JobStep
        Author: Sander Stad (@sqlstad), sqlstad.nl

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaAgentJobStep

    .EXAMPLE
        PS C:\> Remove-DbaAgentJobStep -SqlInstance sql1 -Job Job1 -StepName Step1

        Remove 'Step1' from job 'Job1' on sql1.

    .EXAMPLE
        PS C:\> Remove-DbaAgentJobStep -SqlInstance sql1 -Job Job1, Job2, Job3 -StepName Step1

        Remove the job step from multiple jobs.

    .EXAMPLE
        PS C:\> Remove-DbaAgentJobStep -SqlInstance sql1, sql2, sql3 -Job Job1 -StepName Step1

        Remove the job step from the job on multiple servers.

    .EXAMPLE
        PS C:\> sql1, sql2, sql3 | Remove-DbaAgentJobStep -Job Job1 -StepName Step1

        Remove the job step from the job on multiple servers using pipeline.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [object[]]$Job,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$StepName,
        [DbaMode]$Mode = (Get-DbatoolsConfigValue -Name 'message.mode.default' -Fallback "Strict"),
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            foreach ($j in $Job) {
                Write-Message -Level Verbose -Message "Processing job $j"
                # Check if the job exists
                if ($Server.JobServer.Jobs.Name -notcontains $j) {
                    switch ($Mode) {
                        'Lazy' {
                            Write-Message -Level Verbose -Message "Job $j doesn't exists on $instance." -Target $instance
                        }
                        'Strict' {
                            Stop-Function -Message "Job $j doesnn't exist on $instance." -Continue -ContinueLabel main -Target $instance -Category InvalidData
                        }
                    }
                } else {
                    # Check if the job step exists
                    if ($Server.JobServer.Jobs[$j].JobSteps.Name -notcontains $StepName) {
                        switch ($Mode) {
                            'Lazy' {
                                Write-Message -Level Verbose -Message "Step $StepName doesn't exist for $job on $instance." -Target $instance
                            }
                            'Strict' {
                                Stop-Function -Message "Step $StepName doesn't exist for $job on $instance." -Continue -ContinueLabel main -Target $instance -Category InvalidData
                            }
                        }
                    } else {
                        # Execute
                        if ($PSCmdlet.ShouldProcess($instance, "Removing the job step $StepName for job $j")) {
                            try {
                                $JobStep = $Server.JobServer.Jobs[$j].JobSteps[$StepName]
                                Write-Message -Level SomewhatVerbose -Message "Removing the job step $StepName for job $j."
                                $JobStep.Drop()
                            } catch {
                                Stop-Function -Message "Something went wrong removing the job step" -Target $JobStep -Continue -ErrorRecord $_
                                Write-Message -Level Verbose -Message "Could not remove the job step $StepName from $j"
                            }
                        }
                    }
                }
            }
        }
    }
    end {
        Write-Message -Message "Finished removing the jobs step(s)" -Level Verbose
    }
}
tools\dbatools\functions\Remove-DbaAgentSchedule.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaAgentSchedule {
    <#
    .SYNOPSIS
        Remove-DbaAgentJobSchedule removes a job schedule.

    .DESCRIPTION
        Remove-DbaAgentJobSchedule removes a job in the SQL Server Agent.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Schedule
        The name of the job schedule.

    .PARAMETER InputObject
        A collection of schedule (such as returned by Get-DbaAgentSchedule), to be removed.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER Force
        The force parameter will ignore some errors in the parameters and assume defaults.
        It will also remove the any present schedules with the same name for the specific job.

    .NOTES
        Tags: Agent, Job, Schedule
        Author: Sander Stad (@sqlstad), sqlstad.nl

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaAgentJobSchedule

    .EXAMPLE
        PS C:\> Remove-DbaAgentSchedule -SqlInstance sql1 -Schedule weekly

        Remove the schedule weekly

    .EXAMPLE
        PS C:\> Remove-DbaAgentSchedule -SqlInstance sql1 -Schedule weekly -Force

        Remove the schedule weekly from the job even if the schedule is being used by another job.

    .EXAMPLE
        PS C:\> Remove-DbaAgentSchedule -SqlInstance sql1 -Schedule daily, weekly

        Remove multiple schedule

    .EXAMPLE
        PS C:\> Remove-DbaAgentSchedule -SqlInstance sql1, sql2, sql3 -Schedule daily, weekly
        Remove the schedule on multiple servers for multiple schedules

    .EXAMPLE
        sql1, sql2, sql3 | Remove-DbaAgentSchedule -Schedule daily, weekly
        Remove the schedule on multiple servers using pipe line

    .EXAMPLE
        Get-DbaAgentSchedule -SqlInstance sql1 -Schedule sched1, sched2, sched3 | Remove-DbaAgentSchedule

        Remove the schedules using a pipeline

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [parameter(Mandatory, ValueFromPipeline, ParameterSetName = "instance")]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [System.Management.Automation.PSCredential]$SqlCredential,
        [Parameter(Mandatory, ParameterSetName = "instance")]
        [ValidateNotNullOrEmpty()]
        [Alias("Schedules")]
        [object[]]$Schedule,
        [Parameter(ValueFromPipeline, Mandatory, ParameterSetName = "schedules")]
        [Microsoft.SqlServer.Management.Smo.Agent.ScheduleBase[]]$InputObject,
        [Alias('Silent')]
        [switch]$EnableException,
        [switch]$Force
    )

    process {

        foreach ($instance in $sqlinstance) {
            # Try connecting to the instance
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $InputObject += $server.JobServer.SharedSchedules

            if ($Schedule) {
                $InputObject = $InputObject | Where-Object Name -in $Schedule
            }

        } # foreach object instance

        foreach ($currentschedule in $InputObject) {
            $server = $currentschedule.Parent.Parent

            if (-not $server) {
                $server = $currentschedule.Parent
            }

            $server.JobServer.SharedSchedules.Refresh()
            $schedulename = $currentschedule.Name
            $jobCount = $server.JobServer.SharedSchedules[$currentschedule].JobCount

            # Check if the schedule is shared among other jobs
            if ($jobCount -ge 1 -and -not $Force) {
                Stop-Function -Message "The schedule $schedulename is shared connected to one or more jobs. If removal is neccesary use -Force." -Target $instance -Continue
            }

            # Remove the job schedule
            if ($PSCmdlet.ShouldProcess($instance, "Removing schedule $currentschedule on $instance")) {
                # Loop through each of the schedules and drop them
                Write-Message -Message "Removing schedule $schedulename on $instance" -Level Verbose

                #Check if jobs use the schedule
                if ($jobCount -ge 1) {
                    # Get the job object
                    $smoSchedules = $server.JobServer.SharedSchedules | Where-Object { ($_.Name -eq $currentschedule.Name) }

                    Write-Message -Message "Schedule $schedulename is used in one or more jobs. Removing it for each job." -Level Verbose

                    # Loop through each if the schedules
                    foreach ($smoSchedule in ($smoSchedules)) {

                        # Get the job ids
                        $jobGuids = $Server.JobServer.SharedSchedules[$smoSchedule].EnumJobReferences()

                        if (($jobCount -gt 1 -and $Force) -or $jobCount -eq 1) {

                            # Loop though each of the jobs
                            foreach ($guid in $jobGuids) {
                                # Get the job object
                                $smoJob = $Server.JobServer.GetJobByID($guid)

                                # Get the job schedule
                                $jobSchedules = $Server.JobServer.Jobs[$smoJob].JobSchedules | Where-Object { $_.Name -eq $smoSchedule }

                                foreach ($jobSchedule in ($jobSchedules)) {
                                    try {
                                        Write-Message -Message "Removing the schedule $jobSchedule for job $smoJob" -Level Verbose

                                        $jobSchedule.Drop()
                                    } catch {
                                        Stop-Function -Message "Failure" -Target $instance -ErrorRecord $_ -Continue
                                    }
                                }
                            }
                        }
                    }
                }

                Write-Message -Message "Removing schedules that are not being used by other jobs." -Level Verbose
                $server.JobServer.SharedSchedules.Refresh()
                # Get the schedules
                $smoSchedules = $server.JobServer.SharedSchedules | Where-Object { ($_.Name -eq $currentschedule.Name) -and ($_.JobCount -eq 0) }

                # Remove the schedules that have no jobs
                foreach ($smoSchedule in $smoSchedules) {
                    try {
                        $smoSchedule.Drop()
                    } catch {
                        Stop-Function -Message "Something went wrong removing the schedule" -Target $instance -ErrorRecord $_ -Continue
                    }
                }
            }
        }
    }
    end {
        Write-Message -Message "Finished removing jobs schedule(s)." -Level Verbose
    }
}
tools\dbatools\functions\Remove-DbaAgListener.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaAgListener {
    <#
    .SYNOPSIS
        Removes a listener from an availability group on a SQL Server instance.

    .DESCRIPTION
        Removes a listener from an availability group on a SQL Server instance.

   .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.

    .PARAMETER SqlCredential
        Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Listener
        The listener or listeners to remove.

    .PARAMETER AvailabilityGroup
        Only remove listeners from specific availability groups.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER InputObject
        Enables piping from Get-DbaListener

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: AvailabilityGroup, HA, AG
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaAgListener

    .EXAMPLE
        PS C:\> Remove-DbaAgListener -SqlInstance sqlserver2012 -AvailabilityGroup ag1, ag2 -Confirm:$false

        Removes the ag1 and ag2 availability groups on sqlserver2012. Does not prompt for confirmation.

    .EXAMPLE
        PS C:\> Get-DbaAvailabilityGroup -SqlInstance sqlserver2012 -AvailabilityGroup availabilitygroup1 | Remove-DbaAgListener

        Removes the listeners returned from the Get-DbaAvailabilityGroup function. Prompts for confirmation.
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Listener,
        [string[]]$AvailabilityGroup,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.AvailabilityGroupListener[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ((Test-Bound -ParameterName SqlInstance)) {
            if ((Test-Bound -Not -ParameterName Listener)) {
                Stop-Function -Message "You must specify one or more listeners and one or more Availability Groups when using the SqlInstance parameter."
                return
            }
        }

        if ($SqlInstance) {
            $InputObject += Get-DbaAgListener -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Listener $Listener
        }

        foreach ($aglistener in $InputObject) {
            if ($Pscmdlet.ShouldProcess($aglistener.Parent.Parent.Name, "Removing availability group listener $aglistener")) {
                try {
                    $ag = $aglistener.Parent.Name
                    $aglistener.Parent.AvailabilityGroupListeners[$aglistener.Name].Drop()
                    [pscustomobject]@{
                        ComputerName      = $aglistener.ComputerName
                        InstanceName      = $aglistener.InstanceName
                        SqlInstance       = $aglistener.SqlInstance
                        AvailabilityGroup = $ag
                        Listener          = $aglistener.Name
                        Status            = "Removed"
                    }
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Remove-DbaAgReplica.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaAgReplica {
    <#
    .SYNOPSIS
        Removes availability group replicas from availability groups.

    .DESCRIPTION
        Removes availability group replicas from availability groups.

   .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.

    .PARAMETER SqlCredential
        Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER AvailabilityGroup
        The specific availability group to query.

    .PARAMETER Replica
        The replica to remove.

    .PARAMETER InputObject
        Enables piped input from Get-DbaAgReplica.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: AG, HA, AvailabilityGroup, Replica
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaAgReplica

    .EXAMPLE
        PS C:\> Remove-DbaAgReplica -SqlInstance sql2017a -AvailabilityGroup SharePoint -Replica sp1

       Removes the sp1 replica from the SharePoint ag on sql2017a. Prompts for confirmation.

    .EXAMPLE
        PS C:\> Remove-DbaAgReplica -SqlInstance sql2017a | Select-Object *

        Returns full object properties on all availability group replicas found on sql2017a

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$AvailabilityGroup,
        [string[]]$Replica,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.AvailabilityReplica[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ($SqlInstance -and -not $Replica) {
            Stop-Function -Message "You must specify a replica when using the SqlInstance parameter."
            return
        }

        if ($SqlInstance) {
            $InputObject += Get-DbaAgReplica -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Replica $Replica -AvailabilityGroup $AvailabilityGroup
        }

        foreach ($agreplica in $InputObject) {
            if ($Pscmdlet.ShouldProcess($agreplica.Parent.Parent.Name, "Removing availability group replica $agreplica")) {
                try {
                    $agreplica.Parent.AvailabilityGroupReplicas[$agreplica.Name].Drop()
                    [pscustomobject]@{
                        ComputerName      = $agreplica.ComputerName
                        InstanceName      = $agreplica.InstanceName
                        SqlInstance       = $agreplica.SqlInstance
                        AvailabilityGroup = $agreplica.Parent.Name
                        Replica           = $agreplica.Name
                        Status            = "Removed"
                    }
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Remove-DbaAvailabilityGroup.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaAvailabilityGroup {
    <#
    .SYNOPSIS
        Removes availability groups on a SQL Server instance.

    .DESCRIPTION
        Removes availability groups on a SQL Server instance.

        If possible, remove the availability group only while connected to the server instance that hosts the primary replica.
        When the availability group is dropped from the primary replica, changes are allowed in the former primary databases (without high availability protection).
        Deleting an availability group from a secondary replica leaves the primary replica in the RESTORING state, and changes are not allowed on the databases.

        Avoid dropping an availability group when the Windows Server Failover Clustering (WSFC) cluster has no quorum.
        If you must drop an availability group while the cluster lacks quorum, the metadata availability group that is stored in the cluster is not removed.
        After the cluster regains quorum, you will need to drop the availability group again to remove it from the WSFC cluster.

        For more information: https://docs.microsoft.com/en-us/sql/t-sql/statements/drop-availability-group-transact-sql

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.

    .PARAMETER SqlCredential
        Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER AvailabilityGroup
        Only remove specific availability groups.

    .PARAMETER AllAvailabilityGroups
        Remove all availability groups on an instance.

    .PARAMETER InputObject
        Enables piping from Get-DbaAvailabilityGroup.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: AvailabilityGroup, HA, AG
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaAvailabilityGroup

    .EXAMPLE
        PS C:\> Remove-DbaAvailabilityGroup -SqlInstance sqlserver2012 -AllAvailabilityGroups

        Removes all availability groups on the sqlserver2014 instance. Prompts for confirmation.

    .EXAMPLE
        PS C:\> Remove-DbaAvailabilityGroup -SqlInstance sqlserver2012 -AvailabilityGroup ag1, ag2 -Confirm:$false

        Removes the ag1 and ag2 availability groups on sqlserver2012.  Does not prompt for confirmation.

    .EXAMPLE
        PS C:\> Get-DbaAvailabilityGroup -SqlInstance sqlserver2012 -AvailabilityGroup availabilitygroup1 | Remove-DbaAvailabilityGroup

        Removes the availability groups returned from the Get-DbaAvailabilityGroup function. Prompts for confirmation.
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$AvailabilityGroup,
        [switch]$AllAvailabilityGroups,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.AvailabilityGroup[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ((Test-Bound -ParameterName SqlInstance) -and (Test-Bound -Not -ParameterName AvailabilityGroup, AllAvailabilityGroups)) {
            Stop-Function -Message "You must specify AllAvailabilityGroups groups or AvailabilityGroups when using the SqlInstance parameter."
            return
        }
        if ($SqlInstance) {
            $InputObject += Get-DbaAvailabilityGroup -SqlInstance $SqlInstance -SqlCredential $SqlCredential -AvailabilityGroup $AvailabilityGroup
        }
        foreach ($ag in $InputObject) {
            if ($Pscmdlet.ShouldProcess($ag.Parent.Name, "Removing availability group $ag")) {
                # avoid enumeration issues
                try {
                    $ag.Parent.Query("DROP AVAILABILITY GROUP $ag")
                    [pscustomobject]@{
                        ComputerName      = $ag.ComputerName
                        InstanceName      = $ag.InstanceName
                        SqlInstance       = $ag.SqlInstance
                        AvailabilityGroup = $ag.Name
                        Status            = "Removed"
                    }
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Remove-DbaBackup.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaBackup {
    <#
    .SYNOPSIS
        Removes SQL Server backups from disk.

    .DESCRIPTION
        Removes SQL Server backups from disk.

        Provides all of the same functionality for removing SQL backups from disk as a standard maintenance plan would.

        As an addition you have the ability to check the Archive bit on files before deletion. This will allow you to ensure backups have been archived to your archive location before removal.

        Also included is the ability to remove empty folders as part of this cleanup activity.

    .PARAMETER Path
        Specifies the name of the base level folder to search for backup files. Deletion of backup files will be recursive from this location.

    .PARAMETER BackupFileExtension
        Specifies the filename extension of the backup files you wish to remove (typically 'bak', 'trn' or 'log'). Do not include the period.

    .PARAMETER RetentionPeriod
        Specifies the retention period for backup files. Correct format is ##U.

        ## is the retention value and must be an integer value
        U signifies the units where the valid units are:
        h = hours
        d = days
        w = weeks
        m = months

        Formatting Examples:
        '48h' = 48 hours
        '7d' = 7 days
        '4w' = 4 weeks
        '1m' = 1 month

    .PARAMETER CheckArchiveBit
        If this switch is enabled, the filesystem Archive bit is checked before deletion. If this bit is set (which translates to "it has not been backed up to another location yet", the file won't be deleted.

    .PARAMETER RemoveEmptyBackupFolder
        If this switch is enabled, empty folders will be removed after the cleanup process is complete.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.i

    .NOTES
        Tags: Storage, DisasterRecovery, Backup
        Author: Chris Sommer (@cjsommer), www.cjsommer.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaBackup

    .EXAMPLE
        PS C:\> Remove-DbaBackup -Path 'C:\MSSQL\SQL Backup\' -BackupFileExtension trn -RetentionPeriod 48h

        '*.trn' files in 'C:\MSSQL\SQL Backup\' and all subdirectories that are more than 48 hours old will be removed.

    .EXAMPLE
        PS C:\> Remove-DbaBackup -Path 'C:\MSSQL\SQL Backup\' -BackupFileExtension trn -RetentionPeriod 48h -WhatIf

        Same as example #1, but doesn't actually remove any files. The function will instead show you what would be done.
        This is useful when first experimenting with using the function.

    .EXAMPLE
        PS C:\> Remove-DbaBackup -Path 'C:\MSSQL\Backup\' -BackupFileExtension bak -RetentionPeriod 7d -CheckArchiveBit

        '*.bak' files in 'C:\MSSQL\Backup\' and all subdirectories that are more than 7 days old will be removed, but only if the files have been backed up to another location as verified by checking the Archive bit.

    .EXAMPLE
        PS C:\> Remove-DbaBackup -Path 'C:\MSSQL\Backup\' -BackupFileExtension bak -RetentionPeriod 1w -RemoveEmptyBackupFolder

        '*.bak' files in 'C:\MSSQL\Backup\' and all subdirectories that are more than 1 week old will be removed. Any folders left empty will be removed as well.

#>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, HelpMessage = "Full path to the root level backup folder (ex. 'C:\SQL\Backups'")]
        [Alias("BackupFolder")]
        [string]$Path,
        [parameter(Mandatory, HelpMessage = "Backup File extension to remove (ex. bak, trn, dif)")]
        [string]$BackupFileExtension ,
        [parameter(Mandatory, HelpMessage = "Backup retention period. (ex. 24h, 7d, 4w, 6m)")]
        [string]$RetentionPeriod ,
        [switch]$CheckArchiveBit = $false ,
        [switch]$RemoveEmptyBackupFolder = $false,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        # Ensure BackupFileExtension does not begin with a .
        if ($BackupFileExtension -match "^[.]") {
            Write-Message -Level Warning -Message "Parameter -BackupFileExtension begins with a period '$BackupFileExtension'. A period is automatically prepended to -BackupFileExtension and need not be passed in."
        }
    }
    process {
        # Process stuff
        Write-Message -Message "Removing backups from $Path" -Level Verbose
        Find-DbaBackup -Path $Path -BackupFileExtension $BackupFileExtension -RetentionPeriod $RetentionPeriod -CheckArchiveBit:$CheckArchiveBit -EnableException |
            Foreach-Object {
            $file = $_
            if ($PSCmdlet.ShouldProcess($file.Directory.FullName, "Removing backup file $($file.Name)")) {
                try {
                    $file | Remove-Item -Force -EA Stop
                } catch {
                    Write-Message -Message "Failed to remove $file." -Level Warning -ErrorRecord $_
                }
            }
        }
        Write-Message -Message "File Cleaning ended." -Level Verbose
        # Cleanup empty backup folders.
        if ($RemoveEmptyBackupFolder) {
            Write-Message -Message "Removing empty folders." -Level Verbose
            (Get-ChildItem -Directory -Path $Path -Recurse -ErrorAction SilentlyContinue -ErrorVariable EnumErrors).FullName |
                Sort-Object -Descending |
                Foreach-Object {
                $OrigPath = $_
                try {
                    $Contents = @(Get-ChildItem -Force $OrigPath -ErrorAction Stop)
                } catch {
                    Write-Message -Message "Can't enumerate $OrigPath." -Level Warning -ErrorRecord $_
                }
                if ($Contents.Count -eq 0) {
                    return $_
                }
            } |
                Foreach-Object {
                $FolderPath = $_
                if ($PSCmdlet.ShouldProcess($Path, "Removing empty folder .$($FolderPath.Replace($Path, ''))")) {
                    try {
                        $FolderPath | Remove-Item -ErrorAction Stop
                    } catch {
                        Write-Message -Message "Failed to remove $FolderPath." -Level Warning -ErrorRecord $_
                    }
                }
            }
            if ($EnumErrors) {
                Write-Message "Errors encountered enumerating folders." -Level Warning -ErrorRecord $EnumErrors
            }
            Write-Message -Message "Removed empty folders." -Level Verbose
        }
    }
}
tools\dbatools\functions\Remove-DbaClientAlias.ps1
function Remove-DbaClientAlias {
    <#
    .SYNOPSIS
        Removes a sql alias for the specified server - mimics cliconfg.exe

    .DESCRIPTION
        Removes a sql alias for the specified server by altering HKLM:\SOFTWARE\Microsoft\MSSQLServer\Client - mimics cliconfg.exe.

    .PARAMETER ComputerName
        The target computer where the alias will be created.

    .PARAMETER Credential
        Allows you to login to remote computers using alternative credentials

    .PARAMETER Alias
        The alias or array of aliases to be deleted

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Alias
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaClientAlias

    .EXAMPLE
        PS C:\> Remove-DbaClientAlias -ComputerName workstationx -Alias sqlps

        Removes the sqlps SQL client alias on workstationx

    .EXAMPLE
        PS C:\> Get-DbaClientAlias | Remove-DbaClientAlias

        Removes all SQL Server client aliases on the local computer

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(ValueFromPipelineByPropertyName = $true)]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [parameter(Mandatory, ValueFromPipelineByPropertyName = $true)]
        [Alias('AliasName')]
        [string[]]$Alias,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $scriptblock = {
            $Alias = $args

            $basekeys = "HKLM:\SOFTWARE\WOW6432Node\Microsoft\MSSQLServer", "HKLM:\SOFTWARE\Microsoft\MSSQLServer"

            foreach ($basekey in $basekeys) {
                $fullKey = "$basekey\Client\ConnectTo"
                if ((Test-Path $fullKey) -eq $false) {
                    <# DO NOT use Write-Message as this is inside of a script block #>
                    Write-Warning "Registry key ($fullKey) does not exist. Quitting."
                    continue
                }

                if ($basekey -like "*WOW64*") {
                    $architecture = "32-bit"
                } else {
                    $architecture = "64-bit"
                }

                $all = Get-Item -Path $fullKey
                foreach ($entry in $all) {
                    $e = $entry.ToString().Replace('HKEY_LOCAL_MACHINE', 'HKLM:\')
                    foreach ($a in $Alias) {
                        if ($entry.Property -contains $a) {
                            Remove-ItemProperty -Path $e -Name $a

                            [PSCustomObject]@{
                                ComputerName = $computer
                                Architecture = $architecture
                                Alias        = $a
                                Status       = "Removed"
                            }
                        }
                    }
                }
            }
        }
    }

    process {
        foreach ($computer in $ComputerName) {
            $null = Test-ElevationRequirement -ComputerName $computer -Continue

            if ($PSCmdlet.ShouldProcess("$($Alias -join ', ') on $computer", "Remove aliases")) {
                try {
                    Invoke-Command2 -ComputerName $computer -Credential $Credential -ScriptBlock $scriptblock -ErrorAction Stop -Verbose:$false -ArgumentList $Alias
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target $computer -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Remove-DbaCmConnection.ps1
function Remove-DbaCmConnection {
    <#
    .SYNOPSIS
        Removes connection objects from the connection cache used for remote computer management.

    .DESCRIPTION
        Removes connection objects from the connection cache used for remote computer management.

    .PARAMETER ComputerName
        The target computer. Accepts both text as well as the output of Get-DbaCmConnection.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ComputerManagement, CIM
        Author: Friedrich Weinmann (@FredWeinmann)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaCmConnection

    .EXAMPLE
        PS C:\> Remove-DbaCmConnection -ComputerName sql2014

        Removes the cached connection to the server sql2014 from the cache.

    .EXAMPLE
        PS C:\> Get-DbaCmConnection | Remove-DbaCmConnection

        Clears the entire connection cache.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [Parameter(ValueFromPipeline, Mandatory)]
        [Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter[]]
        $ComputerName,

        [switch]
        [Alias('Silent')]$EnableException
    )

    begin {
        Write-Message -Level InternalComment -Message "Starting"
        Write-Message -Level Verbose -Message "Bound parameters: $($PSBoundParameters.Keys -join ", ")"
    }
    process {
        foreach ($connectionObject in $ComputerName) {
            if (-not $connectionObject.Success) { Stop-Function -Message "Failed to interpret computername input: $($connectionObject.InputObject)" -Category InvalidArgument -Target $connectionObject.InputObject -Continue }
            Write-Message -Level VeryVerbose -Message "Removing from connection cache: $($connectionObject.Connection.ComputerName)" -Target $connectionObject.Connection.ComputerName
            if ($Pscmdlet.ShouldProcess($($connectionObject.Connection.ComputerName), "Removing Connection")) {
                if ([Sqlcollaborative.Dbatools.Connection.ConnectionHost]::Connections.ContainsKey($connectionObject.Connection.ComputerName)) {
                    $null = [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::Connections.Remove($connectionObject.Connection.ComputerName)
                    Write-Message -Level Verbose -Message "Successfully removed $($connectionObject.Connection.ComputerName)" -Target $connectionObject.Connection.ComputerName
                } else {
                    Write-Message -Level Verbose -Message "Not found: $($connectionObject.Connection.ComputerName)" -Target $connectionObject.Connection.ComputerName
                }
            }
        }
    }
    end {
        Write-Message -Level InternalComment -Message "Ending"
    }
}
tools\dbatools\functions\Remove-DbaCmsRegServer.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaCmsRegServer {
    <#
    .SYNOPSIS
        Removes registered servers found in SQL Server Central Management Server (CMS).

    .DESCRIPTION
        Removes registered servers found in SQL Server Central Management Server (CMS).

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Name
        Specifies one or more names to include. Name is the visible name in SSMS CMS interface (labeled Registered Server Name)

    .PARAMETER ServerName
        Specifies one or more server names to include. Server Name is the actual instance name (labeled Server Name)

    .PARAMETER Group
        Specifies one or more groups to include from SQL Server Central Management Server.

    .PARAMETER InputObject
        Allows results from Get-DbaCmsRegServer to be piped in

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.

        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.

        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: RegisteredServer, CMS
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaCmsRegServer

    .EXAMPLE
        PS C:\> Remove-DbaCmsRegServer -SqlInstance sql2012 -Group HR, Accounting

        Removes all servers from the HR and Accounting groups on sql2012

    .EXAMPLE
        PS C:\> Remove-DbaCmsRegServer -SqlInstance sql2012 -Group HR\Development

        Removes all servers from the HR and sub-group Development from the CMS on sql2012.

    .EXAMPLE
        PS C:\> Remove-DbaCmsRegServer -SqlInstance sql2012 -Confirm:$false

        Removes all registered servers on sql2012 and turns off all prompting

    #>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Name,
        [string[]]$ServerName,
        [string[]]$Group,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.RegisteredServers.RegisteredServer[]]$InputObject,
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaCmsRegServer -SqlInstance $instance -SqlCredential $SqlCredential -Group $Group -ExcludeGroup $ExcludeGroup -Name $Name -ServerName $ServerName
        }

        foreach ($regserver in $InputObject) {
            $server = $regserver.Parent

            if ($Pscmdlet.ShouldProcess($regserver.Parent, "Removing $regserver")) {
                $null = $regserver.Drop()
                Disconnect-RegServer -Server $server

                try {
                    [pscustomobject]@{
                        ComputerName = $regserver.ComputerName
                        InstanceName = $regserver.InstanceName
                        SqlInstance  = $regserver.SqlInstance
                        Name         = $regserver.Name
                        ServerName   = $regserver.ServerName
                        Status       = "Dropped"
                    }
                } catch {
                    Stop-Function -Message "Failed to drop $regserver on $server" -ErrorRecord $_ -Continue
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Remove-DbaRegisteredServer
    }
}
tools\dbatools\functions\Remove-DbaCmsRegServerGroup.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaCmsRegServerGroup {
    <#
    .SYNOPSIS
        Gets list of Server Groups objects stored in SQL Server Central Management Server (CMS).

    .DESCRIPTION
        Returns an array of Server Groups found in the CMS.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Name
        Specifies one or more groups to include from SQL Server Central Management Server.

    .PARAMETER InputObject
        Allows results from Get-DbaCmsRegServerGroup to be piped in

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.

        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.

        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: RegisteredServer, CMS
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaCmsRegServerGroup

    .EXAMPLE
        PS C:\> Remove-DbaCmsRegServerGroup -SqlInstance sql2012 -Group HR, Accounting

        Removes the HR and Accounting groups on sql2012

    .EXAMPLE
        PS C:\> Remove-DbaCmsRegServerGroup -SqlInstance sql2012 -Group HR\Development -Confirm:$false

        Removes the Development subgroup within the HR group on sql2012 and turns off all prompting

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Group")]
        [string[]]$Name,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.RegisteredServers.ServerGroup[]]$InputObject,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaCmsRegServerGroup -SqlInstance $instance -SqlCredential $SqlCredential -Group $Name
        }

        foreach ($regservergroup in $InputObject) {
            $parentserver = Get-RegServerParent -InputObject $regservergroup

            if ($null -eq $parentserver) {
                Stop-Function -Message "Something went wrong and it's hard to explain, sorry. This basically shouldn't happen." -Continue
            }

            if ($Pscmdlet.ShouldProcess($parentserver.DomainInstanceName, "Removing $($regservergroup.Name) CMS Group")) {
                $null = $parentserver.ServerConnection.ExecuteNonQuery($regservergroup.ScriptDrop().GetScript())
                $parentserver.ServerConnection.Disconnect()
                try {
                    [pscustomobject]@{
                        ComputerName = $parentserver.ComputerName
                        InstanceName = $parentserver.InstanceName
                        SqlInstance  = $parentserver.SqlInstance
                        Name         = $regservergroup.Name
                        Status       = "Dropped"
                    }
                } catch {
                    Stop-Function -Message "Failed to drop $regservergroup on $parentserver" -ErrorRecord $_ -Continue
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Remove-DbaRegisteredServerGroup
    }
}
tools\dbatools\functions\Remove-DbaComputerCertificate.ps1
function Remove-DbaComputerCertificate {
    <#
    .SYNOPSIS
        Removes a computer certificate - useful for removing easily certs from remote computers

    .DESCRIPTION
        Removes a computer certificate from a local or remote compuer

    .PARAMETER ComputerName
        The target computer. Defaults to localhost.

    .PARAMETER Credential
        Allows you to login to $ComputerName using alternative credentials

    .PARAMETER Thumbprint
        The thumbprint of the certificate object

    .PARAMETER Store
        Certificate store - defaults to LocalMachine (otherwise exceptions can be thrown on remote connections)

    .PARAMETER Folder
        Certificate folder

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .NOTES
        Tags: Certificate
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaComputerCertificate

    .EXAMPLE
        PS C:\> Remove-DbaComputerCertificate -ComputerName Server1 -Thumbprint C2BBE81A94FEE7A26FFF86C2DFDAF6BFD28C6C94

        Removes certificate with thumbprint C2BBE81A94FEE7A26FFF86C2DFDAF6BFD28C6C94 in the LocalMachine store on Server1

    .EXAMPLE
        PS C:\> Get-DbaComputerCertificate | Where-Object Thumbprint -eq E0A071E387396723C45E92D42B2D497C6A182340 | Remove-DbaComputerCertificate

        Removes certificate using the pipeline

    .EXAMPLE
        PS C:\> Remove-DbaComputerCertificate -ComputerName Server1 -Thumbprint C2BBE81A94FEE7A26FFF86C2DFDAF6BFD28C6C94 -Store User -Folder My

        Removes certificate with thumbprint C2BBE81A94FEE7A26FFF86C2DFDAF6BFD28C6C94 in the User\My (Personal) store on Server1

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")]
    param (
        [Alias("ServerInstance", "SqlServer", "SqlInstance")]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [parameter(ValueFromPipelineByPropertyName, Mandatory)]
        [string[]]$Thumbprint,
        [string]$Store = "LocalMachine",
        [string]$Folder = "My",
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        #region Scriptblock for remoting
        $scriptblock = {
            param (
                $Thumbprint,
                $Store,
                $Folder
            )
            <# DO NOT use Write-Message as this is inside of a script block #>
            Write-Verbose "Searching Cert:\$Store\$Folder for thumbprint: $thumbprint"
            function Get-CoreCertStore {
                [CmdletBinding()]
                param (
                    [ValidateSet("CurrentUser", "LocalMachine")]
                    [string]$Store,
                    [ValidateSet("AddressBook", "AuthRoot, CertificateAuthority", "Disallowed", "My", "Root", "TrustedPeople", "TrustedPublisher")]
                    [string]$Folder,
                    [ValidateSet("ReadOnly", "ReadWrite")]
                    [string]$Flag = "ReadOnly"
                )

                $storename = [System.Security.Cryptography.X509Certificates.StoreLocation]::$Store
                $foldername = [System.Security.Cryptography.X509Certificates.StoreName]::$Folder
                $flags = [System.Security.Cryptography.X509Certificates.OpenFlags]::$Flag
                $certstore = [System.Security.Cryptography.X509Certificates.X509Store]::New($foldername, $storename)
                $certstore.Open($flags)

                $certstore
            }

            function Get-CoreCertificate {
                [CmdletBinding()]
                param (
                    [ValidateSet("CurrentUser", "LocalMachine")]
                    [string]$Store,
                    [ValidateSet("AddressBook", "AuthRoot, CertificateAuthority", "Disallowed", "My", "Root", "TrustedPeople", "TrustedPublisher")]
                    [string]$Folder,
                    [ValidateSet("ReadOnly", "ReadWrite")]
                    [string]$Flag = "ReadOnly",
                    [string[]]$Thumbprint,
                    [System.Security.Cryptography.X509Certificates.X509Store[]]$InputObject
                )

                if (-not $InputObject) {
                    $InputObject += Get-CoreCertStore -Store $Store -Folder $Folder -Flag $Flag
                }

                $certs = ($InputObject).Certificates

                if ($Thumbprint) {
                    $certs = $certs | Where-Object Thumbprint -in $Thumbprint
                }
                $certs
            }

            if ($Thumbprint) {
                try {
                    <# DO NOT use Write-Message as this is inside of a script block #>
                    Write-Verbose "Searching Cert:\$Store\$Folder"
                    $cert = Get-CoreCertificate -Store $Store -Folder $Folder -Thumbprint $Thumbprint
                } catch {
                    # don't care - there's a weird issue with remoting where an exception gets thrown for no apparent reason
                    # here to avoid an empty catch
                    $null = 1
                }
            }

            if ($cert) {
                $certstore = Get-CoreCertStore -Store $Store -Folder $Folder -Flag ReadWrite
                $certstore.Remove($cert)
                $status = "Removed"
            } else {
                $status = "Certificate not found in Cert:\$Store\$Folder"
            }

            [pscustomobject]@{
                ComputerName = $env:COMPUTERNAME
                Store        = $Store
                Folder       = $Folder
                Thumbprint   = $thumbprint
                Status       = $status
            }
        }
        #endregion Scriptblock for remoting
    }

    process {
        foreach ($computer in $computername) {
            foreach ($thumb in $Thumbprint) {
                if ($PScmdlet.ShouldProcess("local", "Connecting to $computer to remove cert from Cert:\$Store\$Folder")) {
                    try {
                        Invoke-Command2 -ComputerName $computer -Credential $Credential -ArgumentList $thumb, $Store, $Folder -ScriptBlock $scriptblock -ErrorAction Stop
                    } catch {
                        Stop-Function -Message $_ -ErrorRecord $_ -Target $computer -Continue
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Remove-DbaDatabase.ps1
function Remove-DbaDatabase {
    <#
    .SYNOPSIS
        Drops a database, hopefully even the really stuck ones.

    .DESCRIPTION
        Tries a bunch of different ways to remove a database or two or more.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER InputObject
        A collection of databases (such as returned by Get-DbaDatabase), to be removed.

    .PARAMETER IncludeSystemDb
        Use this switch to disable any kind of verbose messages

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Delete, Databases
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaDatabase

    .EXAMPLE
        PS C:\> Remove-DbaDatabase -SqlInstance sql2016 -Database containeddb

        Prompts then removes the database containeddb on SQL Server sql2016

    .EXAMPLE
        PS C:\> Remove-DbaDatabase -SqlInstance sql2016 -Database containeddb, mydb

        Prompts then removes the databases containeddb and mydb on SQL Server sql2016

    .EXAMPLE
        PS C:\> Remove-DbaDatabase -SqlInstance sql2016 -Database containeddb -Confirm:$false

        Does not prompt and swiftly removes containeddb on SQL Server sql2016

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance server\instance -ExcludeSystem | Remove-DbaDatabase

        Removes all the user databases from server\instance

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance server\instance -ExcludeSystem | Remove-DbaDatabase -Confirm:$false

        Removes all the user databases from server\instance without any confirmation
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High', DefaultParameterSetName = "Default")]
    param (
        [parameter(Mandatory, ParameterSetName = "instance")]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]
        $SqlCredential,
        [parameter(Mandatory, ParameterSetName = "instance")]
        [Alias("Databases")]
        [object[]]$Database,
        [Parameter(ValueFromPipeline, Mandatory, ParameterSetName = "databases")]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$IncludeSystemDb,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            $InputObject += $server.Databases | Where-Object { $_.Name -in $Database }
        }

        $system_dbs = @( "master", "model", "tempdb", "resource", "msdb" )

        if (-not($IncludeSystemDb)) {
            $InputObject = $InputObject | Where-Object { $_.Name -notin $system_dbs}
        }

        foreach ($db in $InputObject) {
            try {
                $server = $db.Parent
                if ($Pscmdlet.ShouldProcess("$db on $server", "KillDatabase")) {
                    $server.KillDatabase($db.name)
                    $server.Refresh()

                    [pscustomobject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Database     = $db.name
                        Status       = "Dropped"
                    }
                }
            } catch {
                try {
                    if ($Pscmdlet.ShouldProcess("$db on $server", "alter db set single_user with rollback immediate then drop")) {
                        $null = $server.Query("if exists (select * from sys.databases where name = '$($db.name)' and state = 0) alter database $db set single_user with rollback immediate; drop database $db")

                        [pscustomobject]@{
                            ComputerName = $server.ComputerName
                            InstanceName = $server.ServiceName
                            SqlInstance  = $server.DomainInstanceName
                            Database     = $db.name
                            Status       = "Dropped"
                        }
                    }
                } catch {
                    try {
                        if ($Pscmdlet.ShouldProcess("$db on $server", "SMO drop")) {
                            $dbname = $db.Name
                            $db.Parent.databases[$dbname].Drop()
                            $server.Refresh()

                            [pscustomobject]@{
                                ComputerName = $server.ComputerName
                                InstanceName = $server.ServiceName
                                SqlInstance  = $server.DomainInstanceName
                                Database     = $db.name
                                Status       = "Dropped"
                            }
                        }
                    } catch {
                        Write-Message -Level Verbose -Message "Could not drop database $db on $server"

                        [pscustomobject]@{
                            ComputerName = $server.ComputerName
                            InstanceName = $server.ServiceName
                            SqlInstance  = $server.DomainInstanceName
                            Database     = $db.name
                            Status       = (Get-ErrorMessage -Record $_)
                        }
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Remove-DbaDatabaseSafely.ps1
function Remove-DbaDatabaseSafely {
    <#
    .SYNOPSIS
        Safely removes a SQL Database and creates an Agent Job to restore it.

    .DESCRIPTION
        Performs a DBCC CHECKDB on the database, backs up the database with Checksum and verify only to a final (golden) backup location, creates an Agent Job to restore from that backup, drops the database, runs the agent job to restore the database, performs a DBCC CHECKDB and drops the database.

        With huge thanks to Grant Fritchey and his verify your backups video. Take a look, it's only 3 minutes long. http://sqlps.io/backuprant

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        If specified, Agent jobs will be created on this server. By default, the jobs will be created on the server specified by SqlInstance. You must have sysadmin access and the server must be SQL Server 2000 or higher. The SQL Agent service will be started if it is not already running.

    .PARAMETER DestinationCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies one or more databases to remove.

    .PARAMETER NoDbccCheckDb
        If this switch is enabled, the initial DBCC CHECK DB will be skipped. This will make the process quicker but will also allow you to create an Agent job that restores a database backup containing a corrupt database.

        A second DBCC CHECKDB is performed on the restored database so you will still be notified BUT USE THIS WITH CARE.

    .PARAMETER BackupFolder
        Specifies the path to a folder where the final backups of the removed databases will be stored. If you are using separate source and destination servers, you must specify a UNC path such as  \\SERVER1\BACKUPSHARE\

    .PARAMETER JobOwner
        Specifies the name of the account which will own the Agent jobs. By default, sa is used.

    .PARAMETER UseDefaultFilePaths
        If this switch is enabled, the default file paths for the data and log files on the instance where the database is restored will be used. By default, the original file paths will be used.

    .PARAMETER CategoryName
        Specifies the Category Name for the Agent job that is created for restoring the database(s). By default, the name is "Rationalisation".

    .PARAMETER BackupCompression
        If this switch is enabled, compression will be used for the backup regardless of the SQL Server instance setting. By default, the SQL Server instance setting for backup compression is used.

    .PARAMETER AllDatabases
        If this switch is enabled, all user databases on the server will be removed. This is useful when decommissioning a server. You should use a Destination with this switch.

    .PARAMETER ReuseSourceFolderStructure
        If this switch is enabled, the source folder structure will be used when restoring instead of using the destination instance default folder structure.

    .PARAMETER Force
        If this switch is enabled, all actions will be performed even if DBCC errors are detected. An Agent job will be created with 'DBCCERROR' in the name and the backup file will have 'DBCC' in its name.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database, Remove
        Author: Rob Sewell (@SQLDBAWithBeard), sqldbawithabeard.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaDatabaseSafely

    .EXAMPLE
        PS C:\> Remove-DbaDatabaseSafely -SqlInstance 'Fade2Black' -Database RideTheLightning -BackupFolder 'C:\MSSQL\Backup\Rationalised - DO NOT DELETE'

        Performs a DBCC CHECKDB on database RideTheLightning on server Fade2Black. If there are no errors, the database is backup to the folder C:\MSSQL\Backup\Rationalised - DO NOT DELETE. Then, an Agent job to restore the database from that backup is created. The database is then dropped, the Agent job to restore it run, a DBCC CHECKDB run against the restored database, and then it is dropped again.

        Any DBCC errors will be written to your documents folder

    .EXAMPLE
        PS C:\> $Database = 'DemoNCIndex','RemoveTestDatabase'
        PS C:\> Remove-DbaDatabaseSafely -SqlInstance 'Fade2Black' -Database $Database -BackupFolder 'C:\MSSQL\Backup\Rationalised - DO NOT DELETE'

        Performs a DBCC CHECKDB on two databases, 'DemoNCIndex' and 'RemoveTestDatabase' on server Fade2Black. Then, an Agent job to restore each database from those backups is created. The databases are then dropped, the Agent jobs to restore them run, a DBCC CHECKDB run against the restored databases, and then they are dropped again.

        Any DBCC errors will be written to your documents folder

    .EXAMPLE
        PS C:\> Remove-DbaDatabaseSafely -SqlInstance 'Fade2Black' -Destination JusticeForAll -Database RideTheLightning -BackupFolder '\\BACKUPSERVER\BACKUPSHARE\MSSQL\Rationalised - DO NOT DELETE'

        Performs a DBCC CHECKDB on database RideTheLightning on server Fade2Black. If there are no errors, the database is backup to the folder \\BACKUPSERVER\BACKUPSHARE\MSSQL\Rationalised - DO NOT DELETE . Then, an Agent job is created on server JusticeForAll to restore the database from that backup is created. The database is then dropped on Fade2Black, the Agent job to restore it on JusticeForAll is run, a DBCC CHECKDB run against the restored database, and then it is dropped from JusticeForAll.

        Any DBCC errors will be written to your documents folder

    .EXAMPLE
        PS C:\> Remove-DbaDatabaseSafely -SqlInstance IronMaiden -Database $Database -Destination TheWildHearts -BackupFolder Z:\Backups -NoDbccCheckDb -JobOwner 'THEBEARD\Rob'

        For the databases $Database on the server IronMaiden a DBCC CHECKDB will not be performed before backing up the databases to the folder Z:\Backups. Then, an Agent job is created on server TheWildHearts with a Job Owner of THEBEARD\Rob to restore each database from that backup using the instance's default file paths. The database(s) is(are) then dropped on IronMaiden, the Agent job(s) run, a DBCC CHECKDB run on the restored database(s), and then the database(s) is(are) dropped.

    .EXAMPLE
        PS C:\> Remove-DbaDatabaseSafely -SqlInstance IronMaiden -Database $Database -Destination TheWildHearts -BackupFolder Z:\Backups

        The databases $Database on the server IronMaiden will be backed up the to the folder Z:\Backups. Then, an Agent job is created on server TheWildHearts with a Job Owner of THEBEARD\Rob to restore each database from that backup using the instance's default file paths. The database(s) is(are) then dropped on IronMaiden, the Agent job(s) run, a DBCC CHECKDB run on the restored database(s), and then the database(s) is(are) dropped.

        If there is a DBCC Error, the function  will continue to perform rest of the actions and will create an Agent job with 'DBCCERROR' in the name and a Backup file with 'DBCCError' in the name.

    #>
    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = "Default")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]
        $SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [DbaInstanceParameter]$Destination = $sqlinstance,
        [PSCredential]
        $DestinationCredential,
        [Alias("NoCheck")]
        [switch]$NoDbccCheckDb,
        [parameter(Mandatory)]
        [string]$BackupFolder,
        [string]$CategoryName = 'Rationalisation',
        [string]$JobOwner,
        [switch]$AllDatabases,
        [ValidateSet("Default", "On", "Of")]
        [string]$BackupCompression = 'Default',
        [switch]$ReuseSourceFolderStructure,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        if (!$AllDatabases -and !$Database) {
            Stop-Function -Message "You must specify at least one database. Use -Database or -AllDatabases." -ErrorRecord $_
            return
        }

        $sourceserver = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $sqlCredential -ParameterConnection

        if (-not $destination) {
            $destination = $sqlinstance
            $DestinationCredential = $SqlCredential
        }

        if ($sqlinstance -ne $destination) {

            $destserver = Connect-SqlInstance -SqlInstance $destination -SqlCredential $DestinationCredential

            $sourcenb = $instance.ComputerName
            $destnb = $instance.ComputerName

            if ($BackupFolder.StartsWith("\\") -eq $false -and $sourcenb -ne $destnb) {
                Stop-Function -Message "Backup folder must be a network share if the source and destination servers are not the same." -ErrorRecord $_ -Target $backupFolder
                return
            }
        } else {
            $destserver = $sourceserver
        }

        $source = $sourceserver.DomainInstanceName
        $destination = $destserver.DomainInstanceName

        if (!$jobowner) {
            $jobowner = Get-SqlSaLogin $destserver
        }

        if ($alldatabases -or !$Database) {
            $database = ($sourceserver.databases | Where-Object { $_.IsSystemObject -eq $false -and ($_.Status -match 'Offline') -eq $false }).Name
        }

        if (!(Test-DbaPath -SqlInstance $destserver -Path $backupFolder)) {
            $serviceaccount = $destserver.ServiceAccount
            Stop-Function -Message "Can't access $backupFolder Please check if $serviceaccount has permissions." -ErrorRecord $_ -Target $backupFolder
        }

        $jobname = "Rationalised Final Database Restore for $dbname"
        $jobStepName = "Restore the $dbname database from Final Backup"

        if (!($destserver.Logins | Where-Object { $_.Name -eq $jobowner })) {
            Stop-Function -Message "$destination does not contain the login $jobowner - Please fix and try again - Aborting." -ErrorRecord $_ -Target $jobowner
        }

        function Start-SqlAgent {
            <#
                .SYNOPSIS
            #>
            [CmdletBinding(SupportsShouldProcess)]
            param ()
            if ($destserver.VersionMajor -eq 8) {
                $serviceName = 'MSSQLSERVER'
            } else {
                $instance = $destserver.InstanceName
                if ($instance.length -eq 0) { $instance = "MSSQLSERVER" }
                $serviceName = "SQL Server Agent ($instance)"
            }

            if ($Pscmdlet.ShouldProcess($destination, "Starting Sql Agent")) {
                try {
                    $ipaddr = Resolve-SqlIpAddress $destserver
                    $agentservice = Get-Service -ComputerName $ipaddr -DisplayName $serviceName

                    if ($agentservice.Status -ne 'Running') {
                        $agentservice.Start()
                        $timeout = New-Timespan -seconds 60
                        $sw = [diagnostics.stopwatch]::StartNew()
                        $agentstatus = (Get-Service -ComputerName $ipaddr -DisplayName $serviceName).Status
                        while ($AgentStatus -ne 'Running' -and $sw.elapsed -lt $timeout) {
                            $agentStatus = (Get-Service -ComputerName $ipaddr -DisplayName $serviceName).Status
                        }
                    }
                }

                catch {
                    throw $_
                }

                if ($agentservice.Status -ne 'Running') {
                    throw "Cannot start Agent Service on $destination - Aborting."
                }
            }
        }

        function Start-DbccCheck {
            <#
            .SYNOPSIS

            #>

            [CmdletBinding(SupportsShouldProcess)]
            param (
                [object]$server,
                [string]$dbname
            )

            $servername = $server.name
            $db = $server.databases[$dbname]

            if ($Pscmdlet.ShouldProcess($sourceserver, "Running dbcc check on $dbname on $servername")) {
                try {
                    $null = $db.CheckTables('None')
                    Write-Message -Level Verbose -Message "DBCC CHECKDB finished successfully for $dbname on $servername."
                }

                catch {
                    Write-Message -Level Warning -Message "DBCC CHECKDB failed."
                    Stop-Function -Message "Error occured: $_" -Target $agentservice -ErrorRecord $_ -Continue

                    if ($force) {
                        return $true
                    } else {
                        return $false
                    }
                }
            }
        }

        function New-SqlAgentJobCategory {
            <#
                .SYNOPSIS

            #>
            [CmdletBinding(SupportsShouldProcess)]
            param ([string]$categoryname,
                [object]$jobServer)

            if (!$jobServer.JobCategories[$categoryname]) {
                if ($Pscmdlet.ShouldProcess($sourceserver, "Running dbcc check on $dbname on $sourceserver")) {
                    try {
                        Write-Message -Level Verbose -Message "Creating Agent Job Category $categoryname."
                        $category = New-Object Microsoft.SqlServer.Management.Smo.Agent.JobCategory
                        $category.Parent = $jobServer
                        $category.Name = $categoryname
                        $category.Create()
                        Write-Message -Level Verbose -Message "Created Agent Job Category $categoryname."
                    } catch {
                        Stop-Function -Message "FAILED : To Create Agent Job Category - $categoryname - Aborting." -Target $categoryname -ErrorRecord $_
                        return
                    }
                }
            }
        }

        function Restore-Database {
            <#
                .SYNOPSIS
                    Internal function. Restores .bak file to Sql database. Creates db if it doesn't exist. $filestructure is
                a custom object that contains logical and physical file locations.
            #>

            param (
                [Parameter(Mandatory)]
                [Alias('ServerInstance', 'SqlInstance', 'SqlServer')]
                [object]$server,
                [Parameter(Mandatory)]
                [ValidateNotNullOrEmpty()]
                [string]$dbname,
                [Parameter(Mandatory)]
                [string]$backupfile,
                [string]$filetype = 'Database',
                [Parameter(Mandatory)]
                [object]$filestructure,
                [switch]$norecovery,
                [PSCredential]$sqlCredential,
                [switch]$TSql = $false
            )

            $server = Connect-SqlInstance -SqlInstance $server -SqlCredential $sqlCredential
            $servername = $server.name
            $server.ConnectionContext.StatementTimeout = 0
            $restore = New-Object 'Microsoft.SqlServer.Management.Smo.Restore'
            $restore.ReplaceDatabase = $true

            foreach ($file in $filestructure.values) {
                $movefile = New-Object 'Microsoft.SqlServer.Management.Smo.RelocateFile'
                $movefile.LogicalFileName = $file.logical
                $movefile.PhysicalFileName = $file.physical
                $null = $restore.RelocateFiles.Add($movefile)
            }

            try {
                if ($TSql) {
                    $restore.PercentCompleteNotification = 1
                    $restore.add_Complete($complete)
                    $restore.ReplaceDatabase = $true
                    $restore.Database = $dbname
                    $restore.Action = $filetype
                    $restore.NoRecovery = $norecovery
                    $device = New-Object -TypeName Microsoft.SqlServer.Management.Smo.BackupDeviceItem
                    $device.name = $backupfile
                    $device.devicetype = 'File'
                    $restore.Devices.Add($device)
                    $restorescript = $restore.script($server)
                    return $restorescript
                } else {
                    $percent = [Microsoft.SqlServer.Management.Smo.PercentCompleteEventHandler] {
                        Write-Progress -id 1 -activity "Restoring $dbname to $servername" -percentcomplete $_.Percent -status ([System.String]::Format("Progress: {0} %", $_.Percent))
                    }
                    $restore.add_PercentComplete($percent)
                    $restore.PercentCompleteNotification = 1
                    $restore.add_Complete($complete)
                    $restore.ReplaceDatabase = $true
                    $restore.Database = $dbname
                    $restore.Action = $filetype
                    $restore.NoRecovery = $norecovery
                    $device = New-Object -TypeName Microsoft.SqlServer.Management.Smo.BackupDeviceItem
                    $device.name = $backupfile
                    $device.devicetype = 'File'
                    $restore.Devices.Add($device)

                    Write-Progress -id 1 -activity "Restoring $dbname to $servername" -percentcomplete 0 -status ([System.String]::Format("Progress: {0} %", 0))
                    $restore.sqlrestore($server)
                    Write-Progress -id 1 -activity "Restoring $dbname to $servername" -status 'Complete' -Completed

                    return $true
                }
            } catch {
                Stop-Function -Message "Restore failed" -ErrorRecord $_ -Target $dbname
                return $false
            }
        }

    }
    process {
        if (Test-FunctionInterrupt) {
            return
        }
        try {
            Start-SqlAgent
        } catch {
            Stop-Function -Message "Failure starting SQL Agent" -ErrorRecord $_
            return
        }

        $start = Get-Date
        Write-Message -Level Verbose -Message "Starting Rationalisation Script at $start."

        foreach ($dbname in $Database) {

            $db = $sourceserver.databases[$dbname]

            # The db check is needed when the number of databases exceeds 255, then it's no longer auto-populated
            if (!$db) {
                Stop-Function -Message "$dbname does not exist on $source. Aborting routine for this database." -Continue
            }

            $lastFullBckDuration = (Get-DbaBackupHistory -SqlInstance $sourceserver -Database $dbname -LastFull).Duration

            if (-NOT ([string]::IsNullOrEmpty($lastFullBckDuration))) {
                $lastFullBckDurationSec = $lastFullBckDuration.TotalSeconds
                $lastFullBckDurationMin = [Math]::Round($lastFullBckDuration.TotalMinutes, 2)

                Write-Message -Level Verbose -Message "From the backup history the last full backup took $lastFullBckDurationSec seconds ($lastFullBckDurationMin minutes)"
                if ($lastFullBckDurationSec -gt 600) {
                    Write-Message -Level Verbose -Message "Last full backup took more than 10 minutes. Do you want to continue?"

                    # Set up the parts for the user choice
                    $Title = "Backup duration"
                    $Info = "Last full backup took more than $lastFullBckDurationMin minutes. Do you want to continue?"

                    $Options = [System.Management.Automation.Host.ChoiceDescription[]] @("&Yes", "&No (Skip)")
                    [int]$Defaultchoice = 0
                    $choice = $host.UI.PromptForChoice($Title, $Info, $Options, $Defaultchoice)
                    # Check the given option
                    if ($choice -eq 1) {
                        Stop-Function -Message "You have chosen skipping the database $dbname because of last known backup time ($lastFullBckDurationMin minutes)." -ErrorRecord $_ -Target $dbname -Continue
                        Continue
                    }
                }
            } else {
                Write-Message -Level Verbose -Message "Couldn't find last full backup time for database $dbname using Get-DbaBackupHistory."
            }

            $jobname = "Rationalised Database Restore Script for $dbname"
            $jobStepName = "Restore the $dbname database from Final Backup"
            $jobServer = $destserver.JobServer

            if ($jobServer.Jobs[$jobname].count -gt 0) {
                if ($force -eq $false) {
                    Stop-Function -Message "FAILED: The Job $jobname already exists. Have you done this before? Rename the existing job and try again or use -Force to drop and recreate." -Continue
                } else {
                    if ($Pscmdlet.ShouldProcess($dbname, "Dropping $jobname on $source")) {
                        Write-Message -Level Verbose -Message "Dropping $jobname on $source."
                        $jobServer.Jobs[$jobname].Drop()
                        $jobServer.Jobs.Refresh()
                    }
                }
            }


            Write-Message -Level Verbose -Message "Starting Rationalisation of $dbname."
            ## if we want to Dbcc before to abort if we have a corrupt database to start with
            if ($NoDbccCheckDb -eq $false) {
                if ($Pscmdlet.ShouldProcess($dbname, "Running dbcc check on $dbname on $source")) {
                    Write-Message -Level Verbose -Message "Starting DBCC CHECKDB for $dbname on $source."
                    $dbccgood = Start-DbccCheck -Server $sourceserver -DBName $dbname

                    if ($dbccgood -eq $false) {
                        if ($force -eq $false) {
                            Write-Message -Level Verbose -Message "DBCC failed for $dbname (you should check that).  Aborting routine for this database."
                            continue
                        } else {
                            Write-Message -Level Verbose -Message "DBCC failed, but Force specified. Continuing."
                        }
                    }
                }
            }

            if ($Pscmdlet.ShouldProcess($source, "Backing up $dbname")) {
                Write-Message -Level Verbose -Message "Starting Backup for $dbname on $source."
                ## Take a Backup
                try {
                    $timenow = [DateTime]::Now.ToString('yyyyMMdd_HHmmss')
                    $backup = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Backup
                    $backup.Action = [Microsoft.SqlServer.Management.SMO.BackupActionType]::Database
                    $backup.BackupSetDescription = "Final Full Backup of $dbname Prior to Dropping"
                    $backup.Database = $dbname
                    $backup.Checksum = $True
                    if ($sourceserver.versionMajor -gt 9) {
                        $backup.CompressionOption = $BackupCompression
                    }
                    if ($force -and $dbccgood -eq $false) {

                        $filename = "$backupFolder\$($dbname)_DBCCERROR_$timenow.bak"
                    } else {
                        $filename = "$backupFolder\$($dbname)_Final_Before_Drop_$timenow.bak"
                    }

                    $devicetype = [Microsoft.SqlServer.Management.Smo.DeviceType]::File
                    $backupDevice = New-Object -TypeName Microsoft.SqlServer.Management.Smo.BackupDeviceItem($filename, $devicetype)

                    $backup.Devices.Add($backupDevice)
                    #Progress
                    $percent = [Microsoft.SqlServer.Management.Smo.PercentCompleteEventHandler] {
                        Write-Progress -id 1 -activity "Backing up database $dbname on $source to $filename" -percentcomplete $_.Percent -status ([System.String]::Format("Progress: {0} %", $_.Percent))
                    }
                    $backup.add_PercentComplete($percent)
                    $backup.add_Complete($complete)
                    Write-Progress -id 1 -activity "Backing up database $dbname on $source to $filename" -percentcomplete 0 -status ([System.String]::Format("Progress: {0} %", 0))
                    $backup.SqlBackup($sourceserver)
                    $null = $backup.Devices.Remove($backupDevice)
                    Write-Progress -id 1 -activity "Backing up database $dbname  on $source to $filename" -status "Complete" -Completed
                    Write-Message -Level Verbose -Message "Backup Completed for $dbname on $source."

                    Write-Message -Level Verbose -Message "Running Restore Verify only on Backup of $dbname on $source."
                    try {
                        $restoreverify = New-Object 'Microsoft.SqlServer.Management.Smo.Restore'
                        $restoreverify.Database = $dbname
                        $restoreverify.Devices.AddDevice($filename, $devicetype)
                        $result = $restoreverify.SqlVerify($sourceserver)

                        if ($result -eq $false) {
                            Write-Message -Level Warning -Message "FAILED : Restore Verify Only failed for $filename on $server - aborting routine for this database."
                            continue
                        }

                        Write-Message -Level Verbose -Message "Restore Verify Only for $filename succeeded."
                    } catch {
                        Stop-Function -Message "FAILED : Restore Verify Only failed for $filename on $server - aborting routine for this database. Exception: $_" -Target $filename -ErrorRecord $_ -Continue
                    }
                } catch {
                    Stop-Function -Message "FAILED : Restore Verify Only failed for $filename on $server - aborting routine for this database. Exception: $_" -Target $filename -ErrorRecord $_ -Continue
                }
            }

            if ($Pscmdlet.ShouldProcess($destination, "Creating Automated Restore Job from Golden Backup for $dbname on $destination")) {
                Write-Message -Level Verbose -Message "Creating Automated Restore Job from Golden Backup for $dbname on $destination."
                try {
                    if ($force -eq $true -and $dbccgood -eq $false) {
                        $jobName = $jobname -replace "Rationalised", "DBCC ERROR"
                    }

                    ## Create an agent job to restore the database
                    $job = New-Object Microsoft.SqlServer.Management.Smo.Agent.Job $jobServer, $jobname
                    $job.Name = $jobname
                    $job.OwnerLoginName = $jobowner
                    $job.Description = "This job will restore the $dbname database using the final backup located at $filename."

                    ## Create a Job Category
                    if (!$jobServer.JobCategories[$categoryname]) {
                        New-SqlAgentJobCategory -JobServer $jobServer -categoryname $categoryname
                    }

                    $job.Category = $categoryname
                    try {
                        if ($Pscmdlet.ShouldProcess($destination, "Creating Agent Job on $destination")) {
                            Write-Message -Level Verbose -Message "Created Agent Job $jobname on $destination."
                            $job.Create()
                        }
                    } catch {
                        Stop-Function -Message "FAILED : To Create Agent Job $jobname on $destination - aborting routine for this database." -Target $categoryname -ErrorRecord $_ -Continue
                    }

                    ## Create Job Step
                    ## Aaron's Suggestion: In the restore script, add a comment block that tells the last known size of each file in the database.
                    ## Suggestion check for disk space before restore
                    ## Create Restore Script
                    try {
                        $restore = New-Object Microsoft.SqlServer.Management.Smo.Restore
                        $device = New-Object -TypeName Microsoft.SqlServer.Management.Smo.BackupDeviceItem $filename, 'FILE'
                        $restore.Devices.Add($device)
                        try {
                            $filelist = $restore.ReadFileList($destserver)
                        }

                        catch {
                            throw 'File list could not be determined. This is likely due to connectivity issues or tiemouts with the Sql Server, the database version is incorrect, or the Sql Server service account does not have access to the file share. Script terminating.'
                        }

                        $filestructure = Get-OfflineSqlFileStructure $destserver $dbname $filelist $ReuseSourceFolderStructure

                        $jobStepCommand = Restore-Database $destserver $dbname $filename "Database" $filestructure -TSql -ErrorAction Stop
                        $jobStep = new-object Microsoft.SqlServer.Management.Smo.Agent.JobStep $job, $jobStepName
                        $jobStep.SubSystem = 'TransactSql' # 'PowerShell'
                        $jobStep.DatabaseName = 'master'
                        $jobStep.Command = $jobStepCommand
                        $jobStep.OnSuccessAction = 'QuitWithSuccess'
                        $jobStep.OnFailAction = 'QuitWithFailure'
                        if ($Pscmdlet.ShouldProcess($destination, "Creating Agent JobStep on $destination")) {
                            $null = $jobStep.Create()
                        }
                        $jobStartStepid = $jobStep.ID
                        Write-Message -Level Verbose -Message "Created Agent JobStep $jobStepName on $destination."
                    } catch {
                        Stop-Function -Message "FAILED : To Create Agent JobStep $jobStepName on $destination - Aborting." -Target $jobStepName -ErrorRecord $_ -Continue
                    }
                    if ($Pscmdlet.ShouldProcess($destination, "Applying Agent Job $jobname to $destination")) {
                        $job.ApplyToTargetServer($destination)
                        $job.StartStepID = $jobStartStepid
                        $job.Alter()
                    }
                } catch {
                    Stop-Function -Message "FAILED : To Create Agent Job $jobname on $destination - aborting routine for $dbname. Exception: $_" -Target $jobname -ErrorRecord $_ -Continue
                }
            }

            if ($Pscmdlet.ShouldProcess($destination, "Dropping Database $dbname on $sourceserver")) {
                ## Drop the database
                try {
                    $null = Remove-DbaDatabase -SqlInstance $sourceserver -Database $dbname -Confirm:$false
                    Write-Message -Level Verbose -Message "Dropped $dbname Database on $source prior to running the Agent Job"
                } catch {
                    Stop-Function -Message "FAILED : To Drop database $dbname on $server - aborting routine for $dbname. Exception: $_" -Continue
                }
            }

            if ($Pscmdlet.ShouldProcess($destination, "Running Agent Job on $destination to restore $dbname")) {
                ## Run the restore job to restore it
                Write-Message -Level Verbose -Message "Starting $jobname on $destination."
                try {
                    $job = $destserver.JobServer.Jobs[$jobname]
                    $job.Start()
                    $job.Refresh()
                    $status = $job.CurrentRunStatus

                    while ($status -ne 'Idle') {
                        Write-Message -Level Verbose -Message "Restore Job for $dbname on $destination is $status."
                        Start-Sleep -Seconds 15
                        $job.Refresh()
                        $status = $job.CurrentRunStatus
                    }

                    Write-Message -Level Verbose -Message "Restore Job $jobname has completed on $destination."
                    Write-Message -Level Verbose -Message "Sleeping for a few seconds to ensure the next step (DBCC) succeeds."
                    Start-Sleep -Seconds 10 ## This is required to ensure the next DBCC Check succeeds
                } catch {
                    Stop-Function -Message "FAILED : Restore Job $jobname failed on $destination - aborting routine for $dbname. Exception: $_" -Continue
                }

                if ($job.LastRunOutcome -ne 'Succeeded') {
                    # LOL, love the plug.
                    Write-Message -Level Warning -Message "FAILED : Restore Job $jobname failed on $destination - aborting routine for $dbname."
                    Write-Message -Level Warning -Message "Check the Agent Job History on $destination - if you have SSMS2016 July release or later."
                    Write-Message -Level Warning -Message "Get-SqlAgentJobHistory -JobName '$jobname' -ServerInstance $destination -OutcomesType Failed."
                    continue
                }
            }

            $refreshRetries = 1

            while ($null -eq ($destserver.databases[$dbname]) -and $refreshRetries -lt 6) {
                Write-Message -Level verbose -Message "Database $dbname not found! Refreshing collection."

                #refresh database list, otherwise the next step (DBCC) can fail
                $destserver.Databases.Refresh()

                Start-Sleep -Seconds 1

                $refreshRetries += 1
            }


            ## Run a Dbcc No choice here
            if ($Pscmdlet.ShouldProcess($dbname, "Running Dbcc CHECKDB on $dbname on $destination")) {
                Write-Message -Level Verbose -Message "Starting Dbcc CHECKDB for $dbname on $destination."
                $null = Start-DbccCheck -Server $destserver -DbName $dbname
            }

            if ($Pscmdlet.ShouldProcess($dbname, "Dropping Database $dbname on $destination")) {
                ## Drop the database
                try {
                    $null = Remove-DbaDatabase -SqlInstance $sourceserver -Database $dbname -Confirm:$false
                    Write-Message -Level Verbose -Message "Dropped $dbname database on $destination."
                } catch {
                    Stop-Function -Message "FAILED : To Drop database $dbname on $destination - Aborting. Exception: $_" -Target $dbname -ErrorRecord $_ -Continue
                }
            }
            Write-Message -Level Verbose -Message "Rationalisation Finished for $dbname."

            [PSCustomObject]@{
                SqlInstance     = $source
                DatabaseName    = $dbname
                JobName         = $jobname
                TestingInstance = $destination
                BackupFolder    = $backupFolder
            }
        }
    }

    end {
        if (Test-FunctionInterrupt) {
            return
        }
        if ($Pscmdlet.ShouldProcess("console", "Showing final message")) {
            $End = Get-Date
            Write-Message -Level Verbose -Message "Finished at $End."
            $Duration = $End - $start
            Write-Message -Level Verbose -Message "Script Duration: $Duration."
        }

        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Remove-SqlDatabaseSafely
    }
}
tools\dbatools\functions\Remove-DbaDbBackupRestoreHistory.ps1
function Remove-DbaDbBackupRestoreHistory {
    <#
    .SYNOPSIS
        Reduces the size of the backup and restore history tables by deleting old entries for backup sets.

    .DESCRIPTION
        Reduces the size of the backup and restore history tables by deleting the entries for backup sets.

        Can be used at server level, in this case a retention period -KeepDays can be set (default is 30 days).
        Can also be used at database level, in this case the complete history for the database(s) is deleted.

        The backup and restore history tables reside in the msdb database.

        To periodically remove old data from backup and restore history tables it is recommended to schedule the agent job sp_delete_backuphistory from the
        SQL Server Maintenance Solution created by Ola Hallengren (https://ola.hallengren.com).

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER KeepDays
        The number of days of history to keep. Defaults to 30 days.

    .PARAMETER Database
        The database(s) to process. If unspecified, all databases will be processed.

    .PARAMETER InputObject
        Enables piped input from Get-DbaDatabase

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Delete
        Author: IJeb Reitsma

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaDbBackupRestoreHistory

    .EXAMPLE
        PS C:\> Remove-DbaDbBackupRestoreHistory -SqlInstance sql2016

        Prompts for confirmation then deletes backup and restore history on SQL Server sql2016 older than 30 days (default period)

        PS C:\> Remove-DbaDbBackupRestoreHistory -SqlInstance sql2016 -KeepDays 100 -Confirm:$false

        Remove backup and restore history on SQL Server sql2016 older than 100 days. Does not prompt for confirmation.

        PS C:\> Remove-DbaDbBackupRestoreHistory -SqlInstance sql2016 -Database db1

        Prompts for confirmation then deletes all backup and restore history for database db1 on SQL Server sql2016

        PS C:\> Get-DbaDatabase -SqlInstance sql2016 | Remove-DbaDbBackupRestoreHistory -WhatIf

        Remove complete backup and restore history for all databases on SQL Server sql2016
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [int]$KeepDays,
        [string[]]$Database,
        [Parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )

    begin {
        if (-not $KeepDays -and -not $Database) {
            $KeepDays = 30
        }
        $odt = (Get-Date).AddDays(-$KeepDays)
    }

    process {
        if ($KeepDays -and $Database) {
            Stop-Function -Message "KeepDays cannot be used with Database. When Database is specified, all backup/restore history for that database is deleted."
            return
        }
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            if (-not $Database) {
                try {
                    if ($Pscmdlet.ShouldProcess($server, "Remove backup/restore history before $($odt) for all databases")) {
                        # While this method is named DeleteBackupHistory, it also removes restore history
                        $server.DeleteBackupHistory($odt)
                        $server.Refresh()
                    }
                } catch {
                    Stop-Function -Message "Could not remove backup/restore history on $server" -Continue
                }
            } else {
                $InputObject += $server.Databases | Where-Object { $_.Name -in $Database }
            }
        }

        foreach ($db in $InputObject) {
            try {
                $servername = $db.Parent.Name
                if ($Pscmdlet.ShouldProcess("$db on $servername", "Remove complete backup/restore history")) {
                    # While this method is named DeleteBackupHistory, it also removes restore history
                    $db.DropBackupHistory()
                    $db.Refresh()
                }
            } catch {
                Stop-Function -Message "Could not remove backup/restore history for database $db on $servername" -Continue
            }
        }
    }
}
tools\dbatools\functions\Remove-DbaDbCertificate.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaDbCertificate {
    <#
    .SYNOPSIS
        Deletes specified database certificate

    .DESCRIPTION
        Deletes specified database certificate

    .PARAMETER SqlInstance
        The SQL Server to create the certificates on.

    .PARAMETER SqlCredential
        Allows you to login to SQL Server using alternative credentials.

    .PARAMETER Database
        The database where the certificate will be removed.

    .PARAMETER Certificate
        The certificate that will be removed

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER InputObject
        Piped certificate objects

    .NOTES
        Tags: Certificate
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Remove-DbaDbCertificate -SqlInstance Server1

        The certificate in the master database on server1 will be removed if it exists.

    .EXAMPLE
        PS C:\> Remove-DbaDbCertificate -SqlInstance Server1 -Database db1 -Confirm:$false

        Suppresses all prompts to remove the certificate in the 'db1' database and drops the key.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess, ConfirmImpact = "High")]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [string[]]$Certificate,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Certificate[]]$InputObject,
        [switch]$EnableException
    )
    begin {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Remove-DbaDatabaseCertificate
    }
    process {
        if ($SqlInstance) {
            $InputObject += Get-DbaDbCertificate -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Certificate $Certificate -Database $Database
        }
        foreach ($cert in $InputObject) {
            $db = $cert.Parent
            $server = $db.Parent

            if ($Pscmdlet.ShouldProcess($server.Name, "Dropping the certificate named $cert for database $db")) {
                try {
                    # erroractionprefs are not invoked for .net methods suddenly (??), so use Invoke-DbaQuery
                    # Avoids modifying the collection
                    Invoke-DbaQuery -SqlInstance $server -Database $db.Name -Query "DROP CERTIFICATE $cert" -EnableException
                    Write-Message -Level Verbose -Message "Successfully removed certificate named $cert from the $db database on $server"
                    [pscustomobject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Database     = $db.Name
                        Certificate  = $cert.Name
                        Status       = "Success"
                    }
                } catch {
                    Stop-Function -Message "Failed to drop certificate named $($cert.Name) from $($db.Name) on $($server.Name)." -Target $smocert -ErrorRecord $_ -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Remove-DbaDbMasterKey.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaDbMasterKey {
    <#
    .SYNOPSIS
        Deletes specified database master key

    .DESCRIPTION
        Deletes specified database master key

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Allows you to login to SQL Server using alternative credentials

    .PARAMETER Database
        The database where the master key will be removed.

    .PARAMETER ExcludeDatabase
        List of databases to exclude from clearing all master keys

    .PARAMETER All
        Purge the master keys from all databases on an instance

    .PARAMETER InputObject
        Enables pipeline input from Get-DbaDatabase

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .NOTES
        Tags: Certificate, Masterkey
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaMasterKey

    .EXAMPLE
        PS C:\> Remove-DbaDbMasterKey -SqlInstance sql2017, sql2016 -Database pubs

        The master key in the pubs database on sql2017 and sql2016 will be removed if it exists.

    .EXAMPLE
        PS C:\> Remove-DbaDbMasterKey -SqlInstance sql2017 -Database db1 -Confirm:$false

        Suppresses all prompts to remove the master key in the 'db1' database and drops the key.

    .EXAMPLE
        PS C:\> Get-DbaDbMasterKey -SqlInstance sql2017 -Database db1 | Remove-DbaDbMasterKey -Confirm:$false

        Suppresses all prompts to remove the master key in the 'db1' database and drops the key.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess, ConfirmImpact = "High")]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [System.Management.Automation.PSCredential]$SqlCredential,
        [string[]]$Database,
        [string[]]$ExcludeDatabase,
        [switch]$All,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.MasterKey[]]$InputObject,
        [switch]$EnableException
    )

    process {
        if ($SqlInstance) {
            if (-not $Database -and -not $ExcludeDatabase -and -not $All) {
                Stop-Function -Message "You must specify Database, ExcludeDatabase or All when using SqlInstance"
                return
            }
            # all does not need to be addressed in the code because it gets all the dbs if $databases is empty
            $databases = Get-DbaDatabase -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase
            if ($databases) {
                foreach ($key in $databases.MasterKey) {
                    $InputObject += $key
                }
            }
        }

        foreach ($masterkey in $InputObject) {
            $server = $masterkey.Parent.Parent
            $db = $masterkey.Parent
            if ($Pscmdlet.ShouldProcess($server.Name, "Removing master key on $($db.Name)")) {
                # avoid enumeration issues
                try {
                    $masterkey.Parent.Query("DROP MASTER KEY")
                    [pscustomobject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Database     = $db.Name
                        Status       = "Master key removed"
                    }
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Remove-DbaDbMirror.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaDbMirror {
    <#
    .SYNOPSIS
        Removes database mirrors.

    .DESCRIPTION
        Removes database mirrors. Does not set databases in recovery to recovered.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function
        to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The target database.

    .PARAMETER Partner
        The partner fqdn.

    .PARAMETER Witness
        The witness fqdn.

    .PARAMETER InputObject
        Allows piping from Get-DbaDatabase.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Mirror, HA
        Author: Chrissy LeMaire (@cl), netnerds.net
        dbatools PowerShell module (https://dbatools.io, [email protected])
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaDbMirror

    .EXAMPLE
        PS C:\> Set-DbaDbMirror -SqlInstance localhost

        Returns all Endpoint(s) on the local default SQL Server instance

    .EXAMPLE
        PS C:\> Set-DbaDbMirror -SqlInstance localhost, sql2016

        Returns all Endpoint(s) for the local and sql2016 SQL Server instances

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ((Test-Bound -ParameterName SqlInstance) -and (Test-Bound -Not -ParameterName Database)) {
            Stop-Function -Message "Database is required when SqlInstance is specified"
            return
        }
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $instance -SqlCredential $SqlCredential -Database $Database
        }

        foreach ($db in $InputObject) {
            if ($Pscmdlet.ShouldProcess($db.Parent.Name, "Turning off mirror for $db")) {
                # use t-sql cuz $db.Alter() doesnt always work against restoring dbs
                try {
                    try {
                        $db.ChangeMirroringState([Microsoft.SqlServer.Management.Smo.MirroringOption]::Off)
                        $db.Alter()
                    } catch {
                        try {
                            $db.Parent.Query("ALTER DATABASE $db SET PARTNER OFF")
                        } catch {
                            Stop-Function -Message "Failure on $($db.Parent) for $db" -ErrorRecord $_ -Continue
                        }
                    }
                    [pscustomobject]@{
                        ComputerName = $db.ComputerName
                        InstanceName = $db.InstanceName
                        SqlInstance  = $db.SqlInstance
                        Database     = $db.Name
                        Status       = "Removed"
                    }
                } catch {
                    Stop-Function -Message "Failure on $($db.Parent.Name)" -ErrorRecord $_
                }
            }
        }
    }
}
tools\dbatools\functions\Remove-DbaDbMirrorMonitor.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaDbMirrorMonitor {
    <#
    .SYNOPSIS
        Stops and deletes the mirroring monitor job for all the databases on the server instance.

    .DESCRIPTION
        Stops and deletes the mirroring monitor job for all the databases on the server instance.

        Basically executes sp_dbmmonitordropmonitoring.

    .PARAMETER SqlInstance
        The target SQL Server instance

    .PARAMETER SqlCredential
        Login to the target instance using alternate Windows or SQL Login Authentication. Accepts credential objects (Get-Credential).

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Mirror, HA, Monitor
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaDbMirrorMonitor

    .EXAMPLE
        PS C:\> Remove-DbaDbMirrorMonitor -SqlInstance sql2008, sql2012

        Stops and deletes the mirroring monitor job for all the databases on sql2008 and sql2012.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            if ($Pscmdlet.ShouldProcess($instance, "Removing mirror monitoring")) {
                try {
                    $server.Query("msdb.dbo.sp_dbmmonitordropmonitoring")
                    [pscustomobject]@{
                        ComputerName  = $server.ComputerName
                        InstanceName  = $server.ServiceName
                        SqlInstance   = $server.DomainInstanceName
                        MonitorStatus = "Removed"
                    }
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Remove-DbaDbOrphanUser.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaDbOrphanUser {
    <#
    .SYNOPSIS
        Drop orphan users with no existing login to map

    .DESCRIPTION
        An orphan user is defined by a user that does not have their matching login. (Login property = "").

        If user is the owner of the schema with the same name and if if the schema does not have any underlying objects the schema will be dropped.

        If user owns more than one schema, the owner of the schemas that does not have the same name as the user, will be changed to 'dbo'. If schemas have underlying objects, you must specify the -Force parameter so the user can be dropped.

        If exists a login to map the drop will not be performed unless you specify the -Force parameter (only when calling from Repair-DbaDbOrphanUser.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server

    .PARAMETER User
        Specifies the list of users to remove.

    .PARAMETER Force
        If this switch is enabled:
        If exists any schema which owner is the User, this will force the change of the owner to 'dbo'.
        If exists a login to map the drop will not be performed unless you specify this parameter.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Orphan, Database, Security, Login
        Author: Claudio Silva (@ClaudioESSilva) | Simone Bizzotto (@niphlod)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaDbOrphanUser

    .EXAMPLE
        PS C:\> Remove-DbaDbOrphanUser -SqlInstance sql2005

        Finds and drops all orphan users without matching Logins in all databases present on server 'sql2005'.

    .EXAMPLE
        PS C:\> Remove-DbaDbOrphanUser -SqlInstance sqlserver2014a -SqlCredential $cred

        Finds and drops all orphan users without matching Logins in all databases present on server 'sqlserver2014a'. SQL Server authentication will be used in connecting to the server.

    .EXAMPLE
        PS C:\> Remove-DbaDbOrphanUser -SqlInstance sqlserver2014a -Database db1, db2 -Force

        Finds and drops orphan users even if they have a matching Login on both db1 and db2 databases.

    .EXAMPLE
        PS C:\> Remove-DbaDbOrphanUser -SqlInstance sqlserver2014a -ExcludeDatabase db1, db2 -Force

        Finds and drops orphan users even if they have a matching Login from all databases except db1 and db2.

    .EXAMPLE
        PS C:\> Remove-DbaDbOrphanUser -SqlInstance sqlserver2014a -User OrphanUser

        Removes user OrphanUser from all databases only if there is no matching login.

    .EXAMPLE
        PS C:\> Remove-DbaDbOrphanUser -SqlInstance sqlserver2014a -User OrphanUser -Force

        Removes user OrphanUser from all databases even if they have a matching Login. Any schema that the user owns will change ownership to dbo.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]
        $SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [parameter(ValueFromPipeline)]
        [object[]]$User,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($Instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $Instance -SqlCredential $SqlCredential
            } catch {
                Write-Message -Level Warning -Message "Can't connect to $Instance or access denied. Skipping."
                continue
            }

            $DatabaseCollection = $server.Databases | Where-Object IsAccessible

            if ($Database) {
                $DatabaseCollection = $DatabaseCollection | Where-Object Name -In $Database
            }
            if ($ExcludeDatabase) {
                $DatabaseCollection = $DatabaseCollection | Where-Object Name -NotIn $ExcludeDatabase
            }

            $CallStack = Get-PSCallStack | Select-Object -Property *
            if ($CallStack.Count -eq 1) {
                $StackSource = $CallStack[0].Command
            } else {
                #-2 because index base is 0 and we want the one before the last (the last is the actual command)
                $StackSource = $CallStack[($CallStack.Count - 2)].Command
            }

            if ($DatabaseCollection) {
                foreach ($db in $DatabaseCollection) {
                    try {
                        #if SQL 2012 or higher only validate databases with ContainmentType = NONE
                        if ($server.versionMajor -gt 10) {
                            if ($db.ContainmentType -ne [Microsoft.SqlServer.Management.Smo.ContainmentType]::None) {
                                Write-Message -Level Warning -Message "Database '$db' is a contained database. Contained databases can't have orphaned users. Skipping validation."
                                Continue
                            }
                        }

                        if ($StackSource -eq "Repair-DbaDbOrphanUser") {
                            Write-Message -Level Verbose -Message "Call origin: Repair-DbaDbOrphanUser."
                            #Will use collection from parameter ($User)
                        } else {
                            Write-Message -Level Verbose -Message "Validating users on database $db."

                            if ($User.Count -eq 0) {
                                #the third validation will remove from list sql users without login  or mapped to certificate. The rule here is Sid with length higher than 16
                                $User = $db.Users | Where-Object { $_.Login -eq "" -and ($_.ID -gt 4) -and (($_.Sid.Length -gt 16 -and $_.LoginType -in @([Microsoft.SqlServer.Management.Smo.LoginType]::SqlLogin, [Microsoft.SqlServer.Management.Smo.LoginType]::Certificate)) -eq $false) }
                            } else {
                                #the fourth validation will remove from list sql users without login or mapped to certificate. The rule here is Sid with length higher than 16
                                $User = $db.Users | Where-Object { $_.Login -eq "" -and ($_.ID -gt 4) -and ($User -contains $_.Name) -and (($_.Sid.Length -gt 16 -and $_.LoginType -in @([Microsoft.SqlServer.Management.Smo.LoginType]::SqlLogin, [Microsoft.SqlServer.Management.Smo.LoginType]::Certificate)) -eq $false) }
                            }
                        }

                        if ($User.Count -gt 0) {
                            Write-Message -Level Verbose -Message "Orphan users found."
                            foreach ($dbuser in $User) {
                                $SkipUser = $false

                                $ExistLogin = $null

                                if ($StackSource -ne "Repair-DbaDbOrphanUser") {
                                    #Need to validate Existing Login because the call does not came from Repair-DbaDbOrphanUser
                                    $ExistLogin = $server.logins | Where-Object {
                                        $_.Isdisabled -eq $False -and
                                        $_.IsSystemObject -eq $False -and
                                        $_.IsLocked -eq $False -and
                                        $_.Name -eq $dbuser.Name
                                    }
                                }

                                #Schemas only appears on SQL Server 2005 (v9.0)
                                if ($server.versionMajor -gt 8) {

                                    #reset variables
                                    $AlterSchemaOwner = ""
                                    $DropSchema = ""

                                    #Validate if user owns any schema
                                    $Schemas = @()
                                    $Schemas = $db.Schemas | Where-Object Owner -eq $dbuser.Name

                                    if (@($Schemas).Count -gt 0) {
                                        Write-Message -Level Verbose -Message "User $dbuser owns one or more schemas."

                                        foreach ($sch in $Schemas) {
                                            <#
                                                On sql server 2008 or lower the EnumObjects method does not accept empty parameter.
                                                0x1FFFFFFF is the way we can say we want everything known by those versions

                                                When it is a higher version we can use empty to get all
                                            #>
                                            if ($server.versionMajor -lt 11) {
                                                $NumberObjects = ($db.EnumObjects(0x1FFFFFFF) | Where-Object { $_.Schema -eq $sch.Name } | Measure-Object).Count
                                            } else {
                                                $NumberObjects = ($db.EnumObjects() | Where-Object { $_.Schema -eq $sch.Name } | Measure-Object).Count
                                            }

                                            if ($NumberObjects -gt 0) {
                                                if ($Force) {
                                                    Write-Message -Level Verbose -Message "Parameter -Force was used! The schema '$($sch.Name)' have $NumberObjects underlying objects. We will change schema owner to 'dbo' and drop the user."

                                                    if ($Pscmdlet.ShouldProcess($db.Name, "Changing schema '$($sch.Name)' owner to 'dbo'. -Force used.")) {
                                                        $AlterSchemaOwner += "ALTER AUTHORIZATION ON SCHEMA::[$($sch.Name)] TO [dbo]`r`n"

                                                        [pscustomobject]@{
                                                            ComputerName      = $server.ComputerName
                                                            InstanceName      = $server.ServiceName
                                                            SqlInstance       = $server.DomainInstanceName
                                                            DatabaseName      = $db.Name
                                                            SchemaName        = $sch.Name
                                                            Action            = "ALTER OWNER"
                                                            SchemaOwnerBefore = $sch.Owner
                                                            SchemaOwnerAfter  = "dbo"
                                                        }
                                                    }
                                                } else {
                                                    Write-Message -Level Warning -Message "Schema '$($sch.Name)' owned by user $($dbuser.Name) have $NumberObjects underlying objects. If you want to change the schemas' owner to 'dbo' and drop the user anyway, use -Force parameter. Skipping user '$dbuser'."
                                                    $SkipUser = $true
                                                    break
                                                }
                                            } else {
                                                if ($sch.Name -eq $dbuser.Name) {
                                                    Write-Message -Level Verbose -Message "The schema '$($sch.Name)' have the same name as user $dbuser. Schema will be dropped."

                                                    if ($Pscmdlet.ShouldProcess($db.Name, "Dropping schema '$($sch.Name)'.")) {
                                                        $DropSchema += "DROP SCHEMA [$($sch.Name)]"

                                                        [pscustomobject]@{
                                                            ComputerName      = $server.ComputerName
                                                            InstanceName      = $server.ServiceName
                                                            SqlInstance       = $server.DomainInstanceName
                                                            DatabaseName      = $db.Name
                                                            SchemaName        = $sch.Name
                                                            Action            = "DROP"
                                                            SchemaOwnerBefore = $sch.Owner
                                                            SchemaOwnerAfter  = "N/A"
                                                        }
                                                    }
                                                } else {
                                                    Write-Message -Level Warning -Message "Schema '$($sch.Name)' does not have any underlying object. Ownership will be changed to 'dbo' so the user can be dropped. Remember to re-check permissions on this schema!"

                                                    if ($Pscmdlet.ShouldProcess($db.Name, "Changing schema '$($sch.Name)' owner to 'dbo'.")) {
                                                        $AlterSchemaOwner += "ALTER AUTHORIZATION ON SCHEMA::[$($sch.Name)] TO [dbo]`r`n"

                                                        [pscustomobject]@{
                                                            ComputerName      = $server.ComputerName
                                                            InstanceName      = $server.ServiceName
                                                            SqlInstance       = $server.DomainInstanceName
                                                            DatabaseName      = $db.Name
                                                            SchemaName        = $sch.Name
                                                            Action            = "ALTER OWNER"
                                                            SchemaOwnerBefore = $sch.Owner
                                                            SchemaOwnerAfter  = "dbo"
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                    } else {
                                        Write-Message -Level Verbose -Message "User $dbuser does not own any schema. Will be dropped."
                                    }

                                    $query = "$AlterSchemaOwner `r`n$DropSchema `r`nDROP USER " + $dbuser

                                    Write-Message -Level Debug -Message $query
                                } else {
                                    $query = "EXEC master.dbo.sp_droplogin @loginame = N'$($dbuser.name)'"
                                }

                                if ($ExistLogin) {
                                    if (-not $SkipUser) {
                                        if ($Force) {
                                            if ($Pscmdlet.ShouldProcess($db.Name, "Dropping user $dbuser using -Force")) {
                                                $server.Databases[$db.Name].ExecuteNonQuery($query) | Out-Null
                                                Write-Message -Level Verbose -Message "User $dbuser was dropped from $($db.Name). -Force parameter was used!"
                                            }
                                        } else {
                                            Write-Message -Level Warning -Message "Orphan user $($dbuser.Name) has a matching login. The user will not be dropped. If you want to drop anyway, use -Force parameter."
                                            Continue
                                        }
                                    }
                                } else {
                                    if (-not $SkipUser) {
                                        if ($Pscmdlet.ShouldProcess($db.Name, "Dropping user $dbuser")) {
                                            $server.Databases[$db.Name].ExecuteNonQuery($query) | Out-Null
                                            Write-Message -Level Verbose -Message "User $dbuser was dropped from $($db.Name)."
                                        }
                                    }
                                }
                            }
                        } else {
                            Write-Message -Level Verbose -Message "No orphan users found on database $db."
                        }
                        #reset collection
                        $User = $null
                    } catch {
                        Stop-Function -Message "Failure" -ErrorRecord $_ -Target $db -Continue
                    }
                }
            } else {
                Write-Message -Level Verbose -Message "There are no databases to analyse."
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Alias Remove-SqlOrphanUser
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Alias Remove-DbaOrphanUser
    }
}
tools\dbatools\functions\Remove-DbaDbSnapshot.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaDbSnapshot {
    <#
    .SYNOPSIS
        Removes database snapshots

    .DESCRIPTION
        Removes (drops) database snapshots from the server

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Credential object used to connect to the SQL Server as a different user

    .PARAMETER Database
        Removes snapshots for only this specific base db

    .PARAMETER ExcludeDatabase
        Removes snapshots excluding this specific base dbs

    .PARAMETER Snapshot
        Restores databases from snapshot with this name only

    .PARAMETER AllSnapshots
        Specifies that you want to remove all snapshots from the server

    .PARAMETER Force
        Will forcibly kill all running queries that prevent the drop process.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run

    .PARAMETER Confirm
        Prompts for confirmation of every step.

    .PARAMETER InputObject
        Enables input from Get-DbaDbSnapshot

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Snapshot, Database
        Author: Simone Bizzotto (@niphold)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaDbSnapshot

    .EXAMPLE
        PS C:\> Remove-DbaDbSnapshot -SqlInstance sql2014 -Snapshot HR_snap_20161201, HR_snap_20161101

        Removes database snapshots named HR_snap_20161201 and HR_snap_20161101

    .EXAMPLE
        PS C:\> Remove-DbaDbSnapshot -SqlInstance sql2014 -Database HR, Accounting

        Removes all database snapshots having HR and Accounting as base dbs

    .EXAMPLE
        PS C:\> Get-DbaDbSnapshot -SqlInstance sql2014 -Database HR, Accounting | Remove-DbaDbSnapshot

        Removes all database snapshots having HR and Accounting as base dbs

    .EXAMPLE
        PS C:\> Remove-DbaDbSnapshot -SqlInstance sql2014 -Snapshot HR_snapshot, Accounting_snapshot

        Removes HR_snapshot and Accounting_snapshot

    .EXAMPLE
        PS C:\> Get-DbaDbSnapshot -SqlInstance sql2016 | Where SnapshotOf -like '*dumpsterfire*' | Remove-DbaDbSnapshot

        Removes all snapshots associated with databases that have dumpsterfire in the name

    .EXAMPLE
        PS C:\> Get-DbaDbSnapshot -SqlInstance sql2016 | Out-GridView -Passthru | Remove-DbaDbSnapshot

        Allows the selection of snapshots on sql2016 to remove

    .EXAMPLE
        PS C:\> Remove-DbaDbSnapshot -SqlInstance sql2014 -AllSnapshots

        Removes all database snapshots from sql2014

    .EXAMPLE
        PS C:\> Remove-DbaDbSnapshot -SqlInstance sql2014 -AllSnapshots -Confirm

        Removes all database snapshots from sql2014 and prompts for each database

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [string[]]$Database,
        [string[]]$ExcludeDatabase,
        [string[]]$Snapshot,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$AllSnapshots,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        $defaultprops = 'ComputerName', 'InstanceName', 'SqlInstance', 'Database as Name', 'Status'
    }
    process {
        if (!$Snapshot -and !$Database -and !$AllSnapshots -and $null -eq $InputObject -and !$ExcludeDatabase) {
            Stop-Function -Message "You must pipe in a snapshot or specify -Snapshot, -Database, -ExcludeDatabase or -AllSnapshots"
            return
        }

        # if piped value either doesn't exist or is not the proper type
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $InputObject += Get-DbaDbSnapshot -SqlInstance $server -Database $Database -ExcludeDatabase $ExcludeDatabase -Snapshot $Snapshot
        }

        foreach ($db in $InputObject) {
            $server = $db.Parent

            if (-not $db.DatabaseSnapshotBaseName) {
                Stop-Function -Message "$db on $server is not a database snapshot" -Continue
            }

            if ($Force) {
                $db | Remove-DbaDatabase -Confirm:$false | Select-DefaultView -Property $defaultprops
            } else {
                try {
                    if ($Pscmdlet.ShouldProcess("$db on $server", "Drop snapshot")) {
                        $db.Drop()
                        $server.Refresh()

                        [pscustomobject]@{
                            ComputerName = $server.ComputerName
                            InstanceName = $server.ServiceName
                            SqlInstance  = $server.DomainInstanceName
                            Database     = $db.name
                            Status       = "Dropped"
                        } | Select-DefaultView -Property $defaultprops
                    }
                } catch {
                    Write-Message -Level Verbose -Message "Could not drop database $db on $server"

                    [pscustomobject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Database     = $db.name
                        Status       = (Get-ErrorMessage -Record $_)
                    } | Select-DefaultView -Property $defaultprops
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Remove-DbaDatabaseSnapshot
    }
}
tools\dbatools\functions\Remove-DbaDbUser.ps1
function Remove-DbaDbUser {
    <#
    .SYNOPSIS
        Drop database user

    .DESCRIPTION
        If user is the owner of a schema with the same name and if if the schema does not have any underlying objects the schema will be
        dropped.  If user owns more than one schema, the owner of the schemas that does not have the same name as the user, will be
        changed to 'dbo'. If schemas have underlying objects, you must specify the -Force parameter so the user can be dropped.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Credential object used to connect to the SQL Server as a different user.

    .PARAMETER Database
        Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.

    .PARAMETER User
        Specifies the list of users to remove.

    .PARAMETER InputObject
        Support piping from Get-DbaDbUser.

    .PARAMETER Force
        If enabled this will force the change of the owner to 'dbo' for any schema which owner is the User.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database, User, Login, Security
        Author: Doug Meyers (@dgmyrs)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaDbUser

    .EXAMPLE
        PS C:\> Remove-DbaDbUser -SqlInstance sqlserver2014 -User user1

        Drops user1 from all databases it exists in on server 'sqlserver2014'.

    .EXAMPLE
        PS C:\> Remove-DbaDbUser -SqlInstance sqlserver2014 -Database database1 -User user1

        Drops user1 from the database1 database on server 'sqlserver2014'.

    .EXAMPLE
        PS C:\> Remove-DbaDbUser -SqlInstance sqlserver2014 -ExcludeDatabase model -User user1

        Drops user1 from all databases it exists in on server 'sqlserver2014' except for the model database.

    .EXAMPLE
        PS C:\> Get-DbaDbUser sqlserver2014 | Where-Object Name -In "user1" | Remove-DbaDbUser

        Drops user1 from all databases it exists in on server 'sqlserver2014'.

    #>

    [CmdletBinding(DefaultParameterSetName = 'User', SupportsShouldProcess)]
    param (
        [parameter(Position = 1, Mandatory, ValueFromPipeline, ParameterSetName = 'User')]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,

        [parameter(ParameterSetName = 'User')]
        [Alias("Credential")]
        [PSCredential]
        $SqlCredential,

        [parameter(ParameterSetName = 'User')]
        [Alias("Databases")]
        [object[]]$Database,

        [parameter(ParameterSetName = 'User')]
        [object[]]$ExcludeDatabase,

        [parameter(Mandatory, ParameterSetName = 'User')]
        [object[]]$User,

        [parameter(Mandatory, ValueFromPipeline, ParameterSetName = 'Object')]
        [Microsoft.SqlServer.Management.Smo.User[]]$InputObject,

        [parameter(ParameterSetName = 'User')]
        [parameter(ParameterSetName = 'Object')]
        [switch]$Force,

        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        function Remove-DbUser {
            [CmdletBinding(SupportsShouldProcess)]
            param ([Microsoft.SqlServer.Management.Smo.User[]]$users)

            foreach ($user in $users) {
                $db = $user.Parent
                $server = $db.Parent
                $ownedObjects = $false
                $alterSchemas = @()
                $dropSchemas = @()
                Write-Message -Level Verbose -Message "Removing User $user from Database $db on target $server"

                if ($Pscmdlet.ShouldProcess($user, "Removing user from Database $db")) {
                    # Drop Schemas owned by the user before droping the user
                    $schemaUrns = $user.EnumOwnedObjects() | Where-Object Type -EQ Schema
                    if ($schemaUrns) {
                        Write-Message -Level Verbose -Message "User $user owns $($schemaUrns.Count) schema(s)."

                        # Need to gather up the schema changes so they can be done in a non-desctructive order
                        foreach ($schemaUrn in $schemaUrns) {
                            $schema = $server.GetSmoObject($schemaUrn)

                            # Drop any schema that is the same name as the user
                            if ($schema.Name -EQ $user.Name) {
                                # Check for owned objects early so we can exit before any changes are made
                                $ownedUrns = $schema.EnumOwnedObjects()
                                if (-Not $ownedUrns) {
                                    $dropSchemas += $schema
                                } else {
                                    Write-Message -Level Warning -Message "User owns objects in the database and will not be removed."
                                    foreach ($ownedUrn in $ownedUrns) {
                                        $obj = $server.GetSmoObject($ownedUrn)
                                        Write-Message -Level Warning -Message "User $user owns $($obj.GetType().Name) $obj"
                                    }
                                    $ownedObjects = $true
                                }
                            }

                            # Change the owner of any schema not the same name as the user
                            if ($schema.Name -NE $user.Name) {
                                # Check for owned objects early so we can exit before any changes are made
                                $ownedUrns = $schema.EnumOwnedObjects()
                                if (($ownedUrns -And $Force) -Or (-Not $ownedUrns)) {
                                    $alterSchemas += $schema
                                } else {
                                    Write-Message -Level Warning -Message "User $user owns the Schema $schema, which owns $($ownedUrns.Count) Object(s).  If you want to change the schemas' owner to [dbo] and drop the user anyway, use -Force parameter.  User $user will not be removed."
                                    $ownedObjects = $true
                                }
                            }
                        }
                    }

                    if (-Not $ownedObjects) {
                        try {
                            # Alter Schemas
                            foreach ($schema in $alterSchemas) {
                                Write-Message -Level Verbose -Message "Owner of Schema $schema will be changed to [dbo]."
                                if ($PSCmdlet.ShouldProcess($server, "Change the owner of Schema $schema to [dbo].")) {
                                    $schema.Owner = "dbo"
                                    $schema.Alter()
                                }
                            }

                            # Drop Schemas
                            foreach ($schema in $dropSchemas) {
                                if ($PSCmdlet.ShouldProcess($server, "Drop Schema $schema from Database $db.")) {
                                    $schema.Drop()
                                }
                            }

                            # Finally, Drop user
                            if ($PSCmdlet.ShouldProcess($server, "Drop User $user from Database $db.")) {
                                $user.Drop()
                            }

                            $status = "Dropped"

                        } catch {
                            Write-Error -Message "Could not drop $user from Database $db on target $server"
                            $status = "Not Dropped"
                        }

                        [pscustomobject]@{
                            ComputerName = $server.ComputerName
                            InstanceName = $server.ServiceName
                            SqlInstance  = $server.DomainInstanceName
                            Database     = $db.name
                            User         = $user
                            Status       = $status
                        }
                    }
                }
            }
        }
    }

    process {
        if ($InputObject) {
            Remove-DbUser $InputObject
        } else {
            foreach ($instance in $SqlInstance) {
                try {
                    $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
                } catch {
                    Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                }

                $databases = $server.Databases | Where-Object IsAccessible

                if ($Database) {
                    $databases = $databases | Where-Object Name -In $Database
                }
                if ($ExcludeDatabase) {
                    $databases = $databases | Where-Object Name -NotIn $ExcludeDatabase
                }

                foreach ($db in $databases) {
                    Write-Message -Level Verbose -Message "Get users in Database $db on target $server"
                    $users = Get-DbaDbUser -SqlInstance $server -Database $db.Name
                    $users = $users | Where-Object Name -In $User
                    Remove-DbUser $users
                }
            }
        }
    }

}
tools\dbatools\functions\Remove-DbaEndpoint.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaEndpoint {
    <#
    .SYNOPSIS
        Removes endpoints from a SQL Server instance.

    .DESCRIPTION
        Removes endpoints from a SQL Server instance.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Endpoint
        Only remove specific endpoints.

    .PARAMETER AllEndpoints
        Remove all endpoints on an instance.

    .PARAMETER InputObject
        Enables piping from Get-Endpoint.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Endpoint
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaEndpoint

    .EXAMPLE
        PS C:\> Remove-DbaEndpoint -SqlInstance sqlserver2012 -AllEndpoints

        Removes all endpoints on the sqlserver2014 instance. Prompts for confirmation.

    .EXAMPLE
        PS C:\> Remove-DbaEndpoint -SqlInstance sqlserver2012 -Endpoint endpoint1,endpoint2 -Confirm:$false

        Removes the endpoint1 and endpoint2 endpoints. Does not prompt for confirmation.

    .EXAMPLE
        PS C:\> Get-DbaEndpoint -SqlInstance sqlserver2012 -Endpoint endpoint1 | Remove-DbaEndpoint

        Removes the endpoints returned from the Get-DbaEndpoint function. Prompts for confirmation.
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$EndPoint,
        [switch]$AllEndpoints,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Endpoint[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ((Test-Bound -ParameterName SqlInstance) -and (Test-Bound -Not -ParameterName Endpoint, AllEndpoints)) {
            Stop-Function -Message "You must specify AllEndpoints or Endpoint when using the SqlInstance parameter."
            return
        }
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaEndpoint -SqlInstance $instance -SqlCredential $SqlCredential -EndPoint $Endpoint
        }

        foreach ($ep in $InputObject) {
            if ($Pscmdlet.ShouldProcess($ep.Parent.name, "Removing endpoint $ep")) {
                try {
                    # avoid enumeration issues
                    $ep.Parent.Query("DROP ENDPOINT $ep")
                    [pscustomobject]@{
                        ComputerName = $ep.ComputerName
                        InstanceName = $ep.InstanceName
                        SqlInstance  = $ep.SqlInstance
                        Endpoint     = $ep.Name
                        Status       = "Removed"
                    }
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Remove-DbaLogin.ps1
function Remove-DbaLogin {
    <#
    .SYNOPSIS
        Drops a Login

    .DESCRIPTION
        Tries a bunch of different ways to remove a Login or two or more.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Allows you to login to servers using alternative credentials.

    .PARAMETER Login
        The Login(s) to process - this list is auto-populated from the server. If unspecified, all Logins will be processed.

    .PARAMETER InputObject
        A collection of Logins (such as returned by Get-DbaLogin), to be removed.

    .PARAMETER Force
        Kills any sessions associated with the login prior to drop

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Delete, Login
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaLogin

    .EXAMPLE
        PS C:\> Remove-DbaLogin -SqlInstance sql2016 -Login mylogin

        Prompts then removes the Login mylogin on SQL Server sql2016

    .EXAMPLE
        PS C:\> Remove-DbaLogin -SqlInstance sql2016 -Login mylogin, yourlogin

        Prompts then removes the Logins mylogin and yourlogin on SQL Server sql2016

    .EXAMPLE
        PS C:\> Remove-DbaLogin -SqlInstance sql2016 -Login mylogin -Confirm:$false

        Does not prompt and swiftly removes mylogin on SQL Server sql2016

    .EXAMPLE
        PS C:\> Get-DbaLogin -SqlInstance server\instance -Login yourlogin | Remove-DbaLogin

        Removes mylogin on SQL Server server\instance

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High', DefaultParameterSetName = "Default")]
    param (
        [parameter(Mandatory, ParameterSetName = "instance")]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [parameter(Mandatory, ParameterSetName = "instance")]
        [string[]]$Login,
        [Parameter(ValueFromPipeline, Mandatory, ParameterSetName = "Logins")]
        [Microsoft.SqlServer.Management.Smo.Login[]]$InputObject,
        [switch]$Force,
        [switch]$EnableException
    )

    process {

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            $InputObject += $server.Logins | Where-Object { $_.Name -in $Login }
        }

        foreach ($currentlogin in $InputObject) {
            try {
                $server = $currentlogin.Parent
                if ($Pscmdlet.ShouldProcess("$currentlogin on $server", "KillLogin")) {
                    if ($force) {
                        $null = Stop-DbaProcess -SqlInstance $server -Login $currentlogin.name
                    }

                    $currentlogin.Drop()

                    [pscustomobject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Login        = $currentlogin.name
                        Status       = "Dropped"
                    }
                }
            } catch {
                [pscustomobject]@{
                    ComputerName = $server.ComputerName
                    InstanceName = $server.ServiceName
                    SqlInstance  = $server.DomainInstanceName
                    Login        = $currentlogin.name
                    Status       = $_
                }
                Stop-Function -Message "Could not drop Login $currentlogin on $server" -ErrorRecord $_ -Target $currentlogin -Continue
            }
        }
    }
}
tools\dbatools\functions\Remove-DbaNetworkCertificate.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#

function Remove-DbaNetworkCertificate {
    <#
    .SYNOPSIS
        Removes the network certificate for SQL Server instance

    .DESCRIPTION
        Removes the network certificate for SQL Server instance. This setting is found in Configuration Manager.

    .PARAMETER SqlInstance
       The target SQL Server instance or instances. Defaults to localhost. If target is a cluster, you must also specify InstanceClusterName (see below)

    .PARAMETER Credential
        Allows you to login to the computer (not sql instance) using alternative credentials.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .NOTES
        Tags: Certificate
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaNetworkCertificate

    .EXAMPLE
        PS C:\> Remove-DbaNetworkCertificate

        Removes the Network Certificate for the default instance (MSSQLSERVER) on localhost

    .EXAMPLE
        PS C:\> Remove-DbaNetworkCertificate -SqlInstance sql1\SQL2008R2SP2

        Removes the Network Certificate for the SQL2008R2SP2 instance on sql1

    .EXAMPLE
        PS C:\> Remove-DbaNetworkCertificate -SqlInstance localhost\SQL2008R2SP2 -WhatIf

        Shows what would happen if the command were run

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low", DefaultParameterSetName = 'Default')]
    param (
        [Parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "ComputerName")]
        [DbaInstanceParameter[]]$SqlInstance = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [switch]$EnableException
    )
    process {
        # Registry access
        
        
        foreach ($instance in $sqlinstance) {
            Write-Message -Level VeryVerbose -Message "Processing $instance" -Target $instance
            $null = Test-ElevationRequirement -ComputerName $instance -Continue

            Write-Message -Level Verbose -Message "Resolving hostname"
            $resolved = $null
            $resolved = Resolve-DbaNetworkName -ComputerName $instance -Turbo

            if ($null -eq $resolved) {
                Stop-Function -Message "Can't resolve $instance" -Target $instance -Continue -Category InvalidArgument
            }

            try {
                $sqlwmi = Invoke-ManagedComputerCommand -ComputerName $resolved.FQDN -ScriptBlock { $wmi.Services } -Credential $Credential -ErrorAction Stop | Where-Object DisplayName -eq "SQL Server ($($instance.InstanceName))"
            } catch {
                Stop-Function -Message "Failed to access $instance" -Target $instance -Continue -ErrorRecord $_
            }

            $regroot = ($sqlwmi.AdvancedProperties | Where-Object Name -eq REGROOT).Value
            $vsname = ($sqlwmi.AdvancedProperties | Where-Object Name -eq VSNAME).Value
            $instancename = $sqlwmi.DisplayName.Replace('SQL Server (', '').Replace(')', '') # Don't clown, I don't know regex :(
            $serviceaccount = $sqlwmi.ServiceAccount

            if ([System.String]::IsNullOrEmpty($regroot)) {
                $regroot = $sqlwmi.AdvancedProperties | Where-Object { $_ -match 'REGROOT' }
                $vsname = $sqlwmi.AdvancedProperties | Where-Object { $_ -match 'VSNAME' }

                if (![System.String]::IsNullOrEmpty($regroot)) {
                    $regroot = ($regroot -Split 'Value\=')[1]
                    $vsname = ($vsname -Split 'Value\=')[1]
                } else {
                    Stop-Function -Message "Can't find instance $vsname on $instance" -Continue -Category ObjectNotFound -Target $instance
                }
            }

            if ([System.String]::IsNullOrEmpty($vsname)) { $vsname = $instance }

            Write-Message -Level Output -Message "Regroot: $regroot" -Target $instance
            Write-Message -Level Output -Message "ServiceAcct: $serviceaccount" -Target $instance
            Write-Message -Level Output -Message "InstanceName: $instancename" -Target $instance
            Write-Message -Level Output -Message "VSNAME: $vsname" -Target $instance

            $scriptblock = {
                $regroot = $args[0]
                $serviceaccount = $args[1]
                $instancename = $args[2]
                $vsname = $args[3]

                $regpath = "Registry::HKEY_LOCAL_MACHINE\$($regroot)\MSSQLServer\SuperSocketNetLib"
                $cert = (Get-ItemProperty -Path $regpath -Name Certificate).Certificate
                Set-ItemProperty -Path $regpath -Name Certificate -Value $null

                [pscustomobject]@{
                    ComputerName      = $env:COMPUTERNAME
                    InstanceName      = $instancename
                    SqlInstance       = $vsname
                    ServiceAccount    = $serviceaccount
                    RemovedThumbprint = $cert.Thumbprint
                }
            }

            if ($PScmdlet.ShouldProcess("local", "Connecting to $ComputerName to remove the cert")) {
                try {
                    Invoke-Command2 -ComputerName $resolved.fqdn -Credential $Credential -ArgumentList $regroot, $serviceaccount, $instancename, $vsname -ScriptBlock $scriptblock -ErrorAction Stop
                } catch {
                    Stop-Function -Message "Failed to connect to $($resolved.fqdn) using PowerShell remoting!" -ErrorRecord $_ -Target $instance -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Remove-DbaPfDataCollectorCounter.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaPfDataCollectorCounter {
    <#
    .SYNOPSIS
        Removes a Performance Data Collector Counter.

    .DESCRIPTION
        Removes a Performance Data Collector Counter.

    .PARAMETER ComputerName
        The target computer. Defaults to localhost.

    .PARAMETER Credential
        Allows you to login to the target computer using alternative credentials. To use:

        $cred = Get-Credential, then pass $cred object to the -Credential parameter.

    .PARAMETER CollectorSet
        The name of the Collector Set to search.

    .PARAMETER Collector
        The name of the Collector to remove.

    .PARAMETER Counter
        The name of the Counter - in the form of '\Processor(_Total)\% Processor Time'.

    .PARAMETER InputObject
        Accepts the object output by Get-DbaPfDataCollectorSet via the pipeline.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: PerfMon
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaPfDataCollectorCounter

    .EXAMPLE
        PS C:\> Remove-DbaPfDataCollectorCounter -ComputerName sql2017 -CollectorSet 'System Correlation' -Collector DataCollector01  -Counter '\LogicalDisk(*)\Avg. Disk Queue Length'

        Prompts for confirmation then removes the '\LogicalDisk(*)\Avg. Disk Queue Length' counter within the DataCollector01 collector within the System Correlation collector set on sql2017.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorCounter | Out-GridView -PassThru | Remove-DbaPfDataCollectorCounter -Confirm:$false

        Allows you to select which counters you'd like on localhost and does not prompt for confirmation.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")]
    param (
        [DbaInstance[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [Alias("DataCollectorSet")]
        [string[]]$CollectorSet,
        [Alias("DataCollector")]
        [string[]]$Collector,
        [parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [Alias("Name")]
        [object[]]$Counter,
        [parameter(ValueFromPipeline)]
        [object[]]$InputObject,
        [switch]$EnableException
    )
    begin {
        $setscript = {
            $setname = $args[0]; $removexml = $args[1]
            $CollectorSet = New-Object -ComObject Pla.DataCollectorSet
            $CollectorSet.SetXml($removexml)
            $CollectorSet.Commit($setname, $null, 0x0003) #add or modify.
            $CollectorSet.Query($setname, $Null)
        }
    }
    process {
        
        
        if ($InputObject.Credential -and (Test-Bound -ParameterName Credential -Not)) {
            $Credential = $InputObject.Credential
        }

        if (-not $InputObject -or ($InputObject -and (Test-Bound -ParameterName ComputerName))) {
            foreach ($computer in $ComputerName) {
                $InputObject += Get-DbaPfDataCollectorCounter -ComputerName $computer -Credential $Credential -CollectorSet $CollectorSet -Collector $Collector -Counter $Counter
            }
        }

        if ($InputObject) {
            if (-not $InputObject.CounterObject) {
                Stop-Function -Message "InputObject is not of the right type. Please use Get-DbaPfDataCollectorCounter."
                return
            }
        }

        foreach ($object in $InputObject) {
            $computer = $InputObject.ComputerName
            $null = Test-ElevationRequirement -ComputerName $computer -Continue
            $setname = $InputObject.DataCollectorSet
            $collectorname = $InputObject.DataCollector

            $xml = [xml]($InputObject.DataCollectorSetXml)

            foreach ($countername in $counter) {
                $node = $xml.SelectSingleNode("//Name[.='$collectorname']").SelectSingleNode("//Counter[.='$countername']")
                $null = $node.ParentNode.RemoveChild($node)
                $node = $xml.SelectSingleNode("//Name[.='$collectorname']").SelectSingleNode("//CounterDisplayName[.='$countername']")
                $null = $node.ParentNode.RemoveChild($node)
            }

            $plainxml = $xml.OuterXml

            if ($Pscmdlet.ShouldProcess("$computer", "Remove $countername from $collectorname with the $setname collection set")) {
                try {
                    $results = Invoke-Command2 -ComputerName $computer -Credential $Credential -ScriptBlock $setscript -ArgumentList $setname, $plainxml -ErrorAction Stop -Raw
                    Write-Message -Level Verbose -Message " $results"
                    [pscustomobject]@{
                        ComputerName     = $computer
                        DataCollectorSet = $setname
                        DataCollector    = $collectorname
                        Name             = $counterName
                        Status           = "Removed"
                    }
                } catch {
                    Stop-Function -Message "Failure importing $Countername to $computer." -ErrorRecord $_ -Target $computer -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Remove-DbaPfDataCollectorSet.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaPfDataCollectorSet {
    <#
    .SYNOPSIS
        Removes a Performance Monitor Data Collector Set

    .DESCRIPTION
        Removes a Performance Monitor Data Collector Set. When removing data collector sets from the local instance, Run As Admin is required.

    .PARAMETER ComputerName
        The target computer. Defaults to localhost.

    .PARAMETER Credential
        Allows you to login to the target computer using alternative credentials. To use:

        $cred = Get-Credential, then pass $cred object to the -Credential parameter.

    .PARAMETER CollectorSet
        The name of the Collector Set to remove.

    .PARAMETER InputObject
        Accepts the object output by Get-DbaPfDataCollectorSet via the pipeline.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: PerfMon
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaPfDataCollectorSet

    .EXAMPLE
        PS C:\> Remove-DbaPfDataCollectorSet

        Prompts for confirmation then removes all ready Collectors on localhost.

    .EXAMPLE
        PS C:\> Remove-DbaPfDataCollectorSet -ComputerName sql2017 -Confirm:$false

        Attempts to remove all ready Collectors on localhost and does not prompt to confirm.

    .EXAMPLE
        PS C:\> Remove-DbaPfDataCollectorSet -ComputerName sql2017, sql2016 -Credential ad\sqldba -CollectorSet 'System Correlation'

        Prompts for confirmation then removes the 'System Correlation' Collector on sql2017 and sql2016 using alternative credentials.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorSet -CollectorSet 'System Correlation' | Remove-DbaPfDataCollectorSet

        Removes the 'System Correlation' Collector.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorSet -CollectorSet 'System Correlation' | Stop-DbaPfDataCollectorSet | Remove-DbaPfDataCollectorSet

        Stops and removes the 'System Correlation' Collector.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")]
    param (
        [DbaInstance[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [Alias("DataCollectorSet")]
        [string[]]$CollectorSet,
        [parameter(ValueFromPipeline)]
        [object[]]$InputObject,
        [switch]$EnableException
    )
    begin {
        $setscript = {
            $setname = $args
            $collectorset = New-Object -ComObject Pla.DataCollectorSet
            $collectorset.Query($setname, $null)
            if ($collectorset.name -eq $setname) {
                $null = $collectorset.Delete()
            } else {
                <# DO NOT use Write-Message as this is inside of a script block #>
                Write-Warning "Data Collector Set $setname does not exist on $env:COMPUTERNAME."
            }
        }
    }
    process {
        
        
        if (-not $InputObject -or ($InputObject -and (Test-Bound -ParameterName ComputerName))) {
            foreach ($computer in $ComputerName) {
                $InputObject += Get-DbaPfDataCollectorSet -ComputerName $computer -Credential $Credential -CollectorSet $CollectorSet
            }
        }

        if ($InputObject) {
            if (-not $InputObject.DataCollectorSetObject) {
                Stop-Function -Message "InputObject is not of the right type. Please use Get-DbaPfDataCollectorSet."
                return
            }
        }

        # Check to see if its running first
        foreach ($set in $InputObject) {
            $setname = $set.Name
            $computer = $set.ComputerName
            $status = $set.State

            $null = Test-ElevationRequirement -ComputerName $computer -Continue

            Write-Message -Level Verbose -Message "$setname on $ComputerName is $status."

            if ($status -eq "Running") {
                Stop-Function -Message "$setname on $computer is running. Use Stop-DbaPfDataCollectorSet to stop first." -Continue
            }

            if ($Pscmdlet.ShouldProcess("$computer", "Removing collector set $setname")) {
                try {
                    Invoke-Command2 -ComputerName $computer -Credential $Credential -ScriptBlock $setscript -ArgumentList $setname -ErrorAction Stop
                    [pscustomobject]@{
                        ComputerName = $computer
                        Name         = $setname
                        Status       = "Removed"
                    }
                } catch {
                    Stop-Function -Message "Failure Removing $setname on $computer." -ErrorRecord $_ -Target $computer -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Remove-DbaSpn.ps1
#ValidationTags#FlowControl,Pipeline#
function Remove-DbaSpn {
    <#
    .SYNOPSIS
        Removes an SPN for a given service account in active directory and also removes delegation to the same SPN, if found

    .DESCRIPTION
        This function will connect to Active Directory and search for an account. If the account is found, it will attempt to remove the specified SPN. Once the SPN is removed, the function will also remove delegation to that service.

        In order to run this function, the credential you provide must have write access to Active Directory.

    .PARAMETER SPN
        The SPN you want to remove

    .PARAMETER ServiceAccount
        The account you want the SPN remove from

    .PARAMETER Credential
        The credential you want to use to connect to Active Directory to make the changes

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER Confirm
        Turns confirmations before changes on or off

    .PARAMETER WhatIf
        Shows what would happen if the command was executed

    .NOTES
        Tags: SPN
        Author: Drew Furgiuele (@pittfurg), http://www.port1433.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaSpn

    .EXAMPLE
        PS C:\> Remove-DbaSpn -SPN MSSQLSvc\SQLSERVERA.domain.something -ServiceAccount domain\account

        Connects to Active Directory and removes a provided SPN from the given account (and also the relative delegation)

    .EXAMPLE
        PS C:\> Remove-DbaSpn -SPN MSSQLSvc\SQLSERVERA.domain.something -ServiceAccount domain\account -EnableException

        Connects to Active Directory and removes a provided SPN from the given account, suppressing all error messages and throw exceptions that can be caught instead

    .EXAMPLE
        PS C:\> Remove-DbaSpn -SPN MSSQLSvc\SQLSERVERA.domain.something -ServiceAccount domain\account -Credential ad\sqldba

        Connects to Active Directory and removes a provided SPN to the given account. Uses alternative account to connect to AD.

    .EXAMPLE
        PS C:\> Test-DbaSpn -ComputerName sql2005 | Where { $_.isSet -eq $true } | Remove-DbaSpn -WhatIf

        Shows what would happen trying to remove all set SPNs for sql2005 and the relative delegations

    .EXAMPLE
        PS C:\> Test-DbaSpn -ComputerName sql2005 | Where { $_.isSet -eq $true } | Remove-DbaSpn

        Removes all set SPNs for sql2005 and the relative delegations

    #>
    [cmdletbinding(SupportsShouldProcess, DefaultParameterSetName = "Default")]
    param (
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [Alias("RequiredSPN")]
        [string]$SPN,
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [Alias("InstanceServiceAccount", "AccountName")]
        [string]$ServiceAccount,
        [Parameter(ValueFromPipelineByPropertyName)]
        [PSCredential]$Credential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        Write-Message -Message "Looking for account $ServiceAccount..." -Level Verbose
        $searchfor = 'User'
        if ($ServiceAccount.EndsWith('$')) {
            $searchfor = 'Computer'
        }
        try {
            $Result = Get-DbaADObject -ADObject $ServiceAccount -Type $searchfor -Credential $Credential -EnableException
        } catch {
            Stop-Function -Message "AD lookup failure. This may be because the domain cannot be resolved for the SQL Server service account ($ServiceAccount). $($_.Exception.Message)" -EnableException $EnableException -InnerErrorRecord $_ -Target $ServiceAccount
        }
        if ($Result.Count -gt 0) {
            try {
                $adentry = $Result.GetUnderlyingObject()
            } catch {
                Stop-Function -Message "The SQL Service account ($ServiceAccount) has been found, but you don't have enough permission to inspect its properties $($_.Exception.Message)" -EnableException $EnableException -InnerErrorRecord $_ -Target $ServiceAccount
            }
        } else {
            Stop-Function -Message "The SQL Service account ($ServiceAccount) has not been found" -EnableException $EnableException -Target $ServiceAccount
        }

        # Cool! Remove an SPN
        $delegate = $true
        $spnadobject = $adentry.Properties['servicePrincipalName']

        if ($spnadobject -notcontains $spn) {
            Write-Message -Level Warning -Message "SPN $SPN not found"
            $status = "SPN not found"
            $set = $false
        }

        if ($PSCmdlet.ShouldProcess("$spn", "Removing SPN for service account")) {
            try {
                if ($spnadobject -contains $spn) {
                    $null = $spnadobject.Remove($spn)
                    $adentry.CommitChanges()
                    Write-Message -Message "Remove SPN $spn for $serviceaccount" -Level Verbose
                    $set = $false
                    $status = "Successfully removed SPN"
                }
            } catch {
                Write-Message -Message "Could not remove SPN. $($_.Exception.Message)" -Level Warning -EnableException $EnableException.ToBool() -ErrorRecord $_ -Target $ServiceAccountWrite
                $set = $true
                $status = "Failed to remove SPN"
                $delegate = $false
            }

            [pscustomobject]@{
                Name           = $spn
                ServiceAccount = $ServiceAccount
                Property       = "servicePrincipalName"
                IsSet          = $set
                Notes          = $status
            }
        }
        # if we removed the SPN, we should clean up also the delegation
        if ($PSCmdlet.ShouldProcess("$spn", "Removing delegation for service account for SPN")) {
            # if we didn't remove the SPN we shouldn't do anything
            if ($delegate) {
                # even if we removed the SPN, delegation could have been not set at all. We should not raise an error
                if ($adentry.Properties['msDS-AllowedToDelegateTo'] -notcontains $spn) {
                    [pscustomobject]@{
                        Name           = $spn
                        ServiceAccount = $ServiceAccount
                        Property       = "msDS-AllowedToDelegateTo"
                        IsSet          = $false
                        Notes          = "Delegation not found"
                    }
                } else {
                    # we indeed need the cleanup
                    try {
                        $null = $adentry.Properties['msDS-AllowedToDelegateTo'].Remove($spn)
                        $adentry.CommitChanges()
                        Write-Message -Message "Removed kerberos delegation $spn for $ServiceAccount" -Level Verbose
                        $set = $false
                        $status = "Successfully removed delegation"
                    } catch {
                        Write-Message -Message "Could not remove delegation. $($_.Exception.Message)" -Level Warning -EnableException $EnableException.ToBool() -ErrorRecord $_ -Target $ServiceAccount
                        $set = $true
                        $status = "Failed to remove delegation"
                    }

                    [pscustomobject]@{
                        Name           = $spn
                        ServiceAccount = $ServiceAccount
                        Property       = "msDS-AllowedToDelegateTo"
                        IsSet          = $set
                        Notes          = $status
                    }
                }
            }

        }
    }
}
tools\dbatools\functions\Remove-DbaTrace.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaTrace {
    <#
    .SYNOPSIS
        Stops and closes the specified trace and deletes its definition from the server.

    .DESCRIPTION
        Stops and closes the specified trace and deletes its definition from the server.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Id
        A list of trace ids.

    .PARAMETER InputObject
        Internal parameter for piping.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Security, Trace
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Remove-DbaTrace -SqlInstance sql2008

        Stops and removes all traces on sql2008

    .EXAMPLE
        PS C:\> Remove-DbaTrace -SqlInstance sql2008 -Id 1

        Stops and removes all trace with ID 1 on sql2008

    .EXAMPLE
        PS C:\> Get-DbaTrace -SqlInstance sql2008 | Out-GridView -PassThru | Remove-DbaTrace

        Stops and removes selected traces on sql2008

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [int[]]$Id,
        [parameter(ValueFromPipeline)]
        [object[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if (-not $InputObject -and $SqlInstance) {
            $InputObject = Get-DbaTrace -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Id $Id
        }

        foreach ($trace in $InputObject) {
            if (-not $trace.id -and -not $trace.Parent) {
                Stop-Function -Message "Input is of the wrong type. Use Get-DbaTrace." -Continue
                return
            }

            $server = $trace.Parent
            $traceid = $trace.id
            $default = Get-DbaTrace -SqlInstance $server -Default

            if ($default.id -eq $traceid) {
                Stop-Function -Message "The default trace on $server cannot be stopped. Use Set-DbaSpConfigure to turn it off." -Continue
            }

            $stopsql = "sp_trace_setstatus $traceid, 0"
            $removesql = "sp_trace_setstatus $traceid, 2"

            if ($Pscmdlet.ShouldProcess($traceid, "Removing the trace")) {
                try {
                    $server.Query($stopsql)
                    if (Get-DbaTrace -SqlInstance $server -Id $traceid) {
                        $server.Query($removesql)
                    }
                    [pscustomobject]@{
                        ComputerName = $server.ComputerName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Id           = $traceid
                        Status       = "Stopped, closed and deleted"
                    }
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target $server -Continue
                    return
                }
            }
        }
    }
}
tools\dbatools\functions\Remove-DbaXESession.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaXESession {
    <#
    .SYNOPSIS
        Removes Extended Events sessions.

    .DESCRIPTION
        This script removes Extended Events sessions on a SQL Server instance.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Session
        Specifies a list of Extended Events sessions to remove.

    .PARAMETER AllSessions
        If this switch is enabled, all Extended Events sessions will be removed except the packaged sessions AlwaysOn_health, system_health, telemetry_xevents.

    .PARAMETER InputObject
        Accepts a collection of XEsession objects as output by Get-DbaXESession.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaXESession

    .EXAMPLE
        PS C:\> Remove-DbaXESession -SqlInstance sql2012 -AllSessions

        Removes all Extended Event Session on the sqlserver2014 instance.

    .EXAMPLE
        PS C:\> Remove-DbaXESession -SqlInstance sql2012 -Session xesession1,xesession2

        Removes the xesession1 and xesession2 Extended Event sessions.

    .EXAMPLE
        PS C:\> Get-DbaXESession -SqlInstance sql2017 | Remove-DbaXESession -Confirm:$false

        Removes all sessions from sql2017, bypassing prompts.

    .EXAMPLE
        PS C:\> Get-DbaXESession -SqlInstance sql2012 -Session xesession1 | Remove-DbaXESession

        Removes the sessions returned from the Get-DbaXESession function.

    #>
    [CmdletBinding(DefaultParameterSetName = 'Session', SupportsShouldProcess, ConfirmImpact = 'High')]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification = "Internal functions are ignored")]
    param (
        [parameter(Position = 1, Mandatory, ParameterSetName = 'Session')]
        [parameter(Position = 1, Mandatory, ParameterSetName = 'All')]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [parameter(ParameterSetName = 'Session')]
        [parameter(ParameterSetName = 'All')]
        [PSCredential]$SqlCredential,
        [parameter(Mandatory, ParameterSetName = 'Session')]
        [Alias("Sessions")]
        [object[]]$Session,
        [parameter(Mandatory, ParameterSetName = 'All')]
        [switch]$AllSessions,
        [parameter(Mandatory, ValueFromPipeline, ParameterSetName = 'Object')]
        [Microsoft.SqlServer.Management.XEvent.Session[]]$InputObject,
        [switch]$EnableException
    )

    begin {
        # Remove each XESession
        function Remove-XESessions {
            [CmdletBinding(SupportsShouldProcess)]
            param ([Microsoft.SqlServer.Management.XEvent.Session[]]$xeSessions)

            foreach ($xe in $xeSessions) {
                $instance = $xe.Parent.Name
                $session = $xe.Name

                if ($Pscmdlet.ShouldProcess("$instance", "Removing XEvent Session $session")) {
                    try {
                        $xe.Drop()
                        [pscustomobject]@{
                            ComputerName = $xe.Parent.ComputerName
                            InstanceName = $xe.Parent.ServiceName
                            SqlInstance  = $xe.Parent.DomainInstanceName
                            Session      = $session
                            Status       = "Removed"
                        }
                    } catch {
                        Stop-Function -Message "Could not remove XEvent Session on $instance" -Target $session -ErrorRecord $_ -Continue
                    }
                }
            }
        }
    }

    process {
        if ($InputObject) {
            # avoid the collection issue
            $sessions = Get-DbaXESession -SqlInstance $InputObject.Parent -Session $InputObject.Name
            foreach ($item in $sessions) {
                Remove-XESessions $item
            }
        } else {
            foreach ($instance in $SqlInstance) {
                $xeSessions = Get-DbaXESession -SqlInstance $instance -SqlCredential $SqlCredential

                # Filter xeSessions based on parameters
                if ($Session) {
                    $xeSessions = $xeSessions | Where-Object { $_.Name -in $Session }
                } elseif ($AllSessions) {
                    $systemSessions = @('AlwaysOn_health', 'system_health', 'telemetry_xevents')
                    $xeSessions = $xeSessions | Where-Object { $_.Name -notin $systemSessions }
                }

                Remove-XESessions $xeSessions
            }
        }
    }
}
tools\dbatools\functions\Remove-DbaXESmartTarget.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Remove-DbaXESmartTarget {
    <#
    .SYNOPSIS
        Removes XESmartTarget PowerShell jobs.

    .DESCRIPTION
        Removes XESmartTarget PowerShell jobs.

    .PARAMETER InputObject
        Specifies one or more XESmartTarget job objects as output by Get-DbaXESmartTarget.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl) | SmartTarget by Gianluca Sartori (@spaghettidba)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        https://github.com/spaghettidba/XESmartTarget/wiki

    .LINK
        https://dbatools.io/Remove-DbaXESmartTarget

    .EXAMPLE
        PS C:\> Get-DbaXESmartTarget | Remove-DbaXESmartTarget

        Removes all XESmartTarget jobs.

    .EXAMPLE
        PS C:\> Get-DbaXESmartTarget | Where-Object Id -eq 2 | Remove-DbaXESmartTarget

        Removes a specific XESmartTarget job.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [object[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ($Pscmdlet.ShouldProcess("localhost", "Removing job $id")) {
            try {
                $id = $InputObject.Id
                Write-Message -Level Output -Message "Removing job $id, this may take a couple minutes."
                Get-Job -ID $InputObject.Id | Remove-Job -Force
                Write-Message -Level Output -Message "Successfully removed $id."
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_
            }
        }
    }
}
tools\dbatools\functions\Rename-DbaDatabase.ps1
function Rename-DbaDatabase {
    <#
    .SYNOPSIS
        Changes database name, logical file names, file group names and physical file names (optionally handling the move). BETA VERSION.

    .DESCRIPTION
        Can change every database metadata that can be renamed.
        The ultimate goal is choosing to have a default template to enforce in your environment
        so your naming convention for every bit can be put in place in no time.
        The process is as follows (it follows the hierarchy of the entities):
        - database name is changed (optionally, forcing users out)
        - filegroup name(s) are changed accordingly
        - logical name(s) are changed accordingly
        - physical file(s) are changed accordingly
        - if Move is specified, the database will be taken offline and the move will initiate, then it will be taken online
        - if Move is not specified, the database remains online (unless SetOffline), and you are in charge of moving files
        If any of the above fails, the process stops.
        Please take a backup of your databases BEFORE using this, and remember to backup AFTER (also a FULL backup of master)

        It returns an object for each database with all the renames done, plus hidden properties showing a "human" representation of them.

        It's better you store the resulting object in a variable so you can inspect it in case of issues, e.g. "$result = Rename-DbaDatabase ....."

        To get a grasp without worrying of what would happen under the hood, use "Rename-DbaDatabase .... -Preview | Select-Object *"

    .PARAMETER SqlInstance
        Target any number of instances, in order to return their build state.

    .PARAMETER SqlCredential
        When connecting to an instance, use the credentials specified.

    .PARAMETER Database
        Targets only specified databases

    .PARAMETER ExcludeDatabase
        Excludes only specified databases

    .PARAMETER AllDatabases
        If you want to apply the naming convention system wide, you need to pass this parameter

    .PARAMETER DatabaseName
        Pass a template to rename the database name. Valid placeholders are:
        - <DBN> current database name
        - <DATE> date (yyyyMMdd)

    .PARAMETER FileGroupName
        Pass a template to rename file group name. Valid placeholders are:
        - <FGN> current filegroup name
        - <DBN> current database name
        - <DATE> date (yyyyMMdd)
        If distinct names cannot be generated, a counter will be appended (0001, 0002, 0003, etc)

    .PARAMETER LogicalName
        Pass a template to rename logical name. Valid placeholders are:
        - <FT> file type (ROWS, LOG)
        - <LGN> current logical name
        - <FGN> current filegroup name
        - <DBN> current database name
        - <DATE> date (yyyyMMdd)
        If distinct names cannot be generated, a counter will be appended (0001, 0002, 0003, etc)

    .PARAMETER FileName
        Pass a template to rename file name. Valid placeholders are:
        - <FNN> current file name (the basename, without directory nor extension)
        - <FT> file type (ROWS, LOG, MMO, FS)
        - <LGN> current logical name
        - <FGN> current filegroup name
        - <DBN> current database name
        - <DATE> date (yyyyMMdd)
        If distinct names cannot be generated, a counter will be appended (0001, 0002, 0003, etc)

    .PARAMETER ReplaceBefore
        If you pass this switch, all upper level "current names" will be inspected and replaced BEFORE doing the
        rename according to the template in the current level (remember the hierarchy):
        Let's say you have a database named "dbatools_HR", composed by 3 files
        - dbatools_HR_Data.mdf
        - dbatools_HR_Index.ndf
        - dbatools_HR_log.ldf
        Rename-DbaDatabase .... -Database "dbatools_HR" -DatabaseName "dbatools_HRARCHIVE" -FileName '<DBN><FNN>'
        would end up with this logic:
        - database --> no placeholders specified
        - dbatools_HR to dbatools_HRARCHIVE
        - filenames placeholders specified
        <DBN><FNN> --> current database name + current filename"
        - dbatools_HR_Data.mdf to dbatools_HRARCHIVEdbatools_HR_Data.mdf
        - dbatools_HR_Index.mdf to dbatools_HRARCHIVEdbatools_HR_Data.mdf
        - dbatools_HR_log.ldf to dbatools_HRARCHIVEdbatools_HR_log.ldf
        Passing this switch, instead, e.g.
        Rename-DbaDatabase .... -Database "dbatools_HR" -DatabaseName "dbatools_HRARCHIVE" -FileName '<DBN><FNN>' -ReplaceBefore
        end up with this logic instead:
        - database --> no placeholders specified
        - dbatools_HR to dbatools_HRARCHIVE
        - filenames placeholders specified,
        <DBN><FNN>, plus -ReplaceBefore --> current database name + replace OLD "upper level" names inside the current filename
        - dbatools_HR_Data.mdf to dbatools_HRARCHIVE_Data.mdf
        - dbatools_HR_Index.mdf to dbatools_HRARCHIVE_Data.mdf
        - dbatools_HR_log.ldf to dbatools_HRARCHIVE_log.ldf

    .PARAMETER Force
        Kills any open session to be able to do renames.

    .PARAMETER SetOffline
        Kills any open session and sets the database offline to be able to move files

    .PARAMETER Move
        If you want this function to move files, else you're the one in charge of it.
        This enables the same functionality as SetOffline, killing open transactions and putting the database
        offline, then do the actual rename and setting it online again afterwards

    .PARAMETER Preview
        Shows the renames without performing any operation (recommended to find your way around this function parameters ;-) )

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER InputObject
        Accepts piped database objects

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database, Rename
        Author: Simone Bizzotto (@niphold)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Rename-DbaDatabase

    .EXAMPLE
        PS C:\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName HR2 -Preview | select *

        Shows the detailed result set you'll get renaming the HR database to HR2 without doing anything

    .EXAMPLE
        PS C:\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName HR2

        Renames the HR database to HR2

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sqlserver2014a -Database HR | Rename-DbaDatabase -DatabaseName HR2

        Same as before, but with a piped database (renames the HR database to HR2)

    .EXAMPLE
        PS C:\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName "dbatools_<DBN>"

        Renames the HR database to dbatools_HR

    .EXAMPLE
        PS C:\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName "dbatools_<DBN>_<DATE>"

        Renames the HR database to dbatools_HR_20170807 (if today is 07th Aug 2017)

    .EXAMPLE
        PS C:\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -FileGroupName "dbatools_<FGN>"

        Renames every FileGroup within HR to "dbatools_[the original FileGroup name]"

    .EXAMPLE
        PS C:\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName "dbatools_<DBN>" -FileGroupName "<DBN>_<FGN>"

        Renames the HR database to "dbatools_HR", then renames every FileGroup within to "dbatools_HR_[the original FileGroup name]"

    .EXAMPLE
        PS C:\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -FileGroupName "dbatools_<DBN>_<FGN>"
        PS C:\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName "dbatools_<DBN>"

        Renames the HR database to "dbatools_HR", then renames every FileGroup within to "dbatools_HR_[the original FileGroup name]"

    .EXAMPLE
        PS C:\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName "dbatools_<DBN>" -FileName "<DBN>_<FGN>_<FNN>"

        Renames the HR database to "dbatools_HR" and then all filenames as "dbatools_HR_[Name of the FileGroup]_[original_filename]"
        The db stays online (watch out!). You can then proceed manually to move/copy files by hand, set the db offline and then online again to finish the rename process

    .EXAMPLE
        PS C:\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName "dbatools_<DBN>" -FileName "<DBN>_<FGN>_<FNN>" -SetOffline

        Renames the HR database to "dbatools_HR" and then all filenames as "dbatools_HR_[Name of the FileGroup]_[original_filename]"
        The db is then set offline (watch out!). You can then proceed manually to move/copy files by hand and then set it online again to finish the rename process

    .EXAMPLE
        PS C:\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName "dbatools_<DBN>" -FileName "<DBN>_<FGN>_<FNN>" -Move

        Renames the HR database to "dbatools_HR" and then all filenames as "dbatools_HR_[Name of the FileGroup]_[original_filename]"
        The db is then set offline (watch out!). The function tries to do a simple rename and then sets the db online again to finish the rename process

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ParameterSetName = "Server")]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]
        $SqlCredential,
        [parameter(ParameterSetName = "Server")]
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$AllDatabases,
        [string]$DatabaseName,
        [string]$FileGroupName,
        [string]$LogicalName,
        [string]$FileName,
        [switch]$ReplaceBefore,
        [switch]$Force,
        [switch]$Move,
        [switch]$SetOffline,
        [switch]$Preview,
        [parameter(Mandatory, ValueFromPipeline, ParameterSetName = "Pipe")]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $CurrentDate = Get-Date -Format 'yyyyMMdd'

        function Get-DbaNameStructure($database) {
            $obj = @()
            # db name
            $obj += "- Database : $database"
            # FileGroups
            foreach ($fg in $database.FileGroups) {
                $obj += "  - FileGroup: $($fg.Name)"
                # LogicalNames
                foreach ($ln in $fg.Files) {
                    $obj += "    - Logical: $($ln.Name)"
                    $obj += "      - FileName: $($ln.FileName)"
                }
            }
            $obj += "  - Logfiles"
            foreach ($log in $database.LogFiles) {
                $obj += "    - Logical: $($log.Name)"
                $obj += "      - FileName: $($log.FileName)"
            }
            return $obj -Join "`n"
        }


        function Get-DbaKeyByValue($hashtable, $Value) {
            ($hashtable.GetEnumerator() | Where-Object Value -eq $Value).Name
        }

        if ((Test-Bound -ParameterName SetOffline) -and (-not(Test-Bound -ParameterName FileName))) {
            Stop-Function -Category InvalidArgument -Message "-SetOffline is only useful when -FileName is passed. Quitting."
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }
        if (!$Database -and !$AllDatabases -and !$InputObject -and !$ExcludeDatabase) {
            Stop-Function -Message "You must specify a -AllDatabases or -Database/ExcludeDatabase to continue"
            return
        }
        if (!$DatabaseName -and !$FileGroupName -and !$LogicalName -and !$FileName) {
            Stop-Function -Message "You must specify at least one of -DatabaseName,-FileGroupName,-LogicalName or -Filename to continue"
            return
        }
        $dbs = @()
        if ($InputObject) {
            if ($InputObject.Name) {
                # comes from Get-DbaDatabase
                $dbs += $InputObject
            }
        } else {
            foreach ($instance in $SqlInstance) {
                try {
                    $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlCredential
                } catch {
                    Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                }
                $all_dbs = $server.Databases | Where-Object IsAccessible
                $dbs += $all_dbs | Where-Object { @('master', 'model', 'msdb', 'tempdb', 'distribution') -notcontains $_.Name }
                if ($Database) {
                    $dbs = $dbs | Where-Object { $Database -contains $_.Name }
                }
                if ($ExcludeDatabase) {
                    $dbs = $dbs | Where-Object { $ExcludeDatabase -notcontains $_.Name }
                }
            }
        }

        # holds all dbs per instance to avoid naming clashes
        $InstanceDbs = @{}

        # holds all db file enumerations (used for -Move only)
        $InstanceFiles = @{}

        #region db loop
        foreach ($db in $dbs) {
            # used to stop futher operations on database
            $failed = $false

            # pending renames initialized at db level
            $Pending_Renames = @()

            $Entities_Before = @{}

            $server = $db.Parent
            if ($db.Name -in @('master', 'model', 'msdb', 'tempdb', 'distribution')) {
                Write-Message -Level Warning -Message "Database $($db.Name) is a system one, skipping..."
                continue
            }
            if (!$db.IsAccessible) {
                Write-Message -Level Warning -Message "Database $($db.Name) is not accessible, skipping..."
                continue
            }
            if ($db.IsMirroringEnabled -eq $true -or $db.AvailabilityGroupName.Length -gt 0) {
                Write-Message -Level Warning -Message "Database $($db.Name) is either mirrored or in an AG, skipping..."
                continue
            }
            $Server_Id = $server.DomainInstanceName
            if ( !$InstanceDbs.ContainsKey($Server_Id) ) {
                $InstanceDbs[$Server_Id] = @{}
                foreach ($dn in $server.Databases.Name) {
                    $InstanceDbs[$Server_Id][$dn] = 1
                }
            }

            $Entities_Before['DBN'] = @{}
            $Entities_Before['FGN'] = @{}
            $Entities_Before['LGN'] = @{}
            $Entities_Before['FNN'] = @{}
            $Entities_Before['DBN'][$db.Name] = $db.Name
            #region databasename
            if ($DatabaseName) {
                $Orig_DBName = $db.Name
                # fixed replacements
                $NewDBName = $DatabaseName.Replace('<DBN>', $Orig_DBName).Replace('<DATE>', $CurrentDate)
                if ($Orig_DBName -eq $NewDBName) {
                    Write-Message -Level VeryVerbose -Message "Database name unchanged, skipping"
                } else {
                    if ($InstanceDbs[$Server_Id].ContainsKey($NewDBName)) {
                        Write-Message -Level Warning -Message "Database $NewDBName exists already, skipping this rename"
                        $failed = $true
                    } else {
                        if ($PSCmdlet.ShouldProcess($db, "Renaming Database $db to $NewDBName")) {
                            if ($Force) {
                                $server.KillAllProcesses($Orig_DBName)
                            }
                            try {
                                if (!$Preview) {
                                    $db.Rename($NewDBName)
                                }
                                $InstanceDbs[$Server_Id].Remove($Orig_DBName)
                                $InstanceDbs[$Server_Id][$NewDBName] = 1
                                $Entities_Before['DBN'][$Orig_DBName] = $NewDBName
                                #$db.Refresh()
                            } catch {
                                Stop-Function -Message "Failed to rename Database : $($_.Exception.InnerException.InnerException.InnerException)" -ErrorRecord $_ -Target $server.DomainInstanceName -OverrideExceptionMessage
                                # stop any further renames
                                $failed = $true
                            }
                        }
                    }
                }
            }
            #endregion databasename
            #region filegroupname
            if ($ReplaceBefore) {
                #backfill PRIMARY
                $Entities_Before['FGN']['PRIMARY'] = 'PRIMARY'
                foreach ($fg in $db.FileGroups.Name) {
                    $Entities_Before['FGN'][$fg] = $fg
                }
            }

            if (!$failed -and $FileGroupName) {
                $Editable_FGs = $db.FileGroups | Where-Object Name -ne 'PRIMARY'
                $New_FGNames = @{}
                foreach ($fg in $db.FileGroups.Name) {
                    $New_FGNames[$fg] = 1
                }
                $FGCounter = 0
                foreach ($fg in $Editable_FGs) {
                    $Orig_FGName = $fg.Name
                    $Orig_Placeholder = $Orig_FGName
                    if ($ReplaceBefore) {
                        # at Filegroup level, we need to worry about database name
                        $Orig_Placeholder = $Orig_Placeholder.Replace($Entities_Before['DBN'][$Orig_DBName], '')
                    }
                    $NewFGName = $FileGroupName.Replace('<DBN>', $Entities_Before['DBN'][$db.Name]).Replace('<DATE>', $CurrentDate).Replace('<FGN>', $Orig_Placeholder)
                    $FinalFGName = $NewFGName
                    while ($fg.Name -ne $FinalFGName) {
                        if ($FinalFGName -in $New_FGNames.Keys) {
                            $FGCounter += 1
                            $FinalFGName = "$NewFGName$($FGCounter.ToString('000'))"
                        } else {
                            break
                        }
                    }
                    if ($fg.Name -eq $FinalFGName) {
                        Write-Message -Level VeryVerbose -Message "No rename necessary for FileGroup $($fg.Name) (on $db)"
                        continue
                    }
                    if ($PSCmdlet.ShouldProcess($db, "Renaming FileGroup $($fg.Name) to $FinalFGName")) {
                        try {
                            if (!$Preview) {
                                $fg.Rename($FinalFGName)
                            }
                            $New_FGNames.Remove($Orig_FGName)
                            $New_FGNames[$FinalFGName] = 1
                            $Entities_Before['FGN'][$Orig_FGName] = $FinalFGName
                        } catch {
                            Stop-Function -Message "Failed to rename FileGroup : $($_.Exception.InnerException.InnerException.InnerException)" -ErrorRecord $_ -Target $server.DomainInstanceName -OverrideExceptionMessage
                            # stop any further renames
                            $failed = $true
                            break
                        }
                    }
                }
                #$db.FileGroups.Refresh()
            }

            #endregion filegroupname
            #region logicalname
            if ($ReplaceBefore) {
                foreach ($fn in $db.FileGroups.Files.Name) {
                    $Entities_Before['LGN'][$fn] = $fn
                }
                foreach ($fn in $db.Logfiles.Name) {
                    $Entities_Before['LGN'][$fn] = $fn
                }
            }
            if (!$failed -and $LogicalName) {
                $New_LogicalNames = @{}
                foreach ($fn in $db.FileGroups.Files.Name) {
                    $New_LogicalNames[$fn] = 1
                }
                foreach ($fn in $db.Logfiles.Name) {
                    $New_LogicalNames[$fn] = 1
                }
                $LNCounter = 0
                foreach ($fg in $db.FileGroups) {
                    $logicalfiles = @($fg.Files)
                    for ($i = 0; $i -lt $logicalfiles.Count; $i++) {
                        $logical = $logicalfiles[$i]
                        $FileType = switch ($fg.FileGroupType) {
                            'RowsFileGroup' { 'ROWS' }
                            'MemoryOptimizedDataFileGroup' { 'MMO' }
                            'FileStreamDataFileGroup' { 'FS' }
                            default { 'STD' }
                        }
                        $Orig_LGName = $logical.Name
                        $Orig_Placeholder = $Orig_LGName
                        if ($ReplaceBefore) {
                            # at Logical Name level, we need to worry about database name and filegroup name
                            $Orig_Placeholder = $Orig_Placeholder.Replace((Get-DbaKeyByValue -HashTable $Entities_Before['DBN'] -Value $db.Name), '').Replace(
                                (Get-DbaKeyByValue -HashTable $Entities_Before['FGN'] -Value $fg.Name), '')
                        }
                        $NewLGName = $LogicalName.Replace('<DBN>', $db.Name).Replace('<DATE>', $CurrentDate).Replace('<FGN>', $fg.Name).Replace(
                            '<FT>', $FileType).Replace('<LGN>', $Orig_Placeholder)
                        $FinalLGName = $NewLGName
                        while ($logical.Name -ne $FinalLGName) {
                            if ($FinalLGName -in $New_LogicalNames.Keys) {
                                $LNCounter += 1
                                $FinalLGName = "$NewLGName$($LNCounter.ToString('000'))"
                            } else {
                                break
                            }
                        }
                        if ($logical.Name -eq $FinalLGName) {
                            Write-Message -Level VeryVerbose -Message "No rename necessary for LogicalFile $($logical.Name) (on FileGroup $($fg.Name) (on $db))"
                            continue
                        }
                        if ($PSCmdlet.ShouldProcess($db, "Renaming LogicalFile $($logical.Name) to $FinalLGName (on FileGroup $($fg.Name))")) {
                            try {
                                if (!$Preview) {
                                    $logical.Rename($FinalLGName)
                                }
                                $New_LogicalNames.Remove($Orig_LGName)
                                $New_LogicalNames[$FinalLGName] = 1
                                $Entities_Before['LGN'][$Orig_LGName] = $FinalLGName
                            } catch {
                                Stop-Function -Message "Failed to Rename Logical File : $($_.Exception.InnerException.InnerException.InnerException)" -ErrorRecord $_ -Target $server.DomainInstanceName -OverrideExceptionMessage
                                # stop any further renames
                                $failed = $true
                                break
                            }
                        }
                    }
                }
                #$fg.Files.Refresh()
                if (!$failed) {
                    $logfiles = @($db.LogFiles)
                    for ($i = 0; $i -lt $logfiles.Count; $i++) {
                        $logicallog = $logfiles[$i]
                        $Orig_LGName = $logicallog.Name
                        $Orig_Placeholder = $Orig_LGName
                        if ($ReplaceBefore) {
                            # at Logical Name level, we need to worry about database name and filegroup name, but for logfiles filegroup is not there
                            $Orig_Placeholder = $Orig_Placeholder.Replace((Get-DbaKeyByValue -HashTable $Entities_Before['DBN'] -Value $db.Name), '').Replace(
                                (Get-DbaKeyByValue -HashTable $Entities_Before['FGN'] -Value $fg.Name), '')
                        }
                        $NewLGName = $LogicalName.Replace('<DBN>', $db.Name).Replace('<DATE>', $CurrentDate).Replace('<FGN>', '').Replace(
                            '<FT>', 'LOG').Replace('<LGN>', $Orig_Placeholder)
                        $FinalLGName = $NewLGName
                        if ($FinalLGName.Length -eq 0) {
                            #someone passed in -LogicalName '<FGN>'.... but we don't have FGN here
                            $FinalLGName = $Orig_LGName
                        }
                        while ($logicallog.Name -ne $FinalLGName) {
                            if ($FinalLGName -in $New_LogicalNames.Keys) {
                                $LNCounter += 1
                                $FinalLGName = "$NewLGName$($LNCounter.ToString('000'))"
                            } else {
                                break
                            }
                        }
                        if ($logicallog.Name -eq $FinalLGName) {
                            Write-Message -Level VeryVerbose -Message "No Rename necessary for LogicalFile log $($logicallog.Name) (LOG on (on $db))"
                            continue
                        }
                        if ($PSCmdlet.ShouldProcess($db, "Renaming LogicalFile log $($logicallog.Name) to $FinalLGName (LOG)")) {
                            try {
                                if (!$Preview) {
                                    $logicallog.Rename($FinalLGName)
                                }
                                $New_LogicalNames.Remove($Orig_LGName)
                                $New_LogicalNames[$FinalLGName] = 1
                                $Entities_Before['LGN'][$Orig_LGName] = $FinalLGName
                            } catch {
                                Stop-Function -Message "Failed to Rename Logical File : $($_.Exception.InnerException.InnerException.InnerException)" -ErrorRecord $_ -Target $server.DomainInstanceName -OverrideExceptionMessage
                                # stop any further renames
                                $failed = $true
                                break
                            }
                        }
                    }
                    #$db.Logfiles.Refresh()
                }
            }
            #endregion logicalname
            #region filename
            if ($ReplaceBefore) {
                foreach ($fn in $db.FileGroups.Files.FileName) {
                    $Entities_Before['FNN'][$fn] = $fn
                }
                foreach ($fn in $db.Logfiles.FileName) {
                    $Entities_Before['FNN'][$fn] = $fn
                }
            }
            if (!$failed -and $FileName) {

                $New_FileNames = @{}
                foreach ($fn in $db.FileGroups.Files.FileName) {
                    $New_FileNames[$fn] = 1
                }
                foreach ($fn in $db.Logfiles.FileName) {
                    $New_FileNames[$fn] = 1
                }
                # we need to inspect what files are in the same directory
                # to avoid failing the process because the move won't work
                # here we have a dict keyed by instance and then keyed by path
                if ( !$InstanceFiles.ContainsKey($Server_Id) ) {
                    $InstanceFiles[$Server_Id] = @{}
                }
                foreach ($fn in $New_FileNames.Keys) {
                    $dirname = [IO.Path]::GetDirectoryName($fn)
                    if ( !$InstanceFiles[$Server_Id].ContainsKey($dirname) ) {
                        $InstanceFiles[$Server_Id][$dirname] = @{}
                        try {
                            $dirfiles = Get-DbaFile -SqlInstance $server -Path $dirname -EnableException
                        } catch {
                            Write-Message -Level Warning -Message "Failed to enumerate existing files at $dirname, move could go wrong"
                        }
                        foreach ($f in $dirfiles) {
                            $InstanceFiles[$Server_Id][$dirname][$f.Filename] = 1
                        }
                    }
                }
                $FNCounter = 0
                foreach ($fg in $db.FileGroups) {
                    $FG_Files = @($fg.Files)
                    foreach ($logical in $FG_Files) {
                        $FileType = switch ($fg.FileGroupType) {
                            'RowsFileGroup' { 'ROWS' }
                            'MemoryOptimizedDataFileGroup' { 'MMO' }
                            'FileStreamDataFileGroup' { 'FS' }
                            default { 'STD' }
                        }
                        $FNName = $logical.FileName
                        $FNNameDir = [IO.Path]::GetDirectoryName($FNName)
                        $Orig_FNNameLeaf = [IO.Path]::GetFileNameWithoutExtension($logical.FileName)
                        $Orig_Placeholder = $Orig_FNNameLeaf
                        if ($ReplaceBefore) {
                            # at Filename level, we need to worry about database name, filegroup name and logical file name
                            $Orig_Placeholder = $Orig_Placeholder.Replace((Get-DbaKeyByValue -HashTable $Entities_Before['DBN'] -Value $db.Name), '').Replace(
                                (Get-DbaKeyByValue -HashTable $Entities_Before['FGN'] -Value $fg.Name), '').Replace(
                                (Get-DbaKeyByValue -HashTable $Entities_Before['LGN'] -Value $logical.Name), '')
                        }
                        $NewFNName = $FileName.Replace('<DBN>', $db.Name).Replace('<DATE>', $CurrentDate).Replace('<FGN>', $fg.Name).Replace(
                            '<FT>', $FileType).Replace('<LGN>', $logical.Name).Replace('<FNN>', $Orig_Placeholder)
                        $FinalFNName = [IO.Path]::Combine($FNNameDir, "$NewFNName$([IO.Path]::GetExtension($FNName))")

                        while ($logical.FileName -ne $FinalFNName) {
                            if ($InstanceFiles[$Server_Id][$FNNameDir].ContainsKey($FinalFNName)) {
                                $FNCounter += 1
                                $FinalFNName = [IO.Path]::Combine($FNNameDir, "$NewFNName$($FNCounter.ToString('000'))$([IO.Path]::GetExtension($FNName))"
                                )
                            } else {
                                break
                            }
                        }
                        if ($logical.FileName -eq $FinalFNName) {
                            Write-Message -Level VeryVerbose -Message "No rename necessary (on FileGroup $($fg.Name) (on $db))"
                            continue
                        }
                        if ($PSCmdlet.ShouldProcess($db, "Renaming FileName $($logical.FileName) to $FinalFNName (on FileGroup $($fg.Name))")) {
                            try {
                                if (!$Preview) {
                                    $logical.FileName = $FinalFNName
                                    $db.Alter()
                                }
                                $InstanceFiles[$Server_Id][$FNNameDir].Remove($FNName)
                                $InstanceFiles[$Server_Id][$FNNameDir][$FinalFNName] = 1
                                $Entities_Before['FNN'][$FNName] = $FinalFNName
                                $Pending_Renames += [pscustomobject]@{
                                    Source      = $FNName
                                    Destination = $FinalFNName
                                }
                            } catch {
                                Stop-Function -Message "Failed to Rename FileName : $($_.Exception.InnerException.InnerException.InnerException)" -ErrorRecord $_ -Target $server.DomainInstanceName -OverrideExceptionMessage
                                # stop any further renames
                                $failed = $true
                                break
                            }
                        }
                    }
                    if (!$failed) {
                        $FG_Files = @($db.Logfiles)
                        foreach ($logical in $FG_Files) {
                            $FNName = $logical.FileName
                            $FNNameDir = [IO.Path]::GetDirectoryName($FNName)
                            $Orig_FNNameLeaf = [IO.Path]::GetFileNameWithoutExtension($logical.FileName)
                            $Orig_Placeholder = $Orig_FNNameLeaf
                            if ($ReplaceBefore) {
                                # at Filename level, we need to worry about database name, filegroup name and logical file name
                                $Orig_Placeholder = $Orig_Placeholder.Replace((Get-DbaKeyByValue -HashTable $Entities_Before['DBN'] -Value $db.Name), '').Replace(
                                    (Get-DbaKeyByValue -HashTable $Entities_Before['FGN'] -Value $fg.Name), '').Replace(
                                    (Get-DbaKeyByValue -HashTable $Entities_Before['LGN'] -Value $logical.Name), '')
                            }
                            $NewFNName = $FileName.Replace('<DBN>', $db.Name).Replace('<DATE>', $CurrentDate).Replace('<FGN>', '').Replace(
                                '<FT>', 'LOG').Replace('<LGN>', $logical.Name).Replace('<FNN>', $Orig_Placeholder)
                            $FinalFNName = [IO.Path]::Combine($FNNameDir, "$NewFNName$([IO.Path]::GetExtension($FNName))")
                            while ($logical.FileName -ne $FinalFNName) {
                                if ($InstanceFiles[$Server_Id][$FNNameDir].ContainsKey($FinalFNName)) {
                                    $FNCounter += 1
                                    $FinalFNName = [IO.Path]::Combine($FNNameDir, "$NewFNName$($FNCounter.ToString('000'))$([IO.Path]::GetExtension($FNName))")
                                } else {
                                    break
                                }
                            }
                            if ($logical.FileName -eq $FinalFNName) {
                                Write-Message -Level VeryVerbose -Message "No rename necessary for $($logical.FileName) (LOG on (on $db))"
                                continue
                            }

                            if ($PSCmdlet.ShouldProcess($db, "Renaming FileName $($logical.FileName) to $FinalFNName (LOG)")) {
                                try {
                                    if (!$Preview) {
                                        $logical.FileName = $FinalFNName
                                        $db.Alter()
                                    }
                                    $InstanceFiles[$Server_Id][$FNNameDir].Remove($FNName)
                                    $InstanceFiles[$Server_Id][$FNNameDir][$FinalFNName] = 1
                                    $Entities_Before['FNN'][$FNName] = $FinalFNName
                                    $Pending_Renames += [pscustomobject]@{
                                        Source      = $FNName
                                        Destination = $FinalFNName
                                    }
                                } catch {
                                    Stop-Function -Message "Failed to Rename FileName : $($_.Exception.InnerException.InnerException.InnerException)" -ErrorRecord $_ -Target $server.DomainInstanceName -OverrideExceptionMessage
                                    # stop any further renames
                                    $failed = $true
                                    break
                                }
                            }
                        }
                    }

                }
                #endregion filename
                #region move
                $ComputerName = $null
                $Final_Renames = New-Object System.Collections.ArrayList
                if ([DbaValidate]::IsLocalhost($server.ComputerName)) {
                    # locally ran so we can just use rename-item
                    $ComputerName = $server.ComputerName
                } else {
                    # let's start checking if we can access .ComputerName
                    $testPS = $false
                    if ($SqlCredential) {
                        # why does Test-PSRemoting require a Credential param ? this is ugly...
                        $testPS = Test-PSRemoting -ComputerName $server.ComputerName -Credential $SqlCredential -ErrorAction Stop
                    } else {
                        $testPS = Test-PSRemoting -ComputerName $server.ComputerName -ErrorAction Stop
                    }
                    if (!($testPS)) {
                        # let's try to resolve it to a more qualified name, without "cutting" knowledge about the domain (only $server.Name possibly holds the complete info)
                        $Resolved = (Resolve-DbaNetworkName -ComputerName $server.Name).FullComputerName
                        if ($SqlCredential) {
                            $testPS = Test-PSRemoting -ComputerName $Resolved -Credential $SqlCredential -ErrorAction Stop
                        } else {
                            $testPS = Test-PSRemoting -ComputerName $Resolved -ErrorAction Stop
                        }
                        if ($testPS) {
                            $ComputerName = $Resolved
                        }
                    } else {
                        $ComputerName = $server.ComputerName
                    }
                }
                foreach ($op in $pending_renames) {
                    if ([DbaValidate]::IsLocalhost($server.ComputerName)) {
                        $null = $Final_Renames.Add([pscustomobject]@{
                                Source       = $op.Source
                                Destination  = $op.Destination
                                ComputerName = $ComputerName
                            })
                    } else {
                        if ($null -eq $ComputerName) {
                            # if we don't have remote access ($ComputerName is null) we can fallback to admin shares if they're available
                            if (Test-Path (Join-AdminUnc -ServerName $server.ComputerName -filepath $op.Source)) {
                                $null = $Final_Renames.Add([pscustomobject]@{
                                        Source       = Join-AdminUnc -ServerName $server.ComputerName -filepath $op.Source
                                        Destination  = Join-AdminUnc -ServerName $server.ComputerName -filepath $op.Destination
                                        ComputerName = $server.ComputerName
                                    })
                            } else {
                                # flag the impossible rename ($ComputerName is $null)
                                $null = $Final_Renames.Add([pscustomobject]@{
                                        Source       = $op.Source
                                        Destination  = $op.Destination
                                        ComputerName = $ComputerName
                                    })
                            }
                        } else {
                            # we can do renames in a remote pssession
                            $null = $Final_Renames.Add([pscustomobject]@{
                                    Source       = $op.Source
                                    Destination  = $op.Destination
                                    ComputerName = $ComputerName
                                })
                        }
                    }
                }
                $Status = 'FULL'
                if (!$failed -and ($SetOffline -or $Move) -and $Final_Renames) {
                    if (!$Move) {
                        Write-Message -Level VeryVerbose -Message "Setting the database offline. You are in charge of moving the files to the new location"
                        # because renames still need to be dealt with
                        $Status = 'PARTIAL'
                    } else {
                        if ($PSCmdlet.ShouldProcess($db, "File Rename required, setting db offline")) {
                            $SetState = Set-DbaDbState -SqlInstance $server -Database $db.Name -Offline -Force
                            if ($SetState.Status -ne 'OFFLINE') {
                                Write-Message -Level Warning -Message "Setting db offline failed, You are in charge of moving the files to the new location"
                                # because it was impossible to set the database offline
                                $Status = 'PARTIAL'
                            } else {
                                try {
                                    while ($Final_Renames.Count -gt 0) {
                                        $op = $Final_Renames.Item(0)
                                        if ($null -eq $op.ComputerName) {
                                            Stop-Function -Message "No access to physical files for renames"
                                        } else {
                                            Write-Message -Level VeryVerbose -Message "Moving file $($op.Source) to $($op.Destination)"
                                            if (!$Preview) {
                                                $scriptblock = {
                                                    $op = $args[0]
                                                    Rename-Item -Path $op.Source -NewName $op.Destination
                                                }
                                                Invoke-Command2 -ComputerName $op.ComputerName -Credential $sqlCredential -ScriptBlock $scriptblock -ArgumentList $op
                                            }
                                        }
                                        $null = $Final_Renames.RemoveAt(0)
                                    }
                                } catch {
                                    $failed = $true
                                    # because a rename operation failed
                                    $Status = 'PARTIAL'
                                    Stop-Function -Message "Failed to rename $($op.Source) to $($op.Destination), you are in charge of moving the files to the new location" -ErrorRecord $_ -Target $instance -Exception $_.Exception -Continue
                                }
                                if (!$failed) {
                                    if ($PSCmdlet.ShouldProcess($db, "Setting database online")) {
                                        $SetState = Set-DbaDbState -SqlInstance $server -Database $db.Name -Online -Force
                                        if ($SetState.Status -ne 'ONLINE') {
                                            Write-Message -Level Warning -Message "Setting db online failed"
                                            # because renames were done, but the database didn't wake up
                                            $Status = 'PARTIAL'
                                        } else {
                                            $Status = 'FULL'
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    # because of a previous error with renames to do
                    $Status = 'PARTIAL'
                }
            } else {
                if (!$failed) {
                    # because no previous error and not filename
                    $Status = 'FULL'
                } else {
                    # because previous errors and not filename
                    $Status = 'PARTIAL'
                }
            }
            #endregion move
            # remove entities that match for the output
            foreach ($k in $Entities_Before.Keys) {
                $ToRemove = $Entities_Before[$k].GetEnumerator() | Where-Object { $_.Name -eq $_.Value } | Select-Object -ExpandProperty Name
                foreach ($el in $ToRemove) {
                    $Entities_Before[$k].Remove($el)
                }
            }
            [pscustomobject]@{
                ComputerName       = $server.ComputerName
                InstanceName       = $server.ServiceName
                SqlInstance        = $server.DomainInstanceName
                Database           = $db
                DBN                = $Entities_Before['DBN']
                DatabaseRenames    = ($Entities_Before['DBN'].GetEnumerator() | Foreach-Object { "$($_.Name) --> $($_.Value)" }) -Join "`n"
                FGN                = $Entities_Before['FGN']
                FileGroupsRenames  = ($Entities_Before['FGN'].GetEnumerator() | Foreach-Object { "$($_.Name) --> $($_.Value)" }) -Join "`n"
                LGN                = $Entities_Before['LGN']
                LogicalNameRenames = ($Entities_Before['LGN'].GetEnumerator() | Foreach-Object { "$($_.Name) --> $($_.Value)"  }) -Join "`n"
                FNN                = $Entities_Before['FNN']
                FileNameRenames    = ($Entities_Before['FNN'].GetEnumerator() | Foreach-Object { "$($_.Name) --> $($_.Value)"  }) -Join "`n"
                PendingRenames     = $Final_Renames
                Status             = $Status
            } | Select-DefaultView -ExcludeProperty DatabaseRenames, FileGroupsRenames, LogicalNameRenames, FileNameRenames
        }
        #endregion db loop
    }
}
tools\dbatools\functions\Rename-DbaLogin.ps1
function Rename-DbaLogin {
    <#
    .SYNOPSIS
        Rename-DbaLogin will rename login and database mapping for a specified login.

    .DESCRIPTION
        There are times where you might want to rename a login that was copied down, or if the name is not descriptive for what it does.

        It can be a pain to update all of the mappings for a specific user, this does it for you.

    .PARAMETER SqlInstance
        Source SQL Server.You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER Destination
        Destination Sql Server. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Login
        The current Login on the server - this list is auto-populated from the server.

    .PARAMETER NewLogin
        The new Login that you wish to use. If it is a windows user login, then the SID must match.

    .PARAMETER Confirm
        Prompts to confirm actions

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Login
        Author: Mitchell Hamann (@SirCaptainMitch)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Rename-DbaLogin

    .EXAMPLE
        PS C:\>Rename-DbaLogin -SqlInstance localhost -Login DbaToolsUser -NewLogin captain

        SQL Login Example

    .EXAMPLE
        PS C:\>Rename-DbaLogin -SqlInstance localhost -Login domain\oldname -NewLogin domain\newname

        Change the windowsuser login name.

    .EXAMPLE
        PS C:\>Rename-DbaLogin -SqlInstance localhost -Login dbatoolsuser -NewLogin captain -WhatIf

        WhatIf Example

          #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(Mandatory)]
        [string]$Login,
        [parameter(Mandatory)]
        [string]$NewLogin,
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $Databases = $server.Databases | Where-Object IsAccessible
            $currentLogin = $server.Logins[$Login]

            if ($Pscmdlet.ShouldProcess($SqlInstance, "Changing Login name from  [$Login] to [$NewLogin]")) {
                try {
                    $dbenums = $currentLogin.EnumDatabaseMappings()
                    $currentLogin.rename($NewLogin)
                    [pscustomobject]@{
                        ComputerName  = $server.ComputerName
                        InstanceName  = $server.ServiceName
                        SqlInstance   = $server.DomainInstanceName
                        Database      = $null
                        PreviousLogin = $Login
                        NewLogin      = $NewLogin
                        Status        = "Successful"
                    }
                } catch {
                    $dbenums = $null
                    [pscustomobject]@{
                        ComputerName  = $server.ComputerName
                        InstanceName  = $server.ServiceName
                        SqlInstance   = $server.DomainInstanceName
                        Database      = $null
                        PreviousLogin = $Login
                        NewLogin      = $NewLogin
                        Status        = "Failure"
                    }
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target $login
                }
            }

            foreach ($db in $dbenums) {
                $db = $databases[$db.DBName]
                $user = $db.Users[$Login]
                Write-Message -Level Verbose -Message "Starting update for $db"

                if ($Pscmdlet.ShouldProcess($SqlInstance, "Changing database $db user $user from [$Login] to [$NewLogin]")) {
                    try {
                        $oldname = $user.name
                        $user.Rename($NewLogin)
                        [pscustomobject]@{
                            ComputerName = $server.ComputerName
                            InstanceName = $server.ServiceName
                            SqlInstance  = $server.DomainInstanceName
                            Database     = $db.name
                            PreviousUser = $oldname
                            NewUser      = $NewLogin
                            Status       = "Successful"
                        }

                    } catch {
                        Write-Message -Level Warning -Message "Rolling back update to login: $Login"
                        $currentLogin.rename($Login)

                        [pscustomobject]@{
                            ComputerName = $server.ComputerName
                            InstanceName = $server.ServiceName
                            SqlInstance  = $server.DomainInstanceName
                            Database     = $db.name
                            PreviousUser = $NewLogin
                            NewUser      = $oldname
                            Status       = "Failure to rename. Rolled back change."
                        }
                        Stop-Function -Message "Failure" -ErrorRecord $_ -Target $NewLogin
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Repair-DbaDbMirror.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Repair-DbaDbMirror {
    <#
    .SYNOPSIS
        Attempts to repair a suspended or paused mirroring database.

    .DESCRIPTION
        Attempts to repair a suspended mirroring database.

        Restarts the endpoints then sets the partner to resume. See this article for more info:

        http://www.sqlservercentral.com/blogs/vivekssqlnotes/2016/09/03/how-to-resume-suspended-database-mirroring-in-sql-server-/

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function
        to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The target database.

    .PARAMETER InputObject
        Allows piping from Get-DbaDatabase.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Mirror, HA
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Repair-DbaDbMirror

    .EXAMPLE
        PS C:\> Repair-DbaDbMirror -SqlInstance sql2017 -Database pubs

        Attempts to repair the mirrored but suspended pubs database on sql2017.
        Restarts the endpoints then sets the partner to resume. Prompts for confirmation.

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sql2017 -Database pubs | Repair-DbaDbMirror -Confirm:$false

        Attempts to repair the mirrored but suspended pubs database on sql2017.
        Restarts the endpoints then sets the partner to resume. Does not prompt for confirmation.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ((Test-Bound -ParameterName SqlInstance) -and (Test-Bound -Not -ParameterName Database)) {
            Stop-Function -Message "Database is required when SqlInstance is specified"
            return
        }
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $instance -SqlCredential $SqlCredential -Database $Database
        }

        foreach ($db in $InputObject) {
            try {
                Get-DbaEndpoint -SqlInstance $db.Parent | Where-Object EndpointType -eq DatabaseMirroring | Stop-DbaEndPoint
                Get-DbaEndpoint -SqlInstance $db.Parent | Where-Object EndpointType -eq DatabaseMirroring | Start-DbaEndPoint
                $db | Set-DbaDbMirror -State Resume
                if ($Pscmdlet.ShouldProcess("console", "displaying output")) {
                    $db
                }
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_
            }
        }
    }
}
tools\dbatools\functions\Repair-DbaDbOrphanUser.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Repair-DbaDbOrphanUser {
    <#
    .SYNOPSIS
        Finds orphan users with existing login and remaps them.

    .DESCRIPTION
        An orphan user is defined by a user that does not have a matching login (Login property = "").

        If the matching login exists it must be:
        Enabled
        Not a system object
        Not locked
        Have the same name that user

        You can drop users that does not have their matching login by specifying the parameter -RemoveNotExisting.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server

    .PARAMETER Users
        Specifies the list of usernames to repair.

    .PARAMETER Force
        Forces alter schema to dbo owner so users can be dropped.

    .PARAMETER RemoveNotExisting
        If this switch is enabled, all users that do not have a matching login will be dropped from the database.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Orphan
        Author: Claudio Silva (@ClaudioESSilva) | Simone Bizzotto (@niphlod)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Repair-DbaDbOrphanUser

    .EXAMPLE
        PS C:\> Repair-DbaDbOrphanUser -SqlInstance sql2005

        Finds and repairs all orphan users of all databases present on server 'sql2005'

    .EXAMPLE
        PS C:\> Repair-DbaDbOrphanUser -SqlInstance sqlserver2014a -SqlCredential $cred

        Finds and repair all orphan users in all databases present on server 'sqlserver2014a'. SQL credentials are used to authenticate to the server.

    .EXAMPLE
        PS C:\> Repair-DbaDbOrphanUser -SqlInstance sqlserver2014a -Database db1, db2

        Finds and repairs all orphan users in both db1 and db2 databases.

    .EXAMPLE
        PS C:\> Repair-DbaDbOrphanUser -SqlInstance sqlserver2014a -Database db1 -Users OrphanUser

        Finds and repairs user 'OrphanUser' in 'db1' database.

    .EXAMPLE
        PS C:\> Repair-DbaDbOrphanUser -SqlInstance sqlserver2014a -Users OrphanUser

        Finds and repairs user 'OrphanUser' on all databases

    .EXAMPLE
        PS C:\> Repair-DbaDbOrphanUser -SqlInstance sqlserver2014a -RemoveNotExisting

        Finds all orphan users of all databases present on server 'sqlserver2014a'. Removes all users that do not have  matching Logins.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [parameter(ValueFromPipeline)]
        [object[]]$Users,
        [switch]$RemoveNotExisting,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {

        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Write-Message -Level Warning -Message "Failed to connect to: $SqlInstance."
                continue
            }

            $DatabaseCollection = $server.Databases | Where-Object IsAccessible

            if ($Database) {
                $DatabaseCollection = $DatabaseCollection | Where-Object Name -In $Database
            }
            if ($ExcludeDatabase) {
                $DatabaseCollection = $DatabaseCollection | Where-Object Name -NotIn $ExcludeDatabase
            }

            if ($DatabaseCollection.Count -gt 0) {
                foreach ($db in $DatabaseCollection) {
                    try {
                        #if SQL 2012 or higher only validate databases with ContainmentType = NONE
                        if ($server.versionMajor -gt 10) {
                            if ($db.ContainmentType -ne [Microsoft.SqlServer.Management.Smo.ContainmentType]::None) {
                                Write-Message -Level Warning -Message "Database '$db' is a contained database. Contained databases can't have orphaned users. Skipping validation."
                                Continue
                            }
                        }

                        Write-Message -Level Verbose -Message "Validating users on database '$db'."

                        if ($Users.Count -eq 0) {
                            #the third validation will remove from list sql users without login. The rule here is Sid with length higher than 16
                            $UsersToWork = $db.Users | Where-Object { $_.Login -eq "" -and ($_.ID -gt 4) -and (($_.Sid.Length -gt 16 -and $_.LoginType -in @([Microsoft.SqlServer.Management.Smo.LoginType]::SqlLogin, [Microsoft.SqlServer.Management.Smo.LoginType]::Certificate)) -eq $false) }
                        } else {
                            #the fourth validation will remove from list sql users without login. The rule here is Sid with length higher than 16
                            $UsersToWork = $db.Users | Where-Object { $_.Login -eq "" -and ($_.ID -gt 4) -and ($Users -contains $_.Name) -and (($_.Sid.Length -gt 16 -and $_.LoginType -in @([Microsoft.SqlServer.Management.Smo.LoginType]::SqlLogin, [Microsoft.SqlServer.Management.Smo.LoginType]::Certificate)) -eq $false) }
                        }

                        if ($UsersToWork.Count -gt 0) {
                            Write-Message -Level Verbose -Message "Orphan users found"
                            $UsersToRemove = @()
                            foreach ($User in $UsersToWork) {
                                $ExistLogin = $server.logins | Where-Object {
                                    $_.Isdisabled -eq $False -and
                                    $_.IsSystemObject -eq $False -and
                                    $_.IsLocked -eq $False -and
                                    $_.Name -eq $User.Name
                                }

                                if ($ExistLogin) {
                                    if ($server.versionMajor -gt 8) {
                                        $query = "ALTER USER " + $User + " WITH LOGIN = " + $User
                                    } else {
                                        $query = "exec sp_change_users_login 'update_one', '$User'"
                                    }

                                    if ($Pscmdlet.ShouldProcess($db.Name, "Mapping user '$($User.Name)'")) {
                                        $server.Databases[$db.Name].ExecuteNonQuery($query) | Out-Null
                                        Write-Message -Level Verbose -Message "User '$($User.Name)' mapped with their login."

                                        [PSCustomObject]@{
                                            ComputerName = $server.ComputerName
                                            InstanceName = $server.ServiceName
                                            SqlInstance  = $server.DomainInstanceName
                                            DatabaseName = $db.Name
                                            User         = $User.Name
                                            Status       = "Success"
                                        }
                                    }
                                } else {
                                    if ($RemoveNotExisting) {
                                        #add user to collection
                                        $UsersToRemove += $User
                                    } else {
                                        Write-Message -Level Verbose -Message "Orphan user $($User.Name) does not have matching login."
                                        [PSCustomObject]@{
                                            ComputerName = $server.ComputerName
                                            InstanceName = $server.ServiceName
                                            SqlInstance  = $server.DomainInstanceName
                                            DatabaseName = $db.Name
                                            User         = $User.Name
                                            Status       = "No matching login"
                                        }
                                    }
                                }
                            }

                            #With the collection complete invoke remove.
                            if ($RemoveNotExisting) {
                                if ($Force) {
                                    if ($Pscmdlet.ShouldProcess($db.Name, "Remove-DbaDbOrphanUser")) {
                                        Write-Message -Level Verbose -Message "Calling 'Remove-DbaDbOrphanUser' with -Force."
                                        Remove-DbaDbOrphanUser -SqlInstance $server -Database $db.Name -User $UsersToRemove -Force
                                    }
                                } else {
                                    if ($Pscmdlet.ShouldProcess($db.Name, "Remove-DbaDbOrphanUser")) {
                                        Write-Message -Level Verbose -Message "Calling 'Remove-DbaDbOrphanUser'."
                                        Remove-DbaDbOrphanUser -SqlInstance $server -Database $db.Name -User $UsersToRemove
                                    }
                                }
                            }
                        } else {
                            Write-Message -Level Verbose -Message "No orphan users found on database '$db'."
                        }
                        #reset collection
                        $UsersToWork = $null
                    } catch {
                        Stop-Function -Message $_ -Continue
                    }
                }
            } else {
                Write-Message -Level Verbose -Message "There are no databases to analyse."
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Alias Repair-DbaOrphanUser
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Alias Repair-SqlOrphanUser
    }
}
tools\dbatools\functions\Repair-DbaServerName.ps1
function Repair-DbaServerName {
    <#
    .SYNOPSIS
        Renames @@SERVERNAME to match with the Windows name.

    .DESCRIPTION
        When a SQL Server's host OS is renamed, the SQL Server should be as well. This helps with Availability Groups and Kerberos.

        This command renames @@SERVERNAME to match with the Windows name. The new name is automatically determined. It does not matter if you use an alias to connect to the SQL instance.

        If the automatically determined new name matches the old name, the command will not run.

        https://www.mssqltips.com/sqlservertip/2525/steps-to-change-the-server-name-for-a-sql-server-machine/

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER AutoFix
        If this switch is enabled, the repair will be performed automatically.

    .PARAMETER Force
        If this switch is enabled, most confirmation prompts will be skipped.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .NOTES
        Tags: SPN
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Repair-DbaServerName

    .EXAMPLE
        PS C:\> Repair-DbaServerName -SqlInstance sql2014

        Checks to see if the server name is updatable and changes the name with a number of prompts.

    .EXAMPLE
        PS C:\> Repair-DbaServerName -SqlInstance sql2014 -AutoFix

        Checks to see if the server name is updatable and automatically performs the change. Replication or mirroring will be broken if necessary.

    .EXAMPLE
        PS C:\> Repair-DbaServerName -SqlInstance sql2014 -AutoFix -Force

        Checks to see if the server name is updatable and automatically performs the change, bypassing most prompts and confirmations. Replication or mirroring will be broken if necessary.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [switch]$AutoFix,
        [switch]$Force,
        [switch][Alias('Silent')]
        $EnableException
    )

    begin {
        if ($Force -eq $true) {
            $ConfirmPreference = "None"
        }
    }

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($server.isClustered) {
                Write-Message -Level Warning -Message "$instance is a cluster. Microsoft does not support renaming clusters."
                continue
            }


            # Check to see if we can easily proceed

            $nametest = Test-DbaServerName $server -EnableException | Select-Object *
            $oldserverinstancename = $nametest.ServerName
            $SqlInstancename = $nametest.SqlInstance

            if ($nametest.RenameRequired -eq $false) {
                Stop-Function -Continue -Message "Good news! $oldserverinstancename's @@SERVERNAME does not need to be changed. If you'd like to rename it, first rename the Windows server."
            }

            if (-not $nametest.updatable) {
                Write-Message -Level Output -Message "Test-DbaServerName reports that the rename cannot proceed with a rename in this $instance's current state."

                foreach ($nametesterror in $nametest.Blockers) {
                    if ($nametesterror -like '*replication*') {

                        if (-not $AutoFix) {
                            Stop-Function -Message "Cannot proceed because some databases are involved in replication. You can run exec sp_dropdistributor @no_checks = 1 but that may be pretty dangerous. Alternatively, you can run -AutoFix to automatically fix this issue. AutoFix will also break all database mirrors."
                            return
                        } else {
                            if ($Pscmdlet.ShouldProcess("console", "Prompt will appear for confirmation to break replication.")) {
                                $title = "You have chosen to AutoFix the blocker: replication."
                                $message = "We can run sp_dropdistributor which will pretty much destroy replication on this server. Do you wish to continue? (Y/N)"
                                $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Will continue"
                                $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Will exit"
                                $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
                                $result = $host.ui.PromptForChoice($title, $message, $options, 1)

                                if ($result -eq 1) {
                                    Stop-Function -Message "Failure" -Target $server -ErrorRecord $_ -Continue
                                } else {
                                    Write-Message -Level Output -Message "`nPerforming sp_dropdistributor @no_checks = 1."
                                    $sql = "sp_dropdistributor @no_checks = 1"
                                    Write-Message -Level Debug -Message $sql
                                    try {
                                        $null = $server.Query($sql)
                                    } catch {
                                        Stop-Function -Message "Failure" -Target $server -ErrorRecord $_ -Continue
                                    }
                                }
                            }
                        }
                    } elseif ($Error -like '*mirror*') {
                        if ($AutoFix -eq $false) {
                            Stop-Function -Message "Cannot proceed because some databases are being mirrored. Stop mirroring to proceed. Alternatively, you can run -AutoFix to automatically fix this issue. AutoFix will also stop replication." -Continue
                        } else {
                            if ($Pscmdlet.ShouldProcess("console", "Prompt will appear for confirmation to break replication.")) {
                                $title = "You have chosen to AutoFix the blocker: mirroring."
                                $message = "We can run sp_dropdistributor which will pretty much destroy replication on this server. Do you wish to continue? (Y/N)"
                                $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Will continue"
                                $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Will exit"
                                $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
                                $result = $host.ui.PromptForChoice($title, $message, $options, 1)

                                if ($result -eq 1) {
                                    Write-Message -Level Output -Message "Okay, moving on."
                                } else {
                                    Write-Message -Level Verbose -Message "Removing Mirroring"

                                    foreach ($database in $server.Databases) {
                                        if ($database.IsMirroringEnabled) {
                                            $dbname = $database.name

                                            try {
                                                Write-Message -Level Verbose -Message "Breaking mirror for $dbname."
                                                $database.ChangeMirroringState([Microsoft.SqlServer.Management.Smo.MirroringOption]::Off)
                                                $database.Alter()
                                                $database.Refresh()
                                            } catch {
                                                Stop-Function -Message "Failure" -Target $server -ErrorRecord $_
                                                return
                                                #throw "Could not break mirror for $dbname. Skipping."
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            # ^ That's embarrassing

            $instancename = $server.InstanceName

            if (-not $instancename) {
                $instancename = "MSSQLSERVER"
            }

            try {
                $allsqlservices = Get-Service -ComputerName $instance.ComputerName -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -like "SQL*$instancename*" -and $_.Status -eq "Running" }
            } catch {
                Write-Message -Level Warning -Message "Can't contact $instance using Get-Service. This means the script will not be able to automatically restart SQL services."
            }

            if ($nametest.Warnings.length -gt 0) {
                $reportingservice = Get-Service -ComputerName $instance.ComputerName -DisplayName "SQL Server Reporting Services ($instancename)" -ErrorAction SilentlyContinue

                if ($reportingservice.Status -eq "Running") {
                    if ($Pscmdlet.ShouldProcess($server.name, "Reporting Services is running for this instance. Would you like to automatically stop this service?")) {
                        $reportingservice | Stop-Service
                        Write-Message -Level Warning -Message "You must reconfigure Reporting Services using Reporting Services Configuration Manager or PowerShell once the server has been successfully renamed."
                    }
                }
            }

            if ($Pscmdlet.ShouldProcess($server.name, "Performing sp_dropserver to remove the old server name, $oldserverinstancename, then sp_addserver to add $SqlInstancename")) {
                $sql = "sp_dropserver '$oldserverinstancename'"
                Write-Message -Level Debug -Message $sql
                try {
                    $null = $server.Query($sql)
                } catch {
                    Stop-Function -Message "Failure" -Target $server -ErrorRecord $_
                    return
                }

                $sql = "sp_addserver '$SqlInstancename', local"
                Write-Message -Level Debug -Message $sql

                try {
                    $null = $server.Query($sql)
                } catch {
                    Stop-Function -Message "Failure" -Target $server -ErrorRecord $_
                    return
                }
                $renamed = $true
            }

            if ($null -eq $allsqlservices) {
                Write-Message -Level Warning -Message "Could not contact $($instance.ComputerName) using Get-Service. You must manually restart the SQL Server instance."
                $needsrestart = $true
            } else {
                if ($Pscmdlet.ShouldProcess($instance.ComputerName, "Rename complete! The SQL Service must be restarted to commit the changes. Would you like to restart the $instancename instance now?")) {
                    try {
                        Write-Message -Level Verbose -Message "Stopping SQL Services for the $instancename instance"
                        $allsqlservices | Stop-Service -Force -WarningAction SilentlyContinue # because it reports the wrong name
                        Write-Message -Level Verbose -Message "Starting SQL Services for the $instancename instance."
                        $allsqlservices | Where-Object { $_.DisplayName -notlike "*reporting*" } | Start-Service -WarningAction SilentlyContinue # because it reports the wrong name
                    } catch {
                        Stop-Function -Message "Failure" -Target $server -ErrorRecord $_ -Continue
                    }
                }
            }

            if ($renamed -eq $true) {
                Write-Message -Level Verbose -Message "$instance successfully renamed from $oldserverinstancename to $SqlInstancename."
                Test-DbaServerName -SqlInstance $server
            }

            if ($needsrestart -eq $true) {
                Write-Message -Level Warning -Message "SQL Service restart for $SqlInstancename still required."
            }
        }
    }
}
tools\dbatools\functions\Reset-DbaAdmin.ps1
function Reset-DbaAdmin {
    <#
    .SYNOPSIS
        This function allows administrators to regain access to SQL Servers in the event that passwords or access was lost.

        Supports SQL Server 2005 and above. Windows administrator access is required.

    .DESCRIPTION
        This function allows administrators to regain access to local or remote SQL Servers by either resetting the sa password, adding the sysadmin role to existing login, or adding a new login (SQL or Windows) and granting it sysadmin privileges.

        This is accomplished by stopping the SQL services or SQL Clustered Resource Group, then restarting SQL via the command-line using the /mReset-DbaAdmin parameter which starts the server in Single-User mode and only allows this script to connect.

        Once the service is restarted, the following tasks are performed:
        - Login is added if it doesn't exist
        - If login is a Windows User, an attempt is made to ensure it exists
        - If login is a SQL Login, password policy will be set to OFF when creating the login, and SQL Server authentication will be set to Mixed Mode.
        - Login will be enabled and unlocked
        - Login will be added to sysadmin role

        If failures occur at any point, a best attempt is made to restart the SQL Server.

        In order to make this script as portable as possible, System.Data.SqlClient and Get-WmiObject are used (as opposed to requiring the Failover Cluster Admin tools or SMO).

        If using this function against a remote SQL Server, ensure WinRM is configured and accessible. If this is not possible, run the script locally.

        Tested on Windows XP, 7, 8.1, Server 2012 and Windows Server Technical Preview 2.
        Tested on SQL Server 2005 SP4 through 2016 CTP2.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. SQL Server must be 2005 and above, and can be a clustered or stand-alone instance.

    .PARAMETER SqlCredential
        Instead of using Login and SecurePassword, you can just pass in a credential object.

    .PARAMETER Login
        By default, the Login parameter is "sa" but any other SQL or Windows account can be specified. If a login does not currently exist, it will be added.

        When adding a Windows login to remote servers, ensure the SQL Server can add the login (ie, don't add WORKSTATION\Admin to remoteserver\instance. Domain users and Groups are valid input.

    .PARAMETER SecurePassword
        By default, if a SQL Login is detected, you will be prompted for a password. Use this to securely bypass the prompt.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER Force
        If this switch is enabled, the Login(s) will be dropped and recreated on Destination. Logins that own Agent jobs cannot be dropped at this time.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: WSMan
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: Admin access to server (not SQL Services),
        Remoting must be enabled and accessible if $instance is not local

    .LINK
        https://dbatools.io/Reset-DbaAdmin

    .EXAMPLE
        PS C:\> Reset-DbaAdmin -SqlInstance sqlcluster -SqlCredential sqladmin

        Prompts for password, then resets the "sqladmin" account password on sqlcluster.

    .EXAMPLE
        PS C:\> Reset-DbaAdmin -SqlInstance sqlserver\sqlexpress -Login ad\administrator -Confirm:$false

        Adds the domain account "ad\administrator" as a sysadmin to the SQL instance.

        If the account already exists, it will be added to the sysadmin role.

        Does not prompt for a password since it is not a SQL login. Does not prompt for confirmation since -Confirm is set to $false.

    .EXAMPLE
        PS C:\> Reset-DbaAdmin -SqlInstance sqlserver\sqlexpress -Login sqladmin -Force

        Skips restart confirmation, prompts for password, then adds a SQL Login "sqladmin" with sysadmin privileges.
        If the account already exists, it will be added to the sysadmin role and the password will be reset.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWMICmdlet", "", Justification = "Using Get-WmiObject for client backwards compatibilty")]
    param (
        [Parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [pscredential]$SqlCredential,
        [string]$Login = "sa",
        [SecureString]$SecurePassword,
        [switch]$Force,
        [switch]$EnableException
    )

    begin {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Reset-SqlAdmin

        #region Utility functions
        function ConvertTo-PlainText {
            <#
                .SYNOPSIS
                    Internal function.
             #>
            [CmdletBinding()]
            param (
                [Parameter(Mandatory)]
                [Security.SecureString]$Password
            )

            $marshal = [Runtime.InteropServices.Marshal]
            $plaintext = $marshal::PtrToStringAuto($marshal::SecureStringToBSTR($Password))
            return $plaintext
        }

        function Invoke-ResetSqlCmd {
            <#
                .SYNOPSIS
                    Internal function. Executes a SQL statement against specified computer, and uses "Reset-DbaAdmin" as the Application Name.
            #>
            [OutputType([System.Boolean])]
            [CmdletBinding()]
            param (
                [Parameter(Mandatory)]
                [Alias("ServerInstance", "SqlServer")]
                [DbaInstanceParameter]$instance,
                [string]$sql,
                [switch]$EnableException
            )
            try {
                $connstring = "Data Source=$instance;Integrated Security=True;Connect Timeout=20;Application Name=Reset-DbaAdmin"
                $conn = New-Object System.Data.SqlClient.SqlConnection $connstring
                $conn.Open()
                $cmd = New-Object system.data.sqlclient.sqlcommand($null, $conn)
                $cmd.CommandText = $sql
                $cmd.ExecuteNonQuery() | Out-Null
                $cmd.Dispose()
                $conn.Close()
                $conn.Dispose()
                $true
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_
            }
        }
        #endregion Utility functions
        if ($Force) {
            $ConfirmPreference = "none"
        }

        if ($SqlCredential) {
            $Login = $SqlCredential.UserName
            $SecurePassword = $SqlCredential.Password
        }
    }

    process {
        foreach ($instance in $sqlinstance) {
            $stepcounter = 0
            $baseaddress = $instance.ComputerName
            # Get hostname

            if ($baseaddress.IsLocalHost) {
                $ipaddr = "."
                $hostname = $env:COMPUTERNAME
                $baseaddress = $env:COMPUTERNAME
            }

            # If server is not local, get IP address and NetBios name in case CNAME records were referenced in the SQL hostname
            if ($baseaddress -ne $env:COMPUTERNAME) {
                # Test for WinRM #Test-WinRM neh
                winrm id -r:$baseaddress 2>$null | Out-Null
                if ($LastExitCode -ne 0) {
                    Stop-Function -Continue -Message "Remote PowerShell access not enabled on on $instance or access denied. Quitting."
                }

                # Test Connection first using ping class which requires ICMP access then failback to tcp if pings are blocked
                Write-Message -Level Verbose -Message "Testing connection to $baseaddress"
                $ping = New-Object System.Net.NetworkInformation.Ping
                $timeout = 1000 #milliseconds
                $reply = $ping.Send($baseaddress, $timeout)
                if ($reply.Status -ne 'Success') {
                    Write-Message -Level Verbose -Message "First attempt using ICMP failed. Trying to connect using sockets. This may take up to 20 seconds."
                    $tcp = New-Object System.Net.Sockets.TcpClient
                    try {
                        $tcp.Connect($hostname, 135)
                        $tcp.Close()
                        $tcp.Dispose()
                    } catch {
                        Stop-Function -Continue -ErrorRecord $_ -Message "Can't connect to $baseaddress either via ping or tcp (WMI port 135)"
                    }
                }
                Write-Message -Level Verbose -Message "Resolving IP address."
                try {
                    $hostentry = [System.Net.Dns]::GetHostEntry($baseaddress)
                    $ipaddr = ($hostentry.AddressList | Where-Object {
                            $_ -notlike '169.*'
                        } | Select-Object -First 1).IPAddressToString
                } catch {
                    Stop-Function -Continue -ErrorRecord $_ -Message "Could not resolve SqlServer IP or NetBIOS name"
                }

                Write-Message -Level Verbose -Message "Resolving NetBIOS name."
                try {
                    # this is required otherwise, the ip is returned
                    $hostname = (Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName $ipaddr -ErrorAction Stop).PSComputerName
                    if ($null -eq $hostname) {
                        $hostname = (nbtstat -A $ipaddr | Where-Object {
                                $_ -match '\<00\>  UNIQUE'
                            } | ForEach-Object {
                                $_.SubString(4, 14)
                            }).Trim()
                    }
                } catch {
                    Stop-Function -Continue -ErrorRecord $_ -Message "Could not access remote WMI object. Check permissions and firewall."
                }
            }

            # Setup remote session if server is not local
            if (-not $instance.IsLocalHost) {
                try {
                    $session = New-PSSession -ComputerName $hostname -ErrorAction Stop
                } catch {
                    Stop-Function -Continue -ErrorRecord $_ -Message "Can't access $hostname using PSSession. Check your firewall settings and ensure Remoting is enabled or run the script locally."
                }
            }

            Write-Message -Level Verbose -Message "Detecting login type."
            # Is login a Windows login? If so, does it exist?
            if ($login -match "\\") {
                Write-Message -Level Verbose -Message "Windows login detected. Checking to ensure account is valid."
                $windowslogin = $true
                try {
                    if ($hostname -eq $env:COMPUTERNAME) {
                        $account = New-Object System.Security.Principal.NTAccount($args)
                        #Variable $sid marked as unused by PSScriptAnalyzer replace with $null to catch output
                        $null = $account.Translate([System.Security.Principal.SecurityIdentifier])
                    } else {
                        Invoke-Command -ErrorAction Stop -Session $session -ArgumentList $login -ScriptBlock {
                            $account = New-Object System.Security.Principal.NTAccount($args)
                            #Variable $sid marked as unused by PSScriptAnalyzer replace with $null to catch output
                            $null = $account.Translate([System.Security.Principal.SecurityIdentifier])
                        }
                    }
                } catch {
                    Write-Message -Level Warning -Message "Cannot resolve Windows User or Group $login. Trying anyway."
                }
            }

            # If it's not a Windows login, it's a SQL login, so it needs a password.
            if (-not $windowslogin -and -not $SecurePassword) {
                Write-Message -Level Verbose -Message "SQL login detected"
                do {
                    $Password = Read-Host -AsSecureString "Please enter a new password for $login"
                } while ($Password.Length -eq 0)
            }

            If ($SecurePassword) {
                $Password = $SecurePassword
            }

            # Get instance and service display name, then get services
            $instancename = $null
            $instancename = $instance.InstanceName
            if (-not $instancename) {
                $instancename = "MSSQLSERVER"
            }
            $displayName = "SQL Server ($instancename)"

            try {
                if ($hostname -eq $env:COMPUTERNAME) {
                    $instanceservices = Get-Service -ErrorAction Stop | Where-Object {
                        $_.DisplayName -like "*($instancename)*" -and $_.Status -eq "Running"
                    }
                    $sqlservice = Get-Service -ErrorAction Stop | Where-Object DisplayName -eq "SQL Server ($instancename)"
                } else {
                    $instanceservices = Get-Service -ComputerName $ipaddr -ErrorAction Stop | Where-Object {
                        $_.DisplayName -like "*($instancename)*" -and $_.Status -eq "Running"
                    }
                    $sqlservice = Get-Service -ComputerName $ipaddr -ErrorAction Stop | Where-Object DisplayName -eq "SQL Server ($instancename)"
                }
            } catch {
                Stop-Function -Message "Cannot connect to WMI on $hostname or SQL Service does not exist. Check permissions, firewall and SQL Server running status." -ErrorRecord $_ -Target $instance
                return
            }

            if (-not $instanceservices) {
                Stop-Function -Message "Couldn't find SQL Server instance. Check the spelling, ensure the service is running and try again." -Target $instance
                return
            }

            Write-Message -Level Verbose -Message "Attempting to stop SQL Services."

            # Check to see if service is clustered. Clusters don't support -m (since the cluster service
            # itself connects immediately) or -f, so they are handled differently.
            try {
                $checkcluster = Get-Service -ComputerName $ipaddr -ErrorAction Stop | Where-Object {
                    $_.Name -eq "ClusSvc" -and $_.Status -eq "Running"
                }
            } catch {
                Stop-Function -Message "Can't check services." -Target $instance -ErrorRecord $_
                return
            }

            if ($null -ne $checkcluster) {
                $clusterResource = Get-DbaCmObject -ClassName "MSCluster_Resource" -Namespace "root\mscluster" -ComputerName $hostname |
                    Where-Object {
                    $_.Name.StartsWith("SQL Server") -and $_.OwnerGroup -eq "SQL Server ($instancename)"
                }
            }


            if ($pscmdlet.ShouldProcess($baseaddress, "Stop $instance to restart in single-user mode")) {
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Stopping $instance to restart in single-user mode"
                # Take SQL Server offline so that it can be started in single-user mode
                if ($clusterResource.count -gt 0) {
                    $isclustered = $true
                    try {
                        $clusterResource | Where-Object {
                            $_.Name -eq "SQL Server"
                        } | ForEach-Object {
                            $_.TakeOffline(60)
                        }
                    } catch {
                        $clusterResource | Where-Object {
                            $_.Name -eq "SQL Server"
                        } | ForEach-Object {
                            $_.BringOnline(60)
                        }
                        $clusterResource | Where-Object {
                            $_.Name -ne "SQL Server"
                        } | ForEach-Object {
                            $_.BringOnline(60)
                        }
                        Stop-Function -Message "Could not stop the SQL Service. Restarted SQL Service and quit." -ErrorRecord $_ -Target $instance
                        return
                    }
                } else {
                    try {
                        Stop-Service -InputObject $sqlservice -Force -ErrorAction Stop
                        Write-Message -Level Verbose -Message "Successfully stopped SQL service."
                    } catch {
                        Start-Service -InputObject $instanceservices -ErrorAction Stop
                        Stop-Function -Message "Could not stop the SQL Service. Restarted SQL service and quit." -ErrorRecord $_ -Target $instance
                        return
                    }
                }
            }

            # /mReset-DbaAdmin Starts an instance of SQL Server in single-user mode and only allows this script to connect.
            if ($pscmdlet.ShouldProcess($baseaddress, "Starting $instance in single-user mode")) {
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Starting $instance in single-user mode"
                try {
                    if ($instance.IsLocalHost) {
                        $netstart = net start ""$displayname"" /mReset-DbaAdmin 2>&1
                        if ("$netstart" -notmatch "success") {
                            Stop-Function -Message "Restart failure" -Continue
                        }
                    } else {
                        $netstart = Invoke-Command -ErrorAction Stop -Session $session -ArgumentList $displayname -ScriptBlock {
                            net start ""$args"" /mReset-DbaAdmin
                        } 2>&1
                        foreach ($line in $netstart) {
                            if ($line.length -gt 0) {
                                Write-Message -Level Verbose -Message $line
                            }
                        }
                    }
                } catch {
                    Stop-Service -InputObject $sqlservice -Force -ErrorAction SilentlyContinue

                    if ($isclustered) {
                        $clusterResource | Where-Object Name -eq "SQL Server" | ForEach-Object {
                            $_.BringOnline(60)
                        }
                        $clusterResource | Where-Object Name -ne "SQL Server" | ForEach-Object {
                            $_.BringOnline(60)
                        }
                    } else {
                        Start-Service -InputObject $instanceservices -ErrorAction SilentlyContinue
                    }
                    Stop-Function -Message "Couldn't execute net start command. Restarted services and quit." -ErrorRecord $_
                    return
                }
            }

            if ($pscmdlet.ShouldProcess($baseaddress, "Testing $instance to ensure it's back up")) {
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Testing $instance to ensure it's back up"
                try {
                    $null = Invoke-ResetSqlCmd -instance $instance -Sql "SELECT 1" -EnableException
                } catch {
                    try {
                        Start-Sleep 3
                        $null = Invoke-ResetSqlCmd -instance $instance -Sql "SELECT 1" -EnableException
                    } catch {
                        Stop-Service Input-Object $sqlservice -Force -ErrorAction SilentlyContinue
                        if ($isclustered) {
                            $clusterResource | Where-Object {
                                $_.Name -eq "SQL Server"
                            } | ForEach-Object {
                                $_.BringOnline(60)
                            }
                            $clusterResource | Where-Object {
                                $_.Name -ne "SQL Server"
                            } | ForEach-Object {
                                $_.BringOnline(60)
                            }
                        } else {
                            Start-Service -InputObject $instanceservices -ErrorAction SilentlyContinue
                        }
                        Stop-Function -Message "Could not stop the SQL Service. Restarted SQL Service and quit." -ErrorRecord $_
                    }
                }
            }

            # Get login. If it doesn't exist, create it.
            if ($pscmdlet.ShouldProcess($instance, "Adding login $login if it doesn't exist")) {
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Adding login $login if it doesn't exist"
                if ($windowslogin) {
                    $sql = "IF NOT EXISTS (SELECT name FROM master.sys.server_principals WHERE name = '$login')
                    BEGIN CREATE LOGIN [$login] FROM WINDOWS END"
                    if (-not (Invoke-ResetSqlCmd -instance $instance -Sql $sql)) {
                        Write-Message -Level Warning -Message "Couldn't create Windows login."
                    }

                } elseif ($login -ne "sa") {
                    # Create new sql user
                    $sql = "IF NOT EXISTS (SELECT name FROM master.sys.server_principals WHERE name = '$login')
                    BEGIN CREATE LOGIN [$login] WITH PASSWORD = '$(ConvertTo-PlainText $Password)', CHECK_POLICY = OFF, CHECK_EXPIRATION = OFF END"
                    if (-not (Invoke-ResetSqlCmd -instance $instance -Sql $sql)) {
                        Write-Message -Level Warning -Message "Couldn't create SQL login."
                    }
                }
            }


            # If $login is a SQL Login, Mixed mode authentication is required.
            if ($windowslogin -ne $true) {
                if ($pscmdlet.ShouldProcess($instance, "Enabling mixed mode authentication for $login and ensuring account is unlocked")) {
                    Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Enabling mixed mode authentication for $login and ensuring account is unlocked"
                    $sql = "EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'LoginMode', REG_DWORD, 2"
                    if (-not (Invoke-ResetSqlCmd -instance $instance -Sql $sql)) {
                        Write-Message -Level Warning -Message "Couldn't set to Mixed Mode."
                    }

                    $sql = "ALTER LOGIN [$login] WITH CHECK_POLICY = OFF
                    ALTER LOGIN [$login] WITH PASSWORD = '$(ConvertTo-PlainText $Password)' UNLOCK"
                    if (-not (Invoke-ResetSqlCmd -instance $instance -Sql $sql)) {
                        Write-Message -Level Warning -Message "Couldn't unlock account."
                    }
                }
            }

            if ($pscmdlet.ShouldProcess($instance, "Enabling $login")) {
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Ensuring login is enabled"
                $sql = "ALTER LOGIN [$login] ENABLE"
                if (-not (Invoke-ResetSqlCmd -instance $instance -Sql $sql)) {
                    Write-Message -Level Warning -Message "Couldn't enable login."
                }
            }

            if ($login -ne "sa") {
                if ($pscmdlet.ShouldProcess($instance, "Ensuring $login exists within sysadmin role")) {
                    Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Ensuring $login exists within sysadmin role"
                    $sql = "EXEC sp_addsrvrolemember '$login', 'sysadmin'"
                    if (-not (Invoke-ResetSqlCmd -instance $instance -Sql $sql)) {
                        Write-Message -Level Warning -Message "Couldn't add to sysadmin role."
                    }
                }
            }

            if ($pscmdlet.ShouldProcess($instance, "Finished with login tasks. Restarting")) {
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Finished with login tasks. Restarting."
                try {
                    Stop-Service -InputObject $sqlservice -Force -ErrorAction Stop
                    if ($isclustered -eq $true) {
                        $clusterResource | Where-Object Name -eq "SQL Server" | ForEach-Object {
                            $_.BringOnline(60)
                        }
                        $clusterResource | Where-Object Name -ne "SQL Server" | ForEach-Object {
                            $_.BringOnline(60)
                        }
                    } else {
                        Start-Service -InputObject $instanceservices -ErrorAction Stop
                    }
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_
                }
            }

            if ($pscmdlet.ShouldProcess($instance, "Logging in to get account information")) {
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Logging in to get account information"
                if ($securePassword) {
                    $cred = New-Object System.Management.Automation.PSCredential ($Login, $securePassword)
                    Get-DbaLogin -SqlInstance $instance -SqlCredential $cred -Login $Login
                } elseif ($SqlCredential) {
                    Get-DbaLogin -SqlInstance $instance -SqlCredential $SqlCredential -Login $Login
                } else {
                    try {
                        Get-DbaLogin -SqlInstance $instance -SqlCredential $SqlCredential -Login $Login -EnableException
                    } catch {
                        Stop-Function -Message "Password not supplied, tried logging in with Integrated authentication and it failed. Either way, $Login should work now on $instance." -Continue
                    }
                }
            }

        }
    }
    end {
        Write-Message -Level Verbose -Message "Script complete!"
    }
}
tools\dbatools\functions\Resolve-DbaNetworkName.ps1
function Resolve-DbaNetworkName {
    <#
    .SYNOPSIS
        Returns information about the network connection of the target computer including NetBIOS name, IP Address, domain name and fully qualified domain name (FQDN).

    .DESCRIPTION
        Retrieves the IPAddress, ComputerName from one computer.
        The object can be used to take action against its name or IPAddress.

        First ICMP is used to test the connection, and get the connected IPAddress.

        Multiple protocols (e.g. WMI, CIM, etc) are attempted before giving up.

        Important: Remember that FQDN doesn't always match "ComputerName dot Domain" as AD intends.
        There are network setup (google "disjoint domain") where AD and DNS do not match.
        "Full computer name" (as reported by sysdm.cpl) is the only match between the two,
        and it matches the "DNSHostName"  property of the computer object stored in AD.
        This means that the notation of FQDN that matches "ComputerName dot Domain" is incorrect
        in those scenarios.
        In other words, the "suffix" of the FQDN CAN be different from the AD Domain.

        This cmdlet has been providing good results since its inception but for lack of useful
        names some doubts may arise.
        Let this clear the doubts:
        - InputName: whatever has been passed in
        - ComputerName: hostname only
        - IPAddress: IP Address
        - DNSHostName: hostname only, coming strictly from DNS (as reported from the calling computer)
        - DNSDomain: domain only, coming strictly from DNS (as reported from the calling computer)
        - Domain: domain only, coming strictly from AD (i.e. the domain the ComputerName is joined to)
        - DNSHostEntry: Fully name as returned by DNS [System.Net.Dns]::GetHostEntry
        - FQDN: "legacy" notation of ComputerName "dot" Domain (coming from AD)
        - FullComputerName: Full name as configured from within the Computer (i.e. the only secure match between AD and DNS)

        So, if you need to use something, go with FullComputerName, always, as it is the most correct in every scenario.

    .PARAMETER ComputerName
        The target SQL Server instance or instances.
        This can be the name of a computer, a SMO object, an IP address or a SQL Instance.

    .PARAMETER Credential
        Credential object used to connect to the SQL Server as a different user

    .PARAMETER Turbo
        Resolves without accessing the server itself. Faster but may be less accurate because it relies on DNS only,
        so it may fail spectacularly for disjoin-domain setups. Also, everyone has its own DNS (i.e. results may vary
        changing the computer where the function runs)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Network, Resolve
        Author: Klaas Vandenberghe (@PowerDBAKlaas) | Simone Bizzotto (@niphold)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Resolve-DbaNetworkName

    .EXAMPLE
        PS C:\> Resolve-DbaNetworkName -ComputerName ServerA

        Returns a custom object displaying InputName, ComputerName, IPAddress, DNSHostName, DNSDomain, Domain, DNSHostEntry, FQDN, DNSHostEntry for ServerA

    .EXAMPLE
        PS C:\> Resolve-DbaNetworkName -SqlInstance sql2016\sqlexpress

        Returns a custom object displaying InputName, ComputerName, IPAddress, DNSHostName, DNSDomain, Domain, DNSHostEntry, FQDN, DNSHostEntry  for the SQL instance sql2016\sqlexpress

    .EXAMPLE
        PS C:\> Resolve-DbaNetworkName -SqlInstance sql2016\sqlexpress, sql2014

        Returns a custom object displaying InputName, ComputerName, IPAddress, DNSHostName, DNSDomain, Domain, DNSHostEntry, FQDN, DNSHostEntry  for the SQL instance sql2016\sqlexpress and sql2014

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sql2014 | Resolve-DbaNetworkName

        Returns a custom object displaying InputName, ComputerName, IPAddress, DNSHostName, Domain, FQDN for all SQL Servers returned by Get-DbaCmsRegServer

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [Alias('cn', 'host', 'ServerInstance', 'Server', 'SqlInstance')]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [Alias('FastParrot')]
        [switch]$Turbo,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        Function Get-ComputerDomainName {
            Param (
                $FQDN,
                $ComputerName
            )
            # deduce the domain name based on resolved name + original request
            if ($fqdn -notmatch "\.") {
                if ($ComputerName -match "\.") {
                    return $ComputerName.Substring($ComputerName.IndexOf(".") + 1)
                } else {
                    return "$env:USERDNSDOMAIN".ToLower()
                }
            } else {
                return $fqdn.Substring($fqdn.IndexOf(".") + 1)
            }
        }
    }
    process {
        if (-not (Test-Windows -NoWarn)) {
            Write-Message -Level Verbose -Message "Non-Windows client detected. Turbo (DNS resolution only) set to $true"
            $Turbo = $true
        }

        foreach ($computer in $ComputerName) {
            if ($computer.IsLocalhost) {
                $cName = $env:COMPUTERNAME
            } else {
                $cName = $computer.ComputerName
            }

            # resolve IP address
            try {
                Write-Message -Level VeryVerbose -Message "Resolving $cName using .NET.Dns GetHostEntry"
                $resolved = [System.Net.Dns]::GetHostEntry($cName)
                $ipaddresses = $resolved.AddressList | Sort-Object -Property AddressFamily # prioritize IPv4
                $ipaddress = $ipaddresses[0].IPAddressToString
            } catch {
                Stop-Function -Message "DNS name $cName not found" -Continue -ErrorRecord $_
            }

            # try to resolve IP into a hostname
            try {
                Write-Message -Level VeryVerbose -Message "Resolving $ipaddress using .NET.Dns GetHostByAddress"
                $fqdn = [System.Net.Dns]::GetHostByAddress($ipaddress).HostName
            } catch {
                Write-Message -Level Debug -Message "Failed to resolve $ipaddress using .NET.Dns GetHostByAddress"
                $fqdn = $resolved.HostName
            }

            $dnsDomain = Get-ComputerDomainName -FQDN $fqdn -ComputerName $cName
            # augment fqdn if needed
            if ($fqdn -notmatch "\." -and $dnsDomain) {
                $fqdn = "$fqdn.$dnsdomain"
            }
            $hostname = $fqdn.Split(".")[0]

            # create an output object with some preliminary data gathered so far
            $result = [PSCustomObject]@{
                InputName        = $computer
                ComputerName     = $hostname.ToUpper()
                IPAddress        = $ipaddress
                DNSHostname      = $hostname
                DNSDomain        = $dnsdomain
                Domain           = $dnsdomain
                DNSHostEntry     = $fqdn
                FQDN             = $fqdn
                FullComputerName = $cName
            }
            if ($Turbo) {
                # that's a finish line for a Turbo mode
                return $result
            }

            # finding out which IP to use by pinging all of them. The first to respond is the one.
            $ping = New-Object System.Net.NetworkInformation.Ping
            $timeout = 1000 #milliseconds
            foreach ($ip in $ipaddresses) {
                $reply = $ping.Send($ip, $timeout)
                if ($reply.Status -eq 'Success') {
                    $ipaddress = $ip.IPAddressToString
                    break
                }
            }
            $result.IPAddress = $ipaddress

            # re-try DNS reverse zone lookup if the IP to use is not the first one
            if ($ipaddresses[0].IPAddressToString -ne $ipaddress) {
                try {
                    Write-Message -Level VeryVerbose -Message "Resolving $ipaddress using .NET.Dns GetHostByAddress"
                    $fqdn = [System.Net.Dns]::GetHostByAddress($ipaddress).HostName
                    # re-adjust DNS domain again
                    $dnsDomain = Get-ComputerDomainName -FQDN $fqdn -ComputerName $cName
                    # augment fqdn if needed
                    if ($fqdn -notmatch "\." -and $dnsDomain) {
                        $fqdn = "$fqdn.$dnsdomain"
                    }
                    $hostname = $fqdn.Split(".")[0]

                    # update result fields accordingly
                    $result.ComputerName = $hostname.ToUpper()
                    $result.DNSHostname = $hostname
                    $result.DNSDomain = $dnsdomain
                    $result.Domain = $dnsdomain
                    $result.DNSHostEntry = $fqdn
                    $result.FQDN = $fqdn
                } catch {
                    Write-Message -Level VeryVerbose -Message "Failed to obtain a new name from $ipaddress, re-using $fqdn"
                }
            }


            Write-Message -Level Debug -Message "Getting domain name from the remote host $fqdn"
            try {
                $ScBlock = {
                    return [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties().DomainName
                }
                $cParams = @{
                    ComputerName = $cName
                }
                if ($Credential) { $cParams.Credential = $Credential }

                $conn = Get-DbaCmObject @cParams -ClassName win32_ComputerSystem -EnableException
                if ($conn) {
                    # update results accordingly
                    $result.ComputerName = $conn.Name
                    $dnsHostname = $conn.DNSHostname
                    $dnsDomain = $conn.Domain
                    $result.FQDN = "$dnsHostname.$dnsDomain".TrimEnd('.')
                    $result.DNSHostName = $dnsHostname
                    $result.Domain = $dnsDomain
                }
                try {
                    Write-Message -Level Debug -Message "Getting DNS domain from the remote host $($cParams.ComputerName)"
                    $dnsSuffix = Invoke-Command2 @cParams -ScriptBlock $ScBlock -ErrorAction Stop -Raw
                    $result.DNSDomain = $dnsSuffix
                    if ($dnsSuffix) {
                        $fullComputerName = $result.DNSHostName + "." + $dnsSuffix
                    } else {
                        $fullComputerName = $result.DNSHostName
                    }
                    $result.FullComputerName = $fullComputerName
                } catch {
                    Write-Message -Level Verbose -Message "Unable to get DNS domain information from $($cParams.ComputerName)"
                }
            } catch {
                Write-Message -Level Verbose -Message "Unable to get domain name from $($cParams.ComputerName)"
            }

            # getting a DNS host entry for the full name
            try {
                Write-Message -Level VeryVerbose -Message "Resolving $($result.FullComputerName) using .NET.Dns GetHostEntry"
                $result.DNSHostEntry = ([System.Net.Dns]::GetHostEntry($result.FullComputerName)).HostName
            } catch {
                Write-Message -Level Verbose -Message ".NET.Dns GetHostEntry failed for $($result.FullComputerName)"
            }

            # returning the final result
            return $result
        }
    }
}
tools\dbatools\functions\Restart-DbaService.ps1
function Restart-DbaService {
    <#
    .SYNOPSIS
        Restarts SQL Server services on a computer.

    .DESCRIPTION
        Restarts the SQL Server related services on one or more computers. Will follow SQL Server service dependencies.

        Requires Local Admin rights on destination computer(s).

    .PARAMETER ComputerName
        The target SQL Server instance or instances.

    .PARAMETER InstanceName
        Only affects services that belong to the specific instances.

    .PARAMETER Credential
        Credential object used to connect to the computer as a different user.

    .PARAMETER Type
        Use -Type to collect only services of the desired SqlServiceType.
        Can be one of the following: "Agent","Browser","Engine","FullText","SSAS","SSIS","SSRS"

    .PARAMETER Timeout
        How long to wait for the start/stop request completion before moving on. Specify 0 to wait indefinitely.

    .PARAMETER InputObject
        A collection of services from Get-DbaService

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER WhatIf
        Shows what would happen if the cmdlet runs. The cmdlet is not run.

    .PARAMETER Confirm
        Prompts you for confirmation before running the cmdlet.

    .PARAMETER Force
        Will stop dependent SQL Server agents when stopping Engine services.

    .NOTES
        Tags: Service, Instance, Restart
        Author: Kirill Kravtsov (@nvarscar)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires Local Admin rights on destination computer(s).

    .LINK
        https://dbatools.io/Restart-DbaService

    .EXAMPLE
        PS C:\> Restart-DbaService -ComputerName sqlserver2014a

        Restarts the SQL Server related services on computer sqlserver2014a.

    .EXAMPLE
        PS C:\> 'sql1','sql2','sql3'| Get-DbaService | Restart-DbaService

        Gets the SQL Server related services on computers sql1, sql2 and sql3 and restarts them.

    .EXAMPLE
        PS C:\> Restart-DbaService -ComputerName sql1,sql2 -Instance MSSQLSERVER

        Restarts the SQL Server services related to the default instance MSSQLSERVER on computers sql1 and sql2.

    .EXAMPLE
        PS C:\> Restart-DbaService -ComputerName $MyServers -Type SSRS

        Restarts the SQL Server related services of type "SSRS" (Reporting Services) on computers in the variable MyServers.

    .EXAMPLE
        PS C:\> Restart-DbaService -ComputerName sql1 -Type Engine -Force

        Restarts SQL Server database engine services on sql1 forcing dependent SQL Server Agent services to restart as well.

    #>
    [CmdletBinding(DefaultParameterSetName = "Server", SupportsShouldProcess)]
    param (
        [Parameter(ParameterSetName = "Server", Position = 1)]
        [Alias("cn", "host", "Server")]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [Alias("Instance")]
        [string[]]$InstanceName,
        [ValidateSet("Agent", "Browser", "Engine", "FullText", "SSAS", "SSIS", "SSRS")]
        [string[]]$Type,
        [parameter(ValueFromPipeline, Mandatory, ParameterSetName = "Service")]
        [Alias("ServiceCollection")]
        [object[]]$InputObject,
        [int]$Timeout = 60,
        [PSCredential]$Credential,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        $processArray = @()
        if ($PsCmdlet.ParameterSetName -eq "Server") {
            $serviceParams = @{ ComputerName = $ComputerName }
            if ($InstanceName) { $serviceParams.InstanceName = $InstanceName }
            if ($Type) { $serviceParams.Type = $Type }
            if ($Credential) { $serviceParams.Credential = $Credential }
            if ($EnableException) { $serviceParams.Silent = $EnableException }
            $InputObject = Get-DbaService @serviceParams
        }
    }
    process {
        #Get all the objects from the pipeline before proceeding
        $processArray += $InputObject
    }
    end {
        $processArray = [array]($processArray | Where-Object { (!$InstanceName -or $_.InstanceName -in $InstanceName) -and (!$Type -or $_.ServiceType -in $Type) })
        foreach ($service in $processArray) {
            if ($Force -and $service.ServiceType -eq 'Engine' -and !($processArray | Where-Object { $_.ServiceType -eq 'Agent' -and $_.InstanceName -eq $service.InstanceName -and $_.ComputerName -eq $service.ComputerName })) {
                Write-Message -Level Verbose -Message "Adding Agent service to the list for service $($service.ServiceName) on $($service.ComputerName), since -Force has been specified"
                #Construct parameters to call Get-DbaService
                $serviceParams = @{
                    ComputerName = $service.ComputerName
                    InstanceName = $service.InstanceName
                    Type         = 'Agent'
                }
                if ($Credential) { $serviceParams.Credential = $Credential }
                if ($EnableException) { $serviceParams.Silent = $EnableException }
                $processArray += @(Get-DbaService @serviceParams)
            }
        }
        if ($processArray) {
            if ($PSCmdlet.ShouldProcess("$ProcessArray", "Restarting Service")) {
                $services = Update-ServiceStatus -InputObject $processArray -Action 'stop' -Timeout $Timeout -EnableException $EnableException
                foreach ($service in ($services | Where-Object { $_.Status -eq 'Failed'})) {
                    $service
                }
                $services = $services | Where-Object { $_.Status -eq 'Successful'}
                if ($services) {
                    Update-ServiceStatus -InputObject $services -Action 'restart' -Timeout $Timeout -EnableException $EnableException
                }
            }
        } else {
            Stop-Function -EnableException $EnableException -Message "No SQL Server services found with current parameters."
        }

        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Restart-DbaSqlService
    }
}
tools\dbatools\functions\Restore-DbaBackupFromDirectory.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Restore-DbaBackupFromDirectory {
    <#
    .SYNOPSIS
        Please use `Get-ChildItem | Restore-DbaDatabase` instead. This command is no longer supported.

    .DESCRIPTION
        Please use `Get-ChildItem | Restore-DbaDatabase` instead. This command is no longer supported.

    .PARAMETER SqlInstance
        The SQL Server instance to which you will be restoring the database.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Path
        Specifies the full path to the directory that contains the database backups. The SQL Server service must have read access to this path.

    .PARAMETER ReuseSourceFolderStructure
        If this switch is enabled, the folder structure used on the instance where the backup was made will be recreated. By default, the database files will be restored to the default data and log directories for the instance you're restoring onto.

    .PARAMETER NoRecovery
        If this switch is enabled, the database is left in the No Recovery state to enable further backups to be added.

    .PARAMETER Force
        If this switch is enabled, any existing database matching the name of a database being restored will be overwritten.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .NOTES
        Tags: DisasterRecovery, Backup, Restore
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Restore-SqlBackupFromDirectory

    .EXAMPLE
        PS C:\> Restore-SqlBackupFromDirectory -SqlInstance sqlcluster -Path \\fileserver\share\sqlbackups\SQLSERVER2014A

        All user databases contained within \\fileserver\share\sqlbackups\SQLSERVERA will be restored to sqlcluster, down the most recent full/differential/logs.

    #>
    #Requires -Version 3.0
    [CmdletBinding()]
    param (
        [parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [parameter(Mandatory)]
        [string]$Path,
        [switch]$NoRecovery,
        [Alias("ReuseFolderStructure")]
        [switch]$ReuseSourceFolderStructure,
        [PSCredential]$SqlCredential,
        [switch]$Force
    )

    Write-Message -Level Warning -Message "This command is no longer supported. Please use Get-ChildItem | Restore-DbaDatabase instead"
}
tools\dbatools\functions\Restore-DbaDatabase.ps1
function Restore-DbaDatabase {
    <#
    .SYNOPSIS
        Restores a SQL Server Database from a set of backup files

    .DESCRIPTION
        Upon being passed a list of potential backups files this command will scan the files, select those that contain SQL Server
        backup sets. It will then filter those files down to a set that can perform the requested restore, checking that we have a
        full restore chain to the point in time requested by the caller.

        The function defaults to working on a remote instance. This means that all paths passed in must be relative to the remote instance.
        XpDirTree will be used to perform the file scans

        Various means can be used to pass in a list of files to be considered. The default is to non recursively scan the folder
        passed in.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.

    .PARAMETER Path
        Path to SQL Server backup files.

        Paths passed in as strings will be scanned using the desired method, default is a non recursive folder scan
        Accepts multiple paths separated by ','

        Or it can consist of FileInfo objects, such as the output of Get-ChildItem or Get-Item. This allows you to work with
        your own file structures as needed

    .PARAMETER DatabaseName
        Name to restore the database under.
        Only works with a single database restore. If multiple database are found in the provided paths then we will exit

    .PARAMETER DestinationDataDirectory
        Path to restore the SQL Server backups to on the target instance.
        If only this parameter is specified, then all database files (data and log) will be restored to this location

    .PARAMETER DestinationLogDirectory
        Path to restore the database log files to.
        This parameter can only be specified alongside DestinationDataDirectory.

    .PARAMETER DestinationFileStreamDirectory
        Path to restore FileStream data to
        This parameter can only be specified alongside DestinationDataDirectory

    .PARAMETER RestoreTime
        Specify a DateTime object to which you want the database restored to. Default is to the latest point  available in the specified backups

    .PARAMETER NoRecovery
        Indicates if the databases should be recovered after last restore. Default is to recover

    .PARAMETER WithReplace
        Switch indicated is the restore is allowed to replace an existing database.

    .PARAMETER XpDirTree
        Switch that indicated file scanning should be performed by the SQL Server instance using xp_dirtree
        This will scan recursively from the passed in path
        You must have sysadmin role membership on the instance for this to work.

    .PARAMETER OutputScriptOnly
        Switch indicates that ONLY T-SQL scripts should be generated, no restore takes place

    .PARAMETER VerifyOnly
        Switch indicate that restore should be verified

    .PARAMETER MaintenanceSolutionBackup
        Switch to indicate the backup files are in a folder structure as created by Ola Hallengreen's maintenance scripts.
        This switch enables a faster check for suitable backups. Other options require all files to be read first to ensure we have an anchoring full backup. Because we can rely on specific locations for backups performed with OlaHallengren's backup solution, we can rely on file locations.

    .PARAMETER FileMapping
        A hashtable that can be used to move specific files to a location.
        `$FileMapping = @{'DataFile1'='c:\restoredfiles\Datafile1.mdf';'DataFile3'='d:\DataFile3.mdf'}`
        And files not specified in the mapping will be restored to their original location
        This Parameter is exclusive with DestinationDataDirectory

    .PARAMETER IgnoreLogBackup
        This switch tells the function to ignore transaction log backups. The process will restore to the latest full or differential backup point only

    .PARAMETER UseDestinationDefaultDirectories
        Switch that tells the restore to use the default Data and Log locations on the target server. If they don't exist, the function will try to create them

    .PARAMETER ReuseSourceFolderStructure
        By default, databases will be migrated to the destination Sql Server's default data and log directories. You can override this by specifying -ReuseSourceFolderStructure.
        The same structure on the SOURCE will be kept exactly, so consider this if you're migrating between different versions and use part of Microsoft's default Sql structure (MSSql12.INSTANCE, etc)

        *Note, to reuse destination folder structure, specify -WithReplace

    .PARAMETER DestinationFilePrefix
        This value will be prefixed to ALL restored files (log and data). This is just a simple string prefix. If you want to perform more complex rename operations then please use the FileMapping parameter

        This will apply to all file move options, except for FileMapping

    .PARAMETER DestinationFileSuffix
        This value will be suffixed to ALL restored files (log and data). This is just a simple string suffix. If you want to perform more complex rename operations then please use the FileMapping parameter

        This will apply to all file move options, except for FileMapping

    .PARAMETER RestoredDatabaseNamePrefix
        A string which will be prefixed to the start of the restore Database's Name
        Useful if restoring a copy to the same sql server for testing.

    .PARAMETER TrustDbBackupHistory
        This switch can be used when piping the output of Get-DbaBackupHistory or Backup-DbaDatabase into this command.
        It allows the user to say that they trust that the output from those commands is correct, and skips the file header read portion of the process. This means a faster process, but at the risk of not knowing till halfway through the restore that something is wrong with a file.

    .PARAMETER MaxTransferSize
        Parameter to set the unit of transfer. Values must be a multiple by 64kb

    .PARAMETER Blocksize
        Specifies the block size to use. Must be one of 0.5kb,1kb,2kb,4kb,8kb,16kb,32kb or 64kb
        Can be specified in bytes
        Refer to https://msdn.microsoft.com/en-us/library/ms178615.aspx for more detail

    .PARAMETER BufferCount
        Number of I/O buffers to use to perform the operation.
        Refer to https://msdn.microsoft.com/en-us/library/ms178615.aspx for more detail

    .PARAMETER XpNoRecurse
        If specified, prevents the XpDirTree process from recursing (its default behaviour)

    .PARAMETER DirectoryRecurse
        If specified the specified directory will be recursed into

    .PARAMETER Continue
        If specified we will to attempt to recover more transaction log backups onto  database(s) in Recovering or Standby states

    .PARAMETER StandbyDirectory
        If a directory is specified the database(s) will be restored into a standby state, with the standby file placed into this directory (which must exist, and be writable by the target Sql Server instance)

    .PARAMETER AzureCredential
        The name of the SQL Server credential to be used if restoring from an Azure hosted backup using Storage Access Keys
        If a backup path beginning http is passed in and this parameter is not specified then if a credential with a name matching the URL

    .PARAMETER ReplaceDbNameInFile
        If switch set and occurrence of the original database's name in a data or log file will be replace with the name specified in the DatabaseName parameter

    .PARAMETER Recover
        If set will perform recovery on the indicated database

    .PARAMETER AllowContinue
        By default, Restore-DbaDatabase will stop restoring any databases if it comes across an error.
        Use this switch to enable it to restore all databases without issues.

    .PARAMETER GetBackupInformation
        Passing a string value into this parameter will cause a global variable to be created holding the output of Get-DbaBackupInformation

    .PARAMETER SelectBackupInformation
        Passing a string value into this parameter will cause a global variable to be created holding the output of Select-DbaBackupInformation

    .PARAMETER FormatBackupInformation
        Passing a string value into this parameter will cause a global variable to be created holding the output of Format-DbaBackupInformation

    .PARAMETER TestBackupInformation
        Passing a string value into this parameter will cause a global variable to be created holding the output of Test-DbaBackupInformation

    .PARAMETER StopAfterGetBackupInformation
        Switch which will cause the function to exit after returning GetBackupInformation

    .PARAMETER StopAfterSelectBackupInformation
        Switch which will cause the function to exit after returning SelectBackupInformation

    .PARAMETER StopAfterFormatBackupInformation
        Switch which will cause the function to exit after returning FormatBackupInformation

    .PARAMETER StopAfterTestBackupInformation
        Switch which will cause the function to exit after returning TestBackupInformation

    .PARAMETER StatementTimeOut
        Timeout in minutes. Defaults to infinity (restores can take a while.)

    .PARAMETER KeepCDC
        Indicates whether CDC information should be restored as part of the database

    .PARAMETER PageRestore
        Passes in an object from Get-DbaSuspectPages containing suspect pages from a single database.
        Setting this Parameter will cause an Online Page restore if the target Instance is Enterprise Edition, or offline if not.
        This will involve taking a tail log backup, so you must check your restore chain once it has completed

    .PARAMETER PageRestoreTailFolder
        This parameter passes in a location for the tail log backup required for page level restore

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER Confirm
        Prompts to confirm certain actions

    .PARAMETER WhatIf
        Shows what would happen if the command would execute, but does not actually perform the command

    .NOTES
        Tags: DisasterRecovery, Backup, Restore
        Author: Stuart Moore (@napalmgram), stuart-moore.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Restore-DbaDatabase

    .EXAMPLE
        PS C:\> Restore-DbaDatabase -SqlInstance server1\instance1 -Path \\server2\backups

        Scans all the backup files in \\server2\backups, filters them and restores the database to server1\instance1

    .EXAMPLE
        PS C:\> Restore-DbaDatabase -SqlInstance server1\instance1 -Path \\server2\backups -MaintenanceSolutionBackup -DestinationDataDirectory c:\restores

        Scans all the backup files in \\server2\backups$ stored in an Ola Hallengren style folder structure,
        filters them and restores the database to the c:\restores folder on server1\instance1

    .EXAMPLE
        PS C:\> Get-ChildItem c:\SQLbackups1\, \\server\sqlbackups2 | Restore-DbaDatabase -SqlInstance server1\instance1

        Takes the provided files from multiple directories and restores them on  server1\instance1

    .EXAMPLE
        PS C:\> $RestoreTime = Get-Date('11:19 23/12/2016')
        PS C:\> Restore-DbaDatabase -SqlInstance server1\instance1 -Path \\server2\backups -MaintenanceSolutionBackup -DestinationDataDirectory c:\restores -RestoreTime $RestoreTime

        Scans all the backup files in \\server2\backups stored in an Ola Hallengren style folder structure,
        filters them and restores the database to the c:\restores folder on server1\instance1 up to 11:19 23/12/2016

    .EXAMPLE
        PS C:\> $result = Restore-DbaDatabase -SqlInstance server1\instance1 -Path \\server2\backups -DestinationDataDirectory c:\restores -OutputScriptOnly
        PS C:\> $result | Select-Object -ExpandProperty Tsql | Out-File -Filepath c:\scripts\restore.sql

        Scans all the backup files in \\server2\backups stored in an Ola Hallengren style folder structure,
        filters them and generate the T-SQL Scripts to restore the database to the latest point in time,
        and then stores the output in a file for later retrieval

    .EXAMPLE
        PS C:\> Restore-DbaDatabase -SqlInstance server1\instance1 -Path c:\backups -DestinationDataDirectory c:\DataFiles -DestinationLogDirectory c:\LogFile

        Scans all the files in c:\backups and then restores them onto the SQL Server Instance server1\instance1, placing data files
        c:\DataFiles and all the log files into c:\LogFiles

    .EXAMPLE
        PS C:\> Restore-DbaDatabase -SqlInstance server1\instance1 -Path http://demo.blob.core.windows.net/backups/dbbackup.bak -AzureCredential MyAzureCredential

        Will restore the backup held at  http://demo.blob.core.windows.net/backups/dbbackup.bak to server1\instance1. The connection to Azure will be made using the
        credential MyAzureCredential held on instance Server1\instance1

    .EXAMPLE
        PS C:\> Restore-DbaDatabase -SqlInstance server1\instance1 -Path http://demo.blob.core.windows.net/backups/dbbackup.bak

        Will attempt to restore the backups from http://demo.blob.core.windows.net/backups/dbbackup.bak if a SAS credential with the name http://demo.blob.core.windows.net/backups exists on server1\instance1

    .EXAMPLE
        PS C:\> $File = Get-ChildItem c:\backups, \\server1\backups -recurse
        PS C:\> $File | Restore-DbaDatabase -SqlInstance Server1\Instance -UseDestinationDefaultDirectories

        This will take all of the files found under the folders c:\backups and \\server1\backups, and pipeline them into
        Restore-DbaDatabase. Restore-DbaDatabase will then scan all of the files, and restore all of the databases included
        to the latest point in time covered by their backups. All data and log files will be moved to the default SQL Server
        folder for those file types as defined on the target instance.

    .EXAMPLE
        PS C:\> $files = Get-ChildItem C:\dbatools\db1
        PS C:\> $files | Restore-DbaDatabase -SqlInstance server\instance1 `
        >> -DestinationFilePrefix prefix -DatabaseName Restored  `
        >> -RestoreTime (get-date "14:58:30 22/05/2017") `
        >> -NoRecovery -WithReplace -StandbyDirectory C:\dbatools\standby
        >>
        PS C:\> #It's in standby so we can peek at it
        PS C:\> Invoke-DbaQuery -SQLInstance server\instance1 -Query "select top 1 * from Restored.dbo.steps order by dt desc"
        PS C:\> #Not quite there so let's roll on a bit:
        PS C:\> $files | Restore-DbaDatabase -SqlInstance server\instance1 `
        >> -DestinationFilePrefix prefix -DatabaseName Restored `
        >> -continue -WithReplace -RestoreTime (get-date "15:09:30 22/05/2017") `
        >> -StandbyDirectory C:\dbatools\standby
        >>
        PS C:\> Invoke-DbaQuery -SQLInstance server\instance1 -Query "select top 1 * from restored.dbo.steps order by dt desc"
        PS C:\> Restore-DbaDatabase -SqlInstance server\instance1 -DestinationFilePrefix prefix -DatabaseName Restored -Continue -WithReplace

        In this example we step through the backup files held in c:\dbatools\db1 folder.
        First we restore the database to a point in time in standby mode. This means we can check some details in the databases
        We then roll it on a further 9 minutes to perform some more checks
        And finally we continue by rolling it all the way forward to the latest point in the backup.
        At each step, only the log files needed to roll the database forward are restored.

    .EXAMPLE
        PS C:\> Restore-DbaDatabase -SqlInstance server\instance1 -Path c:\backups -DatabaseName example1 -NoRecovery
        PS C:\> Restore-DbaDatabase -SqlInstance server\instance1 -Recover -DatabaseName example1

        In this example we restore example1 database with no recovery, and then the second call is to set the database to recovery.

    .EXAMPLE
        PS C:\> Get-DbaBackupHistory - SqlInstance server\instance1 -Database ProdFinance -Last | Restore-DbaDatabase -PageRestore
        PS C:\> $SuspectPage -PageRestoreTailFolder c:\temp -TrustDbBackupHistory -AllowContinues

        Gets a list of Suspect Pages using Get-DbaSuspectPage. The uses Get-DbaBackupHistory and Restore-DbaDatabase to perform a restore of the suspect pages and bring them up to date
        If server\instance1 is Enterprise edition this will be done online, if not it will be performed offline
        AllowContinue is required to make sure we cope with existing files

    .EXAMPLE
        PS C:\> $BackupHistory = Get-DbaBackupInformation -SqlInstance sql2005 -Path \\backups\sql2000\ProdDb
        PS C:\> $BackupHistory | Restore-DbaDatabase -SqlInstance sql2000 -TrustDbBackupHistory

        Due to SQL Server 2000 not returning all the backup headers we cannot restore directly. As this is an issues with the SQL engine all we can offer is the following workaround
        This will use a SQL Server instance > 2000 to read the headers, and then pass them in to Restore-DbaDatabase as a BackupHistory object.

    .EXAMPLE
        PS C:\> Restore-DbaDatabase -SqlInstance server1\instance1 -Path "C:\Temp\devops_prod_full.bak" -DatabaseName "DevOps_DEV" -ReplaceDbNameInFile
        PS C:\> Rename-DbaDatabase -SqlInstance server1\instance1 -Database "DevOps_DEV" -LogicalName "<DBN>_<FT>"

        This will restore the database from the "C:\Temp\devops_prod_full.bak" file, with the new name "DevOps_DEV" and store the different physical files with the new name. It will use the system default configured data and log locations.
        After the restore the logical names of the database files will be renamed with the "DevOps_DEV_ROWS" for MDF/NDF and "DevOps_DEV_LOG" for LDF

    .EXAMPLE
        PS C:\> $FileStructure = @{
        >> 'database_data' = 'C:\Data\database_data.mdf'
        >> 'database_log' = 'C:\Log\database_log.ldf'
        >> }
        >>
        PS C:\> Restore-DbaDatabase -SqlInstance server1 -Path \\ServerName\ShareName\File -DatabaseName database -FileMapping $FileStructure

        Restores 'database' to 'server1' and moves the files to new locations. The format for the $FileStructure HashTable is the file logical name as the Key, and the new location as the Value.

#>
    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = "Restore")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "AzureCredential", Justification = "For Parameter AzureCredential")]
    param (
        [parameter(Mandatory)][Alias("ServerInstance", "SqlServer")][DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(Mandatory, ValueFromPipeline, ParameterSetName = "Restore")][parameter(Mandatory, ValueFromPipeline, ParameterSetName = "RestorePage")][object[]]$Path,
        [parameter(ValueFromPipeline)][Alias("Name")][object[]]$DatabaseName,
        [parameter(ParameterSetName = "Restore")][String]$DestinationDataDirectory,
        [parameter(ParameterSetName = "Restore")][String]$DestinationLogDirectory,
        [parameter(ParameterSetName = "Restore")][String]$DestinationFileStreamDirectory,
        [parameter(ParameterSetName = "Restore")][DateTime]$RestoreTime = (Get-Date).AddYears(1),
        [parameter(ParameterSetName = "Restore")][switch]$NoRecovery,
        [parameter(ParameterSetName = "Restore")][switch]$WithReplace,
        [parameter(ParameterSetName = "Restore")][Switch]$XpDirTree,
        [switch]$OutputScriptOnly,
        [parameter(ParameterSetName = "Restore")][switch]$VerifyOnly,
        [parameter(ParameterSetName = "Restore")][switch]$MaintenanceSolutionBackup,
        [parameter(ParameterSetName = "Restore")][hashtable]$FileMapping,
        [parameter(ParameterSetName = "Restore")][switch]$IgnoreLogBackup,
        [parameter(ParameterSetName = "Restore")][switch]$UseDestinationDefaultDirectories,
        [parameter(ParameterSetName = "Restore")][switch]$ReuseSourceFolderStructure,
        [parameter(ParameterSetName = "Restore")][string]$DestinationFilePrefix = '',
        [parameter(ParameterSetName = "Restore")][string]$RestoredDatabaseNamePrefix,
        [parameter(ParameterSetName = "Restore")][parameter(ParameterSetName = "RestorePage")][switch]$TrustDbBackupHistory,
        [parameter(ParameterSetName = "Restore")][parameter(ParameterSetName = "RestorePage")][int]$MaxTransferSize,
        [parameter(ParameterSetName = "Restore")][parameter(ParameterSetName = "RestorePage")][int]$BlockSize,
        [parameter(ParameterSetName = "Restore")][parameter(ParameterSetName = "RestorePage")][int]$BufferCount,
        [parameter(ParameterSetName = "Restore")][switch]$DirectoryRecurse,
        [switch]$EnableException,
        [parameter(ParameterSetName = "Restore")][string]$StandbyDirectory,
        [parameter(ParameterSetName = "Restore")][switch]$Continue,
        [string]$AzureCredential,
        [parameter(ParameterSetName = "Restore")][switch]$ReplaceDbNameInFile,
        [parameter(ParameterSetName = "Restore")][string]$DestinationFileSuffix,
        [parameter(ParameterSetName = "Recovery")][switch]$Recover,
        [parameter(ParameterSetName = "Restore")][switch]$KeepCDC,
        [switch]$AllowContinue,
        [string]$GetBackupInformation,
        [switch]$StopAfterGetBackupInformation,
        [string]$SelectBackupInformation,
        [switch]$StopAfterSelectBackupInformation,
        [string]$FormatBackupInformation,
        [switch]$StopAfterFormatBackupInformation,
        [string]$TestBackupInformation,
        [switch]$StopAfterTestBackupInformation,
        [parameter(Mandatory, ParameterSetName = "RestorePage")][object]$PageRestore,
        [parameter(Mandatory, ParameterSetName = "RestorePage")][string]$PageRestoreTailFolder,
        [int]$StatementTimeout = 0
    )
    begin {
        Write-Message -Level InternalComment -Message "Starting"
        Write-Message -Level Debug -Message "Parameters bound: $($PSBoundParameters.Keys -join ", ")"

        #region Validation
        try {
            $RestoreInstance = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            return
        }
        if ($PSCmdlet.ParameterSetName -eq "Restore") {
            $UseDestinationDefaultDirectories = $true
            $paramCount = 0

            if (!(Test-Bound "AllowContinue") -and $true -ne $AllowContinue) {
                $AllowContinue = $false
            }
            if (Test-Bound "FileMapping") {
                $paramCount += 1
            }
            if (Test-Bound "ReuseSourceFolderStructure") {
                $paramCount += 1
            }
            if (Test-Bound "DestinationDataDirectory") {
                $paramCount += 1
            }
            if ($paramCount -gt 1) {
                Stop-Function -Category InvalidArgument -Message "You've specified incompatible Location parameters. Please only specify one of FileMapping, ReuseSourceFolderStructure or DestinationDataDirectory"
                return
            }
            if (($ReplaceDbNameInFile) -and !(Test-Bound "DatabaseName")) {
                Stop-Function -Category InvalidArgument -Message "To use ReplaceDbNameInFile you must specify DatabaseName"
                return
            }

            if ((Test-Bound "DestinationLogDirectory") -and (Test-Bound "ReuseSourceFolderStructure")) {
                Stop-Function -Category InvalidArgument -Message "The parameters DestinationLogDirectory and UseDestinationDefaultDirectories are mutually exclusive"
                return
            }
            if ((Test-Bound "DestinationLogDirectory") -and -not (Test-Bound "DestinationDataDirectory")) {
                Stop-Function -Category InvalidArgument -Message "The parameter DestinationLogDirectory can only be specified together with DestinationDataDirectory"
                return
            }
            if ((Test-Bound "DestinationFileStreamDirectory") -and (Test-Bound "ReuseSourceFolderStructure")) {
                Stop-Function -Category InvalidArgument -Message "The parameters DestinationFileStreamDirectory and UseDestinationDefaultDirectories are mutually exclusive"
                return
            }
            if ((Test-Bound "DestinationFileStreamDirectory") -and -not (Test-Bound "DestinationDataDirectory")) {
                Stop-Function -Category InvalidArgument -Message "The parameter DestinationFileStreamDirectory can only be specified together with DestinationDataDirectory"
                return
            }
            if ((Test-Bound "ReuseSourceFolderStructure") -and (Test-Bound "UseDestinationDefaultDirectories")) {
                Stop-Function -Category InvalidArgument -Message "The parameters UseDestinationDefaultDirectories and ReuseSourceFolderStructure cannot both be applied "
                return
            }

            if (($null -ne $FileMapping) -or $ReuseSourceFolderStructure -or ($DestinationDataDirectory -ne '')) {
                $UseDestinationDefaultDirectories = $false
            }
            if (($MaxTransferSize % 64kb) -ne 0 -or $MaxTransferSize -gt 4mb) {
                Stop-Function -Category InvalidArgument -Message "MaxTransferSize value must be a multiple of 64kb and no greater than 4MB"
                return
            }
            if ($BlockSize) {
                if ($BlockSize -notin (0.5kb, 1kb, 2kb, 4kb, 8kb, 16kb, 32kb, 64kb)) {
                    Stop-Function -Category InvalidArgument -Message "Block size must be one of 0.5kb,1kb,2kb,4kb,8kb,16kb,32kb,64kb"
                    return
                }
            }
            if ('' -ne $StandbyDirectory) {
                if (!(Test-DbaPath -Path $StandbyDirectory -SqlInstance $RestoreInstance)) {
                    Stop-Function -Message "$SqlServer cannot see the specified Standby Directory $StandbyDirectory" -Target $SqlInstance
                    return
                }
            }
            if ($KeepCDC -and ($NoRecovery -or ('' -ne $StandbyDirectory))) {
                Stop-Function -Category InvalidArgument -Message "KeepCDC cannot be specified with Norecovery or Standby as it needs recovery to work"
                return
            }
            if ($Continue) {
                Write-Message -Message "Called with continue, so assume we have an existing db in norecovery"
                $ContinuePoints = Get-RestoreContinuableDatabase -SqlInstance $RestoreInstance
                $LastRestoreType = Get-DbaDbRestoreHistory -SqlInstance $RestoreInstance -Last
            }
            if (!($PSBoundParameters.ContainsKey("DataBasename"))) {
                $PipeDatabaseName = $true
            }
        }

        if ($StatementTimeout -eq 0) {
            Write-Message -Level Verbose -Message "Changing statement timeout to infinity"
        } else {
            Write-Message -Level Verbose -Message "Changing statement timeout to ($StatementTimeout) minutes"
        }
        $RestoreInstance.ConnectionContext.StatementTimeout = ($StatementTimeout * 60)
        #endregion Validation

        if ($UseDestinationDefaultDirectories) {
            $DefaultPath = (Get-DbaDefaultPath -SqlInstance $RestoreInstance)
            $DestinationDataDirectory = $DefaultPath.Data
            $DestinationLogDirectory = $DefaultPath.Log
        }

        $BackupHistory = @()
    }
    process {
        if (Test-FunctionInterrupt) {
            return
        }
        if ($RestoreInstance.VersionMajor -eq 8 -and $true -ne $TrustDbBackupHistory) {
            foreach ($file in $Path) {
                $bh = Get-DbaBackupInformation -SqlInstance $RestoreInstance -Path $file
                $bound = $PSBoundParameters
                $bound['TrustDbBackupHistory'] = $true
                $bound['Path'] = $bh
                Restore-Dbadatabase @bound
            }
            break
        }
        if ($PSCmdlet.ParameterSetName -like "Restore*") {
            if ($PipeDatabaseName -eq $true) {
                $DatabaseName = ''
            }
            Write-Message -message "ParameterSet  = Restore" -Level Verbose
            if ($TrustDbBackupHistory -or $path[0].GetType().ToString() -eq 'Sqlcollaborative.Dbatools.Database.BackupHistory') {
                foreach ($f in $path) {
                    Write-Message -Level Verbose -Message "Trust Database Backup History Set"
                    if ("BackupPath" -notin $f.PSobject.Properties.name) {
                        Write-Message -Level Verbose -Message "adding BackupPath - $($_.FullName)"
                        $f = $f | Select-Object *, @{
                            Name = "BackupPath"; Expression = {
                                $_.FullName
                            }
                        }
                    }
                    if ("DatabaseName" -notin $f.PSobject.Properties.Name) {
                        $f = $f | Select-Object *, @{
                            Name = "DatabaseName"; Expression = {
                                $_.Database
                            }
                        }
                    }
                    if ("Database" -notin $f.PSobject.Properties.Name) {
                        $f = $f | Select-Object *, @{
                            Name = "Database"; Expression = {
                                $_.DatabaseName
                            }
                        }
                    }
                    if ("BackupSetGUID" -notin $f.PSobject.Properties.Name) {
                        $f = $f | Select-Object *, @{
                            Name = "BackupSetGUID"; Expression = {
                                $_.BackupSetID
                            }
                        }
                    }

                    if ($f.BackupPath -like 'http*') {
                        if ('' -ne $AzureCredential) {
                            Write-Message -Message "At least one Azure backup passed in with a credential, assume correct" -Level Verbose
                            Write-Message -Message "Storage Account Identity access means striped backups cannot be restore"
                        } else {
                            $f.BackupPath -match 'https://.*/.*/'
                            if (Get-DbaCredential -SqlInstance $RestoreInstance -name $matches[0].trim('/') ) {
                                Write-Message -Message "We have a SAS credential to use with $($f.BackupPath)" -Level Verbose
                            } else {
                                Stop-Function -Message "A URL to a backup has been passed in, but no credential can be found to access it"
                                return
                            }
                        }
                    }
                    $BackupHistory += $F | Select-Object *, @{
                        Name = "ServerName"; Expression = {
                            $_.SqlInstance
                        }
                    }, @{
                        Name = "BackupStartDate"; Expression = {
                            $_.Start -as [DateTime]
                        }
                    }
                }
            } else {
                $files = @()
                foreach ($f in $Path) {
                    if ($f -is [System.IO.FileSystemInfo]) {
                        $files += $f.FullName
                    } else {
                        $files += $f
                    }
                }
                Write-Message -Level Verbose -Message "Unverified input, full scans - $($files -join ';')"
                if ($BackupHistory.GetType().ToString() -eq 'Sqlcollaborative.Dbatools.Database.BackupHistory') {
                    $BackupHistory = @($BackupHistory)
                }
                $BackupHistory += Get-DbaBackupInformation -SqlInstance $RestoreInstance -SqlCredential $SqlCredential -Path $files -DirectoryRecurse:$DirectoryRecurse -MaintenanceSolution:$MaintenanceSolutionBackup -IgnoreLogBackup:$IgnoreLogBackup -AzureCredential $AzureCredential
            }
            if ($PSCmdlet.ParameterSetName -eq "RestorePage") {
                if (-not (Test-DbaPath -SqlInstance $RestoreInstance -Path $PageRestoreTailFolder)) {
                    Stop-Function -Message "Instance $RestoreInstance cannot read $PageRestoreTailFolder, cannot proceed" -Target $PageRestoreTailFolder
                    return
                }
                $WithReplace = $true
            }
        } elseif ($PSCmdlet.ParameterSetName -eq "Recovery") {
            Write-Message -Message "$($Database.Count) databases to recover" -level Verbose
            foreach ($Database in $DatabaseName) {
                if ($Database -is [object]) {
                    #We've got an object, try the normal options Database, DatabaseName, Name
                    if ("Database" -in $Database.PSobject.Properties.Name) {
                        [string]$DataBase = $Database.Database
                    } elseif ("DatabaseName" -in $Database.PSobject.Properties.Name) {
                        [string]$DataBase = $Database.DatabaseName
                    } elseif ("Name" -in $Database.PSobject.Properties.Name) {
                        [string]$Database = $Database.name
                    }
                }
                Write-Message -Level Verbose -Message "existence - $($RestoreInstance.Databases[$DataBase].State)"
                if ($RestoreInstance.Databases[$DataBase].State -ne 'Existing') {
                    Write-Message -Message "$Database does not exist on $RestoreInstance" -level Warning
                    continue
                }
                if ($RestoreInstance.Databases[$Database].Status -ne "Restoring") {
                    Write-Message -Message "$Database on $RestoreInstance is not in a Restoring State" -Level Warning
                    continue
                }
                $RestoreComplete = $true
                $RecoverSql = "RESTORE DATABASE $Database WITH RECOVERY"
                Write-Message -Message "Recovery Sql Query - $RecoverSql" -level verbose
                try {
                    $RestoreInstance.query($RecoverSql)
                } catch {
                    $RestoreComplete = $False
                    $ExitError = $_.Exception.InnerException
                    Write-Message -Level Warning -Message "Failed to recover $Database on $RestoreInstance, `n $ExitError"
                } finally {
                    [PSCustomObject]@{
                        SqlInstance     = $SqlInstance
                        DatabaseName    = $Database
                        RestoreComplete = $RestoreComplete
                        Scripts         = $RecoverSql
                    }
                }
            }
        }
    }
    end {
        if (Test-FunctionInterrupt) {
            return
        }
        if ($PSCmdlet.ParameterSetName -like "Restore*") {
            if ($BackupHistory.Count -eq 0) {
                Write-Message -Level Warning -Message "No backups passed through. `n This could mean the SQL instance cannot see the referenced files, the file's headers could not be read or some other issue"
                return
            }
            Write-Message -message "Processing DatabaseName - $DatabaseName" -Level Verbose
            $FilteredBackupHistory = @()
            if (Test-Bound -ParameterName GetBackupInformation) {
                Write-Message -Message "Setting $GetBackupInformation to BackupHistory" -Level Verbose
                Set-Variable -Name $GetBackupInformation -Value $BackupHistory -Scope Global
            }
            if ($StopAfterGetBackupInformation) {
                return
            }
            $pathSep = Get-DbaPathSep -Server $RestoreInstance
            $null = $BackupHistory | Format-DbaBackupInformation -DataFileDirectory $DestinationDataDirectory -LogFileDirectory $DestinationLogDirectory -DestinationFileStreamDirectory $DestinationFileStreamDirectory -DatabaseFileSuffix $DestinationFileSuffix -DatabaseFilePrefix $DestinationFilePrefix -DatabaseNamePrefix $RestoredDatabaseNamePrefix -ReplaceDatabaseName $DatabaseName -Continue:$Continue -ReplaceDbNameInFile:$ReplaceDbNameInFile -FileMapping $FileMapping -PathSep $pathSep

            if (Test-Bound -ParameterName FormatBackupInformation) {
                Set-Variable -Name $FormatBackupInformation -Value $BackupHistory -Scope Global
            }
            if ($StopAfterFormatBackupInformation) {
                return
            }
            if ($VerifyOnly) {
                $FilteredBackupHistory = $BackupHistory
            } else {
                $FilteredBackupHistory = $BackupHistory | Select-DbaBackupInformation -RestoreTime $RestoreTime -IgnoreLogs:$IgnoreLogBackups -ContinuePoints $ContinuePoints -LastRestoreType $LastRestoreType -DatabaseName $DatabaseName
            }
            if (Test-Bound -ParameterName SelectBackupInformation) {
                Write-Message -Message "Setting $SelectBackupInformation to FilteredBackupHistory" -Level Verbose
                Set-Variable -Name $SelectBackupInformation -Value $FilteredBackupHistory -Scope Global

            }
            if ($StopAfterSelectBackupInformation) {
                return
            }
            try {
                Write-Message -Level Verbose -Message "VerifyOnly = $VerifyOnly"
                $null = $FilteredBackupHistory | Test-DbaBackupInformation -SqlInstance $RestoreInstance -WithReplace:$WithReplace -Continue:$Continue -VerifyOnly:$VerifyOnly -EnableException:$true -OutputScriptOnly:$OutputScriptOnly
            } catch {
                Stop-Function -ErrorRecord $_ -Message "Failure" -Continue
            }
            if (Test-Bound -ParameterName TestBackupInformation) {
                Set-Variable -Name $TestBackupInformation -Value $FilteredBackupHistory -Scope Global
            }
            if ($StopAfterTestBackupInformation) {
                return
            }
            $DbVerfied = ($FilteredBackupHistory | Where-Object {
                    $_.IsVerified -eq $True
                } | Select-Object -Property Database -Unique).Database -join ','
            Write-Message -Message "$DbVerfied passed testing" -Level Verbose
            if ((@($FilteredBackupHistory | Where-Object {
                            $_.IsVerified -eq $True
                        })).count -lt $FilteredBackupHistory.count) {
                $DbUnVerified = ($FilteredBackupHistory | Where-Object {
                        $_.IsVerified -eq $False
                    } | Select-Object -Property Database -Unique).Database -join ','
                if ($AllowContinue) {
                    Write-Message -Message "$DbUnverified failed testing, AllowContinue set" -Level Verbose
                } else {
                    Stop-Function -Message "Database $DbUnverified failed testing, AllowContinue not set, exiting"
                    return
                }
            }
            If ($PSCmdlet.ParameterSetName -eq "RestorePage") {
                if (($FilteredBackupHistory.Database | select-Object -unique | Measure-Object).count -ne 1) {
                    Stop-Function -Message "Must only 1 database passed in for Page Restore. Sorry"
                    return
                } else {
                    $WithReplace = $false
                }
            }
            Write-Message -Message "Passing in to restore" -Level Verbose
            if ($PSCmdlet.ParameterSetName -eq "RestorePage" -and $RestoreInstance.Edition -notlike '*Enterprise*') {
                Write-Message -Message "Taking Tail log backup for page restore for non-Enterprise" -Level Verbose
                $TailBackup = Backup-DbaDatabase -SqlInstance $RestoreInstance -Database $DatabaseName -Type Log -BackupDirectory $PageRestoreTailFolder -Norecovery -CopyOnly
            }
            try {
                $FilteredBackupHistory | Where-Object {
                    $_.IsVerified -eq $true
                } | Invoke-DbaAdvancedRestore -SqlInstance $RestoreInstance -WithReplace:$WithReplace -RestoreTime $RestoreTime -StandbyDirectory $StandbyDirectory -NoRecovery:$NoRecovery -Continue:$Continue -OutputScriptOnly:$OutputScriptOnly -BlockSize $BlockSize -MaxTransferSize $MaxTransferSize -Buffercount $Buffercount -KeepCDC:$KeepCDC -VerifyOnly:$VerifyOnly -PageRestore $PageRestore -EnableException -AzureCredential $AzureCredential
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Continue -Target $RestoreInstance
            }
            if ($PSCmdlet.ParameterSetName -eq "RestorePage") {
                if ($RestoreInstance.Edition -like '*Enterprise*') {
                    Write-Message -Message "Taking Tail log backup for page restore for Enterprise" -Level Verbose
                    $TailBackup = Backup-DbaDatabase -SqlInstance $RestoreInstance -Database $DatabaseName -Type Log -BackupDirectory $PageRestoreTailFolder -Norecovery -CopyOnly
                }
                Write-Message -Message "Restoring Tail log backup for page restore" -Level Verbose
                $TailBackup | Restore-DbaDatabase -SqlInstance $RestoreInstance -TrustDbBackupHistory -NoRecovery -OutputScriptOnly:$OutputScriptOnly -BlockSize $BlockSize -MaxTransferSize $MaxTransferSize -Buffercount $Buffercount -Continue
                Restore-DbaDatabase -SqlInstance $RestoreInstance -Recover -DatabaseName $DatabaseName -OutputScriptOnly:$OutputScriptOnly
            }
        }
    }
}
tools\dbatools\functions\Restore-DbaDbCertificate.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Restore-DbaDbCertificate {
    <#
    .SYNOPSIS
        Imports certificates from .cer files using SMO.

    .DESCRIPTION
        Imports certificates from.cer files using SMO.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Path
        The Path the contains the certificate and private key files. The path can be a directory or a specific certificate.

    .PARAMETER SecurePassword
        Secure string used to decrypt the private key.

    .PARAMETER EncryptionPassword
        If specified this will be used to encrypt the private key.

    .PARAMETER Database
        The database where the certificate imports into. Defaults to master.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration, Certificate
        Author: Jess Pomfret (@jpomfret), jesspomfret.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Restore-DbaDbCertificate

    .EXAMPLE
        PS C:\> Restore-DbaDbCertificate -SqlInstance Server1 -Path \\Server1\Certificates -SecurePassword (ConvertTo-SecureString -Force -AsPlainText GoodPass1234!!)

        Restores all the certificates in the specified path, password is used to both decrypt and encrypt the private key.

    .EXAMPLE
        PS C:\> Restore-DbaDbCertificate -SqlInstance Server1 -Path \\Server1\Certificates\DatabaseTDE.cer -SecurePassword (ConvertTo-SecureString -force -AsPlainText GoodPass1234!!)

        Restores the DatabaseTDE certificate to Server1 and uses the MasterKey to encrypt the private key.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess, ConfirmImpact = "High")]
    param (
        [Parameter(Mandatory)]
        [DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("FullName")]
        [object[]]$Path,
        [Security.SecureString]$EncryptionPassword,
        [string]$Database = "master",
        [Alias("Password")]
        [Security.SecureString]$SecurePassword = (Read-Host "Password" -AsSecureString),
        [switch]$EnableException
    )
    process {
        try {
            $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $sqlcredential
        } catch {
            Stop-Function -Message "Failed to connect to: $SqlInstance" -Target $SqlInstance -ErrorRecord $_
            return
        }

        foreach ($fullname in $Path) {
            if (-not $SqlInstance.IsLocalHost -and -not $fullname.StartsWith('\')) {
                Stop-Function -Message "Path ($fullname) must be a UNC share when SQL instance is not local." -Continue -Target $fullname
            }

            if (-not (Test-DbaPath -SqlInstance $server -Path $fullname)) {
                Stop-Function -Message "$SqlInstance cannot access $fullname" -Continue -Target $fullname
            }

            $directory = Split-Path $fullname
            $filename = Split-Path $fullname -Leaf
            $certname = [io.path]::GetFileNameWithoutExtension($filename)

            if ($Pscmdlet.ShouldProcess("$certname on $SqlInstance", "Importing Certificate")) {
                $smocert = New-Object Microsoft.SqlServer.Management.Smo.Certificate
                $smocert.Name = $certname
                $smocert.Parent = $server.Databases[$Database]
                Write-Message -Level Verbose -Message "Creating Certificate: $certname"
                try {
                    $fullcertname = "$directory\$certname.cer"
                    $privatekey = "$directory\$certname.pvk"
                    Write-Message -Level Verbose -Message "Full certificate path: $fullcertname"
                    Write-Message -Level Verbose -Message "Private key: $privatekey"
                    $fromfile = $true

                    if ($EncryptionPassword) {
                        $smocert.Create($fullcertname, $fromfile, $privatekey, [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($password)), [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($password)))
                    } else {
                        $smocert.Create($fullcertname, $fromfile, $privatekey, [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($password)))
                    }
                    $cert = $smocert
                } catch {
                    Write-Message -Level Warning -Message $_ -ErrorRecord $_ -Target $instance
                }
            }
            Get-DbaDbCertificate -SqlInstance $server -Database $Database -Certificate $cert.Name
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Retore-DbaDatabaseCertificate

    }
}
tools\dbatools\functions\Restore-DbaDbSnapshot.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Restore-DbaDbSnapshot {
    <#
    .SYNOPSIS
        Restores databases from snapshots

    .DESCRIPTION
        Restores the database from the snapshot, discarding every modification made to the database
        NB: Restoring to a snapshot will result in every other snapshot of the same database to be dropped
        It also fixes some long-standing bugs in SQL Server when restoring from snapshots

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Credential object used to connect to the SQL Server as a different user

    .PARAMETER Database
        Restores from the last snapshot databases with this names only. You can pass either Databases or Snapshots

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER Snapshot
        Restores databases from snapshots with this names only. You can pass either Databases or Snapshots

    .PARAMETER InputObject
        Allows piping from other Snapshot commands

    .PARAMETER Force
        If restoring from a snapshot involves dropping any other snapshot, you need to explicitly
        use -Force to let this command delete the ones not involved in the restore process.
        Also, -Force will forcibly kill all running queries that prevent the restore process.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run

    .PARAMETER Confirm
        Prompts for confirmation of every step.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Snapshot, Backup, Restore, Database
        Author: Simone Bizzotto (@niphold)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Restore-DbaDbSnapshot

    .EXAMPLE
        PS C:\> Restore-DbaDbSnapshot -SqlInstance sql2014 -Database HR, Accounting

        Restores HR and Accounting databases using the latest snapshot available

    .EXAMPLE
        PS C:\> Restore-DbaDbSnapshot -SqlInstance sql2014 -Database HR -Force

        Restores HR database from latest snapshot and kills any active connections in the database on sql2014.

    .EXAMPLE
        PS C:\> Get-DbaDbSnapshot -SqlInstance sql2016 -Database HR | Restore-DbaDbSnapshot -Force

        Restores HR database from latest snapshot and kills any active connections in the database on sql2016.

    .EXAMPLE
        PS C:\> Get-DbaDbSnapshot -SqlInstance sql2016 | Out-GridView -PassThru | Restore-DbaDbSnapshot

        Allows the selection of snapshots on sql2016 to restore

    .EXAMPLE
        PS C:\> Restore-DbaDbSnapshot -SqlInstance sql2014 -Snapshot HR_snap_20161201, Accounting_snap_20161101

        Restores databases from snapshots named HR_snap_20161201 and Accounting_snap_20161101

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [object[]]$Snapshot,
        [Parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        if (-not $Snapshot -and -not $Database -and -not $ExcludeDatabase -and -not $InputObject) {
            Stop-Function -Message "You must specify either -Snapshot (to restore from) or -Database/-ExcludeDatabase (to restore to) or pipe in a snapshot"
            return
        }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $InputObject += Get-DbaDbSnapshot -SqlInstance $server -Database $Database -ExcludeDatabase $ExcludeDatabase -Snapshot $Snapshot | Sort-Object CreateDate -Descending

            if ($Snapshot) {
                # Restore databases from these snapshots
                Write-Message -Level Verbose -Message "Selected only snapshots"
                $dbs = $InputObject | Where-Object { $Snapshot -contains $_.Name }
                $baseDatabases = $dbs | Select-Object -ExpandProperty DatabaseSnapshotBaseName | Get-Unique
                if ($baseDatabases.Count -ne $Snapshot.Count -and $dbs.Count -ne 0) {
                    Stop-Function -Message "Failure. Multiple snapshots selected for the same database" -Continue
                }
            }
        }

        foreach ($snap in $InputObject) {
            # In the event someone passed -Database and it got all the snaps, most of which were dropped by the first
            if ($snap.Parent) {
                $server = $snap.Parent

                if (-not $snap.IsDatabaseSnapshot) {
                    Stop-Function -Continue -Message "$snap on $server is not a valid snapshot"
                }

                if (-not ($snap.IsAccessible)) {
                    Stop-Function -Message "Database $snap is not accessible on $($snap.Parent)." -Continue
                }

                $othersnaps = $server.Databases | Where-Object { $_.DatabaseSnapshotBaseName -eq $snap.DatabaseSnapshotBaseName -and $_.Name -ne $snap.Name }

                $db = $server.Databases | Where-Object Name -eq $snap.DatabaseSnapshotBaseName
                $loginfo = $db.LogFiles | Select-Object Id, Size, Growth, GrowthType

                if (($snap | Where-Object FileGroupType -eq 'FileStreamDataFileGroup')) {
                    Stop-Function -Message "Database $snap on $server has FileStream group(s). You cannot restore from snapshots" -Continue
                }

                if ($othersnaps -and -not $force) {
                    Stop-Function -Message "The restore process for $db from $snap needs to drop other snapshots on $db. Use -Force if you want to drop these snapshots" -Continue
                }

                if ($Pscmdlet.ShouldProcess($server, "Remove other db snapshots for $db")) {
                    try {
                        $null = $othersnaps | Remove-DbaDatabase -Confirm:$false -EnableException
                    } catch {
                        Stop-Function -Message "Failed to remove other snapshots for $db on $server" -ErrorRecord $_ -Continue
                    }
                }

                # Need a proper restore now
                if ($Pscmdlet.ShouldProcess($server, "Restore db $db from $snap")) {
                    try {
                        if ($Force) {
                            $null = Stop-DbaProcess -SqlInstance $server -Database $db.Name, $snap.Name -WarningAction SilentlyContinue
                        }

                        $null = $server.Query("USE master; RESTORE DATABASE [$($db.Name)] FROM DATABASE_SNAPSHOT='$($snap.Name)'")
                    } catch {
                        Stop-Function -Message "Failiure attempting to restore $db on $server" -ErrorRecord $_ -Continue
                    }
                }

                # Comparing sizes before and after, need to refresh to see if size
                foreach ($log in $db.LogFiles) {
                    $log.Refresh()
                }

                foreach ($log in $db.LogFiles) {
                    $matching = $loginfo | Where-Object ID -eq $log.ID
                    $changeflag = 0
                    foreach ($prop in @('Size', 'Growth', 'Growth', 'GrowthType')) {
                        if ($matching.$prop -ne $log.$prop) {
                            $changeflag = 1
                            $log.$prop = $matching.$prop
                        }
                    }
                    if ($changeflag -ne 0) {
                        Write-Message -Level Verbose -Message "Restoring original settings for log file"
                        $log.Alter()
                    }
                }

                Write-Message -Level Verbose -Message "Restored. Remember to take a backup now, and also to remove the snapshot if not needed."
                Get-DbaDatabase -SqlInstance $server -Database $db.Name
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Restore-DbaFromDatabaseSnapshot
    }
}
tools\dbatools\functions\Resume-DbaAgDbDataMovement.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Resume-DbaAgDbDataMovement {
    <#
    .SYNOPSIS
        Resumes data movement for an availability group database on a SQL Server instance.

    .DESCRIPTION
        Resumes data movement for an availability group database on a SQL Server instance.

   .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.

    .PARAMETER SqlCredential
        Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database or databases to resume movement upon.

    .PARAMETER AvailabilityGroup
        The availability group where the database movement will be resumeed.

    .PARAMETER InputObject
        Enables piping from Get-DbaAgDatabase

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: AvailabilityGroup, HA, AG
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Resume-DbaAgDbDataMovement

    .EXAMPLE
        PS C:\> Resume-DbaAgDbDataMovement -SqlInstance sql2017a -AvailabilityGroup ag1 -Database db1, db2

        Resumes data movement on db1 and db2 to ag1 on sql2017a. Prompts for confirmation.

    .EXAMPLE
        PS C:\> Get-DbaAgDatabase -SqlInstance sql2017a, sql2019 | Out-GridView -Passthru | Resume-DbaAgDbDataMovement -Confirm:$false

        Resumes data movement on the selected availability group databases. Does not prompt for confirmation.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$AvailabilityGroup,
        [string[]]$Database,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.AvailabilityDatabase[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ((Test-Bound -ParameterName SqlInstance)) {
            if ((Test-Bound -Not -ParameterName Database) -and (Test-Bound -Not -ParameterName AvailabilityGroup)) {
                Stop-Function -Message "You must specify one or more databases and one Availability Groups when using the SqlInstance parameter."
                return
            }
        }

        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaAgDatabase -SqlInstance $instance -SqlCredential $SqlCredential -Database $Database
        }

        foreach ($agdb in $InputObject) {
            if ($Pscmdlet.ShouldProcess($ag.Parent.Name, "Seting availability group $db to $($db.Parent.Name)")) {
                try {
                    $null = $agdb.ResumeDataMovement()
                    $agdb
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Revoke-DbaAgPermission.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Revoke-DbaAgPermission {
    <#
    .SYNOPSIS
        Revokes endpoint and availability group permissions to a login.

    .DESCRIPTION
        Revokes endpoint and availability group permissions to a login.

   .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.

    .PARAMETER SqlCredential
        Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Login
        The login or logins to modify.

    .PARAMETER AvailabilityGroup
        Only modify specific availability groups.

    .PARAMETER Type
        Specify type: Endpoint or AvailabilityGroup. Endpoint will modify the DatabaseMirror endpoint type.

    .PARAMETER Permission
        Revokes one or more permissions:
            Alter
            Connect
            Control
            CreateAnyDatabase
            CreateSequence
            Delete
            Execute
            Impersonate
            Insert
            Receive
            References
            Select
            Send
            TakeOwnership
            Update
            ViewChangeTracking
            ViewDefinition

        Connect is default.

    .PARAMETER InputObject
        Enables piping from Get-DbaLogin.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: AvailabilityGroup, HA, AG
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Revoke-DbaAgPermission

    .EXAMPLE
        PS C:\> Revoke-DbaAgPermission -SqlInstance sql2017a -Type AvailabilityGroup -AvailabilityGroup SharePoint -Login ad\spservice -Permission CreateAnyDatabase

        Removes CreateAnyDatabase permissions from ad\spservice on the SharePoint availability group on sql2017a. Does not prompt for confirmation.

    .EXAMPLE
        PS C:\> Revoke-DbaAgPermission -SqlInstance sql2017a -Type AvailabilityGroup -AvailabilityGroup ag1, ag2 -Login ad\spservice -Permission CreateAnyDatabase -Confirm

        Removes CreateAnyDatabase permissions from ad\spservice on the ag1 and ag2 availability groups on sql2017a. Prompts for confirmation.

    .EXAMPLE
        PS C:\> Get-DbaLogin -SqlInstance sql2017a | Out-GridView -Passthru | Revoke-DbaAgPermission -Type EndPoint

        Revokes the selected logins Connect permissions on the DatabaseMirroring endpoint for sql2017a.
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Login,
        [string[]]$AvailabilityGroup,
        [parameter(Mandatory)]
        [ValidateSet('Endpoint', 'AvailabilityGroup')]
        [string[]]$Type,
        [ValidateSet('Alter', 'Connect', 'Control', 'CreateAnyDatabase', 'CreateSequence', 'Delete', 'Execute', 'Impersonate', 'Insert', 'Receive', 'References', 'Select', 'Send', 'TakeOwnership', 'Update', 'ViewChangeTracking', 'ViewDefinition')]
        [string[]]$Permission = "Connect",
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Login[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ($SqlInstance -and -not $Login -and -not $AvailabilityGroup) {
            Stop-Function -Message "You must specify one or more logins when using the SqlInstance parameter."
            return
        }

        if ($Type -contains "AvailabilityGroup" -and -not $AvailabilityGroup) {
            Stop-Function -Message "You must specify at least one availability group when using the AvailabilityGroup type."
            return
        }

        foreach ($instance in $SqlInstance) {
            if ($perm -contains "CreateAnyDatabase") {
                try {
                    $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
                } catch {
                    Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                }

                foreach ($ag in $AvailabilityGroup) {
                    try {
                        $server.Query("ALTER AVAILABILITY GROUP $ag GRANT CREATE ANY DATABASE")
                    } catch {
                        Stop-Function -Message "Failure" -ErrorRecord $_ -Target $instance
                        return
                    }
                }
            } elseif ($Login) {
                $InputObject += Get-DbaLogin -SqlInstance $instance -SqlCredential $SqlCredential -Login $Login
                foreach ($account in $Login) {
                    if ($account -notin $InputObject.Name) {
                        try {
                            $InputObject += New-DbaLogin -SqlInstance $server -Login $account -EnableException
                        } catch {
                            Stop-Function -Message "Failure" -ErrorRecord $_ -Target $instance
                            return
                        }
                    }
                }
            }
        }

        foreach ($account in $InputObject) {
            $server = $account.Parent
            if ($Type -contains "Endpoint") {
                $server.Endpoints.Refresh()
                $endpoint = $server.Endpoints | Where-Object EndpointType -eq DatabaseMirroring

                if (-not $endpoint) {
                    Stop-Function -Message "DatabaseMirroring endpoint does not exist on $server" -Target $server -Continue
                }

                foreach ($perm in $Permission) {
                    if ($Pscmdlet.ShouldProcess($server.Name, "Revokeing $perm on $endpoint")) {
                        if ($perm -in 'CreateAnyDatabase') {
                            Stop-Function -Message "$perm not supported by endpoints" -Continue
                        }
                        try {
                            $bigperms = New-Object Microsoft.SqlServer.Management.Smo.ObjectPermissionSet([Microsoft.SqlServer.Management.Smo.ObjectPermission]::$perm)
                            $endpoint.Revoke($bigperms, $account.Name)
                            [pscustomobject]@{
                                ComputerName = $account.ComputerName
                                InstanceName = $account.InstanceName
                                SqlInstance  = $account.SqlInstance
                                Name         = $account.Name
                                Permission   = $perm
                                Type         = "Revoke"
                                Status       = "Success"
                            }
                        } catch {
                            Stop-Function -Message "Failure" -ErrorRecord $_ -Target $ag -Continue
                        }
                    }
                }
            }

            if ($Type -contains "AvailabilityGroup") {
                $ags = Get-DbaAvailabilityGroup -SqlInstance $account.Parent -AvailabilityGroup $AvailabilityGroup
                foreach ($ag in $ags) {
                    foreach ($perm in $Permission) {
                        if ($perm -notin 'Alter', 'Control', 'TakeOwnership', 'ViewDefinition') {
                            Stop-Function -Message "$perm not supported by availability groups" -Continue
                        }
                        if ($Pscmdlet.ShouldProcess($server.Name, "Revokeing $perm on $ags")) {
                            try {
                                $bigperms = New-Object Microsoft.SqlServer.Management.Smo.ObjectPermissionSet([Microsoft.SqlServer.Management.Smo.ObjectPermission]::$perm)
                                $ag.Revoke($bigperms, $account.Name)
                                [pscustomobject]@{
                                    ComputerName = $account.ComputerName
                                    InstanceName = $account.InstanceName
                                    SqlInstance  = $account.SqlInstance
                                    Name         = $account.Name
                                    Permission   = $perm
                                    Type         = "Revoke"
                                    Status       = "Success"
                                }
                            } catch {
                                Stop-Function -Message "Failure" -ErrorRecord $_ -Target $ag -Continue
                            }
                        }
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Save-DbaDiagnosticQueryScript.ps1
function Save-DbaDiagnosticQueryScript {
    <#
    .SYNOPSIS
        Save-DbaDiagnosticQueryScript downloads the most recent version of all Glenn Berry DMV scripts

    .DESCRIPTION
        The dbatools module will have the diagnostic queries pre-installed. Use this only to update to a more recent version or specific versions.

        This function is mainly used by Invoke-DbaDiagnosticQuery, but can also be used independently to download the Glenn Berry DMV scripts.

        Use this function to pre-download the scripts from a device with an Internet connection.

        The function Invoke-DbaDiagnosticQuery will try to download these scripts automatically, but it obviously needs an internet connection to do that.

    .PARAMETER Path
        Specifies the path to the output

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Diagnostic, DMV, Troubleshooting
        Author: Andre Kamman (@AndreKamman), http://clouddba.io

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Save-DbaDiagnosticQueryScript -Path c:\temp

        Downloads the most recent version of all Glenn Berry DMV scripts to the specified location.
        If Path is not specified, the "My Documents" location will be used.

    #>
    [CmdletBinding()]
    param (
        [System.IO.FileInfo]$Path = [Environment]::GetFolderPath("mydocuments"),
        [Alias('Silent')]
        [switch]$EnableException
    )
    function Get-WebData {
        param ($uri)
        try {
            try {
                $data = (Invoke-TlsWebRequest -uri $uri -ErrorAction Stop)
            } catch {
                (New-Object System.Net.WebClient).Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
                $data = (Invoke-TlsWebRequest -uri $uri -ErrorAction Stop)
            }
            return $data
        } catch {
            Stop-Function -Message "Invoke-TlsWebRequest failed: $_" -Target $data -ErrorRecord $_
            return
        }
    }

    if (-not (Test-Path $Path)) {
        Stop-Function -Message "Path does not exist or access denied" -Target $path
        return
    }

    Add-Type -AssemblyName System.Web
    $glenberryrss = "http://www.sqlskills.com/blogs/glenn/feed/"
    $glenberrysql = @()

    Write-Message -Level Verbose -Message "Downloading RSS Feed"
    $rss = [xml](get-webdata -uri $glenberryrss)
    $Feed = $rss.rss.Channel

    $glenberrysql = @()
    $RssPostFilter = "SQL Server Diagnostic Information Queries for*"
    $DropboxLinkFilter = "*dropbox.com*"
    $LinkTitleFilter = "*Diagnostic*"

    foreach ($post in $Feed.item) {
        if ($post.title -like $RssPostFilter) {
            # We found the first post that matches it, lets go visit and scrape.
            $page = Get-WebData -uri $post.link
            $glenberrysql += ($page.Links | Where-Object { $_.href -like $DropboxLinkFilter -and $_.innerText -like $LinkTitleFilter } | ForEach-Object {
                    [pscustomobject]@{
                        URL        = $_.href
                        SQLVersion = $_.innerText -replace " Diagnostic Information Queries", "" -replace "SQL Server ", "" -replace ' ', ''
                        FileYear   = ($post.title -split " ")[-1]
                        FileMonth  = "{0:00}" -f [int]([CultureInfo]::InvariantCulture.DateTimeFormat.MonthNames.IndexOf(($post.title -split " ")[-2]))
                    }
                })
            break
        }
    }
    Write-Message -Level Verbose -Message "Found $($glenberrysql.Count) documents to download"
    foreach ($doc in $glenberrysql) {
        try {
            $link = $doc.URL.ToString().Replace('dl=0', 'dl=1')
            Write-Message -Level Verbose -Message "Downloading $link)"
            Write-ProgressHelper -Activity "Downloading Glenn Berry's most recent DMVs" -ExcludePercent -Message "Downloading $link" -StepNumber 1
            $filename = "{0}\SQLServerDiagnosticQueries_{1}_{2}.sql" -f $Path, $doc.SQLVersion, "$($doc.FileYear)$($doc.FileMonth)"
            Invoke-TlsWebRequest -Uri $link -OutFile $filename -ErrorAction Stop
            Get-ChildItem -Path $filename
        } catch {
            Stop-Function -Message "Requesting and writing file failed: $_" -Target $filename -ErrorRecord $_
            return
        }
    }
}
tools\dbatools\functions\Select-DbaBackupInformation.ps1
function Select-DbaBackupInformation {
    <#
    .SYNOPSIS
        Select a subset of backups from a dbatools backup history object

    .DESCRIPTION
        Select-DbaBackupInformation filters out a subset of backups from the dbatools backup history object with parameters supplied.

    .PARAMETER BackupHistory
        A dbatools.BackupHistory object containing backup history records

    .PARAMETER RestoreTime
        The point in time you want to restore to

    .PARAMETER IgnoreLogs
        This switch will cause Log Backups to be ignored. So will restore to the last Full or Diff backup only

    .PARAMETER IgnoreDiffs
        This switch will cause Differential backups to be ignored. Unless IgnoreLogs is specified, restore to point in time will still occur, just using all available log backups

    .PARAMETER DatabaseName
        A string array of Database Names that you want to filter to

    .PARAMETER ServerName
        A string array of Server Names that you want to filter

    .PARAMETER ContinuePoints
        The Output of Get-RestoreContinuableDatabase while provides 'Database',redo_start_lsn,'FirstRecoveryForkID' values. Used to filter backups to continue a restore on a database
        Sets IgnoreDiffs, and also filters databases to only those within the ContinuePoints object, or the ContinuePoints object AND DatabaseName if both specified

    .PARAMETER LastRestoreType
        The Output of Get-DbaDbRestoreHistory -last
        This is used to check the last type of backup to a database to see if a differential backup can be restored

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Backup, Restore
        Author:Stuart Moore (@napalmgram), stuart-moore.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Select-DbaBackupInformation

    .EXAMPLE
        PS C:\> $Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\server1\backups$
        PS C:\> $FilteredBackups = $Backups | Select-DbaBackupInformation -RestoreTime (Get-Date).AddHours(-1)

        Returns all backups needed to restore all the backups in \\server1\backups$ to 1 hour ago

    .EXAMPLE
        PS C:\> $Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\server1\backups$
        PS C:\> $FilteredBackups = $Backups | Select-DbaBackupInformation -RestoreTime (Get-Date).AddHours(-1) -DatabaseName ProdFinance

        Returns all the backups needed to restore Database ProdFinance to an hour ago

    .EXAMPLE
        PS C:\> $Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\server1\backups$
        PS C:\> $FilteredBackups = $Backups | Select-DbaBackupInformation -RestoreTime (Get-Date).AddHours(-1) -IgnoreLogs

        Returns all the backups in \\server1\backups$ to restore to as close prior to 1 hour ago as can be managed with only full and differential backups

    .EXAMPLE
        PS C:\> $Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\server1\backups$
        PS C:\> $FilteredBackups = $Backups | Select-DbaBackupInformation -RestoreTime (Get-Date).AddHours(-1) -IgnoreDiffs

        Returns all the backups in \\server1\backups$ to restore to 1 hour ago using only Full and Diff backups.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [object]$BackupHistory,
        [DateTime]$RestoreTime = (get-date).addmonths(1),
        [switch]$IgnoreLogs,
        [switch]$IgnoreDiffs,
        [string[]]$DatabaseName,
        [string[]]$ServerName,
        [object]$ContinuePoints,
        [object]$LastRestoreType,
        [switch]$EnableException
    )
    begin {
        $InternalHistory = @()
        $IgnoreFull = $false
        if ((Test-Bound -ParameterName ContinuePoints) -and $null -ne $ContinuePoints) {
            Write-Message -Message "ContinuePoints provided so setting up for a continue" -Level Verbose
            $IgnoreFull = $true
            $Continue = $True
            if (Test-Bound -ParameterName DatabaseName) {
                $DatabaseName = $DatabaseName | Where-Object {$_ -in ($ContinuePoints | Select-Object -Property Database).Database}

                $DroppedDatabases = $DatabaseName | Where-Object {$_ -notin ($ContinuePoints | Select-Object -Property Database).Database}
                if ($null -ne $DroppedDatabases) {
                    Write-Message -Message "$($DroppedDatabases.join(',')) filtered out as not in ContinuePoints" -Level Verbose
                }
            } else {
                $DatabaseName = ($ContinuePoints | Select-Object -Property Database).Database
            }
        }
    }
    process {
        $internalHistory += $BackupHistory
    }

    end {
        ForEach ($History in $InternalHistory) {
            if ("RestoreTime" -notin $History.PSobject.Properties.name) {
                $History | Add-Member -Name 'RestoreTime' -Type NoteProperty -Value $RestoreTime
            }
        }
        if ((Test-Bound -ParameterName DatabaseName) -and '' -ne $DatabaseName) {
            Write-Message -Message "Filtering by DatabaseName" -Level Verbose
            #  $InternalHistory = $InternalHistory | Where-Object {$_.Database -in $DatabaseName}
        }

        if (Test-Bound -ParameterName ServerName) {
            Write-Message -Message "Filtering by ServerName" -Level Verbose
            $InternalHistory = $InternalHistory | Where-Object {$_.InstanceName -in $servername}
        }

        $Databases = ($InternalHistory | Select-Object -Property Database -unique).Database
        if ($continue -and $Databases.count -gt 1 -and $DatabaseName.count -gt 1) {
            Stop-Function -Message "Cannot perform continuing restores on multiple databases with renames, exiting"
            return
        }


        ForEach ($Database in $Databases) {
            #Cope with restores renaming the db
            # $database = the name of database in the backups being scanned
            # $databasefilter = the name of the database the backups are being restore to/against
            if ($null -ne $DatabaseName) {
                $databasefilter = $DatabaseName
            } else {
                $databasefilter = $database
            }

            if ($true -eq $Continue) {
                #Test if Database is in a continuing state and the LSN to continue from:
                if ($Databasefilter -in ($ContinuePoints | Select-Object -Property Database).Database) {
                    Write-Message -Message "$Database in ContinuePoints, will attmept to continue" -Level verbose
                    $IgnoreFull = $True
                    #Check what the last backup restored was
                    if (($LastRestoreType | Where-Object {$_.Database -eq $Databasefilter}).RestoreType -eq 'log') {
                        #log Backup last restored, so diffs cannot be used
                        $IgnoreDiffs = $true
                    } else {
                        #Last restore was a diff or full, so can restore diffs or logs
                        $IgnoreDiffs = $false
                    }
                } else {
                    Write-Message -Message "$Database not in ContinuePoints, will attmept normal restore" -Level Warning
                }
            }

            $dbhistory = @()
            $DatabaseHistory = $internalhistory | Where-Object {$_.Database -eq $Database}
            #For a standard restore, work out the full backup
            if ($false -eq $IgnoreFull) {
                $Full = $DatabaseHistory | Where-Object {$_.Type -in ('Full', 'Database') -and $_.Start -le $RestoreTime} | Sort-Object -Property LastLsn -Descending | Select-Object -First 1
                if ($full.Fullname) {
                    $full.Fullname = ($DatabaseHistory | Where-Object { $_.Type -in ('Full', 'Database') -and $_.BackupSetID -eq $Full.BackupSetID }).Fullname
                } else {
                    Stop-Function -Message "Fullname property not found. This could mean that a full backup could not be found or the command must be re-run with the -Continue switch."
                    return
                }
                $dbHistory += $full
            } elseif ($true -eq $IgnoreFull -and $false -eq $IgnoreDiffs) {
                #Fake the Full backup
                Write-Message -Message "Continuing, so setting a fake full backup from the existing database"
                $Full = [PsCustomObject]@{
                    CheckpointLSN = ($ContinuePoints | Where-Object {$_.Database -eq $DatabaseFilter}).differential_base_lsn
                }
            }

            if ($false -eq $IgnoreDiffs) {
                Write-Message -Message "processing diffs" -Level Verbose
                $Diff = $DatabaseHistory | Where-Object {$_.Type -in ('Differential', 'Database Differential') -and $_.Start -le $RestoreTime -and $_.DatabaseBackupLSN -eq $Full.CheckpointLSN} | Sort-Object -Property LastLsn -Descending | Select-Object -First 1
                if ($null -ne $Diff) {
                    if ($Diff.FullName) {
                        $Diff.FullName = ($DatabaseHistory | Where-Object { $_.Type -in ('Differential', 'Database Differential') -and $_.BackupSetID -eq $diff.BackupSetID }).Fullname
                    } else {
                        Stop-Function -Message "Fullname property not found. This could mean that a full backup could not be found or the command must be re-run with the -Continue switch."
                        return
                    }
                    $dbhistory += $Diff
                }
            }

            #Sort out the LSN for the log restores
            if ($null -ne ($dbHistory | Sort-Object -Property LastLsn -Descending | select-object -First 1).lastLsn) {
                #We have history so use this
                [bigint]$LogBaseLsn = ($dbHistory | Sort-Object -Property LastLsn -Descending | select-object -First 1).lastLsn.ToString()
                $FirstRecoveryForkID = $Full.FirstRecoveryForkID
                Write-Message -Level Verbose -Message "Found LogBaseLsn: $LogBaseLsn and FirstRecoveryForkID: $FirstRecoveryForkID"
            } else {
                Write-Message -Message "No full or diff, so attempting to pull from Continue informmation" -Level Verbose
                try {
                    [bigint]$LogBaseLsn = ($ContinuePoints | Where-Object {$_.Database -eq $DatabaseFilter}).redo_start_lsn
                    $FirstRecoveryForkID = ($ContinuePoints | Where-Object {$_.Database -eq $DatabaseFilter}).FirstRecoveryForkID
                    Write-Message -Level Verbose -Message "Found LogBaseLsn: $LogBaseLsn and FirstRecoveryForkID: $FirstRecoveryForkID from Continue information"
                } catch {
                    Stop-Function -Message "Failed to find LSN or RecoveryForkID for $DatabaseFilter" -Category InvalidOperation -Target $DatabaseFilter
                }
            }

            if ($true -eq $IgnoreFull -and $true -eq $IgnoreDiffs) {
                #Set a Fake starting LSN
            }

            if ($false -eq $IgnoreLogs) {
                $FilteredLogs = $DatabaseHistory | Where-Object {$_.Type -in ('Log', 'Transaction Log') -and $_.Start -le $RestoreTime -and $_.LastLSN.ToString() -ge $LogBaseLsn -and $_.FirstLSN -ne $_.LastLSN}  | Sort-Object -Property LastLsn, FirstLsn
                $GroupedLogs = $FilteredLogs | Group-Object -Property LastLSN, FirstLSN
                ForEach ($Group in $GroupedLogs) {
                    $Log = $DatabaseHistory | Where-Object { $_.BackupSetID -eq $Group.group[0].BackupSetID } | select-object -First 1
                    if ($Log.FullName) {
                        $Log.FullName = ($DatabaseHistory | Where-Object { $_.BackupSetID -eq $Group.group[0].BackupSetID }).Fullname
                    } else {
                        Stop-Function -Message "Fullname property not found. This could mean that a full backup could not be found or the command must be re-run with the -Continue switch."
                        return
                    }
                    #$dbhistory += $Log
                    $dbhistory += $DatabaseHistory | Where-Object {$_.BackupSetID -eq $Group.group[0].BackupSetID}
                }
                # Get Last T-log
                $dbHistory += $DatabaseHistory | Where-Object {$_.Type -in ('Log', 'Transaction Log') -and $_.End -ge $RestoreTime -and $_.DatabaseBackupLSN -eq $Full.CheckpointLSN} | Sort-Object -Property LastLsn, FirstLsn  | Select-Object -First 1
            }
            $dbhistory
        }
    }
}
tools\dbatools\functions\Set-DbaAgentAlert.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Set-DbaAgentAlert {
    <#
    .SYNOPSIS
        Set-DbaAgentAlert updates a the status of a SQL Agent Alert.

    .DESCRIPTION
        Set-DbaAgentAlert updates an alert in the SQL Server Agent with parameters supplied.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Alert
        The name of the alert.

    .PARAMETER NewName
        The new name for the alert.

    .PARAMETER Enabled
        Enabled the alert.

    .PARAMETER Disabled
        Disabled the alert.

    .PARAMETER Force
        The force parameter will ignore some errors in the parameters and assume defaults.

    .PARAMETER InputObject
        Enables piping alert objects

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Alert
        Author: Garry Bargsley (@gbargsley), garrybargsley.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaAgentAlert

    .EXAMPLE
        PS C:\> Set-DbaAgentAlert -SqlInstance sql1 -Alert 'Severity 025: Fatal Error' -Disabled

        Changes the alert to disabled.

    .EXAMPLE
        PS C:\> Set-DbaAgentAlert -SqlInstance sql1 -Alert 'Severity 025: Fatal Error', 'Error Number 825', 'Error Number 824' -Enabled

        Changes multiple alerts to enabled.

    .EXAMPLE
        PS C:\> Set-DbaAgentAlert -SqlInstance sql1, sql2, sql3 -Alert 'Severity 025: Fatal Error', 'Error Number 825', 'Error Number 824' -Enabled

        Changes multiple alerts to enabled on multiple servers.

    .EXAMPLE
        PS C:\> Set-DbaAgentAlert -SqlInstance sql1 -Alert 'Severity 025: Fatal Error' -Disabled -WhatIf

        Doesn't Change the alert but shows what would happen.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Alert,
        [string]$NewName,
        [switch]$Enabled,
        [switch]$Disabled,
        [switch]$Force,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Agent.Alert[]]$InputObject,
        [switch][Alias('Silent')]
        $EnableException
    )

    begin {
    }
    process {

        if (Test-FunctionInterrupt) { return }

        if ((-not $InputObject) -and (-not $Alert)) {
            Stop-Function -Message "You must specify an alert name or pipe in results from another command" -Target $sqlinstance
            return
        }

        foreach ($instance in $sqlinstance) {
            # Try connecting to the instance
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            foreach ($a in $Alert) {
                # Check if the alert exists
                if ($server.JobServer.Alerts.Name -notcontains $a) {
                    Stop-Function -Message "Alert $a doesn't exists on $instance" -Target $instance
                } else {
                    # Get the alert
                    try {
                        $InputObject += $server.JobServer.Alerts[$a]

                        # Refresh the object
                        $InputObject.Refresh()
                    } catch {
                        Stop-Function -Message "Something went wrong retrieving the alert" -Target $a -ErrorRecord $_ -Continue
                    }
                }
            }
        }

        foreach ($currentalert in $InputObject) {
            $server = $currentalert.Parent.Parent

            #region alert options
            # Settings the options for the alert
            if ($NewName) {
                Write-Message -Message "Setting alert name to $NewName" -Level Verbose
                $currentalert.Rename($NewName)
            }

            if ($Enabled) {
                Write-Message -Message "Setting alert to enabled" -Level Verbose
                $currentalert.IsEnabled = $true
            }

            if ($Disabled) {
                Write-Message -Message "Setting alert to disabled" -Level Verbose
                $currentalert.IsEnabled = $false
            }

            #endregion alert options

            # Execute
            if ($PSCmdlet.ShouldProcess($SqlInstance, "Changing the alert $a")) {
                try {
                    Write-Message -Message "Changing the alert" -Level Verbose

                    # Change the alert
                    $currentalert.Alter()
                } catch {
                    Stop-Function -Message "Something went wrong changing the alert" -ErrorRecord $_ -Target $instance -Continue
                }
                Get-DbaAgentAlert -SqlInstance $server | Where-Object Name -eq $currentalert.name
            }
        }
    }
}
tools\dbatools\functions\Set-DbaAgentJob.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Set-DbaAgentJob {
    <#
    .SYNOPSIS
        Set-DbaAgentJob updates a job.

    .DESCRIPTION
        Set-DbaAgentJob updates a job in the SQL Server Agent with parameters supplied.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Job
        The name of the job.

    .PARAMETER Schedule
        Schedule to attach to job. This can be more than one schedule.

    .PARAMETER ScheduleId
        Schedule ID to attach to job. This can be more than one schedule ID.

    .PARAMETER NewName
        The new name for the job.

    .PARAMETER Enabled
        Enabled the job.

    .PARAMETER Disabled
        Disabled the job

    .PARAMETER Description
        The description of the job.

    .PARAMETER StartStepId
        The identification number of the first step to execute for the job.

    .PARAMETER Category
        The category of the job.

    .PARAMETER OwnerLogin
        The name of the login that owns the job.

    .PARAMETER EventLogLevel
        Specifies when to place an entry in the Microsoft Windows application log for this job.
        Allowed values 0, "Never", 1, "OnSuccess", 2, "OnFailure", 3, "Always"
        The text value van either be lowercase, uppercase or something in between as long as the text is correct.

    .PARAMETER EmailLevel
        Specifies when to send an e-mail upon the completion of this job.
        Allowed values 0, "Never", 1, "OnSuccess", 2, "OnFailure", 3, "Always"
        The text value van either be lowercase, uppercase or something in between as long as the text is correct.

    .PARAMETER NetsendLevel
        Specifies when to send a network message upon the completion of this job.
        Allowed values 0, "Never", 1, "OnSuccess", 2, "OnFailure", 3, "Always"
        The text value van either be lowercase, uppercase or something in between as long as the text is correct.

    .PARAMETER PageLevel
        Specifies when to send a page upon the completion of this job.
        Allowed values 0, "Never", 1, "OnSuccess", 2, "OnFailure", 3, "Always"
        The text value van either be lowercase, uppercase or something in between as long as the text is correct.

    .PARAMETER EmailOperator
        The e-mail name of the operator to whom the e-mail is sent when EmailLevel is reached.

    .PARAMETER NetsendOperator
        The name of the operator to whom the network message is sent.

    .PARAMETER PageOperator
        The name of the operator to whom a page is sent.

    .PARAMETER DeleteLevel
        Specifies when to delete the job.
        Allowed values 0, "Never", 1, "OnSuccess", 2, "OnFailure", 3, "Always"
        The text value van either be lowercase, uppercase or something in between as long as the text is correct.

    .PARAMETER Force
        The force parameter will ignore some errors in the parameters and assume defaults.

    .PARAMETER InputObject
        Enables piping job objects

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Job
        Author: Sander Stad (@sqlstad), sqlstad.nl

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaAgentJob

    .EXAMPLE
        PS C:\> Set-DbaAgentJob sql1 -Job Job1 -Disabled

        Changes the job to disabled

    .EXAMPLE
        PS C:\> Set-DbaAgentJob sql1 -Job Job1 -OwnerLogin user1

        Changes the owner of the job

    .EXAMPLE
        PS C:\> Set-DbaAgentJob -SqlInstance sql1 -Job Job1 -EventLogLevel OnSuccess

        Changes the job and sets the notification to write to the Windows Application event log on success

    .EXAMPLE
        PS C:\> Set-DbaAgentJob -SqlInstance sql1 -Job Job1 -EmailLevel OnFailure -EmailOperator dba

        Changes the job and sets the notification to send an e-mail to the e-mail operator

    .EXAMPLE
        PS C:\> Set-DbaAgentJob -SqlInstance sql1 -Job Job1, Job2, Job3 -Enabled

        Changes multiple jobs to enabled

    .EXAMPLE
        PS C:\> Set-DbaAgentJob -SqlInstance sql1, sql2, sql3 -Job Job1, Job2, Job3 -Enabled

        Changes multiple jobs to enabled on multiple servers

    .EXAMPLE
        PS C:\> Set-DbaAgentJob -SqlInstance sql1 -Job Job1 -Description 'Just another job' -Whatif

        Doesn't Change the job but shows what would happen.

    .EXAMPLE
        PS C:\> Set-DbaAgentJob -SqlInstance sql1, sql2, sql3 -Job 'Job One' -Description 'Job One'

        Changes a job with the name "Job1" on multiple servers to have another description

    .EXAMPLE
        PS C:\> sql1, sql2, sql3 | Set-DbaAgentJob -Job Job1 -Description 'Job One'

        Changes a job with the name "Job1" on multiple servers to have another description using pipe line

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Job,
        [object[]]$Schedule,
        [int[]]$ScheduleId,
        [string]$NewName,
        [switch]$Enabled,
        [switch]$Disabled,
        [string]$Description,
        [int]$StartStepId,
        [string]$Category,
        [string]$OwnerLogin,
        [ValidateSet(0, "Never", 1, "OnSuccess", 2, "OnFailure", 3, "Always")]
        [object]$EventLogLevel,
        [ValidateSet(0, "Never", 1, "OnSuccess", 2, "OnFailure", 3, "Always")]
        [object]$EmailLevel,
        [ValidateSet(0, "Never", 1, "OnSuccess", 2, "OnFailure", 3, "Always")]
        [object]$NetsendLevel,
        [ValidateSet(0, "Never", 1, "OnSuccess", 2, "OnFailure", 3, "Always")]
        [object]$PageLevel,
        [string]$EmailOperator,
        [string]$NetsendOperator,
        [string]$PageOperator,
        [ValidateSet(0, "Never", 1, "OnSuccess", 2, "OnFailure", 3, "Always")]
        [object]$DeleteLevel,
        [switch]$Force,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Agent.Job[]]$InputObject,
        [switch][Alias('Silent')]
        $EnableException
    )

    begin {
        # Check of the event log level is of type string and set the integer value
        if (($EventLogLevel -notin 0, 1, 2, 3) -and ($null -ne $EventLogLevel)) {
            $EventLogLevel = switch ($EventLogLevel) { "Never" { 0 } "OnSuccess" { 1 } "OnFailure" { 2 } "Always" { 3 } }
        }

        # Check of the email level is of type string and set the integer value
        if (($EmailLevel -notin 0, 1, 2, 3) -and ($null -ne $EmailLevel)) {
            $EmailLevel = switch ($EmailLevel) { "Never" { 0 } "OnSuccess" { 1 } "OnFailure" { 2 } "Always" { 3 } }
        }

        # Check of the net send level is of type string and set the integer value
        if (($NetsendLevel -notin 0, 1, 2, 3) -and ($null -ne $NetsendLevel)) {
            $NetsendLevel = switch ($NetsendLevel) { "Never" { 0 } "OnSuccess" { 1 } "OnFailure" { 2 } "Always" { 3 } }
        }

        # Check of the page level is of type string and set the integer value
        if (($PageLevel -notin 0, 1, 2, 3) -and ($null -ne $PageLevel)) {
            $PageLevel = switch ($PageLevel) { "Never" { 0 } "OnSuccess" { 1 } "OnFailure" { 2 } "Always" { 3 } }
        }

        # Check of the delete level is of type string and set the integer value
        if (($DeleteLevel -notin 0, 1, 2, 3) -and ($null -ne $DeleteLevel)) {
            $DeleteLevel = switch ($DeleteLevel) { "Never" { 0 } "OnSuccess" { 1 } "OnFailure" { 2 } "Always" { 3 } }
        }

        # Check the e-mail operator name
        if (($EmailLevel -ge 1) -and (-not $EmailOperator)) {
            Stop-Function -Message "Please set the e-mail operator when the e-mail level parameter is set." -Target $sqlinstance
            return
        }

        # Check the e-mail operator name
        if (($NetsendLevel -ge 1) -and (-not $NetsendOperator)) {
            Stop-Function -Message "Please set the netsend operator when the netsend level parameter is set." -Target $sqlinstance
            return
        }

        # Check the e-mail operator name
        if (($PageLevel -ge 1) -and (-not $PageOperator)) {
            Stop-Function -Message "Please set the page operator when the page level parameter is set." -Target $sqlinstance
            return
        }
    }

    process {

        if (Test-FunctionInterrupt) { return }

        if ((-not $InputObject) -and (-not $Job)) {
            Stop-Function -Message "You must specify a job name or pipe in results from another command" -Target $sqlinstance
            return
        }

        foreach ($instance in $sqlinstance) {
            # Try connecting to the instance
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            foreach ($j in $Job) {

                # Check if the job exists
                if ($server.JobServer.Jobs.Name -notcontains $j) {
                    Stop-Function -Message "Job $j doesn't exists on $instance" -Target $instance
                } else {
                    # Get the job
                    try {
                        $InputObject += $server.JobServer.Jobs[$j]

                        # Refresh the object
                        $InputObject.Refresh()
                    } catch {
                        Stop-Function -Message "Something went wrong retrieving the job" -Target $j -ErrorRecord $_ -Continue
                    }
                }
            }
        }

        foreach ($currentjob in $InputObject) {
            $server = $currentjob.Parent.Parent

            #region job options
            # Settings the options for the job
            if ($NewName) {
                Write-Message -Message "Setting job name to $NewName" -Level Verbose
                $currentjob.Rename($NewName)
            }

            if ($Schedule) {
                # Loop through each of the schedules
                foreach ($s in $Schedule) {
                    if ($server.JobServer.SharedSchedules.Name -contains $s) {
                        # Get the schedule ID
                        $sID = $server.JobServer.SharedSchedules[$s].ID

                        # Add schedule to job
                        Write-Message -Message "Adding schedule id $sID to job" -Level Verbose
                        $currentjob.AddSharedSchedule($sID)
                    } else {
                        Stop-Function -Message "Schedule $s cannot be found on instance $instance" -Target $s -Continue
                    }

                }
            }

            if ($ScheduleId) {
                # Loop through each of the schedules IDs
                foreach ($sID in $ScheduleId) {
                    # Check if the schedule is
                    if ($server.JobServer.SharedSchedules.ID -contains $sID) {
                        # Add schedule to job
                        Write-Message -Message "Adding schedule id $sID to job" -Level Verbose
                        $currentjob.AddSharedSchedule($sID)

                    } else {
                        Stop-Function -Message "Schedule ID $sID cannot be found on instance $instance" -Target $sID -Continue
                    }
                }
            }

            if ($Enabled) {
                Write-Message -Message "Setting job to enabled" -Level Verbose
                $currentjob.IsEnabled = $true
            }

            if ($Disabled) {
                Write-Message -Message "Setting job to disabled" -Level Verbose
                $currentjob.IsEnabled = $false
            }

            if ($Description) {
                Write-Message -Message "Setting job description to $Description" -Level Verbose
                $currentjob.Description = $Description
            }

            if ($Category) {
                # Check if the job category exists
                if ($Category -notin $server.JobServer.JobCategories.Name) {
                    if ($Force) {
                        if ($PSCmdlet.ShouldProcess($instance, "Creating job category on $instance")) {
                            try {
                                # Create the category
                                New-DbaAgentJobCategory -SqlInstance $instance -Category $Category

                                Write-Message -Message "Setting job category to $Category" -Level Verbose
                                $currentjob.Category = $Category
                            } catch {
                                Stop-Function -Message "Couldn't create job category $Category from $instance" -Target $instance -ErrorRecord $_
                            }
                        }
                    } else {
                        Stop-Function -Message "Job category $Category doesn't exist on $instance. Use -Force to create it." -Target $instance
                        return
                    }
                } else {
                    Write-Message -Message "Setting job category to $Category" -Level Verbose
                    $currentjob.Category = $Category
                }
            }

            if ($StartStepId) {
                # Get the job steps
                $currentjobSteps = $currentjob.JobSteps

                # Check if there are any job steps
                if ($currentjobSteps.Count -ge 1) {
                    # Check if the start step id value is one of the job steps in the job
                    if ($currentjobSteps.ID -contains $StartStepId) {
                        Write-Message -Message "Setting job start step id to $StartStepId" -Level Verbose
                        $currentjob.StartStepID = $StartStepId
                    } else {
                        Write-Message -Message "The step id is not present in job $j on instance $instance" -Warning
                    }

                } else {
                    Stop-Function -Message "There are no job steps present for job $j on instance $instance" -Target $instance -Continue
                }

            }

            if ($OwnerLogin) {
                # Check if the login name is present on the instance
                if ($server.Logins.Name -contains $OwnerLogin) {
                    Write-Message -Message "Setting job owner login name to $OwnerLogin" -Level Verbose
                    $currentjob.OwnerLoginName = $OwnerLogin
                } else {
                    Stop-Function -Message "The given owner log in name $OwnerLogin does not exist on instance $instance" -Target $instance -Continue
                }
            }

            if ($EventLogLevel) {
                Write-Message -Message "Setting job event log level to $EventlogLevel" -Level Verbose
                $currentjob.EventLogLevel = $EventLogLevel
            }

            if ($EmailLevel) {
                # Check if the notifiction needs to be removed
                if ($EmailLevel -eq 0) {
                    # Remove the operator
                    $currentjob.OperatorToEmail = $null

                    # Remove the notification
                    $currentjob.EmailLevel = $EmailLevel
                } else {
                    # Check if either the operator e-mail parameter is set or the operator is set in the job
                    if ($EmailOperator -or $currentjob.OperatorToEmail) {
                        Write-Message -Message "Setting job e-mail level to $EmailLevel" -Level Verbose
                        $currentjob.EmailLevel = $EmailLevel
                    } else {
                        Stop-Function -Message "Cannot set e-mail level $EmailLevel without a valid e-mail operator name" -Target $instance -Continue
                    }
                }
            }

            if ($NetsendLevel) {
                # Check if the notifiction needs to be removed
                if ($NetsendLevel -eq 0) {
                    # Remove the operator
                    $currentjob.OperatorToNetSend = $null

                    # Remove the notification
                    $currentjob.NetSendLevel = $NetsendLevel
                } else {
                    # Check if either the operator netsend parameter is set or the operator is set in the job
                    if ($NetsendOperator -or $currentjob.OperatorToNetSend) {
                        Write-Message -Message "Setting job netsend level to $NetsendLevel" -Level Verbose
                        $currentjob.NetSendLevel = $NetsendLevel
                    } else {
                        Stop-Function -Message "Cannot set netsend level $NetsendLevel without a valid netsend operator name" -Target $instance -Continue
                    }
                }
            }

            if ($PageLevel) {
                # Check if the notifiction needs to be removed
                if ($PageLevel -eq 0) {
                    # Remove the operator
                    $currentjob.OperatorToPage = $null

                    # Remove the notification
                    $currentjob.PageLevel = $PageLevel
                } else {
                    # Check if either the operator pager parameter is set or the operator is set in the job
                    if ($PageOperator -or $currentjob.OperatorToPage) {
                        Write-Message -Message "Setting job pager level to $PageLevel" -Level Verbose
                        $currentjob.PageLevel = $PageLevel
                    } else {
                        Stop-Function -Message "Cannot set page level $PageLevel without a valid netsend operator name" -Target $instance -Continue
                    }
                }
            }

            # Check the current setting of the job's email level
            if ($EmailOperator) {
                # Check if the operator name is present
                if ($server.JobServer.Operators.Name -contains $EmailOperator) {
                    Write-Message -Message "Setting job e-mail operator to $EmailOperator" -Level Verbose
                    $currentjob.OperatorToEmail = $EmailOperator
                } else {
                    Stop-Function -Message "The e-mail operator name $EmailOperator does not exist on instance $instance. Exiting.." -Target $j -Continue
                }
            }

            if ($NetsendOperator) {
                # Check if the operator name is present
                if ($server.JobServer.Operators.Name -contains $NetsendOperator) {
                    Write-Message -Message "Setting job netsend operator to $NetsendOperator" -Level Verbose
                    $currentjob.OperatorToNetSend = $NetsendOperator
                } else {
                    Stop-Function -Message "The netsend operator name $NetsendOperator does not exist on instance $instance. Exiting.." -Target $j -Continue
                }
            }

            if ($PageOperator) {
                # Check if the operator name is present
                if ($server.JobServer.Operators.Name -contains $PageOperator) {
                    Write-Message -Message "Setting job pager operator to $PageOperator" -Level Verbose
                    $currentjob.OperatorToPage = $PageOperator
                } else {
                    Stop-Function -Message "The page operator name $PageOperator does not exist on instance $instance. Exiting.." -Target $instance -Continue
                }
            }

            if ($DeleteLevel) {
                Write-Message -Message "Setting job delete level to $DeleteLevel" -Level Verbose
                $currentjob.DeleteLevel = $DeleteLevel
            }
            #endregion job options

            # Execute
            if ($PSCmdlet.ShouldProcess($SqlInstance, "Changing the job $j")) {
                try {
                    Write-Message -Message "Changing the job" -Level Verbose

                    # Change the job
                    $currentjob.Alter()
                } catch {
                    Stop-Function -Message "Something went wrong changing the job" -ErrorRecord $_ -Target $instance -Continue
                }
                Get-DbaAgentJob -SqlInstance $server | Where-Object Name -eq $currentjob.name
            }
        }
    }

    end {
        Write-Message -Message "Finished changing job(s)" -Level Verbose
    }
}
tools\dbatools\functions\Set-DbaAgentJobCategory.ps1
function Set-DbaAgentJobCategory {
    <#
    .SYNOPSIS
        Set-DbaAgentJobCategory changes a job category.

    .DESCRIPTION
        Set-DbaAgentJobCategory makes it possible to change a job category.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Category
        The name of the category

    .PARAMETER NewName
        New name of the job category

    .PARAMETER Force
        The force parameter will ignore some errors in the parameters and assume defaults.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Job, JobCategory
        Author: Sander Stad (@sqlstad), sqlstad.nl

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaAgentJobCategory

    .EXAMPLE
        PS C:\> New-DbaAgentJobCategory -SqlInstance sql1 -Category 'Category 1' -NewName 'Category 2'

        Change the name of the category from 'Category 1' to 'Category 2'.

    .EXAMPLE
        PS C:\> Set-DbaAgentJobCategory -SqlInstance sql1, sql2 -Category Category1, Category2 -NewName cat1, cat2

        Rename multiple jobs in one go on multiple servers.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseOutputTypeCorrectly", "", Justification = "PSSA Rule Ignored by BOH")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [ValidateNotNullOrEmpty()]
        [string[]]$Category,
        [string[]]$NewName,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        # Create array list to hold the results
        $collection = New-Object System.Collections.ArrayList

        # Check if multiple categories are being changed
        if ($Category.Count -gt 1 -and $NewName.Count -eq 1) {
            Stop-Function -Message "You cannot rename multiple jobs to the same name" -Target $instance
        }
    }

    process {

        foreach ($instance in $sqlinstance) {
            # Try connecting to the instance
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            # Loop through each of the categories
            foreach ($cat in $Category) {
                # Check if the category exists
                if ($cat -notin $server.JobServer.JobCategories.Name) {
                    Stop-Function -Message "Job category $cat doesn't exist on $instance" -Target $instance -Continue
                }

                # Check if the category already exists
                if ($NewName -and ($NewName -in $server.JobServer.JobCategories.Name)) {
                    Stop-Function -Message "Job category $NewName already exists on $instance" -Target $instance -Continue
                }

                if ($PSCmdlet.ShouldProcess($instance, "Changing the job category $Category")) {
                    try {
                        # Get the job category object
                        $currentCategory = $server.JobServer.JobCategories[$cat]

                        Write-Message -Message "Changing job category $cat" -Level Verbose

                        # Get and set the original and new values
                        $originalCategoryName = $currentCategory.Name
                        $newCategoryName = $null

                        # Check if the job category needs to be renamed
                        if ($NewName) {
                            $currentCategory.Rename($NewName[$Category.IndexOf($cat)])
                            $newCategoryName = $currentCategory.Name
                        }

                        Get-DbaAgentJobCategory -SqlInstance $server -Category $newCategoryName
                    } catch {
                        Stop-Function -Message "Something went wrong changing the job category $cat on $instance" -Target $cat -Continue -ErrorRecord $_
                    }
                }
            }
        }
    }
    end {
        Write-Message -Message "Finished changing job category." -Level Verbose
    }
}
tools\dbatools\functions\Set-DbaAgentJobOutputFile.ps1
function Set-DbaAgentJobOutputFile {
    <#
    .Synopsis
        Set the output file for a step within an Agent job.

    .DESCRIPTION
        Sets the Output File for a step of an agent job with the Job Names and steps provided dynamically if required

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SQLCredential
        Credential object used to connect to the SQL Server as a different user be it Windows or SQL Server. Windows users are determined by the existence of a backslash, so if you are intending to use an alternative Windows connection instead of a SQL login, ensure it contains a backslash.

    .PARAMETER Job
        The job to process - this list is auto-populated from the server.

    .PARAMETER Step
        The Agent Job Step to provide Output File Path for. Also available dynamically

    .PARAMETER OutputFile
        The Full Path to the New Output file

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Job, SqlAgent
        Author: Rob Sewell, https://sqldbawithabeard.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Set-DbaAgentJobOutputFile -SqlInstance SERVERNAME -Job 'The Agent Job' -OutPutFile E:\Logs\AgentJobStepOutput.txt

        Sets the Job step for The Agent job on SERVERNAME to E:\Logs\AgentJobStepOutput.txt

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Parameter(Mandatory, HelpMessage = 'The SQL Server Instance',
            ValueFromPipeline,
            ValueFromPipelineByPropertyName = $true,
            ValueFromRemainingArguments = $false,
            Position = 0)]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Parameter(HelpMessage = 'SQL Credential',
            ValueFromPipeline,
            ValueFromPipelineByPropertyName = $true,
            ValueFromRemainingArguments = $false)]
        [PSCredential]$SqlCredential,
        [object[]]$Job,
        [Parameter(HelpMessage = 'The Job Step name',
            ValueFromPipeline,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [object[]]$Step,
        [Parameter(Mandatory, HelpMessage = 'The Full Output File Path',
            ValueFromPipeline,
            ValueFromPipelineByPropertyName = $true,
            ValueFromRemainingArguments = $false)]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [string]$OutputFile,
        [Alias('Silent')]
        [switch]$EnableException
    )

    foreach ($instance in $sqlinstance) {
        try {
            $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
        } catch {
            Write-Message -Level Warning -Message "Failed to connect to: $instance"
            continue
        }

        if (!$Job) {
            # This is because jobname isn't yet required
            Write-Message -Level Warning -Message "You must specify a job using the -Job parameter."
            return
        }

        foreach ($name in $Job) {
            $currentJob = $server.JobServer.Jobs[$name]

            if ($Step) {
                $steps = $currentJob.JobSteps | Where-Object Name -in $Step

                if (!$steps) {
                    Write-Message -Level Warning -Message "$Step didn't return any steps"
                    return
                }
            } else {
                if (($currentJob.JobSteps).Count -gt 1) {
                    Write-Message -Level Output -Message "Which Job Step do you wish to add output file to?"
                    $steps = $currentJob.JobSteps | Out-GridView -Title "Choose the Job Steps to add an output file to" -PassThru -Verbose
                } else {
                    $steps = $currentJob.JobSteps
                }
            }

            if (!$steps) {
                $steps = $currentJob.JobSteps
            }

            foreach ($jobstep in $steps) {
                $currentoutputfile = $jobstep.OutputFileName

                Write-Message -Level Verbose -Message "Current Output File for $currentJob is $currentoutputfile"
                Write-Message -Level Verbose -Message "Adding $OutputFile to $jobstep for $currentJob"

                try {
                    if ($Pscmdlet.ShouldProcess($jobstep, "Changing Output File from $currentoutputfile to $OutputFile")) {
                        $jobstep.OutputFileName = $OutputFile
                        $jobstep.Alter()
                        $jobstep.Refresh()

                        [pscustomobject]@{
                            ComputerName   = $server.ComputerName
                            InstanceName   = $server.ServiceName
                            SqlInstance    = $server.DomainInstanceName
                            Job            = $currentJob.Name
                            JobStep        = $jobstep.Name
                            OutputFileName = $currentoutputfile
                        }
                    }
                } catch {
                    Stop-Function -Message "Failed to add $OutputFile to $jobstep for $currentJob" -InnerErrorRecord $_ -Target $currentJob
                }
            }
        }
    }
}
tools\dbatools\functions\Set-DbaAgentJobOwner.ps1
function Set-DbaAgentJobOwner {
    <#
    .SYNOPSIS
        Sets SQL Agent job owners with a desired login if jobs do not match that owner.

    .DESCRIPTION
        This function alters SQL Agent Job ownership to match a specified login if their current owner does not match the target login. By default, the target login will be 'sa',
        but the the user may specify a different login for ownership. This be applied to all jobs or only to a select collection of jobs.

        Best practice reference: http://sqlmag.com/blog/sql-server-tip-assign-ownership-jobs-sysadmin-account

        If the 'sa' account was renamed, the new name will be used.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Job
        Specifies the job(s) to process. Options for this list are auto-populated from the server. If unspecified, all jobs will be processed.

    .PARAMETER ExcludeJob
        Specifies the job(s) to exclude from processing. Options for this list are auto-populated from the server.

    .PARAMETER InputObject
        Enables piped input from Get-DbaAgentJob

    .PARAMETER Login
        Specifies the login that you wish check for ownership. This defaults to 'sa' or the sysadmin name if sa was renamed. This must be a valid security principal which exists on the target server.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Job
        Author: Michael Fal (@Mike_Fal), http://mikefal.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaAgentJobOwner

    .EXAMPLE
        PS C:\> Set-DbaAgentJobOwner -SqlInstance localhost

        Sets SQL Agent Job owner to sa on all jobs where the owner does not match sa.

    .EXAMPLE
        PS C:\> Set-DbaAgentJobOwner -SqlInstance localhost -Login DOMAIN\account

        Sets SQL Agent Job owner to 'DOMAIN\account' on all jobs where the owner does not match 'DOMAIN\account'. Note
        that Login must be a valid security principal that exists on the target server.

    .EXAMPLE
        PS C:\> Set-DbaAgentJobOwner -SqlInstance localhost -Job job1, job2

        Sets SQL Agent Job owner to 'sa' on the job1 and job2 jobs if their current owner does not match 'sa'.

    .EXAMPLE
        PS C:\> 'sqlserver','sql2016' | Set-DbaAgentJobOwner

        Sets SQL Agent Job owner to sa on all jobs where the owner does not match sa on both sqlserver and sql2016.

    .EXAMPLE
        PS C:\> Get-DbaAgentJob -SqlInstance vmsql | Where-Object OwnerLoginName -eq login1 | Set-DbaAgentJobOwner -TargetLogin login2 | Out-Gridview

        Sets SQL Agent Job owner to login2 where their current owner is login1 on instance vmsql. Send result to gridview.
    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Jobs")]
        [object[]]$Job,
        [object[]]$ExcludeJob,
        [Parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Agent.Job[]]$InputObject,
        [Alias("TargetLogin")]
        [string]$Login,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Set-DbaJobOwner
    }
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            #Get job list. If value for -Job is passed, massage to make it a string array.
            #Otherwise, use all jobs on the instance where owner not equal to -TargetLogin
            Write-Message -Level Verbose -Message "Gathering jobs to update."

            if ($Job) {
                $jobcollection = $server.JobServer.Jobs | Where-Object {$Job -contains $_.Name}
            } else {
                $jobcollection = $server.JobServer.Jobs
            }

            if ($ExcludeJob) {
                $jobcollection = $jobcollection | Where-Object { $ExcludeJob -notcontains $_.Name }
            }

            $InputObject += $jobcollection
        }

        Write-Message -Level Verbose -Message "Updating $($InputObject.Count) job(s)."
        foreach ($agentJob in $InputObject) {
            $jobname = $agentJob.Name
            $server = $agentJob.Parent.Parent

            if (-not $Login) {
                # dynamic sa name for orgs who have changed their sa name
                $newLogin = ($server.logins | Where-Object { $_.id -eq 1 }).Name
            } else {
                $newLogin = $Login
            }

            #Validate login
            if ($agentJob.OwnerLoginName -eq $newLogin) {
                $status = 'Skipped'
                $notes = "Owner already set"
            } else {
                if (($server.Logins.Name) -notcontains $newLogin) {
                    $status = 'Failed'
                    $notes = "Login $newLogin not valid"
                } else {
                    if ($server.logins[$newLogin].LoginType -eq 'WindowsGroup') {
                        $status = 'Failed'
                        $notes = "$newLogin is a Windows Group and can not be a job owner."
                    } else {
                        if ($PSCmdlet.ShouldProcess($instance, "Setting job owner for $jobname to $newLogin")) {
                            try {
                                Write-Message -Level Verbose -Message "Setting job owner for $jobname to $newLogin on $instance."
                                #Set job owner to $TargetLogin (default 'sa')
                                $agentJob.OwnerLoginName = $newLogin
                                $agentJob.Alter()
                                $status = 'Succesful'
                                $notes = ''
                            } catch {
                                Stop-Function -Message "Issue setting job owner on $jobName." -Target $jobName -InnerErrorRecord $_ -Category InvalidOperation
                            }
                        }
                    }
                }
            }
            Add-Member -Force -InputObject $agentJob -MemberType NoteProperty -Name ComputerName -value $server.ComputerName
            Add-Member -Force -InputObject $agentJob -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
            Add-Member -Force -InputObject $agentJob -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
            Add-Member -Force -InputObject $agentJob -MemberType NoteProperty -Name Status -value $status
            Add-Member -Force -InputObject $agentJob -MemberType NoteProperty -Name Notes -value $notes
            Select-DefaultView -InputObject $agentJob -Property ComputerName, InstanceName, SqlInstance, Name, Category, OwnerLoginName, Status, Notes
        }
    }
}
tools\dbatools\functions\Set-DbaAgentJobStep.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Set-DbaAgentJobStep {
    <#
    .SYNOPSIS
        Set-DbaAgentJobStep updates a job step.

    .DESCRIPTION
        Set-DbaAgentJobStep updates a job step in the SQL Server Agent with parameters supplied.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Job
        The name of the job. Can be null if the the job id is being used.

    .PARAMETER StepName
        The name of the step.

    .PARAMETER NewName
        The new name for the step in case it needs to be renamed.

    .PARAMETER SubSystem
        The subsystem used by the SQL Server Agent service to execute command.
        Allowed values 'ActiveScripting','AnalysisCommand','AnalysisQuery','CmdExec','Distribution','LogReader','Merge','PowerShell','QueueReader','Snapshot','Ssis','TransactSql'

    .PARAMETER Command
        The commands to be executed by SQLServerAgent service through subsystem.

    .PARAMETER CmdExecSuccessCode
        The value returned by a CmdExec subsystem command to indicate that command executed successfully.

    .PARAMETER OnSuccessAction
        The action to perform if the step succeeds.
        Allowed values  "QuitWithSuccess" (default), "QuitWithFailure", "GoToNextStep", "GoToStep".
        The text value van either be lowercase, uppercase or something in between as long as the text is correct.

    .PARAMETER OnSuccessStepId
        The ID of the step in this job to execute if the step succeeds and OnSuccessAction is "GoToNextStep".

    .PARAMETER OnFailAction
        The action to perform if the step fails.
        Allowed values  "QuitWithSuccess" (default), "QuitWithFailure", "GoToNextStep", "GoToStep".
        The text value van either be lowercase, uppercase or something in between as long as the text is correct.

    .PARAMETER OnFailStepId
        The ID of the step in this job to execute if the step fails and OnFailAction is "GoToNextStep".

    .PARAMETER Database
        The name of the database in which to execute a Transact-SQL step. The default is 'master'.

    .PARAMETER DatabaseUser
        The name of the user account to use when executing a Transact-SQL step. The default is 'sa'.

    .PARAMETER RetryAttempts
        The number of retry attempts to use if this step fails. The default is 0.

    .PARAMETER RetryInterval
        The amount of time in minutes between retry attempts. The default is 0.

    .PARAMETER OutputFileName
        The name of the file in which the output of this step is saved.

    .PARAMETER Flag
        Sets the flag(s) for the job step.

        Flag                                    Description
        ----------------------------------------------------------------------------
        AppendAllCmdExecOutputToJobHistory      Job history, including command output, is appended to the job history file.
        AppendToJobHistory                      Job history is appended to the job history file.
        AppendToLogFile                         Job history is appended to the SQL Server log file.
        AppendToTableLog                        Job history is appended to a log table.
        LogToTableWithOverwrite                 Job history is written to a log table, overwriting previous contents.
        None                                    Job history is not appended to a file.
        ProvideStopProcessEvent                 Job processing is stopped.

    .PARAMETER ProxyName
        The name of the proxy that the job step runs as.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER Force
        The force parameter will ignore some errors in the parameters and assume defaults.

    .NOTES
        Tags: Agent, Job, JobStep
        Author: Sander Stad (@sqlstad), sqlstad.nl

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaAgentJobStep

    .EXAMPLE
        PS C:\> Set-DbaAgentJobStep -SqlInstance sql1 -Job Job1 -StepName Step1 -NewName Step2

        Changes the name of the step in "Job1" with the name Step1 to Step2

    .EXAMPLE
        PS C:\> Set-DbaAgentJobStep -SqlInstance sql1 -Job Job1 -StepName Step1 -Database msdb

        Changes the database of the step in "Job1" with the name Step1 to msdb

    .EXAMPLE
        PS C:\> Set-DbaAgentJobStep -SqlInstance sql1 -Job Job1, Job2 -StepName Step1 -Database msdb

        Changes job steps in multiple jobs with the name Step1 to msdb

    .EXAMPLE
        PS C:\> Set-DbaAgentJobStep -SqlInstance sql1, sql2, sql3 -Job Job1, Job2 -StepName Step1 -Database msdb

        Changes job steps in multiple jobs on multiple servers with the name Step1 to msdb

    .EXAMPLE
        PS C:\> Set-DbaAgentJobStep -SqlInstance sql1, sql2, sql3 -Job Job1 -StepName Step1 -Database msdb

        Changes the database of the step in "Job1" with the name Step1 to msdb for multiple servers

    .EXAMPLE
        PS C:\> sql1, sql2, sql3 | Set-DbaAgentJobStep -Job Job1 -StepName Step1 -Database msdb

        Changes the database of the step in "Job1" with the name Step1 to msdb for multiple servers using pipeline

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [object[]]$Job,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$StepName,
        [string]$NewName,
        [ValidateSet('ActiveScripting', 'AnalysisCommand', 'AnalysisQuery', 'CmdExec', 'Distribution', 'LogReader', 'Merge', 'PowerShell', 'QueueReader', 'Snapshot', 'Ssis', 'TransactSql')]
        [string]$Subsystem,
        [string]$Command,
        [int]$CmdExecSuccessCode,
        [ValidateSet('QuitWithSuccess', 'QuitWithFailure', 'GoToNextStep', 'GoToStep')]
        [string]$OnSuccessAction,
        [int]$OnSuccessStepId,
        [ValidateSet('QuitWithSuccess', 'QuitWithFailure', 'GoToNextStep', 'GoToStep')]
        [string]$OnFailAction,
        [int]$OnFailStepId,
        [string]$Database,
        [string]$DatabaseUser,
        [int]$RetryAttempts,
        [int]$RetryInterval,
        [string]$OutputFileName,
        [ValidateSet('AppendAllCmdExecOutputToJobHistory', 'AppendToJobHistory', 'AppendToLogFile', 'LogToTableWithOverwrite', 'None', 'ProvideStopProcessEvent')]
        [string[]]$Flag,
        [string]$ProxyName,
        [Alias('Silent')]
        [switch]$EnableException,
        [switch]$Force
    )

    begin {
        # Check the parameter on success step id
        if (($OnSuccessAction -ne 'GoToStep') -and ($OnSuccessStepId -ge 1)) {
            Stop-Function -Message "Parameter OnSuccessStepId can only be used with OnSuccessAction 'GoToStep'." -Target $SqlInstance
            return
        }

        # Check the parameter on success step id
        if (($OnFailAction -ne 'GoToStep') -and ($OnFailStepId -ge 1)) {
            Stop-Function -Message "Parameter OnFailStepId can only be used with OnFailAction 'GoToStep'." -Target $SqlInstance
            return
        }
    }

    process {

        if (Test-FunctionInterrupt) { return }

        foreach ($instance in $sqlinstance) {

            # Try connecting to the instance
            try {
                $Server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            foreach ($j in $Job) {

                # Check if the job exists
                if ($Server.JobServer.Jobs.Name -notcontains $j) {
                    Stop-Function -Message "Job $j doesn't exists on $instance" -Target $instance -Continue
                } else {
                    # Check if the job step exists
                    if ($Server.JobServer.Jobs[$j].JobSteps.Name -notcontains $StepName) {
                        Stop-Function -Message "Step $StepName doesn't exists for job $j" -Target $instance -Continue
                    } else {

                        # Get the job step
                        $JobStep = $Server.JobServer.Jobs[$j].JobSteps[$StepName]

                        Write-Message -Message "Modifying job $j on $instance" -Level Verbose

                        #region job step options
                        # Setting the options for the job step
                        if ($NewName) {
                            Write-Message -Message "Setting job step name to $NewName" -Level Verbose
                            $JobStep.Rename($NewName)
                        }

                        if ($Subsystem) {
                            Write-Message -Message "Setting job step subsystem to $Subsystem" -Level Verbose
                            $JobStep.Subsystem = $Subsystem
                        }

                        if ($Command) {
                            Write-Message -Message "Setting job step command to $Command" -Level Verbose
                            $JobStep.Command = $Command
                        }

                        if ($CmdExecSuccessCode) {
                            Write-Message -Message "Setting job step command exec success code to $CmdExecSuccessCode" -Level Verbose
                            $JobStep.CommandExecutionSuccessCode = $CmdExecSuccessCode
                        }

                        if ($OnSuccessAction) {
                            Write-Message -Message "Setting job step success action to $OnSuccessAction" -Level Verbose
                            $JobStep.OnSuccessAction = $OnSuccessAction
                        }

                        if ($OnSuccessStepId) {
                            Write-Message -Message "Setting job step success step id to $OnSuccessStepId" -Level Verbose
                            $JobStep.OnSuccessStep = $OnSuccessStepId
                        }

                        if ($OnFailAction) {
                            Write-Message -Message "Setting job step fail action to $OnFailAction" -Level Verbose
                            $JobStep.OnFailAction = $OnFailAction
                        }

                        if ($OnFailStepId) {
                            Write-Message -Message "Setting job step fail step id to $OnFailStepId" -Level Verbose
                            $JobStep.OnFailStep = $OnFailStepId
                        }

                        if ($Database) {
                            # Check if the database is present on the server
                            if ($Server.Databases.Name -contains $Database) {
                                Write-Message -Message "Setting job step database name to $Database" -Level Verbose
                                $JobStep.DatabaseName = $Database
                            } else {
                                Stop-Function -Message "The database is not present on instance $instance." -Target $instance -Continue
                            }
                        }

                        if (($DatabaseUser) -and ($Database)) {
                            # Check if the username is present in the database
                            if ($Server.Databases[$Database].Users.Name -contains $DatabaseUser) {
                                Write-Message -Message "Setting job step database username to $DatabaseUser" -Level Verbose
                                $JobStep.DatabaseUserName = $DatabaseUser
                            } else {
                                Stop-Function -Message "The database user is not present in the database $Database on instance $instance." -Target $instance -Continue
                            }
                        }

                        if ($RetryAttempts) {
                            Write-Message -Message "Setting job step retry attempts to $RetryAttempts" -Level Verbose
                            $JobStep.RetryAttempts = $RetryAttempts
                        }

                        if ($RetryInterval) {
                            Write-Message -Message "Setting job step retry interval to $RetryInterval" -Level Verbose
                            $JobStep.RetryInterval = $RetryInterval
                        }

                        if ($OutputFileName) {
                            Write-Message -Message "Setting job step output file name to $OutputFileName" -Level Verbose
                            $JobStep.OutputFileName = $OutputFileName
                        }

                        if ($ProxyName) {
                            # Check if the proxy exists
                            if ($Server.JobServer.ProxyAccounts.Name -contains $ProxyName) {
                                Write-Message -Message "Setting job step proxy name to $ProxyName" -Level Verbose
                                $JobStep.ProxyName = $ProxyName
                            } else {
                                Stop-Function -Message "The proxy name $ProxyName doesn't exist on instance $instance." -Target $instance -Continue
                            }
                        }

                        if ($Flag.Count -ge 1) {
                            Write-Message -Message "Setting job step flag(s) to $($Flags -join ',')" -Level Verbose
                            $JobStep.JobStepFlags = $Flag
                        }
                        #region job step options

                        # Execute
                        if ($PSCmdlet.ShouldProcess($instance, "Changing the job step $StepName for job $j")) {
                            try {
                                Write-Message -Message "Changing the job step $StepName for job $j" -Level Verbose

                                # Change the job step
                                $JobStep.Alter()
                            } catch {
                                Stop-Function -Message "Something went wrong changing the job step" -ErrorRecord $_ -Target $instance -Continue
                            }
                        }
                    }
                }

            } # foreach object job
        } # foreach object intance
    } # process

    end {
        if (Test-FunctionInterrupt) { return }
        Write-Message -Message "Finished changing job step(s)" -Level Verbose
    }
}
tools\dbatools\functions\Set-DbaAgentSchedule.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Set-DbaAgentSchedule {
    <#
    .SYNOPSIS
        Set-DbaAgentSchedule updates a schedule in the msdb database.

    .DESCRIPTION
        Set-DbaAgentSchedule will help update a schedule for a job. It does not attach the schedule to a job.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Job
        The name of the job that has the schedule.

    .PARAMETER ScheduleName
        The name of the schedule.

    .PARAMETER NewName
        The new name for the schedule.

    .PARAMETER Enabled
        Set the schedule to enabled.

    .PARAMETER Disabled
        Set the schedule to disabled.

    .PARAMETER FrequencyType
        A value indicating when a job is to be executed.
        Allowed values are 1, "Once", 4, "Daily", 8, "Weekly", 16, "Monthly", 32, "MonthlyRelative", 64, "AgentStart", 128 or "IdleComputer"

    .PARAMETER FrequencyInterval
        The days that a job is executed
        Allowed values are 1, "Sunday", 2, "Monday", 4, "Tuesday", 8, "Wednesday", 16, "Thursday", 32, "Friday", 64, "Saturday", 62, "Weekdays", 65, "Weekend", 127, "EveryDay".
        If 62, "Weekdays", 65, "Weekend", 127, "EveryDay" is used it overwwrites any other value that has been passed before.

    .PARAMETER FrequencySubdayType
        Specifies the units for the subday FrequencyInterval.
        Allowed values are 1, "Time", 2, "Seconds", 4, "Minutes", 8 or "Hours"

    .PARAMETER FrequencySubdayInterval
        The number of subday type periods to occur between each execution of a job.

    .PARAMETER FrequencySubdayInterval
        The number of subday type periods to occur between each execution of a job.

    .PARAMETER FrequencyRelativeInterval
        A job's occurrence of FrequencyInterval in each month, if FrequencyInterval is 32 (monthlyrelative).

    .PARAMETER FrequencyRecurrenceFactor
        The number of weeks or months between the scheduled execution of a job. FrequencyRecurrenceFactor is used only if FrequencyType is 8, "Weekly", 16, "Monthly", 32 or "MonthlyRelative".

    .PARAMETER StartDate
        The date on which execution of a job can begin.

    .PARAMETER EndDate
        The date on which execution of a job can stop.

    .PARAMETER StartTime
        The time on any day to begin execution of a job. Format HHMMSS / 24 hour clock.
        Example: '010000' for 01:00:00 AM.
        Example: '140000' for 02:00:00 PM.

    .PARAMETER EndTime
        The time on any day to end execution of a job. Format HHMMSS / 24 hour clock.
        Example: '010000' for 01:00:00 AM.
        Example: '140000' for 02:00:00 PM.

    .PARAMETER Owner
        The name of the server principal that owns the schedule. If no value is given the schedule is owned by the creator.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER Force
        The force parameter will ignore some errors in the parameters and assume defaults.
        It will also remove the any present schedules with the same name for the specific job.

    .NOTES
        Tags: Agent, Job, JobStep
        Author: Sander Stad (@sqlstad, sqlstad.nl)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaAgentSchedule

    .EXAMPLE
        PS C:\> Set-DbaAgentSchedule -SqlInstance sql1 -Job Job1 -ScheduleName daily -Enabled

        Changes the schedule for Job1 with the name 'daily' to enabled

    .EXAMPLE
        PS C:\> Set-DbaAgentSchedule -SqlInstance sql1 -Job Job1 -ScheduleName daily -NewName weekly -FrequencyType Weekly -FrequencyInterval Monday, Wednesday, Friday

        Changes the schedule for Job1 with the name daily to have a new name weekly

    .EXAMPLE
        PS C:\> Set-DbaAgentSchedule -SqlInstance sql1 -Job Job1, Job2, Job3 -ScheduleName daily -StartTime '230000'

        Changes the start time of the schedule for Job1 to 11 PM for multiple jobs

    .EXAMPLE
        PS C:\> Set-DbaAgentSchedule -SqlInstance sql1, sql2, sql3 -Job Job1 -ScheduleName daily -Enabled

        Changes the schedule for Job1 with the name daily to enabled on multiple servers

    .EXAMPLE
        PS C:\> sql1, sql2, sql3 | Set-DbaAgentSchedule -Job Job1 -ScheduleName 'daily' -Enabled

        Changes the schedule for Job1 with the name 'daily' to enabled on multiple servers using pipe line

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Parameter(Mandatory, ValueFromPipeline)]
        [ValidateNotNullOrEmpty()]
        [object[]]$Job,
        [Parameter(Mandatory, ValueFromPipeline)]
        [ValidateNotNullOrEmpty()]
        [string]$ScheduleName,
        [string]$NewName,
        [switch]$Enabled,
        [switch]$Disabled,
        [ValidateSet(1, "Once", 4, "Daily", 8, "Weekly", 16, "Monthly", 32, "MonthlyRelative", 64, "AgentStart", 128, "IdleComputer")]
        [object]$FrequencyType,
        [object[]]$FrequencyInterval,
        [ValidateSet(1, "Time", 2, "Seconds", 4, "Minutes", 8, "Hours")]
        [object]$FrequencySubdayType,
        [int]$FrequencySubdayInterval,
        [ValidateSet('Unused', 'First', 'Second', 'Third', 'Fourth', 'Last')]
        [object]$FrequencyRelativeInterval,
        [int]$FrequencyRecurrenceFactor,
        [string]$StartDate,
        [string]$EndDate,
        [string]$StartTime,
        [string]$EndTime,
        [Alias('Silent')]
        [switch]$EnableException,
        [switch]$Force
    )

    begin {

        # Check of the FrequencyType value is of type string and set the integer value
        if ($FrequencyType -notin 0, 1, 4, 8, 16, 32, 64, 128) {
            [int]$FrequencyType = switch ($FrequencyType) { "Once" { 1 } "Daily" { 4 } "Weekly" { 8 } "Monthly" { 16 } "MonthlyRelative" { 32 } "AgentStart" { 64 } "IdleComputer" { 128 } }
        }

        # Check of the FrequencySubdayType value is of type string and set the integer value
        if ($FrequencySubdayType -notin 0, 1, 2, 4, 8) {
            [int]$FrequencySubdayType = switch ($FrequencySubdayType) { "Time" { 1 } "Seconds" { 2 } "Minutes" { 4 } "Hours" { 8 } default {0} }
        }

        # Check if the interval is valid
        if (($FrequencyType -eq 4) -and ($FrequencyInterval -lt 1 -or $FrequencyInterval -ge 365)) {
            Stop-Function -Message "The interval $FrequencyInterval needs to be higher than 1 and lower than 365 when using a daily frequency the interval." -Target $SqlInstance
            return
        }

        # Check if the recurrence factor is set for weekly or monthly interval
        if (($FrequencyType -in 8, 16) -and $FrequencyRecurrenceFactor -lt 1) {
            if ($Force) {
                $FrequencyRecurrenceFactor = 1
                Write-Message -Message "Recurrence factor not set for weekly or monthly interval. Setting it to $FrequencyRecurrenceFactor." -Level Verbose
            } else {
                Stop-Function -Message "The recurrence factor $FrequencyRecurrenceFactor needs to be at least on when using a weekly or monthly interval." -Target $SqlInstance
                return
            }
        }

        # Check the subday interval
        if (($FrequencySubdayType -in 2, 4) -and (-not ($FrequencySubdayInterval -ge 1 -or $FrequencySubdayInterval -le 59))) {
            Stop-Function -Message "Subday interval $FrequencySubdayInterval must be between 1 and 59 when subday type is 2, 'Seconds', 4 or 'Minutes'" -Target $SqlInstance
            return
        } elseif (($FrequencySubdayType -eq 8) -and (-not ($FrequencySubdayInterval -ge 1 -and $FrequencySubdayInterval -le 23))) {
            Stop-Function -Message "Subday interval $FrequencySubdayInterval must be between 1 and 23 when subday type is 8 or 'Hours" -Target $SqlInstance
            return
        }

        # Check of the FrequencyInterval value is of type string and set the integer value
        if (($null -ne $FrequencyType)) {
            # Create the interval to hold the value(s)
            [int]$Interval = 0

            # If the FrequencyInterval is set for the weekly FrequencyType
            if ($FrequencyType -eq 8) {
                # Loop through the array
                foreach ($Item in $FrequencyInterval) {
                    switch ($Item) {
                        "Sunday" { $Interval += 1 }
                        "Monday" { $Interval += 2 }
                        "Tuesday" { $Interval += 4 }
                        "Wednesday" { $Interval += 8 }
                        "Thursday" { $Interval += 16 }
                        "Friday" { $Interval += 32 }
                        "Saturday" { $Interval += 64 }
                        "Weekdays" { $Interval = 62 }
                        "Weekend" { $Interval = 65 }
                        "EveryDay" {$Interval = 127 }
                        1 { $Interval += 1 }
                        2 { $Interval += 2 }
                        4 { $Interval += 4 }
                        8 { $Interval += 8 }
                        16 { $Interval += 16 }
                        31 { $Interval += 32 }
                        64 { $Interval += 64 }
                        62 { $Interval = 62 }
                        65 { $Interval = 65 }
                        127 {$Interval = 127 }
                    }
                }
            }

            # If the FrequencyInterval is set for the relative monthly FrequencyInterval
            if ($FrequencyType -eq 32) {
                # Loop through the array
                foreach ($Item in $FrequencyInterval) {
                    switch ($Item) {
                        "Sunday" { $Interval += 1 }
                        "Monday" { $Interval += 2 }
                        "Tuesday" { $Interval += 3 }
                        "Wednesday" { $Interval += 4 }
                        "Thursday" { $Interval += 5 }
                        "Friday" { $Interval += 6 }
                        "Saturday" { $Interval += 7 }
                        "Day" { $Interval += 8 }
                        "Weekday" { $Interval += 9 }
                        "WeekendDay" { $Interval += 10 }
                        1 { $Interval += 1 }
                        2 { $Interval += 2 }
                        3 { $Interval += 3 }
                        4 { $Interval += 4 }
                        5 { $Interval += 5 }
                        6 { $Interval += 6 }
                        7 { $Interval += 7 }
                        8 { $Interval += 8 }
                        9 { $Interval += 9 }
                        10 { $Interval += 10 }
                    }
                }
            }
        }

        # Check of the relative FrequencyInterval value is of type string and set the integer value
        if (($FrequencyRelativeInterval -notin 1, 2, 4, 8, 16) -and $null -ne $FrequencyRelativeInterval) {
            [int]$FrequencyRelativeInterval = switch ($FrequencyRelativeInterval) { "First" { 1 } "Second" { 2 } "Third" { 4 } "Fourth" { 8 } "Last" { 16 } "Unused" { 0 } default { 0 }}
        }

        # Check if the interval is valid
        if (($FrequencyType -eq 4) -and ($FrequencyInterval -lt 1 -or $FrequencyInterval -ge 365)) {
            Stop-Function -Message "The interval $FrequencyInterval needs to be higher than 1 and lower than 365 when using a daily frequency the interval." -Target $SqlInstance
            return
        }

        # Setup the regex
        $RegexDate = '(?<!\d)(?:(?:(?:1[6-9]|[2-9]\d)?\d{2})(?:(?:(?:0[13578]|1[02])31)|(?:(?:0[1,3-9]|1[0-2])(?:29|30)))|(?:(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))0229)|(?:(?:1[6-9]|[2-9]\d)?\d{2})(?:(?:0?[1-9])|(?:1[0-2]))(?:0?[1-9]|1\d|2[0-8]))(?!\d)'
        $RegexTime = '^(?:(?:([01]?\d|2[0-3]))?([0-5]?\d))?([0-5]?\d)$'

        # Check the start date
        if ($StartDate -and ($StartDate -notmatch $RegexDate)) {
            Stop-Function -Message "Start date $StartDate needs to be a valid date with format yyyyMMdd" -Target $SqlInstance
            return
        }

        # Check the end date
        if ($EndDate -and ($EndDate -notmatch $RegexDate)) {
            Stop-Function -Message "End date $EndDate needs to be a valid date with format yyyyMMdd" -Target $SqlInstance
            return
        } elseif ($EndDate -lt $StartDate) {
            Stop-Function -Message "End date $EndDate cannot be before start date $StartDate" -Target $SqlInstance
            return
        }

        # Check the start time
        if ($StartTime -and ($StartTime -notmatch $RegexTime)) {
            Stop-Function -Message "Start time $StartTime needs to match between '000000' and '235959'" -Target $SqlInstance
            return
        }

        # Check the end time
        if ($EndTime -and ($EndTime -notmatch $RegexTime)) {
            Stop-Function -Message "End time $EndTime needs to match between '000000' and '235959'" -Target $SqlInstance
            return
        }

        #Format dates and times
        if ($StartDate) {
            $StartDate = $StartDate.Insert(6, '-').Insert(4, '-')
        }
        if ($EndDate) {
            $EndDate = $EndDate.Insert(6, '-').Insert(4, '-')
        }
        if ($StartTime) {
            $StartTime = $StartTime.Insert(4, ':').Insert(2, ':')
        }
        if ($EndTime) {
            $EndTime = $EndTime.Insert(4, ':').Insert(2, ':')
        }
    }

    process {

        if (Test-FunctionInterrupt) { return }

        foreach ($instance in $sqlinstance) {

            foreach ($j in $Job) {

                # Try connecting to the instance
                try {
                    $Server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
                } catch {
                    Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                }

                # Check if the job exists
                if ($Server.JobServer.Jobs.Name -notcontains $j) {
                    Write-Message -Message "Job $j doesn't exists on $instance" -Level Warning
                } else {
                    # Check if the job schedule exists
                    if ($Server.JobServer.Jobs[$j].JobSchedules.Name -notcontains $ScheduleName) {
                        Stop-Function -Message "Schedule $ScheduleName doesn't exists for job $j on $instance" -Target $instance -Continue
                    } else {
                        # Get the job schedule
                        # If for some reason the there are multiple schedules with the same name, the first on is chosen
                        $JobSchedule = $Server.JobServer.Jobs[$j].JobSchedules[$ScheduleName][0]

                        #region job step options
                        # Setting the options for the job schedule
                        if ($NewName) {
                            Write-Message -Message "Setting job schedule name to $NewName for schedule $ScheduleName" -Level Verbose
                            $JobSchedule.Rename($NewName)
                        }

                        if ($Enabled) {
                            Write-Message -Message "Setting job schedule to enabled for schedule $ScheduleName" -Level Verbose
                            $JobSchedule.IsEnabled = $true
                        }

                        if ($Disabled) {
                            Write-Message -Message "Setting job schedule to disabled for schedule $ScheduleName" -Level Verbose
                            $JobSchedule.IsEnabled = $false
                        }

                        if ($FrequencyType -ge 1) {
                            Write-Message -Message "Setting job schedule frequency to $FrequencyType for schedule $ScheduleName" -Level Verbose
                            $JobSchedule.FrequencyTypes = $FrequencyType
                        }

                        if ($Interval -ge 1) {
                            Write-Message -Message "Setting job schedule frequency interval to $Interval for schedule $ScheduleName" -Level Verbose
                            $JobSchedule.FrequencyInterval = $Interval
                        }

                        if ($FrequencySubdayType -ge 1) {
                            Write-Message -Message "Setting job schedule frequency subday type to $FrequencySubdayType for schedule $ScheduleName" -Level Verbose
                            $JobSchedule.FrequencySubDayTypes = $FrequencySubdayType
                        }

                        if ($FrequencySubdayInterval -ge 1) {
                            Write-Message -Message "Setting job schedule frequency subday interval to $FrequencySubdayInterval for schedule $ScheduleName" -Level Verbose
                            $JobSchedule.FrequencySubDayInterval = $FrequencySubdayInterval
                        }

                        if (($FrequencyRelativeInterval -ge 1) -and ($FrequencyType -eq 32)) {
                            Write-Message -Message "Setting job schedule frequency relative interval to $FrequencyRelativeInterval for schedule $ScheduleName" -Level Verbose
                            $JobSchedule.FrequencyRelativeIntervals = $FrequencyRelativeInterval
                        }

                        if (($FrequencyRecurrenceFactor -ge 1) -and ($FrequencyType -in 8, 16, 32)) {
                            Write-Message -Message "Setting job schedule frequency recurrence factor to $FrequencyRecurrenceFactor for schedule $ScheduleName" -Level Verbose
                            $JobSchedule.FrequencyRecurrenceFactor = $FrequencyRecurrenceFactor
                        }

                        if ($StartDate) {
                            Write-Message -Message "Setting job schedule start date to $StartDate for schedule $ScheduleName" -Level Verbose
                            $JobSchedule.StartDate = $StartDate
                        }

                        if ($EndDate) {
                            Write-Message -Message "Setting job schedule end date to $EndDate for schedule $ScheduleName" -Level Verbose
                            $JobSchedule.EndDate = $EndDate
                        }

                        if ($StartTime) {
                            Write-Message -Message "Setting job schedule start time to $StartTime for schedule $ScheduleName" -Level Verbose
                            $JobSchedule.ActiveStartTimeOfDay = $StartTime
                        }

                        if ($EndTime) {
                            Write-Message -Message "Setting job schedule end time to $EndTime for schedule $ScheduleName" -Level Verbose
                            $JobSchedule.ActiveStartTimeOfDay = $EndTime
                        }
                        #endregion job step options

                        # Execute the query
                        if ($PSCmdlet.ShouldProcess($instance, "Changing the schedule $ScheduleName for job $j on $instance")) {
                            try {
                                # Excute the query and save the result
                                Write-Message -Message "Changing the schedule $ScheduleName for job $j" -Level Verbose

                                $JobSchedule.Alter()

                            } catch {
                                Stop-Function -Message "Something went wrong changing the schedule" -Target $instance -ErrorRecord $_ -Continue
                                return
                            }
                        }
                    }
                }
            } # foreach object job
        } # foreach object instance
    } # process

    end {
        if (Test-FunctionInterrupt) { return }
        Write-Message -Message "Finished changing the job schedule(s)" -Level Verbose
    }
}
tools\dbatools\functions\Set-DbaAgentServer.ps1
function Set-DbaAgentServer {
    <#
    .SYNOPSIS
        Set-DbaAgentServer updates properties of a SQL Agent Server.

    .DESCRIPTION
        Set-DbaAgentServer updates properties in the SQL Server Server with parameters supplied.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER InputObject
        Enables piping agent server objects

    .PARAMETER AgentLogLevel
        Specifies the agent log level.
        Allowed values 1, "Errors", 2, "Warnings", 3, "Errors, Warnings", 4, "Informational", 5, "Errors, Informational", 6, "Warnings, Informational", 7, "All"
        The text value can either be lowercase, uppercase or something in between as long as the text is correct.

    .PARAMETER AgentMailType
        Specifies the agent mail type.
        Allowed values 0, "SqlAgentMail", 1, "DatabaseMail"
        The text value can either be lowercase, uppercase or something in between as long as the text is correct.

    .PARAMETER AgentShutdownWaitTime
        The Agent Shutdown Wait Time value of the server agent.

    .PARAMETER DatabaseMailProfile
        The Database Mail Profile to be used. Must exists on database mail profiles.

    .PARAMETER ErrorLogFile
        Error log file location

    .PARAMETER IdleCpuDuration
        Idle CPU Duration value to be used

    .PARAMETER IdleCpuPercentage
        Idle CPU Percentage value to be used

    .PARAMETER CpuPolling
        Enable or Disable the Polling.
        Allowed values Enabled, Disabled

    .PARAMETER LocalHostAlias
        The value for Local Host Alias configuration

    .PARAMETER LoginTimeout
        The value for Login Timeout configuration

    .PARAMETER MaximumHistoryRows
        Indicates the Maximum job history log size (in rows). If you want to turn it off use the value -1

    .PARAMETER MaximumJobHistoryRows
        Indicates the Maximum job history rows per job. If you want to turn it off use the value 0

    .PARAMETER NetSendRecipient
        The Net send recipient value

    .PARAMETER ReplaceAlertTokens
        Enable or Disable the Token replacement property.
        Allowed values Enabled, Disabled

    .PARAMETER SaveInSentFolder
        Enable or Disable the copy of the sent messages is save in the Sent Items folder.
        Allowed values Enabled, Disabled

    .PARAMETER SqlAgentAutoStart
        Enable or Disable the SQL Agent Auto Start.
        Allowed values Enabled, Disabled

    .PARAMETER SqlAgentMailProfile
        The SQL Server Agent Mail Profile to be used. Must exists on database mail profiles.

    .PARAMETER SqlAgentRestart
        Enable or Disable the SQL Agent Restart.
        Allowed values Enabled, Disabled

    .PARAMETER SqlServerRestart
        Enable or Disable the SQL Server Restart.
        Allowed values Enabled, Disabled

    .PARAMETER WriteOemErrorLog
        Enable or Disable the Write OEM Error Log.
        Allowed values Enabled, Disabled

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Server
        Author: Cláudio Silva (@claudioessilva), https://claudioessilva.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaAgentServer

    .EXAMPLE
        PS C:\> Set-DbaAgentServer -SqlInstance sql1 -MaximumHistoryRows 10000 -MaximumJobHistoryRows 100

        Changes the job history retention to 10000 rows with an maximum of 100 rows per job.

    .EXAMPLE
        PS C:\> Set-DbaAgentServer -SqlInstance sql1 -CpuPolling Enabled

        Enable the CPU Polling configurations.

    .EXAMPLE
        PS C:\> Set-DbaAgentServer -SqlInstance sql1, sql2, sql3 -AgentLogLevel 'Errors, Warnings'

        Set the agent log level to Errors and Warnings on multiple servers.

    .EXAMPLE
        PS C:\> Set-DbaAgentServer -SqlInstance sql1 -CpuPolling Disabled

        Disable the CPU Polling configurations.

    #>
    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = "Low")]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Agent.JobServer[]]$InputObject,
        [ValidateSet(1, "Errors", 2, "Warnings", 3, "Errors, Warnings", 4, "Informational", 5, "Errors, Informational", 6, "Warnings, Informational", 7, "All")]
        [object]$AgentLogLevel,
        [ValidateSet(0, "SqlAgentMail", 1, "DatabaseMail")]
        [object]$AgentMailType,
        [int]$AgentShutdownWaitTime,
        [string]$DatabaseMailProfile,
        [string]$ErrorLogFile,
        [int]$IdleCpuDuration,
        [int]$IdleCpuPercentage,
        [ValidateSet("Enabled", "Disabled")]
        [string]$CpuPolling,
        [string]$LocalHostAlias,
        [int]$LoginTimeout,
        [int]$MaximumHistoryRows,
        [int]$MaximumJobHistoryRows,
        [string]$NetSendRecipient,
        [ValidateSet("Enabled", "Disabled")]
        [string]$ReplaceAlertTokens,
        [ValidateSet("Enabled", "Disabled")]
        [string]$SaveInSentFolder,
        [ValidateSet("Enabled", "Disabled")]
        [string]$SqlAgentAutoStart,
        [string]$SqlAgentMailProfile,
        [ValidateSet("Enabled", "Disabled")]
        [string]$SqlAgentRestart,
        [ValidateSet("Enabled", "Disabled")]
        [string]$SqlServerRestart,
        [ValidateSet("Enabled", "Disabled")]
        [string]$WriteOemErrorLog,
        [switch]$EnableException
    )

    begin {
        # Check of the agent mail type is of type string and set the integer value
        if (($AgentMailType -notin 0, 1) -and ($null -ne $AgentMailType)) {
            $AgentMailType = switch ($AgentMailType) { "SqlAgentMail" { 0 } "DatabaseMail" { 1 } }
        }

        # Check of the agent log level is of type string and set the integer value
        if (($AgentLogLevel -notin 0, 1) -and ($null -ne $AgentLogLevel)) {
            $AgentLogLevel = switch ($AgentLogLevel) { "Errors" { 1 } "Warnings" { 2 } "Errors, Warnings" { 3 } "Informational" { 4 } "Errors, Informational" { 5 } "Warnings, Informational" { 6 } "All" { 7 } }
        }
    }
    process {

        if (Test-FunctionInterrupt) { return }

        if ((-not $InputObject) -and (-not $SqlInstance)) {
            Stop-Function -Message "You must specify an Instance or pipe in results from another command" -Target $sqlinstance
            return
        }

        foreach ($instance in $sqlinstance) {
            # Try connecting to the instance
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $InputObject += $server.JobServer
            $InputObject.Refresh()
        }

        foreach ($jobServer in $InputObject) {
            $server = $jobServer.Parent

            #region job server options
            # Settings the options for the job server
            if ($AgentLogLevel) {
                Write-Message -Message "Setting Agent log level to $AgentLogLevel" -Level Verbose
                $jobServer.AgentLogLevel = $AgentLogLevel
            }

            if ($AgentMailType) {
                Write-Message -Message "Setting Agent Mail Type to $AgentMailType" -Level Verbose
                $jobServer.AgentMailType = $AgentMailType
            }

            if ($AgentShutdownWaitTime) {
                Write-Message -Message "Setting Agent Shutdown Wait Time to $AgentShutdownWaitTime" -Level Verbose
                $jobServer.AgentShutdownWaitTime = $AgentShutdownWaitTime
            }

            if ($DatabaseMailProfile) {
                if ($DatabaseMailProfile -in (Get-DbaDbMail -SqlInstance $server).Profiles.Name) {
                    Write-Message -Message "Setting Database Mail Profile to $DatabaseMailProfile" -Level Verbose
                    $jobServer.DatabaseMailProfile = $DatabaseMailProfile
                } else {
                    Write-Message -Message "Database mail profile not found on $server" -Level Warning
                }
            }

            if ($ErrorLogFile) {
                Write-Message -Message "Setting agent server ErrorLogFile to $ErrorLogFile" -Level Verbose
                $jobServer.ErrorLogFile = $ErrorLogFile
            }

            if ($IdleCpuDuration) {
                Write-Message -Message "Setting agent server IdleCpuDuration to $IdleCpuDuration" -Level Verbose
                $jobServer.IdleCpuDuration = $IdleCpuDuration
            }

            if ($IdleCpuPercentage) {
                Write-Message -Message "Setting agent server IdleCpuPercentage to $IdleCpuPercentage" -Level Verbose
                $jobServer.IdleCpuPercentage = $IdleCpuPercentage
            }

            if ($CpuPolling) {
                Write-Message -Message "Setting agent server IsCpuPollingEnabled to $IsCpuPollingEnabled" -Level Verbose
                $jobServer.IsCpuPollingEnabled = if ($CpuPolling -eq "Enabled") {$true} else {$false}
            }

            if ($LocalHostAlias) {
                Write-Message -Message "Setting agent server LocalHostAlias to $LocalHostAlias" -Level Verbose
                $jobServer.LocalHostAlias = $LocalHostAlias
            }

            if ($LoginTimeout) {
                Write-Message -Message "Setting agent server LoginTimeout to $LoginTimeout" -Level Verbose
                $jobServer.LoginTimeout = $LoginTimeout
            }

            if ($MaximumHistoryRows) {
                Write-Message -Message "Setting agent server MaximumHistoryRows to $MaximumHistoryRows" -Level Verbose
                $jobServer.MaximumHistoryRows = $MaximumHistoryRows
            }

            if ($MaximumJobHistoryRows) {
                Write-Message -Message "Setting agent server MaximumJobHistoryRows to $MaximumJobHistoryRows" -Level Verbose
                $jobServer.MaximumJobHistoryRows = $MaximumJobHistoryRows
            }

            if ($NetSendRecipient) {
                Write-Message -Message "Setting agent server NetSendRecipient to $NetSendRecipient" -Level Verbose
                $jobServer.NetSendRecipient = $NetSendRecipient
            }

            if ($ReplaceAlertTokens) {
                Write-Message -Message "Setting agent server ReplaceAlertTokensEnabled to $ReplaceAlertTokens" -Level Verbose
                $jobServer.ReplaceAlertTokens = if ($ReplaceAlertTokens -eq "Enabled") {$true} else {$false}
            }

            if ($SaveInSentFolder) {
                Write-Message -Message "Setting agent server SaveInSentFolder to $SaveInSentFolder" -Level Verbose
                $jobServer.SaveInSentFolder = if ($SaveInSentFolder -eq "Enabled") {$true} else {$false}
            }

            if ($SqlAgentAutoStart) {
                Write-Message -Message "Setting agent server SqlAgentAutoStart to $SqlAgentAutoStart" -Level Verbose
                $jobServer.SqlAgentAutoStart = if ($SqlAgentAutoStart -eq "Enabled") {$true} else {$false}
            }

            if ($SqlAgentMailProfile) {
                Write-Message -Message "Setting agent server SqlAgentMailProfile to $SqlAgentMailProfile" -Level Verbose
                $jobServer.SqlAgentMailProfile = $SqlAgentMailProfile
            }

            if ($SqlAgentRestart) {
                Write-Message -Message "Setting agent server SqlAgentRestart to $SqlAgentRestart" -Level Verbose
                $jobServer.SqlAgentRestart = if ($SqlAgentRestart -eq "Enabled") {$true} else {$false}
            }

            if ($SqlServerRestart) {
                Write-Message -Message "Setting agent server SqlServerRestart to $SqlServerRestart" -Level Verbose
                $jobServer.SqlServerRestart = if ($SqlServerRestart -eq "Enabled") {$true} else {$false}
            }

            if ($WriteOemErrorLog) {
                Write-Message -Message "Setting agent server WriteOemErrorLog to $WriteOemErrorLog" -Level Verbose
                $jobServer.WriteOemErrorLog = if ($WriteOemErrorLog -eq "Enabled") {$true} else {$false}
            }

            #endregion server agent options

            # Execute
            if ($PSCmdlet.ShouldProcess($SqlInstance, "Changing the agent server")) {
                try {
                    Write-Message -Message "Changing the agent server" -Level Verbose

                    # Change the agent server
                    $jobServer.Alter()
                } catch {
                    Stop-Function -Message "Something went wrong changing the agent server" -ErrorRecord $_ -Target $instance -Continue
                }

                Get-DbaAgentServer -SqlInstance $server | Where-Object Name -eq $jobServer.name
            }
        }
    }
    end {
        Write-Message -Message "Finished changing agent server(s)" -Level Verbose
    }
}
tools\dbatools\functions\Set-DbaAgListener.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Set-DbaAgListener {
    <#
    .SYNOPSIS
        Sets a listener property for an availability group on a SQL Server instance.

    .DESCRIPTION
        Sets a listener property for an availability group on a SQL Server instance.

        Basically, only the port is settable at this time, so this command updates the listener port.

   .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.

    .PARAMETER SqlCredential
        Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER AvailabilityGroup
        The Availability Group to which a property will be changed.

    .PARAMETER Port
        Sets the port number used to communicate with the availability group.

    .PARAMETER Listener
        Modify only specific listeners.

    .PARAMETER InputObject
        Enables piping from Get-DbaAvailabilityGroup

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: AvailabilityGroup, HA, AG
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaAgListener

    .EXAMPLE
        PS C:\> Set-DbaAgListener -SqlInstance sql2017 -AvailabilityGroup SharePoint -Port 14333

        Changes the port for the SharePoint AG Listener on sql2017. Prompts for confirmation.

    .EXAMPLE
        PS C:\> Get-DbaAgListener -SqlInstance sql2017 | Out-GridView -Passthru | Set-DbaAgListener -Port 1433 -Confirm:$false

        Changes the port for selected AG listeners to 1433. Does not prompt for confirmation.
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$AvailabilityGroup,
        [string[]]$Listener,
        [Parameter(Mandatory)]
        [int]$Port,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.AvailabilityGroup[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ((Test-Bound -ParameterName SqlInstance) -and (Test-Bound -Not -ParameterName AvailabilityGroup)) {
            Stop-Function -Message "You must specify one or more databases and one or more Availability Groups when using the SqlInstance parameter."
            return
        }

        if ($SqlInstance) {
            $InputObject += Get-DbaAgListener -SqlInstance $SqlInstance -SqlCredential $SqlCredential -AvailabilityGroup $AvailabilityGroup -Listener $Listener
        }

        foreach ($aglistener in $InputObject) {
            if ($Pscmdlet.ShouldProcess($ag.Parent.Name, "Setting port to $Port for $($ag.Name)")) {
                try {
                    $aglistener.PortNumber = $Port
                    $aglistener.Alter()
                    $aglistener
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_
                }
            }
        }
    }
}
tools\dbatools\functions\Set-DbaAgReplica.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Set-DbaAgReplica {
    <#
    .SYNOPSIS
        Sets the properties for a replica to an availability group on a SQL Server instance.

    .DESCRIPTION
        Sets the properties for a replica to an availability group on a SQL Server instance.

        Automatically creates a database mirroring endpoint if required.

   .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.

    .PARAMETER SqlCredential
        Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Replica
        The replicas to modify.

    .PARAMETER AvailabilityGroup
        The availability group of the replica.

    .PARAMETER AvailabilityMode
        Sets the availability mode of the availability group replica. Options are: AsynchronousCommit and SynchronousCommit. SynchronousCommit is default.

    .PARAMETER FailoverMode
        Sets the failover mode of the availability group replica. Options are Automatic and Manual.

    .PARAMETER BackupPriority
        Sets the backup priority availability group replica. Default is 50.

    .PARAMETER EndpointUrl
        The endpoint URL.

     .PARAMETER InputObject
        Enables piping from Get-DbaAgReplica.

    .PARAMETER ConnectionModeInPrimaryRole
        Sets the connection intent modes of an Availability Replica in primary role.

    .PARAMETER ConnectionModeInSecondaryRole
        Sets the connection modes of an Availability Replica in secondary role.

    .PARAMETER ReadonlyRoutingConnectionUrl
        Sets the read only routing connection url for the availability replica.

    .PARAMETER SeedingMode
        Specifies how the secondary replica will be initially seeded.

        Automatic enables direct seeding. This method will seed the secondary replica over the network. This method does not require you to backup and restore a copy of the primary database on the replica.

        Manual requires you to create a backup of the database on the primary replica and manually restore that backup on the secondary replica.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: AvailabilityGroup, HA, AG
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaAgReplica

    .EXAMPLE
        PS C:\> Set-DbaAgReplica -SqlInstance sql2016 -Replica sql2016 -AvailabilityGroup SharePoint -BackupPriority 5000

        Sets the backup priority to 5000 for the sql2016 replica for the SharePoint availability group on sql2016

    .EXAMPLE
        PS C:\> Get-DbaAgReplica -SqlInstance sql2016 | Out-GridView -Passthru | Set-DbaAgReplica -BackupPriority 5000

        Sets the backup priority to 5000 for the selected availability groups.
       #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$AvailabilityGroup,
        [string]$Replica,
        [ValidateSet('AsynchronousCommit', 'SynchronousCommit')]
        [string]$AvailabilityMode,
        [ValidateSet('Automatic', 'Manual', 'External')]
        [string]$FailoverMode,
        [int]$BackupPriority,
        [ValidateSet('AllowAllConnections', 'AllowReadWriteConnections')]
        [string]$ConnectionModeInPrimaryRole,
        [ValidateSet('AllowAllConnections', 'AllowNoConnections', 'AllowReadIntentConnectionsOnly')]
        [string]$ConnectionModeInSecondaryRole,
        [ValidateSet('Automatic', 'Manual')]
        [string]$SeedingMode,
        [string]$EndpointUrl,
        [string]$ReadonlyRoutingConnectionUrl,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.AvailabilityReplica]$InputObject,
        [switch]$EnableException
    )
    process {
        if (-not $InputObject) {
            if (-not $AvailabilityGroup -or -not $Replica) {
                Stop-Function -Message "You must specify an AvailabilityGroup and replica or pipe in an availabilty group to continue."
                return
            }
        }

        if ($SqlInstance) {
            $InputObject += Get-DbaAgReplica -SqlInstance $SqlInstance -SqlCredential $SqlCredential -AvailabilityGroup $AvailabilityGroup -Replica $Replica
        }

        foreach ($agreplica in $InputObject) {
            $server = $agreplica.Parent.Parent
            if ($Pscmdlet.ShouldProcess($server.Name, "Modifying replica for $($agreplica.Name) named $Name")) {
                try {
                    if ($EndpointUrl) {
                        $agreplica.EndpointUrl = $EndpointUrl
                    }

                    if ($FailoverMode) {
                        $agreplica.FailoverMode = [Microsoft.SqlServer.Management.Smo.AvailabilityReplicaFailoverMode]::$FailoverMode
                    }

                    if ($AvailabilityMode) {
                        $agreplica.AvailabilityMode = [Microsoft.SqlServer.Management.Smo.AvailabilityReplicaAvailabilityMode]::$AvailabilityMode
                    }

                    if ($ConnectionModeInPrimaryRole) {
                        $agreplica.ConnectionModeInPrimaryRole = [Microsoft.SqlServer.Management.Smo.AvailabilityReplicaConnectionModeInPrimaryRole]::$ConnectionModeInPrimaryRole
                    }

                    if ($ConnectionModeInSecondaryRole) {
                        $agreplica.ConnectionModeInSecondaryRole = [Microsoft.SqlServer.Management.Smo.AvailabilityReplicaConnectionModeInSecondaryRole]::$ConnectionModeInSecondaryRole
                    }

                    if ($BackupPriority) {
                        $agreplica.BackupPriority = $BackupPriority
                    }

                    if ($ReadonlyRoutingConnectionUrl) {
                        $agreplica.ReadonlyRoutingConnectionUrl = $ReadonlyRoutingConnectionUrl
                    }

                    if ($SeedingMode) {
                        $agreplica.SeedingMode = $SeedingMode
                    }

                    $agreplica.Alter()
                    $agreplica

                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Set-DbaAvailabilityGroup.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Set-DbaAvailabilityGroup {
    <#
    .SYNOPSIS
        Sets availability group properties on a SQL Server instance.

    .DESCRIPTION
        Sets availability group properties on a SQL Server instance.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.

    .PARAMETER SqlCredential
        Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER AvailabilityGroup
        Only set specific availability group properties.

    .PARAMETER AllAvailabilityGroups
        Set properties for all availability group on an instance.

    .PARAMETER DtcSupportEnabled
        Enables DtcSupport.

    .PARAMETER ClusterType
        Cluster type of the Availability Group. Only supported in SQL Server 2017 and above.
        Options include: External, Wsfc or None.

    .PARAMETER AutomatedBackupPreference
        Specifies how replicas in the primary role are treated in the evaluation to pick the desired replica to perform a backup.

    .PARAMETER FailureConditionLevel
        Specifies the different conditions that can trigger an automatic failover in Availability Group.

    .PARAMETER HealthCheckTimeout
        This setting used to specify the length of time, in milliseconds, that the SQL Server resource DLL should wait for information returned by the sp_server_diagnostics stored procedure before reporting the Always On Failover Cluster Instance (FCI) as unresponsive.

        Changes that are made to the timeout settings are effective immediately and do not require a restart of the SQL Server resource.

        Defaults is 30000 (30 seconds).

    .PARAMETER BasicAvailabilityGroup
        Indicates whether the availability group is basic. Basic availability groups like pumpkin spice and uggs.

        https://docs.microsoft.com/en-us/sql/database-engine/availability-groups/windows/basic-availability-groups-always-on-availability-groups

    .PARAMETER DatabaseHealthTrigger
        Indicates whether the availability group triggers the database health.

    .PARAMETER IsDistributedAvailabilityGroup
        Indicates whether the availability group is distributed.

    .PARAMETER InputObject
        Enables piping from Get-DbaAvailabilityGroup.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: AvailabilityGroup, HA, AG
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaAvailabilityGroup

    .EXAMPLE
        PS C:\> Get-DbaAvailabilityGroup -SqlInstance sql2016 | Set-DbaAvailabilityGroup -DtcSupportEnabled

        Enables DTC for all availability groups on sql2016

       .EXAMPLE
        PS C:\> Get-DbaAvailabilityGroup -SqlInstance sql2016 -AvailabilityGroup AG1 | Set-DbaAvailabilityGroup -DtcSupportEnabled:$false

        Disables DTC support for the availability group AG1

        .EXAMPLE
        PS C:\> Set-DbaAvailabilityGroup -SqlInstance sql2016 -AvailabilityGroup AG1 -DtcSupportEnabled:$false

        Disables DTC support for the availability group AG1
    #>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$AvailabilityGroup,
        [switch]$AllAvailabilityGroups,
        [switch]$DtcSupportEnabled,
        [ValidateSet('External', 'Wsfc', 'None')]
        [string]$ClusterType,
        [ValidateSet('None', 'Primary', 'Secondary', 'SecondaryOnly')]
        [string]$AutomatedBackupPreference,
        [ValidateSet('OnAnyQualifiedFailureCondition', 'OnCriticalServerErrors', 'OnModerateServerErrors', 'OnServerDown', 'OnServerUnresponsive')]
        [string]$FailureConditionLevel,
        [int]$HealthCheckTimeout,
        [switch]$BasicAvailabilityGroup,
        [switch]$DatabaseHealthTrigger,
        [switch]$IsDistributedAvailabilityGroup,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.AvailabilityGroup[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ((Test-Bound -ParameterName SqlInstance) -and (Test-Bound -Not -ParameterName AvailabilityGroup, AllAvailabilityGroups)) {
            Stop-Function -Message "You must specify AllAvailabilityGroups groups or AvailabilityGroups when using the SqlInstance parameter."
            return
        }
        if ($SqlInstance) {
            $InputObject += Get-DbaAvailabilityGroup -SqlInstance $SqlInstance -SqlCredential $SqlCredential -AvailabilityGroup $AvailabilityGroup
        }
        $props = "Name", "AutomatedBackupPreference", "BasicAvailabilityGroup", "ClusterType", "DatabaseHealthTrigger", "DtcSupportEnabled", "FailureConditionLevel", "HealthCheckTimeout", "IsDistributedAvailabilityGroup"

        foreach ($ag in $InputObject) {
            try {
                if ($Pscmdlet.ShouldProcess($ag.Parent.Name, "Seting properties on $ag")) {
                    foreach ($prop in $props) {
                        if (Test-Bound -ParameterName $prop) {
                            $ag.$prop = (Get-Variable -Name $prop -ValueOnly)
                        }
                    }
                    $ag.Alter()
                    $ag
                }
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
            }
        }
    }
}
tools\dbatools\functions\Set-DbaCmConnection.ps1
function Set-DbaCmConnection {
    <#
    .SYNOPSIS
        Configures a connection object for use in remote computer management.

    .DESCRIPTION
        Configures a connection object for use in remote computer management.
        This function will either create new records for computers that have no connection registered so far, or it will configure existing connections if already present.

        As such it can be handy in making bulk-edits on connections or manually adjusting some settings.

    .PARAMETER ComputerName
        The computer to build the connection object for.

    .PARAMETER Credential
        The credential to register.

    .PARAMETER UseWindowsCredentials
        Whether using the default windows credentials is legit.
        Not setting this will not exclude using windows credentials, but only not pre-confirm them as working.

    .PARAMETER OverrideExplicitCredential
        Setting this will enable the credential override.
        The override will cause the system to ignore explicitly specified credentials, so long as known, good credentials are available.

    .PARAMETER OverrideConnectionPolicy
        Setting this will configure the connection policy override.
        By default, global configurations enforce, which connection type is available at all and which is disabled.

    .PARAMETER DisabledConnectionTypes
        Explicitly disable connection types.
        These types will then not be used for connecting to the computer.

    .PARAMETER DisableBadCredentialCache
        Will prevent the caching of credentials if set to true.

    .PARAMETER DisableCimPersistence
        Will prevent Cim-Sessions to be reused.

    .PARAMETER DisableCredentialAutoRegister
        Will prevent working credentials from being automatically cached

    .PARAMETER EnableCredentialFailover
        Will enable automatic failing over to known to work credentials, when using bad credentials.
        By default, passing bad credentials will cause the Computer Management functions to interrupt with a warning (Or exception if in silent mode).

    .PARAMETER WindowsCredentialsAreBad
        Will prevent the windows credentials of the currently logged on user from being used for the remote connection.

    .PARAMETER CimWinRMOptions
        Specify a set of options to use when connecting to the target computer using CIM over WinRM.
        Use 'New-CimSessionOption' to create such an object.

    .PARAMETER CimDCOMOptions
        Specify a set of options to use when connecting to the target computer using CIM over DCOM.
        Use 'New-CimSessionOption' to create such an object.

    .PARAMETER AddBadCredential
        Adds credentials to the bad credential cache.
        These credentials will not be used when connecting to the target remote computer.

    .PARAMETER RemoveBadCredential
        Removes credentials from the bad credential cache.

    .PARAMETER ClearBadCredential
        Clears the cache of credentials that didn't worked.
        Will be applied before adding entries to the credential cache.

    .PARAMETER ClearCredential
        Clears the cache of credentials that worked.
        Will be applied before adding entries to the credential cache.

    .PARAMETER ResetCredential
        Resets all credential-related caches:
        - Clears bad credential cache
        - Removes last working credential
        - Un-Confirms the windows credentials as working
        - Un-Confirms the windows credentials as not working

        Automatically implies the parameters -ClearCredential and -ClearBadCredential. Using them together is redundant.
        Will be applied before adding entries to the credential cache.

    .PARAMETER ResetConnectionStatus
        Restores all connection status to default, as if no connection protocol had ever been tested.

    .PARAMETER ResetConfiguration
        Restores the configuration back to system default.
        Configuration elements are the basic behavior controlling settings, such as whether to cache bad credentials, etc.
        These can be configured globally using the dbatools configuration system and overridden locally on a per-connection basis.
        For a list of all available settings, use "Get-DbatoolsConfig -Module ComputerManagement".

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ComputerManagement, CIM
        Author: Friedrich Weinmann (@FredWeinmann)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/set-DbaCmConnection

    .EXAMPLE
        PS C:\> Get-DbaCmConnection sql2014 | Set-DbaCmConnection -ClearBadCredential -UseWindowsCredentials

        Retrieves the already existing connection to sql2014, removes the list of not working credentials and configures it to default to the credentials of the logged on user.

    .EXAMPLE
        PS C:\> Get-DbaCmConnection | Set-DbaCmConnection -RemoveBadCredential $cred

        Removes the credentials stored in $cred from all connections' list of "known to not work" credentials.
        Handy to update changes in privilege.

    .EXAMPLE
        PS C:\> Get-DbaCmConnection | Export-Clixml .\connections.xml
        PS C:\> Import-Clixml .\connections.xml | Set-DbaCmConnection -ResetConfiguration

        At first, the current cached connections are stored in an xml file. At a later time - possibly in the profile when starting the console again - those connections are imported again and applied again to the connection cache.

        In this example, the configuration settings will also be reset, since after re-import those will be set to explicit, rather than deriving them from the global settings.
        In many cases, using the default settings is desirable. For specific settings, use New-DbaCmConnection as part of the profile in order to explicitly configure a connection.

    #>
    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'Credential')]
    param (
        [Parameter(ValueFromPipeline)]
        [Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter[]]
        $ComputerName = $env:COMPUTERNAME,

        [Parameter(ParameterSetName = "Credential")]
        [PSCredential]
        $Credential,

        [Parameter(ParameterSetName = "Windows")]
        [switch]
        $UseWindowsCredentials,

        [switch]
        $OverrideExplicitCredential,

        [switch]
        $OverrideConnectionPolicy,

        [Sqlcollaborative.Dbatools.Connection.ManagementConnectionType]
        $DisabledConnectionTypes = 'None',

        [switch]
        $DisableBadCredentialCache,

        [switch]
        $DisableCimPersistence,

        [switch]
        $DisableCredentialAutoRegister,

        [switch]
        $EnableCredentialFailover,

        [Parameter(ParameterSetName = "Credential")]
        [switch]
        $WindowsCredentialsAreBad,

        [Microsoft.Management.Infrastructure.Options.WSManSessionOptions]
        $CimWinRMOptions,

        [Microsoft.Management.Infrastructure.Options.DComSessionOptions]
        $CimDCOMOptions,

        [System.Management.Automation.PSCredential[]]
        $AddBadCredential,

        [System.Management.Automation.PSCredential[]]
        $RemoveBadCredential,

        [switch]
        $ClearBadCredential,

        [switch]
        $ClearCredential,

        [switch]
        $ResetCredential,

        [switch]
        $ResetConnectionStatus,

        [switch]
        $ResetConfiguration,

        [switch]
        [Alias('Silent')]$EnableException
    )

    begin {
        Write-Message -Level InternalComment -Message "Starting execution"
        Write-Message -Level Verbose -Message "Bound parameters: $($PSBoundParameters.Keys -join ", ")"

        $disable_cache = Get-DbatoolsConfigValue -Name 'ComputerManagement.Cache.Disable.All' -Fallback $false
    }
    process {
        foreach ($connectionObject in $ComputerName) {
            if ($Pscmdlet.ShouldProcess($($connectionObject.Connection.ComputerName), "Setting Connection")) {
                if (-not $connectionObject.Success) { Stop-Function -Message "Failed to interpret computername input: $($connectionObject.InputObject)" -Category InvalidArgument -Target $connectionObject.InputObject -Continue }
                Write-Message -Level VeryVerbose -Message "Processing computer: $($connectionObject.Connection.ComputerName)"

                $connection = $connectionObject.Connection

                if ($ResetConfiguration) {
                    Write-Message -Level Verbose -Message "Resetting the configuration to system default"

                    $connection.RestoreDefaultConfiguration()
                }

                if ($ResetConnectionStatus) {
                    Write-Message -Level Verbose -Message "Resetting the connection status"

                    $connection.CimRM = 'Unknown'
                    $connection.CimDCOM = 'Unknown'
                    $connection.Wmi = 'Unknown'
                    $connection.PowerShellRemoting = 'Unknown'

                    $connection.LastCimRM = New-Object System.DateTime(0)
                    $connection.LastCimDCOM = New-Object System.DateTime(0)
                    $connection.LastWmi = New-Object System.DateTime(0)
                    $connection.LastPowerShellRemoting = New-Object System.DateTime(0)
                }

                if ($ResetCredential) {
                    Write-Message -Level Verbose -Message "Resetting credentials"

                    $connection.KnownBadCredentials.Clear()
                    $connection.Credentials = $null
                    $connection.UseWindowsCredentials = $false
                    $connection.WindowsCredentialsAreBad = $false
                } else {
                    if ($ClearBadCredential) {
                        Write-Message -Level Verbose -Message "Clearing bad credentials"

                        $connection.KnownBadCredentials.Clear()
                        $connection.WindowsCredentialsAreBad = $false
                    }

                    if ($ClearCredential) {
                        Write-Message -Level Verbose -Message "Clearing credentials"

                        $connection.Credentials = $null
                        $connection.UseWindowsCredentials = $false
                    }
                }

                foreach ($badCred in $RemoveBadCredential) {
                    $connection.RemoveBadCredential($badCred)
                }

                foreach ($badCred in $AddBadCredential) {
                    $connection.AddBadCredential($badCred)
                }

                if (Test-Bound "Credential") { $connection.Credentials = $Credential }
                if ($UseWindowsCredentials) {
                    $connection.Credentials = $null
                    $connection.UseWindowsCredentials = $UseWindowsCredentials
                }
                if (Test-Bound "OverrideExplicitCredential") { $connection.OverrideExplicitCredential = $OverrideExplicitCredential }
                if (Test-Bound "DisabledConnectionTypes") { $connection.DisabledConnectionTypes = $DisabledConnectionTypes }
                if (Test-Bound "DisableBadCredentialCache") { $connection.DisableBadCredentialCache = $DisableBadCredentialCache }
                if (Test-Bound "DisableCimPersistence") { $connection.DisableCimPersistence = $DisableCimPersistence }
                if (Test-Bound "DisableCredentialAutoRegister") { $connection.DisableCredentialAutoRegister = $DisableCredentialAutoRegister }
                if (Test-Bound "EnableCredentialFailover") { $connection.DisableCredentialAutoRegister = $EnableCredentialFailover }
                if (Test-Bound "WindowsCredentialsAreBad") { $connection.WindowsCredentialsAreBad = $WindowsCredentialsAreBad }
                if (Test-Bound "CimWinRMOptions") { $connection.CimWinRMOptions = $CimWinRMOptions }
                if (Test-Bound "CimDCOMOptions") { $connection.CimDCOMOptions = $CimDCOMOptions }
                if (Test-Bound "OverrideConnectionPolicy") { $connection.OverrideConnectionPolicy = $OverrideConnectionPolicy }

                if (-not $disable_cache) {
                    Write-Message -Level Verbose -Message "Writing connection to cache"
                    [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::Connections[$connectionObject.Connection.ComputerName] = $connection
                } else { Write-Message -Level Verbose -Message "Skipping writing to cache, since the cache has been disabled!" }
                $connection
            }
        }
    }
    end {
        Write-Message -Level InternalComment -Message "Stopping execution"
    }
}
tools\dbatools\functions\Set-DbaDbCompatibility.ps1
function Set-DbaDbCompatibility {
    <#
    .SYNOPSIS
        Sets the compatibility level for SQL Server databases.

    .DESCRIPTION
        Sets the current database compatibility level for all databases on a server or list of databases passed in to the function.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        SqlCredential object used to connect to the SQL Server as a different user.

    .PARAMETER Database
        The database or databases to process. If unspecified, all databases will be processed.

    .PARAMETER TargetCompatibility
        The target compatibility level version. This is an int and follows Microsoft's versioning:

        9 = SQL Server 2005
        10 = SQL Server 2008
        11 = SQL Server 2012
        12 = SQL Server 2014
        13 = SQL Server 2016
        14 = SQL Server 2017
        15 = SQL Server 2019

    .PARAMETER InputObject
        A collection of databases (such as returned by Get-DbaDatabase)

    .PARAMETER WhatIf
        Shows what would happen if the command were to run

    .PARAMETER Confirm
        Prompts for confirmation of every step. For example:

        Are you sure you want to perform this action?
        Performing the operation "Update database" on target "pubs on SQL2016\VNEXT".
        [Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Compatibility, Database
        Author: Garry Bargsley, http://blog.garrybargsley.com/

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaDbCompatibility

    .EXAMPLE
        PS C:\> Set-DbaDbCompatibility -SqlInstance localhost\sql2017

        Changes database compatibility level for all user databases on server localhost\sql2017 that have a Compatibility level that do not match

    .EXAMPLE
        PS C:\> Set-DbaDbCompatibility -SqlInstance localhost\sql2017 -TargetCompatibility 12

        Changes database compatibility level for all user databases on server localhost\sql2017 to Version120

    .EXAMPLE
        PS C:\> Set-DbaDbCompatibility -SqlInstance localhost\sql2017 -Database Test -TargetCompatibility 12

        Changes database compatibility level for database Test on server localhost\sql2017 to Version 120
    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [ValidateSet(9, 10, 11, 12, 13, 14, 15)]
        [int]$TargetCompatibility,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )
    process {

        if (Test-Bound -not 'SqlInstance', 'InputObject') {
            Write-Message -Level Warning -Message "You must specify either a SQL instance or pipe a database collection"
            continue
        }

        if ($SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database
        }

        foreach ($db in $InputObject) {
            $server = $db.Parent
            $ServerVersion = $server.VersionMajor
            Write-Message -Level Verbose -Message "SQL Server is using Version: $ServerVersion"

            $ogcompat = $db.CompatibilityLevel
            $dbversion = switch ($ogcompat) {
                "Version100" { 10 } # SQL Server 2008
                "Version110" { 11 } # SQL Server 2012
                "Version120" { 12 } # SQL Server 2014
                "Version130" { 13 } # SQL Server 2016
                "Version140" { 14 } # SQL Server 2017
                "Version150" { 15 } # SQL Server 2019
                default { 9 } # SQL Server 2005
            }

            if (-not $TargetCompatibility) {
                if ($dbversion -lt $ServerVersion) {
                    If ($Pscmdlet.ShouldProcess($server.Name, "Updating $db version from $dbversion to $ServerVersion")) {
                        $comp = $ServerVersion * 10
                        $sql = "ALTER DATABASE $db SET COMPATIBILITY_LEVEL = $comp"
                        try {
                            $db.ExecuteNonQuery($sql)
                            $db.Refresh()
                            Get-DbaDbCompatibility -SqlInstance $server -Database $db.Name
                        } catch {
                            Stop-Function -Message "Failed to change Compatibility Level" -ErrorRecord $_ -Target $instance -Continue
                        }
                    }
                }
            } else {
                if ($Pscmdlet.ShouldProcess($server.Name, "Updating $db version from $dbversion to $TargetCompatibility")) {
                    $comp = $TargetCompatibility * 10
                    $sql = "ALTER DATABASE $db SET COMPATIBILITY_LEVEL = $comp"
                    try {
                        $db.ExecuteNonQuery($sql)
                        $db.Refresh()
                        Get-DbaDbCompatibility -SqlInstance $server -Database $db.Name
                    } catch {
                        Stop-Function -Message "Failed to change Compatibility Level" -ErrorRecord $_ -Target $instance -Continue
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Set-DbaDbCompression.ps1
function Set-DbaDbCompression {
    <#
    .SYNOPSIS
        Sets tables and indexes with preferred compression setting.

    .DESCRIPTION
        This function sets the appropriate compression recommendation, determined either by using the Tiger Team's query or set to the CompressionType parameter.

        Remember Uptime is critical for the Tiger Team query, the longer uptime, the more accurate the analysis is.
        You would probably be best if you utilized Get-DbaUptime first, before running this command.

        Set-DbaDbCompression script derived from GitHub and the tigertoolbox
        (https://github.com/Microsoft/tigertoolbox/tree/master/Evaluate-Compression-Gains)

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto populated from the server.

    .PARAMETER CompressionType
        Control the compression type applied. Default is 'Recommended' which uses the Tiger Team query to use the most appropriate setting per object. Other option is to compress all objects to either Row or Page.

    .PARAMETER MaxRunTime
        Will continue to alter tables and indexes for the given amount of minutes.

    .PARAMETER PercentCompression
        Will only work on the tables/indexes that have the calculated savings at and higher for the given number provided.

    .PARAMETER InputObject
        Takes the output of Test-DbaDbCompression as an object and applied compression based on those recommendations.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Compression, Table, Database
        Author: Jason Squires (@js_0505), [email protected]

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaDbCompression

    .EXAMPLE
        PS C:\> Set-DbaDbCompression -SqlInstance localhost -MaxRunTime 60 -PercentCompression 25

        Set the compression run time to 60 minutes and will start the compression of tables/indexes that have a difference of 25% or higher between current and recommended.

    .EXAMPLE
        PS C:\> Set-DbaDbCompression -SqlInstance ServerA -Database DBName -CompressionType Page

        Utilizes Page compression for all objects in DBName on ServerA with no time limit.

    .EXAMPLE
        PS C:\> Set-DbaDbCompression -SqlInstance ServerA -Database DBName -PercentCompression 25 | Out-GridView

        Will compress tables/indexes within the specified database that would show any % improvement with compression and with no time limit. The results will be piped into a nicely formatted GridView.

    .EXAMPLE
        PS C:\> $testCompression = Test-DbaDbCompression -SqlInstance ServerA -Database DBName
        PS C:\> Set-DbaDbCompression -SqlInstance ServerA -Database DBName -InputObject $testCompression

        Gets the compression suggestions from Test-DbaDbCompression into a variable, this can then be reviewed and passed into Set-DbaDbCompression.

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> Set-DbaDbCompression -SqlInstance ServerA -ExcludeDatabase Database -SqlCredential $cred -MaxRunTime 60 -PercentCompression 25

        Set the compression run time to 60 minutes and will start the compression of tables/indexes for all databases except the specified excluded database. Only objects that have a difference of 25% or higher between current and recommended will be compressed.

    .EXAMPLE
        PS C:\> $servers = 'Server1','Server2'
        PS C:\> foreach ($svr in $servers) {
        >> Set-DbaDbCompression -SqlInstance $svr -MaxRunTime 60 -PercentCompression 25 | Export-Csv -Path C:\temp\CompressionAnalysisPAC.csv -Append
        >> }

        Set the compression run time to 60 minutes and will start the compression of tables/indexes across all listed servers that have a difference of 25% or higher between current and recommended. Output of command is exported to a csv.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseOutputTypeCorrectly", "", Justification = "PSSA Rule Ignored by BOH")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [ValidateSet("Recommended", "Page", "Row", "None")]$CompressionType = "Recommended",
        [int]$MaxRunTime = 0,
        [int]$PercentCompression = 0,
        $InputObject,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        $starttime = Get-Date
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failed to process Instance $instance" -ErrorRecord $_ -Target $instance -Continue
            }

            $Server.ConnectionContext.StatementTimeout = 0

            #The reason why we do this is because of SQL 2016 and they now allow for compression on standard edition.
            if ($server.EngineEdition -notmatch 'Enterprise' -and $server.VersionMajor -lt '13') {
                Stop-Function -Message "Only SQL Server Enterprise Edition supports compression on $server" -Target $server -Continue
            }
            try {
                $dbs = $server.Databases | Where-Object { $_.IsAccessible -and $_.IsSystemObject -eq 0}
                if ($Database) {
                    $dbs = $dbs | Where-Object { $_.Name -in $Database }
                }
                if ($ExcludeDatabase) {
                    $dbs = $dbs | Where-Object { $_.Name -NotIn $ExcludeDatabase }
                }
            } catch {
                Stop-Function -Message "Unable to gather list of databases for $instance" -Target $instance -ErrorRecord $_ -Continue
            }

            foreach ($db in $dbs) {
                try {
                    Write-Message -Level Verbose -Message "Querying $instance - $db"
                    if ($db.status -ne 'Normal' -or $db.IsAccessible -eq $false) {
                        Write-Message -Level Warning -Message "$db is not accessible" -Target $db
                        continue
                    }
                    if ($db.CompatibilityLevel -lt 'Version100') {
                        Stop-Function -Message "$db has a compatibility level lower than Version100 and will be skipped." -Target $db -Continue
                    }
                    if ($CompressionType -eq "Recommended") {
                        if (Test-Bound "InputObject") {
                            Write-Message -Level Verbose -Message "Using passed in compression suggestions"
                            $compressionSuggestion = $InputObject | Where-Object {$_.Database -eq $db.name}
                        } else {
                            Write-Message -Level Verbose -Message "Testing database for compression suggestions for $instance.$db"
                            $compressionSuggestion = Test-DbaDbCompression -SqlInstance $server -Database $db.Name
                        }
                    }
                } catch {
                    Stop-Function -Message "Unable to query $instance - $db" -Target $db -ErrorRecord $_ -Continue
                }

                try {
                    if ($CompressionType -eq "Recommended") {
                        if ($Pscmdlet.ShouldProcess($db, "Applying suggested compression using results from Test-DbaDbCompression")) {
                            Write-Message -Level Verbose -Message "Applying suggested compression settings using Test-DbaDbCompression"
                            $results += $compressionSuggestion | Select-Object *, @{l = 'AlreadyProcessed'; e = {"False"}}
                            foreach ($obj in ($results | Where-Object {$_.CompressionTypeRecommendation -notin @('NO_GAIN', '?') -and $_.PercentCompression -ge $PercentCompression} | Sort-Object PercentCompression -Descending)) {
                                if ($MaxRunTime -ne 0 -and ($(get-date) - $starttime).TotalMinutes -ge $MaxRunTime) {
                                    Write-Message -Level Verbose -Message "Reached max run time of $MaxRunTime"
                                    break
                                }
                                if ($obj.indexId -le 1) {
                                    ##heaps and clustered indexes
                                    Write-Message -Level Verbose -Message "Applying $($obj.CompressionTypeRecommendation) compression to $($obj.Database).$($obj.Schema).$($obj.TableName)"
                                    $($server.Databases[$obj.Database].Tables[$obj.TableName, $obj.Schema].PhysicalPartitions | Where-Object {$_.PartitionNumber -eq $obj.Partition}).DataCompression = $($obj.CompressionTypeRecommendation)
                                    $server.Databases[$obj.Database].Tables[$obj.TableName, $($obj.Schema)].Rebuild()
                                    $obj.AlreadyProcessed = "True"
                                } else {
                                    ##nonclustered indexes
                                    Write-Message -Level Verbose -Message "Applying $($obj.CompressionTypeRecommendation) compression to $($obj.Database).$($obj.Schema).$($obj.TableName).$($obj.IndexName)"
                                    $($server.Databases[$obj.Database].Tables[$obj.TableName, $obj.Schema].Indexes[$obj.IndexName].PhysicalPartitions | Where-Object {$_.PartitionNumber -eq $obj.Partition}).DataCompression = $($obj.CompressionTypeRecommendation)
                                    $server.Databases[$obj.Database].Tables[$obj.TableName, $obj.Schema].Indexes[$obj.IndexName].Rebuild()
                                    $obj.AlreadyProcessed = "True"
                                }
                                $obj
                            }
                        }
                    } else {
                        if ($Pscmdlet.ShouldProcess($db, "Applying $CompressionType compression")) {
                            Write-Message -Level Verbose -Message "Applying $CompressionType compression to all objects in $($db.name)"
                            foreach ($obj in $server.Databases[$($db.name)].Tables | Where-Object {!$_.IsMemoryOptimized}) {
                                if ($MaxRunTime -ne 0 -and ($(get-date) - $starttime).TotalMinutes -ge $MaxRunTime) {
                                    Write-Message -Level Verbose -Message "Reached max run time of $MaxRunTime"
                                    break
                                }
                                foreach ($p in $($obj.PhysicalPartitions | Where-Object {$_.DataCompression -notin ($CompressionType, 'ColumnStore', 'ColumnStoreArchive')})) {
                                    Write-Message -Level Verbose -Message "Compressing table $($obj.Schema).$($obj.Name)"
                                    $($obj.PhysicalPartitions | Where-Object {$_.PartitionNumber -eq $P.PartitionNumber}).DataCompression = $CompressionType
                                    $obj.Rebuild()
                                    [pscustomobject]@{
                                        ComputerName                  = $server.ComputerName
                                        InstanceName                  = $server.ServiceName
                                        SqlInstance                   = $server.DomainInstanceName
                                        Database                      = $db.Name
                                        Schema                        = $obj.Schema
                                        TableName                     = $obj.Name
                                        IndexName                     = $null
                                        Partition                     = $p.PartitionNumber
                                        IndexID                       = 0
                                        IndexType                     = Switch ($obj.HasHeapIndex) {$false {"ClusteredIndex"} $true {"Heap"}}
                                        PercentScan                   = $null
                                        PercentUpdate                 = $null
                                        RowEstimatePercentOriginal    = $null
                                        PageEstimatePercentOriginal   = $null
                                        CompressionTypeRecommendation = $CompressionType.ToUpper()
                                        SizeCurrent                   = $null
                                        SizeRequested                 = $null
                                        PercentCompression            = $null
                                        AlreadyProcessed              = "True"
                                    }
                                }

                                foreach ($index in $($obj.Indexes | Where-Object {!$_.IsMemoryOptimized -and $_.IndexType -notmatch 'Columnstore'})) {
                                    if ($MaxRunTime -ne 0 -and ($(get-date) - $starttime).TotalMinutes -ge $MaxRunTime) {
                                        Write-Message -Level Verbose -Message "Reached max run time of $MaxRunTime"
                                        break
                                    }
                                    foreach ($p in $($index.PhysicalPartitions | Where-Object {$_.DataCompression -ne $CompressionType})) {
                                        Write-Message -Level Verbose -Message "Compressing $($Index.IndexType) $($Index.Name) Partition $($p.PartitionNumber)"

                                        ## There is a bug in SMO where setting compression to None at the index level doesn't work
                                        ## Once this UserVoice item is fixed the workaround can be removed
                                        ## https://feedback.azure.com/forums/908035-sql-server/suggestions/34080112-data-compression-smo-bug
                                        if ($CompressionType -eq "None") {
                                            $query = "ALTER INDEX [$($index.Name)] ON $($index.Parent) REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = $CompressionType)"
                                            $Server.Query($query, $db.Name)
                                        } else {
                                            $($Index.PhysicalPartitions | Where-Object {$_.PartitionNumber -eq $P.PartitionNumber}).DataCompression = $CompressionType
                                            $index.Rebuild()
                                        }

                                        [pscustomobject]@{
                                            ComputerName                  = $server.ComputerName
                                            InstanceName                  = $server.ServiceName
                                            SqlInstance                   = $server.DomainInstanceName
                                            Database                      = $db.Name
                                            Schema                        = $obj.Schema
                                            TableName                     = $obj.Name
                                            IndexName                     = $index.Name
                                            Partition                     = $p.PartitionNumber
                                            IndexID                       = $index.Id
                                            IndexType                     = $index.IndexType
                                            PercentScan                   = $null
                                            PercentUpdate                 = $null
                                            RowEstimatePercentOriginal    = $null
                                            PageEstimatePercentOriginal   = $null
                                            CompressionTypeRecommendation = $CompressionType.ToUpper()
                                            SizeCurrent                   = $null
                                            SizeRequested                 = $null
                                            PercentCompression            = $null
                                            AlreadyProcessed              = "True"
                                        }
                                    }
                                }
                            }
                            foreach ($index in $($server.Databases[$($db.name)].Views | Where-Object {$_.Indexes}).Indexes) {
                                foreach ($p in $($index.PhysicalPartitions | Where-Object {$_.DataCompression -ne $CompressionType})) {
                                    Write-Message -Level Verbose -Message "Compressing $($index.IndexType) $($index.Name) Partition $($p.PartitionNumber)"

                                    ## There is a bug in SMO where setting compression to None at the index level doesn't work
                                    ## Once this UserVoice item is fixed the workaround can be removed
                                    ## https://feedback.azure.com/forums/908035-sql-server/suggestions/34080112-data-compression-smo-bug
                                    if ($CompressionType -eq "None") {
                                        $query = "ALTER INDEX [$($index.Name)] ON $($index.Parent) REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = $CompressionType)"
                                        $query
                                        $Server.Query($query, $db.Name)
                                    } else {
                                        $($index.PhysicalPartitions | Where-Object {$_.PartitionNumber -eq $P.PartitionNumber}).DataCompression = $CompressionType
                                        $index.Rebuild()
                                    }

                                    [pscustomobject]@{
                                        ComputerName                  = $server.ComputerName
                                        InstanceName                  = $server.ServiceName
                                        SqlInstance                   = $server.DomainInstanceName
                                        Database                      = $db.Name
                                        Schema                        = $obj.Schema
                                        TableName                     = $obj.Name
                                        IndexName                     = $index.Name
                                        Partition                     = $p.PartitionNumber
                                        IndexID                       = $index.Id
                                        IndexType                     = $index.IndexType
                                        PercentScan                   = $null
                                        PercentUpdate                 = $null
                                        RowEstimatePercentOriginal    = $null
                                        PageEstimatePercentOriginal   = $null
                                        CompressionTypeRecommendation = $CompressionType.ToUpper()
                                        SizeCurrent                   = $null
                                        SizeRequested                 = $null
                                        PercentCompression            = $null
                                        AlreadyProcessed              = "True"
                                    }
                                }
                            }
                        }
                    }
                } catch {
                    Stop-Function -Message "Compression failed for $instance - $db" -Target $db -ErrorRecord $_ -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Set-DbaDbIdentity.ps1
function Set-DbaDbIdentity {
    <#
    .SYNOPSIS
        Checks and updates the current identity value via DBCC CHECKIDENT

    .DESCRIPTION
        Use the command DBCC CHECKIDENT to check and if necessary update the current identity value of a table and return results
        Can update an individual table via the ReSeedValue and RESEED option of DBCC CHECKIDENT

        Read more:
            - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkident-transact-sql

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.
        Only one database should be specified when using a RESEED value

    .PARAMETER Table
        The table(s) for which to check the current identity value.
        Only one table should be specified when using a RESEED value

    .PARAMETER ReSeedValue
        The new reseed value to be used to set as the current identity value.

    .PARAMETER WhatIf
        Shows what would happen if the cmdlet runs. The cmdlet is not run.

    .PARAMETER Confirm
        Prompts you for confirmation before running the cmdlet.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DBCC
        Author: Patrick Flynn (@sqllensman)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaDbIdentity

    .EXAMPLE
        PS C:\> Set-DbaDbIdentity -SqlInstance SQLServer2017 -Database AdventureWorks2014 -Table 'Production.ScrapReason'

        Connects to AdventureWorks2014 on instance SqlServer2017 using Windows Authentication and runs the command DBCC CHECKIDENT('Production.ScrapReason') to return the current identity value.

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> 'Sql1','Sql2/sqlexpress' | Set-DbaDbIdentity -SqlCredential $cred -Database AdventureWorks2014 -Table 'Production.ScrapReason'

        Connects to AdventureWorks2014 on instances Sql1 and Sql2/sqlexpress using sqladmin credential and runs the command DBCC CHECKIDENT('Production.ScrapReason') to return the current identity value.

    .EXAMPLE
        PS C:\> $query = "Select Schema_Name(t.schema_id) +'.' + t.name as TableName from sys.columns c INNER JOIN sys.tables t on t.object_id = c.object_id WHERE is_identity = 1"
        PS C:\> $IdentityTables = Invoke-DbaQuery -SqlInstance SQLServer2017 -Database AdventureWorks2014 -Query $query
        PS C:\> foreach ($tbl in $IdentityTables) {
        PS C:\>    Set-DbaDbIdentity -SqlInstance SQLServer2017 -Database AdventureWorks2014 -Table $tbl.TableName
        PS C:\> }

        Checks the current identity value for all tables with an Identity in the AdventureWorks2014 database on the SQLServer2017 and, if it is needed, changes the identity value.


    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [string[]]$Table,
        [int]$ReSeedValue,
        [switch]$EnableException
    )
    begin {
        $stringBuilder = New-Object System.Text.StringBuilder
        $null = $stringBuilder.Append("DBCC CHECKIDENT(#options#)")
    }
    process {
        if (Test-Bound -ParameterName ReSeedValue) {
            if ((Test-Bound -Not -ParameterName Database) -or (Test-Bound -Not -ParameterName Table)) {
                Stop-Function -Message "When using a reseed value you must specify a database and a table to execute against."
                return
            }

            if (($Database.Count -gt 1) -or ($Table.Count -gt 1)) {
                Stop-Function -Message "When using a reseed value you must specify a single database and a single table to execute against."
                return
            }
        }

        foreach ($instance in $SqlInstance) {
            Write-Message -Message "Attempting Connection to $instance" -Level Verbose
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $dbs = $server.Databases

            if ($Database) {
                $dbs = $dbs | Where-Object Name -In $Database
            }

            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Processing $db on $instance"

                if ($db.IsAccessible -eq $false) {
                    Stop-Function -Message "The database $db is not accessible. Skipping." -Continue
                }

                foreach ($tbl in $Table) {
                    try {
                        $query = $StringBuilder.ToString()
                        if (Test-Bound -Not -ParameterName ReSeedValue) {
                            $query = $query.Replace('#options#', "'$($tbl)'")
                        } else {
                            $query = $query.Replace('#options#', "'$($tbl)', RESEED, $($ReSeedValue)")
                        }

                        if ($Pscmdlet.ShouldProcess($server.Name, "Execute the command $query against $instance")) {
                            Write-Message -Message "Query to run: $query" -Level Verbose
                            $results = $server | Invoke-DbaQuery  -Query $query -Database $db.Name -MessagesToOutput
                            if ($null -ne $results) {
                                $words = $results.Split(" ")
                                $identityValue = $words[6].Replace("'", "").Replace(",", "")
                                if (Test-Bound -Not -ParameterName ReSeedValue) {
                                    $columnValue = $words[10].Replace("'", "").Replace(".", "")
                                } else {
                                    $columnValue = ''
                                }

                            } else {
                                $identityValue = $null
                                $columnValue = $null
                            }
                        }
                    } catch {
                        Stop-Function -Message "Error running  $query against $db" -Target $instance -ErrorRecord $_ -Exception $_.Exception -Continue
                    }
                    if ($Pscmdlet.ShouldProcess("console", "Outputting object")) {
                        [PSCustomObject]@{
                            ComputerName  = $server.ComputerName
                            InstanceName  = $server.ServiceName
                            SqlInstance   = $server.DomainInstanceName
                            Database      = $db.Name
                            Table         = $tbl
                            Cmd           = $query.ToString()
                            IdentityValue = $identityValue
                            ColumnValue   = $columnValue
                            Output        = $results
                        }
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Set-DbaDbMirror.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Set-DbaDbMirror {
    <#
    .SYNOPSIS
        Sets properties of database mirrors.

    .DESCRIPTION
        Sets properties of database mirrors.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function
        to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The target database.

    .PARAMETER Partner
        Sets the partner fqdn.

    .PARAMETER Witness
        Sets the witness fqdn.

    .PARAMETER SafetyLevel
        Sets the mirroring safety level.

    .PARAMETER State
        Sets the mirror state.

    .PARAMETER InputObject
        Allows piping from Get-DbaDatabase.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Mirror, HA
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaDbMirror

    .EXAMPLE
        PS C:\> Set-DbaDbMirror -SqlInstance sql2005 -Database dbatools -Partner TCP://SQL2008.ad.local:5374

        Prompts for confirmation then sets the partner to TCP://SQL2008.ad.local:5374 for the database "dbtools"

    .EXAMPLE
        PS C:\> Set-DbaDbMirror -SqlInstance sql2005 -Database dbatools -Witness TCP://SQL2012.ad.local:5502 -Confirm:$false

        Does not prompt for confirmation and sets the witness to TCP://SQL2012.ad.local:5502 for the database "dbtools"

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sql2005 | Out-GridView -PassThru | Set-DbaDbMirror -SafetyLevel Full -Confirm:$false

        Sets the safety level to Full for databases selected from a grid view. Does not prompt for confirmation.

    .EXAMPLE
        PS C:\> Set-DbaDbMirror -SqlInstance sql2005 -Database dbatools -State Suspend -Confirm:$false

        Does not prompt for confirmation and sets the state to suspend for the database "dbtools"

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [string]$Partner,
        [string]$Witness,
        [ValidateSet('Full', 'Off', 'None')]
        [string]$SafetyLevel,
        [ValidateSet('ForceFailoverAndAllowDataLoss', 'Failover', 'RemoveWitness', 'Resume', 'Suspend', 'Off')]
        [string]$State,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ((Test-Bound -ParameterName SqlInstance) -and (Test-Bound -Not -ParameterName Database)) {
            Stop-Function -Message "Database is required when SqlInstance is specified"
            return
        }
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $instance -SqlCredential $SqlCredential -Database $Database
        }

        foreach ($db in $InputObject) {
            try {
                if ($Partner) {
                    if ($Pscmdlet.ShouldProcess($db.Parent.Name, "Setting partner on $db")) {
                        # use t-sql cuz $db.Alter() doesnt always work against restoring dbs
                        $db.Parent.Query("ALTER DATABASE $db SET PARTNER = N'$Partner'")
                    }
                } elseif ($Witness) {
                    if ($Pscmdlet.ShouldProcess($db.Parent.Name, "Setting witness on $db")) {
                        $db.Parent.Query("ALTER DATABASE $db SET WITNESS = N'$Witness'")
                    }
                }

                if ($SafetyLevel) {
                    if ($Pscmdlet.ShouldProcess($db.Parent.Name, "Changing safety level to $SafetyLevel on $db")) {
                        $db.Parent.Query("ALTER DATABASE $db SET PARTNER SAFETY $SafetyLevel")
                        # $db.MirroringSafetyLevel = $SafetyLevel
                    }
                }

                if ($State) {
                    if ($Pscmdlet.ShouldProcess($db.Parent.Name, "Changing mirror state to $State on $db")) {
                        $db.ChangeMirroringState($State)
                        $db.Alter()
                        $db
                    }
                }
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_
            }
        }
    }
}
tools\dbatools\functions\Set-DbaDbOwner.ps1
function Set-DbaDbOwner {
    <#
    .SYNOPSIS
        Sets database owners with a desired login if databases do not match that owner.

    .DESCRIPTION
        This function will alter database ownership to match a specified login if their current owner does not match the target login. By default, the target login will be 'sa', but the function will allow the user to specify a different login for  ownership. The user can also apply this to all databases or only to a select list of databases (passed as either a comma separated list or a string array).

        Best Practice reference: http://weblogs.sqlteam.com/dang/archive/2008/01/13/Database-Owner-Troubles.aspx

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.

    .PARAMETER TargetLogin
        Specifies the login that you wish check for ownership. This defaults to 'sa' or the sysadmin name if sa was renamed. This must be a valid security principal which exists on the target server.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database, Owner, DbOwner
        Author: Michael Fal (@Mike_Fal), http://mikefal.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaDbOwner

    .EXAMPLE
        PS C:\> Set-DbaDbOwner -SqlInstance localhost

        Sets database owner to 'sa' on all databases where the owner does not match 'sa'.

    .EXAMPLE
        PS C:\> Set-DbaDbOwner -SqlInstance localhost -TargetLogin DOMAIN\account

        Sets the database owner to DOMAIN\account on all databases where the owner does not match DOMAIN\account.

    .EXAMPLE
        PS C:\> Set-DbaDbOwner -SqlInstance sqlserver -Database db1, db2

        Sets database owner to 'sa' on the db1 and db2 databases if their current owner does not match 'sa'.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [Alias("Login")]
        [string]$TargetLogin,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure." -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            # dynamic sa name for orgs who have changed their sa name
            if (!$TargetLogin) {
                $TargetLogin = ($server.logins | Where-Object { $_.id -eq 1 }).Name
            }

            #Validate login
            if (($server.Logins.Name) -notcontains $TargetLogin) {
                Stop-Function -Message "$TargetLogin is not a valid login on $instance. Moving on." -Continue -EnableException $EnableException
            }

            #Owner cannot be a group
            $TargetLoginObject = $server.Logins | where-object {$PSItem.Name -eq $TargetLogin }| Select-Object -property  Name, LoginType
            if ($TargetLoginObject.LoginType -eq 'WindowsGroup') {
                Stop-Function -Message "$TargetLogin is a group, therefore can't be set as owner. Moving on." -Continue -EnableException $EnableException
            }

            #Get database list. If value for -Database is passed, massage to make it a string array.
            #Otherwise, use all databases on the instance where owner not equal to -TargetLogin
            #use where owner and target login do not match
            #exclude system dbs
            $dbs = $server.Databases | Where-Object { $_.IsAccessible -and $_.Owner -ne $TargetLogin -and @('master', 'model', 'msdb', 'tempdb', 'distribution') -notcontains $_.Name}

            #filter collection based on -Databases/-Exclude parameters
            if ($Database) {
                $dbs = $dbs | Where-Object { $Database -contains $_.Name }
            }

            if ($ExcludeDatabase) {
                $dbs = $dbs | Where-Object { $ExcludeDatabase -notcontains $_.Name }
            }

            Write-Message -Level Verbose -Message "Updating $($dbs.Count) database(s)."
            foreach ($db in $dbs) {
                $dbname = $db.name
                if ($PSCmdlet.ShouldProcess($instance, "Setting database owner for $dbname to $TargetLogin")) {
                    try {
                        Write-Message -Level Verbose -Message "Setting database owner for $dbname to $TargetLogin on $instance."
                        # Set database owner to $TargetLogin (default 'sa')
                        # Ownership validations checks

                        #Database is online and accessible
                        if ($db.Status -notmatch 'Normal') {
                            Write-Message -Level Warning -Message "$dbname on $instance is in a  $($db.Status) state and can not be altered. It will be skipped."
                        }
                        #Database is updatable, not read-only
                        elseif ($db.IsUpdateable -eq $false) {
                            Write-Message -Level Warning -Message "$dbname on $instance is not in an updateable state and can not be altered. It will be skipped."
                        }
                        #Is the login mapped as a user? Logins already mapped in the database can not be the owner
                        elseif ($db.Users.name -contains $TargetLogin) {
                            Write-Message -Level Warning -Message "$dbname on $instance has $TargetLogin as a mapped user. Mapped users can not be database owners."
                        } else {
                            $db.SetOwner($TargetLogin)
                            [PSCustomObject]@{
                                ComputerName = $server.ComputerName
                                InstanceName = $server.ServiceName
                                SqlInstance  = $server.DomainInstanceName
                                Database     = $db
                                Owner        = $TargetLogin
                            }
                        }
                    } catch {
                        Stop-Function -Message "Failure updating owner." -ErrorRecord $_ -Target $instance -Continue
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Set-DbaDatabaseOwner
    }
}
tools\dbatools\functions\Set-DbaDbQueryStoreOption.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Set-DbaDbQueryStoreOption {
    <#
    .SYNOPSIS
        Configure Query Store settings for a specific or multiple databases.

    .DESCRIPTION
        Configure Query Store settings for a specific or multiple databases.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        SqlCredential object used to connect to the SQL Server as a different user.

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER AllDatabases
        Run command against all user databases

    .PARAMETER State
        Set the state of the Query Store. Valid options are "ReadWrite", "ReadOnly" and "Off".

    .PARAMETER FlushInterval
        Set the flush to disk interval of the Query Store in seconds.

    .PARAMETER CollectionInterval
        Set the runtime statistics collection interval of the Query Store in minutes.

    .PARAMETER MaxSize
        Set the maximum size of the Query Store in MB.

    .PARAMETER CaptureMode
        Set the query capture mode of the Query Store. Valid options are "Auto" and "All".

    .PARAMETER CleanupMode
        Set the query cleanup mode policy. Valid options are "Auto" and "Off".

    .PARAMETER StaleQueryThreshold
        Set the stale query threshold in days.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run

    .PARAMETER Confirm
        Prompts for confirmation of every step. For example:

        Are you sure you want to perform this action?
        Performing the operation "Changing Desired State" on target "pubs on SQL2016\VNEXT".
        [Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: QueryStore
        Author: Enrico van de Laar (@evdlaar)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaQueryStoreOptions

    .EXAMPLE
        PS C:\> Set-DbaDbQueryStoreOption -SqlInstance ServerA\SQL -State ReadWrite -FlushInterval 600 -CollectionInterval 10 -MaxSize 100 -CaptureMode All -CleanupMode Auto -StaleQueryThreshold 100 -AllDatabases

        Configure the Query Store settings for all user databases in the ServerA\SQL Instance.

    .EXAMPLE
        PS C:\> Set-DbaDbQueryStoreOption -SqlInstance ServerA\SQL -FlushInterval 600

        Only configure the FlushInterval setting for all Query Store databases in the ServerA\SQL Instance.

    .EXAMPLE
        PS C:\> Set-DbaDbQueryStoreOption -SqlInstance ServerA\SQL -Database AdventureWorks -State ReadWrite -FlushInterval 600 -CollectionInterval 10 -MaxSize 100 -CaptureMode all -CleanupMode Auto -StaleQueryThreshold 100

        Configure the Query Store settings for the AdventureWorks database in the ServerA\SQL Instance.

    .EXAMPLE
        PS C:\> Set-DbaDbQueryStoreOption -SqlInstance ServerA\SQL -Exclude AdventureWorks -State ReadWrite -FlushInterval 600 -CollectionInterval 10 -MaxSize 100 -CaptureMode all -CleanupMode Auto -StaleQueryThreshold 100

        Configure the Query Store settings for all user databases except the AdventureWorks database in the ServerA\SQL Instance.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]
        $SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$AllDatabases,
        [ValidateSet('ReadWrite', 'ReadOnly', 'Off')]
        [string[]]$State,
        [int64]$FlushInterval,
        [int64]$CollectionInterval,
        [int64]$MaxSize,
        [ValidateSet('Auto', 'All')]
        [string[]]$CaptureMode,
        [ValidateSet('Auto', 'Off')]
        [string[]]$CleanupMode,
        [int64]$StaleQueryThreshold,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        $ExcludeDatabase += 'master', 'tempdb'
    }

    process {
        if (!$Database -and !$ExcludeDatabase -and !$AllDatabases) {
            Stop-Function -Message "You must specify a database(s) to execute against using either -Database, -ExcludeDatabase or -AllDatabases"
            return
        }

        if (!$State -and !$FlushInterval -and !$CollectionInterval -and !$MaxSize -and !$CaptureMode -and !$CleanupMode -and !$StaleQueryThreshold) {
            Stop-Function -Message "You must specify something to change."
            return
        }

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 13

            } catch {
                Stop-Function -Message "Can't connect to $instance. Moving on." -Category InvalidOperation -InnerErrorRecord $_ -Target $instance -Continue
            }

            # We have to exclude all the system databases since they cannot have the Query Store feature enabled
            $dbs = Get-DbaDatabase -SqlInstance $server -ExcludeDatabase $ExcludeDatabase -Database $Database | Where-Object IsAccessible

            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Processing $($db.name) on $instance"

                if ($db.IsAccessible -eq $false) {
                    Write-Message -Level Warning -Message "The database $db on server $instance is not accessible. Skipping database."
                    continue
                }

                if ($State) {
                    if ($Pscmdlet.ShouldProcess("$db on $instance", "Changing DesiredState to $state")) {
                        $db.QueryStoreOptions.DesiredState = $State
                        $db.QueryStoreOptions.Alter()
                        $db.QueryStoreOptions.Refresh()
                    }
                }

                if ($db.QueryStoreOptions.DesiredState -eq "Off" -and (Test-Bound -Parameter State -Not)) {
                    Write-Message -Level Warning -Message "State is set to Off; cannot change values. Please update State to ReadOnly or ReadWrite."
                    continue
                }

                if ($FlushInterval) {
                    if ($Pscmdlet.ShouldProcess("$db on $instance", "Changing DataFlushIntervalInSeconds to $FlushInterval")) {
                        $db.QueryStoreOptions.DataFlushIntervalInSeconds = $FlushInterval
                    }
                }

                if ($CollectionInterval) {
                    if ($Pscmdlet.ShouldProcess("$db on $instance", "Changing StatisticsCollectionIntervalInMinutes to $CollectionInterval")) {
                        $db.QueryStoreOptions.StatisticsCollectionIntervalInMinutes = $CollectionInterval
                    }
                }

                if ($MaxSize) {
                    if ($Pscmdlet.ShouldProcess("$db on $instance", "Changing MaxStorageSizeInMB to $MaxSize")) {
                        $db.QueryStoreOptions.MaxStorageSizeInMB = $MaxSize
                    }
                }

                if ($CaptureMode) {
                    if ($Pscmdlet.ShouldProcess("$db on $instance", "Changing QueryCaptureMode to $CaptureMode")) {
                        $db.QueryStoreOptions.QueryCaptureMode = $CaptureMode
                    }
                }

                if ($CleanupMode) {
                    if ($Pscmdlet.ShouldProcess("$db on $instance", "Changing SizeBasedCleanupMode to $CleanupMode")) {
                        $db.QueryStoreOptions.SizeBasedCleanupMode = $CleanupMode
                    }
                }

                if ($StaleQueryThreshold) {
                    if ($Pscmdlet.ShouldProcess("$db on $instance", "Changing StaleQueryThresholdInDays to $StaleQueryThreshold")) {
                        $db.QueryStoreOptions.StaleQueryThresholdInDays = $StaleQueryThreshold
                    }
                }

                # Alter the Query Store Configuration
                if ($Pscmdlet.ShouldProcess("$db on $instance", "Altering Query Store configuration on database")) {
                    try {
                        $db.QueryStoreOptions.Alter()
                        $db.Alter()
                        $db.Refresh()
                    } catch {
                        Stop-Function -Message "Could not modify configuration." -Category InvalidOperation -InnerErrorRecord $_ -Target $db -Continue
                    }
                }

                if ($Pscmdlet.ShouldProcess("$db on $instance", "Getting results from Get-DbaDbQueryStoreOption")) {
                    # Display resulting changes
                    Get-DbaDbQueryStoreOption -SqlInstance $server -Database $db.name -Verbose:$false
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Set-DbaDbQueryStoreOptions
    }
}
tools\dbatools\functions\Set-DbaDbRecoveryModel.ps1
function Set-DbaDbRecoveryModel {
    <#
    .SYNOPSIS
        Set-DbaDbRecoveryModel sets the Recovery Model.

    .DESCRIPTION
        Set-DbaDbRecoveryModel sets the Recovery Model for user databases.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. if unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER AllDatabases
        This is a parameter that was included for safety, so you don't accidentally set options on all databases without specifying

    .PARAMETER RecoveryModel
        Recovery Model to be set. Valid options are 'Simple', 'Full', 'BulkLogged'

        Details about the recovery models can be found here:
        https://docs.microsoft.com/en-us/sql/relational-databases/backup-restore/recovery-models-sql-server

    .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.

    .PARAMETER Confirm
        Prompts for confirmation. For example:

        Are you sure you want to perform this action?
        Performing the operation "ALTER DATABASE [model] SET RECOVERY Full" on target "[model] on WERES14224".
        [Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER InputObject
        A collection of databases (such as returned by Get-DbaDatabase)

    .NOTES
        Tags: RecoveryModel, Database
        Author: Viorel Ciucu (@viorelciucu), https://www.cviorel.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaDbRecoveryModel

    .EXAMPLE
        PS C:\> Set-DbaDbRecoveryModel -SqlInstance sql2014 -RecoveryModel BulkLogged -Database model -Confirm:$true -Verbose

        Sets the Recovery Model to BulkLogged for database [model] on SQL Server instance sql2014. User is requested to confirm the action.

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sql2014 -Database TestDB | Set-DbaDbRecoveryModel -RecoveryModel Simple  -Confirm:$false

        Sets the Recovery Model to Simple for database [TestDB] on SQL Server instance sql2014. Confirmation is not required.

    .EXAMPLE
        PS C:\> Set-DbaDbRecoveryModel -SqlInstance sql2014 -RecoveryModel Simple -Database TestDB -Confirm:$false

        Sets the Recovery Model to Simple for database [TestDB] on SQL Server instance sql2014. Confirmation is not required.

    .EXAMPLE
        PS C:\> Set-DbaDbRecoveryModel -SqlInstance sql2014 -RecoveryModel Simple -AllDatabases -Confirm:$false

        Sets the Recovery Model to Simple for ALL uses databases MODEL database on SQL Server instance sql2014. Runs without asking for confirmation.

    .EXAMPLE
        PS C:\> Set-DbaDbRecoveryModel -SqlInstance sql2014 -RecoveryModel BulkLogged -Database TestDB1, TestDB2 -Confirm:$false -Verbose

        Sets the Recovery Model to BulkLogged for [TestDB1] and [TestDB2] databases on SQL Server instance sql2014. Runs without asking for confirmation.

       #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [parameter(Mandatory, ParameterSetName = "Instance")]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(Mandatory)]
        [ValidateSet('Simple', 'Full', 'BulkLogged')]
        [string]$RecoveryModel,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$AllDatabases,
        [switch]$EnableException,
        [parameter(Mandatory, ValueFromPipeline, ParameterSetName = "Pipeline")]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if (!$Database -and !$AllDatabases -and !$ExcludeDatabase) {
                Stop-Function -Message "You must specify -AllDatabases or -Database to continue"
                return
            }

            # We need to be able to change the RecoveryModel for model database
            $systemdbs = @("tempdb")
            $databases = $server.Databases | Where-Object { $systemdbs -notcontains $_.Name -and $_.IsAccessible }

            # filter collection based on -Database/-Exclude parameters
            if ($Database) {
                $databases = $databases | Where-Object Name -In $Database
            }

            if ($ExcludeDatabase) {
                $databases = $databases | Where-Object Name -NotIn $ExcludeDatabase
            }

            if (!$databases) {
                Stop-Function -Message "The database(s) you specified do not exist on the instance $instance."
                return
            }

            $InputObject += $databases
        }

        foreach ($db in $InputObject) {
            if ($db.RecoveryModel -eq $RecoveryModel) {
                Stop-Function -Message "Recovery Model for database $db is already set to $RecoveryModel" -Category ConnectionError -Target $instance -Continue
            } else {
                if ($Pscmdlet.ShouldProcess("$db on $instance", "ALTER DATABASE $db SET RECOVERY $RecoveryModel")) {
                    $db.RecoveryModel = $RecoveryModel
                    $db.Alter()
                    Write-Message -Level Verbose -Message "Recovery Model set to $RecoveryModel for database $db"
                }
            }
            Get-DbaDbRecoveryModel -SqlInstance $db.Parent -Database $db.name
        }
    }
}
tools\dbatools\functions\Set-DbaDbState.ps1
#ValidationTags#Messaging,FlowControl,Pipeline#
function Set-DbaDbState {
    <#
    .SYNOPSIS
        Sets various options for databases, hereby called "states"

    .DESCRIPTION
        Sets some common "states" on databases:
        - "RW" options (ReadOnly, ReadWrite)
        - "Status" options (Online, Offline, Emergency, plus a special "Detached")
        - "Access" options (SingleUser, RestrictedUser, MultiUser)

        Returns an object with SqlInstance, Database, RW, Status, Access, Notes

        Notes gets filled when something went wrong setting the state

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Credential object used to connect to the SQL Server as a different user

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. if unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER AllDatabases
        This is a parameter that was included for safety, so you don't accidentally set options on all databases without specifying

    .PARAMETER ReadOnly
        RW Option : Sets the database as READ_ONLY

    .PARAMETER ReadWrite
        RW Option : Sets the database as READ_WRITE

    .PARAMETER Online
        Status Option : Sets the database as ONLINE

    .PARAMETER Offline
        Status Option : Sets the database as OFFLINE

    .PARAMETER Emergency
        Status Option : Sets the database as EMERGENCY

    .PARAMETER Detached
        Status Option : Detaches the database

    .PARAMETER SingleUser
        Access Option : Sets the database as SINGLE_USER

    .PARAMETER RestrictedUser
        Access Option : Sets the database as RESTRICTED_USER

    .PARAMETER MultiUser
        Access Option : Sets the database as MULTI_USER

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER Force
        For most options, this translates to instantly rolling back any open transactions
        that may be stopping the process.
        For -Detached it is required to break mirroring and Availability Groups

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER InputObject
        Accepts piped database objects

    .NOTES
        Tags: Database, State
        Author: Simone Bizzotto (@niphold)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaDbState

    .EXAMPLE
        PS C:\> Set-DbaDbState -SqlInstance sqlserver2014a -Database HR -Offline

        Sets the HR database as OFFLINE

    .EXAMPLE
        PS C:\> Set-DbaDbState -SqlInstance sqlserver2014a -AllDatabases -Exclude HR -ReadOnly -Force

        Sets all databases of the sqlserver2014a instance, except for HR, as READ_ONLY

    .EXAMPLE
        PS C:\> Get-DbaDbState -SqlInstance sql2016 | Where-Object Status -eq 'Offline' | Set-DbaDbState -Online

        Finds all offline databases and sets them to online

    .EXAMPLE
        PS C:\> Set-DbaDbState -SqlInstance sqlserver2014a -Database HR -SingleUser

        Sets the HR database as SINGLE_USER

    .EXAMPLE
        PS C:\> Set-DbaDbState -SqlInstance sqlserver2014a -Database HR -SingleUser -Force

        Sets the HR database as SINGLE_USER, dropping all other connections (and rolling back open transactions)

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sqlserver2014a -Database HR | Set-DbaDbState -SingleUser -Force

        Gets the databases from Get-DbaDatabase, and sets them as SINGLE_USER, dropping all other connections (and rolling back open transactions)

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = "Server")]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]
        $SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$AllDatabases,
        [switch]$ReadOnly,
        [switch]$ReadWrite,
        [switch]$Online,
        [switch]$Offline,
        [switch]$Emergency,
        [switch]$Detached,
        [switch]$SingleUser,
        [switch]$RestrictedUser,
        [switch]$MultiUser,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException,
        [parameter(Mandatory, ValueFromPipeline, ParameterSetName = "Database")]
        [PsCustomObject[]]$InputObject
    )

    begin {
        function Get-WrongCombo($optset, $allparams) {
            $x = 0
            foreach ($opt in $optset) {
                if ($allparams.ContainsKey($opt)) { $x += 1 }
            }
            if ($x -gt 1) {
                $msg = $optset -Join ',-'
                $msg = "You can only specify one of: -" + $msg
                throw $msg
            }
        }

        function Edit-DatabaseState($sqlinstance, $dbname, $opt, $immediate = $false) {
            $warn = $null
            $sql = "ALTER DATABASE [$dbname] SET $opt"
            if ($immediate) {
                $sql += " WITH ROLLBACK IMMEDIATE"
            } else {
                $sql += " WITH NO_WAIT"
            }
            try {
                Write-Message -Level System -Message $sql
                if ($immediate) {
                    # this can be helpful only for SINGLE_USER databases
                    # but since $immediate is called, it does no more harm
                    # than the immediate rollback
                    $sqlinstance.KillAllProcesses($dbname)
                }
                $null = $sqlinstance.Query($sql)
            } catch {
                $warn = "Failed to set '$dbname' to $opt"
                Write-Message -Level Warning -Message $warn
            }
            return $warn
        }

        $StatusHash = @{
            'Offline'       = 'OFFLINE'
            'Normal'        = 'ONLINE'
            'EmergencyMode' = 'EMERGENCY'
        }

        function Get-DbState($databaseName, $dbStatuses) {
            $base = $dbStatuses | Where-Object DatabaseName -ceq $databaseName
            foreach ($status in $StatusHash.Keys) {
                if ($base.Status -match $status) {
                    $base.Status = $StatusHash[$status]
                    break
                }
            }
            return $base
        }

        $RWExclusive = @('ReadOnly', 'ReadWrite')
        $StatusExclusive = @('Online', 'Offline', 'Emergency', 'Detached')
        $AccessExclusive = @('SingleUser', 'RestrictedUser', 'MultiUser')
        $allparams = $PSBoundParameters
        try {
            Get-WrongCombo -optset $RWExclusive -allparams $allparams
        } catch {
            Stop-Function -Message $_
            return
        }
        try {
            Get-WrongCombo -optset $StatusExclusive -allparams $allparams
        } catch {
            Stop-Function -Message $_
            return
        }
        try {
            Get-WrongCombo -optset $AccessExclusive -allparams $allparams
        } catch {
            Stop-Function -Message $_
            return
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }
        $dbs = @()
        if (!$Database -and !$AllDatabases -and !$InputObject -and !$ExcludeDatabase) {
            Stop-Function -Message "You must specify a -AllDatabases or -Database to continue"
            return
        }

        if ($InputObject) {
            if ($InputObject.Database) {
                # comes from Get-DbaDbState
                $dbs += $InputObject.Database
            } elseif ($InputObject.Name) {
                # comes from Get-DbaDatabase
                $dbs += $InputObject
            }
        } else {
            foreach ($instance in $SqlInstance) {
                try {
                    $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
                } catch {
                    Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                }
                $all_dbs = $server.Databases
                $dbs += $all_dbs | Where-Object { @('master', 'model', 'msdb', 'tempdb', 'distribution') -notcontains $_.Name }

                if ($database) {
                    $dbs = $dbs | Where-Object { $database -contains $_.Name }
                }
                if ($ExcludeDatabase) {
                    $dbs = $dbs | Where-Object { $ExcludeDatabase -notcontains $_.Name }
                }
            }
        }

        # need to pick up here
        foreach ($db in $dbs) {
            if ($db.Name -in @('master', 'model', 'msdb', 'tempdb', 'distribution')) {
                Write-Message -Level Warning -Message "Database $db is a system one, skipping"
                Continue
            }
            $dbStatuses = @{}
            $server = $db.Parent
            if ($server -notin $dbStatuses.Keys) {
                $dbStatuses[$server] = Get-DbaDbState -SqlInstance $server
            }

            # normalizing properties returned by SMO to something more "fixed"
            $db_status = Get-DbState -DatabaseName $db.Name -dbStatuses $dbStatuses[$server]


            $warn = @()

            if ($db.DatabaseSnapshotBaseName.Length -gt 0) {
                Write-Message -Level Warning -Message "Database $db is a snapshot, skipping"
                Continue
            }

            if ($ReadOnly -eq $true) {
                if ($db_status.RW -eq 'READ_ONLY') {
                    Write-Message -Level VeryVerbose -Message "Database $db is already READ_ONLY"
                } else {
                    if ($Pscmdlet.ShouldProcess($server, "Set $db to READ_ONLY")) {
                        Write-Message -Level VeryVerbose -Message "Setting database $db to READ_ONLY"
                        $partial = Edit-DatabaseState -sqlinstance $server -dbname $db.Name -opt "READ_ONLY" -immediate $Force
                        $warn += $partial
                        if (!$partial) {
                            $db_status.RW = 'READ_ONLY'
                        }
                    }
                }
            }

            if ($ReadWrite -eq $true) {
                if ($db_status.RW -eq 'READ_WRITE') {
                    Write-Message -Level VeryVerbose -Message "Database $db is already READ_WRITE"
                } else {
                    if ($Pscmdlet.ShouldProcess($server, "Set $db to READ_WRITE")) {
                        Write-Message -Level VeryVerbose -Message "Setting database $db to READ_WRITE"
                        $partial = Edit-DatabaseState -sqlinstance $server -dbname $db.Name -opt "READ_WRITE" -immediate $Force
                        $warn += $partial
                        if (!$partial) {
                            $db_status.RW = 'READ_WRITE'
                        }
                    }
                }
            }

            if ($Online -eq $true) {
                if ($db_status.Status -eq 'ONLINE') {
                    Write-Message -Level VeryVerbose -Message "Database $db is already ONLINE"
                } else {
                    if ($Pscmdlet.ShouldProcess($server, "Set $db to ONLINE")) {
                        Write-Message -Level VeryVerbose -Message "Setting database $db to ONLINE"
                        $partial = Edit-DatabaseState -sqlinstance $server -dbname $db.Name -opt "ONLINE" -immediate $Force
                        $warn += $partial
                        if (!$partial) {
                            $db_status.Status = 'ONLINE'
                        }
                    }
                }
            }

            if ($Offline -eq $true) {
                if ($db_status.Status -eq 'OFFLINE') {
                    Write-Message -Level VeryVerbose -Message "Database $db is already OFFLINE"
                } else {
                    if ($Pscmdlet.ShouldProcess($server, "Set $db to OFFLINE")) {
                        Write-Message -Level VeryVerbose -Message "Setting database $db to OFFLINE"
                        $partial = Edit-DatabaseState -sqlinstance $server -dbname $db.Name -opt "OFFLINE" -immediate $Force
                        $warn += $partial
                        if (!$partial) {
                            $db_status.Status = 'OFFLINE'
                        }
                    }
                }
            }

            if ($Emergency -eq $true) {
                if ($db_status.Status -eq 'EMERGENCY') {
                    Write-Message -Level VeryVerbose -Message "Database $db is already EMERGENCY"
                } else {
                    if ($Pscmdlet.ShouldProcess($server, "Set $db to EMERGENCY")) {
                        Write-Message -Level VeryVerbose -Message "Setting database $db to EMERGENCY"
                        $partial = Edit-DatabaseState -sqlinstance $server -dbname $db.Name -opt "EMERGENCY" -immediate $Force
                        if (!$partial) {
                            $db_status.Status = 'EMERGENCY'
                        }
                    }
                }
            }

            if ($SingleUser -eq $true) {
                if ($db_status.Access -eq 'SINGLE_USER') {
                    Write-Message -Level VeryVerbose -Message "Database $db is already SINGLE_USER"
                } else {
                    if ($Pscmdlet.ShouldProcess($server, "Set $db to SINGLE_USER")) {
                        Write-Message -Level VeryVerbose -Message "Setting $db to SINGLE_USER"
                        $partial = Edit-DatabaseState -sqlinstance $server -dbname $db.Name -opt "SINGLE_USER" -immediate $Force
                        if (!$partial) {
                            $db_status.Access = 'SINGLE_USER'
                        }
                    }
                }
            }

            if ($RestrictedUser -eq $true) {
                if ($db_status.Access -eq 'RESTRICTED_USER') {
                    Write-Message -Level VeryVerbose -Message "Database $db is already RESTRICTED_USER"
                } else {
                    if ($Pscmdlet.ShouldProcess($server, "Set $db to RESTRICTED_USER")) {
                        Write-Message -Level VeryVerbose -Message "Setting $db to RESTRICTED_USER"
                        $partial = Edit-DatabaseState -sqlinstance $server -dbname $db.Name -opt "RESTRICTED_USER" -immediate $Force
                        if (!$partial) {
                            $db_status.Access = 'RESTRICTED_USER'
                        }
                    }
                }
            }

            if ($MultiUser -eq $true) {
                if ($db_status.Access -eq 'MULTI_USER') {
                    Write-Message -Level VeryVerbose -Message "Database $db is already MULTI_USER"
                } else {
                    if ($Pscmdlet.ShouldProcess($server, "Set $db to MULTI_USER")) {
                        Write-Message -Level VeryVerbose -Message "Setting $db to MULTI_USER"
                        $partial = Edit-DatabaseState -sqlinstance $server -dbname $db.Name -opt "MULTI_USER" -immediate $Force
                        if (!$partial) {
                            $db_status.Access = 'MULTI_USER'
                        }
                    }
                }
            }

            if ($Detached -eq $true) {
                # Refresh info about database state here (before detaching)
                $db.Refresh()
                # we need to see what snaps are on the server, as base databases cannot be dropped
                $snaps = $server.Databases | Where-Object { $_.DatabaseSnapshotBaseName.Length -gt 0 }
                $snaps = $snaps.DatabaseSnapshotBaseName | Get-Unique
                if ($db.Name -in $snaps) {
                    Write-Message -Level Warning -Message "Database $db has snapshots, you need to drop them before detaching, skipping..."
                    Continue
                }
                if ($db.IsMirroringEnabled -eq $true -or $db.AvailabilityGroupName.Length -gt 0) {
                    if ($Force -eq $false) {
                        Write-Message -Level Warning -Message "Needs -Force to detach $db, skipping"
                        Continue
                    }
                }

                if ($db.IsMirroringEnabled) {
                    if ($Pscmdlet.ShouldProcess($server, "Break mirroring for $db")) {
                        try {
                            $db.ChangeMirroringState([Microsoft.SqlServer.Management.Smo.MirroringOption]::Off)
                            $db.Alter()
                            $db.Refresh()
                            Write-Message -Level VeryVerbose -Message "Broke mirroring for $db"
                        } catch {
                            Stop-Function -Message "Could not break mirror for $db. Skipping." -ErrorRecord $_ -Target $server -Continue
                        }
                    }
                }

                if ($db.AvailabilityGroupName) {
                    $agname = $db.AvailabilityGroupName
                    if ($Pscmdlet.ShouldProcess($server, "Removing $db from AG [$agname]")) {
                        try {
                            $server.AvailabilityGroups[$db.AvailabilityGroupName].AvailabilityDatabases[$db.Name].Drop()
                            Write-Message -Level VeryVerbose -Message "Successfully removed $db from AG [$agname] on $server"
                        } catch {
                            Stop-Function -Message "Could not remove $db from AG [$agname] on $server" -ErrorRecord $_ -Target $server -Continue
                        }
                    }
                }

                # DBA 101 should encourage detaching just OFFLINE databases
                # we can do that here
                if ($Pscmdlet.ShouldProcess($server, "Detaching $db")) {
                    if ($db_status.Status -ne 'OFFLINE') {
                        $null = Edit-DatabaseState -sqlinstance $server -dbname $db.Name -opt "OFFLINE" -immediate $true
                    }
                    try {
                        $sql = "EXEC master.dbo.sp_detach_db N'$($db.Name)'"
                        Write-Message -Level System -Message $sql
                        $null = $server.Query($sql)
                        $db_status.Status = 'DETACHED'
                    } catch {
                        Stop-Function -Message "Failed to detach $db" -ErrorRecord $_ -Target $server -Continue
                        $warn += "Failed to detach"
                    }

                }

            }
            if ($warn) {
                $warn = $warn | Get-Unique
                $warn = $warn -Join ';'
            } else {
                $warn = $null
            }
            if ($Detached -eq $true) {
                [PSCustomObject]@{
                    ComputerName = $server.ComputerName
                    InstanceName = $server.ServiceName
                    SqlInstance  = $server.DomainInstanceName
                    DatabaseName = $db.Name
                    RW           = $db_status.RW
                    Status       = $db_status.Status
                    Access       = $db_status.Access
                    Notes        = $warn
                    Database     = $db
                } | Select-DefaultView -ExcludeProperty Database
            } else {
                $db.Refresh()
                if ($null -eq $warn) {
                    # we avoid reenumerating properties
                    $newstate = $db_status
                } else {
                    $newstate = Get-DbState -databaseName $db.Name -dbStatuses $stateCache[$server]
                }

                [PSCustomObject]@{
                    ComputerName = $server.ComputerName
                    InstanceName = $server.ServiceName
                    SqlInstance  = $server.DomainInstanceName
                    DatabaseName = $db.Name
                    RW           = $newstate.RW
                    Status       = $newstate.Status
                    Access       = $newstate.Access
                    Notes        = $warn
                    Database     = $db
                } | Select-DefaultView -ExcludeProperty Database
            }
        }

    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Set-DbaDatabaseState
    }
}
tools\dbatools\functions\Set-DbaEndpoint.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Set-DbaEndpoint {
    <#
    .SYNOPSIS
        Sets endpoint properties on a SQL Server instance.

    .DESCRIPTION
        Sets endpoint properties on a SQL Server instance.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Owner
        Change the endpoint owner.

    .PARAMETER Type
        Change the endpoint type. Options: DatabaseMirroring, ServiceBroker, Soap, TSql

    .PARAMETER Endpoint
        Only set specific endpoint properties.

    .PARAMETER AllEndpoints
        Set all endpoint properties on an instance.

    .PARAMETER InputObject
        Enables piping from Get-Endpoint.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Endpoint
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaEndpoint

    .EXAMPLE
        PS C:\> Set-DbaEndpoint -SqlInstance sql2016 -AllEndpoints -Owner sa

        Sets all endpoint owners to sa on sql2016

    .EXAMPLE
        PS C:\> Get-DbaEndpoint -SqlInstance sql2016 -Endpoint ep1 | Set-DbaEndpoint -Type TSql

        Changes the endpoint type to tsql on endpoint ep1

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$EndPoint,
        [string]$Owner,
        [ValidateSet('DatabaseMirroring', 'ServiceBroker', 'Soap', 'TSql')]
        [string]$Type,
        [switch]$AllEndpoints,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Endpoint[]]$InputObject,
        [switch]$EnableException
    )

    process {
        if ((Test-Bound -ParameterName SqlInstance) -And (Test-Bound -Not -ParameterName Endpoint, AllEndpoints)) {
            Stop-Function -Message "You must specify AllEndpoints or Endpoint when using the SqlInstance parameter."
            return
        }
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaEndpoint -SqlInstance $instance -SqlCredential $SqlCredential -EndPoint $Endpoint
        }

        $props = "Owner", "Type"
        foreach ($ep in $InputObject) {
            try {
                if ($Pscmdlet.ShouldProcess($ep.Parent.Name, "Seting properties on $ep")) {
                    foreach ($prop in $props) {
                        if ($prop -eq "Type") {
                            $realprop = "EndpointType"
                            if (Test-Bound -ParameterName $prop) {
                                $ep.$realprop = (Get-Variable -Name $prop -ValueOnly)
                            }
                        } elseif (Test-Bound -ParameterName $prop) {
                            $ep.$prop = (Get-Variable -Name $prop -ValueOnly)
                        }
                    }
                    $ep.Alter()
                    $ep
                }
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
            }
        }
    }
}
tools\dbatools\functions\Set-DbaErrorLogConfig.ps1
function Set-DbaErrorLogConfig {
    <#
    .SYNOPSIS
        Set the configuration for the ErrorLog on a given SQL Server instance

    .DESCRIPTION
        Sets the number of log files configured on all versions, and size in KB in SQL Server 2012+ and above.

        To set the Path to the ErrorLog, use Set-DbaStartupParameter -ErrorLog. Note that this command requires
        remote, administrative access to the Windows/WMI server, similar to SQL Configuration Manager.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER LogCount
        Integer value between 6 and 99 for setting the number of error log files to keep for SQL Server instance.

    .PARAMETER LogSize
        Integer value for the size in KB that you want the error log file to grow. This is feature only in SQL Server 2012 and higher. When the file reaches that limit SQL Server will roll the error log over.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Instance, ErrorLog
        Author: Shawn Melton (@wsmelton), https://wsmelton.github.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaErrorLogConfig

    .EXAMPLE
        PS C:\> Set-DbaErrorLogConfig -SqlInstance sql2017,sql2014 -LogCount 25

        Sets the number of error log files to 25 on sql2017 and sql2014

    .EXAMPLE
        PS C:\> Set-DbaErrorLogConfig -SqlInstance sql2014 -LogSize 102400

        Sets the size of the error log file, before it rolls over, to 102400 KB (100 MB) on sql2014

    .EXAMPLE
        PS C:\> Set-DbaErrorLogConfig -SqlInstance sql2012 -LogCount 25 -LogSize 500

        Sets the number of error log files to 25 and size before it will roll over to 500 KB on sql2012

    #>
    [cmdletbinding(SupportsShouldProcess)]
    param(
        [Parameter(ValueFromPipelineByPropertyName, Mandatory)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [ValidateRange(6, 99)]
        [int]$LogCount,
        [int]$LogSize,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $currentNumLogs = $server.NumberOfLogFiles
            $currentLogSize = $server.ErrorLogSizeKb

            $collection = [PSCustomObject]@{
                ComputerName = $server.ComputerName
                InstanceName = $server.ServiceName
                SqlInstance  = $server.DomainInstanceName
                LogCount     = $currentNumLogs
                LogSize      = [dbasize]($currentLogSize * 1024)
            }
            if (Test-Bound -ParameterName 'LogSize') {
                if ($server.VersionMajor -lt 11) {
                    Stop-Function -Message "Size is cannot be set on $instance. SQL Server 2008 R2 and below not supported." -Continue
                }
                if ($LogSize -eq $currentLogSize) {
                    Write-Message -Level Warning -Message "The provided value for LogSize is already set to $LogSize KB on $instance"
                } else {
                    if ($PSCmdlet.ShouldProcess($server, "Updating log size from [$currentLogSize] to [$LogSize]")) {
                        try {
                            $server.ErrorLogSizeKb = $LogSize
                            $server.Alter()
                        } catch {
                            Stop-Function -Message "Issue setting number of log files on $instance" -Target $instance -ErrorRecord $_ -Exception $_.Exception.InnerException.InnerException.InnerException -Continue
                        }
                    }
                    if ($PSCmdlet.ShouldProcess($server, "Output final results of setting error log size")) {
                        $server.Refresh()
                        $collection.LogSize = [dbasize]($server.ErrorLogSizeKb * 1024)
                    }
                }
            }

            if (Test-Bound -ParameterName 'LogCount') {
                if ($LogCount -eq $currentNumLogs) {
                    Write-Message -Level Warning -Message "The provided value for LogCount is already set to $LogCount on $instance"
                } else {
                    if ($PSCmdlet.ShouldProcess($server, "Setting number of logs from [$currentNumLogs] to [$LogCount]")) {
                        try {
                            $server.NumberOfLogFiles = $LogCount
                            $server.Alter()
                        } catch {
                            Stop-Function -Message "Issue setting number of log files on $instance" -Target $instance -ErrorRecord $_ -Exception $_.Exception.InnerException.InnerException.InnerException -Continue
                        }
                    }
                    if ($PSCmdlet.ShouldProcess($server, "Output final results of setting number of log files")) {
                        $server.Refresh()
                        $collection.LogCount = $server.NumberOfLogFiles
                    }
                }
            }
            $collection
        }
    }
}
tools\dbatools\functions\Set-DbaLogin.ps1
function Set-DbaLogin {
    <#
    .SYNOPSIS
        Set-DbaLogin makes it possible to make changes to one or more logins.

    .DESCRIPTION
        Set-DbaLogin will enable you to change the password, unlock, rename, disable or enable, deny or grant login privileges to the login. It's also possible to add or remove server roles from the login.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Login
        The login that needs to be changed

    .PARAMETER SecurePassword
        The new password for the login This can be either a credential or a secure string.

    .PARAMETER Unlock
        Switch to unlock an account. This will only be used in conjunction with the -SecurePassword parameter.
        The default is false.

    .PARAMETER MustChange
        Does the user need to change his/her password. This will only be used in conjunction with the -SecurePassword parameter.
        The default is false.

    .PARAMETER NewName
        The new name for the login.

    .PARAMETER Disable
        Disable the login

    .PARAMETER Enable
        Enable the login

    .PARAMETER DenyLogin
        Deny access to SQL Server

    .PARAMETER GrantLogin
        Grant access to SQL Server

    .PARAMETER PasswordPolicyEnforced
        Should the password policy be enforced.

    .PARAMETER AddRole
        Add one or more server roles to the login
        The following roles can be used "bulkadmin", "dbcreator", "diskadmin", "processadmin", "public", "securityadmin", "serveradmin", "setupadmin", "sysadmin".

    .PARAMETER RemoveRole
        Remove one or more server roles to the login
        The following roles can be used "bulkadmin", "dbcreator", "diskadmin", "processadmin", "public", "securityadmin", "serveradmin", "setupadmin", "sysadmin".

    .PARAMETER InputObject
        Allows logins to be piped in from Get-DbaLogin

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Login
        Author: Sander Stad (@sqlstad), sqlstad.nl

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaLogin

    .EXAMPLE
        PS C:\> $SecurePassword = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
        PS C:\> $cred = New-Object System.Management.Automation.PSCredential ("username", $SecurePassword)
        PS C:\> Set-DbaLogin -SqlInstance sql1 -Login login1 -SecurePassword $cred -Unlock -MustChange

        Set the new password for login1 using a credential, unlock the account and set the option
        that the user must change password at next logon.

    .EXAMPLE
        PS C:\> Set-DbaLogin -SqlInstance sql1 -Login login1 -Enable

        Enable the login

    .EXAMPLE
        PS C:\> Set-DbaLogin -SqlInstance sql1 -Login login1, login2, login3, login4 -Enable

        Enable multiple logins

    .EXAMPLE
        PS C:\> Set-DbaLogin -SqlInstance sql1, sql2, sql3 -Login login1, login2, login3, login4 -Enable

        Enable multiple logins on multiple instances

    .EXAMPLE
        PS C:\> Set-DbaLogin -SqlInstance sql1 -Login login1 -Disable

        Disable the login

    .EXAMPLE
        PS C:\> Set-DbaLogin -SqlInstance sql1 -Login login1 -DenyLogin

        Deny the login to connect to the instance

    .EXAMPLE
        PS C:\> Set-DbaLogin -SqlInstance sql1 -Login login1 -GrantLogin

        Grant the login to connect to the instance

    .EXAMPLE
        PS C:\> Set-DbaLogin -SqlInstance sql1 -Login login1 -PasswordPolicyEnforced

        Enforces the password policy on a login

    .EXAMPLE
        PS C:\> Set-DbaLogin -SqlInstance sql1 -Login login1 -PasswordPolicyEnforced:$false

        Disables enforcement of the password policy on a login

    .EXAMPLE
        PS C:\> Set-DbaLogin -SqlInstance sql1 -Login test -AddRole serveradmin

        Add the server role "serveradmin" to the login

    .EXAMPLE
        PS C:\> Set-DbaLogin -SqlInstance sql1 -Login test -RemoveRole bulkadmin

        Remove the server role "bulkadmin" to the login

    .EXAMPLE
        PS C:\> $login = Get-DbaLogin -SqlInstance sql1 -Login test
        PS C:\> $login | Set-DbaLogin -Disable

        Disable the login from the pipeline

    #>

    [CmdletBinding(SupportsShouldProcess)]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "", Justification = "For Parameter Password")]
    param (
        [Alias('ServerInstance', 'SqlServer')]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Login,
        [Alias("Password")]
        [object]$SecurePassword, #object so that it can accept credential or securestring
        [switch]$Unlock,
        [switch]$MustChange,
        [string]$NewName,
        [switch]$Disable,
        [switch]$Enable,
        [switch]$DenyLogin,
        [switch]$GrantLogin,
        [switch]$PasswordPolicyEnforced,
        [ValidateSet('bulkadmin', 'dbcreator', 'diskadmin', 'processadmin', 'public', 'securityadmin', 'serveradmin', 'setupadmin', 'sysadmin')]
        [string[]]$AddRole,
        [ValidateSet('bulkadmin', 'dbcreator', 'diskadmin', 'processadmin', 'public', 'securityadmin', 'serveradmin', 'setupadmin', 'sysadmin')]
        [string[]]$RemoveRole,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Login[]]$InputObject,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        # Check the parameters
        if ((Test-Bound -ParameterName 'SqlInstance') -and (Test-Bound -ParameterName 'Login' -Not)) {
            Stop-Function -Message 'You must specify a Login when using SqlInstance'
        }

        if ((Test-Bound -ParameterName 'NewName') -and $Login -eq $NewName) {
            Stop-Function -Message 'Login name is the same as the value in -NewName' -Target $Login -Continue
        }

        if ((Test-Bound -ParameterName 'Disable') -and (Test-Bound -ParameterName 'Enable')) {
            Stop-Function -Message 'You cannot use both -Enable and -Disable together' -Target $Login -Continue
        }

        if ((Test-Bound -ParameterName 'GrantLogin') -and (Test-Bound -ParameterName 'DenyLogin')) {
            Stop-Function -Message 'You cannot use both -GrantLogin and -DenyLogin together' -Target $Login -Continue
        }

        if (Test-bound -ParameterName 'SecurePassword') {
            switch ($SecurePassword.GetType().Name) {
                'PSCredential' { $NewSecurePassword = $SecurePassword.Password }
                'SecureString' { $NewSecurePassword = $SecurePassword }
                default {
                    Stop-Function -Message 'Password must be a PSCredential or SecureString' -Target $Login
                }
            }
        }
    }

    process {
        if (Test-FunctionInterrupt) { return }

        $allLogins = @{}
        foreach ($instance in $sqlinstance) {
            # Try connecting to the instance
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message 'Failure' -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            $allLogins[$instance.ToString()] = Get-DbaLogin -SqlInstance $server
            $InputObject += $allLogins[$instance.ToString()] | Where-Object { ($_.Name -eq $Login) -and ($_.IsSystemObject -eq $false) -and ($_.Name -notlike '##*') }
        }

        # Loop through all the logins
        foreach ($l in $InputObject) {
            if ($Pscmdlet.ShouldProcess($l, "Setting Changes to Login on $($server.name)")) {
                $server = $l.Parent

                # Create the notes
                $notes = @()

                # Change the name
                if (Test-Bound -ParameterName 'NewName') {
                    # Check if the new name doesn't already exist
                    if ($allLogins[$server.Name].Name -notcontains $NewName) {
                        try {
                            $l.Rename($NewName)
                        } catch {
                            $notes += "Couldn't rename login"
                            Stop-Function -Message "Something went wrong changing the name for $l" -Target $l -ErrorRecord $_ -Continue
                        }
                    } else {
                        $notes += 'New login name already exists'
                        Write-Message -Message "New login name $NewName already exists on $instance" -Level Verbose
                    }
                }

                # Change the password
                if (Test-bound -ParameterName 'SecurePassword') {
                    try {
                        $l.ChangePassword($NewSecurePassword, $Unlock, $MustChange)
                        $passwordChanged = $true
                    } catch {
                        $notes += "Couldn't change password"
                        $passwordChanged = $false
                        Stop-Function -Message "Something went wrong changing the password for $l" -Target $l -ErrorRecord $_ -Continue
                    }
                }

                # Disable the login
                if (Test-Bound -ParameterName 'Disable') {
                    if ($l.IsDisabled) {
                        Write-Message -Message "Login $l is already disabled" -Level Verbose
                    } else {
                        try {
                            $l.Disable()
                        } catch {
                            $notes += "Couldn't disable login"
                            Stop-Function -Message "Something went wrong disabling $l" -Target $l -ErrorRecord $_ -Continue
                        }
                    }
                }

                # Enable the login
                if (Test-Bound -ParameterName 'Enable') {
                    if (-not $l.IsDisabled) {
                        Write-Message -Message "Login $l is already enabled" -Level Verbose
                    } else {
                        try {
                            $l.Enable()
                        } catch {
                            $notes += "Couldn't enable login"
                            Stop-Function -Message "Something went wrong enabling $l" -Target $l -ErrorRecord $_ -Continue
                        }
                    }
                }

                # Deny access
                if (Test-Bound -ParameterName 'DenyLogin') {
                    if ($l.DenyWindowsLogin) {
                        Write-Message -Message "Login $l already has login access denied" -Level Verbose
                    } else {
                        $l.DenyWindowsLogin = $true
                    }
                }

                # Grant access
                if (Test-Bound -ParameterName 'GrantLogin') {
                    if (-not $l.DenyWindowsLogin) {
                        Write-Message -Message "Login $l already has login access granted" -Level Verbose
                    } else {
                        $l.DenyWindowsLogin = $false
                    }
                }

                # Enforce password policy
                if (Test-Bound -ParameterName 'PasswordPolicyEnforced') {
                    if ($l.PasswordPolicyEnforced -eq $PasswordPolicyEnforced) {
                        Write-Message -Message "Login $l password policy is already set to $($l.PasswordPolicyEnforced)" -Level Verbose
                    } else {
                        $l.PasswordPolicyEnforced = $PasswordPolicyEnforced
                    }
                }

                # Add server roles to login
                if ($AddRole) {
                    # Loop through each of the roles
                    foreach ($role in $AddRole) {
                        try {
                            $l.AddToRole($role)
                        } catch {
                            $notes += "Couldn't add role $role"
                            Stop-Function -Message "Something went wrong adding role $role to $l" -Target $l -ErrorRecord $_ -Continue
                        }
                    }
                }

                # Remove server roles from login
                if ($RemoveRole) {
                    # Loop through each of the roles
                    foreach ($role in $RemoveRole) {
                        try {
                            $server.Roles[$role].DropMember($l.Name)
                        } catch {
                            $notes += "Couldn't remove role $role"
                            Stop-Function -Message "Something went wrong removing role $role to $l" -Target $l -ErrorRecord $_ -Continue
                        }
                    }
                }

                # Alter the login to make the changes
                $l.Alter()

                # Retrieve the server roles for the login
                $roles = Get-DbaServerRoleMember -SqlInstance $server | Where-Object { $_.Name -eq $l.Name }

                # Check if there were any notes to include in the results
                if ($notes) {
                    $notes = $notes | Get-Unique
                    $notes = $notes -Join ';'
                } else {
                    $notes = $null
                }
                $rolenames = $roles.Role | Select-Object -Unique

                Add-Member -Force -InputObject $l -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName
                Add-Member -Force -InputObject $l -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName
                Add-Member -Force -InputObject $l -MemberType NoteProperty -Name SqlInstance -Value $server.DomainInstanceName
                Add-Member -Force -InputObject $l -MemberType NoteProperty -Name PasswordChanged -Value $passwordChanged
                Add-Member -Force -InputObject $l -MemberType NoteProperty -Name ServerRole -Value ($rolenames -join ', ')
                Add-Member -Force -InputObject $l -MemberType NoteProperty -Name Notes -Value $notes

                # backwards compatibility: LoginName, DenyLogin
                Add-Member -Force -InputObject $l -MemberType NoteProperty -Name LoginName -Value $l.Name
                Add-Member -Force -InputObject $l -MemberType NoteProperty -Name DenyLogin -Value $l.DenyWindowsLogin

                $defaults = 'ComputerName', 'InstanceName', 'SqlInstance', 'LoginName', 'DenyLogin', 'IsDisabled', 'IsLocked',
                'PasswordPolicyEnforced', 'MustChangePassword', 'PasswordChanged', 'ServerRole', 'Notes'

                Select-DefaultView -InputObject $l -Property $defaults
            }
        }
    }
}
tools\dbatools\functions\Set-DbaMaxDop.ps1
function Set-DbaMaxDop {
    <#
    .SYNOPSIS
        Sets SQL Server maximum degree of parallelism (Max DOP), then displays information relating to SQL Server Max DOP configuration settings. Works on SQL Server 2005 and higher.

    .DESCRIPTION
        Uses the Test-DbaMaxDop command to get the recommended value if -MaxDop parameter is not specified.

        These are just general recommendations for SQL Server and are a good starting point for setting the "max degree of parallelism" option.

        You can set MaxDop database scoped configurations if the server is version 2016 or higher

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Defaults to localhost.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies one or more databases to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies one or more databases to exclude from processing. Options for this list are auto-populated from the server

    .PARAMETER MaxDop
        Specifies the Max DOP value to set.

    .PARAMETER AllDatabases
        If this switch is enabled, Max DOP will be set on all databases. This switch is only useful on SQL Server 2016 and higher.

    .PARAMETER InputObject
        If Test-SqlMaxDop has been executed prior to this function, the results may be passed in via this parameter.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER WhatIf
        Shows what would happen if the cmdlet runs. The cmdlet is not run.

    .PARAMETER Confirm
        Prompts you for confirmation before running the cmdlet.

    .NOTES
        Tags: MaxDop, SpConfigure
        Author: Claudio Silva (@claudioessilva)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaMaxDop

    .EXAMPLE
        PS C:\> Set-DbaMaxDop -SqlInstance sql2008, sql2012

        Sets Max DOP to the recommended value for servers sql2008 and sql2012.

    .EXAMPLE
        PS C:\> Set-DbaMaxDop -SqlInstance sql2014 -MaxDop 4

        Sets Max DOP to 4 for server sql2014.

    .EXAMPLE
        PS C:\> Test-DbaMaxDop -SqlInstance sql2008 | Set-DbaMaxDop

        Gets the recommended Max DOP from Test-DbaMaxDop and applies it to to sql2008.

    .EXAMPLE
        PS C:\> Set-DbaMaxDop -SqlInstance sql2016 -Database db1

        Set recommended Max DOP for database db1 on server sql2016.

    .EXAMPLE
        PS C:\> Set-DbaMaxDop -SqlInstance sql2016 -AllDatabases

        Set recommended Max DOP for all databases on server sql2016.

       #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [int]$MaxDop = -1,
        [Parameter(ValueFromPipeline)]
        [pscustomobject]$InputObject,
        [Alias("All")]
        [switch]$AllDatabases,
        [switch]$EnableException
    )

    process {
        if ((Test-Bound -Parameter Database) -and (Test-Bound -Parameter AllDatabases) -and (Test-Bound -Parameter ExcludeDatabase)) {
            Stop-Function -Category InvalidArgument -Message "-Database, -AllDatabases and -ExcludeDatabase are mutually exclusive. Please choose only one. Quitting."
            return
        }

        $dbscopedconfiguration = $false

        if ($MaxDop -eq -1) {
            $UseRecommended = $true
        }

        if ((Test-Bound -Not -Parameter InputObject)) {
            $InputObject = Test-DbaMaxDop -SqlInstance $sqlinstance -SqlCredential $SqlCredential -Verbose:$false
        } elseif ($null -eq $InputObject.SqlInstance) {
            $InputObject = Test-DbaMaxDop -SqlInstance $sqlinstance -SqlCredential $SqlCredential -Verbose:$false
        }

        $InputObject | Add-Member -Force -NotePropertyName PreviousInstanceMaxDopValue -NotePropertyValue 0
        $InputObject | Add-Member -Force -NotePropertyName PreviousDatabaseMaxDopValue -NotePropertyValue 0

        #If we have servers 2016 or higher we will have a row per database plus the instance level, getting unique we only run one time per instance
        $servers = $InputObject | Select-Object SqlInstance -Unique

        foreach ($server in $servers) {
            $servername = $server.SqlInstance

            try {
                $server = Connect-SqlInstance -SqlInstance $servername -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $servername -Continue
            }

            if (!(Test-SqlSa -SqlInstance $server -SqlCredential $SqlCredential)) {
                Stop-Function -Message "Not a sysadmin on $server. Skipping." -Category PermissionDenied -ErrorRecord $_ -Target $currentServer -Continue
            }

            if ($server.versionMajor -ge 13) {
                Write-Message -Level Verbose -Message "Server '$servername' supports Max DOP configuration per database."

                if ((Test-Bound -Not -Parameter Database) -and (Test-Bound -Not -Parameter ExcludeDatabase)) {
                    #Set at instance level
                    $InputObject = $InputObject | Where-Object { $_.DatabaseMaxDop -eq "N/A" }
                } else {
                    $dbscopedconfiguration = $true

                    if ((Test-Bound -Not -Parameter AllDatabases) -and (Test-Bound -Parameter Database)) {
                        $InputObject = $InputObject | Where-Object { $_.Database -in $Database }
                    } elseif ((Test-Bound -Not -Parameter AllDatabases) -and (Test-Bound -Parameter ExcludeDatabase)) {
                        $InputObject = $InputObject | Where-Object { $_.Database -notin $ExcludeDatabase }
                    } else {
                        if (Test-Bound -Parameter AllDatabases) {
                            $InputObject = $InputObject | Where-Object { $_.DatabaseMaxDop -ne "N/A" }
                        } else {
                            $InputObject = $InputObject | Where-Object { $_.DatabaseMaxDop -eq "N/A" }
                            $dbscopedconfiguration = $false
                        }
                    }
                }
            } else {
                if ((Test-Bound -Parameter database) -or (Test-Bound -Parameter AllDatabases)) {
                    Write-Message -Level Warning -Message "Server '$servername' (v$($server.versionMajor)) does not support Max DOP configuration at the database level. Remember that this option is only available from SQL Server 2016 (v13). Run the command again without using database related parameters. Skipping."
                    Continue
                }
            }

            foreach ($row in $InputObject | Where-Object { $_.SqlInstance -eq $servername }) {
                if ($UseRecommended -and ($row.RecommendedMaxDop -eq $row.CurrentInstanceMaxDop) -and !($dbscopedconfiguration)) {
                    Write-Message -Level Verbose -Message "$servername is configured properly. No change required."
                    Continue
                }

                if ($UseRecommended -and ($row.RecommendedMaxDop -eq $row.DatabaseMaxDop) -and $dbscopedconfiguration) {
                    Write-Message -Level Verbose -Message "Database $($row.Database) on $servername is configured properly. No change required."
                    Continue
                }

                $row.PreviousInstanceMaxDopValue = $row.CurrentInstanceMaxDop

                try {
                    if ($UseRecommended) {
                        if ($dbscopedconfiguration) {
                            $row.PreviousDatabaseMaxDopValue = $row.DatabaseMaxDop

                            if ($resetDatabases) {
                                Write-Message -Level Verbose -Message "Changing $($row.Database) database max DOP to $($row.DatabaseMaxDop)."
                                $server.Databases["$($row.Database)"].MaxDop = $row.DatabaseMaxDop
                            } else {
                                Write-Message -Level Verbose -Message "Changing $($row.Database) database max DOP from $($row.DatabaseMaxDop) to $($row.RecommendedMaxDop)."
                                $server.Databases["$($row.Database)"].MaxDop = $row.RecommendedMaxDop
                                $row.DatabaseMaxDop = $row.RecommendedMaxDop
                            }

                        } else {
                            Write-Message -Level Verbose -Message "Changing $server SQL Server max DOP from $($row.CurrentInstanceMaxDop) to $($row.RecommendedMaxDop)."
                            $server.Configuration.MaxDegreeOfParallelism.ConfigValue = $row.RecommendedMaxDop
                            $row.CurrentInstanceMaxDop = $row.RecommendedMaxDop
                        }
                    } else {
                        if ($dbscopedconfiguration) {
                            $row.PreviousDatabaseMaxDopValue = $row.DatabaseMaxDop

                            Write-Message -Level Verbose -Message "Changing $($row.Database) database max DOP from $($row.DatabaseMaxDop) to $MaxDop."
                            $server.Databases["$($row.Database)"].MaxDop = $MaxDop
                            $row.DatabaseMaxDop = $MaxDop
                        } else {
                            Write-Message -Level Verbose -Message "Changing $servername SQL Server max DOP from $($row.CurrentInstanceMaxDop) to $MaxDop."
                            $server.Configuration.MaxDegreeOfParallelism.ConfigValue = $MaxDop
                            $row.CurrentInstanceMaxDop = $MaxDop
                        }
                    }

                    if ($dbscopedconfiguration) {
                        if ($Pscmdlet.ShouldProcess($row.Database, "Setting max dop on database")) {
                            $server.Databases["$($row.Database)"].Alter()
                        }
                    } else {
                        if ($Pscmdlet.ShouldProcess($servername, "Setting max dop on instance")) {
                            $server.Configuration.Alter()
                        }
                    }

                    $results = [pscustomobject]@{
                        ComputerName                = $server.ComputerName
                        InstanceName                = $server.ServiceName
                        SqlInstance                 = $server.DomainInstanceName
                        InstanceVersion             = $row.InstanceVersion
                        Database                    = $row.Database
                        DatabaseMaxDop              = $row.DatabaseMaxDop
                        CurrentInstanceMaxDop       = $row.CurrentInstanceMaxDop
                        RecommendedMaxDop           = $row.RecommendedMaxDop
                        PreviousDatabaseMaxDopValue = $row.PreviousDatabaseMaxDopValue
                        PreviousInstanceMaxDopValue = $row.PreviousInstanceMaxDopValue
                    }

                    if ($dbscopedconfiguration) {
                        Select-DefaultView -InputObject $results -Property InstanceName, Database, PreviousDatabaseMaxDopValue, @{
                            name = "CurrentDatabaseMaxDopValue"; expression = {
                                $_.DatabaseMaxDop
                            }
                        }
                    } else {
                        Select-DefaultView -InputObject $results -Property InstanceName, PreviousInstanceMaxDopValue, CurrentInstanceMaxDop
                    }
                } catch {
                    Stop-Function -Message "Could not modify Max Degree of Parallelism for $server." -ErrorRecord $_ -Target $server -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Set-DbaMaxMemory.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Set-DbaMaxMemory {
    <#
    .SYNOPSIS
        Sets SQL Server 'Max Server Memory' configuration setting to a new value then displays information this setting.

    .DESCRIPTION
        Sets SQL Server max memory then displays information relating to SQL Server Max Memory configuration settings.

        Inspired by Jonathan Kehayias's post about SQL Server Max memory (http://bit.ly/sqlmemcalc), this uses a formula to
        determine the default optimum RAM to use, then sets the SQL max value to that number.

        Jonathan notes that the formula used provides a *general recommendation* that doesn't account for everything that may
        be going on in your specific environment.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Max
        Specifies the max megabytes (MB)

    .PARAMETER InputObject
        A InputObject returned by Test-DbaMaxMemory

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER WhatIf
        Shows what would happen if the cmdlet runs. The cmdlet is not run.

    .PARAMETER Confirm
        Prompts you for confirmation before running the cmdlet.

    .NOTES
        Tags: MaxMemory, Memory
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaMaxMemory

    .EXAMPLE
        PS C:\> Set-DbaMaxMemory sqlserver1

        Set max memory to the recommended on just one server named "sqlserver1"

    .EXAMPLE
        PS C:\> Set-DbaMaxMemory -SqlInstance sqlserver1 -Max 2048

        Explicitly set max memory to 2048 on just one server, "sqlserver1"

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sqlserver | Test-DbaMaxMemory | Where-Object { $_.MaxValue -gt $_.Total } | Set-DbaMaxMemory

        Find all servers in SQL Server Central Management Server that have Max SQL memory set to higher than the total memory
        of the server (think 2147483647), then pipe those to Set-DbaMaxMemory and use the default recommendation.

       #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [int]$Max,
        [Parameter(ValueFromPipeline)]
        [PSCustomObject[]]$InputObject,
        [switch]$EnableException
    )
    begin {
        if ($Max -eq 0) {
            $UseRecommended = $true
        }
    }
    process {
        if ($SqlInstance) {
            $InputObject += Test-DbaMaxMemory -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        }

        foreach ($result in $InputObject) {
            $server = $result.Server
            Add-Member -Force -InputObject $result -NotePropertyName PreviousMaxValue -NotePropertyValue $result.MaxValue

            try {
                if ($UseRecommended) {
                    Write-Message -Level Verbose -Message "Change $server SQL Server Max Memory from $($result.MaxValue) to $($result.RecommendedValue) "

                    if ($result.RecommendedValue -eq 0 -or $null -eq $result.RecommendedValue) {
                        $maxMem = $result.RecommendedValue
                        Write-Message -Level VeryVerbose -Message "Max memory recommended: $maxMem"
                        $server.Configuration.MaxServerMemory.ConfigValue = $maxMem
                    } else {
                        $server.Configuration.MaxServerMemory.ConfigValue = $result.RecommendedValue
                    }
                } else {
                    Write-Message -Level Verbose -Message "Change $server SQL Server Max Memory from $($result.MaxValue) to $Max "
                    $server.Configuration.MaxServerMemory.ConfigValue = $Max
                }

                if ($PSCmdlet.ShouldProcess($server.Name, "Change Max Memory from $($result.PreviousMaxValue) to $($server.Configuration.MaxServerMemory.ConfigValue)")) {
                    try {
                        $server.Configuration.Alter()
                        $result.MaxValue = $server.Configuration.MaxServerMemory.ConfigValue
                    } catch {
                        Stop-Function -Message "Failed to apply configuration change for $server" -ErrorRecord $_ -Target $server -Continue
                    }
                }
            } catch {
                Stop-Function -Message "Could not modify Max Server Memory for $server" -ErrorRecord $_ -Target $server -Continue
            }

            Add-Member -InputObject $result -Force -MemberType NoteProperty -Name MaxValue -Value $result.MaxValue
            Select-DefaultView -InputObject $result -Property ComputerName, InstanceName, SqlInstance, Total, MaxValue, PreviousMaxValue
        }
    }
}
tools\dbatools\functions\Set-DbaNetworkCertificate.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Set-DbaNetworkCertificate {
    <#
    .SYNOPSIS
        Sets the network certificate for SQL Server instance

    .DESCRIPTION
        Sets the network certificate for SQL Server instance. This setting is found in Configuration Manager.

        This command also grants read permissions for the service account on the certificate's private key.

        References:
        http://sqlmag.com/sql-server/7-steps-ssl-encryption
        https://azurebi.jppp.org/2016/01/23/using-lets-encrypt-certificates-for-secure-sql-server-connections/
        https://blogs.msdn.microsoft.com/sqlserverfaq/2016/09/26/creating-and-registering-ssl-certificates/

    .PARAMETER SqlInstance
       The target SQL Server instance or instances. Defaults to localhost.

    .PARAMETER Credential
        Allows you to login to the computer (not sql instance) using alternative credentials.

    .PARAMETER Certificate
        The target certificate object

    .PARAMETER Thumbprint
        The thumbprint of the target certificate

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .NOTES
        Tags: Certificate
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaNetworkCertificate

    .EXAMPLE
        PS C:\> New-DbaComputerCertificate | Set-DbaNetworkCertificate -SqlInstance localhost\SQL2008R2SP2

        Creates and imports a new certificate signed by an Active Directory CA on localhost then sets the network certificate for the SQL2008R2SP2 to that newly created certificate.

    .EXAMPLE
        PS C:\> Set-DbaNetworkCertificate -SqlInstance sql1\SQL2008R2SP2 -Thumbprint 1223FB1ACBCA44D3EE9640F81B6BA14A92F3D6E2

        Sets the network certificate for the SQL2008R2SP2 instance to the certificate with the thumbprint of 1223FB1ACBCA44D3EE9640F81B6BA14A92F3D6E2 in LocalMachine\My on sql1

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low", DefaultParameterSetName = 'Default')]
    param (
        [Parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "ComputerName")]
        [DbaInstanceParameter[]]$SqlInstance = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [parameter(Mandatory, ParameterSetName = "Certificate", ValueFromPipeline)]
        [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
        [parameter(Mandatory, ParameterSetName = "Thumbprint")]
        [string]$Thumbprint,
        [switch]$EnableException
    )
    
    process {
        # Registry access
        
        if (Test-FunctionInterrupt) { return }

        if (-not $Certificate -and -not $Thumbprint) {
            Stop-Function -Message "You must specify a certificate or thumbprint"
            return
        }

        if (-not $Thumbprint) {
            Write-Message -Level SomewhatVerbose -Message "Getting thumbprint"
            $Thumbprint = $Certificate.Thumbprint
        }

        foreach ($instance in $sqlinstance) {
            Write-Message -Level VeryVerbose -Message "Processing $instance" -Target $instance
            $null = Test-ElevationRequirement -ComputerName $instance -Continue

            Write-Message -Level Verbose -Message "Resolving hostname"
            $resolved = $null
            $resolved = Resolve-DbaNetworkName -ComputerName $instance -Turbo

            if ($null -eq $resolved) {
                Stop-Function -Message "Can't resolve $instance" -Target $instance -Continue -Category InvalidArgument
            }

            $computername = $instance.ComputerName
            $instancename = $instance.instancename

            try {
                $sqlwmi = Invoke-ManagedComputerCommand -ComputerName $resolved.FQDN -ScriptBlock { $wmi.Services } -Credential $Credential -ErrorAction Stop | Where-Object DisplayName -eq "SQL Server ($instancename)"
            } catch {
                Stop-Function -Message "Failed to access $instance" -Target $instance -Continue -ErrorRecord $_
            }

            if (-not $sqlwmi) {
                Stop-Function -Message "Cannot find $instancename on $computerName" -Continue -Category ObjectNotFound -Target $instance
            }

            $regroot = ($sqlwmi.AdvancedProperties | Where-Object Name -eq REGROOT).Value
            $vsname = ($sqlwmi.AdvancedProperties | Where-Object Name -eq VSNAME).Value
            $instancename = $sqlwmi.DisplayName.Replace('SQL Server (', '').Replace(')', '') # Don't clown, I don't know regex :(
            $serviceaccount = $sqlwmi.ServiceAccount

            if ([System.String]::IsNullOrEmpty($regroot)) {
                $regroot = $sqlwmi.AdvancedProperties | Where-Object { $_ -match 'REGROOT' }
                $vsname = $sqlwmi.AdvancedProperties | Where-Object { $_ -match 'VSNAME' }

                if (![System.String]::IsNullOrEmpty($regroot)) {
                    $regroot = ($regroot -Split 'Value\=')[1]
                    $vsname = ($vsname -Split 'Value\=')[1]
                } else {
                    Stop-Function -Message "Can't find instance $vsname on $instance" -Continue -Category ObjectNotFound -Target $instance
                }
            }

            if ([System.String]::IsNullOrEmpty($vsname)) { $vsname = $instance }

            Write-Message -Level Output -Message "Regroot: $regroot" -Target $instance
            Write-Message -Level Output -Message "ServiceAcct: $serviceaccount" -Target $instance
            Write-Message -Level Output -Message "InstanceName: $instancename" -Target $instance
            Write-Message -Level Output -Message "VSNAME: $vsname" -Target $instance

            $scriptblock = {
                $regroot = $args[0]
                $serviceaccount = $args[1]
                $instancename = $args[2]
                $vsname = $args[3]
                $Thumbprint = $args[4]

                $regpath = "Registry::HKEY_LOCAL_MACHINE\$regroot\MSSQLServer\SuperSocketNetLib"

                $oldthumbprint = (Get-ItemProperty -Path $regpath -Name Certificate).Certificate

                $cert = Get-ChildItem Cert:\LocalMachine -Recurse -ErrorAction Stop | Where-Object { $_.Thumbprint -eq $Thumbprint }

                if ($null -eq $cert) {
                    <# DO NOT use Write-Message as this is inside of a script block #>
                    Write-Warning "Certificate does not exist on $env:COMPUTERNAME"
                    return
                }

                $permission = $serviceaccount, "Read", "Allow"
                $accessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permission

                $keyPath = $env:ProgramData + "\Microsoft\Crypto\RSA\MachineKeys\"
                $keyName = $cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName
                $keyFullPath = $keyPath + $keyName

                $acl = Get-Acl -Path $keyFullPath
                $null = $acl.AddAccessRule($accessRule)
                Set-Acl -Path $keyFullPath -AclObject $acl

                if ($acl) {
                    Set-ItemProperty -Path $regpath -Name Certificate -Value $Thumbprint.ToString().ToLower() # to make it compat with SQL config
                } else {
                    <# DO NOT use Write-Message as this is inside of a script block #>
                    Write-Warning "Read-only permissions could not be granted to certificate"
                    return
                }

                if (![System.String]::IsNullOrEmpty($oldthumbprint)) {
                    $notes = "Granted $serviceaccount read access to certificate private key. Replaced thumbprint: $oldthumbprint."
                } else {
                    $notes = "Granted $serviceaccount read access to certificate private key"
                }

                $newthumbprint = (Get-ItemProperty -Path $regpath -Name Certificate).Certificate

                [pscustomobject]@{
                    ComputerName          = $env:COMPUTERNAME
                    InstanceName          = $instancename
                    SqlInstance           = $vsname
                    ServiceAccount        = $serviceaccount
                    CertificateThumbprint = $newthumbprint
                    Notes                 = $notes
                }
            }

            if ($PScmdlet.ShouldProcess("local", "Connecting to $instanceName to import new cert")) {
                try {
                    Invoke-Command2 -Raw -ComputerName $resolved.fqdn -Credential $Credential -ArgumentList $regroot, $serviceaccount, $instancename, $vsname, $Thumbprint -ScriptBlock $scriptblock -ErrorAction Stop
                } catch {
                    Stop-Function -Message "Failed to connect to $($resolved.fqdn) using PowerShell remoting!" -ErrorRecord $_ -Target $instance -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Set-DbaPowerPlan.ps1
function Set-DbaPowerPlan {
    <#
    .SYNOPSIS
        Sets the SQL Server OS's Power Plan.

    .DESCRIPTION
        Sets the SQL Server OS's Power Plan. Defaults to High Performance which is best practice.

        If your organization uses a custom power plan that is considered best practice, specify -CustomPowerPlan.

        References:
        https://support.microsoft.com/en-us/kb/2207548
        http://www.sqlskills.com/blogs/glenn/windows-power-plan-effects-on-newer-intel-processors/

    .PARAMETER ComputerName
        The server(s) to set the Power Plan on.

    .PARAMETER Credential
        Specifies a PSCredential object to use in authenticating to the server(s), instead of the current user account.

    .PARAMETER PowerPlan
        Specifies the Power Plan that you wish to use. Valid options for this match the Windows default Power Plans of "Power Saver", "Balanced", and "High Performance".

    .PARAMETER CustomPowerPlan
        Specifies the name of a custom Power Plan to use.

    .PARAMETER InputObject
        Enables piping from Get-DbaPowerPlan

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .NOTES
        Tags: PowerPlan, OS, Configure
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: WMI access to servers

    .LINK
        https://dbatools.io/Set-DbaPowerPlan

    .EXAMPLE
        PS C:\> Set-DbaPowerPlan -ComputerName sql2017

        Sets the Power Plan to High Performance. Skips it if its already set.

    .EXAMPLE
        PS C:\> 'Server1', 'Server2' | Set-DbaPowerPlan -PowerPlan Balanced

        Sets the Power Plan to Balanced for Server1 and Server2. Skips it if its already set.

    .EXAMPLE
        PS C:\> $cred = Get-Credential 'Domain\User'
        PS C:\> Set-DbaPowerPlan -ComputerName sql2017 -Credential $cred

        Connects using alternative Windows credential and sets the Power Plan to High Performance. Skips it if its already set.

    .EXAMPLE
        PS C:\> Set-DbaPowerPlan -ComputerName sqlcluster -CustomPowerPlan 'Maximum Performance'

        Sets the Power Plan to the custom power plan called "Maximum Performance". Skips it if its already set.

       #>
    [CmdletBinding(SupportsShouldProcess)]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseOutputTypeCorrectly", "", Justification = "PSSA Rule Ignored by BOH")]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstance[]]$ComputerName,
        [PSCredential]$Credential,
        [string]$PowerPlan = 'High Performance',
        [string]$CustomPowerPlan,
        [parameter(ValueFromPipeline)]
        [pscustomobject]$InputObject,
        [switch]$EnableException
    )

    begin {
        if ($CustomPowerPlan) {
            $powerPlanRequested = $CustomPowerPlan
        } else {
            $powerPlanRequested = $PowerPlan
        }
        function Set-DbaPowerPlanInternal {
            [CmdletBinding(SupportsShouldProcess)]
            param (
                [string]$ComputerName,
                [PSCredential]$Credential
            )

            if (Test-Bound -ParameterName Credential) {
                $IncludeCred = $true
            }
            try {
                Write-Message -Level Verbose -Message "Testing connection to $computer"
                $computerResolved = Resolve-DbaNetworkName -ComputerName $computer -Credential $Credential

                $computerResolved = $computerResolved.FullComputerName
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $computer
                return
            }

            $splatDbaCmObject = @{
                ComputerName    = $computerResolved
                EnableException = $true
            }
            if ($IncludeCred) {
                $splatDbaCmObject["Credential"] = $Credential
            }

            try {
                Write-Message -Level Verbose -Message "Getting Power Plan information from $computer."
                $currentplan = Get-DbaCmObject @splatDbaCmObject -ClassName Win32_PowerPlan -Namespace "root\cimv2\power" | Where-Object IsActive -eq 'True'
                $currentplan = $currentplan.ElementName
            } catch {
                if ($_.Exception -match "namespace") {
                    Stop-Function -Message "Can't get Power Plan Info for $computer. Unsupported operating system." -Continue -ErrorRecord $_ -Target $computer
                } else {
                    Stop-Function -Message "Can't get Power Plan Info for $computer. Check logs for more details." -Continue -ErrorRecord $_ -Target $computer
                }
            }

            if ($null -eq $currentplan) {
                # the try/catch above isn't working, so make it silent and handle it here.
                Stop-Function -Message "Cannot get Power Plan for $computer." -Category ConnectionError -ErrorRecord $_ -Target $computer
                return
            }

            $planinfo = [PSCustomObject]@{
                ComputerName      = $computer
                PreviousPowerPlan = $currentplan
                ActivePowerPlan   = $powerPlanRequested
            }
            if ($Pscmdlet.ShouldProcess($powerPlanRequested, "Setting Powerplan on $computer")) {
                if ($powerPlanRequested -ne $currentplan) {
                    if ($Pscmdlet.ShouldProcess($computer, "Changing Power Plan from $CurrentPlan to $powerPlanRequested")) {
                        Write-Message -Level Verbose -Message "Creating CIMSession on $computer over WSMan"
                        if ($IncludeCred) {
                            $cimSession = New-CimSession -ComputerName $computer -ErrorAction SilentlyContinue -Credential $Credential
                        } else {
                            $cimSession = New-CimSession -ComputerName $computer -ErrorAction SilentlyContinue
                        }
                        if (-not $cimSession) {
                            Write-Message -Level Verbose -Message "Creating CIMSession on $computer over WSMan failed. Creating CIMSession on $computer over DCom"
                            $sessionOption = New-CimSessionOption -Protocol DCom
                            if ($IncludeCred) {
                                $cimSession = New-CimSession -ComputerName $computer -SessionOption $sessionoption -ErrorAction SilentlyContinue -Credential $Credential
                            } else {
                                $cimSession = New-CimSession -ComputerName $computer -SessionOption $sessionoption -ErrorAction SilentlyContinue
                            }
                        }
                        if ($cimSession) {
                            Write-Message -Level Verbose -Message "Setting Power Plan to $powerPlanRequested."

                            $cimInstance = Get-CimInstance -Namespace root\cimv2\power -ClassName win32_PowerPlan -Filter "ElementName = '$powerPlanRequested'" -CimSession $CIMSession
                            if ($cimInstance) {
                                $cimResult = Invoke-CimMethod -InputObject $cimInstance[0] -MethodName Activate -CimSession $cimSession
                                if (!$cimResult) {
                                    Stop-Function -Message "Couldn't set the requested Power Plan '$powerPlanRequested' on $computer." -Category ConnectionError -Target $computer
                                    return
                                }
                            } else {
                                Stop-Function -Message "Couldn't find the requested Power Plan '$powerPlanRequested' on $computer." -Category ConnectionError -Target $computer
                                return
                            }
                        } else {
                            Stop-Function -Message "Couldn't set Power Plan on $computer." -Category ConnectionError -ErrorRecord $_ -Target $computer
                            return
                        }
                    }
                } else {
                    if ($Pscmdlet.ShouldProcess($computer, "Stating power plan is already set to $powerPlanRequested, won't change.")) {
                        Write-Message -Level Verbose -Message "PowerPlan on $computer is already set to $powerPlanRequested. Skipping."
                    }
                }

                return $planInfo
            }
        }
    }

    process {
        # uses cim commands
        
        
        if (Test-Bound -ParameterName ComputerName) {
            $InputObject += Get-DbaPowerPlan -ComputerName $ComputerName -Credential $Credential
        }

        foreach ($pplan in $InputObject) {
            $computer = $pplan.ComputerName
            $Credential = $pplan.Credential
            Write-Message -Level Verbose -Message "Calling Set-DbaPowerPlanInternal for $computer"
            if (Test-Bound -ParameterName Credential) {
                $data = Set-DbaPowerPlanInternal -ComputerName $Computer -Credential $Credential
            } else {
                $data = Set-DbaPowerPlanInternal -ComputerName $Computer
            }

            if ($data.Count -gt 1) {
                $data.GetEnumerator() | ForEach-Object {
                    $_
                }
            } else {
                $data
            }
        }
    }
}
tools\dbatools\functions\Set-DbaPrivilege.ps1
function Set-DbaPrivilege {
    <#
    .SYNOPSIS
        Adds the SQL Service account to local privileges on one or more computers.

    .DESCRIPTION
        Adds the SQL Service account to local privileges 'Lock Pages in Memory', 'Instant File Initialization', 'Logon as Batch' on one or more computers.

        Requires Local Admin rights on destination computer(s).

    .PARAMETER ComputerName
        The target SQL Server instance or instances.

    .PARAMETER Credential
        Credential object used to connect to the computer as a different user.

    .PARAMETER Type
        Use this to choose the privilege(s) to which you want to add the SQL Service account.
        Accepts 'IFI', 'LPIM' and/or 'BatchLogon' for local privileges 'Instant File Initialization', 'Lock Pages in Memory' and 'Logon as Batch'.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Privilege
        Author: Klaas Vandenberghe ( @PowerDBAKlaas )

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaPrivilege

    .EXAMPLE
        PS C:\> Set-DbaPrivilege -ComputerName sqlserver2014a -Type LPIM,IFI

        Adds the SQL Service account(s) on computer sqlserver2014a to the local privileges 'SeManageVolumePrivilege' and 'SeLockMemoryPrivilege'.

    .EXAMPLE
        PS C:\> 'sql1','sql2','sql3' | Set-DbaPrivilege -Type IFI

        Adds the SQL Service account(s) on computers sql1, sql2 and sql3 to the local privilege 'SeManageVolumePrivilege'.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(ValueFromPipeline)]
        [Alias("cn", "host", "Server")]
        [dbainstanceparameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [Parameter(Mandatory)]
        [ValidateSet('IFI', 'LPIM', 'BatchLogon')]
        [string[]]$Type,
        [switch][Alias('Silent')]
        $EnableException
    )

    begin {
        $ResolveAccountToSID = @"
function Convert-UserNameToSID ([string] `$Acc ) {
`$objUser = New-Object System.Security.Principal.NTAccount(`"`$Acc`")
`$strSID = `$objUser.Translate([System.Security.Principal.SecurityIdentifier])
`$strSID.Value
}
"@
        $ComputerName = $ComputerName.ComputerName | Select-Object -Unique
    }
    process {
        foreach ($computer in $ComputerName) {
            if ($Pscmdlet.ShouldProcess($computer, "Setting Privilege for SQL Service Account")) {
                try {
                    $null = Test-ElevationRequirement -ComputerName $Computer -Continue
                    if (Test-PSRemoting -ComputerName $Computer) {
                        Write-Message -Level Verbose -Message "Exporting Privileges on $Computer"
                        Invoke-Command2 -Raw -ComputerName $computer -Credential $Credential -ScriptBlock {
                            $temp = ([System.IO.Path]::GetTempPath()).TrimEnd(""); secedit /export /cfg $temp\secpolByDbatools.cfg > $NULL;
                        }
                        Write-Message -Level Verbose -Message "Getting SQL Service Accounts on $computer"
                        $SQLServiceAccounts = (Get-DbaService -ComputerName $computer -Type Engine).StartName
                        if ($SQLServiceAccounts.count -ge 1) {
                            Write-Message -Level Verbose -Message "Setting Privileges on $Computer"
                            Invoke-Command2 -Raw -ComputerName $computer -Credential $Credential -Verbose -ArgumentList $ResolveAccountToSID, $SQLServiceAccounts, $BatchLogon, $IFI, $LPIM -ScriptBlock {
                                [CmdletBinding()]
                                param ($ResolveAccountToSID,
                                    $SQLServiceAccounts,
                                    $BatchLogon,
                                    $IFI,
                                    $LPIM)
                                . ([ScriptBlock]::Create($ResolveAccountToSID))
                                $temp = ([System.IO.Path]::GetTempPath()).TrimEnd("");
                                $tempfile = "$temp\secpolByDbatools.cfg"
                                if ('BatchLogon' -in $Type) {
                                    $BLline = Get-Content $tempfile | Where-Object { $_ -match "SeBatchLogonRight" }
                                    ForEach ($acc in $SQLServiceAccounts) {
                                        $SID = Convert-UserNameToSID -Acc $acc;
                                        if ($BLline -notmatch $SID) {
                                            (Get-Content $tempfile) -replace "SeBatchLogonRight = ", "SeBatchLogonRight = *$SID," |
                                                Set-Content $tempfile
                                            <# DO NOT use Write-Message as this is inside of a script block #>
                                            Write-Verbose "Added $acc to Batch Logon Privileges on $env:ComputerName"
                                        } else {
                                            <# DO NOT use Write-Message as this is inside of a script block #>
                                            Write-Warning "$acc already has Batch Logon Privilege on $env:ComputerName"
                                        }
                                    }
                                }
                                if ('IFI' -in $Type) {
                                    $IFIline = Get-Content $tempfile | Where-Object { $_ -match "SeManageVolumePrivilege" }
                                    ForEach ($acc in $SQLServiceAccounts) {
                                        $SID = Convert-UserNameToSID -Acc $acc;
                                        if ($IFIline -notmatch $SID) {
                                            (Get-Content $tempfile) -replace "SeManageVolumePrivilege = ", "SeManageVolumePrivilege = *$SID," |
                                                Set-Content $tempfile
                                            <# DO NOT use Write-Message as this is inside of a script block #>
                                            Write-Verbose "Added $acc to Instant File Initialization Privileges on $env:ComputerName"
                                        } else {
                                            <# DO NOT use Write-Message as this is inside of a script block #>
                                            Write-Warning "$acc already has Instant File Initialization Privilege on $env:ComputerName"
                                        }
                                    }
                                }
                                if ('LPIM' -in $Type) {
                                    $LPIMline = Get-Content $tempfile | Where-Object { $_ -match "SeLockMemoryPrivilege" }
                                    ForEach ($acc in $SQLServiceAccounts) {
                                        $SID = Convert-UserNameToSID -Acc $acc;
                                        if ($LPIMline -notmatch $SID) {
                                            (Get-Content $tempfile) -replace "SeLockMemoryPrivilege = ", "SeLockMemoryPrivilege = *$SID," |
                                                Set-Content $tempfile
                                            <# DO NOT use Write-Message as this is inside of a script block #>
                                            Write-Verbose "Added $acc to Lock Pages in Memory Privileges on $env:ComputerName"
                                        } else {
                                            <# DO NOT use Write-Message as this is inside of a script block #>
                                            Write-Warning "$acc already has Lock Pages in Memory Privilege on $env:ComputerName"
                                        }
                                    }
                                }
                                $null = secedit /configure /cfg $tempfile /db secedit.sdb /areas USER_RIGHTS /overwrite /quiet
                            } -ErrorAction SilentlyContinue
                            Write-Message -Level Verbose -Message "Removing secpol file on $computer"
                            Invoke-Command2 -Raw -ComputerName $computer -Credential $Credential -ScriptBlock { $temp = ([System.IO.Path]::GetTempPath()).TrimEnd(""); Remove-Item $temp\secpolByDbatools.cfg -Force > $NULL }
                        } else {
                            Write-Message -Level Warning -Message "No SQL Service Accounts found on $Computer"
                        }
                    } else {
                        Write-Message -Level Warning -Message "Failed to connect to $Computer"
                    }
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target $computer -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Set-DbaSpConfigure.ps1
function Set-DbaSpConfigure {
    <#
    .SYNOPSIS
        Changes the server level system configuration (sys.configuration/sp_configure) value for a given configuration

    .DESCRIPTION
        This function changes the configured value for sp_configure settings. If the setting is dynamic this setting will be used, otherwise the user will be warned that a restart of SQL is required.
        This is designed to be safe and will not allow for configurations to be set outside of the defined configuration min and max values.
        While it is possible to set below the min, or above the max this can cause serious problems with SQL Server (including startup failures), and so is not permitted.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a
        collection and receive pipeline input

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Name
        The name of the configuration to be set -- Configs is auto-populated for tabbing convenience.

    .PARAMETER Value
        The new value for the configuration

    .PARAMETER InputObject
        Piped objects from Get-DbaSpConfigure

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .NOTES
        Tags: SpConfigure
        Author: Nic Cain, https://sirsql.net/

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaSpConfigure

    .EXAMPLE
        PS C:\> Set-DbaSpConfigure -SqlInstance localhost -Name ScanForStartupProcedures -Value 1

        Adjusts the Scan for startup stored procedures configuration value to 1 and notifies the user that this requires a SQL restart to take effect

    .EXAMPLE
        PS C:\> Get-DbaSpConfigure -SqlInstance sql2017, sql2014 -Name XPCmdShellEnabled, IsSqlClrEnabled | Set-DbaSpConfigure -Value $false

        Sets the values for XPCmdShellEnabled and IsSqlClrEnabled on sql2017 and sql2014 to False

    .EXAMPLE
        PS C:\> Set-DbaSpConfigure -SqlInstance localhost -Name XPCmdShellEnabled -Value 1

        Adjusts the xp_cmdshell configuration value to 1.

    .EXAMPLE
        PS C:\> Set-DbaSpConfigure -SqlInstance localhost -Name XPCmdShellEnabled -Value 1 -WhatIf

        Returns information on the action that would be performed. No actual change will be made.

       #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [System.Management.Automation.PSCredential]$SqlCredential,
        [Alias("NewValue", "NewConfig")]
        [int]$Value,
        [Alias("Config", "ConfigName")]
        [string[]]$Name,
        [parameter(ValueFromPipeline)]
        [object[]]$InputObject,
        [switch][Alias('Silent')]
        $EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaSpConfigure -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Name $Name
        }

        foreach ($configobject in $InputObject) {
            $server = $InputObject.Parent
            $currentRunValue = $configobject.RunningValue
            $currentConfigValue = $configobject.ConfiguredValue
            $minValue = $configobject.MinValue
            $maxValue = $configobject.MaxValue
            $isDynamic = $configobject.IsDynamic
            $configuration = $configobject.Name

            #Let us not waste energy setting the value to itself
            if ($currentConfigValue -eq $value) {
                Stop-Function -Message "Value to set is the same as the existing value. No work being performed." -Continue -Target $server -Category InvalidData
            }

            #Going outside the min/max boundary can be done, but it can break SQL, so I don't think allowing that is wise at this juncture
            if ($value -lt $minValue -or $value -gt $maxValue) {
                Stop-Function -Message "Value out of range for $configuration ($minValue <-> $maxValue)" -Continue -Category InvalidArgument
            }

            If ($Pscmdlet.ShouldProcess($SqlInstance, "Adjusting server configuration $configuration from $currentConfigValue to $value.")) {
                try {
                    $server.Configuration.$configuration.ConfigValue = $value
                    $server.Configuration.Alter()

                    [pscustomobject]@{
                        ComputerName  = $server.ComputerName
                        InstanceName  = $server.ServiceName
                        SqlInstance   = $server.DomainInstanceName
                        ConfigName    = $configuration
                        PreviousValue = $currentConfigValue
                        NewValue      = $value
                    }

                    #If it's a dynamic setting we're all clear, otherwise let the user know that SQL needs to be restarted for the change to take
                    if ($isDynamic -eq $false) {
                        Write-Message -Level Warning -Message "Configuration setting $configuration has been set, but restart of SQL Server is required for the new value `"$value`" to be used (old value: `"$currentRunValue`")" -Target $Instance
                    }
                } catch {
                    Stop-Function -Message "Unable to change config setting" -Target $Instance -ErrorRecord $_ -Continue -ContinueLabel main
                }
            }
        }
    }
}
tools\dbatools\functions\Set-DbaSpn.ps1
#ValidationTags#FlowControl,Pipeline#
function Set-DbaSpn {
    <#
    .SYNOPSIS
        Sets an SPN for a given service account in active directory (and also enables delegation to the same SPN by default)

    .DESCRIPTION
        This function will connect to Active Directory and search for an account. If the account is found, it will attempt to add an SPN. Once the SPN is added, the function will also set delegation to that service, unless -NoDelegation is specified. In order to run this function, the credential you provide must have write access to Active Directory.

        Note: This function supports -WhatIf

    .PARAMETER SPN
        The SPN you want to add

    .PARAMETER ServiceAccount
        The account you want the SPN added to

    .PARAMETER Credential
        The credential you want to use to connect to Active Directory to make the changes

    .PARAMETER NoDelegation
        Skips setting the delegation

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER Confirm
        Turns confirmations before changes on or off

    .PARAMETER WhatIf
        Shows what would happen if the command was executed

    .NOTES
        Tags: SPN
        Author: Drew Furgiuele (@pittfurg), http://www.port1433.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaSpn

    .EXAMPLE
        PS C:\> Set-DbaSpn -SPN MSSQLSvc/SQLSERVERA.domain.something -ServiceAccount domain\account
        PS C:\> Set-DbaSpn -SPN MSSQLSvc/SQLSERVERA.domain.something -ServiceAccount domain\account -EnableException

        Connects to Active Directory and adds a provided SPN to the given account.
        Connects to Active Directory and adds a provided SPN to the given account, suppressing all error messages and throw exceptions that can be caught instead

    .EXAMPLE
        PS C:\> Set-DbaSpn -SPN MSSQLSvc/SQLSERVERA.domain.something -ServiceAccount domain\account -Credential ad\sqldba

        Connects to Active Directory and adds a provided SPN to the given account. Uses alternative account to connect to AD.

    .EXAMPLE
        PS C:\> Set-DbaSpn -SPN MSSQLSvc/SQLSERVERA.domain.something -ServiceAccount domain\account -NoDelegation

        Connects to Active Directory and adds a provided SPN to the given account, without the delegation.

    .EXAMPLE
        PS C:\> Test-DbaSpn -ComputerName sql2016 | Where { $_.isSet -eq $false } | Set-DbaSpn

        Sets all missing SPNs for sql2016

    .EXAMPLE
        PS C:\> Test-DbaSpn -ComputerName sql2016 | Where { $_.isSet -eq $false } | Set-DbaSpn -WhatIf

        Displays what would happen trying to set all missing SPNs for sql2016

    #>
    [cmdletbinding(SupportsShouldProcess, DefaultParameterSetName = "Default")]
    param (
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [Alias("RequiredSPN")]
        [string]$SPN,
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [Alias("InstanceServiceAccount", "AccountName")]
        [string]$ServiceAccount,
        [Parameter(ValueFromPipelineByPropertyName)]
        [PSCredential]$Credential,
        [switch]$NoDelegation,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        #did we find the server account?
        Write-Message -Message "Looking for account $ServiceAccount..." -Level Verbose
        $searchfor = 'User'
        if ($ServiceAccount.EndsWith('$')) {
            $searchfor = 'Computer'
        }
        try {
            $Result = Get-DbaADObject -ADObject $ServiceAccount -Type $searchfor -Credential $Credential -EnableException
        } catch {
            Stop-Function -Message "AD lookup failure. This may be because the domain cannot be resolved for the SQL Server service account ($ServiceAccount). $($_.Exception.Message)" -EnableException $EnableException -InnerErrorRecord $_ -Target $ServiceAccount
        }
        if ($Result.Count -gt 0) {
            try {
                $adentry = $Result.GetUnderlyingObject()
            } catch {
                Stop-Function -Message "The SQL Service account ($ServiceAccount) has been found, but you don't have enough permission to inspect its properties $($_.Exception.Message)" -EnableException $EnableException -InnerErrorRecord $_ -Target $ServiceAccount
            }
        } else {
            Stop-Function -Message "The SQL Service account ($ServiceAccount) has not been found" -EnableException $EnableException -Target $ServiceAccount
        }
        # Cool! Add an SPN
        $delegate = $true
        if ($PSCmdlet.ShouldProcess("$spn", "Adding SPN to service account")) {
            try {
                $null = $adentry.Properties['serviceprincipalname'].Add($spn)
                $status = "Successfully added SPN"
                $adentry.CommitChanges()
                Write-Message -Message "Added SPN $spn to $ServiceAccount" -Level Verbose
                $set = $true
            } catch {
                Write-Message -Message "Could not add SPN. $($_.Exception.Message)" -Level Warning -EnableException $EnableException.ToBool() -ErrorRecord $_ -Target $ServiceAccount
                $set = $false
                $status = "Failed to add SPN"
                $delegate = $false
            }

            [pscustomobject]@{
                Name           = $spn
                ServiceAccount = $ServiceAccount
                Property       = "servicePrincipalName"
                IsSet          = $set
                Notes          = $status
            }
        }

        #if we have the SPN set, we can add the delegation
        if ($delegate) {
            # but only if $NoDelegation is not passed
            if (!$NoDelegation) {
                if ($PSCmdlet.ShouldProcess("$spn", "Adding constrained delegation to service account for SPN")) {
                    try {
                        $null = $adentry.Properties['msDS-AllowedToDelegateTo'].Add($spn)
                        $adentry.CommitChanges()
                        Write-Message -Message "Added kerberos delegation to $spn for $ServiceAccount" -Level Verbose
                        $set = $true
                        $status = "Successfully added constrained delegation"
                    } catch {
                        Write-Message -Message "Could not add delegation. $($_.Exception.Message)" -Level Warning -EnableException $EnableException.ToBool() -ErrorRecord $_ -Target $ServiceAccount
                        $set = $false
                        $status = "Failed to add constrained delegation"
                    }

                    [pscustomobject]@{
                        Name           = $spn
                        ServiceAccount = $ServiceAccount
                        Property       = "msDS-AllowedToDelegateTo"
                        IsSet          = $set
                        Notes          = $status
                    }
                }
            } else {
                Write-Message -Message "Skipping delegation as instructed" -Level Verbose
            }
        }
    }
}
tools\dbatools\functions\Set-DbaStartupParameter.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Set-DbaStartupParameter {
    <#
    .SYNOPSIS
        Sets the Startup Parameters for a SQL Server instance

    .DESCRIPTION
        Modifies the startup parameters for a specified SQL Server Instance

        For full details of what each parameter does, please refer to this MSDN article - https://msdn.microsoft.com/en-us/library/ms190737(v=sql.105).aspx

    .PARAMETER SqlInstance
        The SQL Server instance to be modified

        If the Sql Instance is offline path parameters will be ignored as we cannot test the instance's access to the path. If you want to force this to work then please use the Force switch

    .PARAMETER SqlCredential
        Windows or Sql Login Credential with permission to log into the SQL instance

    .PARAMETER Credential
        Windows Credential with permission to log on to the server running the SQL instance

    .PARAMETER MasterData
        Path to the data file for the Master database

        Will be ignored if SqlInstance is offline or the Offline switch is set. To override this behaviour use the Force switch. This is to ensure you understand the risk as we cannot validate the path if the instance is offline

    .PARAMETER MasterLog
        Path to the log file for the Master database

        Will be ignored if SqlInstance is offline or the Offline switch is set. To override this behaviour use the Force switch. This is to ensure you understand the risk as we cannot validate the path if the instance is offline

    .PARAMETER ErrorLog
        Path to the SQL Server error log file

        Will be ignored if SqlInstance is offline or the Offline switch is set. To override this behaviour use the Force switch. This is to ensure you understand the risk as we cannot validate the path if the instance is offline

    .PARAMETER TraceFlags
        A comma separated list of TraceFlags to be applied at SQL Server startup
        By default these will be appended to any existing trace flags set

    .PARAMETER CommandPromptStart
        Shortens startup time when starting SQL Server from the command prompt. Typically, the SQL Server Database Engine starts as a service by calling the Service Control Manager.
        Because the SQL Server Database Engine does not start as a service when starting from the command prompt

    .PARAMETER MinimalStart
        Starts an instance of SQL Server with minimal configuration. This is useful if the setting of a configuration value (for example, over-committing memory) has
        prevented the server from starting. Starting SQL Server in minimal configuration mode places SQL Server in single-user mode

    .PARAMETER MemoryToReserve
        Specifies an integer number of megabytes (MB) of memory that SQL Server will leave available for memory allocations within the SQL Server process,
        but outside the SQL Server memory pool. The memory outside of the memory pool is the area used by SQL Server for loading items such as extended procedure .dll files,
        the OLE DB providers referenced by distributed queries, and automation objects referenced in Transact-SQL statements. The default is 256 MB.

    .PARAMETER SingleUser
        Start Sql Server in single user mode

    .PARAMETER NoLoggingToWinEvents
        Don't use Windows Application events log

    .PARAMETER StartAsNamedInstance
        Allows you to start a named instance of SQL Server

    .PARAMETER DisableMonitoring
        Disables the following monitoring features:

        SQL Server performance monitor counters
        Keeping CPU time and cache-hit ratio statistics
        Collecting information for the DBCC SQLPERF command
        Collecting information for some dynamic management views
        Many extended-events event points

        ** Warning *\* When you use the -x startup option, the information that is available for you to diagnose performance and functional problems with SQL Server is greatly reduced.

    .PARAMETER SingleUserDetails
        The username for single user

    .PARAMETER IncreasedExtents
        Increases the number of extents that are allocated for each file in a filegroup.

    .PARAMETER TraceFlagsOverride
        Overrides the default behaviour and replaces any existing trace flags. If not trace flags specified will just remove existing ones

    .PARAMETER StartUpConfig
        Pass in a previously saved SQL Instance startup config
        using this parameter will set TraceFlagsOverride to true, so existing Trace Flags will be overridden

    .PARAMETER Offline
        Setting this switch will try perform the requested actions without connect to the SQL Server Instance, this will speed things up if you know the Instance is offline.

        When working offline, path inputs (MasterData, MasterLog and ErrorLog) will be ignored, unless Force is specified

    .PARAMETER Force
        By default we test the values passed in via MasterData, MasterLog, ErrorLog

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Startup, Parameter, Configure
        Author: Stuart Moore (@napalmgram), stuart-moore.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Set-DbaStartupParameter -SqlInstance server1\instance1 -SingleUser

        Will configure the SQL Instance server1\instance1 to startup up in Single User mode at next startup

    .EXAMPLE
        PS C:\> Set-DbaStartupParameter -SqlInstance sql2016 -IncreasedExtents

        Will configure the SQL Instance sql2016 to IncreasedExtents = True (-E)

    .EXAMPLE
        PS C:\> Set-DbaStartupParameter -SqlInstance sql2016  -IncreasedExtents:$false -WhatIf

        Shows what would happen if you attempted to configure the SQL Instance sql2016 to IncreasedExtents = False (no -E)

    .EXAMPLE
        PS C:\> Set-DbaStartupParameter -SqlInstance server1\instance1 -SingleUser -TraceFlags 8032,8048

        This will append Trace Flags 8032 and 8048 to the startup parameters

    .EXAMPLE
        PS C:\> Set-DbaStartupParameter -SqlInstance sql2016 -SingleUser:$false -TraceFlagsOverride

        This will remove all trace flags and set SingleUser to false

    .EXAMPLE
        PS C:\> Set-DbaStartupParameter -SqlInstance server1\instance1 -SingleUser -TraceFlags 8032,8048 -TraceFlagsOverride

        This will set Trace Flags 8032 and 8048 to the startup parameters, removing any existing Trace Flags

    .EXAMPLE
        PS C:\> Set-DbaStartupParameter -SqlInstance sql2016 -SingleUser:$false -TraceFlagsOverride -Offline

        This will remove all trace flags and set SingleUser to false from an offline instance

    .EXAMPLE
        PS C:\> Set-DbaStartupParameter -SqlInstance sql2016 -ErrorLog c:\Sql\ -Offline

        This will attempt to change the ErrorLog path to c:\sql\. However, with the offline switch this will not happen. To force it, use the -Force switch like so:

        Set-DbaStartupParameter -SqlInstance sql2016 -ErrorLog c:\Sql\ -Offline -Force

    .EXAMPLE
        PS C:\> $StartupConfig = Get-DbaStartupParameter -SqlInstance server1\instance1
        PS C:\> Set-DbaStartupParameter -SqlInstance server1\instance1 -SingleUser -NoLoggingToWinEvents
        PS C:\> #Restart your SQL instance with the tool of choice
        PS C:\> #Do Some work
        PS C:\> Set-DbaStartupParameter -SqlInstance server1\instance1 -StartUpConfig $StartUpConfig
        PS C:\> #Restart your SQL instance with the tool of choice and you're back to normal

        In this example we take a copy of the existing startup configuration of server1\instance1

        We then change the startup parameters ahead of some work

        After the work has been completed, we can push the original startup parameters back to server1\instance1 and resume normal operation

#>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")]
    param ([parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [PSCredential]$Credential,
        [string]$MasterData,
        [string]$MasterLog,
        [string]$ErrorLog,
        [string[]]$TraceFlags,
        [switch]$CommandPromptStart,
        [switch]$MinimalStart,
        [int]$MemoryToReserve,
        [switch]$SingleUser,
        [string]$SingleUserDetails,
        [switch]$NoLoggingToWinEvents,
        [switch]$StartAsNamedInstance,
        [switch]$DisableMonitoring,
        [switch]$IncreasedExtents,
        [switch]$TraceFlagsOverride,
        [object]$StartUpConfig,
        [switch]$Offline,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {

        if (-not $Offline) {
            try {
                $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
            } catch {
                Write-Message -Level Warning -Message "Failed to connect to $SqlInstance, will try to work with just WMI. Path options will be ignored unless Force was indicated"
                $Server = $SqlInstance
                $Offline = $true
            }
        } else {
            Write-Message -Level Verbose -Message "Offline switch set, proceeding with just WMI"
            $Server = $SqlInstance
        }

        #Get Current parameters:
        $currentstartup = Get-DbaStartupParameter -SqlInstance $SqlInstance -Credential $Credential
        $originalparamstring = $currentstartup.ParameterString

        Write-Message -Level Verbose -Message "Original startup parameter string: $originalparamstring"

        if ('startUpconfig' -in $PsBoundParameters.keys) {
            Write-Message -Level VeryVerbose -Message "StartupObject passed in"
            $newstartup = $StartUpConfig
            $TraceFlagsOverride = $true
        } else {
            Write-Message -Level VeryVerbose -Message "Parameters passed in"
            $newstartup = $currentstartup.PSObject.copy()
            foreach ($param in ($PsBoundParameters.keys | Where-Object { $_ -in ($newstartup.PSObject.Properties.name) })) {
                if ($PsBoundParameters.item($param) -ne $newstartup.$param) {
                    $newstartup.$param = $PsBoundParameters.item($param)
                }
            }
        }

        if (!($currentstartup.SingleUser)) {

            if ($newstartup.Masterdata.length -gt 0) {
                if ($Offline -and -not $Force) {
                    Write-Message -Level Warning -Message "Working offline, skipping untested MasterData path"
                    $ParameterString += "-d$($CurrentStartup.MasterData);"

                } else {
                    if ($Force) {
                        $ParameterString += "-d$($newstartup.MasterData);"
                    } elseif (Test-DbaPath -SqlInstance $server -SqlCredential $SqlCredential -Path (Split-Path $newstartup.MasterData -Parent)) {
                        $ParameterString += "-d$($newstartup.MasterData);"
                    } else {
                        Stop-Function -Message "Specified folder for Master Data file is not reachable by instance $SqlInstance"
                        return
                    }
                }
            } else {
                Stop-Function -Message "MasterData value must be provided"
                return
            }

            if ($newstartup.ErrorLog.length -gt 0) {
                if ($Offline -and -not $Force) {
                    Write-Message -Level Warning -Message "Working offline, skipping untested ErrorLog path"
                    $ParameterString += "-e$($CurrentStartup.ErrorLog);"
                } else {
                    if ($Force) {
                        $ParameterString += "-e$($newstartup.ErrorLog);"
                    } elseif (Test-DbaPath -SqlInstance $server -SqlCredential $SqlCredential -Path (Split-Path $newstartup.ErrorLog -Parent)) {
                        $ParameterString += "-e$($newstartup.ErrorLog);"
                    } else {
                        Stop-Function -Message "Specified folder for ErrorLog  file is not reachable by $SqlInstance"
                        return
                    }
                }
            } else {
                Stop-Function -Message "ErrorLog value must be provided"
                return
            }

            if ($newstartup.MasterLog.Length -gt 0) {
                if ($offline -and -not $Force) {
                    Write-Message -Level Warning -Message "Working offline, skipping untested MasterLog path"
                    $ParameterString += "-l$($CurrentStartup.MasterLog);"
                } else {
                    if ($Force) {
                        $ParameterString += "-l$($newstartup.MasterLog);"
                    } elseif (Test-DbaPath -SqlInstance $server -SqlCredential $SqlCredential -Path (Split-Path $newstartup.MasterLog -Parent)) {
                        $ParameterString += "-l$($newstartup.MasterLog);"
                    } else {
                        Stop-Function -Message "Specified folder for Master Log  file is not reachable by $SqlInstance"
                        return
                    }
                }
            } else {
                Stop-Function -Message "MasterLog value must be provided."
                return
            }
        } else {

            Write-Message -Level Verbose -Message "Sql instance is presently configured for single user, skipping path validation"
            if ($newstartup.MasterData.Length -gt 0) {
                $ParameterString += "-d$($newstartup.MasterData);"
            } else {
                Stop-Function -Message "Must have a value for MasterData"
                return
            }
            if ($newstartup.ErrorLog.Length -gt 0) {
                $ParameterString += "-e$($newstartup.ErrorLog);"
            } else {
                Stop-Function -Message "Must have a value for Errorlog"
                return
            }
            if ($newstartup.MasterLog.Length -gt 0) {
                $ParameterString += "-l$($newstartup.MasterLog);"
            } else {
                Stop-Function -Message "Must have a value for MsterLog"
                return
            }
        }

        if ($newstartup.CommandPromptStart) {
            $ParameterString += "-c;"
        }
        if ($newstartup.MinimalStart) {
            $ParameterString += "-f;"
        }
        if ($newstartup.MemoryToReserve -notin ($null, 0)) {
            $ParameterString += "-g$($newstartup.MemoryToReserve)"
        }
        if ($newstartup.SingleUser) {
            if ($SingleUserDetails.length -gt 0) {
                if ($SingleUserDetails -match ' ') {
                    $SingleUserDetails = """$SingleUserDetails"""
                }
                $ParameterString += "-m$SingleUserDetails;"
            } else {
                $ParameterString += "-m;"
            }
        }
        if ($newstartup.NoLoggingToWinEvents) {
            $ParameterString += "-n;"
        }
        If ($newstartup.StartAsNamedInstance) {
            $ParameterString += "-s;"
        }
        if ($newstartup.DisableMonitoring) {
            $ParameterString += "-x;"
        }
        if ($newstartup.IncreasedExtents) {
            $ParameterString += "-E;"
        }
        if ($newstartup.TraceFlags -eq 'None') {
            $newstartup.TraceFlags = ''
        }
        if ($TraceFlagsOverride -and 'TraceFlags' -in $PsBoundParameters.keys) {
            if ($null -ne $TraceFlags -and '' -ne $TraceFlags) {
                $newstartup.TraceFlags = $TraceFlags -join ','
                $ParameterString += (($TraceFlags.split(',') | ForEach-Object { "-T$_" }) -join ';') + ";"
            }
        } else {
            if ('TraceFlags' -in $PsBoundParameters.keys) {
                if ($null -eq $TraceFlags) { $TraceFlags = '' }
                $oldflags = @($currentstartup.TraceFlags) -split ',' | Where-Object { $_ -ne 'None' }
                $newflags = $TraceFlags
                $newstartup.TraceFlags = (@($oldFlags) + @($newflags) | Sort-Object -Unique) -join ','
            } elseif ($TraceFlagsOverride) {
                $newstartup.TraceFlags = ''
            } else {
                $newstartup.TraceFlags = if ($currentstartup.TraceFlags -eq 'None') { }
                else { $currentstartup.TraceFlags -join ',' }
            }
            If ($newstartup.TraceFlags.Length -ne 0) {
                $ParameterString += (($newstartup.TraceFlags.split(',') | ForEach-Object { "-T$_" }) -join ';') + ";"
            }
        }

        $instance = $SqlInstance.ComputerName
        $instancename = $SqlInstance.InstanceName

        if ($instancename.Length -eq 0) { $instancename = "MSSQLSERVER" }

        $displayname = "SQL Server ($instancename)"

        $Scriptblock = {
            #Variable marked as unused by PSScriptAnalyzer
            #$instance = $args[0]
            $displayname = $args[1]
            $ParameterString = $args[2]

            $wmisvc = $wmi.Services | Where-Object { $_.DisplayName -eq $displayname }
            $wmisvc.StartupParameters = $ParameterString
            $wmisvc.Alter()
            $wmisvc.Refresh()
            if ($wmisvc.StartupParameters -eq $ParameterString) {
                $true
            } else {
                $false
            }
        }

        if ($pscmdlet.ShouldProcess("Setting Sql Server start parameters on $SqlInstance to $ParameterString")) {
            try {
                if ($Credential) {
                    #Variable $response marked as unused by PSScriptAnalyzer replace with $null to catch output
                    $null = Invoke-ManagedComputerCommand -ComputerName $server.ComputerName -Credential $Credential -ScriptBlock $Scriptblock -ArgumentList $server.ComputerName, $displayname, $ParameterString -EnableException
                    $output = Get-DbaStartupParameter -SqlInstance $server.ComputerName -Credential $Credential -EnableException
                    Add-Member -Force -InputObject $output -MemberType NoteProperty -Name OriginalStartupParameters -Value $originalparamstring
                } else {
                    #Variable $response marked as unused by PSScriptAnalyzer replace with $null to catch output
                    $null = Invoke-ManagedComputerCommand -ComputerName $server.ComputerName -ScriptBlock $Scriptblock -ArgumentList $server.ComputerName, $displayname, $ParameterString -EnableException
                    $output = Get-DbaStartupParameter -SqlInstance $server.ComputerName -EnableException
                    Add-Member -Force -InputObject $output -MemberType NoteProperty -Name OriginalStartupParameters -Value $originalparamstring
                    Add-Member -Force -InputObject $output -MemberType NoteProperty -Name Notes -Value "Startup parameters changed on $SqlInstance. You must restart SQL Server for changes to take effect."
                }

                $output
            } catch {
                Stop-Function -Message "Startup parameters failed to change on $SqlInstance. " -Target $SqlInstance -ErrorRecord $_
                return
            }
        }
    }
}
tools\dbatools\functions\Set-DbaTcpPort.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Set-DbaTcpPort {
    <#
    .SYNOPSIS
        Changes the TCP port used by the specified SQL Server.

    .DESCRIPTION
        This function changes the TCP port used by the specified SQL Server.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Credential object used to connect to the SQL Server instance as a different user

    .PARAMETER Credential
        Credential object used to connect to the Windows server itself as a different user (like SQL Configuration Manager)

    .PARAMETER Port
        TCPPort that SQLService should listen on.

    .PARAMETER IpAddress
        Which IpAddress should the portchange , if omitted allip (0.0.0.0) will be changed with the new port number.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .NOTES
        Tags: Service, Port, TCP, Configure
        Author: @H0s0n77
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaTcpPort

    .EXAMPLE
        PS C:\> Set-DbaTcpPort -SqlInstance sql2017 -Port 1433

        Sets the port number 1433 for all IP Addresses on the default instance on sql2017. Prompts for confirmation.

    .EXAMPLE
        PS C:\> Set-DbaTcpPort -SqlInstance winserver\sqlexpress -IpAddress 192.168.1.22 -Port 1433 -Confirm:$false

        Sets the port number 1433 for IP 192.168.1.22 on the sqlexpress instance on winserver. Does not prompt for confirmation.

    .EXAMPLE
        PS C:\> Set-DbaTcpPort -SqlInstance sql2017, sql2019 -port 1337 -Credential ad\dba

        Sets the port number 1337 for all IP Addresses on SqlInstance sql2017 and sql2019 using the credentials for ad\dba. Prompts for confirmation.

       #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$Credential,
        [parameter(Mandatory)]
        [ValidateRange(1, 65535)]
        [int]$Port,
        [IpAddress[]]$IpAddress,
        [switch]$EnableException
    )

    begin {
        if (-not $IpAddress) {
            $IpAddress = '0.0.0.0'
        } else {
            if ($SqlInstance.Count -gt 1) {
                Stop-Function -Message "-IpAddress switch cannot be used with a collection of serveraddresses" -Target $SqlInstance
                return
            }
        }
        $scriptblock = {
            $computername = $args[0]
            $wmiinstancename = $args[1]
            $port = $args[2]
            $IpAddress = $args[3]
            $sqlinstanceName = $args[4]

            $wmi = New-Object Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer $computername
            $wmiinstance = $wmi.ServerInstances | Where-Object {
                $_.Name -eq $wmiinstancename
            }
            $tcp = $wmiinstance.ServerProtocols | Where-Object {
                $_.DisplayName -eq 'TCP/IP'
            }
            $IpAddress = $tcp.IpAddresses | where-object {
                $_.IpAddress -eq $IpAddress
            }
            $tcpport = $IpAddress.IpAddressProperties | Where-Object {
                $_.Name -eq 'TcpPort'
            }

            $oldport = $tcpport.Value
            try {
                $tcpport.value = $port
                $tcp.Alter()
                [pscustomobject]@{
                    ComputerName       = $computername
                    InstanceName       = $wmiinstancename
                    SqlInstance        = $sqlinstanceName
                    PreviousPortNumber = $oldport
                    PortNumber         = $Port
                    Status             = "Success"
                }
            } catch {
                [pscustomobject]@{
                    ComputerName       = $computername
                    InstanceName       = $wmiinstancename
                    SqlInstance        = $sqlinstanceName
                    PreviousPortNumber = $oldport
                    PortNumber         = $Port
                    Status             = "Failed: $_"
                }
            }
        }
    }
    process {
        if (Test-FunctionInterrupt) {
            return
        }

        foreach ($instance in $SqlInstance) {
            $wmiinstancename = $instance.InstanceName
            $computerName = $instance.ComputerName

            if ($Pscmdlet.ShouldProcess($computerName, "Setting port to $Port for $wmiinstancename")) {
                try {
                    $computerName = $instance.ComputerName
                    $resolved = Resolve-DbaNetworkName -ComputerName $computerName
                    Invoke-ManagedComputerCommand -ComputerName $resolved.FullComputerName -ScriptBlock $scriptblock -ArgumentList $instance.ComputerName, $wmiinstancename, $port, $IpAddress, $instance.InputObject -Credential $Credential
                } catch {
                    try {
                        Invoke-ManagedComputerCommand -ComputerName $instance.ComputerName -ScriptBlock $scriptblock -ArgumentList $instance.ComputerName, $wmiinstancename, $port, $IpAddress, $instance.InputObject -Credential $Credential
                    } catch {
                        Stop-Function -Message "Failure setting port to $Port for $wmiinstancename on $computerName" -Continue
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Set-DbaTempDbConfig.ps1
function Set-DbaTempdbConfig {
    <#
    .SYNOPSIS
        Sets tempdb data and log files according to best practices.

    .DESCRIPTION
        Calculates tempdb size and file configurations based on passed parameters, calculated values, and Microsoft best practices. User must declare SQL Server to be configured and total data file size as mandatory values. Function then calculates the number of data files based on logical cores on the target host and create evenly sized data files based on the total data size declared by the user, with a log file 25% of the total data file size.

        Other parameters can adjust the settings as the user desires (such as different file paths, number of data files, and log file size). No functions that shrink or delete data files are performed. If you wish to do this, you will need to resize tempdb so that it is "smaller" than what the function will size it to before running the function.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER DataFileCount
        Specifies the number of data files to create. If this number is not specified, the number of logical cores of the host will be used.

    .PARAMETER DataFileSize
        Specifies the total data file size in megabytes. This is distributed across the total number of data files.

    .PARAMETER LogFileSize
        Specifies the log file size in megabytes. If not specified, this will be set to 25% of total data file size.

    .PARAMETER DataFileGrowth
        Specifies the growth amount for the data file(s) in megabytes. The default is 512 MB.

    .PARAMETER LogFileGrowth
        Specifies the growth amount for the log file in megabytes. The default is 512 MB.

    .PARAMETER DataPath
        Specifies the filesystem path in which to create the tempdb data files. If not specified, current tempdb location will be used.

    .PARAMETER LogPath
        Specifies the filesystem path in which to create the tempdb log file. If not specified, current tempdb location will be used.

    .PARAMETER OutputScriptOnly
        If this switch is enabled, only the T-SQL script to change the tempdb configuration is created and output.

    .PARAMETER OutFile
        Specifies the filesystem path into which the generated T-SQL script will be saved.

    .PARAMETER DisableGrowth
        If this switch is enabled, the tempdb files will be configured to not grow. This overrides -DataFileGrowth and -LogFileGrowth.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Tempdb, Space, Configure, Configuration
        Author: Michael Fal (@Mike_Fal), http://mikefal.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Set-DbaTempdbConfig

    .EXAMPLE
        PS C:\> Set-DbaTempdbConfig -SqlInstance localhost -DataFileSize 1000

        Creates tempdb with a number of data files equal to the logical cores where each file is equal to 1000MB divided by the number of logical cores, with a log file of 250MB.

    .EXAMPLE
        PS C:\> Set-DbaTempdbConfig -SqlInstance localhost -DataFileSize 1000 -DataFileCount 8

        Creates tempdb with 8 data files, each one sized at 125MB, with a log file of 250MB.

    .EXAMPLE
        PS C:\> Set-DbaTempdbConfig -SqlInstance localhost -DataFileSize 1000 -OutputScriptOnly

        Provides a SQL script output to configure tempdb according to the passed parameters.

    .EXAMPLE
        PS C:\> Set-DbaTempdbConfig -SqlInstance localhost -DataFileSize 1000 -DisableGrowth

        Disables the growth for the data and log files.

    .EXAMPLE
        PS C:\> Set-DbaTempdbConfig -SqlInstance localhost -DataFileSize 1000 -OutputScriptOnly

        Returns the T-SQL script representing tempdb configuration.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseOutputTypeCorrectly", "", Justification = "PSSA Rule Ignored by BOH")]
    param (
        [parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [int]$DataFileCount,
        [Parameter(Mandatory)]
        [int]$DataFileSize,
        [int]$LogFileSize,
        [int]$DataFileGrowth = 512,
        [int]$LogFileGrowth = 512,
        [string]$DataPath,
        [string]$LogPath,
        [string]$OutFile,
        [switch]$OutputScriptOnly,
        [switch]$DisableGrowth,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9

            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $cores = $server.Processors
            if ($cores -gt 8) {
                $cores = 8
            }

            #Set DataFileCount if not specified. If specified, check against best practices.
            if (-not $DataFileCount) {
                $DataFileCount = $cores
                Write-Message -Message "Data file count set to number of cores: $DataFileCount" -Level Verbose
            } else {
                if ($DataFileCount -gt $cores) {
                    Write-Message -Message "Data File Count of $DataFileCount exceeds the Logical Core Count of $cores. This is outside of best practices." -Level Warning
                }
                Write-Message -Message "Data file count set explicitly: $DataFileCount" -Level Verbose
            }

            $DataFilesizeSingle = $([Math]::Floor($DataFileSize / $DataFileCount))
            Write-Message -Message "Single data file size (MB): $DataFilesizeSingle." -Level Verbose

            if (Test-Bound -ParameterName DataPath) {
                if ((Test-DbaPath -SqlInstance $server -Path $DataPath) -eq $false) {
                    Stop-Function -Message "$datapath is an invalid path." -Continue
                }
            } else {
                $Filepath = $server.Databases['tempdb'].ExecuteWithResults('SELECT physical_name as FileName FROM sys.database_files WHERE file_id = 1').Tables[0].Rows[0].FileName
                $DataPath = Split-Path $Filepath
            }

            Write-Message -Message "Using data path: $datapath." -Level Verbose

            if (Test-Bound -ParameterName LogPath) {
                if ((Test-DbaPath -SqlInstance $server -Path $LogPath) -eq $false) {
                    Stop-Function -Message "$LogPath is an invalid path." -Continue
                }
            } else {
                $Filepath = $server.Databases['tempdb'].ExecuteWithResults('SELECT physical_name as FileName FROM sys.database_files WHERE file_id = 2').Tables[0].Rows[0].FileName
                $LogPath = Split-Path $Filepath
            }
            Write-Message -Message "Using log path: $LogPath." -Level Verbose

            # Check if the file growth needs to be disabled
            if ($DisableGrowth) {
                $DataFileGrowth = 0
                $LogFileGrowth = 0
            }

            # Check current tempdb. Throw an error if current tempdb is larger than config.
            $CurrentFileCount = $server.Databases['tempdb'].ExecuteWithResults('SELECT count(1) as FileCount FROM sys.database_files WHERE type=0').Tables[0].Rows[0].FileCount
            $TooBigCount = $server.Databases['tempdb'].ExecuteWithResults("SELECT TOP 1 (size/128) as Size FROM sys.database_files WHERE size/128 > $DataFilesizeSingle AND type = 0").Tables[0].Rows[0].Size

            if ($CurrentFileCount -gt $DataFileCount) {
                Stop-Function -Message "Current tempdb in $instance is not suitable to be reconfigured. The current tempdb has a greater number of files ($CurrentFileCount) than the calculated configuration ($DataFileCount)." -Continue
            }

            if ($TooBigCount) {
                Stop-Function -Message "Current tempdb in $instance is not suitable to be reconfigured. The current tempdb ($TooBigCount MB) is larger than the calculated individual file configuration ($DataFilesizeSingle MB)." -Continue
            }

            $EqualCount = $server.Databases['tempdb'].ExecuteWithResults("SELECT count(1) as FileCount FROM sys.database_files WHERE size/128 = $DataFilesizeSingle AND type = 0").Tables[0].Rows[0].FileCount

            Write-Message -Message "tempdb configuration validated." -Level Verbose

            $DataFiles = $server.Databases['tempdb'].ExecuteWithResults("select f.name as Name, f.physical_name as FileName from sys.filegroups fg join sys.database_files f on fg.data_space_id = f.data_space_id where fg.name = 'PRIMARY' and f.type_desc = 'ROWS'").Tables[0];

            #Checks passed, process reconfiguration
            for ($i = 0; $i -lt $DataFileCount; $i++) {
                $File = $DataFiles.Rows[$i]
                if ($File) {
                    $Filename = Split-Path $File.FileName -Leaf
                    $LogicalName = $File.Name
                    $NewPath = "$datapath\$Filename"
                    $sql += "ALTER DATABASE tempdb MODIFY FILE(name=$LogicalName,filename='$NewPath',size=$DataFilesizeSingle MB,filegrowth=$DataFileGrowth);"
                } else {
                    $NewName = "tempdev$i.ndf"
                    $NewPath = "$datapath\$NewName"
                    $sql += "ALTER DATABASE tempdb ADD FILE(name=tempdev$i,filename='$NewPath',size=$DataFilesizeSingle MB,filegrowth=$DataFileGrowth);"
                }
            }

            if (-not $LogFileSize) {
                $LogFileSize = [Math]::Floor($DataFileSize / 4)
            }

            $logfile = $server.Databases['tempdb'].ExecuteWithResults("SELECT name, physical_name as FileName FROM sys.database_files WHERE file_id = 2").Tables[0].Rows[0];
            $Filename = Split-Path $logfile.FileName -Leaf
            $LogicalName = $logfile.Name
            $NewPath = "$LogPath\$Filename"
            $sql += "ALTER DATABASE tempdb MODIFY FILE(name=$LogicalName,filename='$NewPath',size=$LogFileSize MB,filegrowth=$LogFileGrowth);"

            Write-Message -Message "SQL Statement to resize tempdb." -Level Verbose
            Write-Message -Message ($sql -join "`n`n") -Level Verbose

            if ($OutputScriptOnly) {
                return $sql
            } elseif ($OutFile) {
                $sql | Set-Content -Path $OutFile
            } else {
                if ($Pscmdlet.ShouldProcess($instance, "Executing query and informing that a restart is required.")) {
                    try {
                        $server.Databases['master'].ExecuteNonQuery($sql)
                        Write-Message -Level Verbose -Message "tempdb successfully reconfigured."

                        [PSCustomObject]@{
                            ComputerName       = $server.ComputerName
                            InstanceName       = $server.ServiceName
                            SqlInstance        = $server.DomainInstanceName
                            DataFileCount      = $DataFileCount
                            DataFileSize       = [dbasize]($DataFileSize * 1024 * 1024)
                            SingleDataFileSize = [dbasize]($DataFilesizeSingle * 1024 * 1024)
                            LogSize            = [dbasize]($LogFileSize * 1024 * 1024)
                            DataPath           = $DataPath
                            LogPath            = $LogPath
                            DataFileGrowth     = [dbasize]($DataFileGrowth * 1024 * 1024)
                            LogFileGrowth      = [dbasize]($LogFileGrowth * 1024 * 1024)
                        }

                        Write-Message -Level Output -Message "tempdb reconfigured. You must restart the SQL Service for settings to take effect."
                    } catch {
                        Stop-Function -Message "Unable to reconfigure tempdb. Exception: $_" -Target $sql -ErrorRecord $_ -Continue
                    }
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Set-SqlTempDbConfiguration
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Set-DbaTempDbConfiguration
    }
}
tools\dbatools\functions\Show-DbaDbList.ps1
function Show-DbaDbList {
    <#
    .SYNOPSIS
        Shows a list of databases in a GUI.

    .DESCRIPTION
        Shows a list of databases in a GUI. Returns a string holding the name of the selected database. Hitting cancel returns null.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances..

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Title
        Title of the window being displayed. Default is "Select Database".

    .PARAMETER Header
        Header text displayed above the database listing. Default is "Select the database:".

    .PARAMETER DefaultDb
        Specify a database to have selected when the window appears.

    .NOTES
        Tags: Database, FileSystem
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Show-DbaDbList

    .EXAMPLE
        PS C:\> Show-DbaDbList -SqlInstance sqlserver2014a

        Shows a GUI list of databases using Windows Authentication to connect to the SQL Server. Returns a string of the selected database.

    .EXAMPLE
        PS C:\> Show-DbaDbList -SqlInstance sqlserver2014a -SqlCredential $cred

        Shows a GUI list of databases using SQL credentials to connect to the SQL Server. Returns a string of the selected database.

    .EXAMPLE
        PS C:\> Show-DbaDbList -SqlInstance sqlserver2014a -DefaultDb master

        Shows a GUI list of databases using Windows Authentication to connect to the SQL Server. The "master" database will be selected when the lists shows. Returns a string of the selected database.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$Title = "Select Database",
        [string]$Header = "Select the database:",
        [string]$DefaultDb
    )

    begin {
        try {
            Add-Type -AssemblyName PresentationFramework
        } catch {
            throw "Windows Presentation Framework required but not installed"
        }

        function Add-TreeItem {
            param (
                [string]$name,
                [object]$parent,
                [string]$tag
            )

            $childitem = New-Object System.Windows.Controls.TreeViewItem
            $textblock = New-Object System.Windows.Controls.TextBlock
            $textblock.Margin = "5,0"
            $stackpanel = New-Object System.Windows.Controls.StackPanel
            $stackpanel.Orientation = "Horizontal"
            $image = New-Object System.Windows.Controls.Image
            $image.Height = 20
            $image.Width = 20
            $image.Stretch = "Fill"
            $image.Source = $dbicon
            $textblock.Text = $name
            $childitem.Tag = $name

            if ($name -eq $DefaultDb) {
                $childitem.IsSelected = $true
                $script:selected = $name
            }

            [void]$stackpanel.Children.Add($image)
            [void]$stackpanel.Children.Add($textblock)

            $childitem.Header = $stackpanel
            [void]$parent.Items.Add($childitem)
        }

        function Convert-b64toimg {
            param ($base64)

            $bitmap = New-Object System.Windows.Media.Imaging.BitmapImage
            $bitmap.BeginInit()
            $bitmap.StreamSource = [System.IO.MemoryStream][System.Convert]::FromBase64String($base64)
            $bitmap.EndInit()
            $bitmap.Freeze()
            return $bitmap
        }

        $dbicon = Convert-b64toimg "iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAAFRSURBVDhPY/j//z9VMVZBSjCCgQZunFn6/8zenv+7llf83zA75/+6WTn/N80v+L93ddP/M/tnY2jAayDIoNvn5/5/cX/t/89vdv7/9fUQGIPYj2+t/H/xyJT/O1ZUoWjCaeCOxcX///48ShSeWhMC14jXwC9Xs/5/fzHr/6/PW+GaQS78/WH9/y+Pe8DyT3fYEmcgKJw+HHECawJp/vZ60f8v95v/fzgd8P/tVtn/L1cw/n+0iOH/7TlMxBkIigBiDewr9iVsICg2qWrg6qnpA2dgW5YrYQOX9icPAQPfU9PA2S2RRLuwMtaGOAOf73X+//FyGl4DL03jIM5AEFjdH/x//+Lo/1cOlP9/dnMq2MA3x/z/312l/P/4JNH/axoU/0/INUHRhNdAEDi+pQ1cZIFcDEpvoPCaVOTwf1Gjy/9ds5MxNGAYSC2MVZB8/J8BAGcHwqQBNWHRAAAAAElFTkSuQmCC"
        $foldericon = Convert-b64toimg "iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAAHaSURBVDhPY/j//z9VMVZBSjBWQUowVkFKMApnzZL+/+gYWZ4YDGeANL95sun/j3fbwPjbm5X/Pz+cRLKhcAayq2B45YKe/8vndoHx4lltYLxgajMKhumHYRQDf37Yh4J/fNry//fb1f9/v1n6/8/Tqf//3O/6/+dO9f9fV4v+fzmV/v/L0aj/lflJQO1YDAS5AmwI1MvfPyAZ9KgbYtDlvP/fzyT9/3w45P+HPT7/z8+UwG0gyDvIBmIYBnQVyDCQq0CGPV9p8v94P/f/rKQwoHYsBs4HhgfIQJjLfr+YjdOwt5tt/z9eov1/fxf3/+ggD6B2HAaCXQYKM6hhv+81oYQXzLCXq03/P5qn/H9LE/9/LycroHYsBs7oq4EYCDIM6FVshr3Z4gg2DOS6O9Nk/q+sFvlvZawD1I7FwKldleC0h2zY9wuZEMP2+aMYdn+W/P/rE0T/zy+T+q+jJg/UjsXASe1l/z/cX/T/1dn8/492ePy/vc7s/82VOv8vLVT9f3yGwv89ffL/1zXL/l9dJwF2GciwaYVy/xVlxIDasRjY31Lyv7Uy+39ZTvz/1JiA/8Hejv8dLA3+62sqgTWJC/HixDAzQBjOoBbGKkgJxipICcYqSD7+zwAAkIiWzSGuSg0AAAAASUVORK5CYII="
        $dbatoolsicon = Convert-b64toimg "iVBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAAO9SURBVEhL3VVdTFNXHO9MzPTF+OzDeBixFdTMINIWsAUK3AIVkFvAIQVFRLYZKR8Wi1IEKV9DYB8PGFAyEx8QScySabYY5+I2JvK18iWISKGk0JGhLzA3+e2c29uHtpcvH/0lv9yennN+v3vO/3fOFb2fCAg4vXWPNOmMRJ745TtTSskqeElviGXJ0XtkWvjJkyGLPoFAVQZoe/NkX/n6Mh/ysu4Qy7WZdJAutxRW6zT6LcNQaE4LiGgREH4cibpCMNqzCIk9hbScEoSSZ0zKOa7fRxG/k5d1h8ukvO4a5ubmMT1jw5E0vZcBZWzqOTS3dcB8tRXZeRX4/v5DZH5uIu0Wrn8NEzaNDjgYoUPd120oMjViX2iql8H6ZFd8DzE7eFl3iOWpuyQydlh44kbJroilSd8RuQ+cqh7wC9Z+JJaxY8KTN0gp+5Yk9DaREzYhb5FOBwZFZ6LlZifKa5ux//AxYTHCvSEp8A9O5n77B6dwqXS119guZ+GrGq9jfn4eM7ZZxB/PdxN2UfOpHq3kRWq/uoE8Yx3u/fQLzhSYUdN0g+tfN126z0oxNj6BJz0Dq0b4E2UawuJzuPhKyZmKYr/AocgMrk37VzWRBLGRdE/psuXqk9wkT/GNUCJLWqS3By/rDh9FxjaSrnahiZ7cq8wCUzKImLIJqC+Ngbk4gmjjIKKKB6Aq7l+OLBmfVF0YnlQZR1p4eSd2y5IiyEr+oyJ0CwIi0gUNKAOPmnG04Q0utf+DHweWkFjjQOyVWajLpsCUPkeUcRgqAzE09Dfz8k64aqI9YcDziUk87bMgOCZL0CQ0ux2J9UtIbXyFwall/PD0NeLKrU6DkhGymj8RXtRDjU7x8k64TKpJQmi6bLOzSEgv8DYhNWMujiK+9jU0VQs4Vm/H2MwSOh4vcP+rii2cQVh+F+IqbRJe3glyReuoSFBUJtpu3eWulv2h3ueE1iOu0g5N9QL3jLk8jerbdrz59y1yGoYQUdSLsII/CLscIsD9UPrLUz4myXhBhWjCPMVdPBBnhMbsIAZzSDDbcOvRIhyLy6i4+Qyq82QFxECR9xjK/K5OXtodNHo+CsW2tagunbxADbK+sXP16Bv/G7lNQ8hpHEX21UGoDb/j8NmfoSzoNvCymwdTPvMotsKGB32LaL1H0mS0oOHOFLpH/0L3iAOF3/YSk4dgTBMh/JTNgdVbtzNl1il12UuSpHE+SRayTb0IL3yCMP2vUJKtUuh/szNNK8Jfxw3BZNpiMoGjiKPJm54Ffw8gEv0PQRYX7wDAUKEAAAAASUVORK5CYII="

        $sourceserver = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
    }

    process {
        # Create XAML form in Visual Studio, ensuring the ListView looks chromeless
        [xml]$xaml = "<Window
        xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
        xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
        Title='$Title' SizeToContent='WidthAndHeight' Background='#F0F0F0'
        WindowStartupLocation='CenterScreen' MaxHeight='600'>
    <Grid>
        <TreeView Name='treeview' Height='Auto' Width='Auto' Background='#FFFFFF' BorderBrush='#FFFFFF' Foreground='#FFFFFF' Margin='11,36,11,79'/>
        <Label x:Name='label' Content='$header' HorizontalAlignment='Left' Margin='15,4,10,0' VerticalAlignment='Top'/>
        <StackPanel HorizontalAlignment='Right' Orientation='Horizontal' VerticalAlignment='Bottom' Margin='0,50,10,30'>
        <Button Name='okbutton' Content='OK'  Margin='0,0,0,0' Width='75'/>
        <Label Width='10'/>
        <Button Name='cancelbutton' Content='Cancel' Margin='0,0,0,0' Width='75'/>
    </StackPanel>
</Grid>
</Window>"
        #second pushes it down
        # Turn XAML into PowerShell objects
        $window = [Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader $xaml))
        $window.icon = $dbatoolsicon

        $xaml.SelectNodes("//*[@Name]") | ForEach-Object { Set-Variable -Name ($_.Name) -Value $window.FindName($_.Name) -Scope Script }

        $childitem = New-Object System.Windows.Controls.TreeViewItem
        $textblock = New-Object System.Windows.Controls.TextBlock
        $textblock.Margin = "5,0"
        $stackpanel = New-Object System.Windows.Controls.StackPanel
        $stackpanel.Orientation = "Horizontal"
        $image = New-Object System.Windows.Controls.Image
        $image.Height = 20
        $image.Width = 20
        $image.Stretch = "Fill"
        $image.Source = $foldericon
        $textblock.Text = "Databases"
        $childitem.Tag = "Databases"
        $childitem.isExpanded = $true
        [void]$stackpanel.Children.Add($image)
        [void]$stackpanel.Children.Add($textblock)
        $childitem.Header = $stackpanel
        #Variable marked as unused by PSScriptAnalyzer
        #$databaseParent = $treeview.Items.Add($childitem)

        try {
            $databases = $sourceserver.databases.name
        } catch {
            return
        }

        foreach ($database in $databases) {
            Add-TreeItem -Name $database -Parent $childitem -Tag $nameSpace
        }

        $okbutton.Add_Click( {
                $window.Close()
                $script:okay = $true
            })

        $cancelbutton.Add_Click( {
                $script:selected = $null
                $window.Close()
            })

        $window.Add_SourceInitialized( {
                [System.Windows.RoutedEventHandler]$Event = {
                    if ($_.OriginalSource -is [System.Windows.Controls.TreeViewItem]) {
                        $script:selected = $_.OriginalSource.Tag
                    }
                }
                $treeview.AddHandler([System.Windows.Controls.TreeViewItem]::SelectedEvent, $Event)
            })

        $null = $window.ShowDialog()
    }

    end {
        if ($script:selected.length -gt 0 -and $script:okay -eq $true) {
            return $script:selected
        }

        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Show-SqlDatabaseList
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Show-DbaDatabaseList
    }
}
tools\dbatools\functions\Show-DbaServerFileSystem.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Show-DbaServerFileSystem {
    <#
    .SYNOPSIS
        Shows file system on remote SQL Server in a local GUI and returns the selected directory name

    .DESCRIPTION
        Similar to the remote file system popup you see when browsing a remote SQL Server in SQL Server Management Studio, this function allows you to traverse the remote SQL Server's file structure.

        Show-DbaServerFileSystem uses SQL Management Objects to browse the directories and what you see is limited to the permissions of the account running the command.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Defaults to localhost.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Storage, FileSystem
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Show-DbaServerFileSystem

    .EXAMPLE
        PS C:\> Show-DbaServerFileSystem -SqlInstance sql2017

        Shows a list of databases using Windows Authentication to connect to the SQL Server. Returns a string of the selected path.

    .EXAMPLE
        PS C:\> Show-DbaServerFileSystem -SqlInstance sql2017 -SqlCredential $cred

        Shows a list of databases using SQL credentials to connect to the SQL Server. Returns a string of the selected path.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )
    begin {
        try {
            Add-Type -AssemblyName PresentationFramework
        } catch {
            Stop-Function -Message "Windows Presentation Framework required but not installed."
            return
        }

        function Add-TreeItem {
            param (
                [string]$name,
                [object]$parent,
                [string]$tag
            )

            $childitem = New-Object System.Windows.Controls.TreeViewItem

            $textblock = New-Object System.Windows.Controls.TextBlock
            $textblock.Margin = "5,0"

            $stackpanel = New-Object System.Windows.Controls.StackPanel
            $stackpanel.Orientation = "Horizontal"

            $image = New-Object System.Windows.Controls.Image
            $image.Height = 20
            $image.Width = 20
            $image.Stretch = "Fill"

            if ($name.length -eq 1) {
                $image.Source = $diskicon
                $textblock.Text = "$name`:"
                $childitem.Tag = "$name`:"

            } else {
                $image.Source = $foldericon
                $textblock.Text = $name
                $childitem.Tag = "$tag\$name"
            }

            [void]$stackpanel.Children.Add($image)
            [void]$stackpanel.Children.Add($textblock)

            $childitem.Header = $stackpanel

            [void]$childitem.Items.Add("*")
            [void]$parent.Items.Add($childitem)
        }

        function Get-SubDirectory {
            param (
                [string]$nameSpace,
                [object]$treeviewItem
            )

            $textbox.Text = $nameSpace
            try {
                $dirs = $server.EnumDirectories($nameSpace)
            } catch {
                return
            }
            $subdirs = $dirs.Name

            foreach ($subdir in $subdirs) {
                if (!$subdir.StartsWith("$") -and $subdir -ne 'System Volume Information') {
                    Add-TreeItem -Name $subdir -Parent $treeviewItem -Tag $nameSpace
                }
            }
        }

        function Convert-b64toimg {
            param ($base64)

            $bitmap = New-Object System.Windows.Media.Imaging.BitmapImage
            $bitmap.BeginInit()
            $bitmap.StreamSource = [System.IO.MemoryStream][System.Convert]::FromBase64String($base64)
            $bitmap.EndInit()
            $bitmap.Freeze()
            return $bitmap
        }

        $diskicon = Convert-b64toimg "iVBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAACxEAAAsRAX9kX5EAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAAJtSURBVEhLtZJLa1NBGIa78ze4EZeu3bjS36BduVOsVCGmUqo1QlMaTV3E0oVugm0obdUQTZtYEnNvboTczjlN0ubaWE2aWGhuVQQXKbzOBM+BmokinA48nI+XmefjfDNDAE4dZig3zFBumKHcMEO5YYZywwwppVL5QrG4+217OweO30IiySPJCT1ozQsp7GTzoHvoXpZDpC/4Ut2/nc7sRIhYqO3Xuq1GA512C53WSY46bbSaTVQr1S5pLNAz9OyfPopUlMuf9KFAWO9yeit2uwtWiw1Ohwd+XwBBfxjBAIF+f9dkLzZ9QTg/umGzuuGwe+F0uivBQEhPXcwmJtM6HOSA2+VDOBRBaisNno4nwSOR4PqIx5LgyRhzuQK4NIdYPE7ORXsO6hK9FKkYHb0Po3ENGXIHzVabRP9ex13gsHkI7qcdobwTyUgapncWUBdZ/U3Gxx/j9aoJqVQGpd0KCsWvhPpAavXv8Ls5KCfGcMN7EcOay9CpX8D8/gOoS/RSTjQxLK6QlyRgt1xFvlAn1AZSq/yAZzOCW7pruHpwBlc056C+8xxr5o3BTRSKid6fZHM5VKoH2PvcIjQH0mwcwx/gcFN1HcOxs7ikPI+ZsTnyWHygLtFLkQq1ehZTUxpYrRvI58sQhAIhP5Bsbg9+Txzzcy+hddzDkwUVnk3PY1arA3WJXopUmEwWjIzcheqRGsa3ZjK65b+y8GoJy0tvyEWvY9W+CJvXhqczup6DukQvRSqi0QQMhhVMTk5DqXzYm+v/oFA8IJPQkhdqBnWJXopUnCbMUG6YodwwQ7lhhnLDDOWGGcoNM5QXDP0CA9dqCMSSjzkAAAAASUVORK5CYII="
        $foldericon = Convert-b64toimg "iVBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAACxEAAAsRAX9kX5EAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAAU0SURBVEhLtZXpU5NXFIf9q/qto9bRuhc3xqUiUK3KoLYq6ihu1VIU1DpjRZ3BHVR8i6hUkDUJASNL2EJIWLKvBLJAAmHRpwfb6ai10Q/2w29u3pP3/p57zrn3vnOA/13/CkwMlzLuv0rMfYaoM59R+1ki1lwiFtHgGcIDuYT6fiZoPsWI6SSBnmyGeo4yZDxN2KEQHXr54H3Pdx5mNe6/QnzkGtMxNVNjeqK+AkLWQ/iMWdg7sxnz3uZ1vIrJSBnx0O9MhBQmggqxkRJC9hsEzFc+Dol5cpkcFaNXHbyasTMVNzARqWXEeZv+lh+xG/OIRWrgtU5ebxG1yu9meb+JEct57C+2fwLEe04g95mOPxJV8JphCcPUuBOHfg/6qm/pa8klNvyA6fFqZqbqZaxiZqKWQF8uVm3qp0LuMTNZyfREuUx+JuEo8agLe1smHTXpGLXSB3O+lKqMV5N1UtZypqJ/SCwHS2P6J0Iis5BqgTyR3tyVcIj4mAtL807aq1IxqLJwdR6TJhfL/xUCK3kjn/Ekg9rvPg6JevL/hlQJ5KmU4qGEg9IXCwNN22ir3ES3ap9AjjLqvU48/FBgN0SFeAzZDDSk3nnf852HWY25zxKPFEut/4JMRmcX5mM8bKJPm0bLs/V01e/B2X6IsPMyscAtRt2XRZdwdx1kQPsJ5Rp1nRGIZCKQqZhs09FiCTuJhQyYNFtoLl9HZ20mjtb9BK0XJJsrhG3nZJvn4Wr/AUfbEc+I/fFsI//xfAcwq4gjR0pTxPRkhQAeMh66zavpHkYDWoz1m3j5ZDWd1duxN+9muO80IVuejCcImI7h0W/F2boLtyFfrBJAwtZTjAdvMTn+VFZ/j7HADSbGahh2FGGoWYeuLImOynRsL3bg7zksgGP4DPvwdu2W52wp4wH6NJvFKgEkaP2J6LA0dKxMxruM+q9LFnfxmH+hu3oVTY+S0FekyFbdhrdzr1wnWXg6MnC1phBwVuOxqelvSBOrBJCRgWOM+a9JmUqI+AoJea4SlMY6pamdlStoVJbTVr6BQemPq22ngDJwNm/B3rSKgFuPzz0gmXwEEug7TMTzm5TpDkHXZYbtFxm2XsTenkX7s2VoS76m9cla+lUbcbxMlQxmAclYNEsIuzSE3N0CSRWrBBC/6RBB50XC3kICtl/xD+bh78/DIveWvnwJDQ8W0iJ96atNxtYoIN0GrA1JWOoX4Ler8Dq7MKu3iFUCiK/ngKw8Xy7EAnwDZ6UXOXjkGh/QZdL2dDHq+1/RXLoSc80aMV+LTbsKm3opHvU8buoqKdC1YFKliFUCiKdrr6w8B7/lAu7eUzi7j+PoPCIH8XtaHi9CXTyPZmUJpqqVDKq/wapZgUO9mKB2LqmlVSQ9bKG3fqNYJYA4O3bhMZ2QDHJxdGVj0x/E2rafXnW6QBaiKZ7LS2URpucrGFQtF8hyHJqlDGkXcLz0OnuVUno/loldvwO37He3MQebXB3W1n1yMe7BKBNnIeqiL9GVLHwDsaiWYdMsw6pehl1A7bXraK7birlhh1glgLi6T2Br24tZmyqr34BJvZn+xu1y2r+l9fF86m5+gbZ4PsbnazDXJ9OvXv9mNNUl45LSDck3x91bKFYJIF7TJWVQl6mYNGn6fl0WpoYMeupSaK9Yje7RcjmMqbSWZ9gNz9crxvotSq86TTHWpiiGmk2KUZWuOAyXlBG3Snnb8x3A2wp6m3b6rE+wtp+nq2oDL0oX01CaQndjAVZjbdGH5vyXPhj83Ppg8POKOX8Cx4yjZbQFLr4AAAAASUVORK5CYII="
        $dbatoolsicon = Convert-b64toimg "iVBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAAO9SURBVEhL3VVdTFNXHO9MzPTF+OzDeBixFdTMINIWsAUK3AIVkFvAIQVFRLYZKR8Wi1IEKV9DYB8PGFAyEx8QScySabYY5+I2JvK18iWISKGk0JGhLzA3+e2c29uHtpcvH/0lv9yennN+v3vO/3fOFb2fCAg4vXWPNOmMRJ745TtTSskqeElviGXJ0XtkWvjJkyGLPoFAVQZoe/NkX/n6Mh/ysu4Qy7WZdJAutxRW6zT6LcNQaE4LiGgREH4cibpCMNqzCIk9hbScEoSSZ0zKOa7fRxG/k5d1h8ukvO4a5ubmMT1jw5E0vZcBZWzqOTS3dcB8tRXZeRX4/v5DZH5uIu0Wrn8NEzaNDjgYoUPd120oMjViX2iql8H6ZFd8DzE7eFl3iOWpuyQydlh44kbJroilSd8RuQ+cqh7wC9Z+JJaxY8KTN0gp+5Yk9DaREzYhb5FOBwZFZ6LlZifKa5ux//AxYTHCvSEp8A9O5n77B6dwqXS119guZ+GrGq9jfn4eM7ZZxB/PdxN2UfOpHq3kRWq/uoE8Yx3u/fQLzhSYUdN0g+tfN126z0oxNj6BJz0Dq0b4E2UawuJzuPhKyZmKYr/AocgMrk37VzWRBLGRdE/psuXqk9wkT/GNUCJLWqS3By/rDh9FxjaSrnahiZ7cq8wCUzKImLIJqC+Ngbk4gmjjIKKKB6Aq7l+OLBmfVF0YnlQZR1p4eSd2y5IiyEr+oyJ0CwIi0gUNKAOPmnG04Q0utf+DHweWkFjjQOyVWajLpsCUPkeUcRgqAzE09Dfz8k64aqI9YcDziUk87bMgOCZL0CQ0ux2J9UtIbXyFwall/PD0NeLKrU6DkhGymj8RXtRDjU7x8k64TKpJQmi6bLOzSEgv8DYhNWMujiK+9jU0VQs4Vm/H2MwSOh4vcP+rii2cQVh+F+IqbRJe3glyReuoSFBUJtpu3eWulv2h3ueE1iOu0g5N9QL3jLk8jerbdrz59y1yGoYQUdSLsII/CLscIsD9UPrLUz4myXhBhWjCPMVdPBBnhMbsIAZzSDDbcOvRIhyLy6i4+Qyq82QFxECR9xjK/K5OXtodNHo+CsW2tagunbxADbK+sXP16Bv/G7lNQ8hpHEX21UGoDb/j8NmfoSzoNvCymwdTPvMotsKGB32LaL1H0mS0oOHOFLpH/0L3iAOF3/YSk4dgTBMh/JTNgdVbtzNl1il12UuSpHE+SRayTb0IL3yCMP2vUJKtUuh/szNNK8Jfxw3BZNpiMoGjiKPJm54Ffw8gEv0PQRYX7wDAUKEAAAAASUVORK5CYII="
    }

    process {
        if (Test-FunctionInterrupt) { return }

        try {
            $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $SqlInstance
            return
        }

        # Create XAML form in Visual Studio, ensuring the ListView looks chromeless
        [xml]$xaml = '<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Locate Folder" Height="620" Width="440" Background="#F0F0F0"
        WindowStartupLocation="CenterScreen">
    <Grid>
        <TreeView Name="treeview" Height="462" Width="391" Background="#FFFFFF" BorderBrush="#FFFFFF" Foreground="#FFFFFF" Margin="11,36,11,79"/>
        <Label x:Name="label" Content="Select the folder:" HorizontalAlignment="Left" Margin="15,4,0,0" VerticalAlignment="Top"/>
        <Label x:Name="path" Content="Selected Path" HorizontalAlignment="Left" Margin="15,502,0,0" VerticalAlignment="Top"/>
        <TextBox Name="textbox" HorizontalAlignment="Left" Height="Auto" Margin="111,504,0,0" TextWrapping="NoWrap" Text="C:\" VerticalAlignment="Top" Width="292"/>
        <Button Name="okbutton" Content="OK" HorizontalAlignment="Left" Margin="241,540,0,0" VerticalAlignment="Top" Width="75"/>
        <Button Name="cancelbutton" Content="Cancel" HorizontalAlignment="Left" Margin="328.766,540,0,0" VerticalAlignment="Top" Width="75"/>
    </Grid>
</Window>
'
        # Turn XAML into PowerShell objects
        $window = [Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader $xaml))
        $window.icon = $dbatoolsicon

        $xaml.SelectNodes("//*[@Name]") | ForEach-Object { Set-Variable -Name ($_.Name) -Value $window.FindName($_.Name) -Scope Script }

        try {
            $drives = ($server.EnumAvailableMedia()).Name
        } catch {
            Stop-Function -Message "No access to remote SQL Server files." -Target $SqlInstance
            return
        }

        foreach ($drive in $drives) {
            $drive = $drive.Replace(":", "")
            Add-TreeItem -Name $drive -Parent $treeview -Tag $drive
        }

        $window.Add_SourceInitialized( {
                [System.Windows.RoutedEventHandler]$Event = {
                    if ($_.OriginalSource -is [System.Windows.Controls.TreeViewItem]) {
                        $treeviewItem = $_.OriginalSource
                        $treeviewItem.items.clear()
                        Get-SubDirectory -NameSpace $treeviewItem.Tag -TreeViewItem $treeviewItem
                    }
                }
                $treeview.AddHandler([System.Windows.Controls.TreeViewItem]::ExpandedEvent, $Event)
                $treeview.AddHandler([System.Windows.Controls.TreeViewItem]::SelectedEvent, $Event)
            })

        $okbutton.Add_Click( {
                $window.Close()
            })

        $cancelbutton.Add_Click( {
                $textbox.Text = $null
                $window.Close()
            })

        $null = $window.ShowDialog()
    }

    end {

        if ($textbox.Text.Length -gt 0) {
            $drive = $textbox.Text + '\'
            return $drive
        }

        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Show-SqlServerFileSystem
    }
}
tools\dbatools\functions\Start-DbaAgentJob.ps1
function Start-DbaAgentJob {
    <#
    .SYNOPSIS
        Starts a running SQL Server Agent Job.

    .DESCRIPTION
        This command starts a job then returns connected SMO object for SQL Agent Job information for each instance(s) of SQL Server.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Job
        The job(s) to process - this list is auto-populated from the server. If unspecified, all jobs will be processed.

    .PARAMETER ExcludeJob
        The job(s) to exclude - this list is auto-populated from the server.

    .PARAMETER AllJobs
        Retrieve all the jobs

    .PARAMETER Wait
        Wait for output until the job has started

    .PARAMETER WaitPeriod
        Wait period in seconds to use when -Wait is used

    .PARAMETER SleepPeriod
        Period in milliseconds to wait after a job has started

    .PARAMETER InputObject
        Internal parameter that enables piping

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Job, Agent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Start-DbaAgentJob

    .EXAMPLE
        PS C:\> Start-DbaAgentJob -SqlInstance localhost

        Starts all running SQL Agent Jobs on the local SQL Server instance

    .EXAMPLE
        PS C:\> Get-DbaAgentJob -SqlInstance sql2016 -Job cdc.DBWithCDC_capture | Start-DbaAgentJob

        Starts the cdc.DBWithCDC_capture SQL Agent Job on sql2016

    .EXAMPLE
        PS C:\> Start-DbaAgentJob -SqlInstance sql2016 -Job cdc.DBWithCDC_capture

        Starts the cdc.DBWithCDC_capture SQL Agent Job on sql2016

    .EXAMPLE
        PS C:\> $servers | Find-DbaAgentJob -IsFailed | Start-DbaAgentJob

        Restarts all failed jobs on all servers in the $servers collection

    .EXAMPLE
        PS C:\> Start-DbaAgentJob -SqlInstance sql2016 -AllJobs

        Start all the jobs

    #>
    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = "Default")]
    param (
        [parameter(Mandatory, ParameterSetName = "Instance")]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Job,
        [string[]]$ExcludeJob,
        [parameter(Mandatory, ValueFromPipeline, ParameterSetName = "Object")]
        [Microsoft.SqlServer.Management.Smo.Agent.Job[]]$InputObject,
        [switch]$AllJobs,
        [switch]$Wait,
        [int]$WaitPeriod = 3,
        [int]$SleepPeriod = 300,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        if ((Test-Bound -not -ParameterName AllJobs) -and (Test-Bound -not -ParameterName Job) -and (Test-Bound -not -ParameterName InputObject)) {
            Stop-Function -Message "Please use one of the job parameters, either -Job or -AllJobs. Or pipe in a list of jobs." -Target $instance
            return
        }
        # Loop through each of the instances
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            # Check if all the jobs need to included
            if ($AllJobs) {
                $InputObject += $server.JobServer.Jobs
            }

            # If a specific job needs to be added
            if (-not $AllJobs -and $Job) {
                $InputObject = $server.JobServer.Jobs | Where-Object Name -In $Job
            }

            # If a job needs to be excluded
            if ($ExcludeJob) {
                $InputObject = $InputObject | Where-Object Name -NotIn $ExcludeJob
            }
        }

        # Loop through each of the jobs
        foreach ($currentjob in $InputObject) {
            $server = $currentjob.Parent.Parent
            $status = $currentjob.CurrentRunStatus

            if ($status -ne 'Idle') {
                Stop-Function -Message "$currentjob on $server is not idle ($status)" -Target $currentjob -Continue
            }

            If ($Pscmdlet.ShouldProcess($server, "Starting job $currentjob")) {
                # Start the job
                $lastrun = $currentjob.LastRunDate
                Write-Message -Level Verbose -Message "Last run date was $lastrun"
                $null = $currentjob.Start()

                # Wait and refresh so that it has a chance to change status
                Start-Sleep -Milliseconds $SleepPeriod
                $currentjob.Refresh()

                $i = 0
                # Check if the status is Idle
                while (($currentjob.CurrentRunStatus -eq 'Idle' -and $i++ -lt 60)) {
                    Write-Message -Level Verbose -Message "Job $($currentjob.Name) status is $($currentjob.CurrentRunStatus)"
                    Write-Message -Level Verbose -Message "Job $($currentjob.Name) last run date is $($currentjob.LastRunDate)"

                    Write-Message -Level Verbose -Message "Sleeping for $SleepPeriod ms and refreshing"
                    Start-Sleep -Milliseconds $SleepPeriod
                    $currentjob.Refresh()

                    # If it failed fast, speed up output
                    if ($lastrun -ne $currentjob.LastRunDate) {
                        $i = 600
                    }
                }

                # Wait for the job
                if (Test-Bound -ParameterName Wait) {
                    while ($currentjob.CurrentRunStatus -ne 'Idle') {
                        Write-Message -Level Output -Message "$currentjob is $($currentjob.CurrentRunStatus)"
                        Start-Sleep -Seconds $WaitPeriod
                        $currentjob.Refresh()
                    }
                    Get-DbaAgentJob -SqlInstance $server -Job $currentjob.Name
                } else {
                    Get-DbaAgentJob -SqlInstance $server -Job $currentjob.Name
                }
            }
        }
    }
}
tools\dbatools\functions\Start-DbaEndpoint.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Start-DbaEndpoint {
    <#
    .SYNOPSIS
        Starts endpoints on a SQL Server instance.

    .DESCRIPTION
        Starts endpoints on a SQL Server instance.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Endpoint
        Only start specific endpoints.

    .PARAMETER AllEndpoints
        Start all endpoints on an instance.

    .PARAMETER InputObject
        Enables piping from Get-Endpoint.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Endpoint
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Start-DbaEndpoint

    .EXAMPLE
        PS C:\> Start-DbaEndpoint -SqlInstance sqlserver2012 -AllEndpoints

        Starts all endpoints on the sqlserver2014 instance.

    .EXAMPLE
        PS C:\> Start-DbaEndpoint -SqlInstance sqlserver2012 -Endpoint endpoint1,endpoint2 -SqlCredential sqladmin

        Logs into sqlserver2012 using alternative credentials and starts the endpoint1 and endpoint2 endpoints.

    .EXAMPLE
        PS C:\> Get-Endpoint -SqlInstance sqlserver2012 -Endpoint endpoint1 | Start-DbaEndpoint

        Starts the endpoints returned from the Get-Endpoint function.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$EndPoint,
        [switch]$AllEndpoints,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Endpoint[]]$InputObject,
        [switch]$EnableException
    )

    process {
        if ((Test-Bound -ParameterName SqlInstance) -And (Test-Bound -Not -ParameterName Endpoint, AllEndpoints)) {
            Stop-Function -Message "You must specify AllEndpoints or Endpoint when using the SqlInstance parameter."
            return
        }
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaEndpoint -SqlInstance $instance -SqlCredential $SqlCredential -EndPoint $Endpoint
        }

        foreach ($ep in $InputObject) {
            try {
                if ($Pscmdlet.ShouldProcess($ep.Parent.Name, "Starting $ep")) {
                    $ep.Start()
                    $ep
                }
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
            }
        }
    }
}
tools\dbatools\functions\Start-DbaMigration.ps1
function Start-DbaMigration {
    <#
    .SYNOPSIS
        Migrates SQL Server *ALL* databases, logins, database mail profiles/accounts, credentials, SQL Agent objects, linked servers,
        Central Management Server objects, server configuration settings (sp_configure), user objects in systems databases,
        system triggers and backup devices from one SQL Server to another.

        For more granular control, please use Exclude or use the other functions available within the dbatools module.

    .DESCRIPTION
        Start-DbaMigration consolidates most of the migration tools in dbatools into one command.  This is useful when you're looking to migrate entire instances. It less flexible than using the underlying functions. Think of it as an easy button. It migrates:

        All user databases to exclude support databases such as ReportServerTempDB (Use -IncludeSupportDbs for this). Use -Exclude Databases to skip.
        All logins. Use -Exclude Logins to skip.
        All database mail objects. Use -Exclude DatabaseMail
        All credentials. Use -Exclude Credentials to skip.
        All objects within the Job Server (SQL Agent). Use -Exclude AgentServer to skip.
        All linked servers. Use -Exclude LinkedServers to skip.
        All groups and servers within Central Management Server. Use -Exclude CentralManagementServer to skip.
        All SQL Server configuration objects (everything in sp_configure). Use -Exclude SpConfigure to skip.
        All user objects in system databases. Use -Exclude SysDbUserObjects to skip.
        All system triggers. Use -Exclude SystemTriggers to skip.
        All system backup devices. Use -Exclude BackupDevices to skip.
        All Audits. Use -Exclude Audits to skip.
        All Endpoints. Use -Exclude Endpoints to skip.
        All Extended Events. Use -Exclude ExtendedEvents to skip.
        All Policy Management objects. Use -Exclude PolicyManagement to skip.
        All Resource Governor objects. Use -Exclude ResourceGovernor to skip.
        All Server Audit Specifications. Use -Exclude ServerAuditSpecifications to skip.
        All Custom Errors (User Defined Messages). Use -Exclude CustomErrors to skip.
        Copies All Data Collector collection sets. Does not configure the server. Use -Exclude DataCollector to skip.

        This script provides the ability to migrate databases using detach/copy/attach or backup/restore. SQL Server logins, including passwords, SID and database/server roles can also be migrated. In addition, job server objects can be migrated and server configuration settings can be exported or migrated. This script works with named instances, clusters and SQL Express.

        By default, databases will be migrated to the destination SQL Server's default data and log directories. You can override this by specifying -ReuseSourceFolderStructure. Filestreams and filegroups are also migrated. Safety is emphasized.

    .PARAMETER Source
        Source SQL Server.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You may specify multiple servers.

        Note that when using -BackupRestore with multiple servers, the backup will only be performed once and backups will be deleted at the end (if you didn't specify -ExcludeBackupCleanup).

        When using -DetachAttach with multiple servers, -Reattach must be specified.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER BackupRestore
        If this switch is enabled, the Copy-Only backup and restore method is used to perform database migrations. You must specify -SharedPath with a valid UNC format as well (\\server\share).

    .PARAMETER SharedPath
        Specifies the network location for the backup files. The SQL Server service accounts on both Source and Destination must have read/write permission to access this location.

    .PARAMETER WithReplace
        If this switch is enabled, databases are restored from backup using WITH REPLACE. This is useful if you want to stage some complex file paths.

    .PARAMETER ReuseSourceFolderStructure
        If this switch is enabled, the data and log directory structures on Source will be kept on Destination. Otherwise, databases will be migrated to Destination's default data and log directories.

        Consider this if you're migrating between different versions and use part of Microsoft's default SQL structure (MSSQL12.INSTANCE, etc.).

    .PARAMETER DetachAttach
        If this switch is enabled, the the detach/copy/attach method is used to perform database migrations. No files are deleted on Source. If the destination attachment fails, the source database will be reattached. File copies are performed over administrative shares (\\server\x$\mssql) using BITS. If a database is being mirrored, the mirror will be broken prior to migration.

    .PARAMETER Reattach
        If this switch is enabled, all databases are reattached to Source after a DetachAttach migration is complete.

    .PARAMETER NoRecovery
        If this switch is enabled, databases will be left in the No Recovery state to enable further backups to be added.

    .PARAMETER IncludeSupportDbs
        If this switch is enabled, the ReportServer, ReportServerTempDb, SSIDb, and distribution databases will be migrated if they exist. A logfile named $SOURCE-$DESTINATION-$date-Sqls.csv will be written to the current directory. Requires -BackupRestore or -DetachAttach.

    .PARAMETER SetSourceReadOnly
        If this switch is enabled, all migrated databases will be set to ReadOnly on the source instance prior to detach/attach & backup/restore. If -Reattach is specified, the database is set to read-only after reattaching.

    
    .PARAMETER Exclude
        Exclude one or more objects to migrate
    
        Databases
        Logins
        AgentServer
        Credentials
        LinkedServers
        SpConfigure
        CentralManagementServer
        DatabaseMail
        SysDbUserObjects
        SystemTriggers
        BackupDevices
        Audits
        Endpoints
        ExtendedEvents
        PolicyManagement
        ResourceGovernor
        ServerAuditSpecifications
        CustomErrors
        DataCollector

    .PARAMETER ExcludeSaRename
        If this switch is enabled, the sa account will not be renamed on the destination instance to match the source.

    .PARAMETER DisableJobsOnDestination
        If this switch is enabled, migrated SQL Agent jobs will be disabled on the destination instance.

    .PARAMETER DisableJobsOnSource
        If this switch is enabled, SQL Agent jobs will be disabled on the source instance.

    .PARAMETER UseLastBackup
        Use the last full, diff and logs instead of performing backups. Note that the backups must exist in a location accessible by all destination servers, such a network share.

    .PARAMETER Continue
        If specified, will to attempt to restore transaction log backups on top of existing database(s) in Recovering or Standby states. Only usable with -UseLastBackup

    .PARAMETER Force
        If migrating users, forces drop and recreate of SQL and Windows logins.
        If migrating databases, deletes existing databases with matching names.
        If using -DetachAttach, -Force will break mirrors and drop dbs from Availability Groups.

        For other migration objects, it will just drop existing items and readd, if -force is supported within the underlying function.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Start-DbaMigration

    .EXAMPLE
        PS C:\> Start-DbaMigration -Source sqlserver\instance -Destination sqlcluster -DetachAttach

        All databases, logins, job objects and sp_configure options will be migrated from sqlserver\instance to sqlcluster. Databases will be migrated using the detach/copy files/attach method. Dbowner will be updated. User passwords, SIDs, database roles and server roles will be migrated along with the login.

    .EXAMPLE
        PS C:\> $params = @{
        >> Source = "sqlcluster"
        >> Destination = "sql2016"
        >> SourceSqlCredential = $scred
        >> DestinationSqlCredential = $cred
        >> SharedPath = "\\fileserver\share\sqlbackups\Migration"
        >> BackupRestore = $true
        >> ReuseSourceFolderStructure = $true
        >> Force = $true
        >> }
        >>
        PS C:\> Start-DbaMigration @params -Verbose

        Utilizes splatting technique to set all the needed parameters. This will migrate databases using the backup/restore method. It will also include migration of the logins, database mail configuration, credentials, SQL Agent, Central Management Server, and SQL Server global configuration.

    .EXAMPLE
        PS C:\> Start-DbaMigration -Verbose -Source sqlcluster -Destination sql2016 -DetachAttach -Reattach -SetSourceReadonly

        Migrates databases using detach/copy/attach. Reattach at source and set source databases read-only. Also migrates everything else.

    .EXAMPLE
        PS C:\> $PSDefaultParameters = @{
        >> "dbatools:Source" = "sqlcluster"
        >> "dbatools:Destination" = "sql2016"
        >> }
        >>
        PS C:\> Start-DbaMigration -Verbose -Exclude Databases, Logins

        Utilizes the PSDefaultParameterValues system variable, and sets the Source and Destination parameters for any function in the module that has those parameter names. This prevents the need from passing them in constantly.
        The execution of the function will migrate everything but logins and databases.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [DbaInstanceParameter]$Source,
        [DbaInstanceParameter[]]$Destination,
        [switch]$DetachAttach,
        [switch]$Reattach,
        [switch]$BackupRestore,
        [Alias("NetworkShare")]
        [parameter(HelpMessage = "Specify a valid network share in the format \\server\share that can be accessed by your account and both Sql Server service accounts.")]
        [string]$SharedPath,
        [switch]$WithReplace,
        [switch]$NoRecovery,
        [switch]$SetSourceReadOnly,
        [switch]$ReuseSourceFolderStructure,
        [switch]$IncludeSupportDbs,
        [PSCredential]$SourceSqlCredential,
        [PSCredential]$DestinationSqlCredential,
        [ValidateSet('Databases', 'Logins', 'AgentServer', 'Credentials', 'LinkedServers', 'SpConfigure', 'CentralManagementServer', 'DatabaseMail', 'SysDbUserObjects', 'SystemTriggers', 'BackupDevices', 'Audits', 'Endpoints', 'ExtendedEvents', 'PolicyManagement', 'ResourceGovernor', 'ServerAuditSpecifications', 'CustomErrors', 'DataCollector')]
        [string[]]$Exclude,
        [switch]$DisableJobsOnDestination,
        [switch]$DisableJobsOnSource,
        [switch]$ExcludeSaRename,
        [switch]$UseLastBackup,
        [switch]$Continue,
        [switch]$Force,
        [switch]$EnableException
    )
    
    begin {
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter NetworkShare -CustomMessage "Using the parameter NetworkShare is deprecated. This parameter will be removed in version 1.0.0 or before. Use SharedPath instead."
        
        if ($Exclude -notcontains "Databases") {
            if (-not $BackupRestore -and -not $DetachAttach -and -not $UseLastBackup) {
                Stop-Function -Message "You must specify a database migration method (-BackupRestore or -DetachAttach) or -Exclude Databases"
                return
            }
        }

        if ($DetachAttach -and ($BackupRestore -or $UseLastBackup)) {
            Stop-Function -Message "-DetachAttach cannot be used with -BackupRestore or -UseLastBackup"
            return
        }
        if ($BackupRestore -and (-not $SharedPath -and -not $UseLastBackup)) {
            Stop-Function -Message "When using -BackupRestore, you must specify -SharedPath or -UseLastBackup"
            return
        }
        if ($SharedPath -and $UseLastBackup) {
            Stop-Function -Message "-SharedPath cannot be used with -UseLastBackup because the backup path is determined by the paths in the last backups"
            return
        }
        if ($DetachAttach -and -not $Reattach -and $Destination.Count -gt 1) {
            Stop-Function -Message "When using -DetachAttach with multiple servers, you must specify -Reattach to reattach database at source"
            return
        }
        if ($Continue -and -not $UseLastBackup) {
            Stop-Function -Message "-Continue cannot be used without -UseLastBackup"
            return
        }
        if ($UseLastBackup -and -not $BackupRestore) {
            $BackupRestore = $true
        }
        
        $elapsed = [System.Diagnostics.Stopwatch]::StartNew()
        $started = Get-Date
        $sourceserver = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential
    }

    process {
        if (Test-FunctionInterrupt) { return }

        # testing twice for whatif reasons
        if ($Exclude -notcontains "Databases") {
            if (-not $BackupRestore -and -not $DetachAttach -and -not $UseLastBackup) {
                Stop-Function -Message "You must specify a database migration method (-BackupRestore or -DetachAttach) or -Exclude Databases"
                return
            }
        }

        if ($DetachAttach -and ($BackupRestore -or $UseLastBackup)) {
            Stop-Function -Message "-DetachAttach cannot be used with -BackupRestore or -UseLastBackup"
            return
        }
        if ($BackupRestore -and (-not $SharedPath -and -not $UseLastBackup)) {
            Stop-Function -Message "When using -BackupRestore, you must specify -SharedPath or -UseLastBackup"
            return
        }
        if ($SharedPath -and $UseLastBackup) {
            Stop-Function -Message "-SharedPath cannot be used with -UseLastBackup because the backup path is determined by the paths in the last backups"
            return
        }
        if ($DetachAttach -and -not $Reattach -and $Destination.Count -gt 1) {
            Stop-Function -Message "When using -DetachAttach with multiple servers, you must specify -Reattach to reattach database at source"
            return
        }
        if ($Continue -and -not $UseLastBackup) {
            Stop-Function -Message "-Continue cannot be used without -UseLastBackup"
            return
        }
        if ($UseLastBackup -and -not $BackupRestore) {
            $BackupRestore = $true
        }
        if ($Exclude -notcontains 'SpConfigure') {
            Write-Message -Level Verbose -Message "Migrating SQL Server Configuration"
            Copy-DbaSpConfigure -Source $sourceserver -Destination $Destination -DestinationSqlCredential $DestinationSqlCredential
        }

        if ($Exclude -notcontains 'CustomErrors') {
            Write-Message -Level Verbose -Message "Migrating custom errors (user defined messages)"
            Copy-DbaCustomError -Source $sourceserver -Destination $Destination -DestinationSqlCredential $DestinationSqlCredential -Force:$Force
        }

        if ($Exclude -notcontains 'Credentials') {
            Write-Message -Level Verbose -Message "Migrating SQL credentials"
            Copy-DbaCredential -Source $sourceserver -Destination $Destination -DestinationSqlCredential $DestinationSqlCredential -Force:$Force
        }

        if ($Exclude -notcontains 'DatabaseMail') {
            Write-Message -Level Verbose -Message "Migrating database mail"
            Copy-DbaDbMail -Source $sourceserver -Destination $Destination -DestinationSqlCredential $DestinationSqlCredential -Force:$Force
        }

        if ($Exclude -notcontains 'CentralManagementServer') {
            Write-Message -Level Verbose -Message "Migrating Central Management Server"
            Copy-DbaCmsRegServer -Source $sourceserver -Destination $Destination -DestinationSqlCredential $DestinationSqlCredential -Force:$Force
        }

        if ($Exclude -notcontains 'BackupDevices') {
            Write-Message -Level Verbose -Message "Migrating Backup Devices"
            Copy-DbaBackupDevice -Source $sourceserver -Destination $Destination -DestinationSqlCredential $DestinationSqlCredential -Force:$Force
        }

        if ($Exclude -notcontains 'SystemTriggers') {
            Write-Message -Level Verbose -Message "Migrating System Triggers"
            Copy-DbaServerTrigger -Source $sourceserver -Destination $Destination -DestinationSqlCredential $DestinationSqlCredential -Force:$Force
        }

        if ($Exclude -notcontains 'Databases') {
            # Do it
            Write-Message -Level Verbose -Message "Migrating databases"
            if ($BackupRestore) {
                if ($UseLastBackup) {
                    Copy-DbaDatabase -Source $sourceserver -Destination $Destination -DestinationSqlCredential $DestinationSqlCredential -AllDatabases -SetSourceReadOnly:$SetSourceReadOnly -ReuseSourceFolderStructure:$ReuseSourceFolderStructure -BackupRestore -Force:$Force -NoRecovery:$NoRecovery -WithReplace:$WithReplace -IncludeSupportDbs:$IncludeSupportDbs -UseLastBackup:$UseLastBackup -Continue:$Continue
                } else {
                    Copy-DbaDatabase -Source $sourceserver -Destination $Destination -DestinationSqlCredential $DestinationSqlCredential -AllDatabases -SetSourceReadOnly:$SetSourceReadOnly -ReuseSourceFolderStructure:$ReuseSourceFolderStructure -BackupRestore -SharedPath $SharedPath -Force:$Force -NoRecovery:$NoRecovery -WithReplace:$WithReplace -IncludeSupportDbs:$IncludeSupportDbs
                }
            } else {
                Copy-DbaDatabase -Source $sourceserver -Destination $Destination -DestinationSqlCredential $DestinationSqlCredential -AllDatabases -SetSourceReadOnly:$SetSourceReadOnly -ReuseSourceFolderStructure:$ReuseSourceFolderStructure -DetachAttach:$DetachAttach -Reattach:$Reattach -Force:$Force -IncludeSupportDbs:$IncludeSupportDbs
            }
        }

        if ($Exclude -notcontains 'Logins') {
            Write-Message -Level Verbose -Message "Migrating logins"
            $syncit = $ExcludeSaRename -eq $false
            Copy-DbaLogin -Source $sourceserver -Destination $Destination -DestinationSqlCredential $DestinationSqlCredential -Force:$Force -SyncSaName:$syncit
        }

        if ($Exclude -notcontains 'Logins' -and $Exclude -notcontains 'Databases' -and -not $NoRecovery) {
            Write-Message -Level Verbose -Message "Updating database owners to match newly migrated logins"
            foreach ($dest in $Destination) {
                $null = Update-SqlDbOwner -Source $sourceserver -Destination $dest -DestinationSqlCredential $DestinationSqlCredential
            }
        }
        
        if ($Exclude -notcontains 'LinkedServers') {
            Write-Message -Level Verbose -Message "Migrating linked servers"
            Copy-DbaLinkedServer -Source $sourceserver -Destination $Destination -DestinationSqlCredential $DestinationSqlCredential -Force:$Force
        }
        
        if ($Exclude -notcontains 'DataCollector') {
            Write-Message -Level Verbose -Message "Migrating Data Collector collection sets"
            Copy-DbaDataCollector -Source $sourceserver -Destination $Destination -DestinationSqlCredential $DestinationSqlCredential -Force:$Force
        }

        if ($Exclude -notcontains 'Audits') {
            Write-Message -Level Verbose -Message "Migrating Audits"
            Copy-DbaServerAudit -Source $sourceserver -Destination $Destination -DestinationSqlCredential $DestinationSqlCredential -Force:$Force
        }

        if ($Exclude -notcontains 'ServerAuditSpecifications') {
            Write-Message -Level Verbose -Message "Migrating Server Audit Specifications"
            Copy-DbaServerAuditSpecification -Source $sourceserver -Destination $Destination -DestinationSqlCredential $DestinationSqlCredential -Force:$Force
        }

        if ($Exclude -notcontains 'Endpoints') {
            Write-Message -Level Verbose -Message "Migrating Endpoints"
            Copy-DbaEndpoint -Source $sourceserver -Destination $Destination -DestinationSqlCredential $DestinationSqlCredential -Force:$Force
        }

        if ($Exclude -notcontains 'PolicyManagement') {
            Write-Message -Level Verbose -Message "Migrating Policy Management"
            Copy-DbaPolicyManagement -Source $sourceserver -Destination $Destination -DestinationSqlCredential $DestinationSqlCredential -Force:$Force
        }

        if ($Exclude -notcontains 'ResourceGovernor') {
            Write-Message -Level Verbose -Message "Migrating Resource Governor"
            Copy-DbaResourceGovernor -Source $sourceserver -Destination $Destination -DestinationSqlCredential $DestinationSqlCredential -Force:$Force
        }

        if ($Exclude -notcontains 'SysDbUserObjects') {
            Write-Message -Level Verbose -Message "Migrating user objects in system databases (this can take a second)."
            If ($Pscmdlet.ShouldProcess($destination, "Copying user objects.")) {
                Copy-DbaSysDbUserObject -Source $sourceserver -Destination $Destination -DestinationSqlCredential $DestinationSqlCredential -Force:$force
            }
        }

        if ($Exclude -notcontains 'ExtendedEvents') {
            Write-Message -Level Verbose -Message "Migrating Extended Events"
            Copy-DbaXESession -Source $sourceserver -Destination $Destination -DestinationSqlCredential $DestinationSqlCredential -Force:$Force
        }

        if ($Exclude -notcontains 'AgentServer') {
            Write-Message -Level Verbose -Message "Migrating job server"
            Copy-DbaAgentServer -Source $sourceserver -Destination $Destination -DestinationSqlCredential $DestinationSqlCredential -DisableJobsOnDestination:$DisableJobsOnDestination -DisableJobsOnSource:$DisableJobsOnSource -Force:$Force
        }
    }
    end {
        if (Test-FunctionInterrupt) { return }
        $totaltime = ($elapsed.Elapsed.toString().Split(".")[0])
        Write-Message -Level Verbose -Message "SQL Server migration complete."
        Write-Message -Level Verbose -Message "Migration started: $started"
        Write-Message -Level Verbose -Message "Migration completed: $(Get-Date)"
        Write-Message -Level Verbose -Message "Total Elapsed time: $totaltime"
    }
}
tools\dbatools\functions\Start-DbaPfDataCollectorSet.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Start-DbaPfDataCollectorSet {
    <#
    .SYNOPSIS
        Starts Performance Monitor Data Collector Set.

    .DESCRIPTION
        Starts Performance Monitor Data Collector Set.

    .PARAMETER ComputerName
        The target computer. Defaults to localhost.

    .PARAMETER Credential
        Allows you to login to $ComputerName using alternative credentials. To use:

        $cred = Get-Credential, then pass $cred object to the -Credential parameter.

    .PARAMETER CollectorSet
        The name of the Collector Set to start.

    .PARAMETER NoWait
        If this switch is enabled, the collector is started and the results are returned immediately.

    .PARAMETER InputObject
        Accepts the object output by Get-DbaPfDataCollectorSet via the pipeline.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: PerfMon
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Start-DbaPfDataCollectorSet

    .EXAMPLE
        PS C:\> Start-DbaPfDataCollectorSet

        Attempts to start all ready Collectors on localhost.

    .EXAMPLE
        PS C:\> Start-DbaPfDataCollectorSet -ComputerName sql2017

        Attempts to start all ready Collectors on localhost.

    .EXAMPLE
        PS C:\> Start-DbaPfDataCollectorSet -ComputerName sql2017, sql2016 -Credential ad\sqldba -CollectorSet 'System Correlation'

        Starts the 'System Correlation' Collector on sql2017 and sql2016 using alternative credentials.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorSet -CollectorSet 'System Correlation' | Start-DbaPfDataCollectorSet

        Starts the 'System Correlation' Collector.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [DbaInstance[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [Alias("DataCollectorSet")]
        [string[]]$CollectorSet,
        [parameter(ValueFromPipeline)]
        [object[]]$InputObject,
        [switch]$NoWait,
        [switch]$EnableException
    )
    begin {
        $wait = $NoWait -eq $false

        $setscript = {
            $setname = $args[0]; $wait = $args[1]
            $collectorset = New-Object -ComObject Pla.DataCollectorSet
            $collectorset.Query($setname, $null)
            $null = $collectorset.Start($wait)
        }
    }
    process {
        
        
        if (-not $InputObject -or ($InputObject -and (Test-Bound -ParameterName ComputerName))) {
            foreach ($computer in $ComputerName) {
                $InputObject += Get-DbaPfDataCollectorSet -ComputerName $computer -Credential $Credential -CollectorSet $CollectorSet
            }
        }

        if ($InputObject) {
            if (-not $InputObject.DataCollectorSetObject) {
                Stop-Function -Message "InputObject is not of the right type. Please use Get-DbaPfDataCollectorSet."
                return
            }
        }

        # Check to see if its running first
        foreach ($set in $InputObject) {
            $setname = $set.Name
            $computer = $set.ComputerName
            $status = $set.State
            Write-Message -Level Verbose -Message "$setname on $ComputerName is $status."
            if ($Pscmdlet.ShouldProcess($computer, "Starting Performance Monitor collection set")) {
                if ($status -eq "Running") {
                    Stop-Function -Message "$setname on $computer is already running." -Continue
                }
                if ($status -eq "Disabled") {
                    Stop-Function -Message "$setname on $computer is disabled." -Continue
                }
                try {
                    Invoke-Command2 -ComputerName $computer -Credential $Credential -ScriptBlock $setscript -ArgumentList $setname, $wait -ErrorAction Stop
                } catch {
                    Stop-Function -Message "Failure starting $setname on $computer." -ErrorRecord $_ -Target $computer -Continue
                }

                Get-DbaPfDataCollectorSet -ComputerName $computer -Credential $Credential -CollectorSet $setname
            }
        }
    }
}
tools\dbatools\functions\Start-DbaService.ps1
function Start-DbaService {
    <#
    .SYNOPSIS
        Starts SQL Server services on a computer.

    .DESCRIPTION
        Starts the SQL Server related services on one or more computers. Will follow SQL Server service dependencies.

        Requires Local Admin rights on destination computer(s).

    .PARAMETER ComputerName
        The target SQL Server instance or instances.

    .PARAMETER InstanceName
        Only affects services that belong to the specific instances.

    .PARAMETER Credential
        Credential object used to connect to the computer as a different user.

    .PARAMETER Type
        Use -Type to collect only services of the desired SqlServiceType.
        Can be one of the following: "Agent","Browser","Engine","FullText","SSAS","SSIS","SSRS"

    .PARAMETER Timeout
        How long to wait for the start/stop request completion before moving on. Specify 0 to wait indefinitely.

    .PARAMETER InputObject
        A collection of services from Get-DbaService

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER WhatIf
        Shows what would happen if the cmdlet runs. The cmdlet is not run.

    .PARAMETER Confirm
        Prompts you for confirmation before running the cmdlet.

    .NOTES
        Tags: Service, SqlServer, Instance, Connect
        Author: Kirill Kravtsov (@nvarscar)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires Local Admin rights on destination computer(s).

    .LINK
        https://dbatools.io/Start-DbaService

    .EXAMPLE
        PS C:\> Start-DbaService -ComputerName sqlserver2014a

        Starts the SQL Server related services on computer sqlserver2014a.

    .EXAMPLE
        PS C:\> 'sql1','sql2','sql3'| Get-DbaService | Start-DbaService

        Gets the SQL Server related services on computers sql1, sql2 and sql3 and starts them.

    .EXAMPLE
        PS C:\> Start-DbaService -ComputerName sql1,sql2 -Instance MSSQLSERVER

        Starts the SQL Server services related to the default instance MSSQLSERVER on computers sql1 and sql2.

    .EXAMPLE
        PS C:\> Start-DbaService -ComputerName $MyServers -Type SSRS

        Starts the SQL Server related services of type "SSRS" (Reporting Services) on computers in the variable MyServers.

    #>
    [CmdletBinding(DefaultParameterSetName = "Server", SupportsShouldProcess)]
    param (
        [Parameter(ParameterSetName = "Server", Position = 1)]
        [Alias("cn", "host", "Server")]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [Alias("Instance")]
        [string[]]$InstanceName,
        [ValidateSet("Agent", "Browser", "Engine", "FullText", "SSAS", "SSIS", "SSRS")]
        [string[]]$Type,
        [parameter(ValueFromPipeline, Mandatory, ParameterSetName = "Service")]
        [Alias("ServiceCollection")]
        [object[]]$InputObject,
        [int]$Timeout = 60,
        [PSCredential]$Credential,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        $processArray = @()
        if ($PsCmdlet.ParameterSetName -eq "Server") {
            $serviceParams = @{ ComputerName = $ComputerName }
            if ($InstanceName) { $serviceParams.InstanceName = $InstanceName }
            if ($Type) { $serviceParams.Type = $Type }
            if ($Credential) { $serviceParams.Credential = $Credential }
            if ($EnableException) { $serviceParams.EnableException = $EnableException }
            $InputObject = Get-DbaService @serviceParams
        }
    }
    process {
        #Get all the objects from the pipeline before proceeding
        $processArray += $InputObject
    }
    end {
        $processArray = $processArray | Where-Object { (!$InstanceName -or $_.InstanceName -in $InstanceName) -and (!$Type -or $_.ServiceType -in $Type) }
        if ($PSCmdlet.ShouldProcess("$ProcessArray", "Starting Service")) {
            if ($processArray) {
                Update-ServiceStatus -InputObject $processArray -Action 'start' -Timeout $Timeout -EnableException $EnableException
            } else {
                Stop-Function -EnableException $EnableException -Message "No SQL Server services found with current parameters." -Category ObjectNotFound
            }
        }
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Start-DbaSqlService
    }
}
tools\dbatools\functions\Start-DbaTrace.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Start-DbaTrace {
    <#
    .SYNOPSIS
        Starts SQL Server traces

    .DESCRIPTION
        Starts SQL Server traces

    .PARAMETER SqlInstance
        The target SQL Server instance

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Id
        A list of trace ids

    .PARAMETER InputObject
        Internal parameter for piping

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Security, Trace
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Start-DbaTrace -SqlInstance sql2008

        Starts all traces on sql2008

    .EXAMPLE
        PS C:\> Start-DbaTrace -SqlInstance sql2008 -Id 1

        Starts all trace with ID 1 on sql2008

    .EXAMPLE
        PS C:\> Get-DbaTrace -SqlInstance sql2008 | Out-GridView -PassThru | Start-DbaTrace

        Starts selected traces on sql2008

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [int[]]$Id,
        [parameter(ValueFromPipeline)]
        [object[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if (-not $InputObject -and $SqlInstance) {
            $InputObject = Get-DbaTrace -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Id $Id
        }

        foreach ($trace in $InputObject) {
            if (-not $trace.id -and -not $trace.Parent) {
                Stop-Function -Message "Input is of the wrong type. Use Get-DbaTrace." -Continue
                return
            }

            $server = $trace.Parent
            $traceid = $trace.id
            $default = Get-DbaTrace -SqlInstance $server -Default

            if ($default.id -eq $traceid) {
                Stop-Function -Message "The default trace on $server cannot be started. Use Set-DbaSpConfigure to turn it on." -Continue
            }

            $sql = "sp_trace_setstatus $traceid, 1"
            if ($Pscmdlet.ShouldProcess($traceid, "Starting the TraceID on $server")) {
                try {
                    $server.Query($sql)
                    Get-DbaTrace -SqlInstance $server -Id $traceid
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target $server -Continue
                    return
                }
            }
        }
    }
}
tools\dbatools\functions\Start-DbaXESession.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Start-DbaXESession {
    <#
    .SYNOPSIS
        Starts Extended Events sessions.

    .DESCRIPTION
        This script starts Extended Events sessions on a SQL Server instance.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Session
        Only start specific Extended Events sessions.

    .PARAMETER AllSessions
        Start all Extended Events sessions on an instance, ignoring the packaged sessions: AlwaysOn_health, system_health, telemetry_xevents.

    .PARAMETER InputObject
        Internal parameter to support piping from Get-DbaXESession

    .PARAMETER StopAt
        Specifies a datetime at which the session will be stopped. This is done via a self-deleting schedule.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Doug Meyers

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Start-DbaXESession

    .EXAMPLE
        PS C:\> Start-DbaXESession -SqlInstance sqlserver2012 -AllSessions

        Starts all Extended Event Session on the sqlserver2014 instance.

    .EXAMPLE
        PS C:\> Start-DbaXESession -SqlInstance sqlserver2012 -Session xesession1,xesession2

        Starts the xesession1 and xesession2 Extended Event sessions.

    .EXAMPLE
        PS C:\> Start-DbaXESession -SqlInstance sqlserver2012 -Session xesession1,xesession2 -StopAt (Get-Date).AddMinutes(30)

        Starts the xesession1 and xesession2 Extended Event sessions and stops them in 30 minutes.

    .EXAMPLE
        PS C:\> Get-DbaXESession -SqlInstance sqlserver2012 -Session xesession1 | Start-DbaXESession

        Starts the sessions returned from the Get-DbaXESession function.

    #>
    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'Session')]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification = "Internal functions are ignored")]
    param (
        [parameter(Position = 1, Mandatory, ParameterSetName = 'Session')]
        [parameter(Position = 1, Mandatory, ParameterSetName = 'All')]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [parameter(ParameterSetName = 'Session')]
        [parameter(ParameterSetName = 'All')]
        [PSCredential]$SqlCredential,
        [parameter(Mandatory, ParameterSetName = 'Session')]
        [Alias("Sessions")]
        [object[]]$Session,
        [datetime]$StopAt,
        [parameter(Mandatory, ParameterSetName = 'All')]
        [switch]$AllSessions,
        [parameter(Mandatory, ValueFromPipeline, ParameterSetName = 'Object')]
        [Microsoft.SqlServer.Management.XEvent.Session[]]$InputObject,
        [switch]$EnableException
    )

    begin {
        # Start each XESession
        function Start-XESessions {
            [CmdletBinding(SupportsShouldProcess)]
            param ([Microsoft.SqlServer.Management.XEvent.Session[]]$xeSessions)

            foreach ($xe in $xeSessions) {
                $instance = $xe.Parent.Name
                $session = $xe.Name

                if (-Not $xe.isRunning) {
                    Write-Message -Level Verbose -Message "Starting XEvent Session $session on $instance."
                    if ($Pscmdlet.ShouldProcess("$instance", "Starting XEvent Session $session")) {
                        try {
                            $xe.Start()
                        } catch {
                            Stop-Function -Message "Could not start XEvent Session on $instance." -Target $session -ErrorRecord $_ -Continue
                        }
                    }
                } else {
                    Write-Message -Level Warning -Message "$session on $instance is already running."
                }
                Get-DbaXESession -SqlInstance $xe.Parent -Session $session
            }
        }

        function New-StopJob {
            [CmdletBinding(SupportsShouldProcess)]
            param (
                [Microsoft.SqlServer.Management.XEvent.Session[]]$xeSessions,
                [datetime]$StopAt
            )

            foreach ($xe in $xeSessions) {
                $server = $xe.Parent
                $session = $xe.Name
                $name = "XE Session Stop - $session"
                if ($Pscmdlet.ShouldProcess("$Server", "Making New XEvent StopJob for $session")) {
                    # Setup the schedule time
                    $time = $(($StopAt).ToString("HHmmss"))

                    # Create the schedule
                    $schedule = New-DbaAgentSchedule -SqlInstance $server -Schedule $name -FrequencyType Once -StartTime $time -Force

                    # Create the job and attach the schedule
                    $job = New-DbaAgentJob -SqlInstance $server -Job $name -Schedule $schedule -DeleteLevel Always -Force

                    # Create the job step
                    $sql = "ALTER EVENT SESSION [$session] ON SERVER STATE = stop;"
                    #Variable $jobstep marked as unused by PSScriptAnalyzer replace with $null to catch output
                    $null = New-DbaAgentJobStep -SqlInstance $server -Job $job -StepName 'T-SQL Stop' -Subsystem TransactSql -Command $sql -Force
                }
            }
        }
    }
    process {
        if ($InputObject) {
            Start-XESessions $InputObject
        } else {
            foreach ($instance in $SqlInstance) {
                $xeSessions = Get-DbaXESession -SqlInstance $instance -SqlCredential $SqlCredential

                # Filter xeSessions based on parameters
                if ($Session) {
                    $xeSessions = $xeSessions | Where-Object { $_.Name -in $Session }
                } elseif ($AllSessions) {
                    $systemSessions = @('AlwaysOn_health', 'system_health', 'telemetry_xevents')
                    $xeSessions = $xeSessions | Where-Object { $_.Name -notin $systemSessions }
                }

                if ($Pscmdlet.ShouldProcess("$instance", "Configuring XEvent Session $session to start")) {
                    Start-XESessions $xeSessions

                    if ($StopAt) {
                        New-StopJob -xeSessions $xeSessions -StopAt $stopat
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Start-DbaXESmartTarget.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Start-DbaXESmartTarget {
    <#
    .SYNOPSIS
        XESmartTarget runs as a client application for an Extended Events session running on a SQL Server instance.

    .DESCRIPTION
        XESmartTarget offers the ability to set up complex actions in response to Extended Events captured in sessions, without writing a single line of code.

        See more at https://github.com/spaghettidba/XESmartTarget/wiki

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Session
        Name of the Extended Events session to attach to.

        You can monitor a single session with an instance of XESmartTarget. In case you need to perform action on multiple sessions, run an additional instance of XESmartTarget, with its own configuration file.

    .PARAMETER Database
        Specifies the name of the database that contains the target table.

    .PARAMETER FailOnProcessingError
        If this switch is enabled, the a processing error will trigger a failure.

    .PARAMETER Responder
        The list of responses can include zero or more Response objects, each to be configured by specifying values for their public members.

    .PARAMETER Template
        Path to the dbatools built-in templates

    .PARAMETER NotAsJob
        If this switch is enabled, output will be sent to screen indefinitely. BY default, a job will be run in the background.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl) | SmartTarget by Gianluca Sartori (@spaghettidba)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Start-DbaXESmartTarget

    .EXAMPLE
        PS C:\>$response = New-DbaXESmartQueryExec -SqlInstance sql2017 -Database dbadb -Query "update table set whatever = 1"
        PS C:\>Start-DbaXESmartTarget -SqlInstance sql2017 -Session deadlock_tracker -Responder $response

        Executes a T-SQL command against dbadb on sql2017 whenever a deadlock event is recorded.

    .EXAMPLE
        PS C:\>$response = New-DbaXESmartQueryExec -SqlInstance sql2017 -Database dbadb -Query "update table set whatever = 1"
        PS C:\>$params = @{
        >> SmtpServer = "smtp.ad.local"
        >> To = "[email protected]"
        >> Sender = "[email protected]"
        >> Subject = "Query executed"
        >> Body = "Query executed at {collection_time}"
        >> Attachment = "batch_text"
        >> AttachmentFileName = "query.sql"
        >> }
        PS C:\> $emailresponse = New-DbaXESmartEmail @params
        PS C:\> Start-DbaXESmartTarget -SqlInstance sql2017 -Session querytracker -Responder $response, $emailresponse

        Executes a T-SQL command against dbadb on sql2017 and sends an email whenever a querytracker event is recorded.

    .EXAMPLE
        PS C:\> $columns = "cpu_time", "duration", "physical_reads", "logical_reads", "writes", "row_count", "batch_text"
        PS C:\> $response = New-DbaXESmartTableWriter -SqlInstance sql2017 -Database dbadb -Table deadlocktracker -OutputColumns $columns -Filter "duration > 10000"
        PS C:\> Start-DbaXESmartTarget -SqlInstance sql2017 -Session deadlock_tracker -Responder $response

        Writes Extended Events to the deadlocktracker table in dbadb on sql2017.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$Database,
        [parameter(Mandatory)]
        [string]$Session,
        [switch]$FailOnProcessingError,
        [object[]]$Responder,
        [string[]]$Template,
        [switch]$NotAsJob,
        [switch]$EnableException
    )
    begin {
        function Start-SmartFunction {
            [CmdletBinding(SupportsShouldProcess)]
            param (
                [parameter(Mandatory, ValueFromPipeline)]
                [Alias("ServerInstance", "SqlServer")]
                [DbaInstanceParameter[]]$SqlInstance,
                [PSCredential]$SqlCredential,
                [string]$Database,
                [parameter(Mandatory)]
                [string]$Session,
                [switch]$FailOnProcessingError,
                [object[]]$Responder,
                [string[]]$Template,
                [switch]$NotAsJob,
                [switch]$EnableException
            )
            begin {
                try {
                    Add-Type -Path "$script:PSModuleRoot\bin\XESmartTarget\XESmartTarget.Core.dll" -ErrorAction Stop
                } catch {
                    Stop-Function -Message "Could not load XESmartTarget.Core.dll" -ErrorRecord $_ -Target "XESmartTarget"
                    return
                }
            }
            process {
                if (Test-FunctionInterrupt) { return }

                foreach ($instance in $SqlInstance) {
                    try {
                        $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 11
                    } catch {
                        Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                    }

                    $target = New-Object -TypeName XESmartTarget.Core.Target
                    $target.ServerName = $instance
                    $target.SessionName = $Session
                    $target.FailOnProcessingError = $FailOnProcessingError

                    if ($SqlCredential) {
                        $target.UserName = $SqlCredential.UserName
                        $target.Password = $SqlCredential.GetNetworkCredential().Password
                    }

                    foreach ($response in $Responder) {
                        $target.Responses.Add($response)
                    }

                    if ($Pscmdlet.ShouldProcess("$instance", "Starting SmartTarget on $($server.name)")) {
                        try {
                            $target.Start()
                        } catch {
                            $message = $_.Exception.InnerException.InnerException | Out-String

                            if ($message) {
                                Stop-Function -Message $message -Target "XESmartTarget" -Continue
                            } else {
                                Stop-Function -Message "Failure" -Target "XESmartTarget" -ErrorRecord $_ -Continue
                            }
                        }
                    }
                }
            }
        }
    }
    process {
        foreach ($instance in $SqlInstance) {
            if (-not ($xesession = Get-DbaXESession -SqlInstance $instance -SqlCredential $SqlCredential -Session $Session)) {
                Stop-Function -Message "Session $Session does not exist on $instance."
                return
            }
            if ($xesession.Status -ne "Running") {
                Stop-Function -Message "Session $Session on $instance is not running."
                return
            }
        }
        if ($Pscmdlet.ShouldProcess("$instance", "Configuring SmartTarget to start")) {
            if ($NotAsJob) {
                Start-SmartFunction @PSBoundParameters
            } else {
                $date = (Get-Date -UFormat "%H%M%S") #"%m%d%Y%H%M%S"
                Start-Job -Name "XESmartTarget-$session-$date" -ArgumentList $PSBoundParameters, $script:PSModuleRoot -ScriptBlock {
                    param (
                        $Parameters,
                        $ModulePath
                    )
                    Import-Module "$ModulePath\dbatools.psd1"
                    Add-Type -Path "$ModulePath\bin\XESmartTarget\XESmartTarget.Core.dll" -ErrorAction Stop
                    $params = @{
                        SqlInstance = $Parameters.SqlInstance.InputObject
                        Database    = $Parameters.Database
                        Session     = $Parameters.Session
                        Responder   = @()
                    }
                    if ($Parameters.SqlCredential) {
                        $params["SqlCredential"] = $Parameters.SqlCredential
                    }
                    foreach ($responder in $Parameters.Responder) {
                        $typename = $responder.PSObject.TypeNames[0] -replace "^Deserialized\.", ""
                        $newResponder = New-Object -TypeName $typename
                        foreach ($property in $responder.PSObject.Properties) {
                            if ($property.Value) {
                                if ($property.Value -is [Array]) {
                                    $name = $property.Name
                                    $newResponder.$name = [object[]]$property.Value
                                } else {
                                    $name = $property.Name
                                    $newResponder.$name = $property.Value
                                }
                            }

                        }
                        $params["Responder"] += $newResponder
                    }

                    Start-DbaXESmartTarget @params -NotAsJob -FailOnProcessingError
                } | Select-Object -Property ID, Name, State
            }
        }
    }
}
tools\dbatools\functions\Stop-DbaAgentJob.ps1
function Stop-DbaAgentJob {
    <#
    .SYNOPSIS
        Stops a running SQL Server Agent Job.

    .DESCRIPTION
        This command stops a job then returns connected SMO object for SQL Agent Job information for each instance(s) of SQL Server.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Job
        The job(s) to process - this list is auto-populated from the server. If unspecified, all jobs will be processed.

    .PARAMETER ExcludeJob
        The job(s) to exclude - this list is auto-populated from the server.

    .PARAMETER Wait
        Wait for output until the job has completely stopped

    .PARAMETER InputObject
        Internal parameter that enables piping

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Job, Agent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Stop-DbaAgentJob

    .EXAMPLE
        PS C:\> Stop-DbaAgentJob -SqlInstance localhost

        Stops all running SQL Agent Jobs on the local SQL Server instance

    .EXAMPLE
        PS C:\> Get-DbaAgentJob -SqlInstance sql2016 -Job cdc.DBWithCDC_capture | Stop-DbaAgentJob

        Stops the cdc.DBWithCDC_capture SQL Agent Job on sql2016

    .EXAMPLE
        PS C:\> Stop-DbaAgentJob -SqlInstance sql2016 -Job cdc.DBWithCDC_capture

        Stops the cdc.DBWithCDC_capture SQL Agent Job on sql2016

    #>
    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = "Default")]
    param (
        [parameter(Mandatory, ParameterSetName = "Instance")]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Job,
        [string[]]$ExcludeJob,
        [parameter(Mandatory, ValueFromPipeline, ParameterSetName = "Object")]
        [Microsoft.SqlServer.Management.Smo.Agent.Job[]]$InputObject,
        [switch]$Wait,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $InputObject += $server.JobServer.Jobs

            if ($Job) {
                $InputObject = $InputObject | Where-Object Name -In $Job
            }
            if ($ExcludeJob) {
                $InputObject = $InputObject | Where-Object Name -NotIn $ExcludeJob
            }
        }

        foreach ($currentjob in $InputObject) {

            $server = $currentjob.Parent.Parent
            $status = $currentjob.CurrentRunStatus

            if ($status -eq 'Idle') {
                Stop-Function -Message "$currentjob on $server is idle ($status)" -Target $currentjob -Continue
            }

            If ($Pscmdlet.ShouldProcess($server, "Stopping job $currentjob")) {
                $null = $currentjob.Stop()
                Start-Sleep -Milliseconds 300
                $currentjob.Refresh()

                $waits = 0
                while ($currentjob.CurrentRunStatus -ne 'Idle' -and $waits++ -lt 10) {
                    Start-Sleep -Milliseconds 100
                    $currentjob.Refresh()
                }

                if ($wait) {
                    while ($currentjob.CurrentRunStatus -ne 'Idle') {
                        Write-Message -Level Output -Message "$currentjob is $($currentjob.CurrentRunStatus)"
                        Start-Sleep -Seconds 3
                        $currentjob.Refresh()
                    }
                    $currentjob
                } else {
                    $currentjob
                }
            }
        }
    }
}
tools\dbatools\functions\Stop-DbaEndpoint.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Stop-DbaEndpoint {
    <#
    .SYNOPSIS
        Stops endpoints on a SQL Server instance.

    .DESCRIPTION
        Stops endpoints on a SQL Server instance.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Endpoint
        Only stop specific endpoints.

    .PARAMETER AllEndpoints
        Stops all endpoints on an instance.

    .PARAMETER InputObject
        Enables piping from Get-Endpoint.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Endpoint
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Stop-DbaEndpoint

    .EXAMPLE
        PS C:\> Stop-DbaEndpoint -SqlInstance sql2017a -AllEndpoints

        Stops all endpoints on the sqlserver2014 instance.

    .EXAMPLE
        PS C:\> Stop-DbaEndpoint -SqlInstance sql2017a -Endpoint endpoint1,endpoint2

        Stops the endpoint1 and endpoint2 endpoints.

    .EXAMPLE
        PS C:\> Get-Endpoint -SqlInstance sql2017a -Endpoint endpoint1 | Stop-DbaEndpoint

        Stops the endpoints returned from the Get-Endpoint command.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$EndPoint,
        [switch]$AllEndpoints,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Endpoint[]]$InputObject,
        [switch]$EnableException
    )

    process {
        if ((Test-Bound -ParameterName SqlInstance) -And (Test-Bound -Not -ParameterName Endpoint, AllEndpoints)) {
            Stop-Function -Message "You must specify AllEndpoints or Endpoint when using the SqlInstance parameter."
            return
        }
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaEndpoint -SqlInstance $instance -SqlCredential $SqlCredential -EndPoint $Endpoint
        }

        foreach ($ep in $InputObject) {
            try {
                if ($Pscmdlet.ShouldProcess($ep.Parent.Name, "Stopping $ep")) {
                    $ep.Stop()
                    $ep
                }
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
            }
        }
    }
}
tools\dbatools\functions\Stop-DbaPfDataCollectorSet.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Stop-DbaPfDataCollectorSet {
    <#
    .SYNOPSIS
        Stops Performance Monitor Data Collector Set.

    .DESCRIPTION
        Stops Performance Monitor Data Collector Set.

    .PARAMETER ComputerName
        The target computer. Defaults to localhost.

    .PARAMETER Credential
        Allows you to login to $ComputerName using alternative credentials. To use:

        $cred = Get-Credential, then pass $cred object to the -Credential parameter.

    .PARAMETER CollectorSet
        The name of the Collector Set to stop.

    .PARAMETER NoWait
        If this switch is enabled, the collector is stopped and the results are returned immediately.

    .PARAMETER InputObject
        Accepts the object output by Get-DbaPfDataCollectorSet via the pipeline.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: PerfMon
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Stop-DbaPfDataCollectorSet

    .EXAMPLE
        PS C:\> Stop-DbaPfDataCollectorSet

        Attempts to stop all ready Collectors on localhost.

    .EXAMPLE
        PS C:\> Stop-DbaPfDataCollectorSet -ComputerName sql2017

        Attempts to stop all ready Collectors on localhost.

    .EXAMPLE
        PS C:\> Stop-DbaPfDataCollectorSet -ComputerName sql2017, sql2016 -Credential ad\sqldba -CollectorSet 'System Correlation'

        Stops the 'System Correlation' Collector on sql2017 and sql2016 using alternative credentials.

    .EXAMPLE
        PS C:\> Get-DbaPfDataCollectorSet -CollectorSet 'System Correlation' | Stop-DbaPfDataCollectorSet

        Stops the 'System Correlation' Collector.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [DbaInstance[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [Alias("DataCollectorSet")]
        [string[]]$CollectorSet,
        [parameter(ValueFromPipeline)]
        [object[]]$InputObject,
        [switch]$NoWait,
        [switch]$EnableException
    )
    begin {
        #Variable marked as unused by PSScriptAnalyzer
        #$sets = @()
        $wait = $NoWait -eq $false

        $setscript = {
            $setname = $args[0]; $wait = $args[1]
            $collectorset = New-Object -ComObject Pla.DataCollectorSet
            $collectorset.Query($setname, $null)
            $null = $collectorset.Stop($wait)
        }
    }
    process {
        
        
        if (-not $InputObject -or ($InputObject -and (Test-Bound -ParameterName ComputerName))) {
            foreach ($computer in $ComputerName) {
                $InputObject += Get-DbaPfDataCollectorSet -ComputerName $computer -Credential $Credential -CollectorSet $CollectorSet
            }
        }

        if ($InputObject) {
            if (-not $InputObject.DataCollectorSetObject) {
                Stop-Function -Message "InputObject is not of the right type. Please use Get-DbaPfDataCollectorSet."
                return
            }
        }

        # Check to see if its running first
        foreach ($set in $InputObject) {
            $setname = $set.Name
            $computer = $set.ComputerName
            $status = $set.State

            Write-Message -Level Verbose -Message "$setname on $ComputerName is $status."
            if ($status -ne "Running") {
                Stop-Function -Message "$setname on $computer is already stopped." -Continue
            }
            if ($Pscmdlet.ShouldProcess($computer, "Stoping Performance Monitor collection set")) {
                try {
                    Invoke-Command2 -ComputerName $computer -Credential $Credential -ScriptBlock $setscript -ArgumentList $setname, $wait -ErrorAction Stop
                } catch {
                    Stop-Function -Message "Failure stopping $setname on $computer." -ErrorRecord $_ -Target $computer -Continue
                }

                Get-DbaPfDataCollectorSet -ComputerName $computer -Credential $Credential -CollectorSet $setname
            }
        }
    }
}
tools\dbatools\functions\Stop-DbaProcess.ps1
function Stop-DbaProcess {
    <#
    .SYNOPSIS
        This command finds and kills SQL Server processes.

    .DESCRIPTION
        This command kills all spids associated with a spid, login, host, program or database.

        If you are attempting to kill your own login sessions, the process performing the kills will be skipped.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Spid
        Specifies one or more spids to be killed. Options for this parameter are auto-populated from the server.

    .PARAMETER Login
        Specifies one or more login names whose processes will be killed. Options for this parameter are auto-populated from the server and only login names that have active processes are offered.

    .PARAMETER Hostname
        Specifies one or more client hostnames whose processes will be killed. Options for this parameter are auto-populated from the server and only hostnames that have active processes are offered.

    .PARAMETER Program
        Specifies one or more client programs whose processes will be killed. Options for this parameter are auto-populated from the server and only programs that have active processes are offered.

    .PARAMETER Database
        Specifies one or more databases whose processes will be killed. Options for this parameter are auto-populated from the server and only databases that have active processes are offered.

        This parameter is auto-populated from -SqlInstance and allows only database names that have active processes. You can specify one or more Databases whose processes will be killed.

    .PARAMETER ExcludeSpid
        Specifies one or more spids which will not be killed. Options for this parameter are auto-populated from the server.

        Exclude is the last filter to run, so even if a spid matches (for example) Hosts, if it's listed in Exclude it wil be excluded.

    .PARAMETER InputObject
        This is the process object passed by Get-DbaProcess if using a pipeline.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Processes
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Stop-DbaProcess

    .EXAMPLE
        PS C:\> Stop-DbaProcess -SqlInstance sqlserver2014a -Login base\ctrlb, sa

        Finds all processes for base\ctrlb and sa on sqlserver2014a, then kills them. Uses Windows Authentication to login to sqlserver2014a.

    .EXAMPLE
        PS C:\> Stop-DbaProcess -SqlInstance sqlserver2014a -SqlCredential $credential -Spid 56, 77

        Finds processes for spid 56 and 57, then kills them. Uses alternative (SQL or Windows) credentials to login to sqlserver2014a.

    .EXAMPLE
        PS C:\> Stop-DbaProcess -SqlInstance sqlserver2014a -Program 'Microsoft SQL Server Management Studio'

        Finds processes that were created in Microsoft SQL Server Management Studio, then kills them.

    .EXAMPLE
        PS C:\> Stop-DbaProcess -SqlInstance sqlserver2014a -Hostname workstationx, server100

        Finds processes that were initiated (computers/clients) workstationx and server 1000, then kills them.

    .EXAMPLE
        PS C:\> Stop-DbaProcess -SqlInstance sqlserver2014  -Database tempdb -WhatIf

        Shows what would happen if the command were executed.

    .EXAMPLE
        PS C:\> Get-DbaProcess -SqlInstance sql2016 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess

        Finds processes that were created with dbatools, then kills them.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ParameterSetName = "Server")]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [int[]]$Spid,
        [int[]]$ExcludeSpid,
        [string[]]$Database,
        [string[]]$Login,
        [string[]]$Hostname,
        [string[]]$Program,
        [parameter(ValueFromPipeline, Mandatory, ParameterSetName = "Process")]
        [object[]]$InputObject,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        if (Test-FunctionInterrupt) { return }

        if (!$InputObject) {
            $InputObject = Get-DbaProcess @PSBoundParameters
        }

        foreach ($session in $InputObject) {
            $sourceserver = $session.Parent

            if (!$sourceserver) {
                Stop-Function -Message "Only process objects can be passed through the pipeline." -Category InvalidData -Target $session
                return
            }

            $currentspid = $session.spid

            if ($sourceserver.ConnectionContext.ProcessID -eq $currentspid) {
                Write-Message -Level Warning -Message "Skipping spid $currentspid because you cannot use KILL to kill your own process." -Target $session
                Continue
            }

            if ($Pscmdlet.ShouldProcess($sourceserver, "Killing spid $currentspid")) {
                try {
                    $sourceserver.KillProcess($currentspid)
                    [pscustomobject]@{
                        SqlInstance = $sourceserver.name
                        Spid        = $session.Spid
                        Login       = $session.Login
                        Host        = $session.Host
                        Database    = $session.Database
                        Program     = $session.Program
                        Status      = 'Killed'
                    }
                } catch {
                    Stop-Function -Message "Couldn't kill spid $currentspid." -Target $session -ErrorRecord $_ -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Stop-DbaService.ps1
function Stop-DbaService {
    <#
    .SYNOPSIS
        Stops SQL Server services on a computer.

    .DESCRIPTION
        Stops the SQL Server related services on one or more computers. Will follow SQL Server service dependencies.

        Requires Local Admin rights on destination computer(s).

    .PARAMETER ComputerName
        The target SQL Server instance or instances.

    .PARAMETER InstanceName
        Only affects services that belong to the specific instances.

    .PARAMETER Credential
        Credential object used to connect to the computer as a different user.

    .PARAMETER Type
        Use -Type to collect only services of the desired SqlServiceType.
        Can be one of the following: "Agent","Browser","Engine","FullText","SSAS","SSIS","SSRS"

    .PARAMETER Timeout
        How long to wait for the start/stop request completion before moving on. Specify 0 to wait indefinitely.

    .PARAMETER InputObject
        A collection of services from Get-DbaService

    .PARAMETER Force
        Use this switch to stop dependent services before proceeding with the specified service

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER WhatIf
        Shows what would happen if the cmdlet runs. The cmdlet is not run.

    .PARAMETER Confirm
        Prompts you for confirmation before running the cmdlet.

    .PARAMETER Force
        Will stop dependent SQL Server agents when stopping Engine services.

    .NOTES
        Tags: Service, Stop
        Author: Kirill Kravtsov (@nvarscar)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires Local Admin rights on destination computer(s).

    .LINK
        https://dbatools.io/Stop-DbaService

    .EXAMPLE
        PS C:\> Stop-DbaService -ComputerName sqlserver2014a

        Stops the SQL Server related services on computer sqlserver2014a.

    .EXAMPLE
        PS C:\> 'sql1','sql2','sql3'| Get-DbaService | Stop-DbaService

        Gets the SQL Server related services on computers sql1, sql2 and sql3 and stops them.

    .EXAMPLE
        PS C:\> Stop-DbaService -ComputerName sql1,sql2 -Instance MSSQLSERVER

        Stops the SQL Server services related to the default instance MSSQLSERVER on computers sql1 and sql2.

    .EXAMPLE
        PS C:\> Stop-DbaService -ComputerName $MyServers -Type SSRS

        Stops the SQL Server related services of type "SSRS" (Reporting Services) on computers in the variable MyServers.

    .EXAMPLE
        PS C:\> Stop-DbaService -ComputerName sql1 -Type Engine -Force

        Stops SQL Server database engine services on sql1 forcing dependent SQL Server Agent services to stop as well.

    #>
    [CmdletBinding(DefaultParameterSetName = "Server", SupportsShouldProcess)]
    param (
        [Parameter(ParameterSetName = "Server", Position = 1)]
        [Alias("cn", "host", "Server")]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [Alias("Instance")]
        [string[]]$InstanceName,
        [ValidateSet("Agent", "Browser", "Engine", "FullText", "SSAS", "SSIS", "SSRS")]
        [string[]]$Type,
        [parameter(ValueFromPipeline, Mandatory, ParameterSetName = "Service")]
        [Alias("ServiceCollection")]
        [object[]]$InputObject,
        [int]$Timeout = 60,
        [PSCredential]$Credential,
        [switch]$Force,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        $processArray = @()
        if ($PsCmdlet.ParameterSetName -eq "Server") {
            $serviceParams = @{ ComputerName = $ComputerName }
            if ($InstanceName) { $serviceParams.InstanceName = $InstanceName }
            if ($Type) { $serviceParams.Type = $Type }
            if ($Credential) { $serviceParams.Credential = $Credential }
            if ($EnableException) { $serviceParams.Silent = $EnableException }
            $InputObject = Get-DbaService @serviceParams
        }
    }
    process {
        #Get all the objects from the pipeline before proceeding
        $processArray += $InputObject
    }
    end {
        $processArray = [array]($processArray | Where-Object { (!$InstanceName -or $_.InstanceName -in $InstanceName) -and (!$Type -or $_.ServiceType -in $Type) })
        foreach ($service in $processArray) {
            if ($Force -and $service.ServiceType -eq 'Engine' -and !($processArray | Where-Object { $_.ServiceType -eq 'Agent' -and $_.InstanceName -eq $service.InstanceName -and $_.ComputerName -eq $service.ComputerName })) {
                #Construct parameters to call Get-DbaService
                $serviceParams = @{
                    ComputerName = $service.ComputerName
                    InstanceName = $service.InstanceName
                    Type         = 'Agent'
                }
                if ($Credential) { $serviceParams.Credential = $Credential }
                if ($EnableException) { $serviceParams.EnableException = $EnableException }
                $processArray += @(Get-DbaService @serviceParams)
            }
        }
        if ($PSCmdlet.ShouldProcess("$ProcessArray", "Stopping Service")) {
            if ($processArray) {
                Update-ServiceStatus -InputObject $processArray -Action 'stop' -Timeout $Timeout -EnableException $EnableException
            } else {
                Stop-Function -EnableException $EnableException -Message "No SQL Server services found with current parameters." -Category ObjectNotFound
            }
        }
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Stop-DbaSqlService
    }
}
tools\dbatools\functions\Stop-DbaTrace.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Stop-DbaTrace {
    <#
    .SYNOPSIS
        Stops SQL Server traces

    .DESCRIPTION
        Stops SQL Server traces

    .PARAMETER SqlInstance
        The target SQL Server instance

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Id
        A list of trace ids

    .PARAMETER InputObject
        Internal parameter for piping

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Security, Trace
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Stop-DbaTrace -SqlInstance sql2008

        Stops all traces on sql2008

    .EXAMPLE
        PS C:\> Stop-DbaTrace -SqlInstance sql2008 -Id 1

        Stops all trace with ID 1 on sql2008

    .EXAMPLE
        PS C:\> Get-DbaTrace -SqlInstance sql2008 | Out-GridView -PassThru | Stop-DbaTrace

        Stops selected traces on sql2008

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [int[]]$Id,
        [parameter(ValueFromPipeline)]
        [object[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if (-not $InputObject -and $SqlInstance) {
            $InputObject = Get-DbaTrace -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Id $Id
        }

        foreach ($trace in $InputObject) {
            if (-not $trace.id -and -not $trace.Parent) {
                Stop-Function -Message "Input is of the wrong type. Use Get-DbaTrace." -Continue
                return
            }

            $server = $trace.Parent
            $traceid = $trace.id
            $default = Get-DbaTrace -SqlInstance $server -Default

            if ($default.id -eq $traceid) {
                Stop-Function -Message "The default trace on $server cannot be stopped. Use Set-DbaSpConfigure to turn it off." -Continue
            }

            $sql = "sp_trace_setstatus $traceid, 0"

            if ($Pscmdlet.ShouldProcess($traceid, "Stopping the TraceID on $server")) {
                try {
                    $server.Query($sql)
                    $output = Get-DbaTrace -SqlInstance $server -Id $traceid
                    if (-not $output) {
                        $output = [PSCustomObject]@{
                            ComputerName      = $server.ComputerName
                            InstanceName      = $server.ServiceName
                            SqlInstance       = $server.DomainInstanceName
                            Id                = $traceid
                            Status            = $null
                            IsRunning         = $false
                            Path              = $null
                            MaxSize           = $null
                            StopTime          = $null
                            MaxFiles          = $null
                            IsRowset          = $null
                            IsRollover        = $null
                            IsShutdown        = $null
                            IsDefault         = $null
                            BufferCount       = $null
                            BufferSize        = $null
                            FilePosition      = $null
                            ReaderSpid        = $null
                            StartTime         = $null
                            LastEventTime     = $null
                            EventCount        = $null
                            DroppedEventCount = $null
                            Parent            = $server
                        } | Select-DefaultView -Property 'ComputerName', 'InstanceName', 'SqlInstance', 'Id', 'IsRunning'
                    }
                    $output
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target $server -Continue
                    return
                }
            }
        }
    }
}
tools\dbatools\functions\Stop-DbaXESession.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Stop-DbaXESession {
    <#
    .SYNOPSIS
        Stops Extended Events sessions.

    .DESCRIPTION
        This script stops Extended Events sessions on a SQL Server instance.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Session
        Specifies individual Extended Events sessions to stop.

    .PARAMETER AllSessions
        If this switch is enabled, all Extended Events sessions will be stopped except the packaged sessions AlwaysOn_health, system_health, telemetry_xevents.

    .PARAMETER InputObject
        Accepts the object output by Get-DbaXESession as the list of sessions to be stopped.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Doug Meyers

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Stop-DbaXESession

    .EXAMPLE
        PS C:\> Stop-DbaXESession -SqlInstance sqlserver2012 -AllSessions

        Stops all Extended Event Session on the sqlserver2014 instance.

    .EXAMPLE
        PS C:\> Stop-DbaXESession -SqlInstance sqlserver2012 -Session xesession1,xesession2

        Stops the xesession1 and xesession2 Extended Event sessions.

    .EXAMPLE
        PS C:\> Get-DbaXESession -SqlInstance sqlserver2012 -Session xesession1 | Stop-DbaXESession

        Stops the sessions returned from the Get-DbaXESession function.

    #>
    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'Session')]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification = "Internal functions are ignored")]
    param (
        [parameter(Position = 1, Mandatory, ParameterSetName = 'Session')]
        [parameter(Position = 1, Mandatory, ParameterSetName = 'All')]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,

        [parameter(ParameterSetName = 'Session')]
        [parameter(ParameterSetName = 'All')]
        [PSCredential]$SqlCredential,

        [parameter(Mandatory, ParameterSetName = 'Session')]
        [Alias("Sessions")]
        [object[]]$Session,

        [parameter(Mandatory, ParameterSetName = 'All')]
        [switch]$AllSessions,

        [parameter(Mandatory, ValueFromPipeline, ParameterSetName = 'Object')]
        [Microsoft.SqlServer.Management.XEvent.Session[]]$InputObject,
        [switch]$EnableException
    )

    begin {
        # Stop each XESession
        function Stop-XESessions {
            [CmdletBinding(SupportsShouldProcess)]
            param ([Microsoft.SqlServer.Management.XEvent.Session[]]$xeSessions)

            foreach ($xe in $xeSessions) {
                $instance = $xe.Parent.Name
                $session = $xe.Name
                if ($xe.isRunning) {
                    Write-Message -Level Verbose -Message "Stopping XEvent Session $session on $instance."
                    if ($Pscmdlet.ShouldProcess("$instance", "Stopping XEvent Session $session")) {
                        try {
                            $xe.Stop()
                        } catch {
                            Stop-Function -Message "Could not stop XEvent Session on $instance" -Target $session -ErrorRecord $_ -Continue
                        }
                    }
                } else {
                    Write-Message -Level Warning -Message "$session on $instance is already stopped"
                }
                Get-DbaXESession -SqlInstance $xe.Parent -Session $session
            }
        }
    }

    process {
        if ($InputObject) {
            if ($Pscmdlet.ShouldProcess("Configuring XEvent Sessions to stop")) {
                Stop-XESessions $InputObject
            }
        } else {
            foreach ($instance in $SqlInstance) {
                $xeSessions = Get-DbaXESession -SqlInstance $instance -SqlCredential $SqlCredential

                # Filter xesessions based on parameters
                if ($Session) {
                    $xeSessions = $xeSessions | Where-Object { $_.Name -in $Session }
                } elseif ($AllSessions) {
                    $systemSessions = @('AlwaysOn_health', 'system_health', 'telemetry_xevents')
                    $xeSessions = $xeSessions | Where-Object { $_.Name -notin $systemSessions }
                }

                if ($Pscmdlet.ShouldProcess("$instance", "Configuring XEvent Session $xeSessions to Stop")) {
                    Stop-XESessions $xeSessions
                }
            }
        }
    }
}
tools\dbatools\functions\Stop-DbaXESmartTarget.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Stop-DbaXESmartTarget {
    <#
    .SYNOPSIS
        Stops an XESmartTarget PowerShell job. Useful if you want to run a target, but not right now.

    .DESCRIPTION
        Stops an XESmartTarget PowerShell job. Useful if you want to run a target, but not right now.

    .PARAMETER InputObject
        The XESmartTarget job object.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl) | SmartTarget by Gianluca Sartori (@spaghettidba)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Stop-DbaXESmartTarget
        https://github.com/spaghettidba/XESmartTarget/wiki

    .EXAMPLE
        PS C:\> Get-DbaXESmartTarget | Stop-DbaXESmartTarget

        Stops all XESmartTarget jobs.

    .EXAMPLE
        PS C:\> Get-DbaXESmartTarget | Where-Object Id -eq 2 | Stop-DbaXESmartTarget

        Stops a specific XESmartTarget job.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [object[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ($Pscmdlet.ShouldProcess("localhost", "Stopping job $id")) {
            try {
                $id = $InputObject.Id
                Write-Message -Level Output -Message "Stopping job $id, this may take a couple minutes."
                Get-Job -ID $InputObject.Id | Stop-Job
                Write-Message -Level Output -Message "Successfully Stopped $id. If you need to remove the job for good, use Remove-DbaXESmartTarget."
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_
            }
        }
    }
}
tools\dbatools\functions\Suspend-DbaAgDbDataMovement.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Suspend-DbaAgDbDataMovement {
    <#
    .SYNOPSIS
        Suspends data movement for an availability group database on a SQL Server instance.

    .DESCRIPTION
        Suspends data movement for an availability group database on a SQL Server instance.

   .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.

    .PARAMETER SqlCredential
        Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database or databases to suspend movement upon.

    .PARAMETER AvailabilityGroup
        The availability group where the database movement will be suspended.

    .PARAMETER InputObject
        Enables piping from Get-DbaAgDatabase

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: AvailabilityGroup, HA, AG
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Suspend-DbaAgDbDataMovement

    .EXAMPLE
        PS C:\> Suspend-DbaAgDbDataMovement -SqlInstance sql2017a -AvailabilityGroup ag1 -Database db1, db2

        Suspends data movement on db1 and db2 to ag1 on sql2017a. Prompts for confirmation.

    .EXAMPLE
        PS C:\> Get-DbaAgDatabase -SqlInstance sql2017a, sql2019 | Out-GridView -Passthru | Suspend-DbaAgDbDataMovement -Confirm:$false

        Suspends data movement on the selected availability group databases. Does not prompt for confirmation.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$AvailabilityGroup,
        [string[]]$Database,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.AvailabilityDatabase[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ((Test-Bound -ParameterName SqlInstance)) {
            if ((Test-Bound -Not -ParameterName Database) -and (Test-Bound -Not -ParameterName AvailabilityGroup)) {
                Stop-Function -Message "You must specify one or more databases and one Availability Groups when using the SqlInstance parameter."
                return
            }
        }

        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaAgDatabase -SqlInstance $instance -SqlCredential $SqlCredential -Database $Database
        }

        foreach ($agdb in $InputObject) {
            if ($Pscmdlet.ShouldProcess($ag.Parent.Name, "Seting availability group $db to $($db.Parent.Name)")) {
                try {
                    $null = $agdb.SuspendDataMovement()
                    $agdb
                } catch {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Sync-DbaAvailabilityGroup.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Sync-DbaAvailabilityGroup {
    <#
    .SYNOPSIS
        Syncs depdendent objects such as jobs, logins and custom errors for availability groups

    .DESCRIPTION
        Syncs depdendent objects for availability groups. Such objects include:

        SpConfigure
        CustomErrors
        Credentials
        DatabaseMail
        LinkedServers
        Logins
        LoginPermissions
        SystemTriggers
        DatabaseOwner
        AgentCategory
        AgentOperator
        AgentAlert
        AgentProxy
        AgentSchedule
        AgentJob

        Note that any of these can be excluded. For specific object exclusions (such as a single job), using the underlying Copy-Dba* command will be required.

        This command does not filter by which logins are in use by the ag databases or which linked servers are used. All objects that are not excluded will be copied like hulk smash.

    .PARAMETER Primary
        The primary SQL Server instance. Server version must be SQL Server version 2012 or higher.

    .PARAMETER PrimarySqlCredential
        Login to the primary instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Secondary
        The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.

    .PARAMETER SecondarySqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER AvailabilityGroup
        The name of the Availability Group.

    .PARAMETER Exclude
        Exclude one or more objects to export

        SpConfigure
        CustomErrors
        Credentials
        DatabaseMail
        LinkedServers
        Logins
        LoginPermissions
        SystemTriggers
        DatabaseOwner
        AgentCategory
        AgentOperator
        AgentAlert
        AgentProxy
        AgentSchedule
        AgentJob

    .PARAMETER Login
        Specific logins to sync. If unspecified, all logins will be processed.

    .PARAMETER ExcludeLogin
        Specific logins to exclude when performing the sync. If unspecified, all logins will be processed.

    .PARAMETER Job
        Specific jobs to sync. If unspecified, all logins will be processed.

    .PARAMETER ExcludeJob
         Specific jobs to exclude when performing the sync. If unspecified, all logins will be processed.

    .PARAMETER InputObject
        Enables piping from Get-DbaAvailabilityGroup.

    .PARAMETER Force
        If this switch is enabled, the objects will dropped and recreated on Destination.

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: HA
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Sync-DbaAvailabilityGroup

    .EXAMPLE
        PS C:\> Sync-DbaAvailabilityGroup -Primary sql2016a -AvailabilityGroup db3

        Syncs the following on all replicas found in the db3 AG:
        SpConfigure, CustomErrors, Credentials, DatabaseMail, LinkedServers
        Logins, LoginPermissions, SystemTriggers, DatabaseOwner, AgentCategory,
        AgentOperator, AgentAlert, AgentProxy, AgentScheduleAgentJob

    .EXAMPLE
        PS C:\> Get-DbaAvailabilityGroup -SqlInstance sql2016a | Sync-DbaAvailabilityGroup -ExcludeType LoginPermissions, LinkedServers -ExcludeLogin login1, login2 -Job job1, job2

        Syncs the following on all replicas found in the db3 AG:
        SpConfigure, CustomErrors, Credentials, DatabaseMail, Logins,
        SystemTriggers, DatabaseOwner, AgentCategory, AgentOperator
        AgentAlert, AgentProxy, AgentScheduleAgentJob.

        Copies all logins except for login1 and login2 and only syncs job1 and job2

    .EXAMPLE
        PS C:\> Get-DbaAvailabilityGroup -SqlInstance sql2016a | Sync-DbaAvailabilityGroup -WhatIf

        Shows what would happen if the command were to run but doesn't actually perform the action.
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
    param (
        [DbaInstanceParameter]$Primary,
        [PSCredential]$PrimarySqlCredential,
        [DbaInstanceParameter[]]$Secondary,
        [PSCredential]$SecondarySqlCredential,
        [string]$AvailabilityGroup,
        [Alias("ExcludeType")]
        [ValidateSet('AgentCategory', 'AgentOperator', 'AgentAlert', 'AgentProxy', 'AgentSchedule', 'AgentJob', 'Credentials', 'CustomErrors', 'DatabaseMail', 'DatabaseOwner', 'LinkedServers', 'Logins', 'LoginPermissions', 'SpConfigure', 'SystemTriggers')]
        [string[]]$Exclude,
        [string[]]$Login,
        [string[]]$ExcludeLogin,
        [string[]]$Job,
        [string[]]$ExcludeJob,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.AvailabilityGroup[]]$InputObject,
        [switch]$Force,
        [switch]$EnableException
    )
    begin {
        $allcombos = @()
    }
    process {
        if (-not $AvailabilityGroup -and -not $Secondary -and -not $InputObject) {
            Stop-Function -Message "You must specify a secondary or an availability group."
            return
        }

        if ($InputObject) {
            $server = $InputObject.Parent
        } else {
            try {
                $server = Connect-SqlInstance -SqlInstance $Primary -SqlCredential $PrimarySqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Primary
                return
            }
        }

        if ($AvailabilityGroup) {
            $InputObject += Get-DbaAvailabilityGroup -SqlInstance $server -AvailabilityGroup $AvailabilityGroup
        }

        if ($InputObject) {
            $Secondary += (($InputObject.AvailabilityReplicas | Where-Object Name -ne $server.DomainInstanceName).Name | Select-Object -Unique)
        }

        if ($Secondary) {
            $Secondary = $Secondary | Sort-Object
            $secondaries = @()
            foreach ($computer in $Secondary) {
                try {
                    $secondaries += Connect-SqlInstance -SqlInstance $computer -SqlCredential $SecondarySqlCredential
                } catch {
                    Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Primary
                    return
                }
            }
        }

        $thiscombo = [pscustomobject]@{
            PrimaryServer   = $server
            SecondaryServer = $secondaries
        }

        # In the event that someone pipes in an availability group, this will keep the syncer from running a bunch of times
        $dupe = $false

        foreach ($ag in $allcombos) {
            if ($ag.PrimaryServer.Name -eq $thiscombo.PrimaryServer.Name -and
                $ag.SecondaryServer.Name.ToString() -eq $thiscombo.SecondaryServer.Name.ToString()) {
                $dupe = $true
            }
        }

        if ($dupe -eq $false) {
            $allcombos += $thiscombo
        }
    }

    end {
        if (Test-FunctionInterrupt) { return }

        # now that all combinations have been figured out, begin sync without duplicating work
        foreach ($ag in $allcombos) {
            $server = $ag.PrimaryServer
            $secondaries = $ag.SecondaryServer

            $stepCounter = 0
            $activity = "Syncing availability group $AvailabilityGroup"

            if (-not $secondaries) {
                Stop-Function -Message "No secondaries found."
                return
            }

            $primaryserver = $server.Name
            $secondaryservers = $secondaries.Name -join ", "

            if ($Exclude -notcontains "SpConfigure") {
                if ($PSCmdlet.ShouldProcess("Syncing SQL Server Configuration from $primaryserver to $secondaryservers")) {
                    Write-ProgressHelper -Activity $activity -StepNumber ($stepCounter++) -Message "Syncing SQL Server Configuration"
                    Copy-DbaSpConfigure -Source $server -Destination $secondaries
                }
            }

            if ($Exclude -notcontains "Logins") {
                if ($PSCmdlet.ShouldProcess("Syncing logins from $primaryserver to $secondaryservers")) {
                    Write-ProgressHelper -Activity $activity -StepNumber ($stepCounter++) -Message "Syncing logins"
                    Copy-DbaLogin -Source $server -Destination $secondaries -ExcludeLogin $ExcludeLogin -Force:$Force
                }
            }

            if ($Exclude -notcontains "DatabaseOwner") {
                if ($PSCmdlet.ShouldProcess("Updating database owners to match newly migrated logins from $primaryserver to $secondaryservers")) {
                    Write-ProgressHelper -Activity $activity -StepNumber ($stepCounter++) -Message "Updating database owners to match newly migrated logins"
                    foreach ($sec in $secondaries) {
                        $null = Update-SqlDbOwner -Source $server -Destination $sec
                    }
                }
            }

            if ($Exclude -notcontains "CustomErrors") {
                if ($PSCmdlet.ShouldProcess("Syncing custom errors (user defined messages) from $primaryserver to $secondaryservers")) {
                    Write-ProgressHelper -Activity $activity -StepNumber ($stepCounter++) -Message "Syncing custom errors (user defined messages)"
                    Copy-DbaCustomError -Source $server -Destination $secondaries -Force:$Force
                }
            }

            if ($Exclude -notcontains "Credentials") {
                if ($PSCmdlet.ShouldProcess("Syncing SQL credentials from $primaryserver to $secondaryservers")) {
                    Write-ProgressHelper -Activity $activity -StepNumber ($stepCounter++) -Message "Syncing SQL credentials"
                    Copy-DbaCredential -Source $server -Destination $secondaries -Force:$Force
                }
            }

            if ($Exclude -notcontains "DatabaseMail") {
                if ($PSCmdlet.ShouldProcess("Syncing database mail from $primaryserver to $secondaryservers")) {
                    Write-ProgressHelper -Activity $activity -StepNumber ($stepCounter++) -Message "Syncing database mail"
                    Copy-DbaDbMail -Source $server -Destination $secondaries -Force:$Force
                }
            }

            if ($Exclude -notcontains "LinkedServers") {
                if ($PSCmdlet.ShouldProcess("Syncing linked servers from $primaryserver to $secondaryservers")) {
                    Write-ProgressHelper -Activity $activity -StepNumber ($stepCounter++) -Message "Syncing linked servers"
                    Copy-DbaLinkedServer -Source $server -Destination $secondaries -Force:$Force
                }
            }

            if ($Exclude -notcontains "SystemTriggers") {
                if ($PSCmdlet.ShouldProcess("Syncing System Triggers from $primaryserver to $secondaryservers")) {
                    Write-ProgressHelper -Activity $activity -StepNumber ($stepCounter++) -Message "Syncing System Triggers"
                    Copy-DbaServerTrigger -Source $server -Destination $secondaries -Force:$Force
                }
            }

            if ($Exclude -notcontains "AgentCategory") {
                if ($PSCmdlet.ShouldProcess("Syncing Agent Categories from $primaryserver to $secondaryservers")) {
                    Write-ProgressHelper -Activity $activity -StepNumber ($stepCounter++) -Message "Syncing Agent Categories"
                    Copy-DbaAgentJobCategory -Source $server -Destination $secondaries -Force:$force
                    $secondaries.JobServer.JobCategories.Refresh()
                    $secondaries.JobServer.OperatorCategories.Refresh()
                    $secondaries.JobServer.AlertCategories.Refresh()
                }
            }

            if ($Exclude -notcontains "AgentOperator") {
                if ($PSCmdlet.ShouldProcess("Syncing Agent Operators from $primaryserver to $secondaryservers")) {
                    Write-ProgressHelper -Activity $activity -StepNumber ($stepCounter++) -Message "Syncing Agent Operators"
                    Copy-DbaAgentOperator -Source $server -Destination $secondaries -Force:$force
                    $secondaries.JobServer.Operators.Refresh()
                }
            }

            if ($Exclude -notcontains "AgentAlert") {
                if ($PSCmdlet.ShouldProcess("Syncing Agent Alerts from $primaryserver to $secondaryservers")) {
                    Write-ProgressHelper -Activity $activity -StepNumber ($stepCounter++) -Message "Syncing Agent Alerts"
                    Copy-DbaAgentAlert -Source $server -Destination $secondaries -Force:$force -IncludeDefaults
                    $secondaries.JobServer.Alerts.Refresh()
                }
            }

            if ($Exclude -notcontains "AgentProxy") {
                if ($PSCmdlet.ShouldProcess("Syncing Agent Proxy Accounts from $primaryserver to $secondaryservers")) {
                    Write-ProgressHelper -Activity $activity -StepNumber ($stepCounter++) -Message "Syncing Agent Proxy Accounts"
                    Copy-DbaAgentProxy -Source $server -Destination $secondaries -Force:$force
                    $secondaries.JobServer.ProxyAccounts.Refresh()
                }
            }

            if ($Exclude -notcontains "AgentSchedule") {
                if ($PSCmdlet.ShouldProcess("Syncing Agent Schedules from $primaryserver to $secondaryservers")) {
                    Write-ProgressHelper -Activity $activity -StepNumber ($stepCounter++) -Message "Syncing Agent Schedules"
                    Copy-DbaAgentSchedule -Source $server -Destination $secondaries -Force:$force
                    $secondaries.JobServer.SharedSchedules.Refresh()
                    $secondaries.JobServer.Refresh()
                    $secondaries.Refresh()
                }
            }

            if ($Exclude -notcontains "AgentJob") {
                if ($PSCmdlet.ShouldProcess("Syncing Agent Jobs from $primaryserver to $secondaryservers")) {
                    Write-ProgressHelper -Activity $activity -StepNumber ($stepCounter++) -Message "Syncing Agent Jobs"
                    Copy-DbaAgentJob -Source $server -Destination $secondaries -Force:$force -Job $Job -ExcludeJob $ExcludeJob
                }
            }

            if ($Exclude -notcontains "LoginPermissions") {
                if ($PSCmdlet.ShouldProcess("Syncing login permissions from $primaryserver to $secondaryservers")) {
                    Write-ProgressHelper -Activity $activity -StepNumber ($stepCounter++) -Message "Syncing login permissions"
                    Sync-DbaLoginPermission -Source $server -Destination $secondaries -Login $Login -ExcludeLogin $ExcludeLogin
                }
            }
        }
    }
}
tools\dbatools\functions\Sync-DbaLoginPermission.ps1
function Sync-DbaLoginPermission {
    <#
    .SYNOPSIS
        Copies SQL login permissions from one server to another.

    .DESCRIPTION
        Syncs only SQL Server login permissions, roles, etc. Does not add or drop logins. If a matching login does not exist on the destination, the login will be skipped. Credential removal is not currently supported for this operation.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Login
        The login(s) to process. Options for this list are auto-populated from the server. If unspecified, all logins will be processed.

    .PARAMETER ExcludeLogin
        The login(s) to exclude. Options for this list are auto-populated from the server.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration, Login
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Sync-DbaLoginPermission

    .EXAMPLE
        PS C:\> Sync-DbaLoginPermission -Source sqlserver2014a -Destination sqlcluster

        Syncs only SQL Server login permissions, roles, etc. Does not add or drop logins or users. To copy logins and their permissions, use Copy-SqlLogin.

    .EXAMPLE
        PS C:\> Sync-DbaLoginPermission -Source sqlserver2014a -Destination sqlcluster -Exclude realcajun -SourceSqlCredential $scred -DestinationSqlCredential $dcred

        Copies all login permissions except for realcajun using SQL Authentication to connect to each server. If a login already exists on the destination, the permissions will not be migrated.

    .EXAMPLE
        PS C:\> Sync-DbaLoginPermission -Source sqlserver2014a -Destination sqlcluster -Login realcajun, netnerds

        Copies permissions ONLY for logins netnerds and realcajun.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter]$Source,
        [PSCredential]$SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Destination,
        [PSCredential]$DestinationSqlCredential,
        [string[]]$Login,
        [string[]]$ExcludeLogin,
        [switch]$EnableException
    )
    begin {
        function Sync-Only {
            [CmdletBinding()]
            param (
                [Parameter(Mandatory)]
                [ValidateNotNullOrEmpty()]
                [object]$sourceServer,
                [object]$destServer,
                [array]$Logins,
                [array]$Exclude
            )

            try {
                $sa = Get-SqlSaLogin -SqlInstance $destServer -ErrorAction Stop
            } catch {
                $sa = "sa"
            }

            foreach ($sourceLogin in $sourceServer.Logins) {

                $username = $sourceLogin.Name
                $currentLogin = $sourceServer.ConnectionContext.TrueLogin

                if (!$Login -and $currentLogin -eq $username) {
                    Write-Message -Level Verbose -Message "Sync does not modify the permissions of the current user. Skipping."
                    continue
                }

                if ($null -ne $Logins -and $Logins -notcontains $username) {
                    continue
                }

                if ($Exclude -contains $username -or $username.StartsWith("##") -or $username -eq $sa) {
                    continue
                }

                $serverName = Resolve-NetBiosName $sourceServer
                $userBase = ($username.Split("\")[0]).ToLower()

                if ($serverName -eq $userBase -or $username.StartsWith("NT ")) {
                    continue
                }

                if ($null -eq ($destLogin = $destServer.Logins.Item($username))) {
                    continue
                }

                Update-SqlPermission -SourceServer $sourceServer -SourceLogin $sourceLogin -DestServer $destServer -DestLogin $destLogin
            }
        }

        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $sqlcredential
            if ((Test-Bound -ParameterName Login)) {
                $Login = ($sourceServer.Logins | Where-Object Name -NotIn $ExcludeLogin).Name
            }
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source -Continue
            return
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }

        foreach ($dest in $Destination) {
            try {
                $destServer = Connect-SqlInstance -SqlInstance $dest -SqlCredential $DestinationSqlCredential -MinimumVersion 8
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $dest -Continue
            }

            if ($PSCmdlet.ShouldProcess("Syncing Logins $Login")) {
                Sync-Only -SourceServer $sourceServer -DestServer $destServer -Logins $Login -Exclude $ExcludeLogin
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Sync-SqlLoginPermissions
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Sync-DbaSqlLoginPermission
    }
}
tools\dbatools\functions\Test-DbaBackupInformation.ps1
function Test-DbaBackupInformation {
    <#
    .SYNOPSIS
        Tests a dbatools backup history object is correct for restoring

    .DESCRIPTION
        Input is normally from a backup history object generated from `Format-DbaBackupInformation`. This is then parse to check that it's valid for restore. Tests performed include:
          - Checking unbroken LSN chain
          - If the target database exists and WithReplace has been provided
          - If any files already exist, but owned by other databases
          - Creates any new folders required
          - That the backup files exists at the location specified, and can be seen by the Sql Instance
          - If no errors are found then the objects for that database will me marked as Verified

    .PARAMETER BackupHistory
        dbatools BackupHistory object. Normally this will have been process with `Select-` and then `Format-DbaBackupInformation`

    .PARAMETER SqlInstance
        The Sql Server instance that wil be performing the restore

    .PARAMETER SqlCredential
        A Sql Credential to connect to $SqlInstance

    .PARAMETER WithReplace
        By default we won't overwrite an existing database, this switch tells us you want to

    .PARAMETER Continue
        Switch to indicate a continuing restore

    .PARAMETER OutputScriptOnly
        Switch to disable path creation. Will write a warning that a path does not exist

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER VerifyOnly
        This switch indicates that you only wish to verify a restore, so runs a smaller number of tests as you won't be writing anything to the restore server

    .PARAMETER WhatIf
        Shows what would happen if the cmdlet runs. The cmdlet is not run.

    .PARAMETER Confirm
        Prompts you for confirmation before running the cmdlet.

    .NOTES
        Tags: Backup, Restore, DisasterRecovery
        Author: Stuart Moore (@napalmgram), stuart-moore.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaBackupInformation

    .EXAMPLE
        PS C:\> $BackupHistory | Test-DbaBackupInformation -SqlInstance MyInstance
        PS C:\> $PassedDbs = $BackupHistory | Where-Object {$_.IsVerified -eq $True}
        PS C:\> $FailedDbs = $BackupHistory | Where-Object {$_.IsVerified -ne $True}

        Pass in a BackupHistory object to be tested against MyInstance.
        Those records that pass are marked as verified. We can then use the IsVerified property to divide the failures and successes

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseOutputTypeCorrectly", "", Justification = "PSSA Rule Ignored by BOH")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [object[]]$BackupHistory,
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$WithReplace,
        [switch]$Continue,
        [switch]$VerifyOnly,
        [switch]$OutputScriptOnly,
        [switch]$EnableException
    )

    begin {
        try {
            $RestoreInstance = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            return
        }
        $InternalHistory = @()
    }
    process {
        foreach ($bh in $BackupHistory) {
            $InternalHistory += $bh
        }
    }
    end {
        $RegisteredFileCheck = Get-DbaDbPhysicalFile -SqlInstance $RestoreInstance

        $Databases = $InternalHistory.Database | Select-Object -Unique
        foreach ($Database in $Databases) {
            $VerificationErrors = 0
            Write-Message -Message "Testing restore for $Database" -Level Verbose
            #Test we're only restoring backups from one database, or hilarity will ensure
            $DbHistory = $InternalHistory | Where-Object {$_.Database -eq $Database}
            if (( $DbHistory | Select-Object -Property OriginalDatabase -Unique ).Count -gt 1) {
                Write-Message -Message "Trying to restore $Database from multiple sources databases" -Level Warning
                $VerificationErrors++
            }
            #Test Db Existance on destination
            $DbCheck = Get-DbaDatabase -SqlInstance $RestoreInstance -Database $Database
            # Only do file and db tests if we're not verifing
            Write-Message -Level Verbose -Message "VerifyOnly = $VerifyOnly"
            If ($VerifyOnly -ne $true) {
                if ($null -ne $DbCheck -and ($WithReplace -ne $true -and $Continue -ne $true)) {
                    Stop-Function -Message "Database $Database exists, so WithReplace must be specified" -Target $database
                    $VerificationErrors++
                }

                $DBFileCheck = ($RegisteredFileCheck | Where-Object Name -eq $Database).PhysicalName
                $OtherFileCheck = ($RegisteredFileCheck | Where-Object Name -ne $Database).PhysicalName
                $DBHistoryPhysicalPaths = ($DbHistory | Select-Object -ExpandProperty filelist | Select-Object PhysicalName -Unique).PhysicalName
                $DBHistoryPhysicalPathsTest = Test-DbaPath -SqlInstance $RestoreInstance -Path $DBHistoryPhysicalPaths
                $DBHistoryPhysicalPathsExists = ($DBHistoryPhysicalPathsTest | Where-Object FileExists -eq $True).FilePath
                $pathSep = Get-DbaPathSep -Server $RestoreInstance
                foreach ($path in $DBHistoryPhysicalPaths) {
                    if (($DBHistoryPhysicalPathsTest | Where-Object FilePath -eq $path).FileExists) {
                        if ($path -in $DBFileCheck) {
                            #If the Files are owned by the db we're restoring check for Continue or WithReplace. If not, then report error otherwise just carry on
                            if ($WithReplace -ne $True -and $Continue -ne $True) {
                                Write-Message -Message "File $path already exists on $SqlInstance and WithReplace not specified, cannot restore" -Level Warning
                                $VerificationErrors++
                            }
                        } elseif ($path -in $OtherFileCheck) {
                            Write-Message -Message "File $path already exists on $SqlInstance and owned by another database, cannot restore" -Level Warning
                            $VerificationErrors++
                        } elseif ($path -in $DBHistoryPhysicalPathsExists -and $RestoreInstance.VersionMajor -gt 8) {
                            Write-Message -Message "File $path already exists on $($SqlInstance.ComputerName), not owned by any database in $SqlInstance, will not overwrite." -Level Warning
                            $VerificationErrors++
                        }
                    } else {
                        <#
                        dang, Split-Path converts path separators always using the "current system" settings
                        PS C:> Split-Path -Path '/var/opt/mssql/data/foo.bak' -Parent
                        \var\opt\mssql\data
                        I'm not aware of a safe way to change this so...we do a little hack.
                        #>
                        $pathSep = Get-DbaPathSep -Server $RestoreInstance
                        $ParentPath = Split-Path $path -Parent
                        $ParentPath = $ParentPath.Replace('\', $pathSep)
                        if (!(Test-DbaPath -SqlInstance $RestoreInstance -Path $ParentPath) ) {
                            if (-not $OutputScriptOnly) {
                                $ConfirmMessage = "`n Creating Folder $ParentPath on $SqlInstance `n"
                                if ($Pscmdlet.ShouldProcess("$Path on $SqlInstance `n `n", $ConfirmMessage)) {
                                    if (New-DbaDirectory -SqlInstance $RestoreInstance -Path $ParentPath) {
                                        Write-Message -Message "Created Folder $ParentPath on $SqlInstance" -Level Verbose
                                    } else {
                                        Write-Message -Message "Failed to create $ParentPath on $SqlInstance" -Level Warning
                                        $VerificationErrors++
                                    }
                                }
                            } else {
                                Write-Message -Message "Parth $ParentPath on $SqlInstance does not exist" -Level Verbose
                            }
                        }
                    }
                }
                #Test for LSN chain
                if ($true -ne $Continue) {
                    if (!($DbHistory | Test-DbaLsnChain)) {
                        Write-Message -Message "LSN Check failed" -Level Verbose
                        $VerificationErrors++
                    }
                }
            }

            #Test all backups readable
            $allpaths = $DbHistory | Select-Object -ExpandProperty FullName
            $allpaths_validity = Test-DbaPath -SqlInstance $RestoreInstance -Path $allpaths
            foreach ($path in $allpaths_validity) {
                if ($path.FileExists -eq $false -and ($path.FilePath -notlike 'http*')) {
                    Write-Message -Message "Backup File $($path.FilePath) cannot be read by $($RestoreInstance.Name). Does the service account ($($RestoreInstance.ServiceAccount)) have permission?" -Level Warning
                    $VerificationErrors++
                }
            }

            if ($VerificationErrors -eq 0) {
                Write-Message -Message "Marking $Database as verified" -Level Verbose
                $InternalHistory | Where-Object {$_.Database -eq $Database} | Foreach-Object {$_.IsVerified = $True}
            } else {
                Write-Message -Message "Verification errors  = $VerificationErrors - Has not Passed" -Level Verbose
            }
        }
        $InternalHistory
    }
}
tools\dbatools\functions\Test-DbaBuild.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Test-DbaBuild {
    <#
    .SYNOPSIS
        Returns SQL Server Build "compliance" level on a build.

    .DESCRIPTION
        Returns info about the specific build of a SQL instance, including the SP, the CU and the reference KB, End Of Support, wherever possible. It adds a Compliance property as true/false, and adds details about the "targeted compliance".

    .PARAMETER Build
        Instead of connecting to a real instance, pass a string identifying the build to get the info back.

    .PARAMETER MinimumBuild
        This is the build version to test "compliance" against. Anything below this is flagged as not compliant.

    .PARAMETER MaxBehind
        Instead of using a specific MinimumBuild here you can pass "how many service packs and cu back" is the targeted compliance level. You can use xxSP or xxCU or both, where xx is a number. See the Examples for more information.

    .PARAMETER Latest
        Shortcut for specifying the very most up-to-date build available.

    .PARAMETER SqlInstance
        Target any number of instances, in order to return their compliance state.

    .PARAMETER SqlCredential
        When connecting to an instance, use the credentials specified.

    .PARAMETER Update
        Looks online for the most up to date reference, replacing the local one.

    .PARAMETER Quiet
        Makes the function just return $true/$false. It's useful if you use Test-DbaBuild in your own scripts.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: SqlBuild, Version
        Author: Simone Bizzotto (@niphold) | Friedrich Weinmann (@FredWeinmann)

        dbatools PowerShell module (https://dbatools.io, [email protected])
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaBuild

    .EXAMPLE
        PS C:\> Test-DbaBuild -Build "12.0.5540" -MinimumBuild "12.0.5557"

        Returns information about a build identified by "12.0.5540" (which is SQL 2014 with SP2 and CU4), which is not compliant as the minimum required
        build is "12.0.5557" (which is SQL 2014 with SP2 and CU8).

    .EXAMPLE
        PS C:\> Test-DbaBuild -Build "12.0.5540" -MaxBehind "1SP"

        Returns information about a build identified by "12.0.5540", making sure it is AT MOST 1 Service Pack "behind". For that version,
        that identifies an SP2, means accepting as the lowest compliance version as "12.0.4110", that identifies 2014 with SP1.

        Output column CUTarget is not relevant (empty). SPTarget and BuildTarget are filled in the result.

    .EXAMPLE
        PS C:\> Test-DbaBuild -Build "12.0.5540" -MaxBehind "1SP 1CU"

        Returns information about a build identified by "12.0.5540", making sure it is AT MOST 1 Service Pack "behind", plus 1 CU "behind". For that version,
        that identifies an SP2 and CU, rolling back 1 SP brings you to "12.0.4110", but given the latest CU for SP1 is CU13, the target "compliant" build
        will be "12.0.4511", which is 2014 with SP1 and CU12.

    .EXAMPLE
        PS C:\> Test-DbaBuild -Build "12.0.5540" -MaxBehind "0CU"

        Returns information about a build identified by "12.0.5540", making sure it is the latest CU release.

        Output columns CUTarget, SPTarget and BuildTarget are relevant. If the latest build is a service pack (not a CU), CUTarget will be empty.

    .EXAMPLE
        PS C:\> Test-DbaBuild -Build "12.0.5540" -Latest

        Returns information about a build identified by "12.0.5540", making sure it is the latest build available.

        Output columns CUTarget and SPTarget are not relevant (empty), only the BuildTarget is.

    .EXAMPLE
        PS C:\> Test-DbaBuild -Build "12.00.4502" -MinimumBuild "12.0.4511" -Update

        Same as before, but tries to fetch the most up to date index online. When the online version is newer, the local one gets overwritten.

    .EXAMPLE
        PS C:\> Test-DbaBuild -Build "12.0.4502","10.50.4260" -MinimumBuild "12.0.4511"

        Returns information builds identified by these versions strings.

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sqlserver2014a | Test-DbaBuild -MinimumBuild "12.0.4511"

        Integrate with other cmdlets to have builds checked for all your registered servers on sqlserver2014a.

    #>
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding()]
    param (
        [version[]]$Build,
        [version]$MinimumBuild,
        [string]$MaxBehind,
        [switch] $Latest,
        [parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [switch]$Update,
        [switch]$Quiet,
        [switch][Alias('Silent')]$EnableException
    )

    begin {
        #region Helper functions
        function Get-DbaBuildReferenceIndex {
            [CmdletBinding()]

            $DbatoolsData = Get-DbatoolsConfigValue -Name 'Path.DbatoolsData'
            $writable_idxfile = Join-Path $DbatoolsData "dbatools-buildref-index.json"
            $result = Get-Content $writable_idxfile -Raw | ConvertFrom-Json
            $result.Data | Select-Object @{ Name = "VersionObject"; Expression = { [version]$_.Version } }, *
        }

        $ComplianceSpec = @()
        $ComplianceSpecExclusiveParams = @('MinimumBuild', 'MaxBehind', 'Latest')
        foreach ($exclParam in $ComplianceSpecExclusiveParams) {
            if (Test-Bound -Parameter $exclParam) { $ComplianceSpec += $exclParam }
        }
        if ($ComplianceSpec.Length -gt 1) {
            Stop-Function -Category InvalidArgument -Message "-MinimumBuild, -MaxBehind and -Latest are mutually exclusive. Please choose only one. Quitting."
            return
        }
        if ($ComplianceSpec.Length -eq 0) {
            Stop-Function -Category InvalidArgument -Message "You need to choose one from -MinimumBuild, -MaxBehind and -Latest. Quitting."
            return
        }
        if ($MaxBehind) {
            $MaxBehindValidator = [regex]'^(?<howmany>[\d]+)(?<what>SP|CU)$'
            $pieces = $MaxBehind.Split(' ')	| Where-Object { $_ }
            try {
                $ParsedMaxBehind = @{}
                foreach ($piece in $pieces) {
                    $pieceMatch = $MaxBehindValidator.Match($piece)
                    if ($pieceMatch.Success -ne $true) {
                        Stop-Function -Message "MaxBehind has an invalid syntax ('$piece' could not be parsed correctly)" -ErrorRecord $_
                        return
                    } else {
                        $howmany = [int]$pieceMatch.Groups['howmany'].Value
                        $what = $pieceMatch.Groups['what'].Value
                        if ($ParsedMaxBehind.ContainsKey($what)) {
                            Stop-Function -Message "The specifier $what has been already passed" -ErrorRecord $_
                            return
                        } else {
                            $ParsedMaxBehind[$what] = $howmany
                        }
                    }
                }
                if (-not $ParsedMaxBehind.ContainsKey('SP')) {
                    $ParsedMaxBehind['SP'] = 0
                }
            } catch {
                Stop-Function -Message "Error parsing MaxBehind" -ErrorRecord $_
                return
            }
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }
        $hiddenProps = @()
        if (-not $SqlInstance) {
            $hiddenProps += 'SqlInstance'
        }
        if ($MinimumBuild) {
            $hiddenProps += 'MaxBehind', 'SPTarget', 'CUTarget', 'BuildTarget'
        } elseif ($MaxBehind -or $Latest) {
            $hiddenProps += 'MinimumBuild'
        }
        if ($Build) {
            $BuildVersions = Get-DbaBuildReference -Build $Build -Update:$Update -EnableException:$EnableException
        } elseif ($SqlInstance) {
            $BuildVersions = Get-DbaBuildReference -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Update:$Update -EnableException:$EnableException
        }
        # Moving it down here to only trigger after -Update was properly called
        if (!$IdxRef) {
            try {
                $IdxRef = Get-DbaBuildReferenceIndex
            } catch {
                Stop-Function -Message "Error loading SQL build reference" -ErrorRecord $_
                return
            }
        }
        foreach ($BuildVersion in $BuildVersions) {
            $inputbuild = $BuildVersion.Build
            $compliant = $false
            $targetSPName = $null
            $targetCUName = $null
            if ($BuildVersion.MatchType -eq 'Approximate') {
                Write-Message -Level Warning -Message "$($BuildVersion.Build) is not recognized as a correct version"
            }
            if ($MinimumBuild) {
                Write-Message -Level Debug -Message "Comparing $MinimumBuild to $inputbuild"
                if ($inputbuild -ge $MinimumBuild) {
                    $compliant = $true
                }
            } elseif ($MaxBehind -or $Latest) {
                $IdxVersion = $IdxRef | Where-Object Version -like "$($inputbuild.Major).$($inputbuild.Minor).*"
                $lastsp = ''
                $SPsAndCUs = @()
                foreach ($el in $IdxVersion) {
                    if ($null -ne $el.SP) {
                        $lastsp = $el.SP | Where-Object { $_ -ne 'LATEST' }
                        $SPsAndCUs += @{
                            VersionObject = $el.VersionObject
                            SP            = $lastsp
                        }
                    }
                    if ($null -ne $el.CU) {
                        $SPsAndCUs += @{
                            VersionObject = $el.VersionObject
                            SP            = $lastsp
                            CU            = $el.CU
                        }
                    }
                }
                $targetedBuild = $SPsAndCUs[0]
                if ($Latest) {
                    $targetedBuild = $IdxVersion[$IdxVersion.Length - 1]
                } else {
                    if ($ParsedMaxBehind.ContainsKey('SP')) {
                        [string[]]$AllSPs = $SPsAndCUs.SP | Select-Object -Unique
                        $targetSP = $AllSPs.Length - $ParsedMaxBehind['SP'] - 1
                        if ($targetSP -lt 0) {
                            $targetSP = 0
                        }
                        $targetSPName = $AllSPs[$targetSP]
                        Write-Message -Level Debug -Message "Target SP is $targetSPName - $targetSP on $($AllSPs.Length)"
                        $targetedBuild = $SPsAndCUs | Where-Object SP -eq $targetSPName | Select-Object -First 1
                    }
                    if ($ParsedMaxBehind.ContainsKey('CU')) {
                        $AllCUs = ($SPsAndCUs | Where-Object VersionObject -gt $targetedBuild.VersionObject).CU | Select-Object -Unique
                        if ($AllCUs.Length -gt 0) {
                            #CU after the targeted build available
                            $targetCU = $AllCUs.Length - $ParsedMaxBehind['CU'] - 1
                            if ($targetCU -lt 0) {
                                $targetCU = 0
                            }
                            $targetCUName = $AllCUs[$targetCU]
                            Write-Message -Level Debug -Message "Target CU is $targetCUName - $targetCU on $($AllCUs.Length)"
                            $targetedBuild = $SPsAndCUs | Where-Object VersionObject -gt $targetedBuild.VersionObject | Where-Object CU -eq $targetCUName | Select-Object -First 1
                        }
                    }
                }
                if ($inputbuild -ge $targetedBuild.VersionObject) {
                    $compliant = $true
                }
            }
            Add-Member -InputObject $BuildVersion -MemberType NoteProperty -Name Compliant -Value $compliant
            Add-Member -InputObject $BuildVersion -MemberType NoteProperty -Name MinimumBuild -Value $MinimumBuild
            Add-Member -InputObject $BuildVersion -MemberType NoteProperty -Name MaxBehind -Value $MaxBehind
            Add-Member -InputObject $BuildVersion -MemberType NoteProperty -Name SPTarget -Value $targetSPName
            Add-Member -InputObject $BuildVersion -MemberType NoteProperty -Name CUTarget -Value $targetCUName
            Add-Member -InputObject $BuildVersion -MemberType NoteProperty -Name BuildTarget -Value $targetedBuild.VersionObject
            if ($Quiet) {
                $BuildVersion.Compliant
            } else {
                $BuildVersion | Select-Object * | Select-DefaultView -ExcludeProperty $hiddenProps
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Test-DbaSqlBuild
    }
}
tools\dbatools\functions\Test-DbaCmConnection.ps1
function Test-DbaCmConnection {
    <#
    .SYNOPSIS
        Tests over which paths a computer can be managed.

    .DESCRIPTION
        Tests over which paths a computer can be managed.

        This function tries out the connectivity for:
        - Cim over WinRM
        - Cim over DCOM
        - Wmi
        - PowerShellRemoting
        Results will be written to the connectivity cache and will cause Get-DbaCmObject and Invoke-DbaCmMethod to connect using the way most likely to succeed. This way, it is likely the other commands will take less time to execute. These others too cache their results, in order to dynamically update connection statistics.

        This function ignores global configuration settings limiting which protocols may be used.

    .PARAMETER ComputerName
        The computer to test against.

    .PARAMETER Credential
        The credentials to use when running the test. Bad credentials are automatically cached as non-working. This behavior can be disabled by the 'Cache.Management.Disable.BadCredentialList' configuration.

    .PARAMETER Type
        The connection protocol types to test.
        By default, all types are tested.

        Note that this function will ignore global configurations limiting the types of connections available and test all connections specified here instead.

        Available connection protocol types: "CimRM", "CimDCOM", "Wmi", "PowerShellRemoting"

    .PARAMETER Force
        If this switch is enabled, the Alert will be dropped and recreated on Destination.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ComputerManagement, CIM
        Author: Friedrich Weinmann (@FredWeinmann)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        **This function should not be called from within dbatools. It is meant as a tool for users only.**

    .LINK
        https://dbatools.io/Test-DbaCmConnection

    .EXAMPLE
        PS C:\> Test-DbaCmConnection -ComputerName sql2014

        Performs a full-spectrum connection test against the computer sql2014. The results will be reported and registered. Future calls from Get-DbaCmObject will recognize the results and optimize the query.

    .EXAMPLE
        PS C:\> Test-DbaCmConnection -ComputerName sql2014 -Credential $null -Type CimDCOM, CimRM

        This test will run a connectivity test of CIM over DCOM and CIM over WinRM against the computer sql2014 using Windows Authentication.

        The results will be reported and registered. Future calls from Get-DbaCmObject will recognize the results and optimize the query.

    #>
    [CmdletBinding()]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWMICmdlet", "", Justification = "Using Get-WmiObject is used as a fallback for testing connections")]
    param (
        [Parameter(ValueFromPipeline)]
        [Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter[]]
        $ComputerName = $env:COMPUTERNAME,

        [System.Management.Automation.PSCredential]
        $Credential,

        [Sqlcollaborative.Dbatools.Connection.ManagementConnectionType[]]
        $Type = @("CimRM", "CimDCOM", "Wmi", "PowerShellRemoting"),

        [switch]
        $Force,

        [switch]
        [Alias('Silent')]$EnableException
    )

    begin {
        #region Configuration Values
        $disable_cache = Get-DbatoolsConfigValue -Name "ComputerManagement.Cache.Disable.All" -Fallback $false
        #Variable marked as unused by PSScriptAnalyzer
        #$disable_badcredentialcache = Get-DbatoolsConfigValue -Name "ComputerManagement.Cache.Disable.BadCredentialList" -Fallback $false
        #endregion Configuration Values

        #region Helper Functions
        function Test-ConnectionCimRM {
            [CmdletBinding()]
            param (
                [Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter]
                $ComputerName,

                [System.Management.Automation.PSCredential]
                $Credential
            )

            try {
                #Variable $os marked as unused by PSScriptAnalyzer replace with $null to catch output
                $null = $ComputerName.Connection.GetCimRMInstance($Credential, "Win32_OperatingSystem", "root\cimv2")

                New-Object PSObject -Property @{
                    Success       = "Success"
                    Timestamp     = Get-Date
                    Authenticated = $true
                }
            } catch {
                if (($_.Exception.InnerException -eq 0x8007052e) -or ($_.Exception.InnerException -eq 0x80070005)) {
                    New-Object PSObject -Property @{
                        Success       = "Error"
                        Timestamp     = Get-Date
                        Authenticated = $false
                    }
                } else {
                    New-Object PSObject -Property @{
                        Success       = "Error"
                        Timestamp     = Get-Date
                        Authenticated = $true
                    }
                }
            }
        }

        function Test-ConnectionCimDCOM {
            [CmdletBinding()]
            param (
                [Sqlcollaborative.Dbatools.Parameter.DbaCmConnectionParameter]
                $ComputerName,

                [System.Management.Automation.PSCredential]
                $Credential
            )

            try {
                #Variable $os marked as unused by PSScriptAnalyzer replace with $null to catch output
                $null = $ComputerName.Connection.GetCimDComInstance($Credential, "Win32_OperatingSystem", "root\cimv2")

                New-Object PSObject -Property @{
                    Success       = "Success"
                    Timestamp     = Get-Date
                    Authenticated = $true
                }
            } catch {
                if (($_.Exception.InnerException -eq 0x8007052e) -or ($_.Exception.InnerException -eq 0x80070005)) {
                    New-Object PSObject -Property @{
                        Success       = "Error"
                        Timestamp     = Get-Date
                        Authenticated = $false
                    }
                } else {
                    New-Object PSObject -Property @{
                        Success       = "Error"
                        Timestamp     = Get-Date
                        Authenticated = $true
                    }
                }
            }
        }

        function Test-ConnectionWmi {
            [CmdletBinding()]
            param (
                [string]
                $ComputerName,

                [System.Management.Automation.PSCredential]
                $Credential
            )

            try {
                #Variable $os marked as unused by PSScriptAnalyzer replace with $null to catch output
                $null = Get-WmiObject -ComputerName $ComputerName -Credential $Credential -Class Win32_OperatingSystem -ErrorAction Stop
                New-Object PSObject -Property @{
                    Success       = "Success"
                    Timestamp     = Get-Date
                    Authenticated = $true
                }
            } catch [System.UnauthorizedAccessException] {
                New-Object PSObject -Property @{
                    Success       = "Error"
                    Timestamp     = Get-Date
                    Authenticated = $false
                }
            } catch {
                New-Object PSObject -Property @{
                    Success       = "Error"
                    Timestamp     = Get-Date
                    Authenticated = $true
                }
            }
        }

        function Test-ConnectionPowerShellRemoting {
            [CmdletBinding()]
            param (
                [string]
                $ComputerName,

                [System.Management.Automation.PSCredential]
                $Credential
            )

            try {
                $parameters = @{
                    ScriptBlock  = { Get-WmiObject -Class Win32_OperatingSystem -ErrorAction Stop }
                    ComputerName = $ComputerName
                    ErrorAction  = 'Stop'
                }
                if ($Credential) { $parameters["Credential"] = $Credential }
                #Variable $os marked as unused by PSScriptAnalyzer replace with $null to catch output
                $null = Invoke-Command @parameters

                New-Object PSObject -Property @{
                    Success       = "Success"
                    Timestamp     = Get-Date
                    Authenticated = $true
                }
            } catch {
                # Will always consider authenticated, since any call with credentials to a server that doesn't exist will also carry invalid credentials error.
                # There simply is no way to differentiate between actual authentication errors and server not reached
                New-Object PSObject -Property @{
                    Success       = "Error"
                    Timestamp     = Get-Date
                    Authenticated = $true
                }
            }
        }
        #endregion Helper Functions
    }
    process {
        foreach ($ConnectionObject in $ComputerName) {
            if (-not $ConnectionObject.Success) { Stop-Function -Message "Failed to interpret input: $($ConnectionObject.Input)" -Category InvalidArgument -Target $ConnectionObject.Input -Continue}

            $Computer = $ConnectionObject.Connection.ComputerName.ToLower()
            Write-Message -Level VeryVerbose -Message "[$Computer] Testing management connection"

            #region Setup connection object
            $con = $ConnectionObject.Connection
            #endregion Setup connection object

            #region Handle credentials
            #Variable marked as unused by PSScriptAnalyzer
            #$BadCredentialsFound = $false
            if ($con.DisableBadCredentialCache) { $con.KnownBadCredentials.Clear() }
            elseif ($con.IsBadCredential($Credential) -and (-not $Force)) {
                Stop-Function -Message "[$Computer] The credentials supplied are on the list of known bad credentials, skipping. Use -Force to override this." -Continue -Category InvalidArgument -Target $Computer
            } elseif ($con.IsBadCredential($Credential) -and $Force) {
                $con.RemoveBadCredential($Credential)
            }
            #endregion Handle credentials

            #region Connectivity Tests
            :types foreach ($ConnectionType in $Type) {
                switch ($ConnectionType) {
                    #region CimRM
                    "CimRM" {
                        Write-Message -Level Verbose -Message "[$Computer] Testing management access using CIM over WinRM"
                        $res = Test-ConnectionCimRM -ComputerName $con -Credential $Credential
                        $con.LastCimRM = $res.Timestamp
                        $con.CimRM = $res.Success
                        Write-Message -Level VeryVerbose -Message "[$Computer] CIM over WinRM Results | Success: $($res.Success), Authentication: $($res.Authenticated)"

                        if (-not $res.Authenticated) {
                            Write-Message -Level Important -Message "[$Computer] The credentials supplied proved to be invalid. Skipping further tests"
                            $con.AddBadCredential($Credential)
                            break types
                        }
                    }
                    #endregion CimRM

                    #region CimDCOM
                    "CimDCOM" {
                        Write-Message -Level Verbose -Message "[$Computer] Testing management access using CIM over DCOM."
                        $res = Test-ConnectionCimDCOM -ComputerName $con -Credential $Credential
                        $con.LastCimDCOM = $res.Timestamp
                        $con.CimDCOM = $res.Success
                        Write-Message -Level VeryVerbose -Message "[$Computer] CIM over DCOM Results | Success: $($res.Success), Authentication: $($res.Authenticated)"

                        if (-not $res.Authenticated) {
                            Write-Message -Level Important -Message "[$Computer] The credentials supplied proved to be invalid. Skipping further tests."
                            $con.AddBadCredential($Credential)
                            break types
                        }
                    }
                    #endregion CimDCOM

                    #region Wmi
                    "Wmi" {
                        Write-Message -Level Verbose -Message "[$Computer] Testing management access using WMI."
                        $res = Test-ConnectionWmi -ComputerName $Computer -Credential $Credential
                        $con.LastWmi = $res.Timestamp
                        $con.Wmi = $res.Success
                        Write-Message -Level VeryVerbose -Message "[$Computer] WMI Results | Success: $($res.Success), Authentication: $($res.Authenticated)"

                        if (-not $res.Authenticated) {
                            Write-Message -Level Important -Message "[$Computer] The credentials supplied proved to be invalid. Skipping further tests"
                            $con.AddBadCredential($Credential)
                            break types
                        }
                    }
                    #endregion Wmi

                    #region PowerShell Remoting
                    "PowerShellRemoting" {
                        Write-Message -Level Verbose -Message "[$Computer] Testing management access using PowerShell Remoting."
                        $res = Test-ConnectionPowerShellRemoting -ComputerName $Computer -Credential $Credential
                        $con.LastPowerShellRemoting = $res.Timestamp
                        $con.PowerShellRemoting = $res.Success
                        Write-Message -Level VeryVerbose -Message "[$Computer] PowerShell Remoting Results | Success: $($res.Success)"
                    }
                    #endregion PowerShell Remoting
                }
            }
            #endregion Connectivity Tests

            if (-not $disable_cache) { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::Connections[$Computer] = $con }
            $con
        }
    }
    end {

    }
}
tools\dbatools\functions\Test-DbaConnection.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#

function Test-DbaConnection {
    <#
    .SYNOPSIS
        Tests the connection to a single instance.

    .DESCRIPTION
        Tests the ability to connect to an SQL Server instance outputting information about the server and instance.

    .PARAMETER SqlInstance
        The SQL Server Instance to test connection

    .PARAMETER Credential
        Credential object used to connect to the Computer as a different user

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: CIM, Test, Connection
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaConnection

    .EXAMPLE
        PS C:\> Test-DbaConnection SQL2016
        ```
        ComputerName         : SQL2016
        InstanceName         : MSSQLSERVER
        SqlInstance          : sql2016
        SqlVersion           : 13.0.4001
        ConnectingAsUser     : BASE\ctrlb
        ConnectSuccess       : True
        AuthType             : Windows Authentication
        AuthScheme           : KERBEROS
        TcpPort              : 1433
        IPAddress            : 10.2.1.5
        NetBiosName          : sql2016.base.local
        IsPingable           : True
        PSRemotingAccessible : True
        DomainName           : base.local
        LocalWindows         : 10.0.15063.0
        LocalPowerShell      : 5.1.15063.502
        LocalCLR             : 4.0.30319.42000
        LocalSMOVersion      : 13.0.0.0
        LocalDomainUser      : True
        LocalRunAsAdmin      : False
        ```

        Test connection to SQL2016 and outputs information collected
    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$Credential,
        [PSCredential]$SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            # Get local environment
            Write-Message -Level Verbose -Message "Getting local environment information"
            $localInfo = [pscustomobject]@{
                Windows    = [environment]::OSVersion.Version.ToString()
                Edition    = $PSVersionTable.PSEdition
                PowerShell = $PSVersionTable.PSversion.ToString()
                CLR        = [string]$PSVersionTable.CLRVersion
                SMO        = ((([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.Fullname -like "Microsoft.SqlServer.SMO,*" }).FullName -Split ", ")[1]).TrimStart("Version=")
                DomainUser = $env:computername -ne $env:USERDOMAIN
                RunAsAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
            }

            try {
                <# gather following properties #>
                <#
                        InputName        :
                        ComputerName     :
                        IPAddress        :
                        DNSHostName      :
                        DNSDomain        :
                        Domain           :
                        DNSHostEntry     :
                        FQDN             :
                        FullComputerName :
                     #>
                $resolved = Resolve-DbaNetworkName -ComputerName $instance.ComputerName -Credential $Credential
            } catch {
                Stop-Function -Message "Unable to resolve server information" -Category ConnectionError -Target $instance -ErrorRecord $_ -Continue
            }

            # Test for WinRM #Test-WinRM neh
            Write-Message -Level Verbose -Message "Checking remote acccess"
            try {
                $null = Invoke-Command2 -ComputerName $instance.ComputerName -Credential $Credential -ScriptBlock { Get-ChildItem } -ErrorAction Stop
                $remoting = $true
            } catch {
                $remoting = $_
            }

            # Test Connection first using Ping class which requires ICMP access then failback to tcp if pings are blocked
            Write-Message -Level Verbose -Message "Testing ping to $($instance.ComputerName)"
            $ping = New-Object System.Net.NetworkInformation.Ping
            $timeout = 1000 #milliseconds
            $reply = $ping.Send($instance.ComputerName, $timeout)
            $pingable = $reply.Status -eq 'Success'

            # this whole section does nothing and returns errors for default instances with a non-default port - baseaddress not defined
            # commenting it all out
            # SQL Server connection
            # if ($instance.InstanceName -ne "MSSQLSERVER") {
            #     #Variable marked as unused by PSScriptAnalyzer, need to be in PSCustomObject?
            #     #$sqlport = "N/A"
            # } else {
            #     Write-Message -Level Verbose -Message "Testing raw socket connection to default SQL port"
            #     $tcp = New-Object System.Net.Sockets.TcpClient
            #     try {
            #         $tcp.Connect($baseaddress, 1433)
            #         $tcp.Close()
            #         $tcp.Dispose()
            #     } catch {
            #         # here to avoid an empty catch
            #         $null = 1
            #     }
            # }

            try {
                $server = Connect-SqlInstance -SqlInstance $instance.FullSmoName -SqlCredential $SqlCredential
                $connectSuccess = $true
                $instanceName = $server.InstanceName
            } catch {
                $connectSuccess = $false
                $instanceName = $instance.InstanceName
                Stop-Function -Message "Issue connection to SQL Server on $instance" -Category ConnectionError -Target $instance -ErrorRecord $_ -Continue
            }

            $username = $server.ConnectionContext.TrueLogin
            if ($username -like "*\*") {
                $authType = "Windows Authentication"
            } else {
                $authType = "SQL Authentication"
            }

            # TCP Port
            try {
                $tcpport = (Get-DbaTcpPort -SqlInstance $server -EnableException).Port
            } catch {
                $tcpport = $_
            }

            # Auth Scheme
            try {
                $authscheme = (Test-DbaConnectionAuthScheme -SqlInstance $server -WarningVariable authwarning -WarningAction SilentlyContinue).AuthScheme
            } catch {
                $authscheme = $_
            }

            if ($authwarning) {
                $authscheme = "N/A"
            }

            [pscustomobject]@{
                ComputerName         = $resolved.ComputerName
                InstanceName         = $instanceName
                SqlInstance          = $instance.FullSmoName
                SqlVersion           = $server.Version
                ConnectingAsUser     = $username
                ConnectSuccess       = $connectSuccess
                AuthType             = $authType
                AuthScheme           = $authscheme
                TcpPort              = $tcpport
                IPAddress            = $resolved.IPAddress
                NetBiosName          = $resolved.FullComputerName
                IsPingable           = $pingable
                PSRemotingAccessible = $remoting
                DomainName           = $resolved.Domain
                LocalWindows         = $localInfo.Windows
                LocalPowerShell      = $localInfo.PowerShell
                LocalCLR             = $localInfo.CLR
                LocalSMOVersion      = $localInfo.SMO
                LocalDomainUser      = $localInfo.DomainUser
                LocalRunAsAdmin      = $localInfo.RunAsAdmin
                LocalEdition         = $localInfo.Edition
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Test-SqlConnection
    }
}
tools\dbatools\functions\Test-DbaConnectionAuthScheme.ps1
function Test-DbaConnectionAuthScheme {
    <#
    .SYNOPSIS
        Returns the transport protocol and authentication scheme of the connection. This is useful to determine if your connection is using Kerberos.

    .DESCRIPTION
        By default, this command will return the ConnectName, ServerName, Transport and AuthScheme of the current connection.

        ConnectName is the name you used to connect. ServerName is the name that the SQL Server reports as its @@SERVERNAME which is used to register its SPN. If you were expecting a Kerberos connection and got NTLM instead, ensure ConnectName and ServerName match.

        If -Kerberos or -Ntlm is specified, the $true/$false results of the test will be returned. Returns $true or $false by default for one server. Returns Server name and Results for more than one server.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Server(s) must be SQL Server 2005 or higher.

    .PARAMETER Kerberos
        If this switch is enabled, checks will be made for Kerberos authentication.

    .PARAMETER Ntlm
        If this switch is enabled, checks will be made for NTLM authentication.

    .PARAMETER Detailed
        Output all properties, will be deprecated in 1.0.0 release.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: SPN, Kerberos
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaConnectionAuthScheme

    .EXAMPLE
        PS C:\> Test-DbaConnectionAuthScheme -SqlInstance sqlserver2014a, sql2016

        Returns ConnectName, ServerName, Transport and AuthScheme for sqlserver2014a and sql2016.

    .EXAMPLE
        PS C:\> Test-DbaConnectionAuthScheme -SqlInstance sqlserver2014a -Kerberos

        Returns $true or $false depending on if the connection is Kerberos or not.

    .EXAMPLE
        PS C:\> Test-DbaConnectionAuthScheme -SqlInstance sqlserver2014a | Select-Object *

        Returns the results of "SELECT * from sys.dm_exec_connections WHERE session_id = @@SPID"

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential", "Cred")]
        [PSCredential]$SqlCredential,
        [switch]$Kerberos,
        [switch]$Ntlm,
        [switch]$Detailed,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter Detailed

        $sql = "SELECT  SERVERPROPERTY('MachineName') AS ComputerName,
                            ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
                            SERVERPROPERTY('ServerName') AS SqlInstance,
                            session_id as SessionId, most_recent_session_id as MostRecentSessionId, connect_time as ConnectTime,
                            net_transport as Transport, protocol_type as ProtocolType, protocol_version as ProtocolVersion,
                            endpoint_id as EndpointId, encrypt_option as EncryptOption, auth_scheme as AuthScheme, node_affinity as NodeAffinity,
                            num_reads as NumReads, num_writes as NumWrites, last_read as LastRead, last_write as LastWrite,
                            net_packet_size as PacketSize, client_net_address as ClientNetworkAddress, client_tcp_port as ClientTcpPort,
                            local_net_address as ServerNetworkAddress, local_tcp_port as ServerTcpPort, connection_id as ConnectionId,
                            parent_connection_id as ParentConnectionId, most_recent_sql_handle as MostRecentSqlHandle
                            FROM sys.dm_exec_connections WHERE session_id = @@SPID"
    }

    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            Write-Message -Level Verbose -Message "Getting results for the following query: $sql."
            try {
                $results = $server.Query($sql)
            } catch {
                Stop-Function -Message "Failure" -Target $server -Exception $_ -Continue
            }

            # sorry, standards!
            if ($Kerberos -or $Ntlm) {
                if ($Ntlm) {
                    $auth = 'NTLM'
                } else {
                    $auth = 'Kerberos'
                }
                [PSCustomObject]@{
                    ComputerName = $results.ComputerName
                    InstanceName = $results.InstanceName
                    SqlInstance  = $results.SqlInstance
                    Result       = ($server.AuthScheme -eq $auth)
                } | Select-DefaultView -Property SqlInstance, Result
            } else {
                Select-DefaultView -InputObject $results -Property ComputerName, InstanceName, SqlInstance, Transport, AuthScheme
            }
        }
    }
}
tools\dbatools\functions\Test-DbaDbCollation.ps1
function Test-DbaDbCollation {
    <#
    .SYNOPSIS
        Compares Database Collations to Server Collation

    .DESCRIPTION
        Compares Database Collations to Server Collation

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.

    .PARAMETER Detailed
        Output all properties, will be deprecated in 1.0.0 release.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database, Collation
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaDbCollation

    .EXAMPLE
        PS C:\> Test-DbaDbCollation -SqlInstance sqlserver2014a

        Returns server name, database name and true/false if the collations match for all databases on sqlserver2014a.

    .EXAMPLE
        PS C:\> Test-DbaDbCollation -SqlInstance sqlserver2014a -Database db1, db2

        Returns information for the db1 and db2 databases on sqlserver2014a.

    .EXAMPLE
        PS C:\> Test-DbaDbCollation -SqlInstance sqlserver2014a, sql2016 -Exclude db1

        Returns information for database and server collations for all databases except db1 on sqlserver2014a and sql2016.

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sql2016 | Test-DbaDbCollation

        Returns db/server collation information for every database on every server listed in the Central Management Server on sql2016.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$Detailed,
        [switch]$EnableException
    )
    begin {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Parameter "Detailed"
    }
    process {
        foreach ($instance in $sqlinstance) {
            # Try connecting to the instance
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $dbs = $server.Databases | Where-Object IsAccessible

            if ($Database) {
                $dbs = $dbs | Where-Object { $Database -contains $_.Name }
            }

            if ($ExcludeDatabase) {
                $dbs = $dbs | Where-Object Name -NotIn $ExcludeDatabase
            }

            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Processing $($db.name) on $servername."
                [PSCustomObject]@{
                    ComputerName      = $server.ComputerName
                    InstanceName      = $server.ServiceName
                    SqlInstance       = $server.DomainInstanceName
                    Database          = $db.name
                    ServerCollation   = $server.collation
                    DatabaseCollation = $db.collation
                    IsEqual           = $db.collation -eq $server.collation
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Test-DbaDatabaseCollation
    }
}
tools\dbatools\functions\Test-DbaDbCompatibility.ps1
function Test-DbaDbCompatibility {
    <#
    .SYNOPSIS
        Compares Database Compatibility level to Server Compatibility

    .DESCRIPTION
        Compares Database Compatibility level to Server Compatibility

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER Credential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.

    .PARAMETER Detailed
        Will be deprecated in 1.0.0 release.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database, Compatibility
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaDbCompatibility

    .EXAMPLE
        PS C:\> Test-DbaDbCompatibility -SqlInstance sqlserver2014a

        Returns server name, database name and true/false if the compatibility level match for all databases on sqlserver2014a.

    .EXAMPLE
        PS C:\> Test-DbaDbCompatibility -SqlInstance sqlserver2014a -Database db1, db2

        Returns detailed information for database and server compatibility level for the db1 and db2 databases on sqlserver2014a.

    .EXAMPLE
        PS C:\> Test-DbaDbCompatibility -SqlInstance sqlserver2014a, sql2016 -Exclude db1

        Returns detailed information for database and server compatibility level for all databases except db1 on sqlserver2014a and sql2016.

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sql2014 | Test-DbaDbCompatibility

        Returns db/server compatibility information for every database on every server listed in the Central Management Server on sql2016.

    #>
    [CmdletBinding()]
    [OutputType("System.Collections.ArrayList")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$Credential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$Detailed,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Parameter "Detailed"
    }

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $serverversion = "Version$($server.VersionMajor)0"
            $dbs = $server.Databases | Where-Object IsAccessible

            if ($Database) {
                $dbs = $dbs | Where-Object { $Database -contains $_.Name }
            }

            if ($ExcludeDatabase) {
                $dbs = $dbs | Where-Object Name -NotIn $ExcludeDatabase
            }

            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Processing $($db.name) on $instance."
                [PSCustomObject]@{
                    ComputerName          = $server.ComputerName
                    InstanceName          = $server.ServiceName
                    SqlInstance           = $server.DomainInstanceName
                    ServerLevel           = $serverversion
                    Database              = $db.name
                    DatabaseCompatibility = $db.CompatibilityLevel
                    IsEqual               = $db.CompatibilityLevel -eq $serverversion
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Test-DbaDatabaseCompatibility
    }
}
tools\dbatools\functions\Test-DbaDbCompression.ps1
function Test-DbaDbCompression {
    <#
    .SYNOPSIS
        Returns tables and indexes with preferred compression setting.
    .DESCRIPTION
        This function returns the results of a full table/index compression analysis and the estimated, best option to date for either NONE, Page, or Row Compression.

        Remember Uptime is critical, the longer uptime, the more accurate the analysis is, and it would be best if you utilized Get-DbaUptime first, before running this command.

        Test-DbaDbCompression script derived from GitHub and the tigertoolbox
        (https://github.com/Microsoft/tigertoolbox/tree/master/Evaluate-Compression-Gains)
        In the output, you will find the following information:
        - Column Percent_Update shows the percentage of update operations on a specific table, index, or partition, relative to total operations on that object. The lower the percentage of Updates (that is, the table, index, or partition is infrequently updated), the better candidate it is for page compression.
        - Column Percent_Scan shows the percentage of scan operations on a table, index, or partition, relative to total operations on that object. The higher the value of Scan (that is, the table, index, or partition is mostly scanned), the better candidate it is for page compression.
        - Column Compression_Type_Recommendation can have four possible outputs indicating where there is most gain, if any: 'PAGE', 'ROW', 'NO_GAIN' or '?'. When the output is '?' this approach could not give a recommendation, so as a rule of thumb I would lean to ROW if the object suffers mainly UPDATES, or PAGE if mainly INSERTS, but this is where knowing your workload is essential. When the output is 'NO_GAIN' well, that means that according to sp_estimate_data_compression_savings no space gains will be attained when compressing, as in the above output example, where compressing would grow the affected object.

        This script will execute on the context of the current database.
        Also be aware that this may take a while to execute on large objects, because if the IS locks taken by the
        sp_estimate_data_compression_savings cannot be honored, the SP will be blocked.
        It only considers Row or Page Compression (not column compression)
        It only evaluates User Tables

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER Schema
        Filter to only get specific schemas If unspecified, all schemas will be processed.

    .PARAMETER Table
        Filter to only get specific tables If unspecified, all User tables will be processed.

    .PARAMETER ResultSize
        Allows you to limit the number of results returned, as some systems can have very large number of tables.  Default value is no restriction.

    .PARAMETER Rank
        Allows you to specify the field used for ranking when determining the ResultSize
        Can be either TotalPages, UsedPages or TotalRows with default of TotalPages. Only applies when ResultSize is used.

    .PARAMETER FilterBy
        Allows you to specify level of filtering when determining the ResultSize
        Can be at either Table, Index or Partition level with default of Partition. Only applies when ResultSize is used.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .INPUTS
        Accepts a DbaInstanceParameter. Any collection of SQL Server Instance names or SMO objects can be piped to command.

    .OUTPUTS
        Returns a PsCustomObject with following fields: ComputerName, InstanceName, SqlInstance, Database, IndexName, Partition, IndexID, PercentScan, PercentUpdate, RowEstimatePercentOriginal, PageEstimatePercentOriginal, CompressionTypeRecommendation, SizeCurrent, SizeRequested, PercentCompression

    .NOTES
        Tags: Compression, Table, Database
        Author: Jason Squires (@js_0505), [email protected]

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaDbCompression

    .EXAMPLE
        PS C:\> Test-DbaDbCompression -SqlInstance localhost

        Returns results of all potential compression options for all databases for the default instance on the local host. Returns a recommendation of either Page, Row or NO_GAIN

    .EXAMPLE
        PS C:\> Test-DbaDbCompression -SqlInstance ServerA

        Returns results of all potential compression options for all databases on the instance ServerA

    .EXAMPLE
        PS C:\> Test-DbaDbCompression -SqlInstance ServerA -Database DBName | Out-GridView

        Returns results of all potential compression options for a single database DBName with the recommendation of either Page or Row or NO_GAIN in a nicely formatted GridView

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> Test-DbaDbCompression -SqlInstance ServerA -ExcludeDatabase MyDatabase -SqlCredential $cred

        Returns results of all potential compression options for all databases except MyDatabase on instance ServerA using SQL credentials to authentication to ServerA.
        Returns the recommendation of either Page, Row or NO_GAIN

    .EXAMPLE
        PS C:\> Test-DbaDbCompression -SqlInstance ServerA -Schema Test -Table MyTable

        Returns results of all potential compression options for the Table Test.MyTable in instance ServerA on ServerA and ServerB.
        Returns the recommendation of either Page, Row or NO_GAIN.
        Returns a result for each partition of any Heap, Clustered or NonClustered index.

    .EXAMPLE
        PS C:\> Test-DbaDbCompression -SqlInstance ServerA, ServerB -ResultSize 10

        Returns results of all potential compression options for all databases on ServerA and ServerB.
        Returns the recommendation of either Page, Row or NO_GAIN.
        Returns results for the top 10 partitions by TotalPages used per database.

    .EXAMPLE
        PS C:\> ServerA | Test-DbaDbCompression -Schema Test -ResultSize 10 -Rank UsedPages -FilterBy Table

        Returns results of all potential compression options for all databases on ServerA containing a schema Test
        Returns results for the top 10 Tables by Used Pages per database.
        Results are split by Table, Index and Partition so more than 10 results may be returned.

    .EXAMPLE
        PS C:\> $servers = 'Server1','Server2'
        PS C:\> $servers | Test-DbaDbCompression -Database DBName | Out-GridView

        Returns results of all potential compression options for a single database DBName on Server1 or Server2
        Returns the recommendation of either Page, Row or NO_GAIN in a nicely formatted GridView

    .EXAMPLE
        PS C:\> $cred = Get-Credential sqladmin
        PS C:\> Test-DbaDbCompression -SqlInstance ServerA -Database MyDB -SqlCredential $cred -Schema Test -Table Test1, Test2

        Returns results of all potential compression options for objects in Database MyDb on instance ServerA using SQL credentials to authentication to ServerA.
        Returns the recommendation of either Page, Row or NO_GAIN for tables with SchemA Test and name in Test1 or Test2

    .EXAMPLE
        PS C:\> $servers = 'Server1','Server2'
        PS C:\> foreach ($svr in $servers) {
        >> Test-DbaDbCompression -SqlInstance $svr | Export-Csv -Path C:\temp\CompressionAnalysisPAC.csv -Append
        >> }

        This produces a full analysis of all your servers listed and is pushed to a csv for you to analyze.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [string[]]$Schema,
        [string[]]$Table,
        [int]$ResultSize,
        [ValidateSet('TotalPages', 'UsedPages', 'TotalRows')]
        [string]$Rank = 'TotalPages',
        [ValidateSet('Partition', 'Index', 'Table')]
        [string]$FilterBy = 'Partition',
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        Write-Message -Level System -Message "Bound parameters: $($PSBoundParameters.Keys -join ", ")"

        if ($Schema) {
            $sqlSchemaWhere = "AND s.name IN ('$($Schema -join "','")')"
        }

        if ($Table) {
            $sqlTableWhere = "AND t.name IN ('$($Table -join "','")')"
        }

        if ($ResultSize) {
            $sqlOrderBy = switch ($Rank) {
                UsedPages { 'UsedSpaceKB' }
                TotalRows { 'RowCounts' }
                default { 'TotalSpaceKB' }
            }

            if ($FilterBy -eq 'Table') {
                $sqlJoinFiltered = 'AND t.TableName = tdc.TableName COLLATE DATABASE_DEFAULT'
                $indexSQL = '0 as [IndexID]'
                $partitionSQL = '0 AS [Partition]'
                $groupBySQL = 's.Name, t.Name'
            } elseif ($FilterBy -eq 'Index') {
                $sqlJoinFiltered = 'AND t.TableName = tdc.TableName COLLATE DATABASE_DEFAULT AND t.IndexID = tdc.IndexID'
                $indexSQL = 'i.index_id as [IndexID]'
                $partitionSQL = '0 AS [Partition]'
                $groupBySQL = 's.Name, t.Name, i.index_id'
            } else {
                $sqlJoinFiltered = 'AND t.TableName = tdc.TableName COLLATE DATABASE_DEFAULT AND t.IndexID = tdc.IndexID AND t.[Partition] = tdc.[Partition]'
                $indexSQL = 'i.index_id as [IndexID]'
                $partitionSQL = 'p.partition_number AS [Partition]'
                $groupBySQL = 's.Name, t.Name, i.index_id, p.partition_number'
            }

            $sqlRestrict = "-- remove tables not in Top N
                With TopN(SchemaName, TableName, IndexID, [Partition], RowCounts, TotalSpaceKB, UsedSpaceKB) as
                (
                    SELECT TOP $ResultSize
                        s.Name AS SchemaName,
                        t.NAME as TableName,
                        $indexSQL,
                        $partitionSQL,
                        SUM(p.rows) AS RowCounts,
                        SUM(a.total_pages) * 8 AS TotalSpaceKB,
                        SUM(a.used_pages) * 8 AS UsedSpaceKB
                    FROM
                        sys.tables t
                    INNER JOIN
                        sys.indexes i ON t.OBJECT_ID = i.object_id
                    INNER JOIN
                        sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
                    INNER JOIN
                        sys.allocation_units a ON p.partition_id = a.container_id
                    LEFT OUTER JOIN
                        sys.schemas s ON t.schema_id = s.schema_id
                    WHERE objectproperty(t.object_id, 'IsUserTable') = 1
                        AND p.data_compression_desc = 'NONE'
                        AND p.rows > 0
                        $sqlSchemaWhere
                        $sqlTableWhere
                    GROUP BY
                        $groupBySQL
                    ORDER BY
                        $sqlOrderBy Desc
                )
                DELETE tdc
                FROM ##testdbacompression tdc
                LEFT JOIN TopN t
                    ON t.SchemaName = tdc.[Schema] COLLATE DATABASE_DEFAULT
                    $sqlJoinFiltered
                WHERE t.IndexID IS NULL;"
        }
    }

    process {

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failed to process Instance $Instance" -ErrorRecord $_ -Target $instance -Continue
            }

            $Server.ConnectionContext.StatementTimeout = 0
            $sqlVersion = $(Get-DbaBuildReference -SqlInstance $server).Build.Major

            $sqlVersionRestrictions = @()

            if ($sqlVersion -ge 12) {
                $sqlVersionRestrictions += "
            BEGIN
                -- remove memory optimized tables
                DELETE tdc
                FROM ##testdbacompression tdc
                INNER JOIN sys.tables t
                    ON SCHEMA_NAME(t.schema_id) = tdc.[Schema] COLLATE DATABASE_DEFAULT
                    AND t.name = tdc.TableName COLLATE DATABASE_DEFAULT
                WHERE t.is_memory_optimized = 1
            END"
            }
            if ($sqlVersion -ge 13) {
                $sqlVersionRestrictions += "
            BEGIN
                -- remove tables with encrypted columns
                DELETE tdc
                FROM ##testdbacompression tdc
                INNER JOIN sys.tables t
                    ON SCHEMA_NAME(t.schema_id) = tdc.[Schema] COLLATE DATABASE_DEFAULT
                    AND t.name = tdc.TableName COLLATE DATABASE_DEFAULT
                INNER JOIN sys.columns c
                    ON t.object_id = c.object_id
                WHERE encryption_type IS NOT NULL
            END"
            }
            if ($sqlVersion -ge 14) {
                $sqlVersionRestrictions += "
            BEGIN
                -- remove graph (node/edge) tables
                DELETE tdc
                FROM ##testdbacompression tdc
                INNER JOIN sys.tables t
                    ON tdc.[Schema] = SCHEMA_NAME(t.schema_id) COLLATE DATABASE_DEFAULT
                    AND tdc.TableName = t.name COLLATE DATABASE_DEFAULT
                WHERE (is_node = 1 OR is_edge = 1)
            END"
            }
            $sql = "SET NOCOUNT ON;

IF OBJECT_ID('tempdb..##testdbacompression', 'U') IS NOT NULL
    DROP TABLE ##testdbacompression

IF OBJECT_ID('tempdb..##tmpEstimateRow', 'U') IS NOT NULL
    DROP TABLE ##tmpEstimateRow

IF OBJECT_ID('tempdb..##tmpEstimatePage', 'U') IS NOT NULL
    DROP TABLE ##tmpEstimatePage

CREATE TABLE ##testdbacompression (
    [Schema] SYSNAME
    ,[TableName] SYSNAME
    ,[ObjectId] INT
    ,[IndexName] SYSNAME NULL
    ,[Partition] INT
    ,[IndexID] INT
    ,[IndexType] VARCHAR(25)
    ,[PercentScan] SMALLINT
    ,[PercentUpdate] SMALLINT
    ,[RowEstimatePercentOriginal] BIGINT
    ,[PageEstimatePercentOriginal] BIGINT
    ,[CompressionTypeRecommendation] VARCHAR(7)
    ,SizeCurrent BIGINT
    ,SizeRequested BIGINT
    ,PercentCompression NUMERIC(10, 2)
    );

CREATE TABLE ##tmpEstimateRow (
    objname SYSNAME
    ,schname SYSNAME
    ,indid INT
    ,partnr INT
    ,SizeCurrent BIGINT
    ,SizeRequested BIGINT
    ,SampleCurrent BIGINT
    ,SampleRequested BIGINT
    );

CREATE TABLE ##tmpEstimatePage (
    objname SYSNAME
    ,schname SYSNAME
    ,indid INT
    ,partnr INT
    ,SizeCurrent BIGINT
    ,SizeRequested BIGINT
    ,SampleCurrent BIGINT
    ,SampleRequested BIGINT
    );

INSERT INTO ##testdbacompression (
    [Schema]
    ,[TableName]
    ,[ObjectId]
    ,[IndexName]
    ,[Partition]
    ,[IndexID]
    ,[IndexType]
    ,[PercentScan]
    ,[PercentUpdate]
    )
    SELECT s.NAME AS [Schema]
    ,t.NAME AS [TableName]
    ,t.OBJECT_ID AS [OBJECTID]
    ,x.NAME AS [IndexName]
    ,p.partition_number AS [Partition]
    ,x.Index_ID AS [IndexID]
    ,x.type_desc AS [IndexType]
    ,NULL AS [PercentScan]
    ,NULL AS [PercentUpdate]
FROM sys.tables t
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
INNER JOIN sys.indexes x ON x.object_id = t.object_id
INNER JOIN sys.partitions p ON x.object_id = p.object_id
    AND x.Index_ID = p.Index_ID
WHERE objectproperty(t.object_id, 'IsUserTable') = 1
    AND p.data_compression_desc = 'NONE'
    AND p.rows > 0
    $sqlSchemaWhere
    $sqlTableWhere
ORDER BY [TableName] ASC;

$sqlRestrict

$sqlVersionRestrictions

DECLARE @schema SYSNAME
    ,@tbname SYSNAME
    ,@ixid INT

DECLARE cur CURSOR FAST_FORWARD
FOR
SELECT [Schema]
    ,[TableName]
    ,[IndexID]
FROM ##testdbacompression

OPEN cur

FETCH NEXT
FROM cur
INTO @schema
    ,@tbname
    ,@ixid

WHILE @@FETCH_STATUS = 0
BEGIN
    DECLARE @sqlcmd NVARCHAR(500)

    SET @sqlcmd = 'EXEC sp_estimate_data_compression_savings ''' + @schema + ''', ''' + @tbname + ''', ''' + cast(@ixid AS VARCHAR) + ''', NULL, ''ROW''';

    INSERT INTO ##tmpEstimateRow (
        objname
        ,schname
        ,indid
        ,partnr
        ,SizeCurrent
        ,SizeRequested
        ,SampleCurrent
        ,SampleRequested
        )
    EXECUTE sp_executesql @sqlcmd

    SET @sqlcmd = 'EXEC sp_estimate_data_compression_savings ''' + @schema + ''', ''' + @tbname + ''', ''' + cast(@ixid AS VARCHAR) + ''', NULL, ''PAGE''';

    INSERT INTO ##tmpEstimatePage (
        objname
        ,schname
        ,indid
        ,partnr
        ,SizeCurrent
        ,SizeRequested
        ,SampleCurrent
        ,SampleRequested
        )
    EXECUTE sp_executesql @sqlcmd

    FETCH NEXT
    FROM cur
    INTO @schema
        ,@tbname
        ,@ixid
END

CLOSE cur

DEALLOCATE cur;

--Update usage and partition_number - If database was restore the sys.dm_db_index_operational_stats will be empty until tables have accesses. Executing the sp_estimate_data_compression_savings first will make those entries appear
UPDATE ##testdbacompression
SET
 [PercentScan] =
     case when (i.range_scan_count + i.leaf_insert_count + i.leaf_delete_count + i.leaf_update_count + i.leaf_page_merge_count + i.singleton_lookup_count) = 0 THEN 0
     ELSE i.range_scan_count * 100.0 / NULLIF((i.range_scan_count + i.leaf_insert_count + i.leaf_delete_count + i.leaf_update_count + i.leaf_page_merge_count + i.singleton_lookup_count), 0)
     END
 ,[PercentUpdate] =
    case when (i.range_scan_count + i.leaf_insert_count + i.leaf_delete_count + i.leaf_update_count + i.leaf_page_merge_count + i.singleton_lookup_count) = 0 THEN 0
    ELSE i.leaf_update_count * 100.0 / NULLIF((i.range_scan_count + i.leaf_insert_count + i.leaf_delete_count + i.leaf_update_count + i.leaf_page_merge_count + i.singleton_lookup_count), 0)
    END
FROM sys.dm_db_index_operational_stats(db_id(), NULL, NULL, NULL) i
INNER JOIN ##testdbacompression tmp
    ON tmp.ObjectId = i.object_id
    AND tmp.IndexID = i.index_id;


WITH tmp_cte (
    objname
    ,schname
    ,indid
    ,partnr
    ,pct_of_orig_row
    ,pct_of_orig_page
    ,SizeCurrent
    ,SizeRequested
    )
AS (
    SELECT tr.objname
        ,tr.schname
        ,tr.indid
        ,tr.partnr
        ,(tr.SampleRequested * 100) / CASE
            WHEN tr.SampleCurrent = 0
                THEN 1
            ELSE tr.SampleCurrent
            END AS pct_of_orig_row
        ,(tp.SampleRequested * 100) / CASE
            WHEN tp.SampleCurrent = 0
                THEN 1
            ELSE tp.SampleCurrent
            END AS pct_of_orig_page
        ,tr.SizeCurrent
        ,tr.SizeRequested
    FROM ##tmpestimaterow tr
    INNER JOIN ##tmpestimatepage tp ON tr.objname = tp.objname
        AND tr.schname = tp.schname
        AND tr.indid = tp.indid
        AND tr.partnr = tp.partnr
    )
UPDATE ##testdbacompression
SET [RowEstimatePercentOriginal] = tcte.pct_of_orig_row
    ,[PageEstimatePercentOriginal] = tcte.pct_of_orig_page
    ,SizeCurrent = tcte.SizeCurrent
    ,SizeRequested = tcte.SizeRequested
    ,PercentCompression = 100 - (cast(tcte.[SizeRequested] AS NUMERIC(21, 2)) * 100 / (tcte.[SizeCurrent] - ABS(SIGN(tcte.[SizeCurrent])) + 1))
FROM tmp_cte tcte
    ,##testdbacompression tcomp
WHERE tcte.objname = tcomp.TableName
    AND tcte.schname = tcomp.[schema]
    AND tcte.indid = tcomp.IndexID
    AND tcte.partnr = tcomp.Partition;

WITH tmp_cte2 (
    TableName
    ,[schema]
    ,IndexID
    ,[CompressionTypeRecommendation]
    )
AS (
    SELECT TableName
        ,[schema]
        ,IndexID
        ,CASE
            WHEN [RowEstimatePercentOriginal] >= 100
                AND [PageEstimatePercentOriginal] >= 100
                THEN 'NO_GAIN'
            WHEN [PercentUpdate] >= 10
                THEN 'ROW'
            WHEN [PercentScan] <= 1
                AND [PercentUpdate] <= 1
                AND [RowEstimatePercentOriginal] < [PageEstimatePercentOriginal]
                THEN 'ROW'
            WHEN [PercentScan] <= 1
                AND [PercentUpdate] <= 1
                AND [RowEstimatePercentOriginal] > [PageEstimatePercentOriginal]
                THEN 'PAGE'
            WHEN [PercentScan] >= 60
                AND [PercentUpdate] <= 5
                THEN 'PAGE'
            WHEN [PercentScan] <= 35
                AND [PercentUpdate] <= 5
                THEN '?'
            ELSE 'ROW'
            END
    FROM ##testdbacompression
    )
UPDATE ##testdbacompression
SET [CompressionTypeRecommendation] = tcte2.[CompressionTypeRecommendation]
FROM tmp_cte2 tcte2
    ,##testdbacompression tcomp2
WHERE tcte2.TableName = tcomp2.TableName
    AND tcte2.[schema] = tcomp2.[schema]
    AND tcte2.IndexID = tcomp2.IndexID;

SET NOCOUNT ON;

SELECT DBName = DB_Name()
    ,[Schema]
    ,[TableName]
    ,[IndexName]
    ,[Partition]
    ,[IndexID]
    ,[IndexType]
    ,[PercentScan]
    ,[PercentUpdate]
    ,[RowEstimatePercentOriginal]
    ,[PageEstimatePercentOriginal]
    ,[CompressionTypeRecommendation]
    ,SizeCurrentKB = [SizeCurrent]
    ,SizeRequestedKB = [SizeRequested]
    ,PercentCompression
FROM ##testdbacompression;

IF OBJECT_ID('tempdb..##setdbacompression', 'U') IS NOT NULL
    DROP TABLE ##testdbacompression

IF OBJECT_ID('tempdb..##tmpEstimateRow', 'U') IS NOT NULL
    DROP TABLE ##tmpEstimateRow

IF OBJECT_ID('tempdb..##tmpEstimatePage', 'U') IS NOT NULL
    DROP TABLE ##tmpEstimatePage;

"
            Write-Message -Level Debug -Message "SQL Statement: $sql"
            [long]$instanceVersionNumber = $($server.VersionString).Replace(".", "")


            #If SQL Server 2016 SP1 (13.0.4001.0) or higher every version supports compression.
            if ($Server.EngineEdition -ne "EnterpriseOrDeveloper" -and $instanceVersionNumber -lt 13040010) {
                Stop-Function -Message "Compression before SQLServer 2016 SP1 (13.0.4001.0) is only supported by enterprise, developer or evaluation edition. $Server has version $($server.VersionString) and edition is $($Server.EngineEdition)." -Target $db -Continue
            }
            #Filter Database list
            try {
                $dbs = $server.Databases | Where-Object IsAccessible

                if ($Database) {
                    $dbs = $dbs | Where-Object { $Database -contains $_.Name -and $_.IsSystemObject -eq 0 }
                }

                else {
                    $dbs = $dbs | Where-Object { $_.IsSystemObject -eq 0 }
                }

                if (Test-Bound "ExcludeDatabase") {
                    $dbs = $dbs | Where-Object Name -NotIn $ExcludeDatabase
                }
            } catch {
                Stop-Function -Message "Unable to gather list of databases for $instance" -Target $instance -ErrorRecord $_ -Continue
            }

            foreach ($db in $dbs) {
                try {
                    $dbCompatibilityLevel = [int]($db.CompatibilityLevel.ToString().Replace('Version', ''))

                    Write-Message -Level Verbose -Message "Querying $instance - $db"
                    if ($db.status -ne 'Normal' -or $db.IsAccessible -eq $false) {
                        Write-Message -Level Warning -Message "$db is not accessible." -Target $db
                        Continue
                    }

                    if ($dbCompatibilityLevel -lt 100) {
                        Stop-Function -Message "$db has a compatibility level lower than Version100 and will be skipped." -Target $db -Continue
                        Continue
                    }
                    #Execute query against individual database and add to output
                    foreach ($row in ($server.Query($sql, $db.Name))) {
                        [pscustomobject]@{
                            ComputerName                  = $server.ComputerName
                            InstanceName                  = $server.ServiceName
                            SqlInstance                   = $server.DomainInstanceName
                            Database                      = $row.DBName
                            Schema                        = $row.Schema
                            TableName                     = $row.TableName
                            IndexName                     = $row.IndexName
                            Partition                     = $row.Partition
                            IndexID                       = $row.IndexID
                            IndexType                     = $row.IndexType
                            PercentScan                   = $row.PercentScan
                            PercentUpdate                 = $row.PercentUpdate
                            RowEstimatePercentOriginal    = $row.RowEstimatePercentOriginal
                            PageEstimatePercentOriginal   = $row.PageEstimatePercentOriginal
                            CompressionTypeRecommendation = $row.CompressionTypeRecommendation
                            SizeCurrent                   = [dbasize]($row.SizeCurrentKB * 1024)
                            SizeRequested                 = [dbasize]($row.SizeRequestedKB * 1024)
                            PercentCompression            = $row.PercentCompression
                        }
                    }
                } catch {
                    Stop-Function -Message "Unable to query $instance - $db" -Target $db -ErrorRecord $_ -Continue
                }
            }
        }
    }
}
tools\dbatools\functions\Test-DbaDbLogShipStatus.ps1
function Test-DbaDbLogShipStatus {
    <#
    .SYNOPSIS
        Test-DbaDbLogShipStatus returns the status of your log shipping databases

    .DESCRIPTION
        Most of the time your log shipping "just works".
        Checking your log shipping status can be done really easy with this function.

        Make sure you're connecting to the monitoring instance of your log shipping infrastructure.

        The function will return the status for a database. This can be one or more messages in a comma separated list.
        If everything is OK with the database than you should only see the message "All OK".

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Allows you to filter the results to only return the databases you're interested in. This can be one or more values separated by commas.
        This is not a wildcard and should be the exact database name. See examples for more info.

    .PARAMETER ExcludeDatabase
        Allows you to filter the results to only return the databases you're not interested in. This can be one or more values separated by commas.
        This is not a wildcard and should be the exact database name.

    .PARAMETER Primary
        Allows to filter the results to only return values that apply to the primary instance.

    .PARAMETER Secondary
        Allows to filter the results to only return values that apply to the secondary instance.

    .PARAMETER Simple
        By default all the information will be returned.
        If this parameter is used you get an overview with the SQL Instance, Database, Instance Type and the status

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: LogShipping
        Author: Sander Stad (@sqlstad), sqlstad.nl

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaDbLogShipStatus

    .EXAMPLE
        PS C:\> Test-DbaDbLogShipStatus -SqlInstance sql1

        Retrieves the log ship information from sql1 and displays all the information present including the status.

    .EXAMPLE
        PS C:\> Test-DbaDbLogShipStatus -SqlInstance sql1 -Database AdventureWorks2014

        Retrieves the log ship information for just the database AdventureWorks.

    .EXAMPLE
        PS C:\> Test-DbaDbLogShipStatus -SqlInstance sql1 -Primary

        Retrieves the log ship information and only returns the information for the databases on the primary instance.

    .EXAMPLE
        PS C:\> Test-DbaDbLogShipStatus -SqlInstance sql1 -Secondary

        Retrieves the log ship information and only returns the information for the databases on the secondary instance.

    .EXAMPLE
        PS C:\> Test-DbaDbLogShipStatus -SqlInstance sql1 -Simple

        Retrieves the log ship information and only returns the columns SQL Instance, Database, Instance Type and Status

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [string[]]$ExcludeDatabase,
        [switch]$Simple,
        [switch]$Primary,
        [switch]$Secondary,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        # Setup the query
        [string[]]$query = "
IF ( OBJECT_ID('tempdb..#logshippingstatus') ) IS NOT NULL
BEGIN
DROP TABLE #logshippingstatus;
END;

CREATE TABLE #logshippingstatus
(
    Status BIT ,
    IsPrimary BIT ,
    Server VARCHAR(100) ,
    DatabaseName VARCHAR(100) ,
    TimeSinceLastBackup INT ,
    LastBackupFile VARCHAR(255) ,
    BackupThreshold INT ,
    IsBackupAlertEnabled BIT ,
    TimeSinceLastCopy INT ,
    LastCopiedFile VARCHAR(255) ,
    TimeSinceLastRestore INT ,
    LastRestoredFile VARCHAR(255) ,
    LastRestoredLatency INT ,
    RestoreThreshold INT ,
    IsRestoreAlertEnabled BIT
);

INSERT INTO #logshippingstatus
(   Status ,
    IsPrimary ,
    Server ,
    DatabaseName ,
    TimeSinceLastBackup ,
    LastBackupFile ,
    BackupThreshold ,
    IsBackupAlertEnabled ,
    TimeSinceLastCopy ,
    LastCopiedFile ,
    TimeSinceLastRestore ,
    LastRestoredFile ,
    LastRestoredLatency ,
    RestoreThreshold ,
    IsRestoreAlertEnabled
)
EXEC master.sys.sp_help_log_shipping_monitor"

        $select = "SELECT * FROM #logshippingstatus"

        if ($Database -or $ExcludeDatabase) {

            if ($database) {
                $where += "DatabaseName IN ('$($Database -join ''',''')')"
            } elseif ($ExcludeDatabase) {
                $where += "DatabaseName NOT IN ('$($ExcludeDatabase -join ''',''')')"
            }

            $select = "$select WHERE $where"
        }

        $query += $select
        $query += "DROP TABLE #logshippingstatus"
        $sql = $query -join ";`n"
        Write-Message -level Debug -Message $sql
    }

    process {
        foreach ($instance in $sqlinstance) {
            # Try connecting to the instance
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($server.EngineEdition -match "Express") {
                Write-Message -Level Warning -Message "$instance is Express Edition which does not support Log Shipping"
                continue
            }

            # Check the variables
            if ($Primary -and $Secondary) {
                Stop-Function -Message "Invalid parameter combination. Please enter either -Primary or -Secondary" -Target $instance -Continue
            }

            # Get the log shipped databases
            $results = $server.Query($sql)

            # Check if any rows were returned
            if ($results.Count -lt 1) {
                Stop-Function -Message "No information available about any log shipped databases for $instance. Please check the instance name." -Target $instance -Continue
            }

            # Filter the results
            if ($Primary) {
                $results = $results | Where-Object { $_.IsPrimary -eq $true }
            }

            if ($Secondary) {
                $results = $results | Where-Object { $_.IsPrimary -eq $false }
            }

            # Loop through each of the results
            foreach ($result in $results) {

                # Setup a variable to hold the errors
                $statusDetails = @()

                # Check if there are any results that need to be returned
                if ($result.Status -notin 0, 1) {
                    $statusDetails += "N/A"
                } else {
                    # Check the status of the row is true which indicates that something is wrong
                    if ($result.Status) {
                        # Check if the row is part of the primary or secondary instance
                        if ($result.IsPrimary) {
                            # Check the backup
                            if (-not $result.TimeSinceLastBackup) {
                                $statusDetails += "The backup has never been executed."
                            } elseif ($result.TimeSinceLastBackup -ge $result.BackupThreshold) {
                                $statusDetails += "The backup has not been executed in the last $($result.BackupThreshold) minutes"
                            }
                        } elseif (-not $result.IsPrimary) {
                            # Check the restore
                            if ($null -eq $result.TimeSinceLastRestore) {
                                $statusDetails += "The restore has never been executed."
                            } elseif ($result.TimeSinceLastRestore -ge $result.RestoreThreshold) {
                                $statusDetails += "The restore has not been executed in the last $($result.RestoreThreshold) minutes"
                            }
                        }
                    } else {
                        $statusDetails += "All OK"
                    }


                    # Check the time for the backup, copy and restore
                    if ($result.TimeSinceLastBackup -eq [DBNull]::Value) {
                        $lastBackup = "N/A"
                    } else {
                        $lastBackup = (Get-Date).AddMinutes(- $result.TimeSinceLastBackup)
                    }

                    if ($result.TimeSinceLastCopy -eq [DBNull]::Value) {
                        $lastCopy = "N/A"
                    } else {
                        $lastCopy = (Get-Date).AddMinutes(- $result.TimeSinceLastCopy)
                    }

                    if ($result.TimeSinceLastRestore -eq [DBNull]::Value) {
                        $lastRestore = "N/A"
                    } else {
                        $lastRestore = (Get-Date).AddMinutes(- $result.TimeSinceLastRestore)
                    }
                }

                # Set up the custom object
                $object = [PSCustomObject]@{
                    ComputerName          = $server.ComputerName
                    InstanceName          = $server.ServiceName
                    SqlInstance           = $server.DomainInstanceName
                    Database              = $result.DatabaseName
                    InstanceType          = switch ($result.IsPrimary) { $true { "Primary Instance" } $false { "Secondary Instance" } }
                    TimeSinceLastBackup   = $lastBackup
                    LastBackupFile        = $result.LastBackupFile
                    BackupThreshold       = $result.BackupThreshold
                    IsBackupAlertEnabled  = $result.IsBackupAlertEnabled
                    TimeSinceLastCopy     = $lastCopy
                    LastCopiedFile        = $result.LastCopiedFile
                    TimeSinceLastRestore  = $lastRestore
                    LastRestoredFile      = $result.LastRestoredFile
                    LastRestoredLatency   = $result.LastRestoredLatency
                    RestoreThreshold      = $result.RestoreThreshold
                    IsRestoreAlertEnabled = $result.IsRestoreAlertEnabled
                    Status                = $statusDetails -join ","
                }

                if ($Simple) {
                    $object | Select-DefaultView -Property SqlInstance, Database, InstanceType, Status
                } else {
                    $object
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Test-DbaLogShippingStatus
    }
}
tools\dbatools\functions\Test-DbaDbOwner.ps1
function Test-DbaDbOwner {
    <#
    .SYNOPSIS
        Checks database owners against a login to validate which databases do not match that owner.

    .DESCRIPTION
        This function will check all databases on an instance against a SQL login to validate if that
        login owns those databases or not. By default, the function will check against 'sa' for
        ownership, but the user can pass a specific login if they use something else.

        Best Practice reference: http://weblogs.sqlteam.com/dang/archive/2008/01/13/Database-Owner-Troubles.aspx

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.

    .PARAMETER TargetLogin
        Specifies the login that you wish check for ownership. This defaults to 'sa' or the sysadmin name if sa was renamed. This must be a valid security principal which exists on the target server.

    .PARAMETER Detailed
        Will be deprecated in 1.0.0 release.

    .PARAMETER InputObject
        Enables piped input from Get-DbaDatabase.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Database, Owner, DbOwner
        Author: Michael Fal (@Mike_Fal), http://mikefal.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaDbOwner

    .EXAMPLE
        PS C:\> Test-DbaDbOwner -SqlInstance localhost

        Returns all databases where the owner does not match 'sa'.

    .EXAMPLE
        PS C:\> Test-DbaDbOwner -SqlInstance localhost -TargetLogin 'DOMAIN\account'

        Returns all databases where the owner does not match 'DOMAIN\account'.

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance localhost -OnlyAccessible | Test-DbaDbOwner

        Gets only accessible databases and checks where the owner does not match 'sa'.
    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [string]$TargetLogin,
        [Switch]$Detailed,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [Switch]$EnableException
    )

    begin {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Parameter "Detailed"
    }
    process {
        if (-not $InputObject -and -not $Sqlinstance) {
            Stop-Function -Message 'You must specify a $SqlInstance parameter'
        }

        if ($SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase
        }

        #for each database, create custom object for return set.
        foreach ($db in $InputObject) {
            $server = $db.Parent

            # dynamic sa name for orgs who have changed their sa name
            if (Test-Bound -ParameterName TargetLogin -Not) {
                $TargetLogin = ($server.logins | Where-Object {
                        $_.id -eq 1
                    }).Name
            }

            #Validate login
            if (($server.Logins.Name) -notmatch [Regex]::Escape($TargetLogin)) {
                Write-Message -Level Verbose -Message "$TargetLogin is not a login on $instance" -Target $instance
            }

            Write-Message -Level Verbose -Message "Checking $db"
            [pscustomobject]@{
                ComputerName = $server.ComputerName
                InstanceName = $server.ServiceName
                SqlInstance  = $server.DomainInstanceName
                Server       = $server.DomainInstanceName
                Database     = $db.Name
                DBState      = $db.Status
                CurrentOwner = $db.Owner
                TargetOwner  = $TargetLogin
                OwnerMatch   = ($db.owner -eq $TargetLogin)
            } | Select-DefaultView -ExcludeProperty Server
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Test-DbaDatabaseOwner
    }
}
tools\dbatools\functions\Test-DbaDbRecoveryModel.ps1
function Test-DbaDbRecoveryModel {
    <#
    .SYNOPSIS
        Find if database is really a specific recovery model or not.

    .DESCRIPTION
        When you switch a database into FULL recovery model, it will behave like a SIMPLE recovery model until a full backup is taken in order to begin a log backup chain.

        However, you may also desire to validate if a database is SIMPLE or BULK LOGGED on an instance.

        Inspired by Paul Randal's post (http://www.sqlskills.com/blogs/paul/new-script-is-that-database-really-in-the-full-recovery-mode/)

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.

    .PARAMETER RecoveryModel
        Specifies the type of recovery model you wish to test. By default it will test for FULL Recovery Model.

    .PARAMETER Detailed
        Output all properties, will be deprecated in 1.0.0 release.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DisasterRecovery, Backup
        Author: Claudio Silva (@ClaudioESSilva)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: GNU GPL v3 https://opensource.org/licenses/GPL-3.0

    .LINK
        https://dbatools.io/Test-DbaDbRecoveryModel

    .EXAMPLE
        PS C:\> Test-DbaDbRecoveryModel -SqlInstance sql2005

        Shows all databases where the configured recovery model is FULL and indicates whether or not they are really in FULL recovery model.

    .EXAMPLE
        PS C:\> Test-DbaDbRecoveryModel -SqlInstance . | Where-Object {$_.ActualRecoveryModel -ne "FULL"}

        Only shows the databases that are functionally in 'simple' mode.

    .EXAMPLE
        PS C:\> Test-DbaDbRecoveryModel -SqlInstance sql2008 -RecoveryModel Bulk_Logged | Sort-Object Server  -Descending

        Shows all databases where the configured recovery model is BULK_LOGGED and sort them by server name descending

    .EXAMPLE
        PS C:\> Test-DbaDbRecoveryModel -SqlInstance localhost | Select-Object -Property *

        Shows all of the properties for the databases that have Full Recovery Model

       #>
    [CmdletBinding()]
    [OutputType("System.Collections.ArrayList")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [PSCredential]$SqlCredential,
        [validateSet("Full", "Simple", "Bulk_Logged")]
        [object]$RecoveryModel,
        [switch]$Detailed,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter Detailed
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Alias Test-DbaFullRecoveryModel

        if (Test-Bound -ParameterName RecoveryModel -Not) {
            $RecoveryModel = "Full"
        }

        switch ($RecoveryModel) {
            "Full" {$recoveryCode = 1}
            "Bulk_Logged" {$recoveryCode = 2}
            "Simple" {$recoveryCode = 3}
        }

        $sqlRecoveryModel = "SELECT  SERVERPROPERTY('MachineName') AS ComputerName,
                ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
                SERVERPROPERTY('ServerName') AS SqlInstance
                        , d.[name] AS [Database]
                        , d.recovery_model AS RecoveryModel
                        , d.recovery_model_desc AS RecoveryModelDesc
                        , CASE
                            WHEN d.recovery_model = 1 AND drs.last_log_backup_lsn IS NOT NULL THEN 1
                            ELSE 0
                           END AS IsReallyInFullRecoveryModel
                  FROM sys.databases AS D
                    INNER JOIN sys.database_recovery_status AS drs
                       ON D.database_id = drs.database_id
                  WHERE d.recovery_model = $recoveryCode"

        if ($Database) {
            $dblist = $Database -join "','"
            $databasefilter += "AND d.[name] in ('$dblist')"
        }
        if ($ExcludeDatabase) {
            $dblist = $ExcludeDatabase -join "','"
            $databasefilter += "AND d.[name] NOT IN ('$dblist')"
        }

        $sql = "$sqlRecoveryModel $databasefilter"

        Write-Message -Level Debug -Message $sql
    }
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            try {
                $results = $server.Query($sql)

                if (-not $results) {
                    Write-Message -Level Verbose -Message "Server '$instance' does not have any databases in the $RecoveryModel recovery model."
                }

                foreach ($row in $results) {
                    if (!([bool]$row.IsReallyInFullRecoveryModel) -and $RecoveryModel -eq 'Full') {
                        $ActualRecoveryModel = "SIMPLE"
                    } else {
                        $ActualRecoveryModel = "$($RecoveryModel.ToString().ToUpper())"
                    }

                    [PSCustomObject]@{
                        ComputerName            = $row.ComputerName
                        InstanceName            = $row.InstanceName
                        SqlInstance             = $row.SqlInstance
                        Database                = $row.Database
                        ConfiguredRecoveryModel = $row.RecoveryModelDesc
                        ActualRecoveryModel     = $ActualRecoveryModel
                    } | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, Database, ConfiguredRecoveryModel, ActualRecoveryModel
                }
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Test-DbaRecoveryModel
    }
}
tools\dbatools\functions\Test-DbaDbVirtualLogFile.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Test-DbaDbVirtualLogFile {
    <#
    .SYNOPSIS
        Returns calculations on the database virtual log files for database on a SQL instance.

    .DESCRIPTION
        Having a transaction log file with too many virtual log files (VLFs) can hurt database performance.

        Too many VLFs can cause transaction log backups to slow down and can also slow down database recovery and, in extreme cases, even affect insert/update/delete performance.

        References:
        http://www.sqlskills.com/blogs/kimberly/transaction-log-vlfs-too-many-or-too-few/
        http://blogs.msdn.com/b/saponsqlserver/archive/2012/02/22/too-many-virtual-log-files-vlfs-can-cause-slow-database-recovery.aspx

        If you've got a high number of VLFs, you can use Expand-SqlTLogResponsibly to reduce the number.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.

    .PARAMETER IncludeSystemDBs
        If this switch is enabled, system database information will be displayed.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: VLF, Database
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaDbVirtualLogFile

    .EXAMPLE
        PS C:\> Test-DbaDbVirtualLogFile -SqlInstance sqlcluster

        Returns all user database virtual log file counts for the sqlcluster instance.

    .EXAMPLE
        PS C:\> Test-DbaDbVirtualLogFile -SqlInstance sqlserver | Where-Object {$_.Count -ge 50}

        Returns user databases that have 50 or more VLFs.

    .EXAMPLE
        PS C:\> @('sqlserver','sqlcluster') | Test-DbaDbVirtualLogFile

        Returns all VLF information for the sqlserver and sqlcluster SQL Server instances. Processes data via the pipeline.

    .EXAMPLE
        PS C:\> Test-DbaDbVirtualLogFile -SqlInstance sqlcluster -Database db1, db2

        Returns VLF counts for the db1 and db2 databases on sqlcluster.

    #>
    [CmdletBinding()]
    [OutputType([System.Collections.ArrayList])]
    param ([parameter(ValueFromPipeline, Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$IncludeSystemDBs,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $dbs = $server.Databases
            if ($Database) {
                $dbs = $dbs | Where-Object Name -in $Database
            }
            if ($ExcludeDatabase) {
                $dbs = $dbs | Where-Object Name -NotIn $ExcludeDatabase
            }

            if (!$IncludeSystemDBs) {
                $dbs = $dbs | Where-Object IsSystemObject -eq $false
            }

            foreach ($db in $dbs) {
                try {
                    $data = Get-DbaDbVirtualLogFile -SqlInstance $server -Database $db.Name
                    $logFile = Get-DbaDbFile -SqlInstance $server -Database $db.Name | Where-Object Type -eq 1

                    $active = $data | Where-Object Status -eq 2
                    $inactive = $data | Where-Object Status -eq 0

                    [PSCustomObject]@{
                        ComputerName      = $server.ComputerName
                        InstanceName      = $server.ServiceName
                        SqlInstance       = $server.DomainInstanceName
                        Database          = $db.name
                        Total             = $data.Count
                        TotalCount        = $data.Count
                        Inactive          = if ($inactive -and $null -eq $inactive.Count) {1} else {$inactive.Count}
                        Active            = if ($active -and $null -eq $active.Count) {1} else {$active.Count}
                        LogFileName       = $logFile.LogicalName -join ","
                        LogFileGrowth     = $logFile.Growth -join ","
                        LogFileGrowthType = $logFile.GrowthType -join ","
                    } | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, Database, Total
                } catch {
                    Stop-Function -Message "Unable to query $($db.name) on $instance." -ErrorRecord $_ -Target $db -Continue
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Test-DbaVirtualLogFile
    }
}
tools\dbatools\functions\Test-DbaDeprecatedFeature.ps1
function Test-DbaDeprecatedFeature {
    <#
    .SYNOPSIS
        Displays information relating to deprecated features for SQL Server 2005 and above.

    .DESCRIPTION
        Displays information relating to deprecated features for SQL Server 2005 and above.

    .PARAMETER SqlInstance
        The target SQL Server instance

    .PARAMETER SqlCredential
        Login to the target instance using alternate Windows or SQL Login Authentication. Accepts credential objects (Get-Credential).

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER InputObject
        A collection of databases (such as returned by Get-DbaDatabase), to be tested.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Deprecated
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaDeprecatedFeature

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sql2008 -Database testdb, db2 | Test-DbaDeprecatedFeature

        Check deprecated features on server sql2008 for only the testdb and db2 databases

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sql2008 -Database testdb, db2 | Test-DbaDeprecatedFeature | Select *

        See the object definition in the output as well

    .EXAMPLE
        PS C:\> Test-DbaDeprecatedFeature -SqlInstance sql2008, sqlserver2012

        Check deprecated features for all databases on the servers sql2008 and sqlserver2012.

    .EXAMPLE
        PS C:\> Test-DbaDeprecatedFeature -SqlInstance sql2008 -Database TestDB

        Check deprecated features on server sql2008 for only the TestDB database

    #>
    [CmdletBinding()]
    param (
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [string[]]$ExcludeDatabase,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )

    begin {
        $sql = "SELECT  SERVERPROPERTY('MachineName') AS ComputerName,
            ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
            SERVERPROPERTY('ServerName') AS SqlInstance, object_id as ID, Name, type_desc as Type, Object_Definition (object_id) as Definition FROM sys.all_objects
            Where Type = 'P' AND is_ms_shipped = 0"
    }

    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase
        }
        foreach ($db in $InputObject) {
            Write-Message -Level Verbose -Message "Processing $db on $($db.Parent.Name)"

            if ($db.IsAccessible -eq $false) {
                Stop-Function -Message "The database $db is not accessible. Skipping database." -Continue
            }

            $deps = $db.Query("select instance_name as dep from sys.dm_os_performance_counters where object_name like '%Deprecated%'")
            try {
                $results = $db.Query($sql)
                foreach ($dep in $deps) {
                    $escaped = [Regex]::Escape("$($dep.dep)".Trim())
                    $matchedep = $results | Where-Object Definition -match $escaped
                    if ($matchedep) {
                        $matchedep | Add-Member -NotePropertyName DeprecatedFeature -NotePropertyValue $dep.dep.ToString().Trim() -PassThru -Force |
                            Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, DeprecatedFeature, ID, Name, Type
                    }
                }
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
            }
        }
    }
}
tools\dbatools\functions\Test-DbaDiskAlignment.ps1
function Test-DbaDiskAlignment {
    <#
    .SYNOPSIS
        Verifies that your non-dynamic disks are aligned according to physical constraints.

    .DESCRIPTION
        Returns $true or $false by default for one server. Returns Server name and IsBestPractice for more than one server.

        Please refer to your storage vendor best practices before following any advice below.

        By default issues with disk alignment should be resolved by a new installation of Windows Server 2008, Windows Vista, or later operating systems, but verifying disk alignment continues to be recommended as a best practice.
        While some versions of Windows use different starting alignments, if you are starting anew 1MB is generally the best practice offset for current operating systems (because it ensures that the partition offset % common stripe unit sizes == 0 )

        Caveats:
        * Dynamic drives (or those provisioned via third party software) may or may not have accurate results when polled by any of the built in tools, see your vendor for details.
        * Windows does not have a reliable way to determine stripe unit Sizes. These values are obtained from vendor disk management software or from your SAN administrator.
        * System drives in versions previous to Windows Server 2008 cannot be aligned, but it is generally not recommended to place SQL Server databases on system drives.

    .PARAMETER ComputerName
        The target computer or computers.

    .PARAMETER Credential
        Specifies an alternate Windows account to use when enumerating drives on the server. May require Administrator privileges. To use:

        $cred = Get-Credential, then pass $cred object to the -Credential parameter.

    .PARAMETER SQLCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER NoSqlCheck
        If this switch is enabled, the disk(s) will not be checked for SQL Server data or log files.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Storage
        Author: Constantine Kokkinos (@mobileck), https://constantinekokkinos.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        The preferred way to determine if your disks are aligned (or not) is to calculate:
        1. Partition offset - stripe unit size
        2. Stripe unit size - File allocation unit size

        References:
        - Disk Partition Alignment Best Practices for SQL Server - https://technet.microsoft.com/en-us/library/dd758814(v=sql.100).aspx
        - Getting Partition Offset information with Powershell - http://sqlblog.com/blogs/jonathan_kehayias/archive/2010/03/01/getting-partition-Offset-information-with-powershell.aspx
        Thanks to Jonathan Kehayias!
        - Decree: Set your partition Offset and block Size and make SQL Server faster - http://www.midnightdba.com/Jen/2014/04/decree-set-your-partition-Offset-and-block-Size-make-sql-server-faster/
        Thanks to Jen McCown!
        - Disk Performance Hands On - http://www.kendalvandyke.com/2009/02/disk-performance-hands-on-series-recap.html
        Thanks to Kendal Van Dyke!
        - Get WMI Disk Information - http://powershell.com/cs/media/p/7937.aspx
        Thanks to jbruns2010!

    .LINK
        https://dbatools.io/Test-DbaDiskAlignment

    .EXAMPLE
        PS C:\> Test-DbaDiskAlignment -ComputerName sqlserver2014a

        Tests the disk alignment of a single server named sqlserver2014a

    .EXAMPLE
        PS C:\> Test-DbaDiskAlignment -ComputerName sqlserver2014a, sqlserver2014b, sqlserver2014c

        Tests the disk alignment of multiple servers

    #>
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlInstance")]
        [DbaInstanceParameter[]]$ComputerName,
        [System.Management.Automation.PSCredential]$Credential,
        [System.Management.Automation.PSCredential]$SqlCredential,
        [switch]$NoSqlCheck,
        [switch]$EnableException
    )
    begin {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Parameter 'Detailed'

        $sessionoption = New-CimSessionOption -Protocol DCom

        function Get-DiskAlignment {
            [CmdletBinding()]
            param (
                $CimSession,
                [string]$FunctionName = (Get-PSCallStack)[0].Command,
                [bool]$NoSqlCheck,
                [string]$ComputerName,
                [System.Management.Automation.PSCredential]$SqlCredential,
                [bool]$EnableException = $EnableException
            )

            $SqlInstances = @()
            $offsets = @()

            #region Retrieving partition/disk Information
            try {
                Write-Message -Level Verbose -Message "Gathering information about first partition on each disk for $ComputerName." -FunctionName $FunctionName

                try {
                    $partitions = Get-CimInstance -CimSession $CimSession -ClassName Win32_DiskPartition -Namespace "root\cimv2" -ErrorAction Stop
                } catch {
                    if ($_.Exception -match "namespace") {
                        Stop-Function -Message "Can't get disk alignment info for $ComputerName. Unsupported operating system." -InnerErrorRecord $_ -Target $ComputerName -FunctionName $FunctionName
                        return
                    } else {
                        Stop-Function -Message "Can't get disk alignment info for $ComputerName. Check logs for more details." -InnerErrorRecord $_ -Target $ComputerName -FunctionName $FunctionName
                        return
                    }
                }


                $disks = @()
                $disks += $($partitions | ForEach-Object {
                        Get-CimInstance -CimSession $CimSession -Query "ASSOCIATORS OF {Win32_DiskPartition.DeviceID=""$($_.DeviceID.Replace("\", "\\"))""} WHERE AssocClass = Win32_LogicalDiskToPartition" |
                            Add-Member -Force -MemberType noteproperty -Name BlockSize -Value $_.BlockSize -PassThru |
                            Add-Member -Force -MemberType noteproperty -Name BootPartition -Value $_.BootPartition -PassThru |
                            Add-Member -Force -MemberType noteproperty -Name DiskIndex -Value $_.DiskIndex -PassThru |
                            Add-Member -Force -MemberType noteproperty -Name Index -Value $_.Index -PassThru |
                            Add-Member -Force -MemberType noteproperty -Name NumberOfBlocks -Value $_.NumberOfBlocks -PassThru |
                            Add-Member -Force -MemberType noteproperty -Name StartingOffset -Value $_.StartingOffset -PassThru |
                            Add-Member -Force -MemberType noteproperty -Name Type -Value $_.Type -PassThru
                    } |
                        Select-Object BlockSize, BootPartition, Description, DiskIndex, Index, Name, NumberOfBlocks, Size, StartingOffset, Type
                )
                Write-Message -Level Verbose -Message "Gathered CIM information." -FunctionName $FunctionName
            } catch {
                Stop-Function -Message "Can't connect to CIM on $ComputerName." -FunctionName $FunctionName -InnerErrorRecord $_
                return
            }
            #endregion Retrieving partition Information

            #region Retrieving Instances
            if (-not $NoSqlCheck) {
                Write-Message -Level Verbose -Message "Checking for SQL Services." -FunctionName $FunctionName
                $sqlservices = Get-CimInstance -ClassName Win32_Service -CimSession $CimSession | Where-Object DisplayName -like 'SQL Server (*'
                foreach ($service in $sqlservices) {
                    $instance = $service.DisplayName.Replace('SQL Server (', '')
                    $instance = $instance.TrimEnd(')')

                    $instancename = $instance.Replace("MSSQLSERVER", "Default")
                    Write-Message -Level Verbose -Message "Found instance $instancename" -FunctionName $FunctionName
                    if ($instance -eq 'MSSQLSERVER') {
                        $SqlInstances += $ComputerName
                    } else {
                        $SqlInstances += "$ComputerName\$instance"
                    }
                }
                $sqlcount = $SqlInstances.Count
                Write-Message -Level Verbose -Message "$sqlcount instance(s) found." -FunctionName $FunctionName
            }
            #endregion Retrieving Instances

            #region Offsets
            foreach ($disk in $disks) {
                if (!$disk.name.StartsWith("\\")) {
                    $diskname = $disk.Name
                    if ($NoSqlCheck -eq $false) {
                        $sqldisk = $false

                        foreach ($SqlInstance in $SqlInstances) {
                            try {
                                if ($null -ne $SqlCredential) {
                                    $smoserver = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
                                } else {
                                    $smoserver = Connect-SqlInstance -SqlInstance $SqlInstance # win auth
                                }
                                $sql = "Select count(*) as Count from sys.master_files where physical_name like '$diskname%'"
                                Write-Message -Level Verbose -Message "Query is: $sql" -FunctionName $FunctionName
                                Write-Message -Level Verbose -Message "SQL Server is: $SqlInstance." -FunctionName $FunctionName
                                $sqlcount = $smoserver.Databases['master'].ExecuteWithResults($sql).Tables[0].Count
                                if ($sqlcount -gt 0) {
                                    $sqldisk = $true
                                    break
                                }
                            } catch {
                                Stop-Function -Message "Can't connect to $ComputerName ($SqlInstance)." -FunctionName $FunctionName -InnerErrorRecord $_
                                return
                            }
                        }
                    }

                    if ($NoSqlCheck -eq $false) {
                        if ($sqldisk -eq $true) {
                            $offsets += $disk
                        }
                    } else {
                        $offsets += $disk
                    }
                }
            }
            #endregion Offsets

            #region Processing results
            Write-Message -Level Verbose -Message "Checking $($offsets.count) partitions." -FunctionName $FunctionName
            foreach ($partition in $offsets) {
                # Unfortunately "Windows does not have a reliable way to determine stripe unit Sizes. These values are obtained from vendor disk management software or from your SAN administrator."
                # And this is the #1 most impactful issue with disk alignment :D
                # What we can do is test common stripe unit Sizes against the Offset we have and give advice if the Offset they chose would work in those scenarios
                $offset = $partition.StartingOffset / 1kb
                $type = $partition.Type
                $stripe_units = @(64, 128, 256, 512, 1024) # still wish I had a better way to verify this or someone to pat my back and say its alright.

                # testing dynamic disks, everyone states that info from dynamic disks is not to be trusted, so throw a warning.
                Write-Message -Level Verbose -Message "Testing for dynamic disks." -FunctionName $FunctionName
                if ($type -eq "Logical Disk Manager") {
                    $IsDynamicDisk = $true
                    Write-Message -Level Warning -Message "Disk is dynamic, all Offset calculations should be suspect, please refer to your vendor to determine actual Offset calculations." -FunctionName $FunctionName
                } else {
                    $IsDynamicDisk = $false
                }

                Write-Message -Level Verbose -Message "Checking for best practices offsets." -FunctionName $FunctionName

                if ($offset -ne 64 -and $offset -ne 128 -and $offset -ne 256 -and $offset -ne 512 -and $offset -ne 1024) {
                    $IsOffsetBestPractice = $false
                } else {
                    $IsOffsetBestPractice = $true
                }

                # as we can't tell the actual size of the file strip unit, just check all the sizes I know about
                foreach ($size in $stripe_units) {
                    if ($offset % $size -eq 0) {
                        # for proper alignment we really only need to know that your offset divided by your stripe unit size has a remainder of 0
                        $OffsetModuloKB = "$($offset % $size)"
                        $isBestPractice = $true
                    } else {
                        $OffsetModuloKB = "$($offset % $size)"
                        $isBestPractice = $false
                    }

                    [PSCustomObject]@{
                        ComputerName            = $ogcomputer
                        Name                    = "$($partition.Name)"
                        PartitonSize            = [dbasize]($($partition.Size / 1MB) * 1024 * 1024)
                        PartitionType           = $partition.Type
                        TestingStripeSize       = [dbasize]($size * 1024)
                        OffsetModuluCalculation = [dbasize]($OffsetModuloKB * 1024)
                        StartingOffset          = [dbasize]($offset * 1024)
                        IsOffsetBestPractice    = $IsOffsetBestPractice
                        IsBestPractice          = $isBestPractice
                        NumberOfBlocks          = $partition.NumberOfBlocks
                        BootPartition           = $partition.BootPartition
                        PartitionBlockSize      = $partition.BlockSize
                        IsDynamicDisk           = $IsDynamicDisk
                    }
                }
            }
        }
    }

    process {
        # uses cim commands
        
        
        foreach ($computer in $ComputerName) {
            $computer = $ogcomputer = $computer.ComputerName
            Write-Message -Level VeryVerbose -Message "Processing: $computer."

            $computer = Resolve-DbaNetworkName -ComputerName $computer -Credential $Credential
            $Computer = $computer.FullComputerName

            if (-not $Computer) {
                Stop-Function -Message "Couldn't resolve hostname. Skipping." -Continue
            }

            #region Connecting to server via Cim
            Write-Message -Level Verbose -Message "Creating CimSession on $computer over WSMan"

            if (-not $Credential) {
                $cimsession = New-CimSession -ComputerName $Computer -ErrorAction Ignore
            } else {
                $cimsession = New-CimSession -ComputerName $Computer -ErrorAction Ignore -Credential $Credential
            }

            if ($null -eq $cimsession.id) {
                Write-Message -Level Verbose -Message "Creating CimSession on $computer over WSMan failed. Creating CimSession on $computer over DCOM."

                if (!$Credential) {
                    $cimsession = New-CimSession -ComputerName $Computer -SessionOption $sessionoption -ErrorAction Ignore
                } else {
                    $cimsession = New-CimSession -ComputerName $Computer -SessionOption $sessionoption -ErrorAction Ignore -Credential $Credential
                }
            }

            if ($null -eq $cimsession.id) {
                Stop-Function -Message "Can't create CimSession on $computer." -Target $Computer -Continue
            }
            #endregion Connecting to server via Cim

            Write-Message -Level Verbose -Message "Getting Power Plan information from $Computer."


            try {
                Get-DiskAlignment -CimSession $cimsession -NoSqlCheck $NoSqlCheck -ComputerName $Computer -ErrorAction Stop
            } catch {
                Stop-Function -Message "Failed to process $($Computer): $($_.Exception.Message)" -Continue -InnerErrorRecord $_ -Target $Computer
            }
        }
    }
}
tools\dbatools\functions\Test-DbaDiskAllocation.ps1
function Test-DbaDiskAllocation {
    <#
    .SYNOPSIS
        Checks all disks on a computer to see if they are formatted with allocation units of 64KB.

    .DESCRIPTION
        Checks all disks on a computer for disk allocation units that match best practice recommendations. If one server is checked, only $true or $false is returned. If multiple servers are checked, each server's name and an IsBestPractice field are returned.

        References:
        https://technet.microsoft.com/en-us/library/dd758814(v=sql.100).aspx - "The performance question here is usually not one of correlation per the formula, but whether the cluster size has been explicitly defined at 64 KB, which is a best practice for SQL Server."

    .PARAMETER ComputerName
        The server(s) to check disk configuration on.

    .PARAMETER NoSqlCheck
        If this switch is enabled, the disk(s) will not be checked for SQL Server data or log files.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Credential
        Specifies an alternate Windows account to use when enumerating drives on the server. May require Administrator privileges. To use:

        $cred = Get-Credential, then pass $cred object to the -Credential parameter.

    .PARAMETER Detailed
        Output all properties, will be deprecated in 1.0.0 release.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: CIM, Storage
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaDiskAllocation

    .EXAMPLE
        PS C:\> Test-DbaDiskAllocation -ComputerName sqlserver2014a

        Scans all disks on server sqlserver2014a for best practice allocation unit size.

    .EXAMPLE
        PS C:\> Test-DbaDiskAllocation -ComputerName sqlserver2014 | Select-Output *

        Scans all disks on server sqlserver2014a for allocation unit size and returns detailed results for each.

    .EXAMPLE
        PS C:\> Test-DbaDiskAllocation -ComputerName sqlserver2014a -NoSqlCheck

        Scans all disks not hosting SQL Server data or log files on server sqlserver2014a for best practice allocation unit size.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    [OutputType("System.Collections.ArrayList", "System.Boolean")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlInstance")]
        [object[]]$ComputerName,
        [switch]$NoSqlCheck,
        [PSCredential]$SqlCredential,
        [PSCredential]$Credential,
        [switch]$Detailed,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter Detailed

        $sessionoptions = New-CimSessionOption -Protocol DCOM

        function Get-AllDiskAllocation {
            $alldisks = @()
            $SqlInstances = @()

            try {
                Write-Message -Level Verbose -Message "Getting disk information from $computer."

                # $query = "Select Label, BlockSize, Name from Win32_Volume WHERE FileSystem='NTFS'"
                # $disks = Get-WmiObject -ComputerName $ipaddr -Query $query | Sort-Object -Property Name
                $disks = Get-CimInstance -CimSession $CIMsession -ClassName win32_volume -Filter "FileSystem='NTFS'" -ErrorAction Stop | Sort-Object -Property Name
            } catch {
                Stop-Function -Message "Can't connect to WMI on $computer."
                return
            }

            if ($NoSqlCheck -eq $false) {
                Write-Message -Level Verbose -Message "Checking for SQL Services"
                $sqlservices = Get-Service -ComputerName $ipaddr | Where-Object { $_.DisplayName -like 'SQL Server (*' }
                foreach ($service in $sqlservices) {
                    $instance = $service.DisplayName.Replace('SQL Server (', '')
                    $instance = $instance.TrimEnd(')')

                    $instancename = $instance.Replace("MSSQLSERVER", "Default")
                    Write-Message -Level Verbose -Message "Found instance $instancename."

                    if ($instance -eq 'MSSQLSERVER') {
                        $SqlInstances += $ipaddr
                    } else {
                        $SqlInstances += "$ipaddr\$instance"
                    }
                }
                $sqlcount = $SqlInstances.Count

                Write-Message -Level Verbose -Message "$sqlcount instance(s) found."
            }

            foreach ($disk in $disks) {
                if (!$disk.name.StartsWith("\\")) {
                    $diskname = $disk.Name

                    if ($NoSqlCheck -eq $false) {
                        $sqldisk = $false

                        foreach ($SqlInstance in $SqlInstances) {
                            try {
                                $smoserver = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
                                $sql = "Select count(*) as Count from sys.master_files where physical_name like '$diskname%'"
                                $sqlcount = $smoserver.Databases['master'].ExecuteWithResults($sql).Tables[0].Count
                                if ($sqlcount -gt 0) {
                                    $sqldisk = $true
                                    break
                                }
                            } catch {
                                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                                continue
                            }
                        }
                    }

                    if ($disk.BlockSize -eq 65536) {
                        $IsBestPractice = $true
                    } else {
                        $IsBestPractice = $false
                    }

                    $windowsdrive = "$env:SystemDrive\"

                    if ($diskname -eq $windowsdrive) {
                        $IsBestPractice = $false
                    }

                    if ($NoSqlCheck -eq $false) {
                        $alldisks += [PSCustomObject]@{
                            Server         = $computer
                            Name           = $diskname
                            Label          = $disk.Label
                            BlockSize      = $disk.BlockSize
                            IsSqlDisk      = $sqldisk
                            IsBestPractice = $IsBestPractice
                        }
                    } else {
                        $alldisks += [PSCustomObject]@{
                            Server         = $computer
                            Name           = $diskname
                            Label          = $disk.Label
                            BlockSize      = $disk.BlockSize
                            IsBestPractice = $IsBestPractice
                        }
                    }
                }
            }
            return $alldisks
        }
    }

    process {
        # uses cim commands
        
        
        foreach ($computer in $ComputerName) {

            $computer = Resolve-DbaNetworkName -ComputerName $computer -Credential $Credential
            $ipaddr = $computer.IpAddress
            $Computer = $computer.FullComputerName

            if (!$Computer) {
                Stop-Function -Message "Couldn't resolve hostname. Skipping." -Continue
            }

            Write-Message -Level Verbose -Message "Creating CimSession on $computer over WSMan."

            if (!$Credential) {
                $cimsession = New-CimSession -ComputerName $Computer -ErrorAction SilentlyContinue
            } else {
                $cimsession = New-CimSession -ComputerName $Computer -ErrorAction SilentlyContinue -Credential $Credential
            }

            if ($null -eq $cimsession.id) {
                Write-Message -Level Verbose -Message "Creating CimSession on $computer over WSMan failed. Creating CimSession on $computer over DCOM."

                if (!$Credential) {
                    $cimsession = New-CimSession -ComputerName $Computer -SessionOption $sessionoptions -ErrorAction SilentlyContinue
                } else {
                    $cimsession = New-CimSession -ComputerName $Computer -SessionOption $sessionoptions -ErrorAction SilentlyContinue -Credential $Credential
                }
            }

            if ($null -eq $cimsession.id) {
                Stop-Function -Message "Can't create CimSession on $computer" -Target $Computer
            }

            Write-Message -Level Verbose -Message "Getting Power Plan information from $Computer"

            if ($PScmdlet.ShouldProcess("$computer", "Getting Disk Allocation")) {
                $data = Get-AllDiskAllocation $computer

                if ($data.Count -gt 1) {
                    $data.GetEnumerator()
                } else {
                    $data
                }
            }
        }
    }
}
tools\dbatools\functions\Test-DbaDiskSpeed.ps1
function Test-DbaDiskSpeed {
    <#
    .SYNOPSIS
        Tests how disks are performing.

    .DESCRIPTION
        Tests how disks are performing.

        This command uses a query from Rich Benner which was adapted from David Pless's article:
        https://blogs.msdn.microsoft.com/dpless/2010/12/01/leveraging-sys-dm_io_virtual_file_stats/
        https://github.com/RichBenner/PersonalCode/blob/master/Disk_Speed_Check.sql

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Allows you to login to the SQL Server using alternative credentials.

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Performance
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaDiskSpeed

    .EXAMPLE
        PS C:\> Test-DbaDiskSpeed -SqlInstance sql2008, sqlserver2012

        Tests how disks are performing on sql2008 and sqlserver2012.

    .EXAMPLE
        PS C:\> Test-DbaDiskSpeed -SqlInstance sql2008 -Database tempdb

        Tests how disks storing tempdb files on sql2008 are performing.

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$EnableException
    )

    begin {

        $sql = "SELECT  SERVERPROPERTY('MachineName') AS ComputerName,
        ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
        SERVERPROPERTY('ServerName') AS SqlInstance, db_name(a.database_id) AS [Database]
        , CAST(((a.size_on_disk_bytes/1024)/1024.0)/1024 AS DECIMAL(10,2)) AS [SizeGB]
        , RIGHT(b.physical_name, CHARINDEX('\', REVERSE(b.physical_name)) -1) AS [FileName]
        , a.file_id AS [FileID]
        , CASE WHEN a.file_id = 2 THEN 'Log' ELSE 'Data' END AS [FileType]
        , UPPER(SUBSTRING(b.physical_name, 1, 2)) AS [DiskLocation]
        , a.num_of_reads AS [Reads]
        , CASE WHEN a.num_of_reads < 1 THEN NULL ELSE CAST(a.io_stall_read_ms/(a.num_of_reads) AS INT) END AS [AverageReadStall]
        , CASE
            WHEN CASE WHEN a.num_of_reads < 1 THEN NULL ELSE CAST(a.io_stall_read_ms/(a.num_of_reads) AS INT) END < 10 THEN 'Very Good'
            WHEN CASE WHEN a.num_of_reads < 1 THEN NULL ELSE CAST(a.io_stall_read_ms/(a.num_of_reads) AS INT) END < 20 THEN 'OK'
            WHEN CASE WHEN a.num_of_reads < 1 THEN NULL ELSE CAST(a.io_stall_read_ms/(a.num_of_reads) AS INT) END < 50 THEN 'Slow, Needs Attention'
            WHEN CASE WHEN a.num_of_reads < 1 THEN NULL ELSE CAST(a.io_stall_read_ms/(a.num_of_reads) AS INT) END >= 50 THEN 'Serious I/O Bottleneck'
            END AS [ReadPerformance]
        , a.num_of_writes AS [Writes]
        , CASE WHEN a.num_of_writes < 1 THEN NULL ELSE CAST(a.io_stall_write_ms/a.num_of_writes AS INT) END AS [AverageWriteStall]
        , CASE
            WHEN CASE WHEN a.num_of_writes < 1 THEN NULL ELSE CAST(a.io_stall_write_ms/(a.num_of_writes) AS INT) END < 10 THEN 'Very Good'
            WHEN CASE WHEN a.num_of_writes < 1 THEN NULL ELSE CAST(a.io_stall_write_ms/(a.num_of_writes) AS INT) END < 20 THEN 'OK'
            WHEN CASE WHEN a.num_of_writes < 1 THEN NULL ELSE CAST(a.io_stall_write_ms/(a.num_of_writes) AS INT) END < 50 THEN 'Slow, Needs Attention'
            WHEN CASE WHEN a.num_of_writes < 1 THEN NULL ELSE CAST(a.io_stall_write_ms/(a.num_of_writes) AS INT) END >= 50 THEN 'Serious I/O Bottleneck'
            END AS [WritePerformance]
        FROM sys.dm_io_virtual_file_stats (NULL, NULL) a
        JOIN sys.master_files b
            ON a.file_id = b.file_id
            AND a.database_id = b.database_id"

        if ($Database -or $ExcludeDatabase) {
            if ($database) {
                $where = " where db_name(a.database_id) in ('$($Database -join "'")') "
            }
            if ($ExcludeDatabase) {
                $where = " where db_name(a.database_id) not in ('$($ExcludeDatabase -join "'")') "
            }
            $sql += $where
        }

        $sql += " ORDER BY (a.num_of_reads + a.num_of_writes) DESC"
    }

    process {
        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            Write-Message -Level Debug -Message "Executing $sql"
            $server.Query("$sql")
        }
    }
}
tools\dbatools\functions\Test-DbaEndpoint.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Test-DbaEndpoint {
    <#
    .SYNOPSIS
        Performs a simple connectivity test for TCP and SSL enabled endpoints.

    .DESCRIPTION
        Performs a simple connectivity test for TCP and SSL enabled endpoints. Tests if port is accessible, not if endpoint is working.

        Note that if an endpoint does not have a tcp listener port, it will be skipped.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Endpoint
        Test only specific endpoint or endpoints.

    .PARAMETER InputObject
        Enables piping from Get-DbaEndpoint.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Endpoint
        Author: Chrissy LeMaire (@cl), netnerds.net
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaEndpoint

    .EXAMPLE
        PS C:\> Test-DbaEndpoint -SqlInstance localhost

        Tests all endpoints on the local default SQL Server instance.

        Note that if an endpoint does not have a tcp listener port, it will be skipped.

    .EXAMPLE
        PS C:\> Get-DbaEndpoint -SqlInstance localhost, sql2016 -Endpoint Mirror | Test-DbaEndpoint

        Tests all endpoints named Mirroring on sql2016 and localhost.

        Note that if an endpoint does not have a tcp listener port, it will be skipped.

    .EXAMPLE
        PS C:\> Test-DbaEndpoint -SqlInstance localhost, sql2016 -Endpoint Mirror

        Tests all endpoints named Mirroring on sql2016 and localhost.

        Note that if an endpoint does not have a tcp listener port, it will be skipped.

    .EXAMPLE
        PS C:\> Test-DbaEndpoint -SqlInstance localhost -Verbose

        Tests all endpoints on the local default SQL Server instance.

        See all endpoints that were skipped due to not having a tcp listener port.

    #>
    [CmdletBinding()]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Endpoint,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Endpoint[]]$InputObject,
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            $InputObject += Get-DbaEndpoint -SqlInstance $instance -SqlCredential $SqlCredential -Endpoint $Endpoint
        }

        foreach ($end in $InputObject) {
            if (-not $end.Protocol.Tcp.ListenerPort) {
                Write-Message -Level Verbose -Message "$end on $($end.Parent) does not have a tcp listener port"
            } else {
                Write-Message "Connecting to port $($end.Protocol.Tcp.ListenerPort) on $($end.ComputerName) for endpoint $($end.Name)"

                try {
                    $tcp = New-Object System.Net.Sockets.TcpClient
                    $tcp.Connect($end.ComputerName, $end.Protocol.Tcp.ListenerPort)
                    $tcp.Close()
                    $tcp.Dispose()
                    $connect = "Success"
                } catch {
                    $connect = $_
                }

                try {
                    $ssl = $end.Protocol.Tcp.SslPort
                    if ($ssl) {
                        $tcp = New-Object System.Net.Sockets.TcpClient
                        $tcp.Connect($end.ComputerName, $ssl)
                        $tcp.Close()
                        $tcp.Dispose()
                        $sslconnect = "Success"
                    } else {
                        $sslconnect = "None"
                    }
                } catch {
                    $sslconnect = $_
                }

                [pscustomobject]@{
                    ComputerName  = $end.ComputerName
                    InstanceName  = $end.InstanceName
                    SqlInstance   = $end.SqlInstance
                    Endpoint      = $end.Name
                    Port          = $end.Protocol.Tcp.ListenerPort
                    Connection    = $connect
                    SslConnection = $sslconnect
                }
            }
        }
    }
}
tools\dbatools\functions\Test-DbaIdentityUsage.ps1
function Test-DbaIdentityUsage {
    <#
    .SYNOPSIS
        Displays information relating to IDENTITY seed usage.  Works on SQL Server 2008 and above.

    .DESCRIPTION
        IDENTITY seeds have max values based off of their data type.  This module will locate identity columns and report the seed usage.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER Threshold
        Allows you to specify a minimum % of the seed range being utilized.  This can be used to ignore seeds that have only utilized a small fraction of the range.

    .PARAMETER ExcludeSystem
        Allows you to suppress output on system databases

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Identity, Table, Column
        Author: Brandon Abshire, netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaIdentityUsage

    .EXAMPLE
        PS C:\> Test-DbaIdentityUsage -SqlInstance sql2008, sqlserver2012

        Check identity seeds for servers sql2008 and sqlserver2012.

    .EXAMPLE
        PS C:\> Test-DbaIdentityUsage -SqlInstance sql2008 -Database TestDB

        Check identity seeds on server sql2008 for only the TestDB database

    .EXAMPLE
        PS C:\> Test-DbaIdentityUsage -SqlInstance sql2008 -Database TestDB -Threshold 20

        Check identity seeds on server sql2008 for only the TestDB database, limiting results to 20% utilization of seed range or higher

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [parameter(Position = 1)]
        [int]$Threshold = 0,
        [parameter(Position = 2)]
        [Alias("ExcludeSystemDb")]
        [switch]$ExcludeSystem,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter ExcludeSystem

        $sql = ";WITH CT_DT AS
        (
            SELECT 'tinyint' AS DataType, 0 AS MinValue ,255 AS MaxValue UNION
            SELECT 'smallint' AS DataType, -32768 AS MinValue ,32767 AS MaxValue UNION
            SELECT 'int' AS DataType, -2147483648 AS MinValue ,2147483647 AS MaxValue UNION
            SELECT 'bigint' AS DataType, -9223372036854775808 AS MinValue ,9223372036854775807 AS MaxValue
        ), CTE_1
        AS
        (
          SELECT SCHEMA_NAME(o.schema_id) AS SchemaName,
                 OBJECT_NAME(a.Object_id) as TableName,
                 a.Name as ColumnName,
                 seed_value AS SeedValue,
                 CONVERT(bigint, increment_value) as IncrementValue,

                 CONVERT(bigint, ISNULL(a.last_value, seed_value)) AS LastValue,

                 (CASE
                        WHEN CONVERT(bigint, increment_value) < 0 THEN
                            (CONVERT(bigint, seed_value)
                            - CONVERT(bigint, ISNULL(last_value, seed_value))
                            + (CASE WHEN CONVERT(bigint, seed_value) <> 0 THEN ABS(CONVERT(bigint, increment_value)) ELSE 0 END))
                        ELSE
                            (CONVERT(bigint, ISNULL(last_value, seed_value))
                            - CONVERT(bigint, seed_value)
                            + (CASE WHEN CONVERT(bigint, seed_value) <> 0 THEN ABS(CONVERT(bigint, increment_value)) ELSE 0 END))
                    END) / ABS(CONVERT(bigint, increment_value))  AS NumberOfUses,

                  CAST (
                        (CASE
                            WHEN CONVERT(Numeric(20, 0), increment_value) < 0 THEN
                                ABS(CONVERT(Numeric(20, 0),dt.MinValue)
                                - CONVERT(Numeric(20, 0), seed_value)
                                - (CASE WHEN CONVERT(Numeric(20, 0), seed_value) <> 0 THEN ABS(CONVERT(Numeric(20, 0), increment_value)) ELSE 0 END))
                            ELSE
                                CONVERT(Numeric(20, 0),dt.MaxValue)
                                - CONVERT(Numeric(20, 0), seed_value)
                                + (CASE WHEN CONVERT(Numeric(20, 0), seed_value) <> 0 THEN ABS(CONVERT(Numeric(20, 0), increment_value)) ELSE 0 END)
                        END) / ABS(CONVERT(Numeric(20, 0), increment_value))
                    AS Numeric(20, 0)) AS MaxNumberRows

            FROM sys.identity_columns a
                INNER JOIN sys.objects o
                   ON a.object_id = o.object_id
                INNER JOIN sys.types As b
                     ON a.system_type_id = b.system_type_id
                INNER JOIN CT_DT dt
                     ON b.name = dt.DataType
          WHERE a.seed_value is not null
        ),
        CTE_2
        AS
        (
        SELECT SchemaName, TableName, ColumnName, CONVERT(BIGINT, SeedValue) AS SeedValue, CONVERT(BIGINT, IncrementValue) AS IncrementValue, LastValue, ABS(CONVERT(NUMERIC(20,0),MaxNumberRows)) AS MaxNumberRows, NumberOfUses,
               CONVERT(NUMERIC(18, 2), ((CONVERT(FLOAT, NumberOfUses) / ABS(CONVERT(NUMERIC(20, 0), NULLIF(MaxNumberRows,0))) * 100))) AS [PercentUsed]
          FROM CTE_1
        )
        SELECT DB_NAME() as DatabaseName, SchemaName, TableName, ColumnName, SeedValue, IncrementValue, LastValue, MaxNumberRows, NumberOfUses, [PercentUsed]
          FROM CTE_2"

        if ($Threshold -gt 0) {
            $sql += " WHERE [PercentUsed] >= " + $Threshold + " ORDER BY [PercentUsed] DESC"
        } else {
            $sql += " ORDER BY [PercentUsed] DESC"
        }
    }

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $dbs = $server.Databases

            if ($Database) {
                $dbs = $dbs | Where-Object Name -In $Database
            }

            if ($ExcludeDatabase) {
                $dbs = $dbs | Where-Object Name -NotIn $ExcludeDatabase
            }

            if ($ExcludeSystem) {
                $dbs = $dbs | Where-Object IsSystemObject -EQ $false
            }

            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Processing $db on $instance"

                if ($db.IsAccessible -eq $false) {
                    Stop-Function -Message "The database $db is not accessible. Skipping." -Continue
                }

                try {
                    $results = $db.Query($sql)
                } catch {
                    Stop-Function -Message "Error capturing data on $db" -Target $instance -ErrorRecord $_ -Exception $_.Exception -Continue
                }

                foreach ($row in $results) {
                    if ($row.PercentUsed -eq [System.DBNull]::Value) {
                        continue
                    }

                    if ($row.PercentUsed -ge $threshold) {
                        [PSCustomObject]@{
                            ComputerName   = $server.ComputerName
                            InstanceName   = $server.ServiceName
                            SqlInstance    = $server.DomainInstanceName
                            Database       = $row.DatabaseName
                            Schema         = $row.SchemaName
                            Table          = $row.TableName
                            Column         = $row.ColumnName
                            SeedValue      = $row.SeedValue
                            IncrementValue = $row.IncrementValue
                            LastValue      = $row.LastValue
                            MaxNumberRows  = $row.MaxNumberRows
                            NumberOfUses   = $row.NumberOfUses
                            PercentUsed    = $row.PercentUsed
                        } | Select-DefaultView -Exclude MaxNumberRows, NumberOfUses
                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Test-DbaJobOwner.ps1
function Test-DbaAgentJobOwner {
    <#
    .SYNOPSIS
        Checks SQL Agent Job owners against a login to validate which jobs do not match that owner.

    .DESCRIPTION
        This function checks all SQL Agent Jobs on an instance against a SQL login to validate if that login owns those SQL Agent Jobs or not. By default, the function checks against 'sa' for ownership, but the user can pass a specific login if they use something else.

        Only SQL Agent Jobs that do not match this ownership will be displayed.
        Best practice reference: http://sqlmag.com/blog/sql-server-tip-assign-ownership-jobs-sysadmin-account

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Job
        Specifies the job(s) to process. Options for this list are auto-populated from the server. If unspecified, all jobs will be processed.

    .PARAMETER ExcludeJob
        Specifies the job(s) to exclude from processing. Options for this list are auto-populated from the server.

    .PARAMETER Login
        Specifies the login that you wish check for ownership. This defaults to 'sa' or the sysadmin name if sa was renamed. This must be a valid security principal which exists on the target server.

    .PARAMETER Detailed
        Output all properties, will be deprecated in 1.0.0 release.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Job, Owner
        Author: Michael Fal (@Mike_Fal), http://mikefal.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaAgentJobOwner

    .EXAMPLE
        PS C:\> Test-DbaAgentJobOwner -SqlInstance localhost

        Returns all SQL Agent Jobs where the owner does not match 'sa'.

    .EXAMPLE
        PS C:\> Test-DbaAgentJobOwner -SqlInstance localhost -ExcludeJob 'syspolicy_purge_history'

        Returns SQL Agent Jobs except for the syspolicy_purge_history job

    .EXAMPLE
        PS C:\> Test-DbaAgentJobOwner -SqlInstance localhost -Login DOMAIN\account

        Returns all SQL Agent Jobs where the owner does not match DOMAIN\account. Note
        that Login must be a valid security principal that exists on the target server.

    #>
    [CmdletBinding()]
    [OutputType('System.Object[]')]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Jobs")]
        [object[]]$Job,
        [object[]]$ExcludeJob,
        [Alias("TargetLogin")]
        [string]$Login,
        [switch]$Detailed,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter Detailed
        #connect to the instance and set return array empty
        $return = @()
    }
    process {
        foreach ($instance in $SqlInstance) {
            #connect to the instance
            $server = Connect-SqlInstance $instance -SqlCredential $SqlCredential

            #Validate login
            if ($Login -and ($server.Logins.Name) -notcontains $Login) {
                if ($SqlInstance.count -eq 1) {
                    Stop-Function -Message "Invalid login: $Login."
                    return
                } else {
                    Write-Message -Level Warning -Message "$Login is not a valid login on $instance. Moving on."
                    continue
                }
            }
            if ($Login -and $server.Logins[$Login].LoginType -eq 'WindowsGroup') {
                Stop-Function -Message "$Login is a Windows Group and can not be a job owner."
                return
            }

            #Sets the Default Login to sa if the Login Paramater is not set.
            if (!($PSBoundParameters.ContainsKey('Login'))) {
                $Login = "sa"
            }
            #sql2000 id property is empty -force target login to 'sa' login
            if ($Login -and ( ($server.VersionMajor -lt 9) -and ([string]::IsNullOrEmpty($Login)) )) {
                $Login = "sa"
            }
            # dynamic sa name for orgs who have changed their sa name
            if ($Login -eq "sa") {
                $Login = ($server.Logins | Where-Object { $_.id -eq 1 }).Name
            }

            #Get database list. If value for -Job is passed, massage to make it a string array.
            #Otherwise, use all jobs on the instance where owner not equal to -TargetLogin
            Write-Message -Level Verbose -Message "Gathering jobs to check."
            if ($Job) {
                $jobCollection = $server.JobServer.Jobs | Where-Object { $Job -contains $_.Name }
            } elseif ($ExcludeJob) {
                $jobCollection = $server.JobServer.Jobs | Where-Object { $ExcludeJob -notcontains $_.Name }
            } else {
                $jobCollection = $server.JobServer.Jobs
            }

            #for each database, create custom object for return set.
            foreach ($j in $jobCollection) {
                Write-Message -Level Verbose -Message "Checking $j"
                $row = [ordered]@{
                    Server       = $server.Name
                    Job          = $j.Name
                    JobType      = if ($j.CategoryID -eq 1) { "Remote" } else { $j.JobType }
                    CurrentOwner = $j.OwnerLoginName
                    TargetOwner  = $Login
                    OwnerMatch   = if ($j.CategoryID -eq 1) { $true } else { $j.OwnerLoginName -eq $Login }

                }
                #add each custom object to the return array
                $return += New-Object PSObject -Property $row
            }
            if ($Job) {
                $results = $return
            } else {
                $results = $return | Where-Object {$_.OwnerMatch -eq $False}
            }
        }
    }
    end {
        #return results
        Select-DefaultView -InputObject $results -Property Server, Job, JobType, CurrentOwner, TargetOwner, OwnerMatch
    }

}
tools\dbatools\functions\Test-DbaLastBackup.ps1
function Test-DbaLastBackup {
    <#
    .SYNOPSIS
        Quickly and easily tests the last set of full backups for a server.

    .DESCRIPTION
        Restores all or some of the latest backups and performs a DBCC CHECKDB.

        1. Gathers information about the last full backups
        2. Restores the backups to the Destination with a new name. If no Destination is specified, the originating SQL Server instance wil be used.
        3. The database is restored as "dbatools-testrestore-$databaseName" by default, but you can change dbatools-testrestore to whatever you would like using -Prefix
        4. The internal file names are also renamed to prevent conflicts with original database
        5. A DBCC CHECKDB is then performed
        6. And the test database is finally dropped

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. Unlike many of the other commands, you cannot specify more than one server.

    .PARAMETER Destination
        The destination server to use to test the restore. By default, the Destination will be set to the source server

        If a different Destination server is specified, you must ensure that the database backups are on a shared location

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER DestinationCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database backups to test. If -Database is not provided, all database backups will be tested.

    .PARAMETER ExcludeDatabase
        Exclude specific Database backups to test.

    .PARAMETER DataDirectory
        Specifies an alternative directory for mdfs, ndfs and so on. The command uses the SQL Server's default data directory for all restores.

    .PARAMETER LogDirectory
        Specifies an alternative directory for ldfs. The command uses the SQL Server's default log directory for all restores.

    .PARAMETER VerifyOnly
        If this switch is enabled, VERIFYONLY will be performed. An actual restore will not be executed.

    .PARAMETER NoCheck
        If this switch is enabled, DBCC CHECKDB will be skipped

    .PARAMETER NoDrop
        If this switch is enabled, the newly-created test database will not be dropped.

    .PARAMETER CopyFile
        If this switch is enabled, the backup file will be copied to the destination default backup location unless CopyPath is specified.

    .PARAMETER CopyPath
        Specifies a path relative to the SQL Server to copy backups when CopyFile is specified. If not specified will use destination default backup location. If destination SQL Server is not local, admin UNC paths will be utilized for the copy.

    .PARAMETER MaxSize
        Max size in MB. Databases larger than this value will not be restored.

    .PARAMETER AzureCredential
        The name of the SQL Server credential on the destination instance that holds the key to the azure storage account.

    .PARAMETER IncludeCopyOnly
        If this switch is enabled, copy only backups will be counted as a last backup.

    .PARAMETER IgnoreLogBackup
        If this switch is enabled, transaction log backups will be ignored. The restore will stop at the latest full or differential backup point.

    .PARAMETER Prefix
        The database is restored as "dbatools-testrestore-$databaseName" by default. You can change dbatools-testrestore to whatever you would like using this parameter.

    .PARAMETER InputObject
        Enables piping from Get-DbaDatabase

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: DisasterRecovery, Backup, Restore
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaLastBackup

    .EXAMPLE
        PS C:\> Test-DbaLastBackup -SqlInstance sql2016

        Determines the last full backup for ALL databases, attempts to restore all databases (with a different name and file structure), then performs a DBCC CHECKDB. Once the test is complete, the test restore will be dropped.

    .EXAMPLE
        PS C:\> Test-DbaLastBackup -SqlInstance sql2016 -Database SharePoint_Config

        Determines the last full backup for SharePoint_Config, attempts to restore it, then performs a DBCC CHECKDB.

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sql2016, sql2017 | Test-DbaLastBackup

        Tests every database backup on sql2016 and sql2017

    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sql2016, sql2017 -Database SharePoint_Config | Test-DbaLastBackup

        Tests the database backup for the SharePoint_Config database on sql2016 and sql2017

    .EXAMPLE
       PS C:\> Test-DbaLastBackup -SqlInstance sql2016 -Database model, master -VerifyOnly

       Skips performing an action restore of the database and simply verifies the backup using VERIFYONLY option of the restore.

    .EXAMPLE
        PS C:\> Test-DbaLastBackup -SqlInstance sql2016 -NoCheck -NoDrop

        Skips the DBCC CHECKDB check. This can help speed up the tests but makes it less tested. The test restores will remain on the server.

    .EXAMPLE
        PS C:\> Test-DbaLastBackup -SqlInstance sql2016 -DataDirectory E:\bigdrive -LogDirectory L:\bigdrive -MaxSize 10240

        Restores data and log files to alternative locations and only restores databases that are smaller than 10 GB.

    .EXAMPLE
        PS C:\> Test-DbaLastBackup -SqlInstance sql2014 -Destination sql2016 -CopyFile

        Copies the backup files for sql2014 databases to sql2016 default backup locations and then attempts restore from there.

    .EXAMPLE
        PS C:\> Test-DbaLastBackup -SqlInstance sql2014 -Destination sql2016 -CopyFile -CopyPath "\\BackupShare\TestRestore\"

        Copies the backup files for sql2014 databases to sql2016 default backup locations and then attempts restore from there.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "", Justification = "For Parameters DestinationCredential and AzureCredential")]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [DbaInstanceParameter]$Destination,
        [object]$DestinationCredential,
        [string]$DataDirectory,
        [string]$LogDirectory,
        [string]$Prefix = "dbatools-testrestore-",
        [switch]$VerifyOnly,
        [switch]$NoCheck,
        [switch]$NoDrop,
        [switch]$CopyFile,
        [string]$CopyPath,
        [Alias("MaxMB")]
        [int]$MaxSize,
        [switch]$IncludeCopyOnly,
        [switch]$IgnoreLogBackup,
        [string]$AzureCredential,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )
    begin {
        Test-DbaDeprecation -DeprecatedOn "1.0" -Parameter 'MaxMB'
    }
    process {
        if ($SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase
        }

        foreach ($db in $InputObject) {
            if ($db.Name -eq "tempdb") {
                continue
            }

            $sourceserver = $db.Parent
            $source = $db.Parent.Name
            $instance = [DbaInstanceParameter]$source
            $copysuccess = $true
            $dbname = $db.Name
            $restoreresult = $null

            if (-not (Test-Bound -ParameterName Destination)) {
                $destination = $sourceserver.Name
                $DestinationCredential = $SqlCredential
            }

            try {
                $destserver = Connect-SqlInstance -SqlInstance $destination -SqlCredential $DestinationCredential
            } catch {
                Stop-Function -Message "Failed to connect to: $destination." -Target $destination -Continue
            }

            if ($destserver.VersionMajor -lt $sourceserver.VersionMajor) {
                Stop-Function -Message "$Destination is a lower version than $instance. Backups would be incompatible." -Continue
            }

            if ($destserver.VersionMajor -eq $sourceserver.VersionMajor -and $destserver.VersionMinor -lt $sourceserver.VersionMinor) {
                Stop-Function -Message "$Destination is a lower version than $instance. Backups would be incompatible." -Continue
            }

            if ($CopyPath) {
                $testpath = Test-DbaPath -SqlInstance $destserver -Path $CopyPath
                if (-not $testpath) {
                    Stop-Function -Message "$destserver cannot access $CopyPath." -Continue
                }
            } else {
                # If not CopyPath is specified, use the destination server default backup directory
                $copyPath = $destserver.BackupDirectory
            }

            if ($instance -ne $destination -and -not $CopyFile) {
                $sourcerealname = $sourceserver.ComputerNetBiosName
                $destrealname = $destserver.ComputerNetBiosName

                if ($BackupFolder) {
                    if ($BackupFolder.StartsWith("\\") -eq $false -and $sourcerealname -ne $destrealname) {
                        Stop-Function -Message "Backup folder must be a network share if the source and destination servers are not the same." -Continue
                    }
                }
            }

            if ($datadirectory) {
                if (-not (Test-DbaPath -SqlInstance $destserver -Path $datadirectory)) {
                    $serviceaccount = $destserver.ServiceAccount
                    Stop-Function -Message "Can't access $datadirectory Please check if $serviceaccount has permissions." -Continue
                }
            } else {
                $datadirectory = Get-SqlDefaultPaths -SqlInstance $destserver -FileType mdf
            }

            if ($logdirectory) {
                if (-not (Test-DbaPath -SqlInstance $destserver -Path $logdirectory)) {
                    $serviceaccount = $destserver.ServiceAccount
                    Stop-Function -Message "$Destination can't access its local directory $logdirectory. Please check if $serviceaccount has permissions." -Continue
                }
            } else {
                $logdirectory = Get-SqlDefaultPaths -SqlInstance $destserver -FileType ldf
            }

            if ((Test-Bound -ParameterName AzureCredential) -and (Test-Bound -ParameterName CopyFile)) {
                Stop-Function -Message "Cannot use copyfile with Azure backups, set to false." -continue
                $CopyFile = $false
            }

            Write-Message -Level Verbose -Message "Getting recent backup history for $($db.Name) on $instance."

            if (Test-Bound "IgnoreLogBackup") {
                Write-Message -Level Verbose -Message "Skipping Log backups as requested."
                $lastbackup = @()
                $lastbackup += $full = Get-DbaBackupHistory -SqlInstance $sourceserver -Database $dbname -IncludeCopyOnly:$IncludeCopyOnly -LastFull -WarningAction SilentlyContinue
                $diff = Get-DbaBackupHistory -SqlInstance $sourceserver -Database $dbname -IncludeCopyOnly:$IncludeCopyOnly -LastDiff -WarningAction SilentlyContinue
                if ($full.start -le $diff.start) {
                    $lastbackup += $diff
                }
            } else {
                $lastbackup = Get-DbaBackupHistory -SqlInstance $sourceserver -Database $dbname -IncludeCopyOnly:$IncludeCopyOnly -Last -WarningAction SilentlyContinue
            }

            if (-not $lastbackup) {
                Write-Message -Level Verbose -Message "No backups exist for this database."
                $lastbackup = @{
                    Path = "No backups exist for this database"
                }
                $fileexists = $false
                $success = $restoreresult = $dbccresult = "Skipped"
                continue
            }

            if ($CopyFile) {
                try {
                    Write-Message -Level Verbose -Message "Gathering information for file copy."
                    $removearray = @()

                    foreach ($backup in $lastbackup) {
                        foreach ($file in $backup) {
                            $filename = Split-Path -Path $file.FullName -Leaf
                            Write-Message -Level Verbose -Message "Processing $filename."

                            $sourcefile = Join-AdminUnc -servername $instance.ComputerName -filepath "$($file.Path)"

                            if ($instance.IsLocalHost) {
                                $remotedestdirectory = Join-AdminUnc -servername $instance.ComputerName -filepath $copyPath
                            } else {
                                $remotedestdirectory = $copyPath
                            }

                            $remotedestfile = "$remotedestdirectory\$filename"
                            $localdestfile = "$copyPath\$filename"
                            Write-Message -Level Verbose -Message "Destination directory is $destdirectory."
                            Write-Message -Level Verbose -Message "Destination filename is $remotedestfile."

                            try {
                                Write-Message -Level Verbose -Message "Copying $sourcefile to $remotedestfile."
                                Copy-Item -Path $sourcefile -Destination $remotedestfile -ErrorAction Stop
                                $backup.Path = $localdestfile
                                $backup.FullName = $localdestfile
                                $removearray += $remotedestfile
                            } catch {
                                $backup.Path = $sourcefile
                                $backup.FullName = $sourcefile
                            }
                        }
                    }
                    $copysuccess = $true
                } catch {
                    Write-Message -Level Warning -Message "Failed to copy backups for $dbname on $instance to $destdirectory - $_."
                    $copysuccess = $false
                }
            }
            if (-not $copysuccess) {
                Write-Message -Level Verbose -Message "Failed to copy backups."
                $lastbackup = @{
                    Path = "Failed to copy backups"
                }
                $fileexists = $false
                $success = $restoreresult = $dbccresult = "Skipped"
            } elseif (-not ($lastbackup | Where-Object {
                        $_.type -eq 'Full'
                    })) {
                Write-Message -Level Verbose -Message "No full backup returned from lastbackup."
                $lastbackup = @{
                    Path = "Not found"
                }
                $fileexists = $false
                $success = $restoreresult = $dbccresult = "Skipped"
            } elseif ($source -ne $destination -and $lastbackup[0].Path.StartsWith('\\') -eq $false -and -not $CopyFile) {
                Write-Message -Level Verbose -Message "Path not UNC and source does not match destination. Use -CopyFile to move the backup file."
                $fileexists = $dbccresult = "Skipped"
                $success = $restoreresult = "Restore not located on shared location"
            } elseif (($lastbackup[0].Path | ForEach-Object {
                        Test-DbaPath -SqlInstance $destserver -Path $_
                    }) -eq $false) {
                Write-Message -Level Verbose -Message "SQL Server cannot find backup."
                $fileexists = $false
                $success = $restoreresult = $dbccresult = "Skipped"
            }
            if ($restoreresult -ne "Skipped" -or $lastbackup[0].Path -like 'http*') {
                Write-Message -Level Verbose -Message "Looking good!"

                $fileexists = $true
                $ogdbname = $dbname
                $restorelist = Read-DbaBackupHeader -SqlInstance $destserver -Path $lastbackup[0].Path -AzureCredential $AzureCredential

                if ($MaxSize -and $MaxSize -lt $restorelist.BackupSize.Megabyte) {
                    $success = "The backup size for $dbname ($mb MB) exceeds the specified maximum size ($MaxSize MB)."
                    $dbccresult = "Skipped"
                } else {
                    $dbccElapsed = $restoreElapsed = $startRestore = $endRestore = $startDbcc = $endDbcc = $null

                    $dbname = "$prefix$dbname"
                    $destdb = $destserver.databases[$dbname]

                    if ($destdb) {
                        Stop-Function -Message "$dbname already exists on $destination - skipping." -Continue
                    }

                    if ($Pscmdlet.ShouldProcess($destination, "Restoring $ogdbname as $dbname.")) {
                        Write-Message -Level Verbose -Message "Performing restore."
                        $startRestore = Get-Date
                        if ($verifyonly) {
                            $restoreresult = $lastbackup | Restore-DbaDatabase -SqlInstance $destserver -RestoredDatabaseNamePrefix $prefix -DestinationFilePrefix $Prefix -DestinationDataDirectory $datadirectory -DestinationLogDirectory $logdirectory -VerifyOnly:$VerifyOnly -IgnoreLogBackup:$IgnoreLogBackup -AzureCredential $AzureCredential -TrustDbBackupHistory
                        } else {
                            $restoreresult = $lastbackup | Restore-DbaDatabase -SqlInstance $destserver -RestoredDatabaseNamePrefix $prefix -DestinationFilePrefix $Prefix -DestinationDataDirectory $datadirectory -DestinationLogDirectory $logdirectory -IgnoreLogBackup:$IgnoreLogBackup -AzureCredential $AzureCredential -TrustDbBackupHistory
                            Write-Message -Level Verbose -Message " Restore-DbaDatabase -SqlInstance $destserver -RestoredDatabaseNamePrefix $prefix -DestinationFilePrefix $Prefix -DestinationDataDirectory $datadirectory -DestinationLogDirectory $logdirectory -IgnoreLogBackup:$IgnoreLogBackup -AzureCredential $AzureCredential -TrustDbBackupHistory"

                        }

                        $endRestore = Get-Date
                        $restorets = New-TimeSpan -Start $startRestore -End $endRestore
                        $ts = [timespan]::fromseconds($restorets.TotalSeconds)
                        $restoreElapsed = "{0:HH:mm:ss}" -f ([datetime]$ts.Ticks)

                        if ($restoreresult.RestoreComplete -eq $true) {
                            $success = "Success"
                        } else {
                            $success = "Failure"
                        }
                    }

                    $destserver = Connect-SqlInstance -SqlInstance $destination -SqlCredential $DestinationCredential

                    if (-not $NoCheck -and -not $VerifyOnly) {
                        # shouldprocess is taken care of in Start-DbccCheck
                        if ($ogdbname -eq "master") {
                            $dbccresult = "DBCC CHECKDB skipped for restored master ($dbname) database."
                        } else {
                            if ($success -eq "Success") {
                                Write-Message -Level Verbose -Message "Starting DBCC."

                                $startDbcc = Get-Date
                                $dbccresult = Start-DbccCheck -Server $destserver -DbName $dbname 3>$null
                                $endDbcc = Get-Date

                                $dbccts = New-TimeSpan -Start $startDbcc -End $endDbcc
                                $ts = [timespan]::fromseconds($dbccts.TotalSeconds)
                                $dbccElapsed = "{0:HH:mm:ss}" -f ([datetime]$ts.Ticks)
                            } else {
                                $dbccresult = "Skipped"
                            }
                        }
                    }

                    if ($VerifyOnly) {
                        $dbccresult = "Skipped"
                    }

                    if (-not $NoDrop -and $null -ne $destserver.databases[$dbname]) {
                        if ($Pscmdlet.ShouldProcess($dbname, "Dropping Database $dbname on $destination")) {
                            Write-Message -Level Verbose -Message "Dropping database."

                            ## Drop the database
                            try {
                                #Variable $removeresult marked as unused by PSScriptAnalyzer replace with $null to catch output
                                $null = Remove-DbaDatabase -SqlInstance $destserver -Database $dbname -Confirm:$false
                                Write-Message -Level Verbose -Message "Dropped $dbname Database on $destination."
                            } catch {
                                $destserver.Databases.Refresh()
                                if ($destserver.databases[$dbname]) {
                                    Write-Message -Level Warning -Message "Failed to Drop database $dbname on $destination."
                                }
                            }
                        }
                    }

                    #Cleanup BackupFiles if -CopyFile and backup was moved to destination

                    $destserver.Databases.Refresh()
                    if ($destserver.Databases[$dbname] -and -not $NoDrop) {
                        Write-Message -Level Warning -Message "$dbname was not dropped."
                    }
                }

                if ($CopyFile) {
                    Write-Message -Level Verbose -Message "Removing copied backup file from $destination."
                    try {
                        $removearray | Remove-item -ErrorAction Stop
                    } catch {
                        Write-Message -Level Warning -Message $_ -ErrorRecord $_ -Target $instance
                    }
                }
            }

            if ($Pscmdlet.ShouldProcess("console", "Showing results")) {
                [pscustomobject]@{
                    SourceServer   = $source
                    TestServer     = $destination
                    Database       = $db.name
                    FileExists     = $fileexists
                    Size           = [dbasize](($lastbackup.TotalSize | Measure-Object -Sum).Sum)
                    RestoreResult  = $success
                    DbccResult     = $dbccresult
                    RestoreStart   = [dbadatetime]$startRestore
                    RestoreEnd     = [dbadatetime]$endRestore
                    RestoreElapsed = $restoreElapsed
                    DbccStart      = [dbadatetime]$startDbcc
                    DbccEnd        = [dbadatetime]$endDbcc
                    DbccElapsed    = $dbccElapsed
                    BackupDates    = [String[]]($lastbackup.Start)
                    BackupFiles    = $lastbackup.FullName
                }
            }
        }
    }
}
tools\dbatools\functions\Test-DbaLinkedServerConnection.ps1
function Test-DbaLinkedServerConnection {
    <#
    .SYNOPSIS
        Test all linked servers from the sql servers passed

    .DESCRIPTION
        Test each linked server on the instance

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Credential object used to connect to the SQL Server as a different user

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.

        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: LinkedServer
        Author: Thomas LaRock ( https://thomaslarock.com )

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaLinkedServerConnection

    .EXAMPLE
        PS C:\> Test-DbaLinkedServerConnection -SqlInstance DEV01

        Test all Linked Servers for the SQL Server instance DEV01

    .EXAMPLE
        PS C:\> Test-DbaLinkedServerConnection -SqlInstance sql2016 | Out-File C:\temp\results.txt

        Test all Linked Servers for the SQL Server instance sql2016 and output results to file

    .EXAMPLE
        PS C:\> Test-DbaLinkedServerConnection -SqlInstance sql2016, sql2014, sql2012

        Test all Linked Servers for the SQL Server instances sql2016, sql2014 and sql2012

    .EXAMPLE
        PS C:\> $servers = "sql2016","sql2014","sql2012"
        PS C:\> $servers | Test-DbaLinkedServerConnection -SqlCredential sqladmin

        Test all Linked Servers for the SQL Server instances sql2016, sql2014 and sql2012 using SQL login credentials

    .EXAMPLE
        PS C:\> $servers | Get-DbaLinkedServer | Test-DbaLinkedServerConnection

        Test all Linked Servers for the SQL Server instances sql2016, sql2014 and sql2012

    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            if ($instance.LinkedLive) {
                $linkedServerCollection = $instance.LinkedServer
            } else {
                try {
                    $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
                } catch {
                    Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                }
            }

            $linkedServerCollection = $server.LinkedServers

            foreach ($ls in $linkedServerCollection) {
                Write-Message -Level Verbose -Message "Testing linked server $($ls.name) on server $($ls.parent.name)"
                try {
                    $null = $ls.TestConnection()
                    $result = "Success"
                    $connectivity = $true
                } catch {
                    $result = $_.Exception.InnerException.InnerException.Message
                    $connectivity = $false
                }

                New-Object Sqlcollaborative.Dbatools.Validation.LinkedServerResult($ls.parent.ComputerName, $ls.parent.ServiceName, $ls.parent.DomainInstanceName, $ls.Name, $ls.DataSource, $connectivity, $result)
            }
        }
    }
}
tools\dbatools\functions\Test-DbaLoginPassword.ps1
function Test-DbaLoginPassword {
    <#
    .SYNOPSIS
        Test-DbaLoginPassword finds any logins on SQL instance that are SQL Logins and have a password that is either null or same as the login

    .DESCRIPTION
        The purpose of this function is to find SQL Server logins that have no password or the same password as login. You can add your own password to check for or add them to a csv file.
        By default it will test for empty password and the same password as username.

    .PARAMETER SqlInstance
        The SQL Server instance you're checking logins on. You must have sysadmin access and server version must be SQL Server version 2008 or higher.

    .PARAMETER SqlCredential
        Allows you to login to servers using SQL Logins instead of Windows Authentication (AKA Integrated or Trusted). To use:

        $scred = Get-Credential, then pass $scred object to the -SqlCredential parameter.

        Windows Authentication will be used if SqlCredential is not specified. SQL Server does not accept Windows credentials being passed as credentials.

        To connect as a different Windows user, run PowerShell as that user.

    .PARAMETER Dictionary
        Specifies a list of passwords to include in the test for weak passwords.

    .PARAMETER Login
        The login(s) to process.

    .PARAMETER InputObject
        Allows piping from Get-DbaLogin.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Login, Security
        Author: Peter Samuelsson

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaLoginPassword

    .EXAMPLE
        PS C:\> Test-DbaLoginPassword -SqlInstance Dev01

        Test all SQL logins that the password is null or same as username on SQL server instance Dev01

    .EXAMPLE
        PS C:\> Test-DbaLoginPassword -SqlInstance Dev01 -Login sqladmin

        Test the 'sqladmin' SQL login that the password is null or same as username on SQL server instance Dev01

    .EXAMPLE
        PS C:\> Test-DbaLoginPassword -SqlInstance Dev01 -Dictionary Test1,test2

        Test all SQL logins that the password is null, same as username or Test1,Test2 on SQL server instance Dev0

    .EXAMPLE
        PS C:\> Get-DbaLogin -SqlInstance "sql2017","sql2016" | Test-DbaLoginPassword

        Test all logins on sql2017 and sql2016

    .EXAMPLE
        PS C:\> $servers | Get-DbaLogin | Out-GridView -PassThru | Test-DbaLoginPassword

        Test selected logins on all servers in the $servers variable

    #>
    [CmdletBinding()]
    param (
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [String[]]$Login,
        [String[]]$Dictionary,
        [Parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Login[]]$InputObject,
        [switch]$EnableException
    )

    begin {
        $CheckPasses = "''", "'@@Name'"
        if ($Dictionary) {
            $Dictionary | ForEach-Object { $CheckPasses += "'" + $psitem + "'" }
        }

        foreach ($CheckPass in $CheckPasses) {
            if ($CheckPasses.IndexOf($CheckPass) -eq 0) {
                $checks = "SELECT " + $CheckPass
            } else {
                $checks += "
        UNION SELECT " + $CheckPass
            }
        }

        $sql = "DECLARE @WeakPwdList TABLE(WeakPwd NVARCHAR(255))
            --Define weak password list
            --Use @@Name if users password contain their name
            INSERT INTO @WeakPwdList(WeakPwd)
            $checks

            SELECT SERVERPROPERTY('MachineName') AS [ComputerName],
                ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
                SERVERPROPERTY('ServerName') AS [SqlInstance],
                SysLogins.name as SqlLogin,
                WeakPassword = 'True',
                REPLACE(WeakPassword.WeakPwd,'@@Name',SysLogins.name) As [Password],
                SysLogins.is_disabled as Disabled,
                SysLogins.create_date as CreatedDate,
                SysLogins.modify_date as ModifiedDate,
                SysLogins.default_database_name as DefaultDatabase
            FROM sys.sql_logins SysLogins
            INNER JOIN @WeakPwdList WeakPassword ON (PWDCOMPARE(WeakPassword.WeakPwd, password_hash) = 1
                OR PWDCOMPARE(REPLACE(WeakPassword.WeakPwd,'@@Name',SysLogins.name),password_hash) = 1)"
    }
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential -MinimumVersion 10
                Write-Message -Message "Connected to: $instance." -Level Verbose
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            $InputObject += Get-DbaLogin -SqlInstance $server -Login $Login
        }

        $logins += $InputObject
    }
    end {
        $servers = $logins | Select-Object -Unique -ExpandProperty Parent
        $names = $logins | Select-Object -Unique -ExpandProperty Name

        foreach ($serverinstance in $servers) {
            Write-Message -Level Debug -Message "Executing $sql"
            Write-Message -Level Verbose -Message "Testing: same username as Password"
            Write-Message -Level Verbose -Message "Testing: the following Passwords $CheckPasses"
            try {
                $serverinstance.Query("$sql") | Where-Object SqlLogin -in $names
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Target $serverinstance -Continue
            }
        }
    }
}
tools\dbatools\functions\Test-DbaManagementObject.ps1
function Test-DbaManagementObject {
    <#
    .SYNOPSIS
        Tests to see if the SMO version specified exists on the computer.

    .DESCRIPTION
        The Test-DbaManagementObject returns True if the Version is on the computer, and False if it does not exist.

    .PARAMETER ComputerName
        The name of the target you would like to check

    .PARAMETER Credential
        This command uses Windows credentials. This parameter allows you to connect remotely as a different user.

    .PARAMETER VersionNumber
        This is the specific version number you are looking for and the return will be True.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: SMO
        Author: Ben Miller (@DBAduck), http://dbaduck.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaManagementObject

    .EXAMPLE
        PS C:\> Test-DbaManagementObject -VersionNumber 13

        Returns True if the version exists, if it does not exist it will return False

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlInstance")]
        [DbaInstance[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [Parameter(Mandatory)]
        [int[]]$VersionNumber,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $scriptblock = {
            foreach ($number in $args) {
                $smoList = (Get-ChildItem -Path "$($env:SystemRoot)\assembly\GAC_MSIL\Microsoft.SqlServer.Smo" -Filter "$number.*" | Sort-Object Name -Descending).Name

                if ($smoList) {
                    [pscustomobject]@{
                        ComputerName = $env:COMPUTERNAME
                        Version      = $number
                        Exists       = $true
                    }
                } else {
                    [pscustomobject]@{
                        ComputerName = $env:COMPUTERNAME
                        Version      = $number
                        Exists       = $false
                    }
                }
            }
        }
    }
    process {
        foreach ($computer in $ComputerName.ComputerName) {
            try {
                Invoke-Command2 -ComputerName $computer -ScriptBlock $scriptblock -Credential $Credential -ArgumentList $VersionNumber -ErrorAction Stop
            } catch {
                Stop-Function -Continue -Message "Failure" -ErrorRecord $_ -Target $computer -Continue
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Test-DbaSqlManagementObject
    }
}
tools\dbatools\functions\Test-DbaMaxDop.ps1
function Test-DbaMaxDop {
    <#
    .SYNOPSIS
        Displays information relating to SQL Server Max Degree of Parallelism setting. Works on SQL Server 2005-2016.

    .DESCRIPTION
        Inspired by Sakthivel Chidambaram's post about SQL Server MAXDOP Calculator (https://blogs.msdn.microsoft.com/sqlsakthi/p/maxdop-calculator-SqlInstance/),
        this script displays a SQL Server's: max dop configured, and the calculated recommendation.

        For SQL Server 2016 shows:
        - Instance max dop configured and the calculated recommendation
        - max dop configured per database (new feature)

        More info:
        https://support.microsoft.com/en-us/kb/2806535
        https://blogs.msdn.microsoft.com/sqlsakthi/2012/05/23/wow-we-have-maxdop-calculator-for-sql-server-it-makes-my-job-easier/

        These are just general recommendations for SQL Server and are a good starting point for setting the "max degree of parallelism" option.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Detailed
        Output all properties, will be deprecated in 1.0.0 release.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: MaxDop, SpConfigure
        Author: Claudio Silva (@claudioessilva)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires: sysadmin access on SQL Servers

    .LINK
        https://dbatools.io/Test-DbaMaxDop

    .EXAMPLE
        PS C:\> Test-DbaMaxDop -SqlInstance sql2008, sqlserver2012

        Get Max DOP setting for servers sql2008 and sqlserver2012 and also the recommended one.

    .EXAMPLE
        PS C:\> Test-DbaMaxDop -SqlInstance sql2014 | Select-Object *

        Shows Max DOP setting for server sql2014 with the recommended value. Piping the output to Select-Object * will also show the 'NumaNodes' and 'NumberOfCores' of each instance

    .EXAMPLE
        PS C:\> Test-DbaMaxDop -SqlInstance sqlserver2016 | Select-Object *

        Get Max DOP setting for servers sql2016 with the recommended value. Piping the output to Select-Object * will also show the 'NumaNodes' and 'NumberOfCores' of each instance. Because it is an 2016 instance will be shown 'InstanceVersion', 'Database' and 'DatabaseMaxDop' columns.

       #>
    [CmdletBinding()]
    [OutputType([System.Collections.ArrayList])]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$Detailed,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter Detailed

        $notesDopLT = "Before changing MaxDop, consider that the lower value may have been intentionally set."
        $notesDopGT = "Before changing MaxDop, consider that the higher value may have been intentionally set."
        $notesDopZero = "This is the default setting. Consider using the recommended value instead."
        $notesDopOne = "Some applications like SharePoint, Dynamics NAV, SAP, BizTalk has the need to use MAXDOP = 1. Please confirm that your instance is not supporting one of these applications prior to changing the MaxDop."
        $notesAsRecommended = "Configuration is as recommended."
    }

    process {
        #Variable marked as unused by PSScriptAnalyzer
        #$hasScopedConfig = $false

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            #Get current configured value
            $maxDop = $server.Configuration.MaxDegreeOfParallelism.ConfigValue

            try {
                #represents the Number of NUMA nodes
                $sql = "SELECT COUNT(DISTINCT memory_node_id) AS NUMA_Nodes FROM sys.dm_os_memory_clerks WHERE memory_node_id!=64"
                $NumaNodes = $server.ConnectionContext.ExecuteScalar($sql)
            } catch {
                Stop-Function -Message "Failed to get Numa node count." -ErrorRecord $_ -Target $server -Continue
            }

            try {
                #represents the Number of Processor Cores
                $sql = "SELECT COUNT(scheduler_id) FROM sys.dm_os_schedulers WHERE status = 'VISIBLE ONLINE'"
                $numberOfCores = $server.ConnectionContext.ExecuteScalar($sql)
            } catch {
                Stop-Function -Message "Failed to get number of cores." -ErrorRecord $_ -Target $server -Continue
            }

            #Calculate Recommended Max Dop to instance
            #Server with single NUMA node
            if ($NumaNodes -eq 1) {
                if ($numberOfCores -lt 8) {
                    #Less than 8 logical processors - Keep MAXDOP at or below # of logical processors
                    $recommendedMaxDop = $numberOfCores
                } else {
                    #Equal or greater than 8 logical processors - Keep MAXDOP at 8
                    $recommendedMaxDop = 8
                }
            } else {
                #Server with multiple NUMA nodes
                if (($numberOfCores / $NumaNodes) -lt 8) {
                    # Less than 8 logical processors per NUMA node - Keep MAXDOP at or below # of logical processors per NUMA node
                    $recommendedMaxDop = [int]($numberOfCores / $NumaNodes)
                } else {
                    # Greater than 8 logical processors per NUMA node - Keep MAXDOP at 8
                    $recommendedMaxDop = 8
                }
            }

            #Setting notes for instance max dop value
            $notes = $null
            if ($maxDop -eq 1) {
                $notes = $notesDopOne
            } else {
                if ($maxDop -ne 0 -and $maxDop -lt $recommendedMaxDop) {
                    $notes = $notesDopLT
                } else {
                    if ($maxDop -ne 0 -and $maxDop -gt $recommendedMaxDop) {
                        $notes = $notesDopGT
                    } else {
                        if ($maxDop -eq 0) {
                            $notes = $notesDopZero
                        } else {
                            $notes = $notesAsRecommended
                        }
                    }
                }
            }

            [pscustomobject]@{
                ComputerName          = $server.ComputerName
                InstanceName          = $server.ServiceName
                SqlInstance           = $server.DomainInstanceName
                InstanceVersion       = $server.Version
                Database              = "N/A"
                DatabaseMaxDop        = "N/A"
                CurrentInstanceMaxDop = $maxDop
                RecommendedMaxDop     = $recommendedMaxDop
                NumaNodes             = $NumaNodes
                NumberOfCores         = $numberOfCores
                Notes                 = $notes
            } | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, Database, DatabaseMaxDop, CurrentInstanceMaxDop, RecommendedMaxDop, Notes

            # On SQL Server 2016 and higher, MaxDop can be set on a per-database level
            if ($server.VersionMajor -ge 13) {
                #Variable marked as unused by PSScriptAnalyzer
                #$hasScopedConfig = $true
                Write-Message -Level Verbose -Message "SQL Server 2016 or higher detected, checking each database's MaxDop."

                $databases = $server.Databases | where-object {$_.IsSystemObject -eq $false}

                foreach ($database in $databases) {
                    if ($database.IsAccessible -eq $false) {
                        Write-Message -Level Verbose -Message "Database $database is not accessible."
                        continue
                    }
                    Write-Message -Level Verbose -Message "Checking database '$($database.Name)'."

                    $dbmaxdop = $database.MaxDop

                    [pscustomobject]@{
                        ComputerName          = $server.ComputerName
                        InstanceName          = $server.ServiceName
                        SqlInstance           = $server.DomainInstanceName
                        InstanceVersion       = $server.Version
                        Database              = $database.Name
                        DatabaseMaxDop        = $dbmaxdop
                        CurrentInstanceMaxDop = $maxDop
                        RecommendedMaxDop     = $recommendedMaxDop
                        NumaNodes             = $NumaNodes
                        NumberOfCores         = $numberOfCores
                        Notes                 = if ($dbmaxdop -eq 0) { "Will use CurrentInstanceMaxDop value" } else { "$notes" }
                    }  | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, Database, DatabaseMaxDop, CurrentInstanceMaxDop, RecommendedMaxDop, Notes
                }
            }
        }
    }
}
tools\dbatools\functions\Test-DbaMaxMemory.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Test-DbaMaxMemory {
    <#
    .SYNOPSIS
        Calculates the recommended value for SQL Server 'Max Server Memory' configuration setting. Works on SQL Server 2000-2014.

    .DESCRIPTION
        Inspired by Jonathan Kehayias's post about SQL Server Max memory (http://bit.ly/sqlmemcalc), this script displays a SQL Server's: total memory, currently configured SQL max memory, and the calculated recommendation.

        Jonathan notes that the formula used provides a *general recommendation* that doesn't account for everything that may be going on in your specific environment.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Windows or Sql Login Credential with permission to log into the SQL instance

    .PARAMETER Credential
        Windows Credential with permission to log on to the server running the SQL instance

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: MaxMemory, Memory
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaMaxMemory

    .EXAMPLE
        PS C:\> Test-DbaMaxMemory -SqlInstance sqlcluster,sqlserver2012

        Calculate the 'Max Server Memory' for SQL Server instances sqlcluster and sqlserver2012

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sqlcluster | Test-DbaMaxMemory

        Calculate the 'Max Server Memory' settings for all servers within the SQL Server Central Management Server "sqlcluster"

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sqlcluster | Test-DbaMaxMemory | Where-Object { $_.MaxValue -gt $_.Total } | Set-DbaMaxMemory

        Find all servers in CMS that have Max SQL memory set to higher than the total memory of the server (think 2147483647) and set it to recommended value.

       #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [PSCredential]$Credential,
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            Write-Message -Level VeryVerbose -Message "Processing $instance" -Target $instance

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            Write-Message -Level Verbose -Target $instance -Message "Retrieving maximum memory statistics from $instance"
            $serverMemory = Get-DbaMaxMemory -SqlInstance $server
            try {
                Write-Message -Level Verbose -Target $instance -Message "Retrieving number of instances from $($instance.ComputerName)"
                if ($Credential) {
                    $serverService = Get-DbaService -ComputerName $instance -Credential $Credential -EnableException
                } else {
                    $serverService = Get-DbaService -ComputerName $instance -EnableException
                }
                $instanceCount = ($serverService | Where-Object State -Like Running | Where-Object InstanceName | Group-Object InstanceName | Measure-Object Count).Count
            } catch {
                Write-Message -Level Warning -Message "Couldn't get accurate SQL Server instance count on $instance. Defaulting to 1." -Target $instance -ErrorRecord $_
                $instanceCount = 1
            }

            if ($null -eq $serverMemory) {
                continue
            }
            $reserve = 1

            $maxMemory = $serverMemory.MaxValue
            $totalMemory = $serverMemory.Total

            if ($totalMemory -ge 4096) {
                $currentCount = $totalMemory
                while ($currentCount / 4096 -gt 0) {
                    if ($currentCount -gt 16384) {
                        $reserve += 1
                        $currentCount += -8192
                    } else {
                        $reserve += 1
                        $currentCount += -4096
                    }
                }
                $recommendedMax = [int]($totalMemory - ($reserve * 1024))
            } else {
                $recommendedMax = $totalMemory * .5
            }

            $recommendedMax = $recommendedMax / $instanceCount

            [pscustomobject]@{
                ComputerName     = $server.ComputerName
                InstanceName     = $server.ServiceName
                SqlInstance      = $server.DomainInstanceName
                InstanceCount    = $instanceCount
                Total            = [int]$totalMemory
                MaxValue         = [int]$maxMemory
                RecommendedValue = [int]$recommendedMax
                Server           = $server # This will allowing piping a non-connected object
            } | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, InstanceCount, Total, MaxValue, RecommendedValue
        }
    }
}
tools\dbatools\functions\Test-DbaMigrationConstraint.ps1
function Test-DbaMigrationConstraint {
    <#
    .SYNOPSIS
        Show if you can migrate the database(s) between the servers.

    .DESCRIPTION
        When you want to migrate from a higher edition to a lower one there are some features that can't be used.
        This function will validate if you have any of this features in use and will report to you.
        The validation will be made ONLY on on SQL Server 2008 or higher using the 'sys.dm_db_persisted_sku_features' dmv.

        This function only validate SQL Server 2008 versions or higher.
        The editions supported by this function are:
        - Enterprise
        - Developer
        - Evaluation
        - Standard
        - Express

        Take into account the new features introduced on SQL Server 2016 SP1 for all versions. More information at https://blogs.msdn.microsoft.com/sqlreleaseservices/sql-server-2016-service-pack-1-sp1-released/

        The -Database parameter is auto-populated for command-line completion.

    .PARAMETER Source
        Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SourceSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Destination
        Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.

    .PARAMETER DestinationSqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude. Options for this list are auto-populated from the server.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Migration
        Author: Claudio Silva (@ClaudioESSilva)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaMigrationConstraint

    .EXAMPLE
        PS C:\> Test-DbaMigrationConstraint -Source sqlserver2014a -Destination sqlcluster

        All databases on sqlserver2014a will be verified for features in use that can't be supported on sqlcluster.

    .EXAMPLE
        PS C:\> Test-DbaMigrationConstraint -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred

        All databases will be verified for features in use that can't be supported on the destination server. SQL credentials are used to authenticate against sqlserver2014a and Windows Authentication is used for sqlcluster.

    .EXAMPLE
        PS C:\> Test-DbaMigrationConstraint -Source sqlserver2014a -Destination sqlcluster -Database db1

        Only db1 database will be verified for features in use that can't be supported on the destination server.

    #>
    [CmdletBinding(DefaultParameterSetName = "DbMigration")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstance]$Source,
        [PSCredential]$SourceSqlCredential,
        [parameter(Mandatory)]
        [DbaInstance]$Destination,
        [PSCredential]$DestinationSqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        <#
            1804890536 = Enterprise
            1872460670 = Enterprise Edition: Core-based Licensing
            610778273 = Enterprise Evaluation
            284895786 = Business Intelligence
            -2117995310 = Developer
            -1592396055 = Express
            -133711905= Express with Advanced Services
            -1534726760 = Standard
            1293598313 = Web
            1674378470 = SQL Database
        #>

        $editions = @{
            "Enterprise" = 10;
            "Developer"  = 10;
            "Evaluation" = 10;
            "Standard"   = 5;
            "Express"    = 1
        }
        $notesCanMigrate = "Database can be migrated."
        $notesCannotMigrate = "Database cannot be migrated."
    }
    process {
        try {
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source -Continue
        }

        try {
            $destServer = Connect-SqlInstance -SqlInstance $Destination -SqlCredential $DestinationSqlCredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Destination -Continue
        }

        if (-Not $Database) {
            $Database = $sourceServer.Databases | Where-Object IsSystemObject -eq 0 | Select-Object Name, Status
        }

        if ($ExcludeDatabase) {
            $Database = $sourceServer.Databases | Where-Object Name -NotIn $ExcludeDatabase
        }

        if ($Database.Count -gt 0) {
            if ($Database -in @("master", "msdb", "tempdb")) {
                Stop-Function -Message "Migrating system databases is not currently supported."
                return
            }

            if ($sourceServer.VersionMajor -lt 9 -and $destServer.VersionMajor -gt 10) {
                Stop-Function -Message "Sql Server 2000 databases cannot be migrated to SQL Server version 2012 and above. Quitting."
                return
            }

            if ($sourceServer.Collation -ne $destServer.Collation) {
                Write-Message -Level Warning -Message "Collation on $Source, $($sourceServer.collation) differs from the $Destination, $($destServer.collation)."
            }

            if ($sourceServer.VersionMajor -gt $destServer.VersionMajor) {
                #indicate they must use 'Generate Scripts' and 'Export Data' options?
                Stop-Function -Message "You can't migrate databases from a higher version to a lower one. Quitting."
                return
            }

            if ($sourceServer.VersionMajor -lt 10) {
                Stop-Function -Message "This function does not support versions lower than SQL Server 2008 (v10)"
                return
            }

            #if editions differs, from higher to lower one, verify the sys.dm_db_persisted_sku_features - only available from SQL 2008 +
            if (($sourceServer.VersionMajor -ge 10 -and $destServer.VersionMajor -ge 10)) {
                foreach ($db in $Database) {
                    if ([string]::IsNullOrEmpty($db.Status)) {
                        $dbstatus = ($sourceServer.Databases | Where-Object Name -eq $db).Status.ToString()
                        $dbName = $db
                    } else {
                        $dbstatus = $db.Status.ToString()
                        $dbName = $db.Name
                    }

                    Write-Message -Level Verbose -Message "Checking database '$dbName'."

                    if ($dbstatus.Contains("Offline") -eq $false -or $db.IsAccessible -eq $true) {

                        [long]$destVersionNumber = $($destServer.VersionString).Replace(".", "")
                        [string]$sourceVersion = "$($sourceServer.Edition) $($sourceServer.ProductLevel) ($($sourceServer.Version))"
                        [string]$destVersion = "$($destServer.Edition) $($destServer.ProductLevel) ($($destServer.Version))"
                        [string]$dbFeatures = ""

                        #Check if database has any FILESTREAM filegroup
                        Write-Message -Level Verbose -Message "Checking if FileStream is in use for database '$dbName'."
                        if ($sourceServer.Databases[$dbName].FileGroups | Where-Object FileGroupType -eq 'FileStreamDataFileGroup') {
                            Write-Message -Level Verbose -Message "Found FileStream filegroup and files."
                            $fileStreamSource = Get-DbaSpConfigure -SqlInstance $sourceServer -ConfigName FilestreamAccessLevel
                            $fileStreamDestination = Get-DbaSpConfigure -SqlInstance $destServer -ConfigName FilestreamAccessLevel

                            if ($fileStreamSource.RunningValue -ne $fileStreamDestination.RunningValue) {
                                [pscustomobject]@{
                                    SourceInstance      = $sourceServer.Name
                                    DestinationInstance = $destServer.Name
                                    SourceVersion       = $sourceVersion
                                    DestinationVersion  = $destVersion
                                    Database            = $dbName
                                    FeaturesInUse       = $dbFeatures
                                    IsMigratable        = $false
                                    Notes               = "$notesCannotMigrate. Destination server dones not have the 'FilestreamAccessLevel' configuration (RunningValue: $($fileStreamDestination.RunningValue)) equal to source server (RunningValue: $($fileStreamSource.RunningValue))."
                                }
                                Continue
                            }
                        }

                        try {
                            $sql = "SELECT feature_name FROM sys.dm_db_persisted_sku_features"

                            $skuFeatures = $sourceServer.Query($sql, $dbName)

                            Write-Message -Level Verbose -Message "Checking features in use..."

                            if (@($skuFeatures).Count -gt 0) {
                                foreach ($row in $skuFeatures) {
                                    $dbFeatures += ",$($row["feature_name"])"
                                }

                                $dbFeatures = $dbFeatures.TrimStart(",")
                            }
                        } catch {
                            Stop-Function -Message "Issue collecting sku features." -ErrorRecord $_ -Target $sourceServer -Continue
                        }

                        #If SQL Server 2016 SP1 (13.0.4001.0) or higher
                        if ($destVersionNumber -ge 13040010) {
                            <#
                                Need to verify if Edition = EXPRESS and database uses 'Change Data Capture' (CDC)
                                This means that database cannot be migrated because Express edition doesn't have SQL Server Agent
                            #>
                            if ($editions.Item($destServer.Edition.ToString().Split(" ")[0]) -eq 1 -and $dbFeatures.Contains("ChangeCapture")) {
                                [pscustomobject]@{
                                    SourceInstance      = $sourceServer.Name
                                    DestinationInstance = $destServer.Name
                                    SourceVersion       = $sourceVersion
                                    DestinationVersion  = $destVersion
                                    Database            = $dbName
                                    FeaturesInUse       = $dbFeatures
                                    IsMigratable        = $false
                                    Notes               = "$notesCannotMigrate. Destination server edition is EXPRESS which does not support 'ChangeCapture' feature that is in use."
                                }
                            } else {
                                [pscustomobject]@{
                                    SourceInstance      = $sourceServer.Name
                                    DestinationInstance = $destServer.Name
                                    SourceVersion       = $sourceVersion
                                    DestinationVersion  = $destVersion
                                    Database            = $dbName
                                    FeaturesInUse       = $dbFeatures
                                    IsMigratable        = $true
                                    Notes               = $notesCanMigrate
                                }
                            }
                        }
                        #Version is lower than SQL Server 2016 SP1
                        else {
                            Write-Message -Level Verbose -Message "Source Server Edition: $($sourceServer.Edition) (Weight: $($editions.Item($sourceServer.Edition.ToString().Split(" ")[0])))"
                            Write-Message -Level Verbose -Message "Destination Server Edition: $($destServer.Edition) (Weight: $($editions.Item($destServer.Edition.ToString().Split(" ")[0])))"

                            #Check for editions. If destination edition is lower than source edition and exists features in use
                            if (($editions.Item($destServer.Edition.ToString().Split(" ")[0]) -lt $editions.Item($sourceServer.Edition.ToString().Split(" ")[0])) -and (!([string]::IsNullOrEmpty($dbFeatures)))) {
                                [pscustomobject]@{
                                    SourceInstance      = $sourceServer.Name
                                    DestinationInstance = $destServer.Name
                                    SourceVersion       = $sourceVersion
                                    DestinationVersion  = $destVersion
                                    Database            = $dbName
                                    FeaturesInUse       = $dbFeatures
                                    IsMigratable        = $false
                                    Notes               = "$notesCannotMigrate There are features in use not available on destination instance."
                                }
                            }
                            #
                            else {
                                [pscustomobject]@{
                                    SourceInstance      = $sourceServer.Name
                                    DestinationInstance = $destServer.Name
                                    SourceVersion       = $sourceVersion
                                    DestinationVersion  = $destVersion
                                    Database            = $dbName
                                    FeaturesInUse       = $dbFeatures
                                    IsMigratable        = $true
                                    Notes               = $notesCanMigrate
                                }
                            }
                        }
                    } else {
                        Write-Message -Level Warning -Message "Database '$dbName' is offline or not accessible. Bring database online and re-run the command."
                    }
                }
            } else {
                #SQL Server 2005 or under
                Write-Message -Level Warning -Message "This validation will not be made on versions lower than SQL Server 2008 (v10)."
                Write-Message -Level Verbose -Message "Source server version: $($sourceServer.VersionMajor)."
                Write-Message -Level Verbose -Message "Destination server version: $($destServer.VersionMajor)."
            }
        } else {
            Write-Message -Level Output -Message "There are no databases to validate."
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Test-SqlMigrationConstraint
    }
}
tools\dbatools\functions\Test-DbaNetworkLatency.ps1
function Test-DbaNetworkLatency {
    <#
    .SYNOPSIS
        Tests how long a query takes to return from SQL Server

    .DESCRIPTION
        This function is intended to help measure SQL Server network latency by establishing a connection and executing a simple query. This is a better than a simple ping because it actually creates the connection to the SQL Server and measures the time required for only the entire routine, but the duration of the query as well how long it takes for the results to be returned.

        By default, this command will execute "SELECT TOP 100 * FROM INFORMATION_SCHEMA.TABLES" three times. It will then output how long the entire connection and command took, as well as how long *only* the execution of the command took.

        This allows you to see if the issue is with the connection or the SQL Server itself.

    .PARAMETER SqlInstance
        The SQL Server you want to run the test on.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Query
        Specifies the query to be executed. By default, "SELECT TOP 100 * FROM INFORMATION_SCHEMA.TABLES" will be executed on master. To execute in other databases, use fully qualified object names.

    .PARAMETER Count
        Specifies how many times the query should be executed. By default, the query is executed three times.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Performance, Network
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaNetworkLatency

    .EXAMPLE
        PS C:\> Test-DbaNetworkLatency -SqlInstance sqlserver2014a, sqlcluster

        Tests the round trip return of "SELECT TOP 100 * FROM INFORMATION_SCHEMA.TABLES" on sqlserver2014a and sqlcluster using Windows credentials.

    .EXAMPLE
        PS C:\> Test-DbaNetworkLatency -SqlInstance sqlserver2014a -SqlCredential $cred

        Tests the execution results return of "SELECT TOP 100 * FROM INFORMATION_SCHEMA.TABLES" on sqlserver2014a using SQL credentials.

    .EXAMPLE
        PS C:\> Test-DbaNetworkLatency -SqlInstance sqlserver2014a, sqlcluster, sqlserver -Query "select top 10 * from otherdb.dbo.table" -Count 10

        Tests the execution results return of "select top 10 * from otherdb.dbo.table" 10 times on sqlserver2014a, sqlcluster, and sqlserver using Windows credentials.

    #>
    [CmdletBinding()]
    [OutputType([System.Object[]])]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$Query = "select top 100 * from INFORMATION_SCHEMA.TABLES",
        [int]$Count = 3,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $start = [System.Diagnostics.Stopwatch]::StartNew()
                $currentCount = 0
                try {
                    $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
                } catch {
                    Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                }

                do {
                    if (++$currentCount -eq 1) {
                        $first = [System.Diagnostics.Stopwatch]::StartNew()
                    }
                    $null = $server.Query($query)
                    if ($currentCount -eq $count) {
                        $last = $first.Elapsed
                    }
                }
                while ($currentCount -lt $count)

                $end = $start.Elapsed
                $totalTime = $end.TotalMilliseconds
                $average = $totalTime / $count

                $totalWarm = $last.TotalMilliseconds
                if ($Count -eq 1) {
                    $averageWarm = $totalWarm
                } else {
                    $averageWarm = $totalWarm / $count
                }

                [PSCustomObject]@{
                    ComputerName     = $server.ComputerName
                    InstanceName     = $server.ServiceName
                    SqlInstance      = $server.DomainInstanceName
                    Count            = $count
                    Total            = [prettytimespan]::FromMilliseconds($totalTime)
                    Avg              = [prettytimespan]::FromMilliseconds($average)
                    ExecuteOnlyTotal = [prettytimespan]::FromMilliseconds($totalWarm)
                    ExecuteOnlyAvg   = [prettytimespan]::FromMilliseconds($averageWarm)
                    NetworkOnlyTotal = [prettytimespan]::FromMilliseconds($totalTime - $totalWarm)
                } | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, 'Count as ExecutionCount', Total, 'Avg as Average', ExecuteOnlyTotal, 'ExecuteOnlyAvg as ExecuteOnlyAverage', NetworkOnlyTotal #backwards compat
            } catch {
                Stop-Function -Message "Error occurred testing dba network latency: $_" -ErrorRecord $_ -Continue -Target $instance
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Test-SqlNetworkLatency
    }
}
tools\dbatools\functions\Test-DbaOptimizeForAdHoc.ps1
function Test-DbaOptimizeForAdHoc {
    <#
    .SYNOPSIS
        Displays information relating to SQL Server Optimize for AdHoc Workloads setting.  Works on SQL Server 2008-2016.

    .DESCRIPTION
        When this option is set, plan cache size is further reduced for single-use ad hoc OLTP workload.

        More info: https://msdn.microsoft.com/en-us/library/cc645587.aspx
        http://www.sqlservercentral.com/blogs/glennberry/2011/02/25/some-suggested-sql-server-2008-r2-instance-configuration-settings/

        These are just general recommendations for SQL Server and are a good starting point for setting the "optimize for ad-hoc workloads" option.

    .PARAMETER SqlInstance
        A collection of one or more SQL Server instance names to query.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Configure, SPConfigure
        Author: Brandon Abshire, netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaOptimizeForAdHoc

    .EXAMPLE
        PS C:\> Test-DbaOptimizeForAdHoc -SqlInstance sql2008, sqlserver2012

        Validates whether Optimize for AdHoc Workloads setting is enabled for servers sql2008 and sqlserver2012.

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $notesAdHocZero = "Recommended configuration is 1 (enabled)."
        $notesAsRecommended = "Configuration is already set as recommended."
        $recommendedValue = 1
    }
    process {

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential -MinimumVersion 10
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            #Get current configured value
            $optimizeAdHoc = $server.Configuration.OptimizeAdhocWorkloads.ConfigValue

            #Setting notes for optimize adhoc value
            if ($optimizeAdHoc -eq $recommendedValue) {
                $notes = $notesAsRecommended
            } else {
                $notes = $notesAdHocZero
            }

            [pscustomobject]@{
                ComputerName             = $server.ComputerName
                InstanceName             = $server.ServiceName
                SqlInstance              = $server.DomainInstanceName
                CurrentOptimizeAdHoc     = $optimizeAdHoc
                RecommendedOptimizeAdHoc = $recommendedValue
                Notes                    = $notes
            }
        }
    }
}
tools\dbatools\functions\Test-DbaPath.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Test-DbaPath {
    <#
    .SYNOPSIS
        Tests if file or directory exists from the perspective of the SQL Server service account.

    .DESCRIPTION
        Uses master.dbo.xp_fileexist to determine if a file or directory exists.

    .PARAMETER SqlInstance
        The SQL Server you want to run the test on.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Path
        The Path to test. This can be a file or directory

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Path, ServiceAccount
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaPath

    .EXAMPLE
        PS C:\> Test-DbaPath -SqlInstance sqlcluster -Path L:\MSAS12.MSSQLSERVER\OLAP

        Tests whether the service account running the "sqlcluster" SQL Server instance can access L:\MSAS12.MSSQLSERVER\OLAP. Logs into sqlcluster using Windows credentials.

    .EXAMPLE
        PS C:\> $credential = Get-Credential
        PS C:\> Test-DbaPath -SqlInstance sqlcluster -SqlCredential $credential -Path L:\MSAS12.MSSQLSERVER\OLAP

        Tests whether the service account running the "sqlcluster" SQL Server instance can access L:\MSAS12.MSSQLSERVER\OLAP. Logs into sqlcluster using SQL authentication.

    #>
    [CmdletBinding()]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseOutputTypeCorrectly", "", Justification = "PSSA Rule Ignored by BOH")]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Parameter(Mandatory)]
        [object]$Path,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Target $instance -Continue
            }
            $counter = [pscustomobject] @{ Value = 0 }
            $groupSize = 100
            $RawPath = $Path
            $Path = [string[]]$Path
            $groups = $Path | Group-Object -Property { [math]::Floor($counter.Value++ / $groupSize) }
            foreach ($g in $groups) {
                $PathsBatch = $g.Group
                $query = @()
                foreach ($p in $PathsBatch) {
                    $query += "EXEC master.dbo.xp_fileexist '$p'"
                }
                $sql = $query -join ';'
                $batchresult = $server.ConnectionContext.ExecuteWithResults($sql)
                if ($Path.Count -eq 1 -and $SqlInstance.Count -eq 1 -and (-not($RawPath -is [array]))) {
                    if ($batchresult.Tables.rows[0] -eq $true -or $batchresult.Tables.rows[1] -eq $true) {
                        return $true
                    } else {
                        return $false
                    }
                } else {
                    $i = 0
                    foreach ($r in $batchresult.tables.rows) {
                        $DoesPass = $r[0] -eq $true -or $r[1] -eq $true
                        [pscustomobject]@{
                            SqlInstance  = $server.Name
                            InstanceName = $server.ServiceName
                            ComputerName = $server.ComputerName
                            FilePath     = $PathsBatch[$i]
                            FileExists   = $DoesPass
                            IsContainer  = $r[1] -eq $true
                        }
                        $i += 1
                    }
                }
            }
        }

    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Test-SqlPath
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Test-DbaSqlPath
    }
}
tools\dbatools\functions\Test-DbaPowerPlan.ps1
function Test-DbaPowerPlan {
    <#
    .SYNOPSIS
        Checks the Power Plan settings for compliance with best practices, which recommend High Performance for SQL Server.

    .DESCRIPTION
        Checks the Power Plan settings on a computer against best practices recommendations. If one server is checked, only $true or $false is returned. If multiple servers are checked, each server's name and an isBestPractice field are returned.

        References:
        https://support.microsoft.com/en-us/kb/2207548
        http://www.sqlskills.com/blogs/glenn/windows-power-plan-effects-on-newer-intel-processors/

    .PARAMETER ComputerName
        The server(s) to check Power Plan settings on.

    .PARAMETER Credential
        Specifies a PSCredential object to use in authenticating to the server(s), instead of the current user account.

    .PARAMETER CustomPowerPlan
        If your organization uses a custom power plan that's considered best practice, specify it here.

    .PARAMETER Detailed
        Output all properties, will be deprecated in 1.0.0 release.

    .PARAMETER InputObject
        Enables piping from Get-DbaPowerPlan

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: PowerPlan
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaPowerPlan

    .EXAMPLE
        PS C:\> Test-DbaPowerPlan -ComputerName sqlserver2014a

        Checks the Power Plan settings for sqlserver2014a and indicates whether or not it complies with best practices.

    .EXAMPLE
        PS C:\> Test-DbaPowerPlan -ComputerName sqlserver2014a -CustomPowerPlan 'Maximum Performance'

        Checks the Power Plan settings for sqlserver2014a and indicates whether or not it is set to the custom plan "Maximum Performance".

       #>
    param (
        [parameter(ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlInstance")]
        [DbaInstance[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [string]$CustomPowerPlan,
        [parameter(ValueFromPipeline)]
        [pscustomobject]$InputObject,
        [switch]$Detailed,
        [switch]$EnableException
    )

    begin {
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter Detailed

        $bpPowerPlan = [PSCustomObject]@{
            InstanceID  = '8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c'
            ElementName = $null
        }
    }

    process {
        if (Test-Bound -ParameterName ComputerName) {
            $InputObject += Get-DbaPowerPlan -ComputerName $ComputerName -Credential $Credential
        }

        foreach ($powerPlan in $InputObject) {
            $computer = $powerPlan.ComputerName
            $Credential = $powerPlan.Credential

            $server = Resolve-DbaNetworkName -ComputerName $computer -Credential $Credential

            $computerResolved = $server.FullComputerName

            if (-not $computerResolved) {
                Stop-Function -Message "Couldn't resolve hostname. Skipping." -Continue
            }

            $splatDbaCmObject = @{
                ComputerName    = $computerResolved
                EnableException = $true
            }

            if (Test-Bound "Credential") {
                $splatDbaCmObject["Credential"] = $Credential
            }

            Write-Message -Level Verbose -Message "Getting Power Plan information from $computer."

            try {
                $powerPlans = Get-DbaCmObject @splatDbaCmObject -ClassName Win32_PowerPlan -Namespace "root\cimv2\power" | Select-Object ElementName, InstanceId, IsActive
            } catch {
                if ($_.Exception -match "namespace") {
                    Stop-Function -Message "Can't get Power Plan Info for $computer. Unsupported operating system." -Continue -ErrorRecord $_ -Target $computer
                } else {
                    Stop-Function -Message "Can't get Power Plan Info for $computer. Check logs for more details." -Continue -ErrorRecord $_ -Target $computer
                }
            }

            $powerPlan = $powerPlans | Where-Object IsActive -eq 'True' | Select-Object ElementName, InstanceID
            $powerPlan.InstanceID = $powerPlan.InstanceID.Split('{')[1].Split('}')[0]

            if ($null -eq $powerPlan.InstanceID) {
                $powerPlan.ElementName = "Unknown"
            }
            if ($CustomPowerPlan) {
                $bpPowerPlan.ElementName = $CustomPowerPlan
                $bpPowerPlan.InstanceID = $($powerPlans | Where-Object {
                        $_.ElementName -eq $CustomPowerPlan
                    }).InstanceID
            } else {
                $bpPowerPlan.ElementName = $($powerPlans | Where-Object {
                        $_.InstanceID.Split('{')[1].Split('}')[0] -eq $bpPowerPlan.InstanceID
                    }).ElementName
                if ($null -eq $bpPowerplan.ElementName) {
                    $bpPowerPlan.ElementName = "You do not have the high performance plan installed on this machine."
                }
            }

            Write-Message -Level Verbose -Message "Recommended GUID is $($bpPowerPlan.InstanceID) and you have $($powerPlan.InstanceID)."

            if ($null -eq $powerPlan.InstanceID) {
                $powerPlan.ElementName = "Unknown"
            }

            if ($powerPlan.InstanceID -eq $bpPowerPlan.InstanceID) {
                $isBestPractice = $true
            } else {
                $isBestPractice = $false
            }

            [PSCustomObject]@{
                ComputerName         = $computer
                ActivePowerPlan      = $powerPlan.ElementName
                RecommendedPowerPlan = $bpPowerPlan.ElementName
                isBestPractice       = $isBestPractice
                Credential           = $Credential
            } | Select-DefaultView -ExcludeProperty Credential
        }
    }
}
tools\dbatools\functions\Test-DbaRepLatency.ps1
function Test-DbaRepLatency {
    <#
    .SYNOPSIS
        Displays replication latency for all transactional publications for a server or database.

    .DESCRIPTION
        Creates tracer tokens to determine latency between the publisher/distributor and the distributor/subscriber
        for all transactional publications for a server, database, or publication.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER Database
        The database(s) to process. If unspecified, all databases will be processed.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER PublicationName
        The publication(s) to process. If unspecified, all publications will be processed.

    .PARAMETER TimeToLive
        How long, in seconds, to wait for a tracer token to complete its journey from the publisher to the subscriber.
        If unspecified, all tracer tokens will take as long as they need to process results.

    .PARAMETER RetainToken
        Retains the tracer tokens created for each publication. If unspecified, all tracer tokens created will be discarded.

    .PARAMETER DisplayTokenHistory
        Displays all tracer tokens in each publication. If unspecified, the current tracer token created will be only token displayed.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Replication
        Author: Colin Douglas

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaRepLatency

    .EXAMPLE
        PS C:\> Test-DbaRepLatency -SqlInstance sql2008, sqlserver2012

        Return replication latency for all transactional publications for servers sql2008 and sqlserver2012.

    .EXAMPLE
        PS C:\> Test-DbaRepLatency -SqlInstance sql2008 -Database TestDB

        Return replication latency for all transactional publications on server sql2008 for only the TestDB database

    .EXAMPLE
        PS C:\> Test-DbaRepLatency -SqlInstance sql2008 -Database TestDB -PublicationName TestDB_Pub

        Return replication latency for the TestDB_Pub publication for the TestDB database located on the server sql2008.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]] $SqlInstance, #Publisher
        [object[]]$Database,
        [PSCredential]$SqlCredential,
        [object[]]$PublicationName,
        [int]$TimeToLive,
        [switch]$RetainToken,
        [switch]$DisplayTokenHistory,
        [switch]$EnableException
    )

    process {

        foreach ($instance in $SqlInstance) {


            # Connect to the publisher
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $publicationNames = Get-DbaRepPublication -SqlInstance $server -Database $Database -SqlCredential $SqlCredentials -PublicationType "Transactional"

            if ($PublicationName) {
                $publicationNames = $publicationNames | Where-Object PublicationName -in $PublicationName
            }


            foreach ($publication in $publicationNames) {

                # Create an instance of TransPublication
                $transPub = New-Object Microsoft.SqlServer.Replication.TransPublication

                $transPub.Name = $publication.PublicationName
                $transPub.DatabaseName = $publication.Database

                # Set the Name and DatabaseName properties for the publication, and set the ConnectionContext property to the connection created in step 1.
                $transPub.ConnectionContext = $server.ConnectionContext.SqlConnectionObject

                # Call the LoadProperties method to get the properties of the object. If this method returns false, either the publication properties in Step 3 were defined incorrectly or the publication does not exist.
                if (!$transPub.LoadProperties()) {
                    Stop-Function -Message "LoadProperties() failed. The publication does not exist." -Continue
                }

                # Call the PostTracerToken method. This method inserts a tracer token into the publication's Transaction log.
                $transPub.PostTracerToken() | Out-Null
            }

            ##################################################################################
            ### Determine Latency and validate connections for a transactional publication ###
`           ##################################################################################

            $repServer = New-Object Microsoft.SqlServer.Replication.ReplicationServer

            # Set the Name and DatabaseName properties for the Replication Server, and set the ConnectionContext property to the connection created in step 1.
            $repServer.ConnectionContext = $server.ConnectionContext.SqlConnectionObject

            $distributionServer = $repServer.DistributionServer
            $distributionDatabase = $repServer.DistributionDatabase

            # Step 1: Connect to the distributor

            try {
                $distServer = Connect-SqlInstance -SqlInstance $DistributionServer -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $DistributionServer -Continue
            }

            foreach ($publication in $publicationNames) {

                $pubMon = New-Object Microsoft.SqlServer.Replication.PublicationMonitor

                $pubMon.Name = $publication.PublicationName
                $pubMon.DistributionDBName = $distributionDatabase
                $pubMon.PublisherName = $publication.Server
                $pubMon.PublicationDBName = $publication.Database

                $pubMon.ConnectionContext = $distServer.ConnectionContext.SqlConnectionObject;


                # Call the LoadProperties method to get the properties of the object. If this method returns false, either the publication monitor properties in Step 3 were defined incorrectly or the publication does not exist.
                if (!$pubMon.LoadProperties()) {
                    Stop-Function -Message "LoadProperties() failed. The publication does not exist." -Continue
                }

                $tokenList = $pubMon.EnumTracerTokens()

                if (!$DisplayTokenHistory) {
                    $tokenList = $tokenList[0]
                }


                foreach ($token in $tokenList) {

                    $tracerTokenId = $token.TracerTokenId

                    $tokenInfo = $pubMon.EnumTracerTokenHistory($tracerTokenId)

                    $timer = 0

                    $continue = $true

                    while (($tokenInfo.Tables[0].Rows[0].subscriber_latency -eq [System.DBNull]::Value) -and $continue ) {
                        if ($TimeToLive -and ($timer -gt $TimeToLive)) {
                            $continue = $false
                            Stop-Function -Message "TimeToLive has been reached for token: $tracerTokenId" -Continue
                        }

                        Start-Sleep -Seconds 1
                        $timer += 1
                        $tokenInfo = $PubMon.EnumTracerTokenHistory($tracerTokenId)
                    }


                    foreach ($info in $tokenInfo.Tables[0].Rows) {

                        $totalLatency = if (($info.distributor_latency -eq [System.DBNull]::Value) -or ($info.subscriber_latency -eq [System.DBNull]::Value)) {
                            [System.DBNull]::Value
                        } else {
                            ($info.distributor_latency + $info.subscriber_latency)
                        }

                        [PSCustomObject]@{
                            ComputerName                   = $server.ComputerName
                            InstanceName                   = $server.InstanceName
                            SqlInstance                    = $server.SqlInstance
                            TokenID                        = $tracerTokenId
                            TokenCreateDate                = $token.PublisherCommitTime
                            PublicationServer              = $publication.Server
                            PublicationDB                  = $publication.Database
                            PublicationName                = $publication.PublicationName
                            PublicationType                = $publication.PublicationType
                            DistributionServer             = $distributionServer
                            DistributionDB                 = $distributionDatabase
                            SubscriberServer               = $info.subscriber
                            SubscriberDB                   = $info.subscriber_db
                            PublisherToDistributorLatency  = $info.distributor_latency
                            DistributorToSubscriberLatency = $info.subscriber_latency
                            TotalLatency                   = $totalLatency
                        } | Select-DefaultView -ExcludeProperty PublicationType


                        if (!$RetainToken) {

                            $pubMon.CleanUpTracerTokenHistory($tracerTokenId)

                        }

                    }
                }
            }
        }
    }
}
tools\dbatools\functions\Test-DbaServerName.ps1
function Test-DbaServerName {
    <#
    .SYNOPSIS
        Tests to see if it's possible to easily rename the server at the SQL Server instance level, or if it even needs to be changed.

    .DESCRIPTION
        When a SQL Server's host OS is renamed, the SQL Server should be as well. This helps with Availability Groups and Kerberos.

        This command helps determine if your OS and SQL Server names match, and whether a rename is required.

        It then checks conditions that would prevent a rename, such as database mirroring and replication.

        https://www.mssqltips.com/sqlservertip/2525/steps-to-change-the-server-name-for-a-sql-server-machine/

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Detailed
        Output all properties, will be deprecated in 1.0.0 release.

    .PARAMETER ExcludeSsrs
        If this switch is enabled, checking for SQL Server Reporting Services will be skipped.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: SPN, ServerName
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaServerName

    .EXAMPLE
        PS C:\> Test-DbaServerName -SqlInstance sqlserver2014a

        Returns ServerInstanceName, SqlServerName, IsEqual and RenameRequired for sqlserver2014a.

    .EXAMPLE
        PS C:\> Test-DbaServerName -SqlInstance sqlserver2014a, sql2016

        Returns ServerInstanceName, SqlServerName, IsEqual and RenameRequired for sqlserver2014a and sql2016.

    .EXAMPLE
        PS C:\> Test-DbaServerName -SqlInstance sqlserver2014a, sql2016 -ExcludeSsrs

        Returns ServerInstanceName, SqlServerName, IsEqual and RenameRequired for sqlserver2014a and sql2016, but skips validating if SSRS is installed on both instances.

    .EXAMPLE
        PS C:\> Test-DbaServerName -SqlInstance sqlserver2014a, sql2016 | Select-Object *

        Returns ServerInstanceName, SqlServerName, IsEqual and RenameRequired for sqlserver2014a and sql2016.
        If a Rename is required, it will also show Updatable, and Reasons if the server name is not updatable.

    #>
    [CmdletBinding()]
    [OutputType([System.Collections.ArrayList])]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$Detailed,
        [Alias("NoWarning")]
        [switch]$ExcludeSsrs,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter Detailed
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter NoWarning
    }
    process {

        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($server.IsClustered) {
                Write-Message -Level Warning -Message "$instance is a cluster. Renaming clusters is not supported by Microsoft."
            }

            $sqlInstanceName = $server.Query("SELECT @@servername AS ServerName").ServerName
            $instance = $server.InstanceName

            if ($instance.Length -eq 0) {
                $serverInstanceName = $server.NetName
                $instance = "MSSQLSERVER"
            } else {
                $netname = $server.NetName
                $serverInstanceName = "$netname\$instance"
            }

            $serverInfo = [PSCustomObject]@{
                ComputerName   = $server.NetName
                ServerName     = $sqlInstanceName
                InstanceName   = $server.ServiceName
                SqlInstance    = $server.DomainInstanceName
                RenameRequired = $serverInstanceName -ne $sqlInstanceName
                Updatable      = "N/A"
                Warnings       = $null
                Blockers       = $null
            }

            $reasons = @()
            $ssrsService = "SQL Server Reporting Services ($instance)"

            Write-Message -Level Verbose -Message "Checking for $serverName on $netBiosName"
            $rs = $null
            if ($SkipSsrs -eq $false -or $NoWarning -eq $false) {
                try {
                    $rs = Get-DbaService -ComputerName $instance.ComputerName -InstanceName $server.ServiceName -Type SSRS -EnableException -WarningAction Stop
                } catch {
                    Write-Message -Level Warning -Message "Unable to pull information on $ssrsService." -ErrorRecord $_ -Target $instance
                }
            }

            if ($null -ne $rs -or $rs.Count -gt 0) {
                if ($rs.State -eq 'Running') {
                    $rstext = "$ssrsService must be stopped and updated."
                } else {
                    $rstext = "$ssrsService exists. When it is started again, it must be updated."
                }
                $serverInfo.Warnings = $rstext
            } else {
                $serverInfo.Warnings = "N/A"
            }

            # check for mirroring
            $mirroredDb = $server.Databases | Where-Object { $_.IsMirroringEnabled -eq $true }

            Write-Message -Level Debug -Message "Found the following mirrored dbs: $($mirroredDb.Name)"

            if ($mirroredDb.Length -gt 0) {
                $dbs = $mirroredDb.Name -join ", "
                $reasons += "Databases are being mirrored: $dbs"
            }

            # check for replication
            $sql = "SELECT name FROM sys.databases WHERE is_published = 1 OR is_subscribed = 1 OR is_distributor = 1"
            Write-Message -Level Debug -Message "SQL Statement: $sql"
            $replicatedDb = $server.Query($sql)

            if ($replicatedDb.Count -gt 0) {
                $dbs = $replicatedDb.Name -join ", "
                $reasons += "Database(s) are involved in replication: $dbs"
            }

            # check for even more replication
            $sql = "SELECT srl.remote_name as RemoteLoginName FROM sys.remote_logins srl JOIN sys.sysservers sss ON srl.server_id = sss.srvid"
            Write-Message -Level Debug -Message "SQL Statement: $sql"
            $results = $server.Query($sql)

            if ($results.RemoteLoginName.Count -gt 0) {
                $remoteLogins = $results.RemoteLoginName -join ", "
                $reasons += "Remote logins still exist: $remoteLogins"
            }

            if ($reasons.Length -gt 0) {
                $serverInfo.Updatable = $false
                $serverInfo.Blockers = $reasons
            } else {
                $serverInfo.Updatable = $true
                $serverInfo.Blockers = "N/A"
            }

            $serverInfo | Select-DefaultView -ExcludeProperty InstanceName, SqlInstance
        }
    }
}
tools\dbatools\functions\Test-DbaSpn.ps1
#ValidationTags#FlowControl,Pipeline#
function Test-DbaSpn {
    <#
    .SYNOPSIS
        Test-DbaSpn will determine what SPNs *should* be set for a given server (and any instances of SQL running on it) and return
        whether the SPNs are set or not.

    .DESCRIPTION
        This function is designed to take in a server name(s) and attempt to determine required SPNs. It was initially written to mimic the (previously) broken functionality of the Microsoft Kerberos Configuration manager and SQL Server 2016.

        - For any instances with TCP/IP enabled, the script will determine which port(s) the instances are listening on and generate the required SPNs.
        - For named instances NOT using dynamic ports, the script will generate a port-based SPN for those instances as well.
        - At a minimum, the script will test a base, port-less SPN for each instance discovered.

        Once the required SPNs are generated, the script will connect to Active Directory and search for any of the SPNs (if any) that are already set. The function will return a custom object(s) that contains the server name checked, the instance name discovered, the account the service is running under, and what the "required" SPN should be. It will also return a boolean property indicating if the SPN is set in Active Directory or not.

    .PARAMETER ComputerName
        The computer you want to discover any SQL Server instances on. This parameter is required.

    .PARAMETER Credential
        The credential you want to use to connect to the remote server and active directory.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: SPN
        Author: Drew Furgiuele (@pittfurg), http://www.port1433.com | niphlod

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaSpn

    .EXAMPLE
        Test-DbaSpn -ComputerName SQLSERVERA -Credential ad\sqldba

        Connects to a computer (SQLSERVERA) and queries WMI for all SQL instances and return "required" SPNs. It will then take each SPN it generates
        and query Active Directory to make sure the SPNs are set.

    .EXAMPLE
        Test-DbaSpn -ComputerName SQLSERVERA,SQLSERVERB -Credential ad\sqldba

        Connects to multiple computers (SQLSERVERA, SQLSERVERB) and queries WMI for all SQL instances and return "required" SPNs.
        It will then take each SPN it generates and query Active Directory to make sure the SPNs are set.

    .EXAMPLE
        Test-DbaSpn -ComputerName SQLSERVERC -Credential ad\sqldba

        Connects to a computer (SQLSERVERC) on a specified and queries WMI for all SQL instances and return "required" SPNs.
        It will then take each SPN it generates and query Active Directory to make sure the SPNs are set. Note that the credential you pass must have be a valid login with appropriate rights on the domain

    #>
    [cmdletbinding()]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseOutputTypeCorrectly", "", Justification = "PSSA Rule Ignored by BOH")]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [DbaInstance[]]$ComputerName,
        [PSCredential]$Credential,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        # spare the cmdlet to search for the same account over and over
        $resultCache = @{}
    }
    process {
        foreach ($computer in $ComputerName) {
            try {
                $resolved = Resolve-DbaNetworkName -ComputerName $computer.ComputerName -Credential $Credential -ErrorAction Stop
            } catch {
                $resolved = Resolve-DbaNetworkName -ComputerName $computer.ComputerName -Turbo
            }

            if ($null -eq $resolved.IPAddress) {
                Write-Message -Level Warning -Message "Cannot resolve IP address, moving on."
                continue
            }

            $hostEntry = $resolved.FullComputerName

            Write-Message -Message "Resolved ComputerName to FQDN: $hostEntry" -Level Verbose

            $Scriptblock = {

                function Convert-SqlVersion {
                    [cmdletbinding()]
                    param (
                        [version]$version
                    )

                    switch ($version.Major) {
                        9 { "SQL Server 2005" }
                        10 {
                            if ($version.Minor -eq 0) {
                                "SQL Server 2008"
                            } else {
                                "SQL Server 2008 R2"
                            }
                        }
                        11 { "SQL Server 2012" }
                        12 { "SQL Server 2014" }
                        13 { "SQL Server 2016" }
                        14 { "SQL Server 2017" }
                        default { $version }
                    }
                }

                $spns = @()
                $servereName = $args[0]
                $hostEntry = $args[1]
                $instanceName = $args[2]
                $instanceCount = $wmi.ServerInstances.Count

                <# DO NOT use Write-Message as this is inside of a script block #>
                Write-Verbose "Found $instanceCount instances"

                foreach ($instance in $wmi.ServerInstances) {
                    $spn = [pscustomobject] @{
                        ComputerName           = $servereName
                        InstanceName           = $instanceName
                        #SKUNAME
                        SqlProduct             = $null
                        InstanceServiceAccount = $null
                        RequiredSPN            = $null
                        IsSet                  = $false
                        Cluster                = $false
                        TcpEnabled             = $false
                        Port                   = $null
                        DynamicPort            = $false
                        Warning                = "None"
                        Error                  = "None"
                        # for piping
                        Credential             = $Credential
                    }

                    $spn.InstanceName = $instance.Name
                    $instanceName = $spn.InstanceName

                    <# DO NOT use Write-Message as this is inside of a script block #>
                    Write-Verbose "Parsing $instanceName"

                    $services = $wmi.Services | Where-Object DisplayName -EQ "SQL Server ($instanceName)"
                    $spn.InstanceServiceAccount = $services.ServiceAccount
                    $spn.Cluster = ($services.advancedproperties | Where-Object Name -EQ 'Clustered').Value

                    if ($spn.Cluster) {
                        $hostEntry = ($services.advancedproperties | Where-Object Name -EQ 'VSNAME').Value.ToLower()
                        <# DO NOT use Write-Message as this is inside of a script block #>
                        Write-Verbose "Found cluster $hostEntry"
                        $hostEntry = ([System.Net.Dns]::GetHostEntry($hostEntry)).HostName
                        $spn.ComputerName = $hostEntry
                    }

                    $rawVersion = [version]($services.AdvancedProperties | Where-Object Name -EQ 'VERSION').Value

                    $version = Convert-SqlVersion $rawVersion
                    $skuName = ($services.AdvancedProperties | Where-Object Name -EQ 'SKUNAME').Value

                    $spn.SqlProduct = "$version $skuName"

                    #is tcp enabled on this instance? If not, we don't need an spn, son
                    if ((($instance.ServerProtocols | Where-Object { $_.Displayname -eq "TCP/IP" }).ProtocolProperties | Where-Object { $_.Name -eq "Enabled" }).Value -eq $true) {
                        <# DO NOT use Write-Message as this is inside of a script block #>
                        Write-Verbose "TCP is enabled, gathering SPN requirements"
                        $spn.TcpEnabled = $true
                        #Each instance has a default SPN of MSSQLSvc\<fqdn> or MSSSQLSvc\<fqdn>:Instance
                        if ($instance.Name -eq "MSSQLSERVER") {
                            $spn.RequiredSPN = "MSSQLSvc/$hostEntry"
                        } else {
                            $spn.RequiredSPN = "MSSQLSvc/" + $hostEntry + ":" + $instance.Name
                        }
                    }

                    $spns += $spn
                }
                # Now, for each spn, do we need a port set? Only if TCP is enabled and NOT DYNAMIC!
                foreach ($spn in $spns) {
                    $ports = @()

                    $ips = (($wmi.ServerInstances | Where-Object { $_.Name -eq $spn.InstanceName }).ServerProtocols | Where-Object { $_.DisplayName -eq "TCP/IP" -and $_.IsEnabled -eq "True" }).IpAddresses
                    $ipAllPort = $null
                    foreach ($ip in $ips) {
                        if ($ip.Name -eq "IPAll") {
                            $ipAllPort = ($ip.IPAddressProperties | Where-Object { $_.Name -eq "TCPPort" }).Value
                            if (($ip.IpAddressProperties | Where-Object { $_.Name -eq "TcpDynamicPorts" }).Value -ne "") {
                                $ipAllPort = ($ip.IPAddressProperties | Where-Object { $_.Name -eq "TcpDynamicPorts" }).Value + "d"
                            }
                        } else {
                            $enabled = ($ip.IPAddressProperties | Where-Object { $_.Name -eq "Enabled" }).Value
                            $active = ($ip.IPAddressProperties | Where-Object { $_.Name -eq "Active" }).Value
                            $tcpDynamicPorts = ($ip.IPAddressProperties | Where-Object { $_.Name -eq "TcpDynamicPorts" }).Value
                            if ($enabled -and $active -and $tcpDynamicPorts -eq "") {
                                $ports += ($ip.IPAddressProperties | Where-Object { $_.Name -eq "TCPPort" }).Value
                            } elseif ($enabled -and $active -and $tcpDynamicPorts -ne "") {
                                $ports += $ipAllPort + "d"
                            }
                        }
                    }
                    if ($ipAllPort -ne "") {
                        #IPAll overrides any set ports. Not sure why that's the way it is?
                        $ports = $ipAllPort
                    }

                    $ports = $ports | Select-Object -Unique
                    foreach ($port in $ports) {
                        $newspn = $spn.PSObject.Copy()
                        if ($port -like "*d") {
                            $newspn.Port = ($port.replace("d", ""))
                            $newspn.RequiredSPN = $newspn.RequiredSPN.Replace($newSPN.InstanceName, $newspn.Port)
                            $newspn.DynamicPort = $true
                            $newspn.Warning = "Dynamic port is enabled"
                        } else {
                            #If this is a named instance, replace the instance name with a port number (for non-dynamic ported named instances)
                            $newspn.Port = $port
                            $newspn.DynamicPort = $false

                            if ($newspn.InstanceName -eq "MSSQLSERVER") {
                                $newspn.RequiredSPN = $newspn.RequiredSPN + ":" + $port
                            } else {
                                $newspn.RequiredSPN = $newspn.RequiredSPN.Replace($newSPN.InstanceName, $newspn.Port)
                            }
                        }
                        $spns += $newspn
                    }
                }
                $spns
            }


            try {
                $spns = Invoke-ManagedComputerCommand -ComputerName $hostEntry -ScriptBlock $Scriptblock -ArgumentList $resolved.FullComputerName, $hostEntry, $computer.InstanceName -Credential $Credential -ErrorAction Stop
            } catch {
                Stop-Function -Message "Couldn't connect to $computer" -ErrorRecord $_ -Continue
            }

            #Now query AD for each required SPN
            foreach ($spn in $spns) {
                $searchfor = 'User'
                if ($spn.InstanceServiceAccount -eq 'LocalSystem' -or $spn.InstanceServiceAccount -like 'NT SERVICE\*') {
                    Write-Message -Level Verbose -Message "Virtual account detected, changing target registration to computername"
                    $spn.InstanceServiceAccount = "$($resolved.Domain)\$($resolved.ComputerName)$"
                    $searchfor = 'Computer'
                } elseif ($spn.InstanceServiceAccount -like '*\*$') {
                    Write-Message -Level Verbose -Message "Managed Service Account detected"
                    $searchfor = 'Computer'
                }

                $serviceAccount = $spn.InstanceServiceAccount
                # spare the cmdlet to search for the same account over and over
                if ($spn.InstanceServiceAccount -notin $resultCache.Keys) {
                    Write-Message -Message "Searching for $serviceAccount" -Level Verbose
                    try {
                        $result = Get-DbaADObject -ADObject $serviceAccount -Type $searchfor -Credential $Credential -EnableException
                        $resultCache[$spn.InstanceServiceAccount] = $result
                    } catch {
                        if (![System.String]::IsNullOrEmpty($spn.InstanceServiceAccount)) {
                            Write-Message -Message "AD lookup failure. This may be because the domain cannot be resolved for the SQL Server service account ($serviceAccount)." -Level Warning
                        }
                    }
                } else {
                    $result = $resultCache[$spn.InstanceServiceAccount]
                }
                if ($result.Count -gt 0) {
                    try {
                        $results = $result.GetUnderlyingObject()
                        if ($results.Properties.servicePrincipalName -contains $spn.RequiredSPN) {
                            $spn.IsSet = $true
                        }
                    } catch {
                        Write-Message -Message "The SQL Service account ($serviceAccount) has been found, but you don't have enough permission to inspect its SPNs" -Level Warning
                        continue
                    }
                } else {
                    Write-Message -Level Warning -Message "SQL Service account not found. Results may not be accurate."
                    $spn
                    continue
                }
                if (!$spn.IsSet -and $spn.TcpEnabled) {
                    $spn.Error = "SPN missing"
                }

                $spn | Select-DefaultView -ExcludeProperty Credential, DomainName
            }
        }
    }
}
tools\dbatools\functions\Test-DbaTempDbConfig.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Test-DbaTempdbConfig {
    <#
    .SYNOPSIS
        Evaluates tempdb against several rules to match best practices.

    .DESCRIPTION
        Evaluates tempdb against a set of rules to match best practices. The rules are:

        * TF 1118 enabled - Is Trace Flag 1118 enabled (See KB328551).
        * File Count - Does the count of data files in tempdb match the number of logical cores, up to 8?
        * File Growth - Are any files set to have percentage growth? Best practice is all files have an explicit growth value.
        * File Location - Is tempdb located on the C:\? Best practice says to locate it elsewhere.
        * File MaxSize Set (optional) - Do any files have a max size value? Max size could cause tempdb problems if it isn't allowed to grow.
        * Data File Size Equal - Are the sizes of all the tempdb data files the same?

        Other rules can be added at a future date.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. SQL Server 2005 and higher are supported.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Detailed
        Output all properties, will be depreciated in 1.0.0 release.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: tempdb, configuration
        Author: Michael Fal (@Mike_Fal), http://mikefal.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Based on Amit Bannerjee's (@banerjeeamit) Get-TempDB function (https://github.com/amitmsft/SqlOnAzureVM/blob/master/Get-TempdbFiles.ps1)

    .LINK
        https://dbatools.io/Test-DbaTempdbConfig

    .EXAMPLE
        PS C:\> Test-DbaTempdbConfig -SqlInstance localhost

        Checks tempdb on the localhost machine.

    .EXAMPLE
        PS C:\> Test-DbaTempdbConfig -SqlInstance localhost | Select-Object *

        Checks tempdb on the localhost machine. All rest results are shown.

    .EXAMPLE
        PS C:\> Get-DbaCmsRegServer -SqlInstance sqlserver2014a | Test-DbaTempdbConfig | Select-Object * | Out-GridView

        Checks tempdb configuration for a group of servers from SQL Server Central Management Server (CMS). Output includes all columns. Send output to GridView.
    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$Detailed,
        [switch]$EnableException
    )
    begin {
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter Detailed
    }
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            # removed previous assumption that 2016+ will have it enabled
            $tfCheck = $server.Databases['tempdb'].Query("DBCC TRACEON (3604);DBCC TRACESTATUS(-1)")
            $current = ($tfCheck.TraceFlag -join ',').Contains('1118')

            [PSCustomObject]@{
                ComputerName   = $server.ComputerName
                InstanceName   = $server.ServiceName
                SqlInstance    = $server.DomainInstanceName
                Rule           = 'TF 1118 Enabled'
                Recommended    = $true
                CurrentSetting = $current
                IsBestPractice = $current -eq $true
                Notes          = 'KB328551 describes how TF 1118 can benefit performance. SQL Server 2016 has this functionality enabled by default.'
            }

            Write-Message -Level Verbose -Message "TF 1118 evaluated"

            #get files and log files
            $tempdbFiles = Get-DbaDbFile -SqlInstance $server -Database tempdb
            [array]$dataFiles = $tempdbFiles | Where-Object Type -ne 1
            $logFiles = $tempdbFiles | Where-Object Type -eq 1
            Write-Message -Level Verbose -Message "TempDB file objects gathered"

            [PSCustomObject]@{
                ComputerName   = $server.ComputerName
                InstanceName   = $server.ServiceName
                SqlInstance    = $server.DomainInstanceName
                Rule           = 'File Count'
                Recommended    = [Math]::Min(8, $server.Processors)
                CurrentSetting = $dataFiles.Count
                IsBestPractice = $dataFiles.Count -eq [Math]::Min(8, $server.Processors)
                Notes          = 'Microsoft recommends that the number of tempdb data files is equal to the number of logical cores up to 8.'
            }

            Write-Message -Level Verbose -Message "File counts evaluated."

            #test file growth
            $percData = $dataFiles | Where-Object GrowthType -ne 'KB' | Measure-Object
            $percLog = $logFiles | Where-Object GrowthType -ne 'KB' | Measure-Object

            $totalCount = $percData.Count + $percLog.Count
            if ($totalCount -gt 0) {
                $totalCount = $true
            } else {
                $totalCount = $false
            }

            [PSCustomObject]@{
                ComputerName   = $server.ComputerName
                InstanceName   = $server.ServiceName
                SqlInstance    = $server.DomainInstanceName
                Rule           = 'File Growth in Percent'
                Recommended    = $false
                CurrentSetting = $totalCount
                IsBestPractice = $totalCount -eq $false
                Notes          = 'Set file growth to explicit values, not by percent.'
            }

            Write-Message -Level Verbose -Message "File growth settings evaluated."
            #test file Location

            $cdata = ($dataFiles | Where-Object PhysicalName -like 'C:*' | Measure-Object).Count + ($logFiles | Where-Object PhysicalName -like 'C:*' | Measure-Object).Count
            if ($cdata -gt 0) {
                $cdata = $true
            } else {
                $cdata = $false
            }

            [PSCustomObject]@{
                ComputerName   = $server.ComputerName
                InstanceName   = $server.ServiceName
                SqlInstance    = $server.DomainInstanceName
                Rule           = 'File Location'
                Recommended    = $false
                CurrentSetting = $cdata
                IsBestPractice = $cdata -eq $false
                Notes          = "Do not place your tempdb files on C:\."
            }

            Write-Message -Level Verbose -Message "File locations evaluated."

            #Test growth limits
            $growthLimits = ($dataFiles | Where-Object MaxSize -gt 0 | Measure-Object).Count + ($logFiles | Where-Object MaxSize -gt 0 | Measure-Object).Count
            if ($growthLimits -gt 0) {
                $growthLimits = $true
            } else {
                $growthLimits = $false
            }

            [PSCustomObject]@{
                ComputerName   = $server.ComputerName
                InstanceName   = $server.ServiceName
                SqlInstance    = $server.DomainInstanceName
                Rule           = 'File MaxSize Set'
                Recommended    = $false
                CurrentSetting = $growthLimits
                IsBestPractice = $growthLimits -eq $false
                Notes          = "Consider setting your tempdb files to unlimited growth."
            }

            Write-Message -Level Verbose -Message "MaxSize values evaluated."

            #Test Data File Size Equal
            $distinctCountSizeDataFiles = ($dataFiles | Group-Object -Property Size | Measure-Object).Count

            if ($distinctCountSizeDataFiles -eq 1) {
                $equalSizeDataFiles = $true
            } else {
                $equalSizeDataFiles = $false
            }

            $value = [PSCustomObject]@{
                ComputerName   = $server.ComputerName
                InstanceName   = $server.ServiceName
                SqlInstance    = $server.DomainInstanceName
                Rule           = 'Data File Size Equal'
                Recommended    = $true
                CurrentSetting = $equalSizeDataFiles
                IsBestPractice = $equalSizeDataFiles -eq $true
                Notes          = "Consider creating equally sized data files."
            }
            Write-Message -Level Verbose -Message "Data File Size Equal evaluated."
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Test-SqlTempDbConfiguration
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Test-DbaTempDbConfiguration
    }
}
tools\dbatools\functions\Test-DbaWindowsLogin.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Test-DbaWindowsLogin {
    <#
    .SYNOPSIS
        Test-DbaWindowsLogin finds any logins on SQL instance that are AD logins with either disabled AD user accounts or ones that no longer exist

    .DESCRIPTION
        The purpose of this function is to find SQL Server logins that are used by active directory users that are either disabled or removed from the domain. It allows you to keep your logins accurate and up to date by removing accounts that are no longer needed.

    .PARAMETER SqlInstance
        The SQL Server instance you're checking logins on. You must have sysadmin access and server version must be SQL Server version 2000 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Login
        Specifies a list of logins to include in the results. Options for this list are auto-populated from the server.

    .PARAMETER ExcludeLogin
        Specifies a list of logins to exclude from the results. Options for this list are auto-populated from the server.

    .PARAMETER FilterBy
        Specifies the object types to return. By default, both Logins and Groups are returned. Valid options for this parameter are 'GroupsOnly' and 'LoginsOnly'.

    .PARAMETER IgnoreDomains
        Specifies a list of Active Directory domains to ignore. By default, all domains in the forest as well as all trusted domains are traversed.

    .PARAMETER Detailed
        Output all properties, will be depreciated in 1.0.0 release.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Login, Security
        Author: Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/ | Chrissy LeMaire (@cl)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Test-DbaWindowsLogin

    .EXAMPLE
        PS C:\> Test-DbaWindowsLogin -SqlInstance Dev01

        Tests all logins in the current Active Directory domain that are either disabled or do not exist on the SQL Server instance Dev01

    .EXAMPLE
        PS C:\> Test-DbaWindowsLogin -SqlInstance Dev01 -FilterBy GroupsOnly | Select-Object -Property *

        Tests all Active Directory groups that have logins on Dev01, and shows all information for those logins

    .EXAMPLE
        PS C:\> Test-DbaWindowsLogin -SqlInstance Dev01 -IgnoreDomains testdomain

        Tests all Domain logins excluding any that are from the testdomain

    #>
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer", "SqlServers")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Login,
        [object[]]$ExcludeLogin,
        [ValidateSet("LoginsOnly", "GroupsOnly", "None")]
        [string]$FilterBy = "None",
        [string[]]$IgnoreDomains,
        [switch]$Detailed,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter Detailed

        if ($IgnoreDomains) {
            $IgnoreDomainsNormalized = $IgnoreDomains.ToUpper()
            Write-Message -Message ("Excluding logins for domains " + ($IgnoreDomains -join ',')) -Level Verbose
        }

        $mappingRaw = @{
            'SCRIPT'                                 = 1
            'ACCOUNTDISABLE'                         = 2
            'HOMEDIR_REQUIRED'                       = 8
            'LOCKOUT'                                = 16
            'PASSWD_NOTREQD'                         = 32
            'PASSWD_CANT_CHANGE'                     = 64
            'ENCRYPTED_TEXT_PASSWORD_ALLOWED'        = 128
            'TEMP_DUPLICATE_ACCOUNT'                 = 256
            'NORMAL_ACCOUNT'                         = 512
            'INTERDOMAIN_TRUST_ACCOUNT'              = 2048
            'WORKSTATION_TRUST_ACCOUNT'              = 4096
            'SERVER_TRUST_ACCOUNT'                   = 8192
            'DONT_EXPIRE_PASSWD'                     = 65536
            'MNS_LOGON_ACCOUNT'                      = 131072
            'SMARTCARD_REQUIRED'                     = 262144
            'TRUSTED_FOR_DELEGATION'                 = 524288
            'NOT_DELEGATED'                          = 1048576
            'USE_DES_KEY_ONLY'                       = 2097152
            'DONT_REQUIRE_PREAUTH'                   = 4194304
            'PASSWORD_EXPIRED'                       = 8388608
            'TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION' = 16777216
            'NO_AUTH_DATA_REQUIRED'                  = 33554432
            'PARTIAL_SECRETS_ACCOUNT'                = 67108864
        }
    }
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
                Write-Message -Message "Connected to: $instance." -Level Verbose
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }


            # we can only validate AD logins
            $allWindowsLoginsGroups = $server.Logins | Where-Object { $_.LoginType -in ('WindowsUser', 'WindowsGroup') }

            # we cannot validate local users
            $allWindowsLoginsGroups = $allWindowsLoginsGroups | Where-Object { $_.Name.StartsWith("NT ") -eq $false -and $_.Name.StartsWith($server.ComputerName) -eq $false -and $_.Name.StartsWith("BUILTIN") -eq $false }
            if ($Login) {
                $allWindowsLoginsGroups = $allWindowsLoginsGroups | Where-Object Name -In $Login
            }
            if ($ExcludeLogin) {
                $allWindowsLoginsGroups = $allWindowsLoginsGroups | Where-Object Name -NotIn $ExcludeLogin
            }
            switch ($FilterBy) {
                "LoginsOnly" {
                    Write-Message -Message "Search restricted to logins." -Level Verbose
                    $windowsLogins = $allWindowsLoginsGroups | Where-Object LoginType -eq 'WindowsUser'
                }
                "GroupsOnly" {
                    Write-Message -Message "Search restricted to groups." -Level Verbose
                    $windowsGroups = $allWindowsLoginsGroups | Where-Object LoginType -eq 'WindowsGroup'
                }
                "None" {
                    Write-Message -Message "Search both logins and groups." -Level Verbose
                    $windowsLogins = $allWindowsLoginsGroups | Where-Object LoginType -eq 'WindowsUser'
                    $windowsGroups = $allWindowsLoginsGroups | Where-Object LoginType -eq 'WindowsGroup'
                }
            }
            foreach ($login in $windowsLogins) {
                $adLogin = $login.Name
                $loginSid = $login.Sid -join ''
                $domain, $username = $adLogin.Split("\")
                if ($domain.ToUpper() -in $IgnoreDomainsNormalized) {
                    Write-Message -Message "Skipping Login $adLogin." -Level Verbose
                    continue
                }
                Write-Message -Message "Parsing Login $adLogin." -Level Verbose
                $exists = $false
                try {
                    $u = Get-DbaADObject -ADObject $adLogin -Type User -EnableException
                    if ($null -eq $u -and $adLogin -like '*$') {
                        Write-Message -Message "Parsing Login as computer" -Level Verbose
                        $u = Get-DbaADObject -ADObject $adLogin -Type Computer -EnableException
                        $adType = 'Computer'
                    } else {
                        $adType = 'User'
                    }
                    $foundUser = $u.GetUnderlyingObject()
                    $foundSid = $foundUser.ObjectSid.Value -join ''
                    if ($foundUser) {
                        $exists = $true
                    }
                    if ($foundSid -ne $loginSid) {
                        Write-Message -Message "SID mismatch detected for $adLogin." -Level Warning
                        Write-Message -Message "SID mismatch detected for $adLogin (MSSQL: $loginSid, AD: $foundSid)." -Level Debug
                        $exists = $false
                    }
                } catch {
                    Write-Message -Message "AD Searcher Error for $username." -Level Warning
                }

                $uac = $foundUser.Properties.UserAccountControl

                $additionalProps = @{
                    AccountNotDelegated               = $null
                    AllowReversiblePasswordEncryption = $null
                    CannotChangePassword              = $null
                    PasswordExpired                   = $null
                    LockedOut                         = $null
                    Enabled                           = $null
                    PasswordNeverExpires              = $null
                    PasswordNotRequired               = $null
                    SmartcardLogonRequired            = $null
                    TrustedForDelegation              = $null
                }
                if ($uac) {
                    $additionalProps = @{
                        AccountNotDelegated               = [bool]($uac.Value -band $mappingRaw['NOT_DELEGATED'])
                        AllowReversiblePasswordEncryption = [bool]($uac.Value -band $mappingRaw['ENCRYPTED_TEXT_PASSWORD_ALLOWED'])
                        CannotChangePassword              = [bool]($uac.Value -band $mappingRaw['PASSWD_CANT_CHANGE'])
                        PasswordExpired                   = [bool]($uac.Value -band $mappingRaw['PASSWORD_EXPIRED'])
                        LockedOut                         = [bool]($uac.Value -band $mappingRaw['LOCKOUT'])
                        Enabled                           = !($uac.Value -band $mappingRaw['ACCOUNTDISABLE'])
                        PasswordNeverExpires              = [bool]($uac.Value -band $mappingRaw['DONT_EXPIRE_PASSWD'])
                        PasswordNotRequired               = [bool]($uac.Value -band $mappingRaw['PASSWD_NOTREQD'])
                        SmartcardLogonRequired            = [bool]($uac.Value -band $mappingRaw['SMARTCARD_REQUIRED'])
                        TrustedForDelegation              = [bool]($uac.Value -band $mappingRaw['TRUSTED_FOR_DELEGATION'])
                        UserAccountControl                = $uac.Value
                    }
                }
                $rtn = [PSCustomObject]@{
                    Server                            = $server.DomainInstanceName
                    Domain                            = $domain
                    Login                             = $username
                    Type                              = $adType
                    Found                             = $exists
                    DisabledInSQLServer               = $login.IsDisabled
                    AccountNotDelegated               = $additionalProps.AccountNotDelegated
                    AllowReversiblePasswordEncryption = $additionalProps.AllowReversiblePasswordEncryption
                    CannotChangePassword              = $additionalProps.CannotChangePassword
                    PasswordExpired                   = $additionalProps.PasswordExpired
                    LockedOut                         = $additionalProps.LockedOut
                    Enabled                           = $additionalProps.Enabled
                    PasswordNeverExpires              = $additionalProps.PasswordNeverExpires
                    PasswordNotRequired               = $additionalProps.PasswordNotRequired
                    SmartcardLogonRequired            = $additionalProps.SmartcardLogonRequired
                    TrustedForDelegation              = $additionalProps.TrustedForDelegation
                    UserAccountControl                = $additionalProps.UserAccountControl
                }

                Select-DefaultView -InputObject $rtn -ExcludeProperty AccountNotDelegated, AllowReversiblePasswordEncryption, CannotChangePassword, PasswordNeverExpires, SmartcardLogonRequired, TrustedForDelegation, UserAccountControl

            }

            foreach ($login in $windowsGroups) {
                $adLogin = $login.Name
                $loginSid = $login.Sid -join ''
                $domain, $groupName = $adLogin.Split("\")
                if ($domain.ToUpper() -in $IgnoreDomainsNormalized) {
                    Write-Message -Message "Skipping Login $adLogin." -Level Verbose
                    continue
                }
                Write-Message -Message "Parsing Login $adLogin on $server." -Level Verbose
                $exists = $false
                try {
                    $u = Get-DbaADObject -ADObject $adLogin -Type Group -EnableException
                    $foundUser = $u.GetUnderlyingObject()
                    $foundSid = $foundUser.objectSid.Value -join ''
                    if ($foundUser) {
                        $exists = $true
                    }
                    if ($foundSid -ne $loginSid) {
                        Write-Message -Message "SID mismatch detected for $adLogin." -Level Warning
                        Write-Message -Message "SID mismatch detected for $adLogin (MSSQL: $loginSid, AD: $foundSid)." -Level Debug
                        $exists = $false
                    }
                } catch {
                    Write-Message -Message "AD Searcher Error for $groupName on $server" -Level Warning
                }
                $rtn = [PSCustomObject]@{
                    Server                            = $server.DomainInstanceName
                    Domain                            = $domain
                    Login                             = $groupName
                    Type                              = "Group"
                    Found                             = $exists
                    DisabledInSQLServer               = $login.IsDisabled
                    AccountNotDelegated               = $null
                    AllowReversiblePasswordEncryption = $null
                    CannotChangePassword              = $null
                    PasswordExpired                   = $null
                    LockedOut                         = $null
                    Enabled                           = $null
                    PasswordNeverExpires              = $null
                    PasswordNotRequired               = $null
                    SmartcardLogonRequired            = $null
                    TrustedForDelegation              = $null
                    UserAccountControl                = $null
                }

                Select-DefaultView -InputObject $rtn -ExcludeProperty AccountNotDelegated, AllowReversiblePasswordEncryption, CannotChangePassword, PasswordNeverExpires, SmartcardLogonRequired, TrustedForDelegation, UserAccountControl

            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Test-DbaValidLogin
    }
}
tools\dbatools\functions\Uninstall-DbaSqlWatch.ps1
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
Function Uninstall-DbaSqlWatch {
    <#
    .SYNOPSIS
        Uninstalls SqlWatch.

    .DESCRIPTION
        Deletes all user objects, agent jobs, and historical data associated with SqlWatch.

    .PARAMETER SqlInstance
        SQL Server name or SMO object representing the SQL Server to connect to.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        Specifies the database to install SqlWatch into. Defaults to master.

    .PARAMETER Confirm
        Prompts to confirm actions

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: SqlWatch
        Author: Ken K (github.com/koglerk)
        Website: https://sqlwatch.io
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Uninstall-DbaSqlWatch

    .EXAMPLE
        Uninstall-DbaSqlWatch -SqlInstance server1

        Deletes all user objects, agent jobs, and historical data associated with SqlWatch from the master database.
       #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$Database = "master",
        [switch]$EnableException
    )

    begin {

        # validate database parameter

        if (Test-Bound -Not -ParameterName 'DacfxPath') {
            $dacfxPath = "$script:PSModuleRoot\bin\smo\Microsoft.SqlServer.Dac.dll"
        }

        if ((Test-Path $dacfxPath) -eq $false) {
            Stop-Function -Message 'No usable version of Dac Fx found.'
        } else {
            try {
                Add-Type -Path $dacfxPath
                Write-Message -Level Verbose -Message "Dac Fx loaded."
            } catch {
                Stop-Function -Message 'No usable version of Dac Fx found.' -ErrorRecord $_
            }
        }
    }
    process {
        if (Test-FunctionInterrupt) {
            return
        }

        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            # get SqlWatch objects
            $tables = Get-DbaDbTable -SqlInstance $server -Database $Database | Where-Object {$PSItem.Name -like "sql_perf_mon_*" -or $PSItem.Name -like "logger_*" }
            $views = Get-DbaDbView -SqlInstance $server -Database $Database | Where-Object {$PSItem.Name -like "vw_sql_perf_mon_*" }
            $sprocs = Get-DbaDbStoredProcedure -SqlInstance $server -Database $Database | Where-Object {$PSItem.Name -like "sp_sql_perf_mon_*" -or $PSItem.Name -like "usp_logger_*" }
            $agentJobs = Get-DbaAgentJob -SqlInstance $server | Where-Object { ($PSItem.Name -like "SqlWatch-*") -or ($PSItem.Name -like "DBA-PERF-*") }

            if ($PSCmdlet.ShouldProcess($server, "Removing SqlWatch SQL Agent jobs")) {
                try {
                    Write-Message -Level Verbose -Message "Removing SQL Agent jobs from $server."
                    $agentJobs | Remove-DbaAgentJob | Out-Null
                } catch {
                    Stop-Function -Message "Could not remove all SqlWatch Agent Jobs on $server." -ErrorRecord $_ -Target $server -Continue
                }
            }

            if ($PSCmdlet.ShouldProcess($server, "Removing SqlWatch stored procedures")) {
                try {
                    Write-Message -Level Verbose -Message "Removing SqlWatch stored procedures from $database on $server."
                    $dropScript = ""
                    $sprocs | ForEach-Object {
                        $dropScript += "DROP PROCEDURE $($PSItem.Name);`n"
                    }
                    if ($dropScript) {
                        Invoke-DbaQuery -SqlInstance $server -Database $Database -Query $dropScript
                    }
                } catch {
                    Stop-Function -Message "Could not remove all SqlWatch stored procedures from $database on $server." -ErrorRecord $_ -Target $server -Continue
                }
            }

            if ($PSCmdlet.ShouldProcess($server, "Removing SqlWatch views")) {
                try {
                    Write-Message -Level Verbose -Message "Removing SqlWatch views from $database on $server."
                    $dropScript = ""
                    $views | ForEach-Object {
                        $dropScript += "DROP VIEW $($PSItem.Name);`n"
                    }
                    if ($dropScript) {
                        Invoke-DbaQuery -SqlInstance $server -Database $Database -Query $dropScript
                    }
                } catch {
                    Stop-Function -Message "Could not remove all SqlWatch views from $database on $server." -ErrorRecord $_ -Target $server -Continue
                }
            }

            if ($PSCmdlet.ShouldProcess($server, "Removing SqlWatch tables")) {
                try {
                    Write-Message -Level Verbose -Message "Removing foreign keys from SqlWatch tables in $database on $server."
                    if ($tables.ForeignKeys) {
                        $tables.ForeignKeys | ForEach-Object { $PSItem.Drop() }
                    }
                } catch {
                    Stop-Function -Message "Could not remove all foreign keys from SqlWatch tables in $database on $server." -ErrorRecord $_ -Target $server -Continue
                }

                try {
                    Write-Message -Level Verbose -Message "Removing SqlWatch tables from $database on $server."
                    $dropScript = ""
                    $tables | ForEach-Object {
                        $dropScript += "DROP TABLE $($PSItem.Name);`n"
                    }
                    if ($dropScript) {
                        Invoke-DbaQuery -SqlInstance $server -Database $Database -Query $dropScript
                    }
                } catch {
                    Stop-Function -Message "Could not remove all SqlWatch tables from $database on $server." -ErrorRecord $_ -Target $server -Continue
                }
            }

            if ($PSCmdlet.ShouldProcess($server, "Unpublishing DACPAC")) {
                try {
                    Write-Message -Level Verbose -Message "Unpublishing SqlWatch DACPAC from $database on $server."
                    $connectionString = $server | Select-Object -ExpandProperty ConnectionContext
                    $dacServices = New-Object Microsoft.SqlServer.Dac.DacServices $connectionString
                    $dacServices.Unregister($Database)
                } catch {
                    Stop-Function -Message "Failed to unpublish SqlWatch DACPAC from $database on $server." -ErrorRecord $_
                }
            }
        }
    }
}
tools\dbatools\functions\Uninstall-DbaWatchUpdate.ps1
function Uninstall-DbaWatchUpdate {
    <#
    .SYNOPSIS
        Removes the scheduled task created for Watch-DbaUpdate by Install-DbaWatchUpdate so that notifications no longer pop up.

    .DESCRIPTION
        Removes the scheduled task created for Watch-DbaUpdate by Install-DbaWatchUpdate so that notifications no longer pop up.

    .NOTES
        Tags: JustForFun, Module
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Uninstall-DbaWatchUpdate

    .EXAMPLE
        PS C:\> Uninstall-DbaWatchUpdate

        Removes the scheduled task created by Install-DbaWatchUpdate.

    #>
    process {
        if (([Environment]::OSVersion).Version.Major -lt 10) {
            Write-Message -Level Warning -Message "This command only supports Windows 10 and higher."
            return
        }

        <# Does not utilize message system because of script block #>
        $script = {
            try {
                $task = Get-ScheduledTask -TaskName "dbatools version check" -ErrorAction SilentlyContinue

                if ($null -eq $task) {
                    Write-Message -Level Warning -Message "Task doesn't exist. Skipping removal."
                } else {
                    Write-Message -Level Output -Message "Removing watchupdate.xml."
                    $file = "$env:LOCALAPPDATA\dbatools\watchupdate.xml"
                    Remove-Item $file -ErrorAction SilentlyContinue

                    Write-Message -Level Output -Message "Removing Scheduled Task 'dbatools version check'."
                    $task | Unregister-ScheduledTask -Confirm:$false -ErrorAction Stop

                    Write-Message -Level Output -Message "Task removed"

                    Start-Sleep -Seconds 2
                }
            } catch {
                Write-Message -Level Warning -Message "Task could not be deleted. Please remove 'dbatools version check' manually."
            }
        }
        # Needs admin credentials to remove the task because of the way it was setup

        $task = Get-ScheduledTask -TaskName "dbatools version check" -ErrorAction SilentlyContinue

        if ($null -eq $task) {
            Write-Message -Level Warning -Message "dbatools update watcher is not installed."
            return
        }

        if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
            Write-Message -Level Warning -Message "Removal of this scheduled task requires elevated permissions."
            Start-Process powershell -Verb runAs -ArgumentList Uninstall-DbaWatchUpdate -Wait
        } else {
            Invoke-Command -ScriptBlock $script
        }

        Write-Message -Level Output -Message "All done!"
    }
}
tools\dbatools\functions\Update-DbaInstance.ps1
function Update-DbaInstance {
    <#
    .SYNOPSIS
        Invokes installation of SQL Server Service Packs and Cumulative Updates on local and remote servers.

    .DESCRIPTION
        Starts and automated process of updating SQL Server installation to a specific version defined in the parameters.
        The command will:

        * Search for SQL Server installations in a remote registry
        * Check if current settings are applicable to the current SQL Server versions
        * Search for a KB executable in a folder specified in -Path
        * Establish a PSRemote connection to the target machine if necessary
        * Extract KB to a temporary folder in a current user's profile
        * Run the installation from the temporary folder updating all instances on the computer at once
        * Remove temporary files
        * Restart the computer (if -Restart is specified)
        * Repeat for each consequent KB and computer

        The impact of this function is set to High, if you don't want to receive interactive prompts, set -Confirm to $false.
        Credentials are a required parameter for remote machines. Without specifying -Credential, the installation will fail due to lack of permissions.

        CredSSP is a recommended transport for running the updates remotely. Update-DbaInstance will attempt to reconfigure
        local and remote hosts to support CredSSP, which is why it is desirable to run this command in an elevated console at all times.
        CVE-2018-0886 security update is required for both local and remote hosts. If CredSSP connections are failing, make sure to
        apply recent security updates prior to doing anything else.

        Always backup databases and configurations prior to upgrade.

    .PARAMETER ComputerName
        Target computer with SQL instance or instances.

    .PARAMETER Credential
        Windows Credential with permission to log on to the remote server.
        Must be specified for any remote connection if update Repository is located on a network folder.

    .PARAMETER Type
        Type of the update: All | ServicePack | CumulativeUpdate.
        Default: All
        Use -Version to limit upgrade to a certain Major version of SQL Server.

    .PARAMETER KB
        Install a specific update or list of updates. Can be a number of a string KBXXXXXXX.

    .PARAMETER Version
        A target version of the installation you want to reach. If not specified, a latest available version would be used by default.
        Can be defined using the following general pattern: <MajorVersion><SPX><CUX>.
        Any part of the pattern can be omitted if needed:
        2008R2SP1 - will update SQL 2008R2 to SP1
        2016CU3 - will update SQL 2016 to CU3 of current Service Pack installed
        SP0CU3 - will update all existing SQL Server versions to RTM CU3 without installing any service packs
        SP1CU7 - will update all existing SQL Server versions to SP1 and then (after restart if -Restart is specified) to SP1CU7
        CU7 - will update all existing SQL Server versions to CU7 of current Service Pack installed

    .PARAMETER Path
        Path to the folder(s) with SQL Server patches downloaded. It will be scanned recursively for available patches.
        Path should be available from both server with SQL Server installation and client that runs the command.
        All file names should match the pattern used by Microsoft: SQLServer####*-KB###-*x##*.exe
        If a file is missing in the repository, the installation will fail.
        Consider setting the following configuration if you want to omit this parameter: `Set-DbatoolsConfig -Name Path.SQLServerUpdates -Value '\\path\to\updates'`

    .PARAMETER Restart
        Restart computer automatically after a successful installation of a patch and wait until it comes back online.
        Using this parameter is the only way to chain-install more than 1 patch on a computer, since every single patch will require a restart of said computer.

    .PARAMETER Continue
        Continues a failed installation attempt when specified. Will abort a previously failed installation otherwise.

    .PARAMETER Authentication
        Chooses an authentication protocol for remote connections.
        If the protocol fails to establish a connection

        Defaults:
        * CredSSP when -Credential is specified - due to the fact that repository Path is usually a network share and credentials need to be passed to the remote host
          to avoid the double-hop issue.
        * Default when -Credential is not specified. Will likely fail if a network path is specified.

    .PARAMETER InstanceName
        Only updates a specific instance(s).

    .PARAMETER Throttle
        Maximum number of computers updated in parallel. Once reached, the update operations will queue up.
        Default: 50

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Install, Patching, SP, CU, Instance
        Author: Kirill Kravtsov (@nvarscar) https://nvarscar.wordpress.com/

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires Local Admin rights on destination computer(s).

    .EXAMPLE
        PS C:\> Update-DbaInstance -ComputerName SQL1 -Version SP3 -Path \\network\share

        Updates all applicable SQL Server installations on SQL1 to SP3.
        Binary files for the update will be searched among all files and folders recursively in \\network\share.
        Prompts for confirmation before the update.

    .EXAMPLE
        PS C:\> Update-DbaInstance -ComputerName SQL1, SQL2 -Restart -Path \\network\share -Confirm:$false

        Updates all applicable SQL Server installations on SQL1 and SQL2 with the most recent patch.
        It will install latest ServicePack, restart the computers, install latest Cumulative Update, and finally restart the computer once again.
        Binary files for the update will be searched among all files and folders recursively in \\network\share.
        Does not prompt for confirmation.

    .EXAMPLE
        PS C:\> Update-DbaInstance -ComputerName SQL1 -Version 2012 -Type ServicePack -Path \\network\share

        Updates SQL Server 2012 on SQL1 with the most recent ServicePack found in your patch repository.
        Binary files for the update will be searched among all files and folders recursively in \\network\share.
        Prompts for confirmation before the update.

    .EXAMPLE
        PS C:\> Update-DbaInstance -ComputerName SQL1 -KB 123456 -Restart -Path \\network\share -Confirm:$false

        Installs KB 123456 on SQL1 and restarts the computer.
        Binary files for the update will be searched among all files and folders recursively in \\network\share.
        Does not prompt for confirmation.

    .EXAMPLE
        PS C:\> Update-DbaInstance -ComputerName Server1 -Version SQL2012SP3, SQL2016SP2CU3 -Path \\network\share -Restart -Confirm:$false

        Updates SQL 2012 to SP3 and SQL 2016 to SP2CU3 on Server1. Each update will be followed by a restart.
        Binary files for the update will be searched among all files and folders recursively in \\network\share.
        Does not prompt for confirmation.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High', DefaultParameterSetName = 'Version')]
    Param (
        [parameter(ValueFromPipeline, Position = 1)]
        [Alias("cn", "host", "Server")]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [pscredential]$Credential,
        [Parameter(ParameterSetName = 'Version')]
        [ValidateNotNullOrEmpty()]
        [string[]]$Version,
        [Parameter(ParameterSetName = 'Version')]
        [ValidateSet('All', 'ServicePack', 'CumulativeUpdate')]
        [string[]]$Type = @('All'),
        [Parameter(Mandatory, ParameterSetName = 'KB')]
        [ValidateNotNullOrEmpty()]
        [string[]]$KB,
        [Alias("Instance")]
        [string]$InstanceName,
        [string[]]$Path,
        [switch]$Restart,
        [switch]$Continue,
        [ValidateNotNull()]
        [int]$Throttle = 50,
        [ValidateSet('Default', 'Basic', 'Negotiate', 'NegotiateWithImplicitCredential', 'Credssp', 'Digest', 'Kerberos')]
        [string]$Authentication = 'Credssp',
        [switch]$EnableException
    )
    begin {
        $notifiedCredentials = $false
        $notifiedUnsecure = $false
        #Validating parameters
        if ($PSCmdlet.ParameterSetName -eq 'Version') {
            foreach ($v in $Version) {
                if ($v -notmatch '^((SQL)?\d{4}(R2)?)?\s*(RTM|SP\d+)?\s*(CU\d+)?$') {
                    Stop-Function -Category InvalidArgument -Message "$Version is an incorrect Version value, please refer to Get-Help Update-DbaInstance -Parameter Version"
                    return
                }
            }
        } elseif ($PSCmdlet.ParameterSetName -eq 'KB') {
            $kbList = @()
            foreach ($kbItem in $KB) {
                if ($kbItem -match '^(KB)?(\d+)$') {
                    $kbList += $Matches[2]
                } else {
                    Stop-Function -Category InvalidArgument -Message "$kbItem is an incorrect KB value, please refer to Get-Help Update-DbaInstance -Parameter KB"
                    return
                }
            }
        }
        $actions = @()
        $actionTemplate = @{}
        if ($InstanceName) { $actionTemplate.InstanceName = $InstanceName }
        if ($Continue) { $actionTemplate.Continue = $Continue }
        #Putting together list of actions based on current ParameterSet
        if ($PSCmdlet.ParameterSetName -eq 'Version') {
            if ($Type -contains 'All') { $typeList = @('ServicePack', 'CumulativeUpdate') }
            else { $typeList = $Type | Sort-Object -Descending }
            foreach ($ver in $Version) {
                $currentAction = $actionTemplate.Clone()
                if ($ver -and $ver -match '^(SQL)?(\d{4}(R2)?)?\s*(RTM|SP)?(\d+)?(CU)?(\d+)?') {
                    $majorV, $spV, $cuV = $Matches[2, 5, 7]
                    Write-Message -Level Debug -Message "Parsed Version as Major $majorV SP $spV CU $cuV"
                    # Add appropriate fields to the splat
                    # Add version to every field
                    if ($null -ne $majorV) {
                        $currentAction += @{
                            MajorVersion = $majorV
                        }
                        # When version is the only thing that is specified, we want all the types added
                        if ($null -eq $spV -and $null -eq $cuV) {
                            foreach ($currentType in $typeList) {
                                $actions += $currentAction.Clone() + @{ Type = $currentType }
                            }
                        }
                    }
                    #when SP# is specified
                    if ($null -ne $spV) {
                        $currentAction += @{
                            ServicePack = $spV
                        }
                        # ignore SP0 and trigger only when SP is in Type
                        if ($spV -ne '0' -and 'ServicePack' -in $typeList) {
                            $actions += $currentAction.Clone()
                        }
                    }
                    # When CU# is specified, but ignore CU0 and trigger only when CU is in Type
                    if ($null -ne $cuV -and $cuV -ne '0' -and 'CumulativeUpdate' -in $typeList) {
                        $actions += $currentAction.Clone() + @{ CumulativeUpdate = $cuV }
                    }
                } else {
                    Stop-Function -Category InvalidArgument -Message "$ver is an incorrect Version value, please refer to Get-Help Update-DbaInstance -Parameter Version"
                    return
                }
            }
            # If no version specified, simply apply latest $currentType
            if (!$Version) {
                foreach ($currentType in $typeList) {
                    $currentAction = $actionTemplate.Clone() + @{
                        Type = $currentType
                    }
                    $actions += $currentAction
                }
            }
        } elseif ($PSCmdlet.ParameterSetName -eq 'KB') {
            foreach ($kbItem in $kbList) {
                $currentAction = $actionTemplate.Clone() + @{
                    KB = $kbItem
                }
                $actions += $currentAction
            }
        }
        # debug message
        foreach ($a in $actions) {
            Write-Message -Level Debug -Message "Added installation action $($a | ConvertTo-Json -Depth 1 -Compress)"
        }
        # defining how to process the final results
        $outputHandler = {
            $_ | Select-DefaultView -Property ComputerName, MajorVersion, TargetLevel, KB, Successful, Restarted, InstanceName, Installer, Notes
            if ($_.Successful -eq $false) {
                Write-Message -Level Warning -Message "Update failed: $($_.Notes -join ' | ')"
            }
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }

        #Resolve all the provided names
        $resolvedComputers = @()
        $pathIsNetwork = $Path | Foreach-Object -Begin { $o = @() } -Process { $o += $_ -like '\\*'} -End { $o -contains $true }
        foreach ($computer in $ComputerName) {
            $null = Test-ElevationRequirement -ComputerName $computer -Continue
            if (!$computer.IsLocalHost -and -not $notifiedCredentials -and -not $Credential -and $pathIsNetwork) {
                Write-Message -Level Warning -Message "Explicit -Credential might be required when running agains remote hosts and -Path is a network folder"
                $notifiedCredentials = $true
            }
            if ($resolvedComputer = Resolve-DbaNetworkName -ComputerName $computer.ComputerName) {
                $resolvedComputers += $resolvedComputer.FullComputerName
            }
        }
        #Leave only unique computer names
        $resolvedComputers = $resolvedComputers | Sort-Object -Unique
        #Process planned actions and gather installation actions
        $installActions = @()
        :computers foreach ($resolvedName in $resolvedComputers) {
            $activity = "Preparing to update SQL Server on $resolvedName"
            ## Find the current version on the computer
            Write-ProgressHelper -ExcludePercent -Activity $activity -StepNumber 0 -Message "Gathering all SQL Server instance versions"
            $components = Get-SQLInstanceComponent -ComputerName $resolvedName -Credential $Credential
            if (!$components) {
                Stop-Function -Message "No SQL Server installations found on $resolvedName" -Continue
            }
            Write-Message -Level Debug -Message "Found $(($components | Measure-Object).Count) existing SQL Server instance components: $(($components | Foreach-Object { "$($_.InstanceName)($($_.InstanceType) $($_.Version.NameLevel))" }) -join ',')"
            # Filter for specific instance name
            if ($InstanceName) {
                $components = $components | Where-Object {$_.InstanceName -eq $InstanceName }
            }
            $upgrades = @()
            :actions foreach ($currentAction in $actions) {
                $restartNeeded = Test-PendingReboot -ComputerName $resolvedName
                if ($restartNeeded -and (-not $Restart -or ([DbaInstanceParameter]$resolvedName).IsLocalHost)) {
                    #Exit the actions loop altogether - nothing can be installed here anyways
                    Stop-Function -Message "$resolvedName is pending a reboot. Reboot the computer before proceeding." -Continue -ContinueLabel computers
                }
                # Attempt to configure CredSSP for the remote host when credentials are defined
                if ($Credential -and -not ([DbaInstanceParameter]$resolvedName).IsLocalHost -and $Authentication -eq 'Credssp') {
                    Write-Message -Level Verbose -Message "Attempting to configure CredSSP for remote connections"
                    Initialize-CredSSP -ComputerName $resolvedName -Credential $Credential -EnableException $false
                    # Verify remote connection and confirm using unsecure credentials
                    try {
                        $secureProtocol = Invoke-Command2 -ComputerName $resolvedName -Credential $Credential -Authentication $Authentication -ScriptBlock { $true } -Raw
                    } catch {
                        $secureProtocol = $false
                    }
                    # only ask once about using unsecure protocol
                    if (-not $secureProtocol -and -not $notifiedUnsecure) {
                        if ($PSCmdlet.ShouldProcess($resolvedName, "Primary protocol ($Authentication) failed, sending credentials via potentially unsecure protocol")) {
                            $notifiedUnsecure = $true
                        } else {
                            Stop-Function -Message "Failed to connect to $resolvedName through $Authentication protocol. No actions will be performed on that computer." -Continue -ContinueLabel computers
                        }
                    }
                }
                # Pass only relevant components
                if ($currentAction.MajorVersion) {
                    Write-Message -Level Debug -Message "Limiting components to version $($currentAction.MajorVersion)"
                    $selectedComponents = $components | Where-Object { $_.Version.NameLevel -contains $currentAction.MajorVersion }
                    $currentAction.Remove('MajorVersion')
                } else {
                    $selectedComponents = $components
                }
                Write-ProgressHelper -ExcludePercent -Activity $activity -Message "Looking for a KB file for a chosen version"
                Write-Message -Level Debug -Message "Looking for appropriate KB file on $resolvedName with following params: $($currentAction | ConvertTo-Json -Depth 1 -Compress)"
                # get upgrade details for each component
                $upgradeDetails = Get-SqlServerUpdate @currentAction -ComputerName $resolvedName -Credential $Credential -Component $selectedComponents
                if ($upgradeDetails.Successful -contains $false) {
                    #Exit the actions loop altogether - upgrade cannot be performed
                    $upgradeDetails
                    Stop-Function -Message "Update cannot be applied to $resolvedName | $($upgradeDetails.Notes -join ' | ')" -Continue -ContinueLabel computers
                }

                foreach ($detail in $upgradeDetails) {
                    # search for installer for each target upgrade
                    $kbLookupParams = @{
                        ComputerName   = $resolvedName
                        Credential     = $Credential
                        Authentication = $Authentication
                        Architecture   = $detail.Architecture
                        MajorVersion   = $detail.MajorVersion
                        Path           = $Path
                        KB             = $detail.KB
                    }
                    $installer = Find-SqlServerUpdate @kbLookupParams
                    if ($installer) {
                        $detail.Installer = $installer.FullName
                    } else {
                        Stop-Function -Message "Could not find installer for the SQL$($detail.MajorVersion) update KB$($detail.KB)" -Continue
                    }
                    # update components to mirror the updated version - will be used for multi-step upgrades
                    foreach ($component in $components) {
                        if ($component.Version.NameLevel -eq $detail.TargetVersion.NameLevel) {
                            $component.Version = $detail.TargetVersion
                        }
                    }
                    # finally, add the upgrade details to the upgrade list
                    $upgrades += $detail
                }
            }
            if ($upgrades) {
                Write-ProgressHelper -ExcludePercent -Activity $activity -Message "Preparing installation"
                $chosenVersions = ($upgrades | ForEach-Object { "$($_.MajorVersion) to $($_.TargetLevel) (KB$($_.KB))" }) -join ', '
                if ($PSCmdlet.ShouldProcess($resolvedName, "Update $chosenVersions")) {
                    $installActions += [pscustomobject]@{
                        ComputerName  = $resolvedName
                        Actions       = $upgrades
                        RestartNeeded = $restartNeeded
                    }
                }
            }
            Write-Progress -Activity $activity -Completed
        }
        # Declare the installation script
        $installScript = {
            $computer = $_.ComputerName
            $activity = "Updating SQL Server components on $computer"
            $restarted = $false
            $restartParams = @{
                ComputerName = $computer
                ErrorAction  = 'Stop'
                For          = 'WinRM'
                Wait         = $true
                Force        = $true
            }
            if ($Credential) {
                $restartParams.Credential = $Credential
            }
            if ($_.RestartNeeded -and $Restart) {
                # Restart the computer prior to doing anything
                Write-ProgressHelper -ExcludePercent -Activity $activity -Message "Restarting computer $($computer) due to pending restart"
                Write-Message -Level Verbose "Restarting computer $($computer) due to pending restart" -FunctionName Update-DbaInstance
                try {
                    $null = Restart-Computer @restartParams
                    $restarted = $true
                } catch {
                    Stop-Function -Message "Failed to restart computer" -ErrorRecord $_ -FunctionName Update-DbaInstance
                }
            }
            Write-Message -Level Debug -Message "Processing $($computer) with $(($_.Actions | Measure-Object).Count) actions" -FunctionName Update-DbaInstance
            #foreach action passed to the script for this particular computer
            foreach ($currentAction in $_.Actions) {
                $output = $currentAction
                $output.Successful = $false
                $output.Restarted = $restarted
                ## Start the installation sequence
                Write-ProgressHelper -ExcludePercent -Activity $activity -Message "Launching installation of $($currentAction.TargetLevel) KB$($currentAction.KB) ($($currentAction.Installer)) for SQL$($currentAction.MajorVersion) ($($currentAction.Build))"
                $execParams = @{
                    ComputerName   = $computer
                    ErrorAction    = 'Stop'
                    Authentication = $Authentication
                }
                if ($Credential) {
                    $execParams.Credential = $Credential
                } else {
                    if (Test-Bound -Not Authentication) {
                        # Use Default authentication instead of CredSSP when Authentication is not specified and Credential is null
                        $execParams.Authentication = "Default"
                    }
                }
                # Find a temporary folder to extract to - the drive that has most free space
                $chosenDrive = (Get-DbaDiskSpace -ComputerName $computer -Credential $Credential | Sort-Object -Property Free -Descending | Select-Object -First 1).Name
                if (!$chosenDrive) {
                    # Fall back to the system drive
                    $chosenDrive = Invoke-Command2 -ComputerName $computer -Credential $Credential -ScriptBlock { $env:SystemDrive } -Raw -ErrorAction Stop
                }
                $spExtractPath = $chosenDrive.TrimEnd('\') + "\dbatools_KB$($currentAction.KB)_Extract"
                if ($spExtractPath) {
                    $output.ExtractPath = $spExtractPath
                    try {
                        # Extract file
                        Write-ProgressHelper -ExcludePercent -Activity $activity -Message "Extracting $($currentAction.Installer) to $spExtractPath"
                        Write-Message -Level Verbose -Message "Extracting $($currentAction.Installer) to $spExtractPath" -FunctionName Update-DbaInstance
                        $extractResult = Invoke-Program @execParams -Path $currentAction.Installer -ArgumentList "/x`:`"$spExtractPath`" /quiet" -Fallback
                        if (-not $extractResult.Successful) {
                            $msg = "Extraction failed with exit code $($extractResult.ExitCode)"
                            $output.Notes += $msg
                            Stop-Function -Message $msg -FunctionName Update-DbaInstance
                            return $output
                        }
                        # Install the patch
                        if ($currentAction.InstanceName) {
                            $instanceClause = "/instancename=$($currentAction.InstanceName)"
                        } else {
                            $instanceClause = '/allinstances'
                        }
                        Write-ProgressHelper -ExcludePercent -Activity $activity -Message "Now installing update SQL$($currentAction.MajorVersion)$($currentAction.TargetLevel) from $spExtractPath"
                        Write-Message -Level Verbose -Message "Starting installation from $spExtractPath" -FunctionName Update-DbaInstance
                        $updateResult = Invoke-Program @execParams -Path "$spExtractPath\setup.exe" -ArgumentList @('/quiet', $instanceClause, '/IAcceptSQLServerLicenseTerms') -WorkingDirectory $spExtractPath -Fallback
                        if ($updateResult.Successful) {
                            $output.Successful = $true
                        } else {
                            $msg = "Update failed with exit code $($updateResult.ExitCode)"
                            $output.Notes += $msg
                            Stop-Function -Message $msg -FunctionName Update-DbaInstance
                            return $output
                        }
                        $output.Log = $updateResult.stdout
                    } catch {
                        Stop-Function -Message "Upgrade failed" -ErrorRecord $_ -FunctionName Update-DbaInstance
                        $output.Notes += $_.Exception.Message
                        return $output
                    } finally {
                        ## Cleanup temp
                        Write-ProgressHelper -ExcludePercent -Activity $activity -Message "Cleaning up extracted files from $spExtractPath"
                        try {
                            Write-ProgressHelper -ExcludePercent -Activity $activity -Message "Removing temporary files"
                            $null = Invoke-CommandWithFallBack @execParams -ScriptBlock {
                                if ($args[0] -like '*\dbatools_KB*_Extract' -and (Test-Path $args[0])) {
                                    Remove-Item -Recurse -Force -LiteralPath $args[0] -ErrorAction Stop
                                }
                            } -Raw -ArgumentList $spExtractPath
                        } catch {
                            $message = "Failed to cleanup temp folder on computer $($computer)`: $($_.Exception.Message)"
                            Write-Message -Level Verbose -Message $message -FunctionName Update-DbaInstance
                            $output.Notes += $message
                        }
                    }
                }
                #double check if restart is needed
                if ($updateResult.ExitCode -eq 3010 -or (Test-PendingReboot -ComputerName $resolvedName)) {
                    if ($Restart) {
                        # Restart the computer
                        Write-ProgressHelper -ExcludePercent -Activity $activity -Message "Restarting computer $($computer) and waiting for it to come back online"
                        Write-Message -Level Verbose "Restarting computer $($computer) and waiting for it to come back online" -FunctionName Update-DbaInstance
                        try {
                            $null = Restart-Computer @restartParams
                            $output.Restarted = $true
                        } catch {
                            Stop-Function -Message "Failed to restart computer" -ErrorRecord $_ -FunctionName Update-DbaInstance
                            return $output
                        }
                    } else {
                        $output.Notes += "Restart is required for computer $($computer) to finish the installation of SQL$($currentAction.MajorVersion)$($currentAction.TargetLevel)"
                    }
                }
                $output
                Write-Progress -Activity $activity -Completed
            }
        }
        # check how many computers we are looking at and decide upon parallelism
        if ($installActions.Count -eq 1) {
            $installActions | ForEach-Object -Process $installScript | ForEach-Object -Process $outputHandler
        } elseif ($installActions.Count -ge 2) {
            $installActions | Invoke-Parallel -ImportModules -ImportVariables -ScriptBlock $installScript -Throttle $Throttle | ForEach-Object -Process $outputHandler
        }
    }
}
tools\dbatools\functions\Update-DbaServiceAccount.ps1
function Update-DbaServiceAccount {
    <#
    .SYNOPSIS
        Changes service account (or just its password) of the SQL Server service.

    .DESCRIPTION
        Reconfigure the service account or update the password of the specified SQL Server service. The service will be restarted in the event of changing the account.

    .PARAMETER ComputerName
        The target SQL Server instance or instances.

    .PARAMETER Credential
        Windows Credential with permission to log on to the server running the SQL instance

    .PARAMETER InputObject
        A collection of services. Basically, any object that has ComputerName and ServiceName properties. Can be piped from Get-DbaService.

    .PARAMETER ServiceName
        A name of the service on which the action is performed. E.g. MSSQLSERVER or SqlAgent$INSTANCENAME

    .PARAMETER ServiceCredential
        Windows Credential object under which the service will be setup to run. Cannot be used with -Username. For local service accounts use one of the following usernames with empty password:
        LOCALSERVICE
        NETWORKSERVICE
        LOCALSYSTEM

    .PARAMETER PreviousPassword
        An old password of the service account. Optional when run under local admin privileges.

    .PARAMETER SecurePassword
        New password of the service account. The function will ask for a password if not specified. MSAs and local system accounts will ignore the password.

    .PARAMETER Username
        Username of the service account. Cannot be used with -ServiceCredential. For local service accounts use one of the following usernames omitting the -SecurePassword parameter:
        LOCALSERVICE
        NETWORKSERVICE
        LOCALSYSTEM

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Service, SqlServer, Instance, Connect
        Author: Kirill Kravtsov (@nvarscar)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires Local Admin rights on destination computer(s).

    .EXAMPLE
        PS C:\> $SecurePassword = ConvertTo-SecureString 'Qwerty1234' -AsPlainText -Force
        Update-DbaServiceAccount -ComputerName sql1 -ServiceName 'MSSQL$MYINSTANCE' -SecurePassword $SecurePassword

        Changes the current service account's password of the service MSSQL$MYINSTANCE to 'Qwerty1234'

    .EXAMPLE
        PS C:\> $cred = Get-Credential
        PS C:\> Get-DbaService sql1 -Type Engine,Agent -Instance MYINSTANCE | Update-DbaServiceAccount -ServiceCredential $cred

        Requests credentials from the user and configures them as a service account for the SQL Server engine and agent services of the instance sql1\MYINSTANCE

    .EXAMPLE
        PS C:\> Update-DbaServiceAccount -ComputerName sql1,sql2 -ServiceName 'MSSQLSERVER','SQLSERVERAGENT' -Username NETWORKSERVICE

        Configures SQL Server engine and agent services on the machines sql1 and sql2 to run under Network Service system user.

    .EXAMPLE
        PS C:\> Get-DbaService sql1 -Type Engine -Instance MSSQLSERVER | Update-DbaServiceAccount -Username 'MyDomain\sqluser1'

        Configures SQL Server engine service on the machine sql1 to run under MyDomain\sqluser1. Will request user to input the account password.

    #>
    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = "ServiceName" )]
    param (
        [parameter(ParameterSetName = "ServiceName")]
        [Alias("cn", "host", "Server")]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [PSCredential]$Credential,
        [parameter(ValueFromPipeline, Mandatory, ParameterSetName = "InputObject")]
        [Alias("ServiceCollection")]
        [object[]]$InputObject,
        [parameter(ParameterSetName = "ServiceName", Position = 1, Mandatory)]
        [Alias("Name", "Service")]
        [string[]]$ServiceName,
        [Alias("User")]
        [string]$Username,
        [PSCredential]$ServiceCredential,
        [securestring]$PreviousPassword = (New-Object System.Security.SecureString),
        [Alias("Password", "NewPassword")]
        [securestring]$SecurePassword = (New-Object System.Security.SecureString),
        [switch]$EnableException
    )
    begin {
        $svcCollection = @()
        $scriptAccountChange = {
            $service = $wmi.Services[$args[0]]
            $service.SetServiceAccount($args[1], $args[2])
            $service.Alter()
        }
        $scriptPasswordChange = {
            $service = $wmi.Services[$args[0]]
            $service.ChangePassword($args[1], $args[2])
            $service.Alter()
        }
        #Check parameters
        if ($Username) {
            $actionType = 'Account'
            if ($ServiceCredential) {
                Stop-Function -EnableException $EnableException -Message "You cannot specify both -UserName and -ServiceCredential parameters" -Category InvalidArgument
                return
            }
            #System logins should not have a domain name, whitespaces or passwords
            $trimmedUsername = (Split-Path $Username -Leaf).Trim().Replace(' ', '')
            #Request password input if password was not specified and account is not MSA or system login
            if ($SecurePassword.Length -eq 0 -and $PSBoundParameters.Keys -notcontains 'SecurePassword' -and $trimmedUsername -notin 'NETWORKSERVICE', 'LOCALSYSTEM', 'LOCALSERVICE' -and $Username.EndsWith('$') -eq $false -and $Username.StartsWith('NT Service\') -eq $false) {
                $SecurePassword = Read-Host -Prompt "Input new password for account $UserName" -AsSecureString
                $NewPassword2 = Read-Host -Prompt "Repeat password" -AsSecureString
                if ((New-Object System.Management.Automation.PSCredential ("user", $SecurePassword)).GetNetworkCredential().Password -ne `
                    (New-Object System.Management.Automation.PSCredential ("user", $NewPassword2)).GetNetworkCredential().Password) {
                    Stop-Function -Message "Passwords do not match" -Category InvalidArgument -EnableException $EnableException
                    return
                }
            }
            $currentCredential = New-Object System.Management.Automation.PSCredential ($Username, $SecurePassword)
        } elseif ($ServiceCredential) {
            $actionType = 'Account'
            $currentCredential = $ServiceCredential
        } else {
            $actionType = 'Password'
        }
        if ($actionType -eq 'Account') {
            #System logins should not have a domain name, whitespaces or passwords
            $credUserName = (Split-Path $currentCredential.UserName -Leaf).Trim().Replace(' ', '')
            #Check for system logins and replace the Credential object to simplify passing localsystem-like login names
            if ($credUserName -in 'NETWORKSERVICE', 'LOCALSYSTEM', 'LOCALSERVICE') {
                $currentCredential = New-Object System.Management.Automation.PSCredential ($credUserName, (New-Object System.Security.SecureString))
            }
        }
    }
    process {
        if ($PsCmdlet.ParameterSetName -match 'ServiceName') {
            foreach ($Computer in $ComputerName.ComputerName) {
                $Server = Resolve-DbaNetworkName -ComputerName $Computer -Credential $credential
                if ($Server.ComputerName) {
                    foreach ($service in $ServiceName) {
                        $svcCollection += [psobject]@{
                            ComputerName = $server.ComputerName
                            ServiceName  = $service
                        }
                    }
                } else {
                    Stop-Function -EnableException $EnableException -Message "Failed to connect to $Computer" -Continue
                }
            }
        } elseif ($PsCmdlet.ParameterSetName -match 'InputObject') {
            foreach ($service in $InputObject) {
                $Server = Resolve-DbaNetworkName -ComputerName $service.ComputerName -Credential $credential
                if ($Server.ComputerName) {
                    $svcCollection += [psobject]@{
                        ComputerName = $Server.ComputerName
                        ServiceName  = $service.ServiceName
                    }
                } else {
                    Stop-Function -EnableException $EnableException -Message "Failed to connect to $($service.ComputerName)" -Continue
                }
            }
        }

    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Update-DbaSqlServiceAccount

        foreach ($svc in $svcCollection) {
            if ($serviceObject = Get-DbaService -ComputerName $svc.ComputerName -ServiceName $svc.ServiceName -Credential $Credential -EnableException:$EnableException) {
                $outMessage = $outStatus = $agent = $null
                if ($actionType -eq 'Password' -and $SecurePassword.Length -eq 0) {
                    $currentPassword = Read-Host -Prompt "New password for $($serviceObject.StartName) ($($svc.ServiceName) on $($svc.ComputerName))" -AsSecureString
                    $currentPassword2 = Read-Host -Prompt "Repeat password" -AsSecureString
                    if ((New-Object System.Management.Automation.PSCredential ("user", $currentPassword)).GetNetworkCredential().Password -ne `
                        (New-Object System.Management.Automation.PSCredential ("user", $currentPassword2)).GetNetworkCredential().Password) {
                        Stop-Function -Message "Passwords do not match. This service will not be updated" -Category InvalidArgument -EnableException $EnableException -Continue
                    }
                } else {
                    $currentPassword = $SecurePassword
                }
                if ($serviceObject.ServiceType -eq 'Engine') {
                    #Get SQL Agent running status
                    $agent = Get-DbaService -ComputerName $svc.ComputerName -Type Agent -InstanceName $serviceObject.InstanceName
                }
                if ($PsCmdlet.ShouldProcess($serviceObject, "Changing account information for service $($svc.ServiceName) on $($svc.ComputerName)")) {
                    try {
                        if ($actionType -eq 'Account') {
                            Write-Message -Level Verbose -Message "Attempting an account change for service $($svc.ServiceName) on $($svc.ComputerName)"
                            $null = Invoke-ManagedComputerCommand -ComputerName $svc.ComputerName -Credential $Credential -ScriptBlock $scriptAccountChange -ArgumentList @($svc.ServiceName, $currentCredential.UserName, $currentCredential.GetNetworkCredential().Password) -EnableException:$EnableException
                            $outMessage = "The login account for the service has been successfully set."
                        } elseif ($actionType -eq 'Password') {
                            Write-Message -Level Verbose -Message "Attempting a password change for service $($svc.ServiceName) on $($svc.ComputerName)"
                            $null = Invoke-ManagedComputerCommand -ComputerName $svc.ComputerName -Credential $Credential -ScriptBlock $scriptPasswordChange -ArgumentList @($svc.ServiceName, (New-Object System.Management.Automation.PSCredential ("user", $PreviousPassword)).GetNetworkCredential().Password, (New-Object System.Management.Automation.PSCredential ("user", $currentPassword)).GetNetworkCredential().Password) -EnableException:$EnableException
                            $outMessage = "The password has been successfully changed."
                        }
                        $outStatus = 'Successful'
                    } catch {
                        $outStatus = 'Failed'
                        $outMessage = $_.Exception.Message
                        Write-Message -Level Warning -Message $_.Exception.Message -EnableException $EnableException.ToBool()
                    }
                } else {
                    $outStatus = 'Successful'
                    $outMessage = 'No changes made - running in -WhatIf mode.'
                }
                if ($serviceObject.ServiceType -eq 'Engine' -and $actionType -eq 'Account' -and $outStatus -eq 'Successful' -and $agent.State -eq 'Running') {
                    #Restart SQL Agent after SQL Engine has been restarted
                    if ($PsCmdlet.ShouldProcess($serviceObject, "Starting SQL Agent after Engine account change on $($svc.ComputerName)")) {
                        $res = Start-DbaService -ComputerName $svc.ComputerName -Type Agent -InstanceName $serviceObject.InstanceName
                        if ($res.Status -ne 'Successful') {
                            Write-Message -Level Warning -Message "Failed to restart SQL Agent after changing credentials. $($res.Message)"
                        }
                    }
                }
                $serviceObject = Get-DbaService -ComputerName $svc.ComputerName -ServiceName $svc.ServiceName -Credential $Credential -EnableException:$EnableException
                Add-Member -Force -InputObject $serviceObject -NotePropertyName Message -NotePropertyValue $outMessage
                Add-Member -Force -InputObject $serviceObject -NotePropertyName Status -NotePropertyValue $outStatus
                Select-DefaultView -InputObject $serviceObject -Property ComputerName, ServiceName, State, StartName, Status, Message
            } Else {
                Stop-Function -Message "The service $($svc.ServiceName) has not been found on $($svc.ComputerName)" -EnableException $EnableException -Continue
            }
        }
    }
}
tools\dbatools\functions\Update-dbatools.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Update-Dbatools {
    <#
    .SYNOPSIS
        Exported function. Updates dbatools. Deletes current copy and replaces it with freshest copy.

    .DESCRIPTION
        Exported function. Updates dbatools. Deletes current copy and replaces it with freshest copy.

    .PARAMETER Development
        If this switch is enabled, the current development branch will be installed. By default, the latest official release is installed.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .NOTES
        Tags: Module
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Update-DbaTools

    .EXAMPLE
        PS C:\> Update-Dbatools

        Updates dbatools. Deletes current copy and replaces it with freshest copy.

    .EXAMPLE
        PS C:\> Update-Dbatools -dev

        Updates dbatools to the current development branch. Deletes current copy and replaces it with latest from github.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification = "It is the proper noun of the cmdlet")]
    param(
        [Alias("dev", "devbranch")]
        [switch]$Development,
        [Alias('Silent')]
        [switch]$EnableException
    )
    $MyModuleBase = [SqlCollaborative.Dbatools.dbaSystem.SystemHost]::ModuleBase
    $InstallScript = join-path -path $MyModuleBase -ChildPath "install.ps1";
    if ($Development) {
        Write-Message -Level Verbose -Message "Installing dev/beta channel via $Installscript.";
        if ($PSCmdlet.ShouldProcess("development branch", "Updating dbatools")) {
            & $InstallScript -beta;
        }
    } else {
        Write-Message -Level Verbose -Message "Installing release version via $Installscript."
        if ($PSCmdlet.ShouldProcess("release branch", "Updating dbatools")) {
            & $InstallScript;
        }
    }
}
tools\dbatools\functions\Watch-DbaDbLogin.ps1
function Watch-DbaDbLogin {
    <#
    .SYNOPSIS
        Tracks SQL Server logins: which host they came from, what database they're using, and what program is being used to log in.

    .DESCRIPTION
        Watch-DbaDbLogin uses SQL Server DMV's to track logins into a SQL Server table. This is helpful when you need to migrate a SQL Server and update connection strings, but have inadequate documentation on which servers/applications are logging into your SQL instance.

        Running this script every 5 minutes for a week should give you a sufficient idea about database and login usage.

    .PARAMETER SqlInstance
        The SQL Server that stores the Watch database.

    .PARAMETER SqlCms
        Specifies a Central Management Server to query for a list of servers to watch.

    .PARAMETER ServersFromFile
        Specifies a file containing a list of servers to watch. This file must contain one server name per line.

    .PARAMETER Database
        The name of the Watch database.

    .PARAMETER Table
        The name of the Watch table. By default, this is DbaTools-WatchDbLogins.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Login
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT
        Requires: sysadmin access on all SQL Servers for the most accurate results

    .LINK
        https://dbatools.io/Watch-DbaDbLogin

    .EXAMPLE
        PS C:\> Watch-DbaDbLogin -SqlInstance sqlserver -SqlCms SqlCms1

        A list of all database instances within the Central Management Server SqlCms1 is generated. Using this list, the script enumerates all the processes and gathers login information and saves it to the table Dblogins in the DatabaseLogins database on SQL Server sqlserver.

    .EXAMPLE
        PS C:\> Watch-DbaDbLogin -SqlInstance sqlcluster -Database CentralAudit -ServersFromFile .\sqlservers.txt

        A list of servers is gathered from the file sqlservers.txt in the current directory. Using this list, the script enumerates all the processes and gathers login information and saves it to the table Dblogins in the CentralAudit database on SQL Server sqlcluster.

    .EXAMPLE
        PS C:\> Watch-DbaDbLogin -SqlInstance sqlserver -SqlCms SqlCms1 -SqlCredential $cred

        A list of servers is generated using database instance names within the SQL2014Clusters group on the Central Management Server SqlCms1. Using this list, the script enumerates all the processes and gathers login information and saves it to the table Dblogins in the DatabaseLogins database on sqlserver.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default")]
    param (
        [parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance]$SqlInstance,
        [object]$Database,
        [string]$Table = "DbaTools-WatchDbLogins",
        [PSCredential]$SqlCredential,

        # Central Management Server
        [string]$SqlCms,

        # File with one server per line
        [string]$ServersFromFile,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        if (Test-Bound 'SqlCms', 'ServersFromFile' -Not) {
            Stop-Function -Message "You must specify a server list source using -SqlCms or -ServersFromFile"
            return
        }

        try {
            $serverDest = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $SqlInstance -Continue
        }

        $systemdbs = "master", "msdb", "model", "tempdb"
        $excludedPrograms = "Microsoft SQL Server Management Studio - Query", "SQL Management"

        <#
            Get servers to query from Central Management Server or File
        #>
        if ($SqlCms) {
            try {
                $servers = Get-DbaCmsRegServerName -SqlInstance $SqlCms -SqlCredential $SqlCredential -EnableException
            } catch {
                Stop-Function -Message "The CMS server, $SqlCms, was not accessible." -Target $SqlCms -ErrorRecord $_
                return
            }
        }
        if (Test-Bound 'ServersFromFile') {
            if (Test-Path $ServersFromFile) {
                $servers = Get-Content $ServersFromFile
            } else {
                Stop-Function -Message "$ServersFromFile was not found." -Target $ServersFromFile
                return
            }
        }

        <#
            Process each server
        #>
        foreach ($instance in $servers) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if (!(Test-SqlSa $server)) {
                Write-Message -Level Warning -Message "Not a sysadmin on $instance, resultset would be underwhelming. Skipping.";
                continue
            }

            $sql = "
            SELECT
                s.login_time AS [LoginTime]
                , s.login_name AS [Login]
                , ISNULL(s.host_name,N'') AS [Host]
                , ISNULL(s.program_name,N'') AS [Program]
                , ISNULL(r.database_id,N'') AS [DatabaseId]
                , ISNULL(DB_NAME(r.database_id),N'') AS [Database]
                , CAST(~s.is_user_process AS bit) AS [IsSystem]
                , CaptureTime = (SELECT GETDATE())
            FROM sys.dm_exec_sessions AS s
            LEFT OUTER JOIN sys.dm_exec_requests AS r
                ON r.session_id = s.session_id"
            Write-Message -Level Debug -Message $sql

            $procs = $server.Query($sql) | Where-Object { $_.Host -ne $instance.ComputerName -and ![string]::IsNullOrEmpty($_.Host) }
            $procs = $procs | Where-Object { $systemdbs -notcontains $_.Database -and $excludedPrograms -notcontains $_.Program }

            if ($procs.Count -gt 0) {
                $procs | Select-Object @{Label = "ComputerName"; Expression = {$server.ComputerName}}, @{Label = "InstanceName"; Expression = {$server.ServiceName}}, @{Label = "SqlInstance"; Expression = {$server.DomainInstanceName}}, LoginTime, Login, Host, Program, DatabaseId, Database, IsSystem, CaptureTime | ConvertTo-DbaDataTable | Write-DbaDataTable -SqlInstance $serverDest -Database $Database -Table $Table -AutoCreateTable

                Write-Message -Level Output -Message "Added process information for $instance to datatable."
            } else {
                Write-Message -Level Verbose -Message "No data returned for $instance."
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Watch-SqlDbLogin
    }
}
tools\dbatools\functions\Watch-DbaUpdate.ps1
function Watch-DbaUpdate {
    <#
    .SYNOPSIS
        Just for fun - checks the PowerShell Gallery every 1 hour for updates to dbatools. Notifies once per release.

    .DESCRIPTION
        Just for fun - checks the PowerShell Gallery every 1 hour for updates to dbatools. Notifies once max per release.

        Anyone know how to make it clickable so that it opens an URL?

    .NOTES
        Tags: JustForFun, Module
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Watch-DbaUpdate

    .EXAMPLE
        PS C:\> Watch-DbaUpdate

        Watches the gallery for updates to dbatools.

    #>
    [cmdletbinding()]
    param()
    process {
        if (([Environment]::OSVersion).Version.Major -lt 10) {
            Write-Message -Level Warning -Message "This command only supports Windows 10 and higher."
            return
        }

        if ($null -eq (Get-ScheduledTask -TaskName "dbatools version check" -ErrorAction SilentlyContinue)) {
            Install-DbaWatchUpdate
        }

        # leave this in for the scheduled task
        $module = Get-Module -Name dbatools

        if (-not $module) {
            Import-Module dbatools
            $module = Get-Module -Name dbatools
        }

        $galleryVersion = (Find-Module -Name dbatools -Repository PSGallery).Version
        $localVersion = $module.Version

        if ($galleryVersion -le $localVersion) { return }

        $file = "$env:LOCALAPPDATA\dbatools\watchupdate.xml"

        $new = [PSCustomObject]@{
            NotifyVersion = $galleryVersion
        }

        # now that notifications stay until they are checked, we just have to keep
        # track of the last version we notified about

        if (Test-Path $file) {
            $old = Import-Clixml -Path $file -ErrorAction SilentlyContinue

            if ($galleryVersion -gt $old.NotifyVersion) {
                Export-Clixml -InputObject $new -Path $file
                Show-Notification -GalleryVersion $galleryVersion
            }
        } else {
            $directory = Split-Path $file

            if (!(Test-Path $directory)) {
                $null = New-Item -ItemType Directory -Path $directory
            }

            Export-Clixml -InputObject $new -Path $file
            Show-Notification -GalleryVersion $galleryVersion
        }
    }
}
tools\dbatools\functions\Watch-DbaXESession.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Watch-DbaXESession {
    <#
    .SYNOPSIS
        Watch live XEvent Data as it happens

    .DESCRIPTION
        Watch live XEvent Data as it happens. This command runs until you stop the session, kill the PowerShell session, or Ctrl-C.

        Thanks to Dave Mason (@BeginTry) for some straightforward code samples https://itsalljustelectrons.blogspot.be/2017/01/SQL-Server-Extended-Event-Handling-Via-Powershell.html

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Session
        Only return a specific session. Options for this parameter are auto-populated from the server.

    .PARAMETER Raw
        If this switch is enabled, the Microsoft.SqlServer.XEvent.Linq.QueryableXEventData enumeration object is returned.

    .PARAMETER InputObject
        Accepts an XESession object returned by Get-DbaXESession.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: ExtendedEvent, XE, XEvent
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Watch-DbaXESession

    .EXAMPLE
        PS C:\> Watch-DbaXESession -SqlInstance sql2017 -Session system_health

        Shows events for the system_health session as it happens.

    .EXAMPLE
        PS C:\> Watch-DbaXESession -SqlInstance sql2017 -Session system_health | Export-Csv -NoTypeInformation -Path C:\temp\system_health.csv

        Exports live events to CSV. Ctrl-C may not not cancel out of it - fastest way is to stop the session.

    .EXAMPLE
        PS C:\> Get-DbaXESession -SqlInstance sql2017 -Session system_health | Start-DbaXESession | Watch-DbaXESession | Export-Csv -NoTypeInformation -Path C:\temp\system_health.csv

        Exports live events to CSV. Ctrl-C may not not cancel out of this. The fastest way to do so is to stop the session.

    #>
    [CmdletBinding(DefaultParameterSetName = "Default")]
    param (
        [parameter(ValueFromPipeline, ParameterSetName = "instance", Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$Session,
        [parameter(ValueFromPipeline, ParameterSetName = "piped", Mandatory)]
        [Microsoft.SqlServer.Management.XEvent.Session]$InputObject,
        [switch]$Raw,
        [switch][Alias('Silent')]
        $EnableException
    )
    process {
        if (-not $SqlInstance) {

        } else {
            try {
                $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential -MinimumVersion 11
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $SqlInstance -Continue
            }
            $SqlConn = $server.ConnectionContext.SqlConnectionObject
            $SqlStoreConnection = New-Object Microsoft.SqlServer.Management.Sdk.Sfc.SqlStoreConnection $SqlConn
            $XEStore = New-Object  Microsoft.SqlServer.Management.XEvent.XEStore $SqlStoreConnection
            Write-Message -Level Verbose -Message "Getting XEvents Sessions on $SqlInstance."
            $InputObject += $XEStore.sessions | Where-Object Name -eq $Session
        }

        foreach ($xesession in $InputObject) {
            $server = $xesession.Parent
            $sessionname = $xesession.Name
            Write-Message -Level Verbose -Message "Watching $sessionname on $($server.Name)."

            if (-not $xesession.IsRunning -and -not $xesession.IsRunning) {
                Stop-Function -Message "$($xesession.Name) is not running on $($server.Name)" -Continue
            }

            # Setup all columns for csv but do it in an order
            $columns = @("name", "timestamp")
            $newcolumns = @()

            $fields = ($xesession.Events.EventFields.Name | Select-Object -Unique)
            foreach ($column in $fields) {
                $newcolumns += $column.TrimStart("collect_")
            }

            $actions = ($xesession.Events.Actions.Name | Select-Object -Unique)
            foreach ($action in $actions) {
                $newcolumns += ($action -Split '\.')[-1]
            }

            $newcolumns = $newcolumns | Sort-Object
            $columns = ($columns += $newcolumns) | Select-Object -Unique

            try {
                $xevent = New-Object -TypeName Microsoft.SqlServer.XEvent.Linq.QueryableXEventData(
                    ($server.ConnectionContext.ConnectionString),
                    ($xesession.Name),
                    [Microsoft.SqlServer.XEvent.Linq.EventStreamSourceOptions]::EventStream,
                    [Microsoft.SqlServer.XEvent.Linq.EventStreamCacheOptions]::DoNotCache
                )

                if ($raw) {
                    return $xevent
                }

                # Format output
                foreach ($event in $xevent) {
                    $hash = [ordered]@{}

                    foreach ($column in $columns) {
                        $null = $hash.Add($column, $event.$column) # this basically adds name and timestamp then nulls
                    }

                    foreach ($action in $event.Actions) {
                        $hash[$action.Name] = $action.Value
                    }

                    foreach ($field in $event.Fields) {
                        $hash[$field.Name] = $field.Value
                    }

                    [PSCustomObject]($hash)
                }
            } catch {
                Start-Sleep 1
                $status = Get-DbaXESession -SqlInstance $server -Session $sessionname
                if ($status.Status -ne "Running") {
                    Stop-Function -Message "$($xesession.Name) was stopped."
                } else {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target $sessionname
                }
            } finally {
                if ($xevent -is [IDisposable]) {
                    $xevent.Dispose()
                }
            }
        }
    }
}
tools\dbatools\functions\Write-DbaDataTable.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Write-DbaDataTable {
    <#
    .SYNOPSIS
        Writes data to a SQL Server Table.

    .DESCRIPTION
        Writes a .NET DataTable to a SQL Server table using SQL Bulk Copy.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

    .PARAMETER Database
        The database to import the table into.

    .PARAMETER InputObject
        This is the DataTable (or data row) to import to SQL Server.

    .PARAMETER Table
        The table name to import data into. You can specify a one, two, or three part table name. If you specify a one or two part name, you must also use -Database.

        If the table does not exist, you can use -AutoCreateTable to automatically create the table with inefficient data types.

        If the object has special characters please wrap them in square brackets [ ].
        Using dbo.First.Table will try to import to a table named 'Table' on schema 'First' and database 'dbo'.
        The correct way to import to a table named 'First.Table' on schema 'dbo' is by passing dbo.[First.Table]
        Any actual usage of the ] must be escaped by duplicating the ] character.
        The correct way to import to a table Name] in schema Schema.Name is by passing [Schema.Name].[Name]]]

    .PARAMETER Schema
        Defaults to dbo if no schema is specified.

    .PARAMETER BatchSize
        The BatchSize for the import defaults to 5000.

    .PARAMETER NotifyAfter
        Sets the option to show the notification after so many rows of import

    .PARAMETER AutoCreateTable
        If this switch is enabled, the table will be created if it does not already exist. The table will be created with sub-optimal data types such as nvarchar(max)

    .PARAMETER NoTableLock
        If this switch is enabled, a table lock (TABLOCK) will not be placed on the destination table. By default, this operation will lock the destination table while running.

    .PARAMETER CheckConstraints
        If this switch is enabled, the SqlBulkCopy option to process check constraints will be enabled.

        Per Microsoft "Check constraints while data is being inserted. By default, constraints are not checked."

    .PARAMETER FireTriggers
        If this switch is enabled, the SqlBulkCopy option to fire insert triggers will be enabled.

        Per Microsoft "When specified, cause the server to fire the insert triggers for the rows being inserted into the Database."

    .PARAMETER KeepIdentity
        If this switch is enabled, the SqlBulkCopy option to preserve source identity values will be enabled.

        Per Microsoft "Preserve source identity values. When not specified, identity values are assigned by the destination."

    .PARAMETER KeepNulls
        If this switch is enabled, the SqlBulkCopy option to preserve NULL values will be enabled.

        Per Microsoft "Preserve null values in the destination table regardless of the settings for default values. When not specified, null values are replaced by default values where applicable."

    .PARAMETER Truncate
        If this switch is enabled, the destination table will be truncated after prompting for confirmation.

    .PARAMETER BulkCopyTimeOut
        Value in seconds for the BulkCopy operations timeout. The default is 30 seconds.

    .PARAMETER RegularUser
        Deprecated - now all connections are regular user (don't require admin)

    .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.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER UseDynamicStringLength
        By default, all string columns will be NVARCHAR(MAX).
        If this switch is enabled, all columns will get the length specified by the column's MaxLength property (if specified)

    .NOTES
        Tags: DataTable, Insert
        Author: Chrissy LeMaire (@cl), netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Write-DbaDataTable

    .EXAMPLE
        PS C:\> $DataTable = Import-Csv C:\temp\customers.csv
        PS C:\> Write-DbaDataTable -SqlInstance sql2014 -InputObject $DataTable -Table mydb.dbo.customers

        Performs a bulk insert of all the data in customers.csv into database mydb, schema dbo, table customers. A progress bar will be shown as rows are inserted. If the destination table does not exist, the import will be halted.

    .EXAMPLE
        PS C:\> $tableName = "MyTestData"
        PS C:\> $query = "SELECT name, create_date, owner_sid FROM sys.databases"
        PS C:\> $dataset = Invoke-DbaQuery -SqlInstance 'localhost,1417' -SqlCredential $containerCred -Database master -Query $query
        PS C:\> $dataset | Select-Object name, create_date, @{L="owner_sid";E={$_."owner_sid"}} | Write-DbaDataTable -SqlInstance 'localhost,1417' -SqlCredential $containerCred -Database tempdb -Table myTestData -Schema dbo -AutoCreateTable

        Pulls data from a SQL Server instance and then performs a bulk insert of the dataset to a new, auto-generated table tempdb.dbo.MyTestData.

    .EXAMPLE
        PS C:\> $DataTable = Import-Csv C:\temp\customers.csv
        PS C:\> Write-DbaDataTable -SqlInstance sql2014 -InputObject $DataTable -Table mydb.dbo.customers -AutoCreateTable -Confirm

        Performs a bulk insert of all the data in customers.csv. If mydb.dbo.customers does not exist, it will be created with inefficient but forgiving DataTypes.

        Prompts for confirmation before a variety of steps.

    .EXAMPLE
        PS C:\> $DataTable = Import-Csv C:\temp\customers.csv
        PS C:\> Write-DbaDataTable -SqlInstance sql2014 -InputObject $DataTable -Table mydb.dbo.customers -Truncate

        Performs a bulk insert of all the data in customers.csv. Prior to importing into mydb.dbo.customers, the user is informed that the table will be truncated and asks for confirmation. The user is prompted again to perform the import.

    .EXAMPLE
        PS C:\> $DataTable = Import-Csv C:\temp\customers.csv
        PS C:\> Write-DbaDataTable -SqlInstance sql2014 -InputObject $DataTable -Database mydb -Table customers -KeepNulls

        Performs a bulk insert of all the data in customers.csv into mydb.dbo.customers. Because Schema was not specified, dbo was used. NULL values in the destination table will be preserved.

    .EXAMPLE
        PS C:\> $passwd = ConvertTo-SecureString "P@ssw0rd" -AsPlainText -Force
        PS C:\> $AzureCredential = New-Object System.Management.Automation.PSCredential("AzureAccount"),$passwd)
        PS C:\> $DataTable = Import-Csv C:\temp\customers.csv
        PS C:\> Write-DbaDataTable -SqlInstance AzureDB.database.windows.net -InputObject $DataTable -Database mydb -Table customers -KeepNulls -Credential $AzureCredential -BulkCopyTimeOut 300

        This performs the same operation as the previous example, but against a SQL Azure Database instance using the required credentials.

    .EXAMPLE
        PS C:\> $process = Get-Process
        PS C:\> Write-DbaDataTable -InputObject $process -SqlInstance sql2014 -Table "[[DbName]]].[Schema.With.Dots].[`"[Process]]`"]" -AutoCreateTable

        Creates a table based on the Process object with over 60 columns, converted from PowerShell data types to SQL Server data types. After the table is created a bulk insert is performed to add process information into the table
        Writes the results of Get-Process to a table named: "[Process]" in schema named: Schema.With.Dots in database named: [DbName]
        The Table name, Schema name and Database name must be wrapped in square brackets [ ]
        Special charcters like " must be escaped by a ` charcter.
        In addition any actual instance of the ] character must be escaped by being duplicated.

        This is an example of the type conversion in action. All process properties are converted, including special types like TimeSpan. Script properties are resolved before the type conversion starts thanks to ConvertTo-DbaDataTable.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [Parameter(Position = 0, Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [ValidateNotNull()]
        [DbaInstanceParameter]$SqlInstance,
        [Parameter(Position = 1)]
        [ValidateNotNull()]
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Parameter(Position = 2)]
        [object]$Database,
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias("DataTable")]
        [ValidateNotNull()]
        [object]$InputObject,
        [Parameter(Position = 3, Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Table,
        [Parameter(Position = 4)]
        [ValidateNotNullOrEmpty()]
        [string]$Schema = 'dbo',
        [ValidateNotNull()]
        [int]$BatchSize = 50000,
        [ValidateNotNull()]
        [int]$NotifyAfter = 5000,
        [switch]$AutoCreateTable,
        [switch]$NoTableLock,
        [switch]$CheckConstraints,
        [switch]$FireTriggers,
        [switch]$KeepIdentity,
        [switch]$KeepNulls,
        [switch]$Truncate,
        [ValidateNotNull()]
        [int]$bulkCopyTimeOut = 5000,
        [switch]$RegularUser,
        [Alias('Silent')]
        [switch]$EnableException,
        [switch]$UseDynamicStringLength
    )

    begin {
        # Null variable to make sure upper-scope variables don't interfere later
        $steppablePipeline = $null

        #region Utility Functions
        function Invoke-BulkCopy {
            <#
            .SYNOPSIS
                Copies a datatable in bulk over to a table.

            .DESCRIPTION
                Copies a datatable in bulk over to a table.

            .PARAMETER DataTable
                The datatable to copy.

            .PARAMETER SqlInstance
                Needs not be specified. The SqlInstance targeted. For message purposes only.

            .PARAMETER Fqtn
                Needs not be specified. The fqtn written to. For message purposes only.

            .PARAMETER BulkCopy
                Needs not be specified. The bulk copy object used to perform the copy operation.
        #>
            [CmdletBinding()]
            param (
                $DataTable,
                [DbaInstance]$SqlInstance = $SqlInstance,
                [string]$Fqtn = $fqtn,
                $BulkCopy = $bulkCopy
            )
            Write-Message -Level Verbose -Message "Importing in bulk to $fqtn"

            $rowCount = $DataTable.Rows.Count
            if ($rowCount -eq 0) {
                $rowCount = 1
            }

            if ($Pscmdlet.ShouldProcess($SqlInstance, "Writing $rowCount rows to $Fqtn")) {
                $bulkCopy.WriteToServer($DataTable)
                if ($rowCount -is [int]) {
                    Write-Progress -id 1 -activity "Inserting $rowCount rows" -status "Complete" -Completed
                }
            }
        }

        function New-Table {
            <#
            .SYNOPSIS
                Creates a table, based upon a DataTable.

            .DESCRIPTION
                Creates a table, based upon a DataTable.

            .PARAMETER DataTable
                The DataTable to base the table structure upon.

            .PARAMETER PStoSQLTypes
                Automatically inherits from parent.

            .PARAMETER SqlInstance
                Automatically inherits from parent.

            .PARAMETER Fqtn
                Automatically inherits from parent.

            .PARAMETER Server
                Automatically inherits from parent.

            .PARAMETER DatabaseName
                Automatically inherits from parent.

            .PARAMETER EnableException
                By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
                This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
                Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

            .PARAMETER UseDynamicStringLength
                Automatically inherits from parent.
        #>
            [CmdletBinding(SupportsShouldProcess)]
            param (
                $DataTable,
                $PStoSQLTypes = $PStoSQLTypes,
                $SqlInstance = $SqlInstance,
                $Fqtn = $fqtn,
                $Server = $server,
                $DatabaseName = $databaseName,
                [switch]$EnableException
            )

            Write-Message -Level Verbose -Message "Creating table for $fqtn"

            # Get SQL datatypes by best guess on first data row
            $sqlDataTypes = @();
            $columns = $DataTable.Columns

            if ($null -eq $columns) {
                $columns = $DataTable.Table.Columns
            }

            foreach ($column in $columns) {
                $sqlColumnName = $column.ColumnName

                try {
                    $columnValue = $DataTable.Rows[0].$sqlColumnName
                } catch {
                    $columnValue = $DataTable.$sqlColumnName
                }

                if ($null -eq $columnValue) {
                    $columnValue = $DataTable.$sqlColumnName
                }

                <#
                PS to SQL type conversion
                If data type exists in hash table, use the corresponding SQL type
                Else, fallback to nvarchar.
                If UseDynamicStringLength is specified, the DataColumn MaxLength is used if specified
            #>
                if ($PStoSQLTypes.Keys -contains $column.DataType) {
                    $sqlDataType = $PStoSQLTypes[$($column.DataType.toString())]
                    if ($UseDynamicStringLength -and $column.MaxLength -gt 0 -and ($column.DataType -in ("String", "System.String"))) {
                        $sqlDataType = $sqlDataType.Replace("(MAX)", "($($column.MaxLength))")
                    }
                } else {
                    $sqlDataType = "nvarchar(MAX)"
                }

                $sqlDataTypes += "[$sqlColumnName] $sqlDataType"
            }

            $sql = "BEGIN CREATE TABLE $fqtn ($($sqlDataTypes -join ' NULL,')) END"

            Write-Message -Level Debug -Message $sql

            if ($Pscmdlet.ShouldProcess($SqlInstance, "Creating table $Fqtn")) {
                try {
                    $null = $Server.Databases[$DatabaseName].Query($sql)
                } catch {
                    Stop-Function -Message "The following query failed: $sql" -ErrorRecord $_
                    return
                }
            }
        }

        #endregion Utility Functions

        #region Prepare type for bulk copy
        if (-not $Truncate) { $ConfirmPreference = "None" }

        # Getting the total rows copied is a challenge. Use SqlBulkCopyExtension.
        # http://stackoverflow.com/questions/1188384/sqlbulkcopy-row-count-when-complete

        $sourcecode = 'namespace System.Data.SqlClient {
            using Reflection;

            public static class SqlBulkCopyExtension
            {
                const String _rowsCopiedFieldName = "_rowsCopied";
                static FieldInfo _rowsCopiedField = null;

                public static int RowsCopiedCount(this SqlBulkCopy bulkCopy)
                {
                    if (_rowsCopiedField == null) _rowsCopiedField = typeof(SqlBulkCopy).GetField(_rowsCopiedFieldName, BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
                    return (int)_rowsCopiedField.GetValue(bulkCopy);
                }
            }
        }'
        # Load the basics
        if (-not $script:core) {
            try {
                Add-Type -ReferencedAssemblies System.Data.dll -TypeDefinition $sourcecode -ErrorAction Stop
            } catch {
                $null = 1
            }
        }
        #endregion Prepare type for bulk copy

        #region Resolve Full Qualified Table Name
        $fqtnObj = Get-TableNameParts $Table

        if ($fqtnObj.$parsed) {
            Stop-Function -Message "Unable to parse $($fqtnObj.InputValue) as a valid tablename."
            return
        }

        if ($null -eq $fqtnObj.Database -and $null -eq $Database) {
            Stop-Function -Message "You must specify a database or fully qualified table name."
            return
        }

        if (Test-Bound -ParameterName Database) {
            if ($null -eq $fqtnObj.Database) {
                $databaseName = "$Database"
            } else {
                if ($fqtnObj.Database -eq $Database) {
                    $databaseName = "$Database"
                } else {
                    Stop-Function -Message "The database parameter $($Database) differs from value from the fully qualified table name $($fqtnObj.Database)."
                    return
                }
            }
        } else {
            $databaseName = $fqtnObj.Database
        }

        if ($fqtnObj.Schema) {
            $schemaName = $fqtnObj.Schema
        } else {
            $schemaName = $Schema
        }

        $tableName = $fqtnObj.Table

        $quotedFQTN = New-Object System.Text.StringBuilder

        [void]$quotedFQTN.Append( '[' )
        if ($databaseName.Contains(']')) {
            [void]$quotedFQTN.Append( $databaseName.Replace(']', ']]') )
        } else {
            [void]$quotedFQTN.Append( $databaseName )
        }
        [void]$quotedFQTN.Append( '].' )

        [void]$quotedFQTN.Append( '[' )
        if ($schemaName.Contains(']')) {
            [void]$quotedFQTN.Append( $schemaName.Replace(']', ']]') )
        } else {
            [void]$quotedFQTN.Append( $schemaName )
        }
        [void]$quotedFQTN.Append( '].' )

        [void]$quotedFQTN.Append( '[' )
        if ($tableName.Contains(']')) {
            [void]$quotedFQTN.Append( $tableName.Replace(']', ']]') )
        } else {
            [void]$quotedFQTN.Append( $tableName )
        }
        [void]$quotedFQTN.Append( ']' )

        $fqtn = $quotedFQTN.ToString()
        Write-Message -Level SomewhatVerbose -Message "FQTN processed: $fqtn"
        #endregion Resolve Full Qualified Table Name

        #region Connect to server and get database
        try {
            $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $SqlInstance
            return
        }

        if ($server.ServerType -eq 'SqlAzureDatabase') {
            <#
                For some reasons SMO wants an initial pull when talking to Azure Sql DB
                This will throw and be caught, and then we can continue as normal.
            #>
            try {
                $null = $server.Databases
            } catch {
                # here to avoid an empty catch
                $null = 1
            }
        }
        $databaseObject = $server.Databases[$databaseName]
        #endregion Connect to server and get database

        #region Prepare database and bulk operations
        if ($null -eq $databaseObject) {
            Stop-Function -Message "$databaseName does not exist." -Target $SqlInstance
            return
        }

        $databaseObject.Tables.Refresh()
        if ($schemaName -notin $databaseObject.Schemas.Name) {
            Stop-Function -Message "Schema does not exist."
            return
        }

        $tableExists = ($tableName -in $databaseObject.Tables.Name) -and ($databaseObject.Tables.Schema -eq $schemaName)

        if ((-not $tableExists) -and (-not $AutoCreateTable)) {
            Stop-Function -Message "Table does not exist and automatic creation of the table has not been selected. Specify the '-AutoCreateTable'-parameter to generate a suitable table."
            return
        }

        $bulkCopyOptions = 0
        $options = "TableLock", "CheckConstraints", "FireTriggers", "KeepIdentity", "KeepNulls", "Default"

        foreach ($option in $options) {
            $optionValue = Get-Variable $option -ValueOnly -ErrorAction SilentlyContinue
            if ($option -eq "TableLock" -and (!$NoTableLock)) {
                $optionValue = $true
            }
            if ($optionValue -eq $true) {
                $bulkCopyOptions += $([Data.SqlClient.SqlBulkCopyOptions]::$option).value__
            }
        }

        if ($Truncate -eq $true) {
            if ($Pscmdlet.ShouldProcess($SqlInstance, "Truncating $fqtn")) {
                try {
                    Write-Message -Level Output -Message "Truncating $fqtn."
                    $null = $server.Databases[$databaseName].Query("TRUNCATE TABLE $fqtn")
                } catch {
                    Write-Message -Level Warning -Message "Could not truncate $fqtn. Table may not exist or may have key constraints." -ErrorRecord $_
                }
            }
        }

        $bulkCopy = New-Object Data.SqlClient.SqlBulkCopy("$($server.ConnectionContext.ConnectionString);Database=$databaseName", $bulkCopyOptions)
        $bulkCopy.DestinationTableName = $fqtn
        $bulkCopy.BatchSize = $BatchSize
        $bulkCopy.NotifyAfter = $NotifyAfter
        $bulkCopy.BulkCopyTimeOut = $BulkCopyTimeOut

        $elapsed = [System.Diagnostics.Stopwatch]::StartNew()
        # Add RowCount output
        $bulkCopy.Add_SqlRowsCopied( {
                $script:totalRows = $args[1].RowsCopied
                $percent = [int](($script:totalRows / $rowCount) * 100)
                $timeTaken = [math]::Round($elapsed.Elapsed.TotalSeconds, 1)
                Write-Progress -id 1 -activity "Inserting $rowCount rows." -PercentComplete $percent -Status ([System.String]::Format("Progress: {0} rows ({1}%) in {2} seconds", $script:totalRows, $percent, $timeTaken))
            })

        $PStoSQLTypes = @{
            #PS datatype      = SQL data type
            'System.Int32'    = 'int';
            'System.UInt32'   = 'bigint';
            'System.Int16'    = 'smallint';
            'System.UInt16'   = 'int';
            'System.Int64'    = 'bigint';
            'System.UInt64'   = 'decimal(20,0)';
            'System.Decimal'  = 'decimal(38,5)';
            'System.Single'   = 'bigint';
            'System.Double'   = 'float';
            'System.Byte'     = 'tinyint';
            'System.SByte'    = 'smallint';
            'System.TimeSpan' = 'nvarchar(30)';
            'System.String'   = 'nvarchar(MAX)';
            'System.Char'     = 'nvarchar(1)'
            'System.DateTime' = 'datetime2';
            'System.Boolean'  = 'bit';
            'System.Guid'     = 'uniqueidentifier';
            'Int32'           = 'int';
            'UInt32'          = 'bigint';
            'Int16'           = 'smallint';
            'UInt16'          = 'int';
            'Int64'           = 'bigint';
            'UInt64'          = 'decimal(20,0)';
            'Decimal'         = 'decimal(38,5)';
            'Single'          = 'bigint';
            'Double'          = 'float';
            'Byte'            = 'tinyint';
            'SByte'           = 'smallint';
            'TimeSpan'        = 'nvarchar(30)';
            'String'          = 'nvarchar(MAX)';
            'Char'            = 'nvarchar(1)'
            'DateTime'        = 'datetime2';
            'Boolean'         = 'bit';
            'Bool'            = 'bit';
            'Guid'            = 'uniqueidentifier';
            'int'             = 'int';
            'long'            = 'bigint';
        }

        $validTypes = @([System.Data.DataSet], [System.Data.DataTable], [System.Data.DataRow], [System.Data.DataRow[]])
        #endregion Prepare database and bulk operations

        #region ConvertTo-DbaDataTable wrapper
        try {
            $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('ConvertTo-DbaDataTable', [System.Management.Automation.CommandTypes]::Function)
            $splatCDDT = @{
                TimeSpanType = (Get-DbatoolsConfigValue -FullName 'commands.write-dbadatatable.timespantype' -Fallback 'TotalMilliseconds')
                SizeType     = (Get-DbatoolsConfigValue -FullName 'commands.write-dbadatatable.sizetype' -Fallback 'Int64')
                IgnoreNull   = (Get-DbatoolsConfigValue -FullName 'commands.write-dbadatatable.ignorenull' -Fallback $false)
                Raw          = (Get-DbatoolsConfigValue -FullName 'commands.write-dbadatatable.raw' -Fallback $false)
            }
            $scriptCmd = { & $wrappedCmd @splatCDDT }
            $steppablePipeline = $scriptCmd.GetSteppablePipeline()
            $steppablePipeline.Begin($true)
        } catch {
            Stop-Function -Message "Failed to initialize "
        }
        #endregion ConvertTo-DbaDataTable wrapper
    }
    process {
        if (Test-FunctionInterrupt) { return }

        if ($null -ne $InputObject) { $inputType = $InputObject.GetType() }
        else { $inputType = $null }

        if ($inputType -eq [System.Data.DataSet]) {
            $inputData = $InputObject.Tables
            $inputType = [System.Data.DataTable[]]
        } else {
            $inputData = $InputObject
        }

        #region Scenario 1: Single valid table
        if ($inputType -in $validTypes) {
            if (-not $tableExists) {
                try {
                    New-Table -DataTable $InputObject -EnableException
                    $tableExists = $true
                } catch {
                    Stop-Function -Message "Failed to create table $fqtn" -ErrorRecord $_ -Target $SqlInstance
                    return
                }
            }

            try { Invoke-BulkCopy -DataTable $InputObject }
            catch {
                Stop-Function -Message "Failed to bulk import to $fqtn" -ErrorRecord $_ -Target $SqlInstance
            }
            return
        }
        #endregion Scenario 1: Single valid table

        foreach ($object in $inputData) {
            #region Scenario 2: Multiple valid tables
            if ($object.GetType() -in $validTypes) {
                if (-not $tableExists) {
                    try {
                        New-Table -DataTable $object -EnableException
                        $tableExists = $true
                    } catch {
                        Stop-Function -Message "Failed to create table $fqtn" -ErrorRecord $_ -Target $SqlInstance
                        return
                    }
                }

                try { Invoke-BulkCopy -DataTable $object }
                catch {
                    Stop-Function -Message "Failed to bulk import to $fqtn" -ErrorRecord $_ -Target $SqlInstance -Continue
                }
                continue
            }
            #endregion Scenario 2: Multiple valid tables

            #region Scenario 3: Invalid data types
            else {
                $null = $steppablePipeline.Process($object)
                continue
            }
            #endregion Scenario 3: Invalid data types
        }
    }
    end {
        #region ConvertTo-DbaDataTable wrapper
        if ($null -ne $steppablePipeline) {
            $dataTable = $steppablePipeline.End()

            if (-not $tableExists) {
                try {
                    New-Table -DataTable $dataTable[0] -EnableException
                    $tableExists = $true
                } catch {
                    Stop-Function -Message "Failed to create table $fqtn" -ErrorRecord $_ -Target $SqlInstance
                    return
                }
            }

            try { Invoke-BulkCopy -DataTable $dataTable[0] }
            catch {
                Stop-Function -Message "Failed to bulk import to $fqtn" -ErrorRecord $_ -Target $SqlInstance
            }
        }
        #endregion ConvertTo-DbaDataTable wrapper

        if ($bulkCopy) {
            $bulkCopy.Close()
            $bulkCopy.Dispose()
        }
        Test-DbaDeprecation -DeprecatedOn 1.0.0 -Parameter RegularUser
    }
}
tools\dbatools\install.ps1
[CmdletBinding()]
param (
    [string]$Path,
    [switch]$Beta
)

function Write-LocalMessage {
    [CmdletBinding()]
    param (
        [string]$Message
    )

    if (Test-Path function:Write-Message) { Write-Message -Level Output -Message $Message }
    else { Write-Host $Message }
}

try {
    Update-Module dbatools -Erroraction Stop
    Write-LocalMessage -Message "Updated using the PowerShell Gallery"
    return
} catch {
    Write-LocalMessage -Message "dbatools was not installed by the PowerShell Gallery, continuing with web install."
}

$currentVersionTls = [Net.ServicePointManager]::SecurityProtocol
$currentSupportableTls = [Math]::Max($currentVersionTls.value__, [Net.SecurityProtocolType]::Tls.value__)
$availableTls = [enum]::GetValues('Net.SecurityProtocolType') | Where-Object {
    $_ -gt $currentSupportableTls
}
$availableTls | ForEach-Object {
    [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor $_
}

$dbatools_copydllmode = $true
$module = Import-Module -Name dbatools -ErrorAction SilentlyContinue
$localpath = $module.ModuleBase

if ($null -eq $localpath) {
    $localpath = "$HOME\Documents\WindowsPowerShell\Modules\dbatools"
} else {
    Write-LocalMessage -Message "Updating current install"
}

try {
    if (-not $path) {
        if ($PSCommandPath.Length -gt 0) {
            $path = Split-Path $PSCommandPath
            if ($path -match "github") {
                Write-LocalMessage -Message "Looks like this installer is run from your GitHub Repo, defaulting to psmodulepath"
                $path = $localpath
            }
        } else {
            $path = $localpath
        }
    }
} catch {
    $path = $localpath
}

if (-not $path -or (Test-Path -Path "$path\.git")) {
    $path = $localpath
}

If ($lib = [appdomain]::CurrentDomain.GetAssemblies() | Where-Object FullName -like "dbatools, *") {
    if ($lib.Location -like "$Path\*") {
        Write-LocalMessage @"
We have detected dbatools to be already imported from
$path
In a manner that prevents us from updating it, since dll files have been locked.
In order to ensure a valid update, please:
- Close all consoles that have dbatools imported (Remove-Module dbatools is NOT enough)
- Start a new PowerShell console
- Run '`$dbatools_copydllmode = `$true' (without the single-quotes)
- Import dbatools and run Update-Dbatools
If done in this order, the binaries will be copied to another location before import, allowing for a save update.
"@
        return
    }
}

Write-LocalMessage -Message "Installing module to $path"

if (!(Test-Path -Path $path)) {
    try {
        Write-LocalMessage -Message "Creating directory: $path"
        New-Item -Path $path -ItemType Directory | Out-Null
    } catch {
        throw "Can't create $Path. You may need to Run as Administrator: $_"
    }
}

if ($beta) {
    $url = 'https://dbatools.io/devzip'
    $branch = "development"
} else {
    $url = 'https://dbatools.io/zip'
    $branch = "master"
}

$temp = ([System.IO.Path]::GetTempPath()).TrimEnd("\")
$zipfile = "$temp\dbatools.zip"

Write-LocalMessage -Message "Downloading archive from github"
try {
    (New-Object System.Net.WebClient).DownloadFile($url, $zipfile)
} catch {
    try {
        #try with default proxy and usersettings
        Write-LocalMessage -Message "Probably using a proxy for internet access, trying default proxy settings"
        $wc = (New-Object System.Net.WebClient)
        $wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
        $wc.DownloadFile($url, $zipfile)
    } catch {
        Write-Warning "Error downloading file :( $_"
        return
    }
}

# Unblock if there's a block
Unblock-File $zipfile -ErrorAction SilentlyContinue

Write-LocalMessage -Message "Unzipping"

# Keep it backwards compatible
Remove-Item -ErrorAction SilentlyContinue "$temp\dbatools-$branch" -Recurse -Force
Remove-Item -ErrorAction SilentlyContinue "$temp\dbatools-old" -Recurse -Force
$null = New-Item "$temp\dbatools-old" -ItemType Directory
$shell = New-Object -ComObject Shell.Application
$zipPackage = $shell.NameSpace($zipfile)
$destinationFolder = $shell.NameSpace($temp)
$destinationFolder.CopyHere($zipPackage.Items())

Write-LocalMessage -Message "Applying Update"
Write-LocalMessage -Message "1) Backing up previous installation"
Copy-Item -Path "$Path\*" -Destination "$temp\dbatools-old" -ErrorAction Stop
try {
    Write-LocalMessage -Message "2) Cleaning up installation directory"
    Remove-Item "$Path\*" -Recurse -Force -ErrorAction Stop
} catch {
    Write-LocalMessage -Message @"
Failed to clean up installation directory, rolling back update.
This usually has one of two causes:
- Insufficient privileges (need to run as admin)
- A file is locked - generally a dll file from having the module imported in some process.

You can run the following line before importing dbatools to prevent file locking:
`$dbatools_copydllmode = `$true
But it increases the time needed to import the module, so we only recommend using it for updates.

Exception:
$_
"@
    Copy-Item -Path "$temp\dbatools-old\*" -Destination $path -ErrorAction Ignore -Recurse
    Remove-Item "$temp\dbatools-old" -Recurse -Force
    return
}
Write-LocalMessage -Message "3) Setting up current version"
Move-Item -Path "$temp\dbatools-$branch\*" -Destination $path -ErrorAction SilentlyContinue -Force
Remove-Item -Path "$temp\dbatools-$branch" -Recurse -Force
Remove-Item "$temp\dbatools-old" -Recurse -Force
Remove-Item -Path $zipfile -Recurse -Force

Write-LocalMessage -Message "Done! Please report any bugs to dbatools.io/issues or [email protected]."
if (Get-Module dbatools) {
    Write-LocalMessage -Message @"

Please restart PowerShell before working with dbatools.
"@
} else {
    Import-Module "$path\dbatools.psd1" -Force
    Write-LocalMessage @"

dbatools v $((Get-Module dbatools).Version)
# Commands available: $((Get-Command -Module dbatools -CommandType Function | Measure-Object).Count)

"@
}
[Net.ServicePointManager]::SecurityProtocol = $currentVersionTls
Write-LocalMessage -Message "`n`nIf you experience any function missing errors after update, please restart PowerShell or reload your profile."
# SIG # Begin signature block
# MIIcYgYJKoZIhvcNAQcCoIIcUzCCHE8CAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUBX7xyD/g2AIoCKG+yQp8AF7/
# +GuggheRMIIFGjCCBAKgAwIBAgIQAsF1KHTVwoQxhSrYoGRpyjANBgkqhkiG9w0B
# AQsFADByMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYD
# VQQLExB3d3cuZGlnaWNlcnQuY29tMTEwLwYDVQQDEyhEaWdpQ2VydCBTSEEyIEFz
# c3VyZWQgSUQgQ29kZSBTaWduaW5nIENBMB4XDTE3MDUwOTAwMDAwMFoXDTIwMDUx
# MzEyMDAwMFowVzELMAkGA1UEBhMCVVMxETAPBgNVBAgTCFZpcmdpbmlhMQ8wDQYD
# VQQHEwZWaWVubmExETAPBgNVBAoTCGRiYXRvb2xzMREwDwYDVQQDEwhkYmF0b29s
# czCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAI8ng7JxnekL0AO4qQgt
# Kr6p3q3SNOPh+SUZH+SyY8EA2I3wR7BMoT7rnZNolTwGjUXn7bRC6vISWg16N202
# 1RBWdTGW2rVPBVLF4HA46jle4hcpEVquXdj3yGYa99ko1w2FOWzLjKvtLqj4tzOh
# K7wa/Gbmv0Si/FU6oOmctzYMI0QXtEG7lR1HsJT5kywwmgcjyuiN28iBIhT6man0
# Ib6xKDv40PblKq5c9AFVldXUGVeBJbLhcEAA1nSPSLGdc7j4J2SulGISYY7ocuX3
# tkv01te72Mv2KkqqpfkLEAQjXgtM0hlgwuc8/A4if+I0YtboCMkVQuwBpbR9/6ys
# Z+sCAwEAAaOCAcUwggHBMB8GA1UdIwQYMBaAFFrEuXsqCqOl6nEDwGD5LfZldQ5Y
# MB0GA1UdDgQWBBRcxSkFqeA3vvHU0aq2mVpFRSOdmjAOBgNVHQ8BAf8EBAMCB4Aw
# EwYDVR0lBAwwCgYIKwYBBQUHAwMwdwYDVR0fBHAwbjA1oDOgMYYvaHR0cDovL2Ny
# bDMuZGlnaWNlcnQuY29tL3NoYTItYXNzdXJlZC1jcy1nMS5jcmwwNaAzoDGGL2h0
# dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9zaGEyLWFzc3VyZWQtY3MtZzEuY3JsMEwG
# A1UdIARFMEMwNwYJYIZIAYb9bAMBMCowKAYIKwYBBQUHAgEWHGh0dHBzOi8vd3d3
# LmRpZ2ljZXJ0LmNvbS9DUFMwCAYGZ4EMAQQBMIGEBggrBgEFBQcBAQR4MHYwJAYI
# KwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmRpZ2ljZXJ0LmNvbTBOBggrBgEFBQcwAoZC
# aHR0cDovL2NhY2VydHMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0U0hBMkFzc3VyZWRJ
# RENvZGVTaWduaW5nQ0EuY3J0MAwGA1UdEwEB/wQCMAAwDQYJKoZIhvcNAQELBQAD
# ggEBANuBGTbzCRhgG0Th09J0m/qDqohWMx6ZOFKhMoKl8f/l6IwyDrkG48JBkWOA
# QYXNAzvp3Ro7aGCNJKRAOcIjNKYef/PFRfFQvMe07nQIj78G8x0q44ZpOVCp9uVj
# sLmIvsmF1dcYhOWs9BOG/Zp9augJUtlYpo4JW+iuZHCqjhKzIc74rEEiZd0hSm8M
# asshvBUSB9e8do/7RhaKezvlciDaFBQvg5s0fICsEhULBRhoyVOiUKUcemprPiTD
# xh3buBLuN0bBayjWmOMlkG1Z6i8DUvWlPGz9jiBT3ONBqxXfghXLL6n8PhfppBhn
# daPQO8+SqF5rqrlyBPmRRaTz2GQwggUwMIIEGKADAgECAhAECRgbX9W7ZnVTQ7Vv
# lVAIMA0GCSqGSIb3DQEBCwUAMGUxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdp
# Q2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xJDAiBgNVBAMTG0Rp
# Z2lDZXJ0IEFzc3VyZWQgSUQgUm9vdCBDQTAeFw0xMzEwMjIxMjAwMDBaFw0yODEw
# MjIxMjAwMDBaMHIxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMx
# GTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xMTAvBgNVBAMTKERpZ2lDZXJ0IFNI
# QTIgQXNzdXJlZCBJRCBDb2RlIFNpZ25pbmcgQ0EwggEiMA0GCSqGSIb3DQEBAQUA
# A4IBDwAwggEKAoIBAQD407Mcfw4Rr2d3B9MLMUkZz9D7RZmxOttE9X/lqJ3bMtdx
# 6nadBS63j/qSQ8Cl+YnUNxnXtqrwnIal2CWsDnkoOn7p0WfTxvspJ8fTeyOU5JEj
# lpB3gvmhhCNmElQzUHSxKCa7JGnCwlLyFGeKiUXULaGj6YgsIJWuHEqHCN8M9eJN
# YBi+qsSyrnAxZjNxPqxwoqvOf+l8y5Kh5TsxHM/q8grkV7tKtel05iv+bMt+dDk2
# DZDv5LVOpKnqagqrhPOsZ061xPeM0SAlI+sIZD5SlsHyDxL0xY4PwaLoLFH3c7y9
# hbFig3NBggfkOItqcyDQD2RzPJ6fpjOp/RnfJZPRAgMBAAGjggHNMIIByTASBgNV
# HRMBAf8ECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIBhjATBgNVHSUEDDAKBggrBgEF
# BQcDAzB5BggrBgEFBQcBAQRtMGswJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmRp
# Z2ljZXJ0LmNvbTBDBggrBgEFBQcwAoY3aHR0cDovL2NhY2VydHMuZGlnaWNlcnQu
# Y29tL0RpZ2lDZXJ0QXNzdXJlZElEUm9vdENBLmNydDCBgQYDVR0fBHoweDA6oDig
# NoY0aHR0cDovL2NybDQuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0QXNzdXJlZElEUm9v
# dENBLmNybDA6oDigNoY0aHR0cDovL2NybDMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0
# QXNzdXJlZElEUm9vdENBLmNybDBPBgNVHSAESDBGMDgGCmCGSAGG/WwAAgQwKjAo
# BggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNlcnQuY29tL0NQUzAKBghghkgB
# hv1sAzAdBgNVHQ4EFgQUWsS5eyoKo6XqcQPAYPkt9mV1DlgwHwYDVR0jBBgwFoAU
# Reuir/SSy4IxLVGLp6chnfNtyA8wDQYJKoZIhvcNAQELBQADggEBAD7sDVoks/Mi
# 0RXILHwlKXaoHV0cLToaxO8wYdd+C2D9wz0PxK+L/e8q3yBVN7Dh9tGSdQ9RtG6l
# jlriXiSBThCk7j9xjmMOE0ut119EefM2FAaK95xGTlz/kLEbBw6RFfu6r7VRwo0k
# riTGxycqoSkoGjpxKAI8LpGjwCUR4pwUR6F6aGivm6dcIFzZcbEMj7uo+MUSaJ/P
# QMtARKUT8OZkDCUIQjKyNookAv4vcn4c10lFluhZHen6dGRrsutmQ9qzsIzV6Q3d
# 9gEgzpkxYz0IGhizgZtPxpMQBvwHgfqL2vmCSfdibqFT+hKUGIUukpHqaGxEMrJm
# oecYpJpkUe8wggZqMIIFUqADAgECAhADAZoCOv9YsWvW1ermF/BmMA0GCSqGSIb3
# DQEBBQUAMGIxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAX
# BgNVBAsTEHd3dy5kaWdpY2VydC5jb20xITAfBgNVBAMTGERpZ2lDZXJ0IEFzc3Vy
# ZWQgSUQgQ0EtMTAeFw0xNDEwMjIwMDAwMDBaFw0yNDEwMjIwMDAwMDBaMEcxCzAJ
# BgNVBAYTAlVTMREwDwYDVQQKEwhEaWdpQ2VydDElMCMGA1UEAxMcRGlnaUNlcnQg
# VGltZXN0YW1wIFJlc3BvbmRlcjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
# ggEBAKNkXfx8s+CCNeDg9sYq5kl1O8xu4FOpnx9kWeZ8a39rjJ1V+JLjntVaY1sC
# SVDZg85vZu7dy4XpX6X51Id0iEQ7Gcnl9ZGfxhQ5rCTqqEsskYnMXij0ZLZQt/US
# s3OWCmejvmGfrvP9Enh1DqZbFP1FI46GRFV9GIYFjFWHeUhG98oOjafeTl/iqLYt
# WQJhiGFyGGi5uHzu5uc0LzF3gTAfuzYBje8n4/ea8EwxZI3j6/oZh6h+z+yMDDZb
# esF6uHjHyQYuRhDIjegEYNu8c3T6Ttj+qkDxss5wRoPp2kChWTrZFQlXmVYwk/PJ
# YczQCMxr7GJCkawCwO+k8IkRj3cCAwEAAaOCAzUwggMxMA4GA1UdDwEB/wQEAwIH
# gDAMBgNVHRMBAf8EAjAAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMIMIIBvwYDVR0g
# BIIBtjCCAbIwggGhBglghkgBhv1sBwEwggGSMCgGCCsGAQUFBwIBFhxodHRwczov
# L3d3dy5kaWdpY2VydC5jb20vQ1BTMIIBZAYIKwYBBQUHAgIwggFWHoIBUgBBAG4A
# eQAgAHUAcwBlACAAbwBmACAAdABoAGkAcwAgAEMAZQByAHQAaQBmAGkAYwBhAHQA
# ZQAgAGMAbwBuAHMAdABpAHQAdQB0AGUAcwAgAGEAYwBjAGUAcAB0AGEAbgBjAGUA
# IABvAGYAIAB0AGgAZQAgAEQAaQBnAGkAQwBlAHIAdAAgAEMAUAAvAEMAUABTACAA
# YQBuAGQAIAB0AGgAZQAgAFIAZQBsAHkAaQBuAGcAIABQAGEAcgB0AHkAIABBAGcA
# cgBlAGUAbQBlAG4AdAAgAHcAaABpAGMAaAAgAGwAaQBtAGkAdAAgAGwAaQBhAGIA
# aQBsAGkAdAB5ACAAYQBuAGQAIABhAHIAZQAgAGkAbgBjAG8AcgBwAG8AcgBhAHQA
# ZQBkACAAaABlAHIAZQBpAG4AIABiAHkAIAByAGUAZgBlAHIAZQBuAGMAZQAuMAsG
# CWCGSAGG/WwDFTAfBgNVHSMEGDAWgBQVABIrE5iymQftHt+ivlcNK2cCzTAdBgNV
# HQ4EFgQUYVpNJLZJMp1KKnkag0v0HonByn0wfQYDVR0fBHYwdDA4oDagNIYyaHR0
# cDovL2NybDMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0QXNzdXJlZElEQ0EtMS5jcmww
# OKA2oDSGMmh0dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEFzc3VyZWRJ
# RENBLTEuY3JsMHcGCCsGAQUFBwEBBGswaTAkBggrBgEFBQcwAYYYaHR0cDovL29j
# c3AuZGlnaWNlcnQuY29tMEEGCCsGAQUFBzAChjVodHRwOi8vY2FjZXJ0cy5kaWdp
# Y2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURDQS0xLmNydDANBgkqhkiG9w0BAQUF
# AAOCAQEAnSV+GzNNsiaBXJuGziMgD4CH5Yj//7HUaiwx7ToXGXEXzakbvFoWOQCd
# 42yE5FpA+94GAYw3+puxnSR+/iCkV61bt5qwYCbqaVchXTQvH3Gwg5QZBWs1kBCg
# e5fH9j/n4hFBpr1i2fAnPTgdKG86Ugnw7HBi02JLsOBzppLA044x2C/jbRcTBu7k
# A7YUq/OPQ6dxnSHdFMoVXZJB2vkPgdGZdA0mxA5/G7X1oPHGdwYoFenYk+VVFvC7
# Cqsc21xIJ2bIo4sKHOWV2q7ELlmgYd3a822iYemKC23sEhi991VUQAOSK2vCUcIK
# SK+w1G7g9BQKOhvjjz3Kr2qNe9zYRDCCBs0wggW1oAMCAQICEAb9+QOWA63qAArr
# Pye7uhswDQYJKoZIhvcNAQEFBQAwZTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERp
# Z2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEkMCIGA1UEAxMb
# RGlnaUNlcnQgQXNzdXJlZCBJRCBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTIx
# MTExMDAwMDAwMFowYjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IElu
# YzEZMBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEhMB8GA1UEAxMYRGlnaUNlcnQg
# QXNzdXJlZCBJRCBDQS0xMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
# 6IItmfnKwkKVpYBzQHDSnlZUXKnE0kEGj8kz/E1FkVyBn+0snPgWWd+etSQVwpi5
# tHdJ3InECtqvy15r7a2wcTHrzzpADEZNk+yLejYIA6sMNP4YSYL+x8cxSIB8HqIP
# kg5QycaH6zY/2DDD/6b3+6LNb3Mj/qxWBZDwMiEWicZwiPkFl32jx0PdAug7Pe2x
# QaPtP77blUjE7h6z8rwMK5nQxl0SQoHhg26Ccz8mSxSQrllmCsSNvtLOBq6thG9I
# hJtPQLnxTPKvmPv2zkBdXPao8S+v7Iki8msYZbHBc63X8djPHgp0XEK4aH631XcK
# J1Z8D2KkPzIUYJX9BwSiCQIDAQABo4IDejCCA3YwDgYDVR0PAQH/BAQDAgGGMDsG
# A1UdJQQ0MDIGCCsGAQUFBwMBBggrBgEFBQcDAgYIKwYBBQUHAwMGCCsGAQUFBwME
# BggrBgEFBQcDCDCCAdIGA1UdIASCAckwggHFMIIBtAYKYIZIAYb9bAABBDCCAaQw
# OgYIKwYBBQUHAgEWLmh0dHA6Ly93d3cuZGlnaWNlcnQuY29tL3NzbC1jcHMtcmVw
# b3NpdG9yeS5odG0wggFkBggrBgEFBQcCAjCCAVYeggFSAEEAbgB5ACAAdQBzAGUA
# IABvAGYAIAB0AGgAaQBzACAAQwBlAHIAdABpAGYAaQBjAGEAdABlACAAYwBvAG4A
# cwB0AGkAdAB1AHQAZQBzACAAYQBjAGMAZQBwAHQAYQBuAGMAZQAgAG8AZgAgAHQA
# aABlACAARABpAGcAaQBDAGUAcgB0ACAAQwBQAC8AQwBQAFMAIABhAG4AZAAgAHQA
# aABlACAAUgBlAGwAeQBpAG4AZwAgAFAAYQByAHQAeQAgAEEAZwByAGUAZQBtAGUA
# bgB0ACAAdwBoAGkAYwBoACAAbABpAG0AaQB0ACAAbABpAGEAYgBpAGwAaQB0AHkA
# IABhAG4AZAAgAGEAcgBlACAAaQBuAGMAbwByAHAAbwByAGEAdABlAGQAIABoAGUA
# cgBlAGkAbgAgAGIAeQAgAHIAZQBmAGUAcgBlAG4AYwBlAC4wCwYJYIZIAYb9bAMV
# MBIGA1UdEwEB/wQIMAYBAf8CAQAweQYIKwYBBQUHAQEEbTBrMCQGCCsGAQUFBzAB
# hhhodHRwOi8vb2NzcC5kaWdpY2VydC5jb20wQwYIKwYBBQUHMAKGN2h0dHA6Ly9j
# YWNlcnRzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEFzc3VyZWRJRFJvb3RDQS5jcnQw
# gYEGA1UdHwR6MHgwOqA4oDaGNGh0dHA6Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9EaWdp
# Q2VydEFzc3VyZWRJRFJvb3RDQS5jcmwwOqA4oDaGNGh0dHA6Ly9jcmw0LmRpZ2lj
# ZXJ0LmNvbS9EaWdpQ2VydEFzc3VyZWRJRFJvb3RDQS5jcmwwHQYDVR0OBBYEFBUA
# EisTmLKZB+0e36K+Vw0rZwLNMB8GA1UdIwQYMBaAFEXroq/0ksuCMS1Ri6enIZ3z
# bcgPMA0GCSqGSIb3DQEBBQUAA4IBAQBGUD7Jtygkpzgdtlspr1LPUukxR6tWXHvV
# DQtBs+/sdR90OPKyXGGinJXDUOSCuSPRujqGcq04eKx1XRcXNHJHhZRW0eu7NoR3
# zCSl8wQZVann4+erYs37iy2QwsDStZS9Xk+xBdIOPRqpFFumhjFiqKgz5Js5p8T1
# zh14dpQlc+Qqq8+cdkvtX8JLFuRLcEwAiR78xXm8TBJX/l/hHrwCXaj++wc4Tw3G
# XZG5D2dFzdaD7eeSDY2xaYxP+1ngIw/Sqq4AfO6cQg7PkdcntxbuD8O9fAqg7iwI
# VYUiuOsYGk38KiGtSTGDR5V3cdyxG0tLHBCcdxTBnU8vWpUIKRAmMYIEOzCCBDcC
# AQEwgYYwcjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcG
# A1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTExMC8GA1UEAxMoRGlnaUNlcnQgU0hBMiBB
# c3N1cmVkIElEIENvZGUgU2lnbmluZyBDQQIQAsF1KHTVwoQxhSrYoGRpyjAJBgUr
# DgMCGgUAoHgwGAYKKwYBBAGCNwIBDDEKMAigAoAAoQKAADAZBgkqhkiG9w0BCQMx
# DAYKKwYBBAGCNwIBBDAcBgorBgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkq
# hkiG9w0BCQQxFgQUJG2qmbkxMSfcmauDcSrIyGH89VYwDQYJKoZIhvcNAQEBBQAE
# ggEAEEMPAz1Jq4IhIzcxlG2P1bTEggImMGFtnHiZvhApxmu/cb9xxVLSSGhc/iql
# 2/FDM/HSjlxhFqNeY1y67ADhptftY94+Lng1hW8tPtq1RdFEgb1BOmQj6ZNEfPXl
# artCM9uA7uGv8t45I9TklFlljaOqD41gTpGqjPux9bJTPtQLhFXFddMEv9BqKTIX
# MWea5psrRM+pp8LqpYPty9pMomNRqiX86hKF4VhUNSkb7Dw4qNv1CvoeHV/OPok3
# kSgKlOgkY08eQE9/fdQebqvLMQbFvT2QH3ZdL2naqU+JfOb6yNX9YCdVNOasBvwc
# qbftY7bkvXjVavpitMcVqVwZPqGCAg8wggILBgkqhkiG9w0BCQYxggH8MIIB+AIB
# ATB2MGIxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNV
# BAsTEHd3dy5kaWdpY2VydC5jb20xITAfBgNVBAMTGERpZ2lDZXJ0IEFzc3VyZWQg
# SUQgQ0EtMQIQAwGaAjr/WLFr1tXq5hfwZjAJBgUrDgMCGgUAoF0wGAYJKoZIhvcN
# AQkDMQsGCSqGSIb3DQEHATAcBgkqhkiG9w0BCQUxDxcNMTkwMTA4MTkwNzM3WjAj
# BgkqhkiG9w0BCQQxFgQU47h5ZKo0VO6Ks83Bq9vU3j1z9lIwDQYJKoZIhvcNAQEB
# BQAEggEAREULfDxNxnxrXiP8dxqv2MW0Kp62p2gjgCYcpqqYTn4QTOprT6oEjtfY
# 6fZXQghR3haZCFgcHrnfG34bB2kaCYoiW6nlS2paBpOrqOQYn8n/nY3mfG5ToRoY
# H/5OuhdCmbYKK3L1oj3o0ZTBiWSQZZS5IlSDek3+RDaNLWca/n95oc1VXuUwmchq
# a8mx3caEfdloZlVZxcCo+/9Waz8vI5XKKm5ybvw0EZxEd6T3ZmFWy5JCaljJiBv8
# DvR6aUjScpTVJbYdomsnYt+csSsmVWGF0uhP+2IGq1CHdecgqNrLq9R59zXDGLOl
# XV4zj7+0mwKEEsQBe7Ad3qszPgc6pg==
# SIG # End signature block
tools\dbatools\internal\configurations\configuration.ps1
<#

#-------------------------#
# Warning Warning Warning #
#-------------------------#

This is the global configuration management file.

DO NOT EDIT THIS FILE!!!!!
Disobedience shall be answered by the wrath of Fred.
You've been warned.
;)

The purpose of this file is to manage the configuration system.
That means, messing with this may mess with every function using this infrastructure.
Don't, unless you know what you do.

#---------------------------------------#
# Implementing the configuration system #
#---------------------------------------#

The configuration system is designed, to keep as much hard coded configuration out of the functions.
Instead we keep it in a central location: The Configuration store (= this folder).

In Order to put something here, either find a configuration file whose topic suits you and add configuration there,
or create your own file. The configuration system is loaded last during module import process, so you have access to all
that dbatools has to offer (Keep module load times in mind though).

Examples are better than a thousand words:

a) Setting the configuration value
# Put this in a configuration file in this folder
Set-DbatoolsConfig -Name 'Path.DbatoolsLog' -Value "$($env:AppData)\PowerShell\dbatools" -Initialize -Description "Sopmething meaningful here"

b) Retrieving the configuration value in your function
# Put this in the function that uses this setting
$path = Get-DbatoolsConfigValue -Name 'Path.DbatoolsLog' -FallBack $env:temp

# Explanation #
#-------------#

In step a), which is run during module import, we assign the configuration of the name 'Path.DbatoolsLog' the value "$($env:AppData)\PowerShell\dbatools"
Unless there already IS a value set to this name (that's what the '-Default' switch is doing).
That means, that if a user had a different configuration value in his profile, that value will win. Userchoice over preset.
ALL configurations defined by the module should be 'default' values.

In step b), which will be run whenever the function is called within which it is written, we retrieve the value stored behind the name 'Path.DbatoolsLog'.
If there is nothing there (for example, if the user accidentally removed or nulled the configuration), then it will fall back to using "$($env:temp)\dbatools.log"

#>

#region Paths
$script:path_RegistryUserDefault = "HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\Config\Default"
$script:path_RegistryUserEnforced = "HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\Config\Enforced"
$script:path_RegistryMachineDefault = "HKLM:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\Config\Default"
$script:path_RegistryMachineEnforced = "HKLM:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\Config\Enforced"
$psVersionName = "WindowsPowerShell"
if ($PSVersionTable.PSVersion.Major -ge 6) { $psVersionName = "PowerShell" }

#region User Local
if ($IsLinux -or $IsMacOs)
{
    # Defaults to $Env:XDG_CONFIG_HOME on Linux or MacOS ($HOME/.config/)
    $fileUserLocal = $Env:XDG_CONFIG_HOME
    if (-not $fileUserLocal) { $fileUserLocal = Join-Path $HOME .config/ }
    
    $script:path_FileUserLocal = Join-DbaPath $fileUserLocal $psVersionName "dbatools/"
}
else
{
    # Defaults to $Env:LocalAppData on Windows
    $script:path_FileUserLocal = Join-Path $Env:LocalAppData "$psVersionName\dbatools\Config"
    if (-not $script:path_FileUserLocal) { $script:path_FileUserLocal = Join-Path ([Environment]::GetFolderPath("LocalApplicationData")) "$psVersionName\dbatools\Config" }
}
#endregion User Local

#region User Shared
if ($IsLinux -or $IsMacOs)
{
    # Defaults to the first value in $Env:XDG_CONFIG_DIRS on Linux or MacOS (or $HOME/.local/share/)
    $fileUserShared = @($Env:XDG_CONFIG_DIRS -split ([IO.Path]::PathSeparator))[0]
    if (-not $fileUserShared) { $fileUserShared = Join-Path $HOME .local/share/ }
    
    $script:path_FileUserShared = Join-DbaPath $fileUserShared $psVersionName "dbatools/"
    $script:AppData = $fileUserShared
}
else
{
    # Defaults to $Env:AppData on Windows
    $script:path_FileUserShared = Join-DbaPath $Env:AppData $psVersionName "dbatools" "Config"
    $script:AppData = $Env:APPDATA
    if (-not $Env:AppData)
    {
        $script:path_FileUserShared = Join-DbaPath ([Environment]::GetFolderPath("ApplicationData")) $psVersionName "dbatools" "Config"
        $script:AppData = [Environment]::GetFolderPath("ApplicationData")
    }
}
#endregion User Shared

#region System
if ($IsLinux -or $IsMacOs)
{
    # Defaults to /etc/xdg elsewhere
    $XdgConfigDirs = $Env:XDG_CONFIG_DIRS -split ([IO.Path]::PathSeparator) | Where-Object { $_ -and (Test-Path $_) }
    if ($XdgConfigDirs.Count -gt 1) { $basePath = $XdgConfigDirs[1] }
    else { $basePath = "/etc/xdg/" }
    $script:path_FileSystem = Join-DbaPath $basePath $psVersionName "dbatools/"
}
else
{
    # Defaults to $Env:ProgramData on Windows
    $script:path_FileSystem = Join-DbaPath $Env:ProgramData $psVersionName "dbatools" "Config"
    if (-not $script:path_FileSystem) { $script:path_FileSystem = Join-DbaPath ([Environment]::GetFolderPath("CommonApplicationData")) $psVersionName "dbatools" "Config" }
}
#endregion System

#region Special Paths
# $script:AppData is already OS localized
$script:path_Logging = Join-DbaPath $script:AppData $psVersionName "dbatools" "Logs"
$script:path_typedata = Join-DbaPath $script:AppData $psVersionName "dbatools" "TypeData"
#endregion Special Paths
#endregion Paths

# Determine Registry Availability
$script:NoRegistry = $false
if (($PSVersionTable.PSVersion.Major -ge 6) -and ($PSVersionTable.OS -notlike "*Windows*"))
{
    $script:NoRegistry = $true
}

$configpath = Resolve-Path "$script:PSModuleRoot\internal\configurations"

# Import configuration validation
foreach ($file in (Get-ChildItem -Path (Resolve-Path "$configpath\validation")))
{
    if ($script:doDotSource) { . $file.FullName }
    else { . ([scriptblock]::Create([io.file]::ReadAllText($file.FullName))) }
}

# Import other configuration files
foreach ($file in (Get-ChildItem -Path (Resolve-Path "$configpath\settings")))
{
    if ($script:doDotSource) { . $file.FullName }
    else { . ([scriptblock]::Create([io.file]::ReadAllText($file.FullName))) }
}

if (-not [Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::ImportFromRegistryDone)
{
    # Read config from all settings
    $config_hash = Read-DbatoolsConfigPersisted -Scope 127
    
    foreach ($value in $config_hash.Values)
    {
        try
        {
            if (-not $value.KeepPersisted) { Set-DbatoolsConfig -FullName $value.FullName -Value $value.Value -EnableException }
            else { Set-DbatoolsConfig -FullName $value.FullName -PersistedValue $value.Value -PersistedType $value.Type -EnableException }
            [Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations[$value.FullName.ToLower()].PolicySet = $value.Policy
            [Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations[$value.FullName.ToLower()].PolicyEnforced = $value.Enforced
        }
        catch { }
    }
    
    if ($null -ne $global:dbatools_config)
    {
        if ($global:dbatools_config.GetType().FullName -eq "System.Management.Automation.ScriptBlock")
        {
            [System.Management.Automation.ScriptBlock]::Create($global:dbatools_config.ToString()).Invoke()
        }
    }
    
    [Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::ImportFromRegistryDone = $true
}
tools\dbatools\internal\configurations\settings\assets.ps1
<#
This is designed for all online assets you need configurations for.
#>

# The default path where dbatools stores persistent data
Set-DbatoolsConfig -FullName 'assets.sqlbuildreference' -Value 'https://sqlcollaborative.github.io/assets/dbatools-buildref-index.json' -Initialize -Validation string -Handler { } -Description "The url where dbatools fetches the up to date buildreference index (e.g. for Get-DbaBuildReference)"
tools\dbatools\internal\configurations\settings\commands.ps1
# Write-DbaDataTable: Settings for ConvertTo-DbaDataTable
Set-DbatoolsConfig -FullName 'commands.write-dbadatatable.timespantype' -Value 'TotalMilliseconds' -Initialize -Validation string -Description "When passing random objects at Write-DbaDataTable, it will convert them to a DataTable before writing it, using ConvertTo-DbaDataTable. This setting controls how Timespan objects are converted"
Set-DbatoolsConfig -FullName 'commands.write-dbadatatable.sizetype' -Value 'Int64' -Initialize -Validation string -Description "When passing random objects at Write-DbaDataTable, it will convert them to a DataTable before writing it, using ConvertTo-DbaDataTable. This setting controls how Size objects are converted"
Set-DbatoolsConfig -FullName 'commands.write-dbadatatable.ignorenull' -Value $false -Initialize -Validation bool -Description "When passing random objects at Write-DbaDataTable, it will convert them to a DataTable before writing it, using ConvertTo-DbaDataTable. This setting controls whether null objects will be ignored, rather than generating an empty row"
Set-DbatoolsConfig -FullName 'commands.write-dbadatatable.raw' -Value $false -Initialize -Validation bool -Description "When passing random objects at Write-DbaDataTable, it will convert them to a DataTable before writing it, using ConvertTo-DbaDataTable. This setting controls whether all properties will be stored as string (`$true) or as much as possible in their native type (`$false)"
tools\dbatools\internal\configurations\settings\computermanagement.ps1
<#
This is designed for all things that control how anything that caches acts
#>

# Sets the default timeout on bad connections
Set-DbatoolsConfig -FullName 'ComputerManagement.BadConnectionTimeout' -Value (New-TimeSpan -Minutes 15) -Initialize -Validation timespan -Handler { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::BadConnectionTimeout = $args[0] } -Description 'The timeout used on bad computer management connections. When a connection using a protocol fails, it will not be reattempted for this timespan.'

# Disable the management cache entire
Set-DbatoolsConfig -FullName 'ComputerManagement.Cache.Disable.All' -Value $false -Initialize -Validation bool -Handler { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::DisableCache = $args[0] } -Description 'Globally disables all caching done by the Computer Management functions'

# Disables the caching of bad credentials, which is kept in order to avoid reusing them
Set-DbatoolsConfig -FullName 'ComputerManagement.Cache.Disable.BadCredentialList' -Value $false -Initialize -Validation bool -Handler { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::DisableBadCredentialCache = $args[0] } -Description 'Disables the caching of bad credentials. dbatools caches bad logon credentials for wmi/cim and will not reuse them.'

# Disables reuse of CIM Sessions
Set-DbatoolsConfig -FullName 'ComputerManagement.Cache.Disable.CimPersistence' -Value $false -Initialize -Validation bool -Handler { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::DisableCimPersistence = $args[0] } -Description 'Disables the reuse of Cim Sessions. Setting this config to "true" will hurt Computer Management Performance, but may be necessary in some rare cases'

# Disables automatic caching of working credentials
Set-DbatoolsConfig -FullName 'ComputerManagement.Cache.Disable.CredentialAutoRegister' -Value $false -Initialize -Validation bool -Handler { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::DisableCredentialAutoRegister = $args[0] } -Description 'Disables the automatic registration of working credentials. dbatools will caches the last working credential when connecting using wmi/cim and will use those rather than using known bad credentials'

# Enables automatic failover of credentials. If enabled, CM will use known-to-work credentials in case of non-working credentials
Set-DbatoolsConfig -FullName 'ComputerManagement.Cache.Enable.CredentialFailover' -Value $false -Initialize -Validation bool -Handler { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::EnableCredentialFailover = $args[0] } -Description 'Enables automatically failing over to known to work credentials, when specified credentials will not work.'

# Force-Overrides explicit credentials with cached-as-working credentials
Set-DbatoolsConfig -FullName 'ComputerManagement.Cache.Force.OverrideExplicitCredential' -Value $false -Initialize -Validation bool -Handler { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::OverrideExplicitCredential = $args[0] } -Description 'Enabling this will force the use of the last credentials known to work, rather than even trying explicit credentials.'

# Disables or enables globally which Remote Management channels can be used
Set-DbatoolsConfig -FullName 'ComputerManagement.Type.Disable.CimRM' -Value $false -Initialize -Validation bool -Handler { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::DisableConnectionCimRM = $args[0] } -Description 'Globally disables all connections using Cim over WinRM'
Set-DbatoolsConfig -FullName 'ComputerManagement.Type.Disable.CimDCOM' -Value $false -Initialize -Validation bool -Handler { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::DisableConnectionCimDCOM = $args[0] } -Description 'Globally disables all connections using Cim over DCOM'
Set-DbatoolsConfig -FullName 'ComputerManagement.Type.Disable.WMI' -Value $true -Initialize -Validation bool -Handler { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::DisableConnectionWMI = $args[0] } -Description 'Globally disables all connections using WMI'
Set-DbatoolsConfig -FullName 'ComputerManagement.Type.Disable.PowerShellRemoting' -Value $true -Initialize -Validation bool -Handler { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::DisableConnectionPowerShellRemoting = $args[0] } -Description 'Globally disables all connections using PowerShell Remoting'
#TODO: Implement Handler for type validation
tools\dbatools\internal\configurations\settings\formatting.ps1
# The default formatting style for dates
Set-DbatoolsConfig -FullName 'Formatting.Date' -Value "dd MMM yyyy" -Initialize -Validation string -Handler { [Sqlcollaborative.Dbatools.Utility.UtilityHost]::FormatDate = $args[0] } -Description "The default formatting of Dates"

# The default formatting style for full datetime objects
Set-DbatoolsConfig -FullName 'Formatting.DateTime' -Value "yyyy-MM-dd HH:mm:ss.fff" -Initialize -Validation string -Handler { [Sqlcollaborative.Dbatools.Utility.UtilityHost]::FormatDateTime = $args[0] } -Description "The default formatting style for full datetime objects"

# The default formatting style for time objects
Set-DbatoolsConfig -FullName 'Formatting.Time' -Value "HH:mm:ss" -Initialize -Validation string -Handler { [Sqlcollaborative.Dbatools.Utility.UtilityHost]::FormatTime = $args[0] } -Description "The default formatting style for full datetime objects"

# Disable custom Datetime formats
Set-DbatoolsConfig -FullName 'Formatting.Disable.CustomDateTime' -Value $false -Initialize -Validation bool -Handler { [Sqlcollaborative.Dbatools.Utility.UtilityHost]::DisableCustomDateTime = $args[0] } -Description "Controls whether custom DateTime formats are used or whether to default back to DateTime standard."

# Disable custom TimeSpan formats
Set-DbatoolsConfig -FullName 'Formatting.Disable.CustomTimeSpan' -Value $false -Initialize -Validation bool -Handler { [Sqlcollaborative.Dbatools.Utility.UtilityHost]::DisableCustomTimeSpan = $args[0] } -Description "Controls whether custom TimeSpan formats are used or whether to default back to DateTime standard."

Set-DbatoolsConfig -FullName 'Formatting.size.style' -Value ([Sqlcollaborative.Dbatools.Utility.SizeStyle]::Dynamic) -Initialize -Validation sizestyle -Handler { [Sqlcollaborative.Dbatools.Utility.UtilityHost]::SizeStyle = $args[0] } -Description "Controls how size objects are displayed by default. Generally, their string representation is calculated to be user friendly (dynamic), can be updated to 'plain' number or a specific size. Can be overriden on a per-object basis."
Set-DbatoolsConfig -FullName 'Formatting.size.digits' -Value 2 -Initialize -Validation integer0to9 -Handler { [Sqlcollaborative.Dbatools.Utility.UtilityHost]::SizeDigits = $args[0] } -Description "How many digits are used when displaying a size object."
tools\dbatools\internal\configurations\settings\import.ps1
# Handle dotsourcing on import
Set-DbatoolsConfig -Name 'Import.DoDotSource' -Value $false -Initialize -Validation bool -Handler {
    try {
        if (-not (Test-Path "HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\System")) {
            $null = New-Item "HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\System" -ItemType Container -Force -ErrorAction Stop
        }
        if ($args[0]) {
            $null = New-ItemProperty "HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\System" -Name DoDotSource -PropertyType DWORD -Value 1 -Force -ErrorAction Stop
        } else {
            $null = New-ItemProperty "HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\System" -Name DoDotSource -PropertyType DWORD -Value 0 -Force -ErrorAction Stop
        }
        # Scope Boundary exception: $cfg is defined in Set-DbatoolsConfig
        Register-DbatoolsConfig -Config $cfg
    } catch {
        Write-Message -Level Warning -Message "Failed to apply configuration 'Import.DoDotSource'" -ErrorRecord $_ -Target 'Import.DoDotSource'
    }
} -Description "Causes the module to be imported using dotsourcing. Security policy may require it, also useful for debugging. This configuration setting persists across all PowerShell consoles for this user!"

# Handle dotsourcing on import
Set-DbatoolsConfig -Name 'Import.StrictSecurityMode' -Value $false -Initialize -Validation bool -Handler {
    try {
        if (-not (Test-Path "HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\System")) {
            $null = New-Item "HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\System" -ItemType Container -Force -ErrorAction Stop
        }
        if ($args[0]) {
            $null = New-ItemProperty "HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\System" -Name StrictSecurityMode -PropertyType DWORD -Value 1 -Force -ErrorAction Stop
        } else {
            $null = New-ItemProperty "HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\System" -Name StrictSecurityMode -PropertyType DWORD -Value 0 -Force -ErrorAction Stop
        }
        # Scope Boundary exception: $cfg is defined in Set-DbatoolsConfig
        Register-DbatoolsConfig -Config $cfg
    } catch {
        Write-Message -Level Warning -Message "Failed to apply configuration 'Import.StrictSecurityMode'" -ErrorRecord $_ -Target 'Import.StrictSecurityMode'
    }
} -Description "Causes the module to import its components only from the module directory. This makes it harder to update the module, but may be required by security policy. This configuration setting persists across all PowerShell consoles for this user!"

# Handle dotsourcing on import
Set-DbatoolsConfig -Name 'Import.AlwaysBuildLibrary' -Value $false -Initialize -Validation bool -Handler {
    try {
        if (-not (Test-Path "HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\System")) {
            $null = New-Item "HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\System" -ItemType Container -Force -ErrorAction Stop
        }
        if ($args[0]) {
            $null = New-ItemProperty "HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\System" -Name AlwaysBuildLibrary -PropertyType DWORD -Value 1 -Force -ErrorAction Stop
        } else {
            $null = New-ItemProperty "HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\System" -Name AlwaysBuildLibrary -PropertyType DWORD -Value 0 -Force -ErrorAction Stop
        }
        # Scope Boundary exception: $cfg is defined in Set-DbatoolsConfig
        Register-DbatoolsConfig -Config $cfg
    } catch {
        Write-Message -Level Warning -Message "Failed to apply configuration 'Import.AlwaysBuildLibrary'" -ErrorRecord $_ -Target 'Import.AlwaysBuildLibrary'
    }
} -Description "Causes the module to compile the library from source on every import. Of interest for developers only, as this imposes a significant increase in import time. This configuration setting persists across all PowerShell consoles for this user!"

# Handle dotsourcing on import
Set-DbatoolsConfig -Name 'Import.SerialImport' -Value $false -Initialize -Validation bool -Handler {
    try {
        if (-not (Test-Path "HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\System")) {
            $null = New-Item "HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\System" -ItemType Container -Force -ErrorAction Stop
        }
        if ($args[0]) {
            $null = New-ItemProperty "HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\System" -Name SerialImport -PropertyType DWORD -Value 1 -Force -ErrorAction Stop
        } else {
            $null = New-ItemProperty "HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\System" -Name SerialImport -PropertyType DWORD -Value 0 -Force -ErrorAction Stop
        }
        # Scope Boundary exception: $cfg is defined in Set-DbatoolsConfig
        Register-DbatoolsConfig -Config $cfg
    } catch {
        Write-Message -Level Warning -Message "Failed to apply configuration 'Import.SerialImport'" -ErrorRecord $_ -Target 'Import.SerialImport'
    }
} -Description "Enabling this will cause the module to perform import in a serial manner, not parallelizing anything. This will impose a significant delay on import, but reduces the CPU impact during import. Setting this for an unattended script may be useful to avoid resource alerts. Can be set on script level by placing the following code in the first line: '`$dbatools_serialimport = `$true'. This configuration setting persists across all PowerShell consoles for this user."

# Check for SqlPs
Set-DbatoolsConfig -Name 'Import.SqlpsCheck' -Value $true -Initialize -Validation bool -Description "Does not warn about sqlps being imported at the time of the dbatools import"
tools\dbatools\internal\configurations\settings\logging.ps1
<#
This is for all configuration values regarding the logging system

NOTES:
- All these configurations should have a handler, as the logging system relies entirely on static fields for performance reasons
- If you want to change the default values, change them both here AND in the C# library
#>

Set-DbatoolsConfig -FullName 'Logging.MaxErrorCount' -Value 128 -Initialize -Validation integerpositive -Handler { [Sqlcollaborative.Dbatools.Message.LogHost]::MaxErrorCount = $args[0] } -Description "The maximum number of error records maintained in-memory. This setting is on a per-Process basis. Runspaces share, jobs or other consoles counted separately."
Set-DbatoolsConfig -FullName 'Logging.MaxMessageCount' -Value 1024 -Initialize -Validation integerpositive -Handler { [Sqlcollaborative.Dbatools.Message.LogHost]::MaxMessageCount = $args[0] } -Description "The maximum number of messages that can be maintained in the in-memory message queue. This setting is on a per-Process basis. Runspaces share, jobs or other consoles counted separately."
Set-DbatoolsConfig -FullName 'Logging.MaxMessagefileBytes' -Value 5MB -Initialize -Validation integerpositive -Handler { [Sqlcollaborative.Dbatools.Message.LogHost]::MaxMessagefileBytes = $args[0] } -Description "The maximum size of a given logfile. When reaching this limit, the file will be abandoned and a new log created. Set to 0 to not limit the size. This setting is on a per-Process basis. Runspaces share, jobs or other consoles counted separately."
Set-DbatoolsConfig -FullName 'Logging.MaxMessagefileCount' -Value 5 -Initialize -Validation integerpositive -Handler { [Sqlcollaborative.Dbatools.Message.LogHost]::MaxMessagefileCount = $args[0] } -Description "The maximum number of logfiles maintained at a time. Exceeding this number will cause the oldest to be culled. Set to 0 to disable the limit. This setting is on a per-Process basis. Runspaces share, jobs or other consoles counted separately."
Set-DbatoolsConfig -FullName 'Logging.MaxErrorFileBytes' -Value 20MB -Initialize -Validation integerpositive -Handler { [Sqlcollaborative.Dbatools.Message.LogHost]::MaxErrorFileBytes = $args[0] } -Description "The maximum size all error files combined may have. When this number is exceeded, the oldest entry is culled. This setting is on a per-Process basis. Runspaces share, jobs or other consoles counted separately."
Set-DbatoolsConfig -FullName 'Logging.MaxTotalFolderSize' -Value 100MB -Initialize -Validation integerpositive -Handler { [Sqlcollaborative.Dbatools.Message.LogHost]::MaxTotalFolderSize = $args[0] } -Description "This is the upper limit of length all items in the log folder may have combined across all processes."
Set-DbatoolsConfig -FullName 'Logging.MaxLogFileAge' -Value (New-TimeSpan -Days 7) -Initialize -Validation timespan -Handler { [Sqlcollaborative.Dbatools.Message.LogHost]::MaxLogFileAge = $args[0] } -Description "Any logfile older than this will automatically be cleansed. This setting is global."
Set-DbatoolsConfig -FullName 'Logging.MessageLogFileEnabled' -Value $true -Initialize -Validation bool -Handler { [Sqlcollaborative.Dbatools.Message.LogHost]::MessageLogFileEnabled = $args[0] } -Description "Governs, whether a log file for the system messages is written. This setting is on a per-Process basis. Runspaces share, jobs or other consoles counted separately."
Set-DbatoolsConfig -FullName 'Logging.MessageLogEnabled' -Value $true -Initialize -Validation bool -Handler { [Sqlcollaborative.Dbatools.Message.LogHost]::MessageLogEnabled = $args[0] } -Description "Governs, whether a log of recent messages is kept in memory. This setting is on a per-Process basis. Runspaces share, jobs or other consoles counted separately."
Set-DbatoolsConfig -FullName 'Logging.ErrorLogFileEnabled' -Value $true -Initialize -Validation bool -Handler { [Sqlcollaborative.Dbatools.Message.LogHost]::ErrorLogFileEnabled = $args[0] } -Description "Governs, whether log files for errors are written. This setting is on a per-Process basis. Runspaces share, jobs or other consoles counted separately."
Set-DbatoolsConfig -FullName 'Logging.ErrorLogEnabled' -Value $true -Initialize -Validation bool -Handler { [Sqlcollaborative.Dbatools.Message.LogHost]::ErrorLogEnabled = $args[0] } -Description "Governs, whether a log of recent errors is kept in memory. This setting is on a per-Process basis. Runspaces share, jobs or other consoles counted separately."
tools\dbatools\internal\configurations\settings\paths.ps1
<#
This is designed for all paths you need configurations for.
#>

# The default path where dbatools stores persistent data
Set-DbatoolsConfig -FullName 'Path.DbatoolsData' -Value (Join-DbaPath $script:AppData "PowerShell" "dbatools") -Initialize -Validation string -Handler {  } -Description "The path where dbatools stores persistent data on a per user basis."

# The default path where dbatools stores temporary data
Set-DbatoolsConfig -FullName 'Path.DbatoolsTemp' -Value ([System.IO.Path]::GetTempPath()).TrimEnd("\") -Initialize -Validation string -Handler { } -Description "The path where dbatools stores temporary data."

# The default path for writing logs
Set-DbatoolsConfig -FullName 'Path.DbatoolsLogPath' -Value (Join-DbaPath $script:AppData "PowerShell" "dbatools") -Initialize -Validation string -Handler { [Sqlcollaborative.Dbatools.Message.LogHost]::LoggingPath = $args[0] } -Description "The path where dbatools writes all its logs and debugging information."

# The default Path for where the tags Json is stored
Set-DbatoolsConfig -FullName 'Path.TagCache' -Value (Resolve-Path "$script:PSModuleRoot\bin\dbatools-index.json") -Initialize -Validation string -Handler { } -Description "The file in which dbatools stores the tag cache. That cache is used in Find-DbaCommand for more comfortable autocomplete"

# The default Path for the server list (Get-DbaServerList, etc)
Set-DbatoolsConfig -FullName 'Path.Servers' -Value (Join-DbaPath $script:AppData "PowerShell" "dbatools" "servers.xml") -Initialize -Validation string -Handler { } -Description "The file in which dbatools stores the current user's server list, as managed by Get/Add/Update-DbaServerList"
tools\dbatools\internal\configurations\settings\remoting.ps1
# Handles PowerShell Session scrapping timeout
Set-DbatoolsConfig -FullName 'PSRemoting.Sessions.ExpirationTimeout' -Value (New-TimeSpan -Minutes 5) -Initialize -Validation timespan -Handler { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::PSSessionTimeout = $args[0] } -Description 'The timeout interval for PowerShell remote sessions. Dbatools will kill sessions that have been idle for this amount of time.'

# Disables session caching
Set-DbatoolsConfig -FullName 'PSRemoting.Sessions.Enable' -Value $true -Initialize -Validation bool -Handler { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::PSSessionCacheEnabled = $args[0] } -Description 'Globally enables session caching for PowerShell remoting'
tools\dbatools\internal\configurations\settings\sql.ps1
# Controls the timeout on sql connects
Set-DbatoolsConfig -FullName 'sql.connection.timeout' -Value 15 -Initialize -Validation integerpositive -Handler { [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::SqlConnectionTimeout = $args[0] } -Description "The number of seconds before sql server connection attempts are aborted"
tools\dbatools\internal\configurations\settings\tabexpansion.ps1
# Sets the default interval and timeout for TEPP updates
Set-DbatoolsConfig -FullName 'TabExpansion.UpdateInterval' -Value (New-TimeSpan -Minutes 3) -Initialize -Validation timespan -Handler { [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppUpdateInterval = $args[0] } -Description 'The frequency in which TEPP tries to update each cache for autocompletion'
Set-DbatoolsConfig -FullName 'TabExpansion.UpdateTimeout' -Value (New-TimeSpan -Seconds 30) -Initialize -Validation timespan -Handler { [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppUpdateTimeout = $args[0] } -Description 'After this timespan has passed without connections to a server, the TEPP updater will no longer update the cache.'

# Disable the management cache entire
Set-DbatoolsConfig -FullName 'TabExpansion.Disable' -Value $false -Initialize -Validation bool -Handler {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppDisabled = $args[0]

    # Disable Async TEPP runspace if not needed
    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppAsyncDisabled -or [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppDisabled) {
        [Sqlcollaborative.Dbatools.Runspace.RunspaceHost]::Runspaces["dbatools-teppasynccache"].Stop()
    } else {
        [Sqlcollaborative.Dbatools.Runspace.RunspaceHost]::Runspaces["dbatools-teppasynccache"].Start()
    }
} -Description 'Globally disables all TEPP functionality by dbatools'
Set-DbatoolsConfig -FullName 'TabExpansion.Disable.Asynchronous' -Value $false -Initialize -Validation bool -Handler {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppAsyncDisabled = $args[0]

    # Disable Async TEPP runspace if not needed
    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppAsyncDisabled -or [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppDisabled) {
        [Sqlcollaborative.Dbatools.Runspace.RunspaceHost]::Runspaces["dbatools-teppasynccache"].Stop()
    } else {
        [Sqlcollaborative.Dbatools.Runspace.RunspaceHost]::Runspaces["dbatools-teppasynccache"].Start()
    }
} -Description 'Globally disables asynchronous TEPP updates in the background'
Set-DbatoolsConfig -FullName 'TabExpansion.Disable.Synchronous' -Value $true -Initialize -Validation bool -Handler { [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppSyncDisabled = $args[0] } -Description 'Globally disables synchronous TEPP updates, performed whenever connecting o the server. If this is not disabled, it will only perform updates that are fast to perform, in order to minimize performance impact. This may lead to some TEPP functionality loss if asynchronous updates are disabled.'
tools\dbatools\internal\configurations\settings\userinteraction.ps1
<#
This configuration file is for all settings of how dbatools interacts with users
#>

# Configure the message levels at which the function will write either an info, a verbose message or debug message
# Used by the internal "Write-Message" function
Set-DbatoolsConfig -Name 'message.maximuminfo' -Value 3 -Initialize -Validation integer0to9 -Handler { [Sqlcollaborative.Dbatools.Message.MessageHost]::MaximumInformation = $args[0] } -Description "The maximum message level to still display to the user directly."
Set-DbatoolsConfig -Name 'message.maximumverbose' -Value 6 -Initialize -Validation integer0to9 -Handler { [Sqlcollaborative.Dbatools.Message.MessageHost]::MaximumVerbose = $args[0] } -Description "The maxium message level where verbose information is still written."
Set-DbatoolsConfig -Name 'message.maximumdebug' -Value 9 -Initialize -Validation integer0to9 -Handler { [Sqlcollaborative.Dbatools.Message.MessageHost]::MaximumDebug = $args[0] } -Description "The maximum message level where debug information is still written."
Set-DbatoolsConfig -Name 'message.minimuminfo' -Value 1 -Initialize -Validation integer0to9 -Handler { [Sqlcollaborative.Dbatools.Message.MessageHost]::MinimumInformation = $args[0] } -Description "The minimum required message level for messages that will be shown to the user."
Set-DbatoolsConfig -Name 'message.minimumverbose' -Value 4 -Initialize -Validation integer0to9 -Handler { [Sqlcollaborative.Dbatools.Message.MessageHost]::MinimumVerbose = $args[0] } -Description "The minimum required message level where verbose information is written."
Set-DbatoolsConfig -Name 'message.minimumdebug' -Value 1 -Initialize -Validation integer0to9 -Handler { [Sqlcollaborative.Dbatools.Message.MessageHost]::MinimumDebug = $args[0] } -Description "The minimum required message level where debug information is written."

# Default color used by the "Write-Message" function in info mode
Set-DbatoolsConfig -Name 'message.infocolor' -Value 'Cyan' -Initialize -Validation consolecolor -Handler { [Sqlcollaborative.Dbatools.Message.MessageHost]::InfoColor = $args[0] } -Description "The color to use when writing text to the screen on PowerShell."
Set-DbatoolsConfig -Name 'message.developercolor' -Value 'Grey' -Initialize -Validation consolecolor -Handler { [Sqlcollaborative.Dbatools.Message.MessageHost]::DeveloperColor = $args[0] } -Description "The color to use when writing text with developer specific additional information to the screen on PowerShell."
Set-DbatoolsConfig -Name 'message.info.color.emphasis' -Value 'green' -Initialize -Validation "consolecolor" -Handler { [Sqlcollaborative.Dbatools.Message.MessageHost]::InfoColorEmphasis = $args[0] } -Description "The color to use when emphasizing written text to the screen on PowerShell."
Set-DbatoolsConfig -Name 'message.info.color.subtle' -Value 'gray' -Initialize -Validation "consolecolor" -Handler { [Sqlcollaborative.Dbatools.Message.MessageHost]::InfoColorSubtle = $args[0] } -Description "The color to use when making writing text to the screen on PowerShell appear subtle."
Set-DbatoolsConfig -Name 'message.consoleoutput.disable' -Value $false -Initialize -Validation "bool" -Handler { [Sqlcollaborative.Dbatools.Message.MessageHost]::DisableVerbosity = $args[0] } -Description "Global toggle that allows disabling all regular messages to screen. Messages from '-Verbose' and '-Debug' are unaffected"
Set-DbatoolsConfig -Name 'message.transform.errorqueuesize' -Value 512 -Initialize -Validation "integerpositive" -Handler { [Sqlcollaborative.Dbatools.Message.MessageHost]::TransformErrorQueueSize = $args[0] } -Description "The size of the queue for transformation errors. May be useful for advanced development, but can be ignored usually."
Set-DbatoolsConfig -Name 'message.nestedlevel.decrement' -Value 0 -Initialize -Validation "integer0to9" -Handler { [Sqlcollaborative.Dbatools.Message.MessageHost]::NestedLevelDecrement = $args[0] } -Description "How many levels should be reduced per callstack depth. This makes commands less verbose, the more nested they are called"

# Messaging mode in non-critical terminations
Set-DbatoolsConfig -Name 'message.mode.default' -Value ([DbaMode]::Strict) -Initialize -Validation string -Handler { } -Description "The mode controls how some functions handle non-critical terminations by default. Strict: Write a warning | Lazy: Write a message | Report: Generate a report object"
Set-DbatoolsConfig -Name 'message.mode.lazymessagelevel' -Value 4 -Initialize -Validation integer0to9 -Handler { } -Description "At what level will the lazy message be written? (By default invisible to the user)"

# Enable Developer mode
Set-DbatoolsConfig -Name 'developer.mode.enable' -Value $false -Initialize -Validation bool -Handler { [Sqlcollaborative.Dbatools.Message.MessageHost]::DeveloperMode = $args[0] } -Description "Developermode enables advanced logging and verbosity features. There is little benefit for enabling this as a regular user. but developers can use it to more easily troubleshoot issues."

# Message display style options
Set-DbatoolsConfig -Name 'message.style.breadcrumbs' -Value $false -Initialize -Validation "bool" -Handler { [Sqlcollaborative.Dbatools.Message.MessageHost]::EnableMessageBreadcrumbs = $args[0] } -Description "Controls how messages are displayed. Enables Breadcrumb display, showing the entire callstack. Takes precedence over command name display."
Set-DbatoolsConfig -Name 'message.style.functionname' -Value $true -Initialize -Validation "bool" -Handler { [Sqlcollaborative.Dbatools.Message.MessageHost]::EnableMessageDisplayCommand = $args[0] } -Description "Controls how messages are displayed. Enables command name, showing the name of the writing command. Is overwritten by enabling breadcrumbs."
Set-DbatoolsConfig -Name 'message.style.timestamp' -Value $true -Initialize -Validation "bool" -Handler { [Sqlcollaborative.Dbatools.Message.MessageHost]::EnableMessageTimestamp = $args[0] } -Description "Controls how messages are displayed. Enables timestamp display, including a timestamp in each message."
tools\dbatools\internal\configurations\validation\bool.ps1
Register-DbatoolsConfigValidation -Name "bool" -ScriptBlock {
    param (
        $Value
    )

    $Result = New-Object PSObject -Property @{
        Success = $True
        Value   = $null
        Message = ""
    }
    try {
        if ($Value.GetType().FullName -ne "System.Boolean") {
            $Result.Message = "Not a boolean: $Value"
            $Result.Success = $False
            return $Result
        }
    } catch {
        $Result.Message = "Not a boolean: $Value"
        $Result.Success = $False
        return $Result
    }

    $Result.Value = $Value

    return $Result
}
tools\dbatools\internal\configurations\validation\consolecolor.ps1
Register-DbatoolsConfigValidation -Name "consolecolor" -ScriptBlock {
    param (
        $Value
    )

    $Result = New-Object PSObject -Property @{
        Success = $True
        Value   = $null
        Message = ""
    }

    try { [System.ConsoleColor]$color = $Value }
    catch {
        $Result.Message = "Not a console color: $Value"
        $Result.Success = $False
        return $Result
    }

    $Result.Value = $color

    return $Result
}
tools\dbatools\internal\configurations\validation\datetime.ps1
Register-DbatoolsConfigValidation -Name "datetime" -ScriptBlock {
    param (
        $Value
    )

    $Result = New-Object PSObject -Property @{
        Success = $True
        Value   = $null
        Message = ""
    }

    try { [DateTime]$DateTime = $Value }
    catch {
        $Result.Message = "Not a DateTime: $Value"
        $Result.Success = $False
        return $Result
    }

    $Result.Value = $DateTime

    return $Result
}
tools\dbatools\internal\configurations\validation\double.ps1
Register-DbatoolsConfigValidation -Name "double" -ScriptBlock {
    param (
        $Value
    )

    $Result = New-Object PSOBject -Property @{
        Success = $True
        Value   = $null
        Message = ""
    }

    try { [double]$number = $Value }
    catch {
        $Result.Message = "Not a double: $Value"
        $Result.Success = $False
        return $Result
    }

    $Result.Value = $number

    return $Result
}
tools\dbatools\internal\configurations\validation\integer.ps1
Register-DbatoolsConfigValidation -Name "integer" -ScriptBlock {
    param (
        $Value
    )

    $Result = New-Object PSOBject -Property @{
        Success = $True
        Value   = $null
        Message = ""
    }

    try { [int]$number = $Value }
    catch {
        $Result.Message = "Not an integer: $Value"
        $Result.Success = $False
        return $Result
    }

    $Result.Value = $number

    return $Result
}
tools\dbatools\internal\configurations\validation\integer0to9.ps1
Register-DbatoolsConfigValidation -Name "integer0to9" -ScriptBlock {
    param (
        $Value
    )

    $Result = New-Object PSOBject -Property @{
        Success = $True
        Value   = $null
        Message = ""
    }

    try { [int]$number = $Value }
    catch {
        $Result.Message = "Not an integer: $Value"
        $Result.Success = $False
        return $Result
    }

    if (($number -lt 0) -or ($number -gt 9)) {
        $Result.Message = "Out of range. Specify a number ranging from 0 to 9"
        $Result.Success = $False
        return $Result
    }

    $Result.Value = $Number

    return $Result
}
tools\dbatools\internal\configurations\validation\integerpositive.ps1
Register-DbatoolsConfigValidation -Name "integerpositive" -ScriptBlock {
    param (
        $Value
    )

    $Result = New-Object PSOBject -Property @{
        Success = $True
        Value   = $null
        Message = ""
    }

    try { [int]$number = $Value }
    catch {
        $Result.Message = "Not an integer: $Value"
        $Result.Success = $False
        return $Result
    }

    if ($number -lt 0) {
        $Result.Message = "Negative value: $Value"
        $Result.Success = $False
        return $Result
    }

    $Result.Value = $number

    return $Result
}
tools\dbatools\internal\configurations\validation\long.ps1
Register-DbatoolsConfigValidation -Name "long" -ScriptBlock {
    param (
        $Value
    )

    $Result = New-Object PSOBject -Property @{
        Success = $True
        Value   = $null
        Message = ""
    }

    try { [long]$number = $Value }
    catch {
        $Result.Message = "Not a long: $Value"
        $Result.Success = $False
        return $Result
    }

    $Result.Value = $number

    return $Result
}
tools\dbatools\internal\configurations\validation\sizestyle.ps1
Register-DbatoolsConfigValidation -Name "sizestyle" -ScriptBlock {
    param (
        $Value
    )

    $Result = New-Object PSObject -Property @{
        Success = $True
        Value   = $null
        Message = ""
    }

    try { [Sqlcollaborative.Dbatools.Utility.SizeStyle]$style = $Value }
    catch {
        $Result.Message = "Not a size style: $Value"
        $Result.Success = $False
        return $Result
    }

    $Result.Value = $style

    return $Result
}
tools\dbatools\internal\configurations\validation\string.ps1
Register-DbatoolsConfigValidation -Name "string" -ScriptBlock {
    param (
        $Value
    )

    $Result = New-Object PSObject -Property @{
        Success = $True
        Value   = $null
        Message = ""
    }

    try {
        # Seriously, this should work for almost anybody and anything
        [string]$data = $Value
    } catch {
        $Result.Message = "Not a string: $Value"
        $Result.Success = $False
        return $Result
    }

    if ([string]::IsNullOrEmpty($data)) {
        $Result.Message = "Is an empty string: $Value"
        $Result.Success = $False
        return $Result
    }

    if ($data -eq $Value.GetType().FullName) {
        $Result.Message = "Is an object with no proper string representation: $Value"
        $Result.Success = $False
        return $Result
    }

    $Result.Value = $data

    return $Result
}
tools\dbatools\internal\configurations\validation\timespan.ps1
Register-DbatoolsConfigValidation -Name "timespan" -ScriptBlock {
    param (
        $Value
    )

    $Result = New-Object PSObject -Property @{
        Success = $True
        Value   = $null
        Message = ""
    }

    try { [timespan]$timespan = $Value }
    catch {
        $Result.Message = "Not a Timespan: $Value"
        $Result.Success = $False
        return $Result
    }

    $Result.Value = $timespan

    return $Result
}
tools\dbatools\internal\dynamicparams\alert.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["alert"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["alert"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["alert"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["alert"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["alert"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name alert
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["alert"][$FullSmoName] = $server.JobServer.Alerts.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\alertcategory.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["alertcategory"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["alertcategory"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["alertcategory"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["alertcategory"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["alertcategory"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name AlertCategory
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["alertcategory"][$FullSmoName] = $server.JobServer.AlertCategories.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\audit.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["audit"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["audit"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["audit"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["audit"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["audit"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name Audit
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["audit"][$FullSmoName] = $server.Audits.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\auditspecification.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["auditspecification"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["auditspecification"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["auditspecification"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["auditspecification"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["auditspecification"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name AuditSpecification
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["auditspecification"][$FullSmoName] = $server.AuditSpecifications.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\availabilitygroup.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["availabilitygroup"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["availabilitygroup"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["availabilitygroup"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["availabilitygroup"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["availabilitygroup"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name AvailabilityGroup
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["availabilitygroup"][$FullSmoName] = $server.AvailabilityGroups.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\backupdevice.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["backupdevice"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["backupdevice"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["backupdevice"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["backupdevice"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["backupdevice"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name BackupDevice
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["backupdevice"][$FullSmoName] = $server.BackupDevices.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\config.ps1
#region Tepp Data return: FullName
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    foreach ($name in ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations.Values | Where-Object { -not $_.Hidden -and ($_.FullName -Like "$wordToComplete*") } | Select-Object -ExpandProperty FullName | Sort-Object)) {
        New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name config
#endregion Tepp Data return: FullName

#region Tepp Data return: Name
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $moduleName = "*"
    if ($fakeBoundParameter.Module) { $moduleName = $fakeBoundParameter.Module }

    foreach ($name in ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations.Values | Where-Object { (-not $_.Hidden) -and ($_.Name -Like "$wordToComplete*") -and ($_.Module -like $moduleName) } | Select-Object -ExpandProperty Name | Sort-Object)) {
        New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name config_name
#endregion Tepp Data return: Name

#region Tepp Data return: Module
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    foreach ($name in ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations.Values.Module | Select-Object -Unique | Where-DbaObject -Like "$wordToComplete*" | Sort-Object )) {
        New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name configmodule
#endregion Tepp Data return: Module
tools\dbatools\internal\dynamicparams\configname.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["configname"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["configname"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["configname"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["configname"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["configname"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name ConfigName
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["configname"][$FullSmoName] = (Get-Member -InputObject $server.Configuration -MemberType Property -Force | Where-Object Name -NotIn 'Parent',
        'Properties').Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\credential.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["credential"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["credential"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["credential"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["credential"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["credential"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name Credential
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["credential"][$FullSmoName] = $server.Credentials.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\customerror.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["customerror"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["customerror"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["customerror"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["customerror"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["customerror"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name CustomError
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["customerror"][$FullSmoName] = $server.UserDefinedMessages.ID
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\database.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["database"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["database"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["database"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["database"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["database"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name Database
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["database"][$FullSmoName] = $server.Databases.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\delimiter.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["delimiter"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["delimiter"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,
        $parameterName,
        $wordToComplete,
        $commandAst,
        $fakeBoundParameter
    )

    @("``t", "|", ";", " ", ",", "       ")
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name Delimiter
#endregion Tepp Data return
tools\dbatools\internal\dynamicparams\endpoint.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["endpoint"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["endpoint"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["endpoint"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["endpoint"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["endpoint"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name Endpoint
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["endpoint"][$FullSmoName] = ($server.Endpoints | Where-Object IsSystemObject -eq $false).Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\group.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["group"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["group"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["group"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["group"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["group"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name Group
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    $cms = New-Object Microsoft.SqlServer.Management.RegisteredServers.RegisteredServersStore($server.ConnectionContext.SqlConnectionObject)
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["group"][$FullSmoName] = $cms.DatabaseEngineServerGroup.ServerGroups.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\instanceproperty.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["instanceproperty"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["instanceproperty"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["instanceproperty"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["instanceproperty"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["instanceproperty"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name InstanceProperty
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["instanceproperty"][$FullSmoName] = $server.Information.Properties.Name + $server.UserOptions.Properties.Name + $server.Settings.Properties.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\job.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["job"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["job"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,
        $parameterName,
        $wordToComplete,
        $commandAst,
        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["job"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["job"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["job"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name Job
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["job"][$FullSmoName] = $server.JobServer.Jobs.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\jobcategory.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["jobcategory"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["jobcategory"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["jobcategory"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["jobcategory"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["jobcategory"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name JobCategory
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["jobcategory"][$FullSmoName] = $server.JobServer.JobCategories.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\linkedserver.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["linkedserver"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["linkedserver"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["linkedserver"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["linkedserver"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["linkedserver"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name LinkedServer
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["linkedserver"][$FullSmoName] = $server.LinkedServers.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\login.ps1
tools\dbatools\internal\dynamicparams\mailaccount.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailaccount"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailaccount"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailaccount"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailaccount"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailaccount"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name MailAccount
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailaccount"][$FullSmoName] = $server.Mail.Accounts.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\mailprofile.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailprofile"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailprofile"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailprofile"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailprofile"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailprofile"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name MailProfile
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailprofile"][$FullSmoName] = $server.Mail.Profiles.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\mailserver.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailserver"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailserver"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailserver"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailserver"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailserver"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name MailServer
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailserver"][$FullSmoName] = $server.Mail.Accounts.MailServers.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\operator.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["operator"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["operator"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["operator"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["operator"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["operator"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name Operator
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["operator"][$FullSmoName] = $server.JobServer.Operators.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\operatorcategory.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["operatorcategory"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["operatorcategory"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["operatorcategory"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["operatorcategory"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["operatorcategory"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name OperatorCategory
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["operatorcategory"][$FullSmoName] = $server.JobServer.OperatorCategories.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\perfmontemplate.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["perfmontemplate"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["perfmontemplate"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,
        $parameterName,
        $wordToComplete,
        $commandAst,
        $fakeBoundParameter
    )

    $files = (Get-ChildItem "$script:PSModuleRoot\bin\perfmontemplates\collectorsets\*.xml").BaseName
    foreach ($file in $files) {
        "'$file'"
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name perfmontemplate
#endregion Tepp Data return
tools\dbatools\internal\dynamicparams\powerplan.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["powerplan"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["powerplan"] = @()
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,
        $parameterName,
        $wordToComplete,
        $commandAst,
        $fakeBoundParameter
    )


    foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["powerplan"] | Where-DbaObject -Like "$wordToComplete*")) {
        New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
    }
}
Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name "powerplan"
#endregion Tepp Data return

#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["powerplan"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["powerplan"] = 'High Performance', 'Balanced', 'Power saver'
}
#endregion Initialize Cache
Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name powerplan
#endregion Tepp Data return
tools\dbatools\internal\dynamicparams\processHostname.ps1
$scriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']
    if (-not $server) {
        return
    }
    $sqlCredential = $fakeBoundParameter['SqlCredential']

    try {
        if ($sqlCredential) { $instance = Connect-SqlInstance -SqlInstance $server -ErrorAction Stop }
        else { $instance = Connect-SqlInstance -SqlInstance $server -ErrorAction Stop }

        $instance.EnumProcesses().Host | Select-Object -Unique | Where-DbaObject -Like "$wordToComplete*" | ForEach-Object {
            if (-not ([string]::IsNullOrWhiteSpace($_))) { New-DbaTeppCompletionResult -CompletionText $_ -ToolTip $_ }
        }
    } catch {
        return
    } finally {
    }
}

Register-DbaTeppScriptblock -ScriptBlock $scriptBlock -Name processhostname
tools\dbatools\internal\dynamicparams\processProgram.ps1
$scriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']
    if (-not $server) {
        return
    }
    $sqlCredential = $fakeBoundParameter['SqlCredential']

    try {
        if ($sqlCredential) { $instance = Connect-SqlInstance -SqlInstance $server -ErrorAction Stop  }
        else { $instance = Connect-SqlInstance -SqlInstance $server -ErrorAction Stop }

        $instance.EnumProcesses().Program | Select-Object -Unique | Where-DbaObject -Like "$wordToComplete*" | ForEach-Object {
            if (-not ([string]::IsNullOrWhiteSpace($_))) { New-DbaTeppCompletionResult -CompletionText $_ -ToolTip $_ }
        }
    } catch {
        return
    } finally {
    }
}

Register-DbaTeppScriptblock -ScriptBlock $scriptBlock -Name processprogram
tools\dbatools\internal\dynamicparams\processSpid.ps1
$scriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']
    if (-not $server) {
        return
    }
    $sqlCredential = $fakeBoundParameter['SqlCredential']

    try {
        if ($sqlCredential) { $instance = Connect-SqlInstance -SqlInstance $server -ErrorAction Stop }
        else { $instance = Connect-SqlInstance -SqlInstance $server -ErrorAction Stop }

        $instance.EnumProcesses().Spid | Select-Object -Unique | Where-DbaObject -Like "$wordToComplete*" | ForEach-Object {
            if (-not ([string]::IsNullOrWhiteSpace($_))) { New-DbaTeppCompletionResult -CompletionText $_ -ToolTip $_ }
        }
    } catch {
        return
    } finally {
    }
}

Register-DbaTeppScriptblock -ScriptBlock $scriptBlock -Name processspid
tools\dbatools\internal\dynamicparams\proxyaccount.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["proxyaccount"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["proxyaccount"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["proxyaccount"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["proxyaccount"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["proxyaccount"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name ProxyAccount
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["proxyaccount"][$FullSmoName] = $server.JobServer.ProxyAccounts.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\resourcepool.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["resourcepool"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["resourcepool"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["resourcepool"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["resourcepool"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["resourcepool"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name ResourcePool
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["resourcepool"][$FullSmoName] = ($server.ResourceGovernor.ResourcePools | Where-Object Name -NotIn 'internal', 'default').Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\schedule.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["schedule"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["schedule"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["schedule"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["schedule"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["schedule"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name Schedule
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["schedule"][$FullSmoName] = $server.JobServer.SharedSchedules.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\servertrigger.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["servertrigger"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["servertrigger"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["servertrigger"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["servertrigger"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["servertrigger"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name ServerTrigger
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["servertrigger"][$FullSmoName] = $server.Triggers.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\session.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["session"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["session"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["session"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["session"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["session"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name session
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

    $SqlConn = $server.ConnectionContext.SqlConnectionObject
    $SqlStoreConnection = New-Object Microsoft.SqlServer.Management.Sdk.Sfc.SqlStoreConnection $SqlConn
    $XEStore = New-Object  Microsoft.SqlServer.Management.XEvent.XEStore $SqlStoreConnection
    $xesessions = $XEStore.sessions
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["session"][$FullSmoName] = $xesessions.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\snapshot.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["snapshot"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["snapshot"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    $server = $fakeBoundParameter['SqlInstance']

    if (-not $server) {
        $server = $fakeBoundParameter['Source']
    }

    if (-not $server) {
        $server = $fakeBoundParameter['ComputerName']
    }

    if (-not $server) { return }

    try {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    } catch {
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["snapshot"][$parServer.FullSmoName.ToLower()]) {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["snapshot"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    }

    try {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["snapshot"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*")) {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        return
    } catch {
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name snapshot
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {
    if ($PSVersionTable.PSVersion.Major -ge 4) { [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["snapshot"][$FullSmoName] = $server.Databases.Where( { $_.IsDatabaseSnapShot }).Name }
    else { [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["snapshot"][$FullSmoName] = ($server.Databases | Where-Object IsDatabaseSnapShot).Name }
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache
tools\dbatools\internal\dynamicparams\sqlinstance.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["sqlinstance"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["sqlinstance"] = @()
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )


    foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["sqlinstance"] | Where-DbaObject -Like "$wordToComplete*")) {
        New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
    }
}
Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name "sqlinstance"
#endregion Tepp Data return
tools\dbatools\internal\dynamicparams\tag.ps1
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )

    # Hack till we get this working
    function New-CompletionResult {
        param ([Parameter(Position = 0, ValueFromPipelineByPropertyName, Mandatory, ValueFromPipeline)]
            [ValidateNotNullOrEmpty()]
            [string]
            $CompletionText,

            [Parameter(Position = 1, ValueFromPipelineByPropertyName)]
            [string]
            $ToolTip,

            [Parameter(Position = 2, ValueFromPipelineByPropertyName)]
            [string]
            $ListItemText,

            [System.Management.Automation.CompletionResultType]
            $CompletionResultType = [System.Management.Automation.CompletionResultType]::ParameterValue,

            [switch]
            $NoQuotes = $false
        )

        process {
            $toolTipToUse = if ($ToolTip -eq '') { $CompletionText }
            else { $ToolTip }
            $listItemToUse = if ($ListItemText -eq '') { $CompletionText }
            else { $ListItemText }

            # If the caller explicitly requests that quotes
            # not be included, via the -NoQuotes parameter,
            # then skip adding quotes.

            if ($CompletionResultType -eq [System.Management.Automation.CompletionResultType]::ParameterValue -and -not $NoQuotes) {
                # Add single quotes for the caller in case they are needed.
                # We use the parser to robustly determine how it will treat
                # the argument.  If we end up with too many tokens, or if
                # the parser found something expandable in the results, we
                # know quotes are needed.

                $tokens = $null
                $null = [System.Management.Automation.Language.Parser]::ParseInput("echo $CompletionText", [ref]$tokens, [ref]$null)
                if ($tokens.Length -ne 3 -or
                    ($tokens[1] -is [System.Management.Automation.Language.StringExpandableToken] -and
                        $tokens[1].Kind -eq [System.Management.Automation.Language.TokenKind]::Generic)) {
                    $CompletionText = "'$CompletionText'"
                }
            }
            return New-Object System.Management.Automation.CompletionResult `
            ($CompletionText, $listItemToUse, $CompletionResultType, $toolTipToUse.Trim())
        }

    }

    $moduledirectory = (Get-Module -Name dbatools).ModuleBase
    $idxfile = "$moduledirectory\bin\dbatools-index.json"
    $json = Get-Content $idxfile | ConvertFrom-Json
    $cleantags = @()
    $tags = $json.Tags

    foreach ($tag in $tags) {
        if ($null -ne $tag) {
            $cleantags += $tag.Trim()
        }
    }

    $collection = $cleantags | Select-Object -Unique

    if ($collection) {
        foreach ($item in $collection) {
            New-CompletionResult -CompletionText $item -ToolTip $item
        }
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name "tag"
tools\dbatools\internal\dynamicparams\xesessiontemplate.ps1
#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["xesessiontemplate"]) {
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["xesessiontemplate"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,
        $parameterName,
        $wordToComplete,
        $commandAst,
        $fakeBoundParameter
    )

    $files = (Get-ChildItem "$script:PSModuleRoot\bin\xetemplates\*.xml").BaseName
    foreach ($file in $files) {
        "'$file'"
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name xesessiontemplate
#endregion Tepp Data return
tools\dbatools\internal\functions\configuration\Read-DbatoolsConfigFile.ps1
function Read-DbatoolsConfigFile
{
<#
    .SYNOPSIS
        Reads a configuration file and parses it.
    
    .DESCRIPTION
        Reads a configuration file and parses it.
    
    .PARAMETER Path
        The path to the file to parse.
    
    .PARAMETER WebLink
        The link to a website to download straight as raw json.
    
    .PARAMETER RawJson
        Raw json data to interpret.
    
    .EXAMPLE
        PS C:\> Read-DbatoolsConfigFile -Path config.json
    
        Reads the config.json file and returns interpreted configuration objects.
#>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ParameterSetName = 'Path')]
        [string]
        $Path,
        
        [Parameter(Mandatory = $true, ParameterSetName = 'Weblink')]
        [string]
        $Weblink,
        
        [Parameter(Mandatory = $true, ParameterSetName = 'RawJson')]
        [string]
        $RawJson
    )
    
    #region Utility Function
    function New-ConfigItem
    {
        [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
        [CmdletBinding()]
        param (
            $FullName,
            
            $Value,
            
            $Type,
            
            [switch]
            $KeepPersisted,
            
            [switch]
            $Enforced,
            
            [switch]
            $Policy
        )
        
        [pscustomobject]@{
            FullName        = $FullName
            Value            = $Value
            Type            = $Type
            KeepPersisted   = $KeepPersisted
            Enforced        = $Enforced
            Policy            = $Policy
        }
    }
    
    function Get-WebContent
    {
        [CmdletBinding()]
        param (
            [string]
            $WebLink
        )
        
        $webClient = New-Object System.Net.WebClient
        $webClient.Encoding = [System.Text.Encoding]::UTF8
        $webClient.DownloadString($WebLink)
    }
    #endregion Utility Function
    
    if ($Path)
    {
        if (-not (Test-Path $Path)) { return }
        $data = Get-Content -Path $Path -Encoding UTF8 | ConvertFrom-Json -ErrorAction Stop
    }
    if ($Weblink)
    {
        $data = Get-WebContent -WebLink $Weblink | ConvertFrom-Json -ErrorAction Stop
    }
    if ($RawJson)
    {
        $data = $RawJson | ConvertFrom-Json -ErrorAction Stop
    }
    
    foreach ($item in $data)
    {
        #region No Version
        if (-not $item.Version)
        {
            New-ConfigItem -FullName $item.FullName -Value ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::ConvertFromPersistedValue($item.Value, $item.Type))
        }
        #endregion No Version
        
        #region Version One
        if ($item.Version -eq 1)
        {
            if ((-not $item.Style) -or ($item.Style -eq "Simple")) { New-ConfigItem -FullName $item.FullName -Value $item.Data }
            else
            {
                if (($item.Type -eq "Object") -or ($item.Type -eq 12))
                {
                    New-ConfigItem -FullName $item.FullName -Value $item.Value -Type "Object" -KeepPersisted
                }
                else
                {
                    New-ConfigItem -FullName $item.FullName -Value ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::ConvertFromPersistedValue($item.Value, $item.Type))
                }
            }
        }
        #endregion Version One
    }
}
tools\dbatools\internal\functions\configuration\Read-DbatoolsConfigPersisted.ps1
function Read-DbatoolsConfigPersisted
{
<#
    .SYNOPSIS
        Reads configurations from persisted file / registry.
    
    .DESCRIPTION
        Reads configurations from persisted file / registry.
    
    .PARAMETER Scope
        Where to read from.
    
    .PARAMETER Module
        Load module specific data.
        Use this to load on-demand configuration only when the module is imported.
        Useful when using the config system as cache.
    
    .PARAMETER ModuleVersion
        The configuration version of the module-settings to load.
    
    .PARAMETER Hashtable
        Rather than returning results, insert them into this hashtable.
    
    .PARAMETER Default
        When inserting into a hashtable, existing values are overwritten by default.
        Enabling this setting will cause it to only insert values if the key does not exist yet.
    
    .EXAMPLE
        Read-DbatoolsConfigPersisted -Scope 127
    
        Read all persisted default configuration items in the default mandated order.
#>
    [OutputType([System.Collections.Hashtable])]
    [CmdletBinding()]
    Param (
        [Sqlcollaborative.Dbatools.Configuration.ConfigScope]
        $Scope,
        
        [string]
        $Module,
        
        [int]
        $ModuleVersion = 1,
        
        [System.Collections.Hashtable]
        $Hashtable,
        
        [switch]
        $Default
    )
    
    begin
    {
        #region Helper Functions
        function New-ConfigItem
        {
            [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
            [CmdletBinding()]
            param (
                $FullName,
                
                $Value,
                
                $Type,
                
                [switch]
                $KeepPersisted,
                
                [switch]
                $Enforced,
                
                [switch]
                $Policy
            )
            
            [pscustomobject]@{
                FullName      = $FullName
                Value         = $Value
                Type          = $Type
                KeepPersisted = $KeepPersisted
                Enforced      = $Enforced
                Policy        = $Policy
            }
        }
        
        function Read-Registry
        {
            [CmdletBinding()]
            param (
                $Path,
                
                [switch]
                $Enforced
            )
            
            if (-not (Test-Path $Path)) { return }
            
            $common = 'PSPath', 'PSParentPath', 'PSChildName', 'PSDrive', 'PSProvider'
            
            foreach ($item in ((Get-ItemProperty -Path $Path -ErrorAction Ignore).PSObject.Properties | Where-Object Name -NotIn $common))
            {
                if ($item.Value -like "Object:*")
                {
                    $data = $item.Value.Split(":", 2)
                    New-ConfigItem -FullName $item.Name -Type $data[0] -Value $data[1] -KeepPersisted -Enforced:$Enforced -Policy
                }
                else
                {
                    try { New-ConfigItem -FullName $item.Name -Value ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::ConvertFromPersistedValue($item.Value)) -Policy }
                    catch
                    {
                        Write-Message -Level Warning -Message "Failed to load configuration from Registry: $($item.Name)" -ErrorRecord $_ -Target "$Path : $($item.Name)"
                    }
                }
            }
        }
        #endregion Helper Functions
        
        if (-not $Hashtable) { $results = @{ } }
        else { $results = $Hashtable }
        
        if ($Module) { $filename = "$($Module.ToLower())-$($ModuleVersion).json" }
        else { $filename = "psf_config.json" }
    }
    process
    {
        #region File - Computer Wide
        if ($Scope -band 64)
        {
            foreach ($item in (Read-DbatoolsConfigFile -Path (Join-Path $script:path_FileSystem $filename)))
            {
                if (-not $Default) { $results[$item.FullName] = $item }
                elseif (-not $results.ContainsKey($item.FullName)) { $results[$item.FullName] = $item }
            }
        }
        #endregion File - Computer Wide
        
        #region Registry - Computer Wide
        if (($Scope -band 4) -and (-not $script:NoRegistry))
        {
            foreach ($item in (Read-Registry -Path $script:path_RegistryMachineDefault))
            {
                if (-not $Default) { $results[$item.FullName] = $item }
                elseif (-not $results.ContainsKey($item.FullName)) { $results[$item.FullName] = $item }
            }
        }
        #endregion Registry - Computer Wide
        
        #region File - User Shared
        if ($Scope -band 32)
        {
            foreach ($item in (Read-DbatoolsConfigFile -Path (Join-Path $script:path_FileUserShared $filename)))
            {
                if (-not $Default) { $results[$item.FullName] = $item }
                elseif (-not $results.ContainsKey($item.FullName)) { $results[$item.FullName] = $item }
            }
        }
        #endregion File - User Shared
        
        #region Registry - User Shared
        if (($Scope -band 1) -and (-not $script:NoRegistry))
        {
            foreach ($item in (Read-Registry -Path $script:path_RegistryUserDefault))
            {
                if (-not $Default) { $results[$item.FullName] = $item }
                elseif (-not $results.ContainsKey($item.FullName)) { $results[$item.FullName] = $item }
            }
        }
        #endregion Registry - User Shared
        
        #region File - User Local
        if ($Scope -band 16)
        {
            foreach ($item in (Read-DbatoolsConfigFile -Path (Join-Path $script:path_FileUserLocal $filename)))
            {
                if (-not $Default) { $results[$item.FullName] = $item }
                elseif (-not $results.ContainsKey($item.FullName)) { $results[$item.FullName] = $item }
            }
        }
        #endregion File - User Local
        
        #region Registry - User Enforced
        if (($Scope -band 2) -and (-not $script:NoRegistry))
        {
            foreach ($item in (Read-Registry -Path $script:path_RegistryUserEnforced -Enforced))
            {
                if (-not $Default) { $results[$item.FullName] = $item }
                elseif (-not $results.ContainsKey($item.FullName)) { $results[$item.FullName] = $item }
            }
        }
        #endregion Registry - User Enforced
        
        #region Registry - System Enforced
        if (($Scope -band 8) -and (-not $script:NoRegistry))
        {
            foreach ($item in (Read-Registry -Path $script:path_RegistryMachineEnforced -Enforced))
            {
                if (-not $Default) { $results[$item.FullName] = $item }
                elseif (-not $results.ContainsKey($item.FullName)) { $results[$item.FullName] = $item }
            }
        }
        #endregion Registry - System Enforced
    }
    end
    {
        $results
    }
}
tools\dbatools\internal\functions\configuration\Register-DbatoolsConfigValidation.ps1
function Register-DbatoolsConfigValidation {
    <#
        .SYNOPSIS
            Registers a validation scriptblock for use with the configuration system.

        .DESCRIPTION
            Registers a validation scriptblock for use with the configuration system.

            The scriptblock must be designed according to a few guidelines:
            - It must not throw exceptions
            - It must accept a single parameter (the value to be tested)
            - It must return an object with three properties: 'Message', 'Value' and 'Success'.
            The Success property should be boolean and indicate whether the value is valid.
            The Value property contains the validated input. The scriptblock may legally convert the input (For example from string to int in case of integer validation)
            The message contains a string that will be passed along to an exception in case the input is NOT valid.

        .PARAMETER Name
            The name under which to register the validation scriptblock

        .PARAMETER ScriptBlock
            The scriptblock to register

        .EXAMPLE
            PS C:\> Register-DbatoolsConfigValidation -Name IntPositive -ScriptBlock $scriptblock

            Registers the scriptblock stored in $scriptblock as validation with the name IntPositive
       #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]
        $Name,

        [Parameter(Mandatory)]
        [ScriptBlock]
        $ScriptBlock
    )

    [Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Validation[$Name.ToLower()] = $ScriptBlock
}
tools\dbatools\internal\functions\configuration\Write-DbatoolsConfigFile.ps1
function Write-DbatoolsConfigFile
{
<#
    .SYNOPSIS
        Handles config export to file.
    
    .DESCRIPTION
        Handles config export to file.
    
    .PARAMETER Config
        The configuration items to export.
    
    .PARAMETER Path
        The path to export to.
        Needs to point to the specific file to export to.
        Will create the folder structure if needed.
    
    .PARAMETER Replace
        Completely replaces previous file contents.
        By default, it will integrate settings into one coherent configuration file.
    
    .EXAMPLE
        PS C:\> Write-DbatoolsConfigFile -Config $items -Path .\file.json
    
        Exports all settings stored in $items to .\file.json.
        If the file already exists, the new settings will be merged into the existing file.
#>
    [CmdletBinding()]
    Param (
        [Sqlcollaborative.Dbatools.Configuration.Config[]]
        $Config,
        
        [string]
        $Path,
        
        [switch]
        $Replace
    )
    
    begin
    {
        $parent = Split-Path -Path $Path
        if (-not (Test-Path $parent))
        {
            $null = New-Item $parent -ItemType Directory -Force
        }
        
        $data = @{ }
        if ((Test-Path $Path) -and (-not $Replace))
        {
            foreach ($item in (Get-Content -Path $Path -Encoding UTF8 | ConvertFrom-Json))
            {
                $data[$item.FullName] = $item
            }
        }
    }
    process
    {
        foreach ($item in $Config)
        {
            $datum = @{
                Version  = 1
                FullName = $item.FullName
            }
            if ($item.SimpleExport)
            {
                $datum["Data"] = $item.Value
            }
            else
            {
                $persisted = [Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::ConvertToPersistedValue($item.Value)
                $datum["Value"] = $persisted.PersistedValue
                $datum["Type"] = $persisted.PersistedType
                $datum["Style"] = "default"
            }
            
            $data[$item.FullName] = [pscustomobject]$datum
        }
    }
    end
    {
        $data.Values | ConvertTo-Json | Set-Content -Path $Path -Encoding UTF8 -ErrorAction Stop
    }
}
tools\dbatools\internal\functions\Connect-AsServer.ps1
function Connect-AsServer {
    <#
.SYNOPSIS
Internal function that creates SMO server object.

.DESCRIPTION
Internal function that creates SMO server object.

.PARAMETER AsServer
Analysis Server

.PARAMETER ParameterConnection
Shorten the timeout

.NOTES
Website: https://dbatools.io
Copyright: (c) 2018 by dbatools, licensed under MIT
License: MIT https://opensource.org/licenses/MIT

.EXAMPLE
Connect-AsServer -AsServer localhost
Connects to SSAS on the local server

    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [object]$AsServer,
        [switch]$ParameterConnection
    )

    if ($AsServer.GetType() -eq [Microsoft.AnalysisServices.Server]) {

        if ($ParameterConnection) {
            $paramserver = New-Object Microsoft.AnalysisServices.Server
            $paramserver.Connect("Data Source=$($AsServer.Name);Connect Timeout=2")
            return $paramserver
        }

        if ($AsServer.Connected -eq $false) { $AsServer.Connect("Data Source=$($AsServer.Name);Connect Timeout=3") }
        return $AsServer
    }

    $server = New-Object Microsoft.AnalysisServices.Server

    try {
        if ($ParameterConnection) {
            $server.Connect("Data Source=$AsServer;Connect Timeout=2")
        } else { $server.Connect("Data Source=$AsServer;Connect Timeout=3") }
    } catch {
        $message = $_.Exception.InnerException
        $message = $message.ToString()
        $message = ($message -Split '-->')[0]
        $message = ($message -Split 'at System.Data.SqlClient')[0]
        $message = ($message -Split 'at System.Data.ProviderBase')[0]
        throw "Can't connect to $asserver`: $message "
    }

    return $server
}
tools\dbatools\internal\functions\Connect-ReplicationDB.ps1
#Helper Function
function Connect-ReplicationDB {
    param (
        [object]$Server,
        [object]$Database
    )

    $repDB = New-Object Microsoft.SqlServer.Replication.ReplicationDatabase

    $repDB.Name = $Database.Name
    $repDB.ConnectionContext = $Server.ConnectionContext.SqlConnectionObject

    if (!$repDB.LoadProperties()) {
        Write-Message -Level Verbose -Message "Skipping $($Database.Name). Failed to load properties correctly."
    }

    return $repDB
}
tools\dbatools\internal\functions\Connect-SqlInstance.ps1
function Connect-SqlInstance {
    <#
    .SYNOPSIS
        Internal function to establish smo connections.

    .DESCRIPTION
        Internal function to establish smo connections.

        Can interpret any of the following types of information:
        - String
        - Smo Server objects
        - Smo Linked Server objects

        Related Docs, Pull Requests and Issues:

    Connect commands and alt Windows Credential fix
    https://github.com/sqlcollaborative/dbatools/pull/3835

    Connect-*Instance, fix errors with Windows logins
    https://github.com/sqlcollaborative/dbatools/pull/4426

    Invoke-DbaSqlQuery fails to use proper Windows credentials
    https://github.com/sqlcollaborative/dbatools/issues/3780

    Fixed auth issue
    https://github.com/sqlcollaborative/dbatools/pull/3809

    Connecting to an Instance of SQL Server
    https://docs.microsoft.com/en-us/sql/relational-databases/server-management-objects-smo/create-program/connecting-to-an-instance-of-sql-server

    SQL Server Connection Pooling (ADO.NET)
    https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-connection-pooling

    .PARAMETER SqlInstance
        The SQL Server instance to restore to.

    .PARAMETER SqlCredential
        Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.

    .PARAMETER ParameterConnection
        This call is for dynamic parameters only and is no longer used, actually.

    .PARAMETER AzureUnsupported
        Throw if Azure is detected but not supported

    .PARAMETER RegularUser
        The connection doesn't require SA privileges.
        By default, the assumption is that SA is no longer required.

    .PARAMETER MinimumVersion
       The minimum version that the calling command will support

    .PARAMETER StatementTimeout
        Sets the number of seconds a statement is given to run before failing with a timeout error.

    .EXAMPLE
        Connect-SqlInstance -SqlInstance sql2014

        Connect to the Server sql2014 with native credentials.
    #>
    [CmdletBinding()]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingEmptyCatchBlock", "")]
    param (
        [Parameter(Mandatory)]
        [object]$SqlInstance,
        [object]$SqlCredential,
        [switch]$ParameterConnection,
        [switch]$RegularUser = $true,
        [int]$StatementTimeout,
        [int]$MinimumVersion,
        [switch]$AzureUnsupported,
        [switch]$NonPooled
    )

    #region Utility functions
    function Invoke-TEPPCacheUpdate {
        [CmdletBinding()]
        param (
            [System.Management.Automation.ScriptBlock]$ScriptBlock
        )

        try {
            [ScriptBlock]::Create($scriptBlock).Invoke()
        } catch {
            # If the SQL Server version doesn't support the feature, we ignore it and silently continue
            if ($_.Exception.InnerException.InnerException.GetType().FullName -eq "Microsoft.SqlServer.Management.Sdk.Sfc.InvalidVersionEnumeratorException") {
                return
            }

            if ($ENV:APPVEYOR_BUILD_FOLDER -or ([Sqlcollaborative.Dbatools.Message.MEssageHost]::DeveloperMode)) { throw }
            else {
                Write-Message -Level Warning -Message "Failed TEPP Caching: $($scriptBlock.ToString() | Select-String '"(.*?)"' | ForEach-Object { $_.Matches[0].Groups[1].Value })" -ErrorRecord $_ 3>$null
            }
        }
    }
    #endregion Utility functions

    #region Ensure Credential integrity
    <#
    Usually, the parameter type should have been not object but off the PSCredential type.
    When binding null to a PSCredential type parameter on PS3-4, it'd then show a prompt, asking for username and password.

    In order to avoid that and having to refactor lots of functions (and to avoid making regular scripts harder to read), we created this workaround.
    #>
    if ($SqlCredential) {
        if ($SqlCredential.GetType() -ne [System.Management.Automation.PSCredential]) {
            throw "The credential parameter was of a non-supported type. Only specify PSCredentials such as generated from Get-Credential. Input was of type $($SqlCredential.GetType().FullName)"
        }
    }
    #endregion Ensure Credential integrity

    #region Safely convert input into instance parameters
    <#
    This is a bit ugly, but:
    In some cases functions would directly pass their own input through when the parameter on the calling function was typed as [object[]].
    This would break the base parameter class, as it'd automatically be an array and the parameterclass is not designed to handle arrays (Shouldn't have to).

    Note: Multiple servers in one call were never supported, those old functions were liable to break anyway and should be fixed soonest.
    #>
    if ($SqlInstance.GetType() -eq [Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter]) {
        [DbaInstanceParameter]$ConvertedSqlInstance = $SqlInstance
        if ($ConvertedSqlInstance.Type -like "SqlConnection") {
            [DbaInstanceParameter]$ConvertedSqlInstance = New-Object Microsoft.SqlServer.Management.Smo.Server($ConvertedSqlInstance.InputObject)
        }
    } else {
        [DbaInstanceParameter]$ConvertedSqlInstance = [DbaInstanceParameter]($SqlInstance | Select-Object -First 1)

        if ($SqlInstance.Count -gt 1) {
            Write-Message -Level Warning -EnableException $true -Message "More than on server was specified when calling Connect-SqlInstance from $((Get-PSCallStack)[1].Command)"
        }
    }
    #endregion Safely convert input into instance parameters

    #region Input Object was a server object
    if ($ConvertedSqlInstance.InputObject.GetType() -eq [Microsoft.SqlServer.Management.Smo.Server]) {
        $server = $ConvertedSqlInstance.InputObject
        $authtypeSMO = $SqlCredential.UserName -like '*\*'
        if ($server.ConnectionContext.IsOpen -eq $false) {
            if ($NonPooled) {
                # When the Connect method is called, the connection is not automatically released.
                # The Disconnect method must be called explicitly to release the connection to the connection pool.
                # https://docs.microsoft.com/en-us/sql/relational-databases/server-management-objects-smo/create-program/disconnecting-from-an-instance-of-sql-server
                $server.ConnectionContext.Connect()
            } elseif ($authtypeSMO -eq "Windows Authentication with Credential") {
                # Make it connect in a natural way, hard to explain.
                # See https://docs.microsoft.com/en-us/sql/relational-databases/server-management-objects-smo/create-program/connecting-to-an-instance-of-sql-server
                $null = $server.Information.Version

                # Sometimes, however, the above may not connect as promised. Force it.
                # See https://github.com/sqlcollaborative/dbatools/pull/4426
                if ($server.ConnectionContext.IsOpen -eq $false) {
                    $server.ConnectionContext.Connect()
                }
            } else {
                # SqlConnectionObject.Open() enables connection pooling does not support
                # alternative Windows Credentials and passes default credentials
                # See https://github.com/sqlcollaborative/dbatools/pull/3809
                $server.ConnectionContext.SqlConnectionObject.Open()
            }
        }

        # Register the connected instance, so that the TEPP updater knows it's been connected to and starts building the cache
        [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::SetInstance($ConvertedSqlInstance.FullSmoName.ToLower(), $server.ConnectionContext.Copy(), ($server.ConnectionContext.FixedServerRoles -match "SysAdmin"))

        # Update cache for instance names
        if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["sqlinstance"] -notcontains $ConvertedSqlInstance.FullSmoName.ToLower()) {
            [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["sqlinstance"] += $ConvertedSqlInstance.FullSmoName.ToLower()
        }

        # Update lots of registered stuff
        if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppSyncDisabled) {
            $FullSmoName = $ConvertedSqlInstance.FullSmoName.ToLower()
            foreach ($scriptBlock in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppGatherScriptsFast)) {
                Invoke-TEPPCacheUpdate -ScriptBlock $scriptBlock
            }
        }

        # Make ComputerName easily available in the server object
        if (-not $server.ComputerName) {
            if (-not $server.NetName -or $SqlInstance -match '\.') {
                $parsedcomputername = $ConvertedSqlInstance.ComputerName
            } else {
                $parsedcomputername = $server.NetName
            }
            Add-Member -InputObject $server -NotePropertyName ComputerName -NotePropertyValue $parsedcomputername -Force
        }
        return $server
    }
    #endregion Input Object was a server object

    #region Input Object was anything else

    $server = New-Object Microsoft.SqlServer.Management.Smo.Server $ConvertedSqlInstance.FullSmoName
    $server.ConnectionContext.ApplicationName = "dbatools PowerShell module - dbatools.io"
    if ($ConvertedSqlInstance.IsConnectionString) { $server.ConnectionContext.ConnectionString = $ConvertedSqlInstance.InputObject }

    try {
        if (Test-Bound -ParameterName 'StatementTimeout') {
            $server.ConnectionContext.StatementTimeout = $StatementTimeout
        }
        $server.ConnectionContext.ConnectTimeout = [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::SqlConnectionTimeout

        if ($null -ne $SqlCredential.UserName) {
            $username = ($SqlCredential.UserName).TrimStart("\")

            # support both ad\username and username@ad
            if ($username -like "*\*" -or $username -like "*@*") {
                if ($username -like "*\*") {
                    $domain, $login = $username.Split("\")
                    $authtype = "Windows Authentication with Credential"
                    if ($domain) {
                        $formatteduser = "$login@$domain"
                    } else {
                        $formatteduser = $username.Split("\")[1]
                    }
                } else {
                    $formatteduser = $SqlCredential.UserName
                }

                $server.ConnectionContext.LoginSecure = $true
                $server.ConnectionContext.ConnectAsUser = $true
                $server.ConnectionContext.ConnectAsUserName = $formatteduser
                $server.ConnectionContext.ConnectAsUserPassword = ($SqlCredential).GetNetworkCredential().Password
            } else {
                $authtype = "SQL Authentication"
                $server.ConnectionContext.LoginSecure = $false
                $server.ConnectionContext.set_Login($username)
                $server.ConnectionContext.set_SecurePassword($SqlCredential.Password)
            }
        }
    } catch { }

    try {
        if ($NonPooled) {
            # When the Connect method is called, the connection is not automatically released.
            # The Disconnect method must be called explicitly to release the connection to the connection pool.
            # https://docs.microsoft.com/en-us/sql/relational-databases/server-management-objects-smo/create-program/disconnecting-from-an-instance-of-sql-server
            $server.ConnectionContext.Connect()
        } elseif ($authtype -eq "Windows Authentication with Credential") {
            # Make it connect in a natural way, hard to explain.
            # See https://docs.microsoft.com/en-us/sql/relational-databases/server-management-objects-smo/create-program/connecting-to-an-instance-of-sql-server
            $null = $server.Information.Version

            # Sometimes, however, the above may not connect as promised. Force it.
            # See https://github.com/sqlcollaborative/dbatools/pull/4426
            if ($server.ConnectionContext.IsOpen -eq $false) {
                $server.ConnectionContext.Connect()
            }
        } else {
            # SqlConnectionObject.Open() enables connection pooling does not support
            # alternative Windows Credentials and passes default credentials
            # See https://github.com/sqlcollaborative/dbatools/pull/3809
            $server.ConnectionContext.SqlConnectionObject.Open()
        }
    } catch {
        $message = $_.Exception.InnerException.InnerException
        if ($message) {
            # This is messy but it works to provide users with straightforward & detailed errors
            $message = $message.ToString()
            $message = ($message -Split '-->')[0]
            $message = ($message -Split 'at System.Data.SqlClient')[0]
            $message = ($message -Split 'at System.Data.ProviderBase')[0]

            if ($message -match "network path was not found") {
                $message = "Can't connect to $sqlinstance`: System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections."
            }

            throw "Can't connect to $ConvertedSqlInstance`: $message "
        } else {
            throw $_
        }
    }

    if ($MinimumVersion -and $server.VersionMajor) {
        if ($server.versionMajor -lt $MinimumVersion) {
            throw "SQL Server version $MinimumVersion required - $server not supported."
        }
    }

    if ($AzureUnsupported -and $server.DatabaseEngineType -eq "SqlAzureDatabase") {
        throw "Azure SQL Database not supported"
    }

    if (-not $RegularUser) {
        if ($server.ConnectionContext.FixedServerRoles -notmatch "SysAdmin") {
            throw "Not a sysadmin on $ConvertedSqlInstance. Quitting."
        }
    }
    #'PrimaryFilePath' seems the culprit for slow SMO on databases
    $Fields2000_Db = 'Collation', 'CompatibilityLevel', 'CreateDate', 'ID', 'IsAccessible', 'IsFullTextEnabled', 'IsSystemObject', 'IsUpdateable', 'LastBackupDate', 'LastDifferentialBackupDate', 'LastLogBackupDate', 'Name', 'Owner', 'ReadOnly', 'RecoveryModel', 'ReplicationOptions', 'Status', 'Version'
    $Fields200x_Db = $Fields2000_Db + @('BrokerEnabled', 'DatabaseSnapshotBaseName', 'IsMirroringEnabled', 'Trustworthy')
    $Fields201x_Db = $Fields200x_Db + @('ActiveConnections', 'AvailabilityDatabaseSynchronizationState', 'AvailabilityGroupName', 'ContainmentType', 'EncryptionEnabled')

    $Fields2000_Login = 'CreateDate', 'DateLastModified', 'DefaultDatabase', 'DenyWindowsLogin', 'IsSystemObject', 'Language', 'LanguageAlias', 'LoginType', 'Name', 'Sid', 'WindowsLoginAccessType'
    $Fields200x_Login = $Fields2000_Login + @('AsymmetricKey', 'Certificate', 'Credential', 'ID', 'IsDisabled', 'IsLocked', 'IsPasswordExpired', 'MustChangePassword', 'PasswordExpirationEnabled', 'PasswordPolicyEnforced')
    $Fields201x_Login = $Fields200x_Login + @('PasswordHashAlgorithm')

    try {
        if ($Server.ServerType -ne 'SqlAzureDatabase') {
            $server.SetDefaultInitFields([Microsoft.SqlServer.Management.Smo.Trigger], 'IsSystemObject')
            $server.SetDefaultInitFields([Microsoft.SqlServer.Management.Smo.Schema], 'IsSystemObject')
            $server.SetDefaultInitFields([Microsoft.SqlServer.Management.Smo.SqlAssembly], 'IsSystemObject')
            $server.SetDefaultInitFields([Microsoft.SqlServer.Management.Smo.Table], 'IsSystemObject')
            $server.SetDefaultInitFields([Microsoft.SqlServer.Management.Smo.View], 'IsSystemObject')
            $server.SetDefaultInitFields([Microsoft.SqlServer.Management.Smo.StoredProcedure], 'IsSystemObject')
            $server.SetDefaultInitFields([Microsoft.SqlServer.Management.Smo.UserDefinedFunction], 'IsSystemObject')

            if ($server.VersionMajor -eq 8) {
                # 2000
                $initFieldsDb = New-Object System.Collections.Specialized.StringCollection
                [void]$initFieldsDb.AddRange($Fields2000_Db)
                $initFieldsLogin = New-Object System.Collections.Specialized.StringCollection
                [void]$initFieldsLogin.AddRange($Fields2000_Login)
                $server.SetDefaultInitFields([Microsoft.SqlServer.Management.Smo.Database], $initFieldsDb)
                $server.SetDefaultInitFields([Microsoft.SqlServer.Management.Smo.Login], $initFieldsLogin)
            } elseif ($server.VersionMajor -eq 9 -or $server.VersionMajor -eq 10) {
                # 2005 and 2008
                $initFieldsDb = New-Object System.Collections.Specialized.StringCollection
                [void]$initFieldsDb.AddRange($Fields200x_Db)
                $initFieldsLogin = New-Object System.Collections.Specialized.StringCollection
                [void]$initFieldsLogin.AddRange($Fields200x_Login)
                $server.SetDefaultInitFields([Microsoft.SqlServer.Management.Smo.Database], $initFieldsDb)
                $server.SetDefaultInitFields([Microsoft.SqlServer.Management.Smo.Login], $initFieldsLogin)
            } else {
                # 2012 and above
                $initFieldsDb = New-Object System.Collections.Specialized.StringCollection
                [void]$initFieldsDb.AddRange($Fields201x_Db)
                $initFieldsLogin = New-Object System.Collections.Specialized.StringCollection
                [void]$initFieldsLogin.AddRange($Fields201x_Login)
                $server.SetDefaultInitFields([Microsoft.SqlServer.Management.Smo.Database], $initFieldsDb)
                $server.SetDefaultInitFields([Microsoft.SqlServer.Management.Smo.Login], $initFieldsLogin)
            }
        }
    } catch {
        # perhaps a DLL issue, continue going
    }

    # Register the connected instance, so that the TEPP updater knows it's been connected to and starts building the cache
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::SetInstance($ConvertedSqlInstance.FullSmoName.ToLower(), $server.ConnectionContext.Copy(), ($server.ConnectionContext.FixedServerRoles -match "SysAdmin"))

    # Update cache for instance names
    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["sqlinstance"] -notcontains $ConvertedSqlInstance.FullSmoName.ToLower()) {
        [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["sqlinstance"] += $ConvertedSqlInstance.FullSmoName.ToLower()
    }

    # Update lots of registered stuff
    if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppSyncDisabled) {
        $FullSmoName = $ConvertedSqlInstance.FullSmoName.ToLower()
        foreach ($scriptBlock in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppGatherScriptsFast)) {
            Invoke-TEPPCacheUpdate -ScriptBlock $scriptBlock
        }
    }

    if (-not $server.ComputerName) {
        if (-not $server.NetName -or $SqlInstance -match '\.') {
            $parsedcomputername = $ConvertedSqlInstance.ComputerName
        } else {
            $parsedcomputername = $server.NetName
        }
        Add-Member -InputObject $server -NotePropertyName ComputerName -NotePropertyValue $parsedcomputername -Force
    }
    return $server
    #endregion Input Object was anything else
}
tools\dbatools\internal\functions\Convert-ByteToHexString.ps1
function Convert-ByteToHexString {
    <#
    .SYNOPSIS
    Converts byte object into hex string

    .DESCRIPTION
    Converts byte object ([byte[]]@(1,100,23,54)) into the hex string (e.g. '0x01641736')
    Used when working with SMO logins and their byte parameters: sids and hashed passwords

    .PARAMETER InputObject
    Input byte[] object (e.g. [byte[]]@(18,52))

    .NOTES
    Tags: Login, Internal
    Author: Kirill Kravtsov (@nvarscar)
    dbatools PowerShell module (https://dbatools.io, [email protected])
   Copyright: (c) 2018 by dbatools, licensed under MIT
    License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
    Convert-ByteToHexString ([byte[]]@(1,100,23,54))

    Returns hex string '0x01641736'

    .EXAMPLE
    Convert-ByteToHexString 18,52

    Returns hex string '0x1234'
    #>
    param ([byte[]]$InputObject)
    $outString = "0x"
    $InputObject | ForEach-Object { $outString += ("{0:X}" -f $_).PadLeft(2, "0") }
    $outString
}
tools\dbatools\internal\functions\Convert-DbaLsn.ps1
function Convert-DbaLSN {
    <#
    .SYNOPSIS
        Converts Lsns betweent Hex and/or numeric formats

    .DESCRIPTION
        Function takes an LSN in either split Hexadecimal format () or numberic

        It then returns both formats in an object

    .PARAMETER LSN
        The LSN value to be converted

    .EXAMPLE
        PS C:\ $output = Convert-DbaLSN -LSN 0000002f:000044aa:002b

        Will return object $Output with the following value
        $Output.HexLSN = 0000002f:000044aa:002b
        $Output.NumbericLSN =
          #>
    [CmdletBinding()]
    param(
        [string]$LSN,
        [Alias('Silent')]
        [switch]$EnableException
    )

    if ($LSN -match '^[a-fA-F0-9]{8}:[a-fA-F0-9]{8}:[a-fA-F0-9]{4}$') {
        Write-Message -Message 'Hexadecimal LSN passed in, converting to numeric' -Level Verbose
        $sections = $LSN.Split(':')
        $sect1 = [System.Convert]::ToInt64($sections[0], 16).ToString()
        $sect2 = [System.Convert]::ToInt64($sections[1], 16).ToString().PadLeft(10, '0')
        $sect3 = [System.Convert]::ToInt64($sections[2], 16).ToString().PadLeft(5, '0')
        $Hexadecimal = $LSN
        $Numeric = $sect1 + $sect2 + $sect3

    } elseif ($LSN -match '^[0-9]{15}[0-9]+$') {
        Write-Message -Message 'Numeric LSN passed in, converting to Hexadecimal' -Level Verbose
        $sect1 = '{0:x}' -f [System.Convert]::ToString($LSN.Substring(0, $LSN.length - 15), 16).PadLeft(8, '0')
        $sect2 = '{0:x}' -f [System.Convert]::ToString($LSN.Substring($lsn.length - 14, 9), 16).PadLeft(8, '0')
        $sect3 = '{0:x}' -f [System.Convert]::ToString($LSN.Substring($lsn.length - 5, 5), 16).PadLeft(4, '0')
        $Numeric = $LSN
        $Hexadecimal = $sect1 + ':' + $sect2 + ':' + $sect3
    } else {
        Stop-Function -Message 'LSN passed in is neither Numeric nor in the correct hexadecimal format'
        return
    }

    [PSCustomObject]@{
        Hexadecimal = $Hexadecimal
        Numeric     = $Numeric
    }
}
tools\dbatools\internal\functions\Convert-DbaTimelineStatusColor.ps1
function Convert-DbaTimelineStatusColor {
    <#
        .SYNOPSIS
            Converts literal string status to a html color

        .DESCRIPTION
            This function acceptes Agnet Job status as literal string input and covnerts to html color.
            This is internal function, part of ConvertTo-DbaTimeline

        .PARAMETER Status

            The Status input parameter must be a valid SQL Agent Job status as literal string as defined in MS Books:
                Status of the job execution:
                    Failed
                    Succeeded
                    Retry
                    Canceled
                    In Progress

        .NOTES
            Tags: Internal
            Author: Marcin Gminski (@marcingminski)

            Dependency: None
            Requirements: None

            Website: https://dbatools.io
            Copyright: (c) 2018 by dbatools, licensed under MIT
-           License: MIT https://opensource.org/licenses/MIT

        .LINK
            --internal function, not exposed to end user

        .EXAMPLE
            Convert-DbaTimelineStatusColor ("Succeeded")

            Returned string: #36B300
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]
        $Status
    )
    $out = switch ($Status) {
        "Failed" {"#FF3D3D"}
        "Succeeded" {"#36B300"}
        "Retry" {"#FFFF00"}
        "Canceled" {"#C2C2C2"}
        "In Progress" {"#00CCFF"}
        default {"#FF00CC"}
    }
    return $out
}
tools\dbatools\internal\functions\Convert-DbVersionToSqlVersion.ps1
function Convert-DbVersionToSqlVersion {
    <#
.SYNOPSIS
Internal function that makes db versions human readable

.DESCRIPTION
Internal function that makes db versions human readable

.PARAMETER dbversion
Analysis Server

.EXAMPLE
Convert-DbVersionToSqlVersion -dbversion 856

Returns "SQL Server vNext CTP1"

    #>
    param (
        [string]$dbversion
    )

    $dbversion = switch ($dbversion) {
        869 { "SQL Server 2017"}
        856 { "SQL Server vNext CTP1" }
        852 { "SQL Server 2016" }
        829 { "SQL Server 2016 Prerelease" }
        782 { "SQL Server 2014" }
        706 { "SQL Server 2012" }
        684 { "SQL Server 2012 CTP1" }
        661 { "SQL Server 2008 R2" }
        660 { "SQL Server 2008 R2" }
        655 { "SQL Server 2008 SP2+" }
        612 { "SQL Server 2005" }
        611 { "SQL Server 2005" }
        539 { "SQL Server 2000" }
        515 { "SQL Server 7.0" }
        408 { "SQL Server 6.5" }
        default { $dbversion }
    }

    return $dbversion
}
tools\dbatools\internal\functions\Convert-HexStringToByte.ps1
function Convert-HexStringToByte {
    <#
    .SYNOPSIS
    Converts hex string into byte object

    .DESCRIPTION
    Converts hex string (e.g. '0x01641736') into the byte object ([byte[]]@(1,100,23,54))
    Used when working with SMO logins and their byte parameters: sids and hashed passwords

    .PARAMETER InputObject
    Input hex string (e.g. '0x1234' or 'DBA2FF')

    .NOTES
    Tags: Login, Internal
    Author: Kirill Kravtsov (@nvarscar)
    dbatools PowerShell module (https://dbatools.io, [email protected])
   Copyright: (c) 2018 by dbatools, licensed under MIT
    License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
    Convert-HexStringToByte '0x01641736'

    Returns byte[] object [byte[]]@(1,100,23,54)

    .EXAMPLE
    Convert-HexStringToByte '1234'

    Returns byte[] object [byte[]]@(18,52)
    #>
    param (
        [string]$InputObject
    )
    $hexString = $InputObject.TrimStart("0x")
    if ($hexString.Length % 2 -eq 1) { $hexString = '0' + $hexString }
    [byte[]]$outByte = $null; $outByte += 0 .. (($hexString.Length) / 2 - 1) | ForEach-Object { [Int16]::Parse($hexString.Substring($_ * 2, 2), 'HexNumber') }
    Return $outByte
}
tools\dbatools\internal\functions\ConvertTo-JsDate.ps1
function ConvertTo-JsDate {
    <#
        .SYNOPSIS
            Converts Datetime input to a Java Script date format

        .DESCRIPTION
            This function acceptes date time input and converts to a Java script compatible format.
            Java Script date time format:
                New date (yyyy, MM, dd, HH, mm, ss)

            This is internal function part of ConvertTo-DbaTimeline

        .PARAMETER InputDate

            The InputDate parameter must be a valid datetime type

        .NOTES
            Tags: Internal
            Author: Marcin Gminski (@marcingminski)

            Dependency: None
            Requirements: None

            Website: https://dbatools.io
            Copyright: (c) 2018 by dbatools, licensed under MIT
-           License: MIT https://opensource.org/licenses/MIT

        .LINK
            --internal function, not exposed to end user

        .EXAMPLE
            ConvertTo-JsDate (Get-Date)

            Returned output: new Date(2018, 7, 14, 07, 40, 42)
       #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [datetime]
        $InputDate
    )
    [string]$out = "new Date($(Get-Date $InputDate -format "yyyy"), $($(Get-Date $InputDate -format "MM")-1), $(Get-Date $InputDate -format "dd"), $(Get-Date $InputDate -format "HH"), $(Get-Date $InputDate -format "mm"), $(Get-Date $InputDate -format "ss"))"
    return $out
}
tools\dbatools\internal\functions\Disconnect-Regserver.ps1
function Disconnect-Regserver ($Server) {
    $i = 0
    do { $server = $server.Parent }
    until ($null -ne $server.ServerConnection -or $i++ -gt 20)
    if ($server.ServerConnection) {
        $server.ServerConnection.Disconnect()
    }
}
tools\dbatools\internal\functions\Find-SqlServerUpdate.ps1
function Find-SqlServerUpdate {
    <#
        .SYNOPSIS
            Returns a SQL Server KB filesystem object based on parameters
        .DESCRIPTION
            Recursively searches specified folder for a file that matches the following pattern:
            "SQLServer$MajorVersion*-KB$KB-*$Architecture*.exe"

        .EXAMPLE
            PS> Find-SqlServerUpdate -MajorVersion 2016 -KB 412348 -Path \\my\updates

            Looks for SQLServer2016*-KB412348-*x64*.exe in \\my\updates and all the subfolders
    #>
    [OutputType('System.IO.FileInfo')]
    [CmdletBinding()]
    Param
    (
        [DbaInstanceParameter]$ComputerName,
        [pscredential]$Credential,
        [ValidateSet('Default', 'Basic', 'Negotiate', 'NegotiateWithImplicitCredential', 'Credssp', 'Digest', 'Kerberos')]
        [string]$Authentication = 'Default',
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$MajorVersion,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$KB,
        [ValidateSet('x86', 'x64')]
        [string]$Architecture = 'x64',
        [string[]]$Path = (Get-DbatoolsConfigValue -Name 'Path.SQLServerUpdates'),
        [bool]$EnableException = $EnableException

    )
    begin {
    }
    process {
        if (!$Path) {
            Stop-Function -Message "Path to SQL Server updates folder is not set. Consider running Set-DbatoolsConfig -Name Path.SQLServerUpdates -Value '\\path\to\updates' or specify the path in the original command"
            return
        }
        $filter = "SQLServer$MajorVersion*-KB$KB-*$Architecture*.exe"
        Write-Message -Level Verbose -Message "Using filter [$filter] to check for updates in $Path"
        $getFileScript = {
            Param (
                $Path,
                $Filter
            )
            foreach ($folder in (Get-Item -Path $Path -ErrorAction Stop)) {
                $file = Get-ChildItem -Path $folder -Filter $filter -File -Recurse -ErrorAction Stop
                if ($file) {
                    return $file | Select-Object -First 1
                }
            }
        }
        $params = @{
            ComputerName   = $ComputerName
            Credential     = $Credential
            Authentication = $Authentication
            ScriptBlock    = $getFileScript
            ArgumentList   = @($Path, $filter)
            ErrorAction    = 'Stop'
            Raw            = $true
        }
        try {
            Invoke-CommandWithFallback @params
        } catch {
            Stop-Function -Message "Failed to enumerate files in $Path" -ErrorRecord $_
            return
        }
    }
}
tools\dbatools\internal\functions\flowcontrol\Invoke-Parallel.ps1
function Invoke-Parallel {
    <#
    .SYNOPSIS
        Function to control parallel processing using runspaces

    .DESCRIPTION
        Function to control parallel processing using runspaces

            Note that each runspace will not have access to variables and commands loaded in your session or in other runspaces by default.
            This behaviour can be changed with parameters.

    .PARAMETER ScriptFile
        File to run against all input objects.  Must include parameter to take in the input object, or use $args.  Optionally, include parameter to take in parameter.  Example: C:\script.ps1

    .PARAMETER ScriptBlock
        Scriptblock to run against all computers.

        You may use $Using:<Variable> language in PowerShell 3 and later.

            The parameter block is added for you, allowing behaviour similar to foreach-object:
                Refer to the input object as $_.
                Refer to the parameter parameter as $parameter

    .PARAMETER InputObject
        Run script against these specified objects.

    .PARAMETER Parameter
        This object is passed to every script block.  You can use it to pass information to the script block; for example, the path to a logging folder

            Reference this object as $parameter if using the scriptblock parameterset.

    .PARAMETER ImportVariables
        If specified, get user session variables and add them to the initial session state

    .PARAMETER ImportModules
        If specified, get loaded modules and pssnapins, add them to the initial session state

    .PARAMETER Throttle
        Maximum number of threads to run at a single time.

    .PARAMETER SleepTimer
        Milliseconds to sleep after checking for completed runspaces and in a few other spots.  I would not recommend dropping below 200 or increasing above 500

    .PARAMETER RunspaceTimeout
        Maximum time in seconds a single thread can run.  If execution of your code takes longer than this, it is disposed.  Default: 0 (seconds)

        WARNING:  Using this parameter requires that maxQueue be set to throttle (it will be by default) for accurate timing.  Details here:
        http://gallery.technet.microsoft.com/Run-Parallel-Parallel-377fd430

    .PARAMETER NoCloseOnTimeout
        Do not dispose of timed out tasks or attempt to close the runspace if threads have timed out. This will prevent the script from hanging in certain situations where threads become non-responsive, at the expense of leaking memory within the PowerShell host.

    .PARAMETER MaxQueue
        Maximum number of powershell instances to add to runspace pool.  If this is higher than $throttle, $timeout will be inaccurate

        If this is equal or less than throttle, there will be a performance impact

        The default value is $throttle times 3, if $runspaceTimeout is not specified
        The default value is $throttle, if $runspaceTimeout is specified

    .PARAMETER LogFile
        Path to a file where we can log results, including run time for each thread, whether it completes, completes with errors, or times out.

    .PARAMETER AppendLog
        Append to existing log

    .PARAMETER Quiet
        Disable progress bar

    .EXAMPLE
        Each example uses Test-ForPacs.ps1 which includes the following code:
            param($computer)

            if(test-connection $computer -count 1 -quiet -BufferSize 16){
                $object = [pscustomobject] @{
                    Computer=$computer;
                    Available=1;
                    Kodak=$(
                        if((test-path "\\$computer\c$\users\public\desktop\Kodak Direct View Pacs.url") -or (test-path "\\$computer\c$\documents and settings\all users\desktop\Kodak Direct View Pacs.url") ){"1"}else{"0"}
                    )
                }
            }
            else{
                $object = [pscustomobject] @{
                    Computer=$computer;
                    Available=0;
                    Kodak="NA"
                }
            }

            $object

    .EXAMPLE
        Invoke-Parallel -scriptfile C:\public\Test-ForPacs.ps1 -inputobject $(get-content C:\pcs.txt) -runspaceTimeout 10 -throttle 10

            Pulls list of PCs from C:\pcs.txt,
            Runs Test-ForPacs against each
            If any query takes longer than 10 seconds, it is disposed
            Only run 10 threads at a time

    .EXAMPLE
        Invoke-Parallel -scriptfile C:\public\Test-ForPacs.ps1 -inputobject c-is-ts-91, c-is-ts-95

            Runs against c-is-ts-91, c-is-ts-95 (-computername)
            Runs Test-ForPacs against each

    .EXAMPLE
        $stuff = [pscustomobject] @{
            ContentFile = "windows\system32\drivers\etc\hosts"
            Logfile = "C:\temp\log.txt"
        }

        $computers | Invoke-Parallel -parameter $stuff {
            $contentFile = join-path "\\$_\c$" $parameter.contentfile
            Get-Content $contentFile |
                set-content $parameter.logfile
        }

        This example uses the parameter argument.  This parameter is a single object.  To pass multiple items into the script block, we create a custom object (using a PowerShell v3 language) with properties we want to pass in.

        Inside the script block, $parameter is used to reference this parameter object.  This example sets a content file, gets content from that file, and sets it to a predefined log file.

    .EXAMPLE
        $test = 5
        1..2 | Invoke-Parallel -ImportVariables {$_ * $test}

        Add variables from the current session to the session state.  Without -ImportVariables $Test would not be accessible

    .EXAMPLE
        $test = 5
        1..2 | Invoke-Parallel {$_ * $Using:test}

        Reference a variable from the current session with the $Using:<Variable> syntax.  Requires PowerShell 3 or later. Note that -ImportVariables parameter is no longer necessary.

    .FUNCTIONALITY
        PowerShell Language

    .NOTES
        Credit to Boe Prox for the base runspace code and $Using implementation
            http://learn-powershell.net/2012/05/10/speedy-network-information-query-using-powershell/
            http://gallery.technet.microsoft.com/scriptcenter/Speedy-Network-Information-5b1406fb#content
            https://github.com/proxb/PoshRSJob/

        Credit to T Bryce Yehl for the Quiet and NoCloseOnTimeout implementations

        Credit to Sergei Vorobev for the many ideas and contributions that have improved functionality, reliability, and ease of use

    .LINK
        https://github.com/RamblingCookieMonster/Invoke-Parallel
    #>
    [cmdletbinding(DefaultParameterSetName = 'ScriptBlock')]
    param (
        [Parameter(Position = 0, ParameterSetName = 'ScriptBlock')]
        [System.Management.Automation.ScriptBlock]$ScriptBlock,

        [Parameter(ParameterSetName = 'ScriptFile')]
        [ValidateScript( {Test-Path $_ -pathtype leaf})]
        $ScriptFile,

        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [Alias('CN', '__Server', 'IPAddress', 'Server', 'ComputerName')]
        [PSObject]$InputObject,

        [PSObject]$Parameter,

        [switch]$ImportVariables,
        [switch]$ImportModules,
        [switch]$ImportFunctions,

        [int]$Throttle = 20,
        [int]$SleepTimer = 200,
        [int]$RunspaceTimeout = 0,
        [switch]$NoCloseOnTimeout = $false,
        [int]$MaxQueue,

        [validatescript( {Test-Path (Split-Path $_ -parent)})]
        [switch] $AppendLog = $false,
        [string]$LogFile,

        [switch] $Quiet = $false
    )
    begin {
        # save default runspace
        $defaultrunspace = [System.Management.Automation.Runspaces.Runspace]::DefaultRunspace
        #No max queue specified?  Estimate one.
        #We use the script scope to resolve an odd PowerShell 2 issue where MaxQueue isn't seen later in the function
        if ( -not $PSBoundParameters.ContainsKey('MaxQueue') ) {
            if ($RunspaceTimeout -ne 0) { $script:MaxQueue = $Throttle }
            else { $script:MaxQueue = $Throttle * 3 }
        } else {
            $script:MaxQueue = $MaxQueue
        }
        $ProgressId = Get-Random
        Write-Verbose "Throttle: '$throttle' SleepTimer '$sleepTimer' runSpaceTimeout '$runspaceTimeout' maxQueue '$maxQueue' logFile '$logFile'"

        #If they want to import variables or modules, create a clean runspace, get loaded items, use those to exclude items
        if ($ImportVariables -or $ImportModules -or $ImportFunctions) {
            $StandardUserEnv = [powershell]::Create().addscript( {

                    #Get modules, snapins, functions in this clean runspace
                    $Modules = Get-Module | Select-Object -ExpandProperty Name
                    $Snapins = Get-PSSnapin | Select-Object -ExpandProperty Name
                    $Functions = Get-ChildItem function:\ | Select-Object -ExpandProperty Name

                    #Get variables in this clean runspace
                    #Called last to get vars like $? into session
                    $Variables = Get-Variable | Select-Object -ExpandProperty Name

                    #Return a hashtable where we can access each.
                    @{
                        Variables = $Variables
                        Modules   = $Modules
                        Snapins   = $Snapins
                        Functions = $Functions
                    }
                }).invoke()[0]

            if ($ImportVariables) {
                #Exclude common parameters, bound parameters, and automatic variables
                Function _temp {[cmdletbinding(SupportsShouldProcess)] param() }
                $VariablesToExclude = @( (Get-Command _temp | Select-Object -ExpandProperty parameters).Keys + $PSBoundParameters.Keys + $StandardUserEnv.Variables )
                Write-Verbose "Excluding variables $( ($VariablesToExclude | Sort-Object ) -join ", ")"

                # we don't use 'Get-Variable -Exclude', because it uses regexps.
                # One of the veriables that we pass is '$?'.
                # There could be other variables with such problems.
                # Scope 2 required if we move to a real module
                $UserVariables = @( Get-Variable | Where-Object { -not ($VariablesToExclude -contains $_.Name) } )
                Write-Verbose "Found variables to import: $( ($UserVariables | Select-Object -expandproperty Name | Sort-Object ) -join ", " | Out-String).`n"
            }
            if ($ImportModules) {
                $UserModules = @( Get-Module | Where-Object {$StandardUserEnv.Modules -notcontains $_.Name -and (Test-Path $_.Path -ErrorAction SilentlyContinue)} | Select-Object -ExpandProperty Path )
                $UserSnapins = @( Get-PSSnapin | Select-Object -ExpandProperty Name | Where-Object {$StandardUserEnv.Snapins -notcontains $_ } )
            }
            if ($ImportFunctions) {
                $UserFunctions = @( Get-ChildItem function:\ | Where-Object { $StandardUserEnv.Functions -notcontains $_.Name } )
            }
        }

        #region functions
        Function Get-RunspaceData {
            [cmdletbinding()]
            param( [switch]$Wait )
            #loop through runspaces
            #if $wait is specified, keep looping until all complete
            Do {
                #set more to false for tracking completion
                $more = $false

                #Progress bar if we have inputobject count (bound parameter)
                if (-not $Quiet) {
                    Write-Progress -Id $ProgressId -Activity "Running Query" -Status "Starting threads"`
                        -CurrentOperation "$startedCount threads defined - $totalCount input objects - $script:completedCount input objects processed"`
                        -PercentComplete $( Try { $script:completedCount / $totalCount * 100 } Catch {0} )
                }

                #run through each runspace.
                Foreach ($runspace in $runspaces) {

                    #get the duration - inaccurate
                    $currentdate = Get-Date
                    $runtime = $currentdate - $runspace.startTime
                    $runMin = [math]::Round( $runtime.totalminutes , 2 )

                    #set up log object
                    $log = "" | Select-Object Date, Action, Runtime, Status, Details
                    $log.Action = "Removing:'$($runspace.object)'"
                    $log.Date = $currentdate
                    $log.Runtime = "$runMin minutes"

                    #If runspace completed, end invoke, dispose, recycle, counter++
                    If ($runspace.Runspace.isCompleted) {

                        $script:completedCount++

                        #check if there were errors
                        if ($runspace.powershell.Streams.Error.Count -gt 0) {
                            #set the logging info and move the file to completed
                            $log.status = "CompletedWithErrors"
                            Write-Verbose ($log | ConvertTo-Csv -Delimiter ";" -NoTypeInformation)[1]
                            foreach ($ErrorRecord in $runspace.powershell.Streams.Error) {
                                Write-Error -ErrorRecord $ErrorRecord
                            }
                        } else {
                            #add logging details and cleanup
                            $log.status = "Completed"
                            Write-Verbose ($log | ConvertTo-Csv -Delimiter ";" -NoTypeInformation)[1]
                        }

                        #everything is logged, clean up the runspace
                        $runspace.powershell.EndInvoke($runspace.Runspace)
                        $runspace.powershell.dispose()
                        $runspace.Runspace = $null
                        $runspace.powershell = $null
                    }
                    #If runtime exceeds max, dispose the runspace
                    ElseIf ( $runspaceTimeout -ne 0 -and $runtime.totalseconds -gt $runspaceTimeout) {
                        $script:completedCount++
                        $timedOutTasks = $true

                        #add logging details and cleanup
                        $log.status = "TimedOut"
                        Write-Verbose ($log | ConvertTo-Csv -Delimiter ";" -NoTypeInformation)[1]
                        Write-Error "Runspace timed out at $($runtime.totalseconds) seconds for the object:`n$($runspace.object | out-string)"

                        #Depending on how it hangs, we could still get stuck here as dispose calls a synchronous method on the powershell instance
                        if (!$noCloseOnTimeout) { $runspace.powershell.dispose() }
                        $runspace.Runspace = $null
                        $runspace.powershell = $null
                        $completedCount++
                    }

                    #If runspace isn't null set more to true
                    ElseIf ($runspace.Runspace -ne $null ) {
                        $log = $null
                        $more = $true
                    }

                    #log the results if a log file was indicated
                    if ($logFile -and $log) {
                        ($log | ConvertTo-Csv -Delimiter ";" -NoTypeInformation)[1] | out-file $LogFile -append
                    }
                }

                #Clean out unused runspace jobs
                $temphash = $runspaces.clone()
                $temphash | Where-Object { $_.runspace -eq $Null } | ForEach-Object {
                    $Runspaces.remove($_)
                }

                #sleep for a bit if we will loop again
                if ($PSBoundParameters['Wait']) { Start-Sleep -milliseconds $SleepTimer }

                #Loop again only if -wait parameter and there are more runspaces to process
            } while ($more -and $PSBoundParameters['Wait'])

            #End of runspace function
        }
        #endregion functions

        #region Init

        if ($PSCmdlet.ParameterSetName -eq 'ScriptFile') {
            $ScriptBlock = [scriptblock]::Create( $(Get-Content $ScriptFile | out-string) )
        } elseif ($PSCmdlet.ParameterSetName -eq 'ScriptBlock') {
            #Start building parameter names for the param block
            [string[]]$ParamsToAdd = '$_'
            if ( $PSBoundParameters.ContainsKey('Parameter') ) {
                $ParamsToAdd += '$Parameter'
            }

            $UsingVariableData = $Null

            # This code enables $Using support through the AST.
            # This is entirely from  Boe Prox, and his https://github.com/proxb/PoshRSJob module; all credit to Boe!

            if ($PSVersionTable.PSVersion.Major -gt 2) {
                #Extract using references
                $UsingVariables = $ScriptBlock.ast.FindAll( {$args[0] -is [System.Management.Automation.Language.UsingExpressionAst]}, $True)

                If ($UsingVariables) {
                    $List = New-Object 'System.Collections.Generic.List`1[System.Management.Automation.Language.VariableExpressionAst]'
                    ForEach ($Ast in $UsingVariables) {
                        [void]$list.Add($Ast.SubExpression)
                    }

                    $UsingVar = $UsingVariables | Group-Object -Property SubExpression | ForEach-Object {$_.Group | Select-Object -First 1}

                    #Extract the name, value, and create replacements for each
                    $UsingVariableData = ForEach ($Var in $UsingVar) {
                        try {
                            $Value = Get-Variable -Name $Var.SubExpression.VariablePath.UserPath -ErrorAction Stop
                            [pscustomobject]@{
                                Name       = $Var.SubExpression.Extent.Text
                                Value      = $Value.Value
                                NewName    = ('$__using_{0}' -f $Var.SubExpression.VariablePath.UserPath)
                                NewVarName = ('__using_{0}' -f $Var.SubExpression.VariablePath.UserPath)
                            }
                        } catch {
                            Write-Error "$($Var.SubExpression.Extent.Text) is not a valid Using: variable!"
                        }
                    }
                    $ParamsToAdd += $UsingVariableData | Select-Object -ExpandProperty NewName -Unique

                    $NewParams = $UsingVariableData.NewName -join ', '
                    $Tuple = [Tuple]::Create($list, $NewParams)
                    $bindingFlags = [Reflection.BindingFlags]"Default,NonPublic,Instance"
                    $GetWithInputHandlingForInvokeCommandImpl = ($ScriptBlock.ast.gettype().GetMethod('GetWithInputHandlingForInvokeCommandImpl', $bindingFlags))

                    $StringScriptBlock = $GetWithInputHandlingForInvokeCommandImpl.Invoke($ScriptBlock.ast, @($Tuple))

                    $ScriptBlock = [scriptblock]::Create($StringScriptBlock)

                    Write-Verbose $StringScriptBlock
                }
            }

            $ScriptBlock = $ExecutionContext.InvokeCommand.NewScriptBlock("param($($ParamsToAdd -Join ", "))`r`n" + $Scriptblock.ToString())
        } else {
            Throw "Must provide ScriptBlock or ScriptFile"; Break
        }

        Write-Debug "`$ScriptBlock: $($ScriptBlock | Out-String)"
        Write-Verbose "Creating runspace pool and session states"

        #If specified, add variables and modules/snapins to session state
        $sessionstate = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
        $sessionstate.Variables.Add((New-Object -TypeName System.Management.Automation.Runspaces.SessionStateVariableEntry -ArgumentList 'WarningPreference', 'SilentlyContinue', $null))
        if ($ImportVariables -and $UserVariables.count -gt 0) {
            foreach ($Variable in $UserVariables) {
                $sessionstate.Variables.Add((New-Object -TypeName System.Management.Automation.Runspaces.SessionStateVariableEntry -ArgumentList $Variable.Name, $Variable.Value, $null) )
            }
        }
        if ($ImportModules) {
            if ($UserModules.count -gt 0) {
                foreach ($ModulePath in $UserModules) {
                    $sessionstate.ImportPSModule($ModulePath)
                }
            }
            if ($UserSnapins.count -gt 0) {
                foreach ($PSSnapin in $UserSnapins) {
                    [void]$sessionstate.ImportPSSnapIn($PSSnapin, [ref]$null)
                }
            }
        }
        if ($ImportFunctions -and $UserFunctions.count -gt 0) {
            foreach ($FunctionDef in $UserFunctions) {
                $sessionstate.Commands.Add((New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry -ArgumentList $FunctionDef.Name, $FunctionDef.ScriptBlock))
            }
        }

        #Create runspace pool
        $runspacepool = [runspacefactory]::CreateRunspacePool(1, $Throttle, $sessionstate, $Host)
        $runspacepool.Open()

        Write-Verbose "Creating empty collection to hold runspace jobs"
        $Script:runspaces = New-Object System.Collections.ArrayList

        #If inputObject is bound get a total count and set bound to true
        $bound = $PSBoundParameters.keys -contains "InputObject"
        if (-not $bound) {
            [System.Collections.ArrayList]$allObjects = @()
        }

        #Set up log file if specified
        if ( $LogFile -and (-not (Test-Path $LogFile) -or $AppendLog -eq $false)) {
            New-Item -ItemType file -Path $logFile -Force | Out-Null
            ("" | Select-Object -Property Date, Action, Runtime, Status, Details | ConvertTo-Csv -NoTypeInformation -Delimiter ";")[0] | Out-File $LogFile
        }

        #write initial log entry
        $log = "" | Select-Object -Property Date, Action, Runtime, Status, Details
        $log.Date = Get-Date
        $log.Action = "Batch processing started"
        $log.Runtime = $null
        $log.Status = "Started"
        $log.Details = $null
        if ($logFile) {
            ($log | convertto-csv -Delimiter ";" -NoTypeInformation)[1] | Out-File $LogFile -Append
        }
        $timedOutTasks = $false
        #endregion INIT
    }
    process {
        #add piped objects to all objects or set all objects to bound input object parameter
        if ($bound) {
            $allObjects = $InputObject
        } else {
            [void]$allObjects.add( $InputObject )
        }
    }
    end {
        #Use Try/Finally to catch Ctrl+C and clean up.
        try {
            #counts for progress
            $totalCount = $allObjects.count
            $script:completedCount = 0
            $startedCount = 0
            foreach ($object in $allObjects) {
                #region add scripts to runspace pool
                #Create the powershell instance, set verbose if needed, supply the scriptblock and parameters
                $powershell = [powershell]::Create()

                if ($VerbosePreference -eq 'Continue') {
                    [void]$PowerShell.AddScript( {$VerbosePreference = 'Continue'})
                }

                [void]$PowerShell.AddScript($ScriptBlock).AddArgument($object)

                if ($parameter) {
                    [void]$PowerShell.AddArgument($parameter)
                }

                # $Using support from Boe Prox
                if ($UsingVariableData) {
                    Foreach ($UsingVariable in $UsingVariableData) {
                        Write-Verbose "Adding $($UsingVariable.Name) with value: $($UsingVariable.Value)"
                        [void]$PowerShell.AddArgument($UsingVariable.Value)
                    }
                }

                #Add the runspace into the powershell instance
                $powershell.RunspacePool = $runspacepool

                #Create a temporary collection for each runspace
                $temp = "" | Select-Object PowerShell, StartTime, object, Runspace
                $temp.PowerShell = $powershell
                $temp.StartTime = Get-Date
                $temp.object = $object

                #Save the handle output when calling BeginInvoke() that will be used later to end the runspace
                $temp.Runspace = $powershell.BeginInvoke()
                $startedCount++

                #Add the temp tracking info to $runspaces collection
                Write-Verbose ( "Adding {0} to collection at {1}" -f $temp.object, $temp.starttime.tostring() )
                $runspaces.Add($temp) | Out-Null

                #loop through existing runspaces one time
                Get-RunspaceData

                #If we have more running than max queue (used to control timeout accuracy)
                #Script scope resolves odd PowerShell 2 issue
                $firstRun = $true
                while ($runspaces.count -ge $Script:MaxQueue) {
                    #give verbose output
                    if ($firstRun) {
                        Write-Verbose "$($runspaces.count) items running - exceeded $Script:MaxQueue limit."
                    }
                    $firstRun = $false

                    #run get-runspace data and sleep for a short while
                    Get-RunspaceData
                    Start-Sleep -Milliseconds $sleepTimer
                }
                #endregion add scripts to runspace pool
            }
            Write-Verbose ( "Finish processing the remaining runspace jobs: {0}" -f ( @($runspaces | Where-Object {$_.Runspace -ne $Null}).Count) )

            Get-RunspaceData -wait
            if (-not $quiet) {
                Write-Progress -Id $ProgressId -Activity "Running Query" -Status "Starting threads" -Completed
            }
        } finally {
            #Close the runspace pool, unless we specified no close on timeout and something timed out
            if ( ($timedOutTasks -eq $false) -or ( ($timedOutTasks -eq $true) -and ($noCloseOnTimeout -eq $false) ) ) {
                Write-Verbose "Closing the runspace pool"
                $runspacepool.close()
            }
            #collect garbage
            [gc]::Collect()
        }
        [System.Management.Automation.Runspaces.Runspace]::DefaultRunspace = $defaultrunspace
    }
}
tools\dbatools\internal\functions\flowcontrol\Invoke-SteppablePipeline.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Invoke-SteppablePipeline {
    <#
    .SYNOPSIS
        Allows using steppable pipelines on the pipeline.

    .DESCRIPTION
        Allows using steppable pipelines on the pipeline.

    .PARAMETER InputObject
        The object(s) to process
        Should only receive input from the pipeline!

    .PARAMETER Pipeline
        The pipeline to execute

    .EXAMPLE
        PS C:\> Get-ChildItem | Invoke-SteppablePipeline -Pipeline $steppablePipeline

        Processes the object returned by Get-ChildItem in the pipeline defined
    #>
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        $InputObject,

        [Parameter(Mandatory)]
        $Pipeline
    )

    process {
        $Pipeline.Process($InputObject)
    }
}
tools\dbatools\internal\functions\flowcontrol\Stop-Function.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#

function Stop-Function {
    <#
    .SYNOPSIS
        Function that interrupts a function.

    .DESCRIPTION
        Function that interrupts a function.

        This function is a utility function used by other functions to reduce error catching overhead.
        It is designed to allow gracefully terminating a function with a warning by default and also allow opt-in into terminating errors.
        It also allows simple integration into loops.

        Note:
        When calling this function with the intent to terminate the calling function in non-EnableException mode too, you need to add a return below the call.

    .PARAMETER Message
        A message to pass along, explaining just what the error was.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER Category
        What category does this termination belong to?
        Mandatory so long as no inner exception is passed.

    .PARAMETER ErrorRecord
        An option to include an inner exception in the error record (and in the exception thrown, if one is thrown).
        Use this, whenever you call Stop-Function in a catch block.

        Note:
        Pass the full error record, not just the exception.

    .PARAMETER Tag
        Tags to add to the message written.
        This allows filtering and grouping by category of message, targeting specific messages.

    .PARAMETER FunctionName
        The name of the function to crash.
        This parameter is very optional, since it automatically selects the name of the calling function.
        The function name is used as part of the errorid.
        That in turn allows easily figuring out, which exception belonged to which function when checking out the $error variable.

    .PARAMETER File
        The file in which Stop-Function was called.
        Will be automatically set, but can be overridden when necessary.

    .PARAMETER Line
        The line on which Stop-Function was called.
        Will be automatically set, but can be overridden when necessary.

    .PARAMETER Target
        The object that was processed when the error was thrown.
        For example, if you were trying to process a Database Server object when the processing failed, add the object here.
        This object will be in the error record (which will be written, even in non-EnableException mode, just won't show it).
        If you specify such an object, it becomes simple to actually figure out, just where things failed at.

    .PARAMETER Exception
        Allows specifying an inner exception as input object. This will be passed on to the logging and used for messages.
        When specifying both ErrorRecord AND Exception, Exception wins, but ErrorRecord is still used for record metadata.

    .PARAMETER OverrideExceptionMessage
        Disables automatic appending of exception messages.
        Use in cases where you already have a speaking message interpretation and do not need the original message.

    .PARAMETER Continue
        This will cause the function to call continue while not running silently.
        Useful when mass-processing items where an error shouldn't break the loop.

    .PARAMETER SilentlyContinue
        This will cause the function to call continue while running silently.
        Useful when mass-processing items where an error shouldn't break the loop.

    .PARAMETER ContinueLabel
        When specifying a label in combination with "-Continue" or "-SilentlyContinue", this function will call continue with this specified label.
        Helpful when trying to continue on an upper level named loop.

    .EXAMPLE
        Stop-Function -Message "Foo failed bar!" -EnableException $EnableException -ErrorRecord $_
        return

        Depending on whether $EnableException is true or false it will:
        - Throw a bloody terminating error. Game over.
        - Write a nice warning about how Foo failed bar, then terminate the function. The return on the next line will then end the calling function.

    .EXAMPLE
        Stop-Function -Message "Foo failed bar!" -EnableException $EnableException -Category InvalidOperation -Target $foo -Continue

        Depending on whether $silent is true or false it will:
        - Throw a bloody terminating error. Game over.
        - Write a nice warning about how Foo failed bar, then call continue to process the next item in the loop.
        In both cases, the error record added to $error will have the content of $foo added, the better to figure out what went wrong.
    #>
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding(DefaultParameterSetName = 'Plain')]
    param (
        [Parameter(Mandatory)]
        [string]
        $Message,

        [bool]
        [Alias('Silent')]
        $EnableException = $EnableException,

        [Parameter(ParameterSetName = 'Plain')]
        [Parameter(ParameterSetName = 'Exception')]
        [System.Management.Automation.ErrorCategory]
        $Category = ([System.Management.Automation.ErrorCategory]::NotSpecified),

        [Parameter(ParameterSetName = 'Exception')]
        [Alias('InnerErrorRecord')]
        [System.Management.Automation.ErrorRecord[]]
        $ErrorRecord,

        [string[]]
        $Tag,

        [string]
        $FunctionName = ((Get-PSCallStack)[0].Command),

        [string]
        $File,

        [int]
        $Line,

        [object]
        $Target,

        [System.Exception]
        $Exception,

        [switch]
        $OverrideExceptionMessage,

        [switch]
        $Continue,

        [switch]
        $SilentlyContinue,

        [string]
        $ContinueLabel
    )

    #region Initialize information on the calling command
    $callStack = (Get-PSCallStack)[1]
    if (-not $FunctionName) { $FunctionName = $callStack.Command }
    $ModuleName = "dbatools"
    if (-not $File) { $File = $callStack.Position.File }
    if (-not $Line) { $Line = $callStack.Position.StartLineNumber }
    #endregion Initialize information on the calling command

    #region Apply Transforms
    #region Target Transform
    if ($null -ne $Target) {
        $Target = Convert-DbaMessageTarget -Target $Target -FunctionName $FunctionName -ModuleName $ModuleName
    }
    #endregion Target Transform

    #region Exception Transforms
    if ($Exception) {
        $Exception = Convert-DbaMessageException -Exception $Exception -FunctionName $FunctionName -ModuleName $ModuleName
    } elseif ($ErrorRecord) {
        $int = 0
        while ($int -lt $ErrorRecord.Length) {
            $tempException = Convert-DbaMessageException -Exception $ErrorRecord[$int].Exception -FunctionName $FunctionName -ModuleName $ModuleName
            if ($tempException -ne $ErrorRecord[$int].Exception) {
                $ErrorRecord[$int] = New-Object System.Management.Automation.ErrorRecord($tempException, $ErrorRecord[$int].FullyQualifiedErrorId, $ErrorRecord[$int].CategoryInfo.Category, $ErrorRecord[$int].TargetObject)
            }

            $int++
        }
    }
    #endregion Exception Transforms
    #endregion Apply Transforms

    #region Message Handling
    $records = @()

    if ($ErrorRecord -or $Exception) {
        if ($ErrorRecord) {
            foreach ($record in $ErrorRecord) {
                $msg = Get-ErrorMessage -Record $record
                if (-not $Exception) { $newException = New-Object System.Exception($msg, $record.Exception) }
                else { $newException = $Exception }
                if ($record.CategoryInfo.Category) { $Category = $record.CategoryInfo.Category }
                $records += New-Object System.Management.Automation.ErrorRecord($newException, "$($ModuleName)_$FunctionName", $Category, $Target)
            }
        } else {
            $records += New-Object System.Management.Automation.ErrorRecord($Exception, "$($ModuleName)_$FunctionName", $Category, $Target)
        }

        # Manage Debugging
        if ($EnableException) { Write-Message -Level Warning -Message $Message -EnableException $EnableException -FunctionName $FunctionName -Target $Target -ErrorRecord $records -Tag $Tag -ModuleName $ModuleName -OverrideExceptionMessage:$OverrideExceptionMessage -File $File -Line $Line 3>$null }
        else { Write-Message -Level Warning -Message $Message -EnableException $EnableException -FunctionName $FunctionName -Target $Target -ErrorRecord $records -Tag $Tag -ModuleName $ModuleName -OverrideExceptionMessage:$OverrideExceptionMessage -File $File -Line $Line }
    } else {
        $exception = New-Object System.Exception($Message)
        $records += New-Object System.Management.Automation.ErrorRecord($Exception, "dbatools_$FunctionName", $Category, $Target)

        # Manage Debugging
        if ($EnableException) { Write-Message -Level Warning -Message $Message -EnableException $EnableException -FunctionName $FunctionName -Target $Target -ErrorRecord $records -Tag $Tag -ModuleName $ModuleName -OverrideExceptionMessage:$true -File $File -Line $Line 3>$null}
        else { Write-Message -Level Warning -Message $Message -EnableException $EnableException -FunctionName $FunctionName -Target $Target -ErrorRecord $records -Tag $Tag -ModuleName $ModuleName -OverrideExceptionMessage:$true -File $File -Line $Line }
    }
    #endregion Message Handling



    #region EnableException Mode
    if ($EnableException) {
        if ($SilentlyContinue) {
            foreach ($record in $records) { Write-Error -Message $record -Category $Category -TargetObject $Target -Exception $record.Exception -ErrorId "dbatools_$FunctionName" -ErrorAction Continue }
            if ($ContinueLabel) { continue $ContinueLabel }
            else { Continue }
        }

        # Extra insurance that it'll stop
        Set-Variable -Name "__dbatools_interrupt_function_78Q9VPrM6999g6zo24Qn83m09XF56InEn4hFrA8Fwhu5xJrs6r" -Scope 1 -Value $true

        throw $records[0]
    }
    #endregion EnableException Mode

    #region Non-EnableException Mode
    else {
        # This ensures that the error is stored in the $error variable AND has its Stacktrace (simply adding the record would lack the stacktrace)
        foreach ($record in $records) {
            $null = Write-Error -Message $record -Category $Category -TargetObject $Target -Exception $record.Exception -ErrorId "dbatools_$FunctionName" -ErrorAction Continue 2>&1
        }

        if ($Continue) {
            if ($ContinueLabel) { continue $ContinueLabel }
            else { Continue }
        } else {
            # Make sure the function knows it should be stopping
            Set-Variable -Name "__dbatools_interrupt_function_78Q9VPrM6999g6zo24Qn83m09XF56InEn4hFrA8Fwhu5xJrs6r" -Scope 1 -Value $true

            return
        }
    }
    #endregion Non-EnableException Mode
}
tools\dbatools\internal\functions\flowcontrol\Test-Bound.ps1
function Test-Bound {
    <#
        .SYNOPSIS
            Helperfunction that tests, whether a parameter was bound.

        .DESCRIPTION
            Helperfunction that tests, whether a parameter was bound.

        .PARAMETER ParameterName
            The name(s) of the parameter that is tested for being bound.
            By default, the check is true when AT LEAST one was bound.

        .PARAMETER Not
            Reverses the result. Returns true if NOT bound and false if bound.

        .PARAMETER And
            All specified parameters must be present, rather than at least one of them.

        .PARAMETER BoundParameters
            The hashtable of bound parameters. Is automatically inherited from the calling function via default value. Needs not be bound explicitly.

        .EXAMPLE
            if (Test-Bound "Day")
            {

            }

            Snippet as part of a function. Will check whether the parameter "Day" was bound. If yes, whatever logic is in the conditional will be executed.

        .EXAMPLE
            Test-Bound -Not 'Login', 'Spid', 'ExcludeSpid', 'Host', 'Program', 'Database'

            Returns whether none of the parameters above were specified.

        .EXAMPLE
            Test-Bound -And 'Login', 'Spid', 'ExcludeSpid', 'Host', 'Program', 'Database'

            Returns whether any of the specified parameters was not bound
       #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, Position = 0)]
        [string[]]
        $ParameterName,

        [Alias('Reverse')]
        [switch]
        $Not,

        [switch]
        $And,

        [object]
        $BoundParameters = (Get-PSCallStack)[0].InvocationInfo.BoundParameters
    )

    if ($And) {
        $test = $true
    } else {
        $test = $false
    }

    foreach ($name in $ParameterName) {
        if ($And) {
            if (-not $BoundParameters.ContainsKey($name)) { $test = $false }
        } else {
            if ($BoundParameters.ContainsKey($name)) { $test = $true }
        }
    }

    return ((-not $Not) -eq $test)
}
tools\dbatools\internal\functions\flowcontrol\Test-DbaDeprecation.ps1
function Test-DbaDeprecation {
    <#
        .SYNOPSIS
            Tests whether a function or one of its parameters was called by a bad name.

        .DESCRIPTION
            Tests whether a function or one of its parameters was called by a bad name.
            This allows giving deprecation warnings - once per session - whenever a user uses something we are planning on removing.

            For example, when renaming a function, we give a grace period by adding an Alias for that function with its old name.
            However, we do not want to carry along this alias forever, so we give warning ahead of time using this function.
            When reaching the specified version, we then can safely remove the alias.

            Furthermore, this function is used for testing, whether such a removal was properly done.

        .PARAMETER DeprecatedOn
            The version this parameter or alias will be removed in.
            Generally, deprecated parameters and aliases should only be removed on major releases.

        .PARAMETER FunctionName
            Automatically filled with the calling function.
            The name of the function that contains either a deprecated alias or parameter.

        .PARAMETER Call
            The InvocationInfo of the calling function.
            Automatically filled.

        .PARAMETER Parameter
            The parameter that has become deprecated.
            On renamed parameters, keep a parameter-alias. This function will notice, when the alias is used.

        .PARAMETER Alias
            The alias of the command that will be deprecated.

        .PARAMETER CustomMessage
            This function will generate a default message. However, this may not always be appropriate.
            Use CustomMessage to tailor a response to the necessity of the moment.

        .PARAMETER EnableException
            By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
            This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
            Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

        .EXAMPLE
            PS C:\> Test-DbaDeprecation -DeprecatedOn "1.0.0.0" -Parameter 'Details'

            Will - once per session - complain if the parameter 'Details' is used.
            Will cause tests to fail, if it's still in the code after release 1.0.0.0.

        .EXAMPLE
            PS C:\> Test-DbaDeprecation -DeprecatedOn "1.0.0.0" -Alias Copy-SqlDatabase

            Will - once per session - complain if the alias 'Copy-SqlDatabase' is used.
            Will cause tests to fail, if it's still in the code after release 1.0.0.0.
       #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [Version]
        $DeprecatedOn,

        [string]
        $FunctionName = (Get-PSCallStack)[0].Command,

        [object]
        $Call = (Get-PSCallStack)[0].InvocationInfo,

        [Parameter(ParameterSetName = "Param", Mandatory)]
        [string]
        $Parameter,

        [Parameter(ParameterSetName = "Alias", Mandatory)]
        [string]
        $Alias,

        [string]
        $CustomMessage,

        [bool]
        [Alias('Silent')]
        $EnableException = $EnableException
    )

    switch ($PSCmdlet.ParameterSetName) {
        "Param" {
            $ast = [System.Management.Automation.Language.Parser]::ParseInput($Call.Line, [ref]$null, [ref]$null)
            $objects = $ast.FindAll( { $args[0] -is [System.Management.Automation.Language.CommandAst] }, $true)
            $sub = $objects | Where-Object Parent -Like "$($Call.InvocationName)*" | Select-Object -First 1

            if ($sub.CommandElements | Where-Object ParameterName -eq $Parameter) {
                if ($CustomMessage) { $Message = $CustomMessage }
                else { $Message = "Using the parameter $Parameter is deprecated. This parameter will be removed in version $DeprecatedOn or before, check in the documentation what parameter to use instead" }

                Write-Message -Message $Message -Level Warning -FunctionName $FunctionName -Once "Deprecated.Alias.$Alias"
            }
        }

        "Alias" {
            if ($Alias -eq $Call.InvocationName) {
                if ($CustomMessage) { $Message = $CustomMessage }
                else { $Message = "Using the alias $Alias is deprecated. This alias will be removed in version $DeprecatedOn or before, use $FunctionName instead. Invoke-DbatoolsRenameHelper can also help rename commands within your scripts." }

                Write-Message -Message $Message -Level Warning -FunctionName $FunctionName -Once "Deprecated.Alias.$Alias"
            }
        }
    }
}
tools\dbatools\internal\functions\flowcontrol\Test-ElevationRequirement.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#

function Test-ElevationRequirement {
    <#
        .SYNOPSIS
            Command that tests, whether the process runs elevated and has to run as such.

        .DESCRIPTION
            Command that tests, whether the process runs elevated and has to run as such.
            Some commands require to be run elevated, when executed against localhost, but not when run against a remote computer.
            This command handles that test and manages the reaction to it.

        .PARAMETER ComputerName
            The computer that is being targeted by the calling command.
            This must be a localhost variety, for it to be able to fail.

        .PARAMETER Continue
            When using the native capability to terminate on fail, this will call continue in non-EnableException mode.

        .PARAMETER ContinueLabel
            When using the native capability to terminate on fail, and using a continue mode, the continue will continue with this label.

        .PARAMETER SilentlyContinue
            When using the native capability to terminate on fail, this will call continue in EnableException mode.

        .PARAMETER NoStop
            Does not call stop-function when the test fails, rather only returns $false instead

        .PARAMETER EnableException
            By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
            This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
            Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

        .EXAMPLE
            $null = Test-ElevationRequirement -ComputerName $instance -Continue

            This will test whether the currently processed instance is localhost and the process is running elevated.
            If it should have elevation but is not running with elevation:
            - In silent mode it will terminate with an exception
            - In default mode, it will continue with the next instance

        .EXAMPLE
            if (-not ( Test-ElevationRequirement -ComputerName $instance -NoStop)) {
                # Do whatever
            }

        This will test whether the currently processed instance is localhost and the process is running elevated.
        If it isn't running elevated but should be, the overall condition will be met and the if-block is executed.
    #>
    [CmdletBinding(DefaultParameterSetName = 'Stop')]
    param (
        [DbaInstanceParameter]
        $ComputerName,

        [Parameter(ParameterSetName = 'Stop')]
        [switch]
        $Continue,

        [Parameter(ParameterSetName = 'Stop')]
        [string]
        $ContinueLabel,

        [Parameter(ParameterSetName = 'Stop')]
        [switch]
        $SilentlyContinue,

        [Parameter(ParameterSetName = 'NoStop')]
        [switch]
        $NoStop,

        [bool]
        [Alias('Silent')]
        $EnableException = $EnableException
    )

    $isElevated = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
    $testResult = $true
    if ($ComputerName.IsLocalHost -and (-not $isElevated)) { $testResult = $false }

    if ($PSCmdlet.ParameterSetName -like "NoStop") {
        return $testResult
    } elseif ($PSCmdlet.ParameterSetName -like "Stop") {
        if ($testResult) { return $testResult }

        $splatStopFunction = @{
            Message = "Console not elevated, but elevation is required to perform some actions on localhost for this command."
        }

        if (Test-Bound "Continue") { $splatStopFunction["Continue"] = $Continue }
        if (Test-Bound "ContinueLabel") { $splatStopFunction["ContinueLabel"] = $ContinueLabel }
        if (Test-Bound "SilentlyContinue") { $splatStopFunction["SilentlyContinue"] = $SilentlyContinue }

        . Stop-Function @splatStopFunction -FunctionName (Get-PSCallStack)[1].Command
        return $testResult
    }
}
tools\dbatools\internal\functions\flowcontrol\Test-FunctionInterrupt.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#

function Test-FunctionInterrupt {
    <#
        .SYNOPSIS
            Internal tool, used to gracefully interrupt a function.

        .DESCRIPTION
            This helper function is designed to work in tandem with Stop-Function.
            When gracefully terminating a function, there is a major issue:
            "Return" will only stop the current one of the three blocks (Begin, Process, End).
            All other statements have side effects or produce lots of red text.

            So, Stop-Function writes a variable into the parent scope, that signals the function should cease.
            This function then checks for that very variable and returns true if it is set.

            This avoids having to handle odd variables in the parent function and causes the least impact on contributors.

        .EXAMPLE
            if (Test-FunctionInterrupt) { return }

            The calling function will stop if this function returns true.
       #>
    [CmdletBinding()]
    param (

    )

    $var = Get-Variable -Name "__dbatools_interrupt_function_78Q9VPrM6999g6zo24Qn83m09XF56InEn4hFrA8Fwhu5xJrs6r" -Scope 1 -ErrorAction Ignore
    if ($var.Value) { return $true }

    return $false
}
tools\dbatools\internal\functions\flowcontrol\Test-Windows.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Test-Windows {
    <#
        .SYNOPSIS
            Internal tool, used to detect non-Windows platforms

        .DESCRIPTION
            Some things don't work with Windows, this is an easy way to detect

        .EXAMPLE
            if (-not (Test-Windows)) { return }

            The calling function will stop if this function returns true.
    #>
    [CmdletBinding()]
    param (
        [switch]$NoWarn
    )

    if (($PSVersionTable.Keys -contains "Platform") -and $psversiontable.Platform -ne "Win32NT") {
        if (-not $NoWarn) {
            Write-Message -Level Warning -Message "This command is not supported on non-Windows platforms :("
        }
        return $false
    }

    return $true
}
tools\dbatools\internal\functions\Get-BackupAncientHistory.ps1
function Get-BackupAncientHistory {
    <#
        .SYNOPSIS
            Returns details of the last full backup of a SQL Server 2000 database

        .DESCRIPTION
            Backup History command to pull limited history from a SQL 2000 instance. If not using SQL 2000, please use Get-DbaBackupHistory which pulls more infomation, and has more options. This is just here to cope with 2k and copy-DbaDatabase issues

        .PARAMETER SqlInstance
            SQL Server name or SMO object representing the SQL Server to connect to. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

        .PARAMETER Credential
            Credential object used to connect to the SQL Server Instance as a different user. This can be a Windows or SQL Server account. Windows users are determined by the existence of a backslash, so if you are intending to use an alternative Windows connection instead of a SQL login, ensure it contains a backslash.

        .PARAMETER Database
            Specifies one or more database(s) to process. If unspecified, all databases will be processed.

        .NOTES
        Author: Stuart Moore (@napalmgram), stuart-moore.com

        dbatools PowerShell module (https://dbatools.io, [email protected])
       Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

       #>
    [CmdletBinding(DefaultParameterSetName = "Default")]
    param (
        [parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [Alias("Credential")]
        [PsCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [string]$FileNameStub,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        try {
            $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        } catch {
            Stop-Function -Message "Failed to process Instance $SqlInstance." -InnerErrorRecord $_ -Target $SqlInstance -Continue
        }
        if ($server.SoftwareVersionMajor -gt 8) {
            Write-Message -Level Warning -Message "This is not the function you're looking for. This is for SQL 2000 only, please use Get-DbaBackupHistory instead. It's much nicer"
        }

        $databases = @()
        if ($null -ne $Database) {
            ForEach ($db in $Database) {
                $databases += [PScustomObject]@{name = $db}
            }
        } else {
            $databases = $server.Databases
        }
    }

    process {
        foreach ($db in $Database) {
            Write-Message -Level Verbose -Message "Processing database $db"
            $sql = "
            SELECT
            a.Server,
             a.[Database],
             a.Username,
             a.Start,
             a.[End],
             a.Duration,
             a.[Path],
             a.Type,
            NULL as TotalSize,
             a.MediaSetId,
             a.BackupSetID,
             a.Software,
              a.position,
              a.first_lsn,
              a.database_backup_lsn,
              a.checkpoint_lsn,
              a.last_lsn,
             a.first_lsn as 'FirstLSN',
              a.database_backup_lsn as 'DatabaseBackupLsn',
              a.checkpoint_lsn as 'CheckpointLsn',
              a.last_lsn as 'Lastlsn',
              a.software_major_version,
             a.DeviceType,
                NULL as is_copy_only,
            NULL as last_recovery_fork_guid
            FROM (
            SELECT
              backupset.database_name AS [Database],
              backupset.user_name AS Username,
              backupset.backup_start_date AS Start,
              backupset.server_name as [Server],
              backupset.backup_finish_date AS [End],
              DATEDIFF(SECOND, backupset.backup_start_date, backupset.backup_finish_date) AS Duration,
              mediafamily.physical_device_name AS Path,
              CASE backupset.type
             WHEN 'L' THEN 'Log'
             WHEN 'D' THEN 'Full'
             WHEN 'F' THEN 'File'
             WHEN 'I' THEN 'Differential'
             WHEN 'G' THEN 'Differential File'
             WHEN 'P' THEN 'Partial Full'
             WHEN 'Q' THEN 'Partial Differential'
             ELSE NULL
              END AS Type,
              backupset.media_set_id AS MediaSetId,
              mediafamily.media_family_id as mediafamilyid,
              backupset.backup_set_id as BackupSetID,
              CASE mediafamily.device_type
             WHEN 2 THEN 'Disk'
             WHEN 102 THEN 'Permanent Disk Device'
             WHEN 5 THEN 'Tape'
             WHEN 105 THEN 'Permanent Tape Device'
             WHEN 6 THEN 'Pipe'
             WHEN 106 THEN 'Permanent Pipe Device'
             WHEN 7 THEN 'Virtual Device'
             ELSE 'Unknown'
             END AS DeviceType,
              backupset.position,
              backupset.first_lsn,
              backupset.database_backup_lsn,
              backupset.checkpoint_lsn,
              backupset.last_lsn,
              backupset.software_major_version,
              mediaset.software_name AS Software
            FROM msdb..backupmediafamily AS mediafamily
            JOIN msdb..backupmediaset AS mediaset
              ON mediafamily.media_set_id = mediaset.media_set_id
            JOIN msdb..backupset AS backupset
              ON backupset.media_set_id = mediaset.media_set_id
            WHERE backupset.database_name = '$db'
                    ) AS a
            where  a.backupsetid in (Select max(backup_set_id) from msdb..backupset where database_name='$db')"
            Write-Message -Level Debug -Message $sql
            $results = $server.ConnectionContext.ExecuteWithResults($sql).Tables.Rows | Select-Object * -ExcludeProperty BackupSetRank, RowError, Rowstate, table, itemarray, haserrors
            Write-Message -Level SomewhatVerbose -Message "Processing as grouped output."
            $GroupedResults = $results | Group-Object -Property backupsetid
            Write-Message -Level SomewhatVerbose -Message "$($GroupedResults.Count) result-groups found."
            $groupResults = @()
            foreach ($group in $GroupedResults) {

                $fileSql = "select file_type as FileType, logical_name as LogicalName, physical_name as PhysicalName
                            from msdb.dbo.backupfile where backup_set_id='$($Group.group[0].BackupSetID)'"

                Write-Message -Level Debug -Message "FileSQL: $fileSql"

                $historyObject = New-Object Sqlcollaborative.Dbatools.Database.BackupHistory
                $historyObject.ComputerName = $server.ComputerName
                $historyObject.InstanceName = $server.ServiceName
                $historyObject.SqlInstance = $server.DomainInstanceName
                $historyObject.Database = $group.Group[0].Database
                $historyObject.UserName = $group.Group[0].UserName
                $historyObject.Start = ($group.Group.Start | Measure-Object -Minimum).Minimum
                $historyObject.End = ($group.Group.End | Measure-Object -Maximum).Maximum
                $historyObject.Duration = New-TimeSpan -Seconds ($group.Group.Duration | Measure-Object -Maximum).Maximum
                $historyObject.Path = $group.Group.Path
                $historyObject.TotalSize = $NULL
                $historyObject.Type = $group.Group[0].Type
                $historyObject.BackupSetId = $group.Group[0].BackupSetId
                $historyObject.DeviceType = $group.Group[0].DeviceType
                $historyObject.Software = $group.Group[0].Software
                $historyObject.FullName = $group.Group.Path
                $historyObject.FileList = $server.ConnectionContext.ExecuteWithResults($fileSql).Tables.Rows
                $historyObject.Position = $group.Group[0].Position
                $historyObject.FirstLsn = $group.Group[0].First_LSN
                $historyObject.DatabaseBackupLsn = $group.Group[0].database_backup_lsn
                $historyObject.CheckpointLsn = $group.Group[0].checkpoint_lsn
                $historyObject.LastLsn = $group.Group[0].Last_Lsn
                $historyObject.SoftwareVersionMajor = $group.Group[0].Software_Major_Version
                $historyObject.IsCopyOnly = if ($group.Group[0].is_copy_only -eq 1) {
                    $true
                } else {
                    $false
                }
                $groupResults += $historyObject
            }
            $groupResults | Sort-Object -Property LastLsn, Type
        }

    }

    END {}
}
tools\dbatools\internal\functions\Get-CodePage.ps1
function Get-CodePage {
    <#
        .SYNOPSIS
            Converts Microsoft's code page ID to human readable format

        .DESCRIPTION
            Converts Microsoft's code page ID to human readable format

        .PARAMETER Id
            The code page ID

        .EXAMPLE
            Get-CodePage 1252

            Returns a pscustomobject with id, alias and name
       #>
    [CmdletBinding()]
    param (
        [int]$id
    )
    process {
        $encoding = [System.Text.Encoding]::GetEncoding($id)
        $IncludeProps = 'CodePage', 'BodyName', 'EncodingName', 'HeaderName', 'WebName', 'IsSingleByte'
        Select-DefaultView -InputObject $encoding -Property $IncludeProps
    }
}
tools\dbatools\internal\functions\Get-DbaADObject.ps1
#ValidationTags#FlowControl,Pipeline#
function Get-DbaADObject {
    <#
    .SYNOPSIS
    Get-DbaADObject tries to facilitate searching AD with dbatools, which ATM can't require AD cmdlets.

    .DESCRIPTION
    As working with multiple domains, forests, ldap filters, partitions, etc is quite hard to grasp, let's try to do "the right thing" here and
    facilitate everybody's work with it. It either returns the exact matched result or None if it isn't found. You can inspect the raw object
    calling GetUnderlyingObject() on the returned object.

    .PARAMETER ADObject
    Pass in both the domain and the login name in Domain\sAMAccountName format (the one everybody is accustomed to)
    You can also pass a UserPrincipalName format (with the correct IdentityType, either with Domain\UserPrincipalName or UserPrincipalName@Domain)
    Beware: the "Domain" part of the UPN *can* be different from the real domain, see "UPN suffixes" (https://msdn.microsoft.com/en-us/library/windows/desktop/aa380525(v=vs.85).aspx)
    It's always best to pass the real domain name in (see the examples)
    For any other format, please beware that the domain part must always be specified (again, for the best result, before the slash)

    .PARAMETER Type
    You *should* always know what you are asking for. Please pass in Computer,Group or User to help speeding up the search

    .PARAMETER IdentityType
    By default objects are searched using sAMAccountName format, here you can pass different representation that need to match the passed in ADObject

    .PARAMETER Credential
    Use this credential to connect to the domain and search for the needed ADObject. If not passed, uses the current process' one.

    .PARAMETER SearchAllDomains
    Search for the object in all domains connected to the current one. If you are unsure what domain the object is coming from,
    using this switch will search through all domains in your forest and also in the ones that are trusted. This is HEAVY, but it can save
    some headaches.

    .PARAMETER EnableException
            By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
            This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
            Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
    Author: Niphlod, https://github.com/niphlod
    Tags:
    dbatools PowerShell module (https://dbatools.io, [email protected])
   Copyright: (c) 2018 by dbatools, licensed under MIT
    License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
    Get-DbaADObject -ADObject "contoso\ctrlb" -Type User

    Searches in the contoso domain for a ctrlb user

    .EXAMPLE
    Get-DbaADObject -ADObject "[email protected]" -Type User -IdentityType UserPrincipalName

    Searches in the contoso domain for a ctrlb user using the UserPrincipalName format. Again, beware of the UPN suffixes in elaborate AD structures!

    .EXAMPLE
    Get-DbaADObject -ADObject "contoso\[email protected]" -Type User -IdentityType UserPrincipalName

    Searches in the contoso domain for a [email protected] user using the UserPrincipalName format. This kind of search is better than the previous one
    because it takes into account possible UPN suffixes

    .EXAMPLE
    Get-DbaADObject -ADObject "[email protected]" -Type User -IdentityType UserPrincipalName -SearchAllDomains

    As a last resort, searches in all the current forest for a [email protected] user using the UserPrincipalName format

    .EXAMPLE
    Get-DbaADObject -ADObject "contoso\sqlcollaborative" -Type Group

    Searches in the contoso domain for a sqlcollaborative group

    .EXAMPLE
    Get-DbaADObject -ADObject "contoso\SqlInstance2014$" -Type Group

    Searches in the contoso domain for a SqlInstance2014 computer (remember the ending $ for computer objects)

    .EXAMPLE
    Get-DbaADObject -ADObject "contoso\ctrlb" -Type User -EnableException

    Searches in the contoso domain for a ctrlb user, suppressing all error messages and throw exceptions that can be caught instead

    #>
    [CmdletBinding()]
    param (
        [string[]]$ADObject,
        [ValidateSet("User", "Group", "Computer")]
        [string]$Type,

        [ValidateSet("DistinguishedName", "Guid", "Name", "SamAccountName", "Sid", "UserPrincipalName")]
        [string]$IdentityType = "SamAccountName",

        [PSCredential]$Credential,
        [switch]$SearchAllDomains,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        try {
            Add-Type -AssemblyName System.DirectoryServices.AccountManagement
        } catch {
            Stop-Function -Message "Failed to load the required module $($_.Exception.Message)" -EnableException $EnableException -InnerErrorRecord $_
            return
        }
        switch ($Type) {
            "User" {
                $searchClass = [System.DirectoryServices.AccountManagement.UserPrincipal]
            }
            "Group" {
                $searchClass = [System.DirectoryServices.AccountManagement.GroupPrincipal]
            }
            "Computer" {
                $searchClass = [System.DirectoryServices.AccountManagement.ComputerPrincipal]
            }
            default {
                $searchClass = [System.DirectoryServices.AccountManagement.Principal]
            }
        }

        function Get-DbaADObjectInternal($Domain, $IdentityType, $obj, $EnableException) {
            try {
                # can we simply resolve the passed domain ? This has the benefit of raising almost instantly if the domain is not valid
                $Context = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Domain', $Domain)
                $null = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($Context)
                if ($Credential) {
                    $ctx = New-Object System.DirectoryServices.AccountManagement.PrincipalContext('Domain', $Domain, $Credential.UserName, $Credential.GetNetworkCredential().Password)
                } else {
                    $ctx = New-Object System.DirectoryServices.AccountManagement.PrincipalContext('Domain', $Domain)
                }
                $found = $searchClass::FindByIdentity($ctx, $IdentityType, $obj)
                $found
            } catch {
                Stop-Function -Message "Errors trying to connect to the domain $Domain $($_.Exception.Message)" -EnableException $EnableException -InnerErrorRecord $_ -Target $ADObj
            }
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }
        foreach ($ADObj in $ADObject) {
            # passing the domain as the first part before the \ wins always in defining the domain to search into
            $Splitted = $ADObj.Split("\")
            if ($Splitted.Length -ne 2) {
                # we can also take the object@domain format
                $Splitted = $ADObj.Split("@")
                if ($Splitted.Length -ne 2) {
                    Stop-Function -Message "You need to pass ADObject either DOMAIN\object or object@domain format" -Continue -EnableException $EnableException
                } else {
                    if ($IdentityType -ne 'UserPrincipalName') {
                        $obj, $Domain = $Splitted
                    } else {
                        # if searching for a UserPrincipalName format without a specific domain passed in before the slash,
                        # we can assume there are no custom UPN suffixes in place
                        $obj, $Domain = $AdObj, $Splitted[1]
                    }
                }
            } else {
                $Domain, $obj = $Splitted
            }
            if ($SearchAllDomains) {
                Write-Message -Message "Searching for $obj under all domains in $IdentityType format" -Level VeryVerbose
                # if we're lucky, we can resolve the domain right away
                try {
                    Get-DbaADObjectInternal -Domain $Domain -IdentityType $IdentityType -obj $obj -EnableException $true
                } catch {
                    # if not, let's build up all domains
                    $ForestObject = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
                    $AllDomains = $ForestObject.Domains.Name
                    foreach ($ForestDomain in $AllDomains) {
                        Write-Message -Message "Searching for $obj under domain $ForestDomain in $IdentityType format" -Level VeryVerbose
                        $found = Get-DbaADObjectInternal -Domain $ForestDomain -IdentityType $IdentityType -obj $obj
                        if ($found) {
                            $found
                            break
                        }
                    }
                    # we are very unlucky, let's search also in all trusted domains
                    $AllTrusted = ($ForestObject.GetAllTrustRelationships().TopLevelNames | Where-Object Status -eq 'Enabled').Name
                    foreach ($ForestDomain in $AllTrusted) {
                        Write-Message -Message "Searching for $obj under domain $ForestDomain in $IdentityType format" -Level VeryVerbose
                        $found = Get-DbaADObjectInternal -Domain $ForestDomain -IdentityType $IdentityType -obj $obj
                        if ($found) {
                            $found
                            break
                        }
                    }
                }
            } else {
                Write-Message -Message "Searching for $obj under domain $domain in $IdentityType format" -Level VeryVerbose
                Get-DbaADObjectInternal -Domain $Domain -IdentityType $IdentityType -obj $obj
            }
        }
    }
}
tools\dbatools\internal\functions\Get-DbaDbPhysicalFile.ps1
function Get-DbaDbPhysicalFile {
    <#
    .SYNOPSIS
    Gets raw information about physical files linked to databases

    .DESCRIPTION
    Fastest way to fetch just the paths of the physical files for every database on the instance, also for offline databases.
    Incidentally, it also fetches the paths for MMO and FS filegroups.
    This is partly already in Get-DbaDbFile, but this internal needs to stay lean and fast, as it's heavily used in top-level functions

    .PARAMETER SqlInstance
    SMO object representing the SQL Server to connect to.

    .EXAMPLE
    Get-DbaDbPhysicalFile -SqlInstance server1\instance2

    .NOTES
        Author: Simone Bizzotto

        dbatools PowerShell module (https://dbatools.io, [email protected])
       Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT
       #>
    [CmdletBinding()]
    param(
        [parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]
        $SqlCredential
    )
    try {
        $Server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
    } catch {
        Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $SqlInstance
        return
    }
    if ($Server.versionMajor -le 8) {
        $sql = "SELECT DB_NAME(dbid) AS Name, filename AS PhysicalName FROM sysaltfiles"
    } else {
        $sql = "SELECT DB_NAME(database_id) AS Name, physical_name AS PhysicalName FROM sys.master_files"
    }
    Write-Message -Level Debug -Message "$sql"
    try {
        $Server.Query($sql)
    } catch {
        throw "Error enumerating files"
    }
}
tools\dbatools\internal\functions\Get-DbaFileStreamFolder.ps1
function Get-DbaFileStreamFolder {
    <#

    .SYNOPSIS
        Returns basic information about Filestream folders from a Sql Instance

    .DESCRIPTION
        Given a SQL Instance, and an optional list of databases returns the FileStream containing folders on that Instance. Without the Database parameter, all dbs with FileStream are returned

    .PARAMETER SqlInstance
        The Sql Server instance to be queries

    .PARAMETER SqlCredential
        A Sql Credential to connect to $SqlInstance

    .PARAMETER Database
        Database to be tested, multiple databases may be specified as a comma seperated list.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .EXAMPLE
        Get-DbaFileStreamFolder -SqlInstance server1\instance2

        Returns all FileStream folders from server1\instance2

    .EXAMPLE
        Get-DbaFileStreamFolder -SqlInstance server1\instance2 -Database Archive

        Returns any FileStream folders from the Archive database on server1\instance2

    .NOTES
    Author:Stuart Moore (@napalmgram stuart-moore.com )


    Website: https://dbatools.io
    Copyright: (c) 2018 by dbatools, licensed under MIT
    License: MIT https://opensource.org/licenses/MIT
       #>
    param (
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [switch]$EnableException
    )

    begin {
        try {
            $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        } catch {
            Stop-Function -Message "Failed to process Instance $SqlInstance." -InnerErrorRecord $_ -Target $SqlInstance -Continue
        }
    }

    process {
        $sql = "select d.name as 'dbname', mf.Physical_Name from sys.master_files mf inner join sys.databases d on mf.database_id = d.database_id
        where mf.type=2"
        $databases = @()
        if ($null -ne $Database) {
            ForEach ($db in $Database) {
                $databases += "'$db'"
            }
            $sql = $sql + " and d.name in ( $($databases -join ',') )"
        }

        $results = $server.ConnectionContext.ExecuteWithResults($sql).Tables.Rows | Select-Object * -ExcludeProperty  RowError, Rowstate, table, itemarray, haserrors
        foreach ($result in $results) {
            [PsCustomObject]@{
                ServerInstance   = $SqlInstance
                Database         = $result.dbname
                FileStreamFolder = $result.Physical_Name
            }
        }


    }

    END {}
}
tools\dbatools\internal\functions\Get-DbaPathSep.ps1
function Get-DbaPathSep {
    <#
    Gets the instance path separator, if exists, or return the default one
       #>
    [CmdletBinding()]
    param (
        [object]$Server
    )

    $pathSep = $Server.PathSeparator
    if ($pathSep.Length -eq 0) {
        $pathSep = '\'
    }
    return $pathSep
}
tools\dbatools\internal\functions\Get-DbaReportingService.ps1
function Get-DbaReportingService {
    <#
    .SYNOPSIS
        Gets the SQL Server Reporting Services on a computer.

    .DESCRIPTION
        Gets the SQL Server Reporting Services on one or more computers.

        Requires Local Admin rights on destination computer(s).

    .PARAMETER ComputerName
        The target SQL Server instance or instances.

    .PARAMETER InstanceName
        Only returns services that belong to the specific instances.

    .PARAMETER Credential
        Credential object used to connect to the computer as a different user.

    .PARAMETER ServiceName
        Can be used to specify service names explicitly, without looking for service types/instances.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Service, SqlServer, Instance, Connect
        Author: Kirill Kravtsov ( @nvarscar )

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaService

    .EXAMPLE
        PS C:\> Get-DbaReportingService -ComputerName sqlserver2014a

        Gets the Reporting Services on computer sqlserver2014a.

    .EXAMPLE
        PS C:\> $cred = Get-Credential WindowsUser
        PS C:\> Get-DbaReportingService -ComputerName sql1,sql2 -Credential $cred  | Out-GridView

        Gets the Reporting Services on computers sql1 and sql2 via the user WindowsUser, and shows them in a grid view.

    .EXAMPLE
        PS C:\> Get-DbaReportingService -ComputerName sql1,sql2 -InstanceName MSSQLSERVER

        Gets the Reporting Services related to the default instance MSSQLSERVER on computers sql1 and sql2.

    .EXAMPLE
        PS C:\> $MyServers =  Get-Content .\servers.txt
        PS C:\> Get-DbaReportingService -ComputerName $MyServers -ServiceName MSSQLSERVER,SQLSERVERAGENT

        Gets the Reporting Services with ServiceName MSSQLSERVER or SQLSERVERAGENT  for all the servers that are stored in the file. Every line in the file can only contain one hostname for a server.

    .EXAMPLE
        PS C:\> $services = Get-DbaReportingService -ComputerName sql1
        PS C:\> $services.ChangeStartMode('Manual')

        Gets the Reporting Services on computer sql1 and changes their startup mode to 'Manual'.

    .EXAMPLE
        PS C:\> (Get-DbaReportingService -ComputerName sql1).Restart($true)

        Calls a Restart method for each Reporting service on computer sql1.

    #>
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline, Position = 1)]
        [Alias("cn", "host", "Server")]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [Alias("Instance")]
        [string[]]$InstanceName,
        [PSCredential]$Credential,
        [string[]]$ServiceName,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        $searchClause = ""
        #If filtering by service name create a dynamic WHERE clause
        if ($ServiceName) {
            $searchClause = " WHERE ServiceName = '$($ServiceName -join "' OR ServiceName = '")'"
        }
    }
    process {
        foreach ($computer in $ComputerName) {
            Write-Message -Level VeryVerbose -Message "Getting Reporting Server namespace on $Computer" -Target $Computer
            try {
                $namespaces = Get-DbaCmObject -ComputerName $Computer -NameSpace root\Microsoft\SQLServer\ReportServer -Query "Select Name FROM __NAMESPACE" -EnableException -Credential $credential
            } catch {
                Write-Message -Level Verbose -Message "No SQLServer\ReportServer Namespace on $Computer. Please note that this function is available from SQL 2005 up."
                return
            }
            # querying SqlService namespace
            ForEach ($namespace in $namespaces) {
                Write-Message -Level Verbose -Message "Getting version from the namespace $($namespace.Name) on $Computer." -Target $Computer
                try {
                    $namespaceVersion = Get-DbaCmObject -ComputerName $Computer -Namespace "root\Microsoft\SQLServer\ReportServer\$($namespace.Name)" -Query "SELECT Name FROM __NAMESPACE" -EnableException
                } catch {
                    Stop-Function -EnableException $EnableException -Message "No version Namespace on $Computer. Please note that this function is available from SQL 2005 up." -Continue
                }
                try {
                    $cimQuery = "SELECT * FROM MSReportServer_ConfigurationSetting" + $searchClause
                    $services = Get-DbaCmObject -ComputerName $Computer -Namespace "root\Microsoft\SQLServer\ReportServer\$($namespace.Name)\$($namespaceVersion.Name)\Admin" -Query $cimQuery -EnableException
                } catch {
                    Stop-Function -EnableException $EnableException -Message "Failed to acquire services from namespace $($namespace.Name)\$($namespaceVersion.Name)." -Target $Computer -ErrorRecord $_ -Continue
                }
                ForEach ($service in $services) {
                    if (!$InstanceName -or $service.InstanceName -in $InstanceName) {
                        #Add other properties and methods
                        Add-Member -Force -InputObject $service -MemberType NoteProperty -Name ServiceType -Value 'SSRS'
                        Add-Member -Force -InputObject $service -MemberType AliasProperty -Name StartName -Value WindowsServiceIdentityActual

                        try {
                            $service32 = Get-DbaCmObject -ComputerName $Computer -Namespace "root\cimv2" -Query "SELECT * FROM Win32_Service WHERE Name = '$($service.ServiceName)'" -EnableException
                        } catch {
                            Stop-Function -EnableException $EnableException -Message "Failed to acquire services32" -Target $Computer -ErrorRecord $_ -Continue
                        }
                        Add-Member -Force -InputObject $service -MemberType NoteProperty -Name ComputerName -Value $service32.SystemName
                        Add-Member -Force -InputObject $service -MemberType NoteProperty -Name State -Value $service32.State
                        $startMode = switch ($service32.StartMode) {
                            Auto { 'Automatic' } #Replacing for consistency to match other SQL Services
                            default { $_ }
                        }
                        Add-Member -Force -InputObject $service -MemberType NoteProperty -Name StartMode -Value $startMode
                        Add-Member -Force -InputObject $service -MemberType NoteProperty -Name DisplayName -Value $service32.DisplayName
                        Add-Member -Force -InputObject $service -NotePropertyName ServicePriority -NotePropertyValue 100
                        Add-Member -Force -InputObject $service -MemberType ScriptMethod -Name "Stop" -Value {
                            param ([bool]$Force = $false)
                            Stop-DbaService -InputObject $this -Force:$Force
                        }
                        Add-Member -Force -InputObject $service -MemberType ScriptMethod -Name "Start" -Value { Start-DbaService -InputObject $this }
                        Add-Member -Force -InputObject $service -MemberType ScriptMethod -Name "Restart" -Value {
                            param ([bool]$Force = $false)
                            Restart-DbaService -InputObject $this -Force:$Force
                        }
                        Add-Member -Force -InputObject $service -MemberType ScriptMethod -Name "ChangeStartMode" -Value {
                            param (
                                [parameter(Mandatory)]
                                [string]$Mode
                            )
                            $supportedModes = @("Automatic", "Manual", "Disabled")
                            if ($Mode -notin $supportedModes) {
                                Stop-Function -Message ("Incorrect mode '$Mode'. Use one of the following values: {0}" -f ($supportedModes -join ' | ')) -EnableException $false -FunctionName 'Get-DbaService'
                                Return
                            }
                            Set-ServiceStartMode -InputObject $this -Mode $Mode -ErrorAction Stop
                            $this.StartMode = $Mode
                        }
                        $defaults = "ComputerName", "ServiceName", "ServiceType", "InstanceName", "DisplayName", "StartName", "State", "StartMode"
                        Select-DefaultView -InputObject $service -Property $defaults -TypeName DbaSqlService
                    }
                }
            }
        }
    }
    end {

    }
}
tools\dbatools\internal\functions\Get-DBAServiceErrorMessage.ps1
function Get-DbaServiceErrorMessage {
    <#
    .SYNOPSIS
    Internal function. Returns the list of error code messages for Windows service management.

    #>
    param(
        [parameter(ValueFromPipeline, Position = 1)]
        [int]$ErrorNumber
    )
    $returnCodes = @("The request was accepted.",
        "The request is not supported.",
        "The user did not have the necessary access.",
        "The service cannot be stopped because other services that are running are dependent on it.",
        "The requested control code is not valid, or it is unacceptable to the service.",
        "The requested control code cannot be sent to the service because the state of the service (Win32_BaseService.State property) is equal to 0, 1, or 2.",
        "The service has not been started.",
        "The service did not respond to the start request in a timely fashion.",
        "Unknown failure when starting the service.",
        "The directory path to the service executable file was not found.",
        "The service is already running.",
        "The database to add a new service is locked.",
        "A dependency this service relies on has been removed from the system.",
        "The service failed to find the service needed from a dependent service.",
        "The service has been disabled from the system.",
        "The service does not have the correct authentication to run on the system.",
        "This service is being removed from the system.",
        "The service has no execution thread.",
        "The service has circular dependencies when it starts.",
        "A service is running under the same name.",
        "The service name has invalid characters.",
        "Invalid parameters have been passed to the service.",
        "The account under which this service runs is either invalid or lacks the permissions to run the service.",
        "The service exists in the database of services available from the system.",
        "The service is currently paused in the system.")
    if ($ErrorNumber) {
        if ($ErrorNumber -in 0..($returnCodes.Length - 1)) { Return $returnCodes[$ErrorNumber] }
        else { Return "Unknown error." }
    } else {
        $returnCodes
    }
}
tools\dbatools\internal\functions\Get-DbaSysDbUserObjectScript.ps1
function Get-DbaSysDbUserObjectScript {
    <#
        .SYNOPSIS
            Gets all user objects found in source SQL Server's master, msdb and model databases to the destination.
       #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$EnableException
    )
    begin {
        function get-sqltypename ($type) {
            switch ($type) {
                "VIEW" { "view" }
                "SQL_TABLE_VALUED_FUNCTION" { "User table valued fsunction" }
                "DEFAULT_CONSTRAINT" { "User default constraint" }
                "SQL_STORED_PROCEDURE" { "User stored procedure" }
                "RULE" { "User rule" }
                "SQL_INLINE_TABLE_VALUED_FUNCTION" { "User inline table valued function" }
                "SQL_TRIGGER" { "User server trigger" }
                "SQL_SCALAR_FUNCTION" { "User scalar function" }
                default { $type }
            }
        }
    }
    process {
        try {
            $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        } catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
            return
        }

        if (!(Test-SqlSa -SqlInstance $server -SqlCredential $SqlCredential)) {
            Stop-Function -Message "Not a sysadmin on $source. Quitting."
            return
        }

        $systemDbs = "master", "model", "msdb"

        foreach ($systemDb in $systemDbs) {
            $smodb = $server.databases[$systemDb]
            $destdb = $server.databases[$systemDb]
            Write-Output "USE $systemDb"
            Write-Output "GO"
            $tables = $smodb.Tables | Where-Object IsSystemObject -ne $true
            $schemas = $smodb.Schemas | Where-Object IsSystemObject -ne $true
            $transfer = New-Object Microsoft.SqlServer.Management.Smo.Transfer $smodb
            $null = $transfer.CopyAllObjects = $false
            $null = $transfer.Options.WithDependencies = $true
            $null = $transfer.ObjectList.Add($schema)
            $null = $transfer.Options.ScriptBatchTerminator = $true
            try { $transfer.ScriptTransfer() }
            catch { }
            Write-Output "GO"

            foreach ($table in $tables) {
                Write-Output "GO"
                $transfer = New-Object Microsoft.SqlServer.Management.Smo.Transfer $smodb
                $null = $transfer.CopyAllObjects = $false
                $null = $transfer.Options.WithDependencies = $true
                $null = $transfer.Options.ScriptBatchTerminator = $true
                $null = $transfer.ObjectList.Add($table)
                try { $transfer.ScriptTransfer() } catch {}
            }

            $userobjects = Get-DbaModule -SqlInstance $server -Database $systemDb -ExcludeSystemObjects | Sort-Object Type
            Write-Message -Level Verbose -Message "Copying from $systemDb"
            foreach ($userobject in $userobjects) {
                Write-Output "GO"
                $name = "[$($userobject.SchemaName)].[$($userobject.Name)]"
                $db = $userobject.Database
                $type = get-sqltypename $userobject.Type
                $userobject.Definition
                $schema = $userobject.SchemaName
                $result = Get-DbaModule -SqlInstance $server -ExcludeSystemObjects -Database $db |
                    Where-Object { $psitem.Name -eq $userobject.Name -and $psitem.Type -eq $userobject.Type }
                $smobject = switch ($userobject.Type) {
                    "VIEW" { $smodb.Views.Item($userobject.Name, $userobject.SchemaName) }
                    "SQL_STORED_PROCEDURE" { $smodb.StoredProcedures.Item($userobject.Name, $userobject.SchemaName) }
                    "RULE" { $smodb.Rules.Item($userobject.Name, $userobject.SchemaName) }
                    "SQL_TRIGGER" { $smodb.Triggers.Item($userobject.Name, $userobject.SchemaName) }
                    "SQL_TABLE_VALUED_FUNCTION" { $smodb.UserDefinedFunctions.Item($name) }
                    "SQL_INLINE_TABLE_VALUED_FUNCTION" { $smodb.UserDefinedFunctions.Item($name) }
                    "SQL_SCALAR_FUNCTION" { $smodb.UserDefinedFunctions.Item($name) }
                }

                $smobject = switch ($userobject.Type) {
                    "VIEW" { $smodb.Views.Item($userobject.Name, $userobject.SchemaName) }
                    "SQL_STORED_PROCEDURE" { $smodb.StoredProcedures.Item($userobject.Name, $userobject.SchemaName) }
                    "RULE" { $smodb.Rules.Item($userobject.Name, $userobject.SchemaName) }
                    "SQL_TRIGGER" { $smodb.Triggers.Item($userobject.Name, $userobject.SchemaName) }
                }
                if ($smobject) {
                    $transfer = New-Object Microsoft.SqlServer.Management.Smo.Transfer $smodb
                    $null = $transfer.CopyAllObjects = $false
                    $null = $transfer.Options.WithDependencies = $true
                    $null = $transfer.ObjectList.Add($smobject)
                    $null = $transfer.Options.ScriptBatchTerminator = $true
                    try { $transfer.ScriptTransfer() } catch {}
                }
            }
        }
    }
}
tools\dbatools\internal\functions\Get-DecryptedObject.ps1
function Get-DecryptedObject {
    <#
            .SYNOPSIS
                Internal function.

                This function is heavily based on Antti Rantasaari's script at http://goo.gl/wpqSib
                Antti Rantasaari 2014, NetSPI
                License: BSD 3-Clause http://opensource.org/licenses/BSD-3-Clause
    #>
    param (
        [Parameter(Mandatory)]
        [Microsoft.SqlServer.Management.Smo.Server]$SqlInstance,
        [Parameter(Mandatory)]
        [ValidateSet("LinkedServer", "Credential")]
        [string]$Type,
        [switch]$EnableException
    )

    $server = $SqlInstance
    $sourceName = $server.Name

    # Query Service Master Key from the database - remove padding from the key
    # key_id 102 eq service master key, thumbprint 3 means encrypted with machinekey
    Write-Message -Level Verbose -Message "Querying service master key"
    $sql = "SELECT substring(crypt_property,9,len(crypt_property)-8) as smk FROM sys.key_encryptions WHERE key_id=102 and (thumbprint=0x03 or thumbprint=0x0300000001)"
    try {
        $smkbytes = $server.Query($sql).smk
    } catch {
        Stop-Function -Message "Can't execute query on $sourcename" -Target $server -ErrorRecord $_
        return
    }

    $sourceNetBios = Resolve-NetBiosName $server
    $instance = $server.InstanceName
    $serviceInstanceId = $server.ServiceInstanceId

    Write-Message -Level Verbose -Message "Get entropy from the registry - hopefully finds the right SQL server instance"

    try {
        [byte[]]$entropy = Invoke-Command2 -Raw -Credential $Credential -ComputerName $sourceNetBios -argumentlist $serviceInstanceId {
            $serviceInstanceId = $args[0]
            $entropy = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$serviceInstanceId\Security\" -ErrorAction Stop).Entropy
            return $entropy
        }
    } catch {
        Stop-Function -Message "Can't access registry keys on $sourceName. Do you have administrative access to the Windows registry on $SqlInstance Otherwise, we're out of ideas." -Target $source
        return
    }

    Write-Message -Level Verbose -Message "Decrypt the service master key"
    try {
        $serviceKey = Invoke-Command2 -Raw -Credential $Credential -ComputerName $sourceNetBios -ArgumentList $smkbytes, $Entropy {
            Add-Type -AssemblyName System.Security
            Add-Type -AssemblyName System.Core
            $smkbytes = $args[0]; $Entropy = $args[1]
            $serviceKey = [System.Security.Cryptography.ProtectedData]::Unprotect($smkbytes, $Entropy, 'LocalMachine')
            return $serviceKey
        }
    } catch {
        Stop-Function -Message "Can't unprotect registry data on $sourcename. Do you have administrative access to the Windows registry on $sourcename? Otherwise, we're out of ideas." -Target $source
        return
    }

    # Choose the encryption algorithm based on the SMK length - 3DES for 2008, AES for 2012
    # Choose IV length based on the algorithm
    Write-Message -Level Verbose -Message "Choose the encryption algorithm based on the SMK length - 3DES for 2008, AES for 2012"

    if (($serviceKey.Length -ne 16) -and ($serviceKey.Length -ne 32)) {
        Write-Message -Level Verbose -Message "ServiceKey found: $serviceKey.Length"
        Stop-Function -Message "Unknown key size. Do you have administrative access to the Windows registry on $sourcename? Otherwise, we're out of ideas." -Target $source
        return
    }

    if ($serviceKey.Length -eq 16) {
        $decryptor = New-Object System.Security.Cryptography.TripleDESCryptoServiceProvider
        $ivlen = 8
    } elseif ($serviceKey.Length -eq 32) {
        $decryptor = New-Object System.Security.Cryptography.AESCryptoServiceProvider
        $ivlen = 16
    }

    <#
                Query link server password information from the Db.
                Remove header from pwdhash, extract IV (as iv) and ciphertext (as pass)
                Ignore links with blank credentials (integrated auth ?)
            #>

    Write-Message -Level Verbose -Message "Query link server password information from the Db."

    try {
        if (-not $server.IsClustered) {
            $connString = "Server=ADMIN:$sourceNetBios\$instance;Trusted_Connection=True"
        } else {
            $dacEnabled = $server.Configuration.RemoteDacConnectionsEnabled.ConfigValue

            if ($dacEnabled -eq $false) {
                If ($Pscmdlet.ShouldProcess($server.Name, "Enabling DAC on clustered instance.")) {
                    Write-Message -Level Verbose -Message "DAC must be enabled for clusters, even when accessed from active node. Enabling."
                    $server.Configuration.RemoteDacConnectionsEnabled.ConfigValue = $true
                    $server.Configuration.Alter()
                }
            }

            $connString = "Server=ADMIN:$sourceName;Trusted_Connection=True"
        }
    } catch {
        Stop-Function -Message "Failure enabling DAC on $sourcename" -Target $source -ErrorRecord $_
    }

    <# NOTE: This query is accessing syslnklgns table. Can only be done via the DAC connection #>

    $sql = switch ($Type) {
        "LinkedServer" {
            "SELECT sysservers.srvname,
                syslnklgns.Name,
                substring(syslnklgns.pwdhash,5,$ivlen) iv,
                substring(syslnklgns.pwdhash,$($ivlen + 5),
                len(syslnklgns.pwdhash)-$($ivlen + 4)) pass
            FROM master.sys.syslnklgns
                inner join master.sys.sysservers
                on syslnklgns.srvid=sysservers.srvid
            WHERE len(pwdhash) > 0"
        }
        "Credential" {
            "SELECT QUOTENAME(name) AS name,credential_identity,substring(imageval,5,$ivlen) iv, substring(imageval,$($ivlen + 5),len(imageval)-$($ivlen + 4)) pass from sys.Credentials cred inner join sys.sysobjvalues obj on cred.credential_id = obj.objid where valclass=28 and valnum=2"
        }
    }

    Write-Message -Level Debug -Message $sql
    Write-Message -Level Verbose -Message "Get entropy from the registry"

    try {
        $results = Invoke-Command2 -ErrorAction Stop -Raw -Credential $Credential -ComputerName $sourceNetBios -ArgumentList $connString, $sql {
            $connString = $args[0]; $sql = $args[1]
            $conn = New-Object System.Data.SqlClient.SQLConnection($connString)
            $cmd = New-Object System.Data.SqlClient.SqlCommand($sql, $conn)
            $dt = New-Object System.Data.DataTable
            $conn.open()
            $dt.Load($cmd.ExecuteReader())
            $conn.Close()
            $conn.Dispose()
            return $dt
        }
    } catch {
        try {
            $conn.Close()
            $conn.Dispose()
        } catch {
            $null = 1
        }
        Stop-Function -Message "Can't establish local DAC connection on $sourcename." -Target $server -ErrorRecord $_
        return
    }

    if ($server.IsClustered -and $dacEnabled -eq $false) {
        If ($Pscmdlet.ShouldProcess($server.Name, "Disabling DAC on clustered instance.")) {
            try {
                Write-Message -Level Verbose -Message "Setting DAC config back to 0."
                $server.Configuration.RemoteDacConnectionsEnabled.ConfigValue = $false
                $server.Configuration.Alter()
            } catch {
                Stop-Function -Message "Can't establish local DAC connection on $sourcename" -Target $server -ErrorRecord $_
                return
            }
        }
    }

    Write-Message -Level Verbose -Message "Go through each row in results"
    foreach ($result in $results) {
        # decrypt the password using the service master key and the extracted IV
        $decryptor.Padding = "None"
        $decrypt = $decryptor.Createdecryptor($serviceKey, $result.iv)
        $stream = New-Object System.IO.MemoryStream ( , $result.pass)
        $crypto = New-Object System.Security.Cryptography.CryptoStream $stream, $decrypt, "Write"

        $crypto.Write($result.pass, 0, $result.pass.Length)
        [byte[]]$decrypted = $stream.ToArray()

        # convert decrypted password to unicode
        $encode = New-Object System.Text.UnicodeEncoding

        # Print results - removing the weird padding (8 bytes in the front, some bytes at the end)...
        # Might cause problems but so far seems to work.. may be dependant on SQL server version...
        # If problems arise remove the next three lines..
        $i = 8; foreach ($b in $decrypted) { if ($decrypted[$i] -ne 0 -and $decrypted[$i + 1] -ne 0 -or $i -eq $decrypted.Length) { $i -= 1; break; }; $i += 1; }
        $decrypted = $decrypted[8 .. $i]

        if ($Type -eq "LinkedServer") {
            $name = $result.srvname
            $identity = $result.Name
        } else {
            $name = $result.name
            $identity = $result.credential_identity
        }
        [pscustomobject]@{
            Name     = $name
            Identity = $identity
            Password = $encode.GetString($decrypted)
        }
    }
}
tools\dbatools\internal\functions\Get-DirectoryRestoreFile.ps1
function Get-DirectoryRestoreFile {
    <#
.SYNOPSIS
Internal Function to get SQL Server backfiles from a specified folder

.DESCRIPTION
Takes path, checks for validity. Scans for usual backup file
    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [string]$Path,
        [switch]$Recurse,
        [Alias('Silent')]
        [switch]$EnableException
    )

    Write-Message -Level Verbose -Message "Starting"
    Write-Message -Level Verbose -Message "Checking Path"
    if ((Test-Path $Path) -ne $true) {
        Stop-Function -Message "$Path is not reachable"
        return
    }
    #Path needs to end \* to use includes, which is faster than Where-Object
    $PathCheckArray = $path.ToCharArray()
    if ($PathCheckArray[-2] -eq '\' -and $PathCheckArray[-1] -eq '*') {
        #We're good
    } elseif ($PathCheckArray[-2] -ne '\' -and $PathCheckArray[-1] -eq '*') {
        $Path = ($PathCheckArray[0..(($PathCheckArray.length) - 2)] -join ('')) + "\*"
    } elseif ($PathCheckArray[-2] -eq '\' -and $PathCheckArray[-1] -ne '*') {
        #Append a * to the end
        $Path = "$Path*"
    } elseif ($PathCheckArray[-2] -ne '\' -and $PathCheckArray[-1] -ne '*') {
        #Append a \* to the end
        $Path = "$Path\*"
    }
    Write-Message -Level Verbose -Message "Scanning $path"
    $Results = Get-ChildItem -path $Path -Recurse:$Recurse | Where-Object {$_.PsIsContainer -eq $false}
    return $Results
}
tools\dbatools\internal\functions\Get-ErrorMessage.ps1
function Get-ErrorMessage {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [System.Management.Automation.ErrorRecord]$Record
    )
    process {
        $innermessage = $Record.Exception.InnerException.InnerException.InnerException.InnerException.InnerException.Message
        if (-not $innermessage) { $innermessage = $Record.Exception.InnerException.InnerException.InnerException.InnerException.Message }
        if (-not $innermessage) { $innermessage = $Record.Exception.InnerException.InnerException.InnerException.Message }
        if (-not $innermessage) { $innermessage = $Record.Exception.InnerException.InnerException.Message }
        if (-not $innermessage) { $innermessage = $Record.Exception.InnerException.Message }
        if (-not $innermessage) { $innermessage = $Record.Exception.Message }
        return $innermessage
    }
}
tools\dbatools\internal\functions\Get-InternalService.ps1
function Get-InternalService {
    <#
    .SYNOPSIS
        Uses WMI/CIM to scan for the existance of a specific windows services.

    .DESCRIPTION
        Uses WMI/CIM to scan for the existance of a specific windows services.

        Use Get-InternalService if you are interested in scanning for sql server services exclusively.

    .PARAMETER ComputerName
        The computer to target. Uses localhost by default.

    .PARAMETER Name
        The name of the service to search for.

    .PARAMETER DisplayName
        The display-name of the service to search for.

    .PARAMETER Credential
        The credentials to use when connecting to the computer.

    .PARAMETER DoNotUse
        Connection Protocols that should not be used when retrieving the information.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .EXAMPLE
        Get-InternalService -Name LanmanServer

        Returns information on the LanmanServer service from localhost.

    .EXAMPLE
        Get-ADComputer -Filter * | Get-InternalService -Name Browser

        First retrieves all computer accounts from active directory, then scans all of those computers for the browser service.
        Note: THis may take seriously long time, you may also want to filter out computers that are offline before scanning for services.

    .EXAMPLE
        Get-InternalService -ComputerName "server1","server2","server3" -Name Lanman%

        Scans the servers server1, server2 and server3 for all services whose name starts with 'lanman'
    #>
    [CmdletBinding()]
    param (
        [string[]]
        $Name,

        [string[]]
        $DisplayName,

        [Parameter(ValueFromPipeline)]
        [Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter[]]
        $ComputerName = $env:COMPUTERNAME,

        [System.Management.Automation.PSCredential]
        $Credential,

        [Sqlcollaborative.Dbatools.Connection.ManagementConnectionType[]]
        $DoNotUse,

        [switch]
        [Alias('Silent')]$EnableException
    )

    begin {
        Write-Message -Level InternalComment -Message "Starting"
        Write-Message -Level System -Message "Bound parameters: $($PSBoundParameters.Keys -join ", ")"

        if (-not (Test-Bound "Name") -and -not (Test-Bound "DisplayName")) {
            $Name = "%"
        }
    }
    process {
        :main foreach ($computer in $ComputerName) {
            Write-Message -Level VeryVerbose -Message "Processing queries to $($computer.ComputerName)" -Target $computer.ComputerName
            foreach ($serviceName in $Name) {
                Write-Message -Level Verbose -Message "Searching for services with name: $serviceName" -Target $computer.ComputerName
                try {
                    if (Test-Bound "Credential") { Get-DbaCmObject -Query "SELECT * FROM Win32_Service WHERE Name LIKE '$serviceName'" -ComputerName $computer.ComputerName -Credential $Credential -EnableException -DoNotUse $DoNotUse }
                    else { Get-DbaCmObject -Query "SELECT * FROM Win32_Service WHERE Name LIKE '$serviceName'" -ComputerName $computer.ComputerName -EnableException -DoNotUse $DoNotUse }
                } catch {
                    if ($_.CategoryInfo.Category -eq "OpenError") {
                        Stop-Function -Message "Failed to access computer $($computer.ComputerName)" -ErrorRecord $_ -Target $computer.ComputerName -Continue -ContinueLabel main
                    } else {
                        Stop-Function -Message "Failed to retrieve service" -ErrorRecord $_ -Target $computer.ComputerName -Continue
                    }
                }
            }

            foreach ($serviceDisplayName in $DisplayName) {
                Write-Message -Level Verbose -Message "Searching for services with display name: $serviceDisplayName" -Target $computer.ComputerName
                try {
                    if (Test-Bound "Credential") { Get-DbaCmObject -Query "SELECT * FROM Win32_Service WHERE DisplayName LIKE '$serviceDisplayName'" -ComputerName $computer.ComputerName -Credential $Credential -EnableException -DoNotUse $DoNotUse }
                    else { Get-DbaCmObject -Query "SELECT * FROM Win32_Service WHERE DisplayName LIKE '$serviceDisplayName'" -ComputerName $computer.ComputerName -EnableException -DoNotUse $DoNotUse }
                } catch {
                    if ($_.CategoryInfo.Category -eq "OpenError") {
                        Stop-Function -Message "Failed to access computer $($computer.ComputerName)" -ErrorRecord $_ -Target $computer.ComputerName -Continue -ContinueLabel main
                    } else {
                        Stop-Function -Message "Failed to retrieve service" -ErrorRecord $_ -Target $computer.ComputerName -Continue
                    }
                }
            }
        }
    }
    end {
        Write-Message -Level InternalComment -Message "Ending"
    }
}
tools\dbatools\internal\functions\Get-JobList.ps1
function Get-JobList {
    <#
    .SYNOPSIS
        Helper function to get SQL Agent jobs.
    .DESCRIPTION
        Helper function to get all SQL Agent jobs or provide filter
    .PARAMETER SqlInstance
        SQL Server instance
    .PARAMETER SqlCredential
        Credential to use if SqlInstance did not include it.
    .PARAMETER JobFilter
        Object of jobs to filter on, also supports wildcard patterns
    .PARAMETER StepFilter
        Object of job steps to filter on, also supports wildcard patterns
    .PARAMETER Not
        Reverse results where object returned excludes filtered content.
    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .EXAMPLE
        Get-JobList -SqlInstance sql2016

        Returns the full JobServer.Jobs object found on sql2016
    .EXAMPLE
        Get-JobList -SqlInstance sql2016 -JobFilter '*job*'

        Returns the Job object for each job name found to have "job" in the name on sql2016
    .EXAMPLE
        Get-JobList -SqlInstance sql2016 -JobFilter '*job*' -Not

        Returns any Job object that does not have "job" in the name on sql2016
    .EXAMPLE
        Get-JobList -SqlInstance YourServer -JobFilter 'JobName'

        Returns the Job object where the job name is 'JobName' on sql2016
    .EXAMPLE
        Get-JobList -SqlInstance YourServer -JobFilter 'JobName' -Not

        Returns any Job object where the job name is not 'JobName' on sql2016
    .EXAMPLE
        Get-JobList -SqlInstance YourServer -JobFilter job_3_upload, job_3_download

        Returns the Job object for where job is job_3_upload or job_3_download on sql2016
    .EXAMPLE
        Get-JobList -SqlInstance YourServer -JobFilter job_3_upload, job_3_download -Not

        Returns any Job object where job is not job_3_upload or job_3_download on sql2016
    .NOTES
        Author: Shawn Melton (@wsmelton)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT
       #>
    [cmdletbinding()]
    param(
        [Parameter(ValueFromPipeline)]
        [DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$JobFilter,
        [string[]]$StepFilter,
        [switch]$Not,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential

        $jobs = $server.JobServer.Jobs
        if ( (Test-Bound 'JobFilter') -or (Test-Bound 'StepFilter') ) {
            if ($JobFilter.Count -gt 1) {
                if ($Not) {
                    $jobs | Where-Object Name -NotIn $JobFilter
                } else {
                    $jobs | Where-Object Name -In $JobFilter
                }
            } else {
                foreach ($job in $jobs) {
                    if ($JobFilter -match '`*') {
                        if ($Not) {
                            $job | Where-Object Name -NotLike $JobFilter
                        } else {
                            $job | Where-Object Name -Like $JobFilter
                        }
                    } else {
                        if ($Not) {
                            $job | Where-Object Name -NE $JobFilter
                        } else {
                            $job | Where-Object Name -EQ $JobFilter
                        }
                    }
                    if ($StepFilter -match '`*') {
                        if ($Not) {
                            $stepFound = $job.JobSteps | Where-Object Name -NotLike $StepFilter
                            if ($stepFound.Count -gt 0) {
                                $job
                            }
                        } else {
                            $stepFound = $job.JobSteps | Where-Object Name -Like $StepFilter
                            if ($stepFound.Count -gt 0) {
                                $job
                            }
                        }
                    } elseif ($StepName.Count -gt 1) {
                        if ($Not) {
                            $stepFound = $job.JobSteps | Where-Object Name -NotIn $StepName
                            if ($stepFound.Count -gt 0) {
                                $job
                            }
                        } else {
                            $stepFound = $job.JobSteps | Where-Object Name -In $StepName
                            if ($stepFound.Count -gt 0) {
                                $job
                            }
                        }
                    } else {
                        if ($Not) {
                            $stepFound = $job.JobSteps | Where-Object Name -NE $StepName
                            if ($stepFound.Count -gt 0) {
                                $job
                            }
                        } else {
                            $stepFound = $job.JobSteps | Where-Object Name -EQ $StepName
                            if ($stepFound.Count -gt 0) {
                                $job
                            }
                        }
                    }
                }
            }
        } else {
            $jobs
        }
    }
}
tools\dbatools\internal\functions\Get-Language.ps1
function Get-Language {
    <#
        .SYNOPSIS
            Converts Microsoft's language ID to human readable format

        .DESCRIPTION
            Converts Microsoft's language ID to human readable format

        .PARAMETER Id
            The language ID

        .EXAMPLE
            Get-Language 1033

            Returns a pscustomobject with id, alias and name
       #>
    [CmdletBinding()]
    param (
        [int]$id
    )
    process {

        $culture = [System.Globalization.CultureInfo]::GetCultureInfo($id)

        $excludeProps = 'Parent', 'IetfLanguageTag', 'CompareInfo', 'TextInfo', 'IsNeutralCulture', 'NumberFormat', 'DateTimeFormat', 'Calendar'
        , 'OptionalCalendars', 'UseUserOverride', 'IsReadOnly'
        Select-DefaultView -InputObject $culture -ExcludeProperty $excludeProps
    }
}
tools\dbatools\internal\functions\Get-OfflineSqlFileStructure.ps1
function Get-OfflineSqlFileStructure {
    <#
.SYNOPSIS
Internal function. Returns dictionary object that contains file structures for SQL databases.

    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, Position = 0)]
        [ValidateNotNullOrEmpty()]
        [object]$SqlInstance,
        [Parameter(Mandatory, Position = 1)]
        [string]$dbname,
        [Parameter(Mandatory, Position = 2)]
        [object]$filelist,
        [Parameter(Position = 3)]
        [bool]$ReuseSourceFolderStructure,
        [PSCredential]$SqlCredential
    )

    $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential

    $destinationfiles = @{ };
    $logfiles = $filelist | Where-Object { $_.Type -eq "L" }
    $datafiles = $filelist | Where-Object { $_.Type -ne "L" }
    $filestream = $filelist | Where-Object { $_.Type -eq "S" }

    if ($filestream) {
        $sql = "select coalesce(SERVERPROPERTY('FilestreamConfiguredLevel'),0) as fs"
        $fscheck = $server.databases['master'].ExecuteWithResults($sql)
        if ($fscheck.tables.fs -eq 0) { return $false }
    }

    # Data Files
    foreach ($file in $datafiles) {
        # Destination File Structure
        $d = @{ }
        if ($ReuseSourceFolderStructure -eq $true) {
            $d.physical = $file.PhysicalName
        } else {
            $directory = Get-SqlDefaultPaths $server data
            $filename = Split-Path $($file.PhysicalName) -leaf
            $d.physical = "$directory\$filename"
        }

        $d.logical = $file.LogicalName
        $destinationfiles.add($file.LogicalName, $d)
    }

    # Log Files
    foreach ($file in $logfiles) {
        $d = @{ }
        if ($ReuseSourceFolderStructure) {
            $d.physical = $file.PhysicalName
        } else {
            $directory = Get-SqlDefaultPaths $server log
            $filename = Split-Path $($file.PhysicalName) -leaf
            $d.physical = "$directory\$filename"
        }

        $d.logical = $file.LogicalName
        $destinationfiles.add($file.LogicalName, $d)
    }

    return $destinationfiles
}
tools\dbatools\internal\functions\Get-PasswordHash.ps1
function Get-PasswordHash {
    <#
    .SYNOPSIS
    Generates a password hash for SQL Server login

    .DESCRIPTION
    Generates a hash string based on the plaintext or securestring password and a SQL Server version. Salt is optional

    .PARAMETER Password
    Either plain text or Securestring password

    .PARAMETER SqlMajorVersion
    Major version of the SQL Server. Defines the hash algorithm.

    .PARAMETER byteSalt
    Optional. Inserts custom salt into the hash instead of randomly generating new salt

    .NOTES
    Tags: Login, Internal
    Author: Kirill Kravtsov (@nvarscar)
    dbatools PowerShell module (https://dbatools.io, [email protected])
   Copyright: (c) 2018 by dbatools, licensed under MIT
    License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
    Get-PasswordHash $securePassword 11

    Generates password hash for SQL 2012

    .EXAMPLE
    Get-PasswordHash $securePassword 9 $byte

    Generates password hash for SQL 2005 using custom salt from the $byte variable

    #>
    param (
        [object]$Password,
        $SqlMajorVersion,
        [byte[]]$byteSalt
    )
    #Choose hash algorithm
    if ($SqlMajorVersion -lt 11) {
        $algorithm = 'SHA1'
        $hashVersion = '0100'
    } else {
        $algorithm = 'SHA512'
        $hashVersion = '0200'
    }

    #Generate salt
    if (!$byteSalt) {
        0 .. 3 | ForEach-Object { $byteSalt += Get-Random -Minimum 0 -Maximum 255 }
    }

    #Convert salt to a hex string
    [string]$stringSalt = ""
    $byteSalt | ForEach-Object { $stringSalt += ("{0:X}" -f $_).PadLeft(2, "0") }

    #Extract password
    if ($Password.GetType().Name -eq 'SecureString') {
        $cred = New-Object System.Management.Automation.PSCredential -ArgumentList 'foo', $Password
        $plainPassword = $cred.GetNetworkCredential().Password
    } else {
        $plainPassword = $Password
    }
    #Get byte representation of the password string
    $enc = [system.Text.Encoding]::Unicode
    $data = $enc.GetBytes($plainPassword)
    #Run hash algorithm
    $hash = [Security.Cryptography.HashAlgorithm]::Create($algorithm)
    $bytes = $hash.ComputeHash($data + $byteSalt)
    #Construct hex string
    $hashString = "0x$hashVersion$stringSalt"
    $bytes | ForEach-Object { $hashString += ("{0:X2}" -f $_).PadLeft(2, "0") }
    #Add UPPERCASE hash for SQL 2000 and lower
    if ($SqlMajorVersion -lt 9) {
        $data = $enc.GetBytes($plainPassword.ToUpper())
        $bytes = $hash.ComputeHash($data + $byteSalt)
        $bytes | ForEach-Object { $hashString += ("{0:X2}" -f $_).PadLeft(2, "0") }
    }
    return $hashString
}
tools\dbatools\internal\functions\Get-RegServerGroupReverseParse.ps1
function Get-RegServerGroupReverseParse ($object) {
    if ($object.Name -eq 'DatabaseEngineServerGroup') {
        $object.Name
    } else {
        $name = @()
        do {
            $name += $object.Name.Split("\")[0]
            $object = $object.Parent
        }
        until ($object.Name -eq 'DatabaseEngineServerGroup')

        [array]::Reverse($name)
        $name -join '\'
    }
}
tools\dbatools\internal\functions\Get-RegServerParent.ps1
function Get-RegServerParent {
    [cmdletbinding()]
    param (
        [object]$InputObject
    )
    process {
        $parentcount = 0
        do {
            if ($null -ne $InputObject.Parent) {
                $InputObject = $InputObject.Parent
            }
        }
        until ($null -ne $InputObject.ServerConnection -or $parentcount++ -gt 10)


        if ($parentcount -lt 10) {
            $InputObject
        }
    }
}
tools\dbatools\internal\functions\Get-ResourceState.ps1
function Get-ResourceState ($state) {
    switch ($state) {
        -1 { "Unknown" }
        0 { "Inherited" }
        1 { "Initializing" }
        2 { "Online" }
        3 { "Offline" }
        4 { "Failed" }
        128 { "Pending" }
        129 { "Online Pending" }
        130 { "Offline Pending" }
    }
}
tools\dbatools\internal\functions\Get-RestoreContinuableDatabase.ps1
function Get-RestoreContinuableDatabase {
    <#
    .SYNOPSIS
    Gets a list of databases from a SQL instance that are in a state for further restores

    .DESCRIPTION
    Takes a SQL instance and checks for databases with a redo_start_lsn value, and returns the database name and that value
    -gt SQl 2005 it comes from master.sys.master_files
    -eq SQL 2000 DBCC DBINFO
    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [object]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    try {
        $Server = Connect-SqlInstance -Sqlinstance $SqlInstance -SqlCredential $SqlCredential
    } catch {
        Write-Message -Level Warning -Message "Cannot connect to $SqlInstance"
        break
    }
    if ($Server.VersionMajor -ge 9) {
        $sql = "select distinct db_name(database_id) as 'Database', differential_base_lsn, redo_start_lsn, redo_start_fork_guid as 'FirstRecoveryForkID' from master.sys.master_files where redo_start_lsn is not NULL"
    } else {
        $sql = "
              CREATE TABLE #db_info
                (
                ParentObject NVARCHAR(128) COLLATE database_default ,
                Object       NVARCHAR(128) COLLATE database_default,
                Field        NVARCHAR(128) COLLATE database_default,
                Value        SQL_VARIANT
                )"
    }
    $server.ConnectionContext.ExecuteWithResults($sql).Tables.Rows
}
tools\dbatools\internal\functions\Get-SaLoginName.ps1
function Get-SaLoginName {
    <#
    .SYNOPSIS
    Gets the login matching the standard "sa" user

    .DESCRIPTION
    Gets the login matching the standard "sa" user, useful in case of renames

    .PARAMETER SqlInstance
    The SQL Server instance.

    .PARAMETER SqlCredential
    Allows you to login to servers using SQL Logins instead of Windows Authentication (AKA Integrated or Trusted).

    .EXAMPLE
    Get-SaLoginName -SqlInstance base\sql2016

    .NOTES
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT
       #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [object]$SqlInstance,
        [PSCredential]$SqlCredential
    )

    $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
    $saname = ($server.logins | Where-Object { $_.id -eq 1 }).Name

    return $saname
}
tools\dbatools\internal\functions\Get-SmoServerForDynamicParams.ps1
function Get-SmoServerForDynamicParams {
    ##############################
    # THIS DOES NOT SEEM TO BE USED
    ##############################
    if ($fakeBoundParameter.length -eq 0) { return }

    $SqlInstance = $fakeBoundParameter['SqlInstance']
    $sqlcredential = $fakeBoundParameter['SqlCredential']

    if ($null -eq $SqlInstance) {
        $SqlInstance = $fakeBoundParameter['sqlinstance']
    }
    if ($null -eq $SqlInstance) {
        $SqlInstance = $fakeBoundParameter['source']
    }
    if ($null -eq $sqlcredential) {
        $sqlcredential = $fakeBoundParameter['Credential']
    }

    if ($SqlInstance) {
        Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential -ParameterConnection
    }
}
tools\dbatools\internal\functions\Get-SqlCmdVars.ps1
function Get-SqlCmdVars {
    <#
        .SYNOPSIS
            Retrieves the values of PowerShell parameters and updates values of SqlmdVars listed in the publish.xml.

        .DESCRIPTION
            Attempt to resolve SQLCmd variables via matching powershell variables explicitly defined in the current context.
            To try and avoid 'bad' default values getting deployed, block a deployment if we have SqlCmd variables that aren't defined in current context.
            Function has one reference and is executed when the "getSqlCmdVars" switch is included.
        .PARAMETER SqlCommandVariableValues
            Mandatory. The SqlCommandVariableValues from the DeployOptions property in the Microsoft.SqlServer.Dac.DacProfile
        .PARAMETER EnableException
            By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
            This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
            Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

        .NOTES
            Author: Richie lee (@bzzzt_io)

            Website: https://dbatools.io
            Copyright: (c) 2018 by dbatools, licensed under MIT
            License: MIT https://opensource.org/licenses/MIT
        .LINK
            https://dbatools.io/Test-Noun

        .EXAMPLE
        Imagine content of MyDbProject.publish.xml is as follows -
        <?xml version="1.0" encoding="utf-8"?>
        <Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
        <PropertyGroup>
            <IncludeCompositeObjects>True</IncludeCompositeObjects>
            <TargetDatabaseName>MyDbProject</TargetDatabaseName>
            <DeployScriptFileName>MyDbProject.sql</DeployScriptFileName>
            <TargetConnectionString>Data Source=.;Integrated Security=True;Persist Security Info=False;Pooling=False;MultipleActiveResultSets=False;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True</TargetConnectionString>
            <BlockOnPossibleDataLoss>True</BlockOnPossibleDataLoss>
            <CreateNewDatabase>False</CreateNewDatabase>
            <ProfileVersionNumber>1</ProfileVersionNumber>
        </PropertyGroup>
        <ItemGroup>
            <SqlCmdVariable Include="DeployTag">
            <Value>OldValue</Value>
            </SqlCmdVariable>
        </ItemGroup>
        </Project>
        We will need one PowerShell parameter named $DeployTag to update the value

        The following scenario will fail as no $deployTag -
        "
            $publishXml =  "C:\MyDbProject\bin\Debug\MyDbProject.publish.xml"
            $dacProfile = [Microsoft.SqlServer.Dac.DacProfile]::Load($publishXml)
            Get-SqlCmdVars $dacProfile.DeployOptions.SqlCommandVariableValues -EnableException
        "
        This scenario will pass.
        "
            $deployTag = "NewValue"
            $publishXml =  "C:\MyDbProject\bin\Debug\MyDbProject.publish.xml"
            $dacProfile = [Microsoft.SqlServer.Dac.DacProfile]::Load($publishXml)
            Get-SqlCmdVars $dacProfile.DeployOptions.SqlCommandVariableValues -EnableException
        "
       #>
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory)]
        $SqlCommandVariableValues,
        [switch]$EnableException
    )
    $missingVariables = @()
    $keys = $($SqlCommandVariableValues.Keys)
    foreach ($var in $keys) {
        if (Test-Path variable:$var) {
            $value = Get-Variable $var -ValueOnly
            $SqlCommandVariableValues[$var] = $value
        } else {
            $missingVariables += $var
        }
    }
    if ($missingVariables.Count -gt 0) {
        $errorMsg = 'The following SqlCmd variables are not defined in the session (but are defined in the publish profile): {0}' -f ($missingVariables -join " `n")
        Stop-Function -Message $errorMsg -EnableException $EnableException
    }
}
tools\dbatools\internal\functions\Get-SqlDefaultPaths.ps1
function Get-SqlDefaultPaths {
    <#
    .SYNOPSIS
        Internal function. Returns the default data and log paths for SQL Server. Needed because SMO's server.defaultpath is sometimes null.
    #>
    [CmdletBinding()]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "")]
    param (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [Alias("ServerInstance", "SqlServer")]
        [object]$SqlInstance,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$filetype,
        [PSCredential]$SqlCredential
    )

    try {
        if ($SqlInstance -isnot [Microsoft.SqlServer.Management.Smo.SqlSmoObject]) {
            $Server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        } else {
            $server = $SqlInstance
        }
    } catch {
        Write-Message -Lvel Warning -Message "Cannot connect to $SqlInstance"
        break
    }
    switch ($filetype) { "mdf" { $filetype = "data" } "ldf" { $filetype = "log" } }

    if ($filetype -eq "log") {
        # First attempt
        $filepath = $server.DefaultLog
        # Second attempt
        if ($filepath.Length -eq 0) { $filepath = $server.Information.MasterDbLogPath }
        # Third attempt
        if ($filepath.Length -eq 0) {
            $sql = "select SERVERPROPERTY('InstanceDefaultLogPath') as physical_name"
            $filepath = $server.ConnectionContext.ExecuteScalar($sql)
        }
    } else {
        # First attempt
        $filepath = $server.DefaultFile
        # Second attempt
        if ($filepath.Length -eq 0) { $filepath = $server.Information.MasterDbPath }
        # Third attempt
        if ($filepath.Length -eq 0) {
            $sql = "select SERVERPROPERTY('InstanceDefaultDataPath') as physical_name"
            $filepath = $server.ConnectionContext.ExecuteScalar($sql)
        }
    }

    if ($filepath.Length -eq 0) { throw "Cannot determine the required directory path" }
    $filepath = $filepath.TrimEnd("\")
    return $filepath
}
tools\dbatools\internal\functions\Get-SqlDefaultSpConfigure.ps1
function Get-SqlDefaultSpConfigure {
    <#
        .SYNOPSIS
        Internal function. Returns the default sp_configure options for a given version of SQL Server.

        .NOTES
        Server Configuration Options BOL (links subject to change):
        SQL Server 2017 - https://technet.microsoft.com/en-us/library/ms189631(v=sql.140).aspx
        SQL Server 2016 - https://technet.microsoft.com/en-us/library/ms189631(v=sql.130).aspx
        SQL Server 2014 - http://technet.microsoft.com/en-us/library/ms189631(v=sql.120).aspx
        SQL Server 2012 - http://technet.microsoft.com/en-us/library/ms189631(v=sql.110).aspx
        SQL Server 2008 R2 - http://technet.microsoft.com/en-us/library/ms189631(v=sql.105).aspx
        SQL Server 2008 - http://technet.microsoft.com/en-us/library/ms189631(v=sql.100).aspx
        SQL Server 2005 - http://technet.microsoft.com/en-us/library/ms189631(v=sql.90).aspx
        SQL Server 2000 - http://technet.microsoft.com/en-us/library/aa196706(v=sql.80).aspx (requires PDF download)

        .EXAMPLE
        Get-SqlDefaultSpConfigure -SqlVersion 11
        Returns a list of sp_configure (sys.configurations) items for SQL 2012.

    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [Alias("Version")]
        [object]$SqlVersion
    )

    switch ($SqlVersion) {

        #region SQL2000
        8 {
            [pscustomobject]@{
                "affinity mask"                  = 0
                "allow updates"                  = 0
                "awe enabled"                    = 0
                "c2 audit mode"                  = 0
                "cost threshold for parallelism" = 5
                "Cross DB Ownership Chaining"    = 0
                "cursor threshold"               = -1
                "default full-text language"     = 1033
                "default language"               = 0
                "fill factor (%)"                = 0
                "index create memory (KB)"       = 0
                "lightweight pooling"            = 0
                "locks"                          = 0
                "max degree of parallelism"      = 0
                "max server memory (MB)"         = 2147483647
                "max text repl size (B)"         = 65536
                "max worker threads"             = 255
                "media retention"                = 0
                "min memory per query (KB)"      = 1024
                "min server memory (MB)"         = 0
                "nested triggers"                = 1
                "network packet size (B)"        = 4096
                "open objects"                   = 0
                "priority boost"                 = 0
                "query governor cost limit"      = 0
                "query wait (s)"                 = -1
                "recovery interval (min)"        = 0
                "remote access"                  = 1
                "remote login timeout (s)"       = 20
                "remote proc trans"              = 0
                "remote query timeout (s)"       = 600
                "scan for startup procs"         = 0
                "set working set size"           = 0
                "show advanced options"          = 0
                "two digit year cutoff"          = 2049
                "user connections"               = 0
                "user options"                   = 0
            }
        }
        #endregion SQL2000

        #region SQL2005
        9 {
            [pscustomobject]@{
                "Ad Hoc Distributed Queries"         = 0
                "affinity I/O mask"                  = 0
                "affinity64 I/O mask"                = 0
                "affinity mask"                      = 0
                "affinity64 mask"                    = 0
                "Agent XPs"                          = 0
                "allow updates"                      = 0
                "awe enabled"                        = 0
                "blocked process threshold"          = 0
                "c2 audit mode"                      = 0
                "clr enabled"                        = 0
                "common criteria compliance enabled" = 0
                "cost threshold for parallelism"     = 5
                "cross db ownership chaining"        = 0
                "cursor threshold"                   = -1
                "Database Mail XPs"                  = 0
                "default full-text language"         = 1033
                "default language"                   = 0
                "default trace enabled"              = 1
                "disallow results from triggers"     = 0
                "fill factor (%)"                    = 0
                "ft crawl bandwidth (max)"           = 100
                "ft crawl bandwidth (min)"           = 0
                "ft notify bandwidth (max)"          = 100
                "ft notify bandwidth (min)"          = 0
                "index create memory (KB)"           = 0
                "in-doubt xact resolution"           = 0
                "lightweight pooling"                = 0
                "locks"                              = 0
                "max degree of parallelism"          = 0
                "max full-text crawl range"          = 4
                "max server memory (MB)"             = 2147483647
                "max text repl size (B)"             = 65536
                "max worker threads"                 = 0
                "media retention"                    = 0
                "min memory per query (KB)"          = 1024
                "min server memory (MB)"             = 8
                "nested triggers"                    = 1
                "network packet size (B)"            = 4096
                "Ole Automation Procedures"          = 0
                "open objects"                       = 0
                "PH timeout (s)"                     = 60
                "precompute rank"                    = 0
                "priority boost"                     = 0
                "query governor cost limit"          = 0
                "query wait (s)"                     = -1
                "recovery interval (min)"            = 0
                "remote access"                      = 1
                "remote admin connections"           = 0
                "remote login timeout (s)"           = 20
                "remote proc trans"                  = 0
                "remote query timeout (s)"           = 600
                "Replication XPs"                    = 0
                "scan for startup procs"             = 0
                "server trigger recursion"           = 1
                "set working set size"               = 0
                "show advanced options"              = 0
                "SMO and DMO XPs"                    = 1
                "SQL Mail XPs"                       = 0
                "transform noise words"              = 0
                "two digit year cutoff"              = 2049
                "user connections"                   = 0
                "User Instance Timeout"              = 60
                "user instances enabled"             = 0
                "user options"                       = 0
                "Web Assistant Procedures"           = 0
                "xp_cmdshell"                        = 0
            }
        }

        #endregion SQL2005

        #region SQL2008&2008R2
        10 {
            [pscustomobject]@{
                "access check cache bucket count"    = 0
                "access check cache quota"           = 0
                "Ad Hoc Distributed Queries"         = 0
                "affinity I/O mask"                  = 0
                "affinity64 I/O mask"                = 0
                "affinity mask"                      = 0
                "affinity64 mask"                    = 0
                "Agent XPs"                          = 0
                "allow updates"                      = 0
                "awe enabled"                        = 0
                "backup compression default"         = 0
                "blocked process threshold (s)"      = 0
                "c2 audit mode"                      = 0
                "clr enabled"                        = 0
                "common criteria compliance enabled" = 0
                "cost threshold for parallelism"     = 5
                "cross db ownership chaining"        = 0
                "cursor threshold"                   = -1
                "Database Mail XPs"                  = 0
                "default full-text language"         = 1033
                "default language"                   = 0
                "default trace enabled"              = 1
                "disallow results from triggers"     = 0
                "EKM provider enabled"               = 0
                "filestream access level"            = 0
                "fill factor (%)"                    = 0
                "ft crawl bandwidth (max)"           = 100
                "ft crawl bandwidth (min)"           = 0
                "ft notify bandwidth (max)"          = 100
                "ft notify bandwidth (min)"          = 0
                "index create memory (KB)"           = 0
                "in-doubt xact resolution"           = 0
                "lightweight pooling"                = 0
                "locks"                              = 0
                "max degree of parallelism"          = 0
                "max full-text crawl range"          = 4
                "max server memory (MB)"             = 2147483647
                "max text repl size (B)"             = 65536
                "max worker threads"                 = 0
                "media retention"                    = 0
                "min memory per query (KB)"          = 1024
                "min server memory (MB)"             = 0
                "nested triggers"                    = 1
                "network packet size (B)"            = 4096
                "Ole Automation Procedures"          = 0
                "open objects"                       = 0
                "optimize for ad hoc workloads"      = 0
                "PH timeout (s)"                     = 60
                "precompute rank"                    = 0
                "priority boost"                     = 0
                "query governor cost limit"          = 0
                "query wait (s)"                     = -1
                "recovery interval (min)"            = 0
                "remote access"                      = 1
                "remote admin connections"           = 0
                "remote login timeout (s)"           = 20
                "remote proc trans"                  = 0
                "remote query timeout (s)"           = 600
                "Replication XPs"                    = 0
                "scan for startup procs"             = 0
                "server trigger recursion"           = 1
                "set working set size"               = 0
                "show advanced options"              = 0
                "SMO and DMO XPs"                    = 1
                "SQL Mail XPs"                       = 0
                "transform noise words"              = 0
                "two digit year cutoff"              = 2049
                "user connections"                   = 0
                "User Instance Timeout"              = 60
                "user instances enabled"             = 0
                "user options"                       = 0
                "xp_cmdshell"                        = 0
            }
        }
        #endregion SQL2008&2008R2

        #region SQL2012
        11 {
            [pscustomobject]@{
                "access check cache bucket count"    = 0
                "access check cache quota"           = 0
                "Ad Hoc Distributed Queries"         = 0
                "affinity I/O mask"                  = 0
                "affinity64 I/O mask"                = 0
                "affinity mask"                      = 0
                "affinity64 mask"                    = 0
                "Agent XPs"                          = 0
                "allow updates"                      = 0
                "backup compression default"         = 0
                "blocked process threshold (s)"      = 0
                "c2 audit mode"                      = 0
                "clr enabled"                        = 0
                "common criteria compliance enabled" = 0
                "contained database authentication"  = 0
                "cost threshold for parallelism"     = 5
                "cross db ownership chaining"        = 0
                "cursor threshold"                   = -1
                "Database Mail XPs"                  = 0
                "default full-text language"         = 1033
                "default language"                   = 0
                "default trace enabled"              = 1
                "disallow results from triggers"     = 0
                "EKM provider enabled"               = 0
                "filestream access level"            = 0
                "fill factor (%)"                    = 0
                "ft crawl bandwidth (max)"           = 100
                "ft crawl bandwidth (min)"           = 0
                "ft notify bandwidth (max)"          = 100
                "ft notify bandwidth (min)"          = 0
                "index create memory (KB)"           = 0
                "in-doubt xact resolution"           = 0
                "lightweight pooling"                = 0
                "locks"                              = 0
                "max degree of parallelism"          = 0
                "max full-text crawl range"          = 4
                "max server memory (MB)"             = 2147483647
                "max text repl size (B)"             = 65536
                "max worker threads"                 = 0
                "media retention"                    = 0
                "min memory per query (KB)"          = 1024
                "min server memory (MB)"             = 0
                "nested triggers"                    = 1
                "network packet size (B)"            = 4096
                "Ole Automation Procedures"          = 0
                "open objects"                       = 0
                "optimize for ad hoc workloads"      = 0
                "PH timeout (s)"                     = 60
                "precompute rank"                    = 0
                "priority boost"                     = 0
                "query governor cost limit"          = 0
                "query wait (s)"                     = -1
                "recovery interval (min)"            = 0
                "remote access"                      = 1
                "remote admin connections"           = 0
                "remote login timeout (s)"           = 10
                "remote proc trans"                  = 0
                "remote query timeout (s)"           = 600
                "Replication XPs"                    = 0
                "scan for startup procs"             = 0
                "server trigger recursion"           = 1
                "set working set size"               = 0
                "show advanced options"              = 0
                "SMO and DMO XPs"                    = 1
                "transform noise words"              = 0
                "two digit year cutoff"              = 2049
                "user connections"                   = 0
                "User Instance Timeout"              = 60
                "user instances enabled"             = 0
                "user options"                       = 0
                "xp_cmdshell"                        = 0
            }
        }
        #endregion SQL2012

        #region SQL2014
        12 {
            [pscustomobject]@{
                "access check cache bucket count"    = 0
                "access check cache quota"           = 0
                "Ad Hoc Distributed Queries"         = 0
                "affinity I/O mask"                  = 0
                "affinity64 I/O mask"                = 0
                "affinity mask"                      = 0
                "affinity64 mask"                    = 0
                "Agent XPs"                          = 0
                "allow updates"                      = 0
                "backup checksum default"            = 0
                "backup compression default"         = 0
                "blocked process threshold (s)"      = 0
                "c2 audit mode"                      = 0
                "clr enabled"                        = 0
                "common criteria compliance enabled" = 0
                "contained database authentication"  = 0
                "cost threshold for parallelism"     = 5
                "cross db ownership chaining"        = 0
                "cursor threshold"                   = -1
                "Database Mail XPs"                  = 0
                "default full-text language"         = 1033
                "default language"                   = 0
                "default trace enabled"              = 1
                "disallow results from triggers"     = 0
                "EKM provider enabled"               = 0
                "filestream access level"            = 0
                "fill factor (%)"                    = 0
                "ft crawl bandwidth (max)"           = 100
                "ft crawl bandwidth (min)"           = 0
                "ft notify bandwidth (max)"          = 100
                "ft notify bandwidth (min)"          = 0
                "index create memory (KB)"           = 0
                "in-doubt xact resolution"           = 0
                "lightweight pooling"                = 0
                "locks"                              = 0
                "max degree of parallelism"          = 0
                "max full-text crawl range"          = 4
                "max server memory (MB)"             = 2147483647
                "max text repl size (B)"             = 65536
                "max worker threads"                 = 0
                "media retention"                    = 0
                "min memory per query (KB)"          = 1024
                "min server memory (MB)"             = 0
                "nested triggers"                    = 1
                "network packet size (B)"            = 4096
                "Ole Automation Procedures"          = 0
                "open objects"                       = 0
                "optimize for ad hoc workloads"      = 0
                "PH timeout (s)"                     = 60
                "precompute rank"                    = 0
                "priority boost"                     = 0
                "query governor cost limit"          = 0
                "query wait (s)"                     = -1
                "recovery interval (min)"            = 0
                "remote access"                      = 1
                "remote admin connections"           = 0
                "remote login timeout (s)"           = 10
                "remote proc trans"                  = 0
                "remote query timeout (s)"           = 600
                "Replication XPs"                    = 0
                "scan for startup procs"             = 0
                "server trigger recursion"           = 1
                "set working set size"               = 0
                "show advanced options"              = 0
                "SMO and DMO XPs"                    = 1
                "transform noise words"              = 0
                "two digit year cutoff"              = 2049
                "user connections"                   = 0
                "User Instance Timeout"              = 60
                "user instances enabled"             = 0
                "user options"                       = 0
                "xp_cmdshell"                        = 0
            }
        }
        #endregion SQL2014

        #region SQL2016
        13 {
            [pscustomobject]@{
                "access check cache bucket count"    = 0
                "access check cache quota"           = 0
                "Ad Hoc Distributed Queries"         = 0
                "affinity I/O mask"                  = 0
                "affinity64 I/O mask"                = 0
                "affinity mask"                      = 0
                "affinity64 mask"                    = 0
                "Agent XPs"                          = 0
                "allow polybase export"              = 0
                "allow updates"                      = 0
                "automatic soft-NUMA disabled"       = 0
                "backup checksum default"            = 0
                "backup compression default"         = 0
                "blocked process threshold (s)"      = 0
                "c2 audit mode"                      = 0
                "clr enabled"                        = 0
                "common criteria compliance enabled" = 0
                "contained database authentication"  = 0
                "cost threshold for parallelism"     = 5
                "cross db ownership chaining"        = 0
                "cursor threshold"                   = -1
                "Database Mail XPs"                  = 0
                "default full-text language"         = 1033
                "default language"                   = 0
                "default trace enabled"              = 1
                "disallow results from triggers"     = 0
                "EKM provider enabled"               = 0
                "external scripts enabled"           = 0
                "filestream access level"            = 0
                "fill factor (%)"                    = 0
                "ft crawl bandwidth (max)"           = 100
                "ft crawl bandwidth (min)"           = 0
                "ft notify bandwidth (max)"          = 100
                "ft notify bandwidth (min)"          = 0
                "hadoop connectivity"                = 0
                "index create memory (KB)"           = 0
                "in-doubt xact resolution"           = 0
                "lightweight pooling"                = 0
                "locks"                              = 0
                "max degree of parallelism"          = 0
                "max full-text crawl range"          = 4
                "max server memory (MB)"             = 2147483647
                "max text repl size (B)"             = 65536
                "max worker threads"                 = 0
                "media retention"                    = 0
                "min memory per query (KB)"          = 1024
                "min server memory (MB)"             = 0
                "nested triggers"                    = 1
                "network packet size (B)"            = 4096
                "Ole Automation Procedures"          = 0
                "open objects"                       = 0
                "optimize for ad hoc workloads"      = 0
                "PH timeout (s)"                     = 60
                "polybase network encryption"        = 1
                "precompute rank"                    = 0
                "priority boost"                     = 0
                "query governor cost limit"          = 0
                "query wait (s)"                     = -1
                "recovery interval (min)"            = 0
                "remote access"                      = 1
                "remote admin connections"           = 0
                "remote data archive"                = 0
                "remote login timeout (s)"           = 10
                "remote proc trans"                  = 0
                "remote query timeout (s)"           = 600
                "Replication XPs"                    = 0
                "scan for startup procs"             = 0
                "server trigger recursion"           = 1
                "set working set size"               = 0
                "show advanced options"              = 0
                "SMO and DMO XPs"                    = 1
                "transform noise words"              = 0
                "two digit year cutoff"              = 2049
                "user connections"                   = 0
                "User Instance Timeout"              = 60
                "user instances enabled"             = 0
                "user options"                       = 0
                "xp_cmdshell"                        = 0
            }
        }
        #endregion SQL2016

        #region SQL2017
        14 {
            [pscustomobject]@{
                "access check cache bucket count"    = 0
                "access check cache quota"           = 0
                "Ad Hoc Distributed Queries"         = 0
                "affinity I/O mask"                  = 0
                "affinity mask"                      = 0
                "affinity64 I/O mask"                = 0
                "affinity64 mask"                    = 0
                "Agent XPs"                          = 0
                "allow polybase export"              = 0
                "allow updates"                      = 0
                "automatic soft-NUMA disabled"       = 0
                "backup checksum default"            = 0
                "backup compression default"         = 0
                "blocked process threshold (s)"      = 0
                "c2 audit mode"                      = 0
                "clr enabled"                        = 0
                "clr strict security"                = 1
                "common criteria compliance enabled" = 0
                "contained database authentication"  = 0
                "cost threshold for parallelism"     = 5
                "cross db ownership chaining"        = 0
                "cursor threshold"                   = -1
                "Database Mail XPs"                  = 0
                "default full-text language"         = 1033
                "default language"                   = 0
                "default trace enabled"              = 1
                "disallow results from triggers"     = 0
                "EKM provider enabled"               = 0
                "external scripts enabled"           = 0
                "filestream access level"            = 0
                "fill factor (%)"                    = 0
                "ft crawl bandwidth (max)"           = 100
                "ft crawl bandwidth (min)"           = 0
                "ft notify bandwidth (max)"          = 100
                "ft notify bandwidth (min)"          = 0
                "hadoop connectivity"                = 0
                "index create memory (KB)"           = 0
                "in-doubt xact resolution"           = 0
                "lightweight pooling"                = 0
                "locks"                              = 0
                "max degree of parallelism"          = 0
                "max full-text crawl range"          = 4
                "max server memory (MB)"             = 2147483647
                "max text repl size (B)"             = 65536
                "max worker threads"                 = 0
                "media retention"                    = 0
                "min memory per query (KB)"          = 1024
                "min server memory (MB)"             = 0
                "nested triggers"                    = 1
                "network packet size (B)"            = 4096
                "Ole Automation Procedures"          = 0
                "open objects"                       = 0
                "optimize for ad hoc workloads"      = 0
                "PH timeout (s)"                     = 60
                "polybase network encryption"        = 1
                "precompute rank"                    = 0
                "priority boost"                     = 0
                "query governor cost limit"          = 0
                "query wait (s)"                     = -1
                "recovery interval (min)"            = 0
                "remote access"                      = 1
                "remote admin connections"           = 0
                "remote data archive"                = 0
                "remote login timeout (s)"           = 10
                "remote proc trans"                  = 0
                "remote query timeout (s)"           = 600
                "Replication XPs"                    = 0
                "scan for startup procs"             = 0
                "server trigger recursion"           = 1
                "set working set size"               = 0
                "show advanced options"              = 0
                "SMO and DMO XPs"                    = 1
                "transform noise words"              = 0
                "two digit year cutoff"              = 2049
                "user connections"                   = 0
                "User Instance Timeout"              = 60
                "user instances enabled"             = 0
                "user options"                       = 0
                "xp_cmdshell"                        = 0

            }
        }
        #endregion SQL2017


    }

}
tools\dbatools\internal\functions\Get-SqlFileStructure.ps1
function Get-SqlFileStructure {
    <#
    .SYNOPSIS
    Internal function. Returns custom object that contains file structures on destination paths (\\SqlInstance\m$\mssql\etc\etc\file.mdf) for
    source and destination servers.
    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, Position = 0)]
        [ValidateNotNullOrEmpty()]
        [object]$source,
        [Parameter(Mandatory, Position = 1)]
        [ValidateNotNullOrEmpty()]
        [object]$destination,
        [Parameter(Position = 2)]
        [bool]$ReuseSourceFolderStructure,
        [PSCredential]$SourceSqlCredential,
        [PSCredential]$DestinationSqlCredential
    )

    $sourceserver = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential
    $source = $sourceserver.DomainInstanceName
    $destserver = Connect-SqlInstance -SqlInstance $Destination -SqlCredential $DestinationSqlCredential
    $destination = $destserver.DomainInstanceName

    $sourcenetbios = Resolve-NetBiosName $sourceserver
    $destnetbios = Resolve-NetBiosName $destserver

    $dbcollection = @{ };

    foreach ($db in $sourceserver.databases) {
        $dbstatus = $db.status.toString()
        if ($dbstatus.StartsWith("Normal") -eq $false) { continue }
        $destinationfiles = @{ }; $sourcefiles = @{ }

        # Data Files
        foreach ($filegroup in $db.filegroups) {
            foreach ($file in $filegroup.files) {
                # Destination File Structure
                $d = @{ }
                if ($ReuseSourceFolderStructure) {
                    $d.physical = $file.filename
                } else {
                    $directory = Get-SqlDefaultPaths $destserver data
                    $filename = Split-Path $($file.filename) -leaf
                    $d.physical = "$directory\$filename"
                }
                $d.logical = $file.name
                $d.remotefilename = Join-AdminUnc $destnetbios $d.physical
                $destinationfiles.add($file.name, $d)

                # Source File Structure
                $s = @{ }
                $s.logical = $file.name
                $s.physical = $file.filename
                $s.remotefilename = Join-AdminUnc $sourcenetbios $s.physical
                $sourcefiles.add($file.name, $s)
            }
        }

        # Add support for Full Text Catalogs in SQL Server 2005 and below
        if ($sourceserver.VersionMajor -lt 10) {
            foreach ($ftc in $db.FullTextCatalogs) {
                # Destination File Structure
                $d = @{ }
                $pre = "sysft_"
                $name = $ftc.name
                $physical = $ftc.RootPath
                $logical = "$pre$name"
                if ($ReuseSourceFolderStructure) {
                    $d.physical = $physical
                } else {
                    $directory = Get-SqlDefaultPaths $destserver data
                    if ($destserver.VersionMajor -lt 10) { $directory = "$directory\FTDATA" }
                    $filename = Split-Path($physical) -leaf
                    $d.physical = "$directory\$filename"
                }
                $d.logical = $logical
                $d.remotefilename = Join-AdminUnc $destnetbios $d.physical
                $destinationfiles.add($logical, $d)

                # Source File Structure
                $s = @{ }
                $pre = "sysft_"
                $name = $ftc.name
                $physical = $ftc.RootPath
                $logical = "$pre$name"

                $s.logical = $logical
                $s.physical = $physical
                $s.remotefilename = Join-AdminUnc $sourcenetbios $s.physical
                $sourcefiles.add($logical, $s)
            }
        }

        # Log Files
        foreach ($file in $db.logfiles) {
            $d = @{ }
            if ($ReuseSourceFolderStructure) {
                $d.physical = $file.filename
            } else {
                $directory = Get-SqlDefaultPaths $destserver log
                $filename = Split-Path $($file.filename) -leaf
                $d.physical = "$directory\$filename"
            }
            $d.logical = $file.name
            $d.remotefilename = Join-AdminUnc $destnetbios $d.physical
            $destinationfiles.add($file.name, $d)

            $s = @{ }
            $s.logical = $file.name
            $s.physical = $file.filename
            $s.remotefilename = Join-AdminUnc $sourcenetbios $s.physical
            $sourcefiles.add($file.name, $s)
        }

        $location = @{ }
        $location.add("Destination", $destinationfiles)
        $location.add("Source", $sourcefiles)
        $dbcollection.Add($($db.name), $location)
    }

    $filestructure = [pscustomobject]@{ "databases" = $dbcollection }
    return $filestructure
}
tools\dbatools\internal\functions\Get-SqlInstanceComponent.ps1
function Get-SQLInstanceComponent {
    <#
    .SYNOPSIS
        Retrieves SQL server information from a local or remote servers.
    .DESCRIPTION
        Retrieves SQL server information from a local or remote servers. Pulls all instances from a SQL server and
        detects if in a cluster or not.
    .PARAMETER ComputerName
        Local or remote systems to query for SQL information.
    .NOTES
        Tags: Install, Patching, SP, CU, Instance
        Author: Kirill Kravtsov (@nvarscar) https://nvarscar.wordpress.com/

        Based on https://github.com/adbertram/PSSqlUpdater
        The majority of this function was created by Boe Prox.
    .EXAMPLE
        Get-SQLInstanceComponent -ComputerName SQL01 -Component SSDS
        ComputerName  : BDT005-BT-SQL
        InstanceType  : Database Engine
        InstanceName  : MSSQLSERVER
        InstanceID    : MSSQL11.MSSQLSERVER
        Edition       : Enterprise Edition
        Version       : 11.1.3000.0
        Caption       : SQL Server 2012
        IsCluster     : False
        IsClusterNode : False
        ClusterName   :
        ClusterNodes  : {}
        FullName      : BDT005-BT-SQL
        Description
        -----------
        Retrieves the SQL instance information from SQL01 for component type SSDS (Database Engine).
    .EXAMPLE
        Get-SQLInstanceComponent -ComputerName SQL01
        ComputerName  : BDT005-BT-SQL
        InstanceType  : Analysis Services
        InstanceName  : MSSQLSERVER
        InstanceID    : MSAS11.MSSQLSERVER
        Edition       : Enterprise Edition
        Version       : 11.1.3000.0
        Caption       : SQL Server 2012
        IsCluster     : False
        IsClusterNode : False
        ClusterName   :
        ClusterNodes  : {}
        FullName      : BDT005-BT-SQL
        ComputerName  : BDT005-BT-SQL
        InstanceType  : Reporting Services
        InstanceName  : MSSQLSERVER
        InstanceID    : MSRS11.MSSQLSERVER
        Edition       : Enterprise Edition
        Version       : 11.1.3000.0
        Caption       : SQL Server 2012
        IsCluster     : False
        IsClusterNode : False
        ClusterName   :
        ClusterNodes  : {}
        FullName      : BDT005-BT-SQL
        Description
        -----------
        Retrieves the SQL instance information from SQL01 for all component types (SSAS, SSDS, SSRS).
    #>

    [CmdletBinding()]
    param
    (
        [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [Alias('Computer', 'DNSHostName', 'IPAddress')]
        [DbaInstanceParameter[]]$ComputerName = $Env:COMPUTERNAME,
        [ValidateSet('SSDS', 'SSAS', 'SSRS')]
        [string[]]$Component = @('SSDS', 'SSAS', 'SSRS'),
        [pscredential]$Credential,
        [bool]$EnableException = $EnableException
    )

    begin {

        $regScript = {
            Param (
                [ValidateSet('SSDS', 'SSAS', 'SSRS')]
                [string[]]$Component = @('SSDS', 'SSAS', 'SSRS')
            )
            $componentNameMap = @(
                [pscustomobject]@{
                    ComponentName = 'SSAS';
                    DisplayName   = 'Analysis Services';
                    RegKeyName    = "OLAP";
                },
                [pscustomobject]@{
                    ComponentName = 'SSDS';
                    DisplayName   = 'Database Engine';
                    RegKeyName    = 'SQL';
                },
                [pscustomobject]@{
                    ComponentName = 'SSRS';
                    DisplayName   = 'Reporting Services';
                    RegKeyName    = 'RS';
                }
            );

            function Get-SQLInstanceDetail {
                <#
                    .SYNOPSIS
                        The majority of this function was created by Boe Prox.
                #>
                param
                (
                    [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
                    [string[]]$Instance,

                    [Parameter(Mandatory)]
                    [ValidateNotNullOrEmpty()]
                    [Microsoft.Win32.RegistryKey]$RegKey,

                    [Parameter(Mandatory)]
                    [ValidateNotNullOrEmpty()]
                    [Microsoft.Win32.RegistryKey]$reg,

                    [Parameter(Mandatory)]
                    [ValidateNotNullOrEmpty()]
                    [string]$RegPath
                )
                process {
                    #region Process each instance
                    foreach ($sqlInstance in $Instance) {
                        $log = @()
                        $nodes = New-Object System.Collections.ArrayList;
                        $clusterName = $null;
                        $isCluster = $false;
                        $instanceValue = $regKey.GetValue($sqlInstance);
                        $log += "Working with $regPath\$instanceValue on $computer"
                        $instanceReg = $reg.OpenSubKey("$regPath\\$instanceValue");
                        if ($instanceReg.GetSubKeyNames() -contains 'Cluster') {
                            $isCluster = $true;
                            $instanceRegCluster = $instanceReg.OpenSubKey('Cluster');
                            $clusterName = $instanceRegCluster.GetValue('ClusterName');
                            #Write-Message -Level Verbose -Message "Getting cluster node names";
                            $clusterReg = $reg.OpenSubKey("Cluster\\Nodes");
                            $clusterNodes = $clusterReg.GetSubKeyNames();
                            if ($clusterNodes) {
                                foreach ($clusterNode in $clusterNodes) {
                                    $null = $nodes.Add($clusterReg.OpenSubKey($clusterNode).GetValue("NodeName").ToUpper());
                                }
                            }
                        }

                        #region Gather additional information about SQL instance
                        $instanceRegSetup = $instanceReg.OpenSubKey("Setup")

                        #region Get SQL instance directory
                        try {
                            $instanceDir = $instanceRegSetup.GetValue("SqlProgramDir");
                            if (([System.IO.Path]::GetPathRoot($instanceDir) -ne $instanceDir) -and $instanceDir.EndsWith("\")) {
                                $instanceDir = $instanceDir.Substring(0, $instanceDir.Length - 1);
                            }
                        } catch {
                            $instanceDir = $null;
                        }
                        #endregion Get SQL instance directory

                        #region Get SQL edition
                        try {
                            $edition = $instanceRegSetup.GetValue("Edition");
                        } catch {
                            $edition = $null;
                        }
                        #endregion Get SQL edition

                        #region Get resume value
                        try {
                            $resume = [bool][int]$instanceRegSetup.GetValue("Resume");
                        } catch {
                            $resume = $false;
                        }
                        #endregion Get resume value

                        #region Get SQL version
                        $version = $null
                        try {
                            $versionHash = @{
                                '11' = 'SQLServer2012'
                                '12' = 'SQLServer2014'
                                '13' = 'SQLServer2016'
                                '14' = 'SQL2017'
                                '15' = 'SQL2019'
                            }
                            $version = $instanceRegSetup.GetValue("Version");
                            $log += "Found version $version"
                            if ($patchVersion = $instanceRegSetup.GetValue("PatchLevel")) {
                                $log += "Using patch version $patchVersion over $version"
                                $version = $patchVersion
                            }
                            # if patch version is not available - use global reg node to extract the latest patch
                            $majorVersion = $version.Split('.')[0]
                            if (!$patchVersion -and $majorVersion -and $versionHash[$majorVersion]) {
                                $verKey = $reg.OpenSubKey("SOFTWARE\\Microsoft\\Microsoft SQL Server\\$($majorVersion)0\\$($versionHash[$majorVersion])\\CurrentVersion")
                                $version = $verKey.GetValue('Version')
                                $log += "New version from the CurrentVersion key: $version"
                            }
                        } catch {
                            $log += "Failed to read one of the reg keys, found version $version so far"
                        }
                        #endregion Get SQL version

                        #region Get exe version
                        try {
                            # attempt to recover a real version of a sqlservr.exe by getting file properties from a remote machine
                            # not sure how to support SSRS/SSAS, as SSDS is the only one that has binary path in the Setup node
                            if ($binRoot = $instanceRegSetup.GetValue("SQLBinRoot")) {
                                $fileVersion = (Get-Item -Path (Join-Path $binRoot "sqlservr.exe") -ErrorAction Stop).VersionInfo.ProductVersion
                                if ($fileVersion) {
                                    $version = $fileVersion
                                    $log += "New version from the binary file: $version"
                                }
                            }
                        } catch {
                            $log += "Failed to get exe version, leaving $version as is"
                        }
                        #endregion Get exe version

                        #endregion Gather additional information about SQL instance

                        #region Generate return object
                        [pscustomobject]@{
                            ComputerName  = $computer.ToUpper();
                            InstanceName  = $sqlInstance;
                            InstanceID    = $instanceValue;
                            InstanceDir   = $instanceDir;
                            Edition       = $edition;
                            Version       = $version;
                            Caption       = {
                                switch -regex ($version) {
                                    "^11" { "SQL Server 2012"; break }
                                    "^10\.5" { "SQL Server 2008 R2"; break }
                                    "^10" { "SQL Server 2008"; break }
                                    "^9" { "SQL Server 2005"; break }
                                    "^8" { "SQL Server 2000"; break }
                                    default { "Unknown"; }
                                }
                            }.InvokeReturnAsIs();
                            IsCluster     = $isCluster;
                            IsClusterNode = ($nodes -contains $computer);
                            ClusterName   = $clusterName;
                            ClusterNodes  = ($nodes -ne $computer);
                            FullName      = {
                                if ($sqlInstance -eq "MSSQLSERVER") {
                                    $computer.ToUpper();
                                } else {
                                    "$($computer.ToUpper())\$($sqlInstance)";
                                }
                            }.InvokeReturnAsIs();
                            Log           = $log
                            Resume        = $resume
                        }
                        #endregion Generate return object
                    }
                    #endregion Process each instance
                }
            }
            $reg = [Microsoft.Win32.RegistryKey]::OpenBaseKey('LocalMachine', 'Default')
            $baseKeys = "SOFTWARE\\Microsoft\\Microsoft SQL Server", "SOFTWARE\\Wow6432Node\\Microsoft\\Microsoft SQL Server";
            if ($reg.OpenSubKey($baseKeys[0])) {
                $regPath = $baseKeys[0];
            } elseif ($reg.OpenSubKey($baseKeys[1])) {
                $regPath = $baseKeys[1];
            } else {
                throw "Failed to find any regkeys on $env:computername"
            }

            $computer = $Env:COMPUTERNAME

            $regKey = $reg.OpenSubKey("$regPath");
            if ($regKey.GetSubKeyNames() -contains "Instance Names") {
                foreach ($componentName in $Component) {
                    $componentRegKeyName = $componentNameMap |
                        Where-Object { $_.ComponentName -eq $componentName } |
                        Select-Object -ExpandProperty RegKeyName;
                    $regKey = $reg.OpenSubKey("$regPath\\Instance Names\\{0}" -f $componentRegKeyName);
                    if ($regKey) {
                        foreach ($regValueName in $regKey.GetValueNames()) {
                            if ($componentRegKeyName -eq 'RS' -and $regValueName -eq 'PBIRS') { continue } #filtering out Power BI - not supported
                            if ($componentRegKeyName -eq 'RS' -and $regValueName -eq 'SSRS') { continue }  #filtering out SSRS2017+ - not supported
                            $result = Get-SQLInstanceDetail -RegPath $regPath -Reg $reg -RegKey $regKey -Instance $regValueName;
                            $result | Add-Member -Type NoteProperty -Name InstanceType -Value ($componentNameMap | Where-Object { $_.ComponentName -eq $componentName }).DisplayName -PassThru
                        }
                    }
                }
            } elseif ($regKey.GetValueNames() -contains 'InstalledInstances') {
                $isCluster = $false;
                $regKey.GetValue('InstalledInstances') | ForEach-Object {
                    Get-SQLInstanceDetail -RegPath $regPath -Reg $reg -RegKey $regKey -Instance $_;
                };
            } else {
                throw "Failed to find any instance names on $env:computername"
            }
        }
    }
    process {
        foreach ($computer in $ComputerName) {
            try {
                $results = Invoke-Command2 -ComputerName $computer -ScriptBlock $regScript -Credential $Credential -ErrorAction Stop -Raw -ArgumentList @($Component) -RequiredPSVersion 3.0
            } catch {
                Stop-Function -Message "Failed to get instance components from $computer" -ErrorRecord $_ -Continue
            }
            # Log is stored in the log property, pile it all into the debug log
            foreach ($logEntry in $results.Log) {
                Write-Message -Level Debug -Message $logEntry
            }
            foreach ($result in $results) {
                #Replace first decimal of the minor build with a 0, since we're using build numbers here
                #Refer to https://sqlserverbuilds.blogspot.com/
                Write-Message -Level Debug -Message "Converting version $($result.Version) to [version]"
                $newVersion = New-Object -TypeName System.Version -ArgumentList ([string]$result.Version)
                $newVersion = New-Object -TypeName System.Version -ArgumentList ($newVersion.Major , ($newVersion.Minor - $newVersion.Minor % 10), $newVersion.Build)
                Write-Message -Level Debug -Message "Converted version $($result.Version) to $newVersion"
                #Find a proper build reference and replace Version property
                $result.Version = Get-DbaBuildReference -Build $newVersion
                $result | Select-Object -ExcludeProperty Log
            }
        }
    }
}
tools\dbatools\internal\functions\Get-SqlSaLogin.ps1
function Get-SqlSaLogin {
    <#
        .SYNOPSIS
            Internal function. Gets the name of the sa login in case someone changed it.
        .PARAMETER SqlInstance
            The SQL Server instance.
        .PARAMETER SqlCredential
            Allows you to login to servers using SQL Logins instead of Windows Authentication (AKA Integrated or Trusted).
       #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [object]$SqlInstance,
        [PSCredential]$SqlCredential
    )
    $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
    $sa = $server.Logins | Where-Object Id -eq 1
    return $sa.Name
}
tools\dbatools\internal\functions\Get-SqlServerUpdate.ps1
function Get-SqlServerUpdate {
    <#
    Originally based on https://github.com/adbertram/PSSqlUpdater
    Internal function. Provides information on the target update version for a specific set of SQL Server instances based on current and target SQL Server levels.
    Component parameter is using the output object of Get-SqlInstanceComponent.
    #>
    [CmdletBinding(DefaultParameterSetName = 'Latest')]
    param
    (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [DbaInstanceParameter]$ComputerName,
        [pscredential]$Credential,
        [Parameter(Mandatory, ParameterSetName = 'Latest')]
        [ValidateSet('ServicePack', 'CumulativeUpdate')]
        [string]$Type,
        [object[]]$Component,
        [Parameter(ParameterSetName = 'Number')]
        [int]$ServicePack,
        [Parameter(ParameterSetName = 'Number')]
        [int]$CumulativeUpdate,
        [Parameter(Mandatory, ParameterSetName = 'KB')]
        [ValidateNotNullOrEmpty()]
        [string]$KB,
        [string]$InstanceName,
        [bool]$EnableException = $EnableException,
        [bool]$Continue
    )
    process {

        # check if any type of the update was specified
        if ($PSCmdlet.ParameterSetName -eq 'Number' -and -not ((Test-Bound ServicePack) -or (Test-Bound CumulativeUpdate))) {
            Stop-Function -Message "No update was specified, provide at least one value for either SP/CU"
            return
        }
        $computer = $ComputerName.ComputerName
        $verCount = ($Component | Measure-Object).Count
        $verDesc = ($Component | Foreach-Object { "$($_.Version.NameLevel) ($($_.Version.Build))" }) -join ', '
        Write-Message -Level Debug -Message "Selected $verCount existing SQL Server version(s): $verDesc"

        # Group by version
        $currentVersionGroups = $Component | Group-Object -Property { $_.Version.NameLevel }
        #Check if more than one version is found
        if (($currentVersionGroups | Measure-Object ).Count -gt 1 -and ($CumulativeUpdate -or $ServicePack) -and !$MajorVersion) {
            Stop-Function -Message "Updating multiple different versions of SQL Server to a specific SP/CU is not supported. Please specify a version of SQL Server on $computer that you want to update."
            return
        }
        ## Find the architecture of the computer
        if ($arch = (Get-DbaCmObject -ComputerName $computer -ClassName 'Win32_ComputerSystem').SystemType) {
            if ($arch -eq 'x64-based PC') {
                $arch = 'x64'
            } else {
                $arch = 'x86'
            }
        } else {
            Write-Message -Level Warning -Message "Failed to determine the arch of $computer, using x64 by default"
            $arch = 'x64'
        }
        $targetLevel = ''
        # Launch a setup sequence for each version found
        foreach ($currentGroup in $currentVersionGroups) {
            $currentMajorVersion = "SQL" + $currentGroup.Name
            $currentMajorNumber = $currentGroup.Name

            # Use the earliest version in case specifics are needed
            $currentVersion = $currentGroup.Group | Sort-Object -Property { $_.Version.BuildLevel } | Select-Object -ExpandProperty Version -First 1

            #create output object
            $output = [pscustomobject]@{
                ComputerName  = $ComputerName
                MajorVersion  = $currentMajorNumber
                Build         = $currentVersion.Build
                Architecture  = $arch
                TargetVersion = $null
                TargetLevel   = $null
                KB            = $null
                Successful    = $false
                Restarted     = $false
                InstanceName  = $InstanceName
                Installer     = $null
                ExtractPath   = $null
                Notes         = @()
                ExitCode      = $null
                Log           = $null
            }

            # Find target KB number based on provided SP/CU levels or KB numbers
            if ($CumulativeUpdate -gt 0) {
                #Cumulative update is present - installing CU
                if (Test-Bound -Parameter ServicePack) {
                    #Service pack is present - using it as a reference
                    $targetKB = Get-DbaBuildReference -MajorVersion $currentMajorNumber -ServicePack $ServicePack -CumulativeUpdate $CumulativeUpdate
                } else {
                    #Service pack not present - using current SP level
                    $targetSP = $currentVersion.SPLevel | Where-Object { $_ -ne 'LATEST' } | Select-Object -First 1
                    $targetKB = Get-DbaBuildReference -MajorVersion $currentMajorNumber -ServicePack $targetSP -CumulativeUpdate $CumulativeUpdate
                }
            } elseif ($ServicePack -gt 0) {
                #Service pack number was passed without CU - installing service pack
                $targetKB = Get-DbaBuildReference -MajorVersion $currentMajorNumber -ServicePack $ServicePack
            } elseif ($KB) {
                $targetKB = Get-DbaBuildReference -KB $KB
                if ($targetKB -and $currentMajorNumber -ne $targetKB.NameLevel) {
                    Write-Message -Level Debug -Message "$($targetKB.NameLevel) is not a target Major version $($currentMajorNumber), skipping"
                    continue
                }
            } else {
                #No parameters = latest patch. Find latest SQL Server build and corresponding SP and CU KBs
                $latestCU = Test-DbaBuild -Build $currentVersion.BuildLevel -MaxBehind '0CU'
                if (!$latestCU.Compliant) {
                    #more recent build is found, get KB number depending on what is the current upgrade $Type
                    $targetKB = Get-DbaBuildReference -Build $latestCU.BuildTarget
                    $targetSP = $targetKB.SPLevel | Where-Object { $_ -ne 'LATEST' } | Select-Object -First 1
                    if ($Type -eq 'CumulativeUpdate') {
                        if ($currentVersion.SPLevel -notcontains 'LATEST') {
                            $currentSP = $currentVersion.SPLevel | Where-Object { $_ -ne 'LATEST' } | Select-Object -First 1
                            Stop-Function -Message "Current SP version $currentMajorVersion$currentSP is not the latest available. Make sure to upgade to latest SP level before applying latest CU." -Continue
                        }
                        $targetLevel = "$($targetKB.SPLevel | Where-Object { $_ -ne 'LATEST' })$($targetKB.CULevel)"
                        Write-Message -Level Debug -Message "Found a latest Cumulative Update $targetLevel (KB$($targetKB.KBLevel))"
                    } elseif ($Type -eq 'ServicePack') {
                        $targetKB = Get-DbaBuildReference -MajorVersion $targetKB.NameLevel -ServicePack $targetSP
                        $targetLevel = $targetKB.SPLevel | Where-Object { $_ -ne 'LATEST' }
                        if ($currentVersion.SPLevel -contains 'LATEST') {
                            Write-Message -Message "No need to update $currentMajorVersion to $targetLevel - it's already on the latest SP version" -Level Verbose
                            continue
                        }
                        Write-Message -Level Debug -Message "Found a latest Service Pack $targetLevel (KB$($targetKB.KBLevel))"
                    }
                } else {
                    Write-Message -Message "$($currentVersion.Build) on computer [$($computer)] is already the latest available." -Level Verbose
                    continue
                }
            }
            if ($targetKB.KBLevel) {
                if ($targetKB.MatchType -ne 'Exact') {
                    Stop-Function -Message "Couldn't find an exact build match with specified parameters while updating $currentMajorVersion" -Continue
                }
                $output.TargetVersion = $targetKB
                $targetLevel = "$($targetKB.SPLevel | Where-Object { $_ -ne 'LATEST' })$($targetKB.CULevel)"
                $targetKBLevel = $targetKB.KBLevel | Select-Object -First 1
                Write-Message -Level Verbose -Message "Found applicable upgrade for SQL$($targetKB.NameLevel) to $targetLevel (KB$($targetKBLevel))"
                $output.KB = $targetKBLevel
            } else {
                $msg = "Could not find a KB$KB reference for $currentMajorVersion SP $ServicePack CU $CumulativeUpdate"
                $output.Notes += $msg
                $output
                Stop-Function -Message $msg -Continue
            }

            # Compare versions - whether to proceed with the installation
            $needsUpgrade = $false
            foreach ($currentComponent in $currentGroup.Group) {
                $groupVersion = $currentComponent.Version
                #target version is less than requested
                if ($groupVersion.BuildLevel -lt $targetKB.BuildLevel) {
                    $needsUpgrade = $true
                }
                #target version is the same but installation has failed last time
                elseif ($groupVersion.BuildLevel -eq $targetKB.BuildLevel -and $Continue -and $currentComponent.Resume) {
                    $needsUpgrade = $true
                }
            }
            if (!$needsUpgrade) {
                Write-Message -Message "Current $currentMajorVersion version $($currentVersion.BuildLevel) on computer [$($computer)] matches or already higher than target version $($targetKB.BuildLevel)" -Level Verbose
                continue
            }

            $output.TargetLevel = $targetLevel
            $output.Successful = $true
            #Return the object for further processing
            $output
        }
    }
}
tools\dbatools\internal\functions\Get-TableNameParts.ps1
function Get-TableNameParts {
    <#
    .SYNOPSIS
        Parse a one, two, or three part table name into seperate paths

    .DESCRIPTION
    Generates a hash string based on the plaintext or securestring password and a SQL Server version. Salt is optional

    .PARAMETER Table
        The table name to parse. You can specify a one, two, or three part table name.
        If the object has special characters they must be wrapped in square brackets [ ].
        If the name contains character ']' this must be escaped by duplicating the character

    .NOTES
        Tags: Table, Internal
        Author: Patrick Flynn (@sqllensman)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        Get-TableNameParts 'table'

        Parses a three-part name into its constitute parts.

    .EXAMPLE
        Get-TableNameParts '[Bad. Name]]].[Schema.With.Dots]]].[Another .Silly]] Name..]'

        Parses a three-part name into its constitute parts. Uses square brackets to enclose special characters.
    #>
    param (
        [string]$Table
    )
    process {
        $fqtns = @()
        #Tables with a ']' charcter in name need to be handeled
        #Require charcter to be escaped by being duplicated as per T-SQL QuoteName function
        #These need to be temporarily replaced to allow name to be parsed.
        $t = $Table
        if ($t.Contains(']]')) {
            for ($i = 0; $i -le 65535; $i++) {
                $hexStr = '{0:X4}' -f $i
                $char = [regex]::Unescape("\u$($HexStr)")
                if (!$Table.Contains($Char)) {
                    $fixChar = $Char
                    $t = $t.Replace(']]', $fixChar)
                    Break
                }
            }
        } else {
            $fixChar = $null
        }
        $splitName = [regex]::Matches($t, "(\[.+?\])|([^\.]+)").Value
        $dotcount = $splitName.Count

        $splitDb = $Schema = $tbl = $null

        switch ($dotcount) {
            1 {
                $tbl = $t
                $parsed = $true
            }
            2 {
                $schema = $splitName[0]
                $tbl = $splitName[1]
                $parsed = $true
            }
            3 {
                $splitDb = $splitName[0]
                $schema = $splitName[1]
                $tbl = $splitName[2]
                $parsed = $true
            }
            default {
                $parsed = $false
            }
        }
        if ($splitDb -like "[[]*[]]") {
            $splitDb = $splitDb.Substring(1, ($splitDb.Length - 2))
            if ($fixChar) {
                $splitDb = $splitDb.Replace($fixChar, ']')
            }
        }

        if ($schema -like "[[]*[]]") {
            $schema = $schema.Substring(1, ($schema.Length - 2))
            if ($fixChar) {
                $schema = $schema.Replace($fixChar, ']')
            }
        }

        if ($tbl -like "[[]*[]]") {
            $tbl = $tbl.Substring(1, ($tbl.Length - 2))
            if ($fixChar) {
                $tbl = $tbl.Replace($fixChar, ']')
            }
        }
        $fqtns = [PSCustomObject] @{
            InputValue = $Table
            Database   = $splitDb
            Schema     = $Schema
            Table      = $tbl
            Parsed     = $parsed
        }
        return $fqtns
    }
}
tools\dbatools\internal\functions\Get-WmiHadr.ps1
function Get-WmiHadr {
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$Credential,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {
        foreach ($instance in $SqlInstance) {

            try {
                $computer = $computerName = $instance.ComputerName
                $instanceName = $instance.InstanceName
                $currentState = Invoke-ManagedComputerCommand -ComputerName $computerName -ScriptBlock { $wmi.Services[$args[0]] | Select-Object IsHadrEnabled } -ArgumentList $instanceName -Credential $Credential
            } catch {
                Stop-Function -Message "Failure connecting to $computer" -Category ConnectionError -ErrorRecord $_ -Target $instance
                return
            }

            if ($null -eq $currentState.IsHadrEnabled) {
                $isenabled = $false
            } else {
                $isenabled = $currentState.IsHadrEnabled
            }
            [PSCustomObject]@{
                ComputerName  = $computer
                InstanceName  = $instanceName
                SqlInstance   = $instance.FullName
                IsHadrEnabled = $isenabled
            }
        }
    }
}
tools\dbatools\internal\functions\Get-XpDirTreeRestoreFile.ps1
function Get-XpDirTreeRestoreFile {
    <#
    .SYNOPSIS
        Internal Function to get SQL Server backfiles from a specified folder using xp_dirtree

    .DESCRIPTION
        Takes path, checks for validity. Scans for usual backup file

    .PARAMETER Path
        The path to retrieve the restore for.

    .PARAMETER SqlInstance
        The SQL Server that you're connecting to.

    .PARAMETER SqlCredential
        Credential object used to connect to the SQL Server as a different user

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .EXAMPLE
        PS C:\> Get-XpDirTreeRestoreFile -Path '\\foo\bar\' -SqlInstance $SqlInstance

        Tests whether the instance $SqlInstance has access to the path \\foo\bar\
    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [string]$Path,
        [parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [System.Management.Automation.PSCredential]$SqlCredential,
        [Alias('Silent')]
        [switch]$EnableException,
        [switch]$NoRecurse
    )

    Write-Message -Level InternalComment -Message "Starting"

    $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
    $pathSep = Get-DbaPathSep -Server $server
    if (($path -like '*.bak') -or ($path -like '*.trn')) {
        # For a future person who knows what's up, please replace this comment with the reason this is empty
    } elseif ($Path[-1] -ne $pathSep) {
        $Path = $Path + $pathSep
    }

    if (!(Test-DbaPath -SqlInstance $server -path $path)) {
        Stop-Function -Message "SqlInstance $SqlInstance cannot access $path"
    }
    if (!(Test-DbaPath -SqlInstance $server -path $Path)) {
        Stop-Function -Message "SqlInstance $SqlInstance cannot access $Path"
    }
    if ($server.VersionMajor -ge 14) {
        # this is all kinds of cool, api could be expanded sooo much here
        $sql = "SELECT file_or_directory_name AS subdirectory, ~CONVERT(BIT, is_directory) as [file], 1 as depth
        FROM sys.dm_os_enumerate_filesystem('$Path', '*')
        WHERE  [level] = 0"
    } elseif ($server.VersionMajor -lt 9) {
        $sql = "EXEC master..xp_dirtree '$Path',1,1;"
    } else {
        $sql = "EXEC master.sys.xp_dirtree '$Path',1,1;"
    }
    #$queryResult = Invoke-DbaQuery -SqlInstance $SqlInstance -Credential $SqlCredential -Database tempdb -Query $query
    $queryResult = $server.Query($sql)
    Write-Message -Level Debug -Message $sql
    $dirs = $queryResult | Where-Object file -eq 0
    $Results = @()
    $Results += $queryResult | Where-Object file -eq 1 | Select-Object @{ Name = "FullName"; Expression = { $path + $_.subdirectory } }

    if ($True -ne $NoRecurse) {
        foreach ($d in $dirs) {
            $fullpath = $path + $d.subdirectory
            Write-Message -Level Verbose -Message "Enumerating subdirectory '$fullpath'"
            $Results += Get-XpDirTreeRestoreFile -Path $fullpath -SqlInstance $server
        }
    }
    return $Results
}
tools\dbatools\internal\functions\Import-DbaCmdlet.ps1
function Import-DbaCmdlet {
    <#
    .SYNOPSIS
        Loads a cmdlet into the current context.

    .DESCRIPTION
        Loads a cmdlet into the current context.
        This can be used to register a cmdlet during module import, making it easy to have hybrid modules publishing both cmdlets and functions.
        Can also be used to register cmdlets written in PowerShell classes.

    .PARAMETER Name
        The name of the cmdlet to register.

    .PARAMETER Type
        The type of the class implementing the cmdlet.

    .PARAMETER HelpFile
        Path to the help XML containing the help for the cmdlet.

    .PARAMETER Module
        Module to inject the cmdlet into.

    .EXAMPLE
        PS C:\> Import-DbaCmdlet -Name Get-Something -Type ([GetSomethingCommand])

        Imports the Get-Something cmdlet into the current context.

    .EXAMPLE
        PS C:\> Import-DbaCmdlet -Name Get-Something -Type ([GetSomethingCommand]) -Module (Get-Module PSReadline)

        Imports the Get-Something cmdlet into the PSReadline module.

    .NOTES
        Original Author: Chris Dent
        Link: https://www.indented.co.uk/cmdlets-without-a-dll/
    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [String]
        $Name,

        [Parameter(Mandatory)]
        [Type]
        $Type,

        [string]
        $HelpFile,

        [System.Management.Automation.PSModuleInfo]
        $Module
    )

    begin {
        $scriptBlock = {
            param (
                [String]
                $Name,

                [Type]
                $Type,

                [string]
                $HelpFile
            )

            $sessionStateCmdletEntry = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry(
                $Name,
                $Type,
                $HelpFile
            )

            # System.Management.Automation.Runspaces.LocalPipeline will let us get at ExecutionContext.
            # Note: $ExecutionContext is *not* an instance of this object.
            $pipelineType = [PowerShell].Assembly.GetType('System.Management.Automation.Runspaces.LocalPipeline')
            $method = $pipelineType.GetMethod(
                'GetExecutionContextFromTLS',
                [System.Reflection.BindingFlags]'Static,NonPublic'
            )

            # Invoke the method to get an instance of ExecutionContext.
            $context = $method.Invoke(
                $null,
                [System.Reflection.BindingFlags]'Static,NonPublic',
                $null,
                $null,
                (Get-Culture)
            )

            # Get the SessionStateInternal type
            $internalType = [PowerShell].Assembly.GetType('System.Management.Automation.SessionStateInternal')

            # Get a valid constructor which accepts a param of type ExecutionContext
            $constructor = $internalType.GetConstructor(
                [System.Reflection.BindingFlags]'Instance,NonPublic',
                $null,
                $context.GetType(),
                $null
            )

            # Get the SessionStateInternal for this execution context
            $sessionStateInternal = $constructor.Invoke($context)

            # Get the method which allows Cmdlets to be added to the session
            $method = $internalType.GetMethod(
                'AddSessionStateEntry',
                [System.Reflection.BindingFlags]'Instance,NonPublic',
                $null,
                $sessionStateCmdletEntry.GetType(),
                $null
            )
            # Invoke the method.
            $method.Invoke($sessionStateInternal, $sessionStateCmdletEntry)
        }
    }

    process {
        if (-not $Module) { $scriptBlock.Invoke($Name, $Type, $HelpFile) }
        else { $Module.Invoke($scriptBlock, @($Name, $Type, $HelpFile)) }
    }
}
tools\dbatools\internal\functions\Initialize-CredSSP.ps1
function Initialize-CredSSP {
    <#
    .SYNOPSIS
        Configure local and remote computers to use Credssp protocol

    .DESCRIPTION
        Enables both local and remote machine to participate in a Credssp session.
        Local computer will be told to trust the Delegate (remote) computer.
        Remote computer will be configured to act as a server and accept client connections from local computer.

    .PARAMETER ComputerName
        Remote computer name

    .PARAMETER Credential
        PSCredential object used for authentication

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .EXAMPLE
        PS C:\> Initialize-CredSSP MyRemoteComputer
        # Configure CredSSP protocol to connect to remote computer MyRemoteComputer
    .EXAMPLE
        PS C:\> $cred = Get-Credential
        PS C:\> Initialize-CredSSP -ComputerName PC2 -Credential $cred
        # Configure CredSSP protocol to connect to remote computer with custom credentials
#>

    Param (
        [Parameter(Mandatory, Position = 1)]
        [string]$ComputerName,
        [pscredential]$Credential,
        [bool]$EnableException
    )

    #Configure local machine
    #Start local WinRM service
    if ((Get-Service WinRM).Status -ne 'Running') {
        $null = Get-Service WinRM -ErrorAction Stop | Start-Service -ErrorAction Stop
        Start-Sleep -Seconds 1
    }
    #Get current config
    try {
        $sspList = Get-WSManCredSSP -ErrorAction Stop

    } catch {
        Stop-Function -Message "Failed to get a list of CredSSP hosts" -ErrorRecord $_
        return
    }
    #Enable delegation to a remote server if not declared already
    if ($sspList -and $sspList[0] -notmatch "wsman\/$([regex]::Escape($ComputerName))[\,$]") {
        Write-Message -Level Verbose -Message "Configuring local host to use CredSSP"
        try {
            # Enable client SSP on local machine
            $null = Enable-WSManCredSSP -role Client -DelegateComputer $ComputerName -Force -ErrorAction Stop
        } catch {
            Stop-Function -Message "Failed to configure local CredSSP as a client" -ErrorRecord $_
        }
    }

    # Configure remote machine
    Write-Message -Level Verbose -Message "Configuring remote host to use CredSSP"
    try {
        Invoke-Command2 -ComputerName $ComputerName -Credential $Credential -Raw -RequiredPSVersion 3.0 -ScriptBlock {
            $sspList = Get-WSManCredSSP -ErrorAction Stop
            if ($sspList[1] -ne 'This computer is configured to receive credentials from a remote client computer.') {
                $null = Enable-WSManCredSSP -Role Server -Force -ErrorAction Stop
            }
        }
    } catch {
        Stop-Function -Message "Failed to configure remote CredSSP on $ComputerName as a server" -ErrorRecord $_
    }
}
tools\dbatools\internal\functions\Invoke-Alter.ps1
function Invoke-Alter {
    <#
        For stubborn .net objects that won't throw properly
       #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [object]$Object
    )
    process {
        if ($Pscmdlet.ShouldProcess($Name, "Performing create")) {
            $ErrorActionPreference = 'Stop'
            $EnableException = $true
            $Object.Alter()
        }
    }
}
tools\dbatools\internal\functions\Invoke-Command2.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Invoke-Command2 {
    <#
        .SYNOPSIS
            Wrapper function that calls Invoke-Command and gracefully handles credentials.

        .DESCRIPTION
            Wrapper function that calls Invoke-Command and gracefully handles credentials.

        .PARAMETER ComputerName
            Default: $env:COMPUTERNAME
            The computer to invoke the scriptblock on.

        .PARAMETER Credential
            The credentials to use.
            Can accept $null on older PowerShell versions, since it expects type object, not PSCredential

        .PARAMETER ScriptBlock
            The code to run on the targeted system

        .PARAMETER InputObject
            Object that could be used in the ScriptBlock as $Input.
            NOTE:
            The object will be de-serialized once passed through the remote pipeline.
            Some objects (like hashtables) do not support de-serialization.

        .PARAMETER Authentication
            Choose an authentication to use for the connection

        .PARAMETER ConfigurationName
            Name of the remote PSSessionConfiguration to use.
            Should be registered already using Register-PSSessionConfiguration or internal Register-RemoteSessionConfiguration.

        .PARAMETER ArgumentList
            Any arguments to pass to the scriptblock being run

        .PARAMETER Raw
            Passes through the raw return data, rather than prettifying stuff.

        .PARAMETER RequiredPSVersion
            Verifies that remote Powershell version is meeting specified requirements.

        .EXAMPLE
            PS C:\> Invoke-Command2 -ComputerName sql2014 -Credential $Credential -ScriptBlock { dir }

            Executes the scriptblock '{ dir }' on the computer sql2014 using the credentials stored in $Credential.
            If $Credential is null, no harm done.
    #>
    [CmdletBinding()]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUsePSCredentialType", "")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")]
    param (
        [DbaInstanceParameter]$ComputerName = $env:COMPUTERNAME,
        [object]$Credential,
        [scriptblock]$ScriptBlock,
        [object[]]$ArgumentList,
        [parameter(ValueFromPipeline)]
        [object[]]$InputObject,
        [ValidateSet('Default', 'Basic', 'Negotiate', 'NegotiateWithImplicitCredential', 'Credssp', 'Digest', 'Kerberos')]
        [string]$Authentication = 'Default',
        [string]$ConfigurationName,
        [switch]$Raw,
        [version]$RequiredPSVersion
    )
    <# Note: Credential stays as an object type for legacy reasons. #>

    $InvokeCommandSplat = @{}
    if ($ArgumentList) {
        $InvokeCommandSplat["ArgumentList"] = $ArgumentList
    }
    if ($InputObject) {
        $InvokeCommandSplat["InputObject"] = $InputObject
    }
    if (-not $ComputerName.IsLocalHost) {
        $runspaceId = [System.Management.Automation.Runspaces.Runspace]::DefaultRunspace.InstanceId
        # sessions with different Authentication should have different session names
        if ($ConfigurationName) {
            $sessionName = "dbatools_$($Authentication)_$($ConfigurationName)_$runspaceId"
        } else {
            $sessionName = "dbatools_$($Authentication)_$runspaceId"
        }

        # Retrieve a session from the session cache, if available (it's unique per runspace)
        $currentSession = [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::PSSessionGet($runspaceId, $ComputerName.ComputerName) | Where-Object { $_.State -Match "Opened|Disconnected" -and $_.Name -eq $sessionName }
        if (-not $currentSession) {
            Write-Message -Level Debug "Creating new $Authentication session [$sessionName] for $($ComputerName.ComputerName)"
            $psSessionSplat = @{
                ComputerName   = $ComputerName.ComputerName
                Authentication = $Authentication
                Name           = $sessionName
                ErrorAction    = 'Stop'
            }
            if (Test-Windows -NoWarn) {
                $timeout = New-PSSessionOption -IdleTimeout (New-TimeSpan -Minutes 10).TotalMilliSeconds
                $psSessionSplat += @{ SessionOption = $timeout }
            }
            if ($Credential) {
                $psSessionSplat += @{ Credential = $Credential }
            }
            if ($ConfigurationName) {
                $psSessionSplat += @{ ConfigurationName = $ConfigurationName }
            }
            $currentSession = New-PSSession @psSessionSplat
            $InvokeCommandSplat["Session"] = $currentSession
        } else {
            Write-Message -Level Debug "Found an existing session $sessionName, reusing it"
            if ($currentSession.State -eq "Disconnected") {
                $null = $currentSession | Connect-PSSession -ErrorAction Stop
            }
            $InvokeCommandSplat["Session"] = $currentSession

            # Refresh the session registration if registered, to reset countdown until purge
            [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::PSSessionSet($runspaceId, $ComputerName.ComputerName, $currentSession)
        }
    }
    if ($RequiredPSVersion) {
        $remoteVersion = Invoke-Command @InvokeCommandSplat -ScriptBlock { $PSVersionTable }
        if ($remoteVersion.PSVersion -and $remoteVersion.PSVersion -lt $RequiredPSVersion) {
            throw "Remote PS version $($remoteVersion.PSVersion) is less than defined requirement ($RequiredPSVersion)"
        }
    }

    $InvokeCommandSplat.ScriptBlock = $ScriptBlock
    if ($Raw) {
        Invoke-Command @InvokeCommandSplat
    } else {
        Invoke-Command @InvokeCommandSplat | Select-Object -Property * -ExcludeProperty PSComputerName, RunspaceId, PSShowComputerName
    }

    if (-not $ComputerName.IsLocalhost) {
        # Tell the system to clean up if the session expires
        [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::PSSessionSet($runspaceId, $ComputerName.ComputerName, $currentSession)

        if (-not (Get-DbatoolsConfigValue -FullName 'PSRemoting.Sessions.Enable' -Fallback $true)) {
            $currentSession | Remove-PSSession
        }
    }
}
tools\dbatools\internal\functions\Invoke-CommandWithFallback.ps1
function Invoke-CommandWithFallback {
    <#
    When credentials are specified, it is possible that the chosen protocol would fail to connect with them.
    Fallback will use PSSessionConfiguration to create a session configuration on a remote machine that uses
    provided set of credentials by default. A new session will be created that uses this custom configuration
    and performs remote execution under defined set of credentials without relying on delegation or CredSSP.
    #>
    param (
        [DbaInstanceParameter]$ComputerName = $env:COMPUTERNAME,
        [object]$Credential,
        [scriptblock]$ScriptBlock,
        [object[]]$ArgumentList,
        [parameter(ValueFromPipeline)]
        [object[]]$InputObject,
        [ValidateSet('Default', 'Basic', 'Negotiate', 'NegotiateWithImplicitCredential', 'Credssp', 'Digest', 'Kerberos')]
        [string]$Authentication = 'Default',
        [switch]$Raw,
        [version]$RequiredPSVersion
    )
    try {
        Invoke-Command2 @PSBoundParameters
    } catch [System.Management.Automation.Remoting.PSRemotingTransportException] {
        # This implements a fallback scenario, when both credentials and fallback are specified, but the original session has failed
        # Credentials will be passed on through a default session and used as a default PSSessionConfiguration
        if ($Credential) {
            Write-Message -Level Verbose -Message "Initial connection to $($ComputerName.ComputerName) through $Authentication protocol unsuccessful, falling back to PSSession configurations | $($_.Exception.Message)"
            $configuration = Register-RemoteSessionConfiguration -Computer $ComputerName.ComputerName -Credential $Credential -Name dbatoolsInvokeCommandWithFailback -Confirm:$false
            if ($configuration.Successful) {
                $PSBoundParameters.ConfigurationName = $configuration.Name
                $PSBoundParameters.Authentication = 'Default'
                try {
                    Invoke-Command2 @PSBoundParameters
                } catch {
                    throw $_
                } finally {
                    # Unregister PSRemote configurations once completed. It's slow, but necessary - otherwise we're gonna have leftover junk with credentials on a remote
                    $unreg = Unregister-RemoteSessionConfiguration -ComputerName $ComputerName.ComputerName -Credential $Credential -Name $configuration.Name -Confirm:$false
                    if (-not $unreg.Successful) {
                        Write-Warning -Message "Failed to unregister PSSession Configurations on $($ComputerName.ComputerName) | $($configuration.Status)"
                    }
                }
            } else {
                Stop-Function -Message "Both $Authentication and failback connections failed | $($configuration.Status)" -ErrorRecord $_ -EnableException $true
            }
        } else {
            #default behavior
            throw $_
        }
    } catch {
        throw $_
    }
}
tools\dbatools\internal\functions\Invoke-Create.ps1
function Invoke-Create {
    <#
        For stubborn .net objects that won't throw properly
       #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [object]$Object
    )
    process {
        if ($Object.Name) {
            $Name = $Object.Name
        } else {
            $Name = "target object"
        }
        if ($Pscmdlet.ShouldProcess($Name, "Performing create")) {
            $ErrorActionPreference = 'Stop'
            $EnableException = $true
            $Object.Create()
        }
    }
}
tools\dbatools\internal\functions\Invoke-DbaAsync.ps1
function Invoke-DbaAsync {
    <#
        .SYNOPSIS
            Runs a T-SQL script.

        .DESCRIPTION
            Runs a T-SQL script. It's a stripped down version of https://github.com/sqlcollaborative/Invoke-SqlCmd2 and adapted to use dbatools' facilities.
            If you're looking for a public usable function, see Invoke-DbaQuery

        .PARAMETER SQLConnection
            Specifies an existing SQLConnection object to use in connecting to SQL Server.

        .PARAMETER Query
            Specifies one or more queries to be run. The queries can be Transact-SQL, XQuery statements, or sqlcmd commands. Multiple queries in a single batch may be separated by a semicolon.

            Do not specify the sqlcmd GO separator (or, use the ParseGo parameter). Escape any double quotation marks included in the string.

            Consider using bracketed identifiers such as [MyTable] instead of quoted identifiers such as "MyTable".

        .PARAMETER QueryTimeout
            Specifies the number of seconds before the queries time out.

        .PARAMETER As
            Specifies output type. Valid options for this parameter are 'DataSet', 'DataTable', 'DataRow', 'PSObject', and 'SingleValue'

            PSObject output introduces overhead but adds flexibility for working with results: http://powershell.org/wp/forums/topic/dealing-with-dbnull/

        .PARAMETER SqlParameters
            Specifies a hashtable of parameters for parameterized SQL queries.  http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/

            Example:

        .PARAMETER AppendServerInstance
            If this switch is enabled, the SQL Server instance will be appended to PSObject and DataRow output.


        .PARAMETER MessagesToOutput
            Use this switch to have on the output stream messages too (e.g. PRINT statements). Output will hold the resultset too. See examples for detail

        .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
       #>

    param (
        [Alias('Connection', 'Conn')]
        [ValidateNotNullOrEmpty()]
        [Microsoft.SqlServer.Management.Common.ServerConnection]$SQLConnection,

        [Parameter(Mandatory, Position = 0, ParameterSetName = "Query")]
        [string]
        $Query,

        [ValidateSet("DataSet", "DataTable", "DataRow", "PSObject", "SingleValue")]
        [string]
        $As = "DataRow",

        [System.Collections.IDictionary]
        $SqlParameters,

        [switch]
        $AppendServerInstance,

        [Int32]$QueryTimeout = 600,

        [switch]
        $MessagesToOutput,

        [switch]
        $EnableException
    )

    begin {
        function Resolve-SqlError {
            param($Err)
            if ($Err) {
                if ($Err.Exception.GetType().Name -eq 'SqlException') {
                    # For SQL exception
                    #$Err = $_
                    Write-Message -Level Debug -Message "Capture SQL Error"
                    if ($PSBoundParameters.Verbose) {
                        Write-Message -Level Verbose -Message "SQL Error:  $Err"
                    } #Shiyang, add the verbose output of exception
                    switch ($ErrorActionPreference.ToString()) {
                        { 'SilentlyContinue', 'Ignore' -contains $_ } {   }
                        'Stop' { throw $Err }
                        'Continue' { throw $Err }
                        Default { Throw $Err }
                    }
                } else {
                    # For other exception
                    Write-Message -Level Debug -Message "Capture Other Error"
                    if ($PSBoundParameters.Verbose) {
                        Write-Message -Level Verbose -Message "Other Error:  $Err"
                    }
                    switch ($ErrorActionPreference.ToString()) {
                        { 'SilentlyContinue', 'Ignore' -contains $_ } { }
                        'Stop' { throw $Err }
                        'Continue' { throw $Err }
                        Default { throw $Err }
                    }
                }
            }

        }

        if ($As -eq "PSObject") {
            #This code scrubs DBNulls.  Props to Dave Wyatt
            $cSharp = @'
                using System;
                using System.Data;
                using System.Management.Automation;

                public class DBNullScrubber
                {
                    public static PSObject DataRowToPSObject(DataRow row)
                    {
                        PSObject psObject = new PSObject();

                        if (row != null && (row.RowState & DataRowState.Detached) != DataRowState.Detached)
                        {
                            foreach (DataColumn column in row.Table.Columns)
                            {
                                Object value = null;
                                if (!row.IsNull(column))
                                {
                                    value = row[column];
                                }

                                psObject.Properties.Add(new PSNoteProperty(column.ColumnName, value));
                            }
                        }

                        return psObject;
                    }
                }
'@

            try {
                Add-Type -TypeDefinition $cSharp -ReferencedAssemblies 'System.Data', 'System.Xml' -ErrorAction stop
            } catch {
                if (-not $_.ToString() -like "*The type name 'DBNullScrubber' already exists*") {
                    Write-Warning "Could not load DBNullScrubber.  Defaulting to DataRow output: $_."
                    $As = "Datarow"
                }
            }
        }

        $GoSplitterRegex = [regex]'(?smi)^[\s]*GO[\s]*$'

    }
    process {
        $Conn = $SQLConnection.SqlConnectionObject


        Write-Message -Level Debug -Message "Stripping GOs from source"
        $Pieces = $GoSplitterRegex.Split($Query)

        # Only execute non-empty statements
        $Pieces = $Pieces | Where-Object { $_.Trim().Length -gt 0 }
        foreach ($piece in $Pieces) {
            $cmd = New-Object system.Data.SqlClient.SqlCommand($piece, $conn)
            $cmd.CommandTimeout = $QueryTimeout

            if ($null -ne $SqlParameters) {
                $SqlParameters.GetEnumerator() |
                    ForEach-Object {
                    if ($null -ne $_.Value) {
                        $cmd.Parameters.AddWithValue($_.Key, $_.Value)
                    } else {
                        $cmd.Parameters.AddWithValue($_.Key, [DBNull]::Value)
                    }
                } > $null
            }

            $ds = New-Object system.Data.DataSet
            $da = New-Object system.Data.SqlClient.SqlDataAdapter($cmd)

            if ($MessagesToOutput) {
                $defaultrunspace = [System.Management.Automation.Runspaces.Runspace]::DefaultRunspace
                $pool = [RunspaceFactory]::CreateRunspacePool(1, [int]$env:NUMBER_OF_PROCESSORS + 1)
                $pool.ApartmentState = "MTA"
                $pool.Open()
                $runspaces = @()
                $scriptblock = {
                    param ($da, $ds, $conn, $queue )
                    $conn.FireInfoMessageEventOnUserErrors = $false
                    $handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] { $queue.Enqueue($_) }
                    $conn.add_InfoMessage($handler)
                    $Err = $null
                    try {
                        [void]$da.fill($ds)
                    } catch {
                        $Err = $_
                    } finally {
                        $conn.remove_InfoMessage($handler)
                    }
                    return $Err
                }
                $queue = New-Object System.Collections.Concurrent.ConcurrentQueue[string]
                $runspace = [PowerShell]::Create()
                $null = $runspace.AddScript($scriptblock)
                $null = $runspace.AddArgument($da)
                $null = $runspace.AddArgument($ds)
                $null = $runspace.AddArgument($Conn)
                $null = $runspace.AddArgument($queue)
                $runspace.RunspacePool = $pool
                $runspaces += [PSCustomObject]@{ Pipe = $runspace; Status = $runspace.BeginInvoke() }
                # While streaming ...
                while ($runspaces.Status.IsCompleted -notcontains $true) {
                    $item = $null
                    if ($queue.TryDequeue([ref]$item)) {
                        "$item"
                    }
                }
                # Drain the stream as the runspace is closed, just to be safe
                if ($queue.IsEmpty -ne $true) {
                    $item = $null
                    while ($queue.TryDequeue([ref]$item)) {
                        "$item"
                    }
                }
                foreach ($runspace in $runspaces) {
                    $results = $runspace.Pipe.EndInvoke($runspace.Status)
                    $runspace.Pipe.Dispose()
                    if ($null -ne $results) {
                        Resolve-SqlError $results[0]
                    }
                }
                $pool.Close()
                $pool.Dispose()
                [System.Management.Automation.Runspaces.Runspace]::DefaultRunspace = $defaultrunspace
            } else {
                #Following EventHandler is used for PRINT and RAISERROR T-SQL statements. Executed when -Verbose parameter specified by caller and no -MessageToOutput
                if ($PSBoundParameters.Verbose) {
                    $conn.FireInfoMessageEventOnUserErrors = $false
                    $handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] { Write-Verbose -Message "$($_)" }
                    $conn.add_InfoMessage($handler)
                }
                try {
                    [void]$da.fill($ds)
                } catch {
                    $Err = $_
                } finally {
                    if ($PSBoundParameters.Verbose) {
                        $conn.remove_InfoMessage($handler)
                    }
                }
                Resolve-SqlError $Err
            }
            if ($AppendServerInstance) {
                #Basics from Chad Miller
                $Column = New-Object Data.DataColumn
                $Column.ColumnName = "ServerInstance"

                if ($ds.Tables.Count -ne 0) {
                    $ds.Tables[0].Columns.Add($Column)
                    Foreach ($row in $ds.Tables[0]) {
                        $row.ServerInstance = $SQLConnection.ServerInstance
                    }
                }
            }

            switch ($As) {
                'DataSet' {
                    $ds
                }
                'DataTable' {
                    $ds.Tables
                }
                'DataRow' {
                    if ($ds.Tables.Count -ne 0) {
                        $ds.Tables[0]
                    }
                }
                'PSObject' {
                    if ($ds.Tables.Count -ne 0) {
                        #Scrub DBNulls - Provides convenient results you can use comparisons with
                        #Introduces overhead (e.g. ~2000 rows w/ ~80 columns went from .15 Seconds to .65 Seconds - depending on your data could be much more!)
                        foreach ($row in $ds.Tables[0].Rows) {
                            [DBNullScrubber]::DataRowToPSObject($row)
                        }
                    }
                }
                'SingleValue' {
                    if ($ds.Tables.Count -ne 0) {
                        $ds.Tables[0] | Select-Object -ExpandProperty $ds.Tables[0].Columns[0].ColumnName
                    }
                }
            }
        } #foreach ($piece in $Pieces)

    }
}
tools\dbatools\internal\functions\Invoke-DbaDatabaseCorruption.ps1
function Invoke-DbaDbCorruption {
    <#
      .SYNOPSIS
      Utilizes the DBCC WRITEPAGE functionality  to corrupt a specific database table for testing.  In no uncertain terms, this is a non-production command.
      This will absolutely break your databases and that is its only purpose.
      Using DBCC WritePage will definitely void any support options for your database.

      .DESCRIPTION
      This command can be used to verify your tests for corruption are successful, and to demo various scenarios for corrupting page data.
      This command will take an instance and database (and optionally a table) and set the database to single user mode, corrupt either the specified table or the first table it finds, and returns it to multi-user.

      .PARAMETER SqlInstance
      The SQL Server instance holding the databases to be removed.You must have sysadmin access and Server version must be SQL Server version 2000 or higher.

      .PARAMETER SqlCredential
      Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

      .PARAMETER Database
      The single database you would like to corrupt, this command does not support multiple databases (on purpose.)

      .PARAMETER Table
      The specific table you want corrupted, if you do not choose one, the first user table (alphabetically) will be chosen for corruption.

      .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.

      .PARAMETER Confirm
      If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

      .PARAMETER EnableException
      By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
      This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
      Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

      .NOTES
      Tags: Corruption, Testing
      Author: Constantine Kokkinos (@mobileck https://constantinekokkinos.com)
      Reference: https://www.sqlskills.com/blogs/paul/dbcc-writepage/
      Website: https://dbatools.io
      Copyright: (c) 2018 by dbatools, licensed under MIT
      License: MIT https://opensource.org/licenses/MIT

      .LINK
      https://dbatools.io/Invoke-DbaDbCorruption

      .EXAMPLE
      Invoke-DbaDbCorruption -SqlInstance sql2016 -Database containeddb
      Prompts for confirmation then selects the first table in database containeddb and corrupts it (by putting database into single user mode, writing to garbage to its first non-iam page, and returning it to multi-user.)

      .EXAMPLE
      Invoke-DbaDbCorruption -SqlInstance sql2016 -Database containeddb -Table Customers -Confirm:$false
      Does not prompt and immediately corrupts table customers in database containeddb on the sql2016 instance (by putting database into single user mode, writing to garbage to its first non-iam page, and returning it to multi-user.)
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]
        $SqlCredential,
        [parameter(Mandatory)]
        [string]$Database,
        [string]$Table,
        [Alias('Silent')]
        [switch]$EnableException
    )
    # For later if we want to do bit flipping.
    # function Dbcc-ReadPage {
    #   param (
    #     $SqlInstance,
    #     $Database,
    #     $TableName,
    #     $IndexID = 1
    #   )
    #   $DbccPage = "DBCC PAGE (N'$Database',N'$($TableName)',$IndexID)"
    #   Write-Message -Level Verbose -Message "$DbccPage"
    #   $pages = $SqlInstance.Query($DbccPage) | Where-Object { $_.IAMFID -ne [DBNull]::Value }
    #   return $Pages
    # }

    function Dbcc-Index {
        [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseApprovedVerbs", "")]
        [CmdletBinding()]
        param (
            $SqlInstance,
            $Database,
            $TableName,
            $IndexID = 1
        )
        $DbccInd = "DBCC IND (N'$Database',N'$($TableName)',$IndexID)"
        Write-Message -Level Verbose -Message "$DbccInd"
        $pages = $SqlInstance.Query($DbccInd) | Where-Object { $_.IAMFID -ne [DBNull]::Value }
        return $Pages
    }
    function Dbcc-WritePage {
        [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseApprovedVerbs", "")]
        [CmdletBinding()]
        param (
            $SqlInstance,
            $Database,
            $FileId = 1,
            $PageId,
            $Offset = 4000,
            $NumberOfBytesToChange = 1,
            $HexString = '0x45',
            $bypassbufferpool = 1
        )
        $DbccWritePage = "DBCC WRITEPAGE (N'$Database', $FileId, $PageId, $Offset, $NumberOfBytesToChange, $HexString, $bypassbufferpool);"
        Write-Message -Level Verbose -Message "$DbccWritePage"
        $WriteInfo = $SqlInstance.Databases[$Database].Query($DbccWritePage)
        return $WriteInfo
    }

    if ("master", "tempdb", "model", "msdb" -contains $Database) {
        Stop-Function -Message "You may not corrupt system databases."
        return
    }

    try {
        $Server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential -MinimumVersion 9
    } catch {
        Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $SqlInstance
        return
    }

    $db = $Server.Databases | Where-Object { $_.Name -eq $Database }
    if (!$db) {
        Stop-Function -Message "The database specified does not exist."
        return
    }
    if ($Table) {
        $tb = $db.Tables | Where-Object Name -eq $Table
    } else {
        $tb = $db.Tables | Select-Object -First 1
    }

    if (-not $tb) {
        Stop-Function -Message "There are no accessible tables in $Database on $SqlInstance." -Target $Database
        return
    }

    $RowCount = $db.Query("select top 1 * from $($tb.name)")
    if ($RowCount.count -eq 0) {
        Stop-Function -Message "The table $tb has no rows" -Target $table
        return
    }

    if ($Pscmdlet.ShouldProcess("$db on $SqlInstance", "Corrupt $tb in $Database")) {
        $pages = Dbcc-Index -SqlInstance $Server -Database $Database -TableName $tb.Name | Select-Object -First 1
        #Dbcc-ReadPage -SqlInstance $Server -Database $Database -PageId $pages.PagePID -FileId $pages.PageFID
        Write-Message -Level Verbose -Message "Setting single-user mode."
        $null = Stop-DbaProcess -SqlInstance $Server -Database $Database
        $null = Set-DbaDbState -SqlServer $Server -Database $Database -SingleUser -Force

        try {
            Write-Message -Level Verbose -Message "Stopping processes in target database."
            $null = Stop-DbaProcess -SqlInstance $Server -Database $Database
            Write-Message -Level Verbose -Message "Corrupting data."
            Dbcc-WritePage -SqlInstance $Server -Database $Database -PageId $pages.PagePID -FileId $pages.PageFID
        } catch {
            $Server.ConnectionContext.Disconnect()
            $Server.ConnectionContext.Connect()
            $null = Set-DbaDbState -SqlServer $Server -Database $Database -MultiUser -Force
            Stop-Function -Message "Failed to write page" -Category WriteError -ErrorRecord $_ -Target $instance
            return
        }

        Write-Message -Level Verbose -Message "Setting database into multi-user mode."
        # If you do not disconnect and reconnect, multiuser fails.
        $Server.ConnectionContext.Disconnect()
        $Server.ConnectionContext.Connect()
        $null = Set-DbaDbState -SqlServer $Server -Database $Database -MultiUser -Force

        [pscustomobject]@{
            ComputerName = $Server.ComputerName
            InstanceName = $Server.ServiceName
            SqlInstance  = $Server.DomainInstanceName
            Database     = $db.Name
            Table        = $tb.Name
            Status       = "Corrupted"
        }
    }
}
tools\dbatools\internal\functions\Invoke-DbaDiagnosticQueryScriptParser.ps1
function Invoke-DbaDiagnosticQueryScriptParser {
    [CmdletBinding(DefaultParameterSetName = "Default")]

    Param(
        [parameter(Mandatory)]
        [ValidateScript( {Test-Path $_})]
        [System.IO.FileInfo]$filename,
        [Switch]$ExcludeQueryTextColumn,
        [Switch]$ExcludePlanColumn,
        [Switch]$NoColumnParsing
    )

    $out = "Parsing file {0}" -f $filename
    write-verbose -Message $out

    $ParsedScript = @()
    [string]$scriptpart = ""

    $fullscript = Get-Content -Path $filename

    $start = $false
    $querynr = 0
    $DBSpecific = $false

    if ($ExcludeQueryTextColumn) {$QueryTextColumn = ""}  else {$QueryTextColumn = ", t.[text] AS [Complete Query Text]"}
    if ($ExcludePlanColumn) {$PlanTextColumn = ""} else {$PlanTextColumn = ", qp.query_plan AS [Query Plan]"}

    foreach ($line in $fullscript) {
        if ($start -eq $false) {
            if (($line -match "You have the correct major version of SQL Server for this diagnostic information script") -or ($line.StartsWith("-- Server level queries ***"))) {
                $start = $true
            }
            continue
        }

        if ($line.StartsWith("-- Database specific queries ***") -or ($line.StartsWith("-- Switch to user database **"))) {
            $DBSpecific = $true
        }

        if (!$NoColumnParsing) {
            if (($line -match "-- uncomment out these columns if not copying results to Excel") -or ($line -match "-- comment out this column if copying results to Excel")) {
                $line = $QueryTextColumn + $PlanTextColumn
            }
        }

        if ($line -match "-{2,}\s{1,}(.*) \(Query (\d*)\) \((\D*)\)") {
            $prev_querydescription = $Matches[1]
            $prev_querynr = $Matches[2]
            $prev_queryname = $Matches[3]

            if ($querynr -gt 0) {
                $properties = @{QueryNr = $querynr; QueryName = $queryname; DBSpecific = $DBSpecific; Description = $queryDescription; Text = $scriptpart}
                $newscript = New-Object -TypeName PSObject -Property $properties
                $ParsedScript += $newscript
                $scriptpart = ""
            }

            $querydescription = $prev_querydescription
            $querynr = $prev_querynr
            $queryname = $prev_queryname
        } else {
            if (!$line.startswith("--") -and ($line.trim() -ne "") -and ($null -ne $line) -and ($line -ne "\n")) {
                $scriptpart += $line + "`n"
            }
        }
    }

    $properties = @{QueryNr = $querynr; QueryName = $queryname; DBSpecific = $DBSpecific; Description = $queryDescription; Text = $scriptpart}
    $newscript = New-Object -TypeName PSObject -Property $properties
    $ParsedScript += $newscript
    $ParsedScript
}
tools\dbatools\internal\functions\Invoke-DbMirrorValidation.ps1
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Invoke-DbMirrorValidation {
    <#
        .SYNOPSIS
            Validates if a mirror is ready

        .DESCRIPTION
            Validates if a mirror is ready

            Thanks to https://github.com/mmessano/PowerShell/blob/master/SQL-ConfigureDatabaseMirroring.ps1

        .PARAMETER Primary
            SQL Server name or SMO object representing the primary SQL Server.

        .PARAMETER PrimarySqlCredential
            Login to the primary instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

        .PARAMETER Mirror
            SQL Server name or SMO object representing the mirror SQL Server.

        .PARAMETER MirrorSqlCredential
            Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

        .PARAMETER Witness
            SQL Server name or SMO object representing the witness SQL Server.

        .PARAMETER WitnessSqlCredential
            Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

        .PARAMETER Database
                The database or databases to mirror

        .PARAMETER SharedPath
                The network share where the backups will be

        .PARAMETER InputObject
                Enables piping from Get-DbaDatabase

        .PARAMETER EnableException
            By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
            This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
            Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

        .NOTES
            Tags: Mirror, HA
            Author: Chrissy LeMaire (@cl), netnerds.net
            dbatools PowerShell module (https://dbatools.io, [email protected])
           Copyright: (c) 2018 by dbatools, licensed under MIT
            License: MIT https://opensource.org/licenses/MIT
        .EXAMPLE
            PS C:\> $params = @{
                    Primary = 'sql2017a'
                    Mirror = 'sql2017b'
                    MirrorSqlCredential = 'sqladmin'
                    Witness = 'sql2019'
                    Database = 'onthewall'
                    SharedPath = '\\nas\sql\share'
                }

            PS C:\> Invoke-DbMirrorValidation @params

            Do things

       #>
    [CmdletBinding()]
    param (
        [DbaInstanceParameter]$Primary,
        [PSCredential]$PrimarySqlCredential,
        [parameter(Mandatory)]
        [DbaInstanceParameter[]]$Mirror,
        [PSCredential]$MirrorSqlCredential,
        [DbaInstanceParameter]$Witness,
        [PSCredential]$WitnessSqlCredential,
        [string[]]$Database,
        [string]$SharedPath,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )
    process {
        if ((Test-Bound -ParameterName Primary) -and (Test-Bound -Not -ParameterName Database)) {
            Stop-Function -Message "Database is required when SqlInstance is specified"
            return
        }

        if ($Primary) {
            $InputObject += Get-DbaDatabase -SqlInstance $Primary -SqlCredential $SqlCredential -Database $Database
        }

        foreach ($db in $InputObject) {
            $server = $db.Parent
            $dbname = $db.Name
            $canmirror = $true
            $dest = Connect-DbaInstance -SqlInstance $Mirror -Credential $MirrorSqlCredential

            $endpoints = @()
            $endpoints += Get-DbaEndpoint -SqlInstance $server | Where-Object EndpointType -eq DatabaseMirroring
            $endpoints += Get-DbaEndpoint -SqlInstance $dest | Where-Object EndpointType -eq DatabaseMirroring

            if (Test-Bound -ParameterName Witness) {
                try {
                    $witserver = Connect-DbaInstance -SqlInstance $Witness -SqlCredential $WitnessSqlCredential
                    $endpoints += Get-DbaEndpoint -SqlInstance $witserver | Where-Object EndpointType -eq DatabaseMirroring
                    $witdb = Get-DbaDatabase -SqlInstance $witserver -Database $db.Name
                    $wexists = $true

                    if ($witdb.Status -ne 'Restoring') {
                        $canmirror = $false
                    }

                    if ($witdb) {
                        $witexists = $true
                    } else {
                        Write-Message -Level Verbose -Message "Database ($dbname) exists on witness server"
                        $canmirror = $false
                        $witexists = $false
                    }
                } catch {
                    $wexists = $false
                    $canmirror = $false
                }
            }

            if ($db.MirroringStatus -ne [Microsoft.SqlServer.Management.Smo.MirroringStatus]::None) {
                Write-Message -Level Verbose -Message "Cannot setup mirroring on database ($dbname) due to its current mirroring state: $($db.MirroringStatus)"
                $canmirror = $false
            }

            if ($db.Status -ne [Microsoft.SqlServer.Management.Smo.DatabaseStatus]::Normal) {
                Write-Message -Level Verbose -Message "Cannot setup mirroring on database ($dbname) due to its current Status: $($db.Status)"
                $canmirror = $false
            }

            if ($db.RecoveryModel -ne 'Full') {
                Write-Message -Level Verbose -Message "Cannot setup mirroring on database ($dbname) due to its current recovery model: $($db.RecoveryModel)"
                $canmirror = $false
            }

            $destdb = Get-DbaDatabase -SqlInstance $dest -Database $db.Name

            if ($destdb.RecoveryModel -ne 'Full') {
                $canmirror = $false
            }

            if ($destdb.Status -ne 'Restoring') {
                $canmirror = $false
            }

            if ($destdb) {
                $destdbexists = $true
            } else {
                Write-Message -Level Verbose -Message "Database ($dbname) does not exist on mirror server"
                $canmirror = $false
                $destdbexists = $false
            }

            if ((Test-Bound -ParameterName SharedPath) -and -not (Test-DbaPath -SqlInstance $dest -Path $SharedPath)) {
                Write-Message -Level Verbose -Message "Cannot access $SharedPath from $($destdb.Parent.Name)"
                $canmirror = $false
                $nexists = $false
            } else {
                $nexists = $true
            }

            if ($server.EngineEdition -ne $dest.EngineEdition) {
                Write-Message -Level Verbose -Message "This mirroring configuration is not supported. Because the principal server instance, $server, is $($server.EngineEdition) Edition, the mirror server instance must also be $($server.EngineEdition) Edition."
                $canmirror = $false
                $edition = $false
            } else {
                $edition = $true
            }

            # There's a better way to do this but I'm sleepy
            if ((Test-Bound -ParameterName Witness)) {
                if ($endpoints.Count -eq 3) {
                    $endpointpass = $true
                } else {
                    $endpointpass = $false
                }
            } else {
                if ($endpoints.Count -eq 2) {
                    $endpointpass = $true
                } else {
                    $endpointpass = $false
                }
            }

            $results = [pscustomobject]@{
                Primary                 = $Primary
                Mirror                  = $Mirror
                Witness                 = $Witness
                Database                = $db.Name
                RecoveryModel           = $db.RecoveryModel
                MirroringStatus         = $db.MirroringStatus
                State                   = $db.Status
                EndPoints               = $endpointpass
                DatabaseExistsOnMirror  = $destdbexists
                DatabaseExistsOnWitness = $witexists
                OnlineWitness           = $wexists
                EditionMatch            = $edition
                AccessibleShare         = $nexists
                DestinationDbStatus     = $destdb.Status
                WitnessDbStatus         = $witdb.Status
                ValidationPassed        = $canmirror
            }

            if ((Test-Bound -ParameterName Witness)) {
                $results | Select-DefaultView -Property Primary, Mirror, Witness, Database, RecoveryModel, MirroringStatus, State, EndPoints, DatabaseExistsOnMirror, OnlineWitness, DatabaseExistsOnWitness, EditionMatch, AccessibleShare, DestinationDbStatus, WitnessDbStatus, ValidationPassed
            } else {
                $results | Select-DefaultView -Property Primary, Mirror, Database, RecoveryModel, MirroringStatus, State, EndPoints, DatabaseExistsOnMirror, EditionMatch, AccessibleShare, DestinationDbStatus, ValidationPassed
            }
        }
    }
}
tools\dbatools\internal\functions\Invoke-ManagedComputerCommand.ps1
function Invoke-ManagedComputerCommand {
    <#
        .SYNOPSIS
            Runs wmi commands against a target system.

        .DESCRIPTION
            Runs wmi commands against a target system.
            Either directly or over PowerShell remoting.

        .PARAMETER ComputerName
            The target to run against. Must be resolvable.

        .PARAMETER Credential
            Credentials to use when using PowerShell remoting.

        .PARAMETER ScriptBlock
            The scriptblock to execute.
            Use $wmi to access the smo wmi object.
            Must not include a param block!

        .PARAMETER ArgumentList
            The arguments to pass to your scriptblock.
            Access them within the scriptblock using the automatic variable $args

        .PARAMETER EnableException
            Left in for legacy reasons. This command will throw no matter what
       #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [Alias("Server")]
        [dbainstanceparameter]$ComputerName,
        [PSCredential]$Credential,
        [Parameter(Mandatory)]
        [scriptblock]$ScriptBlock,
        [string[]]$ArgumentList,
        [switch][Alias('Silent')]
        $EnableException # Left in for legacy but this command needs to throw
    )

    $computer = $ComputerName.ComputerName

    $null = Test-ElevationRequirement -ComputerName $computer -EnableException $true

    $resolved = Resolve-DbaNetworkName -ComputerName $computer -Turbo
    $ipaddr = $resolved.IpAddress
    $ArgumentList += $ipaddr

    [scriptblock]$setupScriptBlock = {
        $ipaddr = $args[$args.GetUpperBound(0)]

        # Just in case we go remote, ensure the assembly is loaded
        [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SqlWmiManagement')
        $wmi = New-Object Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer $ipaddr
        $null = $wmi.Initialize()
    }

    $prescriptblock = $setupScriptBlock.ToString()
    $postscriptblock = $ScriptBlock.ToString()

    $scriptblock = [ScriptBlock]::Create("$prescriptblock  $postscriptblock")
    Write-Message -Level Verbose -Message "Connecting to SQL WMI on $computer."

    try {
        Invoke-Command2 -ScriptBlock $ScriptBlock -ArgumentList $ArgumentList -Credential $Credential -ErrorAction Stop
    } catch {
        Write-Message -Level Verbose -Message "Local connection attempt to $computer failed. Connecting remotely."

        # For surely resolve stuff, and going by default with kerberos, this needs to match FullComputerName
        $hostname = $resolved.FullComputerName

        Invoke-Command2 -ScriptBlock $ScriptBlock -ArgumentList $ArgumentList -ComputerName $hostname -ErrorAction Stop
    }
}
tools\dbatools\internal\functions\Invoke-Program.ps1
function Invoke-Program {
    <#
    .SYNOPSIS
        Invokes a remote execution of a file using specific credentials.

    .DESCRIPTION
    Based on https://github.com/adbertram/PSSqlUpdater
    Invokes a remote execution of a file passing credentials over the network to avoid a double-hop issue
    and gain privileges necessary to execute any kind of executables.

    First it tries to initialize a CredSSP connection by configuring both Client and Server to run CredSSP connections.

    If CredSSP connection fails, it falls back to a less secure PSSessionConfiguration workaround, which registers
    a temporary session configuration on a target machine (PS3.0+) and re-creates current PSSession to use remote
    configuration by default.

    .PARAMETER ComputerName
        Remote computer name

    .PARAMETER Path
        Path to the executable

    .PARAMETER Credential
        Credential object that will be used for authentication

    .PARAMETER ArgumentList
        List of arguments to pass to the executable

    .PARAMETER ExpandStrings
        The strings in ArgumentList and WorkingDirectory will be evaluated remotely on a target machine.

    .PARAMETER SuccessReturnCode
        Return codes that will be acknowledged as successful execution. Defaults to 0 (success), 3010 (restart required)

    .PARAMETER WorkingDirectory
        Working directory for the process

    .PARAMETER Authentication
        Choose authentication mechanism to use

    .PARAMETER Raw
        Return plain stdout without any additional information

    .PARAMETER Fallback
        When credentials are specified, it is possible that the chosen protocol would fail to connect with them.
        Fallback will use PSSessionConfiguration to create a session configuration on a remote machine that uses
        provided set of credentials by default.
        Not a default option since it transfers credentials over a potentially unsecure network.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Invoke, Program, Process, Session, PSSession, Authentication
        Author: Kirill Kravtsov (@nvarscar) https://nvarscar.wordpress.com/

    .EXAMPLE
        PS C:\> Invoke-Program -ComputerName ServerA -Credentials $cred -Path "C:\temp\setup.exe" -ArgumentList '/quiet' -WorkingDirectory 'C:'

        Starts "setup.exe /quiet" on ServerA under provided credentials. C:\ will be set as a working directory.

    .EXAMPLE
        PS C:\> Invoke-Program -ComputerName ServerA -Credentials $cred -Authentication Credssp -Path "C:\temp\setup.exe" -Fallback

        Starts "setup.exe" on ServerA under provided credentials. Will use CredSSP as a fisrt attempted protocol and then fallback to the PSSessionConfiguration workaround.

    #>
    [CmdletBinding()]
    [OutputType([System.Management.Automation.PSObject])]
    param
    (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Path,
        [DbaInstanceParameter]$ComputerName = $env:COMPUTERNAME,
        [pscredential]$Credential,
        [ValidateNotNullOrEmpty()]
        [string[]]$ArgumentList,
        [ValidateSet('Default', 'Basic', 'Negotiate', 'NegotiateWithImplicitCredential', 'Credssp', 'Digest', 'Kerberos')]
        [string]$Authentication = 'Default',
        [bool]$ExpandStrings = $false,
        [ValidateNotNullOrEmpty()]
        [string]$WorkingDirectory,
        [ValidateNotNullOrEmpty()]
        [uint32[]]$SuccessReturnCode = @(0, 3010),
        [switch]$Raw,
        [switch]$Fallback,
        [bool]$EnableException = $EnableException
    )
    process {
        $startProcess = {
            Param  (
                $Path,
                $ArgumentList,
                $ExpandStrings,
                $WorkingDirectory,
                $SuccessReturnCode
            )
            $output = [pscustomobject]@{
                ComputerName     = $env:COMPUTERNAME
                Path             = $Path
                ArgumentList     = $ArgumentList
                WorkingDirectory = $WorkingDirectory
                Successful       = $false
                stdout           = $null
                stderr           = $null
                ExitCode         = $null
            }
            $processStartInfo = New-Object System.Diagnostics.ProcessStartInfo
            $processStartInfo.FileName = $Path
            if ($ArgumentList) {
                $processStartInfo.Arguments = $ArgumentList
                if ($ExpandStrings) {
                    $processStartInfo.Arguments = $ExecutionContext.InvokeCommand.ExpandString($ArgumentList)
                }
            }
            if ($WorkingDirectory) {
                $processStartInfo.WorkingDirectory = $WorkingDirectory
                if ($ExpandStrings) {
                    $processStartInfo.WorkingDirectory = $ExecutionContext.InvokeCommand.ExpandString($WorkingDirectory)
                }
            }
            $processStartInfo.UseShellExecute = $false # This is critical for installs to function on core servers
            $processStartInfo.CreateNoWindow = $true
            $processStartInfo.RedirectStandardError = $true
            $processStartInfo.RedirectStandardOutput = $true
            $ps = New-Object System.Diagnostics.Process
            $ps.StartInfo = $processStartInfo
            $started = $ps.Start()
            if ($started) {
                $stdOut = $ps.StandardOutput.ReadToEnd()
                $stdErr = $ps.StandardError.ReadToEnd()
                $ps.WaitForExit()
                # assign output object values
                $output.stdout = $stdOut
                $output.stderr = $stdErr
                $output.ExitCode = $ps.ExitCode
                # Check the exit code of the process to see if it succeeded.
                if ($ps.ExitCode -in $SuccessReturnCode) {
                    $output.Successful = $true
                }
                $output
            }
        }

        $argList = @(
            $Path,
            $ArgumentList,
            $ExpandStrings,
            $WorkingDirectory,
            $SuccessReturnCode
        )

        $params = @{
            ScriptBlock    = $startProcess
            ArgumentList   = $argList
            ComputerName   = $ComputerName
            Credential     = $Credential
            Authentication = $Authentication
            ErrorAction    = 'Stop'
            Raw            = $true
        }

        Write-Message -Level Debug -Message "Acceptable success return codes are [$($SuccessReturnCode -join ',')]"
        Write-Message -Level Verbose -Message "Starting process [$Path] with arguments [$ArgumentList] on $ComputerName through $Authentication protocol"
        try {
            if ($Fallback) {
                $output = Invoke-CommandWithFallback @params
            } else {
                $output = Invoke-Command2 @params
            }
        } catch {
            Stop-Function -Message "Remote execution failed" -ErrorRecord $_
            return
        }

        Write-Message -Level Debug -Message "Process [$Path] returned exit code $($output.ExitCode)"
        if ($Raw) {
            if ($output.Successful) {
                return $output.stdout
            } else {
                $message = "Error running [$Path]: exited with errorcode $($output.ExitCode)`:`n$($output.StdErr)`n$($output.StdOut)"
                Stop-Function -Message "Program execution failed | $message"
            }
        } else {
            # Select * to ensure that the object is a generic object and not a de-serialized one from a remote session
            return $output | Select-Object -Property * -ExcludeProperty PSComputerName, RunspaceId | Select-DefaultView -Property ComputerName, Path, Successful, ExitCode, stdout
        }
    }
}
tools\dbatools\internal\functions\Invoke-SmoCheck.ps1
function Invoke-SmoCheck {
    <#
    .SYNOPSIS
    Checks for PowerShell SMO version vs SQL Server's SMO version.

    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [object]$SqlInstance
    )

    if ($script:smocheck -ne $true) {
        $script:smocheck = $true
        $smo = (([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.Fullname -like "Microsoft.SqlServer.SMO,*" }).FullName -Split ", ")[1]
        $smo = ([version]$smo.TrimStart("Version=")).Major
        $serverversion = $SqlInstance.version.major

        if ($serverversion - $smo -gt 1) {
            Write-Warning "Your version of SMO is $smo, which is significantly older than $($SqlInstance.name)'s version $($SqlInstance.version.major)."
            Write-Warning "This may present an issue when migrating certain portions of SQL Server."
            Write-Warning "If you encounter issues, consider upgrading SMO."
        }
    }
}
tools\dbatools\internal\functions\Invoke-TagCommand.ps1
function Invoke-TagCommand ([string]$Tag, [string]$Keyword) {
    <#
.SYNOPSIS
    An internal command, feel free to ignore.

.EXAMPLE
    Tag-Command -Tag Restore -Keyword Restore
    Tag-Command -Tag Backup -Keyword Backup
    Tag-Command -Tag Orphan -Keyword Orphan
    Tag-Command -Tag DisasterRecovery -Keyword Attach
    Tag-Command -Tag DisasterRecovery -Keyword Detach
    Tag-Command -Tag Snapshot -Keyword Snapshot
    Tag-Command -Tag Memory -Keyword Memory
    Tag-Command -Tag DisasterRecovery -Keyword Restore
    Tag-Command -Tag DisasterRecovery -Keyword Backup
    Tag-Command -Tag Storage -Keyword disk
    Tag-Command -Tag Storage -Keyword storage
    Tag-Command -Tag Migration -Keyword "Copy-"
    Tag-Command -Tag SPN -Keyword Kerberos
    Tag-Command -Tag SPN -Keyword SPN
    Tag-Command -Tag CIM -Keyword CimSession
    Tag-Command -Tag SQLWMI -Keyword Invoke-ManagedComputerCommand
    Tag-Command -Tag WSMan -Keyword Invoke-Command

    #>

    $tagsRex = ([regex]'(?m)^[\s]{0,15}Tags:(.*)$')
    $modulepath = (Get-Module -Name dbatools).Path
    $directory = Split-Path $modulepath
    $basedir = "$directory\functions\"
    Import-Module $modulepath -force
    $allfiles = Get-ChildItem $basedir
    foreach ($f in $allfiles) {
        if ($f -eq "Find-DbaCommand.ps1") { continue }

        $content = Get-Content $f.fullname
        if ($content -like "*$keyword*") {
            Write-Message -Level Warning -Message "$f needs a tag tag"
            $cmdname = $f.name.replace('.ps1', '')

            $fullhelp = get-help $cmdname -full

            $as = $fullhelp.alertset | out-string

            $tags = $tagsrex.Match($as).Groups[1].Value

            if ($tags) {
                $tags = $tags.ToString().split(',').Trim()
                Write-Message -Level Warning -Message "adding tags to existing ones"
                if ($tag -in $tags) {
                    Write-Message -Level Warning -Message "tag $tag is already present"
                    continue
                }
                $out = @()
                foreach ($line in $content) {
                    if ($line.trim().startsWith('Tags:')) {
                        $out += "$line, $tag"
                    } else {
                        $out += $line
                    }
                }
                Write-Message -Level Warning -Message "replacing content into $($f.fullname)"
                $out -join "`r`n" | Set-Content $f.fullname -Encoding UTF8

            } else {
                Write-Message -Level Warning -Message "need to add tags"
                $out = @()
                foreach ($line in $content) {
                    if ($line.startsWith('.NOTES')) {
                        $out += '.NOTES'
                        $out += "Tags: $tag"
                    } else {
                        $out += $line
                    }
                }
                Write-Message -Level Warning -Message "replacing content into $($f.fullname)"
                $out -join "`r`n" | Set-Content $f.fullname -Encoding UTF8
            }
        }
    }
}
tools\dbatools\internal\functions\Invoke-TlsWebRequest.ps1
function Invoke-TlsWebRequest {
    <#
    Internal utility that mimics invoke-webrequest
    but enables all tls available version
    rather than the default, which on a lot
    of standard installations is just TLS 1.0

       #>
    $currentVersionTls = [Net.ServicePointManager]::SecurityProtocol
    $currentSupportableTls = [Math]::Max($currentVersionTls.value__, [Net.SecurityProtocolType]::Tls.value__)
    $availableTls = [enum]::GetValues('Net.SecurityProtocolType') | Where-Object { $_ -gt $currentSupportableTls }
    $availableTls | ForEach-Object {
        [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor $_
    }

    Invoke-WebRequest @Args

    [Net.ServicePointManager]::SecurityProtocol = $currentVersionTls
}
tools\dbatools\internal\functions\Join-AdminUnc.ps1
function Join-AdminUnc {
    <#
    .SYNOPSIS
    Internal function. Parses a path to make it an admin UNC.
    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$servername,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$filepath

    )

    if (!$filepath) { return }
    if ($filepath.StartsWith("\\")) { return $filepath }

    $servername = $servername.Split("\")[0]

    if ($filepath.length -gt 0 -and $filepath -ne [System.DbNull]::Value) {
        $newpath = Join-Path "\\$servername\" $filepath.replace(':', '$')
        return $newpath
    } else { return }
}
tools\dbatools\internal\functions\Join-SomePath.ps1
function Join-SomePath {
    <#
    An internal command that does not require the local path to exist

    Boo, this does not work, but keeping it for future ref.
       #>
    [CmdletBinding()]
    param (
        [string]$Path,
        [string]$ChildPath
    )
    process {
        [IO.Path]::Combine($Path, $ChildPath)
    }
}
tools\dbatools\internal\functions\message\Convert-DbaMessageException.ps1
function Convert-DbaMessageException {
    <#
    .SYNOPSIS
        Transforms the Exception input to the message system.

    .DESCRIPTION
        Transforms the Exception input to the message system.

        If there is an exception running a transformation scriptblock, it will log the error in the transform error queue and return the original object instead.

    .PARAMETER Exception
        The input Exception object, that might have to be transformed (may not either)

    .PARAMETER FunctionName
        The function writing the message

    .PARAMETER ModuleName
        The module, that the function writing the message is part of

    .EXAMPLE
        PS C:\> Convert-DbaMessageException -Exception $Exception -FunctionName 'Get-Test' -ModuleName 'MyModule'

        Checks internal storage for definitions that require a Exception transform, and either returns the original object or the transformed object.
    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        $Exception,

        [Parameter(Mandatory)]
        [string]
        $FunctionName,

        [Parameter(Mandatory)]
        [string]
        $ModuleName
    )

    if ($null -eq $Exception) { return }

    $typeName = $Exception.GetType().FullName.ToLower()

    if ([Sqlcollaborative.Dbatools.Message.MessageHost]::ExceptionTransforms.ContainsKey($typeName)) {
        $scriptBlock = [Sqlcollaborative.Dbatools.Message.MessageHost]::ExceptionTransforms[$typeName]
        try {
            $tempException = $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create($scriptBlock.ToString())), $null, $Exception)
            return $tempException
        } catch {
            [Sqlcollaborative.Dbatools.Message.MessageHost]::WriteTransformError($_, $FunctionName, $ModuleName, $Exception, "Exception", ([System.Management.Automation.Runspaces.Runspace]::DefaultRunspace.InstanceId))
            return $Exception
        }
    }

    if ($transform = [Sqlcollaborative.Dbatools.Message.MessageHost]::ExceptionTransformList.Get($typeName, $ModuleName, $FunctionName)) {
        try {
            $tempException = $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create($transform.ScriptBlock.ToString())), $null, $Exception)
            return $tempException
        } catch {
            [Sqlcollaborative.Dbatools.Message.MessageHost]::WriteTransformError($_, $FunctionName, $ModuleName, $Exception, "Target", ([System.Management.Automation.Runspaces.Runspace]::DefaultRunspace.InstanceId))
            return $Exception
        }
    }

    return $Exception
}
tools\dbatools\internal\functions\message\Convert-DbaMessageLevel.ps1
function Convert-DbaMessageLevel {
    <#
    .SYNOPSIS
        Processes the effective message level of a message

    .DESCRIPTION
        Processes the effective message level of a message
        - Applies level decrements
        - Applies message level modifiers

    .PARAMETER OriginalLevel
        The level the message was originally written to

    .PARAMETER FromStopFunction
        Whether the message was passed through Stop-Function first.
        This is used to increment the automatic message level decrement counter by 1 (so it ignores the fact, that it was passed through Stop-Function).
        The automatic message level decrement functionality allows users to make nested commands' messages be less verbose.

    .PARAMETER Tags
        The tags that were added to the message

    .PARAMETER FunctionName
        The function that wrote the message.

    .PARAMETER ModuleName
        The module the function writing the message comes from.

    .EXAMPLE
        Convert-DbaMessageLevel -OriginalLevel $Level -FromStopFunction $fromStopFunction -Tags $Tag -FunctionName $FunctionName -ModuleName $ModuleName

        This will convert the original level of $Level based on the transformation rules for levels.
    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [Sqlcollaborative.Dbatools.Message.MessageLevel]
        $OriginalLevel,

        [Parameter(Mandatory)]
        [bool]
        $FromStopFunction,

        [Parameter(Mandatory)]
        [AllowNull()]
        [string[]]
        $Tags,

        [Parameter(Mandatory)]
        [string]
        $FunctionName,

        [Parameter(Mandatory)]
        [string]
        $ModuleName
    )

    $number = $OriginalLevel.value__

    if ([Sqlcollaborative.Dbatools.Message.MessageHost]::NestedLevelDecrement -gt 0) {
        $depth = (Get-PSCallStack).Count - 3
        if ($FromStopFunction) { $depth = $depth - 1 }
        $number = $number + $depth * ([Sqlcollaborative.Dbatools.Message.MessageHost]::NestedLevelDecrement)
    }

    foreach ($modifier in [Sqlcollaborative.Dbatools.Message.MessageHost]::MessageLevelModifiers.Values) {
        if ($modifier.AppliesTo($FunctionName, $ModuleName, $Tags)) {
            $number = $number + $modifier.Modifier
        }
    }

    # Finalize number and return
    if ($number -lt 1) { $number = 1 }
    if ($number -gt 9) { $number = 9 }
    return ([Sqlcollaborative.Dbatools.Message.MessageLevel]$number)
}
tools\dbatools\internal\functions\message\Convert-DbaMessageTarget.ps1
function Convert-DbaMessageTarget {
    <#
    .SYNOPSIS
        Transforms the target input to the message system.

    .DESCRIPTION
        Transforms the target input to the message system.

        If there is an exception running a transformation scriptblock, it will log the error in the transform error queue and return the original object instead.

    .PARAMETER Target
        The input target object, that might have to be transformed (may not either)

    .PARAMETER FunctionName
        The function writing the message

    .PARAMETER ModuleName
        The module, that the function writing the message is part of

    .EXAMPLE
        PS C:\> Convert-DbaMessageTarget -Target $Target -FunctionName 'Get-Test' -ModuleName 'MyModule'

        Checks internal storage for definitions that require a target transform, and either returns the original object or the transformed object.
    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        $Target,

        [Parameter(Mandatory)]
        [string]
        $FunctionName,

        [Parameter(Mandatory)]
        [string]
        $ModuleName
    )

    if ($null -eq $Target) { return }

    $typeName = $Target.GetType().FullName.ToLower()

    if ([Sqlcollaborative.Dbatools.Message.MessageHost]::TargetTransforms.ContainsKey($typeName)) {
        $scriptBlock = [Sqlcollaborative.Dbatools.Message.MessageHost]::TargetTransforms[$typeName]
        try {
            $tempTarget = $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create($scriptBlock.ToString())), $null, $Target)
            return $tempTarget
        } catch {
            [Sqlcollaborative.Dbatools.Message.MessageHost]::WriteTransformError($_, $FunctionName, $ModuleName, $Target, "Target", ([System.Management.Automation.Runspaces.Runspace]::DefaultRunspace.InstanceId))
            return $Target
        }
    }

    if ($transform = [Sqlcollaborative.Dbatools.Message.MessageHost]::TargetTransformlist.Get($typeName, $ModuleName, $FunctionName)) {
        try {
            $tempTarget = $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create($transform.ScriptBlock.ToString())), $null, $Target)
            return $tempTarget
        } catch {
            [Sqlcollaborative.Dbatools.Message.MessageHost]::WriteTransformError($_, $FunctionName, $ModuleName, $Target, "Target", ([System.Management.Automation.Runspaces.Runspace]::DefaultRunspace.InstanceId))
            return $Target
        }
    }

    return $Target
}
tools\dbatools\internal\functions\message\Get-DbaMessageLevelModifier.ps1
function Get-DbaMessageLevelModifier {
    <#
    .SYNOPSIS
        Returns all registered message level modifiers with similar name.

    .DESCRIPTION
        Returns all registered message level modifiers with similar name.

        Message level modifiers are created using New-DbaMessageLevelModifier and allow dynamically modifying the actual message level written by commands.

    .PARAMETER Name
        Default: "*"
        A name filter - only commands that are similar to the filter will be returned.

    .EXAMPLE
        PS C:\> Get-DbaMessageLevelModifier

        Returns all message level filters

    .EXAMPLE
        PS C:\> Get-DbaMessageLevelModifier -Name "mymodule.*"

        Returns all message level filters that start with "mymodule."
    #>
    [CmdletBinding()]
    param (
        [string]
        $Name = "*"
    )

    ([Sqlcollaborative.Dbatools.Message.MessageHost]::MessageLevelModifiers.Values) | Where-Object Name -Like $Name
}
tools\dbatools\internal\functions\message\New-DbaMessageLevelModifier.ps1
function New-DbaMessageLevelModifier {
    <#
    .SYNOPSIS
        Allows modifying message levels by powerful filters.

    .DESCRIPTION
        Allows modifying message levels by powerful filters.

        This is designed to allow a developer to have more control over what is written how during the development process.
        It also allows a debug user to fine tune what he is shown.

        This functionality is NOT designed for default implementation within a module.
        Instead, set healthy message levels for your own messages and leave others to tend to their own levels.

        Note:
        Adding too many level modifiers may impact performance, use with discretion.

    .PARAMETER Name
        The name of the level modifier.
        Can be arbitrary, but must be unique. Not case sensitive.

    .PARAMETER Modifier
        The level modifier to apply.
        - Use a negative value to make a message more relevant
        - Use a positive value to make a message less relevant
        While not limited to this range, the original levels range from 1 through 9:
        - 1-3 : Written to host and debug by default
        - 4-6 : Written to verbose and debug by default
        - 7-9 : Internas, written only to debug

    .PARAMETER IncludeFunctionName
        Only messages from functions with one of these exact names will be considered.

    .PARAMETER ExcludeFunctionName
        Messages from functions with one of these exact names will be ignored.

    .PARAMETER IncludeModuleName
        Only messages from modules with one of these exact names will be considered.

    .PARAMETER ExcludeModuleName
        Messages from module with one of these exact names will be ignored.

    .PARAMETER IncludeTags
        Only messages that contain one of these tags will be considered.

    .PARAMETER ExcludeTags
        Messages that contain one of these tags will be ignored.

    .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:\> New-DbaMessageLevelModifier -Name 'MyModule-Include' -Modifier -9 -IncludeModuleName MyModule
        PS C:\> New-DbaMessageLevelModifier -Name 'MyModule-Exclude' -Modifier 9 -ExcludeModuleName MyModule

        These settings will cause all messages from the module 'MyModule' to be highly prioritized and almost certainly written to host.
        It will also make it highly unlikely, that messages from other modules will even be considered for anything but the lowest level.

        This is useful when prioritizing your own module during development.
    #>
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]
        $Name,

        [Parameter(Mandatory)]
        [int]
        $Modifier,

        [string]
        $IncludeFunctionName,

        [string]
        $ExcludeFunctionName,

        [string]
        $IncludeModuleName,

        [string]
        $ExcludeModuleName,

        [string[]]
        $IncludeTags,

        [string[]]
        $ExcludeTags,

        [switch]
        $EnableException
    )

    if (Test-Bound -ParameterName IncludeFunctionName, ExcludeFunctionName, IncludeModuleName, ExcludeModuleName, IncludeTags, ExcludeTags -Not) {
        Stop-Function -Message "Must specify at least one condition in order to apply message level modifier!" -EnableException $EnableException -Category InvalidArgument
        return
    }

    $levelModifier = New-Object Sqlcollaborative.Dbatools.Message.MessageLevelModifier
    $levelModifier.Name = $Name.ToLower()
    $levelModifier.Modifier = $Modifier

    if (Test-Bound -ParameterName IncludeFunctionName) {
        $levelModifier.IncludeFunctionName = $IncludeFunctionName
    }

    if (Test-Bound -ParameterName ExcludeFunctionName) {
        $levelModifier.ExcludeFunctionName = $ExcludeFunctionName
    }

    if (Test-Bound -ParameterName IncludeModuleName) {
        $levelModifier.IncludeModuleName = $IncludeModuleName
    }

    if (Test-Bound -ParameterName ExcludeModuleName) {
        $levelModifier.ExcludeModuleName = $ExcludeModuleName
    }

    if (Test-Bound -ParameterName IncludeTags) {
        $levelModifier.IncludeTags = $IncludeTags
    }

    if (Test-Bound -ParameterName ExcludeTags) {
        $levelModifier.ExcludeTags = $ExcludeTags
    }

    [Sqlcollaborative.Dbatools.Message.MessageHost]::MessageLevelModifiers[$levelModifier.Name] = $levelModifier

    $levelModifier
}
tools\dbatools\internal\functions\message\Register-DbaMessageEvent.ps1
function Register-DbaMessageEvent {
    <#
    .SYNOPSIS
        Registers an event to when a message is written.

    .DESCRIPTION
        Registers an event to when a message is written.
        These events will fire whenever the written message fulfills the specified filter criteria.

        This allows integrating direct alerts and reactions to messages as they occur.

        Warnings:
        - Adding many subscriptions can impact overall performance, even without triggering.
        - Events are executed synchronously. executing complex operations may introduce a significant delay to the command execution.

        It is recommended to push processing that involves outside resources to a separate runspace, then use the event to pass the object as trigger.
        The TaskEngine component may prove to be just what is needed to accomplish this.

    .PARAMETER Name
        The name of the subscription.
        Each subscription must have a name, subscriptions of equal name will overwrite each other.
        This is in order to avoid having runspace uses explode the number of subscriptions on each invocation.

    .PARAMETER ScriptBlock
        The scriptblock to execute.
        It will receive the message entry (as returned by Get-DbatoolsLog) as its sole argument.

    .PARAMETER MessageFilter
        Filter by message content. Understands wildcards, but not regex.

    .PARAMETER ModuleNameFilter
        Filter by Name of the module, from which the message comes. Understands wildcards, but not regex.

    .PARAMETER FunctionNameFilter
        Filter by Name of the function, from which the message comes. Understands wildcards, but not regex.

    .PARAMETER TargetFilter
        Filter by target object. Performs equality comparison on an object level.

    .PARAMETER LevelFilter
        Include only messages of the specified levels.

    .PARAMETER TagFilter
        Only include messages with any of the specified tags.

    .PARAMETER RunspaceFilter
        Only include messages which were written by the specified runspace.
        You can find out the current runspace ID by running this:
        [System.Management.Automation.Runspaces.Runspace]::DefaultRunspace.InstanceId
        You can retrieve the primary runspace - the Guid used by the runspace the user sees - by running this:
        [Sqlcollaborative.Dbatools.Utility.UtilityHost]::PrimaryRunspace

    .EXAMPLE
        PS C:\> Register-DbaMessageEvent -Name 'Mymodule.OffloadTrigger' -ScriptBlock $ScriptBlock -Tag 'engine' -Module 'MyModule' -Level Warning

        Registers an event subscription ...
        - Under the name 'Mymodule.OffloadTrigger' ...
        - To execute $ScriptBlock ...
        - Whenever a message is written with the tag 'engine' by the module 'MyModule' at the level 'Warning'
    #>
    [CmdletBinding(PositionalBinding = $false)]
    param (
        [Parameter(Mandatory)]
        [string]
        $Name,

        [Parameter(Mandatory)]
        [System.Management.Automation.ScriptBlock]
        $ScriptBlock,

        [string]
        $MessageFilter,

        [string]
        $ModuleNameFilter,

        [string]
        $FunctionNameFilter,

        $TargetFilter,

        [Sqlcollaborative.Dbatools.Message.MessageLevel[]]
        $LevelFilter,

        [string[]]
        $TagFilter,

        [System.Guid]
        $RunspaceFilter
    )

    $newName = $Name.ToLower()
    $eventSubscription = New-Object Sqlcollaborative.Dbatools.Message.MessageEventSubscription
    $eventSubscription.Name = $newName
    $eventSubscription.ScriptBlock = $ScriptBlock

    if (Test-Bound -ParameterName MessageFilter) {
        $eventSubscription.MessageFilter = $MessageFilter
    }

    if (Test-Bound -ParameterName ModuleNameFilter) {
        $eventSubscription.ModuleNameFilter = $ModuleNameFilter
    }

    if (Test-Bound -ParameterName FunctionNameFilter) {
        $eventSubscription.FunctionNameFilter = $FunctionNameFilter
    }

    if (Test-Bound -ParameterName TargetFilter) {
        $eventSubscription.TargetFilter = $TargetFilter
    }

    if (Test-Bound -ParameterName LevelFilter) {
        $eventSubscription.LevelFilter = $LevelFilter
    }

    if (Test-Bound -ParameterName TagFilter) {
        $eventSubscription.TagFilter = $TagFilter
    }

    if (Test-Bound -ParameterName RunspaceFilter) {
        $eventSubscription.RunspaceFilter = $RunspaceFilter
    }

    [Sqlcollaborative.Dbatools.Message.MessageHost]::Events[$newName] = $eventSubscription
}
tools\dbatools\internal\functions\message\Register-DbaMessageTransform.ps1
function Register-DbaMessageTransform {
    <#
    .SYNOPSIS
        Registers a scriptblock that can transform message content.

    .DESCRIPTION
        Registers a scriptblock that can transform message content.
        This can be used to convert some kinds of input. Specifically:

        Target:
        When specifying a target, this target may require some conversion.
        For example, an object containing a live connection may need to have a static copy stored instead,
        as otherwise its export on a different runspace may cause access violations.

        Exceptions:
        Some exceptions may need transforming.
        For example some APIs might wrap the actual exception into a common wrapper.
        In this scenario you may want the actual exception in order to provide more specific information.

        In all instances, the scriptblock will be called, receiving only the relevant object as its sole input.

        Note: This transformation is performed synchronously on the active runspace. Complex scriptblocks may delay execution times when a matching object is passed.

    .PARAMETER TargetType
        The full typename of the target object to apply the scriptblock to.
        All objects of that typename will be processed through that scriptblock.

    .PARAMETER ExceptionType
        The full typename of the exception object to apply the scriptblock to.
        All objects of that typename will be processed through that scriptblock.
        Note: In case of error records, the type of the Exception Property is inspected. The error record as a whole will not be touched, except for having its exception exchanged.

    .PARAMETER ScriptBlock
        The scriptblock that performs the transformation.

    .PARAMETER TargetTypeFilter
        A filter for the typename of the target object to transform.
        Supports wildcards, but not regex.
        WARNING: Adding too many filter-type transforms may impact overall performance, try to avoid using them!

    .PARAMETER ExceptionTypeFilter
        A filter for the typename of the exception object to transform.
        Supports wildcards, but not regex.
        WARNING: Adding too many filter-type transforms may impact overall performance, try to avoid using them!

    .PARAMETER FunctionNameFilter
        Default: "*"
        Allows filtering by function name, in order to consider whether the function is affected.
        Supports wildcards, but not regex.
        WARNING: Adding too many filter-type transforms may impact overall performance, try to avoid using them!

    .PARAMETER ModuleNameFilter
        Default: "*"
        Allows filtering by module name, in order to consider whether the function is affected.
        Supports wildcards, but not regex.
        WARNING: Adding too many filter-type transforms may impact overall performance, try to avoid using them!

    .EXAMPLE
        PS C:\> Register-DbaMessageTransform -TargetType 'mymodule.category.classname' -ScriptBlock $ScriptBlock

        Whenever a target object of type 'mymodule.category.classname' is specified, invoke $ScriptBlock (with the object as sole argument) and store the result as target instead.

    .EXAMPLE
        PS C:\> Register-DbaMessageTransform -ExceptionType 'mymodule.category.exceptionname' -ScriptBlock $ScriptBlock

        Whenever an exception or error record of type 'mymodule.category.classname' is specified, invoke $ScriptBlock (with the object as sole argument) and store the result as exception instead.
        If the full error record is specified, only the updated exception will be inserted

    .EXAMPLE
        PS C:\> Register-DbaMessageTransform -TargetTypeFilter 'mymodule.category.*' -ScriptBlock $ScriptBlock

        Adds a transform for all target objects that are of a type whose full name starts with 'mymodule.category.'
        All target objects matching that typename will be run through the specified scriptblock, which in return generates the new target object.
    #>
    [CmdletBinding(PositionalBinding = $false)]
    param (
        [Parameter(Mandatory, ParameterSetName = "Target")]
        [string]
        $TargetType,

        [Parameter(Mandatory, ParameterSetName = "Exception")]
        [string]
        $ExceptionType,

        [Parameter(Mandatory)]
        [ScriptBlock]
        $ScriptBlock,

        [Parameter(Mandatory, ParameterSetName = "TargetFilter")]
        [string]
        $TargetTypeFilter,

        [Parameter(Mandatory, ParameterSetName = "ExceptionFilter")]
        [string]
        $ExceptionTypeFilter,

        [Parameter(ParameterSetName = "TargetFilter")]
        [Parameter(ParameterSetName = "ExceptionFilter")]
        $FunctionNameFilter = "*",

        [Parameter(ParameterSetName = "TargetFilter")]
        [Parameter(ParameterSetName = "ExceptionFilter")]
        $ModuleNameFilter = "*"
    )

    process {
        if ($TargetType) { [Sqlcollaborative.Dbatools.Message.MessageHost]::TargetTransforms[$TargetType.ToLower()] = $ScriptBlock }
        if ($ExceptionType) { [Sqlcollaborative.Dbatools.Message.MessageHost]::ExceptionTransforms[$ExceptionType.ToLower()] = $ScriptBlock }

        if ($TargetTypeFilter) {
            $condition = New-Object Sqlcollaborative.Dbatools.Message.TransformCondition($TargetTypeFilter, $ModuleNameFilter, $FunctionNameFilter, $ScriptBlock, "Target")
            [Sqlcollaborative.Dbatools.Message.MessageHost]::TargetTransformList.Add($condition)
        }

        if ($ExceptionTypeFilter) {
            $condition = New-Object Sqlcollaborative.Dbatools.Message.TransformCondition($ExceptionTypeFilter, $ModuleNameFilter, $FunctionNameFilter, $ScriptBlock, "Exception")
            [Sqlcollaborative.Dbatools.Message.MessageHost]::ExceptionTransformList.Add($condition)
        }
    }
}
tools\dbatools\internal\functions\message\Remove-DbaMessageLevelModifier.ps1
function Remove-DbaMessageLevelModifier {
    <#
    .SYNOPSIS
        Removes a message level modifier.

    .DESCRIPTION
        Removes a message level modifier.

        Message Level Modifiers can be created by using New-DbaMessageLevelModifier.
        They are used to emphasize or deemphasize messages, in order to help with debugging.

    .PARAMETER Name
        Name of the message level modifier to remove.

    .PARAMETER Modifier
        The actual modifier to remove, as returned by Get-DbaMessageLevelModifier.

    .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-DbaMessageLevelModifier | Remove-DbaMessageLevelModifier

        Removes all message level modifiers, restoring everything to their default levels.

    .EXAMPLE
        PS C:\> Remove-DbaMessageLevelModifier -Name "mymodule.foo"

        Removes the message level modifier named "mymodule.foo"
    #>
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [string[]]
        $Name,

        [Parameter(ValueFromPipeline)]
        [Sqlcollaborative.Dbatools.Message.MessageLevelModifier[]]
        $Modifier,

        [switch]
        $EnableException
    )

    process {
        foreach ($item in $Name) {
            if ($item -eq "Sqlcollaborative.Dbatools.Message.MessageLevelModifier") { continue }

            if ([Sqlcollaborative.Dbatools.Message.MessageHost]::MessageLevelModifiers.ContainsKey($item.ToLower())) {
                [Sqlcollaborative.Dbatools.Message.MessageHost]::MessageLevelModifiers.Remove($item.ToLower())
            } else {
                Stop-Function -Message "No message level modifier of name $item found!" -EnableException $EnableException -Category InvalidArgument -Continue
            }
        }
        foreach ($item in $Modifier) {
            if ([Sqlcollaborative.Dbatools.Message.MessageHost]::MessageLevelModifiers.ContainsKey($item.Name)) {
                [Sqlcollaborative.Dbatools.Message.MessageHost]::MessageLevelModifiers.Remove($item.Name)
            } else {
                Stop-Function -Message "No message level modifier of name $($item.Name) found!" -EnableException $EnableException -Category InvalidArgument -Continue
            }
        }
    }
}
tools\dbatools\internal\functions\message\Write-HostColor.ps1
function Write-HostColor {
    <#
    .SYNOPSIS
        Function that recognizes html-style tags to insert color into printed text.

    .DESCRIPTION
        Function that recognizes html-style tags to insert color into printed text.

        Color tags should be designed to look like this:
        <c="<console color>">Text</c>
        For example this would be a valid string:
        "This message should <c="red">partially be painted in red</c>!"

        This allows specifying color within strings and avoids having to piece together colored text in multiple calls to Write-Host.
        Only colors that are part of the ConsoleColor enumeration can be used. Bad colors will be ignored in favor of the default color.

    .PARAMETER String
        The message to write to host.

    .PARAMETER DefaultColor
        Default: (Get-DbatoolsConfigValue -Name "message.infocolor")
        The color to write stuff to host in when no (or bad) color-code was specified.

    .EXAMPLE
        Write-HostColor -String 'This is going to be <c="red">bloody red</c> text! And this is <c="green">green stuff</c> for extra color'

        Will print the specified line in multiple colors

    .EXAMPLE
        $string1 = 'This is going to be <c="red">bloody red</c> text! And this is <c="green">green stuff</c> for extra color'
        $string2 = '<c="red">bloody red</c> text! And this is <c="green">green stuff</c> for extra color'
        $string3 = 'This is going to be <c="red">bloody red</c> text! And this is <c="green">green stuff</c>'
        $string1, $string2, $string3 | Write-HostColor -DefaultColor "Magenta"

        Will print all three lines, respecting the color-codes, but use the color "Magenta" as default color.

    .EXAMPLE
        $stringLong = @"
        Dear <c="red">Sirs</c><c="green"> and</c> <c="blue">Madams</c>,

        it has come to our attention that you are not sufficiently <c="darkblue">awesome!</c>
        Kindly improve your <c="yellow">AP</c> (<c="magenta">awesome-ness points</c>) by at least 50% to maintain you membership in Awesome Inc!

        You have <c="green">27 3/4</c> days time to meet this deadline. <c="darkyellow">After this we will unfortunately be forced to rend you assunder and sacrifice your remains to the devil</c>.

        Best regards,
        <c="red">Luzifer</c>
        "@
        Write-HostColor -String $stringLong

        Will print a long multiline text in its entirety while still respecting the colorcodes
    #>
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "")]
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [string[]]
        $String,

        [ConsoleColor]
        $DefaultColor = (Get-DbatoolsConfigValue -Name "message.infocolor")
    )
    process {
        foreach ($line in $String) {
            foreach ($row in $line.Split("`n").Split([environment]::NewLine)) {
                if ($row -notlike '*<c=["'']*["'']>*</c>*') { Write-Host -Object $row -ForegroundColor $DefaultColor }
                else {
                    $match = ($row | Select-String '<c=["''](.*?)["'']>(.*?)</c>' -AllMatches).Matches
                    $index = 0
                    $count = 0

                    while ($count -le $match.Count) {
                        if ($count -lt $Match.Count) {
                            Write-Host -Object $row.SubString($index, ($match[$count].Index - $Index)) -ForegroundColor $DefaultColor -NoNewline
                            try { Write-Host -Object $match[$count].Groups[2].Value -ForegroundColor $match[$count].Groups[1].Value -NoNewline -ErrorAction Stop }
                            catch { Write-Host -Object $match[$count].Groups[2].Value -ForegroundColor $DefaultColor -NoNewline -ErrorAction Stop }

                            $index = $match[$count].Index + $match[$count].Length
                            $count++
                        } else {
                            Write-Host -Object $row.SubString($index) -ForegroundColor $DefaultColor
                            $count++
                        }
                    }
                }
            }
        }
    }
}
tools\dbatools\internal\functions\New-DbaLogShippingPrimaryDatabase.ps1
function New-DbaLogShippingPrimaryDatabase {
    <#
        .SYNOPSIS
            New-DbaLogShippingPrimaryDatabase add the primary database to log shipping

        .DESCRIPTION
            New-DbaLogShippingPrimaryDatabase will add the primary database to log shipping.
            This is executed on the primary server.

        .PARAMETER SqlInstance
            SQL Server instance. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

        .PARAMETER SqlCredential
            Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

        .PARAMETER Database
            Database to set up log shipping for.

        .PARAMETER BackupDirectory
            Is the path to the backup folder on the primary server.

        .PARAMETER BackupJob
            Is the name of the SQL Server Agent job on the primary server that copies the backup into the backup folder.

        .PARAMETER BackupJobID
            The SQL Server Agent job ID associated with the backup job on the primary server.

        .PARAMETER BackupRetention
            Is the length of time, in minutes, to retain the log backup file in the backup directory on the primary server.

        .PARAMETER BackupShare
            Is the network path to the backup directory on the primary server.

        .PARAMETER BackupThreshold
            Is the length of time, in minutes, after the last backup before a threshold_alert error is raised.
            The default is 60.

        .PARAMETER CompressBackup
            Enables the use of backup compression

        .PARAMETER ThresholdAlert
            Is the length of time, in minutes, when the alert is to be raised when the backup threshold is exceeded.
            The default is 14,420.

        .PARAMETER HistoryRetention
            Is the length of time in minutes in which the history will be retained.
            The default is 14420.

        .PARAMETER MonitorServer
            Is the name of the monitor server.
            The default is the name of the primary server.

        .PARAMETER MonitorCredential
            Allows you to login to enter a secure credential.
            This is only needed in combination with MonitorServerSecurityMode having either a 0 or 'sqlserver' value.
            To use: $scred = Get-Credential, then pass $scred object to the -MonitorCredential parameter.

        .PARAMETER MonitorServerSecurityMode
            The security mode used to connect to the monitor server. Allowed values are 0, "sqlserver", 1, "windows"
            The default is 1 or Windows.

        .PARAMETER ThresholdAlertEnabled
            Specifies whether an alert will be raised when backup threshold is exceeded.
            The default is 0.

        .PARAMETER WhatIf
            Shows what would happen if the command were to run. No actions are actually performed.

        .PARAMETER Confirm
            Prompts you for confirmation before executing any changing operations within the command.

        .PARAMETER EnableException
            By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
            This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
            Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

        .PARAMETER Force
            The force parameter will ignore some errors in the parameters and assume defaults.
            It will also remove the any present schedules with the same name for the specific job.

        .NOTES
            Author: Sander Stad (@sqlstad, sqlstad.nl)
            Website: https://dbatools.io
            Copyright: (c) 2018 by dbatools, licensed under MIT
            License: MIT https://opensource.org/licenses/MIT

        .EXAMPLE
            New-DbaLogShippingPrimaryDatabase -SqlInstance sql1 -Database DB1 -BackupDirectory D:\data\logshipping -BackupJob LSBackup_DB1 -BackupRetention 4320 -BackupShare "\\sql1\logshipping" -BackupThreshold 60 -CompressBackup -HistoryRetention 14420 -MonitorServer sql1 -ThresholdAlertEnabled

       #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]

    param (
        [parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [object]$SqlInstance,
        [System.Management.Automation.PSCredential]$SqlCredential,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [object]$Database,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$BackupDirectory,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$BackupJob,
        [Parameter(Mandatory)]
        [int]$BackupRetention,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$BackupShare,
        [int]$BackupThreshold = 60,
        [switch]$CompressBackup,
        [int]$ThresholdAlert = 14420,
        [int]$HistoryRetention = 14420,
        [string]$MonitorServer,
        [ValidateSet(0, "sqlserver", 1, "windows")]
        [object]$MonitorServerSecurityMode = 1,
        [System.Management.Automation.PSCredential]$MonitorCredential,
        [switch]$ThresholdAlertEnabled,
        [Alias('Silent')]
        [switch]$EnableException,
        [switch]$Force
    )

    # Try connecting to the instance
    try {
        $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
    } catch {
        Stop-Function -Message "Could not connect to Sql Server instance" -Target $SqlInstance -Continue
    }

    # Check if the backup UNC path is correct and reachable
    if ([bool]([uri]$BackupShare).IsUnc -and $BackupShare -notmatch '^\\(?:\\[^<>:`"/\\|?*]+)+$') {
        Stop-Function -Message "The backup share path $BackupShare should be formatted in the form \\server\share." -Target $SqlInstance
        return
    } else {
        if (-not ((Test-Path $BackupShare -PathType Container -IsValid) -and ((Get-Item $BackupShare).PSProvider.Name -eq 'FileSystem'))) {
            Stop-Function -Message "The backup share path $BackupShare is not valid or can't be reached." -Target $SqlInstance
            return
        }
    }

    # Check the backup compression
    if ($CompressBackup -eq $true) {
        Write-Message -Message "Setting backup compression to 1." -Level Verbose
        $BackupCompression = 1
    } elseif ($CompressBackup -eq $false) {
        Write-Message -Message "Setting backup compression to 0." -Level Verbose
        $BackupCompression = 0
    } elseif (-not $CompressBackup) {
        $defaultCompression = (Get-DbaSpConfigure -SqlInstance $SqlInstance -ConfigName DefaultBackupCompression).ConfiguredValue
        Write-Message -Message "Setting backup compression to default value $defaultCompression." -Level Verbose
        $BackupCompression = $defaultCompression

    }

    # Check of the MonitorServerSecurityMode value is of type string and set the integer value
    if ($MonitorServerSecurityMode -notin 0, 1) {
        $MonitorServerSecurityMode = switch ($MonitorServerSecurityMode) {"WINDOWS" { 1 } "SQLSERVER" { 0 } }
        Write-Message -Message "Setting monitor server security mode to $MonitorServerSecurityMode." -Level Verbose
    }

    # Check the MonitorServer
    if (-not $MonitorServer -and $Force) {
        Write-Message -Message "Setting monitor server to $SqlInstance." -Level Verbose
        $MonitorServer = $SqlInstance
    }

    # Check the MonitorServerSecurityMode if it's SQL Server authentication
    if ($MonitorServerSecurityMode -eq 0 -and -not $MonitorCredential) {
        Stop-Function -Message "The MonitorServerCredential cannot be empty when using SQL Server authentication." -Target $SqlInstance
        return
    } elseif ($MonitorServerSecurityMode -eq 0 -and $MonitorCredential) {
        # Get the username and password from the credential
        $MonitorLogin = $MonitorCredential.UserName
        $MonitorPassword = $MonitorCredential.GetNetworkCredential().Password

        # Check if the user is in the database
        if ($server.Databases['master'].Users.Name -notcontains $MonitorLogin) {
            Stop-Function -Message "User $MonitorLogin for monitor login must be in the master database." -Target $SqlInstance
            return
        }
    }

    # Check if the database is present on the source sql server
    if ($server.Databases.Name -notcontains $Database) {
        Stop-Function -Message "Database $Database is not available on instance $SqlInstance" -Target $SqlInstance
        return
    }

    # Check the if Threshold alert needs to be enabled
    if ($ThresholdAlertEnabled) {
        [int]$ThresholdAlertEnabled = 1
        Write-Message -Message "Setting Threshold alert to $ThresholdAlertEnabled." -Level Verbose
    } else {
        [int]$ThresholdAlertEnabled = 0
        Write-Message -Message "Setting Threshold alert to $ThresholdAlertEnabled." -Level Verbose
    }

    # Set the log shipping primary
    $Query = "
        DECLARE @LS_BackupJobId AS uniqueidentifier;
        DECLARE @LS_PrimaryId AS uniqueidentifier;
        EXEC master.sys.sp_add_log_shipping_primary_database
            @database = N'$Database'
            ,@backup_directory = N'$BackupDirectory'
            ,@backup_share = N'$BackupShare'
            ,@backup_job_name = N'$BackupJob'
            ,@backup_retention_period = $BackupRetention
            ,@backup_threshold = $BackupThreshold
            ,@history_retention_period = $HistoryRetention
            ,@backup_job_id = @LS_BackupJobId OUTPUT
            ,@primary_id = @LS_PrimaryId OUTPUT "

    if ($SqlInstance.Version.Major -gt 9) {
        $Query += ",@backup_compression = $BackupCompression"
    }

    if ($MonitorServer) {
        $Query += "
            ,@monitor_server = N'$MonitorServer'
            ,@monitor_server_security_mode = $MonitorServerSecurityMode
            ,@threshold_alert = $ThresholdAlert
            ,@threshold_alert_enabled = $ThresholdAlertEnabled"

        #if ($MonitorServer -and ($SqlInstance.Version.Major -ge 16)) {
        if ($server.Version.Major -ge 12) {
            # Check the MonitorServerSecurityMode if it's SQL Server authentication
            if ($MonitorServer -and $MonitorServerSecurityMode -eq 0 ) {
                $Query += "
                    ,@monitor_server_login = N'$MonitorLogin'
                    ,@monitor_server_password = N'$MonitorPassword' "
            }
        } else {
            $Query += "
                ,@ignoreremotemonitor = 1"
        }
    }

    if ($Force -or ($server.Version.Major -gt 9)) {
        $Query += "
            ,@overwrite = 1;"
    } else {
        $Query += ";"
    }

    # Execute the query to add the log shipping primary
    if ($PSCmdlet.ShouldProcess($SqlServer, ("Configuring logshipping for primary database $Database on $SqlInstance"))) {
        try {
            Write-Message -Message "Configuring logshipping for primary database $Database." -Level Verbose
            Write-Message -Message "Executing query:`n$Query" -Level Verbose
            $server.Query($Query)

            # For versions prior to SQL Server 2014, adding a monitor works in a different way.
            # The next section makes sure the settings are being synchronized with earlier versions
            if ($MonitorServer -and ($server.Version.Major -lt 12)) {
                # Get the details of the primary database
                $query = "SELECT * FROM msdb.dbo.log_shipping_monitor_primary WHERE primary_database = '$Database'"
                $lsDetails = $server.Query($query)

                # Setup the procedure script for adding the monitor for the primary
                $query = "EXEC msdb.dbo.sp_processlogshippingmonitorprimary @mode = $MonitorServerSecurityMode
                    ,@primary_id = '$($lsDetails.primary_id)'
                    ,@primary_server = '$($lsDetails.primary_server)'
                    ,@monitor_server = '$MonitorServer' "

                # Check the MonitorServerSecurityMode if it's SQL Server authentication
                if ($MonitorServer -and $MonitorServerSecurityMode -eq 0 ) {
                    $query += "
                    ,@monitor_server_login = N'$MonitorLogin'
                    ,@monitor_server_password = N'$MonitorPassword' "
                }

                $query += "
                    ,@monitor_server_security_mode = 1
                    ,@primary_database = '$($lsDetails.primary_database)'
                    ,@backup_threshold = $($lsDetails.backup_threshold)
                    ,@threshold_alert = $($lsDetails.threshold_alert)
                    ,@threshold_alert_enabled = $([int]$lsDetails.threshold_alert_enabled)
                    ,@history_retention_period = $($lsDetails.history_retention_period)
                "

                Write-Message -Message "Configuring monitor server for primary database $Database." -Level Verbose
                Write-Message -Message "Executing query:`n$query" -Level Verbose
                Invoke-DbaQuery -SqlInstance $MonitorServer -SqlCredential $MonitorCredential -Database msdb -Query $query

                $query = "
                    UPDATE msdb.dbo.log_shipping_primary_databases
                    SET monitor_server = '$MonitorServer', user_specified_monitor = 1
                    WHERE primary_id = '$($lsDetails.primary_id)'
                "
                Write-Message -Message "Updating monitor information for the primary database $Database." -Level Verbose
                Write-Message -Message "Executing query:`n$query" -Level Verbose
                $server.Query($query)
            }
        } catch {
            Write-Message -Message "$($_.Exception.InnerException.InnerException.InnerException.InnerException.Message)" -Level Warning
            Stop-Function -Message "Error executing the query.`n$($_.Exception.Message)`n$($Query)" -ErrorRecord $_ -Target $SqlInstance -Continue
        }
    }

    Write-Message -Message "Finished adding the primary database $Database to log shipping." -Level Verbose

}
tools\dbatools\internal\functions\New-DbaLogShippingPrimarySecondary.ps1
function New-DbaLogShippingPrimarySecondary {
    <#
        .SYNOPSIS
            New-DbaLogShippingPrimarySecondary adds an entry for a secondary database.

        .DESCRIPTION
            New-DbaLogShippingPrimarySecondary adds an entry for a secondary database.
            This is executed on the primary server.

        .PARAMETER SqlInstance
            SQL Server instance. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

        .PARAMETER SqlCredential
            Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

        .PARAMETER PrimaryDatabase
            Is the name of the database on the primary server.

        .PARAMETER SecondaryDatabase
            Is the name of the secondary database.

        .PARAMETER SecondaryServer
            Is the name of the secondary server.

        .PARAMETER SecondarySqlCredential
            Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted. To use:
            $scred = Get-Credential, then pass $scred object to the -SecondarySqlCredential parameter.

        .PARAMETER WhatIf
            Shows what would happen if the command were to run. No actions are actually performed.

        .PARAMETER Confirm
            Prompts you for confirmation before executing any changing operations within the command.

        .PARAMETER EnableException
            By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
            This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
            Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

        .NOTES
            Author: Sander Stad (@sqlstad, sqlstad.nl)
            Website: https://dbatools.io
            Copyright: (c) 2018 by dbatools, licensed under MIT
            License: MIT https://opensource.org/licenses/MIT

        .LINK
            https://dbatools.io/New-DbaLogShippingPrimarySecondary

        .EXAMPLE
            New-DbaLogShippingPrimarySecondary -SqlInstance sql1 -PrimaryDatabase DB1 -SecondaryServer sql2 -SecondaryDatabase DB1_DR
       #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [object]$PrimaryDatabase,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [object]$SecondaryDatabase,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [DBAInstanceParameter]$SecondaryServer,
        [PSCredential]$SecondarySqlCredential,
        [Alias('Silent')]
        [switch]$EnableException
    )

    # Try connecting to the instance
    try {
        $ServerPrimary = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
    } catch {
        Stop-Function -Message "Could not connect to Sql Server instance" -Target $SqlInstance -Continue
    }

    # Try connecting to the instance
    try {
        $ServerSecondary = Connect-SqlInstance -SqlInstance $SecondaryServer -SqlCredential $SecondarySqlCredential
    } catch {
        Stop-Function -Message "Could not connect to Sql Server instance" -Target $SecondaryServer -Continue
    }

    # Check if the database is present on the source sql server
    if ($ServerPrimary.Databases.Name -notcontains $PrimaryDatabase) {
        Stop-Function -Message "Database $PrimaryDatabase is not available on instance $SqlInstance" -ErrorRecord $_ -Target $SqlInstance -Continue
    }

    # Check if the database is present on the destination sql server
    if ($ServerSecondary.Databases.Name -notcontains $SecondaryDatabase) {
        Stop-Function -Message "Database $SecondaryDatabase is not available on instance $SecondaryServer" -ErrorRecord $_ -Target $SecondaryServer -Continue
    }

    $Query = "SELECT primary_database FROM msdb.dbo.log_shipping_primary_databases WHERE primary_database = '$PrimaryDatabase'"

    try {
        Write-Message -Message "Executing query:`n$Query" -Level Verbose
        $Result = $ServerPrimary.Query($Query)
        if ($Result.Count -eq 0 -or $Result[0] -ne $PrimaryDatabase) {
            Stop-Function -Message "Database $PrimaryDatabase does not exist as log shipping primary.`nPlease run New-DbaLogShippingPrimaryDatabase first."  -ErrorRecord $_ -Target $SqlInstance -Continue
        }
    } catch {
        Stop-Function -Message "Error executing the query.`n$($_.Exception.Message)`n$Query" -ErrorRecord $_ -Target $SqlInstance -Continue
    }

    # Set the query for the log shipping primary and secondary
    $Query = "EXEC master.sys.sp_add_log_shipping_primary_secondary
        @primary_database = N'$PrimaryDatabase'
        ,@secondary_server = N'$SecondaryServer'
        ,@secondary_database = N'$SecondaryDatabase' "

    if ($ServerPrimary.Version.Major -gt 9) {
        $Query += ",@overwrite = 1;"
    } else {
        $Query += ";"
    }

    # Execute the query to add the log shipping primary
    if ($PSCmdlet.ShouldProcess($SqlInstance, ("Configuring logshipping connecting the primary database $PrimaryDatabase to secondary database $SecondaryDatabase on $SqlInstance"))) {
        try {
            Write-Message -Message "Configuring logshipping connecting the primary database $PrimaryDatabase to secondary database $SecondaryDatabase on $SqlInstance." -Level Verbose
            Write-Message -Message "Executing query:`n$Query" -Level Verbose
            $ServerPrimary.Query($Query)
        } catch {
            Write-Message -Message "$($_.Exception.InnerException.InnerException.InnerException.InnerException.Message)" -Level Warning
            Stop-Function -Message "Error executing the query.`n$($_.Exception.Message)`n$Query" -ErrorRecord $_ -Target $SqlInstance -Continue
        }
    }

    Write-Message -Message "Finished configuring of primary database $PrimaryDatabase to secondary database $SecondaryDatabase." -Level Verbose

}
tools\dbatools\internal\functions\New-DbaLogShippingSecondaryDatabase.ps1
function New-DbaLogShippingSecondaryDatabase {
    <#
        .SYNOPSIS
            New-DbaLogShippingSecondaryDatabase sets up a secondary databases for log shipping.

        .DESCRIPTION
            New-DbaLogShippingSecondaryDatabase sets up a secondary databases for log shipping.
            This is executed on the secondary server.

        .PARAMETER SqlInstance
            SQL Server instance. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

        .PARAMETER SqlCredential
            Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

        .PARAMETER BufferCount
            The total number of buffers used by the backup or restore operation.
            The default is -1.

        .PARAMETER BlockSize
            The size, in bytes, that is used as the block size for the backup device.
            The default is -1.

        .PARAMETER DisconnectUsers
            If set to 1, users are disconnected from the secondary database when a restore operation is performed.
            Te default is 0.

        .PARAMETER HistoryRetention
            Is the length of time in minutes in which the history is retained.
            The default is 14420.

        .PARAMETER MaxTransferSize
            The size, in bytes, of the maximum input or output request which is issued by SQL Server to the backup device.

        .PARAMETER PrimaryServer
            The name of the primary instance of the Microsoft SQL Server Database Engine in the log shipping configuration.

        .PARAMETER PrimaryDatabase
            Is the name of the database on the primary server.

        .PARAMETER RestoreAll
            If set to 1, the secondary server restores all available transaction log backups when the restore job runs.
            The default is 1.

        .PARAMETER RestoreDelay
            The amount of time, in minutes, that the secondary server waits before restoring a given backup file.
            The default is 0.

        .PARAMETER RestoreMode
            The restore mode for the secondary database. The default is 0.
            0 = Restore log with NORECOVERY.
            1 = Restore log with STANDBY.

        .PARAMETER RestoreThreshold
            The number of minutes allowed to elapse between restore operations before an alert is generated.

        .PARAMETER SecondaryDatabase
            Is the name of the secondary database.

        .PARAMETER ThresholdAlert
            Is the alert to be raised when the backup threshold is exceeded.
            The default is 14420.

        .PARAMETER ThresholdAlertEnabled
            Specifies whether an alert is raised when backup_threshold is exceeded.

        .PARAMETER MonitorServer
            Is the name of the monitor server.
            The default is the name of the primary server.

        .PARAMETER MonitorCredential
            Allows you to login to enter a secure credential.
            This is only needed in combination with MonitorServerSecurityMode having either a 0 or 'sqlserver' value.
            To use: $scred = Get-Credential, then pass $scred object to the -MonitorCredential parameter.

        .PARAMETER MonitorServerSecurityMode
            The security mode used to connect to the monitor server. Allowed values are 0, "sqlserver", 1, "windows"
            The default is 1 or Windows.

        .PARAMETER WhatIf
            Shows what would happen if the command were to run. No actions are actually performed.

        .PARAMETER Confirm
            Prompts you for confirmation before executing any changing operations within the command.

        .PARAMETER EnableException
            By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
            This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
            Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

        .PARAMETER Force
            The force parameter will ignore some errors in the parameters and assume defaults.
            It will also remove the any present schedules with the same name for the specific job.

        .NOTES
            Author: Sander Stad (@sqlstad, sqlstad.nl)
            Website: https://dbatools.io
            Copyright: (c) 2018 by dbatools, licensed under MIT
            License: MIT https://opensource.org/licenses/MIT

        .EXAMPLE
            New-DbaLogShippingSecondaryDatabase -SqlInstance sql2 -SecondaryDatabase DB1_DR -PrimaryServer sql1 -PrimaryDatabase DB1 -RestoreDelay 0 -RestoreMode standby -DisconnectUsers -RestoreThreshold 45 -ThresholdAlertEnabled -HistoryRetention 14420
       #>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]

    param (
        [parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [int]$BufferCount = -1,
        [int]$BlockSize = -1,
        [switch]$DisconnectUsers,
        [int]$HistoryRetention = 14420,
        [int]$MaxTransferSize,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [DbaInstanceParameter]$PrimaryServer,
        [PSCredential]$PrimarySqlCredential,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [object]$PrimaryDatabase,
        [int]$RestoreAll = 1,
        [int]$RestoreDelay = 0,
        [ValidateSet(0, 'NoRecovery', 1, 'Standby')]
        [object]$RestoreMode = 0,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [int]$RestoreThreshold,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [object]$SecondaryDatabase,
        [int]$ThresholdAlert = 14420,
        [switch]$ThresholdAlertEnabled,
        [string]$MonitorServer,
        [ValidateSet(0, "sqlserver", 1, "windows")]
        [object]$MonitorServerSecurityMode = 1,
        [System.Management.Automation.PSCredential]$MonitorCredential,
        [Alias('Silent')]
        [switch]$EnableException,
        [switch]$Force
    )

    # Try connecting to the instance
    try {
        $ServerSecondary = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
    } catch {
        Stop-Function -Message "Failure" -Category ConnectionError -Target $SqlInstance -ErrorRecord $_ -Continue
    }

    # Try connecting to the instance
    try {
        $ServerPrimary = Connect-SqlInstance -SqlInstance $PrimaryServer -SqlCredential $PrimarySqlCredential
    } catch {
        Stop-Function -Message "Failure" -Category ConnectionError -Target $PrimaryServer -ErrorRecord $_ -Continue
    }

    # Check if the database is present on the primary sql server
    if ($ServerPrimary.Databases.Name -notcontains $PrimaryDatabase) {
        Stop-Function -Message "Database $PrimaryDatabase is not available on instance $PrimaryServer" -Target $PrimaryServer -Continue
    }

    # Check if the database is present on the primary sql server
    if ($ServerSecondary.Databases.Name -notcontains $SecondaryDatabase) {
        Stop-Function -Message "Database $SecondaryDatabase is not available on instance $ServerSecondary" -Target $SqlInstance -Continue
    }

    # Check the restore mode
    if ($RestoreMode -notin 0, 1) {
        $RestoreMode = switch ($RestoreMode) { "NoRecovery" { 0}  "Standby" { 1 } }
        Write-Message -Message "Setting restore mode to $RestoreMode." -Level Verbose
    }

    # Check the if Threshold alert needs to be enabled
    if ($ThresholdAlertEnabled) {
        [int]$ThresholdAlertEnabled = 1
        Write-Message -Message "Setting Threshold alert to $ThresholdAlertEnabled." -Level Verbose
    } else {
        [int]$ThresholdAlertEnabled = 0
        Write-Message -Message "Setting Threshold alert to $ThresholdAlertEnabled." -Level Verbose
    }

    # Checking the option to disconnect users
    if ($DisconnectUsers) {
        [int]$DisconnectUsers = 1
        Write-Message -Message "Setting disconnect users to $DisconnectUsers." -Level Verbose
    } else {
        [int]$DisconnectUsers = 0
        Write-Message -Message "Setting disconnect users to $DisconnectUsers." -Level Verbose
    }

    # Check hte combination of the restore mode with the option to disconnect users
    if ($RestoreMode -eq 0 -and $DisconnectUsers -ne 0) {
        if ($Force) {
            [int]$DisconnectUsers = 0
            Write-Message -Message "Illegal combination of database restore mode $RestoreMode and disconnect users $DisconnectUsers. Setting it to $DisconnectUsers." -Level Warning
        } else {
            Stop-Function -Message "Illegal combination of database restore mode $RestoreMode and disconnect users $DisconnectUsers." -Target $SqlInstance -Continue
        }
    }

    # Set up the query
    $Query = "EXEC master.sys.sp_add_log_shipping_secondary_database
        @secondary_database = '$SecondaryDatabase'
        ,@primary_server = '$PrimaryServer'
        ,@primary_database = '$PrimaryDatabase'
        ,@restore_delay = $RestoreDelay
        ,@restore_all = $RestoreAll
        ,@restore_mode = $RestoreMode
        ,@disconnect_users = $DisconnectUsers
        ,@restore_threshold = $RestoreThreshold
        ,@threshold_alert = $ThresholdAlert
        ,@threshold_alert_enabled = $ThresholdAlertEnabled
        ,@history_retention_period = $HistoryRetention "


    if ($ServerSecondary.Version.Major -le 12) {
        $Query += "
        ,@ignoreremotemonitor = 1"
    }

    # Add inf extra options to the query when needed
    if ($BlockSize -ne -1) {
        $Query += ",@block_size = $BlockSize"
    }

    if ($BufferCount -ne -1) {
        $Query += ",@buffer_count = $BufferCount"
    }

    if ($MaxTransferSize -ge 1) {
        $Query += ",@max_transfer_size = $MaxTransferSize"
    }

    if ($Force -and ($ServerSecondary.Version.Major -gt 9)) {
        $Query += ",@overwrite = 1;"
    } else {
        $Query += ";"
    }

    # Execute the query to add the log shipping primary
    if ($PSCmdlet.ShouldProcess($SqlServer, ("Configuring logshipping for secondary database $SecondaryDatabase on $SqlInstance"))) {
        try {
            Write-Message -Message "Configuring logshipping for secondary database $SecondaryDatabase on $SqlInstance." -Level Verbose
            Write-Message -Message "Executing query:`n$Query" -Level Verbose
            $ServerSecondary.Query($Query)

            # For versions prior to SQL Server 2014, adding a monitor works in a different way.
            # The next section makes sure the settings are being synchronized with earlier versions
            if ($MonitorServer -and ($SqlInstance.Version.Major -lt 12)) {
                # Get the details of the primary database
                $query = "SELECT * FROM msdb.dbo.log_shipping_monitor_secondary WHERE primary_database = '$PrimaryDatabase' AND primary_server = '$PrimaryServer'"
                $lsDetails = $ServerSecondary.Query($query)

                # Setup the procedure script for adding the monitor for the primary
                $query = "EXEC msdb.dbo.sp_processlogshippingmonitorsecondary @mode = $MonitorServerSecurityMode
                    ,@secondary_server = '$SqlInstance'
                    ,@secondary_database = '$SecondaryDatabase'
                    ,@secondary_id = '$($lsDetails.secondary_id)'
                    ,@primary_server = '$($lsDetails.primary_server)'
                    ,@primary_database = '$($lsDetails.primary_database)'
                    ,@restore_threshold = $($lsDetails.restore_threshold)
                    ,@threshold_alert = $([int]$lsDetails.threshold_alert)
                    ,@threshold_alert_enabled = $([int]$lsDetails.threshold_alert_enabled)
                    ,@history_retention_period = $([int]$lsDetails.history_retention_period)
                    ,@monitor_server = '$MonitorServer'
                    ,@monitor_server_security_mode = $MonitorServerSecurityMode "

                # Check the MonitorServerSecurityMode if it's SQL Server authentication
                if ($MonitorServer -and $MonitorServerSecurityMode -eq 0 ) {
                    $query += ",@monitor_server_login = N'$MonitorLogin'
                        ,@monitor_server_password = N'$MonitorPassword' "
                }

                Write-Message -Message "Configuring monitor server for secondary database $SecondaryDatabase." -Level Verbose
                Write-Message -Message "Executing query:`n$query" -Level Verbose
                Invoke-DbaQuery -SqlInstance $MonitorServer -SqlCredential $MonitorCredential -Database msdb -Query $query

                $query = "
                UPDATE msdb.dbo.log_shipping_secondary
                SET monitor_server = '$MonitorServer', user_specified_monitor = 1
                WHERE secondary_id = '$($lsDetails.secondary_id)'
                "

                Write-Message -Message "Updating monitor information for the secondary database $Database." -Level Verbose
                Write-Message -Message "Executing query:`n$query" -Level Verbose
                $ServerSecondary.Query($query)

            }
        } catch {
            Write-Message -Message "$($_.Exception.InnerException.InnerException.InnerException.InnerException.Message)" -Level Warning
            Stop-Function -Message "Error executing the query.`n$($_.Exception.Message)`n$Query"  -ErrorRecord $_ -Target $SqlInstance -Continue
        }
    }

    Write-Message -Message "Finished adding the secondary database $SecondaryDatabase to log shipping." -Level Verbose

}
tools\dbatools\internal\functions\New-DbaLogShippingSecondaryPrimary.ps1
function New-DbaLogShippingSecondaryPrimary {
    <#
        .SYNOPSIS
            New-DbaLogShippingPrimarySecondary sets up the primary information for the primary database.

        .DESCRIPTION
            New-DbaLogShippingPrimarySecondary sets up the primary information, adds local and remote monitor links,
            and creates copy and restore jobs for the specified primary database.
            This is executed on the secondary server.

        .PARAMETER SqlInstance
            SQL Server instance. You must have sysadmin access and server version must be SQL Server version 2000 or greater.

        .PARAMETER SqlCredential
            Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)

        .PARAMETER BackupSourceDirectory
            The directory where transaction log backup files from the primary server are stored.

        .PARAMETER BackupDestinationDirectory
            The directory on the secondary server where backup files are copied to.

        .PARAMETER CopyJob
            The name to use for the SQL Server Agent job being created to copy transaction log backups to the secondary server.

        .PARAMETER CopyJobID
            The UID associated with the copy job on the secondary server.

        .PARAMETER FileRetentionPeriod
            The length of time, in minutes, that a backup file is retained on the secondary server in the path specified by the BackupDestinationDirectory parameter before being deleted.
            The default is 14420.

        .PARAMETER MonitorServer
            Is the name of the monitor server. The default is the secondary server.

        .PARAMETER MonitorServerLogin
            Is the username of the account used to access the monitor server.

        .PARAMETER MonitorServerPassword
            Is the password of the account used to access the monitor server.

        .PARAMETER MonitorServerSecurityMode
            The security mode used to connect to the monitor server. Allowed values are 0, "sqlserver", 1, "windows"
            The default is 1 or Windows.

        .PARAMETER PrimaryServer
            The name of the primary instance of the Microsoft SQL Server Database Engine in the log shipping configuration.

        .PARAMETER PrimaryDatabase
            Is the name of the database on the primary server.

        .PARAMETER RestoreJob
            Is the name of the SQL Server Agent job on the secondary server that restores the backups to the secondary database.

        .PARAMETER RestoreJobID
            The UID associated with the restore job on the secondary server.

        .PARAMETER WhatIf
            Shows what would happen if the command were to run. No actions are actually performed.

        .PARAMETER Confirm
            Prompts you for confirmation before executing any changing operations within the command.

        .PARAMETER EnableException
            By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
            This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
            Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

        .PARAMETER Force
            The force parameter will ignore some errors in the parameters and assume defaults.
            It will also remove the any present schedules with the same name for the specific job.

        .NOTES
            Author: Sander Stad (@sqlstad, sqlstad.nl)
            Website: https://dbatools.io
            Copyright: (c) 2018 by dbatools, licensed under MIT
            License: MIT https://opensource.org/licenses/MIT

        .LINK
            https://dbatools.io/New-DbaLogShippingPrimarySecondary

        .EXAMPLE
            New-DbaLogShippingSecondaryPrimary -SqlInstance sql2 -BackupSourceDirectory "\\sql1\logshipping\DB1" -BackupDestinationDirectory D:\Data\logshippingdestination\DB1_DR -CopyJob LSCopy_sql2_DB1_DR -FileRetentionPeriod 4320 -MonitorServer sql2 -MonitorServerSecurityMode 'Windows' -PrimaryServer sql1 -PrimaryDatabase DB1 -RestoreJob LSRestore_sql2_DB1_DR
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [object]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$BackupSourceDirectory,
        [string]$BackupDestinationDirectory,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$CopyJob,
        [int]$FileRetentionPeriod = 14420,
        [string]$MonitorServer,
        [PSCredential]$MonitorCredential,
        [Parameter(Mandatory)]
        [ValidateSet(0, "sqlserver", 1, "windows")]
        [object]$MonitorServerSecurityMode = 1,
        [object]$PrimaryServer,
        [PSCredential]$PrimarySqlCredential,
        [object]$PrimaryDatabase,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$RestoreJob,
        [Alias('Silent')]
        [switch]$EnableException,
        [switch]$Force
    )

    # Try connecting to the instance
    try {
        $ServerSecondary = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
    } catch {
        Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $SqlInstance -Continue
    }

    # Try connecting to the instance
    try {
        $ServerPrimary = Connect-SqlInstance -SqlInstance $PrimaryServer -SqlCredential $PrimarySqlCredential
    } catch {
        Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $PrimaryServer -Continue
    }

    # Check if the backup UNC path is correct and reachable
    if ([bool]([uri]$BackupDestinationDirectory).IsUnc -and $BackupDestinationDirectory -notmatch '^\\(?:\\[^<>:`"/\\|?*]+)+$') {
        Stop-Function -Message "The backup destination path should be formatted in the form \\server\share." -Target $SqlInstance
        return
    } else {
        if (-not ((Test-Path $BackupDestinationDirectory -PathType Container -IsValid) -and ((Get-Item $BackupDestinationDirectory).PSProvider.Name -eq 'FileSystem'))) {
            Stop-Function -Message "The backup destination path is not valid or can't be reached." -Target $SqlInstance
            return
        }
    }

    # Check the MonitorServer
    if (-not $MonitorServer -and $Force) {
        $MonitorServer = $SqlInstance
        Write-Message -Message "Setting monitor server to $MonitorServer." -Level Verbose
    }

    # Check of the MonitorServerSecurityMode value is of type string and set the integer value
    if ($MonitorServerSecurityMode -notin 0, 1) {
        $MonitorServerSecurityMode = switch ($MonitorServerSecurityMode) {"WINDOWS" { 1 } "SQLSERVER" { 0 } }
        Write-Message -Message "Setting monitor server security mode to $MonitorServerSecurityMode." -Level Verbose
    }

    # Check the MonitorServerSecurityMode if it's SQL Server authentication
    if ($MonitorServerSecurityMode -eq 0 -and -not $MonitorCredential) {
        Stop-Function -Message "The MonitorServerCredential cannot be empty when using SQL Server authentication." -Target $SqlInstance -Continue
        return
    } elseif ($MonitorServerSecurityMode -eq 0 -and $MonitorCredential) {
        # Get the username and password from the credential
        $MonitorLogin = $MonitorCredential.UserName
        $MonitorPassword = $MonitorCredential.GetNetworkCredential().Password

        # Check if the user is in the database
        if ($ServerSecondary.Databases['master'].Users.Name -notcontains $MonitorLogin) {
            Stop-Function -Message "User $MonitorLogin for monitor login must be in the master database." -Target $SqlInstance -Continue
            return
        }
    }

    # Check if the database is present on the primary sql server
    if ($ServerPrimary.Databases.Name -notcontains $PrimaryDatabase) {
        Stop-Function -Message "Database $PrimaryDatabase is not available on instance $PrimaryServer" -Target $PrimaryServer -Continue
        return
    }

    # Set up the query
    $Query = "
        DECLARE @LS_Secondary__CopyJobId AS uniqueidentifier
        DECLARE @LS_Secondary__RestoreJobId	AS uniqueidentifier
        DECLARE @LS_Secondary__SecondaryId AS uniqueidentifier
        EXEC master.sys.sp_add_log_shipping_secondary_primary
                @primary_server = N'$PrimaryServer'
                ,@primary_database = N'$PrimaryDatabase'
                ,@backup_source_directory = N'$BackupSourceDirectory'
                ,@backup_destination_directory = N'$BackupDestinationDirectory'
                ,@copy_job_name = N'$CopyJob'
                ,@restore_job_name = N'$RestoreJob'
                ,@file_retention_period = $FileRetentionPeriod
                ,@copy_job_id = @LS_Secondary__CopyJobId OUTPUT
                ,@restore_job_id = @LS_Secondary__RestoreJobId OUTPUT
                ,@secondary_id = @LS_Secondary__SecondaryId OUTPUT "

    if ($MonitorServer) {
        $Query += ",@monitor_server = N'$MonitorServer'
                ,@monitor_server_security_mode = $($MonitorServerSecurityMode) "
    }


    # Check the MonitorServerSecurityMode if it's SQL Server authentication
    if ($MonitorServerSecurityMode -eq 0 -and $MonitorServer) {
        $Query += ",@monitor_server_login = N'$MonitorLogin'
            ,@monitor_server_password = N'$MonitorPassword' "
    }

    if ($ServerSecondary.Version.Major -gt 9) {
        $Query += ",@overwrite = 1;"
    } else {
        $Query += ";"
    }

    # Execute the query to add the log shipping primary
    if ($PSCmdlet.ShouldProcess($SqlServer, ("Configuring logshipping making settings for the primary database to secondary database on $SqlInstance"))) {
        try {
            Write-Message -Message "Configuring logshipping making settings for the primary database." -Level Verbose
            Write-Message -Message "Executing query:`n$Query" -Level Verbose
            $ServerSecondary.Query($Query)
        } catch {
            Write-Message -Message "$($_.Exception.InnerException.InnerException.InnerException.InnerException.Message)" -Level Warning
            Stop-Function -Message "Error executing the query.`n$($_.Exception.Message)"  -ErrorRecord $_ -Target $SqlInstance -Continue
        }
    }

    Write-Message -Message "Finished configuring of secondary database to primary database $PrimaryDatabase." -Level Verbose
}
tools\dbatools\internal\functions\Register-RemoteSessionConfiguration.ps1
function Register-RemoteSessionConfiguration {
    <#
    .SYNOPSIS
        Registers a PSSessionConfiguration on a remote machine
    .DESCRIPTION
        Registers a session with a custom credentials on a remote machine through WinRM.
        Designed to overcome the double-hop issue and as an alternative to CredSSP protocol.
    #>
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")]
    [CmdletBinding(SupportsShouldProcess)]
    Param (
        [Parameter(Mandatory)]
        $ComputerName,
        [ValidateNotNullOrEmpty()]
        [string]$Name = "dbatools_remotesession",
        [Parameter(Mandatory)]
        [pscredential]$Credential,
        [pscredential]$RunAsCredential = $Credential
    )
    begin {

    }
    process {
        $createRunasSession = {
            Param (
                $Name,
                $user,
                $pwd
            )
            $output = [pscustomobject]@{ 'Name' = $Name; 'Status' = $null ; Successful = $false }
            $credential = New-Object System.Management.Automation.PSCredential @($user, (ConvertTo-SecureString -Force -AsPlainText $pwd))
            try {
                $existing = Get-PSSessionConfiguration -Name $Name -ErrorAction Stop 2>$null
            } catch {
                $null = 1
            }
            try {
                if ($null -eq $existing) {
                    $null = Register-PSSessionConfiguration -Name $Name -RunAsCredential $credential -ErrorAction Stop -NoServiceRestart -Confirm:$false 3>$null
                    $output.Status = 'Created'
                    $output.Successful = $true
                    return $output
                } else {
                    Set-PSSessionConfiguration -Name $Name -RunAsCredential $credential -ErrorAction Stop -NoServiceRestart -Confirm:$false 3>$null
                    $output.Status = 'Updated'
                    $output.Successful = $true
                    return $output
                }
            } catch {
                $output.Status = "Failed`: $($_.Exception.Message)"
                return $output
            }
        }
        Write-Message -Level Debug -Message "Registering new session configuration $Name on $ComputerName"
        if ($PSCmdlet.ShouldProcess($ComputerName, "Registering new session configuration $Name")) {
            try {
                $registerIt = Invoke-Command2 -ComputerName $ComputerName -Credential $Credential -ScriptBlock $createRunasSession -ArgumentList @(
                    $Name,
                    $RunAsCredential.UserName,
                    $RunAsCredential.GetNetworkCredential().Password
                ) -Raw -RequiredPSVersion 3.0 -ErrorAction Stop
            } catch {
                Stop-Function -Message "Failure during remote session configuration execution" -ErrorRecord $_ -EnableException $true
            }
        }
        if ($registerIt) {
            Write-Message -Level Debug -Message "Configuration attempt returned the following status`: $($registerIt.Status)"
            if ($registerIt.Status -in 'Updated', 'Created') {
                Write-Message -Level Verbose -Message "Restarting WinRm service on $ComputerName"
                Restart-WinRMService -ComputerName $ComputerName -Credential $Credential
            }
            return $registerIt
        }
    }
}
tools\dbatools\internal\functions\Remove-InvalidFileNameChars.ps1
Function Remove-InvalidFileNameChars {
    param(
        [Parameter(Mandatory = $true,
            Position = 0,
            ValueFromPipeline = $true,
            ValueFromPipelineByPropertyName = $true)]
        [String]$Name
    )

    $invalidChars = [IO.Path]::GetInvalidFileNameChars() -join ''
    $re = "[{0}]" -f [RegEx]::Escape($invalidChars)
    return ($Name -replace $re)
}
tools\dbatools\internal\functions\Resolve-IpAddress.ps1
function Resolve-IpAddress {
    # Uses the Beard's method to resolve IPs
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [Alias("ServerInstance", "SqlInstance", "ComputerName", "SqlServer")]
        [object]$Server
    )
    $ping = New-Object System.Net.NetworkInformation.Ping
    $timeout = 1000 #milliseconds
    if ($Server.GetType() -eq [Microsoft.SqlServer.Management.Smo.Server]) {
        return $ping.Send($Server.ComputerName, $timeout).Address.IPAddressToString
    } else {
        return $ping.Send($server.Split('\')[0], $timeout).Address.IPAddressToString
    }
}
tools\dbatools\internal\functions\Resolve-NetBiosName.ps1
function Resolve-NetBiosName {
    <#
.SYNOPSIS
Internal function. Takes a best guess at the NetBIOS name of a server.
    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [object]$SqlInstance,
        [PSCredential]$SqlCredential
    )
    $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
    $server.ComputerName
}
tools\dbatools\internal\functions\Resolve-SqlIpAddress.ps1
function Resolve-SqlIpAddress {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [object]$SqlInstance,
        [PSCredential]$SqlCredential
    )

    $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
    $servernetbios = $server.ComputerNamePhysicalNetBIOS
    $ipaddr = (Resolve-DbaNetworkName -ComputerName $servernetbios -Turbo).IPAddress
    return $ipaddr
}
tools\dbatools\internal\functions\Restart-WinRMService.ps1
function Restart-WinRMService {
    <#
    .SYNOPSIS
        Restarts WinRM service on a remote machine and waits for it to get back up
    .DESCRIPTION
        Restarts WinRM service on a remote machine and waits for it to get back up by attempting to establish a WinRM session.
    #>

    [CmdletBinding(SupportsShouldProcess)]
    Param (
        [Parameter(Mandatory)]
        $ComputerName,
        [pscredential]$Credential,
        [int]$Timeout = 30
    )
    begin {

    }
    process {
        if ($PSCmdlet.ShouldProcess($ComputerName, "Restarting WinRm service")) {
            $restartService = {
                $null = Get-Service -Name WinRM -ErrorAction Stop | Restart-Service -ErrorAction Stop
            }
            try {
                $null = Invoke-Command2 -ComputerName $ComputerName -Credential $Credential -ScriptBlock $restartService -Raw -ErrorAction Stop
            } catch [System.Management.Automation.Remoting.PSRemotingTransportException] {
                Write-Message -Level Debug "Expected exception - the pipe was disconnected | $($_.Exception.Message)"
            } catch {
                Write-Message -Level Warning "Failed to restart WinRM service on $ComputerName"
            }
            Write-Message -Level Debug "Removing existing local sessions to $ComputerName - they are no longer valid"
            $runspaceId = [System.Management.Automation.Runspaces.Runspace]::DefaultRunspace.InstanceId
            # Retrieve a session from the session cache, if available (it's unique per runspace)
            [array]$currentSessions = [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::PSSessionGet($runspaceId, $ComputerName)
            Write-Message -Level Debug -Message "Removing $($currentSessions.Count) sessions from $ComputerName in runspace $runspaceId"
            $currentSessions | Remove-PSSession
            Write-Message -Level Debug "Waiting for the WinRM service to restart on $ComputerName"
            $waitCounter = 0
            while ($waitCounter -lt $Timeout * 5) {
                try {
                    $available = Invoke-Command2 -ComputerName $ComputerName -Credential $Credential -ScriptBlock { $true } -Raw -ErrorAction Stop
                } catch {
                    Write-Message -Level Debug -Message "Still waiting for the WinRM service to restart on $ComputerName"
                }
                if ($available) { break }
                Start-Sleep -Milliseconds 200
                $waitCounter++
            }
        }
        Write-Message -Level Debug -Message "WinRM restart comlete on $ComputerName"
    }
}
tools\dbatools\internal\functions\runspaces\Get-DbaRunspace.ps1
function Get-DbaRunspace {
    <#
    .SYNOPSIS
        Returns registered runspaces.

    .DESCRIPTION
        Returns a list of runspaces that have been registered with dbatools

    .PARAMETER Name
        Default: "*"
        Only registered runspaces of similar names are returned.

    .EXAMPLE
        PS C:\> Get-DbaRunspace

        Returns all registered runspaces

    .EXAMPLE
        PS C:\> Get-DbaRunspace -Name 'mymodule.maintenance'

        Returns the runspace registered under the name 'mymodule.maintenance'
    #>
    [CmdletBinding()]
    param (
        [string]
        $Name = "*"
    )

    [Sqlcollaborative.Dbatools.Runspace.RunspaceHost]::Runspaces.Values | Where-Object Name -Like $Name
}
tools\dbatools\internal\functions\runspaces\Register-DbaMaintenanceTask.ps1
function Register-DbaMaintenanceTask {
    <#
        .SYNOPSIS
            Allows scheduling maintenance tasks, that are perfomed in the background.

        .DESCRIPTION
            Allows scheduling maintenance tasks, that are perfomed in the background.

            All scriptblocks scheduled like this will be performed on a separate runspace and have access to all internal dbatools commands.
            None of the scriptblocks will affect the main session (so you cannot manipulate variables, etc.)

        .PARAMETER Name
            The name of the task.
            Must be unique, otherwise it will update the existing task.

        .PARAMETER ScriptBlock
            The task/scriptblock that should be performed as part of the maintenance.
            It will have all of dbatools including internal commands available.

        .PARAMETER Once
            Whether the interval should be performed only once.

        .PARAMETER Interval
            The interval at which the task should be repeated.

        .PARAMETER Delay
            How far after the initial registration should the maintenance script wait before processing this.
            This can be used to delay background stuff that should not content with items that would be good to have as part of the module import.
            Some library specific items can be moved to maintenance if their processing would take too much time on original import, even if it is desirable to have them available as soon as possible.

        .PARAMETER Priority
            How important is this task?
            If multiple tasks are due at the same maintenance cycle, the more critical one will be processed first.

        .PARAMETER EnableException
            By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
            This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
            Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

        .EXAMPLE
            PS C:\> Register-DbaMaintenanceTask -Name 'value1' -ScriptBlock $ScriptBlock -Once
       #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]
        $Name,

        [Parameter(Mandatory)]
        [System.Management.Automation.ScriptBlock]
        $ScriptBlock,

        [Parameter(Mandatory, ParameterSetName = "Once")]
        [switch]
        $Once,

        [Parameter(Mandatory, ParameterSetName = "Repeating")]
        [System.TimeSpan]
        $Interval,

        [System.TimeSpan]
        $Delay,

        [Sqlcollaborative.Dbatools.Maintenance.MaintenancePriority]
        $Priority = "Medium",

        [switch]
        [Alias('Silent')]$EnableException
    )

    #region Case: Task already registered
    if ([Sqlcollaborative.Dbatools.Maintenance.MaintenanceHost]::Tasks.ContainsKey($Name.ToLower())) {
        $task = [Sqlcollaborative.Dbatools.Maintenance.MaintenanceHost]::Tasks[$Name.ToLower()]
        if ($task.ScriptBlock -ne $ScriptBlock) { $task.ScriptBlock = $ScriptBlock }
        if (Test-Bound -ParameterName Once) { $task.Once = $Once }
        if (Test-Bound -ParameterName Interval) {
            $task.Once = $false
            $task.Interval = $Interval
        }
        if (Test-Bound -ParameterName Delay) { $task.Delay = $Delay }
        if (Test-Bound -ParameterName Priority) { $task.Priority = $Priority }
    }
    #endregion Case: Task already registered

    #region New Task
    else {
        $task = New-Object Sqlcollaborative.Dbatools.Maintenance.MaintenanceTask
        $task.Name = $Name.ToLower()
        $task.ScriptBlock = $ScriptBlock
        if (Test-Bound -ParameterName Once) { $task.Once = $true }
        if (Test-Bound -ParameterName Interval) {
            if ($Interval.Ticks -le 0) {
                Stop-Function -Message "Failed to register task: $Name - Interval cannot be 0 or less" -Category InvalidArgument
                return
            } else { $task.Interval = $Interval }
        }
        if (Test-Bound -ParameterName Delay) { $task.Delay = $Delay }
        $task.Priority = $Priority
        $task.Registered = Get-Date
        [Sqlcollaborative.Dbatools.Maintenance.MaintenanceHost]::Tasks[$Name.ToLower()] = $task
    }
    #endregion New Task
}
tools\dbatools\internal\functions\runspaces\Register-DbaRunspace.ps1
function Register-DbaRunspace {
    <#
    .SYNOPSIS
        Registers a scriptblock to run in the background.

    .DESCRIPTION
        This function registers a scriptblock to run in separate runspace.
        This is different from most runspace solutions, in that it is designed for permanent background tasks that need to be done.
        It guarantees a single copy of the task to run within the powershell process, even when running the same module in many runspaces in parallel.

        Updating:
        If this function is called multiple times, targeting the same name, it will update the scriptblock.
        - If that scriptblock is the same as the previous scriptblock, nothing changes
        - If that scriptblock is different from the previous ones, it will be registered, but will not be executed right away!
          Only after stopping and starting the runspace will it operate under the new scriptblock.

    .PARAMETER ScriptBlock
        The scriptblock to run in a dedicated runspace

    .PARAMETER Name
        The name to register the scriptblock under.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .EXAMPLE
        PS C:\> Register-DbaRunspace -ScriptBlock $scriptBlock -Name 'mymodule.maintenance'

        Registers the script defined in $scriptBlock under the name 'mymodule.maintenance'
        It does not start the runspace yet. If it already exists, it will overwrite the scriptblock without affecting the running script.

    .EXAMPLE
        PS C:\> Register-DbaRunspace -ScriptBlock $scriptBlock -Name 'mymodule.maintenance'
        PS C:\> Start-DbaRunspace -Name 'mymodule.maintenance'

        Registers the script defined in $scriptBlock under the name 'mymodule.maintenance'
        Then it starts the runspace, running the registered $scriptBlock
    #>
    [CmdletBinding(PositionalBinding = $false)]
    param
    (
        [Parameter(Mandatory)]
        [Scriptblock]
        $ScriptBlock,

        [Parameter(Mandatory)]
        [String]
        $Name,

        [switch]
        [Alias('Silent')]
        $EnableException
    )

    if ([Sqlcollaborative.Dbatools.Runspace.RunspaceHost]::Runspaces.ContainsKey($Name.ToLower())) {
        Write-Message -Level Verbose -Message "Updating runspace: $($Name.ToLower())" -Target $Name.ToLower()
        [Sqlcollaborative.Dbatools.Runspace.RunspaceHost]::Runspaces[$Name.ToLower()].SetScript($ScriptBlock)
    } else {
        Write-Message -Level Verbose -Message "Registering runspace: $($Name.ToLower())" -Target $Name.ToLower()
        [Sqlcollaborative.Dbatools.Runspace.RunspaceHost]::Runspaces[$Name.ToLower()] = New-Object Sqlcollaborative.Dbatools.Runspace.RunspaceContainer($Name.ToLower(), $ScriptBlock)
    }
}
tools\dbatools\internal\functions\runspaces\Start-DbaRunspace.ps1
function Start-DbaRunspace {
    <#
    .SYNOPSIS
        Starts a managed runspace

    .DESCRIPTION
        Starts a runspace that was registered to dbatools
        Simply registering does not automatically start a given runspace. Only by executing this function will it take effect.

    .PARAMETER Name
        The name of the registered runspace to launch

    .PARAMETER Runspace
        The runspace to launch. Returned by Get-DbaRunspace

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .EXAMPLE
        PS C:\> Start-DbaRunspace -Name 'mymodule.maintenance'

        Starts the runspace registered under the name 'mymodule.maintenance'
    #>
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [string[]]
        $Name,

        [Parameter(ValueFromPipeline)]
        [Sqlcollaborative.Dbatools.Runspace.RunspaceContainer[]]
        $Runspace,

        [switch]
        [Alias('Silent')]$EnableException
    )

    process {
        foreach ($item in $Name) {
            # Ignore all output from Get-DbaRunspace - it'll be handled by the second loop
            if ($item -eq "Sqlcollaborative.Dbatools.Runspace.runspacecontainer") { continue }

            if ([Sqlcollaborative.Dbatools.Runspace.RunspaceHost]::Runspaces.ContainsKey($item.ToLower())) {
                try {
                    Write-Message -Level Verbose -Message "Starting runspace: $($item.ToLower())" -Target $item.ToLower()
                    [Sqlcollaborative.Dbatools.Runspace.RunspaceHost]::Runspaces[$item.ToLower()].Start()
                } catch {
                    Stop-Function -Message "Failed to start runspace: $($item.ToLower())" -EnableException $EnableException -Target $item.ToLower() -Continue
                }
            } else {
                Stop-Function -Message "Failed to start runspace: $($item.ToLower()) | No runspace registered under this name!" -EnableException $EnableException -Category InvalidArgument -Tag "fail", "argument", "runspace", "start" -Target $item.ToLower() -Continue
            }
        }

        foreach ($item in $Runspace) {
            try {
                Write-Message -Level Verbose -Message "Starting runspace: $($item.Name.ToLower())" -Target $item
                $item.Start()
            } catch {
                Stop-Function -Message "Failed to start runspace: $($item.Name.ToLower())" -EnableException $EnableException -Target $item -Continue
            }
        }
    }
}
tools\dbatools\internal\functions\runspaces\Stop-DbaRunspace.ps1
function Stop-DbaRunspace {
    <#
    .SYNOPSIS
        Stops a managed runspace

    .DESCRIPTION
        Stops a runspace that was registered to dbatools.
        Will not cause errors if the runspace is already halted.

        Runspaces may not automatically terminate immediately when calling this function.
        Depending on the implementation of the scriptblock, this may in fact take a little time.
        If the scriptblock hasn't finished and terminated the runspace in a seemingly time, it will be killed by the system.
        This timeout is by default 30 seconds, but can be altered by using the Configuration System.
        For example, this line will increase the timeout to 60 seconds:
        Set-DbatoolsConfig Runspace.StopTimeout 60

    .PARAMETER Name
        The name of the registered runspace to stop

    .PARAMETER Runspace
        The runspace to stop. Returned by Get-DbaRunspace

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .EXAMPLE
        PS C:\> Stop-DbaRunspace -Name 'mymodule.maintenance'

        Stops the runspace registered under the name 'mymodule.maintenance'
    #>
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [string[]]
        $Name,

        [Parameter(ValueFromPipeline)]
        [Sqlcollaborative.Dbatools.Runspace.RunspaceContainer[]]
        $Runspace,

        [switch]
        [Alias('Silent')]$EnableException
    )

    process {
        foreach ($item in $Name) {
            # Ignore all output from Get-DbaRunspace - it'll be handled by the second loop
            if ($item -eq "Sqlcollaborative.Dbatools.Runspace.runspacecontainer") { continue }

            if ([Sqlcollaborative.Dbatools.Runspace.RunspaceHost]::Runspaces.ContainsKey($item.ToLower())) {
                try {
                    Write-Message -Level Verbose -Message "Stopping runspace: $($item.ToLower())" -Target $item.ToLower()
                    [Sqlcollaborative.Dbatools.Runspace.RunspaceHost]::Runspaces[$item.ToLower()].Stop()
                } catch {
                    Stop-Function -Message "Failed to stop runspace: $($item.ToLower())" -EnableException $EnableException -Target $item.ToLower() -Continue
                }
            } else {
                Stop-Function -Message "Failed to stop runspace: $($item.ToLower()) | No runspace registered under this name!" -EnableException $EnableException -Category InvalidArgument -Target $item.ToLower() -Continue
            }
        }

        foreach ($item in $Runspace) {
            try {
                Write-Message -Level Verbose -Message "Stopping runspace: $($item.Name.ToLower())" -Target $item
                $item.Stop()
            } catch {
                Stop-Function -Message "Failed to stop runspace: $($item.Name.ToLower())" -EnableException $EnableException -Target $item -Continue
            }
        }
    }
}
tools\dbatools\internal\functions\Select-DefaultView.ps1
function Select-DefaultView {
    <#

    This command enables us to send full on objects to the pipeline without the user seeing it

    See it in action in Get-DbaDbSnapshot and Remove-DbaDbSnapshot

    a lot of this is from boe, thanks boe!
    https://learn-powershell.net/2013/08/03/quick-hits-set-the-default-property-display-in-powershell-on-custom-objects/

    TypeName creates a new type so that we can use ps1xml to modify the output
       #>

    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [object]
        $InputObject,

        [string[]]
        $Property,

        [string[]]
        $ExcludeProperty,

        [string]
        $TypeName
    )
    process {

        if ($null -eq $InputObject) { return }

        if ($TypeName) {
            $InputObject.PSObject.TypeNames.Insert(0, "dbatools.$TypeName")
        }

        if ($ExcludeProperty) {
            if ($InputObject.GetType().Name.ToString() -eq 'DataRow') {
                $ExcludeProperty += 'Item', 'RowError', 'RowState', 'Table', 'ItemArray', 'HasErrors'
            }

            $props = ($InputObject | Get-Member | Where-Object MemberType -in 'Property', 'NoteProperty', 'AliasProperty' | Where-Object { $_.Name -notin $ExcludeProperty }).Name
            $defaultset = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet', [string[]]$props)
        } else {
            # property needs to be string
            if ("$property" -like "* as *") {
                $newproperty = @()
                foreach ($p in $property) {
                    if ($p -like "* as *") {
                        $old, $new = $p -isplit " as "
                        # Do not be tempted to not pipe here
                        $inputobject | Add-Member -Force -MemberType AliasProperty -Name $new -Value $old -ErrorAction SilentlyContinue
                        $newproperty += $new
                    } else {
                        $newproperty += $p
                    }
                }
                $property = $newproperty
            }
            $defaultset = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet', [string[]]$Property)
        }

        $standardmembers = [System.Management.Automation.PSMemberInfo[]]@($defaultset)

        # Do not be tempted to not pipe here
        $inputobject | Add-Member -Force -MemberType MemberSet -Name PSStandardMembers -Value $standardmembers -ErrorAction SilentlyContinue

        $inputobject
    }
}
tools\dbatools\internal\functions\Set-ServiceStartMode.ps1
function Set-ServiceStartMode {
    <#
        .SYNOPSIS
        Internal function. Implements the method that changes startup mode of the SQL Server service.

        .DESCRIPTION
        Accepts objects from Get-DbaService and performs a corresponding action.

        .PARAMETER InputObject
        A collection of services from Get-DbaService.

        .PARAMETER Mode
        Startup mode of the service: Automatic, Manual or Disabled.

        .PARAMETER WhatIf
        Shows what would happen if the cmdlet runs. The cmdlet is not run.

        .PARAMETER Confirm
        Prompts you for confirmation before running the cmdlet.

        .NOTES
        Author: Kirill Kravtsov ( @nvarscar )

        dbatools PowerShell module (https://dbatools.io)
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        .EXAMPLE
        Get-DbaService -ComputerName sql1 | Set-ServiceStartMode -Mode 'Manual'

        Sets all SQL services on sql1 to Manual startup.

        .EXAMPLE
        $services = Get-DbaService -ComputerName sql1
        Set-ServiceStartMode -InputObject $services -Mode 'Automatic'

        Sets all SQL services on sql1 to Automatic startup.

    #>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [string]$Mode,
        [parameter(ValueFromPipeline, Mandatory)]
        [object[]]$InputObject
    )
    begin {
        $callStack = Get-PSCallStack
        if ($callStack.Length -gt 1) {
            $callerName = $callStack[1].Command
        } else {
            $callerName = $callStack[0].Command
        }
        $ProcessArray = @()
    }
    process {
        #Get all the objects from the pipeline before proceeding
        $ProcessArray += $InputObject
    }
    end {
        foreach ($service in $ProcessArray) {
            #Get WMI object
            $Wmi = Get-DbaCmObject -ComputerName $service.ComputerName -Namespace "root\cimv2" -Query "SELECT * FROM Win32_Service WHERE Name = '$($service.ServiceName)'" -EnableException
            if ($Pscmdlet.ShouldProcess($Wmi, "Changing the Start Mode to $Mode")) {
                $x = $Wmi | Invoke-CimMethod -MethodName ChangeStartMode -Arguments @{ StartMode = $Mode }
                if ($x.ReturnValue -ne 0) {
                    Stop-Function -EnableException $EnableException -Message ("The attempt to change the start mode of $($service.ServiceName) on $($service.ComputerName) returned the following message: " + (Get-DbaServiceErrorMessage $x.ReturnValue))
                    return
                }
            }
        }
    }
}
tools\dbatools\internal\functions\Set-WmiFilestreamSetting.ps1
function Set-FileSystemSetting {
    # not available in SQL WMI
    [CmdletBinding()]
    param (
        [DbaInstance]$Instance,
        [PSCredential]$Credential,
        [string]$ShareName,
        [int]$FilestreamLevel
    )
    begin {
        function Get-WmiFilestreamReturnValue {
            [CmdletBinding()]
            param (
                [object]$Value
            )
            switch ($Value) {
                2147217396 {
                    "Filestream not supported on instance"
                }
                2147217386 {
                    "Filestream cannot change share"
                }
                2147024713 {
                    "Duplicate sharename"
                }
                2147024891 {
                    "Access denied"
                }
                2147023681 {
                    "Invalid sharename"
                }
                2147024690 {
                    "Sharename too long"
                }
                2147019889 {
                    "Primary node not enabled "
                }
                2147019848 {
                    "Sharename node mismatch"
                }
                214721740 {
                    "General error"
                }
                { 2147021885 -or 2147945411 -or 0 } {
                    "The requested operation is successful. Changes will not be effective until the service is restarted."
                }
                default {
                    $return.ReturnValue
                }
            }
        }

        function Get-WmiFilestreamSetting {
            # not available in SQL WMI
            [CmdletBinding()]
            param (
                [DbaInstance]$Instance,
                [PSCredential]$Credential
            )

            $computer = $computerName = $Machine = $instance.ComputerName
            $instanceName = $instance.InstanceName

            Write-Message -Level Verbose -Message "Attempting to connect to $computer's WMI"
            $ognamespace = Get-DbaCmObject -EnableException -ComputerName $computerName -Namespace root\Microsoft\SQLServer -Query "SELECT NAME FROM __NAMESPACE WHERE NAME LIKE 'ComputerManagement%'"
            $namespace = $ognamespace | Where-Object {
                (Get-DbaCmObject -EnableException -ComputerName $computerName -Namespace $("root\Microsoft\SQLServer\" + $_.Name) -ClassName FilestreamSettings).Count -gt 0
            } |
                Sort-Object Name -Descending | Select-Object -First 1

            if (-not $namespace) {
                $namespace = $ognamespace
            }

            if ($namespace.Name) {
                if ($Credential) {
                    $wmi = Get-WmiObject -Credential $Credential -ErrorAction Stop -ComputerName $computerName -Namespace $("root\Microsoft\SQLServer\" + $namespace.Name) -Class FilestreamSettings | Where-Object InstanceName -eq $instanceName | Select-Object -First 1
                } else {
                    $wmi = Get-WmiObject -ErrorAction Stop -ComputerName $computerName -Namespace $("root\Microsoft\SQLServer\" + $namespace.Name) -Class FilestreamSettings | Where-Object InstanceName -eq $instanceName | Select-Object -First 1
                }
            }
            $wmi
        }
    }
    process {
        # Server level
        if ($Force -or $PSCmdlet.ShouldProcess($instance, "Enabling filestream")) {
            try {
                $wmi = Get-WmiFilestreamSetting -Instance $instance -ErrorAction Stop
                if ($ShareName) {
                    $null = $wmi.ShareName = $ShareName
                }
                $return = $wmi.EnableFilestream($FileStreamLevel, $instance.InstanceName)
                $returnvalue = Get-WmiFilestreamReturnValue -Value $return.ReturnValue
            } catch {
                Stop-Function -Message "Failure" -ErrorRecord $_ -Continue
            }
        }
        $returnvalue
    }
}
tools\dbatools\internal\functions\Show-Notification.ps1
function Show-Notification {
    param(
        $GalleryVersion,
        $Title = "dbatools update",
        $Text = "Version $GalleryVersion is now available"
    )
    # ensure the dbatools 'app' exists in registry so that it doesn't immediately disappear from Action Center
    $regPath = 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings'
    $appId = "{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\WindowsPowerShell\v1.0\powershell.exe"

    if (!(Test-Path -Path "$regPath\$appId")) {
        Write-Verbose "Adding required registry entry at $("$regPath\$appId")"
        $null = New-Item -Path "$regPath\$appId" -Force
        $null = New-ItemProperty -Path "$regPath\$appId" -Name 'ShowInActionCenter' -Value 1 -PropertyType 'DWORD' -Force
    }
    $null = [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]
    $template = [Windows.UI.Notifications.ToastTemplateType]::ToastImageAndText02
    [xml]$toastTemplate = ([Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent($template).GetXml())

    [xml]$toastTemplate = "
    <toast launch=`"app-defined-string`">
        <visual>
            <binding template=`"ToastGeneric`">
                <text>`"$Title`"</text>
                <text>`"$Text`"</text>
            </binding>
        </visual>
        <actions>
            <action activationType=`"background`" content=`"OK`" arguments=`"later`"/>
        </actions>
    </toast>"

    $toastXml = New-Object -TypeName Windows.Data.Xml.Dom.XmlDocument
    $toastXml.LoadXml($toastTemplate.OuterXml)

    $notify = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($appId)
    $notify.Show($toastXml)
}
tools\dbatools\internal\functions\Start-DbccCheck.ps1
function Start-DbccCheck {
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [object]$server,
        [string]$dbname,
        [switch]$table
    )

    $servername = $server.name

    if ($Pscmdlet.ShouldProcess($sourceserver, "Running dbcc check on $dbname on $servername")) {
        if ($server.ConnectionContext.StatementTimeout = 0 -ne 0) {
            $server.ConnectionContext.StatementTimeout = 0
        }

        try {
            if ($table) {
                $null = $server.databases[$dbname].CheckTables('None')
                Write-Verbose "Dbcc CheckTables finished successfully for $dbname on $servername"
            } else {
                $null = $server.Query("DBCC CHECKDB ([$dbname])")
                Write-Verbose "Dbcc CHECKDB finished successfully for $dbname on $servername"
            }
            return "Success"
        } catch {
            $message = $_.Exception
            if ($null -ne $_.Exception.InnerException) { $message = $_.Exception.InnerException }

            # english cleanup only sorry
            try {
                $newmessage = ($message -split "at Microsoft.SqlServer.Management.Common.ConnectionManager.ExecuteTSql")[0]
                $newmessage = ($newmessage -split "Microsoft.SqlServer.Management.Common.ExecutionFailureException:")[1]
                $newmessage = ($newmessage -replace "An exception occurred while executing a Transact-SQL statement or batch. ---> System.Data.SqlClient.SqlException:").Trim()
                $message = $newmessage
            } catch {
                $null
            }
            return $message.Trim()
        }
    }
}
tools\dbatools\internal\functions\tabcompletion\New-DbaTeppCompletionResult.ps1
function global:New-DbaTeppCompletionResult {
    <#
        .SYNOPSIS
            Generates a completion result for dbatools internal tab completion.

        .DESCRIPTION
            Generates a completion result for dbatools internal tab completion.

        .PARAMETER CompletionText
            The text to propose.

        .PARAMETER ToolTip
            The tooltip to show in tooltip-aware hosts (ISE, mostly)

        .PARAMETER ListItemText
            ???

        .PARAMETER CompletionResultType
            The type of object that is being completed.
            By default it generates one of type paramter value.

        .PARAMETER NoQuotes
            Whether to put the result in quotes or not.

        .EXAMPLE
            New-DbaTeppCompletionResult -CompletionText 'master' -ToolTip 'master'

            Returns a CompletionResult with the text and tooltip 'master'
    #>
    param (
        [Parameter(Position = 0, ValueFromPipelineByPropertyName = $true, Mandatory, ValueFromPipeline)]
        [ValidateNotNullOrEmpty()]
        [string]
        $CompletionText,

        [Parameter(Position = 1, ValueFromPipelineByPropertyName = $true)]
        [string]
        $ToolTip,

        [Parameter(Position = 2, ValueFromPipelineByPropertyName = $true)]
        [string]
        $ListItemText,

        [System.Management.Automation.CompletionResultType]
        $CompletionResultType = [System.Management.Automation.CompletionResultType]::ParameterValue,

        [switch]
        $NoQuotes = $false
    )

    process {
        $toolTipToUse = if ($ToolTip -eq '') { $CompletionText }
        else { $ToolTip }
        $listItemToUse = if ($ListItemText -eq '') { $CompletionText }
        else { $ListItemText }

        # If the caller explicitly requests that quotes
        # not be included, via the -NoQuotes parameter,
        # then skip adding quotes.

        if ($CompletionResultType -eq [System.Management.Automation.CompletionResultType]::ParameterValue -and -not $NoQuotes) {
            # Add single quotes for the caller in case they are needed.
            # We use the parser to robustly determine how it will treat
            # the argument.  If we end up with too many tokens, or if
            # the parser found something expandable in the results, we
            # know quotes are needed.

            $tokens = $null
            $null = [System.Management.Automation.Language.Parser]::ParseInput("echo $CompletionText", [ref]$tokens, [ref]$null)
            if ($tokens.Length -ne 3 -or ($tokens[1] -is [System.Management.Automation.Language.StringExpandableToken] -and $tokens[1].Kind -eq [System.Management.Automation.Language.TokenKind]::Generic)) {
                $CompletionText = "'$CompletionText'"
            }
        }
        return New-Object System.Management.Automation.CompletionResult($CompletionText, $listItemToUse, $CompletionResultType, $toolTipToUse.Trim())
    }
}

(Get-Item Function:\New-DbaTeppCompletionResult).Visibility = "Private"
tools\dbatools\internal\functions\tabcompletion\Register-DbaTeppArgumentCompleter.ps1
function Register-DbaTeppArgumentCompleter {
    <#
        .SYNOPSIS
            Registers a parameter for a prestored Tepp.

        .DESCRIPTION
            Registers a parameter for a prestored Tepp.
            This function allows easily registering a function's parameter for Tepp in the function-file, rather than in a centralized location.

        .PARAMETER Command
            Name of the command whose parameter should receive Tepp.
            Supports multiple commands at the same time in order to optimize performance.

        .PARAMETER Parameter
            Name of the parameter that should be Tepp'ed.

        .PARAMETER Name
            Name of the Tepp Completioner to use.
            Defaults to the parameter name.
            Best practice requires a Completioner to be named the same as the completed parameter, in which case this parameter needs not be specified.
            However sometimes that may not be universally possible, which is when this parameter comes in.

        .PARAMETER All
            Whether this TEPP applies to all commands in dbatools that have the specified parameter.

        .EXAMPLE
            Register-DbaTeppArgumentCompleter -Command Get-DbaBackupHistory -Parameter Database

            Registers the "Database" parameter of the Get-DbaBackupHistory to receive Database-Tepp
       #>
    [CmdletBinding()]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingEmptyCatchBlock", "")]
    param (
        [string[]]$Command,
        [string[]]$Parameter,
        [string]$Name,
        [switch]$All
    )

    #region ScriptBlock
    $scriptBlock = {
        param (
            $commandName,
            $parameterName,
            $wordToComplete,
            $commandAst,
            $fakeBoundParameter
        )

        if ($teppScript = [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::GetTeppScript($commandName, $parameterName)) {
            $start = Get-Date
            $teppScript.LastExecution = $start
            $teppScript.LastDuration = New-Object System.TimeSpan(-1) # Null it, just in case. It's a new start.

            try { $ExecutionContext.InvokeCommand.InvokeScript($true, ([System.Management.Automation.ScriptBlock]::Create($teppScript.ScriptBlock.ToString())), $null, @($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)) }
            catch { }

            $teppScript.LastDuration = (Get-Date) - $start
        }
    }
    #endregion ScriptBlock

    foreach ($p in $Parameter) {
        $lowername = $PSBoundParameters.Name

        if ($null -eq $lowername) {
            $lowername = $p.ToLower()
        } else {
            $lowername = $lowername.ToLower()
        }

        if ($All) { [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::AddTabCompletionSet("*", $p, $lowername) }
        else {
            foreach ($c in $Command) {
                [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::AddTabCompletionSet($c, $p, $lowername)
            }
        }

        if ($script:TEPP) {
            TabExpansionPlusPlus\Register-ArgumentCompleter -CommandName $Command -ParameterName $p -ScriptBlock $scriptBlock
        } else {
            Register-ArgumentCompleter -CommandName $Command -ParameterName $p -ScriptBlock $scriptBlock
        }
    }
}
tools\dbatools\internal\functions\tabcompletion\Register-DbaTeppInstanceCacheBuilder.ps1
function Register-DbaTeppInstanceCacheBuilder {
    <#
        .SYNOPSIS
            Registers a scriptblock used to build the TEPP cache from an instance connection.

        .DESCRIPTION
            Registers a scriptblock used to build the TEPP cache from an instance connection.
            Used only on import of the module.

        .PARAMETER ScriptBlock
            The ScriptBlock used to build the cache.

            The ScriptBlock may assume the following two variables to exist:
            - $FullSmoName (A string containing the full SMO name as presented by the DbaInstanceParameter class-interpreted input)
            - $server (An SMO connection object)

        .PARAMETER Slow
            This switch implies a gathering process that takes too much time to be performed synchronously.
            Basically, when retrieving the information takes more than 25ms on an average server (on top of establishing the original connection), this switch should be set.

        .EXAMPLE
            Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock

            Registers the scriptblock stored in the aptly named variable $ScriptBlock as a fest cache building scriptblock.
            Note: The scriptblock must execute swiftly! (less than 25ms)

        .EXAMPLE
            Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock -Slow

            Registers the scriptblock stored in the aptly named variable $ScriptBlock as a slow cache building scriptblock.
            This is suitable for cache building scriptblocks that take a while to execute.

        .NOTES
            Additional information about the function.
       #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [System.Management.Automation.ScriptBlock]
        $ScriptBlock,

        [switch]
        $Slow
    )

    if ($Slow -and ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppGatherScriptsSlow -notcontains $ScriptBlock)) {
        [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppGatherScriptsSlow.Add($ScriptBlock)
    } elseif ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppGatherScriptsFast -notcontains $ScriptBlock) {
        [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppGatherScriptsFast.Add($ScriptBlock)
    }
}
tools\dbatools\internal\functions\tabcompletion\Register-DbaTeppScriptBlock.ps1
function Register-DbaTeppScriptblock {
    <#
        .SYNOPSIS
            Registers a scriptblock under name, to later be available for TabExpansion.

        .DESCRIPTION
            Registers a scriptblock under name, to later be available for TabExpansion.

        .PARAMETER ScriptBlock
            The scriptblock to register.

        .PARAMETER Name
            The name under which the scriptblock should be registered.

        .EXAMPLE
            Register-DbaTeppScriptblock -ScriptBlock $scriptBlock -Name MyFirstTeppScriptBlock

            Stores the scriptblock stored in $scriptBlock under the name "MyFirstTeppScriptBlock"
       #>
    [CmdletBinding()]
    param (
        [System.Management.Automation.ScriptBlock]
        $ScriptBlock,

        [string]
        $Name
    )

    $scp = New-Object Sqlcollaborative.Dbatools.TabExpansion.ScriptContainer
    $scp.Name = $Name.ToLower()
    $scp.ScriptBlock = $ScriptBlock
    $scp.LastDuration = New-TimeSpan -Seconds -1

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Scripts[$Name.ToLower()] = $scp
}
tools\dbatools\internal\functions\Test-ComputerTarget.ps1
function Test-ComputerTarget {
    <#
    .SYNOPSIS
        Validates whether the input string can be legally used to target a computer.

    .DESCRIPTION
        Validates whether the input string can be legally used to target a computer.
        It will consider:
        - Names (NETBIOS/dns)
        - IPv4 Addresses
        - IPv6 Addresses
        It will resolve idn names into default ascii names according to the official rules, before rendering judgement.

    .PARAMETER ComputerName
        The name to verify

    .EXAMPLE
        PS C:\> Test-ComputerTarget -ComputerName 'server1'

        Will test whether 'server1' is a legal computername (hint: it is)

    .EXAMPLE
        PS C:\> "foo", "bar", "foo bar" | Test-ComputerTarget

        Will test, whether the names passed to it are legal targets.
        - The first two will pass, the last one will fail
        - Note that it will only return boolean values, so the order needs to be remembered (due to this, using it by pipeline on more than one object is not really recommended).
    #>
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline, Mandatory)]
        [string[]]
        $ComputerName
    )

    process {
        foreach ($Computer in $ComputerName) {
            [Sqlcollaborative.Dbatools.Utility.Validation]::IsValidComputerTarget($ComputerName)
        }
    }
}
tools\dbatools\internal\functions\Test-DbaLsnChain.ps1
function Test-DbaLsnChain {
    <#
    .SYNOPSIS
        Checks that a filtered array from Get-FilteredRestore contains a restorabel chain of LSNs

    .DESCRIPTION
        Finds the anchoring Full backup (or multiple if it's a striped set).
        Then filters to ensure that all the backups are from that anchor point (LastLSN) and that they're all on the same RecoveryForkID
        Then checks that we have either enough Diffs and T-log backups to get to where we want to go. And checks that there is no break between
        LastLSN and FirstLSN in sequential files

    .PARAMETER FilteredRestoreFiles
        This is just an object consisting of the output from Read-DbaBackupHeader. Normally this will have been filtered down to a restorable chain
        before arriving here. (ie; only 1 anchoring Full backup)

    .NOTES
        Author: Stuart Moore (@napalmgram), stuart-moore.com
        Tags:
        dbatools PowerShell module (https://dbatools.io, [email protected])
       Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        Test-DbaLsnChain -FilteredRestoreFiles $FilteredFiles

        Checks that the Restore chain in $FilteredFiles is complete and can be fully restored

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [object[]]$FilteredRestoreFiles,
        [switch]$Continue,
        [switch]$EnableException
    )


    begin {
        #Need to anchor  with full backup:
        $TestHistory = @()
    }
    process {
        foreach ($bh in $FilteredRestoreFiles) {
            $TestHistory += $bh
        }
    }
    end {
        if ($continue) {
            return $true
        }
        Write-Message -Level Verbose -Message "Testing LSN Chain"
        if ($null -eq $TestHistory[0].BackupTypeDescription) {
            $TypeName = 'Type'
        } else {
            $TypeName = "BackupTypeDescription"
        }
        Write-Message -Level VeryVerbose -Message "Testing LSN Chain - Type $typename"
        $FullDBAnchor = $TestHistory | Where-Object {$_.$TypeName -in ('Database', 'Full') }

        if (($FullDBAnchor | Group-Object -Property FirstLSN | Measure-Object).Count -ne 1) {
            $cnt = ($FullDBAnchor | Group-Object -Property FirstLSN | Measure-Object).Count
            foreach ($tFile in $FullDBAnchor) {
                Write-Message -Level Debug -Message "$($tfile.FirstLsn) - $($tfile.TypeName)"
            }
            Write-Message -Level Verbose -Message "db count = $cnt"
            Write-Message -Level Warning -Message "More than 1 full backup from a different LSN, or less than 1, neither supported"

            return $false
            break;
        }

        #Via LSN chain:
        [BigInt]$CheckPointLSN = ($FullDBAnchor | Select-Object -First 1).CheckPointLSN.ToString()
        [BigInt]$FullDBLastLSN = ($FullDBAnchor | Select-Object -First 1).LastLSN.ToString()
        $BackupWrongLSN = $FilteredRestoreFiles | Where-Object {$_.DatabaseBackupLSN -ne $CheckPointLSN}
        #Should be 0 in there, if not, lets check that they're from during the full backup
        if ($BackupWrongLSN.count -gt 0 ) {
            if (($BackupWrongLSN | Where-Object {[BigInt]$_.LastLSN.ToString() -lt $FullDBLastLSN}).count -gt 0) {
                Write-Message -Level Warning -Message "We have non matching LSNs - not supported"
                return $false
                break;
            }
        }
        $DiffAnchor = $TestHistory | Where-Object {$_.$TypeName -in ('Database Differential', 'Differential')}
        #Check for no more than a single Differential backup
        if (($DiffAnchor.FirstLSN | Select-Object -unique | Measure-Object).count -gt 1) {
            Write-Message -Level Warning -Message "More than 1 differential backup, not supported"
            return $false
            break;
        } elseif (($DiffAnchor | Measure-Object).Count -eq 1) {
            Write-Message -Level VeryVerbose -Message "Found a diff file, setting Log Anchor"
            $TlogAnchor = $DiffAnchor
        } else {
            $TlogAnchor = $FullDBAnchor
        }


        #Check T-log LSNs form a chain.
        $TranLogBackups = $TestHistory | Where-Object {$_.$TypeName -in ('Transaction Log', 'Log') -and $_.DatabaseBackupLSN -eq $FullDBAnchor.CheckPointLSN} | Sort-Object -Property LastLSN, FirstLsn
        for ($i = 0; $i -lt ($TranLogBackups.count)) {
            Write-Message -Level Debug -Message "looping t logs"
            if ($i -eq 0) {
                if ($TranLogBackups[$i].FirstLSN -gt $TlogAnchor.LastLSN) {
                    Write-Message -Level Warning -Message "Break in LSN Chain between $($TlogAnchor.FullName) and $($TranLogBackups[($i)].FullName) "
                    Write-Message -Level Verbose -Message "Anchor $($TlogAnchor.LastLSN) - FirstLSN $($TranLogBackups[$i].FirstLSN)"
                    return $false
                    break
                }
            } else {
                if ($TranLogBackups[($i - 1)].LastLsn -ne $TranLogBackups[($i)].FirstLSN -and ($TranLogBackups[($i)] -ne $TranLogBackups[($i - 1)])) {
                    Write-Message -Level Warning -Message "Break in transaction log between $($TranLogBackups[($i-1)].FullName) and $($TranLogBackups[($i)].FullName) "
                    return $false
                    break
                }
            }
            $i++

        }
        Write-Message -Level VeryVerbose -Message "Passed LSN Chain checks"
        return $true
    }
}
tools\dbatools\internal\functions\Test-DbaRestoreVersion.ps1
function Test-DbaRestoreVersion {
    <#
    .SYNOPSIS
        Checks that the restore files are from a version of SQL Server that can be restored on the target version

    .DESCRIPTION
        Finds the anchoring Full backup (or multiple if it's a striped set).
        Then filters to ensure that all the backups are from that anchor point (LastLSN) and that they're all on the same RecoveryForkID
        Then checks that we have either enough Diffs and T-log backups to get to where we want to go. And checks that there is no break between
        LastLSN and FirstLSN in sequential files

    .PARAMETER FilteredRestoreFiles
        This is just an object consisting of the output from Read-DbaBackupHeader. Normally this will have been filtered down to a restorable chain
        before arriving here. (ie; only 1 anchoring Full backup)

    .PARAMETER SqlInstance
        Sql Server Instance against which the restore is going to be performed

    .PARAMETER SqlCredential
        Credential for connecting to SqlInstance

    .PARAMETER SystemDatabaseRestore
        Switch when restoring system databases

    .NOTES
        Author: Stuart Moore (@napalmgram), stuart-moore.com
        Tags:
        dbatools PowerShell module (https://dbatools.io, [email protected])
       Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        Test-DbaRestoreVersion -FilteredRestoreFiles $FilteredFiles -SqlInstance server1\instance1

        Checks that the Restore chain in $FilteredFiles is compatible with the SQL Server version of server1\instance1

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [object]$SqlInstance,
        [parameter(Mandatory)]
        [object[]]$FilteredRestoreFiles,
        [PSCredential]$SqlCredential,
        [switch]$SystemDatabaseRestore
    )
    $RestoreVersion = ($FilteredRestoreFiles.SoftwareVersionMajor | Measure-Object -average).average
    Write-Message -Level Verbose -Message "RestoreVersion is $RestoreVersion"
    #Test to make sure we don't have an upgrade mid backup chain, there's a reason I'm paranoid..
    if ([int]$RestoreVersion -ne $RestoreVersion) {
        Write-Message -Level Warning -Message "Version number change during backups - $RestoreVersion"
        return $false
        break
    }
    #Can't restore backwards
    try {
        if ($SqlInstance -isnot [Microsoft.SqlServer.Management.Smo.SqlSmoObject]) {
            $Newconnection = $true
            $Server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        } else {
            $server = $SqlInstance
        }
    } catch {
        Write-Message -Level Warning -Message "Cannot connect to $SqlInstance"
        break
    }

    if ($SystemDatabaseRestore) {
        if ($RestoreVersion -ne $Server.VersionMajor) {
            Write-Message -Level Warning -Message "For System Database restore versions must match)"
            return $false
            break
        }
    } else {
        if ($RestoreVersion -gt $Server.VersionMajor) {
            Write-Message -Level Warning -Message "Backups are from a newer version of SQL Server than $($Server.Name)"
            return $false
            break
        }

        if (($Server.VersionMajor -gt 10 -and $RestoreVersion -lt 9)  ) {
            Write-Message -Level Warning -Message "This version - $RestoreVersion - too old to restore on to $($Server.Name)"
            return $false
            break
        }
    }
    if ($Newconnection) {
        $server.ConnectionContext.Disconnect()
    }
    return $True
}
tools\dbatools\internal\functions\Test-HostOSLinux.ps1
function Test-HostOSLinux {
    param (
        [object]$SqlInstance,
        [object]$sqlcredential
    )

    $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $sqlcredential
    $server.ConnectionContext.ExecuteScalar("SELECT @@VERSION") -match "Linux"
}
tools\dbatools\internal\functions\Test-PendingReboot.ps1
function Test-PendingReboot {
    <#
        .SYNOPSIS
            Based on https://github.com/adbertram/PSSqlUpdater
            This function tests various registry values to see if the local computer is pending a reboot
        .NOTES
            Inspiration from: https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542
        .EXAMPLE
            PS> Test-PendingReboot

            This example checks various registry values to see if the local computer is pending a reboot.
    #>
    [OutputType([bool])]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [DbaInstanceParameter]$ComputerName,
        [ValidateNotNullOrEmpty()]
        [pscredential]$Credential,
        [bool]$EnableException = $EnableException
    )
    process {
        try {
            $icmParams = @{
                ComputerName = $ComputerName.ComputerName
                Raw          = $true
            }
            if ($PSBoundParameters.ContainsKey('Credential')) {
                $icmParams.Credential = $Credential
            }

            $OperatingSystem = Get-DbaCmObject -ComputerName $ComputerName.ComputerName -ClassName Win32_OperatingSystem

            # If Vista/2008 & Above query the CBS Reg Key
            If ($OperatingSystem.BuildNumber -ge 6001) {
                $PendingReboot = Invoke-Command2 @icmParams -ScriptBlock { Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing' -Name 'RebootPending' -ErrorAction SilentlyContinue }
                if ($PendingReboot) {
                    Write-Message -Level Verbose -Message 'Reboot pending detected in the Component Based Servicing registry key'
                    return $true
                }
            }

            # Query WUAU from the registry
            $PendingReboot = Invoke-Command2 @icmParams -ScriptBlock { Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update' -Name 'RebootRequired' -ErrorAction SilentlyContinue }
            if ($PendingReboot) {
                Write-Message -Level Verbose -Message 'WUAU has a reboot pending'
                return $true
            }

            # Query PendingFileRenameOperations from the registry
            $PendingReboot = Invoke-Command2 @icmParams -ScriptBlock { Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager' -Name 'PendingFileRenameOperations' -ErrorAction SilentlyContinue }
            if ($PendingReboot -and $PendingReboot.PendingFileRenameOperations) {
                Write-Message -Level Verbose -Message 'Reboot pending in the PendingFileRenameOperations registry value'
                return $true
            }
            return $false
        } catch {
            Stop-Function -Message "Failed to obtain any intormation from remote registry on $ComputerName" -ErrorRecord $_
        }
    }
}
tools\dbatools\internal\functions\Test-PSRemoting.ps1
#requires -version 3.0

function Test-PSRemoting {
    <#
    Jeff Hicks
    https://www.petri.com/test-network-connectivity-powershell-test-connection-cmdlet
    #>
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUsePSCredentialType", "")]
    [Cmdletbinding()]
    param(
        [Parameter(Position = 0, Mandatory, ValueFromPipeline)]
        [DbaInstance]$ComputerName,
        $Credential = [System.Management.Automation.PSCredential]::Empty,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        Write-Message -Level VeryVerbose -Message "Testing $($ComputerName.Computername)"
        try {
            $null = Test-WSMan -ComputerName $ComputerName.ComputerName -Credential $Credential -Authentication Default -ErrorAction Stop
            $true
        } catch {
            $false
            Stop-Function -Message "Testing $($ComputerName.Computername)" -Target $ComputerName -ErrorRecord $_
        }

    } #process

} #close function
tools\dbatools\internal\functions\Test-SqlAgent.ps1
function Test-SqlAgent {
    <#
    .SYNOPSIS
        Internal function. Checks to see if SQL Server Agent is running on a server.
    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [Alias("ServerInstance", "SqlServer")]
        [object]$SqlInstance,
        [PSCredential]$SqlCredential
    )

    if ($SqlInstance.GetType() -ne [Microsoft.SqlServer.Management.Smo.Server]) {
        $SqlInstance = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
    }

    if ($null -eq $SqlInstance.JobServer) { return $false }
    try { $null = $SqlInstance.JobServer.script(); return $true }
    catch { return $false }
}
tools\dbatools\internal\functions\Test-SqlLoginAccess.ps1
function Test-SqlLoginAccess {
    <#
    .SYNOPSIS
        Internal function. Ensures login has access on SQL Server.
    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [Alias("ServerInstance", "SqlServer")]
        [object]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$Login
        #[switch]$Detailed - can return if its a login or just has access
    )

    if ($SqlInstance.GetType() -ne [Microsoft.SqlServer.Management.Smo.Server]) {
        $SqlInstance = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
    }

    if (($SqlInstance.Logins.Name) -notcontains $Login) {
        try {
            $rows = $SqlInstance.ConnectionContext.ExecuteScalar("EXEC xp_logininfo '$Login'")

            if (($rows | Measure-Object).Count -eq 0) {
                return $false
            }
        } catch {
            return $false
        }
    }
    return $true
}
tools\dbatools\internal\functions\Test-SqlQueryComplete.ps1
function Test-SqlQueryComplete {
    param (
        [Alias("SqlInstance", "SqlServer")]
        [object]$server,
        [string]$sql,
        [switch]$checkpid
    )

    if ($checkpid) {
        $sqlpid = " and session_id = $sqlpid"
    }

    $sqlpid = $server.ConnectionContext.ProcessID
    $sqlpid = " and session_id = $sqlpid"
    $sql = $sql.Replace("'", "''")
    $testsql = "select sqltext.text FROM sys.dm_exec_requests req CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext where text = '$sql' $sqlpid"

    if ($server.ConnectionContext.ExecuteScalar($testsql) -ne $null) {
        return $false
    } else {
        return $true
    }
}
tools\dbatools\internal\functions\Test-SqlSa.ps1
function Test-SqlSa {
    <#
    .SYNOPSIS
        Internal function. Ensures sysadmin account access on SQL Server.
    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [Alias("ServerInstance", "SqlServer")]
        [object]$SqlInstance,
        [PSCredential]$SqlCredential
    )

    try {

        if ($SqlInstance.GetType() -eq [Microsoft.SqlServer.Management.Smo.Server]) {
            return ($SqlInstance.ConnectionContext.FixedServerRoles -match "SysAdmin")
        }

        $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        return ($server.ConnectionContext.FixedServerRoles -match "SysAdmin")
    } catch { return $false }
}
tools\dbatools\internal\functions\Unregister-RemoteSessionConfiguration.ps1
function Unregister-RemoteSessionConfiguration {
    <#
    .SYNOPSIS
        Unregisters a PSSessionConfiguration on a remote machine
    .DESCRIPTION
        Unregisters a session previously created with Register-RemoteSessionConfiguration through WinRM.
    #>
    [CmdletBinding(SupportsShouldProcess)]
    Param (
        [parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        $ComputerName,
        [parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Name,
        [pscredential]$Credential
    )
    begin {

    }
    process {
        $removeRunasSession = {
            Param (
                $Name
            )
            $existing = Get-PSSessionConfiguration -Name $Name -ErrorAction SilentlyContinue
            if ($null -eq $existing) {
                return [pscustomobject]@{ 'Name' = $Name ; 'Status' = 'Not found'; Successful = $true }
            } else {
                try {
                    Unregister-PSSessionConfiguration -Name $Name -ErrorAction Stop -NoServiceRestart -Confirm:$false 3>$null
                    [pscustomobject]@{ 'Name' = $Name; 'Status' = 'Unregistered' ; Successful = $true }
                } catch {
                    return [pscustomobject]@{ 'Name' = $Name ; 'Status' = $_  ; Successful = $false}
                }
            }
        }
        if ($PSCmdlet.ShouldProcess($ComputerName, "Unregistering session configuration $Name")) {
            try {
                $unregisterIt = Invoke-Command2 -ComputerName $ComputerName -Credential $Credential -ScriptBlock $removeRunasSession -ArgumentList @($Name) -Raw -RequiredPSVersion 3.0
            } catch {
                Stop-Function -Message "Failure during remote session configuration execution" -ErrorRecord $_ -EnableException $true
            }
        }
        if ($unregisterIt) {
            Write-Message -Level Debug -Message "Configuration attempt returned the following status`: $($unregisterIt.Status)"
            if ($unregisterIt.Status -eq 'Unregistered') {
                Write-Message -Level Verbose -Message "Restarting WinRm service on $ComputerName"
                Restart-WinRMService -ComputerName $ComputerName -Credential $Credential
            }
            return $unregisterIt
        }
    }
}
tools\dbatools\internal\functions\Update-ServiceStatus.ps1
function Update-ServiceStatus {
    <#
    .SYNOPSIS
        Internal function. Sends start/stop request to a SQL Server service and wait for the result.

    .DESCRIPTION
        Accepts objects from Get-DbaService and performs a corresponding action.

    .PARAMETER Credential
        Credential object used to connect to the computer as a different user.

    .PARAMETER Timeout
        How long to wait for the start/stop request completion before moving on.

    .PARAMETER InputObject
        A collection of services from Get-DbaService

    .PARAMETER Action
        Start or stop.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER WhatIf
        Shows what would happen if the cmdlet runs. The cmdlet is not run.

    .PARAMETER Confirm
        Prompts you for confirmation before running the cmdlet.

    .NOTES
        Author: Kirill Kravtsov ( @nvarscar )
        Tags:
        dbatools PowerShell module (https://dbatools.io)
       Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        $InputObject = Get-DbaService -ComputerName sql1
        Update-ServiceStatus -InputObject $InputObject -Action 'stop' -Timeout 30
        Update-ServiceStatus -InputObject $InputObject -Action 'start' -Timeout 30

        Restarts SQL services on sql1

    .EXAMPLE
        $InputObject = Get-DbaService -ComputerName sql1
        $credential = Get-Credential
        Update-ServiceStatus -InputObject $InputObject -Action 'stop' -Timeout 0 -Credential $credential

        Stops SQL services on sql1 and waits indefinitely for them to stop. Uses $credential to authorize on the server.
    #>
    [CmdletBinding(SupportsShouldProcess)]
    param(
        [parameter(ValueFromPipeline, Mandatory)]
        [object[]]$InputObject,
        [parameter(Mandatory)]
        [string[]]$Action,
        [int]$Timeout = 60,
        [PSCredential] $Credential,
        [bool][Alias('Silent')]$EnableException
    )
    begin {
        $callStack = Get-PSCallStack
        if ($callStack.Length -gt 1) {
            $callerName = $callStack[1].Command
        } else {
            $callerName = $callStack[0].Command
        }
        #Prepare the service control script block
        $svcControlBlock = {
            $group = $_.Group
            $computerName = $_.Name
            $servicePriorityCollection = $group.ServicePriority | Select-Object -unique | Sort-Object -Property @{ Expression = { [int]$_ }; Descending = $action -ne 'stop' }
            foreach ($priority in $servicePriorityCollection) {
                $services = $group | Where-Object { $_.ServicePriority -eq $priority }
                $servicesToRestart = @()
                foreach ($service in $services) {
                    if ('dbatools.DbaSqlService' -in $service.PSObject.TypeNames) {
                        $cimObject = $service._CimObject
                        if (($cimObject.State -eq 'Running' -and $action -eq 'start') -or ($cimObject.State -eq 'Stopped' -and $action -eq 'stop')) {
                            $service | Add-Member -Force -NotePropertyName Status -NotePropertyValue 'Successful' -PassThru |
                                Add-Member -Force -NotePropertyName Message -NotePropertyValue "The service is already $actionText, no action required" -PassThru
                        } elseif ($cimObject.StartMode -eq 'Disabled' -and $action -in 'start', 'restart') {
                            $service | Add-Member -Force -NotePropertyName Status -NotePropertyValue 'Failed' -PassThru |
                                Add-Member -Force -NotePropertyName Message -NotePropertyValue "The service is disabled and cannot be $actionText" -PassThru
                        } else {
                            $servicesToRestart += $service
                        }
                    } else {
                        throw "Unknown object in pipeline - make sure to use Get-DbaService cmdlet"
                    }
                }
                #Set desired $action
                if ($action -in 'start', 'restart') {
                    $methodName = 'StartService'
                    $desiredState = 'Running'
                    $undesiredState = 'Stopped'
                } elseif ($action -eq 'stop') {
                    $methodName = 'StopService'
                    $desiredState = 'Stopped'
                    $undesiredState = 'Running'
                }
                $invokeResults = @()
                foreach ($service in $servicesToRestart) {
                    if ($Pscmdlet.ShouldProcess("Sending $action request to service $($service.ServiceName) on $($service.ComputerName)")) {
                        #Invoke corresponding CIM method
                        $invokeResult = Invoke-CimMethod -InputObject $service._CimObject -MethodName $methodName
                        $invokeResults += [psobject]@{
                            InvokeResult    = $invokeResult
                            ServiceState    = $invokeResult.State
                            ServiceExitCode = $invokeResult.ReturnValue
                            CheckPending    = $true
                            Service         = $service
                        }
                    }
                }

                $startTime = Get-Date
                if ($Pscmdlet.ShouldProcess("Waiting the services to $action on $computerName")) {
                    #Wait for the service to complete the action until timeout
                    while ($invokeResults.CheckPending -contains $true) {
                        foreach ($result in ($invokeResults | Where-Object CheckPending -eq $true)) {
                            try {
                                #Refresh Cim instance - not using Get-DbaCmObject because module is not loaded here, but it only refreshes existing object
                                $result.Service._CimObject = $result.Service._CimObject | Get-CimInstance
                            } catch {
                                $result.ServiceExitCode = -3
                                $result.ServiceState = 'Unknown'
                                $result.CheckPending = $false
                                continue
                            }
                            $result.ServiceState = $result.Service._CimObject.State
                            #Failed or succeeded
                            if ($result.ServiceExitCode -ne 0 -or $result.ServiceState -eq $desiredState) {
                                $result.CheckPending = $false
                                continue
                            }
                            #Failed after being in the Pending state
                            if ($result.CheckPending -and $result.ServiceState -eq $undesiredState) {
                                $result.ServiceExitCode = -2
                                $result.CheckPending = $false
                                continue
                            }
                            #Timed out
                            if ($timeout -gt 0 -and ((Get-Date) - $startTime).TotalSeconds -gt $timeout) {
                                $result.ServiceExitCode = -1
                                $result.CheckPending = $false
                                continue
                            }
                            #Still pending - leave CheckPending as is and run again
                        }
                        Start-Sleep -Milliseconds 200
                    }
                }
                foreach ($result in $invokeResults) {
                    #Add status
                    $status = switch ($result.ServiceExitCode) {
                        0 { 'Successful' }
                        10 { 'Successful '} #Already running - FullText service is started automatically
                        default { 'Failed' }
                    }
                    Add-Member -Force -InputObject $result.Service -NotePropertyName Status -NotePropertyValue $status
                    #Add error message
                    $errorMessageFromReturnValue = if ($result.ServiceExitCode -in 0..($errorCodes.Length - 1)) {
                        $errorCodes[$result.ServiceExitCode]
                    } else { "Unknown error." }
                    $message = switch ($result.ServiceExitCode) {
                        -2 { "The service failed to $action." }
                        -1 { "The attempt to $action the service has timed out." }
                        0 { "Service was successfully $actionText." }
                        default { "The attempt to $action the service returned the following error: $errorMessageFromReturnValue" }
                    }
                    Add-Member -Force -InputObject $result.Service -NotePropertyName Message -NotePropertyValue $message
                    # Refresh service state for the object
                    if ($result.ServiceState) { $result.Service.State = $result.ServiceState }
                    $result
                }
            }
        }

        $actionText = switch ($action) { stop { 'stopped' }; start { 'started' }; restart { 'restarted' } }
        $errorCodes = Get-DbaServiceErrorMessage
    }

    process {
        #Group services for each computer
        $serviceComputerGroup = $InputObject | Group-Object -Property ComputerName
        foreach ($group in $serviceComputerGroup) {
            Write-Message -Message "Getting CIM objects from computer $($group.Name)"
            $serviceNames = $group.Group.ServiceName -join "' OR name = '"
            try {
                $svcCim = Get-DbaCmObject -ComputerName $group.Name -Namespace "root\cimv2" -query "SELECT * FROM Win32_Service WHERE name = '$serviceNames'" -Credential $credential
            } catch {
                Stop-Function -EnableException $EnableException -FunctionName $callerName -Message ("The attempt to get CIM session for the services on $($group.Name) returned the following error: " + ($_.Exception.Message -join ' ')) -Category ConnectionError -ErrorRecord $_
            }
            foreach ($service in $group.Group) {
                if ($cimObject = ($svcCim | Where-Object Name -eq $service.ServiceName)) {
                    Add-Member -Force -InputObject $service -NotePropertyName _CimObject -NotePropertyValue $cimObject
                } else {
                    Stop-Function -Message "Failed to retrieve service name $($service.ServiceName) from the CIM object collection - the service will not be processed" -Continue -Target $group.Name
                }
            }
        }
        if ($Pscmdlet.ShouldProcess("Running the following service action: $action")) {
            if ($serviceComputerGroup) {
                try {
                    $serviceComputerGroup | Invoke-Parallel -ScriptBlock $svcControlBlock -Throttle 50 -ImportVariables | ForEach-Object {
                        if ($_.ServiceExitCode) {
                            $target = "$($_.Service.ServiceName) on $($_.Service.ComputerName)"
                            Write-Message -Level Warning -Message "($target) $($_.Service.Message)" -Target $target
                            if ($_.Service.ServiceType -eq 'Engine' -and $_.ServiceExitCode -eq 3) {
                                Write-Message -Level Warning -Message "($target) Run the command with '-Force' switch to force the restart of a dependent SQL Agent" -Target $target
                            }
                        }
                        $_.Service | Select-DefaultView -Property ComputerName, ServiceName, InstanceName, ServiceType, State, Status, Message
                    }
                } catch {
                    Stop-Function -Message "Multi-threaded execution returned an error" -ErrorRecord $_ -EnableException $EnableException -FunctionName $callerName
                }
            }
        }
    }
    end {
    }
}
tools\dbatools\internal\functions\Update-SqlDbOwner.ps1
function Update-SqlDbOwner {
    <#
    .SYNOPSIS
        Internal function. Updates specified database dbowner.
    #>
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [object]$Source,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [object]$Destination,
        [string]$DbName,
        [PSCredential]$SourceSqlCredential,
        [PSCredential]$DestinationSqlCredential,
        [switch]$EnableException
    )

    $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential
    $destServer = Connect-SqlInstance -SqlInstance $Destination -SqlCredential $DestinationSqlCredential

    $source = $sourceServer.DomainInstanceName
    $destination = $destServer.DomainInstanceName

    if ($DbName.length -eq 0) {
        $databases = ($sourceServer.Databases | Where-Object { $destServer.databases.name -contains $_.name -and $_.IsSystemObject -eq $false }).Name
    } else { $databases = $DbName }

    foreach ($DbName in $databases) {
        $destdb = $destServer.databases[$DbName]
        $dbowner = $sourceServer.databases[$DbName].owner

        if ($destdb.owner -ne $dbowner) {
            if ($destdb.Status -ne 'Normal') {
                Write-Message -Level Output -Message "Database status not normal. Skipping dbowner update."
                continue
            }
            if ((Get-DbaAgDatabase -SqlInstance $DestServer -Database $dbName)) {
                Write-Message -Level Verbose -Message "Database [$dbName] is part of an availability group. Skipping."
                continue
            }
            
            if ($null -eq $dbowner -or $null -eq $destServer.logins[$dbowner]) {
                try {
                    $dbowner = ($destServer.logins | Where-Object { $_.id -eq 1 }).Name
                } catch {
                    $dbowner = "sa"
                }
            }

            try {
                if ($destdb.ReadOnly -eq $true) {
                    $changeroback = $true
                    Update-SqlDbReadOnly $destServer $DbName $false
                }

                $destdb.SetOwner($dbowner)
                Write-Output "Changed $DbName owner to $dbowner"

                if ($changeroback) {
                    Update-SqlDbReadOnly $destServer $DbName $true
                    $changeroback = $null
                }
            } catch {
                Stop-Function -Message "Failed to update $DbName owner to $dbowner." -ErrorRecord $_
            }
        } else {
            Write-Message -Level Verbose -Message "Proper owner already set on $DbName"
        }
    }
}
tools\dbatools\internal\functions\Update-SqlDbReadOnly.ps1
function Update-SqlDbReadOnly {
    <#
    .SYNOPSIS
        Internal function. Updates specified database to read-only or read-write. Necessary because SMO doesn't appear to support NO_WAIT.
    #>
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [Alias("ServerInstance", "SqlServer")]
        [object]$SqlInstance,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$dbname,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [bool]$readonly
    )

    if ($readonly) {
        Stop-DbaProcess -SqlInstance $SqlInstance -Database $dbname
        $sql = "ALTER DATABASE [$dbname] SET READ_ONLY WITH NO_WAIT"
    } else {
        $sql = "ALTER DATABASE [$dbname] SET READ_WRITE WITH NO_WAIT"
    }

    try {
        $server = Connect-SqlInstance -SqlInstance $SqlInstance
        $null = $server.Query($sql)
        Write-Message -Level Verbose -Message "Changed ReadOnly status to $readonly for $dbname on $($server.name)"
        return $true
    } catch {
        Write-Message -Level Warning "Could not change readonly status for $dbname on $($server.name)"
        return $false
    }
}
tools\dbatools\internal\functions\Update-SqlPermission.ps1
function Update-SqlPermission {
    <#
        .SYNOPSIS
            Internal function. Updates permission sets, roles, database mappings on server and databases
        .PARAMETER SourceServer
            Source Server
        .PARAMETER SourceLogin
            Source login
        .PARAMETER DestServer
            Destination Server
        .PARAMETER DestLogin
            Destination Login
        .PARAMETER EnableException
            Use this switch to disable any kind of verbose messages
    #>
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [object]$SourceServer,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [object]$SourceLogin,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [object]$DestServer,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [object]$DestLogin,
        [Alias('Silent')]
        [switch]$EnableException
    )

    $destination = $DestServer.DomainInstanceName
    $source = $SourceServer.DomainInstanceName
    $userName = $SourceLogin.Name

    # Server Roles: sysadmin, bulklogin, etc
    foreach ($role in $SourceServer.Roles) {
        $roleName = $role.Name
        $destRole = $DestServer.Roles[$roleName]

        if ($null -ne $destRole) {
            try {
                $destRoleMembers = $destRole.EnumMemberNames()
            } catch {
                $destRoleMembers = $destRole.EnumServerRoleMembers()
            }
        }

        try {
            $roleMembers = $role.EnumMemberNames()
        } catch {
            $roleMembers = $role.EnumServerRoleMembers()
        }

        if ($roleMembers -contains $userName) {
            if ($null -ne $destRole) {
                if ($Pscmdlet.ShouldProcess($destination, "Adding $userName to $roleName server role.")) {
                    try {
                        $destRole.AddMember($userName)
                        Write-Message -Level Verbose -Message "Adding $userName to $roleName server role on $destination successfully performed."
                    } catch {
                        Stop-Function -Message "Failed to add $userName to $roleName server role on $destination." -Target $role -ErrorRecord $_
                    }
                }
            }
        }

        # Remove for Syncs
        if ($roleMembers -notcontains $userName -and $destRoleMembers -contains $userName -and $null -ne $destRole) {
            if ($Pscmdlet.ShouldProcess($destination, "Adding $userName to $roleName server role.")) {
                try {
                    $destRole.DropMember($userName)
                    Write-Message -Level Verbose -Message "Removing $userName from $destRoleName server role on $destination successfully performed."
                } catch {
                    Stop-Function -Message "Failed to remove $userName from $destRoleName server role on $destination." -Target $role -ErrorRecord $_
                }
            }
        }
    }

    $ownedJobs = $SourceServer.JobServer.Jobs | Where-Object OwnerLoginName -eq $userName
    foreach ($ownedJob in $ownedJobs) {
        if ($null -ne $DestServer.JobServer.Jobs[$ownedJob.Name]) {
            if ($Pscmdlet.ShouldProcess($destination, "Changing of job owner to $userName for $($ownedJob.Name).")) {
                try {
                    $destOwnedJob = $DestServer.JobServer.Jobs | Where-Object { $_.Name -eq $ownedJobs.Name }
                    $destOwnedJob.Set_OwnerLoginName($userName)
                    $destOwnedJob.Alter()
                    Write-Message -Level Verbose -Message "Changing job owner to $userName for $($ownedJob.Name) on $destination successfully performed."
                } catch {
                    Stop-Function -Message "Failed to change job owner for $($ownedJob.Name) on $destination." -Target $ownedJob -ErrorRecord $_
                }
            }
        }
    }

    if ($SourceServer.VersionMajor -ge 9 -and $DestServer.VersionMajor -ge 9) {
        <#
            These operations are only supported by SQL Server 2005 and above.
            Securables: Connect SQL, View any database, Administer Bulk Operations, etc.
        #>

        $perms = $SourceServer.EnumServerPermissions($userName)
        foreach ($perm in $perms) {
            $permState = $perm.PermissionState
            if ($permState -eq "GrantWithGrant") {
                $grantWithGrant = $true;
                $permState = "grant"
            } else {
                $grantWithGrant = $false
            }

            $permSet = New-Object Microsoft.SqlServer.Management.Smo.ServerPermissionSet($perm.PermissionType)
            if ($Pscmdlet.ShouldProcess($destination, "$permState on $($perm.PermissionType) for $userName.")) {
                try {
                    $DestServer.PSObject.Methods[$permState].Invoke($permSet, $userName, $grantWithGrant)
                    Write-Message -Level Verbose -Message "$permState $($perm.PermissionType) to $userName on $destination successfully performed."
                } catch {
                    Stop-Function -Message "Failed to $permState $($perm.PermissionType) to $userName on $destination." -Target $perm -ErrorRecord $_
                }
            }

            # for Syncs
            $destPerms = $DestServer.EnumServerPermissions($userName)
            foreach ($perm in $destPerms) {
                $permState = $perm.PermissionState
                $sourcePerm = $perms | Where-Object { $_.PermissionType -eq $perm.PermissionType -and $_.PermissionState -eq $permState }

                if ($null -eq $sourcePerm) {
                    if ($Pscmdlet.ShouldProcess($destination, "Revoking $($perm.PermissionType) for $userName.")) {
                        try {
                            $permSet = New-Object Microsoft.SqlServer.Management.Smo.ServerPermissionSet($perm.PermissionType)

                            if ($permState -eq "GrantWithGrant") {
                                $grantWithGrant = $true;
                                $permState = "grant"
                            } else {
                                $grantWithGrant = $false
                            }

                            $DestServer.PSObject.Methods["Revoke"].Invoke($permSet, $userName, $false, $grantWithGrant)
                            Write-Message -Level Verbose -Message "Revoking $($perm.PermissionType) for $userName on $destination successfully performed."
                        } catch {
                            Stop-Function -Message "Failed to revoke $($perm.PermissionType) from $userName on $destination." -Target $perm -ErrorRecord $_
                        }
                    }
                }
            }
        }

        # Credential mapping. Credential removal not currently supported for Syncs.
        $loginCredentials = $SourceServer.Credentials | Where-Object { $_.Identity -eq $SourceLogin.Name }
        foreach ($credential in $loginCredentials) {
            if ($null -eq $DestServer.Credentials[$credential.Name]) {
                if ($Pscmdlet.ShouldProcess($destination, "Creating credential $($credential.Name) for $userName.")) {
                    try {
                        $newCred = New-Object Microsoft.SqlServer.Management.Smo.Credential($DestServer, $credential.Name)
                        $newCred.Identity = $SourceLogin.Name
                        $newCred.Create()
                        Write-Message -Level Verbose -Message "Creating credential $($credential.Name) for $userName on $destination successfully performed."
                    } catch {
                        Stop-Function -Message "Failed to create credential $($credential.Name) for $userName on $destination." -Target $credential -ErrorRecord $_
                    }
                }
            }
        }
    }

    if ($DestServer.VersionMajor -lt 9) {
        Write-Message -Level Warning -Message "SQL Server 2005 or greater required for database mappings.";
        continue
    }

    # For Sync, if info doesn't exist in EnumDatabaseMappings, then no big deal.
    foreach ($db in $DestLogin.EnumDatabaseMappings()) {
        $dbName = $db.DbName
        $destDb = $DestServer.Databases[$dbName]
        $sourceDb = $SourceServer.Databases[$dbName]
        $dbUsername = $db.Username;
        $dbLogin = $db.LoginName

        if ($null -ne $sourceDb) {
            if (-not $sourceDb.IsAccessible) {
                Write-Message -Level Verbose -Message "Database [$($sourceDb.Name)] is not accessible on $source. Skipping."
                continue
            }
            if (-not $destDb.IsAccessible) {
                Write-Message -Level Verbose -Message "Database [$($sourceDb.Name)] is not accessible on destination. Skipping."
                continue
            }
            if ((Get-DbaAgDatabase -SqlInstance $DestServer -Database $dbName -ErrorAction Ignore -WarningAction SilentlyContinue)) {
                Write-Message -Level Verbose -Message "Database [$dbName] is part of an availability group. Skipping."
                continue
            }
            if ($null -eq $sourceDb.Users[$dbUsername] -and $null -eq $destDb.Users[$dbUsername]) {
                if ($Pscmdlet.ShouldProcess($destination, "Dropping user $dbUsername from $dbName.")) {
                    try {
                        $destDb.Users[$dbUsername].Drop()
                        Write-Message -Level Verbose -Message "Dropping user $dbUsername (login: $dbLogin) from $dbName on destination successfully performed."
                        Write-Message -Level Verbose -Message "Any schema in $dbaName owned by $dbUsername may still exist."
                    } catch {
                        Stop-Function -Message "Failed to drop $dbUsername (login: $dbLogin) from $dbName on destination." -Target $db -ErrorRecord $_
                    }
                }
            }

            # Remove user from role. Role removal not currently supported for Syncs.
            # TODO: reassign if dbo, application roles
            foreach ($destRole in $destDb.Roles) {
                $destRoleName = $destRole.Name
                $sourceRole = $sourceDb.Roles[$destRoleName]
                if ($null -eq $sourceRole) {
                    if ($sourceRole.EnumMembers() -notcontains $dbUsername -and $destRole.EnumMembers() -contains $dbUsername) {
                        if ($dbUsername -ne "dbo") {
                            if ($Pscmdlet.ShouldProcess($destination, "Dropping user $userName from $destRoleName database role in $dbName.")) {
                                try {
                                    $destRole.DropMember($dbUsername)
                                    $destDb.Alter()
                                    Write-Message -Level Verbose -Message "Dropping user $dbUsername (login: $dbLogin) from $destRoleName database role in $dbName on $destination successfully performed."
                                } catch {
                                    Stop-Function -Message "Failed to remove $dbUsername (login: $dbLogin) from $destRoleName database role in $dbName on $destination." -Target $destRole -ErrorRecord $_
                                }
                            }
                        }
                    }
                }
            }

            # Remove Connect, Alter Any Assembly, etc
            $destPerms = $destDb.EnumDatabasePermissions($userName)
            $perms = $sourceDb.EnumDatabasePermissions($userName)
            # for Syncs
            foreach ($perm in $destPerms) {
                $permState = $perm.PermissionState
                $sourcePerm = $perms | Where-Object { $_.PermissionType -eq $perm.PermissionType -and $_.PermissionState -eq $permState }
                if ($null -eq $sourcePerm) {
                    if ($Pscmdlet.ShouldProcess($destination, "Revoking $($perm.PermissionType) from $userName in $dbName.")) {
                        try {
                            $permSet = New-Object Microsoft.SqlServer.Management.Smo.DatabasePermissionSet($perm.PermissionType)

                            if ($permState -eq "GrantWithGrant") {
                                $grantWithGrant = $true;
                                $permState = "grant"
                            } else {
                                $grantWithGrant = $false
                            }

                            $destDb.PSObject.Methods["Revoke"].Invoke($permSet, $userName, $false, $grantWithGrant)
                            Write-Message -Level Verbose -Message "Revoking $($perm.PermissionType) from $userName in $dbName on $destination successfully performed."
                        } catch {
                            Stop-Function -Message "Failed to revoke $($perm.PermissionType) from $userName in $dbName on $destination." -Target $perm -ErrorRecord $_
                        }
                    }
                }
            }
        }
    }

    # Adding database mappings and securables
    foreach ($db in $SourceLogin.EnumDatabaseMappings()) {
        $dbName = $db.DbName
        $destDb = $DestServer.Databases[$dbName]
        $sourceDb = $SourceServer.Databases[$dbName]
        $dbUsername = $db.Username;
        $dbLogin = $db.LoginName

        if ($null -ne $destDb) {
            if (-not $destDb.IsAccessible) {
                Write-Message -Level Verbose -Message "Database [$dbName] is not accessible. Skipping."
                continue
            }

            if ((Get-DbaAgDatabase -SqlInstance $DestServer -Database $dbName -ErrorAction Ignore -WarningAction SilentlyContinue)) {
                Write-Message -Level Verbose -Message "Database [$dbName] is part of an availability group. Skipping."
                continue
            }
            if ($null -eq $destDb.Users[$dbUsername]) {
                if ($Pscmdlet.ShouldProcess($destination, "Adding $dbUsername to $dbName.")) {
                    $sql = $SourceServer.Databases[$dbName].Users[$dbUsername].Script() | Out-String
                    try {
                        $destDb.ExecuteNonQuery($sql)
                        Write-Message -Level Verbose -Message "Adding user $dbUsername (login: $dbLogin) to $dbName successfully performed."
                    } catch {
                        Stop-Function -Message "Failed to add $dbUsername (login: $dbLogin) to $dbName on $destination." -Target $db -ErrorRecord $_
                    }
                }
            }

            # Db owner
            if ($sourceDb.Owner -eq $userName) {
                if ($Pscmdlet.ShouldProcess($destination, "Changing $dbName dbowner to $userName.")) {
                    try {
                        $result = Update-SqlDbOwner $SourceServer $DestServer -DbName $dbName
                        if ($result -eq $true) {
                            Write-Message -Level Verbose -Message "Changed $($destDb.Name) owner to $($sourceDb.owner)."
                        } else {
                            Write-Message -Level Warning -Message "Failed to update $($destDb.Name) owner to $($sourceDb.owner)."
                        }
                    } catch {
                        Write-Message -Level Warning -Message "Failed to update $($destDb.Name) owner to $($sourceDb.owner)."
                    }
                }
            }

            # Database Roles: db_owner, db_datareader, etc
            foreach ($role in $sourceDb.Roles) {
                if ($role.EnumMembers() -contains $userName) {
                    $roleName = $role.Name
                    $destDbRole = $destDb.Roles[$roleName]

                    if ($null -ne $destDbRole -and $dbUsername -ne "dbo" -and $destDbRole.EnumMembers() -notcontains $userName) {
                        if ($Pscmdlet.ShouldProcess($destination, "Adding $userName to $roleName database role in $dbName.")) {
                            try {
                                $destDbRole.AddMember($userName)
                                $destDb.Alter()
                                Write-Message -Level Verbose -Message "Adding $userName to $roleName database role in $dbName on $destination successfully performed."
                            } catch {
                                Stop-Function -Message "Failed to add $userName to $roleName database role in $dbName on $destination." -Target $role -ErrorRecord $_
                            }
                        }
                    }
                }
            }

            # Connect, Alter Any Assembly, etc
            $perms = $sourceDb.EnumDatabasePermissions($userName)
            foreach ($perm in $perms) {
                $permState = $perm.PermissionState
                if ($permState -eq "GrantWithGrant") {
                    $grantWithGrant = $true;
                    $permState = "grant"
                } else {
                    $grantWithGrant = $false
                }
                $permSet = New-Object Microsoft.SqlServer.Management.Smo.DatabasePermissionSet($perm.PermissionType)

                if ($Pscmdlet.ShouldProcess($destination, "$permState on $($perm.PermissionType) for $userName on $dbName")) {
                    try {
                        $destDb.PSObject.Methods[$permState].Invoke($permSet, $userName, $grantWithGrant)
                        Write-Message -Level Verbose -Message "$permState on $($perm.PermissionType) to $userName on $dbName on $destination successfully performed."
                    } catch {
                        Stop-Function -Message "Failed to perform $permState on $($perm.PermissionType) to $userName on $dbName on $destination." -Target $perm -ErrorRecord $_
                    }
                }
            }
        }
    }
}
tools\dbatools\internal\functions\utility\Join-DbaPath.ps1
function Join-DbaPath
{
<#
    .SYNOPSIS
        Performs multisegment path joins.
    
    .DESCRIPTION
        Performs multisegment path joins.
    
    .PARAMETER Path
        The basepath to join on.
    
    .PARAMETER Child
        Any number of child paths to add.
    
    .EXAMPLE
        PS C:\> Join-DbaPath -Path 'C:\temp' 'Foo' 'Bar'
    
        Returns 'C:\temp\Foo\Bar' on windows.
        Returns 'C:/temp/Foo/Bar' on non-windows.
#>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, Position = 0)]
        [string]
        $Path,
        
        [Parameter(ValueFromRemainingArguments = $true)]
        [string[]]
        $Child
    )
    
    $resultingPath = $Path
    if (($PSVersionTable.PSVersion.Major -ge 6) -and (-not $script:isWindows))
    {
        $resultingPath = $resultingPath.Replace("\", "/")
    }
    else { $resultingPath = $resultingPath.Replace("/", "\") }
    
    foreach ($childItem in $Child)
    {
        $resultingPath = Join-Path -Path $resultingPath -ChildPath $childItem
    }
    
    $resultingPath
}
tools\dbatools\internal\functions\utility\Resolve-DbaPath.ps1
function Resolve-DbaPath
{
<#
    .SYNOPSIS
        Resolves a path.
    
    .DESCRIPTION
        Resolves a path.
        Will try to resolve to paths including some basic path validation and resolution.
        Will fail if the path cannot be resolved (so an existing path must be reached at).
    
    .PARAMETER Path
        The path to validate.
    
    .PARAMETER Provider
        Ensure the path is of the expected provider.
        Allows ensuring one does not operate in the wrong provider.
        Common providers include the filesystem, the registry or the active directory.
    
    .PARAMETER SingleItem
        Ensure the path should resolve to a single path only.
        This may - intentionally or not - trip up wildcard paths.
    
    .PARAMETER NewChild
        Assumes one wishes to create a new child item.
        The parent path will be resolved and must validate true.
        The final leaf will be treated as a leaf item that does not exist yet.
    
    .EXAMPLE
        PS C:\> Resolve-DbaPath -Path report.log -Provider FileSystem -NewChild -SingleItem
    
        Ensures the resolved path is a FileSystem path.
        This will resolve to the current folder and the file report.log.
        Will not ensure the file exists or doesn't exist.
        If the current path is in a different provider, it will throw an exception.
    
    .EXAMPLE
        PS C:\> Resolve-DbaPath -Path ..\*
    
        This will resolve all items in the parent folder, whatever the current path or drive might be.
#>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
        [string[]]
        $Path,
        
        [string]
        $Provider,
        
        [switch]
        $SingleItem,
        
        [switch]
        $NewChild
    )
    
    process
    {
        foreach ($inputPath in $Path)
        {
            if ($inputPath -eq ".")
            {
                $inputPath = (Get-Location).Path
            }
            if ($NewChild)
            {
                $parent = Split-Path -Path $inputPath
                $child = Split-Path -Path $inputPath -Leaf
                
                try
                {
                    if (-not $parent) { $parentPath = Get-Location -ErrorAction Stop }
                    else { $parentPath = Resolve-Path $parent -ErrorAction Stop }
                }
                catch { Stop-Function -Message "Failed to resolve path" -ErrorRecord $_ -EnableException $true }
                
                if ($SingleItem -and (($parentPath | Measure-Object).Count -gt 1))
                {
                    Stop-Function -Message "Could not resolve to a single parent path!" -EnableException $true
                }
                
                if ($Provider -and ($parentPath.Provider.Name -ne $Provider))
                {
                    Stop-Function -Message "Resolved provider is $($parentPath.Provider.Name) when it should be $($Provider)" -EnableException $true
                }
                
                foreach ($parentItem in $parentPath)
                {
                    Join-Path $parentItem.ProviderPath $child
                }
            }
            else
            {
                try { $resolvedPaths = Resolve-Path $inputPath -ErrorAction Stop }
                catch { Stop-Function -Message "Failed to resolve path" -ErrorRecord $_ -EnableException $true }
                
                if ($SingleItem -and (($resolvedPaths | Measure-Object).Count -gt 1))
                {
                    Stop-Function -Message "Could not resolve to a single parent path!" -EnableException $true
                }
                
                if ($Provider -and ($resolvedPaths.Provider.Name -ne $Provider))
                {
                    Stop-Function -Message "Resolved provider is $($resolvedPaths.Provider.Name) when it should be $($Provider)" -EnableException $true
                }
                
                $resolvedPaths.ProviderPath
            }
        }
    }
}
tools\dbatools\internal\functions\Where-DbaObject.ps1
function global:Where-DbaObject {
    <#
        .SYNOPSIS
            A slightly more efficient filter function than Where-Object.

        .DESCRIPTION
            A slightly more efficient filter function than Where-Object.
            In case multiple filters are set, any one hit will work.

        .PARAMETER InputObject
            The object to process.

        .PARAMETER PropertyName
            Whether a property should be tested, rather than the input object itself.

        .PARAMETER Equals
            Tests for equality.

        .PARAMETER NotEquals
            Tests for inequality.

        .PARAMETER Like
            Tests for similarity.

        .PARAMETER NotLike
            Tests for non-similarity.

        .PARAMETER In
            Tests, whether the input is contained in a specified list.

        .PARAMETER NotIn
            Tests, whether the input is not contained in a specified list.

        .PARAMETER Match
            Tests for regex match.

        .PARAMETER NotMatch
            Tests for regex non-match.

        .EXAMPLE
            dir | Where-DbaObject Length -gt 1024

            Scans the current folder and filters out all files smaller then 1024 bytes

        .EXAMPLE
            "foo","bar" | Where-DbaObject -match "o"

            Filters out all strings that don't contain the letter "o"
       #>
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline, Mandatory)]
        [object]
        $InputObject,

        [Parameter(Position = 0)]
        [Alias('Property')]
        [string]
        $PropertyName,

        [Alias('Eq')]
        [object]
        $Equals,

        [Alias('Ne')]
        [object]
        $NotEquals,

        [object]
        $Like,

        [object]
        $NotLike,

        [object]
        $In,

        [object]
        $NotIn,

        [object]
        $Match,

        [object]
        $NotMatch
    )

    begin {
        $TestEquals = Test-Bound -ParameterName Equals
        $TestNotEquals = Test-Bound -ParameterName NotEquals
        $TestLike = Test-Bound -ParameterName Like
        $TestNotLike = Test-Bound -ParameterName NotLike
        $TestIn = Test-Bound -ParameterName In
        $TestNotIn = Test-Bound -ParameterName NotIn
        $TestMatch = Test-Bound -ParameterName Match
        $TestNotMatch = Test-Bound -ParameterName NotMatch

        $TestObject = -not ($TestEquals -or $TestNotEquals -or $TestLike -or $TestNotLike -or $TestIn -or $TestNotIn -or $TestMatch -or $TestNotMatch)

        $TestProperty = Test-Bound -ParameterName PropertyName
    }
    process {
        foreach ($item in $InputObject) {
            #region Test Property
            if ($TestProperty) {
                if ($TestObject -and $item.$PropertyName) { return $item }

                if ($TestEquals -and ($item.$PropertyName -eq $Equals)) { return $item }
                if ($TestNotEquals -and ($item.$PropertyName -ne $NotEquals)) { return $item }
                if ($TestLike -and ($item.$PropertyName -like $Like)) { return $item }
                if ($TestNotLike -and ($item.$PropertyName -notlike $NotLike)) { return $item }
                if ($TestIn -and ($item.$PropertyName -In $In)) { return $item }
                if ($TestNotIn -and ($item.$PropertyName -NotIn $NotIn)) { return $item }
                if ($TestMatch -and ($item.$PropertyName -Match $Match)) { return $item }
                if ($TestNotMatch -and ($item.$PropertyName -NotMatch $NotMatch)) { return $item }
            }
            #endregion Test Property
            #region Test Object
            else {
                if ($TestObject -and $item) { return $item }

                if ($TestEquals -and ($item -eq $Equals)) { return $item }
                if ($TestNotEquals -and ($item -ne $NotEquals)) { return $item }
                if ($TestLike -and ($item -like $Like)) { return $item }
                if ($TestNotLike -and ($item -notlike $NotLike)) { return $item }
                if ($TestIn -and ($item -In $In)) { return $item }
                if ($TestNotIn -and ($item -NotIn $NotIn)) { return $item }
                if ($TestMatch -and ($item -Match $Match)) { return $item }
                if ($TestNotMatch -and ($item -NotMatch $NotMatch)) { return $item }
            }
            #endregion Test Object
        }
    }
    end {

    }
}

(Get-Item Function:\Where-DbaObject).Visibility = "Private"
tools\dbatools\internal\functions\Write-ProgressHelper.ps1
function Write-ProgressHelper {
    # thanks adam!
    # https://www.adamtheautomator.com/building-progress-bar-powershell-scripts/
    param (
        [int]$StepNumber,
        [string]$Activity,
        [string]$Message,
        [int]$TotalSteps,
        [switch]$ExcludePercent
    )

    $caller = (Get-PSCallStack)[1].Command

    if (-not $Activity) {
        $Activity = switch ($caller) {
            "Export-DbaInstance" {
                "Performing Instance Export for $instance"
            }
            "Install-DbaSqlWatch" {
                "Installing SQLWatch"
            }
            "Invoke-DbaDbLogShipRecovery" {
                "Performing log shipping recovery"
            }
            "Invoke-DbaDbLogShipRecovery" {
                "Performing log shipping recovery"
            }
            "Invoke-DbaDbMirroring" {
                "Setting up mirroring"
            }
            "New-DbaAvailabilityGroup" {
                "Adding new availability group"
            }
            "Sync-DbaAvailabilityGroup" {
                "Syncing availability group"
            }
            "Sync-DbaAvailabilityGroup" {
                "Syncing availability group"
            }
            default {
                "Executing $caller"
            }
        }
    }

    if ($ExcludePercent) {
        Write-Progress -Activity $Activity -Status $Message
    } else {
        if (-not $TotalSteps -and $caller -ne '<ScriptBlock>') {
            $TotalSteps = ([regex]::Matches((Get-Command -Module dbatools -Name $caller).Definition, "Write-ProgressHelper")).Count
        }
        if (-not $TotalSteps) {
            $percentComplete = 0
        } else {
            $percentComplete = ($StepNumber / $TotalSteps) * 100
        }
        Write-Progress -Activity $Activity -Status $Message -PercentComplete $percentComplete
    }
}
tools\dbatools\internal\maintenance\PSSession-Cleanup.ps1
$scriptBlock = {
    while ([Sqlcollaborative.Dbatools.Connection.ConnectionHost]::PSSessionCountExpired -gt 0) {
        $session = $null
        $session = [Sqlcollaborative.Dbatools.Connection.ConnectionHost]::PSSessionPurgeExpired()
        if ($null -ne $session) { $session | Remove-PSSession }
    }
}
Register-DbaMaintenanceTask -Name "pssession_cleanup" -ScriptBlock $scriptBlock -Delay (New-TimeSpan -Minutes 1) -Priority Low -Interval (New-TimeSpan -Minutes 1)

# Cleans up local references in the current runspace. All actual termination logic is handled by the task above
$script:pssession_cleanup_timer = New-Object System.Timers.TImer
$script:pssession_cleanup_timer.Interval = 60000
$null = Register-ObjectEvent -InputObject $script:pssession_cleanup_timer -EventName elapsed -SourceIdentifier dbatools_Timer -Action { Get-PSSession | Where-Object State -Like Closed | Remove-PSSession } -ErrorAction Ignore
$script:pssession_cleanup_timer.Start()
tools\dbatools\internal\maintenance\tempcleanup.ps1
$scriptBlock = {
    Get-ChildItem -Path $env:TEMP -Filter dbatools* | Remove-Item -ErrorAction Ignore -Recurse
}
Register-DbaMaintenanceTask -Name "tempcleanup" -ScriptBlock $scriptBlock -Once -Delay (New-TimeSpan -Minutes 1) -Priority Low
tools\dbatools\internal\maintenance\teppInsertTask.ps1
$scriptBlock = {
    $ModuleRoot = [Sqlcollaborative.Dbatools.dbaSystem.SystemHost]::ModuleBase

    $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText("$ModuleRoot\internal\functions\Register-DbaTeppScriptblock.ps1"))), $null, $null)
    $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText("$ModuleRoot\internal\functions\Register-DbaTeppInstanceCacheBuilder.ps1"))), $null, $null)

    foreach ($file in (Get-ChildItem "$ModuleRoot\internal\dynamicparams\*.ps1")) {
        $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($file.FullName))), $null, $null)
    }

    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::CalculateTabExpansion()
}
Register-DbaMaintenanceTask -Name "teppInsertTask" -ScriptBlock $scriptBlock -Once
tools\dbatools\internal\scripts\cmdlets.ps1
<#
Registers the cmdlets published by this module.
Necessary for full hybrid module support.
#>
$commonParam = @{
    HelpFile = "$($PSModuleRoot)\en-us\dbatools.dll-Help.xml"
    Module   = $ExecutionContext.SessionState.Module
}

Import-DbaCmdlet @commonParam -Name Write-Message -Type ([Sqlcollaborative.Dbatools.Commands.WriteMessageCommand])
Import-DbaCmdlet @commonParam -Name Select-DbaObject -Type ([Sqlcollaborative.Dbatools.Commands.SelectDbaObjectCommand])
Import-DbaCmdlet @commonParam -Name Set-DbatoolsConfig -Type ([Sqlcollaborative.Dbatools.Commands.SetDbatoolsConfigCommand])
tools\dbatools\internal\scripts\dbatools-maintenance.ps1
foreach ($item in (Get-ChildItem "$script:PSModuleRoot\internal\maintenance" -Filter *.ps1)) {
    if ($script:doDotSource) { . $item.FullName }
    else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($item.FullName))), $null, $null) }
}

$scriptBlock = {
    $script:___ScriptName = 'dbatools-maintenance'

    # Import module in a way where internals are available
    $dbatools_disableTimeMeasurements = $true
    Import-Module "$([Sqlcollaborative.Dbatools.dbaSystem.SystemHost]::ModuleBase)\dbatools.psm1"

    try {
        #region Main Execution
        while ($true) {
            # This portion is critical to gracefully closing the script
            if ([Sqlcollaborative.Dbatools.Runspace.RunspaceHost]::Runspaces[$___ScriptName.ToLower()].State -notlike "Running") {
                break
            }

            $task = $null
            $tasksDone = @()
            while ($task = [Sqlcollaborative.Dbatools.Maintenance.MaintenanceHost]::GetNextTask($tasksDone)) {
                try { ([ScriptBlock]::Create($task.ScriptBlock.ToString())).Invoke() }
                catch { Write-Message -EnableException $false -Level Verbose -Message "[Maintenance] Task '$($task.Name)' failed to execute: $_" -ErrorRecord $_ -FunctionName "task:Maintenance" -Target $task }
                $task.LastExecution = Get-Date
                $tasksDone += $task.Name
            }

            Start-Sleep -Seconds 5
        }
        #endregion Main Execution
    } catch {  }
    finally {
        [Sqlcollaborative.Dbatools.Runspace.RunspaceHost]::Runspaces[$___ScriptName.ToLower()].SignalStopped()
    }
}

Register-DbaRunspace -ScriptBlock $scriptBlock -Name "dbatools-maintenance"
Start-DbaRunspace -Name "dbatools-maintenance"
tools\dbatools\internal\scripts\insertTepp.ps1
if (Get-Command TabExpansionPlusPlus\Register-ArgumentCompleter -ErrorAction Ignore) {
    $script:TEPP = $true
} else {
    $script:TEPP = $false
}

$functions = Get-ChildItem function:\*-Dba*
[Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::DbatoolsCommands = $functions
$names = $functions.Name

#region Automatic TEPP by parameter name
Register-DbaTeppArgumentCompleter -Command $names -Parameter Alert -Name Alert -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter AlertCategory -Name AlertCategory -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter Audit -Name Audit -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter AuditSpecification -Name AuditSpecification -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter AvailabilityGroup -Name AvailabilityGroup -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter BackupDevice -Name BackupDevice -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ConfigName -Name ConfigName -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter Credential -Name Credential -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter CredentialIdentity -Name Credential -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter CustomError -Name CustomError -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter Database -Name Database -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter Endpoint -Name Endpoint -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeAlert -Name Alert -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeAlertCategory -Name AlertCategory -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeAudit -Name Audit -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeAuditSpecification -Name AuditSpecification -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeAvailabilityGroup -Name AvailabilityGroup -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeBackupDevice -Name BackupDevice -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeConfigName -Name ConfigName -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeCredential -Name Credential -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeCredentialIdentity -Name Credential -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeCustomError -Name CustomError -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeDatabase -Name Database -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeEndpoint -Name Endpoint -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeGroup -Name Group -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeJob -Name Job -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeJobCategory -Name JobCategory -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeLinkedServer -Name LinkedServer -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeLogin -Name Login -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeMailAccount -Name MailAccount -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeMailProfile -Name MailProfile -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeMailServer -Name MailServer -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeOperator -Name Operator -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeProxyAccount -Name ProxyAccount -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeResourcePool -Name ResourcePool -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeSchedule -Name Schedule -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeServerTrigger -Name ServerTrigger -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeSession -Name Session -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ExcludeSnapshot -Name Snapshot -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter Group -Name Group -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter Job -Name Job -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter JobCategory -Name JobCategory -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter LinkedServer -Name LinkedServer -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter Login -Name Login -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter MailAccount -Name MailAccount -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter MailProfile -Name MailProfile -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter MailServer -Name MailServer -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter Operator -Name Operator -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ProxyAccount -Name ProxyAccount -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ResourcePool -Name ResourcePool -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter Schedule -Name Schedule -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter ServerTrigger -Name ServerTrigger -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter Session -Name Session -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter Snapshot -Name Snapshot -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter SqlInstance -Name SqlInstance -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter InstanceProperty -Name InstanceProperty -All
Register-DbaTeppArgumentCompleter -Command $names -Parameter PowerPlan -Name PowerPlan -All
#endregion Automatic TEPP by parameter name

#region Explicit TEPP
Register-DbaTeppArgumentCompleter -Command "Import-DbaCsv" -Parameter Delimiter -Name delimiter
Register-DbaTeppArgumentCompleter -Command "Find-DbaCommand" -Parameter Tag -Name tag
Register-DbaTeppArgumentCompleter -Command "Get-DbatoolsConfig", "Get-DbatoolsConfigValue", "Register-DbatoolsConfig", "Set-DbatoolsConfig" -Parameter FullName -Name config
Register-DbaTeppArgumentCompleter -Command "Get-DbatoolsConfig", "Register-DbatoolsConfig", "Set-DbatoolsConfig" -Parameter Module -Name configmodule
Register-DbaTeppArgumentCompleter -Command "Get-DbatoolsConfig", "Register-DbatoolsConfig", "Set-DbatoolsConfig" -Parameter Name -Name config_name
Register-DbaTeppArgumentCompleter -Command "Get-DbaProcess", "Stop-DbaProcess" -Parameter ExcludeSpid -Name processSpid
Register-DbaTeppArgumentCompleter -Command "Get-DbaProcess", "Stop-DbaProcess" -Parameter Hostname -Name processHostname
Register-DbaTeppArgumentCompleter -Command "Get-DbaProcess", "Stop-DbaProcess" -Parameter Program -Name processProgram
Register-DbaTeppArgumentCompleter -Command "Get-DbaProcess", "Stop-DbaProcess" -Parameter Spid -Name processSpid
Register-DbaTeppArgumentCompleter -Command "Import-DbaXESessionTemplate", "Get-DbaXESessionTemplate", "Export-DbaXESessionTemplate" -Parameter Template -Name xesessiontemplate
Register-DbaTeppArgumentCompleter -Command "Import-DbaPfDataCollectorSetTemplate", "Get-DbaPfDataCollectorSetTemplate", "Export-DbaPfDataCollectorSetTemplate"  -Parameter Template -Name perfmontemplate
#endregion Explicit TEPP
tools\dbatools\internal\scripts\logfilescript.ps1
$scriptBlock = {
    $script:___ScriptName = 'dbatools-logging'

    #region Helper Functions
    function Clean-ErrorXml {
        [CmdletBinding()]
        param (
            $Path
        )

        $totalLength = $Null
        $files = Get-ChildItem -Path $Path.FullName -Filter "dbatools_$($pid)_error_*.xml" | Sort-Object LastWriteTime
        $totalLength = $files | Measure-Object Length -Sum | Select-Object -ExpandProperty Sum
        if (([Sqlcollaborative.Dbatools.Message.LogHost]::MaxErrorFileBytes) -gt $totalLength) { return }

        $removed = 0
        foreach ($file in $files) {
            $removed += $file.Length
            Remove-Item -Path $file.FullName -Force -Confirm:$false

            if (($totalLength - $removed) -lt ([Sqlcollaborative.Dbatools.Message.LogHost]::MaxErrorFileBytes)) { break }
        }
    }

    function Clean-MessageLog {
        [CmdletBinding()]
        param (
            $Path
        )

        if ([Sqlcollaborative.Dbatools.Message.LogHost]::MaxMessagefileCount -eq 0) { return }

        $files = Get-ChildItem -Path $Path.FullName -Filter "dbatools_$($pid)_message_*.log" | Sort-Object LastWriteTime
        if (([Sqlcollaborative.Dbatools.Message.LogHost]::MaxMessagefileCount) -ge $files.Count) { return }

        $removed = 0
        foreach ($file in $files) {
            $removed++
            Remove-Item -Path $file.FullName -Force -Confirm:$false

            if (($files.Count - $removed) -le ([Sqlcollaborative.Dbatools.Message.LogHost]::MaxMessagefileCount)) { break }
        }
    }

    function Clean-GlobalLog {
        [CmdletBinding()]
        param (
            $Path
        )

        # Kill too old files
        Get-ChildItem -Path "$($Path.FullName)\*" -Include "*.xml", "*.log" -Filter "*" | Where-Object LastWriteTime -LT ((Get-Date) - ([Sqlcollaborative.Dbatools.Message.LogHost]::MaxLogFileAge)) |Remove-Item -Force -Confirm:$false

        # Handle the global overcrowding
        $files = Get-ChildItem -Path "$($Path.FullName)\*" -Include "*.xml", "*.log" -Filter "*" | Sort-Object LastWriteTime
        if (-not ($files)) { return }
        $totalLength = $files | Measure-Object Length -Sum | Select-Object -ExpandProperty Sum

        if (([Sqlcollaborative.Dbatools.Message.LogHost]::MaxTotalFolderSize) -gt $totalLength) { return }

        $removed = 0
        foreach ($file in $files) {
            $removed += $file.Length
            Remove-Item -Path $file.FullName -Force -Confirm:$false

            if (($totalLength - $removed) -lt ([Sqlcollaborative.Dbatools.Message.LogHost]::MaxTotalFolderSize)) { break }
        }
    }
    #endregion Helper Functions

    try {
        while ($true) {
            # This portion is critical to gracefully closing the script
            if ([Sqlcollaborative.Dbatools.Runspace.RunspaceHost]::Runspaces[$___ScriptName.ToLower()].State -notlike "Running") {
                break
            }

            $path = [Sqlcollaborative.Dbatools.Message.LogHost]::LoggingPath
            if (-not (Test-Path $path)) {
                $root = New-Item $path -ItemType Directory -Force -ErrorAction Stop
            } else { $root = Get-Item -Path $path }

            try { [int]$num_Error = (Get-ChildItem -Path $root.FullName -Filter "dbatools_$($pid)_error_*.xml" | Sort-Object LastWriteTime -Descending | Select-Object -First 1 -ExpandProperty Name | Select-String -Pattern "(\d+)" -AllMatches).Matches[1].Value }
            catch { }
            try { [int]$num_Message = (Get-ChildItem -Path $root.FullName -Filter "dbatools_$($pid)_message_*.log" | Sort-Object LastWriteTime -Descending | Select-Object -First 1 -ExpandProperty Name | Select-String -Pattern "(\d+)" -AllMatches).Matches[1].Value }
            catch { }
            if (-not ($num_Error)) { $num_Error = 0 }
            if (-not ($num_Message)) { $num_Message = 0 }

            #region Process Errors
            while ([Sqlcollaborative.Dbatools.Message.LogHost]::OutQueueError.Count -gt 0) {
                $num_Error++

                $Record = $null
                [Sqlcollaborative.Dbatools.Message.LogHost]::OutQueueError.TryDequeue([ref]$Record)

                if ($Record) {
                    $Record | Export-Clixml -Path "$($root.FullName)\dbatools_$($pid)_error_$($num_Error).xml" -Depth 3
                }

                Clean-ErrorXml -Path $root
            }
            #endregion Process Errors

            #region Process Logs
            while ([Sqlcollaborative.Dbatools.Message.LogHost]::OutQueueLog.Count -gt 0) {
                $CurrentFile = "$($root.FullName)\dbatools_$($pid)_message_$($num_Message).log"
                if (Test-Path $CurrentFile) {
                    $item = Get-Item $CurrentFile
                    if ($item.Length -gt ([Sqlcollaborative.Dbatools.Message.LogHost]::MaxMessagefileBytes)) {
                        $num_Message++
                        $CurrentFile = "$($root.FullName)\dbatools_$($pid)_message_$($num_Message).log"
                    }
                }

                $Entry = $null
                [Sqlcollaborative.Dbatools.Message.LogHost]::OutQueueLog.TryDequeue([ref]$Entry)
                if ($Entry) {
                    Add-Content -Path $CurrentFile -Value (ConvertTo-Csv -InputObject $Entry -NoTypeInformation)[1]
                }
            }
            #endregion Process Logs

            Clean-MessageLog -Path $root
            Clean-GlobalLog -Path $root

            Start-Sleep -Seconds 5
        }
    } catch { }
    finally {
        [Sqlcollaborative.Dbatools.Runspace.RunspaceHost]::Runspaces[$___ScriptName.ToLower()].SignalStopped()
    }
}

Register-DbaRunspace -ScriptBlock $scriptBlock -Name "dbatools-logging"
Start-DbaRunspace -Name "dbatools-logging"
tools\dbatools\internal\scripts\message-transforms.ps1
Register-DbaMessageTransform -TargetType 'Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter' -ScriptBlock {
    $args[0].FullSmoName
}
Register-DbaMessageTransform -TargetType 'Microsoft.SqlServer.Management.Smo.Server' -ScriptBlock {
    ([Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter]$args[0]).FullSmoName
}

Register-DbaMessageTransform -ExceptionTypeFilter '*' -ScriptBlock {
    if ($args[0] -is [System.Data.SqlClient.SqlException]) { return $args[0] }

    $item = $args[0]
    while ($item.InnerException) {
        $item = $item.InnerException
        if ($item -is [System.Data.SqlClient.SqlException]) { return $item }
    }

    return $args[0]
}
tools\dbatools\internal\scripts\smoLibraryImport.ps1
$scriptBlock = {
    param (
        $ModuleRoot,

        $DllRoot,

        $DoCopy
    )

    function Copy-Assembly {
        [CmdletBinding()]
        param (
            [string]$ModuleRoot,
            [string]$DllRoot,
            [bool]$DoCopy,
            [string]$Name
        )
        $DllRoot = (Resolve-Path -Path $DllRoot)
        
        if (-not $DoCopy) {
            return
        }
        if ((Resolve-Path -Path "$ModuleRoot\bin\smo") -eq $DllRoot) {
            return
        }

        if (-not (Test-Path $DllRoot)) {
            $null = New-Item -Path $DllRoot -ItemType Directory -ErrorAction Ignore
        }

        Copy-Item -Path (Resolve-Path -Path "$ModuleRoot\bin\smo\$Name.dll") -Destination $DllRoot
    }
    
    #region Names
    if ($PSVersionTable.PSEdition -eq "Core") {
        $names = @(
            'Microsoft.Data.Tools.Sql.BatchParser',
            'Microsoft.SqlServer.ConnectionInfo',
            'Microsoft.SqlServer.Management.Dmf',
            'Microsoft.SqlServer.Management.PSProvider',
            'Microsoft.SqlServer.Management.PSSnapins',
            'Microsoft.SqlServer.Management.Sdk.Sfc',
            'Microsoft.SqlServer.Management.XEvent',
            'Microsoft.SqlServer.Management.XEventDbScoped',
            'Microsoft.SqlServer.Management.XEventDbScopedEnum',
            'Microsoft.SqlServer.Management.XEventEnum',
            'Microsoft.SqlServer.Smo',
            'Microsoft.SqlServer.SmoExtended',
            'Microsoft.SqlServer.SqlEnum',
            'System.Security.SecureString',
            'Microsoft.Data.Tools.Schema.Sql',
            'Microsoft.Data.Tools.Utilities',
            'Microsoft.SqlServer.Dac',
            'Microsoft.SqlServer.Dac.Extensions',
            'Microsoft.SqlServer.TransactSql.ScriptDom',
            'Microsoft.SqlServer.Types'
        )
    } else {
        $names = @(
            'Microsoft.SqlServer.Smo',
            'Microsoft.SqlServer.Dmf',
            'Microsoft.SqlServer.SqlWmiManagement',
            'Microsoft.SqlServer.ConnectionInfo',
            'Microsoft.SqlServer.SmoExtended',
            'Microsoft.SqlServer.Management.RegisteredServers',
            'Microsoft.SqlServer.Management.Sdk.Sfc',
            'Microsoft.SqlServer.SqlEnum',
            'Microsoft.SqlServer.RegSvrEnum',
            'Microsoft.SqlServer.WmiEnum',
            'Microsoft.SqlServer.ServiceBrokerEnum',
            'Microsoft.SqlServer.Management.Collector',
            'Microsoft.SqlServer.Management.CollectorEnum',
            'Microsoft.SqlServer.Management.Utility',
            'Microsoft.SqlServer.Management.UtilityEnum',
            'Microsoft.SqlServer.Management.HadrDMF',
            'Microsoft.SqlServer.VulnerabilityAssessment.Model',
            
            'Microsoft.SqlServer.BatchParser',
            'Microsoft.SqlServer.BatchParserClient',
            'Microsoft.SqlServer.BulkInsertTaskConnections',
            'Microsoft.SqlServer.DTSRuntimeWrap',
            'Microsoft.SqlServer.DtsServer.Interop',
            'Microsoft.SqlServer.DTSUtilities',
            'Microsoft.SqlServer.ForEachFileEnumeratorWrap',
            'Microsoft.SqlServer.ManagedDTS',
            'Microsoft.SqlServer.IntegrationServices.ODataConnectionManager',
            'Microsoft.SqlServer.IntegrationServices.ODataSrc',
            'Microsoft.SqlServer.PipelineHost',
            'Microsoft.SqlServer.PackageFormatUpdate',
            'Microsoft.SqlServer.Replication',
            'Microsoft.SqlServer.SqlCEDest',
            'Microsoft.SqlServer.SQLTask',
            'Microsoft.SqlServer.TxScript',
            'Microsoft.SqlServer.XE.Core',
            'Microsoft.SqlServer.XEvent.Configuration',
            'Microsoft.SqlServer.XEvent',
            'Microsoft.SqlServer.XEvent.Linq',
            'Microsoft.SqlServer.XmlSrc',
            'Microsoft.SqlServer.Rmo',
            'Microsoft.SqlServer.DTSPipelineWrap',
            'Microsoft.SqlServer.ScriptTask',
            
            'Accessibility',
            'EnvDTE',
            'Microsoft.AnalysisServices.AppLocal.Core',
            'Microsoft.AnalysisServices.AppLocal',
            'Microsoft.Azure.KeyVault.Core',
            'Microsoft.Data.Edm',
            'Microsoft.Data.OData',
            'Microsoft.Practices.TransientFaultHandling.Core',
            'Microsoft.DataTransfer.Common.Utils',
            'Microsoft.SqlServer.ASTasks',
            'Microsoft.SqlServer.ConnectionInfoExtended',
            'Microsoft.SqlServer.DataProfiler',
            'Microsoft.SqlServer.DataProfilingTask',
            'Microsoft.SqlServer.Diagnostics.STrace',
            'Microsoft.SqlServer.Dmf.Common',
            
            'Microsoft.SqlServer.DMQueryTask',
            'Microsoft.SqlServer.DTEnum',
            'Microsoft.SqlServer.Dts.Design',
            'Microsoft.SqlServer.Dts.DtsClient',
            'Microsoft.SqlServer.DtsMsg',
            'Microsoft.SqlServer.Edition',
            'Microsoft.SqlServer.ExecProcTask',
            'Microsoft.SqlServer.ExpressionTask',
            'Microsoft.SqlServer.FileSystemTask',
            'Microsoft.SqlServer.ForEachADOEnumerator',
            'Microsoft.SqlServer.ForEachFromVarEnumerator',
            'Microsoft.SqlServer.ForEachNodeListEnumerator',
            'Microsoft.SqlServer.ForEachSMOEnumerator',
            'Microsoft.SqlServer.FtpTask',
            'Microsoft.SqlServer.GridControl',
            'Microsoft.SqlServer.Instapi',
            'Microsoft.SqlServer.IntegrationServices.ClusterManagement',
            'Microsoft.SqlServer.IntegrationServices.Common.ObjectModel',
            'Microsoft.SqlServer.IntegrationServices.ISServerDBUpgrade',
            'Microsoft.SqlServer.IntegrationServices.Server.Common',
            'Microsoft.SqlServer.IntegrationServices.Server',
            'Microsoft.SqlServer.IntegrationServices.Server.IPC',
            'Microsoft.SqlServer.IntegrationServices.server.shared',
            'Microsoft.SqlServer.IntegrationServices.TaskScheduler',
            'Microsoft.SqlServer.ManagedConnections',
            'Microsoft.SqlServer.Management.CollectorTasks',
            'Microsoft.SqlServer.Management.HelpViewer',
            'Microsoft.SqlServer.Management.IntegrationServices',
            'Microsoft.SqlServer.Management.IntegrationServicesEnum',
            'Microsoft.SqlServer.Management.Sdk.Scripting',
            'Microsoft.SqlServer.Management.Sdk.SqlStudio',
            'Microsoft.SqlServer.Management.SmartAdminPolicies',
            'Microsoft.SqlServer.Management.SqlParser',
            'Microsoft.SqlServer.Management.SystemMetadataProvider',
            'Microsoft.SqlServer.Management.XEvent',
            'Microsoft.SqlServer.Management.XEventDbScoped',
            'Microsoft.SqlServer.Management.XEventDbScopedEnum',
            'Microsoft.SqlServer.Management.XEventEnum',
            'Microsoft.SqlServer.MSMQTask',
            'Microsoft.SqlServer.PipelineXML',
            'Microsoft.SqlServer.PolicyEnum',
            'Microsoft.SqlServer.Replication.BusinessLogicSupport',
            'Microsoft.SqlServer.SendMailTask',
            'Microsoft.SqlServer.SqlClrProvider',
            'Microsoft.SqlServer.SQLTaskConnectionsWrap',
            'Microsoft.SqlServer.SqlTDiagm',
            'Microsoft.SqlServer.SString',
            'Microsoft.SqlServer.TransferDatabasesTask',
            'Microsoft.SqlServer.TransferErrorMessagesTask',
            'Microsoft.SqlServer.TransferJobsTask',
            'Microsoft.SqlServer.TransferLoginsTask',
            'Microsoft.SqlServer.TransferObjectsTask',
            'Microsoft.SqlServer.TransferSqlServerObjectsTask',
            'Microsoft.SqlServer.TransferStoredProceduresTask',
            'Microsoft.SqlServer.Types',
            'Microsoft.SqlServer.Types.resources',
            'Microsoft.SqlServer.VSTAScriptingLib',
            'Microsoft.SqlServer.WebServiceTask',
            'Microsoft.SqlServer.WMIDRTask',
            'Microsoft.SqlServer.WMIEWTask',
            'Microsoft.SqlServer.XMLTask',
            'Microsoft.SqlServer.Dmf.Adapters',
            'Microsoft.SqlServer.DmfSqlClrWrapper'
        )
    }
    #endregion Names

    foreach ($name in $names) {
        Copy-Assembly -ModuleRoot $ModuleRoot -DllRoot $DllRoot -DoCopy $DoCopy -Name $name
    }
    if ($PSVersionTable.PSEdition -eq "Core") {
        foreach ($name in $names) {
            Add-Type -Path (Resolve-Path -Path "$DllRoot\coreclr\$name.dll")
        }
    } else {
        foreach ($name in $names) {
            Add-Type -Path (Resolve-Path -Path "$DllRoot\$name.dll")
        }
    }
}

$smo = (Resolve-Path -Path "$script:DllRoot\smo")

if ($script:serialImport) {
    $scriptBlock.Invoke($script:PSModuleRoot, "$script:DllRoot\smo", (-not $script:strictSecurityMode))
} else {
    $script:smoRunspace = [System.Management.Automation.PowerShell]::Create()
    if ($script:smoRunspace.Runspace.Name) {
        try { $script:smoRunspace.Runspace.Name = "dbatools-import-smo" }
        catch { }
    }
    $script:smoRunspace.AddScript($scriptBlock).AddArgument($script:PSModuleRoot).AddArgument($smo).AddArgument((-not $script:strictSecurityMode))
    $script:smoRunspace.BeginInvoke()
}
tools\dbatools\internal\scripts\updateTeppAsync.ps1
$scriptBlock = {
    $script:___ScriptName = 'dbatools-teppasynccache'

    #region Utility Functions
    function Get-PriorityServer {
        [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::InstanceAccess.Values | Where-Object -Property LastUpdate -LT (New-Object System.DateTime(1, 1, 1, 1, 1, 1))
    }

    function Get-ActionableServer {
        [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::InstanceAccess.Values | Where-Object -Property LastUpdate -LT ((Get-Date) - ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppUpdateInterval)) | Where-Object -Property LastUpdate -GT ((Get-Date) - ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppUpdateTimeout))
    }

    function Update-TeppCache {
        [CmdletBinding()]
        param (
            [Parameter(ValueFromPipeline)]
            $ServerAccess
        )

        begin {

        }
        process {
            if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppUdaterStopper) { break }

            foreach ($instance in $ServerAccess) {
                if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppUdaterStopper) { break }
                $server = New-Object Microsoft.SqlServer.Management.Smo.Server($instance.ConnectionObject)
                try {
                    $server.ConnectionContext.Connect()
                } catch {
                    continue
                }

                $FullSmoName = ([Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter]$server).FullSmoName.ToLower()

                foreach ($scriptBlock in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppGatherScriptsFast)) {
                    # Workaround to avoid stupid issue with scriptblock from different runspace
                    [ScriptBlock]::Create($scriptBlock).Invoke()
                }

                foreach ($scriptBlock in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppGatherScriptsSlow)) {
                    # Workaround to avoid stupid issue with scriptblock from different runspace
                    [ScriptBlock]::Create($scriptBlock).Invoke()
                }

                $server.ConnectionContext.Disconnect()

                $instance.LastUpdate = Get-Date
            }
        }
        end {

        }
    }
    #endregion Utility Functions

    try {
        #region Main Execution
        while ($true) {
            # This portion is critical to gracefully closing the script
            if ([Sqlcollaborative.Dbatools.Runspace.RunspaceHost]::Runspaces[$___ScriptName.ToLower()].State -notlike "Running") {
                break
            }

            Get-PriorityServer | Update-TeppCache

            Get-ActionableServer | Update-TeppCache

            Start-Sleep -Seconds 5
        }
        #endregion Main Execution
    } catch { }
    finally {
        [Sqlcollaborative.Dbatools.Runspace.RunspaceHost]::Runspaces[$___ScriptName.ToLower()].SignalStopped()
    }
}

Register-DbaRunspace -ScriptBlock $scriptBlock -Name "dbatools-teppasynccache"
if (-not ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppAsyncDisabled -or [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::TeppDisabled)) {
    Start-DbaRunspace -Name "dbatools-teppasynccache"
}
tools\dbatools\LICENSE
 
tools\dbatools\optional\Compress-Archive.ps1
if ($PSVersionTable.PSVersion.Major -lt 5) {

    <#
Copied from the Microsoft Module: Microsoft.PowerShell.Archive
Which ships with PowerShell Version 5 but will run under v3.
    #>



    function Compress-Archive {
        <#
            .SYNOPSIS
                Creates an archive, or zipped file, from specified files and folders.

            .DESCRIPTION
                The Compress-Archive cmdlet creates a zipped (or compressed) archive file from one or more specified files or folders. An archive file allows multiple files to be packaged, and optionally compressed, into a single zipped file for easier distribution and storage. An archive file can be compressed by using the compression algorithm specified by the CompressionLevel parameter.

                Because Compress-Archive relies upon the Microsoft .NET Framework API System.IO.Compression.ZipArchive to compress files, the maximum file size that you can compress by using Compress-Archive is currently 2 GB. This is a limitation of the underlying API.

            .PARAMETER Path
                Specifies the path or paths to the files that you want to add to the archive zipped file. This parameter can accept wildcard characters. Wildcard characters allow you to add all files in a folder to your zipped archive file. To specify multiple paths, and include files in multiple locations in your output zipped file, use commas to separate the paths.

            .PARAMETER LiteralPath
                Specifies the path or paths to the files that you want to add to the archive zipped file. Unlike the Path parameter, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose each escape character in single quotation marks, to instruct Windows PowerShell not to interpret any characters as escape sequences. To specify multiple paths, and include files in multiple locations in your output zipped file, use commas to separate the paths.

            .PARAMETER DestinationPath
                Specifies the path to the archive output file. This parameter is required. The specified DestinationPath value should include the desired name of the output zipped file; it specifies either the absolute or relative path to the zipped file. If the file name specified in DestinationPath does not have a .zip file name extension, the cmdlet adds a .zip file name extension.

            .PARAMETER CompressionLevel
                Specifies how much compression to apply when you are creating the archive file. Faster compression requires less time to create the file, but can result in larger file sizes. The acceptable values for this parameter are:

                - Fastest. Use the fastest compression method available to decrease processing time; this can result in larger file sizes.
                - NoCompression. Do not compress the source files.
                - Optimal. Processing time is dependent on file size.

                If this parameter is not specified, the command uses the default value, Optimal.

            .PARAMETER Update
                Updates the specified archive by replacing older versions of files in the archive with newer versions of files that have the same names. You can also add this parameter to add files to an existing archive.

            .PARAMETER Force
                @{Text=}

            .PARAMETER Confirm
                Prompts you for confirmation before running the cmdlet.

            .PARAMETER WhatIf
                Shows what would happen if the cmdlet runs. The cmdlet is not run.

            .EXAMPLE
                Example 1: Create an archive file

                PS C:\>Compress-Archive -LiteralPath C:\Reference\Draftdoc.docx, C:\Reference\Images\diagram2.vsd -CompressionLevel Optimal -DestinationPath C:\Archives\Draft.Zip

                This command creates a new archive file, Draft.zip, by compressing two files, Draftdoc.docx and diagram2.vsd, specified by the LiteralPath parameter. The compression level specified for this operation is Optimal.

            .EXAMPLE
                Example 2: Create an archive with wildcard characters

                PS C:\>Compress-Archive -Path C:\Reference\* -CompressionLevel Fastest -DestinationPath C:\Archives\Draft

                This command creates a new archive file, Draft.zip, in the C:\Archives folder. Note that though the file name extension .zip was not added to the value of the DestinationPath parameter, Windows PowerShell appends this to the specified archive file name automatically. The new archive file contains every file in the C:\Reference folder, because a wildcard character was used in place of specific file names in the Path parameter. The specified compression level is Fastest, which might result in a larger output file, but compresses a large number of files faster.

            .EXAMPLE
                Example 3: Update an existing archive file

                PS C:\>Compress-Archive -Path C:\Reference\* -Update -DestinationPath C:\Archives\Draft.Zip

                This command updates an existing archive file, Draft.Zip, in the C:\Archives folder. The command is run to update Draft.Zip with newer versions of existing files that came from the C:\Reference folder, and also to add new files that have been added to C:\Reference since Draft.Zip was initially created.

            .EXAMPLE
                Example 4: Create an archive from an entire folder

                PS C:\>Compress-Archive -Path C:\Reference -DestinationPath C:\Archives\Draft

                This command creates an archive from an entire folder, C:\Reference. Note that though the file name extension .zip was not added to the value of the DestinationPath parameter, Windows PowerShell appends this to the specified archive file name automatically.
        #>
        [CmdletBinding(DefaultParameterSetName = "Path", SupportsShouldProcess, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=393252")]
        param
        (
            [parameter (Mandatory, Position = 0, ParameterSetName = "Path", ValueFromPipeline, ValueFromPipelineByPropertyName = $true)]
            [parameter (Mandatory, Position = 0, ParameterSetName = "PathWithForce", ValueFromPipeline, ValueFromPipelineByPropertyName = $true)]
            [parameter (Mandatory, Position = 0, ParameterSetName = "PathWithUpdate", ValueFromPipeline, ValueFromPipelineByPropertyName = $true)]
            [ValidateNotNullOrEmpty()]
            [string[]]
            $Path,

            [parameter (Mandatory, ParameterSetName = "LiteralPath", ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true)]
            [parameter (Mandatory, ParameterSetName = "LiteralPathWithForce", ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true)]
            [parameter (Mandatory, ParameterSetName = "LiteralPathWithUpdate", ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true)]
            [ValidateNotNullOrEmpty()]
            [Alias("PSPath")]
            [string[]]
            $LiteralPath,

            [parameter (Mandatory,
                Position = 1,
                ValueFromPipeline = $false,
                ValueFromPipelineByPropertyName = $false)]
            [ValidateNotNullOrEmpty()]
            [string]
            $DestinationPath,

            [parameter (
                mandatory = $false,
                ValueFromPipeline = $false,
                ValueFromPipelineByPropertyName = $false)]
            [ValidateSet("Optimal", "NoCompression", "Fastest")]
            [string]
            $CompressionLevel = "Optimal",

            [parameter(Mandatory, ParameterSetName = "PathWithUpdate", ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $false)]
            [parameter(Mandatory, ParameterSetName = "LiteralPathWithUpdate", ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $false)]
            [switch]
            $Update = $false,

            [parameter(Mandatory, ParameterSetName = "PathWithForce", ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $false)]
            [parameter(Mandatory, ParameterSetName = "LiteralPathWithForce", ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $false)]
            [switch]
            $Force = $false
        )

        BEGIN {
            Add-Type -AssemblyName System.IO.Compression -ErrorAction Ignore
            Add-Type -AssemblyName System.IO.Compression.FileSystem -ErrorAction Ignore

            $zipFileExtension = ".zip"

            $LocalizedData = ConvertFrom-StringData @'
    PathNotFoundError=The path '{0}' either does not exist or is not a valid file system path.
    ExpandArchiveInValidDestinationPath=The path '{0}' is not a valid file system directory path.
    InvalidZipFileExtensionError={0} is not a supported archive file format. {1} is the only supported archive file format.
    ArchiveFileIsReadOnly=The attributes of the archive file {0} is set to 'ReadOnly' hence it cannot be updated. If you intend to update the existing archive file, remove the 'ReadOnly' attribute on the archive file else use -Force parameter to override and create a new archive file.
    ZipFileExistError=The archive file {0} already exists. Use the -Update parameter to update the existing archive file or use the -Force parameter to overwrite the existing archive file.
    DuplicatePathFoundError=The input to {0} parameter contains a duplicate path '{1}'. Provide a unique set of paths as input to {2} parameter.
    ArchiveFileIsEmpty=The archive file {0} is empty.
    CompressProgressBarText=The archive file '{0}' creation is in progress...
    ExpandProgressBarText=The archive file '{0}' expansion is in progress...
    AppendArchiveFileExtensionMessage=The archive file path '{0}' supplied to the DestinationPath patameter does not include .zip extension. Hence .zip is appended to the supplied DestinationPath path and the archive file would be created at '{1}'.
    AddItemtoArchiveFile=Adding '{0}'.
    CreateFileAtExpandedPath=Created '{0}'.
    InvalidArchiveFilePathError=The archive file path '{0}' specified as input to the {1} parameter is resolving to multiple file system paths. Provide a unique path to the {2} parameter where the archive file has to be created.
    InvalidExpandedDirPathError=The directory path '{0}' specified as input to the DestinationPath parameter is resolving to multiple file system paths. Provide a unique path to the Destination parameter where the archive file contents have to be expanded.
    FileExistsError=Failed to create file '{0}' while expanding the archive file '{1}' contents as the file '{2}' already exists. Use the -Force parameter if you want to overwrite the existing directory '{3}' contents when expanding the archive file.
    DeleteArchiveFile=The partially created archive file '{0}' is deleted as it is not usable.
    InvalidDestinationPath=The destination path '{0}' does not contain a valid archive file name.
    PreparingToCompressVerboseMessage=Preparing to compress...
    PreparingToExpandVerboseMessage=Preparing to expand...
'@

            #region Utility Functions
            function GetResolvedPathHelper {
                param
                (
                    [string[]]
                    $path,

                    [boolean]
                    $isLiteralPath,

                    [System.Management.Automation.PSCmdlet]
                    $callerPSCmdlet
                )

                $resolvedPaths = @()

                # null and empty check are are already done on Path parameter at the cmdlet layer.
                foreach ($currentPath in $path) {
                    try {
                        if ($isLiteralPath) {
                            $currentResolvedPaths = Resolve-Path -LiteralPath $currentPath -ErrorAction Stop
                        } else {
                            $currentResolvedPaths = Resolve-Path -Path $currentPath -ErrorAction Stop
                        }
                    } catch {
                        $errorMessage = ($LocalizedData.PathNotFoundError -f $currentPath)
                        $exception = New-Object System.InvalidOperationException $errorMessage, $_.Exception
                        $errorRecord = CreateErrorRecordHelper "ArchiveCmdletPathNotFound" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $currentPath
                        $callerPSCmdlet.ThrowTerminatingError($errorRecord)
                    }

                    foreach ($currentResolvedPath in $currentResolvedPaths) {
                        $resolvedPaths += $currentResolvedPath.ProviderPath
                    }
                }

                $resolvedPaths
            }

            function Add-CompressionAssemblies {

                if ($PSEdition -eq "Desktop") {
                    Add-Type -AssemblyName System.IO.Compression
                    Add-Type -AssemblyName System.IO.Compression.FileSystem
                }
            }

            function IsValidFileSystemPath {
                param
                (
                    [string[]]
                    $path
                )

                $result = $true;

                # null and empty check are are already done on Path parameter at the cmdlet layer.
                foreach ($currentPath in $path) {
                    if (!([System.IO.File]::Exists($currentPath) -or [System.IO.Directory]::Exists($currentPath))) {
                        $errorMessage = ($LocalizedData.PathNotFoundError -f $currentPath)
                        ThrowTerminatingErrorHelper "PathNotFound" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $currentPath
                    }
                }

                return $result;
            }


            function ValidateDuplicateFileSystemPath {
                param
                (
                    [string]
                    $inputParameter,

                    [string[]]
                    $path
                )

                $uniqueInputPaths = @()

                # null and empty check are are already done on Path parameter at the cmdlet layer.
                foreach ($currentPath in $path) {
                    $currentInputPath = $currentPath.ToUpper()
                    if ($uniqueInputPaths.Contains($currentInputPath)) {
                        $errorMessage = ($LocalizedData.DuplicatePathFoundError -f $inputParameter, $currentPath, $inputParameter)
                        ThrowTerminatingErrorHelper "DuplicatePathFound" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $currentPath
                    } else {
                        $uniqueInputPaths += $currentInputPath
                    }
                }
            }

            function CompressionLevelMapper {
                param
                (
                    [string]
                    $compressionLevel
                )

                $compressionLevelFormat = [System.IO.Compression.CompressionLevel]::Optimal

                # CompressionLevel format is already validated at the cmdlet layer.
                switch ($compressionLevel.ToString()) {
                    "Fastest" {
                        $compressionLevelFormat = [System.IO.Compression.CompressionLevel]::Fastest
                    }
                    "NoCompression" {
                        $compressionLevelFormat = [System.IO.Compression.CompressionLevel]::NoCompression
                    }
                }

                return $compressionLevelFormat
            }

            function CompressArchiveHelper {
                param
                (
                    [string[]]
                    $sourcePath,

                    [string]
                    $destinationPath,

                    [string]
                    $compressionLevel,

                    [bool]
                    $isUpdateMode
                )

                $numberOfItemsArchived = 0
                $sourceFilePaths = @()
                $sourceDirPaths = @()

                foreach ($currentPath in $sourcePath) {
                    $result = Test-Path -LiteralPath $currentPath -PathType Leaf
                    if ($result -eq $true) {
                        $sourceFilePaths += $currentPath
                    } else {
                        $sourceDirPaths += $currentPath
                    }
                }

                # The Soure Path contains one or more directory (this directory can have files under it) and no files to be compressed.
                if ($sourceFilePaths.Count -eq 0 -and $sourceDirPaths.Count -gt 0) {
                    $currentSegmentWeight = 100 / [double]$sourceDirPaths.Count
                    $previousSegmentWeight = 0
                    foreach ($currentSourceDirPath in $sourceDirPaths) {
                        $count = CompressSingleDirHelper $currentSourceDirPath $destinationPath $compressionLevel $true $isUpdateMode $previousSegmentWeight $currentSegmentWeight
                        $numberOfItemsArchived += $count
                        $previousSegmentWeight += $currentSegmentWeight
                    }
                }

                # The Soure Path contains only files to be compressed.
                elseIf ($sourceFilePaths.Count -gt 0 -and $sourceDirPaths.Count -eq 0) {
                    # $previousSegmentWeight is equal to 0 as there are no prior segments.
                    # $currentSegmentWeight is set to 100 as all files have equal weightage.
                    $previousSegmentWeight = 0
                    $currentSegmentWeight = 100

                    $numberOfItemsArchived = CompressFilesHelper $sourceFilePaths $destinationPath $compressionLevel $isUpdateMode $previousSegmentWeight $currentSegmentWeight
                }
                # The Soure Path contains one or more files and one or more directories (this directory can have files under it) to be compressed.
                elseif ($sourceFilePaths.Count -gt 0 -and $sourceDirPaths.Count -gt 0) {
                    # each directory is considered as an individual segments & all the individual files are clubed in to a separate sgemnet.
                    $currentSegmentWeight = 100 / [double]($sourceDirPaths.Count + 1)
                    $previousSegmentWeight = 0

                    foreach ($currentSourceDirPath in $sourceDirPaths) {
                        $count = CompressSingleDirHelper $currentSourceDirPath $destinationPath $compressionLevel $true $isUpdateMode $previousSegmentWeight $currentSegmentWeight
                        $numberOfItemsArchived += $count
                        $previousSegmentWeight += $currentSegmentWeight
                    }

                    $count = CompressFilesHelper $sourceFilePaths $destinationPath $compressionLevel $isUpdateMode $previousSegmentWeight $currentSegmentWeight
                    $numberOfItemsArchived += $count
                }

                return $numberOfItemsArchived
            }

            function CompressFilesHelper {
                param
                (
                    [string[]]
                    $sourceFilePaths,

                    [string]
                    $destinationPath,

                    [string]
                    $compressionLevel,

                    [bool]
                    $isUpdateMode,

                    [double]
                    $previousSegmentWeight,

                    [double]
                    $currentSegmentWeight
                )

                $numberOfItemsArchived = ZipArchiveHelper $sourceFilePaths $destinationPath $compressionLevel $isUpdateMode $null $previousSegmentWeight $currentSegmentWeight

                return $numberOfItemsArchived
            }

            function CompressSingleDirHelper {
                param
                (
                    [string]
                    $sourceDirPath,

                    [string]
                    $destinationPath,

                    [string]
                    $compressionLevel,

                    [bool]
                    $useParentDirAsRoot,

                    [bool]
                    $isUpdateMode,

                    [double]
                    $previousSegmentWeight,

                    [double]
                    $currentSegmentWeight
                )

                [System.Collections.Generic.List[System.String]]$subDirFiles = @()

                if ($useParentDirAsRoot) {
                    $sourceDirInfo = New-Object -TypeName System.IO.DirectoryInfo -ArgumentList $sourceDirPath
                    $sourceDirFullName = $sourceDirInfo.Parent.FullName

                    # If the directory is present at the drive level the DirectoryInfo.Parent include '\' example: C:\
                    # On the other hand if the directory exists at a deper level then DirectoryInfo.Parent
                    # has just the path (without an ending '\'). example C:\source
                    if ($sourceDirFullName.Length -eq 3) {
                        $modifiedSourceDirFullName = $sourceDirFullName
                    } else {
                        $modifiedSourceDirFullName = $sourceDirFullName + "\"
                    }
                } else {
                    $sourceDirFullName = $sourceDirPath
                    $modifiedSourceDirFullName = $sourceDirFullName + "\"
                }

                $dirContents = Get-ChildItem -LiteralPath $sourceDirPath -Recurse
                foreach ($currentContent in $dirContents) {
                    $isContainer = $currentContent -is [System.IO.DirectoryInfo]
                    if (!$isContainer) {
                        $subDirFiles.Add($currentContent.FullName)
                    } else {
                        # The currentContent points to a directory.
                        # We need to check if the directory is an empty directory, if so such a
                        # directory has to be explictly added to the archive file.
                        # if there are no files in the directory the GetFiles() API returns an empty array.
                        $files = $currentContent.GetFiles()
                        if ($files.Count -eq 0) {
                            $subDirFiles.Add($currentContent.FullName + "\")
                        }
                    }
                }

                $numberOfItemsArchived = ZipArchiveHelper $subDirFiles.ToArray() $destinationPath $compressionLevel $isUpdateMode $modifiedSourceDirFullName $previousSegmentWeight $currentSegmentWeight

                return $numberOfItemsArchived
            }

            function ZipArchiveHelper {
                param
                (
                    [System.Collections.Generic.List[System.String]]
                    $sourcePaths,

                    [string]
                    $destinationPath,

                    [string]
                    $compressionLevel,

                    [bool]
                    $isUpdateMode,

                    [string]
                    $modifiedSourceDirFullName,

                    [double]
                    $previousSegmentWeight,

                    [double]
                    $currentSegmentWeight
                )

                $numberOfItemsArchived = 0
                $fileMode = [System.IO.FileMode]::Create
                $result = Test-Path -LiteralPath $DestinationPath -PathType Leaf
                if ($result -eq $true) {
                    $fileMode = [System.IO.FileMode]::Open
                }

                Add-CompressionAssemblies

                try {
                    # At this point we are sure that the archive file has write access.
                    $archiveFileStreamArgs = @($destinationPath, $fileMode)
                    $archiveFileStream = New-Object -TypeName System.IO.FileStream -ArgumentList $archiveFileStreamArgs

                    $zipArchiveArgs = @($archiveFileStream, [System.IO.Compression.ZipArchiveMode]::Update, $false)
                    $zipArchive = New-Object -TypeName System.IO.Compression.ZipArchive -ArgumentList $zipArchiveArgs

                    $currentEntryCount = 0
                    $progressBarStatus = ($LocalizedData.CompressProgressBarText -f $destinationPath)
                    $bufferSize = 4kb
                    $buffer = New-Object Byte[] $bufferSize

                    foreach ($currentFilePath in $sourcePaths) {
                        if ($modifiedSourceDirFullName -ne $null -and $modifiedSourceDirFullName.Length -gt 0) {
                            $index = $currentFilePath.IndexOf($modifiedSourceDirFullName, [System.StringComparison]::OrdinalIgnoreCase)
                            $currentFilePathSubString = $currentFilePath.Substring($index, $modifiedSourceDirFullName.Length)
                            $relativeFilePath = $currentFilePath.Replace($currentFilePathSubString, "").Trim()
                        } else {
                            $relativeFilePath = [System.IO.Path]::GetFileName($currentFilePath)
                        }

                        # Update mode is selected.
                        # Check to see if archive file already contains one or more zip files in it.
                        if ($isUpdateMode -eq $true -and $zipArchive.Entries.Count -gt 0) {
                            $entryToBeUpdated = $null

                            # Check if the file already exists in the archive file.
                            # If so replace it with new file from the input source.
                            # If the file does not exist in the archive file then default to
                            # create mode and create the entry in the archive file.

                            foreach ($currentArchiveEntry in $zipArchive.Entries) {
                                if ($currentArchiveEntry.FullName -eq $relativeFilePath) {
                                    $entryToBeUpdated = $currentArchiveEntry
                                    break
                                }
                            }

                            if ($entryToBeUpdated -ne $null) {
                                $addItemtoArchiveFileMessage = ($LocalizedData.AddItemtoArchiveFile -f $currentFilePath)
                                $entryToBeUpdated.Delete()
                            }
                        }

                        $compression = CompressionLevelMapper $compressionLevel

                        # If a directory needs to be added to an archive file,
                        # by convention the .Net API's expect the path of the diretcory
                        # to end with '\' to detect the path as an directory.
                        if (!$relativeFilePath.EndsWith("\", [StringComparison]::OrdinalIgnoreCase)) {
                            try {
                                try {
                                    $currentFileStream = [System.IO.File]::Open($currentFilePath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read)
                                } catch {
                                    # Failed to access the file. Write a non terminating error to the pipeline
                                    # and move on with the remaining files.
                                    $exception = $_.Exception
                                    if ($null -ne $_.Exception -and
                                        $null -ne $_.Exception.InnerException) {
                                        $exception = $_.Exception.InnerException
                                    }
                                    $errorRecord = CreateErrorRecordHelper "CompressArchiveUnauthorizedAccessError" $null ([System.Management.Automation.ErrorCategory]::PermissionDenied) $exception $currentFilePath
                                    Write-Error -ErrorRecord $errorRecord
                                }

                                if ($null -ne $currentFileStream) {
                                    $srcStream = New-Object System.IO.BinaryReader $currentFileStream

                                    $currentArchiveEntry = $zipArchive.CreateEntry($relativeFilePath, $compression)

                                    # Updating  the File Creation time so that the same timestamp would be retained after expanding the compressed file.
                                    # At this point we are sure that Get-ChildItem would succeed.
                                    $currentArchiveEntry.LastWriteTime = (Get-Item -LiteralPath $currentFilePath).LastWriteTime

                                    $destStream = New-Object System.IO.BinaryWriter $currentArchiveEntry.Open()

                                    while ($numberOfBytesRead = $srcStream.Read($buffer, 0, $bufferSize)) {
                                        $destStream.Write($buffer, 0, $numberOfBytesRead)
                                        $destStream.Flush()
                                    }

                                    $numberOfItemsArchived += 1
                                    $addItemtoArchiveFileMessage = ($LocalizedData.AddItemtoArchiveFile -f $currentFilePath)
                                }
                            } finally {
                                If ($null -ne $currentFileStream) {
                                    $currentFileStream.Dispose()
                                }
                                If ($null -ne $srcStream) {
                                    $srcStream.Dispose()
                                }
                                If ($null -ne $destStream) {
                                    $destStream.Dispose()
                                }
                            }
                        } else {
                            $currentArchiveEntry = $zipArchive.CreateEntry("$relativeFilePath", $compression)
                            $numberOfItemsArchived += 1
                            $addItemtoArchiveFileMessage = ($LocalizedData.AddItemtoArchiveFile -f $currentFilePath)
                        }

                        if ($null -ne $addItemtoArchiveFileMessage) {
                            Write-Verbose $addItemtoArchiveFileMessage
                        }

                        $currentEntryCount += 1
                        ProgressBarHelper "Compress-Archive" $progressBarStatus $previousSegmentWeight $currentSegmentWeight $sourcePaths.Count  $currentEntryCount
                    }
                } finally {
                    If ($null -ne $zipArchive) {
                        $zipArchive.Dispose()
                    }

                    If ($null -ne $archiveFileStream) {
                        $archiveFileStream.Dispose()
                    }

                    # Complete writing progress.
                    Write-Progress -Activity "Compress-Archive" -Completed
                }

                return $numberOfItemsArchived
            }

            <############################################################################################
# ValidateArchivePathHelper: This is a helper function used to validate the archive file
# path & its file format. The only supported archive file format is .zip
############################################################################################>
            function ValidateArchivePathHelper {
                param
                (
                    [string]
                    $archiveFile
                )

                if ([System.IO.File]::Exists($archiveFile)) {
                    $extension = [system.IO.Path]::GetExtension($archiveFile)

                    # Invalid file extension is specifed for the zip file.
                    if ($extension -ne $zipFileExtension) {
                        $errorMessage = ($LocalizedData.InvalidZipFileExtensionError -f $extension, $zipFileExtension)
                        ThrowTerminatingErrorHelper "NotSupportedArchiveFileExtension" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $extension
                    }
                } else {
                    $errorMessage = ($LocalizedData.PathNotFoundError -f $archiveFile)
                    ThrowTerminatingErrorHelper "PathNotFound" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $archiveFile
                }
            }

            <############################################################################################
# ExpandArchiveHelper: This is a helper function used to expand the archive file contents
# to the specified directory.
############################################################################################>
            function ExpandArchiveHelper {
                param
                (
                    [string]
                    $archiveFile,

                    [string]
                    $expandedDir,

                    [ref]
                    $expandedItems,

                    [boolean]
                    $force,

                    [boolean]
                    $isVerbose,

                    [boolean]
                    $isConfirm
                )

                Add-CompressionAssemblies

                try {
                    # The existance of archive file has already been validated by ValidateArchivePathHelper
                    # before calling this helper function.
                    $archiveFileStreamArgs = @($archiveFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read)
                    $archiveFileStream = New-Object -TypeName System.IO.FileStream -ArgumentList $archiveFileStreamArgs

                    $zipArchiveArgs = @($archiveFileStream, [System.IO.Compression.ZipArchiveMode]::Read, $false)
                    $zipArchive = New-Object -TypeName System.IO.Compression.ZipArchive -ArgumentList $zipArchiveArgs

                    if ($zipArchive.Entries.Count -eq 0) {
                        $archiveFileIsEmpty = ($LocalizedData.ArchiveFileIsEmpty -f $archiveFile)
                        Write-Verbose $archiveFileIsEmpty
                        return
                    }

                    $currentEntryCount = 0
                    $progressBarStatus = ($LocalizedData.ExpandProgressBarText -f $archiveFile)

                    # The archive entries can either be empty directories or files.
                    foreach ($currentArchiveEntry in $zipArchive.Entries) {
                        $currentArchiveEntryPath = Join-Path -Path $expandedDir -ChildPath $currentArchiveEntry.FullName
                        $extension = [system.IO.Path]::GetExtension($currentArchiveEntryPath)

                        # The current archive entry is an empty directory
                        # The FullName of the Archive Entry representing a directory would end with a trailing '\'.
                        if ($extension -eq [string]::Empty -and
                            $currentArchiveEntryPath.EndsWith("\", [StringComparison]::OrdinalIgnoreCase)) {
                            $pathExists = Test-Path -LiteralPath $currentArchiveEntryPath

                            # The current archive entry expects an empty directory.
                            # Check if the existing directory is empty. If its not empty
                            # then it means that user has added this directory by other means.
                            if ($pathExists -eq $false) {
                                New-Item $currentArchiveEntryPath -ItemType Directory -Confirm:$isConfirm | Out-Null

                                if (Test-Path -LiteralPath $currentArchiveEntryPath -PathType Container) {
                                    $addEmptyDirectorytoExpandedPathMessage = ($LocalizedData.AddItemtoArchiveFile -f $currentArchiveEntryPath)
                                    Write-Verbose $addEmptyDirectorytoExpandedPathMessage

                                    $expandedItems.Value += $currentArchiveEntryPath
                                }
                            }
                        } else {
                            try {
                                $currentArchiveEntryFileInfo = New-Object -TypeName System.IO.FileInfo -ArgumentList $currentArchiveEntryPath
                                $parentDirExists = Test-Path -LiteralPath $currentArchiveEntryFileInfo.DirectoryName -PathType Container

                                # If the Parent directory of the current entry in the archive file does not exist, then create it.
                                if ($parentDirExists -eq $false) {
                                    New-Item $currentArchiveEntryFileInfo.DirectoryName -ItemType Directory -Confirm:$isConfirm | Out-Null

                                    if (!(Test-Path -LiteralPath $currentArchiveEntryFileInfo.DirectoryName -PathType Container)) {
                                        # The directory referred by $currentArchiveEntryFileInfo.DirectoryName was not successfully created.
                                        # This could be because the user has specified -Confirm paramter when Expand-Archive was invoked
                                        # and authorization was not provided when confirmation was prompted. In such a scenario,
                                        # we skip the current file in the archive and continue with the remaining archive file contents.
                                        Continue
                                    }

                                    $expandedItems.Value += $currentArchiveEntryFileInfo.DirectoryName
                                }

                                $hasNonTerminatingError = $false

                                # Check if the file in to which the current archive entry contents
                                # would be expanded already exists.
                                if ($currentArchiveEntryFileInfo.Exists) {
                                    if ($force) {
                                        Remove-Item -LiteralPath $currentArchiveEntryFileInfo.FullName -Force -ErrorVariable ev -Verbose:$isVerbose -Confirm:$isConfirm
                                        if ($ev -ne $null) {
                                            $hasNonTerminatingError = $true
                                        }

                                        if (Test-Path -LiteralPath $currentArchiveEntryFileInfo.FullName -PathType Leaf) {
                                            # The file referred by $currentArchiveEntryFileInfo.FullName was not successfully removed.
                                            # This could be because the user has specified -Confirm paramter when Expand-Archive was invoked
                                            # and authorization was not provided when confirmation was prompted. In such a scenario,
                                            # we skip the current file in the archive and continue with the remaining archive file contents.
                                            Continue
                                        }
                                    } else {
                                        # Write non-terminating error to the pipeline.
                                        $errorMessage = ($LocalizedData.FileExistsError -f $currentArchiveEntryFileInfo.FullName, $archiveFile, $currentArchiveEntryFileInfo.FullName, $currentArchiveEntryFileInfo.FullName)
                                        $errorRecord = CreateErrorRecordHelper "ExpandArchiveFileExists" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidOperation) $null $currentArchiveEntryFileInfo.FullName
                                        Write-Error -ErrorRecord $errorRecord
                                        $hasNonTerminatingError = $true
                                    }
                                }

                                if (!$hasNonTerminatingError) {
                                    [System.IO.Compression.ZipFileExtensions]::ExtractToFile($currentArchiveEntry, $currentArchiveEntryPath, $false)

                                    # Add the expanded file path to the $expandedItems array,
                                    # to keep track of all the expanded files created while expanding the archive file.
                                    # If user enters CTRL + C then at that point of time, all these expanded files
                                    # would be deleted as part of the clean up process.
                                    $expandedItems.Value += $currentArchiveEntryPath

                                    $addFiletoExpandedPathMessage = ($LocalizedData.CreateFileAtExpandedPath -f $currentArchiveEntryPath)
                                    Write-Verbose $addFiletoExpandedPathMessage
                                }
                            } finally {
                                If ($null -ne $destStream) {
                                    $destStream.Dispose()
                                }

                                If ($null -ne $srcStream) {
                                    $srcStream.Dispose()
                                }
                            }
                        }

                        $currentEntryCount += 1
                        # $currentSegmentWeight is Set to 100 giving equal weightage to each file that is getting expanded.
                        # $previousSegmentWeight is set to 0 as there are no prior segments.
                        $previousSegmentWeight = 0
                        $currentSegmentWeight = 100
                        ProgressBarHelper "Expand-Archive" $progressBarStatus $previousSegmentWeight $currentSegmentWeight $zipArchive.Entries.Count  $currentEntryCount
                    }
                } finally {
                    If ($null -ne $zipArchive) {
                        $zipArchive.Dispose()
                    }

                    If ($null -ne $archiveFileStream) {
                        $archiveFileStream.Dispose()
                    }

                    # Complete writing progress.
                    Write-Progress -Activity "Expand-Archive" -Completed
                }
            }

            <############################################################################################
# ProgressBarHelper: This is a helper function used to display progress message.
# This function is used by both Compress-Archive & Expand-Archive to display archive file
# creation/expansion progress.
############################################################################################>
            function ProgressBarHelper {
                param
                (
                    [string]
                    $cmdletName,

                    [string]
                    $status,

                    [double]
                    $previousSegmentWeight,

                    [double]
                    $currentSegmentWeight,

                    [int]
                    $totalNumberofEntries,

                    [int]
                    $currentEntryCount
                )

                if ($currentEntryCount -gt 0 -and
                    $totalNumberofEntries -gt 0 -and
                    $previousSegmentWeight -ge 0 -and
                    $currentSegmentWeight -gt 0) {
                    $entryDefaultWeight = $currentSegmentWeight / [double]$totalNumberofEntries

                    $percentComplete = $previousSegmentWeight + ($entryDefaultWeight * $currentEntryCount)
                    Write-Progress -Activity $cmdletName -Status $status -PercentComplete $percentComplete
                }
            }

            <############################################################################################
# CSVHelper: This is a helper function used to append comma after each path specifid by
# the SourcePath array. This helper function is used to display all the user supplied paths
# in the WhatIf message.
############################################################################################>
            function CSVHelper {
                param
                (
                    [string[]]
                    $sourcePath
                )

                # SourcePath has already been validated by the calling funcation.
                if ($sourcePath.Count -gt 1) {
                    $sourcePathInCsvFormat = "`n"
                    for ($currentIndex = 0; $currentIndex -lt $sourcePath.Count; $currentIndex++) {
                        if ($currentIndex -eq $sourcePath.Count - 1) {
                            $sourcePathInCsvFormat += $sourcePath[$currentIndex]
                        } else {
                            $sourcePathInCsvFormat += $sourcePath[$currentIndex] + "`n"
                        }
                    }
                } else {
                    $sourcePathInCsvFormat = $sourcePath
                }

                return $sourcePathInCsvFormat
            }

            <############################################################################################
# ThrowTerminatingErrorHelper: This is a helper function used to throw terminating error.
############################################################################################>
            function ThrowTerminatingErrorHelper {
                param
                (
                    [string]
                    $errorId,

                    [string]
                    $errorMessage,

                    [System.Management.Automation.ErrorCategory]
                    $errorCategory,

                    [object]
                    $targetObject,

                    [Exception]
                    $innerException
                )

                if ($innerException -eq $null) {
                    $exception = New-object System.IO.IOException $errorMessage
                } else {
                    $exception = New-Object System.IO.IOException $errorMessage, $innerException
                }

                $exception = New-Object System.IO.IOException $errorMessage
                $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, $errorId, $errorCategory, $targetObject
                $PSCmdlet.ThrowTerminatingError($errorRecord)
            }

            <############################################################################################
# CreateErrorRecordHelper: This is a helper function used to create an ErrorRecord
############################################################################################>
            function CreateErrorRecordHelper {
                param
                (
                    [string]
                    $errorId,

                    [string]
                    $errorMessage,

                    [System.Management.Automation.ErrorCategory]
                    $errorCategory,

                    [Exception]
                    $exception,

                    [object]
                    $targetObject
                )

                if ($null -eq $exception) {
                    $exception = New-Object System.IO.IOException $errorMessage
                }

                $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, $errorId, $errorCategory, $targetObject
                return $errorRecord
            }
            #endregion Utility Functions

            $inputPaths = @()
            $destinationParentDir = [system.IO.Path]::GetDirectoryName($DestinationPath)
            if ($null -eq $destinationParentDir) {
                $errorMessage = ($LocalizedData.InvalidDestinationPath -f $DestinationPath)
                ThrowTerminatingErrorHelper "InvalidArchiveFilePath" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $DestinationPath
            }

            if ($destinationParentDir -eq [string]::Empty) {
                $destinationParentDir = '.'
            }

            $achiveFileName = [system.IO.Path]::GetFileName($DestinationPath)
            $destinationParentDir = GetResolvedPathHelper $destinationParentDir $false $PSCmdlet

            if ($destinationParentDir.Count -gt 1) {
                $errorMessage = ($LocalizedData.InvalidArchiveFilePathError -f $DestinationPath, "DestinationPath", "DestinationPath")
                ThrowTerminatingErrorHelper "InvalidArchiveFilePath" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $DestinationPath
            }

            IsValidFileSystemPath $destinationParentDir | Out-Null
            $DestinationPath = Join-Path -Path $destinationParentDir -ChildPath $achiveFileName

            # GetExtension API does not validate for the actual existance of the path.
            $extension = [system.IO.Path]::GetExtension($DestinationPath)

            # If user does not specify .Zip extension, we append it.
            If ($extension -eq [string]::Empty) {
                $DestinationPathWithOutExtension = $DestinationPath
                $DestinationPath = $DestinationPathWithOutExtension + $zipFileExtension
                $appendArchiveFileExtensionMessage = ($LocalizedData.AppendArchiveFileExtensionMessage -f $DestinationPathWithOutExtension, $DestinationPath)
                Write-Verbose $appendArchiveFileExtensionMessage
            } else {
                # Invalid file extension is specified for the zip file to be created.
                if ($extension -ne $zipFileExtension) {
                    $errorMessage = ($LocalizedData.InvalidZipFileExtensionError -f $extension, $zipFileExtension)
                    ThrowTerminatingErrorHelper "NotSupportedArchiveFileExtension" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $extension
                }
            }

            $archiveFileExist = Test-Path -LiteralPath $DestinationPath -PathType Leaf

            if ($archiveFileExist -and ($Update -eq $false -and $Force -eq $false)) {
                $errorMessage = ($LocalizedData.ZipFileExistError -f $DestinationPath)
                ThrowTerminatingErrorHelper "ArchiveFileExists" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $DestinationPath
            }

            # If archive file already exists and if -Update is specified, then we check to see
            # if we have write access permission to update the existing archive file.
            if ($archiveFileExist -and $Update -eq $true) {
                $item = Get-Item -Path $DestinationPath
                if ($item.Attributes.ToString().Contains("ReadOnly")) {
                    $errorMessage = ($LocalizedData.ArchiveFileIsReadOnly -f $DestinationPath)
                    ThrowTerminatingErrorHelper "ArchiveFileIsReadOnly" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidOperation) $DestinationPath
                }
            }

            $isWhatIf = $psboundparameters.ContainsKey("WhatIf")
            if (!$isWhatIf) {
                $preparingToCompressVerboseMessage = ($LocalizedData.PreparingToCompressVerboseMessage)
                Write-Verbose $preparingToCompressVerboseMessage

                $progressBarStatus = ($LocalizedData.CompressProgressBarText -f $DestinationPath)
                ProgressBarHelper "Compress-Archive" $progressBarStatus 0 100 100 1
            }
        }
        PROCESS {
            if ($PsCmdlet.ParameterSetName -eq "Path" -or
                $PsCmdlet.ParameterSetName -eq "PathWithForce" -or
                $PsCmdlet.ParameterSetName -eq "PathWithUpdate") {
                $inputPaths += $Path
            }

            if ($PsCmdlet.ParameterSetName -eq "LiteralPath" -or
                $PsCmdlet.ParameterSetName -eq "LiteralPathWithForce" -or
                $PsCmdlet.ParameterSetName -eq "LiteralPathWithUpdate") {
                $inputPaths += $LiteralPath
            }
        }
        END {
            # If archive file already exists and if -Force is specified, we delete the
            # existing artchive file and create a brand new one.
            if (($PsCmdlet.ParameterSetName -eq "PathWithForce" -or
                    $PsCmdlet.ParameterSetName -eq "LiteralPathWithForce") -and $archiveFileExist) {
                Remove-Item -Path $DestinationPath -Force -ErrorAction Stop
            }

            # Validate Source Path depeding on parameter set being used.
            # The specified source path conatins one or more files or directories that needs
            # to be compressed.
            $isLiteralPathUsed = $false
            if ($PsCmdlet.ParameterSetName -eq "LiteralPath" -or
                $PsCmdlet.ParameterSetName -eq "LiteralPathWithForce" -or
                $PsCmdlet.ParameterSetName -eq "LiteralPathWithUpdate") {
                $isLiteralPathUsed = $true
            }

            ValidateDuplicateFileSystemPath $PsCmdlet.ParameterSetName $inputPaths
            $resolvedPaths = GetResolvedPathHelper $inputPaths $isLiteralPathUsed $PSCmdlet
            IsValidFileSystemPath $resolvedPaths | Out-Null

            $sourcePath = $resolvedPaths;

            # CSVHelper: This is a helper function used to append comma after each path specifid by
            # the $sourcePath array. The comma saperated paths are displayed in the -WhatIf message.
            $sourcePathInCsvFormat = CSVHelper $sourcePath
            if ($pscmdlet.ShouldProcess($sourcePathInCsvFormat)) {
                try {
                    # StopProcessing is not avaliable in Script cmdlets. However the pipleline execution
                    # is terminated when ever 'CTRL + C' is entered by user to terminate the cmdlet execution.
                    # The finally block is executed whenever pipleline is terminated.
                    # $isArchiveFileProcessingComplete variable is used to track if 'CTRL + C' is entered by the
                    # user.
                    $isArchiveFileProcessingComplete = $false

                    $numberOfItemsArchived = CompressArchiveHelper $sourcePath $DestinationPath $CompressionLevel $Update

                    $isArchiveFileProcessingComplete = $true
                } finally {
                    # The $isArchiveFileProcessingComplete would be set to $false if user has typed 'CTRL + C' to
                    # terminate the cmdlet execution or if an unhandled exception is thrown.
                    # $numberOfItemsArchived contains the count of number of files or directories add to the archive file.
                    # If the newly created archive file is empty then we delete it as its not usable.
                    if (($isArchiveFileProcessingComplete -eq $false) -or
                        ($numberOfItemsArchived -eq 0)) {
                        $DeleteArchiveFileMessage = ($LocalizedData.DeleteArchiveFile -f $DestinationPath)
                        Write-Verbose $DeleteArchiveFileMessage

                        # delete the partial archive file created.
                        if (Test-Path $DestinationPath) {
                            Remove-Item -LiteralPath $DestinationPath -Force -Recurse -ErrorAction SilentlyContinue
                        }
                    }
                }
            }
        }
    }
}
tools\dbatools\optional\Expand-Archive.ps1
if ($PSVersionTable.PSVersion.Major -lt 5) {


    <#
Copied from the Microsoft Module: Microsoft.PowerShell.Archive
Which ships with PowerShell Version 5 but will run under v3.
    #>



    function Expand-Archive {
        <#
            .SYNOPSIS
                Extracts files from a specified archive (zipped) file.

            .DESCRIPTION
                The Expand-Archive cmdlet extracts files from a specified zipped archive file to a specified destination folder. An archive file allows multiple files to be packaged, and optionally compressed, into a single zipped file for easier distribution and storage.

            .PARAMETER Path
                Specifies the path to the archive file.

            .PARAMETER LiteralPath
                Specifies the path to an archive file. Unlike the Path parameter, the value of LiteralPath is used exactly as it is typed. Wildcard characters are not supported. If the path includes escape characters, enclose each escape character in single quotation marks, to instruct Windows PowerShell not to interpret any characters as escape sequences.

            .PARAMETER DestinationPath
                Specifies the path to the folder in which you want the command to save extracted files. Enter the path to a folder, but do not specify a file name or file name extension. This parameter is required.

            .PARAMETER Force
                Forces the command to run without asking for user confirmation.

            .PARAMETER Confirm
                Prompts you for confirmation before running the cmdlet.

            .PARAMETER WhatIf
                Shows what would happen if the cmdlet runs. The cmdlet is not run.

            .EXAMPLE
                Example 1: Extract the contents of an archive

                PS C:\>Expand-Archive -LiteralPath C:\Archives\Draft.Zip -DestinationPath C:\Reference

                This command extracts the contents of an existing archive file, Draft.zip, into the folder specified by the DestinationPath parameter, C:\Reference.

            .EXAMPLE
                Example 2: Extract the contents of an archive in the current folder

                PS C:\>Expand-Archive -Path Draft.Zip -DestinationPath C:\Reference

                This command extracts the contents of an existing archive file in the current folder, Draft.zip, into the folder specified by the DestinationPath parameter, C:\Reference.
        #>
        [CmdletBinding(
            DefaultParameterSetName = "Path",
            SupportsShouldProcess,
            HelpUri = "http://go.microsoft.com/fwlink/?LinkID=393253")]
        param
        (
            [parameter (
                Mandatory,
                Position = 0,
                ParameterSetName = "Path",
                ValueFromPipeline,
                ValueFromPipelineByPropertyName = $true)]
            [ValidateNotNullOrEmpty()]
            [string]
            $Path,

            [parameter (
                Mandatory,
                ParameterSetName = "LiteralPath",
                ValueFromPipelineByPropertyName = $true)]
            [ValidateNotNullOrEmpty()]
            [Alias("PSPath")]
            [string]
            $LiteralPath,

            [parameter (
                Position = 1,
                ValueFromPipeline = $false,
                ValueFromPipelineByPropertyName = $false)]
            [ValidateNotNullOrEmpty()]
            [string]
            $DestinationPath,

            [parameter (
                ValueFromPipeline = $false,
                ValueFromPipelineByPropertyName = $false)]
            [switch]
            $Force
        )

        BEGIN {
            Add-Type -AssemblyName System.IO.Compression -ErrorAction Ignore
            Add-Type -AssemblyName System.IO.Compression.FileSystem -ErrorAction Ignore

            $zipFileExtension = ".zip"

            $LocalizedData = ConvertFrom-StringData @'
    PathNotFoundError=The path '{0}' either does not exist or is not a valid file system path.
    ExpandArchiveInValidDestinationPath=The path '{0}' is not a valid file system directory path.
    InvalidZipFileExtensionError={0} is not a supported archive file format. {1} is the only supported archive file format.
    ArchiveFileIsReadOnly=The attributes of the archive file {0} is set to 'ReadOnly' hence it cannot be updated. If you intend to update the existing archive file, remove the 'ReadOnly' attribute on the archive file else use -Force parameter to override and create a new archive file.
    ZipFileExistError=The archive file {0} already exists. Use the -Update parameter to update the existing archive file or use the -Force parameter to overwrite the existing archive file.
    DuplicatePathFoundError=The input to {0} parameter contains a duplicate path '{1}'. Provide a unique set of paths as input to {2} parameter.
    ArchiveFileIsEmpty=The archive file {0} is empty.
    CompressProgressBarText=The archive file '{0}' creation is in progress...
    ExpandProgressBarText=The archive file '{0}' expansion is in progress...
    AppendArchiveFileExtensionMessage=The archive file path '{0}' supplied to the DestinationPath patameter does not include .zip extension. Hence .zip is appended to the supplied DestinationPath path and the archive file would be created at '{1}'.
    AddItemtoArchiveFile=Adding '{0}'.
    CreateFileAtExpandedPath=Created '{0}'.
    InvalidArchiveFilePathError=The archive file path '{0}' specified as input to the {1} parameter is resolving to multiple file system paths. Provide a unique path to the {2} parameter where the archive file has to be created.
    InvalidExpandedDirPathError=The directory path '{0}' specified as input to the DestinationPath parameter is resolving to multiple file system paths. Provide a unique path to the Destination parameter where the archive file contents have to be expanded.
    FileExistsError=Failed to create file '{0}' while expanding the archive file '{1}' contents as the file '{2}' already exists. Use the -Force parameter if you want to overwrite the existing directory '{3}' contents when expanding the archive file.
    DeleteArchiveFile=The partially created archive file '{0}' is deleted as it is not usable.
    InvalidDestinationPath=The destination path '{0}' does not contain a valid archive file name.
    PreparingToCompressVerboseMessage=Preparing to compress...
    PreparingToExpandVerboseMessage=Preparing to expand...
'@

            #region Utility Functions
            function GetResolvedPathHelper {
                param
                (
                    [string[]]
                    $path,

                    [boolean]
                    $isLiteralPath,

                    [System.Management.Automation.PSCmdlet]
                    $callerPSCmdlet
                )

                $resolvedPaths = @()

                # null and empty check are are already done on Path parameter at the cmdlet layer.
                foreach ($currentPath in $path) {
                    try {
                        if ($isLiteralPath) {
                            $currentResolvedPaths = Resolve-Path -LiteralPath $currentPath -ErrorAction Stop
                        } else {
                            $currentResolvedPaths = Resolve-Path -Path $currentPath -ErrorAction Stop
                        }
                    } catch {
                        $errorMessage = ($LocalizedData.PathNotFoundError -f $currentPath)
                        $exception = New-Object System.InvalidOperationException $errorMessage, $_.Exception
                        $errorRecord = CreateErrorRecordHelper "ArchiveCmdletPathNotFound" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $currentPath
                        $callerPSCmdlet.ThrowTerminatingError($errorRecord)
                    }

                    foreach ($currentResolvedPath in $currentResolvedPaths) {
                        $resolvedPaths += $currentResolvedPath.ProviderPath
                    }
                }

                $resolvedPaths
            }

            function Add-CompressionAssemblies {

                if ($PSEdition -eq "Desktop") {
                    Add-Type -AssemblyName System.IO.Compression
                    Add-Type -AssemblyName System.IO.Compression.FileSystem
                }
            }

            function IsValidFileSystemPath {
                param
                (
                    [string[]]
                    $path
                )

                $result = $true;

                # null and empty check are are already done on Path parameter at the cmdlet layer.
                foreach ($currentPath in $path) {
                    if (!([System.IO.File]::Exists($currentPath) -or [System.IO.Directory]::Exists($currentPath))) {
                        $errorMessage = ($LocalizedData.PathNotFoundError -f $currentPath)
                        ThrowTerminatingErrorHelper "PathNotFound" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $currentPath
                    }
                }

                return $result;
            }


            function ValidateDuplicateFileSystemPath {
                param
                (
                    [string]
                    $inputParameter,

                    [string[]]
                    $path
                )

                $uniqueInputPaths = @()

                # null and empty check are are already done on Path parameter at the cmdlet layer.
                foreach ($currentPath in $path) {
                    $currentInputPath = $currentPath.ToUpper()
                    if ($uniqueInputPaths.Contains($currentInputPath)) {
                        $errorMessage = ($LocalizedData.DuplicatePathFoundError -f $inputParameter, $currentPath, $inputParameter)
                        ThrowTerminatingErrorHelper "DuplicatePathFound" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $currentPath
                    } else {
                        $uniqueInputPaths += $currentInputPath
                    }
                }
            }

            function CompressionLevelMapper {
                param
                (
                    [string]
                    $compressionLevel
                )

                $compressionLevelFormat = [System.IO.Compression.CompressionLevel]::Optimal

                # CompressionLevel format is already validated at the cmdlet layer.
                switch ($compressionLevel.ToString()) {
                    "Fastest" {
                        $compressionLevelFormat = [System.IO.Compression.CompressionLevel]::Fastest
                    }
                    "NoCompression" {
                        $compressionLevelFormat = [System.IO.Compression.CompressionLevel]::NoCompression
                    }
                }

                return $compressionLevelFormat
            }

            function CompressArchiveHelper {
                param
                (
                    [string[]]
                    $sourcePath,

                    [string]
                    $destinationPath,

                    [string]
                    $compressionLevel,

                    [bool]
                    $isUpdateMode
                )

                $numberOfItemsArchived = 0
                $sourceFilePaths = @()
                $sourceDirPaths = @()

                foreach ($currentPath in $sourcePath) {
                    $result = Test-Path -LiteralPath $currentPath -PathType Leaf
                    if ($result -eq $true) {
                        $sourceFilePaths += $currentPath
                    } else {
                        $sourceDirPaths += $currentPath
                    }
                }

                # The Soure Path contains one or more directory (this directory can have files under it) and no files to be compressed.
                if ($sourceFilePaths.Count -eq 0 -and $sourceDirPaths.Count -gt 0) {
                    $currentSegmentWeight = 100 / [double]$sourceDirPaths.Count
                    $previousSegmentWeight = 0
                    foreach ($currentSourceDirPath in $sourceDirPaths) {
                        $count = CompressSingleDirHelper $currentSourceDirPath $destinationPath $compressionLevel $true $isUpdateMode $previousSegmentWeight $currentSegmentWeight
                        $numberOfItemsArchived += $count
                        $previousSegmentWeight += $currentSegmentWeight
                    }
                }

                # The Soure Path contains only files to be compressed.
                elseIf ($sourceFilePaths.Count -gt 0 -and $sourceDirPaths.Count -eq 0) {
                    # $previousSegmentWeight is equal to 0 as there are no prior segments.
                    # $currentSegmentWeight is set to 100 as all files have equal weightage.
                    $previousSegmentWeight = 0
                    $currentSegmentWeight = 100

                    $numberOfItemsArchived = CompressFilesHelper $sourceFilePaths $destinationPath $compressionLevel $isUpdateMode $previousSegmentWeight $currentSegmentWeight
                }
                # The Soure Path contains one or more files and one or more directories (this directory can have files under it) to be compressed.
                elseif ($sourceFilePaths.Count -gt 0 -and $sourceDirPaths.Count -gt 0) {
                    # each directory is considered as an individual segments & all the individual files are clubed in to a separate sgemnet.
                    $currentSegmentWeight = 100 / [double]($sourceDirPaths.Count + 1)
                    $previousSegmentWeight = 0

                    foreach ($currentSourceDirPath in $sourceDirPaths) {
                        $count = CompressSingleDirHelper $currentSourceDirPath $destinationPath $compressionLevel $true $isUpdateMode $previousSegmentWeight $currentSegmentWeight
                        $numberOfItemsArchived += $count
                        $previousSegmentWeight += $currentSegmentWeight
                    }

                    $count = CompressFilesHelper $sourceFilePaths $destinationPath $compressionLevel $isUpdateMode $previousSegmentWeight $currentSegmentWeight
                    $numberOfItemsArchived += $count
                }

                return $numberOfItemsArchived
            }

            function CompressFilesHelper {
                param
                (
                    [string[]]
                    $sourceFilePaths,

                    [string]
                    $destinationPath,

                    [string]
                    $compressionLevel,

                    [bool]
                    $isUpdateMode,

                    [double]
                    $previousSegmentWeight,

                    [double]
                    $currentSegmentWeight
                )

                $numberOfItemsArchived = ZipArchiveHelper $sourceFilePaths $destinationPath $compressionLevel $isUpdateMode $null $previousSegmentWeight $currentSegmentWeight

                return $numberOfItemsArchived
            }

            function CompressSingleDirHelper {
                param
                (
                    [string]
                    $sourceDirPath,

                    [string]
                    $destinationPath,

                    [string]
                    $compressionLevel,

                    [bool]
                    $useParentDirAsRoot,

                    [bool]
                    $isUpdateMode,

                    [double]
                    $previousSegmentWeight,

                    [double]
                    $currentSegmentWeight
                )

                [System.Collections.Generic.List[System.String]]$subDirFiles = @()

                if ($useParentDirAsRoot) {
                    $sourceDirInfo = New-Object -TypeName System.IO.DirectoryInfo -ArgumentList $sourceDirPath
                    $sourceDirFullName = $sourceDirInfo.Parent.FullName

                    # If the directory is present at the drive level the DirectoryInfo.Parent include '\' example: C:\
                    # On the other hand if the directory exists at a deper level then DirectoryInfo.Parent
                    # has just the path (without an ending '\'). example C:\source
                    if ($sourceDirFullName.Length -eq 3) {
                        $modifiedSourceDirFullName = $sourceDirFullName
                    } else {
                        $modifiedSourceDirFullName = $sourceDirFullName + "\"
                    }
                } else {
                    $sourceDirFullName = $sourceDirPath
                    $modifiedSourceDirFullName = $sourceDirFullName + "\"
                }

                $dirContents = Get-ChildItem -LiteralPath $sourceDirPath -Recurse
                foreach ($currentContent in $dirContents) {
                    $isContainer = $currentContent -is [System.IO.DirectoryInfo]
                    if (!$isContainer) {
                        $subDirFiles.Add($currentContent.FullName)
                    } else {
                        # The currentContent points to a directory.
                        # We need to check if the directory is an empty directory, if so such a
                        # directory has to be explictly added to the archive file.
                        # if there are no files in the directory the GetFiles() API returns an empty array.
                        $files = $currentContent.GetFiles()
                        if ($files.Count -eq 0) {
                            $subDirFiles.Add($currentContent.FullName + "\")
                        }
                    }
                }

                $numberOfItemsArchived = ZipArchiveHelper $subDirFiles.ToArray() $destinationPath $compressionLevel $isUpdateMode $modifiedSourceDirFullName $previousSegmentWeight $currentSegmentWeight

                return $numberOfItemsArchived
            }

            function ZipArchiveHelper {
                param
                (
                    [System.Collections.Generic.List[System.String]]
                    $sourcePaths,

                    [string]
                    $destinationPath,

                    [string]
                    $compressionLevel,

                    [bool]
                    $isUpdateMode,

                    [string]
                    $modifiedSourceDirFullName,

                    [double]
                    $previousSegmentWeight,

                    [double]
                    $currentSegmentWeight
                )

                $numberOfItemsArchived = 0
                $fileMode = [System.IO.FileMode]::Create
                $result = Test-Path -LiteralPath $DestinationPath -PathType Leaf
                if ($result -eq $true) {
                    $fileMode = [System.IO.FileMode]::Open
                }

                Add-CompressionAssemblies

                try {
                    # At this point we are sure that the archive file has write access.
                    $archiveFileStreamArgs = @($destinationPath, $fileMode)
                    $archiveFileStream = New-Object -TypeName System.IO.FileStream -ArgumentList $archiveFileStreamArgs

                    $zipArchiveArgs = @($archiveFileStream, [System.IO.Compression.ZipArchiveMode]::Update, $false)
                    $zipArchive = New-Object -TypeName System.IO.Compression.ZipArchive -ArgumentList $zipArchiveArgs

                    $currentEntryCount = 0
                    $progressBarStatus = ($LocalizedData.CompressProgressBarText -f $destinationPath)
                    $bufferSize = 4kb
                    $buffer = New-Object Byte[] $bufferSize

                    foreach ($currentFilePath in $sourcePaths) {
                        if ($modifiedSourceDirFullName -ne $null -and $modifiedSourceDirFullName.Length -gt 0) {
                            $index = $currentFilePath.IndexOf($modifiedSourceDirFullName, [System.StringComparison]::OrdinalIgnoreCase)
                            $currentFilePathSubString = $currentFilePath.Substring($index, $modifiedSourceDirFullName.Length)
                            $relativeFilePath = $currentFilePath.Replace($currentFilePathSubString, "").Trim()
                        } else {
                            $relativeFilePath = [System.IO.Path]::GetFileName($currentFilePath)
                        }

                        # Update mode is selected.
                        # Check to see if archive file already contains one or more zip files in it.
                        if ($isUpdateMode -eq $true -and $zipArchive.Entries.Count -gt 0) {
                            $entryToBeUpdated = $null

                            # Check if the file already exists in the archive file.
                            # If so replace it with new file from the input source.
                            # If the file does not exist in the archive file then default to
                            # create mode and create the entry in the archive file.

                            foreach ($currentArchiveEntry in $zipArchive.Entries) {
                                if ($currentArchiveEntry.FullName -eq $relativeFilePath) {
                                    $entryToBeUpdated = $currentArchiveEntry
                                    break
                                }
                            }

                            if ($entryToBeUpdated -ne $null) {
                                $addItemtoArchiveFileMessage = ($LocalizedData.AddItemtoArchiveFile -f $currentFilePath)
                                $entryToBeUpdated.Delete()
                            }
                        }

                        $compression = CompressionLevelMapper $compressionLevel

                        # If a directory needs to be added to an archive file,
                        # by convention the .Net API's expect the path of the diretcory
                        # to end with '\' to detect the path as an directory.
                        if (!$relativeFilePath.EndsWith("\", [StringComparison]::OrdinalIgnoreCase)) {
                            try {
                                try {
                                    $currentFileStream = [System.IO.File]::Open($currentFilePath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read)
                                } catch {
                                    # Failed to access the file. Write a non terminating error to the pipeline
                                    # and move on with the remaining files.
                                    $exception = $_.Exception
                                    if ($null -ne $_.Exception -and
                                        $null -ne $_.Exception.InnerException) {
                                        $exception = $_.Exception.InnerException
                                    }
                                    $errorRecord = CreateErrorRecordHelper "CompressArchiveUnauthorizedAccessError" $null ([System.Management.Automation.ErrorCategory]::PermissionDenied) $exception $currentFilePath
                                    Write-Error -ErrorRecord $errorRecord
                                }

                                if ($null -ne $currentFileStream) {
                                    $srcStream = New-Object System.IO.BinaryReader $currentFileStream

                                    $currentArchiveEntry = $zipArchive.CreateEntry($relativeFilePath, $compression)

                                    # Updating  the File Creation time so that the same timestamp would be retained after expanding the compressed file.
                                    # At this point we are sure that Get-ChildItem would succeed.
                                    $currentArchiveEntry.LastWriteTime = (Get-Item -LiteralPath $currentFilePath).LastWriteTime

                                    $destStream = New-Object System.IO.BinaryWriter $currentArchiveEntry.Open()

                                    while ($numberOfBytesRead = $srcStream.Read($buffer, 0, $bufferSize)) {
                                        $destStream.Write($buffer, 0, $numberOfBytesRead)
                                        $destStream.Flush()
                                    }

                                    $numberOfItemsArchived += 1
                                    $addItemtoArchiveFileMessage = ($LocalizedData.AddItemtoArchiveFile -f $currentFilePath)
                                }
                            } finally {
                                If ($null -ne $currentFileStream) {
                                    $currentFileStream.Dispose()
                                }
                                If ($null -ne $srcStream) {
                                    $srcStream.Dispose()
                                }
                                If ($null -ne $destStream) {
                                    $destStream.Dispose()
                                }
                            }
                        } else {
                            $currentArchiveEntry = $zipArchive.CreateEntry("$relativeFilePath", $compression)
                            $numberOfItemsArchived += 1
                            $addItemtoArchiveFileMessage = ($LocalizedData.AddItemtoArchiveFile -f $currentFilePath)
                        }

                        if ($null -ne $addItemtoArchiveFileMessage) {
                            Write-Verbose $addItemtoArchiveFileMessage
                        }

                        $currentEntryCount += 1
                        ProgressBarHelper "Compress-Archive" $progressBarStatus $previousSegmentWeight $currentSegmentWeight $sourcePaths.Count  $currentEntryCount
                    }
                } finally {
                    If ($null -ne $zipArchive) {
                        $zipArchive.Dispose()
                    }

                    If ($null -ne $archiveFileStream) {
                        $archiveFileStream.Dispose()
                    }

                    # Complete writing progress.
                    Write-Progress -Activity "Compress-Archive" -Completed
                }

                return $numberOfItemsArchived
            }

            <############################################################################################
# ValidateArchivePathHelper: This is a helper function used to validate the archive file
# path & its file format. The only supported archive file format is .zip
############################################################################################>
            function ValidateArchivePathHelper {
                param
                (
                    [string]
                    $archiveFile
                )

                if ([System.IO.File]::Exists($archiveFile)) {
                    $extension = [system.IO.Path]::GetExtension($archiveFile)

                    # Invalid file extension is specifed for the zip file.
                    if ($extension -ne $zipFileExtension) {
                        $errorMessage = ($LocalizedData.InvalidZipFileExtensionError -f $extension, $zipFileExtension)
                        ThrowTerminatingErrorHelper "NotSupportedArchiveFileExtension" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $extension
                    }
                } else {
                    $errorMessage = ($LocalizedData.PathNotFoundError -f $archiveFile)
                    ThrowTerminatingErrorHelper "PathNotFound" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $archiveFile
                }
            }

            <############################################################################################
# ExpandArchiveHelper: This is a helper function used to expand the archive file contents
# to the specified directory.
############################################################################################>
            function ExpandArchiveHelper {
                param
                (
                    [string]
                    $archiveFile,

                    [string]
                    $expandedDir,

                    [ref]
                    $expandedItems,

                    [boolean]
                    $force,

                    [boolean]
                    $isVerbose,

                    [boolean]
                    $isConfirm
                )

                Add-CompressionAssemblies

                try {
                    # The existance of archive file has already been validated by ValidateArchivePathHelper
                    # before calling this helper function.
                    $archiveFileStreamArgs = @($archiveFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read)
                    $archiveFileStream = New-Object -TypeName System.IO.FileStream -ArgumentList $archiveFileStreamArgs

                    $zipArchiveArgs = @($archiveFileStream, [System.IO.Compression.ZipArchiveMode]::Read, $false)
                    $zipArchive = New-Object -TypeName System.IO.Compression.ZipArchive -ArgumentList $zipArchiveArgs

                    if ($zipArchive.Entries.Count -eq 0) {
                        $archiveFileIsEmpty = ($LocalizedData.ArchiveFileIsEmpty -f $archiveFile)
                        Write-Verbose $archiveFileIsEmpty
                        return
                    }

                    $currentEntryCount = 0
                    $progressBarStatus = ($LocalizedData.ExpandProgressBarText -f $archiveFile)

                    # The archive entries can either be empty directories or files.
                    foreach ($currentArchiveEntry in $zipArchive.Entries) {
                        $currentArchiveEntryPath = Join-Path -Path $expandedDir -ChildPath $currentArchiveEntry.FullName
                        $extension = [system.IO.Path]::GetExtension($currentArchiveEntryPath)

                        # The current archive entry is an empty directory
                        # The FullName of the Archive Entry representing a directory would end with a trailing '\'.
                        if ($extension -eq [string]::Empty -and
                            $currentArchiveEntryPath.EndsWith("\", [StringComparison]::OrdinalIgnoreCase)) {
                            $pathExists = Test-Path -LiteralPath $currentArchiveEntryPath

                            # The current archive entry expects an empty directory.
                            # Check if the existing directory is empty. If its not empty
                            # then it means that user has added this directory by other means.
                            if ($pathExists -eq $false) {
                                New-Item $currentArchiveEntryPath -ItemType Directory -Confirm:$isConfirm | Out-Null

                                if (Test-Path -LiteralPath $currentArchiveEntryPath -PathType Container) {
                                    $addEmptyDirectorytoExpandedPathMessage = ($LocalizedData.AddItemtoArchiveFile -f $currentArchiveEntryPath)
                                    Write-Verbose $addEmptyDirectorytoExpandedPathMessage

                                    $expandedItems.Value += $currentArchiveEntryPath
                                }
                            }
                        } else {
                            try {
                                $currentArchiveEntryFileInfo = New-Object -TypeName System.IO.FileInfo -ArgumentList $currentArchiveEntryPath
                                $parentDirExists = Test-Path -LiteralPath $currentArchiveEntryFileInfo.DirectoryName -PathType Container

                                # If the Parent directory of the current entry in the archive file does not exist, then create it.
                                if ($parentDirExists -eq $false) {
                                    New-Item $currentArchiveEntryFileInfo.DirectoryName -ItemType Directory -Confirm:$isConfirm | Out-Null

                                    if (!(Test-Path -LiteralPath $currentArchiveEntryFileInfo.DirectoryName -PathType Container)) {
                                        # The directory referred by $currentArchiveEntryFileInfo.DirectoryName was not successfully created.
                                        # This could be because the user has specified -Confirm paramter when Expand-Archive was invoked
                                        # and authorization was not provided when confirmation was prompted. In such a scenario,
                                        # we skip the current file in the archive and continue with the remaining archive file contents.
                                        Continue
                                    }

                                    $expandedItems.Value += $currentArchiveEntryFileInfo.DirectoryName
                                }

                                $hasNonTerminatingError = $false

                                # Check if the file in to which the current archive entry contents
                                # would be expanded already exists.
                                if ($currentArchiveEntryFileInfo.Exists) {
                                    if ($force) {
                                        Remove-Item -LiteralPath $currentArchiveEntryFileInfo.FullName -Force -ErrorVariable ev -Verbose:$isVerbose -Confirm:$isConfirm
                                        if ($ev -ne $null) {
                                            $hasNonTerminatingError = $true
                                        }

                                        if (Test-Path -LiteralPath $currentArchiveEntryFileInfo.FullName -PathType Leaf) {
                                            # The file referred by $currentArchiveEntryFileInfo.FullName was not successfully removed.
                                            # This could be because the user has specified -Confirm paramter when Expand-Archive was invoked
                                            # and authorization was not provided when confirmation was prompted. In such a scenario,
                                            # we skip the current file in the archive and continue with the remaining archive file contents.
                                            Continue
                                        }
                                    } else {
                                        # Write non-terminating error to the pipeline.
                                        $errorMessage = ($LocalizedData.FileExistsError -f $currentArchiveEntryFileInfo.FullName, $archiveFile, $currentArchiveEntryFileInfo.FullName, $currentArchiveEntryFileInfo.FullName)
                                        $errorRecord = CreateErrorRecordHelper "ExpandArchiveFileExists" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidOperation) $null $currentArchiveEntryFileInfo.FullName
                                        Write-Error -ErrorRecord $errorRecord
                                        $hasNonTerminatingError = $true
                                    }
                                }

                                if (!$hasNonTerminatingError) {
                                    [System.IO.Compression.ZipFileExtensions]::ExtractToFile($currentArchiveEntry, $currentArchiveEntryPath, $false)

                                    # Add the expanded file path to the $expandedItems array,
                                    # to keep track of all the expanded files created while expanding the archive file.
                                    # If user enters CTRL + C then at that point of time, all these expanded files
                                    # would be deleted as part of the clean up process.
                                    $expandedItems.Value += $currentArchiveEntryPath

                                    $addFiletoExpandedPathMessage = ($LocalizedData.CreateFileAtExpandedPath -f $currentArchiveEntryPath)
                                    Write-Verbose $addFiletoExpandedPathMessage
                                }
                            } finally {
                                If ($null -ne $destStream) {
                                    $destStream.Dispose()
                                }

                                If ($null -ne $srcStream) {
                                    $srcStream.Dispose()
                                }
                            }
                        }

                        $currentEntryCount += 1
                        # $currentSegmentWeight is Set to 100 giving equal weightage to each file that is getting expanded.
                        # $previousSegmentWeight is set to 0 as there are no prior segments.
                        $previousSegmentWeight = 0
                        $currentSegmentWeight = 100
                        ProgressBarHelper "Expand-Archive" $progressBarStatus $previousSegmentWeight $currentSegmentWeight $zipArchive.Entries.Count  $currentEntryCount
                    }
                } finally {
                    If ($null -ne $zipArchive) {
                        $zipArchive.Dispose()
                    }

                    If ($null -ne $archiveFileStream) {
                        $archiveFileStream.Dispose()
                    }

                    # Complete writing progress.
                    Write-Progress -Activity "Expand-Archive" -Completed
                }
            }

            <############################################################################################
# ProgressBarHelper: This is a helper function used to display progress message.
# This function is used by both Compress-Archive & Expand-Archive to display archive file
# creation/expansion progress.
############################################################################################>
            function ProgressBarHelper {
                param
                (
                    [string]
                    $cmdletName,

                    [string]
                    $status,

                    [double]
                    $previousSegmentWeight,

                    [double]
                    $currentSegmentWeight,

                    [int]
                    $totalNumberofEntries,

                    [int]
                    $currentEntryCount
                )

                if ($currentEntryCount -gt 0 -and
                    $totalNumberofEntries -gt 0 -and
                    $previousSegmentWeight -ge 0 -and
                    $currentSegmentWeight -gt 0) {
                    $entryDefaultWeight = $currentSegmentWeight / [double]$totalNumberofEntries

                    $percentComplete = $previousSegmentWeight + ($entryDefaultWeight * $currentEntryCount)
                    Write-Progress -Activity $cmdletName -Status $status -PercentComplete $percentComplete
                }
            }

            <############################################################################################
# CSVHelper: This is a helper function used to append comma after each path specifid by
# the SourcePath array. This helper function is used to display all the user supplied paths
# in the WhatIf message.
############################################################################################>
            function CSVHelper {
                param
                (
                    [string[]]
                    $sourcePath
                )

                # SourcePath has already been validated by the calling funcation.
                if ($sourcePath.Count -gt 1) {
                    $sourcePathInCsvFormat = "`n"
                    for ($currentIndex = 0; $currentIndex -lt $sourcePath.Count; $currentIndex++) {
                        if ($currentIndex -eq $sourcePath.Count - 1) {
                            $sourcePathInCsvFormat += $sourcePath[$currentIndex]
                        } else {
                            $sourcePathInCsvFormat += $sourcePath[$currentIndex] + "`n"
                        }
                    }
                } else {
                    $sourcePathInCsvFormat = $sourcePath
                }

                return $sourcePathInCsvFormat
            }

            <############################################################################################
# ThrowTerminatingErrorHelper: This is a helper function used to throw terminating error.
############################################################################################>
            function ThrowTerminatingErrorHelper {
                param
                (
                    [string]
                    $errorId,

                    [string]
                    $errorMessage,

                    [System.Management.Automation.ErrorCategory]
                    $errorCategory,

                    [object]
                    $targetObject,

                    [Exception]
                    $innerException
                )

                if ($innerException -eq $null) {
                    $exception = New-object System.IO.IOException $errorMessage
                } else {
                    $exception = New-Object System.IO.IOException $errorMessage, $innerException
                }

                $exception = New-Object System.IO.IOException $errorMessage
                $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, $errorId, $errorCategory, $targetObject
                $PSCmdlet.ThrowTerminatingError($errorRecord)
            }

            <############################################################################################
# CreateErrorRecordHelper: This is a helper function used to create an ErrorRecord
############################################################################################>
            function CreateErrorRecordHelper {
                param
                (
                    [string]
                    $errorId,

                    [string]
                    $errorMessage,

                    [System.Management.Automation.ErrorCategory]
                    $errorCategory,

                    [Exception]
                    $exception,

                    [object]
                    $targetObject
                )

                if ($null -eq $exception) {
                    $exception = New-Object System.IO.IOException $errorMessage
                }

                $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, $errorId, $errorCategory, $targetObject
                return $errorRecord
            }
            #endregion Utility Functions

            $isVerbose = $psboundparameters.ContainsKey("Verbose")
            $isConfirm = $psboundparameters.ContainsKey("Confirm")

            $isDestinationPathProvided = $true
            if ($DestinationPath -eq [string]::Empty) {
                $resolvedDestinationPath = $pwd
                $isDestinationPathProvided = $false
            } else {
                $destinationPathExists = Test-Path -Path $DestinationPath -PathType Container
                if ($destinationPathExists) {
                    $resolvedDestinationPath = GetResolvedPathHelper $DestinationPath $false $PSCmdlet
                    if ($resolvedDestinationPath.Count -gt 1) {
                        $errorMessage = ($LocalizedData.InvalidExpandedDirPathError -f $DestinationPath)
                        ThrowTerminatingErrorHelper "InvalidDestinationPath" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $DestinationPath
                    }

                    # At this point we are sure that the provided path resolves to a valid single path.
                    # Calling Resolve-Path again to get the underlying provider name.
                    $suppliedDestinationPath = Resolve-Path -Path $DestinationPath
                    if ($suppliedDestinationPath.Provider.Name -ne "FileSystem") {
                        $errorMessage = ($LocalizedData.ExpandArchiveInValidDestinationPath -f $DestinationPath)
                        ThrowTerminatingErrorHelper "InvalidDirectoryPath" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $DestinationPath
                    }
                } else {
                    $createdItem = New-Item -Path $DestinationPath -ItemType Directory -Confirm:$isConfirm -Verbose:$isVerbose -ErrorAction Stop
                    if ($createdItem -ne $null -and $createdItem.PSProvider.Name -ne "FileSystem") {
                        Remove-Item "$DestinationPath" -Force -Recurse -ErrorAction SilentlyContinue
                        $errorMessage = ($LocalizedData.ExpandArchiveInValidDestinationPath -f $DestinationPath)
                        ThrowTerminatingErrorHelper "InvalidDirectoryPath" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $DestinationPath
                    }

                    $resolvedDestinationPath = GetResolvedPathHelper $DestinationPath $true $PSCmdlet
                }
            }

            $isWhatIf = $psboundparameters.ContainsKey("WhatIf")
            if (!$isWhatIf) {
                $preparingToExpandVerboseMessage = ($LocalizedData.PreparingToExpandVerboseMessage)
                Write-Verbose $preparingToExpandVerboseMessage

                $progressBarStatus = ($LocalizedData.ExpandProgressBarText -f $DestinationPath)
                ProgressBarHelper "Expand-Archive" $progressBarStatus 0 100 100 1
            }
        }
        PROCESS {
            switch ($PsCmdlet.ParameterSetName) {
                "Path" {
                    $resolvedSourcePaths = GetResolvedPathHelper $Path $false $PSCmdlet

                    if ($resolvedSourcePaths.Count -gt 1) {
                        $errorMessage = ($LocalizedData.InvalidArchiveFilePathError -f $Path, $PsCmdlet.ParameterSetName, $PsCmdlet.ParameterSetName)
                        ThrowTerminatingErrorHelper "InvalidArchiveFilePath" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $Path
                    }
                }
                "LiteralPath" {
                    $resolvedSourcePaths = GetResolvedPathHelper $LiteralPath $true $PSCmdlet

                    if ($resolvedSourcePaths.Count -gt 1) {
                        $errorMessage = ($LocalizedData.InvalidArchiveFilePathError -f $LiteralPath, $PsCmdlet.ParameterSetName, $PsCmdlet.ParameterSetName)
                        ThrowTerminatingErrorHelper "InvalidArchiveFilePath" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $LiteralPath
                    }
                }
            }

            ValidateArchivePathHelper $resolvedSourcePaths

            if ($pscmdlet.ShouldProcess($resolvedSourcePaths)) {
                $expandedItems = @()

                try {
                    # StopProcessing is not avaliable in Script cmdlets. However the pipleline execution
                    # is terminated when ever 'CTRL + C' is entered by user to terminate the cmdlet execution.
                    # The finally block is executed whenever pipleline is terminated.
                    # $isArchiveFileProcessingComplete variable is used to track if 'CTRL + C' is entered by the
                    # user.
                    $isArchiveFileProcessingComplete = $false

                    # The User has not provided a destination path, hence we use '$pwd\ArchiveFileName' as the directory where the
                    # archive file contents would be expanded. If the path '$pwd\ArchiveFileName' already exists then we use the
                    # Windows default mechanism of appending a counter value at the end of the directory name where the contents
                    # would be expanded.
                    if (!$isDestinationPathProvided) {
                        $archiveFile = New-Object System.IO.FileInfo $resolvedSourcePaths
                        $resolvedDestinationPath = Join-Path -Path $resolvedDestinationPath -ChildPath $archiveFile.BaseName
                        $destinationPathExists = Test-Path -LiteralPath $resolvedDestinationPath -PathType Container

                        if (!$destinationPathExists) {
                            New-Item -Path $resolvedDestinationPath -ItemType Directory -Confirm:$isConfirm -Verbose:$isVerbose -ErrorAction Stop | Out-Null
                        }
                    }

                    ExpandArchiveHelper $resolvedSourcePaths $resolvedDestinationPath ([ref]$expandedItems) $Force $isVerbose $isConfirm

                    $isArchiveFileProcessingComplete = $true
                } finally {
                    # The $isArchiveFileProcessingComplete would be set to $false if user has typed 'CTRL + C' to
                    # terminate the cmdlet execution or if an unhandled exception is thrown.
                    if ($isArchiveFileProcessingComplete -eq $false) {
                        if ($expandedItems.Count -gt 0) {
                            # delete the expanded file/directory as the archive
                            # file was not completly expanded.
                            $expandedItems | ForEach-Object { Remove-Item $_ -Force -Recurse }
                        }
                    }
                }
            }
        }
    }
}
tools\dbatools\optional\Get-GenericArgumentCompleter.ps1
if (-not (Get-Command -Name Register-ArgumentCompleter -ErrorAction Ignore)) {
    Function Get-GenericArgumentCompleter {
        param (
            [string]$name,
            [object]$collection
        )

        Register-ArgumentCompleter -ParameterName $name -ScriptBlock {
            param (
                $commandName,
                $parameterName,
                $wordToComplete,
                $commandAst,
                $fakeBoundParameter
            )

            if ($collection) {
                foreach ($item in $collection) {
                    New-CompletionResult -CompletionText $item -ToolTip $item
                }
            }
        }
    }
}
tools\dbatools\optional\TabExpansionPlusPlus.ps1
if (-not (Get-Command -Name Register-ArgumentCompleter -ErrorAction Ignore)) {

    #############################################################################
    #
    # TabExpansionPlusPlus
    #
    #

    <#
Copyright (c) 2013, Jason Shirk
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

    #>

    # Save off the previous tab completion so it can be restored if this module
    # is removed.
    $oldTabExpansion = $function:TabExpansion
    $oldTabExpansion2 = $function:TabExpansion2

    [bool]$updatedTypeData = $false


    #region Exported utility functions for completers

    #############################################################################
    #
    # Helper function to create a new completion results
    #
    function New-CompletionResult {
        param ([Parameter(Position = 0, ValueFromPipelineByPropertyName, Mandatory, ValueFromPipeline)]
            [ValidateNotNullOrEmpty()]
            [string]
            $CompletionText,

            [Parameter(Position = 1, ValueFromPipelineByPropertyName)]
            [string]
            $ToolTip,

            [Parameter(Position = 2, ValueFromPipelineByPropertyName)]
            [string]
            $ListItemText,

            [System.Management.Automation.CompletionResultType]
            $CompletionResultType = [System.Management.Automation.CompletionResultType]::ParameterValue,

            [switch]
            $NoQuotes = $false
        )

        process {
            $toolTipToUse = if ($ToolTip -eq '') { $CompletionText }
            else { $ToolTip }
            $listItemToUse = if ($ListItemText -eq '') { $CompletionText }
            else { $ListItemText }

            # If the caller explicitly requests that quotes
            # not be included, via the -NoQuotes parameter,
            # then skip adding quotes.

            if ($CompletionResultType -eq [System.Management.Automation.CompletionResultType]::ParameterValue -and -not $NoQuotes) {
                # Add single quotes for the caller in case they are needed.
                # We use the parser to robustly determine how it will treat
                # the argument.  If we end up with too many tokens, or if
                # the parser found something expandable in the results, we
                # know quotes are needed.

                $tokens = $null
                $null = [System.Management.Automation.Language.Parser]::ParseInput("echo $CompletionText", [ref]$tokens, [ref]$null)
                if ($tokens.Length -ne 3 -or
                    ($tokens[1] -is [System.Management.Automation.Language.StringExpandableToken] -and
                        $tokens[1].Kind -eq [System.Management.Automation.Language.TokenKind]::Generic)) {
                    $CompletionText = "'$CompletionText'"
                }
            }
            return New-Object System.Management.Automation.CompletionResult `
            ($CompletionText, $listItemToUse, $CompletionResultType, $toolTipToUse.Trim())
        }

    }

    #############################################################################
    #
    # .SYNOPSIS
    #
    #     This is a simple wrapper of Get-Command gets commands with a given
    #     parameter ignoring commands that use the parameter name as an alias.
    #
    function Get-CommandWithParameter {
        [CmdletBinding(DefaultParameterSetName = 'AllCommandSet')]
        param (
            [Parameter(ParameterSetName = 'AllCommandSet', Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
            [ValidateNotNullOrEmpty()]
            [string[]]
            ${Name},

            [Parameter(ParameterSetName = 'CmdletSet', ValueFromPipelineByPropertyName)]
            [string[]]
            ${Verb},

            [Parameter(ParameterSetName = 'CmdletSet', ValueFromPipelineByPropertyName)]
            [string[]]
            ${Noun},

            [Parameter(ValueFromPipelineByPropertyName)]
            [string[]]
            ${Module},

            [ValidateNotNullOrEmpty()]
            [Parameter(Mandatory)]
            [string]
            ${ParameterName})

        begin {
            $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Get-Command', [System.Management.Automation.CommandTypes]::Cmdlet)
            $scriptCmd = { & $wrappedCmd @PSBoundParameters | Where-Object { $_.Parameters[$ParameterName] -ne $null } }
            $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
            $steppablePipeline.Begin($PSCmdlet)
        }
        process {
            $steppablePipeline.Process($_)
        }
        end {
            $steppablePipeline.End()
        }
    }

    #############################################################################
    #
    function Set-CompletionPrivateData {
        param (
            [ValidateNotNullOrEmpty()]
            [string]
            $Key,

            [object]
            $Value,

            [ValidateNotNullOrEmpty()]
            [int]
            $ExpirationSeconds = 604800
        )

        $Cache = [PSCustomObject]@{
            Value          = $Value
            ExpirationTime = (Get-Date).AddSeconds($ExpirationSeconds)
        }
        $completionPrivateData[$key] = $Cache
    }

    #############################################################################
    #
    function Get-CompletionPrivateData {
        param (
            [ValidateNotNullOrEmpty()]
            [string]
            $Key)

        if (!$Key)
        { return $completionPrivateData }

        $cacheValue = $completionPrivateData[$key]
        if ((Get-Date) -lt $cacheValue.ExpirationTime) {
            return $cacheValue.Value
        }
    }

    #############################################################################
    #
    function Get-CompletionWithExtension {
        param ([string]
            $lastWord,

            [string[]]
            $extensions)

        [System.Management.Automation.CompletionCompleters]::CompleteFilename($lastWord) |
            Where-Object {
            # Use ListItemText because it won't be quoted, CompletionText might be
            [System.IO.Path]::GetExtension($_.ListItemText) -in $extensions
        }
    }

    #############################################################################
    #
    function New-CommandTree {
        [CmdletBinding(DefaultParameterSetName = 'Default')]
        param (
            [Parameter(Position = 0, Mandatory, ParameterSetName = 'Default')]
            [Parameter(Position = 0, Mandatory, ParameterSetName = 'Argument')]
            [ValidateNotNullOrEmpty()]
            [string]
            $Completion,

            [Parameter(Position = 1, Mandatory, ParameterSetName = 'Default')]
            [Parameter(Position = 1, Mandatory, ParameterSetName = 'Argument')]
            [string]
            $Tooltip,

            [Parameter(ParameterSetName = 'Argument')]
            [switch]
            $Argument,

            [Parameter(Position = 2, ParameterSetName = 'Default')]
            [Parameter(Position = 1, ParameterSetName = 'ScriptBlockSet')]
            [scriptblock]
            $SubCommands,

            [Parameter(Position = 0, Mandatory, ParameterSetName = 'ScriptBlockSet')]
            [scriptblock]
            $CompletionGenerator
        )

        $actualSubCommands = $null
        if ($null -ne $SubCommands) {
            $actualSubCommands = [NativeCommandTreeNode[]](& $SubCommands)
        }

        switch ($PSCmdlet.ParameterSetName) {
            'Default' {
                New-Object NativeCommandTreeNode $Completion, $Tooltip, $actualSubCommands
                break
            }
            'Argument' {
                New-Object NativeCommandTreeNode $Completion, $Tooltip, $true
            }
            'ScriptBlockSet' {
                New-Object NativeCommandTreeNode $CompletionGenerator, $actualSubCommands
                break
            }
        }
    }

    #############################################################################
    #
    function Get-CommandTreeCompletion {
        param ($wordToComplete,

            $commandAst,

            [NativeCommandTreeNode[]]
            $CommandTree)

        $commandElements = $commandAst.CommandElements

        # Skip the first command element - it's the command name
        # Iterate through the remaining elements, stopping early
        # if we find the element that matches $wordToComplete.
        for ($i = 1; $i -lt $commandElements.Count; $i++) {
            if (!($commandElements[$i] -is [System.Management.Automation.Language.StringConstantExpressionAst])) {
                # Ignore arguments that are expressions.  In some rare cases this
                # could cause strange completions because the context is incorrect, e.g.:
                #    $c = 'advfirewall'
                #    netsh $c firewall
                # Here we would be in advfirewall firewall context, but we'd complete as
                # though we were in firewall context.
                continue
            }

            if ($commandElements[$i].Value -eq $wordToComplete) {
                $CommandTree = $CommandTree |
                    Where-Object { $_.Command -like "$wordToComplete*" -or $_.CompletionGenerator -ne $null }
                break
            }

            foreach ($subCommand in $CommandTree) {
                if ($subCommand.Command -eq $commandElements[$i].Value) {
                    if (!$subCommand.Argument) {
                        $CommandTree = $subCommand.SubCommands
                    }
                    break
                }
            }
        }

        if ($null -ne $CommandTree) {
            $CommandTree | ForEach-Object {
                if ($_.Command) {
                    $toolTip = if ($_.Tooltip) { $_.Tooltip }
                    else { $_.Command }
                    New-CompletionResult -CompletionText $_.Command -ToolTip $toolTip
                } else {
                    & $_.CompletionGenerator $wordToComplete $commandAst
                }
            }
        }
    }

    #endregion Exported utility functions for completers

    #region Exported functions

    #############################################################################
    #
    # .SYNOPSIS
    #     Register a ScriptBlock to perform argument completion for a
    #     given command or parameter.
    #
    # .DESCRIPTION
    #     Argument completion can be extended without needing to do any
    #     parsing in many cases. By registering a handler for specific
    #     commands and/or parameters, PowerShell will call the handler
    #     when appropriate.
    #
    #     There are 2 kinds of extensions - native and PowerShell. Native
    #     refers to commands external to PowerShell, e.g. net.exe. PowerShell
    #     completion covers any functions, scripts, or cmdlets where PowerShell
    #     can determine the correct parameter being completed.
    #
    #     When registering a native handler, you must specify the CommandName
    #     parameter. The CommandName is typically specified without any path
    #     or extension. If specifying a path and/or an extension, completion
    #     will only work when the command is specified that way when requesting
    #     completion.
    #
    #     When registering a PowerShell handler, you must specify the
    #     ParameterName parameter. The CommandName is optional - PowerShell will
    #     first try to find a handler based on the command and parameter, but
    #     if none is found, then it will try just the parameter name. This way,
    #     you could specify a handler for all commands that have a specific
    #     parameter.
    #
    #     A handler needs to return instances of
    #     System.Management.Automation.CompletionResult.
    #
    #     A native handler is passed 2 parameters:
    #
    #         param($wordToComplete, $commandAst)
    #
    #     $wordToComplete  - The argument being completed, possibly an empty string
    #     $commandAst      - The ast of the command being completed.
    #
    #     A PowerShell handler is passed 5 parameters:
    #
    #         param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
    #
    #     $commandName        - The command name
    #     $parameterName      - The parameter name
    #     $wordToComplete     - The argument being completed, possibly an empty string
    #     $commandAst         - The parsed representation of the command being completed.
    #     $fakeBoundParameter - Like $PSBoundParameters, contains values for some of the parameters.
    #                           Certain values are not included, this does not mean a parameter was
    #                           not specified, just that getting the value could have had unintended
    #                           side effects, so no value was computed.
    #
    # .PARAMETER ParameterName
    #     The name of the parameter that the Completion parameter supports.
    #     This parameter is not supported for native completion and is
    #     mandatory for script completion.
    #
    # .PARAMETER CommandName
    #     The name of the command that the Completion parameter supports.
    #     This parameter is mandatory for native completion and is optional
    #     for script completion.
    #
    # .PARAMETER Completion
    #     A ScriptBlock that returns instances of CompletionResult. For
    #     native completion, the script block parameters are
    #
    #         param($wordToComplete, $commandAst)
    #
    #     For script completion, the parameters are:
    #
    #         param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
    #
    # .PARAMETER Description
    #     A description of how the completion can be used.
    #
    function Register-ArgumentCompleter {
        [CmdletBinding(DefaultParameterSetName = "PowerShellSet")]
        param (
            [Parameter(ParameterSetName = "NativeSet", Mandatory)]
            [Parameter(ParameterSetName = "PowerShellSet")]
            [string[]]
            $CommandName = "",

            [Parameter(ParameterSetName = "PowerShellSet", Mandatory)]
            [string]
            $ParameterName = "",

            [Parameter(Mandatory)]
            [scriptblock]
            $ScriptBlock,

            [string]
            $Description,

            [Parameter(ParameterSetName = "NativeSet")]
            [switch]
            $Native)

        $fnDefn = $ScriptBlock.Ast -as [System.Management.Automation.Language.FunctionDefinitionAst]
        if (!$Description) {
            # See if the script block is really a function, if so, use the function name.
            $Description = if ($fnDefn -ne $null) { $fnDefn.Name }
            else { "" }
        }

        if ($MyInvocation.ScriptName -ne (& { $MyInvocation.ScriptName })) {
            # Make an unbound copy of the script block so it has access to TabExpansionPlusPlus when invoked.
            # We can skip this step if we created the script block (Register-ArgumentCompleter was
            # called internally).
            if ($fnDefn -ne $null) {
                $ScriptBlock = $ScriptBlock.Ast.Body.GetScriptBlock() # Don't reparse, just get a new ScriptBlock.
            } else {
                $ScriptBlock = $ScriptBlock.Ast.GetScriptBlock() # Don't reparse, just get a new ScriptBlock.
            }
        }

        foreach ($command in $CommandName) {
            if ($command -and $ParameterName) {
                $command += ":"
            }

            $key = if ($Native) { 'NativeArgumentCompleters' }
            else { 'CustomArgumentCompleters' }
            $tabExpansionOptions[$key]["${command}${ParameterName}"] = $ScriptBlock

            $tabExpansionDescriptions["${command}${ParameterName}$Native"] = $Description
        }
    }

    #############################################################################
    #
    # .SYNOPSIS
    #     Tests the registered argument completer
    #
    # .DESCRIPTION
    #     Invokes the registered parameteter completer for a specified command to make it easier to test
    #     a completer
    #
    # .EXAMPLE
    #  Test-ArgumentCompleter -CommandName Get-Verb -ParameterName Verb -WordToComplete Sta
    #
    # Test what would be completed if Get-Verb -Verb Sta<Tab> was typed at the prompt
    #
    # .EXAMPLE
    #  Test-ArgumentCompleter -NativeCommand Robocopy -WordToComplete /
    #
    # Test what would be completed if Robocopy /<Tab> was typed at the prompt
    #
    function Test-ArgumentCompleter {
        [CmdletBinding(DefaultParametersetName = 'PS')]
        param
        (
            [Parameter(Mandatory, Position = 1, ParameterSetName = 'PS')]
            [string]
            $CommandName
            ,

            [Parameter(Mandatory, Position = 2, ParameterSetName = 'PS')]
            [string]
            $ParameterName
            ,

            [Parameter(ParameterSetName = 'PS')]
            [System.Management.Automation.Language.CommandAst]
            $commandAst
            ,

            [Parameter(ParameterSetName = 'PS')]
            [Hashtable]
            $FakeBoundParameters = @{ }
            ,

            [Parameter(Mandatory, Position = 1, ParameterSetName = 'NativeCommand')]
            [string]
            $NativeCommand
            ,

            [Parameter(Position = 2, ParameterSetName = 'NativeCommand')]
            [Parameter(Position = 3, ParameterSetName = 'PS')]
            [string]
            $WordToComplete = ''

        )

        if ($PSCmdlet.ParameterSetName -eq 'NativeCommand') {
            $Tokens = $null
            $Errors = $null
            $ast = [System.Management.Automation.Language.Parser]::ParseInput($NativeCommand, [ref]$Tokens, [ref]$Errors)
            $commandAst = $ast.EndBlock.Statements[0].PipelineElements[0]
            $command = $commandAst.GetCommandName()
            $completer = $tabExpansionOptions.NativeArgumentCompleters[$command]
            if (-not $Completer) {
                throw "No argument completer registered for command '$Command' (from $NativeCommand)"
            }
            & $completer $WordToComplete $commandAst
        } else {
            $completer = $tabExpansionOptions.CustomArgumentCompleters["${CommandName}:$ParameterName"]
            if (-not $Completer) {
                throw "No argument completer registered for '${CommandName}:$ParameterName'"
            }
            & $completer $CommandName $ParameterName $WordToComplete $commandAst $FakeBoundParameters
        }
    }

    #############################################################################
    #
    # .SYNOPSIS
    # Retrieves a list of argument completers that have been loaded into the
    # PowerShell session.
    #
    # .PARAMETER Name
    # The name of the argument complete to retrieve. This parameter supports
    # wildcards (asterisk).
    #
    # .EXAMPLE
    # Get-ArgumentCompleter -Name *Azure*;
    function Get-ArgumentCompleter {
        [CmdletBinding()]
        param ([string[]]
            $Name = '*')

        if (!$updatedTypeData) {
            # Define the default display properties for the objects returned by Get-ArgumentCompleter
            [string[]]$properties = "Command", "Parameter"
            Update-TypeData -TypeName 'TabExpansionPlusPlus.ArgumentCompleter' -DefaultDisplayPropertySet $properties -Force
            $updatedTypeData = $true
        }

        function WriteCompleters {
            function WriteCompleter($command, $parameter, $native, $scriptblock) {
                foreach ($n in $Name) {
                    if ($command -like $n) {
                        $c = $command
                        if ($command -and $parameter) { $c += ':' }
                        $description = $tabExpansionDescriptions["${c}${parameter}${native}"]
                        $completer = [pscustomobject]@{
                            Command     = $command
                            Parameter   = $parameter
                            Native      = $native
                            Description = $description
                            ScriptBlock = $scriptblock
                            File        = if ($scriptblock.File) { Split-Path -Leaf -Path $scriptblock.File }
                        }

                        $completer.PSTypeNames.Add('TabExpansionPlusPlus.ArgumentCompleter')
                        Write-Output $completer

                        break
                    }
                }
            }

            foreach ($pair in $tabExpansionOptions.CustomArgumentCompleters.GetEnumerator()) {
                if ($pair.Key -match '^(.*):(.*)$') {
                    $command = $matches[1]
                    $parameter = $matches[2]
                } else {
                    $parameter = $pair.Key
                    $command = ""
                }

                WriteCompleter $command $parameter $false $pair.Value
            }

            foreach ($pair in $tabExpansionOptions.NativeArgumentCompleters.GetEnumerator()) {
                WriteCompleter $pair.Key '' $true $pair.Value
            }
        }

        WriteCompleters | Sort-Object -Property Native, Command, Parameter
    }

    #############################################################################
    #
    # .SYNOPSIS
    #     Register a ScriptBlock to perform argument completion for a
    #     given command or parameter.
    #
    # .DESCRIPTION
    #
    # .PARAMETER Option
    #
    #     The name of the option.
    #
    # .PARAMETER Value
    #
    #     The value to set for Option. Typically this will be $true.
    #
    function Set-TabExpansionOption {
        param (
            [ValidateSet('ExcludeHiddenFiles',
                'RelativePaths',
                'LiteralPaths',
                'IgnoreHiddenShares',
                'AppendBackslash')]
            [string]
            $Option,

            [object]
            $Value = $true)

        $tabExpansionOptions[$option] = $value
    }

    #endregion Exported functions

    #region Internal utility functions

    #############################################################################
    #
    # This function checks if an attribute argument's name can be completed.
    # For example:
    #     [Parameter(<TAB>
    #     [Parameter(Po<TAB>
    #     [CmdletBinding(DefaultPa<TAB>
    #
    function TryAttributeArgumentCompletion {
        param (
            [System.Management.Automation.Language.Ast]
            $ast,

            [int]
            $offset
        )

        $results = @()
        $matchIndex = -1

        try {
            # We want to find any NamedAttributeArgumentAst objects where the Ast extent includes $offset
            $offsetInExtentPredicate = {
                param ($ast)
                return $offset -gt $ast.Extent.StartOffset -and
                $offset -le $ast.Extent.EndOffset
            }
            $asts = $ast.FindAll($offsetInExtentPredicate, $true)

            $attributeType = $null
            $attributeArgumentName = ""
            $replacementIndex = $offset
            $replacementLength = 0

            $attributeArg = $asts | Where-Object { $_ -is [System.Management.Automation.Language.NamedAttributeArgumentAst] } | Select-Object -First 1
            if ($null -ne $attributeArg) {
                $attributeAst = [System.Management.Automation.Language.AttributeAst]$attributeArg.Parent
                $attributeType = $attributeAst.TypeName.GetReflectionAttributeType()
                $attributeArgumentName = $attributeArg.ArgumentName
                $replacementIndex = $attributeArg.Extent.StartOffset
                $replacementLength = $attributeArg.ArgumentName.Length
            } else {
                $attributeAst = $asts | Where-Object { $_ -is [System.Management.Automation.Language.AttributeAst] } | Select-Object -First 1
                if ($null -ne $attributeAst) {
                    $attributeType = $attributeAst.TypeName.GetReflectionAttributeType()
                }
            }

            if ($null -ne $attributeType) {
                $results = $attributeType.GetProperties('Public,Instance') |
                    Where-Object {
                    # Ignore TypeId (all attributes inherit it)
                    $_.Name -like "$attributeArgumentName*" -and $_.Name -ne 'TypeId'
                } |
                    Sort-Object -Property Name |
                    ForEach-Object {
                    $propType = [Microsoft.PowerShell.ToStringCodeMethods]::Type($_.PropertyType)
                    $propName = $_.Name
                    New-CompletionResult $propName -ToolTip "$propType $propName" -CompletionResultType Property
                }

                return [PSCustomObject]@{
                    Results           = $results
                    ReplacementIndex  = $replacementIndex
                    ReplacementLength = $replacementLength
                }
            }
        } catch { }
    }

    #############################################################################
    #
    # This function completes native commands options starting with - or --
    # works around a bug in PowerShell that causes it to not complete
    # native command options starting with - or --
    #
    function TryNativeCommandOptionCompletion {
        param (
            [System.Management.Automation.Language.Ast]
            $ast,

            [int]
            $offset
        )

        $results = @()
        $replacementIndex = $offset
        $replacementLength = 0
        try {
            # We want to find any Command element objects where the Ast extent includes $offset
            $offsetInOptionExtentPredicate = {
                param ($ast)
                return $offset -gt $ast.Extent.StartOffset -and
                $offset -le $ast.Extent.EndOffset -and
                $ast.Extent.Text.StartsWith('-')
            }
            $option = $ast.Find($offsetInOptionExtentPredicate, $true)
            if ($option -ne $null) {
                $command = $option.Parent -as [System.Management.Automation.Language.CommandAst]
                if ($command -ne $null) {
                    $nativeCommand = [System.IO.Path]::GetFileNameWithoutExtension($command.CommandElements[0].Value)
                    $nativeCompleter = $tabExpansionOptions.NativeArgumentCompleters[$nativeCommand]

                    if ($nativeCompleter) {
                        $results = @(& $nativeCompleter $option.ToString() $command)
                        if ($results.Count -gt 0) {
                            $replacementIndex = $option.Extent.StartOffset
                            $replacementLength = $option.Extent.Text.Length
                        }
                    }
                }
            }
        } catch { }

        return [PSCustomObject]@{
            Results           = $results
            ReplacementIndex  = $replacementIndex
            ReplacementLength = $replacementLength
        }
    }


    #endregion Internal utility functions

    #############################################################################
    #
    # This function is partly a copy of the V3 TabExpansion2, adding a few
    # capabilities such as completing attribute arguments and excluding hidden
    # files from results.
    #
    function global:TabExpansion2 {
        [CmdletBinding(DefaultParameterSetName = 'ScriptInputSet')]
        param (
            [Parameter(ParameterSetName = 'ScriptInputSet', Mandatory, Position = 0)]
            [string]
            $inputScript,

            [Parameter(ParameterSetName = 'ScriptInputSet', Mandatory, Position = 1)]
            [int]
            $cursorColumn,

            [Parameter(ParameterSetName = 'AstInputSet', Mandatory, Position = 0)]
            [System.Management.Automation.Language.Ast]
            $ast,

            [Parameter(ParameterSetName = 'AstInputSet', Mandatory, Position = 1)]
            [System.Management.Automation.Language.Token[]]
            $tokens,

            [Parameter(ParameterSetName = 'AstInputSet', Mandatory, Position = 2)]
            [System.Management.Automation.Language.IScriptPosition]
            $positionOfCursor,

            [Parameter(ParameterSetName = 'ScriptInputSet', Position = 2)]
            [Parameter(ParameterSetName = 'AstInputSet', Position = 3)]
            [Hashtable]
            $options = $null
        )

        if ($null -ne $options) {
            $options += $tabExpansionOptions
        } else {
            $options = $tabExpansionOptions
        }

        if ($psCmdlet.ParameterSetName -eq 'ScriptInputSet') {
            $results = [System.Management.Automation.CommandCompletion]::CompleteInput(
                <#inputScript#>                $inputScript,
                <#cursorColumn#>                $cursorColumn,
                <#options#>                $options)
        } else {
            $results = [System.Management.Automation.CommandCompletion]::CompleteInput(
                <#ast#>                $ast,
                <#tokens#>                $tokens,
                <#positionOfCursor#>                $positionOfCursor,
                <#options#>                $options)
        }

        if ($results.CompletionMatches.Count -eq 0) {
            # Built-in didn't succeed, try our own completions here.
            if ($psCmdlet.ParameterSetName -eq 'ScriptInputSet') {
                $ast = [System.Management.Automation.Language.Parser]::ParseInput($inputScript, [ref]$tokens, [ref]$null)
            } else {
                $cursorColumn = $positionOfCursor.Offset
            }

            # workaround PowerShell bug that case it to not invoking native completers for - or --
            # making it hard to complete options for many commands
            $nativeCommandResults = TryNativeCommandOptionCompletion -ast $ast -offset $cursorColumn
            if ($null -ne $nativeCommandResults) {
                $results.ReplacementIndex = $nativeCommandResults.ReplacementIndex
                $results.ReplacementLength = $nativeCommandResults.ReplacementLength
                if ($results.CompletionMatches.IsReadOnly) {
                    # Workaround where PowerShell returns a readonly collection that we need to add to.
                    $collection = new-object System.Collections.ObjectModel.Collection[System.Management.Automation.CompletionResult]
                    $results.GetType().GetProperty('CompletionMatches').SetValue($results, $collection)
                }
                $nativeCommandResults.Results | ForEach-Object {
                    $results.CompletionMatches.Add($_)
                }
            }

            $attributeResults = TryAttributeArgumentCompletion $ast $cursorColumn
            if ($null -ne $attributeResults) {
                $results.ReplacementIndex = $attributeResults.ReplacementIndex
                $results.ReplacementLength = $attributeResults.ReplacementLength
                if ($results.CompletionMatches.IsReadOnly) {
                    # Workaround where PowerShell returns a readonly collection that we need to add to.
                    $collection = new-object System.Collections.ObjectModel.Collection[System.Management.Automation.CompletionResult]
                    $results.GetType().GetProperty('CompletionMatches').SetValue($results, $collection)
                }
                $attributeResults.Results | ForEach-Object {
                    $results.CompletionMatches.Add($_)
                }
            }
        }

        if ($options.ExcludeHiddenFiles) {
            foreach ($result in @($results.CompletionMatches)) {
                if ($result.ResultType -eq [System.Management.Automation.CompletionResultType]::ProviderItem -or
                    $result.ResultType -eq [System.Management.Automation.CompletionResultType]::ProviderContainer) {
                    try {
                        $item = Get-Item -LiteralPath $result.CompletionText -ErrorAction Stop
                    } catch {
                        # If Get-Item w/o -Force fails, it is probably hidden, so exclude the result
                        $null = $results.CompletionMatches.Remove($result)
                    }
                }
            }
        }
        if ($options.AppendBackslash -and
            $results.CompletionMatches.ResultType -contains [System.Management.Automation.CompletionResultType]::ProviderContainer) {
            foreach ($result in @($results.CompletionMatches)) {
                if ($result.ResultType -eq [System.Management.Automation.CompletionResultType]::ProviderContainer) {
                    $completionText = $result.CompletionText
                    $lastChar = $completionText[-1]
                    $lastIsQuote = ($lastChar -eq '"' -or $lastChar -eq "'")
                    if ($lastIsQuote) {
                        $lastChar = $completionText[-2]
                    }

                    if ($lastChar -ne '\') {
                        $null = $results.CompletionMatches.Remove($result)

                        if ($lastIsQuote) {
                            $completionText =
                            $completionText.Substring(0, $completionText.Length - 1) +
                            '\' + $completionText[-1]
                        } else {
                            $completionText = $completionText + '\'
                        }

                        $updatedResult = New-Object System.Management.Automation.CompletionResult `
                        ($completionText, $result.ListItemText, $result.ResultType, $result.ToolTip)
                        $results.CompletionMatches.Add($updatedResult)
                    }
                }
            }
        }

        if ($results.CompletionMatches.Count -eq 0) {
            # No results, if this module has overridden another TabExpansion2 function, call it
            # but only if it's not the built-in function (which we assume if function isn't
            # defined in a file.
            if ($oldTabExpansion2 -ne $null -and $oldTabExpansion2.File -ne $null) {
                return (& $oldTabExpansion2 @PSBoundParameters)
            }
        }

        return $results
    }


    #############################################################################
    #
    # Main
    #

    Add-Type @"
using System;
using System.Management.Automation;

public class NativeCommandTreeNode
{
    private NativeCommandTreeNode(NativeCommandTreeNode[] subCommands)
    {
        SubCommands = subCommands;
    }

    public NativeCommandTreeNode(string command, NativeCommandTreeNode[] subCommands)
        : this(command, null, subCommands)
    {
    }

    public NativeCommandTreeNode(string command, string tooltip, NativeCommandTreeNode[] subCommands)
        : this(subCommands)
    {
        this.Command = command;
        this.Tooltip = tooltip;
    }

    public NativeCommandTreeNode(string command, string tooltip, bool argument)
        : this(null)
    {
        this.Command = command;
        this.Tooltip = tooltip;
        this.Argument = true;
    }

    public NativeCommandTreeNode(ScriptBlock completionGenerator, NativeCommandTreeNode[] subCommands)
        : this(subCommands)
    {
        this.CompletionGenerator = completionGenerator;
    }

    public string Command { get; private set; }
    public string Tooltip { get; private set; }
    public bool Argument { get; private set; }
    public ScriptBlock CompletionGenerator { get; private set; }
    public NativeCommandTreeNode[] SubCommands { get; private set; }
}
"@

    # Custom completions are saved in this hashtable
    $tabExpansionOptions = @{
        CustomArgumentCompleters = @{ }
        NativeArgumentCompleters = @{ }
    }
    # Descriptions for the above completions saved in this hashtable
    $tabExpansionDescriptions = @{ }
    # And private data for the above completions cached in this hashtable
    $completionPrivateData = @{ }
}
tools\dbatools\PSGetModuleInfo.xml
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
  <Obj RefId="0">
    <TN RefId="0">
      <T>Microsoft.PowerShell.Commands.PSRepositoryItemInfo</T>
      <T>System.Management.Automation.PSCustomObject</T>
      <T>System.Object</T>
    </TN>
    <MS>
      <S N="Name">dbatools</S>
      <S N="Version">0.9.737</S>
      <S N="Type">Module</S>
      <S N="Description">The community module that enables SQL Server Pros to automate database development and server administration</S>
      <S N="Author">Chrissy LeMaire</S>
      <Obj N="CompanyName" RefId="1">
        <TN RefId="1">
          <T>System.Object[]</T>
          <T>System.Array</T>
          <T>System.Object</T>
        </TN>
        <LST>
          <S>chrissylemaire</S>
          <S>FWN</S>
          <S>SQLDBAWithABeard</S>
          <S>wsmelton</S>
        </LST>
      </Obj>
      <S N="Copyright">Copyright (c) 2018 by dbatools, licensed under MIT</S>
      <DT N="PublishedDate">2019-01-08T19:09:12+00:00</DT>
      <Nil N="InstalledDate" />
      <Nil N="UpdatedDate" />
      <URI N="LicenseUri">https://opensource.org/licenses/MIT</URI>
      <URI N="ProjectUri">https://dbatools.io/</URI>
      <URI N="IconUri">https://dbatools.io/logo.png</URI>
      <Obj N="Tags" RefId="2">
        <TNRef RefId="1" />
        <LST>
          <S>sqlserver</S>
          <S>migrations</S>
          <S>sql</S>
          <S>dba</S>
          <S>databases</S>
          <S>mac</S>
          <S>linux</S>
          <S>core</S>
          <S>PSModule</S>
        </LST>
      </Obj>
      <Obj N="Includes" RefId="3">
        <TN RefId="2">
          <T>System.Collections.Hashtable</T>
          <T>System.Object</T>
        </TN>
        <DCT>
          <En>
            <S N="Key">Function</S>
            <Obj N="Value" RefId="4">
              <TNRef RefId="1" />
              <LST>
                <S>Start-DbaMigration</S>
                <S>Copy-DbaDatabase</S>
                <S>Copy-DbaLogin</S>
                <S>Copy-DbaAgentServer</S>
                <S>Copy-DbaSpConfigure</S>
                <S>Copy-DbaDbMail</S>
                <S>Copy-DbaDbAssembly</S>
                <S>Copy-DbaAgentSchedule</S>
                <S>Copy-DbaAgentOperator</S>
                <S>Copy-DbaAgentJob</S>
                <S>Copy-DbaCustomError</S>
                <S>Copy-DbaServerAuditSpecification</S>
                <S>Copy-DbaEndpoint</S>
                <S>Copy-DbaServerAudit</S>
                <S>Copy-DbaServerRole</S>
                <S>Copy-DbaResourceGovernor</S>
                <S>Copy-DbaXESession</S>
                <S>Copy-DbaBackupDevice</S>
                <S>Copy-DbaServerTrigger</S>
                <S>Copy-DbaCmsRegServer</S>
                <S>Copy-DbaSysDbUserObject</S>
                <S>Copy-DbaAgentProxy</S>
                <S>Copy-DbaAgentAlert</S>
                <S>Get-DbaDetachedDatabaseInfo</S>
                <S>Restore-DbaBackupFromDirectory</S>
                <S>Copy-DbaAgentJobCategory</S>
                <S>Test-DbaPath</S>
                <S>Export-DbaLogin</S>
                <S>Watch-DbaDbLogin</S>
                <S>Expand-DbaDbLogFile</S>
                <S>Test-DbaMigrationConstraint</S>
                <S>Test-DbaNetworkLatency</S>
                <S>Find-DbaDuplicateIndex</S>
                <S>Remove-DbaDatabaseSafely</S>
                <S>Set-DbaTempdbConfig</S>
                <S>Test-DbaTempdbConfig</S>
                <S>Repair-DbaDbOrphanUser</S>
                <S>Remove-DbaDbOrphanUser</S>
                <S>Find-DbaDbUnusedIndex</S>
                <S>Get-DbaDbSpace</S>
                <S>Test-DbaDbOwner</S>
                <S>Set-DbaDbOwner</S>
                <S>Test-DbaJobOwner</S>
                <S>Set-DbaAgentJobOwner</S>
                <S>Test-DbaDbVirtualLogFile</S>
                <S>Get-DbaDbRestoreHistory</S>
                <S>Get-DbaTcpPort</S>
                <S>Test-DbaDbCompatibility</S>
                <S>Test-DbaDbCollation</S>
                <S>Test-DbaConnectionAuthScheme</S>
                <S>Test-DbaServerName</S>
                <S>Repair-DbaServerName</S>
                <S>Stop-DbaProcess</S>
                <S>Find-DbaOrphanedFile</S>
                <S>Get-DbaAvailabilityGroup</S>
                <S>Get-DbaLastGoodCheckDb</S>
                <S>Get-DbaProcess</S>
                <S>Get-DbaRunningJob</S>
                <S>Set-DbaMaxDop</S>
                <S>Test-DbaDbRecoveryModel</S>
                <S>Test-DbaMaxDop</S>
                <S>Remove-DbaBackup</S>
                <S>Get-DbaPermission</S>
                <S>Get-DbaLastBackup</S>
                <S>Connect-DbaInstance</S>
                <S>Get-DbaBackupHistory</S>
                <S>Read-DbaBackupHeader</S>
                <S>Test-DbaLastBackup</S>
                <S>Get-DbaMaxMemory</S>
                <S>Set-DbaMaxMemory</S>
                <S>Get-DbaDbSnapshot</S>
                <S>Remove-DbaDbSnapshot</S>
                <S>Get-DbaDbRoleMember</S>
                <S>Get-DbaServerRoleMember</S>
                <S>Resolve-DbaNetworkName</S>
                <S>Export-DbaAvailabilityGroup</S>
                <S>Write-DbaDataTable</S>
                <S>New-DbaDbSnapshot</S>
                <S>Restore-DbaDbSnapshot</S>
                <S>Get-DbaServerTrigger</S>
                <S>Get-DbaDbTrigger</S>
                <S>Get-DbaDbState</S>
                <S>Set-DbaDbState</S>
                <S>Get-DbaHelpIndex</S>
                <S>Get-DbaAgentAlert</S>
                <S>Get-DbaAgentOperator</S>
                <S>Get-DbaSpConfigure</S>
                <S>Rename-DbaLogin</S>
                <S>Find-DbaAgentJob</S>
                <S>Find-DbaDatabase</S>
                <S>Get-DbaXESession</S>
                <S>Test-DbaOptimizeForAdHoc</S>
                <S>Find-DbaStoredProcedure</S>
                <S>Measure-DbaBackupThroughput</S>
                <S>Get-DbaDatabase</S>
                <S>Find-DbaUserObject</S>
                <S>Get-DbaDependency</S>
                <S>Find-DbaCommand</S>
                <S>Backup-DbaDatabase</S>
                <S>New-DbaDirectory</S>
                <S>Get-DbaDbQueryStoreOption</S>
                <S>Set-DbaDbQueryStoreOption</S>
                <S>Restore-DbaDatabase</S>
                <S>Copy-DbaDbQueryStoreOption</S>
                <S>Get-DbaExecutionPlan</S>
                <S>Export-DbaExecutionPlan</S>
                <S>Set-DbaSpConfigure</S>
                <S>Test-DbaIdentityUsage</S>
                <S>Get-DbaDbAssembly</S>
                <S>Get-DbaAgentJob</S>
                <S>Get-DbaCustomError</S>
                <S>Get-DbaCredential</S>
                <S>Get-DbaBackupDevice</S>
                <S>Get-DbaAgentProxy</S>
                <S>Get-DbaDbEncryption</S>
                <S>Remove-DbaDatabase</S>
                <S>Get-DbaQueryExecutionTime</S>
                <S>Get-DbaTempdbUsage</S>
                <S>Find-DbaDbGrowthEvent</S>
                <S>Test-DbaLinkedServerConnection</S>
                <S>Get-DbaDbFile</S>
                <S>Read-DbaTransactionLog</S>
                <S>Get-DbaDbTable</S>
                <S>Invoke-DbaDbShrink</S>
                <S>Get-DbaEstimatedCompletionTime</S>
                <S>Get-DbaLinkedServer</S>
                <S>New-DbaAgentJob</S>
                <S>Get-DbaLogin</S>
                <S>New-DbaScriptingOption</S>
                <S>Save-DbaDiagnosticQueryScript</S>
                <S>Invoke-DbaDiagnosticQuery</S>
                <S>Export-DbaDiagnosticQuery</S>
                <S>Invoke-DbaWhoIsActive</S>
                <S>Set-DbaAgentJob</S>
                <S>Remove-DbaAgentJob</S>
                <S>New-DbaAgentJobStep</S>
                <S>Set-DbaAgentJobStep</S>
                <S>Remove-DbaAgentJobStep</S>
                <S>New-DbaAgentSchedule</S>
                <S>Set-DbaAgentSchedule</S>
                <S>Remove-DbaAgentSchedule</S>
                <S>Backup-DbaDbCertificate</S>
                <S>Get-DbaDbCertificate</S>
                <S>Get-DbaEndpoint</S>
                <S>Get-DbaDbMasterKey</S>
                <S>Get-DbaSchemaChangeHistory</S>
                <S>Get-DbaServerAudit</S>
                <S>Get-DbaServerAuditSpecification</S>
                <S>Get-DbaProductKey</S>
                <S>Get-DbatoolsLog</S>
                <S>Restore-DbaDbCertificate</S>
                <S>New-DbaDbCertificate</S>
                <S>New-DbaDbMasterKey</S>
                <S>New-DbaServiceMasterKey</S>
                <S>Remove-DbaDbCertificate</S>
                <S>Remove-DbaDbMasterKey</S>
                <S>New-DbaConnectionStringBuilder</S>
                <S>Get-DbaInstanceProperty</S>
                <S>Get-DbaInstanceUserOption</S>
                <S>New-DbaConnectionString</S>
                <S>Get-DbaAgentSchedule</S>
                <S>Read-DbaTraceFile</S>
                <S>Get-DbaServerInstallDate</S>
                <S>Backup-DbaDbMasterKey</S>
                <S>Get-DbaAgentJobHistory</S>
                <S>Get-DbaMaintenanceSolutionLog</S>
                <S>Invoke-DbaDbLogShipRecovery</S>
                <S>Find-DbaTrigger</S>
                <S>Find-DbaView</S>
                <S>Invoke-DbaDbUpgrade</S>
                <S>Get-DbaDbUser</S>
                <S>Get-DbaAgentLog</S>
                <S>Get-DbaDbMailLog</S>
                <S>Get-DbaDbMailHistory</S>
                <S>Get-DbaDbView</S>
                <S>Get-DbaDbUdf</S>
                <S>Get-DbaDbPartitionFunction</S>
                <S>Get-DbaDbPartitionScheme</S>
                <S>Get-DbaDefaultPath</S>
                <S>Get-DbaDbStoredProcedure</S>
                <S>Test-DbaDbCompression</S>
                <S>Mount-DbaDatabase</S>
                <S>Dismount-DbaDatabase</S>
                <S>Get-DbaAgReplica</S>
                <S>Get-DbaAgDatabase</S>
                <S>Get-DbaModule</S>
                <S>Sync-DbaLoginPermission</S>
                <S>New-DbaCredential</S>
                <S>Get-DbaFile</S>
                <S>Set-DbaDbCompression</S>
                <S>Get-DbaTraceFlag</S>
                <S>Invoke-DbaCycleErrorLog</S>
                <S>Get-DbaAvailableCollation</S>
                <S>Get-DbaUserPermission</S>
                <S>Get-DbaAgHadr</S>
                <S>Find-DbaSimilarTable</S>
                <S>Get-DbaTrace</S>
                <S>Get-DbaSuspectPage</S>
                <S>Get-DbaWaitStatistic</S>
                <S>Clear-DbaWaitStatistics</S>
                <S>Get-DbaTopResourceUsage</S>
                <S>New-DbaLogin</S>
                <S>Get-DbaAgListener</S>
                <S>Invoke-DbaDbClone</S>
                <S>Disable-DbaTraceFlag</S>
                <S>Enable-DbaTraceFlag</S>
                <S>Start-DbaAgentJob</S>
                <S>Stop-DbaAgentJob</S>
                <S>New-DbaAgentProxy</S>
                <S>Test-DbaDbLogShipStatus</S>
                <S>Get-DbaXESessionTarget</S>
                <S>New-DbaXESmartTargetResponse</S>
                <S>New-DbaXESmartTarget</S>
                <S>Get-DbaDbVirtualLogFile</S>
                <S>Get-DbaBackupInformation</S>
                <S>Start-DbaXESession</S>
                <S>Stop-DbaXESession</S>
                <S>Set-DbaDbRecoveryModel</S>
                <S>Get-DbaDbRecoveryModel</S>
                <S>Get-DbaWaitingTask</S>
                <S>Remove-DbaDbUser</S>
                <S>Get-DbaDump</S>
                <S>Invoke-DbaAdvancedRestore</S>
                <S>Format-DbaBackupInformation</S>
                <S>Get-DbaAgentJobStep</S>
                <S>Test-DbaBackupInformation</S>
                <S>Invoke-DbaBalanceDataFiles</S>
                <S>Select-DbaBackupInformation</S>
                <S>Publish-DbaDacPackage</S>
                <S>Copy-DbaDbTableData</S>
                <S>Invoke-DbaQuery</S>
                <S>Remove-DbaLogin</S>
                <S>Get-DbaAgentJobCategory</S>
                <S>New-DbaAgentJobCategory</S>
                <S>Remove-DbaAgentJobCategory</S>
                <S>Set-DbaAgentJobCategory</S>
                <S>Get-DbaDbRole</S>
                <S>Get-DbaServerRole</S>
                <S>Find-DbaBackup</S>
                <S>Remove-DbaXESession</S>
                <S>New-DbaXESession</S>
                <S>Get-DbaXEStore</S>
                <S>New-DbaXESmartTableWriter</S>
                <S>New-DbaXESmartReplay</S>
                <S>New-DbaXESmartEmail</S>
                <S>New-DbaXESmartQueryExec</S>
                <S>Start-DbaXESmartTarget</S>
                <S>Get-DbaDbOrphanUser</S>
                <S>Get-DbaOpenTransaction</S>
                <S>Get-DbaDbLogShipError</S>
                <S>Test-DbaBuild</S>
                <S>Get-DbaXESessionTemplate</S>
                <S>ConvertTo-DbaXESession</S>
                <S>Start-DbaTrace</S>
                <S>Stop-DbaTrace</S>
                <S>Remove-DbaTrace</S>
                <S>Set-DbaLogin</S>
                <S>Copy-DbaXESessionTemplate</S>
                <S>Get-DbaXEObject</S>
                <S>ConvertTo-DbaDataTable</S>
                <S>Find-DbaDisabledIndex</S>
                <S>Get-DbaXESmartTarget</S>
                <S>Remove-DbaXESmartTarget</S>
                <S>Stop-DbaXESmartTarget</S>
                <S>Get-DbaCmsRegServerGroup</S>
                <S>New-DbaDbUser</S>
                <S>Measure-DbaDiskSpaceRequirement</S>
                <S>New-DbaXESmartCsvWriter</S>
                <S>Invoke-DbaXeReplay</S>
                <S>Find-DbaInstance</S>
                <S>Test-DbaDiskSpeed</S>
                <S>Get-DbaDbExtentDiff</S>
                <S>Read-DbaAuditFile</S>
                <S>Get-DbaDbCompression</S>
                <S>Invoke-DbaDbDecryptObject</S>
                <S>Get-DbaDbForeignKey</S>
                <S>Get-DbaDbCheckConstraint</S>
                <S>Set-DbaAgentAlert</S>
                <S>Get-DbaWaitResource</S>
                <S>Get-DbaDbPageInfo</S>
                <S>Get-DbaConnection</S>
                <S>Test-DbaLoginPassword</S>
                <S>Get-DbaErrorLogConfig</S>
                <S>Set-DbaErrorLogConfig</S>
                <S>Get-DbaPlanCache</S>
                <S>Clear-DbaPlanCache</S>
                <S>ConvertTo-DbaTimeline</S>
                <S>Get-DbaDbMail</S>
                <S>Get-DbaDbMailAccount</S>
                <S>Get-DbaDbMailProfile</S>
                <S>Get-DbaDbMailConfig</S>
                <S>Get-DbaDbMailServer</S>
                <S>Get-DbaResourceGovernor</S>
                <S>Get-DbaRgResourcePool</S>
                <S>Get-DbaRgWorkloadGroup</S>
                <S>Get-DbaRgClassifierFunction</S>
                <S>Export-DbaInstance</S>
                <S>Invoke-DbatoolsRenameHelper</S>
                <S>Measure-DbatoolsImport</S>
                <S>Get-DbaDeprecatedFeature</S>
                <S>Test-DbaDeprecatedFeature</S>
                <S>Get-DbaDbFeatureUsage</S>
                <S>Stop-DbaEndpoint</S>
                <S>Start-DbaEndpoint</S>
                <S>Set-DbaDbMirror</S>
                <S>Repair-DbaDbMirror</S>
                <S>Remove-DbaEndpoint</S>
                <S>Remove-DbaDbMirrorMonitor</S>
                <S>Remove-DbaDbMirror</S>
                <S>New-DbaEndpoint</S>
                <S>Invoke-DbaDbMirroring</S>
                <S>Invoke-DbaDbMirrorFailover</S>
                <S>Get-DbaDbMirrorMonitor</S>
                <S>Get-DbaDbMirror</S>
                <S>Add-DbaDbMirrorMonitor</S>
                <S>Test-DbaEndpoint</S>
                <S>Get-DbaDbSharePoint</S>
                <S>Get-DbaDbMemoryUsage</S>
                <S>Clear-DbaLatchStatistics</S>
                <S>Get-DbaCpuRingBuffer</S>
                <S>Get-DbaIoLatency</S>
                <S>Get-DbaLatchStatistic</S>
                <S>Get-DbaSpinLockStatistic</S>
                <S>Add-DbaAgDatabase</S>
                <S>Add-DbaAgListener</S>
                <S>Add-DbaAgReplica</S>
                <S>Grant-DbaAgPermission</S>
                <S>Invoke-DbaAgFailover</S>
                <S>Join-DbaAvailabilityGroup</S>
                <S>New-DbaAvailabilityGroup</S>
                <S>Remove-DbaAgDatabase</S>
                <S>Remove-DbaAgListener</S>
                <S>Remove-DbaAvailabilityGroup</S>
                <S>Revoke-DbaAgPermission</S>
                <S>Get-DbaDbCompatibility</S>
                <S>Set-DbaDbCompatibility</S>
                <S>Invoke-DbatoolsFormatter</S>
                <S>Remove-DbaAgReplica</S>
                <S>Resume-DbaAgDbDataMovement</S>
                <S>Set-DbaAgListener</S>
                <S>Set-DbaAgReplica</S>
                <S>Set-DbaAvailabilityGroup</S>
                <S>Set-DbaEndpoint</S>
                <S>Suspend-DbaAgDbDataMovement</S>
                <S>Sync-DbaAvailabilityGroup</S>
                <S>Get-DbaMemoryCondition</S>
                <S>Remove-DbaDbBackupRestoreHistory</S>
                <S>New-DbaDatabase</S>
                <S>New-DbaDacOption</S>
                <S>Get-DbaDbccHelp</S>
                <S>Get-DbaDbccMemoryStatus</S>
                <S>Get-DbaDbccProcCache</S>
                <S>Get-DbaDbccUserOption</S>
                <S>Get-DbaAgentServer</S>
                <S>Set-DbaAgentServer</S>
                <S>Invoke-DbaDbccFreeCache</S>
                <S>Export-DbatoolsConfig</S>
                <S>Import-DbatoolsConfig</S>
                <S>Reset-DbatoolsConfig</S>
                <S>Unregister-DbatoolsConfig</S>
                <S>Join-DbaPath</S>
                <S>Resolve-DbaPath</S>
                <S>Invoke-DbaDbDataMasking</S>
                <S>New-DbaDbMaskingConfig</S>
                <S>Get-DbaDbccSessionBuffer</S>
                <S>Get-DbaDbccStatistic</S>
                <S>Get-DbaDbDbccOpenTran</S>
                <S>Invoke-DbaDbccDropCleanBuffer</S>
                <S>Invoke-DbaDbDbccCheckConstraint</S>
                <S>Invoke-DbaDbDbccCleanTable</S>
                <S>Invoke-DbaDbDbccUpdateUsage</S>
                <S>Export-DbaUser</S>
                <S>Get-DbaSsisExecutionHistory</S>
                <S>Get-DbaRepDistributor</S>
                <S>Get-DbaCmsRegServerStore</S>
                <S>Copy-DbaPolicyManagement</S>
                <S>Copy-DbaDataCollector</S>
                <S>Get-DbaCmsRegServer</S>
                <S>Copy-DbaSsisCatalog</S>
                <S>New-DbaSsisCatalog</S>
                <S>Get-DbaSsisEnvironmentVariable</S>
                <S>Get-DbaPbmCategory</S>
                <S>Get-DbaPbmCategorySubscription</S>
                <S>Get-DbaPbmCondition</S>
                <S>Get-DbaPbmObjectSet</S>
                <S>Get-DbaPbmPolicy</S>
                <S>Get-DbaPbmStore</S>
                <S>Add-DbaCmsRegServer</S>
                <S>Add-DbaCmsRegServerGroup</S>
                <S>Export-DbaCmsRegServer</S>
                <S>Import-DbaCmsRegServer</S>
                <S>Move-DbaCmsRegServer</S>
                <S>Move-DbaCmsRegServerGroup</S>
                <S>Remove-DbaCmsRegServer</S>
                <S>Remove-DbaCmsRegServerGroup</S>
                <S>Get-DbaRepPublication</S>
                <S>Test-DbaRepLatency</S>
                <S>Export-DbaRepServerSetting</S>
                <S>Get-DbaRepServer</S>
                <S>Install-DbaSqlWatch</S>
                <S>Uninstall-DbaSqlWatch</S>
                <S>Get-DbaRegistryRoot</S>
                <S>Install-DbaMaintenanceSolution</S>
                <S>New-DbatoolsSupportPackage</S>
                <S>Export-DbaScript</S>
                <S>Get-DbaAgentJobOutputFile</S>
                <S>Set-DbaAgentJobOutputFile</S>
                <S>Get-DbaBuildReference</S>
                <S>New-DbaDacProfile</S>
                <S>Import-DbaXESessionTemplate</S>
                <S>Export-DbaXESessionTemplate</S>
                <S>Import-DbaSpConfigure</S>
                <S>Export-DbaSpConfigure</S>
                <S>Update-Dbatools</S>
                <S>Install-DbaWhoIsActive</S>
                <S>Install-DbaFirstResponderKit</S>
                <S>Read-DbaXEFile</S>
                <S>Watch-DbaXESession</S>
                <S>Test-DbaMaxMemory</S>
                <S>Rename-DbaDatabase</S>
                <S>Update-DbaInstance</S>
                <S>Invoke-DbaPfRelog</S>
                <S>Get-DbaPfDataCollectorCounter</S>
                <S>Get-DbaPfDataCollectorCounterSample</S>
                <S>Get-DbaPfDataCollector</S>
                <S>Get-DbaPfDataCollectorSet</S>
                <S>Start-DbaPfDataCollectorSet</S>
                <S>Stop-DbaPfDataCollectorSet</S>
                <S>Export-DbaPfDataCollectorSetTemplate</S>
                <S>Get-DbaPfDataCollectorSetTemplate</S>
                <S>Import-DbaPfDataCollectorSetTemplate</S>
                <S>Remove-DbaPfDataCollectorSet</S>
                <S>Add-DbaPfDataCollectorCounter</S>
                <S>Remove-DbaPfDataCollectorCounter</S>
                <S>Get-DbaPfAvailableCounter</S>
                <S>Export-DbaXECsv</S>
                <S>Get-DbaOperatingSystem</S>
                <S>Get-DbaComputerSystem</S>
                <S>Set-DbaPrivilege</S>
                <S>Set-DbaTcpPort</S>
                <S>Set-DbaCmConnection</S>
                <S>Get-DbaUptime</S>
                <S>Get-DbaMemoryUsage</S>
                <S>Clear-DbaConnectionPool</S>
                <S>Get-DbaLocaleSetting</S>
                <S>Get-DbaFilestream</S>
                <S>Enable-DbaFilestream</S>
                <S>Disable-DbaFilestream</S>
                <S>Get-DbaCpuUsage</S>
                <S>Get-DbaPowerPlan</S>
                <S>Get-DbaWsfcAvailableDisk</S>
                <S>Get-DbaWsfcCluster</S>
                <S>Get-DbaWsfcDisk</S>
                <S>Get-DbaWsfcNetwork</S>
                <S>Get-DbaWsfcNetworkInterface</S>
                <S>Get-DbaWsfcNode</S>
                <S>Get-DbaWsfcResource</S>
                <S>Get-DbaWsfcResourceType</S>
                <S>Get-DbaWsfcRole</S>
                <S>Get-DbaWsfcSharedVolume</S>
                <S>Export-DbaCredential</S>
                <S>Export-DbaLinkedServer</S>
                <S>Get-DbaFeature</S>
                <S>Update-DbaServiceAccount</S>
                <S>Remove-DbaClientAlias</S>
                <S>Disable-DbaAgHadr</S>
                <S>Enable-DbaAgHadr</S>
                <S>Stop-DbaService</S>
                <S>Start-DbaService</S>
                <S>Restart-DbaService</S>
                <S>New-DbaClientAlias</S>
                <S>Get-DbaClientAlias</S>
                <S>Remove-DbaNetworkCertificate</S>
                <S>Enable-DbaForceNetworkEncryption</S>
                <S>Disable-DbaForceNetworkEncryption</S>
                <S>Get-DbaForceNetworkEncryption</S>
                <S>Remove-DbaComputerCertificate</S>
                <S>New-DbaComputerCertificate</S>
                <S>Get-DbaComputerCertificate</S>
                <S>Add-DbaComputerCertificate</S>
                <S>Get-DbaNetworkCertificate</S>
                <S>Set-DbaNetworkCertificate</S>
                <S>Invoke-DbaDbLogShipping</S>
                <S>New-DbaCmConnection</S>
                <S>Get-DbaCmConnection</S>
                <S>Remove-DbaCmConnection</S>
                <S>Test-DbaCmConnection</S>
                <S>Get-DbaCmObject</S>
                <S>Set-DbaStartupParameter</S>
                <S>Get-DbaNetworkActivity</S>
                <S>Get-DbaServerProtocol</S>
                <S>Watch-DbaUpdate</S>
                <S>Uninstall-DbaWatchUpdate</S>
                <S>Install-DbaWatchUpdate</S>
                <S>Get-DbaPrivilege</S>
                <S>Get-DbaMsdtc</S>
                <S>Get-DbaPageFileSetting</S>
                <S>Copy-DbaCredential</S>
                <S>Test-DbaConnection</S>
                <S>Reset-DbaAdmin</S>
                <S>Copy-DbaLinkedServer</S>
                <S>Get-DbaDiskSpace</S>
                <S>Test-DbaDiskAllocation</S>
                <S>Test-DbaPowerPlan</S>
                <S>Set-DbaPowerPlan</S>
                <S>Test-DbaDiskAlignment</S>
                <S>Get-DbaStartupParameter</S>
                <S>Get-DbaSpn</S>
                <S>Test-DbaSpn</S>
                <S>Set-DbaSpn</S>
                <S>Remove-DbaSpn</S>
                <S>Get-DbaService</S>
                <S>Get-DbaClientProtocol</S>
                <S>Get-DbaWindowsLog</S>
                <S>Show-DbaServerFileSystem</S>
                <S>Show-DbaDbList</S>
                <S>Test-DbaWindowsLogin</S>
                <S>Find-DbaLoginInGroup</S>
                <S>Import-DbaCsv</S>
                <S>Export-DbaDacPackage</S>
                <S>Get-DbatoolsConfig</S>
                <S>Get-DbatoolsConfigValue</S>
                <S>Register-DbatoolsConfig</S>
                <S>Get-DbaErrorLog</S>
                <S>Get-DbaManagementObject</S>
                <S>Test-DbaManagementObject</S>
              </LST>
            </Obj>
          </En>
          <En>
            <S N="Key">RoleCapability</S>
            <Obj N="Value" RefId="5">
              <TNRef RefId="1" />
              <LST />
            </Obj>
          </En>
          <En>
            <S N="Key">Command</S>
            <Obj N="Value" RefId="6">
              <TNRef RefId="1" />
              <LST>
                <S>Select-DbaObject</S>
                <S>Set-DbatoolsConfig</S>
                <S>Start-DbaMigration</S>
                <S>Copy-DbaDatabase</S>
                <S>Copy-DbaLogin</S>
                <S>Copy-DbaAgentServer</S>
                <S>Copy-DbaSpConfigure</S>
                <S>Copy-DbaDbMail</S>
                <S>Copy-DbaDbAssembly</S>
                <S>Copy-DbaAgentSchedule</S>
                <S>Copy-DbaAgentOperator</S>
                <S>Copy-DbaAgentJob</S>
                <S>Copy-DbaCustomError</S>
                <S>Copy-DbaServerAuditSpecification</S>
                <S>Copy-DbaEndpoint</S>
                <S>Copy-DbaServerAudit</S>
                <S>Copy-DbaServerRole</S>
                <S>Copy-DbaResourceGovernor</S>
                <S>Copy-DbaXESession</S>
                <S>Copy-DbaBackupDevice</S>
                <S>Copy-DbaServerTrigger</S>
                <S>Copy-DbaCmsRegServer</S>
                <S>Copy-DbaSysDbUserObject</S>
                <S>Copy-DbaAgentProxy</S>
                <S>Copy-DbaAgentAlert</S>
                <S>Get-DbaDetachedDatabaseInfo</S>
                <S>Restore-DbaBackupFromDirectory</S>
                <S>Copy-DbaAgentJobCategory</S>
                <S>Test-DbaPath</S>
                <S>Export-DbaLogin</S>
                <S>Watch-DbaDbLogin</S>
                <S>Expand-DbaDbLogFile</S>
                <S>Test-DbaMigrationConstraint</S>
                <S>Test-DbaNetworkLatency</S>
                <S>Find-DbaDuplicateIndex</S>
                <S>Remove-DbaDatabaseSafely</S>
                <S>Set-DbaTempdbConfig</S>
                <S>Test-DbaTempdbConfig</S>
                <S>Repair-DbaDbOrphanUser</S>
                <S>Remove-DbaDbOrphanUser</S>
                <S>Find-DbaDbUnusedIndex</S>
                <S>Get-DbaDbSpace</S>
                <S>Test-DbaDbOwner</S>
                <S>Set-DbaDbOwner</S>
                <S>Test-DbaJobOwner</S>
                <S>Set-DbaAgentJobOwner</S>
                <S>Test-DbaDbVirtualLogFile</S>
                <S>Get-DbaDbRestoreHistory</S>
                <S>Get-DbaTcpPort</S>
                <S>Test-DbaDbCompatibility</S>
                <S>Test-DbaDbCollation</S>
                <S>Test-DbaConnectionAuthScheme</S>
                <S>Test-DbaServerName</S>
                <S>Repair-DbaServerName</S>
                <S>Stop-DbaProcess</S>
                <S>Find-DbaOrphanedFile</S>
                <S>Get-DbaAvailabilityGroup</S>
                <S>Get-DbaLastGoodCheckDb</S>
                <S>Get-DbaProcess</S>
                <S>Get-DbaRunningJob</S>
                <S>Set-DbaMaxDop</S>
                <S>Test-DbaDbRecoveryModel</S>
                <S>Test-DbaMaxDop</S>
                <S>Remove-DbaBackup</S>
                <S>Get-DbaPermission</S>
                <S>Get-DbaLastBackup</S>
                <S>Connect-DbaInstance</S>
                <S>Get-DbaBackupHistory</S>
                <S>Read-DbaBackupHeader</S>
                <S>Test-DbaLastBackup</S>
                <S>Get-DbaMaxMemory</S>
                <S>Set-DbaMaxMemory</S>
                <S>Get-DbaDbSnapshot</S>
                <S>Remove-DbaDbSnapshot</S>
                <S>Get-DbaDbRoleMember</S>
                <S>Get-DbaServerRoleMember</S>
                <S>Resolve-DbaNetworkName</S>
                <S>Export-DbaAvailabilityGroup</S>
                <S>Write-DbaDataTable</S>
                <S>New-DbaDbSnapshot</S>
                <S>Restore-DbaDbSnapshot</S>
                <S>Get-DbaServerTrigger</S>
                <S>Get-DbaDbTrigger</S>
                <S>Get-DbaDbState</S>
                <S>Set-DbaDbState</S>
                <S>Get-DbaHelpIndex</S>
                <S>Get-DbaAgentAlert</S>
                <S>Get-DbaAgentOperator</S>
                <S>Get-DbaSpConfigure</S>
                <S>Rename-DbaLogin</S>
                <S>Find-DbaAgentJob</S>
                <S>Find-DbaDatabase</S>
                <S>Get-DbaXESession</S>
                <S>Test-DbaOptimizeForAdHoc</S>
                <S>Find-DbaStoredProcedure</S>
                <S>Measure-DbaBackupThroughput</S>
                <S>Get-DbaDatabase</S>
                <S>Find-DbaUserObject</S>
                <S>Get-DbaDependency</S>
                <S>Find-DbaCommand</S>
                <S>Backup-DbaDatabase</S>
                <S>New-DbaDirectory</S>
                <S>Get-DbaDbQueryStoreOption</S>
                <S>Set-DbaDbQueryStoreOption</S>
                <S>Restore-DbaDatabase</S>
                <S>Copy-DbaDbQueryStoreOption</S>
                <S>Get-DbaExecutionPlan</S>
                <S>Export-DbaExecutionPlan</S>
                <S>Set-DbaSpConfigure</S>
                <S>Test-DbaIdentityUsage</S>
                <S>Get-DbaDbAssembly</S>
                <S>Get-DbaAgentJob</S>
                <S>Get-DbaCustomError</S>
                <S>Get-DbaCredential</S>
                <S>Get-DbaBackupDevice</S>
                <S>Get-DbaAgentProxy</S>
                <S>Get-DbaDbEncryption</S>
                <S>Remove-DbaDatabase</S>
                <S>Get-DbaQueryExecutionTime</S>
                <S>Get-DbaTempdbUsage</S>
                <S>Find-DbaDbGrowthEvent</S>
                <S>Test-DbaLinkedServerConnection</S>
                <S>Get-DbaDbFile</S>
                <S>Read-DbaTransactionLog</S>
                <S>Get-DbaDbTable</S>
                <S>Invoke-DbaDbShrink</S>
                <S>Get-DbaEstimatedCompletionTime</S>
                <S>Get-DbaLinkedServer</S>
                <S>New-DbaAgentJob</S>
                <S>Get-DbaLogin</S>
                <S>New-DbaScriptingOption</S>
                <S>Save-DbaDiagnosticQueryScript</S>
                <S>Invoke-DbaDiagnosticQuery</S>
                <S>Export-DbaDiagnosticQuery</S>
                <S>Invoke-DbaWhoIsActive</S>
                <S>Set-DbaAgentJob</S>
                <S>Remove-DbaAgentJob</S>
                <S>New-DbaAgentJobStep</S>
                <S>Set-DbaAgentJobStep</S>
                <S>Remove-DbaAgentJobStep</S>
                <S>New-DbaAgentSchedule</S>
                <S>Set-DbaAgentSchedule</S>
                <S>Remove-DbaAgentSchedule</S>
                <S>Backup-DbaDbCertificate</S>
                <S>Get-DbaDbCertificate</S>
                <S>Get-DbaEndpoint</S>
                <S>Get-DbaDbMasterKey</S>
                <S>Get-DbaSchemaChangeHistory</S>
                <S>Get-DbaServerAudit</S>
                <S>Get-DbaServerAuditSpecification</S>
                <S>Get-DbaProductKey</S>
                <S>Get-DbatoolsLog</S>
                <S>Restore-DbaDbCertificate</S>
                <S>New-DbaDbCertificate</S>
                <S>New-DbaDbMasterKey</S>
                <S>New-DbaServiceMasterKey</S>
                <S>Remove-DbaDbCertificate</S>
                <S>Remove-DbaDbMasterKey</S>
                <S>New-DbaConnectionStringBuilder</S>
                <S>Get-DbaInstanceProperty</S>
                <S>Get-DbaInstanceUserOption</S>
                <S>New-DbaConnectionString</S>
                <S>Get-DbaAgentSchedule</S>
                <S>Read-DbaTraceFile</S>
                <S>Get-DbaServerInstallDate</S>
                <S>Backup-DbaDbMasterKey</S>
                <S>Get-DbaAgentJobHistory</S>
                <S>Get-DbaMaintenanceSolutionLog</S>
                <S>Invoke-DbaDbLogShipRecovery</S>
                <S>Find-DbaTrigger</S>
                <S>Find-DbaView</S>
                <S>Invoke-DbaDbUpgrade</S>
                <S>Get-DbaDbUser</S>
                <S>Get-DbaAgentLog</S>
                <S>Get-DbaDbMailLog</S>
                <S>Get-DbaDbMailHistory</S>
                <S>Get-DbaDbView</S>
                <S>Get-DbaDbUdf</S>
                <S>Get-DbaDbPartitionFunction</S>
                <S>Get-DbaDbPartitionScheme</S>
                <S>Get-DbaDefaultPath</S>
                <S>Get-DbaDbStoredProcedure</S>
                <S>Test-DbaDbCompression</S>
                <S>Mount-DbaDatabase</S>
                <S>Dismount-DbaDatabase</S>
                <S>Get-DbaAgReplica</S>
                <S>Get-DbaAgDatabase</S>
                <S>Get-DbaModule</S>
                <S>Sync-DbaLoginPermission</S>
                <S>New-DbaCredential</S>
                <S>Get-DbaFile</S>
                <S>Set-DbaDbCompression</S>
                <S>Get-DbaTraceFlag</S>
                <S>Invoke-DbaCycleErrorLog</S>
                <S>Get-DbaAvailableCollation</S>
                <S>Get-DbaUserPermission</S>
                <S>Get-DbaAgHadr</S>
                <S>Find-DbaSimilarTable</S>
                <S>Get-DbaTrace</S>
                <S>Get-DbaSuspectPage</S>
                <S>Get-DbaWaitStatistic</S>
                <S>Clear-DbaWaitStatistics</S>
                <S>Get-DbaTopResourceUsage</S>
                <S>New-DbaLogin</S>
                <S>Get-DbaAgListener</S>
                <S>Invoke-DbaDbClone</S>
                <S>Disable-DbaTraceFlag</S>
                <S>Enable-DbaTraceFlag</S>
                <S>Start-DbaAgentJob</S>
                <S>Stop-DbaAgentJob</S>
                <S>New-DbaAgentProxy</S>
                <S>Test-DbaDbLogShipStatus</S>
                <S>Get-DbaXESessionTarget</S>
                <S>New-DbaXESmartTargetResponse</S>
                <S>New-DbaXESmartTarget</S>
                <S>Get-DbaDbVirtualLogFile</S>
                <S>Get-DbaBackupInformation</S>
                <S>Start-DbaXESession</S>
                <S>Stop-DbaXESession</S>
                <S>Set-DbaDbRecoveryModel</S>
                <S>Get-DbaDbRecoveryModel</S>
                <S>Get-DbaWaitingTask</S>
                <S>Remove-DbaDbUser</S>
                <S>Get-DbaDump</S>
                <S>Invoke-DbaAdvancedRestore</S>
                <S>Format-DbaBackupInformation</S>
                <S>Get-DbaAgentJobStep</S>
                <S>Test-DbaBackupInformation</S>
                <S>Invoke-DbaBalanceDataFiles</S>
                <S>Select-DbaBackupInformation</S>
                <S>Publish-DbaDacPackage</S>
                <S>Copy-DbaDbTableData</S>
                <S>Invoke-DbaQuery</S>
                <S>Remove-DbaLogin</S>
                <S>Get-DbaAgentJobCategory</S>
                <S>New-DbaAgentJobCategory</S>
                <S>Remove-DbaAgentJobCategory</S>
                <S>Set-DbaAgentJobCategory</S>
                <S>Get-DbaDbRole</S>
                <S>Get-DbaServerRole</S>
                <S>Find-DbaBackup</S>
                <S>Remove-DbaXESession</S>
                <S>New-DbaXESession</S>
                <S>Get-DbaXEStore</S>
                <S>New-DbaXESmartTableWriter</S>
                <S>New-DbaXESmartReplay</S>
                <S>New-DbaXESmartEmail</S>
                <S>New-DbaXESmartQueryExec</S>
                <S>Start-DbaXESmartTarget</S>
                <S>Get-DbaDbOrphanUser</S>
                <S>Get-DbaOpenTransaction</S>
                <S>Get-DbaDbLogShipError</S>
                <S>Test-DbaBuild</S>
                <S>Get-DbaXESessionTemplate</S>
                <S>ConvertTo-DbaXESession</S>
                <S>Start-DbaTrace</S>
                <S>Stop-DbaTrace</S>
                <S>Remove-DbaTrace</S>
                <S>Set-DbaLogin</S>
                <S>Copy-DbaXESessionTemplate</S>
                <S>Get-DbaXEObject</S>
                <S>ConvertTo-DbaDataTable</S>
                <S>Find-DbaDisabledIndex</S>
                <S>Get-DbaXESmartTarget</S>
                <S>Remove-DbaXESmartTarget</S>
                <S>Stop-DbaXESmartTarget</S>
                <S>Get-DbaCmsRegServerGroup</S>
                <S>New-DbaDbUser</S>
                <S>Measure-DbaDiskSpaceRequirement</S>
                <S>New-DbaXESmartCsvWriter</S>
                <S>Invoke-DbaXeReplay</S>
                <S>Find-DbaInstance</S>
                <S>Test-DbaDiskSpeed</S>
                <S>Get-DbaDbExtentDiff</S>
                <S>Read-DbaAuditFile</S>
                <S>Get-DbaDbCompression</S>
                <S>Invoke-DbaDbDecryptObject</S>
                <S>Get-DbaDbForeignKey</S>
                <S>Get-DbaDbCheckConstraint</S>
                <S>Set-DbaAgentAlert</S>
                <S>Get-DbaWaitResource</S>
                <S>Get-DbaDbPageInfo</S>
                <S>Get-DbaConnection</S>
                <S>Test-DbaLoginPassword</S>
                <S>Get-DbaErrorLogConfig</S>
                <S>Set-DbaErrorLogConfig</S>
                <S>Get-DbaPlanCache</S>
                <S>Clear-DbaPlanCache</S>
                <S>ConvertTo-DbaTimeline</S>
                <S>Get-DbaDbMail</S>
                <S>Get-DbaDbMailAccount</S>
                <S>Get-DbaDbMailProfile</S>
                <S>Get-DbaDbMailConfig</S>
                <S>Get-DbaDbMailServer</S>
                <S>Get-DbaResourceGovernor</S>
                <S>Get-DbaRgResourcePool</S>
                <S>Get-DbaRgWorkloadGroup</S>
                <S>Get-DbaRgClassifierFunction</S>
                <S>Export-DbaInstance</S>
                <S>Invoke-DbatoolsRenameHelper</S>
                <S>Measure-DbatoolsImport</S>
                <S>Get-DbaDeprecatedFeature</S>
                <S>Test-DbaDeprecatedFeature</S>
                <S>Get-DbaDbFeatureUsage</S>
                <S>Stop-DbaEndpoint</S>
                <S>Start-DbaEndpoint</S>
                <S>Set-DbaDbMirror</S>
                <S>Repair-DbaDbMirror</S>
                <S>Remove-DbaEndpoint</S>
                <S>Remove-DbaDbMirrorMonitor</S>
                <S>Remove-DbaDbMirror</S>
                <S>New-DbaEndpoint</S>
                <S>Invoke-DbaDbMirroring</S>
                <S>Invoke-DbaDbMirrorFailover</S>
                <S>Get-DbaDbMirrorMonitor</S>
                <S>Get-DbaDbMirror</S>
                <S>Add-DbaDbMirrorMonitor</S>
                <S>Test-DbaEndpoint</S>
                <S>Get-DbaDbSharePoint</S>
                <S>Get-DbaDbMemoryUsage</S>
                <S>Clear-DbaLatchStatistics</S>
                <S>Get-DbaCpuRingBuffer</S>
                <S>Get-DbaIoLatency</S>
                <S>Get-DbaLatchStatistic</S>
                <S>Get-DbaSpinLockStatistic</S>
                <S>Add-DbaAgDatabase</S>
                <S>Add-DbaAgListener</S>
                <S>Add-DbaAgReplica</S>
                <S>Grant-DbaAgPermission</S>
                <S>Invoke-DbaAgFailover</S>
                <S>Join-DbaAvailabilityGroup</S>
                <S>New-DbaAvailabilityGroup</S>
                <S>Remove-DbaAgDatabase</S>
                <S>Remove-DbaAgListener</S>
                <S>Remove-DbaAvailabilityGroup</S>
                <S>Revoke-DbaAgPermission</S>
                <S>Get-DbaDbCompatibility</S>
                <S>Set-DbaDbCompatibility</S>
                <S>Invoke-DbatoolsFormatter</S>
                <S>Remove-DbaAgReplica</S>
                <S>Resume-DbaAgDbDataMovement</S>
                <S>Set-DbaAgListener</S>
                <S>Set-DbaAgReplica</S>
                <S>Set-DbaAvailabilityGroup</S>
                <S>Set-DbaEndpoint</S>
                <S>Suspend-DbaAgDbDataMovement</S>
                <S>Sync-DbaAvailabilityGroup</S>
                <S>Get-DbaMemoryCondition</S>
                <S>Remove-DbaDbBackupRestoreHistory</S>
                <S>New-DbaDatabase</S>
                <S>New-DbaDacOption</S>
                <S>Get-DbaDbccHelp</S>
                <S>Get-DbaDbccMemoryStatus</S>
                <S>Get-DbaDbccProcCache</S>
                <S>Get-DbaDbccUserOption</S>
                <S>Get-DbaAgentServer</S>
                <S>Set-DbaAgentServer</S>
                <S>Invoke-DbaDbccFreeCache</S>
                <S>Export-DbatoolsConfig</S>
                <S>Import-DbatoolsConfig</S>
                <S>Reset-DbatoolsConfig</S>
                <S>Unregister-DbatoolsConfig</S>
                <S>Join-DbaPath</S>
                <S>Resolve-DbaPath</S>
                <S>Invoke-DbaDbDataMasking</S>
                <S>New-DbaDbMaskingConfig</S>
                <S>Get-DbaDbccSessionBuffer</S>
                <S>Get-DbaDbccStatistic</S>
                <S>Get-DbaDbDbccOpenTran</S>
                <S>Invoke-DbaDbccDropCleanBuffer</S>
                <S>Invoke-DbaDbDbccCheckConstraint</S>
                <S>Invoke-DbaDbDbccCleanTable</S>
                <S>Invoke-DbaDbDbccUpdateUsage</S>
                <S>Export-DbaUser</S>
                <S>Get-DbaSsisExecutionHistory</S>
                <S>Get-DbaRepDistributor</S>
                <S>Get-DbaCmsRegServerStore</S>
                <S>Copy-DbaPolicyManagement</S>
                <S>Copy-DbaDataCollector</S>
                <S>Get-DbaCmsRegServer</S>
                <S>Copy-DbaSsisCatalog</S>
                <S>New-DbaSsisCatalog</S>
                <S>Get-DbaSsisEnvironmentVariable</S>
                <S>Get-DbaPbmCategory</S>
                <S>Get-DbaPbmCategorySubscription</S>
                <S>Get-DbaPbmCondition</S>
                <S>Get-DbaPbmObjectSet</S>
                <S>Get-DbaPbmPolicy</S>
                <S>Get-DbaPbmStore</S>
                <S>Add-DbaCmsRegServer</S>
                <S>Add-DbaCmsRegServerGroup</S>
                <S>Export-DbaCmsRegServer</S>
                <S>Import-DbaCmsRegServer</S>
                <S>Move-DbaCmsRegServer</S>
                <S>Move-DbaCmsRegServerGroup</S>
                <S>Remove-DbaCmsRegServer</S>
                <S>Remove-DbaCmsRegServerGroup</S>
                <S>Get-DbaRepPublication</S>
                <S>Test-DbaRepLatency</S>
                <S>Export-DbaRepServerSetting</S>
                <S>Get-DbaRepServer</S>
                <S>Install-DbaSqlWatch</S>
                <S>Uninstall-DbaSqlWatch</S>
                <S>Get-DbaRegistryRoot</S>
                <S>Install-DbaMaintenanceSolution</S>
                <S>New-DbatoolsSupportPackage</S>
                <S>Export-DbaScript</S>
                <S>Get-DbaAgentJobOutputFile</S>
                <S>Set-DbaAgentJobOutputFile</S>
                <S>Get-DbaBuildReference</S>
                <S>New-DbaDacProfile</S>
                <S>Import-DbaXESessionTemplate</S>
                <S>Export-DbaXESessionTemplate</S>
                <S>Import-DbaSpConfigure</S>
                <S>Export-DbaSpConfigure</S>
                <S>Update-Dbatools</S>
                <S>Install-DbaWhoIsActive</S>
                <S>Install-DbaFirstResponderKit</S>
                <S>Read-DbaXEFile</S>
                <S>Watch-DbaXESession</S>
                <S>Test-DbaMaxMemory</S>
                <S>Rename-DbaDatabase</S>
                <S>Update-DbaInstance</S>
                <S>Invoke-DbaPfRelog</S>
                <S>Get-DbaPfDataCollectorCounter</S>
                <S>Get-DbaPfDataCollectorCounterSample</S>
                <S>Get-DbaPfDataCollector</S>
                <S>Get-DbaPfDataCollectorSet</S>
                <S>Start-DbaPfDataCollectorSet</S>
                <S>Stop-DbaPfDataCollectorSet</S>
                <S>Export-DbaPfDataCollectorSetTemplate</S>
                <S>Get-DbaPfDataCollectorSetTemplate</S>
                <S>Import-DbaPfDataCollectorSetTemplate</S>
                <S>Remove-DbaPfDataCollectorSet</S>
                <S>Add-DbaPfDataCollectorCounter</S>
                <S>Remove-DbaPfDataCollectorCounter</S>
                <S>Get-DbaPfAvailableCounter</S>
                <S>Export-DbaXECsv</S>
                <S>Get-DbaOperatingSystem</S>
                <S>Get-DbaComputerSystem</S>
                <S>Set-DbaPrivilege</S>
                <S>Set-DbaTcpPort</S>
                <S>Set-DbaCmConnection</S>
                <S>Get-DbaUptime</S>
                <S>Get-DbaMemoryUsage</S>
                <S>Clear-DbaConnectionPool</S>
                <S>Get-DbaLocaleSetting</S>
                <S>Get-DbaFilestream</S>
                <S>Enable-DbaFilestream</S>
                <S>Disable-DbaFilestream</S>
                <S>Get-DbaCpuUsage</S>
                <S>Get-DbaPowerPlan</S>
                <S>Get-DbaWsfcAvailableDisk</S>
                <S>Get-DbaWsfcCluster</S>
                <S>Get-DbaWsfcDisk</S>
                <S>Get-DbaWsfcNetwork</S>
                <S>Get-DbaWsfcNetworkInterface</S>
                <S>Get-DbaWsfcNode</S>
                <S>Get-DbaWsfcResource</S>
                <S>Get-DbaWsfcResourceType</S>
                <S>Get-DbaWsfcRole</S>
                <S>Get-DbaWsfcSharedVolume</S>
                <S>Export-DbaCredential</S>
                <S>Export-DbaLinkedServer</S>
                <S>Get-DbaFeature</S>
                <S>Update-DbaServiceAccount</S>
                <S>Remove-DbaClientAlias</S>
                <S>Disable-DbaAgHadr</S>
                <S>Enable-DbaAgHadr</S>
                <S>Stop-DbaService</S>
                <S>Start-DbaService</S>
                <S>Restart-DbaService</S>
                <S>New-DbaClientAlias</S>
                <S>Get-DbaClientAlias</S>
                <S>Remove-DbaNetworkCertificate</S>
                <S>Enable-DbaForceNetworkEncryption</S>
                <S>Disable-DbaForceNetworkEncryption</S>
                <S>Get-DbaForceNetworkEncryption</S>
                <S>Remove-DbaComputerCertificate</S>
                <S>New-DbaComputerCertificate</S>
                <S>Get-DbaComputerCertificate</S>
                <S>Add-DbaComputerCertificate</S>
                <S>Get-DbaNetworkCertificate</S>
                <S>Set-DbaNetworkCertificate</S>
                <S>Invoke-DbaDbLogShipping</S>
                <S>New-DbaCmConnection</S>
                <S>Get-DbaCmConnection</S>
                <S>Remove-DbaCmConnection</S>
                <S>Test-DbaCmConnection</S>
                <S>Get-DbaCmObject</S>
                <S>Set-DbaStartupParameter</S>
                <S>Get-DbaNetworkActivity</S>
                <S>Get-DbaServerProtocol</S>
                <S>Watch-DbaUpdate</S>
                <S>Uninstall-DbaWatchUpdate</S>
                <S>Install-DbaWatchUpdate</S>
                <S>Get-DbaPrivilege</S>
                <S>Get-DbaMsdtc</S>
                <S>Get-DbaPageFileSetting</S>
                <S>Copy-DbaCredential</S>
                <S>Test-DbaConnection</S>
                <S>Reset-DbaAdmin</S>
                <S>Copy-DbaLinkedServer</S>
                <S>Get-DbaDiskSpace</S>
                <S>Test-DbaDiskAllocation</S>
                <S>Test-DbaPowerPlan</S>
                <S>Set-DbaPowerPlan</S>
                <S>Test-DbaDiskAlignment</S>
                <S>Get-DbaStartupParameter</S>
                <S>Get-DbaSpn</S>
                <S>Test-DbaSpn</S>
                <S>Set-DbaSpn</S>
                <S>Remove-DbaSpn</S>
                <S>Get-DbaService</S>
                <S>Get-DbaClientProtocol</S>
                <S>Get-DbaWindowsLog</S>
                <S>Show-DbaServerFileSystem</S>
                <S>Show-DbaDbList</S>
                <S>Test-DbaWindowsLogin</S>
                <S>Find-DbaLoginInGroup</S>
                <S>Import-DbaCsv</S>
                <S>Export-DbaDacPackage</S>
                <S>Get-DbatoolsConfig</S>
                <S>Get-DbatoolsConfigValue</S>
                <S>Register-DbatoolsConfig</S>
                <S>Get-DbaErrorLog</S>
                <S>Get-DbaManagementObject</S>
                <S>Test-DbaManagementObject</S>
              </LST>
            </Obj>
          </En>
          <En>
            <S N="Key">DscResource</S>
            <Obj N="Value" RefId="7">
              <TNRef RefId="1" />
              <LST />
            </Obj>
          </En>
          <En>
            <S N="Key">Workflow</S>
            <Obj N="Value" RefId="8">
              <TNRef RefId="1" />
              <LST />
            </Obj>
          </En>
          <En>
            <S N="Key">Cmdlet</S>
            <Obj N="Value" RefId="9">
              <TNRef RefId="1" />
              <LST>
                <S>Select-DbaObject</S>
                <S>Set-DbatoolsConfig</S>
              </LST>
            </Obj>
          </En>
        </DCT>
      </Obj>
      <Nil N="PowerShellGetFormatVersion" />
      <S N="ReleaseNotes">https://dbatools.io/changelog</S>
      <Obj N="Dependencies" RefId="10">
        <TNRef RefId="1" />
        <LST />
      </Obj>
      <S N="RepositorySourceLocation">https://www.powershellgallery.com/api/v2/</S>
      <S N="Repository">PSGallery</S>
      <S N="PackageManagementProvider">NuGet</S>
      <Obj N="AdditionalMetadata" RefId="11">
        <TN RefId="3">
          <T>System.Management.Automation.PSCustomObject</T>
          <T>System.Object</T>
        </TN>
        <MS>
          <S N="copyright">Copyright (c) 2018 by dbatools, licensed under MIT</S>
          <S N="description">The community module that enables SQL Server Pros to automate database development and server administration</S>
          <S N="requireLicenseAcceptance">True</S>
          <S N="releaseNotes">https://dbatools.io/changelog</S>
          <S N="isLatestVersion">True</S>
          <S N="isAbsoluteLatestVersion">True</S>
          <S N="versionDownloadCount">81</S>
          <S N="downloadCount">111929</S>
          <S N="packageSize">22073738</S>
          <S N="published">1/8/2019 7:09:12 PM +00:00</S>
          <S N="created">1/8/2019 7:09:12 PM +00:00</S>
          <S N="lastUpdated">1/9/2019 12:02:09 AM +00:00</S>
          <S N="tags">sqlserver migrations sql dba databases mac linux core PSModule PSCmdlet_Select-DbaObject PSCommand_Select-DbaObject PSCmdlet_Set-DbatoolsConfig PSCommand_Set-DbatoolsConfig PSIncludes_Cmdlet PSFunction_Start-DbaMigration PSCommand_Start-DbaMigration PSFunction_Copy-DbaDatabase PSCommand_Copy-DbaDatabase PSFunction_Copy-DbaLogin PSCommand_Copy-DbaLogin PSFunction_Copy-DbaAgentServer PSCommand_Copy-DbaAgentServer PSFunction_Copy-DbaSpConfigure PSCommand_Copy-DbaSpConfigure PSFunction_Copy-DbaDbMail PSCommand_Copy-DbaDbMail PSFunction_Copy-DbaDbAssembly PSCommand_Copy-DbaDbAssembly PSFunction_Copy-DbaAgentSchedule PSCommand_Copy-DbaAgentSchedule PSFunction_Copy-DbaAgentOperator PSCommand_Copy-DbaAgentOperator PSFunction_Copy-DbaAgentJob PSCommand_Copy-DbaAgentJob PSFunction_Copy-DbaCustomError PSCommand_Copy-DbaCustomError PSFunction_Copy-DbaServerAuditSpecification PSCommand_Copy-DbaServerAuditSpecification PSFunction_Copy-DbaEndpoint PSCommand_Copy-DbaEndpoint PSFunction_Copy-DbaServerAudit PSCommand_Copy-DbaServerAudit PSFunction_Copy-DbaServerRole PSCommand_Copy-DbaServerRole PSFunction_Copy-DbaResourceGovernor PSCommand_Copy-DbaResourceGovernor PSFunction_Copy-DbaXESession PSCommand_Copy-DbaXESession PSFunction_Copy-DbaBackupDevice PSCommand_Copy-DbaBackupDevice PSFunction_Copy-DbaServerTrigger PSCommand_Copy-DbaServerTrigger PSFunction_Copy-DbaCmsRegServer PSCommand_Copy-DbaCmsRegServer PSFunction_Copy-DbaSysDbUserObject PSCommand_Copy-DbaSysDbUserObject PSFunction_Copy-DbaAgentProxy PSCommand_Copy-DbaAgentProxy PSFunction_Copy-DbaAgentAlert PSCommand_Copy-DbaAgentAlert PSFunction_Get-DbaDetachedDatabaseInfo PSCommand_Get-DbaDetachedDatabaseInfo PSFunction_Restore-DbaBackupFromDirectory PSCommand_Restore-DbaBackupFromDirectory PSFunction_Copy-DbaAgentJobCategory PSCommand_Copy-DbaAgentJobCategory PSFunction_Test-DbaPath PSCommand_Test-DbaPath PSFunction_Export-DbaLogin PSCommand_Export-DbaLogin PSFunction_Watch-DbaDbLogin PSCommand_Watch-DbaDbLogin PSFunction_Expand-DbaDbLogFile PSCommand_Expand-DbaDbLogFile PSFunction_Test-DbaMigrationConstraint PSCommand_Test-DbaMigrationConstraint PSFunction_Test-DbaNetworkLatency PSCommand_Test-DbaNetworkLatency PSFunction_Find-DbaDuplicateIndex PSCommand_Find-DbaDuplicateIndex PSFunction_Remove-DbaDatabaseSafely PSCommand_Remove-DbaDatabaseSafely PSFunction_Set-DbaTempdbConfig PSCommand_Set-DbaTempdbConfig PSFunction_Test-DbaTempdbConfig PSCommand_Test-DbaTempdbConfig PSFunction_Repair-DbaDbOrphanUser PSCommand_Repair-DbaDbOrphanUser PSFunction_Remove-DbaDbOrphanUser PSCommand_Remove-DbaDbOrphanUser PSFunction_Find-DbaDbUnusedIndex PSCommand_Find-DbaDbUnusedIndex PSFunction_Get-DbaDbSpace PSCommand_Get-DbaDbSpace PSFunction_Test-DbaDbOwner PSCommand_Test-DbaDbOwner PSFunction_Set-DbaDbOwner PSCommand_Set-DbaDbOwner PSFunction_Test-DbaJobOwner PSCommand_Test-DbaJobOwner PSFunction_Set-DbaAgentJobOwner PSCommand_Set-DbaAgentJobOwner PSFunction_Test-DbaDbVirtualLogFile PSCommand_Test-DbaDbVirtualLogFile PSFunction_Get-DbaDbRestoreHistory PSCommand_Get-DbaDbRestoreHistory PSFunction_Get-DbaTcpPort PSCommand_Get-DbaTcpPort PSFunction_Test-DbaDbCompatibility PSCommand_Test-DbaDbCompatibility PSFunction_Test-DbaDbCollation PSCommand_Test-DbaDbCollation PSFunction_Test-DbaConnectionAuthScheme PSCommand_Test-DbaConnectionAuthScheme PSFunction_Test-DbaServerName PSCommand_Test-DbaServerName PSFunction_Repair-DbaServerName PSCommand_Repair-DbaServerName PSFunction_Stop-DbaProcess PSCommand_Stop-DbaProcess PSFunction_Find-DbaOrphanedFile PSCommand_Find-DbaOrphanedFile PSFunction_Get-DbaAvailabilityGroup PSCommand_Get-DbaAvailabilityGroup PSFunction_Get-DbaLastGoodCheckDb PSCommand_Get-DbaLastGoodCheckDb PSFunction_Get-DbaProcess PSCommand_Get-DbaProcess PSFunction_Get-DbaRunningJob PSCommand_Get-DbaRunningJob PSFunction_Set-DbaMaxDop PSCommand_Set-DbaMaxDop PSFunction_Test-DbaDbRecoveryModel PSCommand_Test-DbaDbRecoveryModel PSFunction_Test-DbaMaxDop PSCommand_Test-DbaMaxDop PSFunction_Remove-DbaBackup PSCommand_Remove-DbaBackup PSFunction_Get-DbaPermission PSCommand_Get-DbaPermission PSFunction_Get-DbaLastBackup PSCommand_Get-DbaLastBackup PSFunction_Connect-DbaInstance PSCommand_Connect-DbaInstance PSFunction_Get-DbaBackupHistory PSCommand_Get-DbaBackupHistory PSFunction_Read-DbaBackupHeader PSCommand_Read-DbaBackupHeader PSFunction_Test-DbaLastBackup PSCommand_Test-DbaLastBackup PSFunction_Get-DbaMaxMemory PSCommand_Get-DbaMaxMemory PSFunction_Set-DbaMaxMemory PSCommand_Set-DbaMaxMemory PSFunction_Get-DbaDbSnapshot PSCommand_Get-DbaDbSnapshot PSFunction_Remove-DbaDbSnapshot PSCommand_Remove-DbaDbSnapshot PSFunction_Get-DbaDbRoleMember PSCommand_Get-DbaDbRoleMember PSFunction_Get-DbaServerRoleMember PSCommand_Get-DbaServerRoleMember PSFunction_Resolve-DbaNetworkName PSCommand_Resolve-DbaNetworkName PSFunction_Export-DbaAvailabilityGroup PSCommand_Export-DbaAvailabilityGroup PSFunction_Write-DbaDataTable PSCommand_Write-DbaDataTable PSFunction_New-DbaDbSnapshot PSCommand_New-DbaDbSnapshot PSFunction_Restore-DbaDbSnapshot PSCommand_Restore-DbaDbSnapshot PSFunction_Get-DbaServerTrigger PSCommand_Get-DbaServerTrigger PSFunction_Get-DbaDbTrigger PSCommand_Get-DbaDbTrigger PSFunction_Get-DbaDbState PSCommand_Get-DbaDbState PSFunction_Set-DbaDbState PSCommand_Set-DbaDbState PSFunction_Get-DbaHelpIndex PSCommand_Get-DbaHelpIndex PSFunction_Get-DbaAgentAlert PSCommand_Get-DbaAgentAlert PSFunction_Get-DbaAgentOperator PSCommand_Get-DbaAgentOperator PSFunction_Get-DbaSpConfigure PSCommand_Get-DbaSpConfigure PSFunction_Rename-DbaLogin PSCommand_Rename-DbaLogin PSFunction_Find-DbaAgentJob PSCommand_Find-DbaAgentJob PSFunction_Find-DbaDatabase PSCommand_Find-DbaDatabase PSFunction_Get-DbaXESession PSCommand_Get-DbaXESession PSFunction_Test-DbaOptimizeForAdHoc PSCommand_Test-DbaOptimizeForAdHoc PSFunction_Find-DbaStoredProcedure PSCommand_Find-DbaStoredProcedure PSFunction_Measure-DbaBackupThroughput PSCommand_Measure-DbaBackupThroughput PSFunction_Get-DbaDatabase PSCommand_Get-DbaDatabase PSFunction_Find-DbaUserObject PSCommand_Find-DbaUserObject PSFunction_Get-DbaDependency PSCommand_Get-DbaDependency PSFunction_Find-DbaCommand PSCommand_Find-DbaCommand PSFunction_Backup-DbaDatabase PSCommand_Backup-DbaDatabase PSFunction_New-DbaDirectory PSCommand_New-DbaDirectory PSFunction_Get-DbaDbQueryStoreOption PSCommand_Get-DbaDbQueryStoreOption PSFunction_Set-DbaDbQueryStoreOption PSCommand_Set-DbaDbQueryStoreOption PSFunction_Restore-DbaDatabase PSCommand_Restore-DbaDatabase PSFunction_Copy-DbaDbQueryStoreOption PSCommand_Copy-DbaDbQueryStoreOption PSFunction_Get-DbaExecutionPlan PSCommand_Get-DbaExecutionPlan PSFunction_Export-DbaExecutionPlan PSCommand_Export-DbaExecutionPlan PSFunction_Set-DbaSpConfigure PSCommand_Set-DbaSpConfigure PSFunction_Test-DbaIdentityUsage PSCommand_Test-DbaIdentityUsage PSFunction_Get-DbaDbAssembly PSCommand_Get-DbaDbAssembly PSFunction_Get-DbaAgentJob PSCommand_Get-DbaAgentJob PSFunction_Get-DbaCustomError PSCommand_Get-DbaCustomError PSFunction_Get-DbaCredential PSCommand_Get-DbaCredential PSFunction_Get-DbaBackupDevice PSCommand_Get-DbaBackupDevice PSFunction_Get-DbaAgentProxy PSCommand_Get-DbaAgentProxy PSFunction_Get-DbaDbEncryption PSCommand_Get-DbaDbEncryption PSFunction_Remove-DbaDatabase PSCommand_Remove-DbaDatabase PSFunction_Get-DbaQueryExecutionTime PSCommand_Get-DbaQueryExecutionTime PSFunction_Get-DbaTempdbUsage PSCommand_Get-DbaTempdbUsage PSFunction_Find-DbaDbGrowthEvent PSCommand_Find-DbaDbGrowthEvent PSFunction_Test-DbaLinkedServerConnection PSCommand_Test-DbaLinkedServerConnection PSFunction_Get-DbaDbFile PSCommand_Get-DbaDbFile PSFunction_Read-DbaTransactionLog PSCommand_Read-DbaTransactionLog PSFunction_Get-DbaDbTable PSCommand_Get-DbaDbTable PSFunction_Invoke-DbaDbShrink PSCommand_Invoke-DbaDbShrink PSFunction_Get-DbaEstimatedCompletionTime PSCommand_Get-DbaEstimatedCompletionTime PSFunction_Get-DbaLinkedServer PSCommand_Get-DbaLinkedServer PSFunction_New-DbaAgentJob PSCommand_New-DbaAgentJob PSFunction_Get-DbaLogin PSCommand_Get-DbaLogin PSFunction_New-DbaScriptingOption PSCommand_New-DbaScriptingOption PSFunction_Save-DbaDiagnosticQueryScript PSCommand_Save-DbaDiagnosticQueryScript PSFunction_Invoke-DbaDiagnosticQuery PSCommand_Invoke-DbaDiagnosticQuery PSFunction_Export-DbaDiagnosticQuery PSCommand_Export-DbaDiagnosticQuery PSFunction_Invoke-DbaWhoIsActive PSCommand_Invoke-DbaWhoIsActive PSFunction_Set-DbaAgentJob PSCommand_Set-DbaAgentJob PSFunction_Remove-DbaAgentJob PSCommand_Remove-DbaAgentJob PSFunction_New-DbaAgentJobStep PSCommand_New-DbaAgentJobStep PSFunction_Set-DbaAgentJobStep PSCommand_Set-DbaAgentJobStep PSFunction_Remove-DbaAgentJobStep PSCommand_Remove-DbaAgentJobStep PSFunction_New-DbaAgentSchedule PSCommand_New-DbaAgentSchedule PSFunction_Set-DbaAgentSchedule PSCommand_Set-DbaAgentSchedule PSFunction_Remove-DbaAgentSchedule PSCommand_Remove-DbaAgentSchedule PSFunction_Backup-DbaDbCertificate PSCommand_Backup-DbaDbCertificate PSFunction_Get-DbaDbCertificate PSCommand_Get-DbaDbCertificate PSFunction_Get-DbaEndpoint PSCommand_Get-DbaEndpoint PSFunction_Get-DbaDbMasterKey PSCommand_Get-DbaDbMasterKey PSFunction_Get-DbaSchemaChangeHistory PSCommand_Get-DbaSchemaChangeHistory PSFunction_Get-DbaServerAudit PSCommand_Get-DbaServerAudit PSFunction_Get-DbaServerAuditSpecification PSCommand_Get-DbaServerAuditSpecification PSFunction_Get-DbaProductKey PSCommand_Get-DbaProductKey PSFunction_Get-DbatoolsLog PSCommand_Get-DbatoolsLog PSFunction_Restore-DbaDbCertificate PSCommand_Restore-DbaDbCertificate PSFunction_New-DbaDbCertificate PSCommand_New-DbaDbCertificate PSFunction_New-DbaDbMasterKey PSCommand_New-DbaDbMasterKey PSFunction_New-DbaServiceMasterKey PSCommand_New-DbaServiceMasterKey PSFunction_Remove-DbaDbCertificate PSCommand_Remove-DbaDbCertificate PSFunction_Remove-DbaDbMasterKey PSCommand_Remove-DbaDbMasterKey PSFunction_New-DbaConnectionStringBuilder PSCommand_New-DbaConnectionStringBuilder PSFunction_Get-DbaInstanceProperty PSCommand_Get-DbaInstanceProperty PSFunction_Get-DbaInstanceUserOption PSCommand_Get-DbaInstanceUserOption PSFunction_New-DbaConnectionString PSCommand_New-DbaConnectionString PSFunction_Get-DbaAgentSchedule PSCommand_Get-DbaAgentSchedule PSFunction_Read-DbaTraceFile PSCommand_Read-DbaTraceFile PSFunction_Get-DbaServerInstallDate PSCommand_Get-DbaServerInstallDate PSFunction_Backup-DbaDbMasterKey PSCommand_Backup-DbaDbMasterKey PSFunction_Get-DbaAgentJobHistory PSCommand_Get-DbaAgentJobHistory PSFunction_Get-DbaMaintenanceSolutionLog PSCommand_Get-DbaMaintenanceSolutionLog PSFunction_Invoke-DbaDbLogShipRecovery PSCommand_Invoke-DbaDbLogShipRecovery PSFunction_Find-DbaTrigger PSCommand_Find-DbaTrigger PSFunction_Find-DbaView PSCommand_Find-DbaView PSFunction_Invoke-DbaDbUpgrade PSCommand_Invoke-DbaDbUpgrade PSFunction_Get-DbaDbUser PSCommand_Get-DbaDbUser PSFunction_Get-DbaAgentLog PSCommand_Get-DbaAgentLog PSFunction_Get-DbaDbMailLog PSCommand_Get-DbaDbMailLog PSFunction_Get-DbaDbMailHistory PSCommand_Get-DbaDbMailHistory PSFunction_Get-DbaDbView PSCommand_Get-DbaDbView PSFunction_Get-DbaDbUdf PSCommand_Get-DbaDbUdf PSFunction_Get-DbaDbPartitionFunction PSCommand_Get-DbaDbPartitionFunction PSFunction_Get-DbaDbPartitionScheme PSCommand_Get-DbaDbPartitionScheme PSFunction_Get-DbaDefaultPath PSCommand_Get-DbaDefaultPath PSFunction_Get-DbaDbStoredProcedure PSCommand_Get-DbaDbStoredProcedure PSFunction_Test-DbaDbCompression PSCommand_Test-DbaDbCompression PSFunction_Mount-DbaDatabase PSCommand_Mount-DbaDatabase PSFunction_Dismount-DbaDatabase PSCommand_Dismount-DbaDatabase PSFunction_Get-DbaAgReplica PSCommand_Get-DbaAgReplica PSFunction_Get-DbaAgDatabase PSCommand_Get-DbaAgDatabase PSFunction_Get-DbaModule PSCommand_Get-DbaModule PSFunction_Sync-DbaLoginPermission PSCommand_Sync-DbaLoginPermission PSFunction_New-DbaCredential PSCommand_New-DbaCredential PSFunction_Get-DbaFile PSCommand_Get-DbaFile PSFunction_Set-DbaDbCompression PSCommand_Set-DbaDbCompression PSFunction_Get-DbaTraceFlag PSCommand_Get-DbaTraceFlag PSFunction_Invoke-DbaCycleErrorLog PSCommand_Invoke-DbaCycleErrorLog PSFunction_Get-DbaAvailableCollation PSCommand_Get-DbaAvailableCollation PSFunction_Get-DbaUserPermission PSCommand_Get-DbaUserPermission PSFunction_Get-DbaAgHadr PSCommand_Get-DbaAgHadr PSFunction_Find-DbaSimilarTable PSCommand_Find-DbaSimilarTable PSFunction_Get-DbaTrace PSCommand_Get-DbaTrace PSFunction_Get-DbaSuspectPage PSCommand_Get-DbaSuspectPage PSFunction_Get-DbaWaitStatistic PSCommand_Get-DbaWaitStatistic PSFunction_Clear-DbaWaitStatistics PSCommand_Clear-DbaWaitStatistics PSFunction_Get-DbaTopResourceUsage PSCommand_Get-DbaTopResourceUsage PSFunction_New-DbaLogin PSCommand_New-DbaLogin PSFunction_Get-DbaAgListener PSCommand_Get-DbaAgListener PSFunction_Invoke-DbaDbClone PSCommand_Invoke-DbaDbClone PSFunction_Disable-DbaTraceFlag PSCommand_Disable-DbaTraceFlag PSFunction_Enable-DbaTraceFlag PSCommand_Enable-DbaTraceFlag PSFunction_Start-DbaAgentJob PSCommand_Start-DbaAgentJob PSFunction_Stop-DbaAgentJob PSCommand_Stop-DbaAgentJob PSFunction_New-DbaAgentProxy PSCommand_New-DbaAgentProxy PSFunction_Test-DbaDbLogShipStatus PSCommand_Test-DbaDbLogShipStatus PSFunction_Get-DbaXESessionTarget PSCommand_Get-DbaXESessionTarget PSFunction_New-DbaXESmartTargetResponse PSCommand_New-DbaXESmartTargetResponse PSFunction_New-DbaXESmartTarget PSCommand_New-DbaXESmartTarget PSFunction_Get-DbaDbVirtualLogFile PSCommand_Get-DbaDbVirtualLogFile PSFunction_Get-DbaBackupInformation PSCommand_Get-DbaBackupInformation PSFunction_Start-DbaXESession PSCommand_Start-DbaXESession PSFunction_Stop-DbaXESession PSCommand_Stop-DbaXESession PSFunction_Set-DbaDbRecoveryModel PSCommand_Set-DbaDbRecoveryModel PSFunction_Get-DbaDbRecoveryModel PSCommand_Get-DbaDbRecoveryModel PSFunction_Get-DbaWaitingTask PSCommand_Get-DbaWaitingTask PSFunction_Remove-DbaDbUser PSCommand_Remove-DbaDbUser PSFunction_Get-DbaDump PSCommand_Get-DbaDump PSFunction_Invoke-DbaAdvancedRestore PSCommand_Invoke-DbaAdvancedRestore PSFunction_Format-DbaBackupInformation PSCommand_Format-DbaBackupInformation PSFunction_Get-DbaAgentJobStep PSCommand_Get-DbaAgentJobStep PSFunction_Test-DbaBackupInformation PSCommand_Test-DbaBackupInformation PSFunction_Invoke-DbaBalanceDataFiles PSCommand_Invoke-DbaBalanceDataFiles PSFunction_Select-DbaBackupInformation PSCommand_Select-DbaBackupInformation PSFunction_Publish-DbaDacPackage PSCommand_Publish-DbaDacPackage PSFunction_Copy-DbaDbTableData PSCommand_Copy-DbaDbTableData PSFunction_Invoke-DbaQuery PSCommand_Invoke-DbaQuery PSFunction_Remove-DbaLogin PSCommand_Remove-DbaLogin PSFunction_Get-DbaAgentJobCategory PSCommand_Get-DbaAgentJobCategory PSFunction_New-DbaAgentJobCategory PSCommand_New-DbaAgentJobCategory PSFunction_Remove-DbaAgentJobCategory PSCommand_Remove-DbaAgentJobCategory PSFunction_Set-DbaAgentJobCategory PSCommand_Set-DbaAgentJobCategory PSFunction_Get-DbaDbRole PSCommand_Get-DbaDbRole PSFunction_Get-DbaServerRole PSCommand_Get-DbaServerRole PSFunction_Find-DbaBackup PSCommand_Find-DbaBackup PSFunction_Remove-DbaXESession PSCommand_Remove-DbaXESession PSFunction_New-DbaXESession PSCommand_New-DbaXESession PSFunction_Get-DbaXEStore PSCommand_Get-DbaXEStore PSFunction_New-DbaXESmartTableWriter PSCommand_New-DbaXESmartTableWriter PSFunction_New-DbaXESmartReplay PSCommand_New-DbaXESmartReplay PSFunction_New-DbaXESmartEmail PSCommand_New-DbaXESmartEmail PSFunction_New-DbaXESmartQueryExec PSCommand_New-DbaXESmartQueryExec PSFunction_Start-DbaXESmartTarget PSCommand_Start-DbaXESmartTarget PSFunction_Get-DbaDbOrphanUser PSCommand_Get-DbaDbOrphanUser PSFunction_Get-DbaOpenTransaction PSCommand_Get-DbaOpenTransaction PSFunction_Get-DbaDbLogShipError PSCommand_Get-DbaDbLogShipError PSFunction_Test-DbaBuild PSCommand_Test-DbaBuild PSFunction_Get-DbaXESessionTemplate PSCommand_Get-DbaXESessionTemplate PSFunction_ConvertTo-DbaXESession PSCommand_ConvertTo-DbaXESession PSFunction_Start-DbaTrace PSCommand_Start-DbaTrace PSFunction_Stop-DbaTrace PSCommand_Stop-DbaTrace PSFunction_Remove-DbaTrace PSCommand_Remove-DbaTrace PSFunction_Set-DbaLogin PSCommand_Set-DbaLogin PSFunction_Copy-DbaXESessionTemplate PSCommand_Copy-DbaXESessionTemplate PSFunction_Get-DbaXEObject PSCommand_Get-DbaXEObject PSFunction_ConvertTo-DbaDataTable PSCommand_ConvertTo-DbaDataTable PSFunction_Find-DbaDisabledIndex PSCommand_Find-DbaDisabledIndex PSFunction_Get-DbaXESmartTarget PSCommand_Get-DbaXESmartTarget PSFunction_Remove-DbaXESmartTarget PSCommand_Remove-DbaXESmartTarget PSFunction_Stop-DbaXESmartTarget PSCommand_Stop-DbaXESmartTarget PSFunction_Get-DbaCmsRegServerGroup PSCommand_Get-DbaCmsRegServerGroup PSFunction_New-DbaDbUser PSCommand_New-DbaDbUser PSFunction_Measure-DbaDiskSpaceRequirement PSCommand_Measure-DbaDiskSpaceRequirement PSFunction_New-DbaXESmartCsvWriter PSCommand_New-DbaXESmartCsvWriter PSFunction_Invoke-DbaXeReplay PSCommand_Invoke-DbaXeReplay PSFunction_Find-DbaInstance PSCommand_Find-DbaInstance PSFunction_Test-DbaDiskSpeed PSCommand_Test-DbaDiskSpeed PSFunction_Get-DbaDbExtentDiff PSCommand_Get-DbaDbExtentDiff PSFunction_Read-DbaAuditFile PSCommand_Read-DbaAuditFile PSFunction_Get-DbaDbCompression PSCommand_Get-DbaDbCompression PSFunction_Invoke-DbaDbDecryptObject PSCommand_Invoke-DbaDbDecryptObject PSFunction_Get-DbaDbForeignKey PSCommand_Get-DbaDbForeignKey PSFunction_Get-DbaDbCheckConstraint PSCommand_Get-DbaDbCheckConstraint PSFunction_Set-DbaAgentAlert PSCommand_Set-DbaAgentAlert PSFunction_Get-DbaWaitResource PSCommand_Get-DbaWaitResource PSFunction_Get-DbaDbPageInfo PSCommand_Get-DbaDbPageInfo PSFunction_Get-DbaConnection PSCommand_Get-DbaConnection PSFunction_Test-DbaLoginPassword PSCommand_Test-DbaLoginPassword PSFunction_Get-DbaErrorLogConfig PSCommand_Get-DbaErrorLogConfig PSFunction_Set-DbaErrorLogConfig PSCommand_Set-DbaErrorLogConfig PSFunction_Get-DbaPlanCache PSCommand_Get-DbaPlanCache PSFunction_Clear-DbaPlanCache PSCommand_Clear-DbaPlanCache PSFunction_ConvertTo-DbaTimeline PSCommand_ConvertTo-DbaTimeline PSFunction_Get-DbaDbMail PSCommand_Get-DbaDbMail PSFunction_Get-DbaDbMailAccount PSCommand_Get-DbaDbMailAccount PSFunction_Get-DbaDbMailProfile PSCommand_Get-DbaDbMailProfile PSFunction_Get-DbaDbMailConfig PSCommand_Get-DbaDbMailConfig PSFunction_Get-DbaDbMailServer PSCommand_Get-DbaDbMailServer PSFunction_Get-DbaResourceGovernor PSCommand_Get-DbaResourceGovernor PSFunction_Get-DbaRgResourcePool PSCommand_Get-DbaRgResourcePool PSFunction_Get-DbaRgWorkloadGroup PSCommand_Get-DbaRgWorkloadGroup PSFunction_Get-DbaRgClassifierFunction PSCommand_Get-DbaRgClassifierFunction PSFunction_Export-DbaInstance PSCommand_Export-DbaInstance PSFunction_Invoke-DbatoolsRenameHelper PSCommand_Invoke-DbatoolsRenameHelper PSFunction_Measure-DbatoolsImport PSCommand_Measure-DbatoolsImport PSFunction_Get-DbaDeprecatedFeature PSCommand_Get-DbaDeprecatedFeature PSFunction_Test-DbaDeprecatedFeature PSCommand_Test-DbaDeprecatedFeature PSFunction_Get-DbaDbFeatureUsage PSCommand_Get-DbaDbFeatureUsage PSFunction_Stop-DbaEndpoint PSCommand_Stop-DbaEndpoint PSFunction_Start-DbaEndpoint PSCommand_Start-DbaEndpoint PSFunction_Set-DbaDbMirror PSCommand_Set-DbaDbMirror PSFunction_Repair-DbaDbMirror PSCommand_Repair-DbaDbMirror PSFunction_Remove-DbaEndpoint PSCommand_Remove-DbaEndpoint PSFunction_Remove-DbaDbMirrorMonitor PSCommand_Remove-DbaDbMirrorMonitor PSFunction_Remove-DbaDbMirror PSCommand_Remove-DbaDbMirror PSFunction_New-DbaEndpoint PSCommand_New-DbaEndpoint PSFunction_Invoke-DbaDbMirroring PSCommand_Invoke-DbaDbMirroring PSFunction_Invoke-DbaDbMirrorFailover PSCommand_Invoke-DbaDbMirrorFailover PSFunction_Get-DbaDbMirrorMonitor PSCommand_Get-DbaDbMirrorMonitor PSFunction_Get-DbaDbMirror PSCommand_Get-DbaDbMirror PSFunction_Add-DbaDbMirrorMonitor PSCommand_Add-DbaDbMirrorMonitor PSFunction_Test-DbaEndpoint PSCommand_Test-DbaEndpoint PSFunction_Get-DbaDbSharePoint PSCommand_Get-DbaDbSharePoint PSFunction_Get-DbaDbMemoryUsage PSCommand_Get-DbaDbMemoryUsage PSFunction_Clear-DbaLatchStatistics PSCommand_Clear-DbaLatchStatistics PSFunction_Get-DbaCpuRingBuffer PSCommand_Get-DbaCpuRingBuffer PSFunction_Get-DbaIoLatency PSCommand_Get-DbaIoLatency PSFunction_Get-DbaLatchStatistic PSCommand_Get-DbaLatchStatistic PSFunction_Get-DbaSpinLockStatistic PSCommand_Get-DbaSpinLockStatistic PSFunction_Add-DbaAgDatabase PSCommand_Add-DbaAgDatabase PSFunction_Add-DbaAgListener PSCommand_Add-DbaAgListener PSFunction_Add-DbaAgReplica PSCommand_Add-DbaAgReplica PSFunction_Grant-DbaAgPermission PSCommand_Grant-DbaAgPermission PSFunction_Invoke-DbaAgFailover PSCommand_Invoke-DbaAgFailover PSFunction_Join-DbaAvailabilityGroup PSCommand_Join-DbaAvailabilityGroup PSFunction_New-DbaAvailabilityGroup PSCommand_New-DbaAvailabilityGroup PSFunction_Remove-DbaAgDatabase PSCommand_Remove-DbaAgDatabase PSFunction_Remove-DbaAgListener PSCommand_Remove-DbaAgListener PSFunction_Remove-DbaAvailabilityGroup PSCommand_Remove-DbaAvailabilityGroup PSFunction_Revoke-DbaAgPermission PSCommand_Revoke-DbaAgPermission PSFunction_Get-DbaDbCompatibility PSCommand_Get-DbaDbCompatibility PSFunction_Set-DbaDbCompatibility PSCommand_Set-DbaDbCompatibility PSFunction_Invoke-DbatoolsFormatter PSCommand_Invoke-DbatoolsFormatter PSFunction_Remove-DbaAgReplica PSCommand_Remove-DbaAgReplica PSFunction_Resume-DbaAgDbDataMovement PSCommand_Resume-DbaAgDbDataMovement PSFunction_Set-DbaAgListener PSCommand_Set-DbaAgListener PSFunction_Set-DbaAgReplica PSCommand_Set-DbaAgReplica PSFunction_Set-DbaAvailabilityGroup PSCommand_Set-DbaAvailabilityGroup PSFunction_Set-DbaEndpoint PSCommand_Set-DbaEndpoint PSFunction_Suspend-DbaAgDbDataMovement PSCommand_Suspend-DbaAgDbDataMovement PSFunction_Sync-DbaAvailabilityGroup PSCommand_Sync-DbaAvailabilityGroup PSFunction_Get-DbaMemoryCondition PSCommand_Get-DbaMemoryCondition PSFunction_Remove-DbaDbBackupRestoreHistory PSCommand_Remove-DbaDbBackupRestoreHistory PSFunction_New-DbaDatabase PSCommand_New-DbaDatabase PSFunction_New-DbaDacOption PSCommand_New-DbaDacOption PSFunction_Get-DbaDbccHelp PSCommand_Get-DbaDbccHelp PSFunction_Get-DbaDbccMemoryStatus PSCommand_Get-DbaDbccMemoryStatus PSFunction_Get-DbaDbccProcCache PSCommand_Get-DbaDbccProcCache PSFunction_Get-DbaDbccUserOption PSCommand_Get-DbaDbccUserOption PSFunction_Get-DbaAgentServer PSCommand_Get-DbaAgentServer PSFunction_Set-DbaAgentServer PSCommand_Set-DbaAgentServer PSFunction_Invoke-DbaDbccFreeCache PSCommand_Invoke-DbaDbccFreeCache PSFunction_Export-DbatoolsConfig PSCommand_Export-DbatoolsConfig PSFunction_Import-DbatoolsConfig PSCommand_Import-DbatoolsConfig PSFunction_Reset-DbatoolsConfig PSCommand_Reset-DbatoolsConfig PSFunction_Unregister-DbatoolsConfig PSCommand_Unregister-DbatoolsConfig PSFunction_Join-DbaPath PSCommand_Join-DbaPath PSFunction_Resolve-DbaPath PSCommand_Resolve-DbaPath PSFunction_Invoke-DbaDbDataMasking PSCommand_Invoke-DbaDbDataMasking PSFunction_New-DbaDbMaskingConfig PSCommand_New-DbaDbMaskingConfig PSFunction_Get-DbaDbccSessionBuffer PSCommand_Get-DbaDbccSessionBuffer PSFunction_Get-DbaDbccStatistic PSCommand_Get-DbaDbccStatistic PSFunction_Get-DbaDbDbccOpenTran PSCommand_Get-DbaDbDbccOpenTran PSFunction_Invoke-DbaDbccDropCleanBuffer PSCommand_Invoke-DbaDbccDropCleanBuffer PSFunction_Invoke-DbaDbDbccCheckConstraint PSCommand_Invoke-DbaDbDbccCheckConstraint PSFunction_Invoke-DbaDbDbccCleanTable PSCommand_Invoke-DbaDbDbccCleanTable PSFunction_Invoke-DbaDbDbccUpdateUsage PSCommand_Invoke-DbaDbDbccUpdateUsage PSFunction_Export-DbaUser PSCommand_Export-DbaUser PSFunction_Get-DbaSsisExecutionHistory PSCommand_Get-DbaSsisExecutionHistory PSFunction_Get-DbaRepDistributor PSCommand_Get-DbaRepDistributor PSFunction_Get-DbaCmsRegServerStore PSCommand_Get-DbaCmsRegServerStore PSFunction_Copy-DbaPolicyManagement PSCommand_Copy-DbaPolicyManagement PSFunction_Copy-DbaDataCollector PSCommand_Copy-DbaDataCollector PSFunction_Get-DbaCmsRegServer PSCommand_Get-DbaCmsRegServer PSFunction_Copy-DbaSsisCatalog PSCommand_Copy-DbaSsisCatalog PSFunction_New-DbaSsisCatalog PSCommand_New-DbaSsisCatalog PSFunction_Get-DbaSsisEnvironmentVariable PSCommand_Get-DbaSsisEnvironmentVariable PSFunction_Get-DbaPbmCategory PSCommand_Get-DbaPbmCategory PSFunction_Get-DbaPbmCategorySubscription PSCommand_Get-DbaPbmCategorySubscription PSFunction_Get-DbaPbmCondition PSCommand_Get-DbaPbmCondition PSFunction_Get-DbaPbmObjectSet PSCommand_Get-DbaPbmObjectSet PSFunction_Get-DbaPbmPolicy PSCommand_Get-DbaPbmPolicy PSFunction_Get-DbaPbmStore PSCommand_Get-DbaPbmStore PSFunction_Add-DbaCmsRegServer PSCommand_Add-DbaCmsRegServer PSFunction_Add-DbaCmsRegServerGroup PSCommand_Add-DbaCmsRegServerGroup PSFunction_Export-DbaCmsRegServer PSCommand_Export-DbaCmsRegServer PSFunction_Import-DbaCmsRegServer PSCommand_Import-DbaCmsRegServer PSFunction_Move-DbaCmsRegServer PSCommand_Move-DbaCmsRegServer PSFunction_Move-DbaCmsRegServerGroup PSCommand_Move-DbaCmsRegServerGroup PSFunction_Remove-DbaCmsRegServer PSCommand_Remove-DbaCmsRegServer PSFunction_Remove-DbaCmsRegServerGroup PSCommand_Remove-DbaCmsRegServerGroup PSFunction_Get-DbaRepPublication PSCommand_Get-DbaRepPublication PSFunction_Test-DbaRepLatency PSCommand_Test-DbaRepLatency PSFunction_Export-DbaRepServerSetting PSCommand_Export-DbaRepServerSetting PSFunction_Get-DbaRepServer PSCommand_Get-DbaRepServer PSFunction_Install-DbaSqlWatch PSCommand_Install-DbaSqlWatch PSFunction_Uninstall-DbaSqlWatch PSCommand_Uninstall-DbaSqlWatch PSFunction_Get-DbaRegistryRoot PSCommand_Get-DbaRegistryRoot PSFunction_Install-DbaMaintenanceSolution PSCommand_Install-DbaMaintenanceSolution PSFunction_New-DbatoolsSupportPackage PSCommand_New-DbatoolsSupportPackage PSFunction_Export-DbaScript PSCommand_Export-DbaScript PSFunction_Get-DbaAgentJobOutputFile PSCommand_Get-DbaAgentJobOutputFile PSFunction_Set-DbaAgentJobOutputFile PSCommand_Set-DbaAgentJobOutputFile PSFunction_Get-DbaBuildReference PSCommand_Get-DbaBuildReference PSFunction_New-DbaDacProfile PSCommand_New-DbaDacProfile PSFunction_Import-DbaXESessionTemplate PSCommand_Import-DbaXESessionTemplate PSFunction_Export-DbaXESessionTemplate PSCommand_Export-DbaXESessionTemplate PSFunction_Import-DbaSpConfigure PSCommand_Import-DbaSpConfigure PSFunction_Export-DbaSpConfigure PSCommand_Export-DbaSpConfigure PSFunction_Update-Dbatools PSCommand_Update-Dbatools PSFunction_Install-DbaWhoIsActive PSCommand_Install-DbaWhoIsActive PSFunction_Install-DbaFirstResponderKit PSCommand_Install-DbaFirstResponderKit PSFunction_Read-DbaXEFile PSCommand_Read-DbaXEFile PSFunction_Watch-DbaXESession PSCommand_Watch-DbaXESession PSFunction_Test-DbaMaxMemory PSCommand_Test-DbaMaxMemory PSFunction_Rename-DbaDatabase PSCommand_Rename-DbaDatabase PSFunction_Update-DbaInstance PSCommand_Update-DbaInstance PSFunction_Invoke-DbaPfRelog PSCommand_Invoke-DbaPfRelog PSFunction_Get-DbaPfDataCollectorCounter PSCommand_Get-DbaPfDataCollectorCounter PSFunction_Get-DbaPfDataCollectorCounterSample PSCommand_Get-DbaPfDataCollectorCounterSample PSFunction_Get-DbaPfDataCollector PSCommand_Get-DbaPfDataCollector PSFunction_Get-DbaPfDataCollectorSet PSCommand_Get-DbaPfDataCollectorSet PSFunction_Start-DbaPfDataCollectorSet PSCommand_Start-DbaPfDataCollectorSet PSFunction_Stop-DbaPfDataCollectorSet PSCommand_Stop-DbaPfDataCollectorSet PSFunction_Export-DbaPfDataCollectorSetTemplate PSCommand_Export-DbaPfDataCollectorSetTemplate PSFunction_Get-DbaPfDataCollectorSetTemplate PSCommand_Get-DbaPfDataCollectorSetTemplate PSFunction_Import-DbaPfDataCollectorSetTemplate PSCommand_Import-DbaPfDataCollectorSetTemplate PSFunction_Remove-DbaPfDataCollectorSet PSCommand_Remove-DbaPfDataCollectorSet PSFunction_Add-DbaPfDataCollectorCounter PSCommand_Add-DbaPfDataCollectorCounter PSFunction_Remove-DbaPfDataCollectorCounter PSCommand_Remove-DbaPfDataCollectorCounter PSFunction_Get-DbaPfAvailableCounter PSCommand_Get-DbaPfAvailableCounter PSFunction_Export-DbaXECsv PSCommand_Export-DbaXECsv PSFunction_Get-DbaOperatingSystem PSCommand_Get-DbaOperatingSystem PSFunction_Get-DbaComputerSystem PSCommand_Get-DbaComputerSystem PSFunction_Set-DbaPrivilege PSCommand_Set-DbaPrivilege PSFunction_Set-DbaTcpPort PSCommand_Set-DbaTcpPort PSFunction_Set-DbaCmConnection PSCommand_Set-DbaCmConnection PSFunction_Get-DbaUptime PSCommand_Get-DbaUptime PSFunction_Get-DbaMemoryUsage PSCommand_Get-DbaMemoryUsage PSFunction_Clear-DbaConnectionPool PSCommand_Clear-DbaConnectionPool PSFunction_Get-DbaLocaleSetting PSCommand_Get-DbaLocaleSetting PSFunction_Get-DbaFilestream PSCommand_Get-DbaFilestream PSFunction_Enable-DbaFilestream PSCommand_Enable-DbaFilestream PSFunction_Disable-DbaFilestream PSCommand_Disable-DbaFilestream PSFunction_Get-DbaCpuUsage PSCommand_Get-DbaCpuUsage PSFunction_Get-DbaPowerPlan PSCommand_Get-DbaPowerPlan PSFunction_Get-DbaWsfcAvailableDisk PSCommand_Get-DbaWsfcAvailableDisk PSFunction_Get-DbaWsfcCluster PSCommand_Get-DbaWsfcCluster PSFunction_Get-DbaWsfcDisk PSCommand_Get-DbaWsfcDisk PSFunction_Get-DbaWsfcNetwork PSCommand_Get-DbaWsfcNetwork PSFunction_Get-DbaWsfcNetworkInterface PSCommand_Get-DbaWsfcNetworkInterface PSFunction_Get-DbaWsfcNode PSCommand_Get-DbaWsfcNode PSFunction_Get-DbaWsfcResource PSCommand_Get-DbaWsfcResource PSFunction_Get-DbaWsfcResourceType PSCommand_Get-DbaWsfcResourceType PSFunction_Get-DbaWsfcRole PSCommand_Get-DbaWsfcRole PSFunction_Get-DbaWsfcSharedVolume PSCommand_Get-DbaWsfcSharedVolume PSFunction_Export-DbaCredential PSCommand_Export-DbaCredential PSFunction_Export-DbaLinkedServer PSCommand_Export-DbaLinkedServer PSFunction_Get-DbaFeature PSCommand_Get-DbaFeature PSFunction_Update-DbaServiceAccount PSCommand_Update-DbaServiceAccount PSFunction_Remove-DbaClientAlias PSCommand_Remove-DbaClientAlias PSFunction_Disable-DbaAgHadr PSCommand_Disable-DbaAgHadr PSFunction_Enable-DbaAgHadr PSCommand_Enable-DbaAgHadr PSFunction_Stop-DbaService PSCommand_Stop-DbaService PSFunction_Start-DbaService PSCommand_Start-DbaService PSFunction_Restart-DbaService PSCommand_Restart-DbaService PSFunction_New-DbaClientAlias PSCommand_New-DbaClientAlias PSFunction_Get-DbaClientAlias PSCommand_Get-DbaClientAlias PSFunction_Remove-DbaNetworkCertificate PSCommand_Remove-DbaNetworkCertificate PSFunction_Enable-DbaForceNetworkEncryption PSCommand_Enable-DbaForceNetworkEncryption PSFunction_Disable-DbaForceNetworkEncryption PSCommand_Disable-DbaForceNetworkEncryption PSFunction_Get-DbaForceNetworkEncryption PSCommand_Get-DbaForceNetworkEncryption PSFunction_Remove-DbaComputerCertificate PSCommand_Remove-DbaComputerCertificate PSFunction_New-DbaComputerCertificate PSCommand_New-DbaComputerCertificate PSFunction_Get-DbaComputerCertificate PSCommand_Get-DbaComputerCertificate PSFunction_Add-DbaComputerCertificate PSCommand_Add-DbaComputerCertificate PSFunction_Get-DbaNetworkCertificate PSCommand_Get-DbaNetworkCertificate PSFunction_Set-DbaNetworkCertificate PSCommand_Set-DbaNetworkCertificate PSFunction_Invoke-DbaDbLogShipping PSCommand_Invoke-DbaDbLogShipping PSFunction_New-DbaCmConnection PSCommand_New-DbaCmConnection PSFunction_Get-DbaCmConnection PSCommand_Get-DbaCmConnection PSFunction_Remove-DbaCmConnection PSCommand_Remove-DbaCmConnection PSFunction_Test-DbaCmConnection PSCommand_Test-DbaCmConnection PSFunction_Get-DbaCmObject PSCommand_Get-DbaCmObject PSFunction_Set-DbaStartupParameter PSCommand_Set-DbaStartupParameter PSFunction_Get-DbaNetworkActivity PSCommand_Get-DbaNetworkActivity PSFunction_Get-DbaServerProtocol PSCommand_Get-DbaServerProtocol PSFunction_Watch-DbaUpdate PSCommand_Watch-DbaUpdate PSFunction_Uninstall-DbaWatchUpdate PSCommand_Uninstall-DbaWatchUpdate PSFunction_Install-DbaWatchUpdate PSCommand_Install-DbaWatchUpdate PSFunction_Get-DbaPrivilege PSCommand_Get-DbaPrivilege PSFunction_Get-DbaMsdtc PSCommand_Get-DbaMsdtc PSFunction_Get-DbaPageFileSetting PSCommand_Get-DbaPageFileSetting PSFunction_Copy-DbaCredential PSCommand_Copy-DbaCredential PSFunction_Test-DbaConnection PSCommand_Test-DbaConnection PSFunction_Reset-DbaAdmin PSCommand_Reset-DbaAdmin PSFunction_Copy-DbaLinkedServer PSCommand_Copy-DbaLinkedServer PSFunction_Get-DbaDiskSpace PSCommand_Get-DbaDiskSpace PSFunction_Test-DbaDiskAllocation PSCommand_Test-DbaDiskAllocation PSFunction_Test-DbaPowerPlan PSCommand_Test-DbaPowerPlan PSFunction_Set-DbaPowerPlan PSCommand_Set-DbaPowerPlan PSFunction_Test-DbaDiskAlignment PSCommand_Test-DbaDiskAlignment PSFunction_Get-DbaStartupParameter PSCommand_Get-DbaStartupParameter PSFunction_Get-DbaSpn PSCommand_Get-DbaSpn PSFunction_Test-DbaSpn PSCommand_Test-DbaSpn PSFunction_Set-DbaSpn PSCommand_Set-DbaSpn PSFunction_Remove-DbaSpn PSCommand_Remove-DbaSpn PSFunction_Get-DbaService PSCommand_Get-DbaService PSFunction_Get-DbaClientProtocol PSCommand_Get-DbaClientProtocol PSFunction_Get-DbaWindowsLog PSCommand_Get-DbaWindowsLog PSFunction_Show-DbaServerFileSystem PSCommand_Show-DbaServerFileSystem PSFunction_Show-DbaDbList PSCommand_Show-DbaDbList PSFunction_Test-DbaWindowsLogin PSCommand_Test-DbaWindowsLogin PSFunction_Find-DbaLoginInGroup PSCommand_Find-DbaLoginInGroup PSFunction_Import-DbaCsv PSCommand_Import-DbaCsv PSFunction_Export-DbaDacPackage PSCommand_Export-DbaDacPackage PSFunction_Get-DbatoolsConfig PSCommand_Get-DbatoolsConfig PSFunction_Get-DbatoolsConfigValue PSCommand_Get-DbatoolsConfigValue PSFunction_Register-DbatoolsConfig PSCommand_Register-DbatoolsConfig PSFunction_Get-DbaErrorLog PSCommand_Get-DbaErrorLog PSFunction_Get-DbaManagementObject PSCommand_Get-DbaManagementObject PSFunction_Test-DbaManagementObject PSCommand_Test-DbaManagementObject PSIncludes_Function</S>
          <S N="developmentDependency">False</S>
          <S N="updated">2019-01-09T00:02:09Z</S>
          <S N="NormalizedVersion">0.9.737</S>
          <S N="Authors">Chrissy LeMaire</S>
          <S N="IsPrerelease">false</S>
          <S N="ItemType">Module</S>
          <S N="FileList">dbatools.nuspec|allcommands.zip|changelog.md|contributing.md|dbatools.psd1|dbatools.psm1|install.ps1|LICENSE|readme.md|bin\build-project.ps1|bin\dbatools-buildref-index.json|bin\dbatools-index.json|bin\dbatools.dll|bin\dbatools.pdb|bin\dbatools.xml|bin\library.ps1|bin\PSScriptAnalyzerRules.psd1|bin\sp_SQLskills_ConvertTraceToEEs.sql|bin\stig.sql|bin\thor.png|bin\type-extensions.ps1|bin\typealiases.ps1|bin\xetemplates-metadata.xml|bin\bcp\bcp.exe|bin\bcp\Resources\1033\bcp.rll|bin\csv\LumenWorks.Framework.IO.dll|bin\datamasking\Bogus.dll|bin\datamasking\columntypes.json|bin\datamasking\example.tables.json|bin\datamasking\firstnames_all.txt|bin\datamasking\firstnames_female.txt|bin\datamasking\firstnames_male.txt|bin\datamasking\lastnames_all.txt|bin\diagnosticquery\SQLServerDiagnosticQueries_2005_201811.sql|bin\diagnosticquery\SQLServerDiagnosticQueries_2008R2_201811.sql|bin\diagnosticquery\SQLServerDiagnosticQueries_2008_201811.sql|bin\diagnosticquery\SQLServerDiagnosticQueries_2012_201811.sql|bin\diagnosticquery\SQLServerDiagnosticQueries_2014_201811.sql|bin\diagnosticquery\SQLServerDiagnosticQueries_2016SP2_201811.sql|bin\diagnosticquery\SQLServerDiagnosticQueries_2016_201811.sql|bin\diagnosticquery\SQLServerDiagnosticQueries_2017_201811.sql|bin\diagnosticquery\SQLServerDiagnosticQueries_2019_201811.sql|bin\diagnosticquery\SQLServerDiagnosticQueries_AzureSQLDatabase_201811.sql|bin\net452\dbatools.dll|bin\net452\dbatools.pdb|bin\net452\dbatools.xml|bin\netcoreapp2.1\dbatools.deps.json|bin\netcoreapp2.1\dbatools.dll|bin\netcoreapp2.1\dbatools.pdb|bin\netcoreapp2.1\dbatools.xml|bin\perfmontemplates\collectorsets.xml|bin\perfmontemplates\collectorsets\Long Running Queries.xml|bin\perfmontemplates\collectorsets\PAL - SQL Server 2005.xml|bin\perfmontemplates\collectorsets\PAL - SQL Server 2008 and R2.xml|bin\perfmontemplates\collectorsets\PAL - SQL Server 2012.xml|bin\perfmontemplates\collectorsets\PAL - SQL Server 2014 and Up.xml|bin\projects\dbatools\.vs\dbatools\v15\.suo|bin\smo\Accessibility.dll|bin\smo\Microsoft.AnalysisServices.AppLocal.Core.dll|bin\smo\Microsoft.AnalysisServices.AppLocal.dll|bin\smo\Microsoft.Azure.KeyVault.Core.dll|bin\smo\Microsoft.Data.Edm.dll|bin\smo\Microsoft.Data.OData.dll|bin\smo\Microsoft.Data.Tools.Components.dll|bin\smo\Microsoft.Data.Tools.Contracts.dll|bin\smo\Microsoft.Data.Tools.Schema.Sql.dll|bin\smo\Microsoft.Data.Tools.Schema.SqlTasks.targets|bin\smo\Microsoft.Data.Tools.Schema.Tasks.Sql.dll|bin\smo\Microsoft.Data.Tools.Schema.Utilities.Sql.dll|bin\smo\Microsoft.Data.Tools.Utilities.dll|bin\smo\Microsoft.DataTransfer.Common.Utils.dll|bin\smo\Microsoft.Practices.TransientFaultHandling.Core.dll|bin\smo\Microsoft.SqlServer.BatchParser.dll|bin\smo\Microsoft.SqlServer.BatchParserClient.dll|bin\smo\Microsoft.SqlServer.BulkInsertTaskConnections.dll|bin\smo\Microsoft.SqlServer.ConnectionInfo.dll|bin\smo\Microsoft.SqlServer.ConnectionInfoExtended.dll|bin\smo\Microsoft.SqlServer.Dac.dll|bin\smo\Microsoft.SqlServer.Dac.Extensions.dll|bin\smo\Microsoft.SqlServer.Dac.Extensions.xml|bin\smo\Microsoft.SqlServer.Dac.xml|bin\smo\Microsoft.SqlServer.Diagnostics.Strace.dll|bin\smo\Microsoft.SqlServer.Dmf.Common.dll|bin\smo\Microsoft.SqlServer.Dmf.dll|bin\smo\Microsoft.SqlServer.DmfSqlClrWrapper.dll|bin\smo\Microsoft.SqlServer.DtsServer.Interop.dll|bin\smo\Microsoft.SqlServer.IntegrationServices.ClusterManagement.dll|bin\smo\Microsoft.SqlServer.IntegrationServices.ISServerDBUpgrade.dll|bin\smo\Microsoft.SqlServer.IntegrationServices.Server.Common.dll|bin\smo\Microsoft.SqlServer.IntegrationServices.Server.dll|bin\smo\Microsoft.SqlServer.IntegrationServices.Server.IPC.dll|bin\smo\Microsoft.SqlServer.IntegrationServices.server.shared.dll|bin\smo\Microsoft.SqlServer.IntegrationServices.SqlTaskScheduler.dll|bin\smo\Microsoft.SqlServer.IntegrationServices.TaskScheduler.dll|bin\smo\Microsoft.SqlServer.IntegrationServices.WorkerAgent.dll|bin\smo\Microsoft.SqlServer.Management.AlwaysEncrypted.AzureKeyVaultProvider.dll|bin\smo\Microsoft.SqlServer.Management.AlwaysEncrypted.Management.dll|bin\smo\Microsoft.SqlServer.Management.AlwaysEncrypted.Types.dll|bin\smo\Microsoft.SqlServer.Management.AzureAuthenticationManagement.dll|bin\smo\Microsoft.SqlServer.Management.CloudAdapter.Client.dll|bin\smo\Microsoft.SqlServer.Management.CloudAdapter.Data.dll|bin\smo\Microsoft.SqlServer.Management.Collector.dll|bin\smo\Microsoft.SqlServer.Management.CollectorEnum.dll|bin\smo\Microsoft.SqlServer.Management.Dac.UniversalAuthProvider.dll|bin\smo\Microsoft.SqlServer.Management.HadrDmf.dll|bin\smo\Microsoft.SqlServer.Management.InMemoryOLTPMigrationAdvisor.dll|bin\smo\Microsoft.SqlServer.Management.IntegrationServices.dll|bin\smo\Microsoft.SqlServer.Management.IntegrationServicesEnum.dll|bin\smo\Microsoft.SqlServer.Management.RegisteredServers.dll|bin\smo\Microsoft.SqlServer.Management.Sdk.Scripting.dll|bin\smo\Microsoft.SqlServer.Management.Sdk.Sfc.dll|bin\smo\Microsoft.SqlServer.Management.SDK.SqlStudio.dll|bin\smo\Microsoft.SqlServer.Management.SmartAdminPolicies.dll|bin\smo\Microsoft.SqlServer.Management.Utility.dll|bin\smo\Microsoft.SqlServer.Management.UtilityEnum.dll|bin\smo\Microsoft.SqlServer.Management.XEvent.dll|bin\smo\Microsoft.SqlServer.Management.XEventDbScoped.dll|bin\smo\Microsoft.SqlServer.Management.XEventDbScopedEnum.dll|bin\smo\Microsoft.SqlServer.Management.XEventEnum.dll|bin\smo\Microsoft.SqlServer.OlapEnum.dll|bin\smo\Microsoft.SqlServer.PolicyEnum.dll|bin\smo\Microsoft.SqlServer.RegSvrEnum.dll|bin\smo\Microsoft.SqlServer.ReplEnum.dll|bin\smo\Microsoft.SqlServer.Replication.BusinessLogicSupport.dll|bin\smo\Microsoft.SqlServer.Replication.dll|bin\smo\Microsoft.SqlServer.Rmo.dll|bin\smo\Microsoft.SqlServer.ServiceBrokerEnum.dll|bin\smo\Microsoft.SqlServer.Smo.dll|bin\smo\Microsoft.SqlServer.SmoExtended.dll|bin\smo\Microsoft.SqlServer.SqlClrProvider.dll|bin\smo\Microsoft.SqlServer.SqlEnum.dll|bin\smo\Microsoft.SqlServer.SqlTDiagm.dll|bin\smo\Microsoft.SqlServer.SqlWmiManagement.dll|bin\smo\Microsoft.SqlServer.SString.dll|bin\smo\Microsoft.SqlServer.TransactSql.ScriptDom.dll|bin\smo\Microsoft.SqlServer.VulnerabilityAssessment.Model.dll|bin\smo\Microsoft.SqlServer.WmiEnum.dll|bin\smo\Microsoft.SqlServer.XE.Core.dll|bin\smo\Microsoft.SqlServer.XEvent.Configuration.dll|bin\smo\Microsoft.SqlServer.XEvent.dll|bin\smo\Microsoft.SqlServer.XEvent.Linq.dll|bin\smo\smo-deps.txt|bin\smo\sqlpackage.exe|bin\smo\sqlpackage.exe.config|bin\smo\coreclr\Microsoft.Data.Tools.Schema.Sql.dll|bin\smo\coreclr\Microsoft.Data.Tools.Sql.BatchParser.dll|bin\smo\coreclr\Microsoft.Data.Tools.Utilities.dll|bin\smo\coreclr\Microsoft.SqlServer.ConnectionInfo.dll|bin\smo\coreclr\Microsoft.SqlServer.Dac.dll|bin\smo\coreclr\Microsoft.SqlServer.Dac.Extensions.dll|bin\smo\coreclr\Microsoft.SqlServer.Management.Dmf.dll|bin\smo\coreclr\Microsoft.SqlServer.Management.PSProvider.dll|bin\smo\coreclr\Microsoft.SqlServer.Management.PSSnapins.dll|bin\smo\coreclr\Microsoft.SqlServer.Management.Sdk.Sfc.dll|bin\smo\coreclr\Microsoft.SqlServer.Management.XEvent.dll|bin\smo\coreclr\Microsoft.SqlServer.Management.XEventDbScoped.dll|bin\smo\coreclr\Microsoft.SqlServer.Management.XEventDbScopedEnum.dll|bin\smo\coreclr\Microsoft.SqlServer.Management.XEventEnum.dll|bin\smo\coreclr\Microsoft.SqlServer.Smo.dll|bin\smo\coreclr\Microsoft.SqlServer.SmoExtended.dll|bin\smo\coreclr\Microsoft.SqlServer.SqlEnum.dll|bin\smo\coreclr\Microsoft.SqlServer.TransactSql.ScriptDom.dll|bin\smo\coreclr\Microsoft.SqlServer.Types.dll|bin\smo\coreclr\System.Security.SecureString.dll|bin\sqlcmd\SQLCMD.EXE|bin\sqlcmd\Resources\1033\license_SQLCMD.txt|bin\sqlcmd\Resources\1033\SQLCMD.rll|bin\third-party-licenses\sql-server-data-tools-license-terms-vs2017.md|bin\third-party-licenses\sql-server-data-tools-license-terms.md|bin\third-party-licenses\ThirdPartyNoticesDacFramework.rtf|bin\XESmartTarget\CommandLine.dll|bin\XESmartTarget\CsvHelper.dll|bin\XESmartTarget\DouglasCrockford.JsMin.dll|bin\XESmartTarget\NLog.dll|bin\XESmartTarget\NLog.dll.nlog|bin\XESmartTarget\SmartFormat.dll|bin\XESmartTarget\XESmartTarget.Core.dll|bin\XEtemplates\15 Second IO Error.xml|bin\XEtemplates\Activity Detail Tracking.xml|bin\XEtemplates\Activity Tracking.xml|bin\XEtemplates\AlwaysOn Health Enhanced.xml|bin\XEtemplates\Blocked Process Report.xml|bin\XEtemplates\Connection Detail Tracking.xml|bin\XEtemplates\Connection Tracking.xml|bin\XEtemplates\Count Query Locks.xml|bin\XEtemplates\Database File IO.xml|bin\XEtemplates\Database Health 2012.xml|bin\XEtemplates\Database Health 2014.xml|bin\XEtemplates\Database Health 2016 and Above.xml|bin\XEtemplates\Deadlock Graphs.xml|bin\XEtemplates\Default Profiler Trace.xml|bin\XEtemplates\Deprecated Feature Usage.xml|bin\XEtemplates\Failing Queries.xml|bin\XEtemplates\Function Executions.xml|bin\XEtemplates\Index Page Splits.xml|bin\XEtemplates\Log File IO Detail Tracking.xml|bin\XEtemplates\Log File IO Tracking.xml|bin\XEtemplates\Login Tracker.xml|bin\XEtemplates\Long Running Queries.xml|bin\XEtemplates\Overly Complex Queries.xml|bin\XEtemplates\Profiler SP Counts.xml|bin\XEtemplates\Profiler Standard.xml|bin\XEtemplates\Profiler TSQL Duration.xml|bin\XEtemplates\Profiler TSQL Locks.xml|bin\XEtemplates\Profiler TSQL Replay.xml|bin\XEtemplates\Profiler TSQL SPs.xml|bin\XEtemplates\Profiler TSQL.xml|bin\XEtemplates\Profiler Tuning.xml|bin\XEtemplates\Queries and Resources.xml|bin\XEtemplates\Query Batch Detail Sampling.xml|bin\XEtemplates\Query Batch Sampling.xml|bin\XEtemplates\Query Batch Tracking.xml|bin\XEtemplates\Query Detail Sampling.xml|bin\XEtemplates\Query Detail Tracking.xml|bin\XEtemplates\Query Timeouts.xml|bin\XEtemplates\Query Wait Statistics Detail.xml|bin\XEtemplates\Query Wait Statistics.xml|bin\XEtemplates\Stored Procedure Parameters.xml|en-us\about_dbatools.help.txt|en-us\about_dbatools_importoptions.help.txt|en-us\about_dbatools_support.help.txt|functions\Add-DbaAgDatabase.ps1|functions\Add-DbaAgListener.ps1|functions\Add-DbaAgReplica.ps1|functions\Add-DbaCmsRegServer.ps1|functions\Add-DbaCmsRegServerGroup.ps1|functions\Add-DbaComputerCertificate.ps1|functions\Add-DbaDbMirrorMonitor.ps1|functions\Add-DbaPfDataCollectorCounter.ps1|functions\Backup-DbaDatabase.ps1|functions\Backup-DbaDbCertificate.ps1|functions\Backup-DbaDbMasterKey.ps1|functions\Clear-DbaConnectionPool.ps1|functions\Clear-DbaLatchStatistics.ps1|functions\Clear-DbaPlanCache.ps1|functions\Clear-DbaWaitStatistics.ps1|functions\Connect-DbaInstance.ps1|functions\ConvertTo-DbaDataTable.ps1|functions\ConvertTo-DbaTimeline.ps1|functions\ConvertTo-DbaXESession.ps1|functions\Copy-DbaAgentAlert.ps1|functions\Copy-DbaAgentJob.ps1|functions\Copy-DbaAgentJobCategory.ps1|functions\Copy-DbaAgentOperator.ps1|functions\Copy-DbaAgentProxy.ps1|functions\Copy-DbaAgentSchedule.ps1|functions\Copy-DbaAgentServer.ps1|functions\Copy-DbaBackupDevice.ps1|functions\Copy-DbaCmsRegServer.ps1|functions\Copy-DbaCredential.ps1|functions\Copy-DbaCustomError.ps1|functions\Copy-DbaDatabase.ps1|functions\Copy-DbaDataCollector.ps1|functions\Copy-DbaDbAssembly.ps1|functions\Copy-DbaDbMail.ps1|functions\Copy-DbaDbQueryStoreOption.ps1|functions\Copy-DbaDbTableData.ps1|functions\Copy-DbaEndpoint.ps1|functions\Copy-DbaLinkedServer.ps1|functions\Copy-DbaLogin.ps1|functions\Copy-DbaPolicyManagement.ps1|functions\Copy-DbaResourceGovernor.ps1|functions\Copy-DbaServerAudit.ps1|functions\Copy-DbaServerAuditSpecification.ps1|functions\Copy-DbaServerTrigger.ps1|functions\Copy-DbaSpConfigure.ps1|functions\Copy-DbaSsisCatalog.ps1|functions\Copy-DbaSysDbUserObject.ps1|functions\Copy-DbaXESession.ps1|functions\Copy-DbaXESessionTemplate.ps1|functions\Disable-DbaAgHadr.ps1|functions\Disable-DbaFilestream.ps1|functions\Disable-DbaForceNetworkEncryption.ps1|functions\Disable-DbaTraceFlag.ps1|functions\Dismount-DbaDatabase.ps1|functions\Enable-DbaAgHadr.ps1|functions\Enable-DbaFilestream.ps1|functions\Enable-DbaForceNetworkEncryption.ps1|functions\Enable-DbaTraceFlag.ps1|functions\Expand-DbaDbLogFile.ps1|functions\Export-DbaAvailabilityGroup.ps1|functions\Export-DbaCmsRegServer.ps1|functions\Export-DbaCredential.ps1|functions\Export-DbaDacPackage.ps1|functions\Export-DbaDiagnosticQuery.ps1|functions\Export-DbaExecutionPlan.ps1|functions\Export-DbaInstance.ps1|functions\Export-DbaLinkedServer.ps1|functions\Export-DbaLogin.ps1|functions\Export-DbaPfDataCollectorSetTemplate.ps1|functions\Export-DbaRepServerSetting.ps1|functions\Export-DbaScript.ps1|functions\Export-DbaSpConfigure.ps1|functions\Export-DbaUser.ps1|functions\Export-DbaXECsv.ps1|functions\Export-DbaXESessionTemplate.ps1|functions\Find-DbaAgentJob.ps1|functions\Find-DbaBackup.ps1|functions\Find-DbaCommand.ps1|functions\Find-DbaDatabase.ps1|functions\Find-DbaDbGrowthEvent.ps1|functions\Find-DbaDbUnusedIndex.ps1|functions\Find-DbaDisabledIndex.ps1|functions\Find-DbaDuplicateIndex.ps1|functions\Find-DbaInstance.ps1|functions\Find-DbaLoginInGroup.ps1|functions\Find-DbaOrphanedFile.ps1|functions\Find-DbaSimilarTable.ps1|functions\Find-DbaStoredProcedure.ps1|functions\Find-DbaTrigger.ps1|functions\Find-DbaUserObject.ps1|functions\Find-DbaView.ps1|functions\Format-DbaBackupInformation.ps1|functions\Get-DbaAgDatabase.ps1|functions\Get-DbaAgentAlert.ps1|functions\Get-DbaAgentJob.ps1|functions\Get-DbaAgentJobCategory.ps1|functions\Get-DbaAgentJobHistory.ps1|functions\Get-DbaAgentJobOutputFile.ps1|functions\Get-DbaAgentJobStep.ps1|functions\Get-DbaAgentLog.ps1|functions\Get-DbaAgentOperator.ps1|functions\Get-DbaAgentProxy.ps1|functions\Get-DbaAgentSchedule.ps1|functions\Get-DbaAgentServer.ps1|functions\Get-DbaAgHadr.ps1|functions\Get-DbaAgListener.ps1|functions\Get-DbaAgReplica.ps1|functions\Get-DbaAvailabilityGroup.ps1|functions\Get-DbaAvailableCollation.ps1|functions\Get-DbaBackupDevice.ps1|functions\Get-DbaBackupHistory.ps1|functions\Get-DbaBackupInformation.ps1|functions\Get-DbaBuildReference.ps1|functions\Get-DbaClientAlias.ps1|functions\Get-DbaClientProtocol.ps1|functions\Get-DbaCmConnection.ps1|functions\Get-DbaCmObject.ps1|functions\Get-DbaCmsRegServer.ps1|functions\Get-DbaCmsRegServerGroup.ps1|functions\Get-DbaCmsRegServerStore.ps1|functions\Get-DbaComputerCertificate.ps1|functions\Get-DbaComputerSystem.ps1|functions\Get-DbaConnection.ps1|functions\Get-DbaCpuRingBuffer.ps1|functions\Get-DbaCpuUsage.ps1|functions\Get-DbaCredential.ps1|functions\Get-DbaCustomError.ps1|functions\Get-DbaDatabase.ps1|functions\Get-DbaDbAssembly.ps1|functions\Get-DbaDbccHelp.ps1|functions\Get-DbaDbccMemoryStatus.ps1|functions\Get-DbaDbccProcCache.ps1|functions\Get-DbaDbccSessionBuffer.ps1|functions\Get-DbaDbccStatistic.ps1|functions\Get-DbaDbccUserOption.ps1|functions\Get-DbaDbCertificate.ps1|functions\Get-DbaDbCheckConstraint.ps1|functions\Get-DbaDbCompatibility.ps1|functions\Get-DbaDbCompression.ps1|functions\Get-DbaDbDbccOpenTran.ps1|functions\Get-DbaDbEncryption.ps1|functions\Get-DbaDbExtentDiff.ps1|functions\Get-DbaDbFeatureUsage.ps1|functions\Get-DbaDbFile.ps1|functions\Get-DbaDbForeignKey.ps1|functions\Get-DbaDbIdentity.ps1|functions\Get-DbaDbLogShipError.ps1|functions\Get-DbaDbMail.ps1|functions\Get-DbaDbMailAccount.ps1|functions\Get-DbaDbMailConfig.ps1|functions\Get-DbaDbMailHistory.ps1|functions\Get-DbaDbMailLog.ps1|functions\Get-DbaDbMailProfile.ps1|functions\Get-DbaDbMailServer.ps1|functions\Get-DbaDbMasterKey.ps1|functions\Get-DbaDbMemoryUsage.ps1|functions\Get-DbaDbMirror.ps1|functions\Get-DbaDbMirrorMonitor.ps1|functions\Get-DbaDbOrphanUser.ps1|functions\Get-DbaDbPageInfo.ps1|functions\Get-DbaDbPartitionFunction.ps1|functions\Get-DbaDbPartitionScheme.ps1|functions\Get-DbaDbQueryStoreOption.ps1|functions\Get-DbaDbRecoveryModel.ps1|functions\Get-DbaDbRestoreHistory.ps1|functions\Get-DbaDbRoleMember.ps1|functions\Get-DbaDbSharePoint.ps1|functions\Get-DbaDbSnapshot.ps1|functions\Get-DbaDbSpace.ps1|functions\Get-DbaDbState.ps1|functions\Get-DbaDbStoredProcedure.ps1|functions\Get-DbaDbTable.ps1|functions\Get-DbaDbTrigger.ps1|functions\Get-DbaDbUdf.ps1|functions\Get-DbaDbUser.ps1|functions\Get-DbaDbView.ps1|functions\Get-DbaDbVirtualLogFile.ps1|functions\Get-DbaDefaultPath.ps1|functions\Get-DbaDependency.ps1|functions\Get-DbaDeprecatedFeature.ps1|functions\Get-DbaDetachedDatabaseInfo.ps1|functions\Get-DbaDiskSpace.ps1|functions\Get-DbaDump.ps1|functions\Get-DbaEndpoint.ps1|functions\Get-DbaErrorLog.ps1|functions\Get-DbaErrorLogConfig.ps1|functions\Get-DbaEstimatedCompletionTime.ps1|functions\Get-DbaExecutionPlan.ps1|functions\Get-DbaFeature.ps1|functions\Get-DbaFile.ps1|functions\Get-DbaFilestream.ps1|functions\Get-DbaForceNetworkEncryption.ps1|functions\Get-DbaHelpIndex.ps1|functions\Get-DbaInstanceProperty.ps1|functions\Get-DbaInstanceUserOption.ps1|functions\Get-DbaIoLatency.ps1|functions\Get-DbaLastBackup.ps1|functions\Get-DbaLastGoodCheckDb.ps1|functions\Get-DbaLatchStatistic.ps1|functions\Get-DbaLinkedServer.ps1|functions\Get-DbaLocaleSetting.ps1|functions\Get-DbaLogin.ps1|functions\Get-DbaMaintenanceSolutionLog.ps1|functions\Get-DbaManagementObject.ps1|functions\Get-DbaMaxMemory.ps1|functions\Get-DbaMemoryCondition.ps1|functions\Get-DbaMemoryUsage.ps1|functions\Get-DbaModule.ps1|functions\Get-DbaMsdtc.ps1|functions\Get-DbaNetworkActivity.ps1|functions\Get-DbaNetworkCertificate.ps1|functions\Get-DbaOpenTransaction.ps1|functions\Get-DbaOperatingSystem.ps1|functions\Get-DbaPageFileSetting.ps1|functions\Get-DbaPbmCategory.ps1|functions\Get-DbaPbmCategorySubscription.ps1|functions\Get-DbaPbmCondition.ps1|functions\Get-DbaPbmObjectSet.ps1|functions\Get-DbaPbmPolicy.ps1|functions\Get-DbaPbmStore.ps1|functions\Get-DbaPermission.ps1|functions\Get-DbaPfAvailableCounter.ps1|functions\Get-DbaPfDataCollector.ps1|functions\Get-DbaPfDataCollectorCounter.ps1|functions\Get-DbaPfDataCollectorCounterSample.ps1|functions\Get-DbaPfDataCollectorSet.ps1|functions\Get-DbaPfDataCollectorSetTemplate.ps1|functions\Get-DbaPlanCache.ps1|functions\Get-DbaPowerPlan.ps1|functions\Get-DbaPrivilege.ps1|functions\Get-DbaProcess.ps1|functions\Get-DbaProductKey.ps1|functions\Get-DbaQueryExecutionTime.ps1|functions\Get-DbaRegistryRoot.ps1|functions\Get-DbaRepDistributor.ps1|functions\Get-DbaRepPublication.ps1|functions\Get-DbaRepServer.ps1|functions\Get-DbaResourceGovernor.ps1|functions\Get-DbaRgClassifierFunction.ps1|functions\Get-DbaRgResourcePool.ps1|functions\Get-DbaRgWorkloadGroup.ps1|functions\Get-DbaRunningJob.ps1|functions\Get-DbaSchemaChangeHistory.ps1|functions\Get-DbaServerAudit.ps1|functions\Get-DbaServerAuditSpecification.ps1|functions\Get-DbaServerInstallDate.ps1|functions\Get-DbaServerProtocol.ps1|functions\Get-DbaServerRole.ps1|functions\Get-DbaServerRoleMember.ps1|functions\Get-DbaServerTrigger.ps1|functions\Get-DbaService.ps1|functions\Get-DbaSpConfigure.ps1|functions\Get-DbaSpinLockStatistic.ps1|functions\Get-DbaSpn.ps1|functions\Get-DbaSsisEnvironmentVariable.ps1|functions\Get-DbaSsisExecutionHistory.ps1|functions\Get-DbaStartupParameter.ps1|functions\Get-DbaSuspectPage.ps1|functions\Get-DbaTcpPort.ps1|functions\Get-DbaTempdbUsage.ps1|functions\Get-DbatoolsLog.ps1|functions\Get-DbaTopResourceUsage.ps1|functions\Get-DbaTrace.ps1|functions\Get-DbaTraceFlag.ps1|functions\Get-DbaUptime.ps1|functions\Get-DbaUserPermission.ps1|functions\Get-DbaWaitingTask.ps1|functions\Get-DbaWaitResource.ps1|functions\Get-DbaWaitStatistic.ps1|functions\Get-DbaWindowsLog.ps1|functions\Get-DbaWsfcAvailableDisk.ps1|functions\Get-DbaWsfcCluster.ps1|functions\Get-DbaWsfcDisk.ps1|functions\Get-DbaWsfcNetwork.ps1|functions\Get-DbaWsfcNetworkInterface.ps1|functions\Get-DbaWsfcNode.ps1|functions\Get-DbaWsfcResource.ps1|functions\Get-DbaWsfcResourceType.ps1|functions\Get-DbaWsfcRole.ps1|functions\Get-DbaWsfcSharedVolume.ps1|functions\Get-DbaXEObject.ps1|functions\Get-DbaXESession.ps1|functions\Get-DbaXESessionTarget.ps1|functions\Get-DbaXESessionTargetFile.ps1|functions\Get-DbaXESessionTemplate.ps1|functions\Get-DbaXESmartTarget.ps1|functions\Get-DbaXEStore.ps1|functions\Grant-DbaAgPermission.ps1|functions\Import-DbaCmsRegServer.ps1|functions\Import-DbaCsv.ps1|functions\Import-DbaPfDataCollectorSetTemplate.ps1|functions\Import-DbaSpConfigure.ps1|functions\Import-DbaXESessionTemplate.ps1|functions\Install-DbaFirstResponderKit.ps1|functions\Install-DbaMaintenanceSolution.ps1|functions\Install-DbaSqlWatch.ps1|functions\Install-DbaWatchUpdate.ps1|functions\Install-DbaWhoIsActive.ps1|functions\Invoke-DbaAdvancedRestore.ps1|functions\Invoke-DbaAgFailover.ps1|functions\Invoke-DbaBalanceDataFiles.ps1|functions\Invoke-DbaCycleErrorLog.ps1|functions\Invoke-DbaDbccDropCleanBuffer.ps1|functions\Invoke-DbaDbccFreeCache.ps1|functions\Invoke-DbaDbClone.ps1|functions\Invoke-DbaDbDataMasking.ps1|functions\Invoke-DbaDbDbccCheckConstraint.ps1|functions\Invoke-DbaDbDbccCleanTable.ps1|functions\Invoke-DbaDbDbccUpdateUsage.ps1|functions\Invoke-DbaDbDecryptObject.ps1|functions\Invoke-DbaDbLogShipping.ps1|functions\Invoke-DbaDbLogShipRecovery.ps1|functions\Invoke-DbaDbMirrorFailover.ps1|functions\Invoke-DbaDbMirroring.ps1|functions\Invoke-DbaDbShrink.ps1|functions\Invoke-DbaDbUpgrade.ps1|functions\Invoke-DbaDiagnosticQuery.ps1|functions\Invoke-DbaPfRelog.ps1|functions\Invoke-DbaQuery.ps1|functions\Invoke-DbatoolsFormatter.ps1|functions\Invoke-DbatoolsRenameHelper.ps1|functions\Invoke-DbaWhoisActive.ps1|functions\Invoke-DbaXEReplay.ps1|functions\Join-DbaAvailabilityGroup.ps1|functions\Measure-DbaBackupThroughput.ps1|functions\Measure-DbaDiskSpaceRequirement.ps1|functions\Measure-DbatoolsImport.ps1|functions\Mount-DbaDatabase.ps1|functions\Move-DbaCmsRegServer.ps1|functions\Move-DbaCmsRegServerGroup.ps1|functions\New-DbaAgentJob.ps1|functions\New-DbaAgentJobCategory.ps1|functions\New-DbaAgentJobStep.ps1|functions\New-DbaAgentProxy.ps1|functions\New-DbaAgentSchedule.ps1|functions\New-DbaAvailabilityGroup.ps1|functions\New-DbaClientAlias.ps1|functions\New-DbaCmConnection.ps1|functions\New-DbaComputerCertificate.ps1|functions\New-DbaConnectionString.ps1|functions\New-DbaConnectionStringBuilder.ps1|functions\New-DbaCredential.ps1|functions\New-DbaDacOption.ps1|functions\New-DbaDacProfile.ps1|functions\New-DbaDatabase.ps1|functions\New-DbaDbCertificate.ps1|functions\New-DbaDbMaskingConfig.ps1|functions\New-DbaDbMasterKey.ps1|functions\New-DbaDbSnapshot.ps1|functions\New-DbaDbUser.ps1|functions\New-DbaDirectory.ps1|functions\New-DbaEndpoint.ps1|functions\New-DbaLogin.ps1|functions\New-DbaScriptingOption.ps1|functions\New-DbaServiceMasterKey.ps1|functions\New-DbaSsisCatalog.ps1|functions\New-DbatoolsSupportPackage.ps1|functions\New-DbaXESession.ps1|functions\New-DbaXESmartCsvWriter.ps1|functions\New-DbaXESmartEmail.ps1|functions\New-DbaXESmartQueryExec.ps1|functions\New-DbaXESmartReplay.ps1|functions\New-DbaXESmartTableWriter.ps1|functions\Publish-DbaDacPackage.ps1|functions\Read-DbaAuditFile.ps1|functions\Read-DbaBackupHeader.ps1|functions\Read-DbaTraceFile.ps1|functions\Read-DbaTransactionLog.ps1|functions\Read-DbaXEFile.ps1|functions\Remove-DbaAgDatabase.ps1|functions\Remove-DbaAgentJob.ps1|functions\Remove-DbaAgentJobCategory.ps1|functions\Remove-DbaAgentJobStep.ps1|functions\Remove-DbaAgentSchedule.ps1|functions\Remove-DbaAgListener.ps1|functions\Remove-DbaAgReplica.ps1|functions\Remove-DbaAvailabilityGroup.ps1|functions\Remove-DbaBackup.ps1|functions\Remove-DbaClientAlias.ps1|functions\Remove-DbaCmConnection.ps1|functions\Remove-DbaCmsRegServer.ps1|functions\Remove-DbaCmsRegServerGroup.ps1|functions\Remove-DbaComputerCertificate.ps1|functions\Remove-DbaDatabase.ps1|functions\Remove-DbaDatabaseSafely.ps1|functions\Remove-DbaDbBackupRestoreHistory.ps1|functions\Remove-DbaDbCertificate.ps1|functions\Remove-DbaDbMasterKey.ps1|functions\Remove-DbaDbMirror.ps1|functions\Remove-DbaDbMirrorMonitor.ps1|functions\Remove-DbaDbOrphanUser.ps1|functions\Remove-DbaDbSnapshot.ps1|functions\Remove-DbaDbUser.ps1|functions\Remove-DbaEndpoint.ps1|functions\Remove-DbaLogin.ps1|functions\Remove-DbaNetworkCertificate.ps1|functions\Remove-DbaPfDataCollectorCounter.ps1|functions\Remove-DbaPfDataCollectorSet.ps1|functions\Remove-DbaSpn.ps1|functions\Remove-DbaTrace.ps1|functions\Remove-DbaXESession.ps1|functions\Remove-DbaXESmartTarget.ps1|functions\Rename-DbaDatabase.ps1|functions\Rename-DbaLogin.ps1|functions\Repair-DbaDbMirror.ps1|functions\Repair-DbaDbOrphanUser.ps1|functions\Repair-DbaServerName.ps1|functions\Reset-DbaAdmin.ps1|functions\Resolve-DbaNetworkName.ps1|functions\Restart-DbaService.ps1|functions\Restore-DbaBackupFromDirectory.ps1|functions\Restore-DbaDatabase.ps1|functions\Restore-DbaDbCertificate.ps1|functions\Restore-DbaDbSnapshot.ps1|functions\Resume-DbaAgDbDataMovement.ps1|functions\Revoke-DbaAgPermission.ps1|functions\Save-DbaDiagnosticQueryScript.ps1|functions\Select-DbaBackupInformation.ps1|functions\Set-DbaAgentAlert.ps1|functions\Set-DbaAgentJob.ps1|functions\Set-DbaAgentJobCategory.ps1|functions\Set-DbaAgentJobOutputFile.ps1|functions\Set-DbaAgentJobOwner.ps1|functions\Set-DbaAgentJobStep.ps1|functions\Set-DbaAgentSchedule.ps1|functions\Set-DbaAgentServer.ps1|functions\Set-DbaAgListener.ps1|functions\Set-DbaAgReplica.ps1|functions\Set-DbaAvailabilityGroup.ps1|functions\Set-DbaCmConnection.ps1|functions\Set-DbaDbCompatibility.ps1|functions\Set-DbaDbCompression.ps1|functions\Set-DbaDbIdentity.ps1|functions\Set-DbaDbMirror.ps1|functions\Set-DbaDbOwner.ps1|functions\Set-DbaDbQueryStoreOption.ps1|functions\Set-DbaDbRecoveryModel.ps1|functions\Set-DbaDbState.ps1|functions\Set-DbaEndpoint.ps1|functions\Set-DbaErrorLogConfig.ps1|functions\Set-DbaLogin.ps1|functions\Set-DbaMaxDop.ps1|functions\Set-DbaMaxMemory.ps1|functions\Set-DbaNetworkCertificate.ps1|functions\Set-DbaPowerPlan.ps1|functions\Set-DbaPrivilege.ps1|functions\Set-DbaSpConfigure.ps1|functions\Set-DbaSpn.ps1|functions\Set-DbaStartupParameter.ps1|functions\Set-DbaTcpPort.ps1|functions\Set-DbaTempDbConfig.ps1|functions\Show-DbaDbList.ps1|functions\Show-DbaServerFileSystem.ps1|functions\Start-DbaAgentJob.ps1|functions\Start-DbaEndpoint.ps1|functions\Start-DbaMigration.ps1|functions\Start-DbaPfDataCollectorSet.ps1|functions\Start-DbaService.ps1|functions\Start-DbaTrace.ps1|functions\Start-DbaXESession.ps1|functions\Start-DbaXESmartTarget.ps1|functions\Stop-DbaAgentJob.ps1|functions\Stop-DbaEndpoint.ps1|functions\Stop-DbaPfDataCollectorSet.ps1|functions\Stop-DbaProcess.ps1|functions\Stop-DbaService.ps1|functions\Stop-DbaTrace.ps1|functions\Stop-DbaXESession.ps1|functions\Stop-DbaXESmartTarget.ps1|functions\Suspend-DbaAgDbDataMovement.ps1|functions\Sync-DbaAvailabilityGroup.ps1|functions\Sync-DbaLoginPermission.ps1|functions\Test-DbaBackupInformation.ps1|functions\Test-DbaBuild.ps1|functions\Test-DbaCmConnection.ps1|functions\Test-DbaConnection.ps1|functions\Test-DbaConnectionAuthScheme.ps1|functions\Test-DbaDbCollation.ps1|functions\Test-DbaDbCompatibility.ps1|functions\Test-DbaDbCompression.ps1|functions\Test-DbaDbLogShipStatus.ps1|functions\Test-DbaDbOwner.ps1|functions\Test-DbaDbRecoveryModel.ps1|functions\Test-DbaDbVirtualLogFile.ps1|functions\Test-DbaDeprecatedFeature.ps1|functions\Test-DbaDiskAlignment.ps1|functions\Test-DbaDiskAllocation.ps1|functions\Test-DbaDiskSpeed.ps1|functions\Test-DbaEndpoint.ps1|functions\Test-DbaIdentityUsage.ps1|functions\Test-DbaJobOwner.ps1|functions\Test-DbaLastBackup.ps1|functions\Test-DbaLinkedServerConnection.ps1|functions\Test-DbaLoginPassword.ps1|functions\Test-DbaManagementObject.ps1|functions\Test-DbaMaxDop.ps1|functions\Test-DbaMaxMemory.ps1|functions\Test-DbaMigrationConstraint.ps1|functions\Test-DbaNetworkLatency.ps1|functions\Test-DbaOptimizeForAdHoc.ps1|functions\Test-DbaPath.ps1|functions\Test-DbaPowerPlan.ps1|functions\Test-DbaRepLatency.ps1|functions\Test-DbaServerName.ps1|functions\Test-DbaSpn.ps1|functions\Test-DbaTempDbConfig.ps1|functions\Test-DbaWindowsLogin.ps1|functions\Uninstall-DbaSqlWatch.ps1|functions\Uninstall-DbaWatchUpdate.ps1|functions\Update-DbaInstance.ps1|functions\Update-DbaServiceAccount.ps1|functions\Update-dbatools.ps1|functions\Watch-DbaDbLogin.ps1|functions\Watch-DbaUpdate.ps1|functions\Watch-DbaXESession.ps1|functions\Write-DbaDataTable.ps1|functions\configuration\Export-DbatoolsConfig.ps1|functions\configuration\Get-DbatoolsConfig.ps1|functions\configuration\Get-DbatoolsConfigValue.ps1|functions\configuration\Import-DbatoolsConfig.ps1|functions\configuration\Register-DbatoolsConfig.ps1|functions\configuration\Reset-DbatoolsConfig.ps1|functions\configuration\Unregister-DbatoolsConfig.ps1|internal\configurations\configuration.ps1|internal\configurations\settings\assets.ps1|internal\configurations\settings\commands.ps1|internal\configurations\settings\computermanagement.ps1|internal\configurations\settings\formatting.ps1|internal\configurations\settings\import.ps1|internal\configurations\settings\logging.ps1|internal\configurations\settings\paths.ps1|internal\configurations\settings\remoting.ps1|internal\configurations\settings\sql.ps1|internal\configurations\settings\tabexpansion.ps1|internal\configurations\settings\userinteraction.ps1|internal\configurations\validation\bool.ps1|internal\configurations\validation\consolecolor.ps1|internal\configurations\validation\datetime.ps1|internal\configurations\validation\double.ps1|internal\configurations\validation\integer.ps1|internal\configurations\validation\integer0to9.ps1|internal\configurations\validation\integerpositive.ps1|internal\configurations\validation\long.ps1|internal\configurations\validation\sizestyle.ps1|internal\configurations\validation\string.ps1|internal\configurations\validation\timespan.ps1|internal\dynamicparams\alert.ps1|internal\dynamicparams\alertcategory.ps1|internal\dynamicparams\audit.ps1|internal\dynamicparams\auditspecification.ps1|internal\dynamicparams\availabilitygroup.ps1|internal\dynamicparams\backupdevice.ps1|internal\dynamicparams\config.ps1|internal\dynamicparams\configname.ps1|internal\dynamicparams\credential.ps1|internal\dynamicparams\customerror.ps1|internal\dynamicparams\database.ps1|internal\dynamicparams\delimiter.ps1|internal\dynamicparams\endpoint.ps1|internal\dynamicparams\group.ps1|internal\dynamicparams\instanceproperty.ps1|internal\dynamicparams\job.ps1|internal\dynamicparams\jobcategory.ps1|internal\dynamicparams\linkedserver.ps1|internal\dynamicparams\login.ps1|internal\dynamicparams\mailaccount.ps1|internal\dynamicparams\mailprofile.ps1|internal\dynamicparams\mailserver.ps1|internal\dynamicparams\operator.ps1|internal\dynamicparams\operatorcategory.ps1|internal\dynamicparams\perfmontemplate.ps1|internal\dynamicparams\powerplan.ps1|internal\dynamicparams\processHostname.ps1|internal\dynamicparams\processProgram.ps1|internal\dynamicparams\processSpid.ps1|internal\dynamicparams\proxyaccount.ps1|internal\dynamicparams\resourcepool.ps1|internal\dynamicparams\schedule.ps1|internal\dynamicparams\servertrigger.ps1|internal\dynamicparams\session.ps1|internal\dynamicparams\snapshot.ps1|internal\dynamicparams\sqlinstance.ps1|internal\dynamicparams\tag.ps1|internal\dynamicparams\xesessiontemplate.ps1|internal\functions\Connect-AsServer.ps1|internal\functions\Connect-ReplicationDB.ps1|internal\functions\Connect-SqlInstance.ps1|internal\functions\Convert-ByteToHexString.ps1|internal\functions\Convert-DbaLsn.ps1|internal\functions\Convert-DbaTimelineStatusColor.ps1|internal\functions\Convert-DbVersionToSqlVersion.ps1|internal\functions\Convert-HexStringToByte.ps1|internal\functions\ConvertTo-JsDate.ps1|internal\functions\Disconnect-Regserver.ps1|internal\functions\Find-SqlServerUpdate.ps1|internal\functions\Get-BackupAncientHistory.ps1|internal\functions\Get-CodePage.ps1|internal\functions\Get-DbaADObject.ps1|internal\functions\Get-DbaDbPhysicalFile.ps1|internal\functions\Get-DbaFileStreamFolder.ps1|internal\functions\Get-DbaPathSep.ps1|internal\functions\Get-DbaReportingService.ps1|internal\functions\Get-DBAServiceErrorMessage.ps1|internal\functions\Get-DbaSysDbUserObjectScript.ps1|internal\functions\Get-DecryptedObject.ps1|internal\functions\Get-DirectoryRestoreFile.ps1|internal\functions\Get-ErrorMessage.ps1|internal\functions\Get-InternalService.ps1|internal\functions\Get-JobList.ps1|internal\functions\Get-Language.ps1|internal\functions\Get-OfflineSqlFileStructure.ps1|internal\functions\Get-PasswordHash.ps1|internal\functions\Get-RegServerGroupReverseParse.ps1|internal\functions\Get-RegServerParent.ps1|internal\functions\Get-ResourceState.ps1|internal\functions\Get-RestoreContinuableDatabase.ps1|internal\functions\Get-SaLoginName.ps1|internal\functions\Get-SmoServerForDynamicParams.ps1|internal\functions\Get-SqlCmdVars.ps1|internal\functions\Get-SqlDefaultPaths.ps1|internal\functions\Get-SqlDefaultSpConfigure.ps1|internal\functions\Get-SqlFileStructure.ps1|internal\functions\Get-SqlInstanceComponent.ps1|internal\functions\Get-SqlSaLogin.ps1|internal\functions\Get-SqlServerUpdate.ps1|internal\functions\Get-TableNameParts.ps1|internal\functions\Get-WmiHadr.ps1|internal\functions\Get-XpDirTreeRestoreFile.ps1|internal\functions\Import-DbaCmdlet.ps1|internal\functions\Initialize-CredSSP.ps1|internal\functions\Invoke-Alter.ps1|internal\functions\Invoke-Command2.ps1|internal\functions\Invoke-CommandWithFallback.ps1|internal\functions\Invoke-Create.ps1|internal\functions\Invoke-DbaAsync.ps1|internal\functions\Invoke-DbaDatabaseCorruption.ps1|internal\functions\Invoke-DbaDiagnosticQueryScriptParser.ps1|internal\functions\Invoke-DbMirrorValidation.ps1|internal\functions\Invoke-ManagedComputerCommand.ps1|internal\functions\Invoke-Program.ps1|internal\functions\Invoke-SmoCheck.ps1|internal\functions\Invoke-TagCommand.ps1|internal\functions\Invoke-TlsWebRequest.ps1|internal\functions\Join-AdminUnc.ps1|internal\functions\Join-SomePath.ps1|internal\functions\New-DbaLogShippingPrimaryDatabase.ps1|internal\functions\New-DbaLogShippingPrimarySecondary.ps1|internal\functions\New-DbaLogShippingSecondaryDatabase.ps1|internal\functions\New-DbaLogShippingSecondaryPrimary.ps1|internal\functions\Register-RemoteSessionConfiguration.ps1|internal\functions\Remove-InvalidFileNameChars.ps1|internal\functions\Resolve-IpAddress.ps1|internal\functions\Resolve-NetBiosName.ps1|internal\functions\Resolve-SqlIpAddress.ps1|internal\functions\Restart-WinRMService.ps1|internal\functions\Select-DefaultView.ps1|internal\functions\Set-ServiceStartMode.ps1|internal\functions\Set-WmiFilestreamSetting.ps1|internal\functions\Show-Notification.ps1|internal\functions\Start-DbccCheck.ps1|internal\functions\Test-ComputerTarget.ps1|internal\functions\Test-DbaLsnChain.ps1|internal\functions\Test-DbaRestoreVersion.ps1|internal\functions\Test-HostOSLinux.ps1|internal\functions\Test-PendingReboot.ps1|internal\functions\Test-PSRemoting.ps1|internal\functions\Test-SqlAgent.ps1|internal\functions\Test-SqlLoginAccess.ps1|internal\functions\Test-SqlQueryComplete.ps1|internal\functions\Test-SqlSa.ps1|internal\functions\Unregister-RemoteSessionConfiguration.ps1|internal\functions\Update-ServiceStatus.ps1|internal\functions\Update-SqlDbOwner.ps1|internal\functions\Update-SqlDbReadOnly.ps1|internal\functions\Update-SqlPermission.ps1|internal\functions\Where-DbaObject.ps1|internal\functions\Write-ProgressHelper.ps1|internal\functions\configuration\Read-DbatoolsConfigFile.ps1|internal\functions\configuration\Read-DbatoolsConfigPersisted.ps1|internal\functions\configuration\Register-DbatoolsConfigValidation.ps1|internal\functions\configuration\Write-DbatoolsConfigFile.ps1|internal\functions\flowcontrol\Invoke-Parallel.ps1|internal\functions\flowcontrol\Invoke-SteppablePipeline.ps1|internal\functions\flowcontrol\Stop-Function.ps1|internal\functions\flowcontrol\Test-Bound.ps1|internal\functions\flowcontrol\Test-DbaDeprecation.ps1|internal\functions\flowcontrol\Test-ElevationRequirement.ps1|internal\functions\flowcontrol\Test-FunctionInterrupt.ps1|internal\functions\flowcontrol\Test-Windows.ps1|internal\functions\message\Convert-DbaMessageException.ps1|internal\functions\message\Convert-DbaMessageLevel.ps1|internal\functions\message\Convert-DbaMessageTarget.ps1|internal\functions\message\Get-DbaMessageLevelModifier.ps1|internal\functions\message\New-DbaMessageLevelModifier.ps1|internal\functions\message\Register-DbaMessageEvent.ps1|internal\functions\message\Register-DbaMessageTransform.ps1|internal\functions\message\Remove-DbaMessageLevelModifier.ps1|internal\functions\message\Write-HostColor.ps1|internal\functions\runspaces\Get-DbaRunspace.ps1|internal\functions\runspaces\Register-DbaMaintenanceTask.ps1|internal\functions\runspaces\Register-DbaRunspace.ps1|internal\functions\runspaces\Start-DbaRunspace.ps1|internal\functions\runspaces\Stop-DbaRunspace.ps1|internal\functions\tabcompletion\New-DbaTeppCompletionResult.ps1|internal\functions\tabcompletion\Register-DbaTeppArgumentCompleter.ps1|internal\functions\tabcompletion\Register-DbaTeppInstanceCacheBuilder.ps1|internal\functions\tabcompletion\Register-DbaTeppScriptBlock.ps1|internal\functions\utility\Join-DbaPath.ps1|internal\functions\utility\Resolve-DbaPath.ps1|internal\maintenance\PSSession-Cleanup.ps1|internal\maintenance\tempcleanup.ps1|internal\maintenance\teppInsertTask.ps1|internal\scripts\cmdlets.ps1|internal\scripts\dbatools-maintenance.ps1|internal\scripts\insertTepp.ps1|internal\scripts\logfilescript.ps1|internal\scripts\message-transforms.ps1|internal\scripts\smoLibraryImport.ps1|internal\scripts\updateTeppAsync.ps1|optional\Compress-Archive.ps1|optional\Expand-Archive.ps1|optional\Get-GenericArgumentCompleter.ps1|optional\TabExpansionPlusPlus.ps1|xml\dbatools.Format.ps1xml|xml\dbatools.Types.ps1xml</S>
          <S N="GUID">9d139310-ce45-41ce-8e8b-d76335aa1789</S>
          <S N="PowerShellVersion">3.0</S>
          <S N="CompanyName">dbatools.io</S>
        </MS>
      </Obj>
      <S N="InstalledLocation">C:\Users\appveyor\AppData\Local\Temp\1\c1a6c370-77d7-48ce-8599-d87b13a0e5df\dbatools\0.9.737</S>
    </MS>
  </Obj>
</Objs>
tools\dbatools\readme.md
# dbatools

<img align="left" src=https://blog.netnerds.net/wp-content/uploads/2016/05/dbatools.png alt="dbatools logo">  dbatools is sort of like a command-line SQL Server Management Studio. The project initially started out as Start-SqlMigration.ps1, but has now grown into a collection of [over 500 commands](https://dbatools.io/commands) that help automate SQL Server tasks and encourage best practices.

Got ideas for new commands? Please propose them as [issues](https://dbatools.io/issues) and let us know what you'd like to see. Bug reports should also be filed under this repository's [issues](https://github.com/sqlcollaborative/dbatools/issues) section.

There's also over 1500 of us on the [SQL Server Community Slack](https://sqlcommunity.slack.com) in the #dbatools channel. Need an invite? Check out the [self-invite page](https://dbatools.io/slack/). Drop by if you'd like to chat about dbatools or even [join the team](https://dbatools.io/team)!

## Installer

dbatools now works on PowerShell Core (aka PowerShell 6+). This means that you can run a large majority of our commands on <strong>Linux</strong> and <strong>macoS </strong>🤩👍

Run the following from an administrative prompt to install dbatools from the PowerShell Gallery:
```powershell
Install-Module dbatools
```

Or if you don't have a version of PowerShell that supports the Gallery, you can install it manually:
```powershell
Invoke-Expression (Invoke-WebRequest https://dbatools.io/in)
```

Note: please only use `Invoke-Expression (Invoke-WebRequest..)` from sources you trust, like us 👍

## Usage scenarios

In addition to the simple things you can do in SSMS (like starting a job), we've also read a whole bunch of docs and came up with commands that do nifty things quickly.

* Lost sysadmin access and need to regain entry to your SQL Server? Use [Reset-DbaAdmin](http://dbatools.io/Reset-DbaAdmin).
* Need to easily test your backups? Use [Test-DbaLastBackup](http://dbatools.io/Test-DbaLastBackup).
* SPN management got you down? Use [our suite of SPN commands](http://dbatools.io/schwifty) to find which SPNs are missing and easily add them.
* Got so many databases you can't keep track? Congrats on your big ol' environment! Use [Find-DbaDatabase](http://dbatools.io/Find-DbaDatabase) to easily find your database.

## Usage examples

As previously mentioned, dbatools now offers [over 400 commands](https://dbatools.io/commands)! [Here are some of the ones we highlight at conferences](https://gist.github.com/potatoqualitee/e8932b64aeb6ef404e252d656b6318a2) - PowerShell v3 and above required. (See below for important information about alternative logins and specifying SQL Server ports).

```powershell
# Set some vars
$new = "localhost\sql2016"
$old = $instance = "localhost"
$allservers = $old, $new

# Alternatively, use Registered Servers
$allservers = Get-DbaCmsRegServer -SqlInstance $instance

# Need to restore a database? It can be as simple as this:
Restore-DbaDatabase -SqlInstance $instance -Path "C:\temp\AdventureWorks2012-Full Database Backup.bak"

# Use Ola Hallengren's backup script? We can restore an *ENTIRE INSTANCE* with just one line
Get-ChildItem -Directory \\workstation\backups\sql2012 | Restore-DbaDatabase -SqlInstance $new

# What about if you need to make a backup? And you are logging in with alternative credentials?
Get-DbaDatabase -SqlInstance $new -SqlCredential sqladmin | Backup-DbaDatabase

# Testing your backups is crazy easy!
Start-Process https://dbatools.io/Test-DbaLastBackup
Test-DbaLastBackup -SqlInstance $old | Out-GridView

# But what if you want to test your backups on a different server?
Test-DbaLastBackup -SqlInstance $old -Destination $new | Out-GridView

# Nowadays, we don't just backup databases. Now, we're backing up logins
Export-DbaLogin -SqlInstance $instance -Path C:\temp\logins.sql
Invoke-Item C:\temp\logins.sql

# And Agent Jobs
Get-DbaAgentJob -SqlInstance $old | Export-DbaScript -Path C:\temp\jobs.sql

# What if you just want to script out your restore?
Get-ChildItem -Directory \\workstation\backups\subset\ | Restore-DbaDatabase -SqlInstance $new -OutputScriptOnly -WithReplace | Out-File -Filepath c:\temp\restore.sql
Invoke-Item c:\temp\restore.sql

# You've probably heard about how easy migrations can be with dbatools. Here's an example
$startDbaMigrationSplat = @{
    Source = $old
    Destination = $new
    BackupRestore = $true
    SharedPath = 'C:\temp'
    NoSysDbUserObjects = $true
    NoCredentials = $true
    NoBackupDevices = $true
    NoEndPoints = $true
}

Start-DbaMigration @startDbaMigrationSplat -Force | Select * | Out-GridView

# Know how snapshots used to be a PITA? Now they're super easy
New-DbaDbSnapshot -SqlInstance $new -Database db1 -Name db1_snapshot
Get-DbaDbSnapshot -SqlInstance $new
Get-DbaProcess -SqlInstance $new -Database db1 | Stop-DbaProcess
Restore-DbaFromDatabaseSnapshot -SqlInstance $new -Database db1 -Snapshot db1_snapshot
Remove-DbaDbSnapshot -SqlInstance $new -Snapshot db1_snapshot # or -Database db1

# Have you tested your last good DBCC CHECKDB? We've got a command for that
$old | Get-DbaLastGoodCheckDb | Out-GridView

# Here's how you can find your integrity jobs and easily start them. Then, you can watch them run, and finally check your newest DBCC CHECKDB results
$old | Get-DbaAgentJob | Where Name -match integrity | Start-DbaAgentJob
$old | Get-DbaRunningJob
$old | Get-DbaLastGoodCheckDb | Out-GridView

# Our new build website is super useful!
Start-Process https://dbatools.io/builds

# You can use the same JSON the website uses to check the status of your own environment
$allservers | Get-DbaBuildReference

# We evaluated 37,545 SQL Server stored procedures on 9 servers in 8.67 seconds!
$new | Find-DbaStoredProcedure -Pattern dbatools

# Have an employee who is leaving? Find all of their objects.
$allservers | Find-DbaUserObject -Pattern ad\jdoe | Out-GridView

# Find detached databases, by example
Detach-DbaDatabase -SqlInstance $instance -Database AdventureWorks2012
Find-DbaOrphanedFile -SqlInstance $instance | Out-GridView

# Check out how complete our sp_configure command is
Get-DbaSpConfigure -SqlInstance $new | Out-GridView

# Easily update configuration values
Set-DbaSpConfigure -SqlInstance $new -ConfigName XPCmdShellEnabled -Value $true

# DB Cloning too!
Invoke-DbaDbClone -SqlInstance $new -Database db1 -CloneDatabase db1_clone | Out-GridView

# Read and watch XEvents
Get-DbaXESession -SqlInstance $new -Session system_health | Read-DbaXEFile
Get-DbaXESession -SqlInstance $new -Session system_health | Read-DbaXEFile | Select -ExpandProperty Fields | Out-GridView

# Reset-DbaAdmin
Reset-DbaAdmin -SqlInstance $instance -Login sqladmin -Verbose
Get-DbaDatabase -SqlInstance $instance -SqlCredential sqladmin

# sp_whoisactive
Install-DbaWhoIsActive -SqlInstance $instance -Database master
Invoke-DbaWhoIsActive -SqlInstance $instance -ShowOwnSpid -ShowSystemSpids

# Diagnostic query!
$instance | Invoke-DbaDiagnosticQuery -UseSelectionHelper | Export-DbaDiagnosticQuery -Path $home
Invoke-Item $home

# Ola, yall
$instance | Install-DbaMaintenanceSolution -ReplaceExisting -BackupLocation C:\temp -InstallJobs

# Startup parameters
Get-DbaStartupParameter -SqlInstance $instance
Set-DbaStartupParameter -SqlInstance $instance -SingleUser -WhatIf

# Database clone
Invoke-DbaDbClone -SqlInstance $new -Database dbwithsprocs -CloneDatabase dbwithsprocs_clone

# Schema change and Pester tests
Get-DbaSchemaChangeHistory -SqlInstance $new -Database tempdb

# Get Db Free Space AND write it to table
Get-DbaDbSpace -SqlInstance $instance | Out-GridView
Get-DbaDbSpace -SqlInstance $instance -IncludeSystemDB | ConvertTo-DbaDataTable | Write-DbaDataTable -SqlInstance $instance -Database tempdb -Table DiskSpaceExample -AutoCreateTable
Invoke-DbaQuery -SqlInstance $instance -Database tempdb -Query 'SELECT * FROM dbo.DiskSpaceExample' | Out-GridView

# History
Get-Command -Module dbatools *history*

# Identity usage
Test-DbaIdentityUsage -SqlInstance $instance | Out-GridView

# Test/Set SQL max memory
$allservers | Get-DbaMaxMemory
$allservers | Test-DbaMaxMemory | Format-Table
$allservers | Test-DbaMaxMemory | Where-Object { $_.SqlMaxMB -gt $_.TotalMB } | Set-DbaMaxMemory -WhatIf
Set-DbaMaxMemory -SqlInstance $instance -MaxMb 1023

# Testing sql server linked server connections
Test-DbaLinkedServerConnection -SqlInstance $instance

# See protocols
Get-DbaServerProtocol -ComputerName $instance | Out-GridView

# Reads trace files - default trace by default
Read-DbaTraceFile -SqlInstance $instance | Out-GridView

# don't have remoting access? Explore the filesystem. Uses master.sys.xp_dirtree
Get-DbaFile -SqlInstance $instance

# Test your SPNs and see what'd happen if you'd set them
$servers | Test-DbaSpn | Out-GridView
$servers | Test-DbaSpn | Out-GridView -PassThru | Set-DbaSpn -WhatIf

# Get Virtual Log File information
Get-DbaDbVirtualLogFile -SqlInstance $new -Database db1
Get-DbaDbVirtualLogFile -SqlInstance $new -Database db1 | Measure-Object

```

## Important Note

#### Alternative SQL Credentials

By default, all SQL-based commands will login to SQL Server using Trusted/Windows Authentication. To use alternative credentials, including SQL Logins or alternative Windows credentials, use the `-SqlCredential`. This parameter accepts the results of `Get-Credential` which generates a [PSCredential](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/get-credential?view=powershell-5.1) object.

```powershell
Get-DbaDatabase -SqlInstance sql2017 -SqlCredential sqladmin
```

<a href="https://dbatools.io/wp-content/uploads/2016/05/cred.jpg"><img class="aligncenter size-full wp-image-6897" src="https://dbatools.io/wp-content/uploads/2016/05/cred.jpg" alt="" width="322" height="261" /></a>

A few (or maybe just one - [Restore-DbaDatabase](/Restore-DbaDatabase)), you can also use `-AzureCredential`.

#### Alternative Windows Credentials

For commands that access Windows such as [Get-DbaDiskSpace](/Get-DbaDiskSpace), you will pass the `-Credential` parameter.

```powershell
$cred = Get-Credential ad\winadmin
Get-DbaDiskSpace -ComputerName sql2017 -Credential $cred
```

To store credentials to disk, please read more at [Jaap Brasser's blog](https://www.jaapbrasser.com/quickly-and-securely-storing-your-credentials-powershell/).

#### Servers with custom ports

If you use non-default ports and SQL Browser is disabled, you can access servers using a semicolon (functionality we've added) or a comma (the way Microsoft does it).

```powershell
-SqlInstance sql2017:55559
-SqlInstance 'sql2017,55559'
```

Note that PowerShell sees commas as arrays, so you must surround the host name with quotes.

#### Using Start-Transcript

Due to an [issue](https://github.com/sqlcollaborative/dbatools/issues/2722) in the way PowerShell 5.1 works you need to use `Import-Module dbatools` before you run `Start-Transcript`. If this isn't done then your transcript will stop when the module is imported:

```powershell
Import-Module dbatools
Start-Transcript
Get-DbaDatabase -SqlInstance sql2017
Stop-Transcript
```

## Support

dbatools aims to support as many configurations as possible, including

* PowerShell v3 and above
* Windows, macOS and Linux
* SQL Server 2000 - 2017
* Express - Datacenter Edition
* Clustered and stand-alone instances
* Windows and SQL authentication
* Default and named instances
* Multiple instances on one server
* Auto-populated parameters for command-line completion (think -Database and -Login)

Read more at our website at [dbatools.io](https://dbatools.io)

## Contributing

Want to contribute to the project? We'd love to have you! Visit our [contributing.md](https://github.com/sqlcollaborative/dbatools/blob/master/contributing.md) for a jump start.
tools\dbatools\xml\dbatools.Format.ps1xml
 
tools\dbatools\xml\dbatools.Types.ps1xml
 
tools\LICENSE.txt
From: https://raw.githubusercontent.com/sqlcollaborative/dbatools/master/LICENSE

LICENSE

MIT License

Copyright (c) 2018 Chrissy LeMaire

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.
tools\VERIFICATION.txt
VERIFICATION
Verification is intended to assist the Chocolatey moderators and community in verifying that this package's contents are trustworthy.

To verify the files using the project source:

1. Please go to the project source location (https://github.com/sqlcollaborative/dbatools) and download the source files;
2. Build the source to create the binary files to verify;
3. Use Get-FileHash -Path <FILE TO VERIFY> to get the file hash value from both the built file (from step 1 above) and the file from the package and compare them;

Alternatively you can download the module from the PowerShell Gallery ...

    Save-Module -Name dbatools -Path <PATH TO DOWNLOAD TO>

... and compare the files from the package against those in the installed module. Again use Get-FileHash -Path <FILE TO VERIFY> to retrieve those hash values.

Log in or click on link to see number of positives.

In cases where actual malware is found, the packages are subject to removal. Software sometimes has false positives. Moderators do not necessarily validate the safety of the underlying software, only that a package retrieves software from the official distribution point and/or validate embedded software against official distribution point (where distribution rights allow redistribution).

Chocolatey Pro provides runtime protection from possible malware.

Add to Builder Version Downloads Last Updated Status
dbatools (PowerShell Module) 2.1.14 1 Friday, April 12, 2024
Waiting for Maintainer
dbatools (PowerShell Module) 2.1.12 567 Saturday, March 30, 2024 Approved
dbatools (PowerShell Module) 2.1.11 607 Saturday, March 16, 2024 Approved
dbatools (PowerShell Module) 2.1.10 333 Saturday, March 9, 2024 Approved
dbatools (PowerShell Module) 2.1.9 42 Saturday, March 9, 2024 Approved
dbatools (PowerShell Module) 2.1.8 634 Thursday, February 22, 2024 Approved
dbatools (PowerShell Module) 2.1.6 1078 Friday, December 22, 2023 Approved
dbatools (PowerShell Module) 2.1.5 899 Sunday, November 5, 2023 Approved
dbatools (PowerShell Module) 2.1.4 660 Saturday, October 14, 2023 Approved
dbatools (PowerShell Module) 2.1.3 282 Wednesday, October 11, 2023 Approved
dbatools (PowerShell Module) 2.1.2 430 Wednesday, October 4, 2023 Approved
dbatools (PowerShell Module) 2.1.1 415 Friday, September 29, 2023 Approved
dbatools (PowerShell Module) 2.1.0 514 Thursday, September 21, 2023 Approved
dbatools (PowerShell Module) 2.0.4 2318 Friday, June 9, 2023 Approved
dbatools (PowerShell Module) 1.1.145 5871 Friday, January 27, 2023 Approved
dbatools (PowerShell Module) 1.1.144 226 Thursday, January 26, 2023 Approved
dbatools (PowerShell Module) 1.1.143 1844 Thursday, November 17, 2022 Approved
dbatools (PowerShell Module) 1.1.142 1136 Sunday, October 23, 2022 Approved
dbatools (PowerShell Module) 1.1.141 142 Friday, October 21, 2022 Approved
dbatools (PowerShell Module) 1.1.140 319 Monday, October 17, 2022 Approved
dbatools (PowerShell Module) 1.1.139 471 Tuesday, October 11, 2022 Approved
dbatools (PowerShell Module) 1.1.138 270 Tuesday, October 11, 2022 Approved
dbatools (PowerShell Module) 1.1.137 345 Thursday, October 6, 2022 Approved
dbatools (PowerShell Module) 1.1.136 390 Friday, September 30, 2022 Approved
dbatools (PowerShell Module) 1.1.134 494 Wednesday, September 21, 2022 Approved
dbatools (PowerShell Module) 1.1.133 298 Saturday, September 17, 2022 Approved
dbatools (PowerShell Module) 1.1.132 529 Friday, September 9, 2022 Approved
dbatools (PowerShell Module) 1.1.131 140 Friday, September 9, 2022 Approved
dbatools (PowerShell Module) 1.1.130 181 Wednesday, September 7, 2022 Approved
dbatools (PowerShell Module) 1.1.129 261 Monday, September 5, 2022 Approved
dbatools (PowerShell Module) 1.1.128 370 Tuesday, August 30, 2022 Approved
dbatools (PowerShell Module) 1.1.127 347 Wednesday, August 24, 2022 Approved
dbatools (PowerShell Module) 1.1.126 359 Friday, August 19, 2022 Approved
dbatools (PowerShell Module) 1.1.125 291 Tuesday, August 16, 2022 Approved
dbatools (PowerShell Module) 1.1.124 175 Tuesday, August 16, 2022 Approved
dbatools (PowerShell Module) 1.1.122 467 Saturday, August 6, 2022 Approved
dbatools (PowerShell Module) 1.1.121 239 Thursday, August 4, 2022 Approved
dbatools (PowerShell Module) 1.1.120 289 Monday, August 1, 2022 Approved
dbatools (PowerShell Module) 1.1.119 242 Saturday, July 30, 2022 Approved
dbatools (PowerShell Module) 1.1.118 389 Monday, July 25, 2022 Approved
dbatools (PowerShell Module) 1.1.117 270 Thursday, July 21, 2022 Approved
dbatools (PowerShell Module) 1.1.116 135 Thursday, July 21, 2022 Approved
dbatools (PowerShell Module) 1.1.115 130 Thursday, July 21, 2022 Approved
dbatools (PowerShell Module) 1.1.114 441 Thursday, July 14, 2022 Approved
dbatools (PowerShell Module) 1.1.113 290 Monday, July 11, 2022 Approved
dbatools (PowerShell Module) 1.1.112 250 Friday, July 8, 2022 Approved
dbatools (PowerShell Module) 1.1.111 330 Sunday, July 3, 2022 Approved
dbatools (PowerShell Module) 1.1.110 202 Thursday, June 30, 2022 Approved
dbatools (PowerShell Module) 1.1.109 224 Wednesday, June 29, 2022 Approved
dbatools (PowerShell Module) 1.1.108 366 Friday, June 24, 2022 Approved
dbatools (PowerShell Module) 1.1.107 274 Wednesday, June 22, 2022 Approved
dbatools (PowerShell Module) 1.1.106 524 Wednesday, June 15, 2022 Approved
dbatools (PowerShell Module) 1.1.105 110 Wednesday, June 15, 2022 Approved
dbatools (PowerShell Module) 1.1.104 202 Tuesday, June 14, 2022 Approved
dbatools (PowerShell Module) 1.1.103 451 Sunday, June 5, 2022 Approved
dbatools (PowerShell Module) 1.1.102 234 Thursday, June 2, 2022 Approved
dbatools (PowerShell Module) 1.1.101 311 Sunday, May 29, 2022 Approved
dbatools (PowerShell Module) 1.1.100 139 Saturday, May 28, 2022 Approved
dbatools (PowerShell Module) 1.1.99 192 Friday, May 27, 2022 Approved
dbatools (PowerShell Module) 1.1.98 243 Tuesday, May 24, 2022 Approved
dbatools (PowerShell Module) 1.1.97 131 Tuesday, May 24, 2022 Approved
dbatools (PowerShell Module) 1.1.96 506 Saturday, May 21, 2022 Approved
dbatools (PowerShell Module) 1.1.95 970 Wednesday, May 11, 2022 Approved
dbatools (PowerShell Module) 1.1.94 49 Tuesday, May 10, 2022 Approved
dbatools (PowerShell Module) 1.1.93 218 Tuesday, May 10, 2022 Approved
dbatools (PowerShell Module) 1.1.92 356 Sunday, May 8, 2022 Approved
dbatools (PowerShell Module) 1.1.91 304 Friday, May 6, 2022 Approved
dbatools (PowerShell Module) 1.1.90 309 Wednesday, May 4, 2022 Approved
dbatools (PowerShell Module) 1.1.89 620 Thursday, April 28, 2022 Approved
dbatools (PowerShell Module) 1.1.88 1377 Friday, April 8, 2022 Approved
dbatools (PowerShell Module) 1.1.87 250 Wednesday, April 6, 2022 Approved
dbatools (PowerShell Module) 1.1.86 244 Monday, April 4, 2022 Approved
dbatools (PowerShell Module) 1.1.85 312 Saturday, April 2, 2022 Approved
dbatools (PowerShell Module) 1.1.84 470 Thursday, March 31, 2022 Approved
dbatools (PowerShell Module) 1.1.83 238 Tuesday, March 29, 2022 Approved
dbatools (PowerShell Module) 1.1.82 653 Friday, March 25, 2022 Approved
dbatools (PowerShell Module) 1.1.81 917 Wednesday, March 16, 2022 Approved
dbatools (PowerShell Module) 1.1.80 186 Tuesday, March 15, 2022 Approved
dbatools (PowerShell Module) 1.1.79 141 Monday, March 14, 2022 Approved
dbatools (PowerShell Module) 1.1.78 588 Friday, March 11, 2022 Approved
dbatools (PowerShell Module) 1.1.77 92 Friday, March 11, 2022 Approved
dbatools (PowerShell Module) 1.1.76 747 Saturday, March 5, 2022 Approved
dbatools (PowerShell Module) 1.1.75 786 Saturday, February 26, 2022 Approved
dbatools (PowerShell Module) 1.1.74 193 Thursday, February 24, 2022 Approved
dbatools (PowerShell Module) 1.1.73 219 Tuesday, February 22, 2022 Approved
dbatools (PowerShell Module) 1.1.72 251 Monday, February 21, 2022 Approved
dbatools (PowerShell Module) 1.1.71 682 Tuesday, February 15, 2022 Approved
dbatools (PowerShell Module) 1.1.70 762 Wednesday, February 9, 2022 Approved
dbatools (PowerShell Module) 1.1.69 265 Monday, February 7, 2022 Approved
dbatools (PowerShell Module) 1.1.68 150 Monday, February 7, 2022 Approved
dbatools (PowerShell Module) 1.1.67 520 Saturday, February 5, 2022 Approved
dbatools (PowerShell Module) 1.1.66 158 Friday, February 4, 2022 Approved
dbatools (PowerShell Module) 1.1.65 230 Thursday, February 3, 2022 Approved
dbatools (PowerShell Module) 1.1.64 102 Wednesday, February 2, 2022 Approved
dbatools (PowerShell Module) 1.1.63 239 Tuesday, February 1, 2022 Approved
dbatools (PowerShell Module) 1.1.62 332 Sunday, January 30, 2022 Approved
dbatools (PowerShell Module) 1.1.61 354 Saturday, January 29, 2022 Approved
dbatools (PowerShell Module) 1.1.60 303 Tuesday, January 25, 2022 Approved
dbatools (PowerShell Module) 1.1.59 630 Thursday, January 20, 2022 Approved
dbatools (PowerShell Module) 1.1.58 124 Thursday, January 20, 2022 Approved
dbatools (PowerShell Module) 1.1.57 139 Thursday, January 20, 2022 Approved
dbatools (PowerShell Module) 1.1.56 232 Tuesday, January 18, 2022 Approved
dbatools (PowerShell Module) 1.1.55 142 Tuesday, January 18, 2022 Approved
dbatools (PowerShell Module) 1.1.54 540 Saturday, January 15, 2022 Approved
dbatools (PowerShell Module) 1.1.53 152 Friday, January 14, 2022 Approved
dbatools (PowerShell Module) 1.1.52 84 Friday, January 14, 2022 Approved
dbatools (PowerShell Module) 1.1.51 161 Thursday, January 13, 2022 Approved
dbatools (PowerShell Module) 1.1.50 206 Tuesday, January 11, 2022 Approved
dbatools (PowerShell Module) 1.1.49 631 Thursday, January 6, 2022 Approved
dbatools (PowerShell Module) 1.1.48 243 Tuesday, January 4, 2022 Approved
dbatools (PowerShell Module) 1.1.46 835 Thursday, December 23, 2021 Approved
dbatools (PowerShell Module) 1.1.45 183 Wednesday, December 22, 2021 Approved
dbatools (PowerShell Module) 1.1.44 742 Tuesday, December 14, 2021 Approved
dbatools (PowerShell Module) 1.1.43 614 Friday, December 10, 2021 Approved
dbatools (PowerShell Module) 1.1.42 210 Wednesday, December 8, 2021 Approved
dbatools (PowerShell Module) 1.1.41 649 Friday, December 3, 2021 Approved
dbatools (PowerShell Module) 1.1.40 214 Wednesday, December 1, 2021 Approved
dbatools (PowerShell Module) 1.1.39 194 Monday, November 29, 2021 Approved
dbatools (PowerShell Module) 1.1.38 683 Wednesday, November 24, 2021 Approved
dbatools (PowerShell Module) 1.1.37 180 Tuesday, November 23, 2021 Approved
dbatools (PowerShell Module) 1.1.36 664 Friday, November 19, 2021 Approved
dbatools (PowerShell Module) 1.1.35 362 Monday, November 15, 2021 Approved
dbatools (PowerShell Module) 1.1.34 568 Thursday, November 11, 2021 Approved
dbatools (PowerShell Module) 1.1.33 231 Tuesday, November 9, 2021 Approved
dbatools (PowerShell Module) 1.1.32 601 Saturday, November 6, 2021 Approved
dbatools (PowerShell Module) 1.1.31 419 Monday, November 1, 2021 Approved
dbatools (PowerShell Module) 1.1.30 90 Monday, November 1, 2021 Approved
dbatools (PowerShell Module) 1.1.29 470 Thursday, October 28, 2021 Approved
dbatools (PowerShell Module) 1.1.28 92 Thursday, October 28, 2021 Approved
dbatools (PowerShell Module) 1.1.27 291 Tuesday, October 26, 2021 Approved
dbatools (PowerShell Module) 1.1.26 470 Saturday, October 23, 2021 Approved
dbatools (PowerShell Module) 1.1.25 304 Wednesday, October 20, 2021 Approved
dbatools (PowerShell Module) 1.1.24 817 Tuesday, October 12, 2021 Approved
dbatools (PowerShell Module) 1.1.23 712 Wednesday, October 6, 2021 Approved
dbatools (PowerShell Module) 1.1.22 264 Tuesday, October 5, 2021 Approved
dbatools (PowerShell Module) 1.1.21 835 Monday, September 27, 2021 Approved
dbatools (PowerShell Module) 1.1.20 600 Wednesday, September 22, 2021 Approved
dbatools (PowerShell Module) 1.1.19 609 Saturday, September 18, 2021 Approved
dbatools (PowerShell Module) 1.1.18 350 Wednesday, September 15, 2021 Approved
dbatools (PowerShell Module) 1.1.17 91 Tuesday, September 14, 2021 Approved
dbatools (PowerShell Module) 1.1.16 109 Tuesday, September 14, 2021 Approved
dbatools (PowerShell Module) 1.1.15 1000 Thursday, September 2, 2021 Approved
dbatools (PowerShell Module) 1.1.14 68 Tuesday, August 31, 2021 Approved
dbatools (PowerShell Module) 1.1.13 279 Tuesday, August 31, 2021 Approved
dbatools (PowerShell Module) 1.1.12 916 Tuesday, August 24, 2021 Approved
dbatools (PowerShell Module) 1.1.11 1068 Wednesday, August 11, 2021 Approved
dbatools (PowerShell Module) 1.1.10 225 Tuesday, August 10, 2021 Approved
dbatools (PowerShell Module) 1.1.9 619 Thursday, August 5, 2021 Approved
dbatools (PowerShell Module) 1.1.8 106 Thursday, August 5, 2021 Approved
dbatools (PowerShell Module) 1.1.7 232 Tuesday, August 3, 2021 Approved
dbatools (PowerShell Module) 1.1.6 199 Monday, August 2, 2021 Approved
dbatools (PowerShell Module) 1.1.5 510 Saturday, July 31, 2021 Approved
dbatools (PowerShell Module) 1.1.4 155 Friday, July 30, 2021 Approved
dbatools (PowerShell Module) 1.1.3 153 Friday, July 30, 2021 Approved
dbatools (PowerShell Module) 1.1.1 202 Tuesday, July 27, 2021 Approved
dbatools (PowerShell Module) 1.1.0 653 Friday, July 23, 2021 Approved
dbatools (PowerShell Module) 1.0.173 758 Tuesday, July 13, 2021 Approved
dbatools (PowerShell Module) 1.0.171 260 Monday, July 12, 2021 Approved
dbatools (PowerShell Module) 1.0.170 607 Wednesday, July 7, 2021 Approved
dbatools (PowerShell Module) 1.0.169 183 Tuesday, July 6, 2021 Approved
dbatools (PowerShell Module) 1.0.168 385 Sunday, July 4, 2021 Approved
dbatools (PowerShell Module) 1.0.167 311 Saturday, July 3, 2021 Approved
dbatools (PowerShell Module) 1.0.166 179 Friday, July 2, 2021 Approved
dbatools (PowerShell Module) 1.0.165 329 Tuesday, June 29, 2021 Approved
dbatools (PowerShell Module) 1.0.164 448 Friday, June 25, 2021 Approved
dbatools (PowerShell Module) 1.0.163 211 Thursday, June 24, 2021 Approved
dbatools (PowerShell Module) 1.0.162 245 Tuesday, June 22, 2021 Approved
dbatools (PowerShell Module) 1.0.161 172 Monday, June 21, 2021 Approved
dbatools (PowerShell Module) 1.0.160 323 Friday, June 18, 2021 Approved
dbatools (PowerShell Module) 1.0.156 605 Friday, June 11, 2021 Approved
dbatools (PowerShell Module) 1.0.155 301 Wednesday, June 9, 2021 Approved
dbatools (PowerShell Module) 1.0.153 984 Wednesday, May 26, 2021 Approved
dbatools (PowerShell Module) 1.0.152 218 Tuesday, May 25, 2021 Approved
dbatools (PowerShell Module) 1.0.151 375 Sunday, May 23, 2021 Approved
dbatools (PowerShell Module) 1.0.150 144 Saturday, May 22, 2021 Approved
dbatools (PowerShell Module) 1.0.149 404 Wednesday, May 19, 2021 Approved
dbatools (PowerShell Module) 1.0.148 339 Friday, May 14, 2021 Approved
dbatools (PowerShell Module) 1.0.147 523 Thursday, May 6, 2021 Approved
dbatools (PowerShell Module) 1.0.146 207 Wednesday, May 5, 2021 Approved
dbatools (PowerShell Module) 1.0.145 821 Sunday, April 18, 2021 Approved
dbatools (PowerShell Module) 1.0.144 132 Sunday, April 18, 2021 Approved
dbatools (PowerShell Module) 1.0.142 839 Sunday, April 4, 2021 Approved
dbatools (PowerShell Module) 1.0.141 1096 Thursday, March 11, 2021 Approved
dbatools (PowerShell Module) 1.0.140 812 Tuesday, February 23, 2021 Approved
dbatools (PowerShell Module) 1.0.139 514 Tuesday, February 16, 2021 Approved
dbatools (PowerShell Module) 1.0.138 213 Monday, February 15, 2021 Approved
dbatools (PowerShell Module) 1.0.137 1615 Tuesday, January 19, 2021 Approved
dbatools (PowerShell Module) 1.0.136 1020 Monday, December 28, 2020 Approved
dbatools (PowerShell Module) 1.0.135 1037 Sunday, December 6, 2020 Approved
dbatools (PowerShell Module) 1.0.134 173 Friday, December 4, 2020 Approved
dbatools (PowerShell Module) 1.0.133 534 Monday, November 23, 2020 Approved
dbatools (PowerShell Module) 1.0.131 419 Monday, November 16, 2020 Approved
dbatools (PowerShell Module) 1.0.130 699 Friday, November 6, 2020 Approved
dbatools (PowerShell Module) 1.0.128 518 Monday, November 2, 2020 Approved
dbatools (PowerShell Module) 1.0.127 327 Wednesday, October 28, 2020 Approved
dbatools (PowerShell Module) 1.0.126 589 Thursday, October 22, 2020 Approved
dbatools (PowerShell Module) 1.0.125 499 Saturday, October 17, 2020 Approved
dbatools (PowerShell Module) 1.0.124 571 Wednesday, October 7, 2020 Approved
dbatools (PowerShell Module) 1.0.123 452 Friday, October 2, 2020 Approved
dbatools (PowerShell Module) 1.0.122 200 Thursday, October 1, 2020 Approved
dbatools (PowerShell Module) 1.0.121 378 Friday, September 25, 2020 Approved
dbatools (PowerShell Module) 1.0.120 568 Friday, September 18, 2020 Approved
dbatools (PowerShell Module) 1.0.119 385 Monday, September 14, 2020 Approved
dbatools (PowerShell Module) 1.0.116 782 Friday, August 28, 2020 Approved
dbatools (PowerShell Module) 1.0.115 1408 Saturday, July 25, 2020 Approved
dbatools (PowerShell Module) 1.0.114 1119 Saturday, July 4, 2020 Approved
dbatools (PowerShell Module) 1.0.113 948 Monday, June 15, 2020 Approved
dbatools (PowerShell Module) 1.0.112 869 Tuesday, June 2, 2020 Approved
dbatools (PowerShell Module) 1.0.111 785 Friday, May 22, 2020 Approved
dbatools (PowerShell Module) 1.0.110 193 Thursday, May 21, 2020 Approved
dbatools (PowerShell Module) 1.0.109 636 Thursday, May 14, 2020 Approved
dbatools (PowerShell Module) 1.0.108 791 Wednesday, May 6, 2020 Approved
dbatools (PowerShell Module) 1.0.107 676 Monday, April 27, 2020 Approved
dbatools (PowerShell Module) 1.0.106 513 Monday, April 20, 2020 Approved
dbatools (PowerShell Module) 1.0.105 500 Wednesday, April 15, 2020 Approved
dbatools (PowerShell Module) 1.0.104 845 Monday, March 30, 2020 Approved
dbatools (PowerShell Module) 1.0.103 558 Monday, March 23, 2020 Approved
dbatools (PowerShell Module) 1.0.102 428 Thursday, March 19, 2020 Approved
dbatools (PowerShell Module) 1.0.101 683 Tuesday, March 3, 2020 Approved
dbatools (PowerShell Module) 1.0.100 414 Friday, February 28, 2020 Approved
dbatools (PowerShell Module) 1.0.99 255 Thursday, February 27, 2020 Approved
dbatools (PowerShell Module) 1.0.97 646 Saturday, February 15, 2020 Approved
dbatools (PowerShell Module) 1.0.96 224 Saturday, February 15, 2020 Approved
dbatools (PowerShell Module) 1.0.95 227 Friday, February 14, 2020 Approved
dbatools (PowerShell Module) 1.0.93 270 Wednesday, February 12, 2020 Approved
dbatools (PowerShell Module) 1.0.92 326 Monday, February 10, 2020 Approved
dbatools (PowerShell Module) 1.0.91 390 Thursday, February 6, 2020 Approved
dbatools (PowerShell Module) 1.0.90 278 Monday, February 3, 2020 Approved
dbatools (PowerShell Module) 1.0.89 292 Saturday, February 1, 2020 Approved
dbatools (PowerShell Module) 1.0.88 503 Saturday, January 25, 2020 Approved
dbatools (PowerShell Module) 1.0.87 267 Thursday, January 23, 2020 Approved
dbatools (PowerShell Module) 1.0.86 260 Thursday, January 23, 2020 Approved
dbatools (PowerShell Module) 1.0.85 241 Monday, January 20, 2020 Approved
dbatools (PowerShell Module) 1.0.84 384 Friday, January 17, 2020 Approved
dbatools (PowerShell Module) 1.0.83 413 Friday, January 10, 2020 Approved
dbatools (PowerShell Module) 1.0.81 294 Wednesday, January 8, 2020 Approved
dbatools (PowerShell Module) 1.0.80 309 Monday, January 6, 2020 Approved
dbatools (PowerShell Module) 1.0.79 297 Friday, January 3, 2020 Approved
dbatools (PowerShell Module) 1.0.78 232 Thursday, January 2, 2020 Approved
dbatools (PowerShell Module) 1.0.77 300 Friday, December 20, 2019 Approved
dbatools (PowerShell Module) 1.0.75 486 Sunday, December 8, 2019 Approved
dbatools (PowerShell Module) 1.0.74 358 Monday, December 2, 2019 Approved
dbatools (PowerShell Module) 1.0.73 391 Friday, November 22, 2019 Approved
dbatools (PowerShell Module) 1.0.72 339 Tuesday, November 19, 2019 Approved
dbatools (PowerShell Module) 1.0.71 346 Thursday, November 14, 2019 Approved
dbatools (PowerShell Module) 1.0.68 275 Monday, November 11, 2019 Approved
dbatools (PowerShell Module) 1.0.67 586 Tuesday, November 5, 2019 Approved
dbatools (PowerShell Module) 1.0.66 212 Monday, November 4, 2019 Approved
dbatools (PowerShell Module) 1.0.65 316 Friday, November 1, 2019 Approved
dbatools (PowerShell Module) 1.0.64 284 Tuesday, October 29, 2019 Approved
dbatools (PowerShell Module) 1.0.62 282 Monday, October 28, 2019 Approved
dbatools (PowerShell Module) 1.0.61 278 Thursday, October 24, 2019 Approved
dbatools (PowerShell Module) 1.0.60 277 Tuesday, October 22, 2019 Approved
dbatools (PowerShell Module) 1.0.59 226 Monday, October 21, 2019 Approved
dbatools (PowerShell Module) 1.0.58 258 Sunday, October 20, 2019 Approved
dbatools (PowerShell Module) 1.0.57 252 Friday, October 18, 2019 Approved
dbatools (PowerShell Module) 1.0.55 198 Friday, October 18, 2019 Approved
dbatools (PowerShell Module) 1.0.54 270 Thursday, October 17, 2019 Approved
dbatools (PowerShell Module) 1.0.53 266 Tuesday, October 15, 2019 Approved
dbatools (PowerShell Module) 1.0.52 317 Monday, October 7, 2019 Approved
dbatools (PowerShell Module) 1.0.51 316 Wednesday, October 2, 2019 Approved
dbatools (PowerShell Module) 1.0.50 309 Friday, September 27, 2019 Approved
dbatools (PowerShell Module) 1.0.49 337 Tuesday, September 24, 2019 Approved
dbatools (PowerShell Module) 1.0.48 262 Monday, September 23, 2019 Approved
dbatools (PowerShell Module) 1.0.47 282 Friday, September 20, 2019 Approved
dbatools (PowerShell Module) 1.0.46 379 Saturday, September 14, 2019 Approved
dbatools (PowerShell Module) 1.0.45 245 Friday, September 13, 2019 Approved
dbatools (PowerShell Module) 1.0.44 257 Thursday, September 12, 2019 Approved
dbatools (PowerShell Module) 1.0.43 273 Tuesday, September 10, 2019 Approved
dbatools (PowerShell Module) 1.0.42 267 Sunday, September 8, 2019 Approved
dbatools (PowerShell Module) 1.0.41 236 Saturday, September 7, 2019 Approved
dbatools (PowerShell Module) 1.0.40 257 Thursday, September 5, 2019 Approved
dbatools (PowerShell Module) 1.0.39 523 Wednesday, September 4, 2019 Approved
dbatools (PowerShell Module) 1.0.38 457 Wednesday, August 28, 2019 Approved
dbatools (PowerShell Module) 1.0.36 263 Tuesday, August 27, 2019 Approved
dbatools (PowerShell Module) 1.0.35 347 Thursday, August 22, 2019 Approved
dbatools (PowerShell Module) 1.0.34 276 Monday, August 19, 2019 Approved
dbatools (PowerShell Module) 1.0.33 302 Thursday, August 15, 2019 Approved
dbatools (PowerShell Module) 1.0.32 263 Wednesday, August 14, 2019 Approved
dbatools (PowerShell Module) 1.0.30 344 Thursday, August 8, 2019 Approved
dbatools (PowerShell Module) 1.0.29 288 Saturday, August 3, 2019 Approved
dbatools (PowerShell Module) 1.0.28 240 Friday, August 2, 2019 Approved
dbatools (PowerShell Module) 1.0.27 281 Wednesday, July 31, 2019 Approved
dbatools (PowerShell Module) 1.0.26 234 Monday, July 29, 2019 Approved
dbatools (PowerShell Module) 1.0.25 213 Monday, July 29, 2019 Approved
dbatools (PowerShell Module) 1.0.23 354 Tuesday, July 23, 2019 Approved
dbatools (PowerShell Module) 1.0.22 353 Tuesday, July 16, 2019 Approved
dbatools (PowerShell Module) 1.0.21 311 Friday, July 12, 2019 Approved
dbatools (PowerShell Module) 1.0.20 300 Wednesday, July 10, 2019 Approved
dbatools (PowerShell Module) 1.0.19 238 Wednesday, July 10, 2019 Approved
dbatools (PowerShell Module) 1.0.17 268 Tuesday, July 9, 2019 Approved
dbatools (PowerShell Module) 1.0.15 285 Saturday, July 6, 2019 Approved
dbatools (PowerShell Module) 1.0.14 213 Friday, July 5, 2019 Approved
dbatools (PowerShell Module) 1.0.13 227 Thursday, July 4, 2019 Approved
dbatools (PowerShell Module) 1.0.12 293 Tuesday, July 2, 2019 Approved
dbatools (PowerShell Module) 1.0.11 197 Monday, July 1, 2019 Approved
dbatools (PowerShell Module) 1.0.10 231 Saturday, June 29, 2019 Approved
dbatools (PowerShell Module) 1.0.9 306 Wednesday, June 26, 2019 Approved
dbatools (PowerShell Module) 1.0.6 240 Wednesday, June 26, 2019 Approved
dbatools (PowerShell Module) 1.0.5 247 Monday, June 24, 2019 Approved
dbatools (PowerShell Module) 1.0.4 280 Sunday, June 23, 2019 Approved
dbatools (PowerShell Module) 1.0.3 239 Sunday, June 23, 2019 Approved
dbatools (PowerShell Module) 1.0.2 267 Friday, June 21, 2019 Approved
dbatools (PowerShell Module) 1.0.0 304 Thursday, June 20, 2019 Approved
dbatools (PowerShell Module) 0.9.834 449 Friday, May 31, 2019 Approved
dbatools (PowerShell Module) 0.9.833 230 Thursday, May 30, 2019 Approved
dbatools (PowerShell Module) 0.9.832 296 Friday, May 24, 2019 Approved
dbatools (PowerShell Module) 0.9.831 273 Thursday, May 23, 2019 Approved
dbatools (PowerShell Module) 0.9.830 280 Tuesday, May 21, 2019 Approved
dbatools (PowerShell Module) 0.9.829 206 Friday, May 17, 2019 Approved
dbatools (PowerShell Module) 0.9.828 288 Wednesday, May 15, 2019 Approved
dbatools (PowerShell Module) 0.9.827 276 Tuesday, May 14, 2019 Approved
dbatools (PowerShell Module) 0.9.826 265 Monday, May 13, 2019 Approved
dbatools (PowerShell Module) 0.9.825 306 Friday, May 10, 2019 Approved
dbatools (PowerShell Module) 0.9.824 253 Friday, May 10, 2019 Approved
dbatools (PowerShell Module) 0.9.823 264 Wednesday, May 8, 2019 Approved
dbatools (PowerShell Module) 0.9.822 287 Monday, May 6, 2019 Approved
dbatools (PowerShell Module) 0.9.821 317 Friday, May 3, 2019 Approved
dbatools (PowerShell Module) 0.9.819 266 Wednesday, May 1, 2019 Approved
dbatools (PowerShell Module) 0.9.818 261 Tuesday, April 30, 2019 Approved
dbatools (PowerShell Module) 0.9.817 236 Tuesday, April 30, 2019 Approved
dbatools (PowerShell Module) 0.9.815 237 Tuesday, April 30, 2019 Approved
dbatools (PowerShell Module) 0.9.814 255 Monday, April 29, 2019 Approved
dbatools (PowerShell Module) 0.9.812 285 Saturday, April 27, 2019 Approved
dbatools (PowerShell Module) 0.9.811 246 Thursday, April 25, 2019 Approved
dbatools (PowerShell Module) 0.9.810 287 Thursday, April 25, 2019 Approved
dbatools (PowerShell Module) 0.9.809 296 Saturday, April 20, 2019 Approved
dbatools (PowerShell Module) 0.9.808 232 Thursday, April 18, 2019 Approved
dbatools (PowerShell Module) 0.9.807 231 Wednesday, April 17, 2019 Approved
dbatools (PowerShell Module) 0.9.804 290 Monday, April 15, 2019 Approved
dbatools (PowerShell Module) 0.9.803 298 Wednesday, April 10, 2019 Approved
dbatools (PowerShell Module) 0.9.802 299 Sunday, April 7, 2019 Approved
dbatools (PowerShell Module) 0.9.801 259 Thursday, April 4, 2019 Approved
dbatools (PowerShell Module) 0.9.800 299 Monday, April 1, 2019 Approved
dbatools (PowerShell Module) 0.9.799 241 Sunday, March 31, 2019 Approved
dbatools (PowerShell Module) 0.9.798 252 Thursday, March 28, 2019 Approved
dbatools (PowerShell Module) 0.9.797 258 Tuesday, March 26, 2019 Approved
dbatools (PowerShell Module) 0.9.795 240 Sunday, March 24, 2019 Approved
dbatools (PowerShell Module) 0.9.794 263 Saturday, March 23, 2019 Approved
dbatools (PowerShell Module) 0.9.793 254 Thursday, March 21, 2019 Approved
dbatools (PowerShell Module) 0.9.792 279 Wednesday, March 20, 2019 Approved
dbatools (PowerShell Module) 0.9.785 196 Saturday, March 16, 2019 Approved
dbatools (PowerShell Module) 0.9.784 208 Tuesday, March 12, 2019 Approved
dbatools (PowerShell Module) 0.9.782 177 Monday, March 11, 2019 Approved
dbatools (PowerShell Module) 0.9.781 172 Saturday, March 9, 2019 Approved
dbatools (PowerShell Module) 0.9.780 196 Thursday, March 7, 2019 Approved
dbatools (PowerShell Module) 0.9.779 189 Wednesday, March 6, 2019 Approved
dbatools (PowerShell Module) 0.9.778 149 Tuesday, March 5, 2019 Approved
dbatools (PowerShell Module) 0.9.777 143 Monday, March 4, 2019 Approved
dbatools (PowerShell Module) 0.9.775 220 Tuesday, February 26, 2019 Approved
dbatools (PowerShell Module) 0.9.774 151 Tuesday, February 26, 2019 Approved
dbatools (PowerShell Module) 0.9.773 219 Monday, February 25, 2019 Approved
dbatools (PowerShell Module) 0.9.772 197 Sunday, February 24, 2019 Approved
dbatools (PowerShell Module) 0.9.771 190 Wednesday, February 20, 2019 Approved
dbatools (PowerShell Module) 0.9.770 244 Sunday, February 17, 2019 Approved
dbatools (PowerShell Module) 0.9.757 214 Tuesday, February 12, 2019 Approved
dbatools (PowerShell Module) 0.9.755 200 Sunday, February 10, 2019 Approved
dbatools (PowerShell Module) 0.9.754 178 Thursday, February 7, 2019 Approved
dbatools (PowerShell Module) 0.9.753 142 Thursday, February 7, 2019 Approved
dbatools (PowerShell Module) 0.9.752 179 Sunday, February 3, 2019 Approved
dbatools (PowerShell Module) 0.9.751 174 Thursday, January 31, 2019 Approved
dbatools (PowerShell Module) 0.9.750 302 Friday, January 25, 2019 Approved
dbatools (PowerShell Module) 0.9.749 249 Thursday, January 24, 2019 Approved
dbatools (PowerShell Module) 0.9.748 256 Thursday, January 24, 2019 Approved
dbatools (PowerShell Module) 0.9.747 382 Thursday, January 24, 2019 Approved
dbatools (PowerShell Module) 0.9.745 189 Wednesday, January 23, 2019 Approved
dbatools (PowerShell Module) 0.9.744 190 Wednesday, January 23, 2019 Approved
dbatools (PowerShell Module) 0.9.743 310 Monday, January 21, 2019 Approved
dbatools (PowerShell Module) 0.9.742 245 Tuesday, January 15, 2019 Approved
dbatools (PowerShell Module) 0.9.740 285 Friday, January 11, 2019 Approved
dbatools (PowerShell Module) 0.9.739 164 Friday, January 11, 2019 Approved
dbatools (PowerShell Module) 0.9.738 199 Thursday, January 10, 2019 Approved
dbatools (PowerShell Module) 0.9.737 190 Wednesday, January 9, 2019 Approved
dbatools (PowerShell Module) 0.9.735 166 Tuesday, January 8, 2019 Approved
dbatools (PowerShell Module) 0.9.734 262 Thursday, January 3, 2019 Approved
dbatools (PowerShell Module) 0.9.733 229 Monday, December 31, 2018 Approved
dbatools (PowerShell Module) 0.9.732 216 Thursday, December 27, 2018 Approved
dbatools (PowerShell Module) 0.9.731 201 Sunday, December 23, 2018 Approved
dbatools (PowerShell Module) 0.9.730 255 Friday, December 21, 2018 Approved
dbatools (PowerShell Module) 0.9.725 219 Thursday, December 20, 2018 Approved
dbatools (PowerShell Module) 0.9.724 192 Thursday, December 20, 2018 Approved
dbatools (PowerShell Module) 0.9.722 177 Wednesday, December 19, 2018 Approved
dbatools (PowerShell Module) 0.9.721 213 Tuesday, December 18, 2018 Approved
dbatools (PowerShell Module) 0.9.720 248 Sunday, December 16, 2018 Approved
dbatools (PowerShell Module) 0.9.719 206 Saturday, December 15, 2018 Approved
dbatools (PowerShell Module) 0.9.718 191 Friday, December 14, 2018 Approved
dbatools (PowerShell Module) 0.9.717 202 Friday, December 14, 2018 Approved
dbatools (PowerShell Module) 0.9.715 198 Thursday, December 13, 2018 Approved
dbatools (PowerShell Module) 0.9.714 245 Monday, December 10, 2018 Approved
dbatools (PowerShell Module) 0.9.712 311 Sunday, December 9, 2018 Approved
dbatools (PowerShell Module) 0.9.711 441 Friday, December 7, 2018 Approved
dbatools (PowerShell Module) 0.9.710 381 Thursday, December 6, 2018 Approved
dbatools (PowerShell Module) 0.9.709 195 Tuesday, December 4, 2018 Approved
dbatools (PowerShell Module) 0.9.707 141 Tuesday, December 4, 2018 Approved
dbatools (PowerShell Module) 0.9.704 204 Monday, December 3, 2018 Approved
dbatools (PowerShell Module) 0.9.703 188 Monday, December 3, 2018 Approved
dbatools (PowerShell Module) 0.9.702 140 Sunday, December 2, 2018 Approved
dbatools (PowerShell Module) 0.9.701 180 Saturday, December 1, 2018 Approved
dbatools (PowerShell Module) 0.9.538 184 Friday, November 30, 2018 Approved
dbatools (PowerShell Module) 0.9.537 179 Friday, November 30, 2018 Approved
dbatools (PowerShell Module) 0.9.535 153 Thursday, November 29, 2018 Approved
dbatools (PowerShell Module) 0.9.533 219 Wednesday, November 28, 2018 Approved
dbatools (PowerShell Module) 0.9.532 178 Tuesday, November 27, 2018 Approved
dbatools (PowerShell Module) 0.9.531 181 Sunday, November 25, 2018 Approved
dbatools (PowerShell Module) 0.9.530 162 Saturday, November 24, 2018 Approved
dbatools (PowerShell Module) 0.9.527 175 Saturday, November 24, 2018 Approved
dbatools (PowerShell Module) 0.9.523 140 Friday, November 23, 2018 Approved
dbatools (PowerShell Module) 0.9.521 245 Thursday, November 22, 2018 Approved
dbatools (PowerShell Module) 0.9.520 183 Thursday, November 22, 2018 Approved
dbatools (PowerShell Module) 0.9.519 195 Sunday, November 18, 2018 Approved
dbatools (PowerShell Module) 0.9.518 138 Friday, November 16, 2018 Approved
dbatools (PowerShell Module) 0.9.517 201 Friday, November 16, 2018 Approved
dbatools (PowerShell Module) 0.9.512 166 Wednesday, November 14, 2018 Approved
dbatools (PowerShell Module) 0.9.510 202 Wednesday, November 14, 2018 Approved
dbatools (PowerShell Module) 0.9.509 183 Monday, November 12, 2018 Approved
dbatools (PowerShell Module) 0.9.508 190 Monday, November 12, 2018 Approved
dbatools (PowerShell Module) 0.9.507 167 Saturday, November 10, 2018 Approved
dbatools (PowerShell Module) 0.9.504 169 Thursday, November 8, 2018 Approved
dbatools (PowerShell Module) 0.9.503 168 Thursday, November 8, 2018 Approved
dbatools (PowerShell Module) 0.9.502 156 Wednesday, November 7, 2018 Approved
dbatools (PowerShell Module) 0.9.501 176 Monday, November 5, 2018 Approved
dbatools (PowerShell Module) 0.9.500 175 Saturday, November 3, 2018 Approved
dbatools (PowerShell Module) 0.9.499 203 Friday, November 2, 2018 Approved
dbatools (PowerShell Module) 0.9.498 141 Friday, November 2, 2018 Approved
dbatools (PowerShell Module) 0.9.497 140 Wednesday, October 31, 2018 Approved
dbatools (PowerShell Module) 0.9.495 175 Tuesday, October 30, 2018 Approved
dbatools (PowerShell Module) 0.9.494 161 Tuesday, October 30, 2018 Approved
dbatools (PowerShell Module) 0.9.492 156 Sunday, October 28, 2018 Approved
dbatools (PowerShell Module) 0.9.491 186 Friday, October 26, 2018 Approved
dbatools (PowerShell Module) 0.9.490 148 Wednesday, October 24, 2018 Approved
dbatools (PowerShell Module) 0.9.489 158 Wednesday, October 24, 2018 Approved
dbatools (PowerShell Module) 0.9.487 208 Friday, October 19, 2018 Approved
dbatools (PowerShell Module) 0.9.485 122 Thursday, October 18, 2018 Approved
dbatools (PowerShell Module) 0.9.484 170 Tuesday, October 16, 2018 Approved
dbatools (PowerShell Module) 0.9.483 162 Monday, October 15, 2018 Approved
dbatools (PowerShell Module) 0.9.481 186 Monday, October 15, 2018 Approved
dbatools (PowerShell Module) 0.9.479 177 Monday, October 15, 2018 Approved
dbatools (PowerShell Module) 0.9.477 149 Friday, October 12, 2018 Approved
dbatools (PowerShell Module) 0.9.475 139 Friday, October 12, 2018 Approved
dbatools (PowerShell Module) 0.9.472 183 Tuesday, October 9, 2018 Approved
dbatools (PowerShell Module) 0.9.471 161 Monday, October 8, 2018 Approved
dbatools (PowerShell Module) 0.9.470 166 Sunday, October 7, 2018 Approved
dbatools (PowerShell Module) 0.9.459 160 Sunday, October 7, 2018 Approved
dbatools (PowerShell Module) 0.9.458 176 Saturday, October 6, 2018 Approved
dbatools (PowerShell Module) 0.9.455 192 Friday, October 5, 2018 Approved
dbatools (PowerShell Module) 0.9.454 166 Thursday, October 4, 2018 Approved
dbatools (PowerShell Module) 0.9.450 176 Monday, October 1, 2018 Approved
dbatools (PowerShell Module) 0.9.447 178 Saturday, September 29, 2018 Approved
dbatools (PowerShell Module) 0.9.445 134 Thursday, September 27, 2018 Approved
dbatools (PowerShell Module) 0.9.442 159 Wednesday, September 26, 2018 Approved
dbatools (PowerShell Module) 0.9.440 142 Wednesday, September 26, 2018 Approved
dbatools (PowerShell Module) 0.9.439 158 Wednesday, September 26, 2018 Approved
dbatools (PowerShell Module) 0.9.438 169 Wednesday, September 26, 2018 Approved
dbatools (PowerShell Module) 0.9.435 173 Monday, September 24, 2018 Approved
dbatools (PowerShell Module) 0.9.434 169 Sunday, September 23, 2018 Approved
dbatools (PowerShell Module) 0.9.433 172 Friday, September 21, 2018 Approved
dbatools (PowerShell Module) 0.9.432 143 Friday, September 21, 2018 Approved
dbatools (PowerShell Module) 0.9.431 176 Wednesday, September 19, 2018 Approved
dbatools (PowerShell Module) 0.9.428 145 Wednesday, September 19, 2018 Approved
dbatools (PowerShell Module) 0.9.427 152 Tuesday, September 18, 2018 Approved
dbatools (PowerShell Module) 0.9.424 175 Tuesday, September 18, 2018 Approved
dbatools (PowerShell Module) 0.9.422 193 Monday, September 17, 2018 Approved
dbatools (PowerShell Module) 0.9.419 170 Friday, September 14, 2018 Approved
dbatools (PowerShell Module) 0.9.417 434 Sunday, September 9, 2018 Approved
dbatools (PowerShell Module) 0.9.415 157 Saturday, September 8, 2018 Approved
dbatools (PowerShell Module) 0.9.412 147 Saturday, September 8, 2018 Approved
dbatools (PowerShell Module) 0.9.411 153 Friday, September 7, 2018 Approved
dbatools (PowerShell Module) 0.9.410 206 Friday, September 7, 2018 Approved
dbatools (PowerShell Module) 0.9.402 160 Thursday, September 6, 2018 Approved
dbatools (PowerShell Module) 0.9.400 145 Wednesday, September 5, 2018 Approved
dbatools (PowerShell Module) 0.9.399 181 Friday, August 31, 2018 Approved
dbatools (PowerShell Module) 0.9.398 188 Friday, August 31, 2018 Approved
dbatools (PowerShell Module) 0.9.395 244 Tuesday, August 28, 2018 Approved
dbatools (PowerShell Module) 0.9.394 169 Monday, August 27, 2018 Approved
dbatools (PowerShell Module) 0.9.393 199 Friday, August 24, 2018 Approved
dbatools (PowerShell Module) 0.9.392 171 Wednesday, August 22, 2018 Approved
dbatools (PowerShell Module) 0.9.390 159 Tuesday, August 21, 2018 Approved
dbatools (PowerShell Module) 0.9.389 163 Sunday, August 19, 2018 Approved
dbatools (PowerShell Module) 0.9.388 139 Friday, August 17, 2018 Approved
dbatools (PowerShell Module) 0.9.387 196 Thursday, August 16, 2018 Approved
dbatools (PowerShell Module) 0.9.385 214 Wednesday, August 8, 2018 Approved
dbatools (PowerShell Module) 0.9.384 199 Friday, August 3, 2018 Approved
dbatools (PowerShell Module) 0.9.383 169 Thursday, August 2, 2018 Approved
dbatools (PowerShell Module) 0.9.382 217 Thursday, July 26, 2018 Approved
dbatools (PowerShell Module) 0.9.381 152 Thursday, July 26, 2018 Approved
dbatools (PowerShell Module) 0.9.380 180 Tuesday, July 24, 2018 Approved
dbatools (PowerShell Module) 0.9.378 212 Monday, July 23, 2018 Approved
dbatools (PowerShell Module) 0.9.377 191 Saturday, July 21, 2018 Approved
dbatools (PowerShell Module) 0.9.376 213 Wednesday, July 18, 2018 Approved
dbatools (PowerShell Module) 0.9.375 211 Monday, July 16, 2018 Approved
dbatools (PowerShell Module) 0.9.362 239 Friday, June 29, 2018 Approved

This package has no dependencies.

Discussion for the dbatools (PowerShell Module) Package

Ground Rules:

  • This discussion is only about dbatools (PowerShell Module) and the dbatools (PowerShell Module) package. If you have feedback for Chocolatey, please contact the Google Group.
  • This discussion will carry over multiple versions. If you have a comment about a particular version, please note that in your comments.
  • The maintainers of this Chocolatey Package will be notified about new comments that are posted to this Disqus thread, however, it is NOT a guarantee that you will get a response. If you do not hear back from the maintainers after posting a message below, please follow up by using the link on the left side of this page or follow this link to contact maintainers. If you still hear nothing back, please follow the package triage process.
  • Tell us what you love about the package or dbatools (PowerShell Module), or tell us what needs improvement.
  • Share your experiences with the package, or extra configuration or gotchas that you've found.
  • If you use a url, the comment will be flagged for moderation until you've been whitelisted. Disqus moderated comments are approved on a weekly schedule if not sooner. It could take between 1-5 days for your comment to show up.
comments powered by Disqus